code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
' The kinds of results. Higher results take precedence over lower results (except that Good and Ambiguous have
' equal priority, generally).
Friend Enum LookupResultKind
Empty
NotATypeOrNamespace
NotAnAttributeType
WrongArity
NotCreatable
Inaccessible
NotReferencable ' e.g., implemented interface member in wrong interface, accessor that can't be called directly.
NotAValue
NotAVariable
MustNotBeInstance
MustBeInstance
NotAnEvent ' appears only in semantic info (not in regular lookup)
LateBound ' appears only in semantic info (not in regular lookup)
' Above this point, we continue looking up the binder chain for better possible symbol
' Below this point, we stop looking further (see StopFurtherLookup property)
EmptyAndStopLookup
WrongArityAndStopLookup
OverloadResolutionFailure
NotAWithEventsMember
Ambiguous
MemberGroup ' Indicates a set of symbols, and they are totally fine.
Good
End Enum
Friend Module LookupResultKindExtensions
<Extension()>
Public Function ToCandidateReason(resultKind As LookupResultKind) As CandidateReason
Select Case resultKind
Case LookupResultKind.Empty, LookupResultKind.EmptyAndStopLookup
Return CandidateReason.None
Case LookupResultKind.OverloadResolutionFailure
Return CandidateReason.OverloadResolutionFailure
Case LookupResultKind.NotATypeOrNamespace
Return CandidateReason.NotATypeOrNamespace
Case LookupResultKind.NotAnEvent
Return CandidateReason.NotAnEvent
Case LookupResultKind.LateBound
Return CandidateReason.LateBound
Case LookupResultKind.NotAnAttributeType
Return CandidateReason.NotAnAttributeType
Case LookupResultKind.NotAWithEventsMember
Return CandidateReason.NotAWithEventsMember
Case LookupResultKind.WrongArity, LookupResultKind.WrongArityAndStopLookup
Return CandidateReason.WrongArity
Case LookupResultKind.NotCreatable
Return CandidateReason.NotCreatable
Case LookupResultKind.Inaccessible
Return CandidateReason.Inaccessible
Case LookupResultKind.NotAValue
Return CandidateReason.NotAValue
Case LookupResultKind.NotAVariable
Return CandidateReason.NotAVariable
Case LookupResultKind.NotReferencable
Return CandidateReason.NotReferencable
Case LookupResultKind.MustNotBeInstance, LookupResultKind.MustBeInstance
Return CandidateReason.StaticInstanceMismatch
Case LookupResultKind.Ambiguous
Return CandidateReason.Ambiguous
Case LookupResultKind.MemberGroup
Return CandidateReason.MemberGroup
Case Else
' Should not call this on LookupResultKind.Good or undefined kind
Throw ExceptionUtilities.UnexpectedValue(resultKind)
End Select
End Function
End Module
''' <summary>
''' Represents a result of lookup operation over a 0 or 1 symbol (as opposed to a scope).
''' The typical use is to represent that a particular symbol is good/bad/unavailable.
'''
'''For more explanation of Kind, Symbol, Error - see LookupResult.
''' </summary>
Friend Structure SingleLookupResult
' the kind of result.
Friend ReadOnly Kind As LookupResultKind
' the symbol or null.
Friend ReadOnly Symbol As Symbol
' the error of the result, if it is Bag or Inaccessible or WrongArityAndStopLookup
Friend ReadOnly Diagnostic As DiagnosticInfo
Friend Sub New(kind As LookupResultKind, symbol As Symbol, diagInfo As DiagnosticInfo)
Me.Kind = kind
Me.Symbol = symbol
Me.Diagnostic = diagInfo
End Sub
Public ReadOnly Property HasDiagnostic As Boolean
Get
Return Diagnostic IsNot Nothing
End Get
End Property
' Get a result for a good (viable) symbol with no errors.
' Get an empty result.
Public Shared ReadOnly Empty As New SingleLookupResult(LookupResultKind.Empty, Nothing, Nothing)
Public Shared Function Good(sym As Symbol) As SingleLookupResult
Return New SingleLookupResult(LookupResultKind.Good, sym, Nothing)
End Function
' 2 or more ambiguous symbols.
Public Shared Function Ambiguous(syms As ImmutableArray(Of Symbol),
generateAmbiguityDiagnostic As Func(Of ImmutableArray(Of Symbol), AmbiguousSymbolDiagnostic)) As SingleLookupResult
Debug.Assert(syms.Length > 1)
Dim diagInfo As DiagnosticInfo = generateAmbiguityDiagnostic(syms)
Return New SingleLookupResult(LookupResultKind.Ambiguous, syms.First(), diagInfo)
End Function
Public Shared Function WrongArityAndStopLookup(sym As Symbol, err As ERRID) As SingleLookupResult
Return New SingleLookupResult(LookupResultKind.WrongArityAndStopLookup, sym, New BadSymbolDiagnostic(sym, err))
End Function
Public Shared ReadOnly EmptyAndStopLookup As New SingleLookupResult(LookupResultKind.EmptyAndStopLookup, Nothing, Nothing)
Public Shared Function WrongArityAndStopLookup(sym As Symbol, diagInfo As DiagnosticInfo) As SingleLookupResult
Return New SingleLookupResult(LookupResultKind.WrongArityAndStopLookup, sym, diagInfo)
End Function
Public Shared Function WrongArity(sym As Symbol,
diagInfo As DiagnosticInfo) As SingleLookupResult
Return New SingleLookupResult(LookupResultKind.WrongArity, sym, diagInfo)
End Function
Public Shared Function WrongArity(sym As Symbol,
err As ERRID) As SingleLookupResult
Return New SingleLookupResult(LookupResultKind.WrongArity, sym, New BadSymbolDiagnostic(sym, err))
End Function
' Gets a bad result for a symbol that doesn't match static/instance
Public Shared Function MustNotBeInstance(sym As Symbol, err As ERRID) As SingleLookupResult
Return New SingleLookupResult(LookupResultKind.MustNotBeInstance, sym, New BadSymbolDiagnostic(sym, err))
End Function
' Gets a bad result for a symbol that doesn't match static/instance, with no error message (special case for API-access)
Public Shared Function MustBeInstance(sym As Symbol) As SingleLookupResult
Return New SingleLookupResult(LookupResultKind.MustBeInstance, sym, Nothing)
End Function
' Gets a inaccessible result for a symbol.
Public Shared Function Inaccessible(sym As Symbol,
diagInfo As DiagnosticInfo) As SingleLookupResult
Return New SingleLookupResult(LookupResultKind.Inaccessible, sym, diagInfo)
End Function
Friend Shared Function NotAnAttributeType(sym As Symbol, [error] As DiagnosticInfo) As SingleLookupResult
Return New SingleLookupResult(LookupResultKind.NotAnAttributeType, sym, [error])
End Function
' Should we stop looking further for a better result?
Public ReadOnly Property StopFurtherLookup As Boolean
Get
Return Kind >= LookupResultKind.WrongArityAndStopLookup
End Get
End Property
Public ReadOnly Property IsGoodOrAmbiguous As Boolean
Get
Return Kind = LookupResultKind.Good OrElse Kind = LookupResultKind.Ambiguous
End Get
End Property
Public ReadOnly Property IsGood As Boolean
Get
Return Kind = LookupResultKind.Good
End Get
End Property
Public ReadOnly Property IsAmbiguous As Boolean
Get
Return Kind = LookupResultKind.Ambiguous
End Get
End Property
End Structure
''' <summary>
''' A LookupResult summarizes the result of a name lookup, and allows combining name lookups
''' from different scopes in an easy way.
'''
''' A LookupResult can be ONE OF:
''' empty - nothing found.
''' a non-accessible result - this kind of result means that search continues into further scopes of lower priority for
''' a viable result. An error is attached with the inaccessibility errors. Non-accessible results take priority over
''' non-viable results.
''' a non-viable result - a result that that means that the search continues into further scopes of lower priority for
''' a viable or non-accessible result. An error is attached with the error that indicates
''' why the result is non-viable.
''' a bad symbol that stops further lookup - this kind of result prevents lookup into further scopes of lower priority.
''' a diagnostic is attached explaining why the symbol is bad.
''' ambiguous symbols.- In this case, an AmbiguousSymbolDiagnostic diagnostic has the other symbols.
''' a good symbol, or set of good overloaded symbols - no diagnostic is attached in this case
'''
''' Occasionally, good or ambiguous results are referred to as "viable" results.
'''
''' Multiple symbols can be represented in a single LookupResult. Multiple symbols are ONLY USED for overloadable
''' entities, such an methods or properties, and represent all the symbols that overload resolution needs to consider.
''' When ambiguous symbols are encountered, a single representative symbols is returned, with an attached AmbiguousSymbolDiagnostic
''' from which all the ambiguous symbols can be retrieved. This implies that Lookup operations that are restricted to namespaces
''' and/or types always create a LookupResult with 0 or 1 symbol.
'''
''' Note that the class is poolable so its instances can be obtained from a pool via GetInstance.
''' Also it is a good idea to call Free on instances after they no longer needed.
'''
''' The typical pattern is "caller allocates / caller frees" -
'''
''' Dim result = LookupResult.GetInstance()
'''
''' scope.Lookup(result, "foo")
''' ... use result ...
'''
''' result.Clear()
''' anotherScope.Lookup(result, "moo")
''' ... use result ...
'''
''' result.Free() 'result and its content is invalid after this
''' </summary>
Friend Class LookupResult
' The kind of result.
Private _kind As LookupResultKind
' The symbol, unless the kind is empty.
Private ReadOnly _symList As ArrayBuilder(Of Symbol)
' The diagnostic. This is always set for NonAccessible and NonViable results. It may be
' set for viable results.
Private _diagInfo As DiagnosticInfo
' The pool used to get instances from.
Private ReadOnly _pool As ObjectPool(Of LookupResult)
''''''''''''''''''''''''''''''
' Access routines
Public ReadOnly Property Kind As LookupResultKind
Get
Return _kind
End Get
End Property
' Should we stop looking further for a better result? Stop for kind EmptyAndStopLookup, WrongArityAndStopLookup, Ambigiuous, or Good.
Public ReadOnly Property StopFurtherLookup As Boolean
Get
Return _kind >= LookupResultKind.EmptyAndStopLookup
End Get
End Property
' Does it have a symbol without error.
Public ReadOnly Property IsGood As Boolean
Get
Return _kind = LookupResultKind.Good
End Get
End Property
Public ReadOnly Property IsGoodOrAmbiguous As Boolean
Get
Return _kind = LookupResultKind.Good OrElse _kind = LookupResultKind.Ambiguous
End Get
End Property
Public ReadOnly Property IsAmbiguous As Boolean
Get
Return _kind = LookupResultKind.Ambiguous
End Get
End Property
Public ReadOnly Property IsWrongArity As Boolean
Get
Return _kind = LookupResultKind.WrongArity OrElse _kind = LookupResultKind.WrongArityAndStopLookup
End Get
End Property
Public ReadOnly Property HasDiagnostic As Boolean
Get
Return _diagInfo IsNot Nothing
End Get
End Property
Public ReadOnly Property Diagnostic As DiagnosticInfo
Get
Return _diagInfo
End Get
End Property
Public ReadOnly Property HasSymbol As Boolean
Get
Return _symList.Count > 0
End Get
End Property
Public ReadOnly Property HasSingleSymbol As Boolean
Get
Return _symList.Count = 1
End Get
End Property
Public ReadOnly Property Symbols As ArrayBuilder(Of Symbol)
Get
Return _symList
End Get
End Property
Public ReadOnly Property SingleSymbol As Symbol
Get
Debug.Assert(HasSingleSymbol)
Return _symList(0)
End Get
End Property
''''''''''''''''''''''''''''''
' Creation routines
Private Shared ReadOnly s_poolInstance As ObjectPool(Of LookupResult) = CreatePool()
Private Shared Function CreatePool() As ObjectPool(Of LookupResult)
Dim pool As ObjectPool(Of LookupResult) = Nothing
pool = New ObjectPool(Of LookupResult)(Function() New LookupResult(pool), 128)
Return pool
End Function
' Private constructor. Use shared methods for construction.
Private Sub New(pool As ObjectPool(Of LookupResult))
MyClass.New()
_pool = pool
End Sub
' used by unit tests
Friend Sub New()
_kind = LookupResultKind.Empty
_symList = New ArrayBuilder(Of Symbol)
_diagInfo = Nothing
End Sub
Public Shared Function GetInstance() As LookupResult
Return s_poolInstance.Allocate()
End Function
Public Sub Free()
Clear()
If _pool IsNot Nothing Then
_pool.Free(Me)
End If
End Sub
Public Sub Clear()
_kind = LookupResultKind.Empty
_symList.Clear()
_diagInfo = Nothing
End Sub
Public ReadOnly Property IsClear As Boolean
Get
Return _kind = LookupResultKind.Empty AndAlso _symList.Count = 0 AndAlso _diagInfo Is Nothing
End Get
End Property
Private Sub SetFrom(kind As LookupResultKind, sym As Symbol, diagInfo As DiagnosticInfo)
_kind = kind
_symList.Clear()
If sym IsNot Nothing Then
_symList.Add(sym)
End If
_diagInfo = diagInfo
End Sub
''' <summary>
''' Set current result according to another
''' </summary>
Public Sub SetFrom(other As SingleLookupResult)
SetFrom(other.Kind, other.Symbol, other.Diagnostic)
End Sub
''' <summary>
''' Set current result according to another
''' </summary>
Public Sub SetFrom(other As LookupResult)
_kind = other._kind
_symList.Clear()
_symList.AddRange(other._symList)
_diagInfo = other._diagInfo
End Sub
''' <summary>
''' Set current result according to a given symbol
''' </summary>
''' <param name="s"></param>
''' <remarks></remarks>
Public Sub SetFrom(s As Symbol)
SetFrom(SingleLookupResult.Good(s))
End Sub
' Get a result for set of symbols.
' If the set is empty, an empty result is created.
' If the set has one member, a good (viable) symbol is created.
' If the set has more than one member, the first member is a good result, but an ambiguity error
' is attached with all the ambiguous symbols in it. The supplied delegate is called to generate the
' ambiguity error (only if the set has >1 symbol in it).
Public Sub SetFrom(syms As ImmutableArray(Of Symbol),
generateAmbiguityDiagnostic As Func(Of ImmutableArray(Of Symbol), AmbiguousSymbolDiagnostic))
If syms.Length = 0 Then
' no symbols provided. return empty result
Clear()
ElseIf syms.Length > 1 Then
' ambiguous symbols.
Dim diagInfo As DiagnosticInfo = generateAmbiguityDiagnostic(syms)
SetFrom(LookupResultKind.Ambiguous, syms(0), diagInfo)
Else
' single good symbol
SetFrom(SingleLookupResult.Good(syms(0)))
End If
End Sub
''''''''''''''''''''''''''''''
' Combining routines
' Merge two results, returning the better one. If they are equally good, the first has
' priority. Never produces an ambiguity.
Public Sub MergePrioritized(other As LookupResult)
If other.Kind > Me.Kind AndAlso Me.Kind < LookupResultKind.Ambiguous Then
SetFrom(other)
End If
End Sub
' Merge two results, returning the better one. If they are equally good, the first has
' priority. Never produces an ambiguity.
Public Sub MergePrioritized(other As SingleLookupResult)
If other.Kind > Me.Kind AndAlso Me.Kind < LookupResultKind.Ambiguous Then
SetFrom(other)
End If
End Sub
' Merge two results, returning the best. If there are
' multiple viable results, instead produce an ambiguity between all of them.
Public Sub MergeAmbiguous(other As LookupResult,
generateAmbiguityDiagnostic As Func(Of ImmutableArray(Of Symbol), AmbiguousSymbolDiagnostic))
If Me.IsGoodOrAmbiguous AndAlso other.IsGoodOrAmbiguous Then
' Two viable or ambiguous results. Produce ambiguity.
Dim ambiguousResults = ArrayBuilder(Of Symbol).GetInstance()
If TypeOf Me.Diagnostic Is AmbiguousSymbolDiagnostic Then
ambiguousResults.AddRange(DirectCast(Me.Diagnostic, AmbiguousSymbolDiagnostic).AmbiguousSymbols)
Else
ambiguousResults.AddRange(Me.Symbols)
End If
If TypeOf other.Diagnostic Is AmbiguousSymbolDiagnostic Then
ambiguousResults.AddRange(DirectCast(other.Diagnostic, AmbiguousSymbolDiagnostic).AmbiguousSymbols)
Else
ambiguousResults.AddRange(other.Symbols)
End If
SetFrom(ambiguousResults.ToImmutableAndFree(), generateAmbiguityDiagnostic)
ElseIf other.Kind > Me.Kind Then
SetFrom(other)
Else
Return
End If
End Sub
' Merge two results, returning the best. If there are
' multiple viable results, instead produce an ambiguity between all of them.
Public Sub MergeAmbiguous(other As SingleLookupResult,
generateAmbiguityDiagnostic As Func(Of ImmutableArray(Of Symbol), AmbiguousSymbolDiagnostic))
If Me.IsGoodOrAmbiguous AndAlso other.IsGoodOrAmbiguous Then
' Two viable results. Produce ambiguity.
Dim ambiguousResults = ArrayBuilder(Of Symbol).GetInstance()
If TypeOf Me.Diagnostic Is AmbiguousSymbolDiagnostic Then
ambiguousResults.AddRange(DirectCast(Me.Diagnostic, AmbiguousSymbolDiagnostic).AmbiguousSymbols)
Else
ambiguousResults.AddRange(Me.Symbols)
End If
If TypeOf other.Diagnostic Is AmbiguousSymbolDiagnostic Then
ambiguousResults.AddRange(DirectCast(other.Diagnostic, AmbiguousSymbolDiagnostic).AmbiguousSymbols)
Else
ambiguousResults.Add(other.Symbol)
End If
SetFrom(ambiguousResults.ToImmutableAndFree(), generateAmbiguityDiagnostic)
ElseIf other.Kind > Me.Kind Then
SetFrom(other)
Else
Return
End If
End Sub
' Determine if two symbols can overload each other.
' Two symbols that are both methods or both properties can overload each other.
Public Shared Function CanOverload(sym1 As Symbol, sym2 As Symbol) As Boolean
Return sym1.Kind = sym2.Kind AndAlso sym1.IsOverloadable AndAlso sym2.IsOverloadable
End Function
' Determine if all property or method symbols in the current result have the "Overloads" modifier.
' The "Overloads" modifier is the opposite of the "Shadows" modifier.
Public Function AllSymbolsHaveOverloads() As Boolean
For Each sym In Symbols
Select Case sym.Kind
Case SymbolKind.Method
If Not DirectCast(sym, MethodSymbol).IsOverloads Then
Return False
End If
Case SymbolKind.Property
If Not DirectCast(sym, PropertySymbol).IsOverloads Then
Return False
End If
End Select
Next
Return True
End Function
' Merge two results, returning the best. If there are
' multiple viable results, either produce an result with both symbols if they can overload each other,
' or use the current one..
Public Sub MergeOverloadedOrPrioritizedExtensionMethods(other As SingleLookupResult)
Debug.Assert(Not Me.IsAmbiguous AndAlso Not other.IsAmbiguous)
Debug.Assert(other.Symbol.IsReducedExtensionMethod())
Debug.Assert(Not Me.HasSymbol OrElse Me.Symbols(0).IsReducedExtensionMethod())
If Me.IsGood AndAlso other.IsGood Then
_symList.Add(other.Symbol)
ElseIf other.Kind > Me.Kind Then
SetFrom(other)
ElseIf Me.Kind <> LookupResultKind.Inaccessible OrElse Me.Kind > other.Kind Then
Return
Else
_symList.Add(other.Symbol)
End If
End Sub
' Merge two results, returning the best. If there are
' multiple viable results, either produce a result with both symbols if they can overload each other,
' or use the current.
' If the "checkIfCurrentHasOverloads" is True, then we only overload if every symbol in our current result has "Overloads" modifier; otherwise
' we overload regardless of the modifier.
Public Sub MergeOverloadedOrPrioritized(other As LookupResult, checkIfCurrentHasOverloads As Boolean)
If Me.IsGoodOrAmbiguous AndAlso other.IsGoodOrAmbiguous Then
If Me.IsGood AndAlso other.IsGood Then
' Two viable results. Either they can overload each other, or we need to produce an ambiguity.
If CanOverload(Me.Symbols(0), other.Symbols(0)) AndAlso (Not checkIfCurrentHasOverloads OrElse AllSymbolsHaveOverloads()) Then
_symList.AddRange(other.Symbols)
Else
' They don't overload each other. Just hide.
Return
End If
Else
Debug.Assert(Me.IsAmbiguous OrElse other.IsAmbiguous)
' Stick with the current result.
' Good result from derived class shouldn't be overriden by an ambiguous result from the base class.
' Ambiguous result from derived class shouldn't be overriden by a good result from the base class.
Return
End If
ElseIf other.Kind > Me.Kind Then
SetFrom(other)
ElseIf Me.Kind <> LookupResultKind.Inaccessible OrElse Me.Kind > other.Kind OrElse
Not CanOverload(Me.Symbols(0), other.Symbols(0)) OrElse
(checkIfCurrentHasOverloads AndAlso Not AllSymbolsHaveOverloads()) Then
Return
Else
_symList.AddRange(other.Symbols)
End If
End Sub
''' <summary>
''' Merge two results, returning the best. If there are
''' multiple viable results, either produce a result with both symbols if they
''' can overload each other, or use the current.
''' </summary>
''' <param name="other">Other result.</param>
''' <param name="checkIfCurrentHasOverloads">
''' If the checkIfCurrentHasOverloads is True, then we only overload if every symbol in
''' our current result has "Overloads" modifier; otherwise we overload
''' regardless of the modifier.
''' </param>
''' <remarks></remarks>
Public Sub MergeOverloadedOrPrioritized(other As SingleLookupResult, checkIfCurrentHasOverloads As Boolean)
If Me.IsGoodOrAmbiguous AndAlso other.IsGoodOrAmbiguous Then
If Me.IsGood AndAlso other.IsGood Then
' Two viable results. Either they can overload each other, or we need to produce an ambiguity.
If CanOverload(Me.Symbols(0), other.Symbol) AndAlso (Not checkIfCurrentHasOverloads OrElse AllSymbolsHaveOverloads()) Then
_symList.Add(other.Symbol)
Else
' They don't overload each other. Just hide.
Return
End If
Else
Debug.Assert(Me.IsAmbiguous OrElse other.IsAmbiguous)
' Stick with the current result.
' Good result from derived class shouldn't be overriden by an ambiguous result from the base class.
' Ambiguous result from derived class shouldn't be overriden by a good result from the base class.
Return
End If
ElseIf other.Kind > Me.Kind Then
SetFrom(other)
ElseIf Me.Kind <> LookupResultKind.Inaccessible OrElse Me.Kind > other.Kind OrElse
Not CanOverload(Me.Symbols(0), other.Symbol) OrElse
(checkIfCurrentHasOverloads AndAlso Not AllSymbolsHaveOverloads()) Then
Return
Else
_symList.Add(other.Symbol)
End If
End Sub
' Merge two results, returning the best. If there are
' multiple viable results, either produce an result with both symbols if they can overload each other,
' or produce an ambiguity error otherwise.
Public Sub MergeMembersOfTheSameType(other As SingleLookupResult, imported As Boolean)
Debug.Assert(Not Me.HasSymbol OrElse other.Symbol Is Nothing OrElse Me.Symbols(0).ContainingType = other.Symbol.ContainingType)
Debug.Assert(Not other.IsAmbiguous)
If Me.IsGoodOrAmbiguous AndAlso other.IsGood Then
' Two viable results. Either they can overload each other, or we need to produce an ambiguity.
MergeOverloadedOrAmbiguousInTheSameType(other, imported)
ElseIf other.Kind > Me.Kind Then
SetFrom(other)
ElseIf Me.Kind <> LookupResultKind.Inaccessible OrElse Me.Kind > other.Kind OrElse
Not CanOverload(Me.Symbols(0), other.Symbol) Then
Return
Else
_symList.Add(other.Symbol)
End If
End Sub
Private Sub MergeOverloadedOrAmbiguousInTheSameType(other As SingleLookupResult, imported As Boolean)
Debug.Assert(Me.IsGoodOrAmbiguous AndAlso other.IsGood)
If Me.IsGood Then
If CanOverload(Me.Symbols(0), other.Symbol) Then
_symList.Add(other.Symbol)
Return
End If
If imported Then
' Prefer more accessible symbols.
Dim lost As Integer = 0
Dim ambiguous As Integer = 0
Dim otherLost As Boolean = False
Dim i As Integer
For i = 0 To _symList.Count - 1
Dim accessibilityCmp As Integer = CompareAccessibilityOfSymbolsConflictingInSameContainer(_symList(i), other.Symbol)
If accessibilityCmp = 0 Then
ambiguous += 1
ElseIf accessibilityCmp < 0 Then
lost += 1
_symList(i) = Nothing
Else
otherLost = True
End If
Next
If lost = _symList.Count Then
Debug.Assert(Not otherLost AndAlso ambiguous = 0)
SetFrom(other)
Return
End If
If otherLost Then
Debug.Assert(lost + ambiguous < _symList.Count)
' Remove ambiguous from the result, because they lost as well.
If ambiguous > 0 Then
lost += ambiguous
ambiguous = RemoveAmbiguousSymbols(other.Symbol, ambiguous)
End If
Debug.Assert(ambiguous = 0)
Else
Debug.Assert(ambiguous = _symList.Count - lost)
End If
' Compact the array of symbols
CompactSymbols(lost)
Debug.Assert(_symList.Count > 0)
If otherLost Then
Return
End If
End If
ElseIf imported Then
Debug.Assert(Me.IsAmbiguous)
' This function guarantees that accessibility of all ambiguous symbols,
' even those dropped from the list by MergeAmbiguous is the same.
' So, it is sufficient to test accesibility of the only symbol we have.
Dim accessibilityCmp As Integer = CompareAccessibilityOfSymbolsConflictingInSameContainer(_symList(0), other.Symbol)
If accessibilityCmp < 0 Then
SetFrom(other)
Return
ElseIf accessibilityCmp > 0 Then
Return
End If
End If
#If DEBUG Then
If imported Then
For i = 0 To _symList.Count - 1
Debug.Assert(_symList(i).DeclaredAccessibility = other.Symbol.DeclaredAccessibility)
Next
End If
#End If
' We were unable to resolve the ambiguity
MergeAmbiguous(other, s_ambiguousInTypeError)
End Sub
' Create a diagnostic for ambiguous names in the same type. This is typically not possible from source, only
' from metadata.
Private Shared ReadOnly s_ambiguousInTypeError As Func(Of ImmutableArray(Of Symbol), AmbiguousSymbolDiagnostic) =
Function(syms As ImmutableArray(Of Symbol)) As AmbiguousSymbolDiagnostic
Dim name As String = syms(0).Name
Dim container As Symbol = syms(0).ContainingSymbol
Debug.Assert(container IsNot Nothing, "ContainingSymbol property of the first ambiguous symbol cannot be Nothing")
Dim containerKindText As String = container.GetKindText()
Return New AmbiguousSymbolDiagnostic(ERRID.ERR_MetadataMembersAmbiguous3, syms, name, containerKindText, container)
End Function
Private Sub CompactSymbols(lost As Integer)
If lost > 0 Then
Dim i As Integer
For i = 0 To _symList.Count - 1
If _symList(i) Is Nothing Then
Exit For
End If
Next
Debug.Assert(i < _symList.Count)
Dim left As Integer = _symList.Count - lost
If left > i Then
Dim j As Integer
For j = i + 1 To _symList.Count - 1
If _symList(j) IsNot Nothing Then
_symList(i) = _symList(j)
i += 1
If i = left Then
Exit For
End If
End If
Next
#If DEBUG Then
For j = j + 1 To _symList.Count - 1
Debug.Assert(_symList(j) Is Nothing)
Next
#End If
End If
Debug.Assert(i = left)
_symList.Clip(left)
End If
End Sub
Private Function RemoveAmbiguousSymbols(other As Symbol, ambiguous As Integer) As Integer
Dim i As Integer
For i = 0 To _symList.Count - 1
If _symList(i) IsNot Nothing AndAlso _symList(i).DeclaredAccessibility = other.DeclaredAccessibility Then
_symList(i) = Nothing
ambiguous -= 1
If ambiguous = 0 Then
Exit For
End If
End If
Next
#If DEBUG Then
For i = i + 1 To _symList.Count - 1
Debug.Assert(_symList(i) Is Nothing OrElse _symList(i).DeclaredAccessibility <> other.DeclaredAccessibility)
Next
#End If
Return ambiguous
End Function
''' <summary>
''' Returns: negative value - when first lost, 0 - when neither lost, > 0 - when second lost.
''' </summary>
Public Shared Function CompareAccessibilityOfSymbolsConflictingInSameContainer(
first As Symbol,
second As Symbol
) As Integer
If first.DeclaredAccessibility = second.DeclaredAccessibility Then
Return 0
End If
' Note, Dev10 logic is - if containing assembly has friends, Protected is preferred over Friend,
' otherwise Friend is preferred over Protected.
' That logic (the dependency on presence of InternalsVisibleTo attribute) seems unnecessary complicated.
' If there are friends, we prefer Protected. If there are no friends, we prefer Friend, but Friend members
' are going to be inaccessible (there are no friend assemblies) and will be discarded by the name lookup,
' leaving Protected members uncontested and thus available. Effectively, Protected always wins over Friend,
' regardless of presence of InternalsVisibleTo attributes. Am I missing something?
' For now implementing simple logic - Protected is better than Friend.
If first.DeclaredAccessibility < second.DeclaredAccessibility Then
If first.DeclaredAccessibility = Accessibility.Protected AndAlso
second.DeclaredAccessibility = Accessibility.Friend Then
Return 1
Else
Return -1
End If
Else
If second.DeclaredAccessibility = Accessibility.Protected AndAlso
first.DeclaredAccessibility = Accessibility.Friend Then
Return -1
Else
Return 1
End If
End If
End Function
Public Sub MergeMembersOfTheSameNamespace(other As SingleLookupResult, sourceModule As ModuleSymbol, options As LookupOptions)
Dim resolution As Integer = ResolveAmbiguityInTheSameNamespace(other, sourceModule, options)
If resolution > 0 Then
Return
ElseIf resolution < 0 Then
SetFrom(other)
Return
End If
MergeAmbiguous(other, s_ambiguousInNSError)
End Sub
Private Enum SymbolLocation
FromSourceModule
FromReferencedAssembly
FromCorLibrary
End Enum
Private Shared Function GetSymbolLocation(sym As Symbol, sourceModule As ModuleSymbol, options As LookupOptions) As SymbolLocation
' Dev10 pays attention to the fact that the [sym] refers to a namespace
' and the namespace has a declaration in source. This needs some special handling for merged namespaces.
If sym.Kind = SymbolKind.Namespace Then
Return If(DirectCast(sym, NamespaceSymbol).IsDeclaredInSourceModule(sourceModule),
SymbolLocation.FromSourceModule,
SymbolLocation.FromReferencedAssembly)
End If
If sym.ContainingModule Is sourceModule Then
Return SymbolLocation.FromSourceModule
End If
If (options And LookupOptions.IgnoreCorLibraryDuplicatedTypes) <> 0 Then
' Ignore duplicate types from the cor library if necessary.
' (Specifically the framework assemblies loaded at runtime in
' the EE may contain types also available from mscorlib.dll.)
Dim containingAssembly = sym.ContainingAssembly
If containingAssembly Is containingAssembly.CorLibrary Then
Return SymbolLocation.FromCorLibrary
End If
End If
Return SymbolLocation.FromReferencedAssembly
End Function
''' <summary>
''' Returns: negative value - when current lost, 0 - when neither lost, > 0 - when other lost.
''' </summary>
Private Function ResolveAmbiguityInTheSameNamespace(other As SingleLookupResult, sourceModule As ModuleSymbol, options As LookupOptions) As Integer
Debug.Assert(Not other.IsAmbiguous)
' Symbols in source take priority over symbols in a referenced assembly.
If other.StopFurtherLookup AndAlso
Me.StopFurtherLookup AndAlso Me.Symbols.Count > 0 Then
Dim currentLocation = GetSymbolLocation(other.Symbol, sourceModule, options)
Dim contenderLocation = GetSymbolLocation(Me.Symbols(0), sourceModule, options)
Dim diff = currentLocation - contenderLocation
If diff <> 0 Then
Return diff
End If
End If
If other.IsGood Then
If Me.IsGood Then
Debug.Assert(Me.HasSingleSymbol)
Debug.Assert(Me.Symbols(0).Kind <> SymbolKind.Namespace OrElse other.Symbol.Kind <> SymbolKind.Namespace) ' namespaces are supposed to be merged
Return ResolveAmbiguityInTheSameNamespace(Me.Symbols(0), other.Symbol, sourceModule)
ElseIf Me.IsAmbiguous Then
' Check to see if all symbols in the ambiguous result are types, which lose to the new symbol.
For Each candidate In DirectCast(Me.Diagnostic, AmbiguousSymbolDiagnostic).AmbiguousSymbols
Debug.Assert(candidate.Kind <> SymbolKind.Namespace OrElse other.Symbol.Kind <> SymbolKind.Namespace) ' namespaces are supposed to be merged
If candidate.Kind = SymbolKind.Namespace Then
Return 0 ' namespace never loses
ElseIf ResolveAmbiguityInTheSameNamespace(candidate, other.Symbol, sourceModule) >= 0 Then
Return 0
End If
Next
Return -1
End If
End If
Return 0
End Function
''' <summary>
''' Returns: negative value - when first lost, 0 - when neither lost, > 0 - when second lost.
''' </summary>
Private Shared Function ResolveAmbiguityInTheSameNamespace(first As Symbol, second As Symbol, sourceModule As ModuleSymbol) As Integer
' If both symbols are from the same container, which could happen in metadata,
' prefer most accessible.
If first.ContainingSymbol Is second.ContainingSymbol Then
If first.ContainingModule Is sourceModule Then
Return 0
End If
Return CompareAccessibilityOfSymbolsConflictingInSameContainer(first, second)
Else
' This needs special handling because containing namespace of a merged namespace symbol is a merged namespace symbol.
' So, condition above will fail.
Debug.Assert(first.Kind <> SymbolKind.Namespace OrElse second.Kind <> SymbolKind.Namespace) ' namespaces are supposed to be merged
' This is a conflict of namespace and non-namespace symbol. Having a non-namespace symbol
' defined in the source module along with namespace symbol leads to all types in the namespace
' being unreachable because of an ambiguity error (Return 0 below).
'
' Conditions 'first.IsEmbedded = second.IsEmbedded' below make sure that if an embedded
' namespace like Microsoft.VisualBasic conflicts with user defined type Microsoft.VisualBasic,
' namespace will win making possible to access embedded types via direct reference,
' such as Microsoft.VisualBasic.Embedded
If first.Kind = SymbolKind.Namespace Then
If second.ContainingModule Is sourceModule AndAlso first.IsEmbedded = second.IsEmbedded Then
Return 0
End If
Return ResolveAmbiguityBetweenTypeAndMergedNamespaceInTheSameNamespace(DirectCast(first, NamespaceSymbol), second)
ElseIf second.Kind = SymbolKind.Namespace Then
If first.ContainingModule Is sourceModule AndAlso first.IsEmbedded = second.IsEmbedded Then
Return 0
End If
Return (-1) * ResolveAmbiguityBetweenTypeAndMergedNamespaceInTheSameNamespace(DirectCast(second, NamespaceSymbol), first)
End If
Return 0
End If
End Function
''' <summary>
''' Returns: negative value - when namespace lost, 0 - when neither lost, > 0 - when type lost.
''' </summary>
Private Shared Function ResolveAmbiguityBetweenTypeAndMergedNamespaceInTheSameNamespace(
possiblyMergedNamespace As NamespaceSymbol,
type As Symbol
) As Integer
Debug.Assert(possiblyMergedNamespace.DeclaredAccessibility = Accessibility.Public)
Debug.Assert(type.Kind = SymbolKind.NamedType)
If type.DeclaredAccessibility < Accessibility.Public AndAlso
possiblyMergedNamespace.Extent.Kind <> NamespaceKind.Module Then
' Namespace should be preferred over a non-public type in the same declaring container. But since the namespace symbol
' we have is a merged one, we need to do extra work here to figure out if this is the case.
For Each sibling In DirectCast(type.ContainingSymbol, NamespaceSymbol).GetMembers(type.Name)
If sibling.Kind = SymbolKind.Namespace Then
' namespace is better
Return 1
End If
Next
End If
Return 0
End Function
' Create a diagnostic for ambiguous names in a namespace
Private Shared ReadOnly s_ambiguousInNSError As Func(Of ImmutableArray(Of Symbol), AmbiguousSymbolDiagnostic) =
Function(syms As ImmutableArray(Of Symbol)) As AmbiguousSymbolDiagnostic
Dim container As Symbol = syms(0).ContainingSymbol
If container.Name.Length > 0 Then
Dim containers = syms.Select(Function(sym) sym.ContainingSymbol).
GroupBy(Function(c) c.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), IdentifierComparison.Comparer).
OrderBy(Function(group) group.Key, IdentifierComparison.Comparer).
Select(Function(group) group.First())
If containers.Skip(1).Any() Then
Return New AmbiguousSymbolDiagnostic(ERRID.ERR_AmbiguousInNamespaces2, syms, syms(0).Name, New FormattedSymbolList(containers))
Else
Return New AmbiguousSymbolDiagnostic(ERRID.ERR_AmbiguousInNamespace2, syms, syms(0).Name, container)
End If
Else
Return New AmbiguousSymbolDiagnostic(ERRID.ERR_AmbiguousInUnnamedNamespace1, syms, syms(0).Name)
End If
End Function
''' <summary>
''' Replace the symbol replaced with a new one, but the kind
''' and diagnostics retained from the current result. Typically used when constructing
''' a type from a symbols and type arguments.
''' </summary>
Public Sub ReplaceSymbol(newSym As Symbol)
_symList.Clear()
_symList.Add(newSym)
End Sub
' Return the lowest non-empty result kind.
' However, if one resultKind is Empty and other is Good, we will return LookupResultKind.Empty
Friend Shared Function WorseResultKind(resultKind1 As LookupResultKind, resultKind2 As LookupResultKind) As LookupResultKind
If resultKind1 = LookupResultKind.Empty Then
Return If(resultKind2 = LookupResultKind.Good, LookupResultKind.Empty, resultKind2)
End If
If resultKind2 = LookupResultKind.Empty Then
Return If(resultKind1 = LookupResultKind.Good, LookupResultKind.Empty, resultKind1)
End If
If resultKind1 < resultKind2 Then
Return resultKind1
Else
Return resultKind2
End If
End Function
End Class
End Namespace
|
furesoft/roslyn
|
src/Compilers/VisualBasic/Portable/Binding/LookupResult.vb
|
Visual Basic
|
apache-2.0
| 47,700
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.ChangeSignature
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature
Partial Public Class ChangeSignatureTests
Inherits AbstractChangeSignatureTests
Protected Overrides Function GetLanguage() As String
Return LanguageNames.VisualBasic
End Function
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace) As CodeRefactoringProvider
Return New ChangeSignatureCodeRefactoringProvider()
End Function
Protected Overrides Function CreateWorkspaceFromFileAsync(definition As String, parseOptions As ParseOptions, compilationOptions As CompilationOptions) As Task(Of TestWorkspace)
Return TestWorkspace.CreateVisualBasicAsync(definition, DirectCast(parseOptions, VisualBasicParseOptions), DirectCast(compilationOptions, VisualBasicCompilationOptions))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Delegates_ImplicitInvokeCalls() As Task
Dim markup = <Text><![CDATA[
Delegate Sub $$MySub(x As Integer, y As String, z As Boolean)
Class C
Sub M()
Dim s As MySub = Nothing
s(1, "Two", True)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Delegate Sub MySub(z As Boolean, y As String)
Class C
Sub M()
Dim s As MySub = Nothing
s(True, "Two")
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Delegates_ExplicitInvokeCalls() As Task
Dim markup = <Text><![CDATA[
Delegate Sub $$MySub(x As Integer, y As String, z As Boolean)
Class C
Sub M()
Dim s As MySub = Nothing
s.Invoke(1, "Two", True)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Delegate Sub MySub(z As Boolean, y As String)
Class C
Sub M()
Dim s As MySub = Nothing
s.Invoke(True, "Two")
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Delegates_BeginInvokeCalls() As Task
Dim markup = <Text><![CDATA[
Delegate Sub $$MySub(x As Integer, y As String, z As Boolean)
Class C
Sub M()
Dim s As MySub = Nothing
s.BeginInvoke(1, "Two", True, Nothing, Nothing)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Delegate Sub MySub(z As Boolean, y As String)
Class C
Sub M()
Dim s As MySub = Nothing
s.BeginInvoke(True, "Two", Nothing, Nothing)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Delegates_SubLambdas() As Task
Dim markup = <Text><![CDATA[
Delegate Sub $$MySub(x As Integer, y As String, z As Boolean)
Class C
Sub M()
Dim s As MySub = Nothing
s = Sub()
End Sub
s = Sub(a As Integer, b As String, c As Boolean)
End Sub
s = Sub(a As Integer, b As String, c As Boolean) System.Console.WriteLine("Test")
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Delegate Sub MySub(z As Boolean, y As String)
Class C
Sub M()
Dim s As MySub = Nothing
s = Sub()
End Sub
s = Sub(c As Boolean, b As String)
End Sub
s = Sub(c As Boolean, b As String) System.Console.WriteLine("Test")
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Delegates_FunctionLambdas() As Task
Dim markup = <Text><![CDATA[
Delegate Function $$MyFunc(x As Integer, y As String, z As Boolean) As Integer
Class C
Sub M()
Dim f As MyFunc = Nothing
f = Function()
Return 1
End Function
f = Function(a As Integer, b As String, c As Boolean)
Return 1
End Function
f = Function(a As Integer, b As String, c As Boolean) 1
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Delegate Function MyFunc(z As Boolean, y As String) As Integer
Class C
Sub M()
Dim f As MyFunc = Nothing
f = Function()
Return 1
End Function
f = Function(c As Boolean, b As String)
Return 1
End Function
f = Function(c As Boolean, b As String) 1
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Delegates_ReferencingLambdas_MethodArgument() As Task
Dim markup = <Text><![CDATA[
Delegate Function $$MyFunc(x As Integer, y As String, z As Boolean) As Integer
Class C
Sub M(f As MyFunc)
M(Function(a As Integer, b As String, c As Boolean) 1)
M(Function(a As Integer, b As String, c As Boolean)
Return 1
End Function)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Delegate Function MyFunc(z As Boolean, y As String) As Integer
Class C
Sub M(f As MyFunc)
M(Function(c As Boolean, b As String) 1)
M(Function(c As Boolean, b As String)
Return 1
End Function)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Delegates_ReferencingLambdas_ReturnValue() As Task
Dim markup = <Text><![CDATA[
Delegate Sub $$MySub(x As Integer, y As String, z As Boolean)
Class C
Function M1() As MySub
Return Sub(a As Integer, b As String, c As Boolean)
End Sub
End Function
Function M2() As MySub
Return Sub(a As Integer, b As String, c As Boolean) System.Console.WriteLine("Test")
End Function
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Delegate Sub MySub(z As Boolean, y As String)
Class C
Function M1() As MySub
Return Sub(c As Boolean, b As String)
End Sub
End Function
Function M2() As MySub
Return Sub(c As Boolean, b As String) System.Console.WriteLine("Test")
End Function
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Delegates_Recursive() As Task
Dim markup = <Text><![CDATA[
Delegate Function $$MyFunc(x As Integer, y As String, z As Boolean) As MyFunc
Class C
Sub M()
Dim f As MyFunc = Nothing
f(1, "Two", True)(1, "Two", True)(1, "Two", True)(1, "Two", True)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Delegate Function MyFunc(z As Boolean, y As String) As MyFunc
Class C
Sub M()
Dim f As MyFunc = Nothing
f(True, "Two")(True, "Two")(True, "Two")(True, "Two")
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Delegates_DocComments() As Task
Dim markup = <Text><![CDATA[
''' <summary>
''' This is <see cref="MyFunc"/>, which has these methods:
''' <see cref="MyFunc.New(Object, System.IntPtr)"/>
''' <see cref="MyFunc.Invoke(Integer, String, Boolean)"/>
''' <see cref="MyFunc.EndInvoke(System.IAsyncResult)"/>
''' <see cref="MyFunc.BeginInvoke(Integer, String, Boolean, System.AsyncCallback, Object)"/>
''' </summary>
''' <param name="x">x!</param>
''' <param name="y">y!</param>
''' <param name="z">z!</param>
Delegate Sub $$MyFunc(x As Integer, y As String, z As Boolean)
Class C
Sub M()
Dim f As MyFunc = AddressOf Test
End Sub
''' <param name="a"></param>
''' <param name="b"></param>
''' <param name="c"></param>
Private Sub Test(a As Integer, b As String, c As Boolean)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
''' <summary>
''' This is <see cref="MyFunc"/>, which has these methods:
''' <see cref="MyFunc.New(Object, System.IntPtr)"/>
''' <see cref="MyFunc.Invoke(Boolean, String)"/>
''' <see cref="MyFunc.EndInvoke(System.IAsyncResult)"/>
''' <see cref="MyFunc.BeginInvoke(Boolean, String, System.AsyncCallback, Object)"/>
''' </summary>
''' <param name="z">z!</param>
''' <param name="y">y!</param>
'''
Delegate Sub MyFunc(z As Boolean, y As String)
Class C
Sub M()
Dim f As MyFunc = AddressOf Test
End Sub
''' <param name="c"></param>
''' <param name="b"></param>
'''
Private Sub Test(c As Boolean, b As String)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Delegates_Relaxation_FunctionToSub() As Task
Dim markup = <Text><![CDATA[
Delegate Sub $$MySub(x As Integer, y As String, z As Boolean)
Class C
Sub M()
Dim f As MySub = AddressOf Test
End Sub
Private Function Test(a As Integer, b As String, c As Boolean) As Integer
Return 1
End Function
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Delegate Sub MySub(z As Boolean, y As String)
Class C
Sub M()
Dim f As MySub = AddressOf Test
End Sub
Private Function Test(c As Boolean, b As String) As Integer
Return 1
End Function
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Delegates_Relaxation_ParameterlessFunctionToFunction() As Task
Dim markup = <Text><![CDATA[
Delegate Function $$MyFunc(x As Integer, y As String, z As Boolean) As Integer
Class C
Sub M()
Dim f As MyFunc = AddressOf Test
End Sub
Private Function Test()
Return 1
End Function
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Delegate Function MyFunc(z As Boolean, y As String) As Integer
Class C
Sub M()
Dim f As MyFunc = AddressOf Test
End Sub
Private Function Test()
Return 1
End Function
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Delegates_CascadeToEvents() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Sub $$MyDelegate(x As Integer, y As String, z As Boolean)
Event MyEvent As MyDelegate
Custom Event MyEvent2 As MyDelegate
AddHandler(value As MyDelegate)
End AddHandler
RemoveHandler(value As MyDelegate)
End RemoveHandler
RaiseEvent(x As Integer, y As String, z As Boolean)
End RaiseEvent
End Event
Sub M()
RaiseEvent MyEvent(1, "Two", True)
RaiseEvent MyEvent2(1, "Two", True)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Sub MyDelegate(z As Boolean, y As String)
Event MyEvent As MyDelegate
Custom Event MyEvent2 As MyDelegate
AddHandler(value As MyDelegate)
End AddHandler
RemoveHandler(value As MyDelegate)
End RemoveHandler
RaiseEvent(z As Boolean, y As String)
End RaiseEvent
End Event
Sub M()
RaiseEvent MyEvent(True, "Two")
RaiseEvent MyEvent2(True, "Two")
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Events_ReferencedBy_RaiseEvent() As Task
Dim markup = <Text><![CDATA[
Class C
Event $$MyEvent(x As Integer, y As String, z As Boolean)
Sub M()
RaiseEvent MyEvent(1, "Two", True)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Event MyEvent(z As Boolean, y As String)
Sub M()
RaiseEvent MyEvent(True, "Two")
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Events_ReferencedBy_AddHandler() As Task
Dim markup = <Text><![CDATA[
Class C
Event $$MyEvent(x As Integer, y As String, z As Boolean)
Sub M()
AddHandler MyEvent, AddressOf MyEventHandler
End Sub
Sub MyEventHandler(a As Integer, b As String, c As Boolean)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Event MyEvent(z As Boolean, y As String)
Sub M()
AddHandler MyEvent, AddressOf MyEventHandler
End Sub
Sub MyEventHandler(c As Boolean, b As String)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Events_ReferencedBy_GeneratedDelegateTypeInvocations() As Task
Dim markup = <Text><![CDATA[
Class C
Event $$MyEvent(x As Integer, y As String, z As Boolean)
Sub M()
Dim e As MyEventEventHandler = Nothing
e(1, "Two", True)
e.Invoke(1, "Two", True)
e.BeginInvoke(1, "Two", True, Nothing, New Object())
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Event MyEvent(z As Boolean, y As String)
Sub M()
Dim e As MyEventEventHandler = Nothing
e(True, "Two")
e.Invoke(True, "Two")
e.BeginInvoke(True, "Two", Nothing, New Object())
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Events_ReferencedBy_HandlesClause() As Task
Dim markup = <Text><![CDATA[
Class C
Event $$MyEvent(x As Integer, y As String, z As Boolean)
Sub MyOtherEventHandler(a As Integer, b As String, c As Boolean) Handles Me.MyEvent
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Event MyEvent(z As Boolean, y As String)
Sub MyOtherEventHandler(c As Boolean, b As String) Handles Me.MyEvent
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_CustomEvents_ReferencedBy_RaiseEvent() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Sub MyDelegate(x As Integer, y As String, z As Boolean)
Custom Event $$MyEvent As MyDelegate
AddHandler(value As MyDelegate)
End AddHandler
RemoveHandler(value As MyDelegate)
End RemoveHandler
RaiseEvent(x As Integer, y As String, z As Boolean)
End RaiseEvent
End Event
Sub M()
RaiseEvent MyEvent(1, "Two", True)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Sub MyDelegate(z As Boolean, y As String)
Custom Event MyEvent As MyDelegate
AddHandler(value As MyDelegate)
End AddHandler
RemoveHandler(value As MyDelegate)
End RemoveHandler
RaiseEvent(z As Boolean, y As String)
End RaiseEvent
End Event
Sub M()
RaiseEvent MyEvent(True, "Two")
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_CustomEvents_ReferencedBy_AddHandler() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Sub MyDelegate(x As Integer, y As String, z As Boolean)
Custom Event $$MyEvent As MyDelegate
AddHandler(value As MyDelegate)
End AddHandler
RemoveHandler(value As MyDelegate)
End RemoveHandler
RaiseEvent(x As Integer, y As String, z As Boolean)
End RaiseEvent
End Event
Sub M()
AddHandler MyEvent, AddressOf MyEventHandler
End Sub
Sub MyEventHandler(a As Integer, b As String, c As Boolean)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Sub MyDelegate(z As Boolean, y As String)
Custom Event MyEvent As MyDelegate
AddHandler(value As MyDelegate)
End AddHandler
RemoveHandler(value As MyDelegate)
End RemoveHandler
RaiseEvent(z As Boolean, y As String)
End RaiseEvent
End Event
Sub M()
AddHandler MyEvent, AddressOf MyEventHandler
End Sub
Sub MyEventHandler(c As Boolean, b As String)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_CustomEvents_ReferencedBy_Invocations() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Sub MyDelegate(x As Integer, y As String, z As Boolean)
Custom Event $$MyEvent As MyDelegate
AddHandler(value As MyDelegate)
End AddHandler
RemoveHandler(value As MyDelegate)
End RemoveHandler
RaiseEvent(x As Integer, y As String, z As Boolean)
End RaiseEvent
End Event
Sub M()
Dim e As MyDelegate = Nothing
e(1, "Two", True)
e.Invoke(1, "Two", True)
e.BeginInvoke(1, "Two", True, Nothing, New Object())
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Sub MyDelegate(z As Boolean, y As String)
Custom Event MyEvent As MyDelegate
AddHandler(value As MyDelegate)
End AddHandler
RemoveHandler(value As MyDelegate)
End RemoveHandler
RaiseEvent(z As Boolean, y As String)
End RaiseEvent
End Event
Sub M()
Dim e As MyDelegate = Nothing
e(True, "Two")
e.Invoke(True, "Two")
e.BeginInvoke(True, "Two", Nothing, New Object())
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_CustomEvents_ReferencedBy_HandlesClause() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Sub MyDelegate(x As Integer, y As String, z As Boolean)
Custom Event $$MyEvent As MyDelegate
AddHandler(value As MyDelegate)
End AddHandler
RemoveHandler(value As MyDelegate)
End RemoveHandler
RaiseEvent(x As Integer, y As String, z As Boolean)
End RaiseEvent
End Event
Sub MyOtherEventHandler(a As Integer, b As String, c As Boolean) Handles Me.MyEvent
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {2, 1}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Sub MyDelegate(z As Boolean, y As String)
Custom Event MyEvent As MyDelegate
AddHandler(value As MyDelegate)
End AddHandler
RemoveHandler(value As MyDelegate)
End RemoveHandler
RaiseEvent(z As Boolean, y As String)
End RaiseEvent
End Event
Sub MyOtherEventHandler(c As Boolean, b As String) Handles Me.MyEvent
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Delegates_Generics() As Task
Dim markup = <Text><![CDATA[
Delegate Sub $$MyDelegate(Of T)(t As T)
Class C
Sub B()
Dim d = New MyDelegate(Of Integer)(AddressOf M1)
End Sub
Sub M1(i As Integer)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = Array.Empty(Of Integer)()
Dim expectedUpdatedCode = <Text><![CDATA[
Delegate Sub MyDelegate(Of T)()
Class C
Sub B()
Dim d = New MyDelegate(Of Integer)(AddressOf M1)
End Sub
Sub M1()
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
End Class
End Namespace
|
jaredpar/roslyn
|
src/EditorFeatures/VisualBasicTest/ChangeSignature/ChangeSignature_Delegates.vb
|
Visual Basic
|
apache-2.0
| 26,389
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
Public Class PDBExternalSourceDirectiveTests
Inherits BasicTestBase
<Fact>
Public Sub TwoMethodsOnlyOneWithMapping()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
Console.WriteLine("Hello World")
#End ExternalSource
Console.WriteLine("Hello World")
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="ff1816ec-aa5e-4d10-87f7-6f4963833460" checkSum="70, 82, DD, 9A, 57, B3, BE, 57, 7E, E8, B4, AE, B8, 1E, 1B, 75, 38, 9D, 13, C9, "/>
<file id="2" name="C:\abc\def.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="FooInvisible">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x1" hidden="true" document="1"/>
<entry offset="0x7" hidden="true" document="1"/>
<entry offset="0x18" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x19">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="str" il_index="0" il_start="0x0" il_end="0x19" attributes="0"/>
</scope>
</method>
<method containingType="C1" name="Main">
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x1" hidden="true" document="1"/>
<entry offset="0xc" startLine="23" startColumn="9" endLine="23" endColumn="41" document="2"/>
<entry offset="0x17" hidden="true" document="2"/>
<entry offset="0x22" hidden="true" document="2"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x23">
<importsforward declaringType="C1" methodName="FooInvisible"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact>
Public Sub TwoMethodsOnlyOneWithMultipleMappingsAndRewriting()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
Console.WriteLine("Hello World")
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def2.vb", 42)
' check that there are normal and hidden sequence points with mapping present
' because a for each will be rewritten
for each i in new Integer() {1, 2, 3}
Console.WriteLine(i)
next i
#End ExternalSource
Console.WriteLine("Hello World")
' hidden sequence points of rewritten statements will survive *iiks*.
for each i in new Integer() {1, 2, 3}
Console.WriteLine(i)
next i
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="ff1816ec-aa5e-4d10-87f7-6f4963833460" checkSum="DB, A9, 94, EF, BC, DF, 10, C9, 60, F, C0, C4, 9F, E4, 77, F9, 37, CF, E1, CE, "/>
<file id="2" name="C:\abc\def.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd"/>
<file id="3" name="C:\abc\def2.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="FooInvisible">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x1" hidden="true" document="1"/>
<entry offset="0x7" hidden="true" document="1"/>
<entry offset="0x18" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x19">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="str" il_index="0" il_start="0x0" il_end="0x19" attributes="0"/>
</scope>
</method>
<method containingType="C1" name="Main">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="372"/>
<slot kind="6" offset="363"/>
<slot kind="8" offset="363"/>
<slot kind="1" offset="363"/>
<slot kind="6" offset="606"/>
<slot kind="8" offset="606"/>
<slot kind="1" offset="606"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x1" hidden="true" document="1"/>
<entry offset="0xc" startLine="23" startColumn="9" endLine="23" endColumn="41" document="2"/>
<entry offset="0x17" startLine="24" startColumn="9" endLine="24" endColumn="41" document="2"/>
<entry offset="0x22" startLine="44" startColumn="9" endLine="44" endColumn="46" document="3"/>
<entry offset="0x36" hidden="true" document="3"/>
<entry offset="0x41" startLine="45" startColumn="13" endLine="45" endColumn="33" document="3"/>
<entry offset="0x4d" startLine="46" startColumn="9" endLine="46" endColumn="15" document="3"/>
<entry offset="0x4e" hidden="true" document="3"/>
<entry offset="0x52" hidden="true" document="3"/>
<entry offset="0x59" hidden="true" document="3"/>
<entry offset="0x5c" hidden="true" document="3"/>
<entry offset="0x67" hidden="true" document="3"/>
<entry offset="0x7d" hidden="true" document="3"/>
<entry offset="0x8a" hidden="true" document="3"/>
<entry offset="0x96" hidden="true" document="3"/>
<entry offset="0x97" hidden="true" document="3"/>
<entry offset="0x9d" hidden="true" document="3"/>
<entry offset="0xa7" hidden="true" document="3"/>
<entry offset="0xab" hidden="true" document="3"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xac">
<importsforward declaringType="C1" methodName="FooInvisible"/>
<local name="i" il_index="0" il_start="0x0" il_end="0xac" attributes="0"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact>
Public Sub EmptyExternalSourceWillBeIgnored()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
#End ExternalSource
Console.WriteLine("Hello World")
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="ff1816ec-aa5e-4d10-87f7-6f4963833460" checkSum="EE, 47, B3, F6, 59, FA, D, E8, DF, B2, 26, 6A, 7D, 82, D3, 52, 3E, C, 36, E1, "/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="FooInvisible">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="37" document="1"/>
<entry offset="0x1" startLine="10" startColumn="13" endLine="10" endColumn="37" document="1"/>
<entry offset="0x7" startLine="11" startColumn="9" endLine="11" endColumn="42" document="1"/>
<entry offset="0x18" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x19">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="str" il_index="0" il_start="0x0" il_end="0x19" attributes="0"/>
</scope>
</method>
<method containingType="C1" name="Main">
<sequencePoints>
<entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="29" document="1"/>
<entry offset="0x1" startLine="15" startColumn="9" endLine="15" endColumn="41" document="1"/>
<entry offset="0xc" startLine="20" startColumn="9" endLine="20" endColumn="41" document="1"/>
<entry offset="0x17" startLine="21" startColumn="5" endLine="21" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x18">
<importsforward declaringType="C1" methodName="FooInvisible"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact>
Public Sub MultipleEmptyExternalSourceWillBeIgnored()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
#ExternalSource("C:\abc\def.vb", 21)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 22)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
#End ExternalSource
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="ff1816ec-aa5e-4d10-87f7-6f4963833460" checkSum="B9, 85, 76, 74, 1E, E7, 27, 25, F7, 8A, CB, A2, B1, 9C, A4, CD, FD, 49, 8C, B7, "/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="FooInvisible">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="37" document="1"/>
<entry offset="0x1" startLine="10" startColumn="13" endLine="10" endColumn="37" document="1"/>
<entry offset="0x7" startLine="11" startColumn="9" endLine="11" endColumn="42" document="1"/>
<entry offset="0x18" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x19">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="str" il_index="0" il_start="0x0" il_end="0x19" attributes="0"/>
</scope>
</method>
<method containingType="C1" name="Main">
<sequencePoints>
<entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="29" document="1"/>
<entry offset="0x1" startLine="18" startColumn="9" endLine="18" endColumn="41" document="1"/>
<entry offset="0xc" startLine="23" startColumn="9" endLine="23" endColumn="41" document="1"/>
<entry offset="0x17" startLine="27" startColumn="5" endLine="27" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x18">
<importsforward declaringType="C1" methodName="FooInvisible"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact>
Public Sub MultipleEmptyExternalSourceWithNonEmptyExternalSource()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
#ExternalSource("C:\abc\def.vb", 21)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 22)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
' boo!
#End ExternalSource
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="ff1816ec-aa5e-4d10-87f7-6f4963833460" checkSum="B6, 80, 9E, 65, 43, 38, 0, C1, 35, 7F, AE, D0, 60, F2, 24, 44, A8, 11, C2, 63, "/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="FooInvisible">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x1" hidden="true" document="1"/>
<entry offset="0x7" hidden="true" document="1"/>
<entry offset="0x18" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x19">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="str" il_index="0" il_start="0x0" il_end="0x19" attributes="0"/>
</scope>
</method>
<method containingType="C1" name="Main">
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x1" hidden="true" document="1"/>
<entry offset="0xc" hidden="true" document="1"/>
<entry offset="0x17" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x18">
<importsforward declaringType="C1" methodName="FooInvisible"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact>
Public Sub MultipleEmptyExternalSourceWithNonEmptyExternalSourceFollowedByEmptyExternalSource()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
#ExternalSource("C:\abc\def.vb", 21)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 22)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
#End ExternalSource
Console.WriteLine("Hello World")
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="ff1816ec-aa5e-4d10-87f7-6f4963833460" checkSum="73, 5, 84, 40, AC, E0, 15, 63, CC, FE, BD, 9A, 99, 23, AA, BD, 24, 40, 24, 44, "/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="FooInvisible">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x1" hidden="true" document="1"/>
<entry offset="0x7" hidden="true" document="1"/>
<entry offset="0x18" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x19">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="str" il_index="0" il_start="0x0" il_end="0x19" attributes="0"/>
</scope>
</method>
<method containingType="C1" name="Main">
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x1" hidden="true" document="1"/>
<entry offset="0xc" hidden="true" document="1"/>
<entry offset="0x17" hidden="true" document="1"/>
<entry offset="0x22" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x23">
<importsforward declaringType="C1" methodName="FooInvisible"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact()>
Public Sub TestPartialClassFieldInitializersWithExternalSource()
Dim source =
<compilation>
<file name="C:\Abc\ACTUAL.vb">
#ExternalSource("C:\abc\def1.vb", 41)
Option strict on
imports system
partial Class C1
public f1 as integer = 23
#End ExternalSource
#ExternalSource("C:\abc\def1.vb", 10)
Public sub DumpFields()
Console.WriteLine(f1)
Console.WriteLine(f2)
End Sub
#End ExternalSource
#ExternalSource("C:\abc\def1.vb", 1)
Public shared Sub Main(args() as string)
Dim c as new C1
c.DumpFields()
End sub
#End ExternalSource
End Class
Class InActual
public f1 as integer = 23
end Class
#ExternalChecksum("C:\abc\def2.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "1234")
#ExternalChecksum("BOGUS.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "1234")
#ExternalChecksum("C:\Abc\ACTUAL.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "6789")
</file>
<file name="b.vb">
Option strict on
imports system
partial Class C1
#ExternalSource("C:\abc\def2.vb", 23)
' more lines to see a different span in the sequence points ...
public f2 as integer = 42
#End ExternalSource
#ExternalChecksum("BOGUS.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "1234")
#ExternalChecksum("C:\Abc\ACTUAL.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "6789")
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="C:\Abc\ACTUAL.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="ff1816ec-aa5e-4d10-87f7-6f4963833460" checkSum="27, 52, E9, 85, 5A, AC, 31, 5, A5, 6F, 70, 40, 55, 3A, 9C, 43, D2, 7, D, 4B, "/>
<file id="2" name="C:\abc\def1.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd"/>
<file id="3" name="C:\abc\def2.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="406ea660-64cf-4c82-b6f0-42d48172a799" checkSum="12, 34, "/>
</files>
<entryPoint declaringType="C1" methodName="Main" parameterNames="args"/>
<methods>
<method containingType="C1" name=".ctor">
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x7" startLine="46" startColumn="12" endLine="46" endColumn="30" document="2"/>
<entry offset="0xf" startLine="27" startColumn="36" endLine="27" endColumn="54" document="3"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x18">
<namespace name="System" importlevel="file"/>
<currentnamespace name=""/>
</scope>
</method>
<method containingType="C1" name="DumpFields">
<sequencePoints>
<entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="28" document="2"/>
<entry offset="0x1" startLine="11" startColumn="9" endLine="11" endColumn="30" document="2"/>
<entry offset="0xd" startLine="12" startColumn="9" endLine="12" endColumn="30" document="2"/>
<entry offset="0x19" startLine="13" startColumn="5" endLine="13" endColumn="12" document="2"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x1a">
<importsforward declaringType="C1" methodName=".ctor"/>
</scope>
</method>
<method containingType="C1" name="Main" parameterNames="args">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="1" startColumn="5" endLine="1" endColumn="45" document="2"/>
<entry offset="0x1" startLine="2" startColumn="13" endLine="2" endColumn="24" document="2"/>
<entry offset="0x7" startLine="3" startColumn="9" endLine="3" endColumn="23" document="2"/>
<entry offset="0xe" startLine="4" startColumn="5" endLine="4" endColumn="12" document="2"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xf">
<importsforward declaringType="C1" methodName=".ctor"/>
<local name="c" il_index="0" il_start="0x0" il_end="0xf" attributes="0"/>
</scope>
</method>
<method containingType="InActual" name=".ctor">
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x7" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x10">
<importsforward declaringType="C1" methodName=".ctor"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact()>
Public Sub IllegalExternalSourceUsageShouldNotAssert_1()
Dim source =
<compilation>
<file name="a.vb">
Option strict on
public Class C1
#ExternalSource("bar1.vb", 41)
#ExternalSource("bar1.vb", 41)
public shared sub main()
End sub
#End ExternalSource
#End ExternalSource
boo
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
source,
TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_NestedExternalSource, "#ExternalSource(""bar1.vb"", 41)"),
Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"))
End Sub
<Fact()>
Public Sub IllegalExternalSourceUsageShouldNotAssert_2()
Dim source =
<compilation>
<file name="a.vb">
Option strict on
public Class C1
#End ExternalSource
#End ExternalSource
public shared sub main()
End sub
boo
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
source,
TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"),
Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "boo"))
End Sub
<Fact()>
Public Sub IllegalExternalSourceUsageShouldNotAssert_3()
Dim source =
<compilation>
<file name="a.vb">
Option strict on
public Class C1
#End ExternalSource
#ExternalSource("bar1.vb", 23)
public shared sub main()
End sub
boo
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
source,
TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"),
Diagnostic(ERRID.ERR_ExpectedEndExternalSource, "#ExternalSource(""bar1.vb"", 23)"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "boo"))
End Sub
<WorkItem(545302, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545302")>
<Fact()>
Public Sub IllegalExternalSourceUsageShouldNotAssert_4()
Dim source =
<compilation>
<file name="a.vb">
Module Program
Sub Main()
#ExternalSource ("bar1.vb", 23)
#ExternalSource ("bar1.vb", 23)
System.Console.WriteLine("boo")
#End ExternalSource
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
source,
TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_NestedExternalSource, "#ExternalSource (""bar1.vb"", 23)"))
End Sub
<WorkItem(545307, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545307")>
<Fact>
Public Sub OverflowLineNumbers()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Imports System.Collections.Generic
Module Program
Public Sub Main()
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 0)
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def.vb", 1)
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def.vb", 2147483647)
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def.vb", 2147483648)
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def.vb", 2147483649)
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def.vb", &hfeefed)
Console.WriteLine("Hello World")
#End ExternalSource
Console.WriteLine("Hello World")
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="ff1816ec-aa5e-4d10-87f7-6f4963833460" checkSum="D2, FF, 5, F8, B7, A2, 25, B0, 96, D9, 97, 2F, 5, F8, F0, B5, 81, 8D, 98, 1D, "/>
<file id="2" name="C:\abc\def.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd"/>
</files>
<entryPoint declaringType="Program" methodName="Main"/>
<methods>
<method containingType="Program" name="Main">
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x1" hidden="true" document="1"/>
<entry offset="0xc" startLine="0" startColumn="9" endLine="0" endColumn="41" document="2"/>
<entry offset="0x17" startLine="1" startColumn="9" endLine="1" endColumn="41" document="2"/>
<entry offset="0x22" startLine="16777215" startColumn="9" endLine="16777215" endColumn="41" document="2"/>
<entry offset="0x2d" startLine="16777215" startColumn="9" endLine="16777215" endColumn="41" document="2"/>
<entry offset="0x38" startLine="16777215" startColumn="9" endLine="16777215" endColumn="41" document="2"/>
<entry offset="0x43" startLine="16707565" startColumn="9" endLine="16707565" endColumn="41" document="2"/>
<entry offset="0x4e" hidden="true" document="2"/>
<entry offset="0x59" hidden="true" document="2"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x5a">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>, format:=DebugInformationFormat.Pdb)
End Sub
<Fact, WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")>
Public Sub RelativePathForExternalSource()
Dim source =
<compilation>
<file name="C:\Folder1\Folder2\Test1.vb">
#ExternalChecksum("..\Test2.vb","{406ea660-64cf-4c82-b6f0-42d48172a799}","DB788882721B2B27C90579D5FE2A0418")
Class Test1
Sub Main()
#ExternalSource("..\Test2.vb",4)
Main()
#End ExternalSource
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
source,
TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default))
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="C:\Folder1\Folder2\Test1.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="ff1816ec-aa5e-4d10-87f7-6f4963833460" checkSum="B9, 49, 3D, 62, 89, 9B, B2, 2F, B6, 72, 90, A1, 2D, 1, 11, 89, B4, C2, 83, B4, "/>
<file id="2" name="C:\Folder1\Test2.vb" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" checkSumAlgorithmId="406ea660-64cf-4c82-b6f0-42d48172a799" checkSum="DB, 78, 88, 82, 72, 1B, 2B, 27, C9, 5, 79, D5, FE, 2A, 4, 18, "/>
</files>
<methods>
<method containingType="Test1" name="Main">
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x1" startLine="4" startColumn="2" endLine="4" endColumn="8" document="2"/>
<entry offset="0x8" hidden="true" document="2"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x9">
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>)
End Sub
End Class
End Namespace
|
thomaslevesque/roslyn
|
src/Compilers/VisualBasic/Test/Emit/PDB/PDBExternalSourceDirectiveTests.vb
|
Visual Basic
|
apache-2.0
| 34,883
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.18034
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Imports System
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("App.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
WillSams/CustomerOrders-ASPNET-MVC3-VB
|
src/My Project/Resources.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,709
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend MustInherit Class StateMachineRewriter(Of TProxy)
Friend MustInherit Class StateMachineMethodToClassRewriter
Inherits MethodToClassRewriter(Of TProxy)
Protected Friend ReadOnly F As SyntheticBoundNodeFactory
Protected NextState As Integer = 0
''' <summary>
''' The "state" of the state machine that is the translation of the iterator method.
''' </summary>
Protected ReadOnly StateField As FieldSymbol
''' <summary>
''' Cached "state" of the state machine within the MoveNext method. We work with a copy of
''' the state to avoid shared mutable state between threads. (Two threads can be executing
''' in a Task's MoveNext method because an awaited task may complete after the awaiter has
''' tested whether the subtask is complete but before the awaiter has returned)
''' </summary>
Protected ReadOnly CachedState As LocalSymbol
''' <summary>
''' For each distinct label, the set of states that need to be dispatched to that label.
''' Note that there is a dispatch occurring at every try-finally statement, so this
''' variable takes on a new set of values inside each try block.
''' </summary>
Protected Dispatches As New Dictionary(Of LabelSymbol, List(Of Integer))
''' <summary>
''' A mapping from each state of the state machine to the new state that will be used to execute
''' finally blocks in case the state machine is disposed. The Dispose method computes the new
''' state and then runs MoveNext.
''' </summary>
Protected ReadOnly FinalizerStateMap As New Dictionary(Of Integer, Integer)()
''' <summary>
''' A try block might have no state (transitions) within it, in which case it does not need
''' to have a state to represent finalization. This flag tells us whether the current try
''' block that we are within has a finalizer state. Initially true as we have the (trivial)
''' finalizer state of -1 at the top level.
''' </summary>
Private _hasFinalizerState As Boolean = True
''' <summary>
''' If hasFinalizerState is true, this is the state for finalization from anywhere in this try block.
''' Initially set to -1, representing the no-op finalization required at the top level.
''' </summary>
Private _currentFinalizerState As Integer = -1
''' <summary>
''' The set of local variables and parameters that were hoisted and need a proxy.
''' </summary>
Private ReadOnly _hoistedVariables As IReadOnlySet(Of Symbol) = Nothing
Private ReadOnly _synthesizedLocalOrdinals As SynthesizedLocalOrdinalsDispenser
Private _nextFreeHoistedLocalSlot As Integer
Public Sub New(F As SyntheticBoundNodeFactory,
stateField As FieldSymbol,
hoistedVariables As IReadOnlySet(Of Symbol),
initialProxies As Dictionary(Of Symbol, TProxy),
synthesizedLocalOrdinals As SynthesizedLocalOrdinalsDispenser,
slotAllocatorOpt As VariableSlotAllocator,
nextFreeHoistedLocalSlot As Integer,
Diagnostics As DiagnosticBag)
MyBase.New(slotAllocatorOpt, F.CompilationState, Diagnostics, preserveOriginalLocals:=False)
Debug.Assert(F IsNot Nothing)
Debug.Assert(stateField IsNot Nothing)
Debug.Assert(hoistedVariables IsNot Nothing)
Debug.Assert(initialProxies IsNot Nothing)
Debug.Assert(nextFreeHoistedLocalSlot >= 0)
Debug.Assert(Diagnostics IsNot Nothing)
Me.F = F
Me.StateField = stateField
Me.CachedState = F.SynthesizedLocal(F.SpecialType(SpecialType.System_Int32), SynthesizedLocalKind.StateMachineCachedState, F.Syntax)
Me._hoistedVariables = hoistedVariables
Me._synthesizedLocalOrdinals = synthesizedLocalOrdinals
Me._nextFreeHoistedLocalSlot = nextFreeHoistedLocalSlot
For Each p In initialProxies
Me.Proxies.Add(p.Key, p.Value)
Next
End Sub
''' <summary>
''' Implementation-specific name for labels to mark state machine resume points.
''' </summary>
Protected MustOverride ReadOnly Property ResumeLabelName As String
''' <summary>
''' Generate return statements from the state machine method body.
''' </summary>
Protected MustOverride Function GenerateReturn(finished As Boolean) As BoundStatement
Protected Overrides ReadOnly Property TypeMap As TypeSubstitution
Get
Return Me.F.CurrentType.TypeSubstitution
End Get
End Property
Protected Overrides ReadOnly Property CurrentMethod As MethodSymbol
Get
Return Me.F.CurrentMethod
End Get
End Property
Protected Overrides ReadOnly Property TopLevelMethod As MethodSymbol
Get
Return Me.F.TopLevelMethod
End Get
End Property
Friend Overrides Function FramePointer(syntax As SyntaxNode, frameClass As NamedTypeSymbol) As BoundExpression
Dim oldSyntax As SyntaxNode = Me.F.Syntax
Me.F.Syntax = syntax
Dim result = Me.F.Me()
Debug.Assert(frameClass = result.Type)
Me.F.Syntax = oldSyntax
Return result
End Function
Protected Structure StateInfo
Public ReadOnly Number As Integer
Public ReadOnly ResumeLabel As GeneratedLabelSymbol
Public Sub New(stateNumber As Integer, resumeLabel As GeneratedLabelSymbol)
Me.Number = stateNumber
Me.ResumeLabel = resumeLabel
End Sub
End Structure
Protected Function AddState() As StateInfo
Dim stateNumber As Integer = Me.NextState
Me.NextState += 1
If Me.Dispatches Is Nothing Then
Me.Dispatches = New Dictionary(Of LabelSymbol, List(Of Integer))()
End If
If Not Me._hasFinalizerState Then
Me._currentFinalizerState = Me.NextState
Me.NextState += 1
Me._hasFinalizerState = True
End If
Dim resumeLabel As GeneratedLabelSymbol = Me.F.GenerateLabel(ResumeLabelName)
Me.Dispatches.Add(resumeLabel, New List(Of Integer)() From {stateNumber})
Me.FinalizerStateMap.Add(stateNumber, Me._currentFinalizerState)
Return New StateInfo(stateNumber, resumeLabel)
End Function
Protected Function Dispatch() As BoundStatement
Return Me.F.Select(
Me.F.Local(Me.CachedState, isLValue:=False),
From kv In Me.Dispatches
Order By kv.Value(0)
Select Me.F.SwitchSection(kv.Value, F.Goto(kv.Key)))
End Function
#Region "Visitors"
Public Overrides Function Visit(node As BoundNode) As BoundNode
If node Is Nothing Then
Return node
End If
Dim oldSyntax As SyntaxNode = Me.F.Syntax
Me.F.Syntax = node.Syntax
Dim result As BoundNode = MyBase.Visit(node)
Me.F.Syntax = oldSyntax
Return result
End Function
Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode
Return PossibleStateMachineScope(node.Locals, MyBase.VisitBlock(node))
End Function
Private Function PossibleStateMachineScope(locals As ImmutableArray(Of LocalSymbol), wrapped As BoundNode) As BoundNode
If locals.IsEmpty Then
Return wrapped
End If
Dim hoistedLocalsWithDebugScopes = ArrayBuilder(Of FieldSymbol).GetInstance()
For Each local In locals
If Not NeedsProxy(local) Then
Continue For
End If
' Ref synthesized variables have proxies that are allocated in VisitAssignmentOperator.
If local.IsByRef Then
Debug.Assert(local.SynthesizedKind = SynthesizedLocalKind.AwaitSpill)
Continue For
End If
Debug.Assert(local.SynthesizedKind.IsLongLived())
' We need to produce hoisted local scope debug information for user locals as well as
' lambda display classes, since Dev12 EE uses them to determine which variables are displayed
' in Locals window.
If local.SynthesizedKind = SynthesizedLocalKind.UserDefined OrElse local.SynthesizedKind = SynthesizedLocalKind.LambdaDisplayClass Then
Dim proxy As TProxy = Nothing
If Proxies.TryGetValue(local, proxy) Then
Me.AddProxyFieldsForStateMachineScope(proxy, hoistedLocalsWithDebugScopes)
End If
End If
Next
' Wrap the node in a StateMachineScope for debugging
Dim translatedStatement As BoundNode = wrapped
If hoistedLocalsWithDebugScopes.Count > 0 Then
translatedStatement = MakeStateMachineScope(hoistedLocalsWithDebugScopes.ToImmutable(), DirectCast(translatedStatement, BoundStatement))
End If
hoistedLocalsWithDebugScopes.Free()
Return translatedStatement
End Function
''' <remarks>
''' Must remain in sync with <see cref="TryUnwrapBoundStateMachineScope"/>.
''' </remarks>
Friend Function MakeStateMachineScope(hoistedLocals As ImmutableArray(Of FieldSymbol), statement As BoundStatement) As BoundBlock
Return Me.F.Block(New BoundStateMachineScope(Me.F.Syntax, hoistedLocals, statement).MakeCompilerGenerated)
End Function
''' <remarks>
''' Must remain in sync with <see cref="MakeStateMachineScope"/>.
''' </remarks>
Friend Function TryUnwrapBoundStateMachineScope(ByRef statement As BoundStatement, <Out> ByRef hoistedLocals As ImmutableArray(Of FieldSymbol)) As Boolean
If statement.Kind = BoundKind.Block Then
Dim rewrittenBlock = DirectCast(statement, BoundBlock)
Dim rewrittenStatements = rewrittenBlock.Statements
If rewrittenStatements.Length = 1 AndAlso rewrittenStatements(0).Kind = BoundKind.StateMachineScope Then
Dim stateMachineScope = DirectCast(rewrittenStatements(0), BoundStateMachineScope)
statement = stateMachineScope.Statement
hoistedLocals = stateMachineScope.Fields
Return True
End If
End If
hoistedLocals = ImmutableArray(Of FieldSymbol).Empty
Return False
End Function
Private Function NeedsProxy(localOrParameter As Symbol) As Boolean
Debug.Assert(localOrParameter.Kind = SymbolKind.Local OrElse localOrParameter.Kind = SymbolKind.Parameter)
Return _hoistedVariables.Contains(localOrParameter)
End Function
Friend MustOverride Sub AddProxyFieldsForStateMachineScope(proxy As TProxy, proxyFields As ArrayBuilder(Of FieldSymbol))
''' <summary>
''' The try statement is the most complex part of the state machine transformation.
''' Since the CLR will not allow a 'goto' into the scope of a try statement, we must
''' generate the dispatch to the state's label stepwise. That is done by translating
''' the try statements from the inside to the outside. Within a try statement, we
''' start with an empty dispatch table (representing the mapping from state numbers
''' to labels). During translation of the try statement's body, the dispatch table
''' will be filled in with the data necessary to dispatch once we're inside the try
''' block. We generate that at the head of the translated try statement. Then, we
''' copy all of the states from that table into the table for the enclosing construct,
''' but associate them with a label just before the translated try block. That way
''' the enclosing construct will generate the code necessary to get control into the
''' try block for all of those states.
''' </summary>
Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode
Dim oldDispatches As Dictionary(Of LabelSymbol, List(Of Integer)) = Me.Dispatches
Dim oldFinalizerState As Integer = Me._currentFinalizerState
Dim oldHasFinalizerState As Boolean = Me._hasFinalizerState
Me.Dispatches = Nothing
Me._currentFinalizerState = -1
Me._hasFinalizerState = False
Dim tryBlock As BoundBlock = Me.F.Block(DirectCast(Me.Visit(node.TryBlock), BoundStatement))
Dim dispatchLabel As GeneratedLabelSymbol = Nothing
If Me.Dispatches IsNot Nothing Then
dispatchLabel = Me.F.GenerateLabel("tryDispatch")
If Me._hasFinalizerState Then
' cause the current finalizer state to arrive here and then "return false"
Dim finalizer As GeneratedLabelSymbol = Me.F.GenerateLabel("finalizer")
Me.Dispatches.Add(finalizer, New List(Of Integer)() From {Me._currentFinalizerState})
Dim skipFinalizer As GeneratedLabelSymbol = Me.F.GenerateLabel("skipFinalizer")
tryBlock = Me.F.Block(SyntheticBoundNodeFactory.HiddenSequencePoint(),
Me.Dispatch(),
Me.F.Goto(skipFinalizer),
Me.F.Label(finalizer),
Me.F.Assignment(
F.Field(F.Me(), Me.StateField, True),
F.AssignmentExpression(F.Local(Me.CachedState, True), F.Literal(StateMachineStates.NotStartedStateMachine))),
Me.GenerateReturn(False),
Me.F.Label(skipFinalizer),
tryBlock)
Else
tryBlock = Me.F.Block(SyntheticBoundNodeFactory.HiddenSequencePoint(), Me.Dispatch(), tryBlock)
End If
If oldDispatches Is Nothing Then
oldDispatches = New Dictionary(Of LabelSymbol, List(Of Integer))()
End If
oldDispatches.Add(dispatchLabel, New List(Of Integer)(From kv In Dispatches.Values From n In kv Order By n Select n))
End If
Me._hasFinalizerState = oldHasFinalizerState
Me._currentFinalizerState = oldFinalizerState
Me.Dispatches = oldDispatches
Dim catchBlocks As ImmutableArray(Of BoundCatchBlock) = Me.VisitList(node.CatchBlocks)
Dim finallyBlockOpt As BoundBlock = If(node.FinallyBlockOpt Is Nothing, Nothing,
Me.F.Block(
SyntheticBoundNodeFactory.HiddenSequencePoint(),
Me.F.If(
condition:=Me.F.IntLessThan(
Me.F.Local(Me.CachedState, False),
Me.F.Literal(StateMachineStates.FirstUnusedState)),
thenClause:=DirectCast(Me.Visit(node.FinallyBlockOpt), BoundBlock)),
SyntheticBoundNodeFactory.HiddenSequencePoint()))
Dim result As BoundStatement = node.Update(tryBlock, catchBlocks, finallyBlockOpt, node.ExitLabelOpt)
If dispatchLabel IsNot Nothing Then
result = Me.F.Block(SyntheticBoundNodeFactory.HiddenSequencePoint(), Me.F.Label(dispatchLabel), result)
End If
Return result
End Function
Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode
Return Me.MaterializeProxy(node, Me.Proxies(Me.TopLevelMethod.MeParameter))
End Function
Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode
Return Me.MaterializeProxy(node, Me.Proxies(Me.TopLevelMethod.MeParameter))
End Function
Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode
Return Me.MaterializeProxy(node, Me.Proxies(Me.TopLevelMethod.MeParameter))
End Function
Private Function TryRewriteLocal(local As LocalSymbol) As LocalSymbol
If NeedsProxy(local) Then
' no longer a local symbol
Return Nothing
End If
Dim newLocal As LocalSymbol = Nothing
If Not LocalMap.TryGetValue(local, newLocal) Then
Dim newType = VisitType(local.Type)
If newType = local.Type Then
' keeping same local
newLocal = local
Else
' need a local of a different type
newLocal = LocalSymbol.Create(local, newType)
LocalMap.Add(local, newLocal)
End If
End If
Return newLocal
End Function
Public Overrides Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode
' Yield/Await aren't supported in Catch block, but we need to
' rewrite the type of the variable owned by the catch block.
' Note that this variable might be a closure frame reference.
Dim rewrittenCatchLocal As LocalSymbol = Nothing
Dim origLocal As LocalSymbol = node.LocalOpt
If origLocal IsNot Nothing Then
rewrittenCatchLocal = TryRewriteLocal(origLocal)
End If
Dim rewrittenExceptionVariable As BoundExpression = DirectCast(Me.Visit(node.ExceptionSourceOpt), BoundExpression)
' rewrite filter and body
' NOTE: this will proxy all accesses to exception local if that got hoisted.
Dim rewrittenErrorLineNumber = DirectCast(Me.Visit(node.ErrorLineNumberOpt), BoundExpression)
Dim rewrittenFilter = DirectCast(Me.Visit(node.ExceptionFilterOpt), BoundExpression)
Dim rewrittenBody = DirectCast(Me.Visit(node.Body), BoundBlock)
' rebuild the node.
Return node.Update(rewrittenCatchLocal,
rewrittenExceptionVariable,
rewrittenErrorLineNumber,
rewrittenFilter,
rewrittenBody,
isSynthesizedAsyncCatchAll:=node.IsSynthesizedAsyncCatchAll)
End Function
#End Region
#Region "Nodes not existing by the time State Machine rewriter is involved"
Public NotOverridable Overrides Function VisitUserDefinedConversion(node As BoundUserDefinedConversion) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitUserDefinedUnaryOperator(node As BoundUserDefinedUnaryOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitBadExpression(node As BoundBadExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitBadVariable(node As BoundBadVariable) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitParenthesized(node As BoundParenthesized) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitUnboundLambda(node As UnboundLambda) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitAttribute(node As BoundAttribute) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitAnonymousTypePropertyAccess(node As BoundAnonymousTypePropertyAccess) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitAnonymousTypeFieldInitializer(node As BoundAnonymousTypeFieldInitializer) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitLateMemberAccess(node As BoundLateMemberAccess) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitLateInvocation(node As BoundLateInvocation) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitLateBoundArgumentSupportingAssignmentWithCapture(node As BoundLateBoundArgumentSupportingAssignmentWithCapture) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitGroupTypeInferenceLambda(node As GroupTypeInferenceLambda) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitLambda(node As BoundLambda) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitQueryLambda(node As BoundQueryLambda) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlNamespace(node As BoundXmlNamespace) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlName(node As BoundXmlName) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlDocument(node As BoundXmlDocument) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlDeclaration(node As BoundXmlDeclaration) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlProcessingInstruction(node As BoundXmlProcessingInstruction) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlComment(node As BoundXmlComment) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlAttribute(node As BoundXmlAttribute) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlElement(node As BoundXmlElement) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlMemberAccess(node As BoundXmlMemberAccess) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlCData(node As BoundXmlCData) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlEmbeddedExpression(node As BoundXmlEmbeddedExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitByRefArgumentPlaceholder(node As BoundByRefArgumentPlaceholder) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitByRefArgumentWithCopyBack(node As BoundByRefArgumentWithCopyBack) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitCompoundAssignmentTargetPlaceholder(node As BoundCompoundAssignmentTargetPlaceholder) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitWithLValueExpressionPlaceholder(node As BoundWithLValueExpressionPlaceholder) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitWithRValueExpressionPlaceholder(node As BoundWithRValueExpressionPlaceholder) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitMethodGroup(node As BoundMethodGroup) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitPropertyGroup(node As BoundPropertyGroup) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitValueTypeMeReference(node As BoundValueTypeMeReference) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitCollectionInitializerExpression(node As BoundCollectionInitializerExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitPropertyAccess(node As BoundPropertyAccess) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitArrayLiteral(node As BoundArrayLiteral) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitNullableIsTrueOperator(node As BoundNullableIsTrueOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitNewT(node As BoundNewT) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitDup(node As BoundDup) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitOmittedArgument(node As BoundOmittedArgument) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitTypeArguments(node As BoundTypeArguments) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitTypeOrValueExpression(node As BoundTypeOrValueExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitAddressOfOperator(node As BoundAddressOfOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
#End Region
End Class
End Class
End Namespace
|
pdelvo/roslyn
|
src/Compilers/VisualBasic/Portable/Lowering/StateMachineRewriter/StateMachineRewriter.StateMachineMethodToClassRewriter.vb
|
Visual Basic
|
apache-2.0
| 31,441
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Text
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class OptionalArgumentTests
Inherits BasicTestBase
<WorkItem(543066, "DevDiv")>
<Fact()>
Public Sub TestOptionalOnGenericMethod()
Dim source =
<compilation name="TestOptionalOnGenericMethod">
<file name="a.vb">
<![CDATA[
Imports System
Module Program
Sub Foo(Of T)(x As Integer, Optional y As Integer = 10)
Console.WriteLine(y)
End Sub
Sub Main(args As String())
Foo(Of Integer)(1)
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source)
comp.AssertNoDiagnostics()
CompileAndVerify(source,
expectedOutput:=<![CDATA[
10
]]>)
End Sub
' Verify that there is no copy back conversion when optional parameters are byref.
<WorkItem(543099, "DevDiv")>
<Fact()>
Public Sub TestIntegerOptionalDoubleWithConversionError()
Dim source =
<compilation name="TestIntegerOptionalDoubleWithConversionError">
<file name="a.vb">
<![CDATA[
Module Program
Sub Foo(x As Integer, Optional y As Double = #1/1/2001#)
End Sub
Sub Main(args As String())
Foo(1)
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source)
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_DateToDoubleConversion, "#1/1/2001#"))
End Sub
<WorkItem(543093, "DevDiv")>
<Fact()>
Public Sub TestOptionalByRef()
Dim source =
<compilation name="TestOptionalByRef">
<file name="a.vb">
<![CDATA[
Option Strict Off
Imports System
Module Program
Sub Foo(Optional byref y As DateTime = #1/1/2012#)
Console.WriteLine(y.ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture))
End Sub
Sub Bar(Optional byref y As integer = 2D)
Console.WriteLine(y)
End Sub
Sub Main(args As String())
Foo()
Bar()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source)
comp.AssertNoDiagnostics()
CompileAndVerify(source,
expectedOutput:=<![CDATA[
1/1/2012 12:00:00 AM
2
]]>)
End Sub
' Report error if the default value of overridden method is different
<Fact()>
Public Sub TestOverridingOptionalWithDifferentDefaultValue()
Dim source =
<compilation name="TestOverridingOptionalWithDifferentDefaultValue">
<file name="a.vb">
<![CDATA[
MustInherit Class c1
Public MustOverride Sub s1(Optional i As Integer = 0)
Public MustOverride Sub s1(s As String)
End Class
Class c2
Inherits c1
Overrides Sub s1(Optional i As Integer = 2)
End Sub
Overrides Sub s1(s As String)
End Sub
End Class
Module Program
Sub Main(args As String())
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source)
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_OverrideWithDefault2, "s1").WithArguments("Public Overrides Sub s1([i As Integer = 2])", "Public MustOverride Sub s1([i As Integer = 0])"))
End Sub
' Should only report an error for guid parameter.
<WorkItem(543202, "DevDiv")>
<Fact()>
Public Sub TestOptionalAfterParameterWithConversionError()
Dim source =
<compilation name="TestOptionalAfterParameterWithConversionError">
<file name="a.vb">
<![CDATA[
Imports System
Module Program
Sub s1(g As Guid, Optional i As Integer = 2)
End Sub
Sub Main(args As String())
s1(1)
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source)
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_TypeMismatch2, "1").WithArguments("Integer", "System.Guid"))
End Sub
<WorkItem(543227, "DevDiv")>
<Fact()>
Public Sub TestMultipleEnumDefaultValues()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Option Strict On
Imports System
Module Program
Enum Alphabet As Byte
A
B
End Enum
Sub s1(i As Integer, Optional l1 As Alphabet = Alphabet.A, Optional l2 As Alphabet = Alphabet.B)
End Sub
Sub Main(args As String())
s1(0)
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source)
comp.AssertNoDiagnostics()
End Sub
<WorkItem(543179, "DevDiv")>
<Fact()>
Public Sub TestOptionalObject()
Dim source =
<compilation name="TestOptionalObject">
<file name="a.vb">
<![CDATA[
Module Program
Public Const myvar As Object = " -5 "
Public Sub foo(Optional o As Object = myvar)
End Sub
Sub Main(args As String())
foo()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source)
comp.AssertNoDiagnostics()
End Sub
<WorkItem(543230, "DevDiv")>
<Fact()>
Public Sub TestOptionalIntegerWithStringValue()
Dim source =
<compilation name="TestOptionalIntegerWithStringValue">
<file name="a.vb">
<![CDATA[
Option Strict Off
Module Program
Sub foo(Optional arg1 As Integer = "12")
End Sub
Sub Main(args As String())
foo()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source)
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_RequiredConstConversion2, """12""").WithArguments("String", "Integer"))
End Sub
<WorkItem(543395, "DevDiv")>
<Fact()>
Public Sub TestEventWithOptionalInteger()
Dim source =
<compilation name="TestEventWithOptionalInteger">
<file name="a.vb">
<![CDATA[
Class A
Event E(Optional I As Integer = 0)
Public Sub Do_E()
RaiseEvent E()
End Sub
End Class
Module Program
Sub Main(args As String())
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source)
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_OptionalIllegal1, "Optional").WithArguments("Event"),
Diagnostic(ERRID.ERR_OmittedArgument2, "RaiseEvent E()").WithArguments("I", "Public Event E(I As Integer)"))
End Sub
<Fact(), WorkItem(543526, "DevDiv")>
Public Sub MidParameterMissOptional()
Dim source =
<compilation name="MidParameterMissOptional">
<file name="a.vb">
<![CDATA[
Module Program
Sub Main(args As String())
End Sub
Sub TEST(ByRef Optional X As Integer = 1, Z As Integer, ByRef Optional Y As String = "STRING")
End Sub
End Module
]]>
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_ExpectedOptional, "Z"))
End Sub
<Fact()>
Public Sub ParamArrayAfterOptional()
Dim source =
<compilation name="MidParameterMissOptional">
<file name="a.vb">
<![CDATA[
Module Program
Sub Main(args As String())
End Sub
Sub TEST(ByRef Optional X As Integer = 1, paramarray Y() As object)
End Sub
End Module
]]>
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_ParamArrayWithOptArgs, "Y"))
End Sub
<Fact()>
Public Sub ParamArrayNotLast()
Dim source =
<compilation name="MidParameterMissOptional">
<file name="a.vb">
<![CDATA[
Module Program
Sub Main(args As String())
End Sub
Sub TEST(ByRef X As Integer, paramarray Y() As object, Optional z As Integer = 1)
End Sub
End Module
]]>
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_ParamArrayMustBeLast, "Optional z As Integer = 1"))
End Sub
<Fact(), WorkItem(543527, "DevDiv")>
Public Sub OptionalParameterValueAssignedToRuntime()
Dim source =
<compilation name="OptionalParameterValueAssignedToRuntime">
<file name="a.vb">
<![CDATA[
Class Program
Sub Main(args As String())
End Sub
Sub test(Optional x As String = String.Empty)
End Sub
End Class
]]>
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_RequiredConstExpr, "String.Empty"))
End Sub
<Fact(), WorkItem(543531, "DevDiv")>
Public Sub OptionalParameterForConstructorofStructure()
Dim source =
<compilation name="OptionalParameterForConstructorofStructure">
<file name="a.vb">
<![CDATA[
Structure S1
Public Sub New(Optional ByVal y As Integer = 1)
End Sub
Shared Sub main()
End Sub
End Structure
]]>
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source).AssertNoDiagnostics()
End Sub
<Fact(), WorkItem(544515, "DevDiv")>
Public Sub OptionalNullableInteger()
Dim source =
<compilation name="OptionalNullableInteger">
<file name="a.vb">
<![CDATA[
Imports System
Module m
Sub X(Optional i As Integer? = 10)
Console.WriteLine("{0}", i)
End Sub
Sub main()
X()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
10
]]>).VerifyIL("m.main", <![CDATA[
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldc.i4.s 10
IL_0002: newobj "Sub Integer?..ctor(Integer)"
IL_0007: call "Sub m.X(Integer?)"
IL_000c: ret
}
]]>)
End Sub
<Fact(), WorkItem(544515, "DevDiv")>
Public Sub OptionalNullableIntegerWithNothingValue()
Dim source =
<compilation name="OptionalNullableInteger">
<file name="a.vb">
<![CDATA[
Imports System
Module m
Sub X(Optional i As Integer? = nothing)
Console.WriteLine("{0}", i.hasValue)
End Sub
Sub main()
X()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
False
]]>).VerifyIL("m.main", <![CDATA[
{
// Code size 15 (0xf)
.maxstack 1
.locals init (Integer? V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "Integer?"
IL_0008: ldloc.0
IL_0009: call "Sub m.X(Integer?)"
IL_000e: ret
}
]]>)
End Sub
<WorkItem(544603, "DevDiv")>
<Fact()>
Public Sub OptionalParameterValueRefersToContainingFunction1()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
End Sub
Class C
Public Shared Function Foo(Optional a As C = Foo()) As C
Return Nothing
End Function
End Class
End Module
]]></file>
</compilation>)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_CircularEvaluation1, "Foo()").WithArguments("[a As Module1.C]")
)
End Sub
<WorkItem(544603, "DevDiv")>
<Fact()>
Public Sub OptionalParameterValueRefersToContainingFunction2()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
End Sub
Class C
Public Shared Function Foo(Optional f As C = Bar()) As C
Return Nothing
End Function
Public Shared Function Bar(Optional b As C = Foo()) As C
Return Nothing
End Function
End Class
End Module
]]></file>
</compilation>)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_CircularEvaluation1, "Bar()").WithArguments("[f As Module1.C]"),
Diagnostic(ERRID.ERR_RequiredConstExpr, "Foo()")
)
End Sub
<WorkItem(544603, "DevDiv")>
<Fact()>
Public Sub OptionalParameterValueRefersToMe()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
End Sub
Class C
Public Shared Function Foo(Optional f As C = Me) As C
Return Nothing
End Function
Public Shared Function Bar(Optional f As C = foo(Me)) As C
Return Nothing
End Function
End Class
End Module
]]></file>
</compilation>)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_UseOfKeywordNotInInstanceMethod1, "Me").WithArguments("Me"),
Diagnostic(ERRID.ERR_UseOfKeywordNotInInstanceMethod1, "Me").WithArguments("Me")
)
End Sub
<WorkItem(545416, "DevDiv")>
<Fact()>
Public Sub OptionalParameterValueWithEnumValue()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Public Enum PropertyPagesDialogAction
None 'Do nothing (don't close the dialog)
Apply 'Click the 'Apply' button (don't close the dialog)
OK 'Click the 'OK' button (and close the dialog)
Cancel 'Click the 'Cancel' button (and close the dialog)
End Enum
Public MustInherit Class Element
Public MustOverride Overloads Function F1( _
Optional ByVal dialogCloseMethod As PropertyPagesDialogAction = PropertyPagesDialogAction.OK) _
As Boolean
Public MustOverride Overloads Property P1( _
Optional ByVal dialogCloseMethod As PropertyPagesDialogAction = PropertyPagesDialogAction.OK) _
As Boolean
End Class
]]></file>
</compilation>)
compilation.AssertNoDiagnostics()
End Sub
<Fact()>
Public Sub NullableEnumAsOptional()
Dim compilation =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Module Module1
Sub Main(args As String())
Test()
End Sub
Sub Test(Optional x As TestEnum? = TestEnum.B)
System.Console.WriteLine(x)
End Sub
End Module
Enum TestEnum
A
B
End Enum
]]></file>
</compilation>
CompileAndVerify(compilation, expectedOutput:="B").VerifyDiagnostics()
End Sub
<WorkItem(536772, "DevDiv")>
<Fact()>
Public Sub NullableConversionsInOptional()
Dim compilation =
<compilation>
<file name="c.vb"><![CDATA[
Imports System
Module Program
Sub foo1(Of T)(Optional x As T = CType(Nothing, T))
Console.WriteLine("x = {0}", x)
End Sub
Sub foo2(Of T)(Optional x As T = DirectCast(Nothing, T))
Console.WriteLine("x = {0}", x)
End Sub
Sub foo3(Of T As Class)(Optional x As T = TryCast(Nothing, T))
Console.WriteLine("x = {0}", If(x Is Nothing, "nothing", x))
End Sub
Sub foo4(Of T As Class)(Optional x As T = CType(CType(Nothing, T), T))
Console.WriteLine("x = {0}", If(x Is Nothing, "nothing", x))
End Sub
Sub Main(args As String())
foo1(Of Integer)()
foo2(Of Integer)()
foo3(Of String)()
foo4(of string)()
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(compilation, expectedOutput:=<![CDATA[
x = 0
x = 0
x = nothing
x = nothing
]]>).VerifyDiagnostics()
End Sub
<WorkItem(543187, "DevDiv")>
<Fact()>
Public Sub OptionalWithIUnknownConstantAndIDispatchConstant()
Dim libSource =
<compilation>
<file name="c.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M1(Optional x As Object = Nothing)
Console.WriteLine(If(x, 1))
End Sub
Public Shared Sub M2(<[Optional]> x As Object)
Console.WriteLine(If(x, 2))
End Sub
Public Shared Sub M3(<IDispatchConstant> Optional x As Object = Nothing)
Console.WriteLine(If(x, 3))
End Sub
Public Shared Sub M4(<IDispatchConstant> <[Optional]> x As Object)
Console.WriteLine(If(x, 4))
End Sub
Public Shared Sub M5(<IUnknownConstant> Optional x As Object = Nothing)
Console.WriteLine(If(x, 5))
End Sub
Public Shared Sub M6(<IUnknownConstant> <[Optional]> x As Object)
Console.WriteLine(If(x, 6))
End Sub
Public Shared Sub M7(<IUnknownConstant> <IDispatchConstant> Optional x As Object = Nothing)
Console.WriteLine(If(x, 7))
End Sub
Public Shared Sub M8(<IUnknownConstant> <IDispatchConstant> <[Optional]> x As Object)
Console.WriteLine(If(x, 8))
End Sub
End Class
]]></file>
</compilation>
Dim libComp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(libSource)
Dim source =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
C.M1()
C.M2()
C.M3()
C.M4()
C.M5()
C.M6()
C.M7()
C.M8()
End Sub
End Module
]]></file>
</compilation>
Dim compilationRef As MetadataReference = libComp.ToMetadataReference()
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, additionalRefs:={compilationRef})
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_OmittedArgument2, "M2").WithArguments("x", "Public Shared Sub M2(x As Object)"),
Diagnostic(ERRID.ERR_OmittedArgument2, "M4").WithArguments("x", "Public Shared Sub M4(x As Object)"),
Diagnostic(ERRID.ERR_OmittedArgument2, "M6").WithArguments("x", "Public Shared Sub M6(x As Object)"),
Diagnostic(ERRID.ERR_OmittedArgument2, "M8").WithArguments("x", "Public Shared Sub M8(x As Object)"))
Dim metadataRef = MetadataReference.CreateFromImage(libComp.EmitToArray())
CompileAndVerify(source, additionalRefs:={metadataRef}, expectedOutput:=<![CDATA[
1
System.Reflection.Missing
3
System.Runtime.InteropServices.DispatchWrapper
5
System.Runtime.InteropServices.UnknownWrapper
7
System.Runtime.InteropServices.DispatchWrapper
]]>).VerifyDiagnostics()
End Sub
<WorkItem(543187, "DevDiv")>
<Fact()>
Public Sub OptionalWithIUnknownConstantAndIDispatchConstantWithString()
Dim libSource =
<compilation>
<file name="c.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
Namespace SpecialOptionalLib
Public Class C
Public Shared Sub M1(<IDispatchConstant> Optional x As string = Nothing)
Console.WriteLine(If(x, 1))
End Sub
Public Shared Sub M2(<IUnknownConstant> Optional x As string = Nothing)
Console.WriteLine(If(x, 2))
End Sub
End Class
End Namespace
]]></file>
</compilation>
Dim libComp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(libSource)
Dim source =
<compilation>
<file name="c.vb"><![CDATA[
Imports SpecialOptionalLib.C
Module Module1
Sub Main()
M1()
M2()
End Sub
End Module
]]></file>
</compilation>
Dim libRef = MetadataReference.CreateFromImage(libComp.EmitToArray())
CompileAndVerify(source, additionalRefs:=New MetadataReference() {libRef}, expectedOutput:=<![CDATA[
1
2
]]>).VerifyDiagnostics()
End Sub
<WorkItem(543187, "DevDiv")>
<Fact>
Public Sub OptionalWithMarshallAs()
Dim libSource =
<compilation>
<file name="c.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M1(<MarshalAs(UnmanagedType.Interface)> <[Optional]> x As Object)
Console.WriteLine(If(x, 1))
End Sub
Public Shared Sub M2(<IDispatchConstant> <MarshalAs(UnmanagedType.Interface)> <[Optional]> x As Object)
Console.WriteLine(If(x, 2))
End Sub
Public Shared Sub M3(<IUnknownConstant> <MarshalAs(UnmanagedType.Interface)> <[Optional]> x As Object)
Console.WriteLine(If(x, 3))
End Sub
Public Shared Sub M4(<IUnknownConstant> <IDispatchConstant> <MarshalAs(UnmanagedType.Interface)> <[Optional]> x As Object)
Console.WriteLine(If(x, 4))
End Sub
Public Shared Sub M5(<IUnknownConstant> <MarshalAs(UnmanagedType.Interface)> <IDispatchConstant> <[Optional]> x As Object)
Console.WriteLine(If(x, 5))
End Sub
Public Shared Sub M6(<MarshalAs(UnmanagedType.Interface)> <IDispatchConstant> <IUnknownConstant> <[Optional]> x As Object)
Console.WriteLine(If(x, 6))
End Sub
Public Shared Sub M7(<IUnknownConstant> <IDispatchConstant> <[Optional]> x As Object)
Console.WriteLine(If(x, 7))
End Sub
Public Shared Sub M8(<IDispatchConstant> <IUnknownConstant> <[Optional]> x As Object)
Console.WriteLine(If(x, 8))
End Sub
End Class
]]></file>
</compilation>
Dim libComp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(libSource)
Dim source =
<compilation>
<file name="c.vb"><![CDATA[
Class D
Shared Sub Main()
C.M1()
C.M2()
C.M3()
C.M4()
C.M5()
C.M6()
C.M7()
C.M8()
End Sub
End Class
]]></file>
</compilation>
Dim expected = <![CDATA[
1
2
3
4
5
6
System.Runtime.InteropServices.DispatchWrapper
System.Runtime.InteropServices.DispatchWrapper
]]>
Dim metadataRef = MetadataReference.CreateFromImage(libComp.EmitToArray())
CompileAndVerify(source, additionalRefs:={metadataRef}, expectedOutput:=expected).VerifyDiagnostics()
End Sub
<WorkItem(545405, "DevDiv")>
<Fact()>
Public Sub OptionalWithNoDefaultValue()
Dim libSource =
<compilation>
<file name="c.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
Namespace SpecialOptionalLib
Public Class C
Public Shared Sub Foo1(<[Optional]> x As Object)
Console.WriteLine(If(x, "nothing"))
End Sub
Public Shared Sub Foo2(<[Optional]> x As String)
Console.WriteLine(If(x, "nothing"))
End Sub
Public Shared Sub Foo3(<[Optional]> x As Integer)
Console.WriteLine(x)
End Sub
End Class
End Namespace
]]></file>
</compilation>
Dim libComp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(libSource)
Dim source =
<compilation>
<file name="c.vb"><![CDATA[
Imports SpecialOptionalLib.C
Module Module1
Sub Main()
Foo1()
Foo2()
Foo3()
End Sub
End Module
]]></file>
</compilation>
Dim libRef As MetadataReference = libComp.ToMetadataReference()
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, additionalRefs:=New MetadataReference() {libRef})
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_OmittedArgument2, "Foo1").WithArguments("x", "Public Shared Sub Foo1(x As Object)"),
Diagnostic(ERRID.ERR_OmittedArgument2, "Foo2").WithArguments("x", "Public Shared Sub Foo2(x As String)"),
Diagnostic(ERRID.ERR_OmittedArgument2, "Foo3").WithArguments("x", "Public Shared Sub Foo3(x As Integer)"))
libRef = MetadataReference.CreateFromImage(libComp.EmitToArray())
CompileAndVerify(source, additionalRefs:=New MetadataReference() {libRef}, expectedOutput:=<![CDATA[
System.Reflection.Missing
nothing
0
]]>).VerifyDiagnostics()
End Sub
<WorkItem(545405, "DevDiv")>
<Fact>
Public Sub OptionalWithOptionCompare()
Dim libSource =
<compilation>
<file name="c.vb"><![CDATA[
Imports System
Imports Microsoft.VisualBasic.CompilerServices
Namespace SpecialOptionalLib
Public Class C
Public Shared Sub foo1(<OptionCompare()> Optional x As Boolean = True)
Console.WriteLine(x)
End Sub
Public Shared Sub foo2(<OptionCompare()> Optional x As Integer = 5)
Console.WriteLine(x)
End Sub
Public Shared Sub foo3(<OptionCompare()> Optional x As String = "a")
Console.WriteLine(x)
End Sub
Public Shared Sub foo4(<OptionCompare()> Optional x As Decimal = 10.0)
Console.WriteLine(x)
End Sub
End Class
End Namespace
]]></file>
</compilation>
Dim libComp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(libSource)
Dim source =
<compilation>
<file name="c.vb"><![CDATA[
Imports SpecialOptionalLib.C
Module Module1
Sub Main()
Foo1()
Foo2()
Foo3()
foo4()
End Sub
End Module
]]></file>
</compilation>
Dim libRef As MetadataReference = libComp.ToMetadataReference()
CompileAndVerify(source, additionalRefs:=New MetadataReference() {libRef}, expectedOutput:=<![CDATA[
True
5
a
10
]]>).VerifyDiagnostics()
libRef = MetadataReference.CreateFromImage(libComp.EmitToArray())
CompileAndVerify(source, additionalRefs:=New MetadataReference() {libRef}, expectedOutput:=<![CDATA[
False
0
0
0
]]>).VerifyDiagnostics()
CompileAndVerify(source,
additionalRefs:=New MetadataReference() {libRef},
options:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, optionCompareText:=True),
expectedOutput:=<![CDATA[
True
1
1
1
]]>).VerifyDiagnostics()
End Sub
<WorkItem(545686, "DevDiv")>
<Fact()>
Public Sub ParameterValueWithGenericSemanticInfo()
Dim compilation = CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Class Generic(Of T)
Public Const X As Integer = 0
End Class
Interface I
Sub Foo(Of T)(Optional x As Integer = Generic(Of T).X) 'BIND:"Generic(Of T)"'BIND:"Generic(Of T)"
End Interface
]]></file>
</compilation>)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of GenericNameSyntax)(compilation, "a.vb")
Assert.Equal("Generic(Of T)", semanticSummary.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind)
Assert.Equal("Generic(Of T)", semanticSummary.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("Generic(Of T)", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.NamedType, semanticSummary.Symbol.Kind)
Assert.Equal(0, semanticSummary.CandidateSymbols.Length)
Assert.Null(semanticSummary.Alias)
Assert.Equal(0, semanticSummary.MemberGroup.Length)
Assert.False(semanticSummary.ConstantValue.HasValue)
End Sub
<WorkItem(578129, "DevDiv")>
<Fact()>
Public Sub Bug578129()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Partial Class PC2 ' attributes on implementation
Partial Private Sub VerifyCallerInfo(
expectedPath As String,
expectedLine As String,
expectedMember As String,
Optional f A String = "",
Optional l As Integer = -1,
Optional m As String = Nothing)
End Sub
End Class
Partial Class PC2
Private Sub VerifyCallerInfo(
expectedPath As String,
expectedLine As String,
expectedMember As String,
<CallerFilePath> Optional f As String = "",
<CallerLineNumber> Optional l As Integer = -1,
<CallerMemberName> Optional m As String = Nothing)
Console.WriteLine("callerinfo: ({0}, {1}, {2})", "[...]", l, m)
End Sub
End Class
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, options:=TestOptions.ReleaseDll)
AssertTheseDiagnostics(comp,
<expected><![CDATA[
BC30529: All parameters must be explicitly typed if any of them are explicitly typed.
Optional f A String = "",
~
BC30812: Optional parameters must specify a default value.
Optional f A String = "",
~
BC30451: 'A' is not declared. It may be inaccessible due to its protection level.
Optional f A String = "",
~
BC30002: Type 'CallerFilePath' is not defined.
<CallerFilePath> Optional f As String = "",
~~~~~~~~~~~~~~
BC30002: Type 'CallerLineNumber' is not defined.
<CallerLineNumber> Optional l As Integer = -1,
~~~~~~~~~~~~~~~~
BC30002: Type 'CallerMemberName' is not defined.
<CallerMemberName> Optional m As String = Nothing)
~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub CallerInfo1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices
Class TestBase
Sub New(
<CallerLineNumber> Optional number As Integer = -1,
<CallerMemberName> Optional member As String = "UnknownMember",
<CallerFilePath> Optional file As String = "UnknownFile")
System.Console.WriteLine("TestBase.New")
System.Console.WriteLine(" {0}", file)
System.Console.WriteLine(" {0}", number)
System.Console.WriteLine(" {0}", member)
End Sub
Property P0 As Integer
End Class
Class TestDerived
Inherits TestBase
Implements IEnumerable(Of String)
Sub New(x As Integer)
MyBase.New()
System.Console.WriteLine("+++ TestDerived.New(Integer)")
System.Console.WriteLine("--- TestDerived.New(Integer)")
End Sub
Sub New()
System.Console.WriteLine("+++ TestDerived.New()")
CallerInfo("TestDerived.New()")
System.Console.WriteLine("--- TestDerived.New()")
End Sub
Public F1 As Integer = CallerInfo("F1")
Public P1 As Integer = CallerInfo("P1")
Public Sub M1()
CallerInfo("M1")
End Sub
Public Property P2 As Integer
Get
Return CallerInfo("get_P2")
End Get
Set(value As Integer)
CallerInfo("set_P2")
End Set
End Property
Custom Event E1 As Action
AddHandler(value As Action)
CallerInfo("AddHandler")
End AddHandler
RemoveHandler(value As Action)
CallerInfo("RemoveHandler")
End RemoveHandler
RaiseEvent()
CallerInfo("RaiseEvent")
End RaiseEvent
End Event
Sub Raise()
RaiseEvent E1()
End Sub
Function Add(
context As String,
<CallerLineNumber> Optional number As Integer = -1,
<CallerMemberName> Optional member As String = "UnknownMember",
<CallerFilePath> Optional file As String = "UnknownFile"
) As Integer
System.Console.WriteLine("Add <{0}>", context)
System.Console.WriteLine(" {0}", file)
System.Console.WriteLine(" {0}", number)
System.Console.WriteLine(" {0}", member)
Return number
End Function
'Sub Overloaded(<CallerLineNumber> Optional number As Integer = -1)
' System.Console.WriteLine("Overloaded(Integer)")
'End Sub
'Sub Overloaded(<CallerLineNumber> Optional number As String = "0")
' System.Console.WriteLine("Overloaded(Byte)")
'End Sub
Function CallerInfo(
context As String,
<CallerLineNumber> Optional number As Integer = -1,
<CallerMemberName> Optional member As String = "UnknownMember",
<CallerFilePath> Optional file As String = "UnknownFile"
) As Integer
System.Console.WriteLine("CallerInfo <{0}>", context)
System.Console.WriteLine(" {0}", file)
System.Console.WriteLine(" {0}", number)
System.Console.WriteLine(" {0}", member)
Return number
End Function
Function CallerInfo(
<CallerLineNumber> Optional number As Integer = -1,
<CallerMemberName> Optional member As String = "UnknownMember",
<CallerFilePath> Optional file As String = "UnknownFile"
) As Integer
System.Console.WriteLine("CallerInfo")
System.Console.WriteLine(" {0}", file)
System.Console.WriteLine(" {0}", number)
System.Console.WriteLine(" {0}", member)
Return number
End Function
Public Function GetEnumerator() As IEnumerator(Of String) Implements IEnumerable(Of String).GetEnumerator
Throw New NotImplementedException()
End Function
Public Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator
Throw New NotImplementedException()
End Function
End Class
Class Enumerable
Function GetEnumerator(
<CallerLineNumber> Optional number As Integer = -1,
<CallerMemberName> Optional member As String = "UnknownMember",
<CallerFilePath> Optional file As String = "UnknownFile"
) As Enumerator
System.Console.WriteLine("GetEnumerator")
System.Console.WriteLine(" {0}", file)
System.Console.WriteLine(" {0}", number)
System.Console.WriteLine(" {0}", member)
Return New Enumerator()
End Function
End Class
Class Enumerator
Private eof As Boolean
Function MoveNext(
<CallerLineNumber> Optional number As Integer = -1,
<CallerMemberName> Optional member As String = "UnknownMember",
<CallerFilePath> Optional file As String = "UnknownFile"
) As Boolean
System.Console.WriteLine("MoveNext")
System.Console.WriteLine(" {0}", file)
System.Console.WriteLine(" {0}", number)
System.Console.WriteLine(" {0}", member)
Dim result = Not eof
eof = True
Return result
End Function
ReadOnly Property Current As String
Get
Return "A"
End Get
End Property
End Class
'<MyAttribute>
Module Module1
'<MyAttribute>
Sub Main()
System.Console.WriteLine("- 01 -")
Dim t01 As New TestBase()
System.Console.WriteLine("- 02 -")
Dim t02 As New TestBase() With {.P0 = 1}
System.Console.WriteLine("- 03 -")
Dim t03 = New TestBase()
System.Console.WriteLine("- 04 -")
Dim t1 As New TestDerived() From
{"Val1"}
System.Console.WriteLine("- 05 -")
System.Console.WriteLine("F1 = {0}", t1.F1)
System.Console.WriteLine("- 06 -")
Dim t2 As New TestDerived(2)
System.Console.WriteLine("- 07 -")
System.Console.WriteLine("F1 = {0}", t2.F1)
System.Console.WriteLine("- 08 -")
t2.M1()
System.Console.WriteLine("- 09 -")
t2.P2 = 1
System.Console.WriteLine("- 10 -")
Dim x = t2.P2
System.Console.WriteLine("- 11 -")
AddHandler t2.E1, Nothing
System.Console.WriteLine("- 12 -")
RemoveHandler t2.E1, Nothing
System.Console.WriteLine("- 13 -")
t2.Raise()
System.Console.WriteLine("- 14 -")
For Each value In New Enumerable()
System.Console.WriteLine(value)
Next
System.Console.WriteLine("- 15 -")
x = t2.CallerInfo
't2.Overloaded()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef}, TestOptions.ReleaseExe)
CompileAndVerify(compilation,
expectedOutput:=
<![CDATA[
- 01 -
TestBase.New
a.vb
185
Main
- 02 -
TestBase.New
a.vb
187
Main
- 03 -
TestBase.New
a.vb
189
Main
- 04 -
TestBase.New
UnknownFile
-1
UnknownMember
CallerInfo <F1>
a.vb
38
F1
CallerInfo <P1>
a.vb
40
P1
+++ TestDerived.New()
CallerInfo <TestDerived.New()>
a.vb
34
.ctor
--- TestDerived.New()
Add <Val1>
a.vb
192
Main
- 05 -
F1 = 38
- 06 -
TestBase.New
a.vb
27
.ctor
CallerInfo <F1>
a.vb
38
F1
CallerInfo <P1>
a.vb
40
P1
+++ TestDerived.New(Integer)
--- TestDerived.New(Integer)
- 07 -
F1 = 38
- 08 -
CallerInfo <M1>
a.vb
43
M1
- 09 -
CallerInfo <set_P2>
a.vb
51
P2
- 10 -
CallerInfo <get_P2>
a.vb
48
P2
- 11 -
CallerInfo <AddHandler>
a.vb
57
E1
- 12 -
CallerInfo <RemoveHandler>
a.vb
60
E1
- 13 -
CallerInfo <RaiseEvent>
a.vb
63
E1
- 14 -
GetEnumerator
a.vb
213
Main
MoveNext
a.vb
213
Main
A
MoveNext
a.vb
213
Main
- 15 -
CallerInfo
a.vb
218
Main
]]>)
End Sub
<Fact()>
Public Sub CallerInfo2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System.Runtime.CompilerServices
Class TestDerived
Sub Overloaded(<CallerLineNumber> Optional number As Integer = -1)
System.Console.WriteLine("Overloaded(Integer)")
End Sub
Sub Overloaded(<CallerLineNumber> Optional number As String = "0")
System.Console.WriteLine("Overloaded(Byte)")
End Sub
End Class
'<MyAttribute>
Module Module1
'<MyAttribute>
Sub Main()
Dim t1 As New TestDerived()
t1.Overloaded()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC30521: Overload resolution failed because no accessible 'Overloaded' is most specific for these arguments:
'Public Sub Overloaded([number As Integer = -1])': Not most specific.
'Public Sub Overloaded([number As String = "0"])': Not most specific.
t1.Overloaded()
~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CallerInfo3()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices
<MyAttribute>
Module Module1
<MyAttribute>
Sub Main()
Dim attribute = GetType(MyAttribute)
Dim output = New List(Of String)
For Each t In GetType(Module1).Assembly.GetTypes()
For Each a As MyAttribute In t.GetCustomAttributes(attribute, False)
output.Add(String.Format("{0} - {1}, {2}, {3}", t, a.X, a.Y, a.Z))
Next
For Each m In t.GetMembers(Reflection.BindingFlags.DeclaredOnly Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance)
For Each a As MyAttribute In m.GetCustomAttributes(attribute, False)
output.Add(String.Format("{0} - {1}, {2}, {3}", m, a.X, a.Y, a.Z))
Next
If m.MemberType = Reflection.MemberTypes.Method Then
Dim method = DirectCast(m, System.Reflection.MethodInfo)
For Each p In method.GetParameters()
For Each a As MyAttribute In p.GetCustomAttributes(attribute, False)
output.Add(String.Format("{4} {0} - {1}, {2}, {3}", p, a.X, a.Y, a.Z, method))
Next
Next
If method.ReturnParameter IsNot Nothing Then
Dim p = method.ReturnParameter
For Each a As MyAttribute In p.GetCustomAttributes(attribute, False)
output.Add(String.Format("{4} {0} - {1}, {2}, {3}", p, a.X, a.Y, a.Z, method))
Next
End If
End If
Next
Next
output.Sort()
For Each s In output
System.Console.WriteLine(s)
Next
End Sub
Function Test1(<MyAttribute> x As Integer, <MyAttribute> y As Integer) As <MyAttribute> Integer
Return 0
End Function
<MyAttribute>
Property P1 As Integer
Property P2 As <MyAttribute> Integer
<MyAttribute>
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
<MyAttribute>
Event E1 As Action
<MyAttribute>
Custom Event E2 As Action
AddHandler(value As Action)
End AddHandler
RemoveHandler(value As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
Custom Event E3 As Action
<MyAttribute>
AddHandler(value As Action)
End AddHandler
RemoveHandler(value As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
<MyAttribute>
Public F1 As Integer
End Module
]]>
</file>
</compilation>
Dim attributeSource =
<compilation>
<file name="b.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Public Class MyAttribute
Inherits System.Attribute
Public ReadOnly X As Integer
Public ReadOnly Y As String
Public ReadOnly Z As String
Sub New(
<CallerLineNumber> Optional x As Integer = -1,
<CallerMemberName> Optional y As String = "UnknownMember",
<CallerFilePath> Optional z As String = "UnknownPath"
)
Me.X = x
Me.Y = y
Me.Z = z
End Sub
End Class
]]>
</file>
</compilation>
Dim expectedOutput =
<![CDATA[
Int32 F1 - 102, F1, a.vb
Int32 get_P2() - 60, P2, a.vb
Int32 get_P2() Int32 - 59, P2, a.vb
Int32 P1 - 56, P1, a.vb
Int32 Test1(Int32, Int32) Int32 - 52, Test1, a.vb
Int32 Test1(Int32, Int32) Int32 x - 52, Test1, a.vb
Int32 Test1(Int32, Int32) Int32 y - 52, Test1, a.vb
Module1 - 7, UnknownMember, a.vb
System.Action E1 - 69, E1, a.vb
System.Action E2 - 72, E2, a.vb
Void add_E3(System.Action) - 88, E3, a.vb
Void Main() - 10, Main, a.vb
]]>
Dim attributeCompilation = CreateCompilationWithReferences(attributeSource, {MscorlibRef_v4_0_30316_17626}, TestOptions.ReleaseDll)
CompileAndVerify(attributeCompilation)
Dim compilation = CreateCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef, New VisualBasicCompilationReference(attributeCompilation)}, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput)
compilation = CreateCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef, MetadataReference.CreateFromImage(attributeCompilation.EmitToArray())}, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput)
End Sub
<Fact()>
Public Sub CallerInfo4()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices
<MyAttribute>
Module Module1
<MyAttribute>
Sub Main()
Dim attribute = GetType(MyAttribute)
Dim output = New List(Of String)
For Each t In attribute.Assembly.GetTypes()
For Each a As MyAttribute In t.GetCustomAttributes(attribute, False)
output.Add(String.Format("{0} - {1}, {2}, {3}", t, a.X, a.Y, a.Z))
Next
For Each m In t.GetMembers(Reflection.BindingFlags.DeclaredOnly Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance)
For Each a As MyAttribute In m.GetCustomAttributes(attribute, False)
output.Add(String.Format("{0} - {1}, {2}, {3}", m, a.X, a.Y, a.Z))
Next
If m.MemberType = Reflection.MemberTypes.Method Then
Dim method = DirectCast(m, System.Reflection.MethodInfo)
For Each p In method.GetParameters()
For Each a As MyAttribute In p.GetCustomAttributes(attribute, False)
output.Add(String.Format("{4} {0} - {1}, {2}, {3}", p, a.X, a.Y, a.Z, method))
Next
Next
If method.ReturnParameter IsNot Nothing Then
Dim p = method.ReturnParameter
For Each a As MyAttribute In p.GetCustomAttributes(attribute, False)
output.Add(String.Format("{4} {0} - {1}, {2}, {3}", p, a.X, a.Y, a.Z, method))
Next
End If
End If
Next
Next
output.Sort()
For Each s In output
System.Console.WriteLine(s)
Next
End Sub
Function Test1(<MyAttribute> x As Integer, <MyAttribute> y As Integer) As <MyAttribute> Integer
Return 0
End Function
<MyAttribute>
Property P1 As Integer
Property P2 As <MyAttribute> Integer
<MyAttribute>
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
<MyAttribute>
Event E1 As Action
<MyAttribute>
Custom Event E2 As Action
AddHandler(value As Action)
End AddHandler
RemoveHandler(value As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
Custom Event E3 As Action
<MyAttribute>
AddHandler(value As Action)
End AddHandler
RemoveHandler(value As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
<MyAttribute>
Public F1 As Integer
End Module
Public Class MyAttribute
Inherits System.Attribute
Public ReadOnly X As Integer
Public ReadOnly Y As String
Public ReadOnly Z As String
Sub New(
<CallerLineNumber> Optional x As Integer = -1,
<CallerMemberName> Optional y As String = "UnknownMember",
<CallerFilePath> Optional z As String = "UnknownPath"
)
Me.X = x
Me.Y = y
Me.Z = z
End Sub
End Class
]]>
</file>
</compilation>
Dim expectedOutput =
<![CDATA[
Int32 F1 - 102, F1, a.vb
Int32 get_P2() - 60, P2, a.vb
Int32 get_P2() Int32 - 59, P2, a.vb
Int32 P1 - 56, P1, a.vb
Int32 Test1(Int32, Int32) Int32 - 52, Test1, a.vb
Int32 Test1(Int32, Int32) Int32 x - 52, Test1, a.vb
Int32 Test1(Int32, Int32) Int32 y - 52, Test1, a.vb
Module1 - 7, UnknownMember, a.vb
System.Action E1 - 69, E1, a.vb
System.Action E2 - 72, E2, a.vb
Void add_E3(System.Action) - 88, E3, a.vb
Void Main() - 10, Main, a.vb
]]>
Dim compilation = CreateCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef}, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput)
End Sub
<WorkItem(1040287)>
<Fact()>
Public Sub CallerInfo5()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class C
ReadOnly Property P As C
Get
Return Me
End Get
End Property
Default ReadOnly Property Q(index As Integer, <CallerLineNumber> Optional line As Integer = 0) As C
Get
Console.WriteLine("{0}: {1}", index, line)
Return Me
End Get
End Property
Function F(Optional id As Integer = 0, <CallerLineNumber> Optional line As Integer = 0) As C
Console.WriteLine("{0}: {1}", id, line)
Return Me
End Function
Shared Sub Main()
Dim c = New C()
c.F(1).
F
c = c(
2
)(3)
c = c.
F(
4
).
P(5)
Dim o As Object = c
o =
DirectCast(o, C)(
6
)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation,
<![CDATA[
1: 21
0: 22
2: 23
3: 23
4: 27
5: 30
6: 33
]]>)
End Sub
<WorkItem(1040287)>
<Fact()>
Public Sub CallerInfo6()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class C
Function F() As C
Return Me
End Function
Default ReadOnly Property P(s As String, <CallerLineNumber> Optional line As Integer = 0) As C
Get
Console.WriteLine("{0}: {1}", s, line)
Return Me
End Get
End Property
Shared Sub Main()
Dim c = (New C())!x.
F()!y
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation,
<![CDATA[
x: 14
y: 15
]]>)
End Sub
<Fact()>
Public Sub CallerInfo7()
Dim compilation1 = CreateCSharpCompilation(<![CDATA[
using System.Runtime.CompilerServices;
public delegate void D(object o = null, [CallerLineNumber]int line = 0);
]]>.Value,
assemblyName:="1",
referencedAssemblies:=New MetadataReference() {MscorlibRef_v4_0_30316_17626})
compilation1.VerifyDiagnostics()
Dim reference1 = MetadataReference.CreateFromImage(compilation1.EmitToArray())
Dim compilation2 = CreateCompilationWithMscorlib45AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class C
Shared Sub M(Optional o As Object = Nothing, <CallerLineNumber> Optional line As Integer = 0)
Console.WriteLine(line)
End Sub
Shared Sub Main()
Dim d As New D(AddressOf M)
d(
1
)
d
End Sub
End Class
]]>
</file>
</compilation>,
options:=TestOptions.ReleaseExe,
additionalRefs:={reference1})
CompileAndVerify(compilation2,
<![CDATA[
9
12
]]>)
End Sub
<Fact>
Public Sub TestCallerFilePath1()
Dim source1 = "
Imports System.Runtime.CompilerServices
Imports System
Partial Module A
Dim i As Integer
Sub Log(<CallerFilePath> Optional filePath As String = Nothing)
i = i + 1
Console.WriteLine(""{0}: '{1}'"", i, filePath)
End Sub
Sub Main()
Log()
Main2()
Main3()
Main4()
End Sub
End Module"
Dim source2 = "
Partial Module A
Sub Main2()
Log()
End Sub
End Module
"
Dim source3 = "
Partial Module A
Sub Main3()
Log()
End Sub
End Module
"
Dim source4 = "
Partial Module A
Sub Main4()
Log()
End Sub
End Module
"
Dim compilation = CreateCompilationWithReferences(
{
SyntaxFactory.ParseSyntaxTree(source1, path:="C:\filename", encoding:=Encoding.UTF8),
SyntaxFactory.ParseSyntaxTree(source2, path:="a\b\..\c\d", encoding:=Encoding.UTF8),
SyntaxFactory.ParseSyntaxTree(source3, path:="*", encoding:=Encoding.UTF8),
SyntaxFactory.ParseSyntaxTree(source4, path:=" ", encoding:=Encoding.UTF8)
},
{MscorlibRef_v4_0_30316_17626, MsvbRef},
TestOptions.ReleaseExe.WithSourceReferenceResolver(SourceFileResolver.Default))
CompileAndVerify(compilation, expectedOutput:="
1: 'C:\filename'
2: 'a\b\..\c\d'
3: '*'
4: ' '
")
End Sub
<Fact>
Public Sub TestCallerFilePath2()
Dim source1 = "
Imports System.Runtime.CompilerServices
Imports System
Partial Module A
Dim i As Integer
Sub Log(<CallerFilePath> Optional filePath As String = Nothing)
i = i + 1
Console.WriteLine(""{0}: '{1}'"", i, filePath)
End Sub
Sub Main()
Log()
Main2()
Main3()
Main4()
Main5()
End Sub
End Module"
Dim source2 = "
Partial Module A
Sub Main2()
Log()
End Sub
End Module
"
Dim source3 = "
#ExternalSource(""make_hidden"", 30)
#End ExternalSource
Partial Module A
Sub Main3()
Log()
End Sub
End Module
"
Dim source4 = "
#ExternalSource(""abc"", 30)
Partial Module A
Sub Main4()
Log()
End Sub
End Module
#End ExternalSource
"
Dim source5 = "
#ExternalSource("" "", 30)
Partial Module A
Sub Main5()
Log()
End Sub
End Module
#End ExternalSource
"
Dim compilation = CreateCompilationWithReferences(
{
SyntaxFactory.ParseSyntaxTree(source1, path:="C:\filename", encoding:=Encoding.UTF8),
SyntaxFactory.ParseSyntaxTree(source2, path:="a\b\..\c\d.vb", encoding:=Encoding.UTF8),
SyntaxFactory.ParseSyntaxTree(source3, path:="*", encoding:=Encoding.UTF8),
SyntaxFactory.ParseSyntaxTree(source4, path:="C:\x.vb", encoding:=Encoding.UTF8),
SyntaxFactory.ParseSyntaxTree(source5, path:="C:\x.vb", encoding:=Encoding.UTF8)
},
{MscorlibRef_v4_0_30316_17626, MsvbRef},
TestOptions.ReleaseExe.WithSourceReferenceResolver(New SourceFileResolver({}, baseDirectory:="C:\A\B")))
CompileAndVerify(compilation, expectedOutput:="
1: 'C:\filename'
2: 'C:\A\B\a\c\d.vb'
3: '*'
4: 'C:\abc'
5: ' '
")
End Sub
<WorkItem(623122, "DevDiv"), WorkItem(619347, "DevDiv")>
<Fact()>
Public Sub Bug_619347_623122()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Program
Public Sub Bug623122(Optional ByVal p3 As Long? = 2)
System.Console.WriteLine(p3)
End Sub
Public Sub Bug619347(Optional x As Char? = "abc")
System.Console.WriteLine(x)
End Sub
Sub Main(args As String())
Bug623122()
Bug619347()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source)
comp.AssertNoDiagnostics()
CompileAndVerify(source,
expectedOutput:=<![CDATA[
2
a
]]>)
Dim prog As NamedTypeSymbol = comp.GetTypeByMetadataName("Program")
Dim Bug623122 = DirectCast(prog.GetMembers("Bug623122").Single, MethodSymbol)
Dim Bug619347 = DirectCast(prog.GetMembers("Bug619347").Single, MethodSymbol)
Assert.Equal("a"c, Bug619347.Parameters(0).ExplicitDefaultValue)
Assert.IsType(Of Char)(Bug619347.Parameters(0).ExplicitDefaultValue)
Assert.Equal(2L, Bug623122.Parameters(0).ExplicitDefaultValue)
Assert.IsType(Of Long)(Bug623122.Parameters(0).ExplicitDefaultValue)
End Sub
<Fact>
<WorkItem(529775, "DevDiv")>
Public Sub IsOptionalVsHasDefaultValue_PrimitiveStruct()
Dim source =
<compilation name="TestOptionalOnGenericMethod">
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.InteropServices
Public Class C
Public Sub M0(p As Integer)
End Sub
Public Sub M1(Optional p As Integer = 0) ' default of type
End Sub
Public Sub M2(Optional p As Integer = 1) ' not default of type
End Sub
Public Sub M3(<[Optional]> p As Integer) ' no default specified (would be illegal)
End Sub
Public Sub M4(<DefaultParameterValue(0)> p As Integer) ' default of type, not optional
End Sub
Public Sub M5(<DefaultParameterValue(1)> p As Integer) ' not default of type, not optional
End Sub
Public Sub M6(<[Optional]> <DefaultParameterValue(0)> p As Integer) ' default of type, optional
End Sub
Public Sub M7(<[Optional]> <DefaultParameterValue(1)> p As Integer) ' not default of type, optional
End Sub
End Class
]]>
</file>
</compilation>
Dim validator As Func(Of Boolean, Action(Of ModuleSymbol)) = Function(isFromSource) _
Sub([module])
Dim methods = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMembers().OfType(Of MethodSymbol)().Where(Function(m) m.MethodKind = MethodKind.Ordinary).ToArray()
Assert.Equal(8, methods.Length)
Dim parameters = methods.Select(Function(m) m.Parameters.Single()).ToArray()
Assert.False(parameters(0).IsOptional)
Assert.False(parameters(0).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(0).ExplicitDefaultValue)
Assert.Null(parameters(0).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(0).GetAttributes().Length)
Assert.True(parameters(1).IsOptional)
Assert.True(parameters(1).HasExplicitDefaultValue)
Assert.Equal(0, parameters(1).ExplicitDefaultValue)
Assert.Equal(ConstantValue.Create(0), parameters(1).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(1).GetAttributes().Length)
Assert.True(parameters(2).IsOptional)
Assert.True(parameters(2).HasExplicitDefaultValue)
Assert.Equal(1, parameters(2).ExplicitDefaultValue)
Assert.Equal(ConstantValue.Create(1), parameters(2).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(2).GetAttributes().Length)
' 3 - see below
Assert.False(parameters(4).IsOptional)
Assert.False(parameters(4).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(4).ExplicitDefaultValue)
Assert.Null(parameters(4).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(4).GetAttributes().Length)
Assert.False(parameters(5).IsOptional)
Assert.False(parameters(5).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(5).ExplicitDefaultValue)
Assert.Null(parameters(5).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(5).GetAttributes().Length)
If isFromSource Then
Assert.False(parameters(3).IsOptional)
Assert.False(parameters(3).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(3).ExplicitDefaultValue)
Assert.Null(parameters(3).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(3).GetAttributes().Length)
Assert.False(parameters(6).IsOptional)
Assert.False(parameters(6).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(6).ExplicitDefaultValue)
Assert.Null(parameters(6).ExplicitDefaultConstantValue)
Assert.Equal(2, parameters(6).GetAttributes().Length)
Assert.False(parameters(7).IsOptional)
Assert.False(parameters(7).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(7).ExplicitDefaultValue)
Assert.Null(parameters(7).ExplicitDefaultConstantValue)
Assert.Equal(2, parameters(7).GetAttributes().Length)
Else
Assert.True(parameters(3).IsOptional)
Assert.False(parameters(3).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(3).ExplicitDefaultValue)
Assert.Null(parameters(3).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(3).GetAttributes().Length)
Assert.True(parameters(6).IsOptional)
Assert.False(parameters(6).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(6).ExplicitDefaultValue)
Assert.Null(parameters(6).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(6).GetAttributes().Length) ' DefaultParameterValue
Assert.True(parameters(7).IsOptional)
Assert.False(parameters(7).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(7).ExplicitDefaultValue)
Assert.Null(parameters(7).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(7).GetAttributes().Length) ' DefaultParameterValue
End If
End Sub
CompileAndVerify(source, {MscorlibRef, SystemRef}, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False))
End Sub
<Fact>
<WorkItem(529775, "DevDiv")>
Public Sub IsOptionalVsHasDefaultValue_UserDefinedStruct()
Dim source =
<compilation name="TestOptionalOnGenericMethod">
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.InteropServices
Public Class C
Public Sub M0(p As S)
End Sub
Public Sub M1(Optional p As S = Nothing)
End Sub
Public Sub M2(<[Optional]> p As S) ' no default specified (would be illegal)
End Sub
Public Sub M3(<DefaultParameterValue(Nothing)> p As S) ' default of type, not optional
End Sub
Public Sub M4(<[Optional]> <DefaultParameterValue(Nothing)> p As S) ' default of type, optional
End Sub
End Class
Public Structure S
Public x As Integer
End Structure
]]>
</file>
</compilation>
Dim validator As Func(Of Boolean, Action(Of ModuleSymbol)) = Function(isFromSource) _
Sub([module])
Dim methods = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMembers().OfType(Of MethodSymbol)().Where(Function(m) m.MethodKind = MethodKind.Ordinary).ToArray()
Assert.Equal(5, methods.Length)
Dim parameters = methods.Select(Function(m) m.Parameters.Single()).ToArray()
Assert.False(parameters(0).IsOptional)
Assert.False(parameters(0).HasExplicitDefaultValue)
Assert.Null(parameters(0).ExplicitDefaultConstantValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(0).ExplicitDefaultValue)
Assert.Equal(0, parameters(0).GetAttributes().Length)
Assert.True(parameters(1).IsOptional)
Assert.True(parameters(1).HasExplicitDefaultValue)
Assert.Null(parameters(1).ExplicitDefaultValue)
Assert.Equal(ConstantValue.Null, parameters(1).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(1).GetAttributes().Length)
' 2 - see below
Assert.False(parameters(3).IsOptional)
Assert.False(parameters(3).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(3).ExplicitDefaultValue)
Assert.Null(parameters(3).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(3).GetAttributes().Length)
If isFromSource Then
Assert.False(parameters(2).IsOptional)
Assert.False(parameters(2).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(2).ExplicitDefaultValue)
Assert.Null(parameters(2).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(2).GetAttributes().Length)
Assert.False(parameters(4).IsOptional)
Assert.False(parameters(4).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(4).ExplicitDefaultValue)
Assert.Null(parameters(4).ExplicitDefaultConstantValue)
Assert.Equal(2, parameters(4).GetAttributes().Length)
Else
Assert.True(parameters(2).IsOptional)
Assert.False(parameters(2).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(2).ExplicitDefaultValue)
Assert.Null(parameters(2).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(2).GetAttributes().Length)
Assert.True(parameters(4).IsOptional)
Assert.False(parameters(4).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(4).ExplicitDefaultValue)
Assert.Null(parameters(4).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(4).GetAttributes().Length) ' DefaultParameterValue
End If
End Sub
CompileAndVerify(source, {MscorlibRef, SystemRef}, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False))
End Sub
<Fact>
<WorkItem(529775, "DevDiv")>
Public Sub IsOptionalVsHasDefaultValue_String()
Dim source =
<compilation name="TestOptionalOnGenericMethod">
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.InteropServices
Public Class C
Public Sub M0(p As String)
End Sub
Public Sub M1(Optional p As String = Nothing) ' default of type
End Sub
Public Sub M2(Optional p As String = "A") ' not default of type
End Sub
Public Sub M3(<[Optional]> p As String) ' no default specified (would be illegal)
End Sub
Public Sub M4(<DefaultParameterValue(Nothing)> p As String) ' default of type, not optional
End Sub
Public Sub M5(<DefaultParameterValue("A")> p As String) ' not default of type, not optional
End Sub
Public Sub M6(<[Optional]> <DefaultParameterValue(Nothing)> p As String) ' default of type, optional
End Sub
Public Sub M7(<[Optional]> <DefaultParameterValue("A")> p As String) ' not default of type, optional
End Sub
End Class
]]>
</file>
</compilation>
Dim validator As Func(Of Boolean, Action(Of ModuleSymbol)) = Function(isFromSource) _
Sub([module])
Dim methods = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMembers().OfType(Of MethodSymbol)().Where(Function(m) m.MethodKind = MethodKind.Ordinary).ToArray()
Assert.Equal(8, methods.Length)
Dim parameters = methods.Select(Function(m) m.Parameters.Single()).ToArray()
Assert.False(parameters(0).IsOptional)
Assert.False(parameters(0).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(0).ExplicitDefaultValue)
Assert.Null(parameters(0).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(0).GetAttributes().Length)
Assert.True(parameters(1).IsOptional)
Assert.True(parameters(1).HasExplicitDefaultValue)
Assert.Null(parameters(1).ExplicitDefaultValue)
Assert.Equal(ConstantValue.Null, parameters(1).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(1).GetAttributes().Length)
Assert.True(parameters(2).IsOptional)
Assert.True(parameters(2).HasExplicitDefaultValue)
Assert.Equal("A", parameters(2).ExplicitDefaultValue)
Assert.Equal(ConstantValue.Create("A"), parameters(2).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(2).GetAttributes().Length)
' 3 - see below
Assert.False(parameters(4).IsOptional)
Assert.False(parameters(4).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(4).ExplicitDefaultValue)
Assert.Null(parameters(4).ExplicitDefaultConstantValue) ' not imported for non-optional parameter
Assert.Equal(1, parameters(4).GetAttributes().Length)
Assert.False(parameters(5).IsOptional)
Assert.False(parameters(5).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(5).ExplicitDefaultValue)
Assert.Null(parameters(5).ExplicitDefaultConstantValue) ' not imported for non-optional parameter
Assert.Equal(1, parameters(5).GetAttributes().Length)
If isFromSource Then
Assert.False(parameters(3).IsOptional)
Assert.False(parameters(3).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(3).ExplicitDefaultValue)
Assert.Null(parameters(3).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(3).GetAttributes().Length)
Assert.False(parameters(6).IsOptional)
Assert.False(parameters(6).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(6).ExplicitDefaultValue)
Assert.Null(parameters(6).ExplicitDefaultConstantValue)
Assert.Equal(2, parameters(6).GetAttributes().Length)
Assert.False(parameters(7).IsOptional)
Assert.False(parameters(7).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(7).ExplicitDefaultValue)
Assert.Null(parameters(7).ExplicitDefaultConstantValue)
Assert.Equal(2, parameters(7).GetAttributes().Length)
Else
Assert.True(parameters(3).IsOptional)
Assert.False(parameters(3).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(3).ExplicitDefaultValue)
Assert.Null(parameters(3).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(3).GetAttributes().Length)
Assert.True(parameters(6).IsOptional)
Assert.False(parameters(6).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(6).ExplicitDefaultValue)
Assert.Null(parameters(6).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(6).GetAttributes().Length)
Assert.True(parameters(7).IsOptional)
Assert.False(parameters(7).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(7).ExplicitDefaultValue)
Assert.Null(parameters(7).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(7).GetAttributes().Length)
End If
End Sub
CompileAndVerify(source, {MscorlibRef, SystemRef}, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False))
End Sub
<Fact>
<WorkItem(529775, "DevDiv")>
Public Sub IsOptionalVsHasDefaultValue_Decimal()
Dim source =
<compilation name="TestOptionalOnGenericMethod">
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
Public Sub M0(p As Decimal)
End Sub
Public Sub M1(Optional p As Decimal = 0) ' default of type
End Sub
Public Sub M2(Optional p As Decimal = 1) ' not default of type
End Sub
Public Sub M3(<[Optional]> p As Decimal) ' no default specified (would be illegal)
End Sub
Public Sub M4(<DefaultParameterValue(0)> p As Decimal) ' default of type, not optional
End Sub
Public Sub M5(<DefaultParameterValue(1)> p As Decimal) ' not default of type, not optional
End Sub
Public Sub M6(<[Optional]> <DefaultParameterValue(0)> p As Decimal) ' default of type, optional
End Sub
Public Sub M7(<[Optional]> <DefaultParameterValue(1)> p As Decimal) ' not default of type, optional
End Sub
Public Sub M8(<DecimalConstant(0, 0, 0, 0, 0)> p As Decimal) ' default of type, not optional
End Sub
Public Sub M9(<DecimalConstant(0, 0, 0, 0, 1)> p As Decimal) ' not default of type, not optional
End Sub
Public Sub M10(<[Optional]> <DecimalConstant(0, 0, 0, 0, 0)> p As Decimal) ' default of type, optional
End Sub
Public Sub M11(<[Optional]> <DecimalConstant(0, 0, 0, 0, 1)> p As Decimal) ' not default of type, optional
End Sub
End Class
]]>
</file>
</compilation>
Dim validator As Func(Of Boolean, Action(Of ModuleSymbol)) = Function(isFromSource) _
Sub([module])
Dim methods = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMembers().OfType(Of MethodSymbol)().Where(Function(m) m.MethodKind = MethodKind.Ordinary).ToArray()
Assert.Equal(12, methods.Length)
Dim parameters = methods.Select(Function(m) m.Parameters.Single()).ToArray()
Dim decimalZero = CType(0, Decimal)
Dim decimalOne = CType(1, Decimal)
Assert.False(parameters(0).IsOptional)
Assert.False(parameters(0).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(0).ExplicitDefaultValue)
Assert.Null(parameters(0).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(0).GetAttributes().Length)
Assert.True(parameters(1).IsOptional)
Assert.True(parameters(1).HasExplicitDefaultValue)
Assert.Equal(decimalZero, parameters(1).ExplicitDefaultValue)
Assert.Equal(ConstantValue.Create(decimalZero), parameters(1).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(1).GetAttributes().Length)
Assert.True(parameters(2).IsOptional)
Assert.True(parameters(2).HasExplicitDefaultValue)
Assert.Equal(decimalOne, parameters(2).ExplicitDefaultValue)
Assert.Equal(ConstantValue.Create(decimalOne), parameters(2).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(2).GetAttributes().Length)
' 3 - see below
Assert.False(parameters(4).IsOptional)
Assert.False(parameters(4).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(4).ExplicitDefaultValue)
Assert.Null(parameters(4).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(4).GetAttributes().Length) ' DefaultParameterValue
Assert.False(parameters(5).IsOptional)
Assert.False(parameters(5).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(5).ExplicitDefaultValue)
Assert.Null(parameters(5).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(5).GetAttributes().Length) ' DefaultParameterValue
' 6 - see below
' 7 - see below
Assert.False(parameters(8).IsOptional)
Assert.False(parameters(8).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(8).ExplicitDefaultValue)
Assert.Null(parameters(8).ExplicitDefaultConstantValue) ' not imported for non-optional parameter
Assert.Equal(1, parameters(8).GetAttributes().Length) ' DecimalConstantAttribute
Assert.False(parameters(9).IsOptional)
Assert.False(parameters(9).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(9).ExplicitDefaultValue)
Assert.Null(parameters(9).ExplicitDefaultConstantValue) ' not imported for non-optional parameter
Assert.Equal(1, parameters(9).GetAttributes().Length) ' DecimalConstantAttribute
If isFromSource Then
Assert.False(parameters(3).IsOptional)
Assert.False(parameters(3).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(3).ExplicitDefaultValue)
Assert.Null(parameters(3).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(3).GetAttributes().Length)
Assert.False(parameters(6).IsOptional)
Assert.False(parameters(6).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(6).ExplicitDefaultValue)
Assert.Null(parameters(6).ExplicitDefaultConstantValue)
Assert.Equal(2, parameters(6).GetAttributes().Length)
Assert.False(parameters(7).IsOptional)
Assert.False(parameters(7).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(7).ExplicitDefaultValue)
Assert.Null(parameters(7).ExplicitDefaultConstantValue)
Assert.Equal(2, parameters(7).GetAttributes().Length)
Assert.False(parameters(10).IsOptional)
Assert.False(parameters(10).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(10).ExplicitDefaultValue)
Assert.Null(parameters(10).ExplicitDefaultConstantValue)
Assert.Equal(2, parameters(10).GetAttributes().Length)
Assert.False(parameters(11).IsOptional)
Assert.False(parameters(11).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(11).ExplicitDefaultValue)
Assert.Null(parameters(11).ExplicitDefaultConstantValue)
Assert.Equal(2, parameters(11).GetAttributes().Length)
Else
Assert.True(parameters(3).IsOptional)
Assert.False(parameters(3).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(3).ExplicitDefaultValue)
Assert.Null(parameters(3).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(3).GetAttributes().Length)
Assert.True(parameters(6).IsOptional)
Assert.False(parameters(6).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(6).ExplicitDefaultValue)
Assert.Null(parameters(6).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(6).GetAttributes().Length) ' DefaultParameterValue
Assert.True(parameters(7).IsOptional)
Assert.False(parameters(7).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(7).ExplicitDefaultValue)
Assert.Null(parameters(7).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(7).GetAttributes().Length) ' DefaultParameterValue
Assert.True(parameters(10).IsOptional)
Assert.True(parameters(10).HasExplicitDefaultValue)
Assert.Equal(decimalZero, parameters(10).ExplicitDefaultValue)
Assert.Equal(ConstantValue.Create(decimalZero), parameters(10).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(10).GetAttributes().Length)
Assert.True(parameters(11).IsOptional)
Assert.True(parameters(11).HasExplicitDefaultValue)
Assert.Equal(decimalOne, parameters(11).ExplicitDefaultValue)
Assert.Equal(ConstantValue.Create(decimalOne), parameters(11).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(11).GetAttributes().Length)
End If
End Sub
CompileAndVerify(source, {MscorlibRef, SystemRef}, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False))
End Sub
<Fact>
<WorkItem(529775, "DevDiv")>
Public Sub IsOptionalVsHasDefaultValue_DateTime()
Dim source =
<compilation name="TestOptionalOnGenericMethod">
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
Public Sub M0(p As Date)
End Sub
Public Sub M1(Optional p As Date = Nothing) ' default of type
End Sub
Public Sub M2(Optional p As Date = #12/25/1991#) ' not default of type
End Sub
Public Sub M3(<[Optional]> p As Date) ' no default specified (would be illegal)
End Sub
Public Sub M4(<DefaultParameterValue(Nothing)> p As Date) ' default of type, not optional (note: can't use a date literal here)
End Sub
Public Sub M5(<[Optional]> <DefaultParameterValue(Nothing)> p As Date) ' default of type, optional
End Sub
Public Sub M6(<DateTimeConstant(0)> p As Date) ' default of type, not optional
End Sub
Public Sub M7(<DateTimeConstant(1)> p As Date) ' not default of type, not optional
End Sub
Public Sub M8(<[Optional]> <DateTimeConstant(0)> p As Date) ' default of type, optional
End Sub
Public Sub M9(<[Optional]> <DateTimeConstant(1)> p As Date) ' not default of type, optional
End Sub
End Class
]]>
</file>
</compilation>
Dim validator As Func(Of Boolean, Action(Of ModuleSymbol)) = Function(isFromSource) _
Sub([module])
Dim methods = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMembers().OfType(Of MethodSymbol)().Where(Function(m) m.MethodKind = MethodKind.Ordinary).ToArray()
Assert.Equal(10, methods.Length)
Dim parameters = methods.Select(Function(m) m.Parameters.Single()).ToArray()
Dim dateTimeZero = New DateTime(0)
Dim dateTimeOne = New DateTime(1)
Dim dateTimeOther = #12/25/1991#
Assert.False(parameters(0).IsOptional)
Assert.False(parameters(0).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(0).ExplicitDefaultValue)
Assert.Null(parameters(0).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(0).GetAttributes().Length)
Assert.True(parameters(1).IsOptional)
Assert.True(parameters(1).HasExplicitDefaultValue)
Assert.Equal(dateTimeZero, parameters(1).ExplicitDefaultValue)
Assert.Equal(ConstantValue.Create(dateTimeZero), parameters(1).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(1).GetAttributes().Length)
Assert.True(parameters(2).IsOptional)
Assert.True(parameters(2).HasExplicitDefaultValue)
Assert.Equal(dateTimeOther, parameters(2).ExplicitDefaultValue)
Assert.Equal(ConstantValue.Create(dateTimeOther), parameters(2).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(2).GetAttributes().Length)
' 3 - see below
Assert.False(parameters(4).IsOptional)
Assert.False(parameters(4).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(4).ExplicitDefaultValue)
Assert.Null(parameters(4).ExplicitDefaultConstantValue) ' not imported for non-optional parameter
Assert.Equal(1, parameters(4).GetAttributes().Length) ' DefaultParameterValue
' 5 - see below
Assert.False(parameters(6).IsOptional)
Assert.False(parameters(6).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(6).ExplicitDefaultValue)
Assert.Null(parameters(6).ExplicitDefaultConstantValue) ' not imported for non-optional parameter
Assert.Equal(1, parameters(6).GetAttributes().Length) ' DateTimeConstant
Assert.False(parameters(7).IsOptional)
Assert.False(parameters(7).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(7).ExplicitDefaultValue)
Assert.Null(parameters(7).ExplicitDefaultConstantValue) ' not imported for non-optional parameter
Assert.Equal(1, parameters(7).GetAttributes().Length) ' DateTimeConstant
If isFromSource Then
Assert.False(parameters(3).IsOptional)
Assert.False(parameters(3).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(3).ExplicitDefaultValue)
Assert.Null(parameters(3).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(3).GetAttributes().Length)
Assert.False(parameters(5).IsOptional)
Assert.False(parameters(5).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(5).ExplicitDefaultValue)
Assert.Null(parameters(5).ExplicitDefaultConstantValue)
Assert.Equal(2, parameters(5).GetAttributes().Length)
Assert.False(parameters(8).IsOptional)
Assert.False(parameters(8).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(8).ExplicitDefaultValue)
Assert.Null(parameters(8).ExplicitDefaultConstantValue)
Assert.Equal(2, parameters(8).GetAttributes().Length)
Assert.False(parameters(9).IsOptional)
Assert.False(parameters(9).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(9).ExplicitDefaultValue)
Assert.Null(parameters(9).ExplicitDefaultConstantValue)
Assert.Equal(2, parameters(9).GetAttributes().Length)
Else
Assert.True(parameters(3).IsOptional)
Assert.False(parameters(3).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(3).ExplicitDefaultValue)
Assert.Null(parameters(3).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(3).GetAttributes().Length)
Assert.True(parameters(5).IsOptional)
Assert.False(parameters(5).HasExplicitDefaultValue)
Assert.Throws(Of InvalidOperationException)(Function() parameters(5).ExplicitDefaultValue)
Assert.Null(parameters(5).ExplicitDefaultConstantValue)
Assert.Equal(1, parameters(5).GetAttributes().Length) ' DefaultParameterValue
Assert.True(parameters(8).IsOptional)
Assert.True(parameters(8).HasExplicitDefaultValue)
Assert.Equal(dateTimeZero, parameters(8).ExplicitDefaultValue)
Assert.Equal(ConstantValue.Create(dateTimeZero), parameters(8).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(8).GetAttributes().Length)
Assert.True(parameters(9).IsOptional)
Assert.True(parameters(9).HasExplicitDefaultValue)
Assert.Equal(dateTimeOne, parameters(9).ExplicitDefaultValue)
Assert.Equal(ConstantValue.Create(dateTimeOne), parameters(9).ExplicitDefaultConstantValue)
Assert.Equal(0, parameters(9).GetAttributes().Length)
End If
End Sub
CompileAndVerify(source, {MscorlibRef, SystemRef}, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False))
End Sub
End Class
End Namespace
|
droyad/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/Semantics/OptionalArgumentTests.vb
|
Visual Basic
|
apache-2.0
| 92,358
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.Editor.Implementation.Outlining
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.Outlining
Friend Class MultilineLambdaOutliner
Inherits AbstractSyntaxNodeOutliner(Of MultiLineLambdaExpressionSyntax)
Private Shared Function GetBannerText(lambdaHeader As LambdaHeaderSyntax) As String
Dim builder As New BannerTextBuilder()
For Each modifier In lambdaHeader.Modifiers
builder.Append(modifier.ToString())
builder.Append(" "c)
Next
builder.Append(lambdaHeader.DeclarationKeyword.ToString())
builder.AppendParameterList(lambdaHeader.ParameterList, emptyParentheses:=True)
builder.AppendAsClause(lambdaHeader.AsClause)
builder.Append(" "c)
builder.Append(Ellipsis)
Return builder.ToString()
End Function
Protected Overrides Sub CollectOutliningSpans(lambdaExpression As MultiLineLambdaExpressionSyntax, spans As List(Of OutliningSpan), cancellationToken As CancellationToken)
If lambdaExpression.EndSubOrFunctionStatement.IsMissing Then
Return
End If
spans.Add(
VisualBasicOutliningHelpers.CreateRegionFromBlock(
lambdaExpression,
GetBannerText(lambdaExpression.SubOrFunctionHeader),
autoCollapse:=False))
End Sub
End Class
End Namespace
|
AlexisArce/roslyn
|
src/EditorFeatures/VisualBasic/Outlining/Outliners/MultilineLambdaOutliner.vb
|
Visual Basic
|
apache-2.0
| 1,727
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Public Class VisualBasicCompilation
Friend Class EntryPointCandidateFinder
Inherits VisualBasicSymbolVisitor(Of Predicate(Of Symbol), Boolean)
Private ReadOnly _entryPointCandidates As ArrayBuilder(Of MethodSymbol)
Private ReadOnly _visitNestedTypes As Boolean
Private ReadOnly _cancellationToken As CancellationToken
Friend Shared Sub FindCandidatesInNamespace(root As NamespaceSymbol, entryPointCandidates As ArrayBuilder(Of MethodSymbol), cancellationToken As CancellationToken)
Dim finder As New EntryPointCandidateFinder(entryPointCandidates, visitNestedTypes:=True, cancellationToken:=cancellationToken)
finder.Visit(root)
End Sub
Private Sub New(entryPointCandidates As ArrayBuilder(Of MethodSymbol),
visitNestedTypes As Boolean,
cancellationToken As CancellationToken)
Me._entryPointCandidates = entryPointCandidates
Me._visitNestedTypes = visitNestedTypes
Me._cancellationToken = cancellationToken
End Sub
Public Overrides Function VisitNamespace(symbol As NamespaceSymbol, filter As Predicate(Of Symbol)) As Boolean
_cancellationToken.ThrowIfCancellationRequested()
If filter Is Nothing OrElse filter(symbol) Then
For Each member In symbol.GetMembersUnordered()
member.Accept(Me, filter)
Next
End If
Return True
End Function
Public Overrides Function VisitNamedType(symbol As NamedTypeSymbol, filter As Predicate(Of Symbol)) As Boolean
_cancellationToken.ThrowIfCancellationRequested()
If filter IsNot Nothing AndAlso Not filter(symbol) Then
Return True
End If
If symbol.IsEmbedded Then
' Don't process embedded types
Return True
End If
For Each member In symbol.GetMembersUnordered()
' process all members that are not methods as usual
If member.Kind = SymbolKind.NamedType Then
If Me._visitNestedTypes Then
member.Accept(Me, filter)
End If
ElseIf member.Kind = SymbolKind.Method Then
Dim method = DirectCast(member, MethodSymbol)
' check if this is an entry point
If Not method.IsSubmissionConstructor AndAlso _entryPointCandidates IsNot Nothing AndAlso Not method.IsImplicitlyDeclared AndAlso method.IsEntryPointCandidate Then
_entryPointCandidates.Add(method)
End If
End If
Next
Return True
End Function
End Class
End Class
End Namespace
|
bbarry/roslyn
|
src/Compilers/VisualBasic/Portable/Compilation/EntryPointCandidateFinder.vb
|
Visual Basic
|
apache-2.0
| 3,470
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("Practica2")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("Practica2")>
<Assembly: AssemblyCopyright("Copyright © 2014")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("b0ebc8ab-3265-4d2b-8b2c-e8710e0af842")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
rafael25/poe-unitec
|
Practica1/Practica1/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,171
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class frmAverageGrade
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.lblGrade = New System.Windows.Forms.Label()
Me.txtGrade = New System.Windows.Forms.TextBox()
Me.btnRecord = New System.Windows.Forms.Button()
Me.btnDisplay = New System.Windows.Forms.Button()
Me.lstGradeData = New System.Windows.Forms.ListBox()
Me.SuspendLayout()
'
'lblGrade
'
Me.lblGrade.AutoSize = True
Me.lblGrade.Location = New System.Drawing.Point(12, 30)
Me.lblGrade.Name = "lblGrade"
Me.lblGrade.Size = New System.Drawing.Size(39, 13)
Me.lblGrade.TabIndex = 0
Me.lblGrade.Text = "Grade:"
'
'txtGrade
'
Me.txtGrade.Location = New System.Drawing.Point(57, 27)
Me.txtGrade.Name = "txtGrade"
Me.txtGrade.Size = New System.Drawing.Size(50, 20)
Me.txtGrade.TabIndex = 1
'
'btnRecord
'
Me.btnRecord.Location = New System.Drawing.Point(132, 12)
Me.btnRecord.Name = "btnRecord"
Me.btnRecord.Size = New System.Drawing.Size(100, 35)
Me.btnRecord.TabIndex = 2
Me.btnRecord.Text = "Record Grade"
Me.btnRecord.UseVisualStyleBackColor = True
'
'btnDisplay
'
Me.btnDisplay.Location = New System.Drawing.Point(12, 53)
Me.btnDisplay.Name = "btnDisplay"
Me.btnDisplay.Size = New System.Drawing.Size(220, 50)
Me.btnDisplay.TabIndex = 3
Me.btnDisplay.Text = "Display Average Grade and Number" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "of Above-Average Grades"
Me.btnDisplay.UseVisualStyleBackColor = True
'
'lstGradeData
'
Me.lstGradeData.FormattingEnabled = True
Me.lstGradeData.Location = New System.Drawing.Point(12, 110)
Me.lstGradeData.Name = "lstGradeData"
Me.lstGradeData.Size = New System.Drawing.Size(220, 30)
Me.lstGradeData.TabIndex = 4
'
'frmAverageGrade
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(244, 162)
Me.Controls.Add(Me.lstGradeData)
Me.Controls.Add(Me.btnDisplay)
Me.Controls.Add(Me.btnRecord)
Me.Controls.Add(Me.txtGrade)
Me.Controls.Add(Me.lblGrade)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
Me.MaximizeBox = False
Me.Name = "frmAverageGrade"
Me.Text = "Grades"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents lblGrade As System.Windows.Forms.Label
Friend WithEvents txtGrade As System.Windows.Forms.TextBox
Friend WithEvents btnRecord As System.Windows.Forms.Button
Friend WithEvents btnDisplay As System.Windows.Forms.Button
Friend WithEvents lstGradeData As System.Windows.Forms.ListBox
End Class
|
patkub/visual-basic-intro
|
Average Grade/Average Grade/frmAverageGrade.Designer.vb
|
Visual Basic
|
mit
| 3,868
|
#Region "Microsoft.VisualBasic::af84cd48b8aea6bf935184af1bc0637c, src\mzmath\TargetedMetabolomics\LinearQuantitative\PeakAreaMethods.vb"
' Author:
'
' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.)
'
' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD.
'
'
' MIT License
'
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
' /********************************************************************************/
' Summaries:
' Enum PeakAreaMethods
'
' MaxPeakHeight, SumAll
'
'
'
'
'
'
' /********************************************************************************/
#End Region
Namespace LinearQuantitative
''' <summary>
''' + 积分方法太敏感了,可能会对ROI以及峰型要求非常高
''' + 净峰法简单相加会比较鲁棒一些
''' </summary>
Public Enum PeakAreaMethods
#Region "A = S - B"
''' <summary>
''' 使用简单的信号相加净峰法来计算峰面积
''' </summary>
NetPeakSum = 0
''' <summary>
''' 使用积分器来进行峰面积的计算
''' </summary>
Integrator = 1
#End Region
''' <summary>
''' No peak finding, sum all chromatogram ticks signal intensity directly.
''' 基线非常低(接近于零)的时候可以使用
''' </summary>
SumAll
''' <summary>
''' 如果色谱柱的压力非常大,出峰非常的集中,可以直接使用最大的峰高度来近似为峰面积
''' </summary>
MaxPeakHeight
End Enum
End Namespace
|
xieguigang/MassSpectrum-toolkits
|
src/mzmath/TargetedMetabolomics/LinearQuantitative/PeakAreaMethods.vb
|
Visual Basic
|
mit
| 2,770
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' Allgemeine Informationen über eine Assembly werden über die folgenden
' Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
' die mit einer Assembly verknüpft sind.
' Die Werte der Assemblyattribute überprüfen
<Assembly: AssemblyTitle("Softeis")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("Softeis")>
<Assembly: AssemblyCopyright("Copyright © 2014")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
<Assembly: Guid("7dc839fa-7aa1-4e1b-9e38-28a0605495bc")>
' Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
'
' Hauptversion
' Nebenversion
' Buildnummer
' Revision
'
' Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
' übernehmen, indem Sie "*" eingeben:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
lbischof/gibb
|
303_Softeis/Softeis/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,189
|
Namespace Inspection
''' <summary>This attribute should declare the Type of object that is encapsulated by the collection.</summary>
''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated>
''' <generator-date>10/02/2014 15:52:05</generator-date>
''' <generator-functions>1</generator-functions>
''' <generator-source>Leviathan\_Inspection\Querying\Generated\AnalyserQuery.tt</generator-source>
''' <generator-template>Text-Templates\Classes\VB_Object.tt</generator-template>
''' <generator-version>1</generator-version>
<System.CodeDom.Compiler.GeneratedCode("Leviathan\_Inspection\Querying\Generated\AnalyserQuery.tt", "1")> _
Partial Public Class AnalyserQuery
Inherits System.Object
#Region " Public Constructors "
''' <summary>Default Constructor</summary>
Public Sub New()
MyBase.New()
m_Parts = New System.Collections.ArrayList
End Sub
''' <summary>Parametered Constructor (1 Parameters)</summary>
Public Sub New( _
ByVal _ReturnType As AnalyserType _
)
MyBase.New()
ReturnType = _ReturnType
m_Parts = New System.Collections.ArrayList
End Sub
''' <summary>Parametered Constructor (2 Parameters)</summary>
Public Sub New( _
ByVal _ReturnType As AnalyserType, _
ByVal _DeclaredBelowType As System.Type _
)
MyBase.New()
ReturnType = _ReturnType
DeclaredBelowType = _DeclaredBelowType
m_Parts = New System.Collections.ArrayList
End Sub
''' <summary>Parametered Constructor (3 Parameters)</summary>
Public Sub New( _
ByVal _ReturnType As AnalyserType, _
ByVal _DeclaredBelowType As System.Type, _
ByVal _NumberOfResults As System.Int32 _
)
MyBase.New()
ReturnType = _ReturnType
DeclaredBelowType = _DeclaredBelowType
NumberOfResults = _NumberOfResults
m_Parts = New System.Collections.ArrayList
End Sub
''' <summary>Parametered Constructor (4 Parameters)</summary>
Public Sub New( _
ByVal _ReturnType As AnalyserType, _
ByVal _DeclaredBelowType As System.Type, _
ByVal _NumberOfResults As System.Int32, _
ByVal _Parts As System.Collections.ArrayList _
)
MyBase.New()
ReturnType = _ReturnType
DeclaredBelowType = _DeclaredBelowType
NumberOfResults = _NumberOfResults
Parts = _Parts
End Sub
#End Region
#Region " Class Plumbing/Interface Code "
#Region " Settable Implementation "
#Region " Public Methods "
Public Function SetReturnType(_ReturnType As AnalyserType) As AnalyserQuery
ReturnType = _ReturnType
Return Me
End Function
Public Function SetDeclaredBelowType(_DeclaredBelowType As System.Type) As AnalyserQuery
DeclaredBelowType = _DeclaredBelowType
Return Me
End Function
Public Function SetNumberOfResults(_NumberOfResults As System.Int32) As AnalyserQuery
NumberOfResults = _NumberOfResults
Return Me
End Function
Public Function SetParts(_Parts As System.Collections.ArrayList) As AnalyserQuery
Parts = _Parts
Return Me
End Function
#End Region
#End Region
#End Region
#Region " Public Constants "
''' <summary>Public Shared Reference to the Name of the Property: ReturnType</summary>
''' <remarks></remarks>
Public Const PROPERTY_RETURNTYPE As String = "ReturnType"
''' <summary>Public Shared Reference to the Name of the Property: DeclaredBelowType</summary>
''' <remarks></remarks>
Public Const PROPERTY_DECLAREDBELOWTYPE As String = "DeclaredBelowType"
''' <summary>Public Shared Reference to the Name of the Property: NumberOfResults</summary>
''' <remarks></remarks>
Public Const PROPERTY_NUMBEROFRESULTS As String = "NumberOfResults"
''' <summary>Public Shared Reference to the Name of the Property: Parts</summary>
''' <remarks></remarks>
Public Const PROPERTY_PARTS As String = "Parts"
#End Region
#Region " Private Variables "
''' <summary>Private Data Storage Variable for Property: ReturnType</summary>
''' <remarks></remarks>
Private m_ReturnType As AnalyserType
''' <summary>Private Data Storage Variable for Property: DeclaredBelowType</summary>
''' <remarks></remarks>
Private m_DeclaredBelowType As System.Type
''' <summary>Private Data Storage Variable for Property: NumberOfResults</summary>
''' <remarks></remarks>
Private m_NumberOfResults As System.Int32
''' <summary>Private Data Storage Variable for Property: Parts</summary>
''' <remarks></remarks>
Private m_Parts As System.Collections.ArrayList
#End Region
#Region " Public Properties "
''' <summary>Provides Access to the Property: ReturnType</summary>
''' <remarks></remarks>
Public Property ReturnType() As AnalyserType
Get
Return m_ReturnType
End Get
Set(value As AnalyserType)
m_ReturnType = value
End Set
End Property
''' <summary>Provides Access to the Property: DeclaredBelowType</summary>
''' <remarks></remarks>
Public Property DeclaredBelowType() As System.Type
Get
Return m_DeclaredBelowType
End Get
Set(value As System.Type)
m_DeclaredBelowType = value
End Set
End Property
''' <summary>Provides Access to the Property: NumberOfResults</summary>
''' <remarks></remarks>
Public Property NumberOfResults() As System.Int32
Get
Return m_NumberOfResults
End Get
Set(value As System.Int32)
m_NumberOfResults = value
End Set
End Property
''' <summary>Provides Access to the Property: Parts</summary>
''' <remarks></remarks>
Public Property Parts() As System.Collections.ArrayList
Get
Return m_Parts
End Get
Set(value As System.Collections.ArrayList)
m_Parts = value
End Set
End Property
#End Region
End Class
End Namespace
|
thiscouldbejd/Leviathan
|
_Inspection/Querying/Generated/AnalyserQuery.vb
|
Visual Basic
|
mit
| 5,889
|
Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
Imports DotNetNdsToolkit
Imports SkyEditor.Core.IO
Imports SkyEditor.Core.Utilities
Public Class Converter
Implements IDisposable
Implements IReportProgress
Public Event ConsoleOutputReceived(sender As Object, e As DataReceivedEventArgs)
''' <summary>
''' Whether or not to forward console output of child processes to the current process.
''' </summary>
''' <returns></returns>
Public Property OutputConsoleOutput As Boolean = True
Private Async Function RunProgram(program As String, arguments As String) As Task
Dim handlersRegistered As Boolean = False
Dim p As New Process
p.StartInfo.FileName = program
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(program)
p.StartInfo.Arguments = arguments
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
p.StartInfo.CreateNoWindow = True
p.StartInfo.RedirectStandardOutput = OutputConsoleOutput
p.StartInfo.RedirectStandardError = p.StartInfo.RedirectStandardOutput
p.StartInfo.UseShellExecute = False
If p.StartInfo.RedirectStandardOutput Then
AddHandler p.OutputDataReceived, AddressOf OnInputRecieved
AddHandler p.ErrorDataReceived, AddressOf OnInputRecieved
handlersRegistered = True
End If
p.Start()
p.BeginOutputReadLine()
p.BeginErrorReadLine()
Await Task.Run(Sub() p.WaitForExit())
If handlersRegistered Then
RemoveHandler p.OutputDataReceived, AddressOf OnInputRecieved
RemoveHandler p.ErrorDataReceived, AddressOf OnInputRecieved
End If
End Function
Private Sub OnInputRecieved(sender As Object, e As DataReceivedEventArgs)
If TypeOf sender Is Process AndAlso Not String.IsNullOrEmpty(e.Data) Then
Console.Write($"[{Path.GetFileNameWithoutExtension(DirectCast(sender, Process).StartInfo.FileName)}] ")
Console.WriteLine(e.Data)
RaiseEvent ConsoleOutputReceived(Me, e)
End If
End Sub
Private Sub EnsureInputIsNotInOutputBeforeDeleting(inputFile As String, outputPath As String)
If Not outputPath.EndsWith("/") Then
outputPath &= "/"
End If
Dim input As New Uri(inputFile)
Dim output As New Uri(outputPath)
If output.IsBaseOf(input) Then
Throw New InputInsideOutputException
End If
End Sub
Public Event UnpackProgressed As EventHandler(Of ProgressReportedEventArgs) Implements IReportProgress.ProgressChanged
Public Event Completed As EventHandler Implements IReportProgress.Completed
#Region "Tool Management"
Private Property ToolDirectory As String
Private Property Path_3dstool As String
Private Property Path_3dsbuilder As String
Private Property Path_makerom As String
Private Property Path_ctrtool As String
Private Property Path_ndstool As String
Public Property Progress As Single Implements IReportProgress.Progress
Get
Return _progress
End Get
Private Set(value As Single)
If value <> _progress Then
_progress = value
RaiseEvent UnpackProgressed(Me, New ProgressReportedEventArgs With {.Progress = Progress, .IsIndeterminate = IsIndeterminate, .Message = Message})
End If
End Set
End Property
Dim _progress As Single
Public Property Message As String Implements IReportProgress.Message
Get
Return _message
End Get
Protected Set(value As String)
If value <> _message Then
_message = value
RaiseEvent UnpackProgressed(Me, New ProgressReportedEventArgs With {.Progress = Progress, .IsIndeterminate = IsIndeterminate, .Message = Message})
End If
End Set
End Property
Dim _message As String
Public Property IsIndeterminate As Boolean Implements IReportProgress.IsIndeterminate
Get
Return _isIndeterminate
End Get
Protected Set(value As Boolean)
If value <> _isIndeterminate Then
_isIndeterminate = value
RaiseEvent UnpackProgressed(Me, New ProgressReportedEventArgs With {.Progress = Progress, .IsIndeterminate = IsIndeterminate, .Message = Message})
End If
End Set
End Property
Dim _isIndeterminate As Boolean
Public Property IsCompleted As Boolean Implements IReportProgress.IsCompleted
Get
Return _isCompleted
End Get
Protected Set(value As Boolean)
If value <> _isCompleted Then
_isCompleted = value
If value Then
Progress = 1
IsIndeterminate = False
RaiseEvent Completed(Me, New EventArgs)
End If
End If
End Set
End Property
Dim _isCompleted As Boolean
Private Sub ResetToolDirectory()
ToolDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DotNet3DSToolkit-" & Guid.NewGuid.ToString)
If Directory.Exists(ToolDirectory) Then
ResetToolDirectory()
Else
Directory.CreateDirectory(ToolDirectory)
End If
End Sub
''' <summary>
''' Copies 3dstool.exe to the the tools directory if it's not already there.
''' </summary>
Private Sub Copy3DSTool()
If String.IsNullOrEmpty(ToolDirectory) Then
ResetToolDirectory()
End If
Dim exePath = Path.Combine(ToolDirectory, "3dstool.exe")
Dim txtPath = Path.Combine(ToolDirectory, "ignore_3dstool.txt")
If Not File.Exists(exePath) Then
File.WriteAllBytes(exePath, My.Resources._3dstool)
Path_3dstool = exePath
End If
If Not File.Exists(txtPath) Then
File.WriteAllText(Path.Combine(ToolDirectory, "ignore_3dstool.txt"), My.Resources.ignore_3dstool)
End If
End Sub
Private Sub Copy3DSBuilder()
If String.IsNullOrEmpty(ToolDirectory) Then
ResetToolDirectory()
End If
Dim exePath = Path.Combine(ToolDirectory, "3DS Builder.exe")
If Not File.Exists(exePath) Then
File.WriteAllBytes(exePath, My.Resources._3DS_Builder)
Path_3dsbuilder = exePath
End If
End Sub
Private Sub CopyCtrTool()
If String.IsNullOrEmpty(ToolDirectory) Then
ResetToolDirectory()
End If
Dim exePath = Path.Combine(ToolDirectory, "ctrtool.exe")
If Not File.Exists(exePath) Then
File.WriteAllBytes(exePath, My.Resources.ctrtool)
Path_ctrtool = exePath
End If
End Sub
Private Sub CopyMakeRom()
If String.IsNullOrEmpty(ToolDirectory) Then
ResetToolDirectory()
End If
Dim exePath = Path.Combine(ToolDirectory, "makerom.exe")
If Not File.Exists(exePath) Then
File.WriteAllBytes(exePath, My.Resources.makerom)
Path_makerom = exePath
End If
End Sub
Private Sub CopyNDSTool()
If String.IsNullOrEmpty(ToolDirectory) Then
ResetToolDirectory()
End If
Dim exePath = Path.Combine(ToolDirectory, "ndstool.exe")
If Not File.Exists(exePath) Then
File.WriteAllBytes(exePath, My.Resources.ndstool)
Path_ndstool = exePath
End If
End Sub
Private Sub DeleteTools()
If Directory.Exists(ToolDirectory) Then
Directory.Delete(ToolDirectory, True)
End If
End Sub
#End Region
#Region "Extraction"
Public Sub ExtractPrivateHeader(sourceCCI As String, outputFile As String)
Dim onlineHeaderBinPath = outputFile
Using f As New FileStream(sourceCCI, FileMode.Open, FileAccess.Read)
Dim buffer(&H2E00 + 1) As Byte
f.Seek(&H1200, SeekOrigin.Begin)
f.Read(buffer, 0, &H2E00)
File.WriteAllBytes(onlineHeaderBinPath, buffer)
End Using
End Sub
Private Async Function ExtractCCIPartitions(options As ExtractionOptions) As Task
Dim headerNcchPath As String = Path.Combine(options.DestinationDirectory, options.RootHeaderName)
Await RunProgram(Path_3dstool, $"-xtf 3ds ""{options.SourceRom}"" --header ""{headerNcchPath}"" -0 DecryptedPartition0.bin -1 DecryptedPartition1.bin -2 DecryptedPartition2.bin -6 DecryptedPartition6.bin -7 DecryptedPartition7.bin")
End Function
Private Async Function ExtractCIAPartitions(options As ExtractionOptions) As Task
Dim headerNcchPath As String = Path.Combine(options.DestinationDirectory, options.RootHeaderName)
Await RunProgram(Path_ctrtool, $"--content=Partition ""{options.SourceRom}""")
Dim partitionRegex As New Regex("Partition\.000([0-9])\.[0-9]{8}")
Dim replace As String = "DecryptedPartition$1.bin"
For Each item In Directory.GetFiles(ToolDirectory)
If partitionRegex.IsMatch(item) Then
File.Move(item, partitionRegex.Replace(item, replace))
End If
Next
End Function
Private Async Function ExtractPartition0(options As ExtractionOptions, partitionFilename As String, ctrTool As Boolean) As Task
'Extract partitions
Dim exheaderPath As String = Path.Combine(options.DestinationDirectory, options.ExheaderName)
Dim headerPath As String = Path.Combine(options.DestinationDirectory, options.Partition0HeaderName)
Dim logoPath As String = Path.Combine(options.DestinationDirectory, options.LogoLZName)
Dim plainPath As String = Path.Combine(options.DestinationDirectory, options.PlainRGNName)
Await RunProgram(Path_3dstool, $"-xtf cxi ""{partitionFilename}"" --header ""{headerPath}"" --exh ""{exheaderPath}"" --exefs DecryptedExeFS.bin --romfs DecryptedRomFS.bin --logo ""{logoPath}"" --plain ""{plainPath}""")
'Extract romfs and exefs
Dim romfsDir As String = Path.Combine(options.DestinationDirectory, options.RomFSDirName)
Dim exefsDir As String = Path.Combine(options.DestinationDirectory, options.ExeFSDirName)
Dim exefsHeaderPath As String = Path.Combine(options.DestinationDirectory, options.ExeFSHeaderName)
Dim tasks As New List(Of Task)
'- romfs
If ctrTool Then
Await RunProgram(Path_ctrtool, $"-t romfs --romfsdir ""{romfsDir}"" DecryptedRomFS.bin")
Else
tasks.Add(RunProgram(Path_3dstool, $"-xtf romfs DecryptedRomFS.bin --romfs-dir ""{romfsDir}"""))
End If
'- exefs
Dim exefsExtractionOptions As String
'If options.DecompressCodeBin Then
exefsExtractionOptions = "-xutf"
'Else
' exefsExtractionOptions = "-xtf"
'End If
If ctrTool Then
Await RunProgram(Path_ctrtool, $"-t exefs --exefsdir=""{exefsDir}"" DecryptedExeFS.bin --decompresscode")
Else
tasks.Add(Task.Run(Async Function() As Task
'- exefs
Await RunProgram(Path_3dstool, $"{exefsExtractionOptions} exefs DecryptedExeFS.bin --exefs-dir ""{exefsDir}"" --header ""{exefsHeaderPath}""")
File.Move(Path.Combine(options.DestinationDirectory, options.ExeFSDirName, "banner.bnr"), Path.Combine(options.DestinationDirectory, options.ExeFSDirName, "banner.bin"))
File.Move(Path.Combine(options.DestinationDirectory, options.ExeFSDirName, "icon.icn"), Path.Combine(options.DestinationDirectory, options.ExeFSDirName, "icon.bin"))
'- banner
Await RunProgram(Path_3dstool, $"-x -t banner -f ""{Path.Combine(options.DestinationDirectory, options.ExeFSDirName, "banner.bin")}"" --banner-dir ""{Path.Combine(options.DestinationDirectory, "ExtractedBanner")}""")
File.Move(Path.Combine(options.DestinationDirectory, "ExtractedBanner", "banner0.bcmdl"), Path.Combine(options.DestinationDirectory, "ExtractedBanner", "banner.cgfx"))
End Function))
End If
'Cleanup while we're waiting
File.Delete(Path.Combine(ToolDirectory, "DecryptedPartition0.bin"))
'Wait for all extractions
Await Task.WhenAll(tasks)
'Cleanup the rest
'File.Delete(Path.Combine(ToolDirectory, "DecryptedRomFS.bin"))
'File.Delete(Path.Combine(ToolDirectory, "DecryptedExeFS.bin"))
End Function
Private Async Function ExtractPartition1(options As ExtractionOptions) As Task
If File.Exists(Path.Combine(ToolDirectory, "DecryptedPartition1.bin")) Then
'Extract
Dim headerPath As String = Path.Combine(options.DestinationDirectory, options.Partition1HeaderName)
Dim extractedPath As String = Path.Combine(options.DestinationDirectory, options.ExtractedManualDirName)
Await RunProgram(Path_3dstool, $"-xtf cfa DecryptedPartition1.bin --header ""{headerPath}"" --romfs DecryptedManual.bin")
Await RunProgram(Path_3dstool, $"-xtf romfs DecryptedManual.bin --romfs-dir ""{extractedPath}""")
'Cleanup
File.Delete(Path.Combine(ToolDirectory, "DecryptedPartition1.bin"))
File.Delete(Path.Combine(ToolDirectory, "DecryptedManual.bin"))
End If
End Function
Private Async Function ExtractPartition2(options As ExtractionOptions) As Task
If File.Exists(Path.Combine(ToolDirectory, "DecryptedPartition2.bin")) Then
'Extract
Dim headerPath As String = Path.Combine(options.DestinationDirectory, options.Partition2HeaderName)
Dim extractedPath As String = Path.Combine(options.DestinationDirectory, options.ExtractedDownloadPlayDirName)
Await RunProgram(Path_3dstool, $"-xtf cfa DecryptedPartition2.bin --header ""{headerPath}"" --romfs DecryptedDownloadPlay.bin")
Await RunProgram(Path_3dstool, $"-xtf romfs DecryptedDownloadPlay.bin --romfs-dir ""{extractedPath}""")
'Cleanup
File.Delete(Path.Combine(ToolDirectory, "DecryptedPartition2.bin"))
File.Delete(Path.Combine(ToolDirectory, "DecryptedDownloadPlay.bin"))
End If
End Function
Private Async Function ExtractPartition6(options As ExtractionOptions) As Task
If File.Exists(Path.Combine(ToolDirectory, "DecryptedPartition6.bin")) Then
'Extract
Dim headerPath As String = Path.Combine(options.DestinationDirectory, options.Partition6HeaderName)
Dim extractedPath As String = Path.Combine(options.DestinationDirectory, options.N3DSUpdateDirName)
Await RunProgram(Path_3dstool, $"-xtf cfa DecryptedPartition6.bin --header ""{headerPath}"" --romfs DecryptedN3DSUpdate.bin")
Await RunProgram(Path_3dstool, $"-xtf romfs DecryptedN3DSUpdate.bin --romfs-dir ""{extractedPath}""")
'Cleanup
File.Delete(Path.Combine(ToolDirectory, "DecryptedPartition6.bin"))
File.Delete(Path.Combine(ToolDirectory, "DecryptedN3DSUpdate.bin"))
End If
End Function
Private Async Function ExtractPartition7(options As ExtractionOptions) As Task
If File.Exists(Path.Combine(ToolDirectory, "DecryptedPartition7.bin")) Then
'Extract
Dim headerPath As String = Path.Combine(options.DestinationDirectory, options.Partition7HeaderName)
Dim extractedPath As String = Path.Combine(options.DestinationDirectory, options.O3DSUpdateDirName)
Await RunProgram(Path_3dstool, $"-xtf cfa DecryptedPartition7.bin --header ""{headerPath}"" --romfs DecryptedO3DSUpdate.bin")
Await RunProgram(Path_3dstool, $"-xtf romfs DecryptedO3DSUpdate.bin --romfs-dir ""{extractedPath}""")
'Cleanup
File.Delete(Path.Combine(ToolDirectory, "DecryptedPartition7.bin"))
File.Delete(Path.Combine(ToolDirectory, "DecryptedO3DSUpdate.bin"))
End If
End Function
#End Region
#Region "Building Parts"
Private Sub UpdateExheader(options As BuildOptions, isCia As Boolean)
Using f As New FileStream(Path.Combine(options.SourceDirectory, options.ExheaderName), FileMode.Open, FileAccess.ReadWrite)
f.Seek(&HD, SeekOrigin.Begin)
Dim sciD = f.ReadByte
If options.CompressCodeBin Then
sciD = sciD Or 1 'We want to set bit 1 to 1 to force using a compressed code.bin
Else
sciD = sciD And &HFE 'We want to set bit 1 to 0 to avoid using a compressed code.bin
End If
If isCia Then
sciD = sciD Or 2 'Set bit 2 to 1
Else
sciD = sciD And &HFD 'Set bit 2 to 0
End If
f.Seek(&HD, IO.SeekOrigin.Begin)
f.WriteByte(sciD)
f.Flush()
End Using
End Sub
Private Async Function BuildRomFS(options As BuildOptions) As Task
Dim romfsDir = Path.Combine(options.SourceDirectory, options.RomFSDirName)
Await BuildRomFS(romfsDir, "CustomRomFS.bin")
End Function
Public Async Function BuildRomFS(sourceDirectory As String, outputFile As String) As Task
Await RunProgram(Path_3dstool, $"-ctf romfs ""{outputFile}"" --romfs-dir ""{sourceDirectory}""")
End Function
Private Async Function BuildExeFS(options As BuildOptions) As Task
Dim bannerBin = Path.Combine(options.SourceDirectory, options.ExeFSDirName, "banner.bin")
Dim bannerBnr = Path.Combine(options.SourceDirectory, options.ExeFSDirName, "banner.bnr")
Dim iconBin = Path.Combine(options.SourceDirectory, options.ExeFSDirName, "icon.bin")
Dim iconIco = Path.Combine(options.SourceDirectory, options.ExeFSDirName, "icon.icn")
'Rename banner
If File.Exists(bannerBin) AndAlso Not File.Exists(bannerBnr) Then
File.Move(bannerBin, bannerBnr)
ElseIf File.Exists(bannerBin) AndAlso File.Exists(bannerBnr) Then
File.Delete(bannerBnr)
File.Move(bannerBin, bannerBnr)
ElseIf Not File.Exists(bannerBin) AndAlso File.Exists(bannerBnr) Then
'Do nothing
Else 'Both files don't exist
Throw New MissingFileException(bannerBin)
End If
'Rename icon
If File.Exists(iconBin) AndAlso Not File.Exists(iconIco) Then
File.Move(iconBin, iconIco)
ElseIf File.Exists(iconBin) AndAlso File.Exists(iconIco) Then
File.Delete(iconIco)
File.Move(iconBin, iconIco)
ElseIf Not File.Exists(iconBin) AndAlso File.Exists(iconIco) Then
'Do nothing
Else 'Both files don't exist
Throw New MissingFileException(iconBin)
End If
'Compress code.bin if applicable
If options.CompressCodeBin Then
Throw New NotImplementedException
'"3dstool -zvf code-patched.bin --compress-type blz --compress-out exefs/code.bin"
End If
Dim headerPath As String = Path.Combine(options.SourceDirectory, options.ExeFSHeaderName)
Dim exefsPath As String = Path.Combine(options.SourceDirectory, options.ExeFSDirName)
Await RunProgram(Path_3dstool, $"-ctf exefs CustomExeFS.bin --exefs-dir ""{exefsPath}"" --header ""{headerPath}""")
'Rename files back
File.Move(bannerBnr, bannerBin)
File.Move(iconIco, iconBin)
End Function
Private Async Function BuildPartition0(options As BuildOptions) As Task
'Build romfs and exefs
Dim romfsTask = BuildRomFS(options)
Dim exefsTask = BuildExeFS(options)
Await romfsTask
Await exefsTask
'Build cxi
Dim exheaderPath As String = Path.Combine(options.SourceDirectory, options.ExheaderName)
Dim headerPath As String = Path.Combine(options.SourceDirectory, options.Partition0HeaderName)
Dim logoPath As String = Path.Combine(options.SourceDirectory, options.LogoLZName)
Dim plainPath As String = Path.Combine(options.SourceDirectory, options.PlainRGNName)
Await RunProgram(Path_3dstool, $"-ctf cxi CustomPartition0.bin --header ""{headerPath}"" --exh ""{exheaderPath}"" --exefs CustomExeFS.bin --romfs CustomRomFS.bin --logo ""{logoPath}"" --plain ""{plainPath}""")
'Cleanup
File.Delete(Path.Combine(ToolDirectory, "CustomExeFS.bin"))
File.Delete(Path.Combine(ToolDirectory, "CustomRomFS.bin"))
End Function
Private Async Function BuildPartition1(options As BuildOptions) As Task
Dim headerPath As String = Path.Combine(options.SourceDirectory, options.Partition1HeaderName)
Dim extractedPath As String = Path.Combine(options.SourceDirectory, options.ExtractedManualDirName)
Await RunProgram(Path_3dstool, $"-ctf romfs CustomManual.bin --romfs-dir ""{extractedPath}""")
Await RunProgram(Path_3dstool, $"-ctf cfa CustomPartition1.bin --header ""{headerPath}"" --romfs CustomManual.bin")
File.Delete(Path.Combine(ToolDirectory, "CustomManual.bin"))
End Function
Private Async Function BuildPartition2(options As BuildOptions) As Task
Dim headerPath As String = Path.Combine(options.SourceDirectory, options.Partition2HeaderName)
Dim extractedPath As String = Path.Combine(options.SourceDirectory, options.ExtractedDownloadPlayDirName)
Await RunProgram(Path_3dstool, $"-ctf romfs CustomDownloadPlay.bin --romfs-dir ""{extractedPath}""")
Await RunProgram(Path_3dstool, $"-ctf cfa CustomPartition2.bin --header ""{headerPath}"" --romfs CustomDownloadPlay.bin")
File.Delete(Path.Combine(ToolDirectory, "CustomDownloadPlay.bin"))
End Function
Private Async Function BuildPartition6(options As BuildOptions) As Task
Dim headerPath As String = Path.Combine(options.SourceDirectory, options.Partition6HeaderName)
Dim extractedPath As String = Path.Combine(options.SourceDirectory, options.N3DSUpdateDirName)
Await RunProgram(Path_3dstool, $"-ctf romfs CustomN3DSUpdate.bin --romfs-dir ""{extractedPath}""")
Await RunProgram(Path_3dstool, $"-ctf cfa CustomPartition6.bin --header ""{headerPath}"" --romfs CustomN3DSUpdate.bin")
File.Delete(Path.Combine(ToolDirectory, "CustomN3DSUpdate.bin"))
End Function
Private Async Function BuildPartition7(options As BuildOptions) As Task
Dim headerPath As String = Path.Combine(options.SourceDirectory, options.Partition7HeaderName)
Dim extractedPath As String = Path.Combine(options.SourceDirectory, options.O3DSUpdateDirName)
Await RunProgram(Path_3dstool, $"-ctf romfs CustomO3DSUpdate.bin --romfs-dir ""{extractedPath}""")
Await RunProgram(Path_3dstool, $"-ctf cfa CustomPartition7.bin --header ""{headerPath}"" --romfs CustomO3DSUpdate.bin")
File.Delete(Path.Combine(ToolDirectory, "CustomO3DSUpdate.bin"))
End Function
Private Async Function BuildPartitions(options As BuildOptions) As Task
Copy3DSTool()
Dim partitionTasks As New List(Of Task)
partitionTasks.Add(BuildPartition0(options))
partitionTasks.Add(BuildPartition1(options))
partitionTasks.Add(BuildPartition2(options))
partitionTasks.Add(BuildPartition6(options))
partitionTasks.Add(BuildPartition7(options))
Await Task.WhenAll(partitionTasks)
If Not File.Exists(Path.Combine(ToolDirectory, "CustomPartition0.bin")) Then
Throw New MissingFileException(Path.Combine(ToolDirectory, "CustomPartition0.bin"))
End If
End Function
#End Region
#Region "Top Level Public Methods"
''' <summary>
''' Extracts a decrypted CCI ROM.
''' </summary>
''' <param name="filename">Full path of the ROM to extract.</param>
''' <param name="outputDirectory">Directory into which to extract the files.</param>
Public Async Function ExtractCCI(filename As String, outputDirectory As String) As Task
EnsureInputIsNotInOutputBeforeDeleting(filename, outputDirectory)
Dim options As New ExtractionOptions
options.SourceRom = filename
options.DestinationDirectory = outputDirectory
Await ExtractCCI(options)
End Function
''' <summary>
''' Extracts a CCI ROM.
''' </summary>
Public Async Function ExtractCCI(options As ExtractionOptions) As Task
EnsureInputIsNotInOutputBeforeDeleting(options.SourceRom, options.DestinationDirectory)
IsIndeterminate = True
IsCompleted = False
Copy3DSTool()
If Not Directory.Exists(options.DestinationDirectory) Then
Directory.CreateDirectory(options.DestinationDirectory)
End If
Await ExtractCCIPartitions(options)
Dim partitionExtractions As New List(Of Task)
partitionExtractions.Add(ExtractPartition0(options, "DecryptedPartition0.bin", False))
partitionExtractions.Add(ExtractPartition1(options))
partitionExtractions.Add(ExtractPartition2(options))
partitionExtractions.Add(ExtractPartition6(options))
partitionExtractions.Add(ExtractPartition7(options))
Await Task.WhenAll(partitionExtractions)
IsCompleted = True
End Function
''' <summary>
''' Extracts a decrypted CXI ROM.
''' </summary>
''' <param name="filename">Full path of the ROM to extract.</param>
''' <param name="outputDirectory">Directory into which to extract the files.</param>
Public Async Function ExtractCXI(filename As String, outputDirectory As String) As Task
EnsureInputIsNotInOutputBeforeDeleting(filename, outputDirectory)
Dim options As New ExtractionOptions
options.SourceRom = filename
options.DestinationDirectory = outputDirectory
Await ExtractCXI(options)
End Function
''' <summary>
''' Extracts a CXI partition.
''' </summary>
Public Async Function ExtractCXI(options As ExtractionOptions) As Task
EnsureInputIsNotInOutputBeforeDeleting(options.SourceRom, options.DestinationDirectory)
IsIndeterminate = True
IsCompleted = False
Copy3DSTool()
CopyCtrTool()
If Not Directory.Exists(options.DestinationDirectory) Then
Directory.CreateDirectory(options.DestinationDirectory)
End If
'Extract partition 0, which is the only partition we have
Await ExtractPartition0(options, options.SourceRom, True)
IsCompleted = True
End Function
''' <summary>
''' Extracts a decrypted CIA.
''' </summary>
''' <param name="filename">Full path of the ROM to extract.</param>
''' <param name="outputDirectory">Directory into which to extract the files.</param>
Public Async Function ExtractCIA(filename As String, outputDirectory As String) As Task
EnsureInputIsNotInOutputBeforeDeleting(filename, outputDirectory)
Dim options As New ExtractionOptions
options.SourceRom = filename
options.DestinationDirectory = outputDirectory
Await ExtractCIA(options)
End Function
''' <summary>
''' Extracts a CIA.
''' </summary>
Public Async Function ExtractCIA(options As ExtractionOptions) As Task
EnsureInputIsNotInOutputBeforeDeleting(options.SourceRom, options.DestinationDirectory)
IsIndeterminate = True
IsCompleted = False
Copy3DSTool()
CopyCtrTool()
If Not Directory.Exists(options.DestinationDirectory) Then
Directory.CreateDirectory(options.DestinationDirectory)
End If
Await ExtractCIAPartitions(options)
Dim partitionExtractions As New List(Of Task)
partitionExtractions.Add(ExtractPartition0(options, "DecryptedPartition0.bin", False))
partitionExtractions.Add(ExtractPartition1(options))
partitionExtractions.Add(ExtractPartition2(options))
partitionExtractions.Add(ExtractPartition6(options))
partitionExtractions.Add(ExtractPartition7(options))
Await Task.WhenAll(partitionExtractions)
IsCompleted = True
End Function
''' <summary>
''' Extracts an NDS ROM.
''' </summary>
''' <param name="filename">Full path of the ROM to extract.</param>
''' <param name="outputDirectory">Directory into which to extract the files.</param>
Public Async Function ExtractNDS(filename As String, outputDirectory As String) As Task
EnsureInputIsNotInOutputBeforeDeleting(filename, outputDirectory)
Progress = 0
IsIndeterminate = False
IsCompleted = False
Dim reportProgress = Sub(sender As Object, e As ProgressReportedEventArgs)
RaiseEvent UnpackProgressed(Me, e)
End Sub
If Not Directory.Exists(outputDirectory) Then
Directory.CreateDirectory(outputDirectory)
End If
Dim r As New NdsRom
Dim p As New PhysicalIOProvider
AddHandler r.ProgressChanged, reportProgress
Await r.OpenFile(filename, p)
Await r.Unpack(outputDirectory, p)
RemoveHandler r.ProgressChanged, reportProgress
IsCompleted = True
End Function
''' <summary>
''' Extracts a decrypted CCI or CXI ROM.
''' </summary>
''' <param name="filename">Full path of the ROM to extract.</param>
''' <param name="outputDirectory">Directory into which to extract the files.</param>
''' <remarks>Extraction type is determined by file extension. Extensions of ".cxi" are extracted as CXI, all others are extracted as CCI. To override this behavior, use a more specific extraction function.</remarks>
''' <exception cref="NotSupportedException">Thrown when the input file is not a supported file.</exception>
Public Async Function ExtractAuto(filename As String, outputDirectory As String) As Task
EnsureInputIsNotInOutputBeforeDeleting(filename, outputDirectory)
Select Case Await MetadataReader.GetROMSystem(filename)
Case SystemType.NDS
Await ExtractNDS(filename, outputDirectory)
Case SystemType.ThreeDS
Dim e As New ASCIIEncoding
Using file As New GenericFile
file.EnableInMemoryLoad = False
file.IsReadOnly = True
Await file.OpenFile(filename, New PhysicalIOProvider)
If file.Length > 104 AndAlso e.GetString(Await file.ReadAsync(&H100, 4)) = "NCSD" Then
'CCI
Await ExtractCCI(filename, outputDirectory)
ElseIf file.Length > 104 AndAlso e.GetString(Await file.ReadAsync(&H100, 4)) = "NCCH" Then
'CXI
Await ExtractCXI(filename, outputDirectory)
ElseIf file.Length > Await file.ReadInt32Async(0) AndAlso e.GetString(Await file.ReadAsync(&H100 + MetadataReader.GetCIAContentOffset(file), 4)) = "NCCH" Then
'CIA
Await ExtractCIA(filename, outputDirectory)
Else
Throw New NotSupportedException(My.Resources.Language.ErrorInvalidFileFormat)
End If
End Using
Case SystemType.Unknown
Throw New NotSupportedException(My.Resources.Language.ErrorInvalidFileFormat)
End Select
End Function
''' <summary>
''' Builds a decrypted CCI/3DS file, for use with Citra or Decrypt9
''' </summary>
''' <param name="options"></param>
Public Async Function Build3DSDecrypted(options As BuildOptions) As Task
IsIndeterminate = True
IsCompleted = False
UpdateExheader(options, False)
Dim headerPath As String = Path.Combine(options.SourceDirectory, options.RootHeaderName)
Dim outputPath As String = Path.Combine(options.SourceDirectory, options.Destination)
Dim partitionArgs As String = ""
If Not File.Exists(headerPath) Then
Throw New IOException($"NCCH header not found. This can happen if you extracted a CXI and are trying to rebuild a decrypted CCI. Try building as a key-0 encrypted CCI instead. Path of missing header: ""{headerPath}"".")
End If
Await BuildPartitions(options)
'Delete partitions that are too small
For Each item In {0, 1, 2, 6, 7}
Dim info As New FileInfo(Path.Combine(ToolDirectory, "CustomPartition" & item.ToString & ".bin"))
If info.Length <= 20000 Then
File.Delete(info.FullName)
Else
If info.Exists Then
Dim num = item.ToString
partitionArgs &= $" -{num} CustomPartition{num}.bin"
End If
End If
Next
Await RunProgram(Path_3dstool, $"-ctf 3ds ""{outputPath}"" --header ""{headerPath}""{partitionArgs}")
'Cleanup
For Each item In {0, 1, 2, 6, 7}
Dim partition = Path.Combine(ToolDirectory, "CustomPartition" & item.ToString & ".bin")
If File.Exists(partition) Then
File.Delete(partition)
End If
Next
IsCompleted = True
End Function
''' <summary>
''' Builds a decrypted CCI from the given files.
''' </summary>
''' <param name="sourceDirectory">Path of the files to build. Must have been created with <see cref="ExtractAuto(String, String)"/> or equivalent function using default settings.</param>
''' <param name="outputROM">Destination of the output ROM.</param>
Public Async Function Build3DSDecrypted(sourceDirectory As String, outputROM As String) As Task
Dim options As New BuildOptions
options.SourceDirectory = sourceDirectory
options.Destination = outputROM
Await Build3DSDecrypted(options)
End Function
''' <summary>
''' Builds a CCI/3DS file encrypted with a 0-key, for use with Gateway. Excludes update partitions, download play, and manual.
''' </summary>
''' <param name="options"></param>
Public Async Function Build3DS0Key(options As BuildOptions) As Task
IsIndeterminate = True
IsCompleted = False
Copy3DSBuilder()
UpdateExheader(options, False)
Dim exHeader As String = Path.Combine(options.SourceDirectory, options.ExheaderName)
Dim exeFS As String = Path.Combine(options.SourceDirectory, options.ExeFSDirName)
Dim romFS As String = Path.Combine(options.SourceDirectory, options.RomFSDirName)
If options.CompressCodeBin Then
Await RunProgram(Path_3dsbuilder, $"""{exeFS}"" ""{romFS}"" ""{exHeader}"" ""{options.Destination}""-compressCode")
Console.WriteLine("WARNING: .code.bin is still compressed, and other operations may be affected.")
Else
Await RunProgram(Path_3dsbuilder, $"""{exeFS}"" ""{romFS}"" ""{exHeader}"" ""{options.Destination}""")
Dim dotCodeBin = Path.Combine(options.SourceDirectory, options.ExeFSDirName, ".code.bin")
Dim codeBin = Path.Combine(options.SourceDirectory, options.ExeFSDirName, "code.bin")
If File.Exists(dotCodeBin) Then
File.Move(dotCodeBin, codeBin)
End If
End If
IsCompleted = True
End Function
''' <summary>
''' Builds a 0-key encrypted CCI from the given files.
''' </summary>
''' <param name="sourceDirectory">Path of the files to build. Must have been created with <see cref="ExtractAuto(String, String)"/> or equivalent function using default settings.</param>
''' <param name="outputROM">Destination of the output ROM.</param>
Public Async Function Build3DS0Key(sourceDirectory As String, outputROM As String) As Task
Dim options As New BuildOptions
options.SourceDirectory = sourceDirectory
options.Destination = outputROM
Await Build3DS0Key(options)
End Function
''' <summary>
''' Builds a CCI/3DS file encrypted with a 0-key, for use with Gateway. Excludes update partitions, download play, and manual.
''' </summary>
''' <param name="options"></param>
Public Async Function BuildCia(options As BuildOptions) As Task
IsIndeterminate = True
IsCompleted = False
UpdateExheader(options, True)
CopyMakeRom()
Await BuildPartitions(options)
Dim partitionArgs As String = ""
'Delete partitions that are too small
For Each item In {0, 1, 2, 6, 7}
Dim info As New FileInfo(Path.Combine(ToolDirectory, "CustomPartition" & item.ToString & ".bin"))
If info.Length <= 20000 Then
File.Delete(info.FullName)
Else
Dim num = item.ToString
partitionArgs &= $" -content CustomPartition{num}.bin:{num}"
End If
Next
Dim headerPath As String = Path.Combine(options.SourceDirectory, options.RootHeaderName)
Dim outputPath As String = Path.Combine(options.SourceDirectory, options.Destination)
Await RunProgram(Path_makerom, $"-f cia -o ""{outputPath}""{partitionArgs}")
'Cleanup
For Each item In {0, 1, 2, 6, 7}
Dim partition = Path.Combine(ToolDirectory, "CustomPartition" & item.ToString & ".bin")
If File.Exists(partition) Then
File.Delete(partition)
End If
Next
IsCompleted = True
End Function
''' <summary>
''' Builds a CIA from the given files.
''' </summary>
''' <param name="sourceDirectory">Path of the files to build. Must have been created with <see cref="ExtractAuto(String, String)"/> or equivalent function using default settings.</param>
''' <param name="outputROM">Destination of the output ROM.</param>
Public Async Function BuildCia(sourceDirectory As String, outputROM As String) As Task
Dim options As New BuildOptions
options.SourceDirectory = sourceDirectory
options.Destination = outputROM
Await BuildCia(options)
End Function
''' <summary>
''' Builds an NDS ROM from the given files.
''' </summary>
''' <param name="sourceDirectory">Path of the files to build. Must have been created with <see cref="ExtractAuto(String, String)"/> or equivalent function using default settings.</param>
''' <param name="outputROM">Destination of the output ROM.</param>
Public Async Function BuildNDS(sourceDirectory As String, outputROM As String) As Task
IsIndeterminate = True
IsCompleted = False
CopyNDSTool()
Await RunProgram(Path_ndstool, String.Format("-c ""{0}"" -9 ""{1}/arm9.bin"" -7 ""{1}/arm7.bin"" -y9 ""{1}/y9.bin"" -y7 ""{1}/y7.bin"" -d ""{1}/data"" -y ""{1}/overlay"" -t ""{1}/banner.bin"" -h ""{1}/header.bin""", outputROM, sourceDirectory))
IsCompleted = True
End Function
''' <summary>
''' Builds files for use with HANS.
''' </summary>
''' <param name="options">Options to use for the build. <see cref="BuildOptions.Destination"/> should be the SD card root.</param>
''' <param name="shortcutName">Name of the shortcut. Should not contain spaces nor special characters.</param>
''' <param name="rawName">Raw name for the destination RomFS and Code files. Should be short, but the exact requirements are unknown.</param>
Public Async Function BuildHans(options As BuildOptions, shortcutName As String, rawName As String) As Task
IsIndeterminate = True
IsCompleted = False
'Validate input. Never trust the user.
shortcutName = shortcutName.Replace(" ", "").Replace("é", "e")
Copy3DSTool()
'Create variables
Dim romfsDir = Path.Combine(options.SourceDirectory, options.RomFSDirName)
Dim romfsFile = Path.Combine(ToolDirectory, "romfsRepacked.bin")
Dim codeFile = Path.Combine(options.SourceDirectory, options.ExeFSDirName, "code.bin")
Dim smdhSourceFile = Path.Combine(options.SourceDirectory, options.ExeFSDirName, "icon.bin")
Dim exheaderFile = Path.Combine(options.SourceDirectory, options.ExheaderName)
Dim titleID As String
If File.Exists(exheaderFile) Then
Dim exheader = File.ReadAllBytes(exheaderFile)
titleID = BitConverter.ToUInt64(exheader, &H200).ToString("X").PadLeft(16, "0"c)
Else
Throw New IOException($"Could not find exheader at the path ""{exheaderFile}"".")
End If
'Repack romfs
Await BuildRomFS(romfsDir, romfsFile)
'Copy the files
'- Create non-existant directories
If Not Directory.Exists(options.Destination) Then
Directory.CreateDirectory(options.Destination)
End If
If Not Directory.Exists(Path.Combine(options.Destination, "hans")) Then
Directory.CreateDirectory(Path.Combine(options.Destination, "hans"))
End If
'- Copy files if they exist
If File.Exists(romfsFile) Then
File.Copy(romfsFile, IO.Path.Combine(options.Destination, "hans", rawName & ".romfs"), True)
End If
If File.Exists(codeFile) Then
File.Copy(codeFile, IO.Path.Combine(options.Destination, "hans", rawName & ".code"), True)
End If
'Create the homebrew launcher shortcut
If Not Directory.Exists(IO.Path.Combine(options.Destination, "3ds")) Then
Directory.CreateDirectory(IO.Path.Combine(options.Destination, "3ds"))
End If
'- Copy smdh
Dim iconExists As Boolean = False
If File.Exists(smdhSourceFile) Then
iconExists = True
File.Copy(smdhSourceFile, IO.Path.Combine(options.Destination, "3ds", shortcutName & ".smdh"), True)
End If
'- Write hans shortcut
Dim shortcut As New Text.StringBuilder
shortcut.AppendLine("<shortcut>")
shortcut.AppendLine(" <executable>/3ds/hans/hans.3dsx</executable>")
If iconExists Then
shortcut.AppendLine($" <icon>/3ds/{shortcutName}.smdh</icon>")
End If
shortcut.AppendLine($" <arg>-f/3ds/hans/titles/{rawName}.txt</arg>")
shortcut.AppendLine("</shortcut>")
shortcut.AppendLine("<targets selectable=""false"">")
shortcut.AppendLine($" <title mediatype=""2"">{titleID}</title>")
shortcut.AppendLine($" <title mediatype=""1"">{titleID}</title>")
shortcut.AppendLine("</targets>")
File.WriteAllText(Path.Combine(options.Destination, "3ds", shortcutName & ".xml"), shortcut.ToString)
'- Write hans title settings
Dim preset As New Text.StringBuilder
preset.Append("region : -1")
preset.Append(vbLf)
preset.Append("language : -1")
preset.Append(vbLf)
preset.Append("clock : 0")
preset.Append(vbLf)
preset.Append("romfs : 0")
preset.Append(vbLf)
preset.Append("code : 0")
preset.Append(vbLf)
preset.Append("nim_checkupdate : 1")
preset.Append(vbLf)
If Not Directory.Exists(Path.Combine(options.Destination, "3ds", "hans", "titles")) Then
Directory.CreateDirectory(Path.Combine(options.Destination, "3ds", "hans", "titles"))
End If
File.WriteAllText(Path.Combine(options.Destination, "3ds", "hans", "titles", rawName & ".txt"), preset.ToString)
IsCompleted = True
End Function
''' <summary>
''' Builds files for use with HANS.
''' </summary>
''' <param name="sourceDirectory">Path of the files to build. Must have been created with <see cref="ExtractAuto(String, String)"/> or equivalent function using default settings.</param>
''' <param name="sdRoot">Root of the SD card</param>
''' <param name="rawName">Raw name for the destination RomFS, Code, and shortcut files. Should be short, but the exact requirements are unknown. To use a different name for shortcut files, use <see cref="BuildHans(BuildOptions, String, String)"/>.</param>
Public Async Function BuildHans(sourceDirectory As String, sdRoot As String, rawName As String) As Task
Dim options As New BuildOptions
options.SourceDirectory = sourceDirectory
options.Destination = sdRoot
Await BuildHans(options, rawName, rawName)
End Function
''' <summary>
''' Builds a ROM from the given files.
''' </summary>
''' <param name="sourceDirectory">Path of the files to build. Must have been created with <see cref="ExtractAuto(String, String)"/> or equivalent function using default settings.</param>
''' <param name="outputROM">Destination of the output ROM.</param>
''' <remarks>Output format is determined by file extension. Extensions of ".cia" build a CIA, extensions of ".3dz" build a 0-key encrypted CCI, and all others build a decrypted CCI. To force a different behavior, use a more specific Build function.</remarks>
Public Async Function BuildAuto(sourceDirectory As String, outputROM As String) As Task
Dim ext = Path.GetExtension(outputROM).ToLower
Select Case ext
Case ".cia"
Await BuildCia(sourceDirectory, outputROM)
Case ".3dz"
Await Build3DS0Key(sourceDirectory, outputROM)
Case ".nds", ".srl"
Await BuildNDS(sourceDirectory, outputROM)
Case Else
Await Build3DSDecrypted(sourceDirectory, outputROM)
End Select
End Function
#End Region
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
DeleteTools()
End If
' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
' TODO: set large fields to null.
End If
disposedValue = True
End Sub
' TODO: override Finalize() only if Dispose(disposing As Boolean) above has code to free unmanaged resources.
'Protected Overrides Sub Finalize()
' ' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
' Dispose(False)
' MyBase.Finalize()
'End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
Dispose(True)
' TODO: uncomment the following line if Finalize() is overridden above.
' GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
|
evandixon/DotNet3dsToolkit
|
Old/DotNet3dsToolkit/Converter.vb
|
Visual Basic
|
mit
| 47,158
|
#Region "Microsoft.VisualBasic::5260ff208b4f75f214af371098230f81, Rscript\Library\mzkit\assembly\Assembly.vb"
' Author:
'
' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.)
'
' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD.
'
'
' MIT License
'
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
' /********************************************************************************/
' Summaries:
' Module Assembly
'
' Function: GetFileType, getMs1Scans, ionMode, IonPeaks, LoadIndex
' MatrixDataFrame, (+2 Overloads) mzMLMs1, mzXML2Mgf, (+2 Overloads) mzXMLMs1, openXmlSeeks
' PeakMs2FileIndex, printPeak, rawScans, ReadMgfIons, ReadMslIons
' ScanIds, Seek, summaryIons, writeMgfIons
'
' Sub: Main
'
' /********************************************************************************/
#End Region
Imports System.IO
Imports System.Runtime.CompilerServices
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.ASCII
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.ASCII.MGF
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.ASCII.MSL
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.DataReader
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.MarkupData
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.MarkupData.mzML
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.mzData.mzWebCache
Imports BioNovoGene.Analytical.MassSpectrometry.Math
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Ms1
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Spectra
Imports Microsoft.VisualBasic.CommandLine.Reflection
Imports Microsoft.VisualBasic.ComponentModel.Collection
Imports Microsoft.VisualBasic.Language
Imports Microsoft.VisualBasic.Linq
Imports Microsoft.VisualBasic.Scripting.MetaData
Imports Microsoft.VisualBasic.Text
Imports Microsoft.VisualBasic.ValueTypes
Imports SMRUCC.Rsharp.Runtime
Imports SMRUCC.Rsharp.Runtime.Components
Imports SMRUCC.Rsharp.Runtime.Internal.Object
Imports SMRUCC.Rsharp.Runtime.Interop
Imports mzXMLAssembly = BioNovoGene.Analytical.MassSpectrometry.Assembly.MarkupData.mzXML
Imports REnv = SMRUCC.Rsharp.Runtime
Imports Rlist = SMRUCC.Rsharp.Runtime.Internal.Object.list
''' <summary>
''' The mass spectrum assembly file read/write library module.
''' </summary>
<Package("assembly", Category:=APICategories.UtilityTools)>
Module Assembly
<RInitialize>
Sub Main()
Call Internal.Object.Converts.makeDataframe.addHandler(GetType(Ions()), AddressOf summaryIons)
Call Internal.Object.Converts.makeDataframe.addHandler(GetType(PeakMs2), AddressOf MatrixDataFrame)
Call Internal.ConsolePrinter.AttachConsoleFormatter(Of PeakMs2)(AddressOf printPeak)
End Sub
Private Function MatrixDataFrame(peak As PeakMs2, args As Rlist, env As Environment) As dataframe
Dim dataframe As New dataframe With {.columns = New Dictionary(Of String, Array)}
dataframe.columns("mz") = peak.mzInto.Select(Function(x) x.mz).ToArray
dataframe.columns("into") = peak.mzInto.Select(Function(x) x.intensity).ToArray
Return dataframe
End Function
Private Function printPeak(peak As PeakMs2) As String
Dim xcms_id As String = $"M{CInt(peak.mz)}T{CInt(peak.rt) + 1}"
Dim top6 As Double() = peak.mzInto _
.OrderByDescending(Function(m) m.intensity) _
.Take(6) _
.Select(Function(m) m.mz) _
.ToArray
Dim top6Str As String = top6 _
.Select(Function(d) d.ToString("F4")) _
.JoinBy(vbTab)
Return $"[{xcms_id}] {peak.activation}-{peak.collisionEnergy}eV,{vbTab}{peak.fragments} fragments: {top6Str}..."
End Function
''' <summary>
''' summary of the mgf ions
''' </summary>
''' <param name="x"></param>
''' <param name="args"></param>
''' <param name="env"></param>
''' <returns></returns>
Private Function summaryIons(x As Ions(), args As Rlist, env As Environment) As dataframe
Dim title As MetaData() = x.Select(Function(a) New MetaData(a.Meta)).ToArray
Dim rt As Array = x.Select(Function(a) CInt(a.RtInSeconds)).ToArray
Dim mz As Array = x.Select(Function(a) Val(a.PepMass.name).ToString("F3")).ToArray
Dim into As Array = x.Select(Function(a) Val(a.PepMass.text).ToString("G2")).ToArray
Dim charge As Array = x.Select(Function(a) a.Charge).ToArray
Dim accession As Array = x.Select(Function(a) a.Accession).ToArray
Dim raw As Array = x.Select(Function(a) a.Rawfile).ToArray
Dim fragments As Array = x.Select(Function(a) a.Peaks.Length).ToArray
Dim da3 = Tolerance.DeltaMass(0.3)
Dim topN As Integer = args.getValue(Of Integer)("top.n", env, 3)
Dim metaFields As Index(Of String) = args.getValue(Of String())("meta", env, {})
Dim topNProduct As Array = x _
.Select(Function(a)
Return a.Peaks _
.Centroid(da3, LowAbundanceTrimming.Default) _
.OrderByDescending(Function(p) p.intensity) _
.Take(topN) _
.Select(Function(p)
Return p.mz.ToString("F3")
End Function) _
.JoinBy(", ")
End Function) _
.ToArray
Dim df As New dataframe With {
.columns = New Dictionary(Of String, Array) From {
{NameOf(mz), mz},
{NameOf(rt), rt},
{NameOf(into), into},
{NameOf(charge), charge},
{NameOf(raw), raw},
{"product(m/z)", topNProduct}
}
}
If "accession" Like metaFields Then
df.columns.Add(NameOf(accession), accession)
End If
If "fragments" Like metaFields Then
df.columns.Add(NameOf(fragments), fragments)
End If
df.columns.Add(NameOf(MetaData.activation), title.Select(Function(a) a.activation).ToArray)
df.columns.Add(NameOf(MetaData.collisionEnergy), title.Select(Function(a) a.collisionEnergy).ToArray)
df.columns.Add(NameOf(MetaData.kegg), title.Select(Function(a) a.kegg).ToArray)
df.columns.Add(NameOf(MetaData.precursor_type), title.Select(Function(a) a.precursor_type).ToArray)
If "compound_class" Like metaFields Then
df.columns.Add(NameOf(MetaData.compound_class), title.Select(Function(a) a.compound_class).ToArray)
End If
If "formula" Like metaFields Then
df.columns.Add(NameOf(MetaData.formula), title.Select(Function(a) a.formula).ToArray)
End If
If "mass" Like metaFields Then
df.columns.Add(NameOf(MetaData.mass), title.Select(Function(a) a.mass).ToArray)
End If
If "name" Like metaFields Then
df.columns.Add(NameOf(MetaData.name), title.Select(Function(a) a.name).ToArray)
End If
If "polarity" Like metaFields Then
df.columns.Add(NameOf(MetaData.polarity), title.Select(Function(a) a.polarity).ToArray)
End If
Return df
End Function
''' <summary>
''' read MSL data files
''' </summary>
''' <param name="file$"></param>
''' <param name="unit"></param>
''' <returns></returns>
<ExportAPI("read.msl")>
Public Function ReadMslIons(file$, Optional unit As TimeScales = TimeScales.Second) As MSLIon()
Return MSL.FileReader.Load(file, unit).ToArray
End Function
<ExportAPI("read.mgf")>
Public Function ReadMgfIons(file As String) As Ions()
Return MgfReader.StreamParser(path:=file).ToArray
End Function
''' <summary>
''' this function ensure that the output result of the any input ion objects is peakms2 data type.
''' </summary>
''' <param name="ions">a vector of mgf <see cref="Ions"/> from the ``read.mgf`` function or other data source.</param>
''' <param name="env"></param>
''' <returns></returns>
<ExportAPI("mgf.ion_peaks")>
<RApiReturn(GetType(PeakMs2))>
Public Function IonPeaks(<RRawVectorArgument> ions As Object, Optional env As Environment = Nothing) As Object
Dim pipeline As pipeline = pipeline.TryCreatePipeline(Of Ions)(ions, env)
If pipeline.isError Then
Return pipeline.getError
End If
Return pipeline.populates(Of Ions)(env) _
.IonPeaks _
.DoCall(AddressOf pipeline.CreateFromPopulator)
End Function
<ExportAPI("open.xml_seek")>
Public Function openXmlSeeks(file As String, Optional env As Environment = Nothing) As Object
If Not file.FileExists Then
Return Internal.debug.stop({
$"the given file '{file}' is not found on your file system!",
$"file: {file}"
}, env)
Else
Return New XmlSeek(file).LoadIndex
End If
End Function
<ExportAPI("seek")>
Public Function Seek(file As XmlSeek, key As String) As MSScan
Return file.ReadScan(key)
End Function
<ExportAPI("scan_id")>
Public Function ScanIds(file As XmlSeek) As String()
Return file.IndexKeys
End Function
<ExportAPI("load_index")>
Public Function LoadIndex(file As String) As FastSeekIndex
Return FastSeekIndex.LoadIndex(file)
End Function
''' <summary>
''' write spectra data in mgf file format.
''' </summary>
''' <param name="ions"></param>
''' <param name="file">the file path of the mgf file to write spectra data.</param>
''' <param name="relativeInto">
''' write relative intensity value into the mgf file instead of the raw intensity value.
''' no recommended...
''' </param>
''' <returns></returns>
<ExportAPI("write.mgf")>
<RApiReturn(GetType(Boolean))>
Public Function writeMgfIons(<RRawVectorArgument> ions As Object, file$, Optional relativeInto As Boolean = False, Optional env As Environment = Nothing) As Object
If ions Is Nothing Then
Return Internal.debug.stop("the required ions data can not be nothing!", env)
End If
If ions.GetType() Is GetType(pipeline) Then
Using mgfWriter As StreamWriter = file.OpenWriter(Encodings.ASCII, append:=False)
Dim pipeStream As pipeline = DirectCast(ions, pipeline)
If Not pipeStream.elementType Is Nothing AndAlso pipeStream.elementType Like GetType(Ions) Then
For Each ion As Ions In pipeStream.populates(Of Ions)(env)
Call ion.WriteAsciiMgf(mgfWriter, relativeInto)
Next
Else
For Each ionPeak As PeakMs2 In pipeStream.populates(Of PeakMs2)(env)
Call ionPeak _
.MgfIon _
.WriteAsciiMgf(mgfWriter, relativeInto)
Next
End If
End Using
ElseIf ions.GetType Is GetType(LibraryMatrix) Then
Using mgf As StreamWriter = file.OpenWriter
Call DirectCast(ions, LibraryMatrix) _
.MgfIon _
.WriteAsciiMgf(mgf)
End Using
ElseIf ions.GetType Is GetType(PeakMs2()) Then
Using mgfWriter As StreamWriter = file.OpenWriter(Encodings.ASCII, append:=False)
For Each ionPeak As PeakMs2 In DirectCast(ions, PeakMs2())
Call ionPeak _
.MgfIon _
.WriteAsciiMgf(mgfWriter, relativeInto)
Next
End Using
ElseIf ions.GetType Is GetType(Ions()) Then
Using mgfWriter As StreamWriter = file.OpenWriter(Encodings.ASCII, append:=False)
For Each ion As Ions In DirectCast(ions, Ions())
Call ion.WriteAsciiMgf(mgfWriter, relativeInto)
Next
End Using
ElseIf TypeOf ions Is Ions Then
Using mgfWriter As StreamWriter = file.OpenWriter(Encodings.ASCII, append:=False)
Call DirectCast(ions, Ions).WriteAsciiMgf(mgfWriter, relativeInto)
End Using
ElseIf ions.GetType Is GetType(PeakMs2) Then
Using mgfWriter As StreamWriter = file.OpenWriter(Encodings.ASCII, append:=False)
Call DirectCast(ions, PeakMs2) _
.MgfIon _
.WriteAsciiMgf(mgfWriter, relativeInto)
End Using
Else
Return Internal.debug.stop(Message.InCompatibleType(GetType(PeakMs2), ions.GetType, env), env)
End If
Return True
End Function
''' <summary>
''' is mzxml or mzml?
''' </summary>
''' <param name="path"></param>
''' <returns></returns>
Public Function GetFileType(path As String) As Type
Using xml As StreamReader = path.OpenReader
Dim header As String
For i As Integer = 0 To 1
header = xml.ReadLine
If InStr(header, "<indexedmzML ") > 0 Then
Return GetType(indexedmzML)
ElseIf InStr(header, "<mzXML ") > 0 Then
Return GetType(mzXMLAssembly.XML)
End If
Next
Return Nothing
End Using
End Function
''' <summary>
''' get file index string of the given ms2 peak data.
''' </summary>
''' <param name="ms2"></param>
''' <returns></returns>
<ExportAPI("file.index")>
Public Function PeakMs2FileIndex(ms2 As PeakMs2) As String
Return $"{ms2.file}#{ms2.scan}"
End Function
''' <summary>
''' Convert mzxml file as mgf ions.
''' </summary>
''' <param name="file"></param>
''' <returns></returns>
<ExportAPI("mzxml.mgf")>
<RApiReturn(GetType(PeakMs2))>
Public Function mzXML2Mgf(file$,
Optional relativeInto As Boolean = False,
Optional onlyMs2 As Boolean = True,
Optional env As Environment = Nothing) As pipeline
Dim raw As IEnumerable(Of PeakMs2)
Dim type As Type = GetFileType(file)
If type Is Nothing Then
Return Internal.debug.stop({"the given file is not exists or file format not supported!", "file: " & file}, env)
ElseIf type Is GetType(indexedmzML) Then
raw = file.mzMLScanLoader(relativeInto, onlyMs2)
Else
raw = file.mzXMLScanLoader(relativeInto, onlyMs2)
End If
Return raw _
.Where(Function(peak) peak.mzInto.Length > 0) _
.DoCall(Function(scans)
Return New pipeline(scans, GetType(PeakMs2))
End Function)
End Function
''' <summary>
''' get raw scans data from the ``mzXML`` or ``mzMl`` data file
''' </summary>
''' <param name="file"></param>
''' <param name="env"></param>
''' <returns></returns>
<ExportAPI("raw.scans")>
<RApiReturn(GetType(spectrum), GetType(mzXML.scan))>
Public Function rawScans(file As String, Optional env As Environment = Nothing) As Object
Dim type As Type = GetFileType(file)
If type Is Nothing Then
Return Internal.debug.stop({"the given file is not exists or file format not supported!", "file: " & file}, env)
ElseIf type Is GetType(indexedmzML) Then
Return indexedmzML.LoadScans(file).DoCall(AddressOf pipeline.CreateFromPopulator)
Else
Return mzXMLAssembly.XML.LoadScans(file).DoCall(AddressOf pipeline.CreateFromPopulator)
End If
End Function
''' <summary>
''' get polarity data for each ms2 scans
''' </summary>
''' <param name="scans"></param>
''' <param name="env"></param>
''' <returns></returns>
<ExportAPI("polarity")>
<RApiReturn(GetType(Integer))>
Public Function ionMode(scans As Object, Optional env As Environment = Nothing) As Object
Dim polar As New List(Of Integer)
If TypeOf scans Is BioNovoGene.Analytical.MassSpectrometry.Assembly.mzPack Then
Dim ms = DirectCast(scans, BioNovoGene.Analytical.MassSpectrometry.Assembly.mzPack).MS
For Each Ms1 As ScanMS1 In ms
For Each ms2 In Ms1.products
polar.Add(ms2.polarity)
Next
Next
ElseIf TypeOf scans Is pipeline Then
Dim scanPip As pipeline = DirectCast(scans, pipeline)
If scanPip.elementType Like GetType(mzXMLAssembly.scan) Then
Dim reader As mzXMLScan = MsDataReader(Of mzXMLAssembly.scan).ScanProvider()
For Each scanVal As mzXMLAssembly.scan In scanPip.populates(Of mzXMLAssembly.scan)(env).Where(Function(s) reader.GetMsLevel(s) = 2)
Call polar.Add(PrecursorType.ParseIonMode(reader.GetPolarity(scanVal)))
Next
ElseIf scanPip.elementType Like GetType(spectrum) Then
Dim reader As mzMLScan = MsDataReader(Of spectrum).ScanProvider()
For Each scanVal As spectrum In scanPip.populates(Of spectrum)(env).Where(Function(s) reader.GetMsLevel(s) = 2)
Call polar.Add(PrecursorType.ParseIonMode(reader.GetPolarity(scanVal)))
Next
Else
Return Message.InCompatibleType(GetType(mzXMLAssembly.scan), scanPip.elementType, env)
End If
Else
Return Message.InCompatibleType(GetType(BioNovoGene.Analytical.MassSpectrometry.Assembly.mzPack), scans.GetType, env)
End If
Return polar.ToArray
End Function
''' <summary>
''' get all ms1 raw scans from the raw files
''' </summary>
''' <param name="raw">
''' the file path of the raw data files.
''' </param>
''' <param name="centroid">
''' the tolerance value of m/z for convert to centroid mode
''' </param>
''' <returns></returns>
<ExportAPI("ms1.scans")>
<RApiReturn(GetType(ms1_scan))>
Public Function getMs1Scans(<RRawVectorArgument>
raw As Object,
Optional centroid As Object = Nothing,
Optional env As Environment = Nothing) As Object
Dim ms1 As New List(Of ms1_scan)
Dim tolerance As Tolerance = Nothing
If Not centroid Is Nothing Then
With getTolerance(centroid, env)
If .GetUnderlyingType Is GetType(Message) Then
Return .TryCast(Of Message)
Else
tolerance = .TryCast(Of Tolerance)
End If
End With
End If
If TypeOf raw Is BioNovoGene.Analytical.MassSpectrometry.Assembly.mzPack Then
ms1.AddRange(DirectCast(raw, BioNovoGene.Analytical.MassSpectrometry.Assembly.mzPack).GetAllScanMs1(tolerance))
ElseIf TypeOf raw Is vector OrElse TypeOf raw Is String() Then
Dim files As String() = REnv.asVector(Of String)(raw)
For Each file As String In files
Select Case file.ExtensionSuffix.ToLower
Case "mzxml"
ms1 += mzXMLMs1(file, tolerance)
Case "mzml"
ms1 += mzMLMs1(file, tolerance)
Case Else
Throw New NotImplementedException
End Select
Next
ElseIf TypeOf raw Is pipeline Then
Dim scanPip As pipeline = DirectCast(raw, pipeline)
If scanPip.elementType Like GetType(mzXMLAssembly.scan) Then
Call scanPip.populates(Of mzXMLAssembly.scan)(env) _
.mzXMLMs1(tolerance) _
.IteratesALL _
.DoCall(AddressOf ms1.AddRange)
ElseIf scanPip.elementType Like GetType(spectrum) Then
Call scanPip.populates(Of spectrum)(env) _
.mzMLMs1(tolerance) _
.IteratesALL _
.DoCall(AddressOf ms1.AddRange)
Else
Return Message.InCompatibleType(GetType(mzXMLAssembly.scan), scanPip.elementType, env)
End If
Else
Return Message.InCompatibleType(GetType(BioNovoGene.Analytical.MassSpectrometry.Assembly.mzPack), raw.GetType, env)
End If
Return ms1.ToArray
End Function
Private Function mzXMLMs1(file As String, centroid As Tolerance) As IEnumerable(Of ms1_scan)
Return mzXMLMs1(mzXML.XML _
.LoadScans(file) _
.Where(Function(s)
Return s.msLevel = 1
End Function), centroid).IteratesALL
End Function
<Extension>
Private Iterator Function mzXMLMs1(scans As IEnumerable(Of mzXML.scan), centroid As Tolerance) As IEnumerable(Of ms1_scan())
Dim reader As New mzXMLScan
Dim peakScans As ms2()
Dim rt_sec As Double
For Each scan As mzXML.scan In From item In scans Where Not reader.IsEmpty(item)
' ms1的数据总是使用raw intensity值
peakScans = reader.GetMsMs(scan)
rt_sec = reader.GetScanTime(scan)
If Not centroid Is Nothing Then
peakScans = peakScans.Centroid(centroid, LowAbundanceTrimming.intoCutff).ToArray
End If
Yield peakScans _
.Select(Function(frag)
Return New ms1_scan With {
.intensity = frag.intensity,
.mz = frag.mz,
.scan_time = rt_sec
}
End Function) _
.ToArray
Next
End Function
Private Function mzMLMs1(file As String, centroid As Tolerance) As IEnumerable(Of ms1_scan)
Dim reader As New mzMLScan
Return mzMLMs1(indexedmzML _
.LoadScans(file) _
.Where(Function(s)
Return reader.GetMsLevel(s) = 1
End Function), centroid).IteratesALL
End Function
<Extension>
Private Iterator Function mzMLMs1(scans As IEnumerable(Of spectrum), centroid As Tolerance) As IEnumerable(Of ms1_scan())
Dim reader As New mzMLScan
Dim peakScans As ms2()
Dim rt_sec As Double
For Each scan As spectrum In From item In scans Where Not reader.IsEmpty(item)
peakScans = reader.GetMsMs(scan)
rt_sec = reader.GetScanTime(scan)
If Not centroid Is Nothing Then
peakScans = peakScans.Centroid(centroid, LowAbundanceTrimming.intoCutff).ToArray
End If
Yield peakScans _
.Select(Function(frag)
Return New ms1_scan With {
.intensity = frag.intensity,
.mz = frag.mz,
.scan_time = rt_sec
}
End Function) _
.ToArray
Next
End Function
End Module
|
xieguigang/MassSpectrum-toolkits
|
Rscript/Library/mzkit/assembly/Assembly.vb
|
Visual Basic
|
mit
| 24,557
|
Imports System.IO
Imports System.Runtime.InteropServices
Module Example
<STAThread()> _
Sub Main()
Dim objApplication As SolidEdgeFramework.Application
Dim objPartDocument As SolidEdgePart.PartDocument
Dim objConstructions As SolidEdgePart.Constructions
Dim objConstructionModel As SolidEdgePart.ConstructionModel
Try
OleMessageFilter.Register()
objApplication = Marshal.GetActiveObject("SolidEdge.Application")
objPartDocument = objApplication.ActiveDocument
objConstructions = objPartDocument.Constructions
objConstructionModel = objConstructions.Item(1)
objConstructionModel.HealAndOptimizeBody(True, True)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
OleMessageFilter.Revoke()
End Try
End Sub
End Module
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgePart.ConstructionModel.HealAndOptimizeBody.vb
|
Visual Basic
|
mit
| 902
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("Connect Kickstart")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("Connect.Kickstart")>
<Assembly: AssemblyCopyright("Copyright © 2014")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("6a6b24fa-e5a9-4f86-a6e6-7a5a68b9ec1c")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("01.00.02")>
<Assembly: AssemblyFileVersion("01.00.02")>
|
DNN-Connect/kickstart
|
My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,152
|
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.FindSymbols
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library
Imports Microsoft.VisualStudio.Shell.Interop
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.VsNavInfo
Public Class VsNavInfoTests
#Region "C# Tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestCSharp_TestNamespace() As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly">
<Document>
namespace $$N { }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("CSharpTestAssembly"),
[Namespace]("N")
},
presentationNodes:={
Package("CSharpTestAssembly"),
[Namespace]("N")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestCSharp_TestClass() As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly">
<Document>
namespace N
{
class $$C { }
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("CSharpTestAssembly"),
[Namespace]("N"),
[Class]("C")
},
presentationNodes:={
Package("CSharpTestAssembly"),
[Namespace]("N"),
[Class]("C")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestCSharp_TestMethod() As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly">
<Document>
namespace N
{
class C
{
void $$M() { }
}
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("CSharpTestAssembly"),
[Namespace]("N"),
[Class]("C"),
Member("M()")
},
presentationNodes:={
Package("CSharpTestAssembly"),
[Namespace]("N"),
[Class]("C"),
Member("M()")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestCSharp_TestMethod_Parameters() As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly">
<Document>
namespace N
{
class C
{
int $$M(int x, int y)
{
return x + y;
}
}
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("CSharpTestAssembly"),
[Namespace]("N"),
[Class]("C"),
Member("M(int, int)")
},
presentationNodes:={
Package("CSharpTestAssembly"),
[Namespace]("N"),
[Class]("C"),
Member("M(int, int)")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestCSharp_TestMetadata_Class1() As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly">
<Document>
using System;
class C
{
String$$ s;
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Class]("String")
},
presentationNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Class]("String")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestCSharp_TestMetadata_Class2() As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly">
<Document>
using System.Text;
class C
{
StringBuilder$$ sb;
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Namespace]("Text"),
[Class]("StringBuilder")
},
presentationNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System.Text"),
[Class]("StringBuilder")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestCSharp_TestMetadata_Ctor1() As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly">
<Document>
using System.Text;
class C
{
StringBuilder sb = new StringBuilder$$();
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Namespace]("Text"),
[Class]("StringBuilder"),
Member("StringBuilder()")
},
presentationNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System.Text"),
[Class]("StringBuilder"),
Member("StringBuilder()")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestCSharp_TestMetadata_Ctor2() As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly">
<Document>
using System;
class C
{
String s = new String$$(' ', 42);
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Class]("String"),
Member("String(char, int)")
},
presentationNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Class]("String"),
Member("String(char, int)")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestCSharp_TestMetadata_Method() As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly">
<Document>
using System;
class C
{
String s = new String(' ', 42).Replace$$(' ', '\r');
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Class]("String"),
Member("Replace(char, char)")
},
presentationNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Class]("String"),
Member("Replace(char, char)")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestCSharp_TestMetadata_GenericType() As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly">
<Document>
using System.Collections.Generic;
class C
{
$$List<int> s;
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Namespace]("Collections"),
[Namespace]("Generic"),
[Class]("List<T>")
},
presentationNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System.Collections.Generic"),
[Class]("List<T>")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestCSharp_TestMetadata_GenericMethod() As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly">
<Document>
using System;
class C
{
void M()
{
var a = new int[] { 1, 2, 3, 4, 5 };
var r = Array.AsReadOnly$$(a);
}
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Class]("Array"),
Member("AsReadOnly<T>(T[])")
},
presentationNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Class]("Array"),
Member("AsReadOnly<T>(T[])")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestCSharp_TestNull_Parameter() As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly">
<Document>
class C
{
void M(int i$$) { }
}
</Document>
</Project>
</Workspace>
Await TestIsNullAsync(workspace)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestCSharp_TestNull_Local() As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly">
<Document>
class C
{
void M()
{
int i$$;
}
}
</Document>
</Project>
</Workspace>
Await TestIsNullAsync(workspace)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestCSharp_TestNull_Label() As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly">
<Document>
class C
{
void M()
{
label$$:
int i;
}
}
</Document>
</Project>
</Workspace>
Await TestIsNullAsync(workspace)
End Function
#End Region
#Region "Visual Basic Tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestVisualBasic_TestNamespace() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly">
<Document>
Namespace $$N
End Namespace
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("VBTestAssembly"),
[Namespace]("N")
},
presentationNodes:={
Package("VBTestAssembly"),
[Namespace]("N")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestVisualBasic_TestClass() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly">
<Document>
Namespace N
Class $$C
End Class
End Namespace
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("VBTestAssembly"),
[Namespace]("N"),
[Class]("C")
},
presentationNodes:={
Package("VBTestAssembly"),
[Namespace]("N"),
[Class]("C")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestVisualBasic_TestMember_Sub() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly">
<Document>
Namespace N
Class C
Sub $$M()
End Sub
End Class
End Namespace
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("VBTestAssembly"),
[Namespace]("N"),
[Class]("C"),
Member("M()")
},
presentationNodes:={
Package("VBTestAssembly"),
[Namespace]("N"),
[Class]("C"),
Member("M()")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestVisualBasic_TestMember_Function() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly">
<Document>
Namespace N
Class C
Function $$M() As Integer
End Function
End Class
End Namespace
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("VBTestAssembly"),
[Namespace]("N"),
[Class]("C"),
Member("M() As Integer")
},
presentationNodes:={
Package("VBTestAssembly"),
[Namespace]("N"),
[Class]("C"),
Member("M() As Integer")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestVisualBasic_TestMember_Parameters() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly">
<Document>
Namespace N
Class C
Function $$M(x As Integer, y As Integer) As Integer
End Function
End Class
End Namespace
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("VBTestAssembly"),
[Namespace]("N"),
[Class]("C"),
Member("M(Integer, Integer) As Integer")
},
presentationNodes:={
Package("VBTestAssembly"),
[Namespace]("N"),
[Class]("C"),
Member("M(Integer, Integer) As Integer")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestVisualBasic_TestMetadata_Class1() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly">
<Document>
Imports System
Class C
Dim s As String$$
End Class
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Class]("String")
},
presentationNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Class]("String")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestVisualBasic_TestMetadata_Class2() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly">
<Document>
Imports System.Text
Class C
Dim s As StringBuilder$$
End Class
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Namespace]("Text"),
[Class]("StringBuilder")
},
presentationNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System.Text"),
[Class]("StringBuilder")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestVisualBasic_TestMetadata_Ctor1() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly">
<Document>
Imports System.Text
Class C
Dim s As New StringBuilder$$()
End Class
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Namespace]("Text"),
[Class]("StringBuilder"),
Member("New()")
},
presentationNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System.Text"),
[Class]("StringBuilder"),
Member("New()")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestVisualBasic_TestMetadata_Ctor2() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly">
<Document>
Imports System
Class C
Dim s As String = New String$$(" "c, 42)
End Class
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Class]("String"),
Member("New(Char, Integer)")
},
presentationNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Class]("String"),
Member("New(Char, Integer)")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestVisualBasic_TestMetadata_Method() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly">
<Document>
Imports System
Class C
Dim s As String = New String(" "c, 42).Replace$$(" "c, "."c)
End Class
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Class]("String"),
Member("Replace(Char, Char) As String")
},
presentationNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Class]("String"),
Member("Replace(Char, Char) As String")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestVisualBasic_TestMetadata_GenericType() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly">
<Document>
Imports System.Collections.Generic
Class C
Dim s As List$$(Of Integer)
End Class
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Namespace]("Collections"),
[Namespace]("Generic"),
[Class]("List(Of T)")
},
presentationNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System.Collections.Generic"),
[Class]("List(Of T)")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestVisualBasic_TestMetadata_GenericMethod() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VisualBasicTestAssembly">
<Document>
Imports System
Class C
Sub M()
Dim a = New Integer() { 1, 2, 3, 4, 5 }
Dim r = Array.AsReadOnly$$(a)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAsync(workspace,
canonicalNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Class]("Array"),
Member("AsReadOnly(Of T)(T()) As System.Collections.ObjectModel.ReadOnlyCollection(Of T)")
},
presentationNodes:={
Package("Z:\FxReferenceAssembliesUri"),
[Namespace]("System"),
[Class]("Array"),
Member("AsReadOnly(Of T)(T()) As System.Collections.ObjectModel.ReadOnlyCollection(Of T)")
})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestVisualBasic_TestNull_Parameter() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly">
<Document>
Class C
Sub M(i$$ As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestIsNullAsync(workspace)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestVisualBasic_TestNull_Local() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly">
<Document>
Class C
Sub M()
Dim i$$ As Integer
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestIsNullAsync(workspace)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.VsNavInfo)>
Public Async Function TestVisualBasic_TestNull_Label() As Task
Dim workspace =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly">
<Document>
Class C
void M()
{
Sub M()
label$$:
Dim i As Integer
End Sub
}
End Class
</Document>
</Project>
</Workspace>
Await TestIsNullAsync(workspace)
End Function
#End Region
Private Shared Sub IsOK(comAction As Func(Of Integer))
Assert.Equal(VSConstants.S_OK, comAction())
End Sub
Private Delegate Sub NodeVerifier(vsNavInfoNode As IVsNavInfoNode)
Private Shared Function Node(expectedListType As _LIB_LISTTYPE, expectedName As String) As NodeVerifier
Return Sub(vsNavInfoNode)
Dim listType As UInteger
IsOK(Function() vsNavInfoNode.get_Type(listType))
Assert.Equal(CUInt(expectedListType), listType)
Dim actualName As String = Nothing
IsOK(Function() vsNavInfoNode.get_Name(actualName))
Assert.Equal(expectedName, actualName)
End Sub
End Function
Private Shared Function Package(expectedName As String) As NodeVerifier
Return Node(_LIB_LISTTYPE.LLT_PACKAGE, expectedName)
End Function
Private Shared Function [Namespace](expectedName As String) As NodeVerifier
Return Node(_LIB_LISTTYPE.LLT_NAMESPACES, expectedName)
End Function
Private Shared Function [Class](expectedName As String) As NodeVerifier
Return Node(_LIB_LISTTYPE.LLT_CLASSES, expectedName)
End Function
Private Shared Function Member(expectedName As String) As NodeVerifier
Return Node(_LIB_LISTTYPE.LLT_MEMBERS, expectedName)
End Function
Private Shared Function Hierarchy(expectedName As String) As NodeVerifier
Return Node(_LIB_LISTTYPE.LLT_HIERARCHY, expectedName)
End Function
Private Shared Sub VerifyNodes(enumerator As IVsEnumNavInfoNodes, verifiers() As NodeVerifier)
Dim index = 0
Dim actualNode = New IVsNavInfoNode(0) {}
Dim fetched As UInteger
While enumerator.Next(1, actualNode, fetched) = VSConstants.S_OK
Dim verifier = verifiers(index)
index += 1
verifier(actualNode(0))
End While
Assert.Equal(index, verifiers.Length)
End Sub
Private Shared Async Function TestAsync(
workspaceDefinition As XElement,
Optional useExpandedHierarchy As Boolean = False,
Optional canonicalNodes As NodeVerifier() = Nothing,
Optional presentationNodes As NodeVerifier() = Nothing
) As Tasks.Task
Using workspace = Await TestWorkspaceFactory.CreateWorkspaceAsync(workspaceDefinition, exportProvider:=VisualStudioTestExportProvider.ExportProvider)
Dim hostDocument = workspace.DocumentWithCursor
Assert.True(hostDocument IsNot Nothing, "Test defined without cursor position")
Dim document = workspace.CurrentSolution.GetDocument(hostDocument.Id)
Dim semanticModel = Await document.GetSemanticModelAsync()
Dim position As Integer = hostDocument.CursorPosition.Value
Dim symbol = SymbolFinder.FindSymbolAtPosition(semanticModel, position, workspace, CancellationToken.None)
Assert.True(symbol IsNot Nothing, $"Could not find symbol as position, {position}")
Dim libraryService = document.Project.LanguageServices.GetService(Of ILibraryService)
Dim project = document.Project
Dim compilation = Await project.GetCompilationAsync()
Dim navInfo = libraryService.NavInfoFactory.CreateForSymbol(symbol, document.Project, compilation, useExpandedHierarchy)
Assert.True(navInfo IsNot Nothing, $"Could not retrieve nav info for {symbol.ToDisplayString()}")
If canonicalNodes IsNot Nothing Then
Dim enumerator As IVsEnumNavInfoNodes = Nothing
IsOK(Function() navInfo.EnumCanonicalNodes(enumerator))
VerifyNodes(enumerator, canonicalNodes)
End If
If presentationNodes IsNot Nothing Then
Dim enumerator As IVsEnumNavInfoNodes = Nothing
IsOK(Function() navInfo.EnumPresentationNodes(CUInt(_LIB_LISTFLAGS.LLF_NONE), enumerator))
VerifyNodes(enumerator, presentationNodes)
End If
End Using
End Function
Private Shared Async Function TestIsNullAsync(
workspaceDefinition As XElement,
Optional useExpandedHierarchy As Boolean = False
) As Tasks.Task
Using workspace = Await TestWorkspaceFactory.CreateWorkspaceAsync(workspaceDefinition, exportProvider:=VisualStudioTestExportProvider.ExportProvider)
Dim hostDocument = workspace.DocumentWithCursor
Assert.True(hostDocument IsNot Nothing, "Test defined without cursor position")
Dim document = workspace.CurrentSolution.GetDocument(hostDocument.Id)
Dim semanticModel = Await document.GetSemanticModelAsync()
Dim position As Integer = hostDocument.CursorPosition.Value
Dim symbol = SymbolFinder.FindSymbolAtPosition(semanticModel, position, workspace, CancellationToken.None)
Assert.True(symbol IsNot Nothing, $"Could not find symbol as position, {position}")
Dim libraryService = document.Project.LanguageServices.GetService(Of ILibraryService)
Dim project = document.Project
Dim compilation = Await project.GetCompilationAsync()
Dim navInfo = libraryService.NavInfoFactory.CreateForSymbol(symbol, document.Project, compilation, useExpandedHierarchy)
Assert.Null(navInfo)
End Using
End Function
End Class
End Namespace
|
mseamari/Stuff
|
src/VisualStudio/Core/Test/VsNavInfo/VsNavInfoTests.vb
|
Visual Basic
|
apache-2.0
| 32,268
|
''' <summary>
''' パスに関するユーティリティクラス
''' </summary>
''' <remarks></remarks>
Public Class Path
''' <summary>
''' インスタンス化不可
''' </summary>
''' <remarks></remarks>
Private Sub New()
End Sub
''' <summary>
''' ディレクトリが存在しなければ作成する
''' </summary>
''' <remarks></remarks>
Public Shared Sub CreateDirectoryIfNone(path As String)
If My.Computer.FileSystem.DirectoryExists(path) = False Then
My.Computer.FileSystem.CreateDirectory(path)
End If
End Sub
''' <summary>
''' プログラムのEXEが格納されているディレクトリ名を返します
''' </summary>
''' <remarks></remarks>
Public Shared Function GetAppPath() As String
Dim exePath = System.Reflection.Assembly.GetExecutingAssembly().Location
Dim file = New IO.FileInfo(exePath)
Return file.DirectoryName
End Function
End Class
|
marqut/CollectBin
|
CollectBin/Util/Path.vb
|
Visual Basic
|
apache-2.0
| 1,002
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.Button1 = New System.Windows.Forms.Button()
Me.Button2 = New System.Windows.Forms.Button()
Me.Button3 = New System.Windows.Forms.Button()
Me.PictureBox1 = New System.Windows.Forms.PictureBox()
Me.Label1 = New System.Windows.Forms.Label()
Me.Label2 = New System.Windows.Forms.Label()
Me.Label3 = New System.Windows.Forms.Label()
Me.shotNumSelector = New System.Windows.Forms.NumericUpDown()
CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.shotNumSelector, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(12, 12)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(297, 40)
Me.Button1.TabIndex = 0
Me.Button1.Text = "Shoot"
Me.Button1.UseVisualStyleBackColor = True
'
'Button2
'
Me.Button2.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.Button2.Location = New System.Drawing.Point(315, 12)
Me.Button2.Name = "Button2"
Me.Button2.Size = New System.Drawing.Size(297, 40)
Me.Button2.TabIndex = 1
Me.Button2.Text = "Set Save Path"
Me.Button2.UseVisualStyleBackColor = True
'
'Button3
'
Me.Button3.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.Button3.Location = New System.Drawing.Point(618, 12)
Me.Button3.Name = "Button3"
Me.Button3.Size = New System.Drawing.Size(297, 40)
Me.Button3.TabIndex = 2
Me.Button3.Text = "Area"
Me.Button3.UseVisualStyleBackColor = True
'
'PictureBox1
'
Me.PictureBox1.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.PictureBox1.Location = New System.Drawing.Point(4, 105)
Me.PictureBox1.Name = "PictureBox1"
Me.PictureBox1.Size = New System.Drawing.Size(920, 391)
Me.PictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
Me.PictureBox1.TabIndex = 3
Me.PictureBox1.TabStop = False
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(12, 55)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(60, 13)
Me.Label1.TabIndex = 4
Me.Label1.Text = "Save Path:"
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.Location = New System.Drawing.Point(12, 68)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(61, 13)
Me.Label2.TabIndex = 5
Me.Label2.Text = " File Prefix:"
'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.Label3.Location = New System.Drawing.Point(15, 84)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(57, 13)
Me.Label3.TabIndex = 6
Me.Label3.Text = "Next Shot:"
'
'shotNumSelector
'
Me.shotNumSelector.Location = New System.Drawing.Point(78, 82)
Me.shotNumSelector.Name = "shotNumSelector"
Me.shotNumSelector.Size = New System.Drawing.Size(46, 20)
Me.shotNumSelector.TabIndex = 7
Me.shotNumSelector.Value = New Decimal(New Integer() {1, 0, 0, 0})
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(927, 498)
Me.Controls.Add(Me.shotNumSelector)
Me.Controls.Add(Me.Label3)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.PictureBox1)
Me.Controls.Add(Me.Button3)
Me.Controls.Add(Me.Button2)
Me.Controls.Add(Me.Button1)
Me.KeyPreview = True
Me.Name = "Form1"
Me.Text = "Screen Shot"
CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.shotNumSelector, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents Button1 As System.Windows.Forms.Button
Friend WithEvents Button2 As System.Windows.Forms.Button
Friend WithEvents Button3 As System.Windows.Forms.Button
Friend WithEvents PictureBox1 As System.Windows.Forms.PictureBox
Friend WithEvents Label1 As Label
Friend WithEvents Label2 As Label
Friend WithEvents Label3 As Label
Friend WithEvents shotNumSelector As NumericUpDown
End Class
|
Cleverbum/Simple-Screen-Shot-Tool
|
Screen-Shot/Form1.Designer.vb
|
Visual Basic
|
apache-2.0
| 6,077
|
Imports BVSoftware.Bvc5.Core
Partial Class BVModules_Themes_Bvc5_Footer
Inherits System.Web.UI.UserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
lnkHome.Text = Content.SiteTerms.GetTerm("Home")
lnkHome.ToolTip = Content.SiteTerms.GetTerm("Home")
lnkSearch.Text = Content.SiteTerms.GetTerm("Search")
lnkSearch.ToolTip = Content.SiteTerms.GetTerm("Search")
lnkSiteMap.Text = Content.SiteTerms.GetTerm("SiteMap")
lnkSiteMap.ToolTip = Content.SiteTerms.GetTerm("SiteMap")
If TypeOf Me.Page Is BaseStorePage Then
If DirectCast(Me.Page, BaseStorePage).UseTabIndexes Then
lnkHome.TabIndex = 10000
lnkSearch.TabIndex = 10001
lnkSiteMap.TabIndex = 10002
End If
End If
End Sub
End Class
|
ajaydex/Scopelist_2015
|
BVModules/Themes/Bvc5/Footer.ascx.vb
|
Visual Basic
|
apache-2.0
| 885
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module DirectiveSyntaxExtensions
Private Class DirectiveInfo
Private ReadOnly _startEndMap As IDictionary(Of DirectiveTriviaSyntax, DirectiveTriviaSyntax)
''' <summary>
''' Returns a map which maps from a DirectiveTriviaSyntax to it's corresponding start/end directive.
''' Directives like #ElseIf which exist in the middle of a start/end pair are not included.
''' </summary>
Public ReadOnly Property StartEndMap As IDictionary(Of DirectiveTriviaSyntax, DirectiveTriviaSyntax)
Get
Return _startEndMap
End Get
End Property
Private ReadOnly _conditionalMap As IDictionary(Of DirectiveTriviaSyntax, IEnumerable(Of DirectiveTriviaSyntax))
''' <summary>
''' Maps a #If/#ElseIf/#Else/#EndIf directive to its list of matching #If/#ElseIf/#Else/#End directives.
''' </summary>
Public ReadOnly Property ConditionalMap As IDictionary(Of DirectiveTriviaSyntax, IEnumerable(Of DirectiveTriviaSyntax))
Get
Return _conditionalMap
End Get
End Property
' A set of inactive regions spans. The items in the tuple are the
' start and end line *both inclusive* of the inactive region.
' Actual PP lines are not contined within.
'
' Note: an interval syntaxTree might be a better structure here if there are lots of
' inactive regions. Consider switching to that if necessary.
Private ReadOnly _inactiveRegionLines As ISet(Of Tuple(Of Integer, Integer))
Public ReadOnly Property InactiveRegionLines() As ISet(Of Tuple(Of Integer, Integer))
Get
Return _inactiveRegionLines
End Get
End Property
Public Sub New(startEndMap As IDictionary(Of DirectiveTriviaSyntax, DirectiveTriviaSyntax),
conditionalMap As IDictionary(Of DirectiveTriviaSyntax, IEnumerable(Of DirectiveTriviaSyntax)),
inactiveRegionLines As ISet(Of Tuple(Of Integer, Integer)))
_startEndMap = startEndMap
_conditionalMap = conditionalMap
_inactiveRegionLines = inactiveRegionLines
End Sub
End Class
Private ReadOnly s_rootToDirectiveInfo As New ConditionalWeakTable(Of SyntaxNode, DirectiveInfo)()
Private Function GetDirectiveInfo(node As SyntaxNode, cancellationToken As CancellationToken) As DirectiveInfo
Dim root = node.GetAbsoluteRoot()
Dim info = s_rootToDirectiveInfo.GetValue(root,
Function(r)
Dim startEndMap = New Dictionary(Of DirectiveTriviaSyntax, DirectiveTriviaSyntax)(DirectiveSyntaxEqualityComparer.Instance)
Dim conditionalMap = New Dictionary(Of DirectiveTriviaSyntax, IEnumerable(Of DirectiveTriviaSyntax))(DirectiveSyntaxEqualityComparer.Instance)
Dim walker = New DirectiveWalker(startEndMap, conditionalMap, cancellationToken)
walker.Visit(r)
walker.Finish()
Return New DirectiveInfo(startEndMap, conditionalMap, inactiveRegionLines:=Nothing)
End Function)
Return info
End Function
<Extension()>
Private Function GetAbsoluteRoot(node As SyntaxNode) As SyntaxNode
While node IsNot Nothing AndAlso (node.Parent IsNot Nothing OrElse TypeOf node Is StructuredTriviaSyntax)
If node.Parent IsNot Nothing Then
node = node.Parent
Else
node = node.ParentTrivia.Token.Parent
End If
End While
Return node
End Function
<Extension()>
Public Function GetStartDirectives(syntaxTree As SyntaxTree, cancellationToken As CancellationToken) As IEnumerable(Of DirectiveTriviaSyntax)
Return GetDirectiveInfo(syntaxTree.GetRoot(cancellationToken), cancellationToken).StartEndMap.Keys.Where(
Function(d) d.Kind = SyntaxKind.RegionDirectiveTrivia OrElse d.Kind = SyntaxKind.IfDirectiveTrivia)
End Function
''' <summary>
''' Given a starting or ending directive, return the matching directive, if it exists. For directives that live
''' the "middle" of a start/end pair, such as #ElseIf or #Else, this method will throw.
''' </summary>
<Extension()>
Public Function GetMatchingStartOrEndDirective(directive As DirectiveTriviaSyntax,
cancellationToken As CancellationToken) As DirectiveTriviaSyntax
If directive Is Nothing Then
Throw New ArgumentNullException("directive")
End If
If directive.Kind = SyntaxKind.ElseIfDirectiveTrivia OrElse directive.Kind = SyntaxKind.ElseDirectiveTrivia Then
Throw New ArgumentException("directive cannot be a ElseIfDirective or ElseDirective.")
End If
Dim result As DirectiveTriviaSyntax = Nothing
GetDirectiveInfo(directive, cancellationToken).StartEndMap.TryGetValue(directive, result)
Return result
End Function
''' <summary>
''' Given a conditional directive (#If, #ElseIf, #Else, or #End If), returns a IEnumerable of all directives in
''' the set.
''' </summary>
<Extension()>
Public Function GetMatchingConditionalDirectives(directive As DirectiveTriviaSyntax,
cancellationToken As CancellationToken) As IEnumerable(Of DirectiveTriviaSyntax)
If directive Is Nothing Then
Throw New ArgumentNullException("directive")
End If
Dim result As IEnumerable(Of DirectiveTriviaSyntax) = Nothing
If Not GetDirectiveInfo(directive, cancellationToken).ConditionalMap.TryGetValue(directive, result) Then
Return SpecializedCollections.EmptyEnumerable(Of DirectiveTriviaSyntax)()
End If
Return result
End Function
End Module
End Namespace
|
akoeplinger/roslyn
|
src/Workspaces/VisualBasic/Portable/Extensions/DirectiveSyntaxExtensions.vb
|
Visual Basic
|
apache-2.0
| 7,045
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Concurrent
Imports System.Collections.Immutable
Imports System.Reflection.PortableExecutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
Partial Friend MustInherit Class PEModuleBuilder
Inherits PEModuleBuilder(Of VisualBasicCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, VisualBasicSyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState)
' Not many methods should end up here.
Private ReadOnly _disableJITOptimization As ConcurrentDictionary(Of MethodSymbol, Boolean) = New ConcurrentDictionary(Of MethodSymbol, Boolean)(ReferenceEqualityComparer.Instance)
' Gives the name of this module (may not reflect the name of the underlying symbol).
' See Assembly.MetadataName.
Private ReadOnly _metadataName As String
Private _lazyExportedTypes As ImmutableArray(Of TypeExport(Of NamedTypeSymbol))
Private _lazyImports As ImmutableArray(Of Cci.UsedNamespaceOrType)
Private _lazyDefaultNamespace As String
' These fields will only be set when running tests. They allow realized IL for a given method to be looked up by method display name.
Private _testData As ConcurrentDictionary(Of String, CompilationTestData.MethodData)
Private _testDataKeyFormat As SymbolDisplayFormat
Private _testDataOperatorKeyFormat As SymbolDisplayFormat
Friend Sub New(sourceModule As SourceModuleSymbol,
emitOptions As EmitOptions,
outputKind As OutputKind,
serializationProperties As ModulePropertiesForSerialization,
manifestResources As IEnumerable(Of ResourceDescription),
assemblySymbolMapper As Func(Of AssemblySymbol, AssemblyIdentity))
MyBase.New(sourceModule.ContainingSourceAssembly.DeclaringCompilation,
sourceModule,
serializationProperties,
manifestResources,
outputKind,
assemblySymbolMapper,
emitOptions,
New ModuleCompilationState())
Dim specifiedName = sourceModule.MetadataName
_metadataName = If(specifiedName <> Microsoft.CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName,
specifiedName,
If(emitOptions.OutputNameOverride, specifiedName))
m_AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, Me)
If sourceModule.AnyReferencedAssembliesAreLinked Then
_embeddedTypesManagerOpt = New NoPia.EmbeddedTypesManager(Me)
End If
End Sub
''' <summary>
''' True if conditional calls may be omitted when the required preprocessor symbols are not defined.
''' </summary>
''' <remarks>
''' Only false in debugger scenarios (where calls should never be omitted).
''' </remarks>
Friend MustOverride ReadOnly Property AllowOmissionOfConditionalCalls As Boolean
Friend Overrides ReadOnly Property Name As String
Get
Return _metadataName
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property ModuleName As String
Get
Return _metadataName
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property CorLibrary As AssemblySymbol
Get
Return SourceModule.ContainingSourceAssembly.CorLibrary
End Get
End Property
Protected Overrides ReadOnly Property GenerateVisualBasicStylePdb As Boolean
Get
Return True
End Get
End Property
Protected Overrides ReadOnly Property LinkedAssembliesDebugInfo As IEnumerable(Of String)
Get
' NOTE: Dev12 does not seem to emit anything but the name (i.e. no version, token, etc).
' See Builder::WriteNoPiaPdbList
Return SourceModule.ReferencedAssemblySymbols.Where(Function(a) a.IsLinked).Select(Function(a) a.Name)
End Get
End Property
Protected NotOverridable Overrides Function GetImports(context As EmitContext) As ImmutableArray(Of Cci.UsedNamespaceOrType)
If _lazyImports.IsDefault Then
ImmutableInterlocked.InterlockedInitialize(
_lazyImports,
NamespaceScopeBuilder.BuildNamespaceScope(context, SourceModule.XmlNamespaces, SourceModule.AliasImports, SourceModule.MemberImports))
End If
Return _lazyImports
End Function
Protected NotOverridable Overrides ReadOnly Property DefaultNamespace As String
Get
If _lazyDefaultNamespace IsNot Nothing Then
Return _lazyDefaultNamespace
End If
Dim rootNamespace = SourceModule.RootNamespace
If rootNamespace Is Nothing OrElse rootNamespace.IsGlobalNamespace Then
Return Nothing
End If
_lazyDefaultNamespace = rootNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)
Return _lazyDefaultNamespace
End Get
End Property
Protected Overrides Iterator Function GetAssemblyReferencesFromAddedModules(diagnostics As DiagnosticBag) As IEnumerable(Of Cci.IAssemblyReference)
Dim modules As ImmutableArray(Of ModuleSymbol) = SourceModule.ContainingAssembly.Modules
For i As Integer = 1 To modules.Length - 1
For Each aRef As AssemblySymbol In modules(i).GetReferencedAssemblySymbols()
Yield Translate(aRef, diagnostics)
Next
Next
End Function
Private Sub ValidateReferencedAssembly(assembly As AssemblySymbol, asmRef As AssemblyReference, diagnostics As DiagnosticBag)
Dim asmIdentity As AssemblyIdentity = SourceModule.ContainingAssembly.Identity
Dim refIdentity As AssemblyIdentity = asmRef.MetadataIdentity
If asmIdentity.IsStrongName AndAlso Not refIdentity.IsStrongName AndAlso
DirectCast(asmRef, Cci.IAssemblyReference).ContentType <> Reflection.AssemblyContentType.WindowsRuntime Then
' Dev12 reported error, we have changed it to a warning to allow referencing libraries
' built for platforms that don't support strong names.
diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton)
End If
If OutputKind <> OutputKind.NetModule AndAlso
Not String.IsNullOrEmpty(refIdentity.CultureName) AndAlso
Not String.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase) Then
diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton)
End If
Dim refMachine = assembly.Machine
' If other assembly is agnostic, this is always safe
' Also, if no mscorlib was specified for back compat we add a reference to mscorlib
' that resolves to the current framework directory. If the compiler Is 64-bit
' this Is a 64-bit mscorlib, which will produce a warning if /platform:x86 Is
' specified.A reference to the default mscorlib should always succeed without
' warning so we ignore it here.
If assembly IsNot assembly.CorLibrary AndAlso
Not (refMachine = Machine.I386 AndAlso Not assembly.Bit32Required) Then
Dim machine = SourceModule.Machine
If Not (machine = machine.I386 AndAlso Not SourceModule.Bit32Required) AndAlso
machine <> refMachine Then
' Different machine types, and neither is agnostic
diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton)
End If
End If
If _embeddedTypesManagerOpt IsNot Nothing AndAlso _embeddedTypesManagerOpt.IsFrozen Then
_embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics)
End If
End Sub
Friend NotOverridable Overrides Function SynthesizeAttribute(attributeConstructor As WellKnownMember) As Cci.ICustomAttribute
Return Me.Compilation.TrySynthesizeAttribute(attributeConstructor)
End Function
Friend NotOverridable Overrides Function GetSourceAssemblyAttributes() As IEnumerable(Of Cci.ICustomAttribute)
Return SourceModule.ContainingSourceAssembly.GetCustomAttributesToEmit(Me.CompilationState, emittingAssemblyAttributesInNetModule:=OutputKind.IsNetModule())
End Function
Friend NotOverridable Overrides Function GetSourceAssemblySecurityAttributes() As IEnumerable(Of Cci.SecurityAttribute)
Return SourceModule.ContainingSourceAssembly.GetSecurityAttributes()
End Function
Friend NotOverridable Overrides Function GetSourceModuleAttributes() As IEnumerable(Of Cci.ICustomAttribute)
Return SourceModule.GetCustomAttributesToEmit(Me.CompilationState)
End Function
Protected Overrides Function GetSymbolToLocationMap() As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation)
Dim result As New MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation)()
Dim namespacesAndTypesToProcess As New Stack(Of NamespaceOrTypeSymbol)()
namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace)
Dim location As Location = Nothing
While namespacesAndTypesToProcess.Count > 0
Dim symbol As NamespaceOrTypeSymbol = namespacesAndTypesToProcess.Pop()
Select Case symbol.Kind
Case SymbolKind.Namespace
location = GetSmallestSourceLocationOrNull(symbol)
' filtering out synthesized symbols not having real source
' locations such as anonymous types, my types, etc...
If location IsNot Nothing Then
For Each member In symbol.GetMembers()
Select Case member.Kind
Case SymbolKind.Namespace, SymbolKind.NamedType
namespacesAndTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol))
Case Else
Throw ExceptionUtilities.UnexpectedValue(member.Kind)
End Select
Next
End If
Case SymbolKind.NamedType
location = GetSmallestSourceLocationOrNull(symbol)
If location IsNot Nothing Then
' add this named type location
AddSymbolLocation(result, location, DirectCast(symbol, Cci.IDefinition))
For Each member In symbol.GetMembers()
Select Case member.Kind
Case SymbolKind.NamedType
namespacesAndTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol))
Case SymbolKind.Method
Dim method = DirectCast(member, MethodSymbol)
If Not method.IsDefaultValueTypeConstructor() Then
AddSymbolLocation(result, member)
End If
Case SymbolKind.Property,
SymbolKind.Field
AddSymbolLocation(result, member)
Case SymbolKind.Event
AddSymbolLocation(result, member)
Dim AssociatedField = (DirectCast(member, EventSymbol)).AssociatedField
If AssociatedField IsNot Nothing Then
' event backing fields do not show up in GetMembers
AddSymbolLocation(result, AssociatedField)
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(member.Kind)
End Select
Next
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(symbol.Kind)
End Select
End While
Return result
End Function
Private Sub AddSymbolLocation(result As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation), symbol As Symbol)
Dim location As Location = GetSmallestSourceLocationOrNull(symbol)
If location IsNot Nothing Then
AddSymbolLocation(result, location, DirectCast(symbol, Cci.IDefinition))
End If
End Sub
Private Sub AddSymbolLocation(result As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation), location As Location, definition As Cci.IDefinition)
Dim span As FileLinePositionSpan = location.GetLineSpan()
Dim doc As Cci.DebugSourceDocument = Me.TryGetDebugDocument(span.Path, basePath:=location.SourceTree.FilePath)
If (doc IsNot Nothing) Then
result.Add(doc,
New Cci.DefinitionWithLocation(
definition,
span.StartLinePosition.Line,
span.StartLinePosition.Character,
span.EndLinePosition.Line,
span.EndLinePosition.Character))
End If
End Sub
Private Function GetSmallestSourceLocationOrNull(symbol As Symbol) As Location
Dim compilation As VisualBasicCompilation = symbol.DeclaringCompilation
Debug.Assert(Me.Compilation Is compilation, "How did we get symbol from different compilation?")
Dim result As Location = Nothing
For Each loc In symbol.Locations
If loc.IsInSource AndAlso (result Is Nothing OrElse compilation.CompareSourceLocations(result, loc) > 0) Then
result = loc
End If
Next
Return result
End Function
Friend Overridable Function TryCreateVariableSlotAllocator(method As MethodSymbol) As VariableSlotAllocator
Return Nothing
End Function
Friend Overridable Function GetPreviousAnonymousTypes() As ImmutableArray(Of AnonymousTypeKey)
Return ImmutableArray(Of AnonymousTypeKey).Empty
End Function
Friend Overridable Function GetNextAnonymousTypeIndex(fromDelegates As Boolean) As Integer
Return 0
End Function
Friend Overridable Function TryGetAnonymousTypeName(template As NamedTypeSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean
Debug.Assert(Compilation Is template.DeclaringCompilation)
name = Nothing
index = -1
Return False
End Function
Friend Overrides Function GetAnonymousTypes() As ImmutableArray(Of Cci.INamespaceTypeDefinition)
If EmitOptions.EmitMetadataOnly Then
Return ImmutableArray(Of Cci.INamespaceTypeDefinition).Empty
End If
Return StaticCast(Of Cci.INamespaceTypeDefinition).
From(SourceModule.ContainingSourceAssembly.DeclaringCompilation.AnonymousTypeManager.AllCreatedTemplates)
End Function
Friend Overrides Iterator Function GetTopLevelTypesCore(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition)
For Each topLevel In GetAdditionalTopLevelTypes()
Yield topLevel
Next
Dim embeddedSymbolManager As EmbeddedSymbolManager = SourceModule.ContainingSourceAssembly.DeclaringCompilation.EmbeddedSymbolManager
Dim stack As New Stack(Of NamespaceOrTypeSymbol)()
stack.Push(SourceModule.GlobalNamespace)
Do
Dim sym As NamespaceOrTypeSymbol = stack.Pop()
If sym.Kind = SymbolKind.NamedType Then
Debug.Assert(sym Is sym.OriginalDefinition)
Debug.Assert(sym.ContainingType Is Nothing)
' Skip unreferenced embedded types.
If Not sym.IsEmbedded OrElse embeddedSymbolManager.IsSymbolReferenced(sym) Then
Dim type = DirectCast(sym, NamedTypeSymbol)
Yield type
End If
Else
Debug.Assert(sym.Kind = SymbolKind.Namespace)
Dim members As ImmutableArray(Of Symbol) = sym.GetMembers()
For i As Integer = members.Length - 1 To 0 Step -1
Dim nortsym As NamespaceOrTypeSymbol = TryCast(members(i), NamespaceOrTypeSymbol)
If nortsym IsNot Nothing Then
stack.Push(nortsym)
End If
Next
End If
Loop While stack.Count > 0
End Function
Friend Overridable Function GetAdditionalTopLevelTypes() As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetExportedTypes(context As EmitContext) As IEnumerable(Of Cci.ITypeExport)
Debug.Assert(HaveDeterminedTopLevelTypes)
If _lazyExportedTypes.IsDefault Then
Dim builder = ArrayBuilder(Of TypeExport(Of NamedTypeSymbol)).GetInstance()
Dim sourceAssembly As SourceAssemblySymbol = SourceModule.ContainingSourceAssembly
If Not OutputKind.IsNetModule() Then
Dim modules = sourceAssembly.Modules
For i As Integer = 1 To modules.Length - 1 'NOTE: skipping modules(0)
GetExportedTypes(modules(i).GlobalNamespace, builder)
Next
End If
Dim seenTopLevelForwardedTypes = New HashSet(Of NamedTypeSymbol)()
GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builder)
If Not OutputKind.IsNetModule() Then
GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builder)
End If
Debug.Assert(_lazyExportedTypes.IsDefault)
_lazyExportedTypes = builder.ToImmutableAndFree()
If _lazyExportedTypes.Length > 0 Then
' Report name collisions.
Dim exportedNamesMap = New Dictionary(Of String, NamedTypeSymbol)()
For Each [alias] In _lazyExportedTypes
Dim aliasedType As NamedTypeSymbol = [alias].AliasedType
Debug.Assert(aliasedType.IsDefinition)
If aliasedType.ContainingType Is Nothing Then
Dim fullEmittedName As String = MetadataHelpers.BuildQualifiedName((DirectCast(aliasedType, Cci.INamespaceTypeReference)).NamespaceName,
Cci.MetadataWriter.GetMangledName(aliasedType))
' First check against types declared in the primary module
If ContainsTopLevelType(fullEmittedName) Then
If aliasedType.ContainingAssembly Is sourceAssembly Then
context.Diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_ExportedTypeConflictsWithDeclaration, aliasedType, aliasedType.ContainingModule),
NoLocation.Singleton))
Else
context.Diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_ForwardedTypeConflictsWithDeclaration, aliasedType),
NoLocation.Singleton))
End If
Continue For
End If
Dim contender As NamedTypeSymbol = Nothing
' Now check against other exported types
If exportedNamesMap.TryGetValue(fullEmittedName, contender) Then
If aliasedType.ContainingAssembly Is sourceAssembly Then
' all exported types precede forwarded types, therefore contender cannot be a forwarded type.
Debug.Assert(contender.ContainingAssembly Is sourceAssembly)
context.Diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_ExportedTypesConflict,
aliasedType, aliasedType.ContainingModule,
contender, contender.ContainingModule),
NoLocation.Singleton))
Else
If contender.ContainingAssembly Is sourceAssembly Then
' Forwarded type conflicts with exported type
context.Diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_ForwardedTypeConflictsWithExportedType,
aliasedType, aliasedType.ContainingAssembly,
contender, contender.ContainingModule),
NoLocation.Singleton))
Else
' Forwarded type conflicts with another forwarded type
context.Diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_ForwardedTypesConflict,
aliasedType, aliasedType.ContainingAssembly,
contender, contender.ContainingAssembly),
NoLocation.Singleton))
End If
End If
Continue For
End If
exportedNamesMap.Add(fullEmittedName, aliasedType)
End If
Next
End If
End If
Return _lazyExportedTypes
End Function
Private Overloads Sub GetExportedTypes(sym As NamespaceOrTypeSymbol, builder As ArrayBuilder(Of TypeExport(Of NamedTypeSymbol)))
If sym.Kind = SymbolKind.NamedType Then
If sym.DeclaredAccessibility = Accessibility.Public Then
Debug.Assert(sym.IsDefinition)
builder.Add(New TypeExport(Of NamedTypeSymbol)(DirectCast(sym, NamedTypeSymbol)))
Else
Return
End If
End If
For Each t In sym.GetMembers()
Dim nortsym = TryCast(t, NamespaceOrTypeSymbol)
If nortsym IsNot Nothing Then
GetExportedTypes(nortsym, builder)
End If
Next
End Sub
Private Shared Sub GetForwardedTypes(
seenTopLevelTypes As HashSet(Of NamedTypeSymbol),
wellKnownAttributeData As CommonAssemblyWellKnownAttributeData(Of NamedTypeSymbol),
builder As ArrayBuilder(Of TypeExport(Of NamedTypeSymbol))
)
If wellKnownAttributeData IsNot Nothing AndAlso wellKnownAttributeData.ForwardedTypes IsNot Nothing Then
For Each forwardedType As NamedTypeSymbol In wellKnownAttributeData.ForwardedTypes
Dim originalDefinition As NamedTypeSymbol = forwardedType.OriginalDefinition
Debug.Assert(originalDefinition.ContainingType Is Nothing, "How did a nested type get forwarded?")
' De-dup the original definitions before emitting.
If Not seenTopLevelTypes.Add(originalDefinition) Then
Continue For
End If
' Return all nested types.
' Note the order: depth first, children in reverse order (to match dev10, not a requirement).
Dim stack = New Stack(Of NamedTypeSymbol)()
stack.Push(originalDefinition)
While stack.Count > 0
Dim curr As NamedTypeSymbol = stack.Pop()
' In general, we don't want private types to appear in the ExportedTypes table.
If curr.DeclaredAccessibility = Accessibility.Private Then
' NOTE: this will also exclude nested types of curr.
Continue While
End If
' NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection.
builder.Add(New TypeExport(Of NamedTypeSymbol)(curr))
' Iterate backwards so they get popped in forward order.
Dim nested As ImmutableArray(Of NamedTypeSymbol) = curr.GetTypeMembers() ' Ordered.
For i As Integer = nested.Length - 1 To 0 Step -1
stack.Push(nested(i))
Next
End While
Next
End If
End Sub
Friend NotOverridable Overrides ReadOnly Property LinkerMajorVersion As Byte
Get
'EDMAURER the Windows loader team says that this value is not used in loading but is used by the appcompat infrastructure.
'It is useful for us to have
'a mechanism to identify the compiler that produced the binary. This is the appropriate
'value to use for that. That is what it was invented for. We don't want to have the high
'bit set for this in case some users perform a signed comparision to determine if the value
'is less than some version. The C++ linker is at 0x0B. Roslyn C# will start at &H30. We'll start our numbering at &H50.
Return &H50
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property LinkerMinorVersion As Byte
Get
Return 0
End Get
End Property
Friend Iterator Function GetReferencedAssembliesUsedSoFar() As IEnumerable(Of AssemblySymbol)
For Each assembly In SourceModule.GetReferencedAssemblySymbols()
If Not assembly.IsLinked AndAlso
Not assembly.IsMissing AndAlso
m_AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(assembly) Then
Yield assembly
End If
Next
End Function
Friend NotOverridable Overrides Function GetSystemType(syntaxOpt As VisualBasicSyntaxNode, diagnostics As DiagnosticBag) As Cci.INamedTypeReference
Dim systemTypeSymbol As NamedTypeSymbol = SourceModule.DeclaringCompilation.GetWellKnownType(WellKnownType.System_Type)
Dim useSiteError = Binder.GetUseSiteErrorForWellKnownType(systemTypeSymbol)
If useSiteError IsNot Nothing Then
Binder.ReportDiagnostic(diagnostics,
If(syntaxOpt IsNot Nothing, syntaxOpt.GetLocation(), NoLocation.Singleton),
useSiteError)
End If
Return Translate(systemTypeSymbol, syntaxOpt, diagnostics, needDeclaration:=True)
End Function
Friend NotOverridable Overrides Function GetSpecialType(specialType As SpecialType, syntaxNodeOpt As VisualBasicSyntaxNode, diagnostics As DiagnosticBag) As Cci.INamedTypeReference
Dim typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType)
Dim info = Binder.GetUseSiteErrorForSpecialType(typeSymbol)
If info IsNot Nothing Then
Binder.ReportDiagnostic(diagnostics, If(syntaxNodeOpt IsNot Nothing, syntaxNodeOpt.GetLocation(), NoLocation.Singleton), info)
End If
Return Translate(typeSymbol,
needDeclaration:=True,
syntaxNodeOpt:=syntaxNodeOpt,
diagnostics:=diagnostics)
End Function
Public Overrides Function GetInitArrayHelper() As Cci.IMethodReference
Return DirectCast(Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle), MethodSymbol)
End Function
Protected Overrides Function IsPlatformType(typeRef As Cci.ITypeReference, platformType As Cci.PlatformType) As Boolean
Dim namedType = TryCast(typeRef, NamedTypeSymbol)
If namedType IsNot Nothing Then
If platformType = Cci.PlatformType.SystemType Then
Return namedType Is Compilation.GetWellKnownType(WellKnownType.System_Type)
End If
Return namedType.SpecialType = CType(platformType, SpecialType)
End If
Return False
End Function
Protected Overrides Function GetCorLibraryReferenceToEmit(context As EmitContext) As Cci.IAssemblyReference
Dim corLib = CorLibrary
If Not corLib.IsMissing AndAlso
Not corLib.IsLinked AndAlso
corLib IsNot SourceModule.ContainingAssembly Then
Return Translate(corLib, context.Diagnostics)
End If
Return Nothing
End Function
Friend NotOverridable Overrides Function GetSynthesizedNestedTypes(container As NamedTypeSymbol) As IEnumerable(Of Cci.INestedTypeDefinition)
Return container.GetSynthesizedNestedTypes()
End Function
Public Sub SetDisableJITOptimization(methodSymbol As MethodSymbol)
Debug.Assert(methodSymbol.ContainingModule Is Me.SourceModule AndAlso methodSymbol Is methodSymbol.OriginalDefinition)
_disableJITOptimization.TryAdd(methodSymbol, True)
End Sub
Public Function JITOptimizationIsDisabled(methodSymbol As MethodSymbol) As Boolean
Debug.Assert(methodSymbol.ContainingModule Is Me.SourceModule AndAlso methodSymbol Is methodSymbol.OriginalDefinition)
Return _disableJITOptimization.ContainsKey(methodSymbol)
End Function
#Region "Test Hooks"
Friend ReadOnly Property SaveTestData() As Boolean
Get
Return _testData IsNot Nothing
End Get
End Property
Friend Sub SetMethodTestData(methodSymbol As MethodSymbol, builder As ILBuilder)
If _testData Is Nothing Then
Throw New InvalidOperationException("Must call SetILBuilderMap before calling SetILBuilder")
End If
' If this ever throws "ArgumentException: An item with the same key has already been added.", then
' the ilBuilderMapKeyFormat will need to be updated to provide a unique key (see SetILBuilderMap).
_testData.Add(
methodSymbol.ToDisplayString(If(methodSymbol.IsUserDefinedOperator(), _testDataOperatorKeyFormat, _testDataKeyFormat)),
New CompilationTestData.MethodData(builder, methodSymbol))
End Sub
Friend Sub SetMethodTestData(methods As ConcurrentDictionary(Of String, CompilationTestData.MethodData))
Me._testData = methods
Me._testDataKeyFormat = New SymbolDisplayFormat(
compilerInternalOptions:=SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames Or SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers,
globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining,
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions:=
SymbolDisplayMemberOptions.IncludeParameters Or
SymbolDisplayMemberOptions.IncludeContainingType Or
SymbolDisplayMemberOptions.IncludeExplicitInterface,
parameterOptions:=
SymbolDisplayParameterOptions.IncludeParamsRefOut Or
SymbolDisplayParameterOptions.IncludeExtensionThis Or
SymbolDisplayParameterOptions.IncludeType,
miscellaneousOptions:=
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers Or
SymbolDisplayMiscellaneousOptions.UseSpecialTypes Or
SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays Or
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName)
' most methods don't need return type to disambiguate signatures, however,
' it is necessary to disambiguate user defined operators:
' Operator op_Implicit(Type) As Integer
' Operator op_Implicit(Type) As Single
' ... etc ...
Me._testDataOperatorKeyFormat = New SymbolDisplayFormat(
_testDataKeyFormat.CompilerInternalOptions,
_testDataKeyFormat.GlobalNamespaceStyle,
_testDataKeyFormat.TypeQualificationStyle,
_testDataKeyFormat.GenericsOptions,
_testDataKeyFormat.MemberOptions Or SymbolDisplayMemberOptions.IncludeType,
_testDataKeyFormat.ParameterOptions,
_testDataKeyFormat.DelegateStyle,
_testDataKeyFormat.ExtensionMethodStyle,
_testDataKeyFormat.PropertyStyle,
_testDataKeyFormat.LocalOptions,
_testDataKeyFormat.KindOptions,
_testDataKeyFormat.MiscellaneousOptions)
End Sub
#End Region
End Class
End Namespace
|
wschae/roslyn
|
src/Compilers/VisualBasic/Portable/Emit/PEModuleBuilder.vb
|
Visual Basic
|
apache-2.0
| 36,093
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports InternalSyntaxFactory = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.SyntaxFactory
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Friend Partial Class Parser
' File: Parser.cpp
' Lines: 14199 - 14199
' Initializer* .Parser::ParseSelectListInitializer( [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseSelectListInitializer() As ExpressionRangeVariableSyntax
Dim nameEqualsOpt As VariableNameEqualsSyntax = Nothing
If ((CurrentToken.Kind = SyntaxKind.IdentifierToken OrElse CurrentToken.IsKeyword()) AndAlso
PeekToken(1).Kind = SyntaxKind.EqualsToken OrElse
(PeekToken(1).Kind = SyntaxKind.QuestionToken AndAlso PeekToken(2).Kind = SyntaxKind.EqualsToken)) Then
Dim varName As ModifiedIdentifierSyntax = Nothing
Dim Equals As PunctuationSyntax = Nothing
' // Parse form: <IdentiferOrKeyword> '=' <Expression>
varName = ParseSimpleIdentifierAsModifiedIdentifier()
' NOTE: do not need to resync here. we should land on "="
Debug.Assert(CurrentToken.Kind = SyntaxKind.EqualsToken)
Equals = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken() '// move off the '='
TryEatNewLine() ' // line continuation allowed after '='
nameEqualsOpt = SyntaxFactory.VariableNameEquals(varName, Nothing, Equals)
End If
Dim expr As ExpressionSyntax = ParseExpressionCore()
Return SyntaxFactory.ExpressionRangeVariable(
nameEqualsOpt,
expr)
End Function
' File: Parser.cpp
' Lines: 14290 - 14290
' InitializerList* .Parser::ParseSelectList( [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseSelectList() As SeparatedSyntaxList(Of ExpressionRangeVariableSyntax)
Dim RangeVariables = Me._pool.AllocateSeparated(Of ExpressionRangeVariableSyntax)()
Do
Dim rangeVar = ParseSelectListInitializer()
If rangeVar.ContainsDiagnostics Then
rangeVar = ResyncAt(rangeVar, SyntaxKind.CommaToken, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
SyntaxKind.FromKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword,
SyntaxKind.IntoKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
End If
RangeVariables.Add(rangeVar)
If CurrentToken.Kind = SyntaxKind.CommaToken Then
Dim comma = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken()
TryEatNewLine()
RangeVariables.AddSeparator(comma)
Else
Exit Do
End If
Loop
Dim result = RangeVariables.ToList
Me._pool.Free(RangeVariables)
Return result
End Function
' File: Parser.cpp
' Lines: 14333 - 14333
' Expression* .Parser::ParseAggregationExpression( [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseAggregationExpression() As AggregationSyntax
If CurrentToken.Kind = SyntaxKind.IdentifierToken Then
Dim curIdent = DirectCast(CurrentToken, IdentifierTokenSyntax)
If curIdent.PossibleKeywordKind = SyntaxKind.GroupKeyword Then
Debug.Assert(PeekToken(1).Kind = SyntaxKind.OpenParenToken)
curIdent = ReportSyntaxError(curIdent, ERRID.ERR_InvalidUseOfKeyword)
GetNextToken()
Return SyntaxFactory.FunctionAggregation(curIdent, Nothing, Nothing, Nothing)
End If
End If
Dim aggName = ParseIdentifier()
Dim aggregateFunc As FunctionAggregationSyntax = Nothing
If Not aggName.ContainsDiagnostics AndAlso CurrentToken.Kind = SyntaxKind.OpenParenToken Then
Dim lParen = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken() ' get off lparen
TryEatNewLine()
Dim arg As ExpressionSyntax = Nothing
If CurrentToken.Kind <> SyntaxKind.CloseParenToken Then
arg = ParseExpressionCore()
End If
Dim rParen As PunctuationSyntax = Nothing
If TryEatNewLineAndGetToken(SyntaxKind.CloseParenToken, rParen, createIfMissing:=True) Then
' // check that expression doesn't continue
If arg IsNot Nothing Then
CheckForEndOfExpression(arg)
End If
End If
aggregateFunc = SyntaxFactory.FunctionAggregation(aggName, lParen, arg, rParen)
Else
aggregateFunc = SyntaxFactory.FunctionAggregation(aggName, Nothing, Nothing, Nothing)
' // check that expression doesn't continue
CheckForEndOfExpression(aggregateFunc)
End If
Return aggregateFunc
End Function
' // check that expression doesn't continue
' File: Parser.cpp
' Lines: 14420 - 14420
' bool .Parser::CheckForEndOfExpression( [ Token* Start ] [ bool& ErrorInConstruct ] )
Private Function CheckForEndOfExpression(Of T As VisualBasicSyntaxNode)(ByRef syntax As T) As Boolean
Debug.Assert(syntax IsNot Nothing)
'TODO: this is very different from original implementation.
' originally we would try to parse the whole thing as an expression and see if we
' will not consume more than "syntax". It seems that "syntax" is always a term
' so the only way ParseExpressionCore could consume more is if there is a binary operator.
' Hopefully checking for binary operator is enough...
If Not CurrentToken.IsBinaryOperator AndAlso
CurrentToken.Kind <> SyntaxKind.DotToken Then
Return True
End If
syntax = ReportSyntaxError(syntax, ERRID.ERR_ExpectedEndOfExpression)
Return False
End Function
' Several places the syntax trees allow a modified identifier, but we actually don't want to
' allow a trailing ?. This function encapsulates that.
Private Function ParseSimpleIdentifierAsModifiedIdentifier() As ModifiedIdentifierSyntax
Dim varName As IdentifierTokenSyntax = ParseIdentifier()
If CurrentToken.Kind = SyntaxKind.QuestionToken Then
Dim unexpectedNullable As SyntaxToken = CurrentToken
varName = varName.AddTrailingSyntax(ReportSyntaxError(unexpectedNullable, ERRID.ERR_NullableTypeInferenceNotSupported))
GetNextToken() ' get off the "?"
End If
Return SyntaxFactory.ModifiedIdentifier(varName, Nothing, Nothing, Nothing)
End Function
' File: Parser.cpp
' Lines: 14447 - 14447
' Initializer* .Parser::ParseAggregateListInitializer( [ bool AllowGroupName ] [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseAggregateListInitializer(AllowGroupName As Boolean) As AggregationRangeVariableSyntax
Dim varName As ModifiedIdentifierSyntax = Nothing
Dim Equals As PunctuationSyntax = Nothing
If ((CurrentToken.Kind = SyntaxKind.IdentifierToken OrElse CurrentToken.IsKeyword()) AndAlso
PeekToken(1).Kind = SyntaxKind.EqualsToken _
OrElse
(PeekToken(1).Kind = SyntaxKind.QuestionToken AndAlso PeekToken(2).Kind = SyntaxKind.EqualsToken)) Then
' // Parse form: <IdentiferOrKeyword> '=' <Expression>
varName = ParseSimpleIdentifierAsModifiedIdentifier()
' NOTE: do not need to resync here. we should land on "="
Debug.Assert(CurrentToken.Kind = SyntaxKind.EqualsToken)
Equals = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken() '// move off the '='
TryEatNewLine() ' // line continuation allowed after '='
End If
Dim expr As AggregationSyntax = Nothing
If CurrentToken.Kind = SyntaxKind.IdentifierToken OrElse CurrentToken.IsKeyword() Then
Dim groupKw As KeywordSyntax = Nothing
If TryTokenAsContextualKeyword(CurrentToken, SyntaxKind.GroupKeyword, groupKw) AndAlso
PeekToken(1).Kind <> SyntaxKind.OpenParenToken Then
If Not AllowGroupName Then
groupKw = ReportSyntaxError(groupKw, ERRID.ERR_UnexpectedGroup)
End If
expr = SyntaxFactory.GroupAggregation(groupKw)
' // check that expression doesn't continue
CheckForEndOfExpression(expr)
GetNextToken() ' // Move off 'Group
Else
expr = ParseAggregationExpression() ' // this must be an Aggregation
End If
Else
Dim missingIdent = InternalSyntaxFactory.MissingIdentifier()
If AllowGroupName Then
missingIdent = ReportSyntaxError(missingIdent, ERRID.ERR_ExpectedIdentifierOrGroup)
Else
missingIdent = ReportSyntaxError(missingIdent, ERRID.ERR_ExpectedIdentifier)
End If
expr = SyntaxFactory.FunctionAggregation(missingIdent, Nothing, Nothing, Nothing)
End If
Debug.Assert((varName Is Nothing) = (Equals Is Nothing))
Dim variableNameEquals As VariableNameEqualsSyntax = Nothing
If varName IsNot Nothing AndAlso Equals IsNot Nothing Then
variableNameEquals = SyntaxFactory.VariableNameEquals(varName, Nothing, Equals)
End If
Return SyntaxFactory.AggregationRangeVariable(
variableNameEquals,
expr)
End Function
' File: Parser.cpp
' Lines: 14615 - 14615
' InitializerList* .Parser::ParseAggregateList( [ bool AllowGroupName ] [ bool IsGroupJoinProjection ] [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseAggregateList(
AllowGroupName As Boolean,
IsGroupJoinProjection As Boolean) As SeparatedSyntaxList(Of AggregationRangeVariableSyntax)
Dim RangeVariables = Me._pool.AllocateSeparated(Of AggregationRangeVariableSyntax)()
Do
Dim rangeVar = ParseAggregateListInitializer(AllowGroupName)
If rangeVar.ContainsDiagnostics Then
If IsGroupJoinProjection Then
rangeVar = ResyncAt(rangeVar, SyntaxKind.CommaToken, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
SyntaxKind.FromKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword,
SyntaxKind.IntoKeyword, SyntaxKind.OnKeyword, SyntaxKind.SkipKeyword,
SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
Else
rangeVar = ResyncAt(rangeVar, SyntaxKind.CommaToken, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
SyntaxKind.FromKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword,
SyntaxKind.IntoKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword,
SyntaxKind.LetKeyword)
End If
End If
RangeVariables.Add(rangeVar)
If CurrentToken.Kind = SyntaxKind.CommaToken Then
Dim comma = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken()
TryEatNewLine()
RangeVariables.AddSeparator(comma)
Else
Exit Do
End If
Loop
Dim result = RangeVariables.ToList
Me._pool.Free(RangeVariables)
Return result
End Function
' File: Parser.cpp
' Lines: 14666 - 14666
' FromList* .Parser::ParseFromList( [ bool AssignmentList ] [ _Inout_ bool& ErrorInConstruct ] )
' TODO: Merge with ParseFromControlVars. The two methods are almost identical.
Private Function ParseLetList() As SeparatedSyntaxList(Of ExpressionRangeVariableSyntax)
Dim RangeVariables = Me._pool.AllocateSeparated(Of ExpressionRangeVariableSyntax)()
Do
Dim varName As ModifiedIdentifierSyntax = ParseNullableModifiedIdentifer()
If varName.ContainsDiagnostics Then
' // If we see As or In before other query operators, then assume that
' // we are still on the Control Variable Declaration.
' // Otherwise, don't resync and allow the caller to
' // decide how to recover.
Dim peek = PeekAheadFor(SyntaxKind.AsKeyword, SyntaxKind.InKeyword, SyntaxKind.CommaToken,
SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
Select Case (peek)
Case SyntaxKind.AsKeyword,
SyntaxKind.InKeyword,
SyntaxKind.CommaToken
varName = varName.AddTrailingSyntax(ResyncAt({peek}))
End Select
End If
If CurrentToken.Kind = SyntaxKind.QuestionToken AndAlso
(PeekToken(1).Kind = SyntaxKind.InKeyword OrElse
PeekToken(1).Kind = SyntaxKind.EqualsToken) Then
Dim unexpectedNullable As SyntaxToken = CurrentToken
varName = varName.AddTrailingSyntax(ReportSyntaxError(unexpectedNullable, ERRID.ERR_NullableTypeInferenceNotSupported))
GetNextToken() ' get off the "?"
End If
Dim AsClause As SimpleAsClauseSyntax = Nothing
Dim TokenFollowingAsWasIn As Boolean = False
' // Parse the type if specified
If CurrentToken.Kind = SyntaxKind.AsKeyword Then
Dim AsKw As KeywordSyntax = DirectCast(CurrentToken, KeywordSyntax)
Debug.Assert(AsKw IsNot Nothing)
' // Parse the type
GetNextToken() ' // get off AS
If CurrentToken.Kind = SyntaxKind.InKeyword Then
TokenFollowingAsWasIn = True
End If
Dim Type As TypeSyntax = ParseGeneralType()
AsClause = SyntaxFactory.SimpleAsClause(AsKw, Nothing, Type)
' // try to recover
If Type.ContainsDiagnostics Then
Dim peek = PeekAheadFor(SyntaxKind.InKeyword, SyntaxKind.CommaToken, SyntaxKind.EqualsToken,
SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
Select Case (peek)
Case SyntaxKind.AsKeyword,
SyntaxKind.InKeyword,
SyntaxKind.CommaToken
AsClause = AsClause.AddTrailingSyntax(ResyncAt({peek}))
End Select
End If
End If
Dim Equals As PunctuationSyntax = Nothing
Dim source As ExpressionSyntax = Nothing
If Not TryGetToken(SyntaxKind.EqualsToken, Equals) Then
Equals = InternalSyntaxFactory.MissingPunctuation(SyntaxKind.EqualsToken)
Equals = ReportSyntaxError(Equals, ERRID.ERR_ExpectedAssignmentOperator)
Else
If Not TokenFollowingAsWasIn Then
TryEatNewLine() ' // enable implicit LC after 'In' or '=' But not if somebody did from x as IN
End If
source = ParseExpressionCore()
End If
' // try to recover
If source Is Nothing OrElse source.ContainsDiagnostics Then
' Fix up source
source = If(source, InternalSyntaxFactory.MissingExpression)
Dim peek = PeekAheadFor(SyntaxKind.CommaToken,
SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
If peek = SyntaxKind.CommaToken Then
source = source.AddTrailingSyntax(ResyncAt({peek}))
End If
End If
Dim rangeVar = SyntaxFactory.ExpressionRangeVariable(
SyntaxFactory.VariableNameEquals(varName, AsClause, Equals),
source)
RangeVariables.Add(rangeVar)
' // check for list continuation
Dim comma As PunctuationSyntax = Nothing
If TryGetTokenAndEatNewLine(SyntaxKind.CommaToken, comma) Then
RangeVariables.AddSeparator(comma)
Else
Exit Do
End If
Loop
Dim result = RangeVariables.ToList
Me._pool.Free(RangeVariables)
Return result
End Function
Private Function ParseFromControlVars() As SeparatedSyntaxList(Of CollectionRangeVariableSyntax)
Dim RangeVariables = Me._pool.AllocateSeparated(Of CollectionRangeVariableSyntax)()
Do
Dim varName As ModifiedIdentifierSyntax = ParseNullableModifiedIdentifer()
If varName.ContainsDiagnostics Then
' // If we see As or In before other query operators, then assume that
' // we are still on the Control Variable Declaration.
' // Otherwise, don't resync and allow the caller to
' // decide how to recover.
Dim peek = PeekAheadFor(SyntaxKind.AsKeyword, SyntaxKind.InKeyword, SyntaxKind.CommaToken,
SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
Select Case (peek)
Case SyntaxKind.AsKeyword,
SyntaxKind.InKeyword,
SyntaxKind.CommaToken
varName = varName.AddTrailingSyntax(ResyncAt({peek}))
End Select
End If
If CurrentToken.Kind = SyntaxKind.QuestionToken AndAlso
(PeekToken(1).Kind = SyntaxKind.InKeyword OrElse
PeekToken(1).Kind = SyntaxKind.EqualsToken) Then
Dim unexpectedNullable As SyntaxToken = CurrentToken
varName = varName.AddTrailingSyntax(ReportSyntaxError(unexpectedNullable, ERRID.ERR_NullableTypeInferenceNotSupported))
GetNextToken() ' get off the "?"
End If
Dim AsClause As SimpleAsClauseSyntax = Nothing
Dim TokenFollowingAsWasIn As Boolean = False
' // Parse the type if specified
If CurrentToken.Kind = SyntaxKind.AsKeyword Then
Dim AsKw As KeywordSyntax = DirectCast(CurrentToken, KeywordSyntax)
Debug.Assert(AsKw IsNot Nothing)
' // Parse the type
GetNextToken() ' // get off AS
If CurrentToken.Kind = SyntaxKind.InKeyword Then
TokenFollowingAsWasIn = True
End If
Dim Type As TypeSyntax = ParseGeneralType()
AsClause = SyntaxFactory.SimpleAsClause(AsKw, Nothing, Type)
' // try to recover
If Type.ContainsDiagnostics Then
Dim peek = PeekAheadFor(SyntaxKind.InKeyword, SyntaxKind.CommaToken, SyntaxKind.EqualsToken,
SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
Select Case (peek)
Case SyntaxKind.AsKeyword,
SyntaxKind.InKeyword,
SyntaxKind.CommaToken
AsClause = AsClause.AddTrailingSyntax(ResyncAt({peek}))
End Select
End If
End If
Dim [In] As KeywordSyntax = Nothing
Dim source As ExpressionSyntax = Nothing
If TryEatNewLineAndGetToken(SyntaxKind.InKeyword, [In], createIfMissing:=True) Then
If Not TokenFollowingAsWasIn Then
TryEatNewLine() ' // enable implicit LC after 'In' or '=' But not if somebody did from x as IN
End If
source = ParseExpressionCore()
End If
' // try to recover
If source Is Nothing OrElse source.ContainsDiagnostics Then
' Fix up source
source = If(source, InternalSyntaxFactory.MissingExpression)
' resync
Dim peek = PeekAheadFor(SyntaxKind.CommaToken,
SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
If peek = SyntaxKind.CommaToken Then
source = source.AddTrailingSyntax(ResyncAt({peek}))
End If
End If
Dim rangeVar = SyntaxFactory.CollectionRangeVariable(varName, AsClause, [In], source)
RangeVariables.Add(rangeVar)
' // check for list continuation
Dim comma As PunctuationSyntax = Nothing
If TryGetTokenAndEatNewLine(SyntaxKind.CommaToken, comma) Then
RangeVariables.AddSeparator(comma)
Else
Exit Do
End If
Loop
Dim result = RangeVariables.ToList
Me._pool.Free(RangeVariables)
Return result
End Function
' /*********************************************************************
' ;ParsePotentialQuery
'
' The parser determined that we might be on a query expression because we were on 'From' or
' 'Aggregate' We now see if we actually are on a query expression and parse it if we are.
' **********************************************************************/
' // the query expression if this is in fact a query we are on
' // [out] true = that we were on a query and that we handled it / false = not a query
' // [out] whether we encountered an error processing the query statement (assuming this actually is a query statement)
' Expression* .Parser::ParsePotentialQuery( [ _Inout_ ParseTree::LineContinuationState& continuationState ] [ _Out_ bool& ParsedQuery ] [ _Out_ bool& ErrorInConstruct ] )
Private Function ParsePotentialQuery(contextualKeyword As KeywordSyntax) As ExpressionSyntax
Debug.Assert(contextualKeyword IsNot Nothing)
Debug.Assert(contextualKeyword.Kind = SyntaxKind.FromKeyword OrElse contextualKeyword.Kind = SyntaxKind.AggregateKeyword)
Debug.Assert(CurrentToken.Text = contextualKeyword.Text)
' // Look ahead and see if it looks like a query, i.e.
' // {AGGREGATE | FROM } <id>[?] {In | As | = }
Dim newLineAfterFrom As Boolean = False
Dim curIndex = 1
Dim current As SyntaxToken = PeekToken(curIndex)
If current IsNot Nothing AndAlso current.IsEndOfLine() Then
If Not NextLineStartsWithStatementTerminator(1) Then '// we don't allow two EOLs in a row here
curIndex += 1
current = PeekToken(curIndex)
newLineAfterFrom = True
End If
End If
' <id>
If current Is Nothing OrElse (current.Kind <> SyntaxKind.IdentifierToken AndAlso Not current.IsKeyword) Then
Return Nothing
End If
' "FROM <id> <EOL>" on the same line is enough to consider this a query. Only do the full check if
' there is a new line between the FROM and the <id>, if this is a keyword after the FROM or if the identifier is
' a contextual keyword.
'
' These are query expressions:
' x = From y (it's important for the IDE to have this classified as a query to offer correct highlighting
' and completion suggestions)
' or
' x = from y
' In ...
' This logic is needed to not classify the identifier "From" in the following JoinCondition as query:
' dim f = Join x On From Equals y
'
' These are two assignments:
' x = From
' y =
' and
' x = from a With
'
' See Bugs 1678 and 10020 for more context.
'
Dim identifierAsContextualKeyword As KeywordSyntax = Nothing
If newLineAfterFrom OrElse
current.IsKeyword OrElse
(current.Kind = SyntaxKind.IdentifierToken AndAlso
TryTokenAsContextualKeyword(current, identifierAsContextualKeyword)) Then
' Note: this block is used to reject queries. Everything that skips this if
' will be classified as a query.
curIndex += 1
current = PeekToken(curIndex)
' // Look ahead for 'IN' as it can start it's own line
If current IsNot Nothing Then
If current.Kind = SyntaxKind.StatementTerminatorToken Then
current = PeekToken(curIndex + 1)
If current Is Nothing OrElse current.Kind <> SyntaxKind.InKeyword Then
Return Nothing
End If
ElseIf current.Kind = SyntaxKind.QuestionToken Then
' // Skip '?'
curIndex += 1
current = PeekToken(curIndex)
End If
End If
If current Is Nothing Then
Return Nothing
End If
' check for As, In or =
' note that = may not come after EoL
If current.Kind <> SyntaxKind.InKeyword AndAlso
current.Kind <> SyntaxKind.AsKeyword AndAlso
(newLineAfterFrom OrElse current.Kind <> SyntaxKind.EqualsToken) Then
Return Nothing
End If
End If
If contextualKeyword.Kind = SyntaxKind.FromKeyword Then
GetNextToken() 'get off the From
Return ParseFromQueryExpression(contextualKeyword)
Else
Debug.Assert(contextualKeyword.Kind = SyntaxKind.AggregateKeyword)
GetNextToken() 'get off the Aggregate
Return ParseAggregateQueryExpression(contextualKeyword)
End If
End Function
Private Function ParseGroupByExpression(groupKw As KeywordSyntax) As GroupByClauseSyntax
Debug.Assert(groupKw IsNot Nothing)
Dim byKw As KeywordSyntax = Nothing
Dim elements As SeparatedSyntaxList(Of ExpressionRangeVariableSyntax) = Nothing
If Not TryEatNewLineAndGetContextualKeyword(SyntaxKind.ByKeyword, byKw, createIfMissing:=False) Then
TryEatNewLine()
' // parse element selector
elements = ParseSelectList()
End If
Dim keys As SeparatedSyntaxList(Of ExpressionRangeVariableSyntax) = Nothing
If byKw IsNot Nothing OrElse TryEatNewLineAndGetContextualKeyword(SyntaxKind.ByKeyword, byKw, createIfMissing:=True) Then
TryEatNewLine()
' // parse key selector
keys = ParseSelectList()
Else
Dim rangeVariables = Me._pool.AllocateSeparated(Of ExpressionRangeVariableSyntax)()
rangeVariables.Add(InternalSyntaxFactory.ExpressionRangeVariable(Nothing, InternalSyntaxFactory.MissingExpression()))
keys = rangeVariables.ToList
Me._pool.Free(rangeVariables)
End If
Dim intoKw As KeywordSyntax = Nothing
Dim Aggregation As SeparatedSyntaxList(Of AggregationRangeVariableSyntax) = Nothing
If TryEatNewLineAndGetContextualKeyword(SyntaxKind.IntoKeyword, intoKw, createIfMissing:=True) Then
TryEatNewLine()
' // parse result selector
Aggregation = ParseAggregateList(True, False)
Else
Aggregation = Me.MissingAggregationRangeVariables()
End If
Return SyntaxFactory.GroupByClause(groupKw, elements, byKw, keys, intoKw, Aggregation)
End Function
Private Function MissingAggregationRangeVariables() As SeparatedSyntaxList(Of AggregationRangeVariableSyntax)
Dim rangeVariables = Me._pool.AllocateSeparated(Of AggregationRangeVariableSyntax)()
rangeVariables.Add(InternalSyntaxFactory.AggregationRangeVariable(Nothing, SyntaxFactory.FunctionAggregation(InternalSyntaxFactory.MissingIdentifier(), Nothing, Nothing, Nothing)))
Dim result As SeparatedSyntaxList(Of AggregationRangeVariableSyntax) = rangeVariables.ToList
Me._pool.Free(rangeVariables)
Return result
End Function
' File: Parser.cpp
' Lines: 15016 - 15016
' GroupJoinExpression* .Parser::ParseGroupJoinExpression( [ _In_ Token* beginSourceToken ] [ _In_opt_ ParseTree::LinqExpression* Source ] [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseInnerJoinOrGroupJoinExpression(groupKw As KeywordSyntax,
joinKw As KeywordSyntax) As JoinClauseSyntax
Debug.Assert(joinKw IsNot Nothing)
' // Make sure control var on the left is always named
' TODO: semantics
' MakeSureLeftControlVarIsNamed(source)
TryEatNewLine()
Dim joinVariable = ParseJoinControlVar()
Dim moreJoinsBuilder = _pool.Allocate(Of JoinClauseSyntax)()
Do
Dim nextJoin = ParseOptionalJoinOperator()
If nextJoin Is Nothing Then
Exit Do
End If
moreJoinsBuilder.Add(nextJoin)
Loop
Dim onKw As KeywordSyntax = Nothing
Dim Predicate As SeparatedSyntaxList(Of JoinConditionSyntax) = Nothing
If TryEatNewLineAndGetToken(SyntaxKind.OnKeyword, onKw, createIfMissing:=True) Then
TryEatNewLine()
Predicate = ParseJoinPredicateExpression()
Else
Dim missingEq = SyntaxFactory.JoinCondition(InternalSyntaxFactory.MissingExpression,
InternalSyntaxFactory.MissingKeyword(SyntaxKind.EqualsKeyword),
InternalSyntaxFactory.MissingExpression)
Predicate = New SeparatedSyntaxList(Of JoinConditionSyntax)(missingEq)
End If
Dim joinVarList = New SeparatedSyntaxList(Of CollectionRangeVariableSyntax)(joinVariable)
Dim moreJoins = moreJoinsBuilder.ToList()
_pool.Free(moreJoinsBuilder)
If groupKw Is Nothing Then
Return SyntaxFactory.SimpleJoinClause(joinKw, joinVarList, moreJoins, onKw, Predicate)
Else
Dim intoKw As KeywordSyntax = Nothing
Dim Aggregation As SeparatedSyntaxList(Of AggregationRangeVariableSyntax) = Nothing
If TryEatNewLineAndGetContextualKeyword(SyntaxKind.IntoKeyword, intoKw, createIfMissing:=True) Then
TryEatNewLine()
' // parse result selector
Aggregation = ParseAggregateList(True, True)
Else
Aggregation = Me.MissingAggregationRangeVariables()
End If
Return SyntaxFactory.GroupJoinClause(groupKw, joinKw, joinVarList, moreJoins, onKw, Predicate, intoKw, Aggregation)
End If
End Function
' File: Parser.cpp
' Lines: 15260 - 15260
' LinqExpression* .Parser::ParseJoinSourceExpression( [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseOptionalJoinOperator() As JoinClauseSyntax
Dim joinKw As KeywordSyntax = Nothing
If TryEatNewLineAndGetContextualKeyword(SyntaxKind.JoinKeyword, joinKw) Then
Return ParseInnerJoinOrGroupJoinExpression(Nothing, joinKw)
End If
Dim groupKw As KeywordSyntax = Nothing
If TryEatNewLineAndGetContextualKeyword(SyntaxKind.GroupKeyword, groupKw) Then
TryGetContextualKeyword(SyntaxKind.JoinKeyword, joinKw, createIfMissing:=True)
Return ParseInnerJoinOrGroupJoinExpression(groupKw, joinKw)
End If
Return Nothing
End Function
' File: Parser.cpp
' Lines: 15107 - 15107
' LinqSourceExpression* .Parser::ParseJoinControlVarExpression( [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseJoinControlVar() As CollectionRangeVariableSyntax
Dim varName As ModifiedIdentifierSyntax = ParseNullableModifiedIdentifer()
If varName.ContainsDiagnostics Then
' // If we see As or In before other query operators, then assume that
' // we are still on the Control Variable Declaration.
' // Otherwise, don't resync and allow the caller to
' // decide how to recover.
Dim peek = PeekAheadFor(SyntaxKind.AsKeyword, SyntaxKind.InKeyword, SyntaxKind.OnKeyword,
SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
Select Case (peek)
Case SyntaxKind.AsKeyword,
SyntaxKind.InKeyword,
SyntaxKind.GroupKeyword,
SyntaxKind.JoinKeyword,
SyntaxKind.OnKeyword
varName = varName.AddTrailingSyntax(ResyncAt({peek}))
End Select
End If
If CurrentToken.Kind = SyntaxKind.QuestionToken AndAlso
PeekToken(1).Kind = SyntaxKind.InKeyword Then
Dim unexpectedNullable As SyntaxToken = CurrentToken
varName = varName.AddTrailingSyntax(ReportSyntaxError(unexpectedNullable, ERRID.ERR_NullableTypeInferenceNotSupported))
GetNextToken() ' get off the "?"
End If
Dim AsClause As SimpleAsClauseSyntax = Nothing
' // Parse the type if specified
If CurrentToken.Kind = SyntaxKind.AsKeyword Then
Dim AsKw As KeywordSyntax = DirectCast(CurrentToken, KeywordSyntax)
Debug.Assert(AsKw IsNot Nothing)
' // Parse the type
GetNextToken() ' // get off AS
Dim Type As TypeSyntax = ParseGeneralType()
AsClause = SyntaxFactory.SimpleAsClause(AsKw, Nothing, Type)
' // try to recover
If Type.ContainsDiagnostics Then
Dim peek = PeekAheadFor(SyntaxKind.InKeyword, SyntaxKind.OnKeyword, SyntaxKind.EqualsToken,
SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
Select Case (peek)
Case SyntaxKind.EqualsToken,
SyntaxKind.InKeyword,
SyntaxKind.GroupKeyword,
SyntaxKind.JoinKeyword,
SyntaxKind.OnKeyword
AsClause = AsClause.AddTrailingSyntax(ResyncAt({peek}))
End Select
End If
End If
Dim [In] As KeywordSyntax = Nothing
Dim source As ExpressionSyntax = Nothing
If TryEatNewLineAndGetToken(SyntaxKind.InKeyword, [In], createIfMissing:=True) Then
TryEatNewLine() ' // dev10_500708 allow line continuation after 'IN'
source = ParseExpressionCore()
End If
' // try to recover
If source Is Nothing OrElse source.ContainsDiagnostics Then
' Fix up source
source = If(source, InternalSyntaxFactory.MissingExpression)
' resync
Dim peek = PeekAheadFor(SyntaxKind.CommaToken,
SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
If peek = SyntaxKind.CommaToken Then
source = source.AddTrailingSyntax(ResyncAt({peek}))
End If
End If
Return SyntaxFactory.CollectionRangeVariable(varName, AsClause, [In], source)
End Function
' File: Parser.cpp
' Lines: 15293 - 15293
' Expression* .Parser::ParseJoinPredicateExpression( [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseJoinPredicateExpression() As SeparatedSyntaxList(Of JoinConditionSyntax)
Dim Exprs = Me._pool.AllocateSeparated(Of JoinConditionSyntax)()
Dim AndTk As KeywordSyntax = Nothing
Do
Dim element As JoinConditionSyntax = Nothing
If CurrentToken.Kind <> SyntaxKind.StatementTerminatorToken Then
Dim Left = ParseExpressionCore(OperatorPrecedence.PrecedenceRelational)
' // try to recover
If Left.ContainsDiagnostics Then
Left = ResyncAt(Left, SyntaxKind.EqualsToken, SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword,
SyntaxKind.GroupKeyword, SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword,
SyntaxKind.JoinKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword,
SyntaxKind.IntoKeyword, SyntaxKind.OnKeyword, SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword,
SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword, SyntaxKind.SkipKeyword, SyntaxKind.SkipKeyword,
SyntaxKind.LetKeyword)
End If
Dim eqKw As KeywordSyntax = Nothing
Dim Right As ExpressionSyntax = Nothing
If TryGetContextualKeywordAndEatNewLine(SyntaxKind.EqualsKeyword, eqKw, createIfMissing:=True) Then
Right = ParseExpressionCore(OperatorPrecedence.PrecedenceRelational)
Else
Right = InternalSyntaxFactory.MissingExpression
End If
element = SyntaxFactory.JoinCondition(Left, eqKw, Right)
Else
element = SyntaxFactory.JoinCondition(InternalSyntaxFactory.MissingExpression,
InternalSyntaxFactory.MissingKeyword(SyntaxKind.EqualsKeyword),
InternalSyntaxFactory.MissingExpression)
element = ReportSyntaxError(element, ERRID.ERR_ExpectedExpression)
End If
' // try to recover
If element.ContainsDiagnostics Then
element = ResyncAt(element, SyntaxKind.AndKeyword, SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword,
SyntaxKind.GroupKeyword, SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword, SyntaxKind.OnKeyword,
SyntaxKind.AndAlsoKeyword, SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword, SyntaxKind.SkipKeyword,
SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
End If
If Exprs.Count > 0 Then
Exprs.AddSeparator(AndTk)
End If
Exprs.Add(element)
If TryGetTokenAndEatNewLine(SyntaxKind.AndKeyword, AndTk) Then
Continue Do
ElseIf CurrentToken.Kind = SyntaxKind.AndAlsoKeyword OrElse
CurrentToken.Kind = SyntaxKind.OrKeyword OrElse
CurrentToken.Kind = SyntaxKind.OrElseKeyword Then
Exprs(Exprs.Count - 1) = Exprs(Exprs.Count - 1).AddTrailingSyntax(CurrentToken, ERRID.ERR_ExpectedAnd)
GetNextToken() ' consume bad token
End If
Exit Do
Loop
Dim result = Exprs.ToList
Me._pool.Free(Exprs)
' // try to recover
If result.Node.ContainsDiagnostics Then
Dim elements = result.Node
elements = ResyncAt(elements, SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword, SyntaxKind.DistinctKeyword,
SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword, SyntaxKind.OnKeyword, SyntaxKind.SkipKeyword,
SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
result = New SeparatedSyntaxList(Of JoinConditionSyntax)(New SyntaxList(Of JoinConditionSyntax)(elements))
End If
Return result
End Function
' File: Parser.cpp
' Lines: 14861 - 14861
' LinqExpression* .Parser::ParseFromExpression( [ bool StartingQuery ] [ bool ImplicitFrom ] [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseFromOperator(FromKw As KeywordSyntax) As FromClauseSyntax
Debug.Assert(FromKw IsNot Nothing)
TryEatNewLine()
Return SyntaxFactory.FromClause(FromKw, ParseFromControlVars())
End Function
Private Function ParseLetOperator(LetKw As KeywordSyntax) As LetClauseSyntax
Debug.Assert(LetKw IsNot Nothing)
TryEatNewLine()
Return SyntaxFactory.LetClause(LetKw, ParseLetList())
End Function
' File: Parser.cpp
' Lines: 15389 - 15389
'ParseTree::OrderByList *
'Parser::ParseOrderByList
'(
' _Inout_ bool &ErrorInConstruct
' _Inout_ ParseTree::LineContinuationState &OrderExprContinuationState, // [out] the continuation situation for the Order statement as relates to the Ascending/Descending keywords
' _Inout_ bool &ErrorInConstruct // [out] whether we ran into an error processing the OrderBy list.
')
Private Function ParseOrderByList() As SeparatedSyntaxList(Of OrderingSyntax)
Dim exprs = Me._pool.AllocateSeparated(Of OrderingSyntax)()
Do
Dim OrderExpression = ParseExpressionCore()
' // try to recover
If OrderExpression.ContainsDiagnostics Then
OrderExpression = ResyncAt(OrderExpression, SyntaxKind.CommaToken, SyntaxKind.AscendingKeyword,
SyntaxKind.DescendingKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
SyntaxKind.FromKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword,
SyntaxKind.IntoKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
End If
Dim element As OrderingSyntax = Nothing
Dim directionKw As KeywordSyntax = Nothing
If TryEatNewLineAndGetContextualKeyword(SyntaxKind.DescendingKeyword, directionKw) Then
element = SyntaxFactory.DescendingOrdering(OrderExpression, directionKw)
Else
TryEatNewLineAndGetContextualKeyword(SyntaxKind.AscendingKeyword, directionKw)
element = SyntaxFactory.AscendingOrdering(OrderExpression, directionKw)
End If
exprs.Add(element)
Dim comma As PunctuationSyntax = Nothing
If TryEatNewLineAndGetToken(SyntaxKind.CommaToken, comma, createIfMissing:=False) Then
TryEatNewLine()
exprs.AddSeparator(comma)
Else
Exit Do
End If
Loop
Dim result = exprs.ToList
Me._pool.Free(exprs)
Return result
End Function
' File: Parser.cpp
' Lines: 15508 - 15508
' LinqExpression* .Parser::ParseFromQueryExpression( [ bool ImplicitFrom ] [ _Inout_ bool& ErrorInConstruct ] )
Private Sub ParseMoreQueryOperators(ByRef operators As SyntaxListBuilder(Of QueryClauseSyntax))
Do
' // try to recover
If operators.Count > 0 AndAlso operators(operators.Count - 1).ContainsDiagnostics Then
operators(operators.Count - 1) = ResyncAt(operators(operators.Count - 1),
SyntaxKind.FromKeyword,
SyntaxKind.WhereKeyword,
SyntaxKind.GroupKeyword,
SyntaxKind.SelectKeyword,
SyntaxKind.OrderKeyword,
SyntaxKind.JoinKeyword,
SyntaxKind.DistinctKeyword,
SyntaxKind.AggregateKeyword,
SyntaxKind.IntoKeyword,
SyntaxKind.SkipKeyword,
SyntaxKind.TakeKeyword,
SyntaxKind.LetKeyword)
End If
Dim clause = ParseNextQueryOperator()
If clause Is Nothing Then
Return
End If
operators.Add(clause)
Loop
End Sub
Private Function ParseNextQueryOperator() As QueryClauseSyntax
Dim Start = CurrentToken
' //We allow implicit line continuations before query keywords when in a query context.
If Start.Kind = SyntaxKind.StatementTerminatorToken Then
If NextLineStartsWithStatementTerminator() OrElse
Not IsContinuableQueryOperator(PeekToken(1)) Then
Return Nothing
End If
' we are going to use this EoL and next token since we know it is a valid operator.
' so it is ok to move to the next token and grab EoL as a trivia.
TryEatNewLine()
Start = CurrentToken
End If
' // it must be Id or Keyword from here
Select Case Start.Kind
Case SyntaxKind.SelectKeyword
GetNextToken() ' get off Select
TryEatNewLine()
Dim Projection = ParseSelectList()
Return InternalSyntaxFactory.SelectClause(DirectCast(Start, KeywordSyntax), Projection)
Case SyntaxKind.LetKeyword
GetNextToken() ' get off Let
Return ParseLetOperator(DirectCast(Start, KeywordSyntax))
Case SyntaxKind.IdentifierToken
Dim kw As KeywordSyntax = Nothing
If Not TryTokenAsContextualKeyword(Start, kw) Then
Return Nothing
End If
Select Case kw.Kind
Case SyntaxKind.WhereKeyword
GetNextToken() ' get off where
TryEatNewLine()
Return InternalSyntaxFactory.WhereClause(kw, ParseExpressionCore())
Case SyntaxKind.SkipKeyword
GetNextToken() ' get off Skip
If CurrentToken.Kind = SyntaxKind.WhileKeyword Then
' // Note: no line continuation if Skip is followed by While, i.e. Skip While is treated as a unit
Dim whileKw = DirectCast(CurrentToken, KeywordSyntax)
GetNextToken() ' get off While
TryEatNewLine()
Return InternalSyntaxFactory.SkipWhileClause(kw, whileKw, ParseExpressionCore())
Else
TryEatNewLineIfNotFollowedBy(SyntaxKind.WhileKeyword) ' // when Skip ends the line, allow a implicit line continuation
Return InternalSyntaxFactory.SkipClause(kw, ParseExpressionCore())
End If
Case SyntaxKind.TakeKeyword
GetNextToken() ' get off Take
If CurrentToken.Kind = SyntaxKind.WhileKeyword Then
' // Note: no line continuation if Skip is followed by While, i.e. Skip While is treated as a unit
Dim whileKw = DirectCast(CurrentToken, KeywordSyntax)
GetNextToken() ' get off While
TryEatNewLine()
Return InternalSyntaxFactory.TakeWhileClause(kw, whileKw, ParseExpressionCore())
Else
TryEatNewLineIfNotFollowedBy(SyntaxKind.WhileKeyword) ' // when Skip ends the line, allow a implicit line continuation
Return InternalSyntaxFactory.TakeClause(kw, ParseExpressionCore())
End If
Case SyntaxKind.GroupKeyword
GetNextToken() 'get off Group
' // See if this is a 'Group Join'
Dim joinKw As KeywordSyntax = Nothing
If TryGetContextualKeyword(SyntaxKind.JoinKeyword, joinKw) Then
Return ParseInnerJoinOrGroupJoinExpression(kw, joinKw)
Else
Return ParseGroupByExpression(kw)
End If
Case SyntaxKind.AggregateKeyword
GetNextToken() ' get off Aggregate
Return ParseAggregateClause(kw)
Case SyntaxKind.OrderKeyword
GetNextToken() ' get off Order
Dim byKw As KeywordSyntax = Nothing
TryGetContextualKeywordAndEatNewLine(SyntaxKind.ByKeyword, byKw, createIfMissing:=True)
TryEatNewLine()
Dim OrderByItems = ParseOrderByList()
Return InternalSyntaxFactory.OrderByClause(kw, byKw, OrderByItems)
Case SyntaxKind.DistinctKeyword
GetNextToken() ' get off Distinct
If CurrentToken.Kind = SyntaxKind.StatementTerminatorToken Then
' Eat the new line only if the distinct is followed by a token that can continue a term or an expression
Dim tokenAfterEOL = PeekToken(1)
Select Case tokenAfterEOL.Kind
Case SyntaxKind.DotToken, SyntaxKind.ExclamationToken, SyntaxKind.QuestionToken, SyntaxKind.OpenParenToken
TryEatNewLine()
Case Else
If tokenAfterEOL.IsBinaryOperator Then
TryEatNewLine()
End If
End Select
End If
Return InternalSyntaxFactory.DistinctClause(kw)
Case SyntaxKind.JoinKeyword
GetNextToken() ' get off Join
Return ParseInnerJoinOrGroupJoinExpression(Nothing, kw)
Case SyntaxKind.FromKeyword
GetNextToken() ' get off From
Return ParseFromOperator(kw)
End Select
End Select
Return Nothing
End Function
Private Function ParseFromQueryExpression(fromKw As KeywordSyntax) As QueryExpressionSyntax
Debug.Assert(fromKw IsNot Nothing)
Dim operators = Me._pool.Allocate(Of QueryClauseSyntax)()
operators.Add(ParseFromOperator(fromKw))
ParseMoreQueryOperators(operators)
Dim result = operators.ToList
Me._pool.Free(operators)
Return SyntaxFactory.QueryExpression(result)
End Function
Private Function ParseAggregateQueryExpression(AggregateKw As KeywordSyntax) As QueryExpressionSyntax
Debug.Assert(AggregateKw IsNot Nothing)
Dim operators = Me._pool.Allocate(Of QueryClauseSyntax)()
operators.Add(ParseAggregateClause(AggregateKw))
Dim result = operators.ToList
Me._pool.Free(operators)
Return SyntaxFactory.QueryExpression(result)
End Function
Private Function ParseAggregateClause(AggregateKw As KeywordSyntax) As AggregateClauseSyntax
Debug.Assert(AggregateKw IsNot Nothing)
TryEatNewLine()
Dim controlVariables = ParseFromControlVars()
Dim moreOperators = Me._pool.Allocate(Of QueryClauseSyntax)()
ParseMoreQueryOperators(moreOperators)
Dim operatorList = moreOperators.ToList
Me._pool.Free(moreOperators)
Dim intoKw As KeywordSyntax = Nothing
Dim variables As SeparatedSyntaxList(Of AggregationRangeVariableSyntax) = Nothing
If TryEatNewLineAndGetContextualKeyword(SyntaxKind.IntoKeyword, intoKw, createIfMissing:=True) Then
' //ILC: I took the liberty of adding implicit line continuations after query keywords in addition to before them...
TryEatNewLine()
' // parse result selector
variables = ParseAggregateList(False, False)
Else
variables = Me.MissingAggregationRangeVariables()
End If
Return SyntaxFactory.AggregateClause(AggregateKw, controlVariables, operatorList, intoKw, variables)
End Function
' bool .Parser::IsContinuableQueryOperator( [ Token* pToken ] )
Private Function IsContinuableQueryOperator(pToken As SyntaxToken) As Boolean
Debug.Assert(pToken IsNot Nothing)
Debug.Assert(pToken.Text Is PeekToken(1).Text)
Dim kind As SyntaxKind = Nothing
If Not TryTokenAsKeyword(pToken, kind) Then
Return False
End If
Dim isQueryKwd As Boolean = KeywordTable.IsQueryClause(kind)
If isQueryKwd AndAlso kind = SyntaxKind.SelectKeyword Then
' //We do not want to allow an implicit line continuation before a "select" keyword if it is immedietly
' //followed by the "case" keyword. This allows code like the following to parse correctly:
' // dim a = from x in xs
' // select case b
' // end select
Dim nextToken = PeekToken(2)
If nextToken.Kind = SyntaxKind.CaseKeyword Then
isQueryKwd = False
End If
End If
Return isQueryKwd
End Function
' File: Parser.cpp
' Lines: 14918 - 14918
' .::MakeSureLeftControlVarIsNamed( [ _In_opt_ ParseTree::LinqExpression* Source ] )
' TODO: this should be done in semantics.
'Private Shared Sub MakeSureLeftControlVarIsNamed( _
' ByVal Source As ParseTree.LinqExpression _
')
' While Source IsNot Nothing
' Select Case (Source.Opcode)
' Case ParseTree.Expression.Opcodes.InnerJoin, _
' ParseTree.Expression.Opcodes.GroupJoin, _
' ParseTree.Expression.Opcodes.CrossJoin, _
' ParseTree.Expression.Opcodes.From, _
' ParseTree.Expression.Opcodes.Let, _
' ParseTree.Expression.Opcodes.GroupBy, _
' ParseTree.Expression.Opcodes.Aggregate, _
' ParseTree.Expression.Opcodes.LinqSource
' Return ' // these operators do not produce unnamed vars
' Case ParseTree.Expression.Opcodes.Where, _
' ParseTree.Expression.Opcodes.SkipWhile, _
' ParseTree.Expression.Opcodes.TakeWhile, _
' ParseTree.Expression.Opcodes.Take, _
' ParseTree.Expression.Opcodes.Skip, _
' ParseTree.Expression.Opcodes.Distinct, _
' ParseTree.Expression.Opcodes.OrderBy
' Source = Source.AsLinqOperator().Source ' // these operators do not declare control vars
' Case ParseTree.Expression.Opcodes.Select
' AssertIfTrue(Source.AsSelect().ForceNameInferenceForSingleElement)
' Source.AsSelect().ForceNameInferenceForSingleElement = True
' Return ' // done
' Case Else
' AssertIfFalse(False) ' // unknown Opcode
' Return
' End Select
' End While
'End Sub
End Class
End Namespace
|
paladique/roslyn
|
src/Compilers/VisualBasic/Portable/Parser/ParseQuery.vb
|
Visual Basic
|
apache-2.0
| 63,242
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Imports System
Imports System.Reflection
Namespace Microsoft.CodeAnalysis.Scripting.VisualBasic
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module VBScriptingResources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("VBScriptingResources", GetType(VBScriptingResources).GetTypeInfo().Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
KevinRansom/roslyn
|
src/Scripting/VisualBasic/VBScriptingResources.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,810
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.CodeFixes.GenerateMember
Imports Microsoft.CodeAnalysis.GenerateType
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateType
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.GenerateType), [Shared]>
<ExtensionOrder(After:=PredefinedCodeFixProviderNames.GenerateVariable)>
Friend Class GenerateTypeCodeFixProvider
Inherits AbstractGenerateMemberCodeFixProvider
Friend Const BC30002 As String = "BC30002" ' error BC30002: Type 'Test' is not defined.
Friend Const BC30182 As String = "BC30182" ' error BC30182: Type expected.
Friend Const BC30451 As String = "BC30451" ' error BC30451: 'Foo' is not declared. It may be inaccessible due to its protection level.
Friend Const BC30456 As String = "BC30456" ' error BC32043: error BC30456: 'B' is not a member of 'A'.
Friend Const BC32042 As String = "BC32042" ' error BC32042: Too few type arguments to 'AA(Of T)'.
Friend Const BC32043 As String = "BC32043" ' error BC32043: Too many type arguments to 'AA(Of T)'.
Friend Const BC32045 As String = "BC32045" ' error BC32045: 'Foo' has no type parameters and so cannot have type arguments.
Friend Const BC40056 As String = "BC40056" ' error BC40056: Namespace or type specified in the Imports 'A' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String)
Get
Return ImmutableArray.Create(BC30002, BC30182, BC30451, BC30456, BC32042, BC32043, BC32045, BC40056)
End Get
End Property
Protected Overrides Function GetCodeActionsAsync(document As Document, node As SyntaxNode, cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of CodeAction))
Dim service = document.GetLanguageService(Of IGenerateTypeService)()
Return service.GenerateTypeAsync(document, node, cancellationToken)
End Function
Protected Overrides Function IsCandidate(node As SyntaxNode, token As SyntaxToken, diagnostic As Diagnostic) As Boolean
Dim qualified = TryCast(node, QualifiedNameSyntax)
If qualified IsNot Nothing Then
Return True
End If
Dim simple = TryCast(node, SimpleNameSyntax)
If simple IsNot Nothing Then
Return Not simple.IsParentKind(SyntaxKind.QualifiedName)
End If
Dim memberAccess = TryCast(node, MemberAccessExpressionSyntax)
If memberAccess IsNot Nothing Then
Return True
End If
Return False
End Function
Protected Overrides Function GetTargetNode(node As SyntaxNode) As SyntaxNode
Return (DirectCast(node, ExpressionSyntax)).GetRightmostName()
End Function
End Class
End Namespace
|
bbarry/roslyn
|
src/Features/VisualBasic/Portable/CodeFixes/GenerateType/GenerateTypeCodeFixProvider.vb
|
Visual Basic
|
apache-2.0
| 3,476
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
'vbc /t:module /vbruntime- Mod3.vb
Public Class Class3
Sub Goo()
Dim x = {1,2}
Dim y = x.Count()
End Sub
End Class
|
mmitche/roslyn
|
src/Compilers/Test/Resources/Core/SymbolsTests/MultiModule/mod3.vb
|
Visual Basic
|
apache-2.0
| 280
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.17929
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.VBNewMailNotification1.My.MySettings
Get
Return Global.VBNewMailNotification1.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
age-killer/Electronic-invoice-document-processing
|
MailSort_CSHARP/packages/Independentsoft.Exchange.3.0.400/Tutorial/VBNewMailNotification1/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,934
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rResumen_Pago_INCE"
'-------------------------------------------------------------------------------------------'
Partial Class rResumen_Pago_INCE
Inherits vis2formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1)) 'Recibo
Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1))
Dim lcParametro2Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2)) 'Contrato del Recibo
Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3)) 'Trabajador
Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4)) 'Contrato del Trabajador
Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4))
Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5)) 'Sucursal
Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5))
Dim lcParametro6Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6)) 'Revisión
Dim lcParametro6Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(6))
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim loComandoSeleccionar As New StringBuilder()
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("SELECT RIGHT('0000'+CAST(YEAR(Recibos.Fecha) AS VARCHAR(4)),4) AS Año,")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN MONTH(Recibos.Fecha) IN(1,2,3) THEN 1")
loComandoSeleccionar.AppendLine(" WHEN MONTH(Recibos.Fecha) IN(4,5,6) THEN 2")
loComandoSeleccionar.AppendLine(" WHEN MONTH(Recibos.Fecha) IN(7,8,9) THEN 3")
loComandoSeleccionar.AppendLine(" WHEN MONTH(Recibos.Fecha) IN(10,11,12) THEN 4")
loComandoSeleccionar.AppendLine(" END AS Trimestre,")
loComandoSeleccionar.AppendLine(" COUNT(DISTINCT Recibos.Cod_Tra) AS Trabajadores,")
loComandoSeleccionar.AppendLine(" SUM(CASE Conceptos_Nomina.tipo")
loComandoSeleccionar.AppendLine(" WHEN 'Asignacion' THEN Renglones_Recibos.mon_net")
loComandoSeleccionar.AppendLine(" else -Renglones_Recibos.mon_net")
loComandoSeleccionar.AppendLine(" END) AS Monto_Devengado,")
loComandoSeleccionar.AppendLine(" (SELECT TOP 1 val_num")
loComandoSeleccionar.AppendLine(" FROM Constantes_Locales")
loComandoSeleccionar.AppendLine(" WHERE COD_CON ='U004')*")
loComandoSeleccionar.AppendLine(" SUM(CASE Conceptos_Nomina.tipo")
loComandoSeleccionar.AppendLine(" WHEN 'Asignacion' THEN Renglones_Recibos.mon_net")
loComandoSeleccionar.AppendLine(" else -Renglones_Recibos.mon_net")
loComandoSeleccionar.AppendLine(" END)/100 AS Aporte")
loComandoSeleccionar.AppendLine("FROM Renglones_Recibos")
loComandoSeleccionar.AppendLine(" JOIN Recibos")
loComandoSeleccionar.AppendLine(" ON Recibos.Documento = Renglones_Recibos.Documento")
loComandoSeleccionar.AppendLine(" JOIN Conceptos_Nomina")
loComandoSeleccionar.AppendLine(" ON Conceptos_Nomina.cod_con = Renglones_Recibos.cod_con ")
loComandoSeleccionar.AppendLine(" JOIN Trabajadores")
loComandoSeleccionar.AppendLine(" ON Trabajadores.Cod_Tra = Recibos.Cod_Tra ")
loComandoSeleccionar.AppendLine("WHERE Conceptos_Nomina.tipo <> 'otro'")
loComandoSeleccionar.AppendLine(" AND Conceptos_Nomina.acumulados = 1")
loComandoSeleccionar.AppendLine(" AND Recibos.Status = 'Confirmado'")
loComandoSeleccionar.AppendLine(" AND Recibos.Fecha BETWEEN " & lcParametro0Desde & " AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Recibos.Documento BETWEEN " & lcParametro1Desde & " AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Recibos.Cod_Con BETWEEN " & lcParametro2Desde & " AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Trabajadores.Cod_Tra BETWEEN " & lcParametro3Desde & " AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Trabajadores.Cod_Con BETWEEN " & lcParametro4Desde & " AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Recibos.Cod_Suc BETWEEN " & lcParametro5Desde & " AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Recibos.Cod_Rev BETWEEN " & lcParametro6Desde & " AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine("GROUP BY RIGHT('0000'+CAST(YEAR(Recibos.Fecha) as VARCHAR(4)),4),")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN MONTH(Recibos.Fecha) IN(1,2,3) THEN 1")
loComandoSeleccionar.AppendLine(" WHEN MONTH(Recibos.Fecha) IN(4,5,6) THEN 2")
loComandoSeleccionar.AppendLine(" WHEN MONTH(Recibos.Fecha) IN(7,8,9) THEN 3")
loComandoSeleccionar.AppendLine(" WHEN MONTH(Recibos.Fecha) IN(10,11,12) THEN 4")
loComandoSeleccionar.AppendLine(" End")
loComandoSeleccionar.AppendLine("ORDER BY RIGHT('0000'+CAST(YEAR(Recibos.Fecha) as VARCHAR(4)),4),")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN MONTH(Recibos.Fecha) IN(1,2,3) THEN 1")
loComandoSeleccionar.AppendLine(" WHEN MONTH(Recibos.Fecha) IN(4,5,6) THEN 2")
loComandoSeleccionar.AppendLine(" WHEN MONTH(Recibos.Fecha) IN(7,8,9) THEN 3")
loComandoSeleccionar.AppendLine(" WHEN MONTH(Recibos.Fecha) IN(10,11,12) THEN 4")
loComandoSeleccionar.AppendLine(" End")
Dim loServicios As New cusDatos.goDatos
'Me.mEscribirConsulta(loComandoSeleccionar.ToString())
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString(), "curReportes")
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rResumen_Pago_INCE", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrResumen_Pago_INCE.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo '
'-------------------------------------------------------------------------------------------'
' EAG: 02/10/15: Codigo inicial '
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
Reportes - Nomina/rResumen_Pago_INCE.aspx.vb
|
Visual Basic
|
mit
| 9,216
|
Imports System.Xml
Imports System.Xml.Serialization
Namespace Snmp
Partial Public Class ObjectMapping
#Region " Public Methods "
Public Function Compile( _
ByVal analyser As TypeAnalyser _
) As ObjectMapping
For i As Integer = 0 To TableMappings.Length - 1
TableMappings(i).Compile(TypeAnalyser.GetInstance( _
TableMappings(i).MappingType).ElementTypeAnalyser)
Next
For i As Integer = 0 To FieldMappings.Length - 1
FieldMappings(i).Member = New MemberAnalyser()
If Not FieldMappings(i).Member.Parse(FieldMappings(i).Name, Nothing, analyser, 0, MemberAccessibility.All) Then _
Throw New MemberNotFoundException(FieldMappings(i).Name, analyser.Type)
Next
Array.Sort(FieldMappings)
Return Me
End Function
Public Overridable Sub Integrate( _
ByRef mappingToIntegrate As ObjectMapping _
)
If mappingToIntegrate.GetType Is GetType(ObjectMapping) _
OrElse mappingToIntegrate.GetType.IsSubclassOf(GetType(ObjectMapping)) Then
Dim newMapping As ObjectMapping = mappingToIntegrate
If Not newMapping.TableMappings Is Nothing Then
For i As Integer = 0 To newMapping.TableMappings.Length - 1
Dim mappingName As String = newMapping.TableMappings(i).Name
Dim alreadyExists As Boolean = False
If TableMappings Is Nothing Then TableMappings = New TableMapping() {}
For j As Integer = 0 To TableMappings.Length - 1
If String.Compare(mappingName, TableMappings(j).Name, True) = 0 Then
alreadyExists = True
Exit For
End If
Next
If Not alreadyExists Then
Array.Resize(TableMappings, TableMappings.Length + 1)
TableMappings(TableMappings.Length - 1) = newMapping.TableMappings(i)
End If
Next
End If
End If
If Not mappingToIntegrate.FieldMappings Is Nothing Then
For i As Integer = 0 To mappingToIntegrate.FieldMappings.Length - 1
Dim mappingName As String = _
mappingToIntegrate.FieldMappings(i).Name
Dim alreadyExists As Boolean = False
If FieldMappings Is Nothing Then FieldMappings = New FieldMapping() {}
For j As Integer = 0 To FieldMappings.Length - 1
If String.Compare(mappingName, _
FieldMappings(j).Name, True) = 0 Then
alreadyExists = True
Exit For
End If
Next
If Not alreadyExists Then
Array.Resize(FieldMappings, FieldMappings.Length + 1)
FieldMappings(FieldMappings.Length - 1) = mappingToIntegrate.FieldMappings(i)
End If
Next
End If
End Sub
Public Overridable Sub PopulateObjectFromMap( _
ByRef target As Object, _
ByVal values As Dictionary(Of MemberAnalyser, Object) _
)
For Each member As MemberAnalyser In values.Keys
PopulateObjectFromMap(target, member, values(member))
Next
End Sub
Public Overridable Sub PopulateObjectFromMap( _
ByRef target As Object, _
ByVal member As MemberAnalyser, _
ByVal value As Object _
)
If Not value Is Nothing Then
Dim populate As Boolean = True
If value.GetType Is GetType(String) AndAlso Not member.ReturnType Is GetType(String) Then _
value = New FromString().Parse(value, populate, member.ReturnType)
If populate Then member.Write(target, TypeAnalyser.Wedge(value, member.ReturnType, populate))
End If
End Sub
#End Region
End Class
End Namespace
|
thiscouldbejd/Caerus
|
_Snmp/Partials/ObjectMapping.vb
|
Visual Basic
|
mit
| 3,901
|
Imports Microsoft.VisualBasic
Imports System.IO
Imports Aspose.Cells
Namespace RowsColumns.HeightAndWidth
Public Class SetWidthAllColumns
Public Shared Sub Run()
' ExStart:1
' The path to the documents directory.
Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
' Create directory if it is not already present.
Dim IsExists As Boolean = System.IO.Directory.Exists(dataDir)
If (Not IsExists) Then
System.IO.Directory.CreateDirectory(dataDir)
End If
' Creating a file stream containing the Excel file to be opened
Dim fstream As New FileStream(dataDir & "book1.xls", FileMode.Open)
' Instantiating a Workbook object
' Opening the Excel file through the file stream
Dim workbook As New Workbook(fstream)
' Accessing the first worksheet in the Excel file
Dim worksheet As Worksheet = workbook.Worksheets(0)
' Setting the width of all columns in the worksheet to 20.5
worksheet.Cells.StandardWidth = 20.5
' Saving the modified Excel file
workbook.Save(dataDir & "output.xls")
' Closing the file stream to free all resources
fstream.Close()
' ExEnd:1
End Sub
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples/VisualBasic/RowsColumns/HeightAndWidth/SetWidthAllColumns.vb
|
Visual Basic
|
mit
| 1,438
|
Imports System
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim window As SolidEdgeFramework.Window = Nothing
Dim view As SolidEdgeFramework.View = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
' A 3D document must be open.
window = TryCast(application.ActiveWindow, SolidEdgeFramework.Window)
If window IsNot Nothing Then
view = window.View
Dim viewName = "TestView"
view.SaveCurrentView(viewName)
End If
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgeFramework.View.SaveCurrentView.vb
|
Visual Basic
|
mit
| 1,271
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global._01.Task1.My.MySettings
Get
Return Global._01.Task1.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
georgipyaramov/CSS
|
CSSOverview/CSS-Overview/01.Task1/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,885
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class dlgSignUp
Inherits System.Windows.Forms.Form
'Form 覆寫 Dispose 以清除元件清單。
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'為 Windows Form 設計工具的必要項
Private components As System.ComponentModel.IContainer
'注意: 以下為 Windows Form 設計工具所需的程序
'可以使用 Windows Form 設計工具進行修改。
'請不要使用程式碼編輯器進行修改。
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.Label1 = New System.Windows.Forms.Label()
Me.Label2 = New System.Windows.Forms.Label()
Me.Label3 = New System.Windows.Forms.Label()
Me.Label4 = New System.Windows.Forms.Label()
Me.btnCancel = New System.Windows.Forms.Button()
Me.btnSign = New System.Windows.Forms.Button()
Me.txtUid = New System.Windows.Forms.TextBox()
Me.txtName = New System.Windows.Forms.TextBox()
Me.txtPwd = New System.Windows.Forms.TextBox()
Me.lblUidHint = New System.Windows.Forms.Label()
Me.lblNameHint = New System.Windows.Forms.Label()
Me.lblPwdHint = New System.Windows.Forms.Label()
Me.SuspendLayout()
'
'Label1
'
Me.Label1.Dock = System.Windows.Forms.DockStyle.Top
Me.Label1.Font = New System.Drawing.Font("微軟正黑體", 24.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.Label1.Location = New System.Drawing.Point(0, 0)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(384, 40)
Me.Label1.TabIndex = 0
Me.Label1.Text = "~ 助教帳號註冊 ~"
Me.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.Font = New System.Drawing.Font("新細明體", 14.0!)
Me.Label2.Location = New System.Drawing.Point(13, 65)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(66, 19)
Me.Label2.TabIndex = 1
Me.Label2.Text = "帳號:"
'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.Font = New System.Drawing.Font("新細明體", 14.0!)
Me.Label3.Location = New System.Drawing.Point(12, 84)
Me.Label3.Name = "Label3"
Me.Label3.Padding = New System.Windows.Forms.Padding(0, 30, 0, 0)
Me.Label3.Size = New System.Drawing.Size(66, 49)
Me.Label3.TabIndex = 2
Me.Label3.Text = "姓名:"
'
'Label4
'
Me.Label4.AutoSize = True
Me.Label4.Font = New System.Drawing.Font("新細明體", 14.0!)
Me.Label4.Location = New System.Drawing.Point(12, 133)
Me.Label4.Name = "Label4"
Me.Label4.Padding = New System.Windows.Forms.Padding(0, 30, 0, 0)
Me.Label4.Size = New System.Drawing.Size(66, 49)
Me.Label4.TabIndex = 3
Me.Label4.Text = "密碼:"
'
'btnCancel
'
Me.btnCancel.Cursor = System.Windows.Forms.Cursors.Hand
Me.btnCancel.Font = New System.Drawing.Font("新細明體", 14.0!)
Me.btnCancel.Location = New System.Drawing.Point(12, 212)
Me.btnCancel.Name = "btnCancel"
Me.btnCancel.Size = New System.Drawing.Size(130, 35)
Me.btnCancel.TabIndex = 4
Me.btnCancel.Text = "取消"
Me.btnCancel.UseVisualStyleBackColor = True
'
'btnSign
'
Me.btnSign.BackColor = System.Drawing.Color.FromArgb(CType(CType(128, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(128, Byte), Integer))
Me.btnSign.Cursor = System.Windows.Forms.Cursors.Hand
Me.btnSign.Font = New System.Drawing.Font("新細明體", 14.0!)
Me.btnSign.Location = New System.Drawing.Point(242, 212)
Me.btnSign.Name = "btnSign"
Me.btnSign.Size = New System.Drawing.Size(130, 35)
Me.btnSign.TabIndex = 5
Me.btnSign.Text = "確定註冊"
Me.btnSign.UseVisualStyleBackColor = False
'
'txtUid
'
Me.txtUid.BackColor = System.Drawing.SystemColors.ControlLight
Me.txtUid.Enabled = False
Me.txtUid.Font = New System.Drawing.Font("新細明體", 14.0!)
Me.txtUid.Location = New System.Drawing.Point(85, 58)
Me.txtUid.Name = "txtUid"
Me.txtUid.ReadOnly = True
Me.txtUid.Size = New System.Drawing.Size(287, 30)
Me.txtUid.TabIndex = 6
'
'txtName
'
Me.txtName.Font = New System.Drawing.Font("新細明體", 14.0!)
Me.txtName.Location = New System.Drawing.Point(84, 106)
Me.txtName.MaxLength = 10
Me.txtName.Name = "txtName"
Me.txtName.Size = New System.Drawing.Size(287, 30)
Me.txtName.TabIndex = 7
'
'txtPwd
'
Me.txtPwd.Font = New System.Drawing.Font("新細明體", 14.0!)
Me.txtPwd.Location = New System.Drawing.Point(84, 156)
Me.txtPwd.MaxLength = 20
Me.txtPwd.Name = "txtPwd"
Me.txtPwd.Size = New System.Drawing.Size(287, 30)
Me.txtPwd.TabIndex = 8
'
'lblUidHint
'
Me.lblUidHint.AutoSize = True
Me.lblUidHint.BackColor = System.Drawing.SystemColors.Info
Me.lblUidHint.Cursor = System.Windows.Forms.Cursors.IBeam
Me.lblUidHint.Font = New System.Drawing.Font("新細明體", 10.0!)
Me.lblUidHint.ForeColor = System.Drawing.SystemColors.GrayText
Me.lblUidHint.Location = New System.Drawing.Point(280, 66)
Me.lblUidHint.Name = "lblUidHint"
Me.lblUidHint.Size = New System.Drawing.Size(91, 14)
Me.lblUidHint.TabIndex = 9
Me.lblUidHint.Text = "系統自動編號"
'
'lblNameHint
'
Me.lblNameHint.AutoSize = True
Me.lblNameHint.BackColor = System.Drawing.Color.White
Me.lblNameHint.Cursor = System.Windows.Forms.Cursors.IBeam
Me.lblNameHint.Font = New System.Drawing.Font("新細明體", 10.0!)
Me.lblNameHint.ForeColor = System.Drawing.SystemColors.GrayText
Me.lblNameHint.Location = New System.Drawing.Point(94, 114)
Me.lblNameHint.Name = "lblNameHint"
Me.lblNameHint.Size = New System.Drawing.Size(133, 14)
Me.lblNameHint.TabIndex = 10
Me.lblNameHint.Text = "十個字以內助教姓名"
'
'lblPwdHint
'
Me.lblPwdHint.AutoSize = True
Me.lblPwdHint.BackColor = System.Drawing.Color.White
Me.lblPwdHint.Cursor = System.Windows.Forms.Cursors.IBeam
Me.lblPwdHint.Font = New System.Drawing.Font("新細明體", 10.0!)
Me.lblPwdHint.ForeColor = System.Drawing.SystemColors.GrayText
Me.lblPwdHint.Location = New System.Drawing.Point(94, 164)
Me.lblPwdHint.Name = "lblPwdHint"
Me.lblPwdHint.Size = New System.Drawing.Size(217, 14)
Me.lblPwdHint.TabIndex = 11
Me.lblPwdHint.Text = "英數字二十個字以內,區分大小寫"
'
'dlgSignUp
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 12.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.SystemColors.GradientActiveCaption
Me.ClientSize = New System.Drawing.Size(384, 262)
Me.ControlBox = False
Me.Controls.Add(Me.lblPwdHint)
Me.Controls.Add(Me.lblNameHint)
Me.Controls.Add(Me.lblUidHint)
Me.Controls.Add(Me.txtPwd)
Me.Controls.Add(Me.txtName)
Me.Controls.Add(Me.txtUid)
Me.Controls.Add(Me.btnSign)
Me.Controls.Add(Me.btnCancel)
Me.Controls.Add(Me.Label4)
Me.Controls.Add(Me.Label3)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.Label1)
Me.MaximumSize = New System.Drawing.Size(400, 278)
Me.MinimumSize = New System.Drawing.Size(400, 278)
Me.Name = "dlgSignUp"
Me.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.ShowInTaskbar = False
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents Label3 As System.Windows.Forms.Label
Friend WithEvents Label4 As System.Windows.Forms.Label
Friend WithEvents btnCancel As System.Windows.Forms.Button
Friend WithEvents btnSign As System.Windows.Forms.Button
Friend WithEvents txtUid As System.Windows.Forms.TextBox
Friend WithEvents txtName As System.Windows.Forms.TextBox
Friend WithEvents txtPwd As System.Windows.Forms.TextBox
Friend WithEvents lblUidHint As System.Windows.Forms.Label
Friend WithEvents lblNameHint As System.Windows.Forms.Label
Friend WithEvents lblPwdHint As System.Windows.Forms.Label
End Class
|
AuCourseHelper/AuCourseHelper_PC
|
Teacher/Forms/dlgSignUp.Designer.vb
|
Visual Basic
|
apache-2.0
| 9,565
|
'*******************************************************************************************'
' '
' Download Free Evaluation Version From: https://bytescout.com/download/web-installer '
' '
' Also available as Web API! Get free API Key https://app.pdf.co/signup '
' '
' Copyright © 2017-2020 ByteScout, Inc. All rights reserved. '
' https://www.bytescout.com '
' https://www.pdf.co '
'*******************************************************************************************'
' import bytescout screen capturing activex object
Imports BytescoutScreenCapturingLib
Module Module1
Sub Main(ByVal args As String())
' Create new Capturer object
Dim capturer As New Capturer
' Merge AVI files that were previously created by the ByteScout Screen Capturer (must be of same size, FPS and type)
capturer.JoinAVIFiles("Sample1.avi", "Sample2.avi", "output.avi")
Console.WriteLine("Files merged successfully!")
' Open output file with associated application
Process.Start("output.avi")
End Sub
End Module
|
bytescout/ByteScout-SDK-SourceCode
|
Screen Capturing SDK/VB.NET/Merge AVI Video Files/Module1.vb
|
Visual Basic
|
apache-2.0
| 1,556
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace System.Runtime.Analyzers
''' <summary>
''' CA1601: Do not use timers that prevent power state changes
''' </summary>
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Public NotInheritable Class BasicDoNotUseTimersThatPreventPowerStateChangesAnalyzer
Inherits DoNotUseTimersThatPreventPowerStateChangesAnalyzer
End Class
End Namespace
|
mattwar/roslyn-analyzers
|
src/System.Runtime.Analyzers/VisualBasic/BasicDoNotUseTimersThatPreventPowerStateChanges.vb
|
Visual Basic
|
apache-2.0
| 707
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class QuickChatStory
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.SuspendLayout()
'
'QuickChatStory
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(284, 261)
Me.Name = "QuickChatStory"
Me.Text = "QuickChatStory"
Me.ResumeLayout(False)
End Sub
End Class
|
TheUltimateHacker/ShiftOS
|
ShiftOS/QuickChatStory.Designer.vb
|
Visual Basic
|
apache-2.0
| 1,290
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("LAN_Hangman")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("LAN_Hangman")>
<Assembly: AssemblyCopyright("Copyright © 2010")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("afa9c846-649f-4bb3-ba3f-ab7aedb5d46b")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
niikoo/NProj
|
Windows/Skole/LAN_Hangman/LAN_Hangman/My Project/AssemblyInfo.vb
|
Visual Basic
|
apache-2.0
| 1,140
|
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel.DataAnnotations
Imports System.ComponentModel.DataAnnotations.Schema
Namespace Models
Public Class Department
Public Property DepartmentID As Integer
<StringLength(50, MinimumLength:=3)>
Public Property Name As String
<DataType(DataType.Currency)>
<Column(TypeName:="money")>
Public Property Budget As Decimal
<DataType(DataType.Date)>
<Display(Name:="Start Date")>
Public Property StartDate As DateTime
<Display(Name:="Administrator")>
Public Property InstructorID As Integer?
<Timestamp>
Public Property RowVersion As Byte()
Public Overridable Property Administrator As Instructor
Public Overridable Property Courses As ICollection(Of Course)
End Class
End Namespace
|
makani-kukini/Contoso-University
|
ContosoUniversity/Models/Department.vb
|
Visual Basic
|
bsd-3-clause
| 887
|
Option Strict Off
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.GenerateType
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateType
Partial Public Class GenerateTypeTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
#Region "Same Project"
#Region "SameProject SameFile"
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDefaultValues() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Class Program
Sub Main()
Dim f As [|$$Goo|]
End Sub
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Class Program
Sub Main()
Dim f As Goo
End Sub
End Class
Class Goo
End Class
</Text>.NormalizedValue,
isNewFile:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeInsideNamespace() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Class Program
Sub Main()
Dim f As [|A.Goo$$|]
End Sub
End Class
Namespace A
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Class Program
Sub Main()
Dim f As A.Goo
End Sub
End Class
Namespace A
Class Goo
End Class
End Namespace</Text>.NormalizedValue,
isNewFile:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeInsideQualifiedNamespace() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Class Program
Sub Main()
Dim f As A.B.Goo
End Sub
End Class
Namespace A.B
Class Goo
End Class
End Namespace</Text>.NormalizedValue,
isNewFile:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeWithinQualifiedNestedNamespace() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Class Program
Sub Main()
Dim f As [|A.B.C.Goo$$|]
End Sub
End Class
Namespace A.B
Namespace C
End Namespace
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Class Program
Sub Main()
Dim f As A.B.C.Goo
End Sub
End Class
Namespace A.B
Namespace C
Class Goo
End Class
End Namespace
End Namespace</Text>.NormalizedValue,
isNewFile:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeWithinNestedQualifiedNamespace() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Class Program
Sub Main()
Dim f As [|A.B.C.Goo$$|]
End Sub
End Class
Namespace A
Namespace B.C
End Namespace
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Class Program
Sub Main()
Dim f As A.B.C.Goo
End Sub
End Class
Namespace A
Namespace B.C
Class Goo
End Class
End Namespace
End Namespace</Text>.NormalizedValue,
isNewFile:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeWithConstructorMembers() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Class Program
Sub Main()
Dim f = New [|$$Goo|](bar:=1, baz:=2)
End Sub
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Class Program
Sub Main()
Dim f = New Goo(bar:=1, baz:=2)
End Sub
End Class
Class Goo
Private bar As Integer
Private baz As Integer
Public Sub New(bar As Integer, baz As Integer)
Me.bar = bar
Me.baz = baz
End Sub
End Class
</Text>.NormalizedValue,
isNewFile:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeWithBaseTypes() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Imports System.Collections.Generic
Class Program
Sub Main()
Dim f As List(Of Integer) = New [|$$Goo|]()
End Sub
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Imports System.Collections.Generic
Class Program
Sub Main()
Dim f As List(Of Integer) = New Goo()
End Sub
End Class
Class Goo
Inherits List(Of Integer)
End Class
</Text>.NormalizedValue,
isNewFile:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeWithPublicInterface() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Class Program
Sub Main()
Dim f As [|A.B.C.Goo$$|]
End Sub
End Class
Namespace A
Namespace B.C
End Namespace
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Class Program
Sub Main()
Dim f As A.B.C.Goo
End Sub
End Class
Namespace A
Namespace B.C
Public Interface Goo
End Interface
End Namespace
End Namespace</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeWithInternalStruct() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Class Program
Sub Main()
Dim f As [|A.B.C.Goo$$|]
End Sub
End Class
Namespace A
Namespace B.C
End Namespace
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Class Program
Sub Main()
Dim f As A.B.C.Goo
End Sub
End Class
Namespace A
Namespace B.C
Friend Structure Goo
End Structure
End Namespace
End Namespace</Text>.NormalizedValue,
accessibility:=Accessibility.Friend,
typeKind:=TypeKind.Structure,
isNewFile:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeWithDefaultEnum() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A
Namespace B
End Namespace
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Class Program
Sub Main()
Dim f As A.B.Goo
End Sub
End Class
Namespace A
Namespace B
Enum Goo
End Enum
End Namespace
End Namespace</Text>.NormalizedValue,
accessibility:=Accessibility.NotApplicable,
typeKind:=TypeKind.Enum,
isNewFile:=False)
End Function
#End Region
#Region "SameProject ExistingFile"
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeInExistingEmptyFile() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true">
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
<Document FilePath="Test2.vb">
</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Namespace A.B
Public Interface Goo
End Interface
End Namespace
</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=False,
existingFilename:="Test2.vb")
End Function
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeInExistingEmptyFile_Usings_Folders() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true">
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|Goo$$|]
End Sub
End Class</Document>
<Document Folders="outer\inner" FilePath="Test2.vb">
</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Namespace outer.inner
Public Interface Goo
End Interface
End Namespace
</Text>.NormalizedValue,
checkIfUsingsIncluded:=True,
expectedTextWithUsings:=<Text>
Imports outer.inner
Class Program
Sub Main()
Dim f As Goo
End Sub
End Class</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=False,
existingFilename:="Test2.vb")
End Function
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeInExistingEmptyFile_NoUsings_Folders_NotSimpleName() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true">
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
<Document FilePath="Test2.vb" Folders="outer\inner">
</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Namespace A.B
Public Interface Goo
End Interface
End Namespace
</Text>.NormalizedValue,
checkIfUsingsNotIncluded:=True,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=False,
existingFilename:="Test2.vb")
End Function
#End Region
#Region "SameProject NewFile"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeInNewFile() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true">
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Namespace A.B
Public Interface Goo
End Interface
End Namespace
</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=True,
newFileFolderContainers:=ImmutableArray(Of String).Empty,
newFileName:="Test2.vb")
End Function
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_UsingsNotNeeded_InNewFile_InFolder() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true">
<Document FilePath="Test1.vb">
Namespace outer
Namespace inner
Class Program
Sub Main()
Dim f As [|Goo$$|]
End Sub
End Class
End Namespace
End Namespace</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Namespace outer.inner
Public Interface Goo
End Interface
End Namespace
</Text>.NormalizedValue,
checkIfUsingsNotIncluded:=True,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=True,
newFileFolderContainers:=ImmutableArray.Create("outer", "inner"),
newFileName:="Test2.vb")
End Function
<WorkItem(898452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/898452")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_InValidFolderNameNotMadeNamespace() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true">
<Document FilePath="Test1.vb">
Namespace outer
Namespace inner
Class Program
Sub Main()
Dim f As [|Goo$$|]
End Sub
End Class
End Namespace
End Namespace</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Public Interface Goo
End Interface
</Text>.NormalizedValue,
checkIfUsingsNotIncluded:=True,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=True,
newFileFolderContainers:=ImmutableArray.Create("@@@@@", "#####"),
areFoldersValidIdentifiers:=False,
newFileName:="Test2.vb")
End Function
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<WorkItem(907454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907454")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_UsingsNeeded_InNewFile_InFolder() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true">
<CompilationOptions RootNamespace="BarBaz"/>
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|$$Goo|]
End Sub
End Class</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Namespace outer.inner
Public Interface Goo
End Interface
End Namespace
</Text>.NormalizedValue,
checkIfUsingsIncluded:=True,
expectedTextWithUsings:=<Text>
Imports BarBaz.outer.inner
Class Program
Sub Main()
Dim f As Goo
End Sub
End Class</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=True,
newFileFolderContainers:=ImmutableArray.Create("outer", "inner"),
newFileName:="Test2.vb")
End Function
<WorkItem(907454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907454")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_UsingsPresentAlready_InNewFile_InFolder() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true">
<CompilationOptions RootNamespace="BarBaz"/>
<Document FilePath="Test1.vb" Folders="outer">
Imports BarBaz.outer
Class Program
Sub Main()
Dim f As [|$$Goo|]
End Sub
End Class</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Namespace outer
Public Interface Goo
End Interface
End Namespace
</Text>.NormalizedValue,
checkIfUsingsIncluded:=True,
expectedTextWithUsings:=<Text>
Imports BarBaz.outer
Class Program
Sub Main()
Dim f As Goo
End Sub
End Class</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=True,
newFileFolderContainers:=ImmutableArray.Create("outer"),
newFileName:="Test2.vb")
End Function
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_UsingsNotNeeded_InNewFile_InFolder_NotSimpleName() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true">
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Namespace A.B
Public Interface Goo
End Interface
End Namespace
</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=True,
newFileFolderContainers:=ImmutableArray.Create("outer", "inner"),
newFileName:="Test2.vb")
End Function
#End Region
#End Region
#Region "SameLanguage DifferentProject"
#Region "SameLanguage DifferentProject ExistingFile"
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoSameLanguageDifferentProjectEmptyFile() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<Document FilePath="Test2.vb">
</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Namespace Global.A.B
Public Interface Goo
End Interface
End Namespace
</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=False,
existingFilename:="Test2.vb",
projectName:="Assembly2")
End Function
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoSameLanguageDifferentProjectExistingFile() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<CompilationOptions RootNamespace="BarBaz"/>
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<CompilationOptions RootNamespace="Zoozoo"/>
<Document FilePath="Test2.vb" Folders="outer\inner">Namespace Global.BarBaz.A
Namespace B
End Namespace
End Namespace</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Namespace Global.BarBaz.A
Namespace B
Public Interface Goo
End Interface
End Namespace
End Namespace</Text>.NormalizedValue,
checkIfUsingsNotIncluded:=True,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=False,
existingFilename:="Test2.vb",
projectName:="Assembly2")
End Function
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoSameLanguageDifferentProjectExistingFile_Usings_Folders() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<CompilationOptions RootNamespace="BarBaz"/>
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<CompilationOptions RootNamespace="Zoozoo"/>
<Document FilePath="Test2.vb" Folders="outer\inner">Namespace A
Namespace B
End Namespace
End Namespace</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Namespace A
Namespace B
End Namespace
End Namespace
Namespace outer.inner
Public Interface Goo
End Interface
End Namespace
</Text>.NormalizedValue,
checkIfUsingsIncluded:=True,
expectedTextWithUsings:=<Text>
Imports Zoozoo.outer.inner
Class Program
Sub Main()
Dim f As Goo
End Sub
End Class
Namespace A.B
End Namespace</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=False,
existingFilename:="Test2.vb",
projectName:="Assembly2")
End Function
#End Region
#Region "SameLanguage DifferentProject NewFile"
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoSameLanguageDifferentProjectNewFile() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<CompilationOptions RootNamespace="BarBaz"/>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Namespace Global.A.B
Public Interface Goo
End Interface
End Namespace
</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=True,
newFileName:="Test2.vb",
newFileFolderContainers:=ImmutableArray(Of String).Empty,
projectName:="Assembly2")
End Function
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_Usings() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<CompilationOptions RootNamespace="BarBaz"/>
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|Goo$$|]
End Sub
End Class</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<CompilationOptions RootNamespace="Zoozoo"/>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Namespace outer.inner
Public Interface Goo
End Interface
End Namespace
</Text>.NormalizedValue,
checkIfUsingsIncluded:=True,
expectedTextWithUsings:=<Text>
Imports Zoozoo.outer.inner
Class Program
Sub Main()
Dim f As Goo
End Sub
End Class</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=True,
newFileName:="Test2.vb",
newFileFolderContainers:=ImmutableArray.Create("outer", "inner"),
projectName:="Assembly2")
End Function
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_NoUsings_NotSimpleName() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<CompilationOptions RootNamespace="BarBaz"/>
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<CompilationOptions RootNamespace="Zoozoo"/>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Namespace Global.BarBaz.A.B
Public Interface Goo
End Interface
End Namespace
</Text>.NormalizedValue,
checkIfUsingsNotIncluded:=True,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=True,
newFileName:="Test2.vb",
newFileFolderContainers:=ImmutableArray(Of String).Empty,
projectName:="Assembly2")
End Function
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_NoUsings_NotSimpleName_ProjectReference() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<CompilationOptions RootNamespace="Zoozoo"/>
<Document FilePath="Test2.vb">
Namespace A.B
Public Class Bar
End Class
End Namespace</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<CompilationOptions RootNamespace="BarBaz"/>
<ProjectReference>Assembly2</ProjectReference>
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|Zoozoo.A.B.Goo$$|]
End Sub
End Class</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Namespace A.B
Public Interface Goo
End Interface
End Namespace
</Text>.NormalizedValue,
checkIfUsingsNotIncluded:=False,
expectedTextWithUsings:=<Text></Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
isNewFile:=True,
newFileName:="Test3.vb",
newFileFolderContainers:=ImmutableArray(Of String).Empty,
projectName:="Assembly2")
End Function
#End Region
#End Region
#Region "Different Language"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoDifferentLanguageNewFile() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
</Project>
<Project Language="C#" AssemblyName="Assembly2" CommonReferences="true">
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>namespace A.B
{
public class Goo
{
}
}</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
isNewFile:=True,
newFileName:="Test2.cs",
newFileFolderContainers:=ImmutableArray(Of String).Empty,
projectName:="Assembly2")
End Function
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoDifferentLanguageNewFile_Folders_Imports() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<CompilationOptions RootNamespace="BarBaz"/>
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
</Project>
<Project Language="C#" AssemblyName="Assembly2" CommonReferences="true">
<CompilationOptions RootNamespace="Zoozoo"/>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>namespace outer.inner
{
public class Goo
{
}
}</Text>.NormalizedValue,
checkIfUsingsIncluded:=True,
expectedTextWithUsings:=<Text>
Imports outer.inner
Class Program
Sub Main()
Dim f As Goo
End Sub
End Class
Namespace A.B
End Namespace</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
isNewFile:=True,
newFileName:="Test2.cs",
newFileFolderContainers:=ImmutableArray.Create("outer", "inner"),
projectName:="Assembly2")
End Function
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoDifferentLanguageNewFile_Folders_NoImports_NotSimpleName() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
</Project>
<Project Language="C#" AssemblyName="Assembly2" CommonReferences="true">
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>namespace A.B
{
public class Goo
{
}
}</Text>.NormalizedValue,
checkIfUsingsNotIncluded:=True,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
isNewFile:=True,
newFileName:="Test2.cs",
newFileFolderContainers:=ImmutableArray.Create("outer", "inner"),
projectName:="Assembly2")
End Function
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoDifferentLanguageNewFile_Folders_Imports_DefaultNamespace() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<CompilationOptions RootNamespace="BarBaz"/>
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
</Project>
<Project Language="C#" AssemblyName="Assembly2" CommonReferences="true">
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>namespace ConsoleApplication.outer.inner
{
public class Goo
{
}
}</Text>.NormalizedValue,
defaultNamespace:="ConsoleApplication",
checkIfUsingsIncluded:=True,
expectedTextWithUsings:=<Text>
Imports ConsoleApplication.outer.inner
Class Program
Sub Main()
Dim f As Goo
End Sub
End Class
Namespace A.B
End Namespace</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
isNewFile:=True,
newFileName:="Test2.cs",
newFileFolderContainers:=ImmutableArray.Create("outer", "inner"),
projectName:="Assembly2")
End Function
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoDifferentLanguageNewFile_Folders_NoImports_NotSimpleName_DefaultNamespace() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<CompilationOptions RootNamespace="BarBaz"/>
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
</Project>
<Project Language="C#" AssemblyName="Assembly2" CommonReferences="true">
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>namespace BarBaz.A.B
{
public class Goo
{
}
}</Text>.NormalizedValue,
defaultNamespace:="ConsoleApplication",
checkIfUsingsNotIncluded:=True,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
isNewFile:=True,
newFileName:="Test2.cs",
newFileFolderContainers:=ImmutableArray.Create("outer", "inner"),
projectName:="Assembly2")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoDifferentLanguageExistingEmptyFile() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
</Project>
<Project Language="C#" AssemblyName="Assembly2" CommonReferences="true">
<Document Folders="outer\inner" FilePath="Test2.cs">
</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>namespace A.B
{
public class Goo
{
}
}</Text>.NormalizedValue,
checkIfUsingsNotIncluded:=True,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
isNewFile:=False,
existingFilename:="Test2.cs",
projectName:="Assembly2")
End Function
<WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoDifferentLanguageExistingEmptyFile_Imports_Folder() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|Goo$$|]
End Sub
End Class</Document>
</Project>
<Project Language="C#" AssemblyName="Assembly2" CommonReferences="true">
<Document Folders="outer\inner" FilePath="Test2.cs">
</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>namespace outer.inner
{
public class Goo
{
}
}</Text>.NormalizedValue,
checkIfUsingsIncluded:=True,
expectedTextWithUsings:=<Text>
Imports outer.inner
Class Program
Sub Main()
Dim f As Goo
End Sub
End Class</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
isNewFile:=False,
existingFilename:="Test2.cs",
projectName:="Assembly2")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoDifferentLanguageExistingNonEmptyFile() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
</Project>
<Project Language="C#" AssemblyName="Assembly2" CommonReferences="true">
<Document FilePath="Test2.cs">
namespace A
{
}</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>
namespace A
{
}
namespace A.B
{
public class Goo
{
}
}</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
isNewFile:=False,
existingFilename:="Test2.cs",
projectName:="Assembly2")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoDifferentLanguageExistingTargetFile() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
</Project>
<Project Language="C#" AssemblyName="Assembly2" CommonReferences="true">
<Document FilePath="Test2.cs">namespace A
{
namespace B
{
}
}</Document>
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>namespace A
{
namespace B
{
public class Goo
{
}
}
}</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
isNewFile:=False,
existingFilename:="Test2.cs",
projectName:="Assembly2")
End Function
<WorkItem(858826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858826")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeIntoDifferentLanguageNewFileAdjustTheFileExtension() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|A.B.Goo$$|]
End Sub
End Class
Namespace A.B
End Namespace</Document>
</Project>
<Project Language="C#" AssemblyName="Assembly2" CommonReferences="true">
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>namespace A.B
{
public class Goo
{
}
}</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
isNewFile:=True,
newFileName:="Test2.cs",
newFileFolderContainers:=ImmutableArray(Of String).Empty,
projectName:="Assembly2")
End Function
#End Region
#Region "Bugfix"
<WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")>
<WorkItem(873066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/873066")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeWithProperAccessibilityAndTypeKind_1() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Public Class C
Implements [|$$D|]
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="D",
expected:=<Text>Public Class C
Implements D
End Class
Public Interface D
End Interface
</Text>.NormalizedValue,
isNewFile:=False,
typeKind:=TypeKind.Interface,
accessibility:=Accessibility.Public,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Interface))
End Function
<WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeWithProperAccessibilityAndTypeKind_2() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Public Class CC
Inherits [|$$DD|]
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="DD",
expected:=<Text>Public Class CC
Inherits DD
End Class
Class DD
End Class
</Text>.NormalizedValue,
isNewFile:=False,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Class))
End Function
<WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeWithProperAccessibilityAndTypeKind_3() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Public Interface CCC
Inherits [|$$DDD|]
End Interface</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="DDD",
expected:=<Text>Public Interface CCC
Inherits DDD
End Interface
Interface DDD
End Interface
</Text>.NormalizedValue,
isNewFile:=False,
typeKind:=TypeKind.Interface,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Interface))
End Function
<WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeWithProperAccessibilityAndTypeKind_4() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Public Structure CCC
Implements [|$$DDD|]
End Structure</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="DDD",
expected:=<Text>Public Structure CCC
Implements DDD
End Structure
Public Interface DDD
End Interface
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Interface,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Interface))
End Function
<WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")>
<WorkItem(869593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/869593")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeWithModuleOption() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim s as [|$$A.B.C|]
End Sub
End Module
Namespace A
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="B",
expected:=<Text>Module Program
Sub Main(args As String())
Dim s as A.B.C
End Sub
End Module
Namespace A
Module B
End Module
End Namespace</Text>.NormalizedValue,
isNewFile:=False,
typeKind:=TypeKind.Module,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module))
End Function
<WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeInMemberAccessExpression() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim s = [|$$A.B|]
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="A",
expected:=<Text>Module Program
Sub Main(args As String())
Dim s = A.B
End Sub
End Module
Public Module A
End Module
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Module,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.MemberAccessWithNamespace))
End Function
<WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeInMemberAccessExpressionWithNamespace() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Namespace A
Module Program
Sub Main(args As String())
Dim s = [|$$A.B.C|]
End Sub
End Module
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="B",
expected:=<Text>Namespace A
Module Program
Sub Main(args As String())
Dim s = A.B.C
End Sub
End Module
Public Module B
End Module
End Namespace</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Module,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.MemberAccessWithNamespace))
End Function
<WorkItem(876202, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876202")>
<WorkItem(883531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883531")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_NoParameterLessConstructor() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim s = new [|$$Goo|]()
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="B",
expected:=<Text>Module Program
Sub Main(args As String())
Dim s = new Goo()
End Sub
End Module
Public Structure B
End Structure
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Structure,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure))
End Function
<WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeWithoutEnumForGenericsInMemberAccessExpression() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim s = [|$$Goo(Of Bar).D|]
End Sub
End Module
Class Bar
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Module Program
Sub Main(args As String())
Dim s = Goo(Of Bar).D
End Sub
End Module
Class Bar
End Class
Public Class Goo(Of T)
End Class
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure))
End Function
<WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeWithoutEnumForGenericsInNameContext() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim s As [|$$Goo(Of Bar)|]
End Sub
End Module
Class Bar
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Module Program
Sub Main(args As String())
Dim s As Goo(Of Bar)
End Sub
End Module
Class Bar
End Class
Public Class Goo(Of T)
End Class
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Interface Or TypeKindOptions.Delegate))
End Function
<WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeInMemberAccessWithNSForModule() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim s = [|$$Goo.Bar|].Baz
End Sub
End Module
Namespace Goo
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Bar",
expected:=<Text>Module Program
Sub Main(args As String())
Dim s = Goo.Bar.Baz
End Sub
End Module
Namespace Goo
Public Class Bar
End Class
End Namespace</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.MemberAccessWithNamespace))
End Function
<WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeInMemberAccessWithGlobalNSForModule() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim s = [|$$Bar|].Baz
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Bar",
expected:=<Text>Module Program
Sub Main(args As String())
Dim s = Bar.Baz
End Sub
End Module
Public Class Bar
End Class
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.MemberAccessWithNamespace))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeInMemberAccessWithoutNS() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim s = [|$$Bar|].Baz
End Sub
End Module
Namespace Bar
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Bar",
isMissing:=True)
End Function
#End Region
#Region "Delegates"
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegateFromObjectCreationExpression() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim s = New [|$$MyD|](AddressOf goo)
End Sub
Sub goo()
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim s = New MyD(AddressOf goo)
End Sub
Sub goo()
End Sub
End Module
Public Delegate Sub MyD()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegateFromObjectCreationExpressionIntoNamespace() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim goo = New NS.[|$$MyD|](Sub()
End Sub)
End Sub
End Module
Namespace NS
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim goo = New NS.MyD(Sub()
End Sub)
End Sub
End Module
Namespace NS
Public Delegate Sub MyD()
End Namespace</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegateFromObjectCreationExpression_1() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim goo = New [|$$NS.MyD|](Function(n) n)
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim goo = New NS.MyD(Function(n) n)
End Sub
End Module
Namespace NS
Public Delegate Function MyD(n As Object) As Object
End Namespace
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegateFromObjectCreationExpression_2() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim goo = New [|$$MyD|](Sub() System.Console.WriteLine(1))
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim goo = New MyD(Sub() System.Console.WriteLine(1))
End Sub
End Module
Public Delegate Sub MyD()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegateFromObjectCreationExpression_3() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim goo = New [|$$MyD|](Function(n As Integer)
Return n + n
End Function)
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim goo = New MyD(Function(n As Integer)
Return n + n
End Function)
End Sub
End Module
Public Delegate Function MyD(n As Integer) As Integer
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegateAddressOfExpression() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim bar As [|$$MyD(Of Integer)|] = AddressOf goo(Of Integer)
End Sub
Public Sub goo(Of T)()
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim bar As MyD(Of Integer) = AddressOf goo(Of Integer)
End Sub
Public Sub goo(Of T)()
End Sub
End Module
Public Delegate Sub MyD(Of T)()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Interface Or TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegateAddressOfExpressionWrongTypeArgument_1() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim bar As [|$$MyD|] = AddressOf goo(Of Integer)
End Sub
Public Sub goo(Of T)()
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim bar As MyD = AddressOf goo(Of Integer)
End Sub
Public Sub goo(Of T)()
End Sub
End Module
Public Delegate Sub MyD(Of T)()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegateAddressOfExpressionWrongTypeArgument_2() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim bar As [|$$MyD|] = AddressOf goo
End Sub
Public Sub goo(Of T)()
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim bar As MyD = AddressOf goo
End Sub
Public Sub goo(Of T)()
End Sub
End Module
Public Delegate Sub MyD(Of T)()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegateAddressOfExpressionWrongTypeArgument_3() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim bar As [|$$MyD|] = AddressOf goo
End Sub
Public Sub goo(Of T)()
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim bar As MyD = AddressOf goo
End Sub
Public Sub goo(Of T)()
End Sub
End Module
Public Delegate Sub MyD(Of T)()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegateWithNoInitializer() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim bar As [|$$MyD|]
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim bar As MyD
End Sub
End Module
Public Delegate Sub MyD()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegateWithLambda_MultiLineFunction() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim bar As [|$$MyD|] = Function()
Return 0
End Function
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim bar As MyD = Function()
Return 0
End Function
End Sub
End Module
Public Delegate Function MyD() As Integer
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegateWithLambda_SingleLineFunction() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim a As [|$$MyD|] = Function(n As Integer) ""
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim a As MyD = Function(n As Integer) ""
End Sub
End Module
Public Delegate Function MyD(n As Integer) As String
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegateWithLambda_MultiLineSub() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim bar As [|$$MyD|] = Sub()
End Sub
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim bar As MyD = Sub()
End Sub
End Sub
End Module
Public Delegate Sub MyD()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegateWithLambda_SingleLineSub() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim a As [|$$MyD|] = Sub(n As Double) Console.WriteLine(0)
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim a As MyD = Sub(n As Double) Console.WriteLine(0)
End Sub
End Module
Public Delegate Sub MyD(n As Double)
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegateWithCast() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim bar = DirectCast(AddressOf goo, [|$$MyD|])
End Sub
Public Sub goo()
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim bar = DirectCast(AddressOf goo, MyD)
End Sub
Public Sub goo()
End Sub
End Module
Public Delegate Sub MyD()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegateWithCastAndError() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim bar = DirectCast(AddressOf goo, [|$$MyD|])
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim bar = DirectCast(AddressOf goo, MyD)
End Sub
End Module
Public Delegate Sub MyD()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateDelegateTypeIntoDifferentLanguageNewFile() As Task
Dim markupString = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document FilePath="Test1.vb">
Module Program
Sub Main(args As String())
Dim gooGoo = DirectCast(AddressOf Main, [|$$Bar|])
End Sub
End Module</Document>
</Project>
<Project Language="C#" AssemblyName="Assembly2" CommonReferences="true">
</Project>
</Workspace>.ToString()
Await TestWithMockedGenerateTypeDialog(
initial:=markupString,
languageName:=LanguageNames.VisualBasic,
typeName:="Bar",
expected:=<Text>public delegate void Bar(string[] args);
</Text>.NormalizedValue,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
isNewFile:=True,
newFileName:="Test2.cs",
newFileFolderContainers:=ImmutableArray(Of String).Empty,
projectName:="Assembly2")
End Function
<WorkItem(860210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860210")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateTypeDelegate_NoInfo() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim s as [|$$MyD(Of Integer)|]
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="MyD",
expected:=<Text>Module Program
Sub Main(args As String())
Dim s as MyD(Of Integer)
End Sub
End Module
Public Delegate Sub MyD(Of T)()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate)
End Function
#End Region
#Region "Dev12Filtering"
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Invocation_NoEnum_0() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim a = [|$$Baz.Goo|].Bar()
End Sub
End Module
Namespace Baz
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Module Program
Sub Main(args As String())
Dim a = Baz.Goo.Bar()
End Sub
End Module
Namespace Baz
Public Class Goo
End Class
End Namespace</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum})
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Invocation_NoEnum_1() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Module Program
Sub Main(args As String())
Dim a = [|$$Goo.Bar|]()
End Sub
End Module</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Bar",
expected:=<Text>Module Program
Sub Main(args As String())
Dim a = Goo.Bar()
End Sub
End Module
Public Class Bar
End Class
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum})
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Invocation_NoEnum_2() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Class C
Custom Event E As Action
AddHandler(value As [|$$Goo|])
End AddHandler
RemoveHandler(value As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Class C
Custom Event E As Action
AddHandler(value As Goo)
End AddHandler
RemoveHandler(value As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
Public Delegate Sub Goo()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertTypeKindPresent:=New TypeKindOptions() {TypeKindOptions.Delegate},
assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum})
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Invocation_NoEnum_3() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Class C
Custom Event E As Action
AddHandler(value As Action)
End AddHandler
RemoveHandler(value As [|$$Goo|])
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>Class C
Custom Event E As Action
AddHandler(value As Action)
End AddHandler
RemoveHandler(value As Goo)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
Public Delegate Sub Goo()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertTypeKindPresent:=New TypeKindOptions() {TypeKindOptions.Delegate},
assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum})
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Invocation_NoEnum_4() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>Imports System
Module Program
Sub Main(args As String())
Dim s As Action = AddressOf [|NS.Bar$$|].Method
End Sub
End Module
Namespace NS
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Bar",
expected:=<Text>Imports System
Module Program
Sub Main(args As String())
Dim s As Action = AddressOf NS.Bar.Method
End Sub
End Module
Namespace NS
Public Class Bar
End Class
End Namespace</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum})
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_TypeConstraint_1() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>
Public Class Goo(Of T As [|$$Bar|])
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Bar",
expected:=<Text>
Public Class Goo(Of T As Bar)
End Class
Public Class Bar
End Class
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.BaseList))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_TypeConstraint_2() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>
Class Outer
Public Class Goo(Of T As [|$$Bar|])
End Class
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Bar",
expected:=<Text>
Class Outer
Public Class Goo(Of T As Bar)
End Class
End Class
Public Class Bar
End Class
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_TypeConstraint_3() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>
Public Class OuterOuter
Public Class Outer
Public Class Goo(Of T As [|$$Bar|])
End Class
End Class
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Bar",
expected:=<Text>
Public Class OuterOuter
Public Class Outer
Public Class Goo(Of T As Bar)
End Class
End Class
End Class
Public Class Bar
End Class
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.BaseList))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Event_1() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>
Class C1
Custom Event E As [|$$Goo|]
AddHandler(value As Goo)
End AddHandler
RemoveHandler(value As Goo)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>
Class C1
Custom Event E As Goo
AddHandler(value As Goo)
End AddHandler
RemoveHandler(value As Goo)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
Public Delegate Sub Goo()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Event_2() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>
Class C1
Custom Event E As [|$$NS.Goo|]
AddHandler(value As Goo)
End AddHandler
RemoveHandler(value As Goo)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>
Class C1
Custom Event E As NS.Goo
AddHandler(value As Goo)
End AddHandler
RemoveHandler(value As Goo)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
Namespace NS
Public Delegate Sub Goo()
End Namespace
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Event_3() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>
Class C1
Custom Event E As [|$$NS.Goo.MyDel|]
AddHandler(value As Goo)
End AddHandler
RemoveHandler(value As Goo)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
Namespace NS
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Goo",
expected:=<Text>
Class C1
Custom Event E As NS.Goo.MyDel
AddHandler(value As Goo)
End AddHandler
RemoveHandler(value As Goo)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
Namespace NS
Public Class Goo
End Class
End Namespace</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Event_4() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>
Class Goo
Public Event F As [|$$Bar|]
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Bar",
expected:=<Text>
Class Goo
Public Event F As Bar
End Class
Public Delegate Sub Bar()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Event_5() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>
Class Goo
Public Event F As [|$$NS.Bar|]
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Bar",
expected:=<Text>
Class Goo
Public Event F As NS.Bar
End Class
Namespace NS
Public Delegate Sub Bar()
End Namespace
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Event_6() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>
Class Goo
Public Event F As [|$$NS.Bar.MyDel|]
End Class
Namespace NS
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Bar",
expected:=<Text>
Class Goo
Public Event F As NS.Bar.MyDel
End Class
Namespace NS
Public Class Bar
End Class
End Namespace</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Event_7() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>
Class Bar
Public WithEvents G As [|$$Delegate1|]
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Delegate1",
expected:=<Text>
Class Bar
Public WithEvents G As Delegate1
End Class
Public Class Delegate1
End Class
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Event_8() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>
Class Bar
Public WithEvents G As [|$$NS.Delegate1|]
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Delegate1",
expected:=<Text>
Class Bar
Public WithEvents G As NS.Delegate1
End Class
Namespace NS
Public Class Delegate1
End Class
End Namespace
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Event_9() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>
Class Bar
Public WithEvents G As [|$$NS.Delegate1.MyDel|]
End Class
Namespace NS
End Namespace</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Delegate1",
expected:=<Text>
Class Bar
Public WithEvents G As NS.Delegate1.MyDel
End Class
Namespace NS
Public Class Delegate1
End Class
End Namespace</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Event_10() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>
Class Baz
Public Class Goo
Public Event F As [|$$Bar|]
End Class
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Bar",
expected:=<Text>
Class Baz
Public Class Goo
Public Event F As Bar
End Class
End Class
Public Delegate Sub Bar()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Event_11() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>
Public Class Baz
Public Class Goo
Public Event F As [|$$Bar|]
End Class
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Bar",
expected:=<Text>
Public Class Baz
Public Class Goo
Public Event F As Bar
End Class
End Class
Public Delegate Sub Bar()
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Delegate,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Delegate))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Event_12() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>
Class Baz
Public Class Bar
Public WithEvents G As [|$$Delegate1|]
End Class
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Delegate1",
expected:=<Text>
Class Baz
Public Class Bar
Public WithEvents G As Delegate1
End Class
End Class
Public Class Delegate1
End Class
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function GenerateType_Event_13() As Task
Await TestWithMockedGenerateTypeDialog(
initial:=<Text>
Public Class Baz
Public Class Bar
Public WithEvents G As [|$$Delegate1|]
End Class
End Class</Text>.NormalizedValue,
languageName:=LanguageNames.VisualBasic,
typeName:="Delegate1",
expected:=<Text>
Public Class Baz
Public Class Bar
Public WithEvents G As Delegate1
End Class
End Class
Public Class Delegate1
End Class
</Text>.NormalizedValue,
isNewFile:=False,
accessibility:=Accessibility.Public,
typeKind:=TypeKind.Class,
assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.BaseList))
End Function
#End Region
End Class
End Namespace
|
abock/roslyn
|
src/EditorFeatures/VisualBasicTest/Diagnostics/GenerateType/GenerateTypeTests_Dialog.vb
|
Visual Basic
|
mit
| 91,028
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Public Class DeterministicTests
Inherits BasicTestBase
Private Function GetBytesEmitted(source As String, platform As Platform, debug As Boolean) As ImmutableArray(Of Byte)
Dim options = If(debug, TestOptions.DebugExe, TestOptions.ReleaseExe).WithPlatform(platform)
options = options.WithFeatures({"dEtErmInIstIc"}.AsImmutable()) ' expect case-insensitivity
Dim compilation = CreateCompilationWithMscorlib({source}, assemblyName:="DeterminismTest", options:=options)
' The resolution of the PE header time date stamp is seconds, and we want to make sure
' that has an opportunity to change between calls to Emit.
Thread.Sleep(TimeSpan.FromSeconds(1))
Return compilation.EmitToArray()
End Function
<Fact>
Public Sub CompareAllBytesEmitted_Release()
Dim source =
"Class Program
Shared Sub Main()
End Sub
End Class"
Dim result1 = GetBytesEmitted(source, platform:=Platform.AnyCpu32BitPreferred, debug:=False)
Dim result2 = GetBytesEmitted(source, platform:=Platform.AnyCpu32BitPreferred, debug:=False)
AssertEx.Equal(result1, result2)
Dim result3 = GetBytesEmitted(source, platform:=Platform.X64, debug:=False)
Dim result4 = GetBytesEmitted(source, platform:=Platform.X64, debug:=False)
AssertEx.Equal(result3, result4)
End Sub
<Fact, WorkItem(926)>
Public Sub CompareAllBytesEmitted_Debug()
Dim source =
"Class Program
Shared Sub Main()
End Sub
End Class"
Dim result1 = GetBytesEmitted(source, platform:=Platform.AnyCpu32BitPreferred, debug:=True)
Dim result2 = GetBytesEmitted(source, platform:=Platform.AnyCpu32BitPreferred, debug:=True)
AssertEx.Equal(result1, result2)
Dim result3 = GetBytesEmitted(source, platform:=Platform.X64, debug:=True)
Dim result4 = GetBytesEmitted(source, platform:=Platform.X64, debug:=True)
AssertEx.Equal(result3, result4)
End Sub
End Class
End Namespace
|
paladique/roslyn
|
src/Compilers/VisualBasic/Test/Emit/Emit/DeterministicTests.vb
|
Visual Basic
|
apache-2.0
| 2,556
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting
Public Class WithBlockHighlighterTests
Inherits AbstractVisualBasicKeywordHighlighterTests
Friend Overrides Function CreateHighlighter() As IHighlighter
Return New WithBlockHighlighter()
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Sub TestWithBlock1()
Test(<Text>
Class C
Sub M()
{|Cursor:[|With|]|} y
.x = 10
Console.WriteLine(.x)
[|End With|]
End Sub
End Class</Text>)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Sub TestWithBlock2()
Test(<Text>
Class C
Sub M()
[|With|] y
.x = 10
Console.WriteLine(.x)
{|Cursor:[|End With|]|}
End Sub
End Class</Text>)
End Sub
End Class
End Namespace
|
jbhensley/roslyn
|
src/EditorFeatures/VisualBasicTest/KeywordHighlighting/WithBlockHighlighterTests.vb
|
Visual Basic
|
apache-2.0
| 1,107
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
''' <summary>
''' Represents a reference to a generic type instantiation that is nested in a non-generic type.
''' e.g. A.B{int}
''' </summary>
Friend NotInheritable Class GenericNestedTypeInstanceReference
Inherits GenericTypeInstanceReference
Implements Cci.INestedTypeReference
Public Sub New(underlyingNamedType As NamedTypeSymbol)
MyBase.New(underlyingNamedType)
End Sub
Private Function ITypeMemberReferenceGetContainingType(context As EmitContext) As Cci.ITypeReference Implements Cci.ITypeMemberReference.GetContainingType
Return (DirectCast(context.Module, PEModuleBuilder)).Translate(m_UnderlyingNamedType.ContainingType, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics)
End Function
Public Overrides ReadOnly Property AsGenericTypeInstanceReference As Cci.IGenericTypeInstanceReference
Get
Return Me
End Get
End Property
Public Overrides ReadOnly Property AsNamespaceTypeReference As Cci.INamespaceTypeReference
Get
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property AsNestedTypeReference As Cci.INestedTypeReference
Get
Return Me
End Get
End Property
Public Overrides ReadOnly Property AsSpecializedNestedTypeReference As Cci.ISpecializedNestedTypeReference
Get
Return Nothing
End Get
End Property
End Class
End Namespace
|
mavasani/roslyn
|
src/Compilers/VisualBasic/Portable/Emit/GenericNestedTypeInstanceReference.vb
|
Visual Basic
|
mit
| 1,978
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Globalization
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.ComponentModelHost
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ObjectBrowser
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ObjectBrowser.VisualBasic
Public Class ObjectBrowserTests
Inherits AbstractObjectBrowserTests
Protected Overrides ReadOnly Property LanguageName As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
Friend Overrides Function CreateLibraryManager(serviceProvider As IServiceProvider, componentModel As IComponentModel, workspace As VisualStudioWorkspace) As AbstractObjectBrowserLibraryManager
Return New ObjectBrowserLibraryManager(serviceProvider, componentModel, workspace)
End Function
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestSimpleContent_NamespaceClassAndMethod()
Dim code =
<Code>
Namespace N
Class C
Sub M()
End Sub
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list.VerifyNames("VisualBasicAssembly1")
list = list.GetNamespaceList(0)
list.VerifyNames("N")
list = list.GetTypeList(0)
list.VerifyNames("C")
list = list.GetMemberList(0)
list.VerifyNames(AddressOf IsImmediateMember, "M()")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestSimpleContent_NoNamespaceWithoutType()
Dim code =
<Code>
Namespace N
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list.VerifyEmpty()
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestSimpleContent_InlcudePrivateNestedTypeMembersInSourceCode()
Dim code =
<Code>
Namespace N
Class C
Private Enum PrivateEnumTest
End Enum
Private Class PrivateClassTest
End Class
Private Structure PrivateStructTest
End Structure
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0).GetTypeList(0)
list.VerifyNames("C", "C.PrivateStructTest", "C.PrivateClassTest", "C.PrivateEnumTest")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestSimpleContent_InlcudePrivateDoubleNestedTypeMembersInSourceCode()
Dim code =
<Code>
Namespace N
Friend Class C
Private Class NestedClass
Private Class NestedNestedClass
End Class
End Class
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0).GetTypeList(0)
list.VerifyNames("C", "C.NestedClass", "C.NestedClass.NestedNestedClass")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestSimpleContent_InlcudeNoPrivateNestedTypeOfMetaData()
Dim metaDatacode =
<Code>
Namespace N
Public Class C
Public Enum PublicEnumTest
V1
End Enum
Private Class PrivateClassTest
End Class
Private Structure PrivateStructTest
End Structure
End Class
End Namespace
</Code>
Dim code = <Code></Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code, metaDatacode, False))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList().GetReferenceList(0).GetNamespaceList(0).GetTypeList(0)
list.VerifyNames("C", "C.PublicEnumTest")
End Using
End Sub
<WorkItem(932387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932387")>
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestContent_InheritedMembers1()
Dim code =
<Code>
Class A
Protected Overridable Sub Goo()
End Sub
End Class
Class B
Inherits A
Protected Overrides Sub Goo()
MyBase.Goo()
End Sub
Overridable Sub Bar()
End Sub
End Class
Class C
Inherits B
Protected Overrides Sub Goo()
MyBase.Goo()
End Sub
Public Overrides Sub Bar()
MyBase.Bar()
End Sub
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyNames(
"Goo()",
"ToString() As String",
"Equals(Object) As Boolean",
"Equals(Object, Object) As Boolean",
"ReferenceEquals(Object, Object) As Boolean",
"GetHashCode() As Integer",
"GetType() As System.Type",
"Finalize()",
"MemberwiseClone() As Object")
End Using
End Sub
<WorkItem(932387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932387")>
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestContent_InheritedMembers2()
Dim code =
<Code>
Class A
Protected Overridable Sub Goo()
End Sub
End Class
Class B
Inherits A
Protected Overrides Sub Goo()
MyBase.Goo()
End Sub
Overridable Sub Bar()
End Sub
End Class
Class C
Inherits B
Protected Overrides Sub Goo()
MyBase.Goo()
End Sub
Public Overrides Sub Bar()
MyBase.Bar()
End Sub
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(1)
list.VerifyNames(
"Goo()",
"Bar()",
"ToString() As String",
"Equals(Object) As Boolean",
"Equals(Object, Object) As Boolean",
"ReferenceEquals(Object, Object) As Boolean",
"GetHashCode() As Integer",
"GetType() As System.Type",
"Finalize()",
"MemberwiseClone() As Object")
End Using
End Sub
<WorkItem(932387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932387")>
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestContent_InheritedMembers3()
Dim code =
<Code>
Class A
Protected Overridable Sub Goo()
End Sub
End Class
Class B
Inherits A
Protected Overrides Sub Goo()
MyBase.Goo()
End Sub
Overridable Sub Bar()
End Sub
End Class
Class C
Inherits B
Protected Overrides Sub Goo()
MyBase.Goo()
End Sub
Public Overrides Sub Bar()
MyBase.Bar()
End Sub
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(2)
list.VerifyNames(
"Goo()",
"Bar()",
"ToString() As String",
"Equals(Object) As Boolean",
"Equals(Object, Object) As Boolean",
"ReferenceEquals(Object, Object) As Boolean",
"GetHashCode() As Integer",
"GetType() As System.Type",
"Finalize()",
"MemberwiseClone() As Object")
End Using
End Sub
<WorkItem(932387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932387")>
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestContent_HelpKeyword_Ctor()
Dim code =
<Code>
Namespace N
Class C
Sub New()
End Sub
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyHelpKeywords("N.C.New")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Project()
Dim code =
<Code>
Namespace N
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list.VerifyDescriptions($"{ServicesVSResources.Project}VisualBasicAssembly1")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Namespace()
Dim code =
<Code>
Namespace N
Class C
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list.VerifyDescriptions(
"Namespace N" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Delegate1()
Dim code =
<Code>
Delegate Function D(x As Integer) As Boolean
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list.VerifyDescriptions(
"Friend Delegate Function D(x As Integer) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Delegate2()
Dim code =
<Code>
Delegate Sub D(y As String)
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list.VerifyDescriptions(
"Friend Delegate Sub D(y As String)" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Delegate3()
Dim code =
<Code>
Delegate Function F(Of T As {Class, New}, U As V, V As List(Of T))(x As T, y As U) As V
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list.VerifyDescriptions(
"Friend Delegate Function F(Of T As {Class, New}, U As V, V As System.Collections.Generic.List(Of T))(x As T, y As U) As V" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Class1()
Dim code =
<Code>
Class C
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list.VerifyDescriptions(
"Friend Class C" & vbCrLf &
" Inherits Object" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Class2()
Dim code =
<Code>
MustInherit Class C
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list.VerifyDescriptions(
"Friend MustInherit Class C" & vbCrLf &
" Inherits Object" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Class3()
Dim code =
<Code>
NotInheritable Class C
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list.VerifyDescriptions(
"Friend NotInheritable Class C" & vbCrLf &
" Inherits Object" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Class4()
Dim code =
<Code>
Public Class C(Of T As Class)
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list.VerifyDescriptions(
"Public Class C(Of T As Class)" & vbCrLf &
" Inherits Object" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Class5()
Dim code =
<Code>
Class C(Of T As Class)
Inherits B
End Class
Class B
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list.VerifyDescriptions(
"Friend Class C(Of T As Class)" & vbCrLf &
" Inherits B" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}",
"Friend Class B" & vbCrLf &
" Inherits Object" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Class6()
Dim code =
<Code>
MustInherit Class B
End Class
NotInheritable Class C
Inherits B
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list.VerifyDescriptions(
"Friend MustInherit Class B" & vbCrLf &
" Inherits Object" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}",
"Friend NotInheritable Class C" & vbCrLf &
" Inherits B" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Structure1()
Dim code =
<Code>
Structure S
End Structure
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list.VerifyDescriptions(
"Friend Structure S" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Structure2()
Dim code =
<Code>
Public Structure S
End Structure
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list.VerifyDescriptions(
"Public Structure S" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Module1()
Dim code =
<Code>
Module M
End Module
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list.VerifyDescriptions(
"Friend Module M" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Module2()
Dim code =
<Code>
Public Module M
End Module
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list.VerifyDescriptions(
"Public Module M" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Enum1()
Dim code =
<Code>
Enum E
A
B
C
End Enum
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list.VerifyDescriptions(
"Friend Enum E" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Enum2()
Dim code =
<Code>
Enum E As Byte
A
B
C
End Enum
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list.VerifyDescriptions(
"Friend Enum E As Byte" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Interfaces()
Dim code =
<Code>
Interface I1
End Interface
Interface I2
Inherits I1
End Interface
Interface I3
Inherits I1
Inherits I2
End Interface
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list.VerifyDescriptions(
"Friend Interface I1" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}",
"Friend Interface I2" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}",
"Friend Interface I3" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Sub1()
Dim code =
<Code>
Namespace N
Class C
Sub M()
End Sub
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Sub M()" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "N.C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Sub2()
Dim code =
<Code>
Namespace N
Class C
Sub M(x As Integer)
End Sub
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Sub M(x As Integer)" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "N.C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Sub3()
Dim code =
<Code>
Namespace N
Class C
Sub M(ByRef x As Integer)
End Sub
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Sub M(ByRef x As Integer)" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "N.C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Sub4()
Dim code =
<Code>
Namespace N
Class C
Sub M(Optional x As Integer = 42)
End Sub
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Sub M(Optional x As Integer = 42)" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "N.C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Sub5()
Dim code =
<Code>
Imports System
Namespace N
Class C
Sub M(Optional x As Double = Math.PI)
End Sub
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code)),
testCulture As New CultureContext(New CultureInfo("en-US", useUserOverride:=False))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Sub M(Optional x As Double = 3.14159265358979)" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "N.C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Sub6()
Dim code =
<Code>
Namespace N
Class C
Sub M(Optional x As Double? = Nothing)
End Sub
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Sub M(Optional x As Double? = Nothing)" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "N.C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Sub7()
Dim code =
<Code>
Namespace N
Class C
Sub M(Optional x As Double? = 42)
End Sub
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Sub M(Optional x As Double? = 42)" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "N.C")}")
End Using
End Sub
<WorkItem(939739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939739")>
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_SubInInterface()
Dim code =
<Code>
Namespace N
interface I
Sub M()
End Interface
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Sub M()" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "N.I")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Function1()
Dim code =
<Code>
Namespace N
Class C
Function M() As Integer
End Function
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Function M() As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "N.C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Function2()
Dim code =
<Code>
Namespace N
Class C
Function M%()
End Function
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Function M() As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "N.C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Function3()
Dim code =
<Code>
Namespace N
MustInherit Class C
MustOverride Function M() As Integer
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public MustOverride Function M() As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "N.C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Function4()
Dim code =
<Code>
Namespace N
MustInherit Class C
Protected Overridable Function M() As Integer
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Protected Overridable Function M() As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "N.C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Function5()
Dim code =
<Code>
Namespace N
MustInherit Class C
NotOverridable Function M() As Integer
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public NotOverridable Function M() As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "N.C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_IteratorFunction()
Dim code =
<Code>
Imports System.Collections.Generic
Namespace N
Class C
Iterator Function M() As IEnumerable(Of Integer)
End Function
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Function M() As System.Collections.Generic.IEnumerable(Of Integer)" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "N.C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Constructor()
Dim code =
<Code>
Imports System.Collections.Generic
Namespace N
Class C
Sub New()
End Sub
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Sub New()" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "N.C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_SharedConstructor()
Dim code =
<Code>
Imports System.Collections.Generic
Namespace N
Class C
Shared Sub New()
End Sub
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Private Shared Sub New()" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "N.C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Property1()
Dim code =
<Code>
Class C
Property P As Integer
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Property P As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Property2()
Dim code =
<Code>
Class C
Property P() As Integer
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Property P As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Property3()
Dim code =
<Code>
Class C
Property P%
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Property P As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Property4()
Dim code =
<Code>
Class C
Property P As Integer = 42
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Property P As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Property5()
Dim code =
<Code>
Class C
ReadOnly Property P As Integer
Get
Return 42
End Get
End Property
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public ReadOnly Property P As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Property6()
Dim code =
<Code>
Class C
ReadOnly Property P As Integer
Protected Get
Return 42
End Get
End Property
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public ReadOnly Property P As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Property7()
Dim code =
<Code>
Class C
WriteOnly Property P As Integer
Set(value As Integer)
End Set
End Property
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public WriteOnly Property P As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Property8()
Dim code =
<Code>
Class C
Property P As Integer
Get
End Get
Protected Set(value As Integer)
End Set
End Property
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Property P As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Property9()
Dim code =
<Code>
Class C
Property P(index As Integer) As Integer
Get
End Get
Protected Set(value As Integer)
End Set
End Property
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Property P(index As Integer) As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_IteratorProperty()
Dim code =
<Code>
Imports System.Collections.Generic
Class C
ReadOnly Iterator Property P As IEnumerable(Of Integer)
Get
End Get
End Property
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public ReadOnly Property P As System.Collections.Generic.IEnumerable(Of Integer)" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Const1()
Dim code =
<Code>
Class C
Const F As Integer = 42
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Private Const F As Integer = 42" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Const2()
Dim code =
<Code>
Class C
Const F = 42
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Private Const F As Integer = 42" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Field1()
Dim code =
<Code>
Class C
Dim x As Integer
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Private x As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Field2()
Dim code =
<Code>
Class C
Private x As Integer
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Private x As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Field3()
Dim code =
<Code>
Class C
ReadOnly x As Integer
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Private ReadOnly x As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Field4()
Dim code =
<Code>
Class C
Shared ReadOnly x As Integer
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Private Shared ReadOnly x As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_EnumMembers()
Dim code =
<Code>
Enum E
A
B
C
End Enum
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Const A As E = 0" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "E")}",
"Public Const B As E = 1" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "E")}",
"Public Const C As E = 2" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "E")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Events()
Dim code =
<Code>
Imports System
Class C
Event E1()
Event E2(i As Integer)
Event E3 As EventHandler
Custom Event E4 As EventHandler
AddHandler(value As EventHandler)
End AddHandler
RemoveHandler(value As EventHandler)
End RemoveHandler
RaiseEvent(sender As Object, e As EventArgs)
End RaiseEvent
End Event
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Event E1()" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}",
"Public Event E2(i As Integer)" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}",
"Public Event E3(sender As Object, e As System.EventArgs)" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}",
"Public Event E4(sender As Object, e As System.EventArgs)" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_Add()
Dim code =
<Code>
Class C
Shared Operator +(c As C, x As Integer) As Integer
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator +(c As C, x As Integer) As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_Subtract()
Dim code =
<Code>
Class C
Shared Operator -(c As C, x As Integer) As Integer
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator -(c As C, x As Integer) As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_Multiply()
Dim code =
<Code>
Class C
Shared Operator *(c As C, x As Integer) As Integer
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator *(c As C, x As Integer) As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_Divide()
Dim code =
<Code>
Class C
Shared Operator /(c As C, x As Integer) As Integer
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator /(c As C, x As Integer) As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_IntegerDivide()
Dim code =
<Code>
Class C
Shared Operator \(c As C, x As Integer) As Integer
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator \(c As C, x As Integer) As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_Modulus()
Dim code =
<Code>
Class C
Shared Operator Mod(c As C, x As Integer) As Integer
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator Mod(c As C, x As Integer) As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_Power()
Dim code =
<Code>
Class C
Shared Operator ^(c As C, x As Integer) As Integer
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator ^(c As C, x As Integer) As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_Concatenate()
Dim code =
<Code>
Class C
Shared Operator &(c As C, x As Integer) As Integer
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator &(c As C, x As Integer) As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_Equality()
Dim code =
<Code>
Class C
Shared Operator =(c As C, x As Integer) As Boolean
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator =(c As C, x As Integer) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_Inequality()
Dim code =
<Code>
Class C
Shared Operator <>(c As C, x As Integer) As Boolean
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator <>(c As C, x As Integer) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_LessThan()
Dim code =
<Code>
Class C
Shared Operator <(c As C, x As Integer) As Boolean
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator <(c As C, x As Integer) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_LessThanOrEqualTo()
Dim code =
<Code>
Class C
Shared Operator <=(c As C, x As Integer) As Boolean
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator <=(c As C, x As Integer) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_GreaterThan()
Dim code =
<Code>
Class C
Shared Operator >(c As C, x As Integer) As Boolean
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator >(c As C, x As Integer) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_GreaterThanOrEqualTo()
Dim code =
<Code>
Class C
Shared Operator >=(c As C, x As Integer) As Boolean
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator >=(c As C, x As Integer) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_Like()
Dim code =
<Code>
Class C
Shared Operator Like(c As C, i As Integer) As Boolean
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator Like(c As C, i As Integer) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_Not()
Dim code =
<Code>
Class C
Shared Operator Not(c As C) As Boolean
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator Not(c As C) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_And()
Dim code =
<Code>
Class C
Shared Operator And(c As C, i As Integer) As Boolean
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator And(c As C, i As Integer) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_Or()
Dim code =
<Code>
Class C
Shared Operator Or(c As C, i As Integer) As Boolean
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator Or(c As C, i As Integer) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_Xor()
Dim code =
<Code>
Class C
Shared Operator Xor(c As C, i As Integer) As Boolean
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator Xor(c As C, i As Integer) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_ShiftLeft()
Dim code =
<Code>
Class C
Shared Operator <<(c As C, x As Integer) As Integer
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator <<(c As C, x As Integer) As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_Right()
Dim code =
<Code>
Class C
Shared Operator >>(c As C, x As Integer) As Integer
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator >>(c As C, x As Integer) As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_IsTrue()
Dim code =
<Code>
Class C
Shared Operator IsTrue(c As C) As Boolean
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator IsTrue(c As C) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_IsFalse()
Dim code =
<Code>
Class C
Shared Operator IsFalse(c As C) As Boolean
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Operator IsFalse(c As C) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_CType1()
Dim code =
<Code>
Class C
Shared Narrowing Operator CType(c As C) As Boolean
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Narrowing Operator CType(c As C) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_Operator_CType2()
Dim code =
<Code>
Class C
Shared Widening Operator CType(c As C) As Boolean
End Operator
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Widening Operator CType(c As C) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_DeclareFunction1()
' Note: DllImport functions that are not Declare should appear as normal functions
Dim code =
<Code>
Imports System.Runtime.InteropServices
Class C
<DllImportAttribute("kernel32.dll", EntryPoint:="MoveFileW",
SetLastError:=True, CharSet:=CharSet.Unicode,
ExactSpelling:=True,
CallingConvention:=CallingConvention.StdCall)>
Public Shared Function moveFile(ByVal src As String, ByVal dst As String) As Boolean
' This function copies a file from the path src to the path dst.
' Leave this function empty. The DLLImport attribute forces calls
' to moveFile to be forwarded to MoveFileW in KERNEL32.DLL.
End Function
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Shared Function moveFile(src As String, dst As String) As Boolean" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_DeclareFunction2()
Dim code =
<Code>
Class C
Declare Function getUserName Lib "advapi32.dll" Alias "GetUserNameA"(lpBuffer As String, ByRef nSize As Integer) As Integer
End Class
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Declare Ansi Function getUserName Lib ""advapi32.dll"" Alias ""GetUserNameA""(ByRef lpBuffer As String, ByRef nSize As Integer) As Integer" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}")
End Using
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestDescription_XmlDocComments()
Dim code =
<Code>
<![CDATA[
Class C
''' <summary>
''' The is my summary!
''' </summary>
''' <typeparam name="T">Hello from a type parameter</typeparam>
''' <param name="i">The parameter i</param>
''' <param name="s">The parameter t</param>
''' <remarks>Takes <paramref name="i"/> and <paramref name="s"/>.</remarks>
Sub M(Of T)(i As Integer, s As String)
End Sub
End Class
]]>
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetTypeList(0)
list = list.GetMemberList(0)
list.VerifyImmediateMemberDescriptions(
"Public Sub M(Of T)(i As Integer, s As String)" & vbCrLf &
$" {String.Format(ServicesVSResources.Member_of_0, "C")}" & vbCrLf &
"" & vbCrLf &
ServicesVSResources.Summary_colon & vbCrLf &
"The is my summary!" & vbCrLf &
"" & vbCrLf &
ServicesVSResources.Type_Parameters_colon & vbCrLf &
"T: Hello from a type parameter" & vbCrLf &
"" & vbCrLf &
ServicesVSResources.Parameters_colon1 & vbCrLf &
"i: The parameter i" & vbCrLf &
"s: The parameter t" & vbCrLf &
"" & vbCrLf &
ServicesVSResources.Remarks_colon & vbCrLf &
"Takes i and s.")
End Using
End Sub
<WorkItem(942021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942021")>
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestNavInfo_Class()
Dim code =
<Code>
Namespace EditorFunctionalityHelper
Public Class EditorFunctionalityHelper
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list.VerifyCanonicalNodes(0,
ProjectNode("VisualBasicAssembly1"),
NamespaceNode("EditorFunctionalityHelper"),
TypeNode("EditorFunctionalityHelper"))
End Using
End Sub
<WorkItem(942021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942021")>
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.ObjectBrowser)>
Public Sub TestNavInfo_NestedEnum()
Dim code =
<Code>
Namespace EditorFunctionalityHelper
Public Class EditorFunctionalityHelper
Public Enum Mapping
EnumOne
EnumTwo
EnumThree
End Enum
End Class
End Namespace
</Code>
Using state = CreateLibraryManager(GetWorkspaceDefinition(code))
Dim library = state.GetLibrary()
Dim list = library.GetProjectList()
list = list.GetNamespaceList(0)
list = list.GetTypeList(0)
list.VerifyCanonicalNodes(1, ' Mapping
ProjectNode("VisualBasicAssembly1"),
NamespaceNode("EditorFunctionalityHelper"),
TypeNode("EditorFunctionalityHelper"),
TypeNode("Mapping"))
End Using
End Sub
End Class
End Namespace
|
DustinCampbell/roslyn
|
src/VisualStudio/Core/Test/ObjectBrowser/VisualBasic/ObjectBrowerTests.vb
|
Visual Basic
|
apache-2.0
| 74,503
|
'------------------------------------------------------------------------------
' <generado automáticamente>
' Este código fue generado por una herramienta.
'
' Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
' se vuelve a generar el código.
' </generado automáticamente>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Partial Public Class FrmCambiarComprador
'''<summary>
'''Control RadCodeBlock1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents RadCodeBlock1 As Global.Telerik.Web.UI.RadCodeBlock
'''<summary>
'''Control lbNuevoUsuario.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lbNuevoUsuario As Global.System.Web.UI.WebControls.LinkButton
'''<summary>
'''Control gvRolPersonal.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents gvRolPersonal As Global.System.Web.UI.WebControls.GridView
'''<summary>
'''Control odsUsuariosSistema.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents odsUsuariosSistema As Global.System.Web.UI.WebControls.ObjectDataSource
'''<summary>
'''Control RadWindowManager1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents RadWindowManager1 As Global.Telerik.Web.UI.RadWindowManager
'''<summary>
'''Control VentanaRoles.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents VentanaRoles As Global.Telerik.Web.UI.RadWindow
'''<summary>
'''Control RadAjaxManager1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents RadAjaxManager1 As Global.Telerik.Web.UI.RadAjaxManager
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.WebSite/Logistica/FrmCambiarComprador.aspx.designer.vb
|
Visual Basic
|
mit
| 2,913
|
Imports System
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim document As SolidEdgeFramework.SolidEdgeDocument = Nothing
Dim selectSet As SolidEdgeFramework.SelectSet = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
document = CType(application.ActiveDocument, SolidEdgeFramework.SolidEdgeDocument)
selectSet = document.SelectSet
' Cut the SelectSet contents to ClipBoard
' SelectSet must be populated first.
selectSet.Cut()
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgeFramework.SelectSet.Cut.vb
|
Visual Basic
|
mit
| 1,245
|
Imports System.Data
Partial Class rZonas02
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim lcComandoSelect as String
lcComandoSelect = "SELECT Cod_Zon, " _
& "Nom_Zon, " _
& "status, " _
& "nivel as numero " _
& "FROM Zonas " _
& "WHERE Cod_Zon between '" & cusAplicacion.goReportes.paParametrosIniciales(0) & "'" _
& " And '" & cusAplicacion.goReportes.paParametrosFinales(0) & "'" _
& " ORDER BY Cod_Zon"
Try
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodos(lcComandoSelect, "curReportes")
Me.crvrrZonas02.ReportSource = cusAplicacion.goReportes.mCargarReporte("rZonas02", laDatosReporte)
Catch loExcepcion As Exception
me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
End Class
|
kodeitsolutions/ef-reports
|
rZonas02.aspx.vb
|
Visual Basic
|
mit
| 1,205
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' Allgemeine Informationen über eine Assembly werden über die folgenden
' Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
' die mit einer Assembly verknüpft sind.
' Die Werte der Assemblyattribute überprüfen
<Assembly: AssemblyTitle("Sortierprogramm Severin Kaderli")>
<Assembly: AssemblyDescription("Sortierprogramm für Modul 318")>
<Assembly: AssemblyCompany("Severin Kaderli")>
<Assembly: AssemblyProduct("Sortierprogramm")>
<Assembly: AssemblyCopyright("Copyright © 2015")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
<Assembly: Guid("88d51612-c8a9-4608-a869-a9204d384221")>
' Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
'
' Hauptversion
' Nebenversion
' Buildnummer
' Revision
'
' Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
' übernehmen, indem Sie "*" eingeben:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("3.0.0.0")>
|
severinkaderli/gibb
|
Lehrjahr_2/Modul_318/KaderliS_Sortieren/KaderliS_Sortieren/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,266
|
Imports System.IO
Imports Aspose.Cells
Imports Aspose.Cells.Drawing
Imports Aspose.Cells.Drawing.Texts
Namespace Articles
Public Class CreateTextBoxWithDifferentHorizontalAlignment
Public Shared Sub Run()
' ExStart:1
' The path to the documents directory.
Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
' Create a workbook.
Dim wb As New Workbook()
' Access first worksheet.
Dim ws As Worksheet = wb.Worksheets(0)
' Add text box inside the sheet.
ws.Shapes.AddTextBox(2, 0, 2, 0, 80, 400)
' Access first shape which is a text box and set is text.
Dim shape As Shape = ws.Shapes(0)
shape.Text = "Sign up for your free phone number." & vbLf & "Call and text online for free." & vbLf & "Call your friends and family."
' Acccess the first paragraph and set its horizontal alignment to left.
Dim p As TextParagraph = shape.TextBody.TextParagraphs(0)
p.AlignmentType = TextAlignmentType.Left
' Acccess the second paragraph and set its horizontal alignment to center.
p = shape.TextBody.TextParagraphs(1)
p.AlignmentType = TextAlignmentType.Center
' Acccess the third paragraph and set its horizontal alignment to right.
p = shape.TextBody.TextParagraphs(2)
p.AlignmentType = TextAlignmentType.Right
' Save the workbook in xlsx format.
wb.Save(dataDir & Convert.ToString("output_out.xlsx"), SaveFormat.Xlsx)
' ExEnd:1
End Sub
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples/VisualBasic/Articles/CreateTextBoxWithDifferentHorizontalAlignment.vb
|
Visual Basic
|
mit
| 1,742
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders
Public Class ObjectInitializerCompletionProviderTests
Inherits AbstractVisualBasicCompletionProviderTests
Public Sub New(workspaceFixture As VisualBasicTestWorkspaceFixture)
MyBase.New(workspaceFixture)
End Sub
Protected Overrides Async Function VerifyWorkerAsync(code As String, position As Integer, expectedItemOrNull As String, expectedDescriptionOrNull As String, sourceCodeKind As SourceCodeKind, usePreviousCharAsTrigger As Boolean, checkForAbsence As Boolean, experimental As Boolean, glyph As Integer?) As Threading.Tasks.Task
' Script/interactive support removed for now.
' TODO: Re-enable these when interactive is back in the product.
If sourceCodeKind <> SourceCodeKind.Regular Then
Return
End If
Await BaseVerifyWorkerAsync(code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, experimental)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNothingToShow() As Task
Dim text = <a>Public Class C
End Class
Class Program
Sub foo()
Dim a as C = new C With { .$$
End Sub
End Class</a>.Value
Await VerifyNoItemsExistAsync(text)
End Function
<WorkItem(530075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530075")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotInArgumentList() As Task
Dim text = <a>Public Class C
Property A As Integer
End Class
Class Program
Sub foo()
Dim a = new C(1, .$$
End Sub
End Class</a>.Value
Await VerifyNoItemsExistAsync(text)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestOneItem() As Task
Dim text = <a>Public Class C
Public bar as Integer
End Class
Class Program
Sub foo()
Dim a as C = new C With { .$$
End Sub
End Program</a>.Value
Await VerifyItemExistsAsync(text, "bar")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFieldAndProperty() As Task
Dim text = <a>Public Class C
Public bar as Integer
Public Property foo as Integer
End Class
Class Program
Sub foo()
Dim a as C = new C With { .$$
End Sub
End Program</a>.Value
Await VerifyItemExistsAsync(text, "bar")
Await VerifyItemExistsAsync(text, "foo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFieldAndPropertyBaseTypes() As Task
Dim text = <a>Public Class C
Public bar as Integer
Public Property foo as Integer
End Class
Public Class D
Inherits C
End Class
Class Program
Sub foo()
Dim a as D = new D With { .$$
End Sub
End Program</a>.Value
Await VerifyItemExistsAsync(text, "bar")
Await VerifyItemExistsAsync(text, "foo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMembersFromObjectInitializerSyntax() As Task
Dim text = <a>Public Class C
End Class
Public Class D
Inherits C
Public bar as Integer
Public Property foo as Integer
End Class
Class Program
Sub foo()
Dim a as C = new D With { .$$
End Sub
End Program</a>.Value
Await VerifyItemExistsAsync(text, "bar")
Await VerifyItemExistsAsync(text, "foo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestOneItemAfterComma() As Task
Dim text = <a>Public Class C
Public bar as Integer
Public Property foo as Integer
End Class
Class Program
Sub foo()
Dim a as C = new C With { .foo = 3, .b$$
End Sub
End Program</a>.Value
Await VerifyItemExistsAsync(text, "bar")
Await VerifyItemIsAbsentAsync(text, "foo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNothingLeftToShow() As Task
Dim text = <a>Public Class C
Public bar as Integer
Public Property foo as Integer
End Class
Class Program
Sub foo()
Dim a as C = new C With { .foo = 3, .bar = 3, .$$
End Sub
End Program</a>.Value
Await VerifyNoItemsExistAsync(text)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestWithoutAsClause() As Task
Dim text = <a>Public Class C
Public bar as Integer
Public Property foo as Integer
End Class
Class Program
Sub foo()
Dim a = new C With { .$$
End Sub
End Program</a>.Value
Await VerifyItemExistsAsync(text, "bar")
Await VerifyItemExistsAsync(text, "foo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestWithoutAsClauseNothingLeftToShow() As Task
Dim text = <a>Public Class C
Public bar as Integer
Public Property foo as Integer
End Class
Class Program
Sub foo()
Dim a = new C With { .foo = 3, .bar = 3, .$$
End Sub
End Program</a>.Value
Await VerifyNoItemsExistAsync(text)
End Function
<WorkItem(544326, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544326")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInactiveInRValue() As Task
Dim text = <a>Class C
Public X As Long = 1
Public Y As Long = 2
End Class
Module Program
Sub Main(args As String())
Dim a As C = New C() With {.X = .$$}
End Sub
End Module</a>.Value
Await VerifyNoItemsExistAsync(text)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNoBackingFields() As Task
Dim text = <a>Class C
Public Property Foo As Integer
Sub M()
Dim c As New C With { .$$
End Sub
End Class</a>.Value
Await VerifyItemExistsAsync(text, "Foo")
Await VerifyItemIsAbsentAsync(text, "_Foo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestReadOnlyPropertiesAreNotPresentOnLeftSide() As Task
Dim text = <a>Class C
Public Property Foo As Integer
Public ReadOnly Property Bar As Integer
Get
Return 0
End Get
End Property
Sub M()
Dim c As New C With { .$$
End Sub
End Class</a>.Value
Await VerifyItemExistsAsync(text, "Foo")
Await VerifyItemIsAbsentAsync(text, "Bar")
End Function
<WorkItem(545881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545881")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNoReadonlyFieldsOrProperties() As Task
Dim text = <a>Module M
Sub Main()
Dim x = New Exception With { .$$
End Sub
End Module
</a>.Value
Await VerifyItemIsAbsentAsync(text, "Data")
End Function
<WorkItem(545844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545844")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNoParameterizedProperties() As Task
Dim text = <a>Module M
Module M
Sub Main()
Dim y = New List(Of Integer()) With {.Capacity = 10, .$$
End Sub
End Module
</a>.Value
Await VerifyItemIsAbsentAsync(text, "Item")
End Function
<WorkItem(545844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545844")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestShowParameterizedPropertiesWithAllOptionalArguments() As Task
Dim text = <a>Imports System
Public Class AImpl
Property P(Optional x As Integer = 3, Optional y As Integer = 2) As Object
Get
Console.WriteLine("P[{0}, {1}].get", x, y)
Return Nothing
End Get
Set(value As Object)
Console.WriteLine("P[{0}, {1}].set", x, y)
End Set
End Property
Sub Foo()
Dim z = New AImpl With {.$$
End Sub
End Class</a>.Value
Await VerifyItemExistsAsync(text, "P")
End Function
<WorkItem(545844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545844")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDoNotShowParameterizedPropertiesWithSomeMandatoryArguments() As Task
Dim text = <a>Imports System
Public Class AImpl
Property P(x As Integer, Optional y As Integer = 2) As Object
Get
Console.WriteLine("P[{0}, {1}].get", x, y)
Return Nothing
End Get
Set(value As Object)
Console.WriteLine("P[{0}, {1}].set", x, y)
End Set
End Property
Sub Foo()
Dim z = New AImpl With {.$$
End Sub
End Class</a>.Value
Await VerifyItemIsAbsentAsync(text, "P")
End Function
<WorkItem(545844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545844")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParameterizedPropertiesWithParamArrays() As Task
Dim text = <a>Option Strict On
Class C
Property P(ParamArray args As Object()) As Object
Get
Return Nothing
End Get
Set(value As Object)
End Set
End Property
Property Q(o As Object, ParamArray args As Object()) As Object
Get
Return Nothing
End Get
Set(value As Object)
End Set
End Property
Shared Sub M()
Dim o As C
o = New C With {.$$
End Sub
End Class
</a>.Value
Await VerifyItemExistsAsync(text, "P")
Await VerifyItemIsAbsentAsync(text, "Q")
End Function
<WorkItem(530491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530491")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestObjectInitializerOnInterface() As Task
Dim text = <a><![CDATA[Option Strict On
Imports System.Runtime.InteropServices
Module Program
Sub Main(args As String())
Dim x = New I With {.$$}
End Sub
End Module
<ComImport>
<Guid("EAA4976A-45C3-4BC5-BC0B-E474F4C3C83F")>
<CoClass(GetType(C))>
Interface I
Property c As Integer
End Interface
Class C
Public Property c As Integer
End Class
]]></a>.Value
Await VerifyItemExistsAsync(text, "c")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function IsCommitCharacterTest() As Threading.Tasks.Task
Const code = "
Public Class C
Public bar as Integer
End Class
Class Program
Sub foo()
Dim a as C = new C With { .$$
End Sub
End Program"
Await VerifyCommonCommitCharactersAsync(code, textTypedSoFar:="")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestIsExclusive() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="VBDocument">
Public Class C
Public bar as Integer
End Class
Class Program
Sub foo()
Dim a as C = new C With { .$$
End Sub
End Program</Document>
</Project>
</Workspace>
Using workspace = Await TestWorkspace.CreateAsync(text)
Dim hostDocument = workspace.Documents.First()
Dim caretPosition = hostDocument.CursorPosition.Value
Dim document = workspace.CurrentSolution.GetDocument(hostDocument.Id)
Dim completionList = Await GetCompletionListContextAsync(document, caretPosition, CompletionTrigger.Default)
Assert.True(completionList Is Nothing OrElse completionList.IsExclusive, "Expected always exclusive")
End Using
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function SendEnterThroughToEditorTest() As Threading.Tasks.Task
Const code = "
Public Class C
Public bar as Integer
End Class
Class Program
Sub foo()
Dim a as C = new C With { .$$
End Sub
End Program"
Await VerifySendEnterThroughToEditorAsync(code, "bar", expected:=False)
End Function
Friend Overrides Function CreateCompletionProvider() As CompletionProvider
Return New ObjectInitializerCompletionProvider()
End Function
End Class
End Namespace
|
khellang/roslyn
|
src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/ObjectInitializerCompletionProviderTests.vb
|
Visual Basic
|
apache-2.0
| 13,606
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("GeekDrop Props")>
<Assembly: AssemblyDescription("Display the Standard Windows Property Sheet via a Command-Line Call.")>
<Assembly: AssemblyCompany("J. Scott Elblein")>
<Assembly: AssemblyProduct("GeekDrop Props")>
<Assembly: AssemblyCopyright("Copyright © 2015")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("2f2a963d-dbcb-4158-a1e8-e53a444bdc92")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.2.0.0")>
<Assembly: AssemblyFileVersion("1.2.0.0")>
|
STaRDoGG/GeekDrop-Props
|
GeekDrop Props/My Project/AssemblyInfo.vb
|
Visual Basic
|
apache-2.0
| 1,229
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("WindowsReceiver.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
KaiserSoft/OpenSimButtonBox
|
Wheel Button Box/Arduino Nano/WindowsReceiver/My Project/Resources.Designer.vb
|
Visual Basic
|
bsd-3-clause
| 2,782
|
Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Diagnostics
Imports System.IO
Imports System.Xml
Imports AnimatGuiCtrls.Controls
Imports AnimatGUI.Framework
Namespace DataObjects
Public MustInherit Class Gain
Inherits Framework.DataObject
#Region " Attributes "
Protected m_bUseLimits As Boolean
Protected m_bLimitsReadOnly As Boolean
Protected m_bLimitOutputsReadOnly As Boolean
Protected m_bUseParentIncomingDataType As Boolean
Protected m_snLowerLimit As AnimatGUI.Framework.ScaledNumber
Protected m_snUpperLimit As AnimatGUI.Framework.ScaledNumber
Protected m_snLowerOutput As AnimatGUI.Framework.ScaledNumber
Protected m_snUpperOutput As AnimatGUI.Framework.ScaledNumber
Protected m_strIndependentUnits As String = ""
Protected m_strDependentUnits As String = ""
Protected m_bdParentData As Behavior.Data
Protected m_strGainPropertyName As String = ""
Protected m_imgGain As Image
#End Region
#Region " Properties "
<Browsable(False)> _
Public MustOverride ReadOnly Property GainType() As String
<Browsable(False)> _
Public MustOverride ReadOnly Property Type() As String
<Browsable(False)> _
Public MustOverride ReadOnly Property GainEquation() As String
<Browsable(False)> _
Public Overridable Property GainPropertyName() As String
Get
Return m_strGainPropertyName
End Get
Set(ByVal Value As String)
m_strGainPropertyName = Value
End Set
End Property
<Browsable(False)> _
Public Overridable Property UseLimits() As Boolean
Get
Return m_bUseLimits
End Get
Set(ByVal Value As Boolean)
SetSimData("UseLimits", Value.ToString, True)
'If we are activating this we may need to set the rest of the limit values. So call this here.
SetAllSimData(m_doInterface)
Me.ManualAddPropertyHistory("UseLimits", m_bUseLimits, Value, True)
m_bUseLimits = Value
End Set
End Property
<Browsable(False)> _
Public Overridable Property LimitsReadOnly() As Boolean
Get
Return m_bLimitsReadOnly
End Get
Set(ByVal Value As Boolean)
Me.ManualAddPropertyHistory("LimitsReadOnly", m_bLimitsReadOnly, Value, True)
m_bLimitsReadOnly = Value
If m_bLimitsReadOnly Then m_bUseLimits = True
End Set
End Property
<Browsable(False)> _
Public Overridable Property LimitOutputsReadOnly() As Boolean
Get
Return m_bLimitOutputsReadOnly
End Get
Set(ByVal Value As Boolean)
Me.ManualAddPropertyHistory("LimitOutputsReadOnly", m_bLimitOutputsReadOnly, Value, True)
m_bLimitOutputsReadOnly = Value
If m_bLimitsReadOnly Then m_bUseLimits = True
End Set
End Property
'<Category("Gain Limits"), _
' Description("Sets the lower limit of the x variable."), _
' TypeConverter(GetType(AnimatGUI.Framework.ScaledNumber.ScaledNumericPropBagConverter))> _
<Browsable(False)> _
Public Overridable Property LowerLimit() As AnimatGUI.Framework.ScaledNumber
Get
Return m_snLowerLimit
End Get
Set(ByVal Value As AnimatGUI.Framework.ScaledNumber)
If Not Value Is Nothing Then
SetSimData("LowerLimit", Value.ActualValue.ToString, True)
Dim snOrig As ScaledNumber = DirectCast(m_snLowerLimit.Clone(m_snLowerLimit.Parent, False, Nothing), ScaledNumber)
If Not Value Is Nothing Then m_snLowerLimit.CopyData(Value)
Dim snNew As ScaledNumber = DirectCast(m_snLowerLimit.Clone(m_snLowerLimit.Parent, False, Nothing), ScaledNumber)
Me.ManualAddPropertyHistory("LowerLimit", snOrig, snNew, True)
End If
End Set
End Property
'<Category("Gain Limits"), _
' Description("Sets the upper limit of the x variable."), _
' TypeConverter(GetType(AnimatGUI.Framework.ScaledNumber.ScaledNumericPropBagConverter))> _
<Browsable(False)> _
Public Overridable Property UpperLimit() As AnimatGUI.Framework.ScaledNumber
Get
Return m_snUpperLimit
End Get
Set(ByVal Value As AnimatGUI.Framework.ScaledNumber)
If Not Value Is Nothing Then
SetSimData("UpperLimit", Value.ActualValue.ToString, True)
Dim snOrig As ScaledNumber = DirectCast(m_snUpperLimit.Clone(m_snUpperLimit.Parent, False, Nothing), ScaledNumber)
If Not Value Is Nothing Then m_snUpperLimit.CopyData(Value)
Dim snNew As ScaledNumber = DirectCast(m_snUpperLimit.Clone(m_snUpperLimit.Parent, False, Nothing), ScaledNumber)
Me.ManualAddPropertyHistory("UpperLimit", snOrig, snNew, True)
End If
End Set
End Property
'<Category("Gain Limits"), _
' Description("Sets the output value to use when the x value is less than the lower limit."), _
' TypeConverter(GetType(AnimatGUI.Framework.ScaledNumber.ScaledNumericPropBagConverter))> _
<Browsable(False)> _
Public Overridable Property LowerOutput() As AnimatGUI.Framework.ScaledNumber
Get
Return m_snLowerOutput
End Get
Set(ByVal Value As AnimatGUI.Framework.ScaledNumber)
If Not Value Is Nothing Then
SetSimData("LowerOutput", Value.ActualValue.ToString, True)
Dim snOrig As ScaledNumber = DirectCast(m_snLowerOutput.Clone(m_snLowerOutput.Parent, False, Nothing), ScaledNumber)
If Not Value Is Nothing Then m_snLowerOutput.CopyData(Value)
Dim snNew As ScaledNumber = DirectCast(m_snLowerOutput.Clone(m_snLowerOutput.Parent, False, Nothing), ScaledNumber)
Me.ManualAddPropertyHistory("LowerOutput", snOrig, snNew, True)
End If
End Set
End Property
'<Category("Gain Limits"), _
' Description("Sets the output value to use when the x value is more than the upper limit."), _
' TypeConverter(GetType(AnimatGUI.Framework.ScaledNumber.ScaledNumericPropBagConverter))> _
<Browsable(False)> _
Public Overridable Property UpperOutput() As AnimatGUI.Framework.ScaledNumber
Get
Return m_snUpperOutput
End Get
Set(ByVal Value As AnimatGUI.Framework.ScaledNumber)
If Not Value Is Nothing Then
SetSimData("UpperOutput", Value.ActualValue.ToString, True)
Dim snOrig As ScaledNumber = DirectCast(m_snUpperOutput.Clone(m_snUpperOutput.Parent, False, Nothing), ScaledNumber)
If Not Value Is Nothing Then m_snUpperOutput.CopyData(Value)
Dim snNew As ScaledNumber = DirectCast(m_snUpperOutput.Clone(m_snUpperOutput.Parent, False, Nothing), ScaledNumber)
Me.ManualAddPropertyHistory("UpperOutput", snOrig, snNew, True)
End If
End Set
End Property
<Browsable(False)> _
Public Overridable Property UseParentIncomingDataType() As Boolean
Get
Return m_bUseParentIncomingDataType
End Get
Set(ByVal Value As Boolean)
Me.ManualAddPropertyHistory("UseParentIncomingDataType", m_bUseParentIncomingDataType, Value, True)
m_bUseParentIncomingDataType = Value
End Set
End Property
<Browsable(False)> _
Public Overrides Property ViewSubProperties() As Boolean
Get
Return False
End Get
Set(ByVal Value As Boolean)
End Set
End Property
<Browsable(False)> _
Public Overridable Property IndependentUnits() As String
Get
Return m_strIndependentUnits
End Get
Set(ByVal Value As String)
m_strIndependentUnits = Value
End Set
End Property
<Browsable(False)> _
Public Overridable Property DependentUnits() As String
Get
Return m_strDependentUnits
End Get
Set(ByVal Value As String)
m_strDependentUnits = Value
End Set
End Property
<Browsable(False)> _
Public Property ParentData() As AnimatGUI.DataObjects.Behavior.Data
Get
Return m_bdParentData
End Get
Set(ByVal Value As AnimatGUI.DataObjects.Behavior.Data)
m_bdParentData = Value
End Set
End Property
<Browsable(False)> _
Public Overridable ReadOnly Property SelectableGain() As Boolean
Get
Return True
End Get
End Property
<Browsable(False)> _
Public Overridable ReadOnly Property BarAssemblyFile() As String
Get
Return "AnimatGUI.dll"
End Get
End Property
<Browsable(False)> _
Public Overridable ReadOnly Property BarClassName() As String
Get
Return "AnimatGUI.Forms.Gain.SelectGainType"
End Get
End Property
<Browsable(False)> _
Public Overridable ReadOnly Property DraggableParent() As AnimatGUI.DataObjects.DragObject
Get
If Not m_doParent Is Nothing AndAlso TypeOf m_doParent Is AnimatGUI.DataObjects.DragObject Then
Return DirectCast(m_doParent, AnimatGUI.DataObjects.DragObject)
Else
Return Nothing
End If
End Get
End Property
<Browsable(False)> _
Public Overridable ReadOnly Property GainImage() As Image
Get
If m_imgGain Is Nothing AndAlso Me.GainImageName <> "" Then
m_imgGain = ImageManager.LoadImage(Me.GainImageName)
End If
Return m_imgGain
End Get
End Property
<Browsable(False)> _
Public Overridable ReadOnly Property GainImageName() As String
Get
Return ""
End Get
End Property
#End Region
#Region " Methods "
Public Sub New(ByVal doParent As Framework.DataObject)
MyBase.New(doParent)
m_strName = "Gain"
m_snLowerLimit = New AnimatGUI.Framework.ScaledNumber(Me, "LowerLimit", 0, AnimatGUI.Framework.ScaledNumber.enumNumericScale.None, "", "")
m_snUpperLimit = New AnimatGUI.Framework.ScaledNumber(Me, "UpperLimit", 1, AnimatGUI.Framework.ScaledNumber.enumNumericScale.None, "", "")
m_snLowerOutput = New AnimatGUI.Framework.ScaledNumber(Me, "LowerOutput", 0, AnimatGUI.Framework.ScaledNumber.enumNumericScale.None, "", "")
m_snUpperOutput = New AnimatGUI.Framework.ScaledNumber(Me, "UpperOutput", 1, AnimatGUI.Framework.ScaledNumber.enumNumericScale.None, "", "")
m_bUseParentIncomingDataType = True
End Sub
Public Sub New(ByVal doParent As Framework.DataObject, ByVal strIndependentUnits As String, ByVal strDependentUnits As String, _
ByVal bLimitsReadOnly As Boolean, ByVal bLimitOutputsReadOnly As Boolean, ByVal bUseParentIncomingDataType As Boolean)
MyBase.New(doParent)
m_snLowerLimit = New AnimatGUI.Framework.ScaledNumber(Me, "LowerLimit", 0, AnimatGUI.Framework.ScaledNumber.enumNumericScale.None, "", "")
m_snUpperLimit = New AnimatGUI.Framework.ScaledNumber(Me, "UpperLimit", 1, AnimatGUI.Framework.ScaledNumber.enumNumericScale.None, "", "")
m_snLowerOutput = New AnimatGUI.Framework.ScaledNumber(Me, "LowerOutput", 0, AnimatGUI.Framework.ScaledNumber.enumNumericScale.None, "", "")
m_snUpperOutput = New AnimatGUI.Framework.ScaledNumber(Me, "UpperOutput", 1, AnimatGUI.Framework.ScaledNumber.enumNumericScale.None, "", "")
m_bUseParentIncomingDataType = bUseParentIncomingDataType
m_strIndependentUnits = strIndependentUnits
m_strDependentUnits = strDependentUnits
m_bLimitsReadOnly = bLimitsReadOnly
m_bLimitOutputsReadOnly = bLimitOutputsReadOnly
End Sub
Public Overridable Function InLimits(ByVal dblInput As Double) As Boolean
If m_bUseLimits AndAlso ((dblInput < m_snLowerLimit.ActualValue) OrElse (dblInput > m_snUpperLimit.ActualValue)) Then
Return False
Else
Return True
End If
End Function
Public Overridable Function CalculateLimitOutput(ByVal dblInput As Double) As Double
If dblInput < m_snLowerLimit.ActualValue Then Return m_snLowerOutput.ActualValue
If dblInput > m_snUpperLimit.ActualValue Then Return m_snUpperOutput.ActualValue
Return 0
End Function
Public MustOverride Function CalculateGain(ByVal dblInput As Double) As Double
Public Overridable Sub RecalculuateLimits()
End Sub
Protected Overridable Sub SetAllSimData(ByVal doInterface As ManagedAnimatInterfaces.IDataObjectInterface)
m_doInterface = doInterface
SetSimData("UseLimits", m_bUseLimits.ToString, True)
SetSimData("LowerLimit", m_snLowerLimit.ActualValue.ToString, True)
SetSimData("UpperLimit", m_snUpperLimit.ActualValue.ToString, True)
SetSimData("LowerOutput", m_snLowerOutput.ActualValue.ToString, True)
SetSimData("UpperOutput", m_snUpperOutput.ActualValue.ToString, True)
End Sub
Protected Overrides Sub CloneInternal(ByVal doOriginal As AnimatGUI.Framework.DataObject, ByVal bCutData As Boolean, _
ByVal doRoot As AnimatGUI.Framework.DataObject)
MyBase.CloneInternal(doOriginal, bCutData, doRoot)
Dim OrigNode As DataObjects.Gain = DirectCast(doOriginal, DataObjects.Gain)
m_strGainPropertyName = OrigNode.m_strGainPropertyName
m_bUseLimits = OrigNode.m_bUseLimits
m_bLimitsReadOnly = OrigNode.m_bLimitsReadOnly
m_bLimitOutputsReadOnly = OrigNode.m_bLimitOutputsReadOnly
m_bUseParentIncomingDataType = OrigNode.m_bUseParentIncomingDataType
m_snLowerLimit = DirectCast(OrigNode.m_snLowerLimit.Clone(Me, bCutData, doRoot), ScaledNumber)
m_snUpperLimit = DirectCast(OrigNode.m_snUpperLimit.Clone(Me, bCutData, doRoot), ScaledNumber)
m_snLowerOutput = DirectCast(OrigNode.m_snLowerOutput.Clone(Me, bCutData, doRoot), ScaledNumber)
m_snUpperOutput = DirectCast(OrigNode.m_snUpperOutput.Clone(Me, bCutData, doRoot), ScaledNumber)
m_strIndependentUnits = OrigNode.m_strIndependentUnits
m_strDependentUnits = OrigNode.m_strDependentUnits
End Sub
Public Overrides Function ToString() As String
Return Me.Type
End Function
#Region " DataObject Methods "
Public Overrides Sub BuildProperties(ByRef propTable As AnimatGuiCtrls.Controls.PropertyTable)
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("ID", Me.ID.GetType(), "ID", _
"Gain Limits", "ID", Me.ID, True))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Use Limits", m_bUseLimits.GetType(), "UseLimits", _
"Gain Limits", "Sets the whether to use the upper and lower limits on the x variable.", m_bUseLimits, _
(m_bLimitsReadOnly Or m_bLimitOutputsReadOnly)))
Dim pbNumberBag As AnimatGuiCtrls.Controls.PropertyBag = m_snLowerLimit.Properties
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Lower Limit", pbNumberBag.GetType(), "LowerLimit", _
"Gain Limits", "Sets the lower limit of the x variable.", pbNumberBag, _
"", GetType(AnimatGUI.Framework.ScaledNumber.ScaledNumericPropBagConverter), m_bLimitsReadOnly))
pbNumberBag = m_snUpperLimit.Properties
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Upper Limit", pbNumberBag.GetType(), "UpperLimit", _
"Gain Limits", "Sets the upper limit of the x variable.", pbNumberBag, _
"", GetType(AnimatGUI.Framework.ScaledNumber.ScaledNumericPropBagConverter), m_bLimitsReadOnly))
pbNumberBag = m_snLowerOutput.Properties
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Value @ Lower Limit", pbNumberBag.GetType(), "LowerOutput", _
"Gain Limits", "Sets the output value to use when the x value is less than the lower limit.", pbNumberBag, _
"", GetType(AnimatGUI.Framework.ScaledNumber.ScaledNumericPropBagConverter), m_bLimitOutputsReadOnly))
pbNumberBag = m_snUpperOutput.Properties
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Value @ Upper Limit", pbNumberBag.GetType(), "UpperOutput", _
"Gain Limits", "Sets the output value to use when the x value is more than the upper limit.", pbNumberBag, _
"", GetType(AnimatGUI.Framework.ScaledNumber.ScaledNumericPropBagConverter), m_bLimitOutputsReadOnly))
End Sub
Public Overridable Overloads Sub LoadData(ByVal oXml As ManagedAnimatInterfaces.IStdXml, ByVal strName As String, ByVal strGainPropertyName As String)
m_strGainPropertyName = strGainPropertyName
oXml.IntoChildElement(strName)
m_strID = oXml.GetChildString("ID", Me.ID)
m_bUseLimits = oXml.GetChildBool("UseLimits")
m_bLimitsReadOnly = oXml.GetChildBool("LimitsReadOnly", m_bLimitsReadOnly)
m_bLimitOutputsReadOnly = oXml.GetChildBool("LimitOutputsReadOnly", m_bLimitOutputsReadOnly)
m_bUseParentIncomingDataType = oXml.GetChildBool("UseParentIncomingDataType", m_bUseParentIncomingDataType)
If oXml.FindChildElement("LowerLimitScale", False) Then m_snLowerLimit.LoadData(oXml, "LowerLimitScale")
If oXml.FindChildElement("UpperLimitScale", False) Then m_snUpperLimit.LoadData(oXml, "UpperLimitScale")
If oXml.FindChildElement("LowerOutputScale", False) Then m_snLowerOutput.LoadData(oXml, "LowerOutputScale")
If oXml.FindChildElement("UpperOutputScale", False) Then m_snUpperOutput.LoadData(oXml, "UpperOutputScale")
Dim strIndependentUnits As String = oXml.GetChildString("IndependentUnits", "")
Dim strDependentUnits As String = oXml.GetChildString("DependentUnits", "")
If m_strIndependentUnits.Trim.Length > 0 Then m_strIndependentUnits = strIndependentUnits
If strDependentUnits.Trim.Length > 0 Then m_strDependentUnits = strDependentUnits
oXml.OutOfElem()
End Sub
Public Overridable Overloads Sub SaveData(ByVal oXml As ManagedAnimatInterfaces.IStdXml, ByVal strName As String)
oXml.AddChildElement(strName)
oXml.IntoElem()
oXml.AddChildElement("ID", Me.ID)
oXml.AddChildElement("Type", Me.Type())
oXml.AddChildElement("AssemblyFile", Me.AssemblyFile)
oXml.AddChildElement("ClassName", Me.ClassName)
oXml.AddChildElement("UseLimits", m_bUseLimits)
oXml.AddChildElement("LimitsReadOnly", m_bLimitsReadOnly)
oXml.AddChildElement("LimitOutputsReadOnly", m_bLimitOutputsReadOnly)
oXml.AddChildElement("UseParentIncomingDataType", m_bUseParentIncomingDataType)
m_snLowerLimit.SaveData(oXml, "LowerLimitScale")
m_snUpperLimit.SaveData(oXml, "UpperLimitScale")
m_snLowerOutput.SaveData(oXml, "LowerOutputScale")
m_snUpperOutput.SaveData(oXml, "UpperOutputScale")
oXml.AddChildElement("IndependentUnits", m_strIndependentUnits)
oXml.AddChildElement("DependentUnits", m_strDependentUnits)
oXml.OutOfElem()
End Sub
Public Overrides Sub SaveSimulationXml(ByVal oXml As ManagedAnimatInterfaces.IStdXml, Optional ByRef nmParentControl As AnimatGUI.Framework.DataObject = Nothing, Optional ByVal strName As String = "")
oXml.AddChildElement(strName)
oXml.IntoElem()
oXml.AddChildElement("ID", Me.ID)
If Me.ModuleName.Trim.Length > 0 Then
oXml.AddChildElement("ModuleName", Me.ModuleName())
End If
oXml.AddChildElement("Type", Me.Type())
oXml.AddChildElement("UseLimits", m_bUseLimits)
If m_bUseLimits Then
m_snLowerLimit.SaveSimulationXml(oXml, Me, "LowerLimit")
m_snUpperLimit.SaveSimulationXml(oXml, Me, "UpperLimit")
m_snLowerOutput.SaveSimulationXml(oXml, Me, "LowerOutput")
m_snUpperOutput.SaveSimulationXml(oXml, Me, "UpperOutput")
End If
oXml.OutOfElem()
End Sub
#End Region
#End Region
End Class
End Namespace
|
NeuroRoboticTech/AnimatLabPublicSource
|
Libraries/AnimatGUI/DataObjects/Gain.vb
|
Visual Basic
|
bsd-3-clause
| 22,565
|
Imports NUnit.Framework
Imports FakeItEasy.Tests
<TestFixture()> _
Public Class NextCallTests
<Test(), ExpectedException(GetType(ExpectationException))> _
Public Overridable Sub AssertWasCalled_should_fail_when_call_has_not_been_made()
Dim foo = A.Fake(Of IFoo)()
NextCall.To(foo).MustHaveHappened()
foo.Bar()
End Sub
<Test()> _
Public Overridable Sub AssertWasCalled_should_succeed_when_call_has_been_made()
Dim foo = A.Fake(Of IFoo)()
foo.Bar()
NextCall.To(foo).MustHaveHappened()
foo.Bar()
End Sub
<Test(), ExpectedException(GetType(ExpectationException))> _
Public Overridable Sub AssertWasCalled_with_arguments_specified_should_fail_if_not_argument_predicate_passes()
Dim foo = A.Fake(Of IFoo)()
foo.Bar("something", "")
NextCall.To(foo).WhenArgumentsMatch(Function(a) a.Get(Of String)(0) = "something else").MustHaveHappened(Repeated.Exactly.Once)
foo.Bar(Nothing, Nothing)
End Sub
<Test()> _
Public Sub AssertWasCalled_should_succeed_when_arguments_matches_argument_predicate()
Dim foo = A.Fake(Of IFoo)()
foo.Bar("something", "")
NextCall.To(foo).WhenArgumentsMatch(Function(a) a.Get(Of String)(0) = "something").MustHaveHappened()
foo.Bar(Nothing, Nothing)
End Sub
End Class
|
khellang/FakeItEasy
|
Source/FakeItEasy.IntegrationTests.VB/NextCallTests.vb
|
Visual Basic
|
mit
| 1,415
|
'Copyright 2013 Esri
'Licensed under the Apache License, Version 2.0 (the "License");
'You may not use this file except in compliance with the License.
'You may obtain a copy of the License at
'http://www.apache.org/licenses/LICENSE-2.0
'Unless required by applicable law or agreed to in writing, software
'distributed under the License is distributed on an "AS IS" BASIS,
'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'See the License for the specific language governing permissions and
'limitations under the License.
Imports System.Net
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Namespace Toolkit.Icons
<TemplatePart(Name := "CompassScale", Type := GetType(ScaleTransform)), TemplatePart(Name := "compassFace", Type := GetType(Ellipse))>
Public Class Compass
Inherits Control
Private oCompass As Compass
Private CompassScale As ScaleTransform
Private dblScale As Double = 1
Private bexpandOnMouseOver As Boolean = False
Private CompassFace As Ellipse
Private face_Fill As Brush
Public Sub New()
Me.DefaultStyleKey = GetType(Compass)
End Sub
''' <summary>
''' When overridden in a derived class, is invoked whenever application code or
''' internal processes (such as a rebuilding layout pass) call
''' <see cref="M:System.Windows.Controls.Control.ApplyTemplate"/>.
''' </summary>
Public Overrides Sub OnApplyTemplate()
oCompass = Me
CompassScale = TryCast(GetTemplateChild("CompassScale"), ScaleTransform)
CompassFace = TryCast(GetTemplateChild("compassFace"), Ellipse)
If dblScale <> 1 Then
oCompass.CompassScale.ScaleX = dblScale
oCompass.CompassScale.ScaleY = dblScale
End If
If bexpandOnMouseOver Then
AddHandler oCompass.MouseEnter, AddressOf compass_MouseEnter
AddHandler oCompass.MouseLeave, AddressOf compass_MouseLeave
End If
If face_Fill IsNot Nothing Then
CompassFace.Fill = face_Fill
End If
End Sub
Private Sub compass_MouseLeave(ByVal sender As Object, ByVal e As MouseEventArgs)
Dim xda As New DoubleAnimation() With {.To = dblScale, .Duration = New Duration(TimeSpan.FromSeconds(0.5))}
Dim yda As New DoubleAnimation() With {.To = dblScale, .Duration = New Duration(TimeSpan.FromSeconds(0.5))}
Dim sb As New Storyboard()
Storyboard.SetTarget(xda, oCompass.CompassScale)
Storyboard.SetTargetProperty(xda, New PropertyPath(ScaleTransform.ScaleXProperty))
Storyboard.SetTarget(yda, oCompass.CompassScale)
Storyboard.SetTargetProperty(yda, New PropertyPath(ScaleTransform.ScaleYProperty))
sb.Children.Add(xda)
sb.Children.Add(yda)
sb.Begin()
End Sub
Private Sub compass_MouseEnter(ByVal sender As Object, ByVal e As MouseEventArgs)
Dim expandScale As Double = dblScale * 1.25
Dim xda As New DoubleAnimation() With {.To = expandScale, .Duration = New Duration(TimeSpan.FromSeconds(0.5))}
Dim yda As New DoubleAnimation() With {.To = expandScale, .Duration = New Duration(TimeSpan.FromSeconds(0.5))}
Dim sb As New Storyboard()
Storyboard.SetTarget(xda, oCompass.CompassScale)
Storyboard.SetTargetProperty(xda, New PropertyPath(ScaleTransform.ScaleXProperty))
Storyboard.SetTarget(yda, oCompass.CompassScale)
Storyboard.SetTargetProperty(yda, New PropertyPath(ScaleTransform.ScaleYProperty))
sb.Children.Add(xda)
sb.Children.Add(yda)
sb.Begin()
End Sub
Public Property Scale() As Double
Get
Return CDbl(GetValue(ScaleProperty))
End Get
Set(ByVal value As Double)
SetValue(ScaleProperty, value)
End Set
End Property
Public Shared ReadOnly ScaleProperty As DependencyProperty = DependencyProperty.Register("Scale", GetType(Double), GetType(Compass), New PropertyMetadata(1.0R, AddressOf OnScalePropertyChanged))
Private Shared Sub OnScalePropertyChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
Dim compass As Compass = TryCast(d, Compass)
Dim value As Double = Convert.ToDouble(e.NewValue)
compass.dblScale = value
If compass.CompassScale IsNot Nothing Then
compass.CompassScale.ScaleX = value
compass.CompassScale.ScaleY = value
End If
End Sub
Public Property ExpandOnMouseOver() As Boolean
Get
Return CBool(GetValue(ExpandOnMouseOverProperty))
End Get
Set(ByVal value As Boolean)
SetValue(ExpandOnMouseOverProperty, value)
End Set
End Property
Public Shared ReadOnly ExpandOnMouseOverProperty As DependencyProperty = DependencyProperty.Register("ExpandOnMouseOver", GetType(Boolean), GetType(Compass), New PropertyMetadata(False, AddressOf OnExpandOnMouseOverChanged))
Private Shared Sub OnExpandOnMouseOverChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
Dim compass As Compass = TryCast(d, Compass)
Dim obj As Object = e.NewValue
If obj IsNot Nothing Then
RemoveHandler compass.MouseEnter, AddressOf compass.compass_MouseEnter
RemoveHandler compass.MouseLeave, AddressOf compass.compass_MouseLeave
Dim expand As Boolean = CBool(obj)
compass.bexpandOnMouseOver = expand
If expand Then
AddHandler compass.MouseEnter, AddressOf compass.compass_MouseEnter
AddHandler compass.MouseLeave, AddressOf compass.compass_MouseLeave
End If
End If
End Sub
Public Property FaceFill() As Brush
Get
Return CType(GetValue(FaceFillProperty), Brush)
End Get
Set(ByVal value As Brush)
SetValue(FaceFillProperty, value)
End Set
End Property
Public Shared ReadOnly FaceFillProperty As DependencyProperty = DependencyProperty.Register("FaceFill", GetType(Brush), GetType(Compass), New PropertyMetadata(New SolidColorBrush(Color.FromArgb(255, 74, 119, 234)), AddressOf OnFaceFillPropertyChanged))
Private Shared Sub OnFaceFillPropertyChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
Dim compass As Compass = TryCast(d, Compass)
Dim brush As Brush = TryCast(e.NewValue, Brush)
compass.face_Fill = brush
If compass.CompassFace IsNot Nothing Then
compass.CompassFace.Fill = brush
End If
End Sub
End Class
End Namespace
|
Esri/arcgis-templates-silverlight
|
src/TabbedRibbonVB/TabbedRibbonVB/Toolkit/Icons/Compass.vb
|
Visual Basic
|
apache-2.0
| 6,594
|
' Copyright 2013, Google Inc. All Rights Reserved.
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
' Author: api.anash@gmail.com (Anash P. Oommen)
Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201309
Imports System
Imports System.Collections.Generic
Imports System.IO
Namespace Google.Api.Ads.AdWords.Examples.VB.v201309
''' <summary>
''' This code example illustrates how to update an ad group, setting its
''' status to 'PAUSED'. To create an ad group, run AddAdGroup.vb.
'''
''' Tags: AdGroupService.mutate
''' </summary>
Public Class UpdateAdGroup
Inherits ExampleBase
''' <summary>
''' Main method, to run this code example as a standalone application.
''' </summary>
''' <param name="args">The command line arguments.</param>
Public Shared Sub Main(ByVal args As String())
Dim codeExample As New UpdateAdGroup
Console.WriteLine(codeExample.Description)
Try
Dim adGroupId As Long = Long.Parse("INSERT_ADGROUP_ID_HERE")
codeExample.Run(New AdWordsUser, adGroupId)
Catch ex As Exception
Console.WriteLine("An exception occurred while running this code example. {0}", _
ExampleUtilities.FormatException(ex))
End Try
End Sub
''' <summary>
''' Returns a description about the code example.
''' </summary>
Public Overrides ReadOnly Property Description() As String
Get
Return "This code example illustrates how to update an ad group, setting its status " & _
"to 'PAUSED'. To create an ad group, run AddAdGroup.vb"
End Get
End Property
''' <summary>
''' Runs the code example.
''' </summary>
''' <param name="user">The AdWords user.</param>
''' <param name="adGroupId">Id of the ad group to be updated.</param>
Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long)
' Get the AdGroupService.
Dim adGroupService As AdGroupService = user.GetService(AdWordsService.v201309.AdGroupService)
' Create the ad group.
Dim adGroup As New AdGroup
adGroup.status = AdGroupStatus.PAUSED
adGroup.id = adGroupId
' Create the operation.
Dim operation As New AdGroupOperation
operation.operator = [Operator].SET
operation.operand = adGroup
Try
' Update the ad group.
Dim retVal As AdGroupReturnValue = adGroupService.mutate(New AdGroupOperation() {operation})
' Display the results.
If ((Not retVal Is Nothing) AndAlso (Not retVal.value Is Nothing) AndAlso _
(retVal.value.Length > 0)) Then
Dim pausedAdGroup As AdGroup = retVal.value(0)
Console.WriteLine("Ad group with id = '{0}' was successfully updated.", _
pausedAdGroup.id)
Else
Console.WriteLine("No ad groups were updated.")
End If
Catch ex As Exception
Throw New System.ApplicationException("Failed to update ad groups.", ex)
End Try
End Sub
End Class
End Namespace
|
akilb/googleads-adwords-dotnet-lib
|
examples/adxbuyer/VB/v201309/BasicOperations/UpdateAdGroup.vb
|
Visual Basic
|
apache-2.0
| 3,528
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.4927
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Imports System
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Class Resources
Private Shared resourceMan As Global.System.Resources.ResourceManager
Private Shared resourceCulture As Global.System.Globalization.CultureInfo
<Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _
Friend Sub New()
MyBase.New
End Sub
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Shared ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Shared Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set
resourceCulture = value
End Set
End Property
End Class
|
devkimchi/Windows-API-Code-Pack-1.1
|
source/Samples/DirectX/VB/Direct2D/TextInlineImage/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,639
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Host.Mef
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Completion
<ExportCompletionProvider(NameOf(VisualBasicMockCompletionProvider), LanguageNames.VisualBasic)>
<[Shared]>
<PartNotDiscoverable>
Friend Class VisualBasicMockCompletionProvider
Inherits MockCompletionProvider
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Friend Overrides ReadOnly Property Language As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/VisualStudio/Core/Test/Completion/VisualBasicMockCompletionProvider.vb
|
Visual Basic
|
mit
| 989
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Commands
Imports Microsoft.CodeAnalysis.Editor.Shared.Options
Imports Microsoft.CodeAnalysis.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.VisualStudio.Composition
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Operations
Imports Moq
Imports Roslyn.Test.EditorUtilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
Friend Module EndConstructTestingHelpers
Private Function CreateMockIndentationService() As ISmartIndentationService
Dim mock As New Mock(Of ISmartIndentationService)
mock.Setup(Function(service) service.GetDesiredIndentation(It.IsAny(Of ITextView), It.IsAny(Of ITextSnapshotLine))).Returns(0)
Return mock.Object
End Function
<ThreadStatic>
Private t_disabledLineCommitExportProvider As ExportProvider
Private ReadOnly Property DisabledLineCommitExportProvider As ExportProvider
Get
If t_disabledLineCommitExportProvider Is Nothing Then
t_disabledLineCommitExportProvider = TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic()
End If
Return t_disabledLineCommitExportProvider
End Get
End Property
Private Sub DisableLineCommit(workspace As Workspace)
' Disable line commit
Dim optionsService = workspace.Services.GetService(Of IOptionService)()
optionsService.SetOptions(optionsService.GetOptions().WithChangedOption(FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic, False))
End Sub
Private Sub VerifyTypedCharApplied(doFunc As Func(Of VisualBasicEndConstructService, ITextView, ITextBuffer, Boolean),
before As String,
after As String,
typedChar As Char,
endCaretPos As Integer())
Dim caretPos = before.IndexOf("$$", StringComparison.Ordinal)
Dim beforeText = before.Replace("$$", "")
Using workspace = VisualBasicWorkspaceFactory.CreateWorkspaceFromFile(beforeText, exportProvider:=DisabledLineCommitExportProvider)
DisableLineCommit(workspace)
Dim view = workspace.Documents.First().GetTextView()
view.Caret.MoveTo(New SnapshotPoint(view.TextSnapshot, caretPos))
Dim endConstructService As New VisualBasicEndConstructService(
CreateMockIndentationService(),
workspace.GetService(Of ITextUndoHistoryRegistry),
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of IEditorOptionsFactoryService))
view.TextBuffer.Replace(New Span(caretPos, 0), typedChar.ToString())
Assert.True(doFunc(endConstructService, view, view.TextBuffer))
Assert.Equal(after, view.TextSnapshot.GetText())
Dim actualLine As Integer
Dim actualCol As Integer
view.Caret.Position.BufferPosition.GetLineAndColumn(actualLine, actualCol)
Assert.Equal(endCaretPos(0), actualLine)
Assert.Equal(endCaretPos(1), actualCol)
End Using
End Sub
Private Sub VerifyApplied(doFunc As Func(Of VisualBasicEndConstructService, ITextView, ITextBuffer, Boolean),
before As String(),
beforeCaret As Integer(),
after As String(),
afterCaret As Integer())
Using workspace = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(before, exportProvider:=DisabledLineCommitExportProvider)
DisableLineCommit(workspace)
Dim textView = workspace.Documents.First().GetTextView()
Dim subjectBuffer = workspace.Documents.First().GetTextBuffer()
textView.TryMoveCaretToAndEnsureVisible(GetSnapshotPointFromArray(textView, beforeCaret, beforeCaret.Length - 2))
If beforeCaret.Length = 4 Then
Dim span = New SnapshotSpan(
GetSnapshotPointFromArray(textView, beforeCaret, 0),
GetSnapshotPointFromArray(textView, beforeCaret, 2))
textView.SetSelection(span)
End If
Dim endConstructService As New VisualBasicEndConstructService(
CreateMockIndentationService(),
workspace.GetService(Of ITextUndoHistoryRegistry),
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of IEditorOptionsFactoryService))
Assert.True(doFunc(endConstructService, textView, textView.TextSnapshot.TextBuffer))
Assert.Equal(EditorFactory.LinesToFullText(after), textView.TextSnapshot.GetText())
Dim afterLine = textView.TextSnapshot.GetLineFromLineNumber(afterCaret(0))
Dim afterCaretPoint As SnapshotPoint
If afterCaret(1) = -1 Then
afterCaretPoint = afterLine.End
Else
afterCaretPoint = New SnapshotPoint(textView.TextSnapshot, afterLine.Start + afterCaret(1))
End If
Assert.Equal(Of Integer)(afterCaretPoint, textView.GetCaretPoint(subjectBuffer).Value.Position)
End Using
End Sub
Private Function GetSnapshotPointFromArray(view As ITextView, caret As Integer(), startIndex As Integer) As SnapshotPoint
Dim line = view.TextSnapshot.GetLineFromLineNumber(caret(startIndex))
If caret(startIndex + 1) = -1 Then
Return line.End
Else
Return line.Start + caret(startIndex + 1)
End If
End Function
Private Sub VerifyNotApplied(doFunc As Func(Of VisualBasicEndConstructService, ITextView, ITextBuffer, Boolean),
text As String(),
caret As Integer())
Using workspace = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(text)
Dim textView = workspace.Documents.First().GetTextView()
Dim subjectBuffer = workspace.Documents.First().GetTextBuffer()
Dim line = textView.TextSnapshot.GetLineFromLineNumber(caret(0))
Dim caretPosition As SnapshotPoint
If caret(1) = -1 Then
caretPosition = line.End
Else
caretPosition = New SnapshotPoint(textView.TextSnapshot, line.Start + caret(1))
End If
textView.TryMoveCaretToAndEnsureVisible(caretPosition)
Dim endConstructService As New VisualBasicEndConstructService(
CreateMockIndentationService(),
workspace.GetService(Of ITextUndoHistoryRegistry),
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of IEditorOptionsFactoryService))
Assert.False(doFunc(endConstructService, textView, textView.TextSnapshot.TextBuffer), "End Construct should not have generated anything.")
' The text should not have changed
Assert.Equal(EditorFactory.LinesToFullText(text), textView.TextSnapshot.GetText())
' The caret should not have moved
Assert.Equal(Of Integer)(caretPosition, textView.GetCaretPoint(subjectBuffer).Value.Position)
End Using
End Sub
Public Sub VerifyStatementEndConstructApplied(before As String(), beforeCaret As Integer(), after As String(), afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoEndConstructForEnterKey(v, b, CancellationToken.None), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyStatementEndConstructNotApplied(text As String(), caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoEndConstructForEnterKey(v, b, CancellationToken.None), text, caret)
End Sub
Public Sub VerifyXmlElementEndConstructApplied(before As String(), beforeCaret As Integer(), after As String(), afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoXmlElementEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyXmlElementEndConstructNotApplied(text As String(), caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoXmlElementEndConstruct(v, b, Nothing), text, caret)
End Sub
Public Sub VerifyXmlCommentEndConstructApplied(before As String(), beforeCaret As Integer(), after As String(), afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoXmlCommentEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyXmlCommentEndConstructNotApplied(text As String(), caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoXmlCommentEndConstruct(v, b, Nothing), text, caret)
End Sub
Public Sub VerifyXmlCDataEndConstructApplied(before As String(), beforeCaret As Integer(), after As String(), afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoXmlCDataEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyXmlCDataEndConstructNotApplied(text As String(), caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoXmlCDataEndConstruct(v, b, Nothing), text, caret)
End Sub
Public Sub VerifyXmlEmbeddedExpressionEndConstructApplied(before As String(), beforeCaret As Integer(), after As String(), afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoXmlEmbeddedExpressionEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyXmlEmbeddedExpressionEndConstructNotApplied(text As String(), caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoXmlEmbeddedExpressionEndConstruct(v, b, Nothing), text, caret)
End Sub
Public Sub VerifyXmlProcessingInstructionEndConstructApplied(before As String(), beforeCaret As Integer(), after As String(), afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoXmlProcessingInstructionEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyXmlProcessingInstructionNotApplied(text As String(), caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoXmlProcessingInstructionEndConstruct(v, b, Nothing), text, caret)
End Sub
Public Sub VerifyEndConstructAppliedAfterChar(before As String, after As String, typedChar As Char, endCaretPos As Integer())
VerifyTypedCharApplied(Function(s, v, b) s.TryDo(v, b, typedChar, Nothing), before, after, typedChar, endCaretPos)
End Sub
Public Sub VerifyEndConstructNotAppliedAfterChar(before As String, after As String, typedChar As Char, endCaretPos As Integer())
VerifyTypedCharApplied(Function(s, v, b) Not s.TryDo(v, b, typedChar, Nothing), before, after, typedChar, endCaretPos)
End Sub
Public Sub VerifyAppliedAfterReturnUsingCommandHandler(
before As String,
beforeCaret As Integer(),
after As String,
afterCaret As Integer())
' create separate composition
Using workspace = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines({before}, exportProvider:=DisabledLineCommitExportProvider)
DisableLineCommit(workspace)
Dim view = workspace.Documents.First().GetTextView()
Dim line = view.TextSnapshot.GetLineFromLineNumber(beforeCaret(0))
If beforeCaret(1) = -1 Then
view.Caret.MoveTo(line.End)
Else
view.Caret.MoveTo(New SnapshotPoint(view.TextSnapshot, line.Start + beforeCaret(1)))
End If
Dim factory = workspace.ExportProvider.GetExportedValue(Of IEditorOperationsFactoryService)()
Dim endConstructor = New EndConstructCommandHandler(
factory,
workspace.ExportProvider.GetExportedValue(Of ITextUndoHistoryRegistry)())
Dim operations = factory.GetEditorOperations(view)
endConstructor.ExecuteCommand_ReturnKeyCommandHandler(New ReturnKeyCommandArgs(view, view.TextBuffer), Sub() operations.InsertNewLine())
Assert.Equal(after, view.TextSnapshot.GetText())
Dim afterLine = view.TextSnapshot.GetLineFromLineNumber(afterCaret(0))
Dim afterCaretPoint As Integer
If afterCaret(1) = -1 Then
afterCaretPoint = afterLine.End
Else
afterCaretPoint = afterLine.Start + afterCaret(1)
End If
Dim caretPosition = view.Caret.Position.VirtualBufferPosition
Assert.Equal(Of Integer)(afterCaretPoint, If(caretPosition.IsInVirtualSpace, caretPosition.Position + caretPosition.VirtualSpaces, caretPosition.Position))
End Using
End Sub
End Module
End Namespace
|
jbhensley/roslyn
|
src/EditorFeatures/VisualBasicTest/EndConstructGeneration/EndConstructTestingHelpers.vb
|
Visual Basic
|
apache-2.0
| 14,123
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.ComponentModel.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities.CommandHandlers
Imports Microsoft.CodeAnalysis.ImplementAbstractClass
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.Text.Operations
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.ImplementAbstractClass
<ExportCommandHandler("ImplementAbstractClassCommandHandler", ContentTypeNames.VisualBasicContentType)>
<Order(Before:=PredefinedCommandHandlerNames.EndConstruct)>
<Order(After:=PredefinedCommandHandlerNames.Completion)>
Friend Class ImplementAbstractClassCommandHandler
Inherits AbstractImplementAbstractClassOrInterfaceCommandHandler
<ImportingConstructor>
Public Sub New(editorOperationsFactoryService As IEditorOperationsFactoryService)
MyBase.New(editorOperationsFactoryService)
End Sub
Protected Overrides Function TryGetNewDocument(
document As Document,
typeSyntax As TypeSyntax,
cancellationToken As CancellationToken
) As Document
If typeSyntax.Parent.Kind <> SyntaxKind.InheritsStatement Then
Return Nothing
End If
Dim classBlock = TryCast(typeSyntax.Parent.Parent, ClassBlockSyntax)
If classBlock Is Nothing Then
Return Nothing
End If
Dim service = document.GetLanguageService(Of IImplementAbstractClassService)()
Dim updatedDocument = service.ImplementAbstractClassAsync(document, classBlock, cancellationToken).WaitAndGetResult(cancellationToken)
If updatedDocument IsNot Nothing AndAlso
updatedDocument.GetTextChangesAsync(document, cancellationToken).WaitAndGetResult(cancellationToken).Count = 0 Then
Return Nothing
End If
Return updatedDocument
End Function
End Class
End Namespace
|
bbarry/roslyn
|
src/EditorFeatures/VisualBasic/ImplementAbstractClass/ImplementAbstractClassCommandHandler.vb
|
Visual Basic
|
apache-2.0
| 2,186
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Option Strict Off
Imports System
Imports System.Collections.Generic
Imports System.Globalization
Module Module1
Sub Main()
Dim BoFalse As Boolean
Dim BoTrue As Boolean
Dim SB As SByte
Dim By As Byte
Dim Sh As Short
Dim US As UShort
Dim [In] As Integer
Dim UI As UInteger
Dim Lo As Long
Dim UL As ULong
Dim De As Decimal
Dim Si As Single
Dim [Do] As Double
Dim SBZero As SByte
Dim ByZero As Byte
Dim ShZero As Short
Dim USZero As UShort
Dim [InZero] As Integer
Dim UIZero As UInteger
Dim LoZero As Long
Dim ULZero As ULong
Dim DeZero As Decimal
Dim SiZero As Single
Dim [DoZero] As Double
Dim St As String
Dim StDate As String
Dim Ob As Object
Dim ObDate As Object
Dim ObChar As Object
Dim ObString As Object
Dim ObGuid As Object
Dim Tc As System.TypeCode
Dim Da As Date
Dim Ch As Char
Dim guidVal As Guid
Dim IEnumerableString As IEnumerable(Of Char)
BoFalse = False
BoTrue = True
SB = 1
By = 2
Sh = 3
US = 4
[In] = 5
UI = 6
Lo = 7
UL = 8
Si = 10
[Do] = 11
De = 9D
St = "12"
Ob = 13
Da = #8:30:00 AM#
StDate = "8:30"
ObDate = Da
Ch = "c"c
ObChar = Ch
ObString = St
SBZero = 0
ByZero = 0
ShZero = 0
USZero = 0
[InZero] = 0
UIZero = 0
LoZero = 0
ULZero = 0
SiZero = 0
[DoZero] = 0
DeZero = 0
guidVal = New Guid()
ObGuid = guidVal
IEnumerableString = St
System.Console.WriteLine("Conversions to Boolean:")
PrintResultBo(SB)
PrintResultBo(By)
PrintResultBo(Sh)
PrintResultBo(US)
PrintResultBo([In])
PrintResultBo(UI)
PrintResultBo(Lo)
PrintResultBo(UL)
PrintResultBo(Si)
PrintResultBo([Do])
PrintResultBo(De)
PrintResultBo(SBZero)
PrintResultBo(ByZero)
PrintResultBo(ShZero)
PrintResultBo(USZero)
PrintResultBo([InZero])
PrintResultBo(UIZero)
PrintResultBo(LoZero)
PrintResultBo(ULZero)
PrintResultBo(SiZero)
PrintResultBo([DoZero])
PrintResultBo(DeZero)
System.Console.WriteLine()
System.Console.WriteLine("Conversions from Boolean:")
PrintResultSB(BoFalse)
PrintResultBy(BoFalse)
PrintResultSh(BoFalse)
PrintResultUs(BoFalse)
PrintResultIn(BoFalse)
PrintResultUI(BoFalse)
PrintResultLo(BoFalse)
PrintResultUL(BoFalse)
PrintResultSi(BoFalse)
PrintResultDo(BoFalse)
PrintResultDe(BoFalse)
PrintResultSB(BoTrue)
PrintResultBy(BoTrue)
PrintResultSh(BoTrue)
PrintResultUs(BoTrue)
PrintResultIn(BoTrue)
PrintResultUI(BoTrue)
PrintResultLo(BoTrue)
PrintResultUL(BoTrue)
PrintResultSi(BoTrue)
PrintResultDo(BoTrue)
PrintResultDe(BoTrue)
System.Console.WriteLine()
System.Console.WriteLine("Conversions between numeric types:")
PrintResultSB(SB)
PrintResultSB(By)
PrintResultSB(Sh)
PrintResultSB(US)
PrintResultSB([In])
PrintResultSB(UI)
PrintResultSB(Lo)
PrintResultSB(UL)
PrintResultSB(Si)
PrintResultSB([Do])
PrintResultSB(2.5F)
PrintResultSB(3.5R)
PrintResultSB(De)
PrintResultBy(SB)
PrintResultBy(By)
PrintResultBy(Sh)
PrintResultBy(US)
PrintResultBy([In])
PrintResultBy(UI)
PrintResultBy(Lo)
PrintResultBy(UL)
PrintResultBy(Si)
PrintResultBy([Do])
PrintResultBy(2.5F)
PrintResultBy(3.5R)
PrintResultBy(De)
PrintResultSh(SB)
PrintResultSh(By)
PrintResultSh(Sh)
PrintResultSh(US)
PrintResultSh([In])
PrintResultSh(UI)
PrintResultSh(Lo)
PrintResultSh(UL)
PrintResultSh(Si)
PrintResultSh([Do])
PrintResultSh(2.5F)
PrintResultSh(3.5R)
PrintResultSh(De)
PrintResultUS(SB)
PrintResultUS(By)
PrintResultUS(Sh)
PrintResultUS(US)
PrintResultUS([In])
PrintResultUS(UI)
PrintResultUS(Lo)
PrintResultUS(UL)
PrintResultUS(Si)
PrintResultUS([Do])
PrintResultUS(2.5F)
PrintResultUS(3.5R)
PrintResultUS(De)
PrintResultIn(SB)
PrintResultIn(By)
PrintResultIn(Sh)
PrintResultIn(US)
PrintResultIn([In])
PrintResultIn(UI)
PrintResultIn(Lo)
PrintResultIn(UL)
PrintResultIn(Si)
PrintResultIn([Do])
PrintResultIn(2.5F)
PrintResultIn(3.5R)
PrintResultIn(De)
PrintResultUI(SB)
PrintResultUI(By)
PrintResultUI(Sh)
PrintResultUI(US)
PrintResultUI([In])
PrintResultUI(UI)
PrintResultUI(Lo)
PrintResultUI(UL)
PrintResultUI(Si)
PrintResultUI([Do])
PrintResultUI(2.5F)
PrintResultUI(3.5R)
PrintResultUI(De)
PrintResultLo(SB)
PrintResultLo(By)
PrintResultLo(Sh)
PrintResultLo(US)
PrintResultLo([In])
PrintResultLo(UI)
PrintResultLo(Lo)
PrintResultLo(UL)
PrintResultLo(Si)
PrintResultLo([Do])
PrintResultLo(2.5F)
PrintResultLo(3.5R)
PrintResultLo(De)
PrintResultUL(SB)
PrintResultUL(By)
PrintResultUL(Sh)
PrintResultUL(US)
PrintResultUL([In])
PrintResultUL(UI)
PrintResultUL(Lo)
PrintResultUL(UL)
PrintResultUL(Si)
PrintResultUL([Do])
PrintResultUL(2.5F)
PrintResultUL(3.5R)
PrintResultUL(De)
PrintResultSi(SB)
PrintResultSi(By)
PrintResultSi(Sh)
PrintResultSi(US)
PrintResultSi([In])
PrintResultSi(UI)
PrintResultSi(Lo)
PrintResultSi(UL)
PrintResultSi(Si)
PrintResultSi([Do])
PrintResultSi(2.5F)
PrintResultSi(3.5R)
PrintResultSi(De)
PrintResultDo(SB)
PrintResultDo(By)
PrintResultDo(Sh)
PrintResultDo(US)
PrintResultDo([In])
PrintResultDo(UI)
PrintResultDo(Lo)
PrintResultDo(UL)
PrintResultDo(Si)
PrintResultDo([Do])
PrintResultDo(2.5F)
PrintResultDo(3.5R)
PrintResultDo(De)
PrintResultDe(SB)
PrintResultDe(By)
PrintResultDe(Sh)
PrintResultDe(US)
PrintResultDe([In])
PrintResultDe(UI)
PrintResultDe(Lo)
PrintResultDe(UL)
PrintResultDe(Si)
PrintResultDe([Do])
PrintResultDe(2.5F)
PrintResultDe(3.5R)
PrintResultDe(De)
System.Console.WriteLine()
System.Console.WriteLine("Conversions to String:")
PrintResultSt(BoFalse)
PrintResultSt(BoTrue)
PrintResultSt(SB)
PrintResultSt(By)
PrintResultSt(Sh)
PrintResultSt(US)
PrintResultSt([In])
PrintResultSt(UI)
PrintResultSt(Lo)
PrintResultSt(UL)
PrintResultSt(Si)
PrintResultSt([Do])
PrintResultSt(De)
PrintResultSt(Da.ToString("h:mm:ss tt", cul))
PrintResultSt(Ch)
PrintResultSt(Ob)
PrintResultSt(St.ToCharArray())
System.Console.WriteLine()
System.Console.WriteLine("Conversions from String:")
PrintResultBo("False")
PrintResultBo("True")
PrintResultSB(St)
PrintResultBy(St)
PrintResultSh(St)
PrintResultUs(St)
PrintResultIn(St)
PrintResultUI(St)
PrintResultLo(St)
PrintResultUL(St)
PrintResultSi(St)
PrintResultDo(St)
PrintResultDe(St)
PrintResultDa(StDate)
PrintResultCh(St)
PrintResultSZCh(St)
System.Console.WriteLine()
System.Console.WriteLine("Conversions from Object:")
PrintResultBo(Ob)
PrintResultSB(Ob)
PrintResultBy(Ob)
PrintResultSh(Ob)
PrintResultUs(Ob)
PrintResultIn(Ob)
PrintResultUI(Ob)
PrintResultLo(Ob)
PrintResultUL(Ob)
PrintResultSi(Ob)
PrintResultDo(Ob)
PrintResultDe(Ob)
PrintResultDa(ObDate)
PrintResultCh(ObChar)
PrintResultSZCh(ObString)
' The string return will change based on system locale
' Apply ToString("h:mm:ss tt", cul) on ObData defeat the purpose of this scenario
'PrintResultSt(GenericParamTestHelperOfString.ObjectToT(ObDate))
End Sub
Dim cul As System.Globalization.CultureInfo = System.Globalization.CultureInfo.InvariantCulture
Class GenericParamTestHelper(Of T)
Public Shared Function ObjectToT(val As Object) As T
Return val
End Function
Public Shared Function TToObject(val As T) As Object
Return val
End Function
Public Shared Function TToIComparable(val As T) As IComparable
Return val
End Function
Public Shared Function IComparableToT(val As IComparable) As T
Return val
End Function
End Class
Class GenericParamTestHelperOfString
Inherits GenericParamTestHelper(Of String)
End Class
Class GenericParamTestHelperOfGuid
Inherits GenericParamTestHelper(Of Guid)
End Class
Sub PrintResultBo(val As Boolean)
System.Console.WriteLine("Boolean: {0}", val)
End Sub
Sub PrintResultSB(val As SByte)
System.Console.WriteLine("SByte: {0}", val)
End Sub
Sub PrintResultBy(val As Byte)
System.Console.WriteLine("Byte: {0}", val)
End Sub
Sub PrintResultSh(val As Short)
System.Console.WriteLine("Short: {0}", val)
End Sub
Sub PrintResultUs(val As UShort)
System.Console.WriteLine("UShort: {0}", val)
End Sub
Sub PrintResultIn(val As Integer)
System.Console.WriteLine("Integer: {0}", val)
End Sub
Sub PrintResultUI(val As UInteger)
System.Console.WriteLine("UInteger: {0}", val)
End Sub
Sub PrintResultLo(val As Long)
System.Console.WriteLine("Long: {0}", val)
End Sub
Sub PrintResultUL(val As ULong)
System.Console.WriteLine("ULong: {0}", val)
End Sub
Sub PrintResultDe(val As Decimal)
System.Console.WriteLine("Decimal: {0}", val.ToString(cul))
End Sub
Sub PrintResultSi(val As Single)
System.Console.WriteLine("Single: {0}", val.ToString(cul))
End Sub
Sub PrintResultDo(val As Double)
System.Console.WriteLine("Double: {0}", val.ToString(cul))
End Sub
Sub PrintResultDa(val As Date)
System.Console.WriteLine("Date: {0}", val.ToString("M/d/yyyy h:mm:ss tt", cul))
End Sub
Sub PrintResultCh(val As Char)
System.Console.WriteLine("Char: {0}", val)
End Sub
Sub PrintResultSZCh(val As Char())
System.Console.WriteLine("Char(): {0}", New String(val))
End Sub
Sub PrintResultSt(val As String)
System.Console.WriteLine("String: {0}", val)
End Sub
Sub PrintResultOb(val As Object)
System.Console.WriteLine("Object: {0}", val)
End Sub
Sub PrintResultGuid(val As System.Guid)
System.Console.WriteLine("Guid: {0}", val)
End Sub
Sub PrintResultIComparable(val As IComparable)
System.Console.WriteLine("IComparable: {0}", val)
End Sub
Sub PrintResultValueType(val As ValueType)
System.Console.WriteLine("ValueType: {0}", val)
End Sub
End Module
|
mmitche/roslyn
|
src/Compilers/VisualBasic/Test/Emit/CodeGen/ConversionsILGenTestSource.vb
|
Visual Basic
|
apache-2.0
| 12,211
|
#Region "Microsoft.VisualBasic::84d199653bb466c7f4dcf8dc477867a3, src\mzmath\ms2_simulator\GA\GA.vb"
' Author:
'
' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.)
'
' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD.
'
'
' MIT License
'
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
' /********************************************************************************/
' Summaries:
' Module GA
'
'
'
' /********************************************************************************/
#End Region
''' <summary>
''' The genetic algorithm core for the simulator.
''' </summary>
Public Module GA
End Module
|
xieguigang/spectrum
|
src/mzmath/ms2_simulator/GA/GA.vb
|
Visual Basic
|
mit
| 1,671
|
Imports System.Data
Imports System.Data.SqlServerCe
Imports System.Windows.Forms.DataVisualization.Charting
Imports System.IO
Public Class frmOeeProgress
Private Sub frmOeeProgress_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en")
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture
Me.Width = frmOEEMain.Width
Me.Height = frmOEEMain.pnlDetails.Height
chaActivityChart.Width = Me.Width - chaActivityChart.Location.X - 10
chaActivityChart.Height = Me.Height - chaActivityChart.Location.Y - 10
lblTimeScale.Location = New Point(lblTimeScale.Location.X, Me.Height - 25)
grpSelection.Height = Me.Height - grpSelection.Location.Y - 10
'chaActivityChart.ChartAreas(0).AxisY.LabelStyle.IsEndLabelVisible = False
'chaActivityChart.ChartAreas(0).AxisY.LabelStyle.Enabled = False
chaActivityChart.ChartAreas(0).AxisX.MajorGrid.Enabled = False
chaActivityChart.ChartAreas(0).AxisX.MinorGrid.Enabled = False
chaActivityChart.ChartAreas(0).AxisX.MajorTickMark.Enabled = False
chaActivityChart.ChartAreas(0).AxisX.MinorTickMark.Enabled = False
chaActivityChart.ChartAreas(0).AxisY.MajorGrid.Enabled = False
chaActivityChart.ChartAreas(0).AxisY.MinorGrid.Enabled = False
chaActivityChart.ChartAreas(0).AxisY.MajorTickMark.Enabled = False
chaActivityChart.ChartAreas(0).AxisY.MinorTickMark.Enabled = False
Try
dtpFromDate.Value = garrTeamShift.datStartShift.AddDays(-2)
Catch ex As Exception
End Try
dtpFromTime.Format = DateTimePickerFormat.Custom
dtpFromTime.CustomFormat = "HH:mm tt"
dtpFromTime.ShowUpDown = True
dtpToTime.Format = DateTimePickerFormat.Custom
dtpToTime.CustomFormat = "HH:mm tt"
dtpToTime.ShowUpDown = True
Call mfblnRefresh(gintSelectedMach)
End Sub
Public Function mfblnRefresh(ByVal intSelMach As Integer) As Boolean
Dim dtaTable2 As New DataTable()
Dim strSqlQuery As String
Dim rstOEEProgress As ADODB.Recordset
Dim strSqlWhereDateAdditive As String
Dim datStartDateTime As DateTime
Dim datEndDateTime As DateTime
Dim intX As Integer
Dim dblDurationPlus As Integer
Dim intY As Integer
Dim dblMaxY As Double
Dim intInterval As Integer
strSqlWhereDateAdditive = ""
If chkCurrentShift.Checked = True Then
datStartDateTime = garrTeamShift.datStartShift
strSqlWhereDateAdditive = "WHERE fldOeeStartDateTime > '" & gfstrDatToStr(datStartDateTime) & "' "
End If
If chkLast24Hours.Checked = True Then
datStartDateTime = garrTeamShift.datStartShift.AddDays(-1)
strSqlWhereDateAdditive = "WHERE (fldOeeStartDateTime > '" & gfstrDatToStr(datStartDateTime) & "') "
End If
If chkFromToDate.Checked = True Then
datStartDateTime = New DateTime(dtpFromDate.Value.Year, dtpFromDate.Value.Month, dtpFromDate.Value.Day, dtpFromTime.Value.Hour, _
dtpFromTime.Value.Minute, 0)
datEndDateTime = New DateTime(dtpToDate.Value.Year, dtpToDate.Value.Month, dtpToDate.Value.Day, dtpToTime.Value.Hour, _
dtpToTime.Value.Minute, 0)
strSqlWhereDateAdditive = "WHERE (fldOeeStartDateTime >'" & gfstrDatToStr(datStartDateTime) & "') " & _
"AND (fldOeeStartDateTime < '" & gfstrDatToStr(datEndDateTime) & "') "
End If
strSqlQuery = "SELECT fldOeeProgressTableKeyID, " & _
" fldOeeCurrentOee, " & _
" fldOeeCurrentAvailability, " & _
" fldOeeCurrentPerformance, " & _
" fldOeeCurrentQuality, " & _
" fldOeeActivityDuration " & _
"FROM tblOee_Progress " & _
strSqlWhereDateAdditive & _
"AND (fldOeeCountryID = " & garrMachine(intSelMach).intCountryNr & ") " & _
"AND (fldOeePlantID = " & garrMachine(intSelMach).intPlantNr & ") " & _
"AND (fldOeeSubPlantID = " & garrMachine(intSelMach).intSubPlantNr & ") " & _
"AND (fldOeeDepartmentID = " & garrMachine(intSelMach).intDepartmentNr & ") " & _
"AND (tblOee_Progress.fldOeeMachineID = '" & garrMachine(intSelMach).intMachineNr & "') " & _
"ORDER BY fldOeeStartDateTime"
rstOEEProgress = gfconvertToADODB(gdtaSqlCeTable(strSqlQuery))
If rstOEEProgress Is Nothing Then
Exit Function
End If
'build datatable to bind to the oee chart
dtaTable2.Columns.Add("fldActivityDurationValue", GetType(Integer))
dtaTable2.Columns.Add("fldAvailabilityValue", GetType(Integer))
dtaTable2.Columns.Add("fldPerformanceValue", GetType(Integer))
dtaTable2.Columns.Add("fldQualityValue", GetType(Integer))
dtaTable2.Columns.Add("fldOEEValue", GetType(Integer))
'add data to oee datatable
If Not rstOEEProgress.EOF Then
rstOEEProgress.MoveFirst()
For intX = 0 To rstOEEProgress.RecordCount - 1
dblDurationPlus = dblDurationPlus + (rstOEEProgress.Fields("fldOeeActivityDuration").Value / 60)
dtaTable2.Rows.Add(dblDurationPlus, rstOEEProgress.Fields("fldOeeCurrentAvailability").Value, _
rstOEEProgress.Fields("fldOeeCurrentPerformance").Value, rstOEEProgress.Fields("fldOeeCurrentQuality").Value, _
rstOEEProgress.Fields("fldOeeCurrentOee").Value)
rstOEEProgress.MoveNext()
Next
Else
Exit Function
End If
'adjust interval oee chart
dblMaxY = dblDurationPlus
intInterval = dblMaxY / 10
For intY = 1 To dblMaxY
If dblMaxY / intY <= 10 Then
If Len(CStr(intY)) > 1 Then
For intX = 1 To 10
If Mid(CStr(intX + intY), Len(CStr(intX + intY))) = "0" Then
intInterval = intX + intY
Exit For
End If
Next
End If
Exit For
End If
Next
'set interval oee chart
With chaActivityChart.ChartAreas(0)
.AxisY.Title = "Percentage"
.AxisY.Minimum = 0
.AxisX.Minimum = 0
.AxisY.Maximum = 100
.AxisY.Interval = 10
.AxisX.Interval = intInterval
End With
'bind column from oee datatable to oee chart
With chaActivityChart.Series(0)
.Points.DataBind(dtaTable2.DefaultView, "fldActivityDurationValue", "fldAvailabilityValue", Nothing)
.ChartType = DataVisualization.Charting.SeriesChartType.Line
.BorderWidth = 2
.IsVisibleInLegend = False
End With
With chaActivityChart.Series(1)
.Points.DataBind(dtaTable2.DefaultView, "fldActivityDurationValue", "fldPerformanceValue", Nothing)
.ChartType = DataVisualization.Charting.SeriesChartType.Line
.BorderWidth = 2
.IsVisibleInLegend = False
End With
With chaActivityChart.Series(2)
.Points.DataBind(dtaTable2.DefaultView, "fldActivityDurationValue", "fldQualityValue", Nothing)
.ChartType = DataVisualization.Charting.SeriesChartType.Line
.BorderWidth = 2
.IsVisibleInLegend = False
End With
With chaActivityChart.Series(3)
.Points.DataBind(dtaTable2.DefaultView, "fldActivityDurationValue", "fldOEEValue", Nothing)
.ChartType = DataVisualization.Charting.SeriesChartType.Line
.BorderWidth = 2
.IsVisibleInLegend = False
End With
'set color
rstOEEProgress.MoveFirst()
For intX = 0 To (rstOEEProgress.RecordCount - 1)
chaActivityChart.Series(0).Points.ElementAt(intX).Color = Color.Yellow
chaActivityChart.Series(0).Points(intX).Color = Color.Yellow
chaActivityChart.Series(1).Points.ElementAt(intX).Color = Color.Red
chaActivityChart.Series(1).Points(intX).Color = Color.Red
chaActivityChart.Series(2).Points.ElementAt(intX).Color = Color.Blue
chaActivityChart.Series(2).Points(intX).Color = Color.Blue
chaActivityChart.Series(3).Points.ElementAt(intX).Color = Color.Lime
chaActivityChart.Series(3).Points(intX).Color = Color.Lime
rstOEEProgress.MoveNext()
Next
chaActivityChart.Legends.Clear()
chaActivityChart.Legends.Add(New Legend("Default"))
chaActivityChart.Legends("Default").Docking = Docking.Right
chaActivityChart.Legends("Default").Alignment = StringAlignment.Near
chaActivityChart.Legends("Default").Font = New System.Drawing.Font("Calibri", 11, System.Drawing.FontStyle.Regular)
chaActivityChart.Legends("Default").BorderColor = Color.White
chaActivityChart.Legends("Default").CustomItems.Add(Color.Yellow, "Availability")
chaActivityChart.Legends("Default").CustomItems.Add(Color.Red, "Performance")
chaActivityChart.Legends("Default").CustomItems.Add(Color.Blue, "Quality")
chaActivityChart.Legends("Default").CustomItems.Add(Color.Lime, "OEE Score")
For intX = 0 To 3
chaActivityChart.Legends("Default").CustomItems(intX).BorderColor = Color.White
Next
End Function
Private Sub chkCurrentShift_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkCurrentShift.CheckedChanged
If chkCurrentShift.Checked Then
chkLast24Hours.Checked = False
chkFromToDate.Checked = False
Else
If chkLast24Hours.Checked = False And chkFromToDate.Checked = False Then
chkCurrentShift.Checked = True
End If
End If
End Sub
Private Sub chkLast24Hours_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkLast24Hours.CheckedChanged
If chkLast24Hours.Checked Then
chkCurrentShift.Checked = False
chkFromToDate.Checked = False
Else
If chkCurrentShift.Checked = False And chkFromToDate.Checked = False Then
chkLast24Hours.Checked = True
End If
End If
End Sub
Private Sub chkFromToDate_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkFromToDate.CheckedChanged
If chkFromToDate.Checked Then
chkCurrentShift.Checked = False
chkLast24Hours.Checked = False
Else
If chkLast24Hours.Checked = False And chkCurrentShift.Checked = False Then
chkFromToDate.Checked = True
End If
End If
End Sub
Private Sub tmrRefresh_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrRefresh.Tick
mfblnRefresh(gintSelectedMach)
End Sub
End Class
|
twister077/OEECollectorAndOEEWeb
|
VB.NET/OEECollector/frmOEEProgress.vb
|
Visual Basic
|
mit
| 11,418
|
Public Class translate
Public row As Int16 = 1
Public column As Int16 = 1
Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
MainMenu.cbLanguage.SelectedIndex = MainMenu.iSavedLanguageIndex
Me.Hide()
End Sub
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
Main.sLocalizationStrings(row, Main.iLanguageSelected) = tbTarget.Text
Main.writeLocalizationFile()
Main.readLocalizationFile()
MainMenu.fillLanguageControl()
Me.Hide()
Me.Close()
MainMenu.cbLanguage.SelectedIndex = MainMenu.iSavedLanguageIndex
End Sub
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.btnForward.BackColor = Color.LightGray
Me.btnOK.BackColor = Color.LawnGreen
End Sub
Public Sub loadTranslate(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
fillControls()
Dim iAddLanguage = MainMenu.cbLanguage.Items.Count - 1
' This example assumes that the Form_Load event handling method
' is connected to the Load event of the form.
' Create the ToolTip and associate with the Form container.
Dim toolTip1 As New ToolTip()
' Set up the delays for the ToolTip.
toolTip1.AutoPopDelay = 5000
toolTip1.InitialDelay = 1000
toolTip1.ReshowDelay = 500
' Force the ToolTip text to be displayed whether or not the form is active.
toolTip1.ShowAlways = True
' Set up the ToolTip text for the Buttons and Textbox.
If MainMenu.cbLanguage.SelectedIndex = iAddLanguage Then
' use English
toolTip1.SetToolTip(Me.btnBack, Main.sLocalizationStrings(Main.iBackAndCancelChange, 1))
toolTip1.SetToolTip(Me.btnForward, Main.sLocalizationStrings(Main.iSaveChangeAndSeeNext, 1))
toolTip1.SetToolTip(Me.btnStart, Main.sLocalizationStrings(Main.iStartText, 1))
toolTip1.SetToolTip(Me.tbSource, Main.sLocalizationStrings(Main.iTypeInOtherBox, 1))
toolTip1.SetToolTip(Me.btnOK, Main.sLocalizationStrings(Main.iSaveChangeAndCloseMenu, 1))
toolTip1.SetToolTip(Me.btnCancel, Main.sLocalizationStrings(Main.iCancelChangeAndCloseMenu, 1))
Else
toolTip1.SetToolTip(Me.btnBack, Main.sLocalizationStrings(Main.iBackAndCancelChange, Main.iLanguageSelected))
toolTip1.SetToolTip(Me.btnForward, Main.sLocalizationStrings(Main.iSaveChangeAndSeeNext, Main.iLanguageSelected))
toolTip1.SetToolTip(Me.btnStart, Main.sLocalizationStrings(Main.iStartText, Main.iLanguageSelected))
toolTip1.SetToolTip(Me.tbSource, Main.sLocalizationStrings(Main.iTypeInOtherBox, Main.iLanguageSelected))
toolTip1.SetToolTip(Me.btnOK, Main.sLocalizationStrings(Main.iSaveChangeAndCloseMenu, Main.iLanguageSelected))
toolTip1.SetToolTip(Me.btnCancel, Main.sLocalizationStrings(Main.iCancelChangeAndCloseMenu, Main.iLanguageSelected))
End If
End Sub
Public Sub fillControls()
Try
' Public sLocalizationStrings(, iMaximumLocalizationLanguages) As String
Debug.Assert(column < Main.iMaximumLocalizationLanguages + 2, "column greater than maximum allowed languages in fill translate controls")
Debug.Assert(column > 0, "column equals 0 in fill translate controls")
Me.tbSource.Text = Main.sLocalizationStrings(row, 1)
Me.tbTarget.Text = Main.sLocalizationStrings(row, Main.iLanguageSelected)
Me.lblLocation.Text = currentLocation()
Catch ex As Exception
MessageBox.Show("Problem filling current location in translate control." & vbCrLf & ex.Message, "Error in translate.", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End Try
End Sub
Private Sub btnForward_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnForward.Click
Main.sLocalizationStrings(row, Main.iLanguageSelected) = tbTarget.Text
' row += 1
If row = Main.iMaximumLocalizationStrings Then Beep() : row = Main.iMaximumLocalizationStrings
fillControls()
Me.btnForward.BackColor = Color.LightGray
Main.writeLocalizationFile()
End Sub
Private Sub btnForward_RightClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnForward.Click
Main.sLocalizationStrings(row, Main.iLanguageSelected) = tbTarget.Text
row += 1
If row = Main.iMaximumLocalizationStrings Then Beep() : row = Main.iMaximumLocalizationStrings
fillControls()
Me.btnForward.BackColor = Color.LightGray
End Sub
Private Sub btnBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBack.Click
row -= 1
If row = 0 Then Beep() : row = 1
fillControls()
Me.btnForward.BackColor = Color.LightGray
End Sub
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
row = 1
fillControls()
End Sub
Private Function currentLocation()
Return row.ToString & ", " & Main.iLanguageSelected.ToString
End Function
Private Sub tbTarget_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbTarget.TextChanged
Me.btnForward.BackColor = Color.LimeGreen
End Sub
Private Sub tbSource_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbSource.TextChanged
fillControls()
End Sub
Private Sub btnFastForward_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFastForward.Click
Main.sLocalizationStrings(row, Main.iLanguageSelected) = tbTarget.Text
row += 10
If row = Main.iMaximumLocalizationStrings Then Beep() : row = Main.iMaximumLocalizationStrings
fillControls()
Me.btnForward.BackColor = Color.LightGray
End Sub
End Class
|
nognkantoor/dramatizer
|
Zany/translate.vb
|
Visual Basic
|
mit
| 6,311
|
Imports System
Imports Independentsoft.Office.Word
Imports Independentsoft.Office.Word.Tables
Module Module1
Sub Main(ByVal args() As String)
Dim doc As New WordDocument("c:\test\input.docx")
For i As Integer = 0 To doc.Body.Content.Count - 1
If TypeOf doc.Body.Content(i) Is Paragraph Then
Dim paragraph As Paragraph = DirectCast(doc.Body.Content(i), Paragraph)
Dim bookmarkId As Long = -1
Dim contentToRemove As IList(Of IParagraphContent) = New List(Of IParagraphContent)()
For Each pContent As IParagraphContent In paragraph.Content
If TypeOf pContent Is BookmarkStart Then
Dim bookmarkStart As BookmarkStart = DirectCast(pContent, BookmarkStart)
If bookmarkStart.Name = "REMOVE" Then
bookmarkId = bookmarkStart.ID
End If
ElseIf TypeOf pContent Is BookmarkEnd Then
Dim bookmarkEnd As BookmarkEnd = DirectCast(pContent, BookmarkEnd)
If bookmarkEnd.ID = bookmarkId Then
bookmarkId = -1
End If
ElseIf TypeOf pContent Is Run AndAlso bookmarkId > -1 Then
Dim run As Run = DirectCast(pContent, Run)
contentToRemove.Add(run)
End If
Next
If contentToRemove.Count > 0 Then
For Each element As IParagraphContent In contentToRemove
paragraph.Content.Remove(element)
Next
End If
End If
Next
doc.Save("c:\test\output.docx", True)
End Sub
End Module
|
AndreKuzubov/Easy_Report
|
packages/Independentsoft.Office.Word.2.0.400/Tutorial/VBRemoveBookmarkContent/Module1.vb
|
Visual Basic
|
apache-2.0
| 1,824
|
Imports Microsoft.VisualBasic
Imports BVSoftware.Bvc5.Core
Imports System.Xml
Imports System.IO
Namespace WS4Processors
Public Class ProductUpdatePricing
Inherits Services.WS4.CommandProcessor
Public Overrides ReadOnly Property CommandName() As String
Get
Return "ProductUpdatePricing"
End Get
End Property
Public Overrides Function Help(ByVal summary As Boolean) As String
Return "Updates only the pricing information for a product."
End Function
Public Overrides Function ProcessRequest(ByVal data As String) As BVSoftware.Bvc5.Core.Services.WS4.WS4Response
Dim result As New BVSoftware.Bvc5.Core.Services.WS4.WS4Response
Try
Dim req As New ProductUpdatePricingRequest()
req.FromXml(data)
Dim p As Catalog.Product = Catalog.InternalProduct.FindByBvin(req.Bvin)
If p IsNot Nothing Then
If p.Sku.ToLower.Trim = req.Bvin.ToLower Then
p.SitePrice = req.SitePrice
p.SiteCost = req.SiteCost
p.ListPrice = req.MSRP
result.Success = Catalog.InternalProduct.Update(p)
End If
End If
Catch ex As Exception
result.Errors.Add(New BVSoftware.Bvc5.Core.Services.WS4.WS4Error("Exception", ex.Message))
End Try
Return result
End Function
End Class
Public Class ProductUpdatePricingRequest
Private _bvin As String = String.Empty
Private _sitePrice As Decimal = 0
Private _msrp As Decimal = 0
Private _siteCost As Decimal = 0
Public Property Bvin() As String
Get
Return _bvin
End Get
Set(ByVal value As String)
_bvin = value
End Set
End Property
Public Property SitePrice() As Decimal
Get
Return _sitePrice
End Get
Set(ByVal value As Decimal)
_sitePrice = value
End Set
End Property
Public Property MSRP() As Decimal
Get
Return _msrp
End Get
Set(ByVal value As Decimal)
_msrp = value
End Set
End Property
Public Property SiteCost() As Decimal
Get
Return _siteCost
End Get
Set(ByVal value As Decimal)
_siteCost = value
End Set
End Property
Public Sub New()
End Sub
Public Sub New(ByVal bvin As String, ByVal sitePrice As Decimal, ByVal msrp As Decimal, ByVal siteCost As Decimal)
End Sub
Public Function ToXml() As String
Dim result As String = String.Empty
Dim sw As StringWriter = New StringWriter(System.Globalization.CultureInfo.InvariantCulture)
Dim xw As XmlTextWriter = New XmlTextWriter(sw)
xw.Formatting = Formatting.Indented
xw.Indentation = 3
xw.WriteStartDocument()
xw.WriteStartElement("ProductPricing")
xw.WriteElementString("BVIN", _bvin)
xw.WriteElementString("SitePrice", _sitePrice)
xw.WriteElementString("MSRP", _msrp)
xw.WriteElementString("SiteCost", _siteCost)
xw.WriteEndElement()
xw.WriteEndDocument()
xw.Flush()
xw.Close()
result = sw.GetStringBuilder.ToString()
sw.Close()
Return result
End Function
Public Sub FromXml(ByVal data As String)
Dim _BVXmlReaderSettings As New XmlReaderSettings
Dim sw As New System.IO.StringReader(data)
Dim xr As XmlReader = XmlReader.Create(sw)
Dim xdoc As New XPath.XPathDocument(xr)
Dim nav As XPath.XPathNavigator = xdoc.CreateNavigator()
If Not nav.SelectSingleNode("/ProductPricing") Is Nothing Then
If nav.SelectSingleNode("/ProductPricing/BVIN") IsNot Nothing Then
_bvin = nav.SelectSingleNode("/ProductPricing/BVIN").Value
End If
If nav.SelectSingleNode("/ProductPricing/SitePrice") IsNot Nothing Then
_sitePrice = nav.SelectSingleNode("/ProductPricing/SitePrice").Value
End If
If nav.SelectSingleNode("/ProductPricing/MSRP") IsNot Nothing Then
_msrp = nav.SelectSingleNode("/ProductPricing/MSRP").Value
End If
If nav.SelectSingleNode("/ProductPricing/SiteCost") IsNot Nothing Then
_siteCost = nav.SelectSingleNode("/ProductPricing/SiteCost").Value
End If
End If
sw.Dispose()
xr.Close()
End Sub
End Class
End Namespace
|
ajaydex/Scopelist_2015
|
App_Code/WS4Processors/ProductUpdatePricing.vb
|
Visual Basic
|
apache-2.0
| 5,045
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Internal.Log
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification
<ExportLanguageService(GetType(ISimplificationService), LanguageNames.VisualBasic), [Shared]>
Partial Friend Class VisualBasicSimplificationService
Inherits AbstractSimplificationService(Of ExpressionSyntax, ExecutableStatementSyntax, CrefReferenceSyntax)
Private Shared ReadOnly s_reducers As ImmutableArray(Of AbstractReducer) =
ImmutableArray.Create(Of AbstractReducer)(
New VisualBasicExtensionMethodReducer(),
New VisualBasicCastReducer(),
New VisualBasicNameReducer(),
New VisualBasicParenthesesReducer(),
New VisualBasicCallReducer(),
New VisualBasicEscapingReducer(), ' order before VisualBasicMiscellaneousReducer, see RenameNewOverload test
New VisualBasicMiscellaneousReducer(),
New VisualBasicCastReducer(),
New VisualBasicVariableDeclaratorReducer(),
New VisualBasicInferredMemberNameReducer())
<ImportingConstructor>
Public Sub New()
MyBase.New(s_reducers)
End Sub
Public Overrides Function Expand(node As SyntaxNode, semanticModel As SemanticModel, aliasReplacementAnnotation As SyntaxAnnotation, expandInsideNode As Func(Of SyntaxNode, Boolean), expandParameter As Boolean, cancellationToken As CancellationToken) As SyntaxNode
Using Logger.LogBlock(FunctionId.Simplifier_ExpandNode, cancellationToken)
If TypeOf node Is ExpressionSyntax OrElse
TypeOf node Is StatementSyntax OrElse
TypeOf node Is AttributeSyntax OrElse
TypeOf node Is SimpleArgumentSyntax OrElse
TypeOf node Is CrefReferenceSyntax OrElse
TypeOf node Is TypeConstraintSyntax Then
Dim rewriter = New Expander(semanticModel, expandInsideNode, cancellationToken, expandParameter, aliasReplacementAnnotation)
Return rewriter.Visit(node)
Else
Throw New ArgumentException(
VBWorkspaceResources.Only_attributes_expressions_or_statements_can_be_made_explicit,
paramName:=NameOf(node))
End If
End Using
End Function
Public Overrides Function Expand(token As SyntaxToken, semanticModel As SemanticModel, expandInsideNode As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken) As SyntaxToken
Using Logger.LogBlock(FunctionId.Simplifier_ExpandToken, cancellationToken)
Dim rewriter = New Expander(semanticModel, expandInsideNode, cancellationToken)
Return TryEscapeIdentifierToken(rewriter.VisitToken(token), semanticModel)
End Using
End Function
Public Shared Function TryEscapeIdentifierToken(identifierToken As SyntaxToken, semanticModel As SemanticModel, Optional oldIdentifierToken As SyntaxToken? = Nothing) As SyntaxToken
If identifierToken.Kind <> SyntaxKind.IdentifierToken OrElse identifierToken.ValueText.Length = 0 Then
Return identifierToken
End If
If identifierToken.IsBracketed Then
Return identifierToken
End If
If identifierToken.GetTypeCharacter() <> TypeCharacter.None Then
Return identifierToken
End If
Dim unescapedIdentifier = identifierToken.ValueText
If SyntaxFacts.GetKeywordKind(unescapedIdentifier) = SyntaxKind.None AndAlso SyntaxFacts.GetContextualKeywordKind(unescapedIdentifier) = SyntaxKind.None Then
Return identifierToken
End If
Return identifierToken.CopyAnnotationsTo(
SyntaxFactory.BracketedIdentifier(identifierToken.LeadingTrivia, identifierToken.ValueText, identifierToken.TrailingTrivia) _
.WithAdditionalAnnotations(Simplifier.Annotation))
End Function
Protected Overrides Function GetSpeculativeSemanticModel(ByRef nodeToSpeculate As SyntaxNode, originalSemanticModel As SemanticModel, originalNode As SyntaxNode) As SemanticModel
Contract.ThrowIfNull(nodeToSpeculate)
Contract.ThrowIfNull(originalNode)
Dim speculativeModel As SemanticModel
Dim methodBlockBase = TryCast(nodeToSpeculate, MethodBlockBaseSyntax)
' Speculation over Field Declarations is not supported
If originalNode.Kind() = SyntaxKind.VariableDeclarator AndAlso
originalNode.Parent.Kind() = SyntaxKind.FieldDeclaration Then
Return originalSemanticModel
End If
If methodBlockBase IsNot Nothing Then
' Certain reducers for VB (escaping, parentheses) require to operate on the entire method body, rather than individual statements.
' Hence, we need to reduce the entire method body as a single unit.
' However, there is no SyntaxNode for the method body or statement list, hence NodesAndTokensToReduceComputer added the MethodBlockBaseSyntax to the list of nodes to be reduced.
' Here we make sure that we create a speculative semantic model for the method body for the given MethodBlockBaseSyntax.
Dim originalMethod = DirectCast(originalNode, MethodBlockBaseSyntax)
Contract.ThrowIfFalse(originalMethod.Statements.Any(), "How did empty method body get reduced?")
Dim position As Integer
If originalSemanticModel.IsSpeculativeSemanticModel Then
' Chaining speculative model Not supported, speculate off the original model.
Debug.Assert(originalSemanticModel.ParentModel IsNot Nothing)
Debug.Assert(Not originalSemanticModel.ParentModel.IsSpeculativeSemanticModel)
position = originalSemanticModel.OriginalPositionForSpeculation
originalSemanticModel = originalSemanticModel.ParentModel
Else
position = originalMethod.Statements.First.SpanStart
End If
speculativeModel = Nothing
originalSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(position, methodBlockBase, speculativeModel)
Return speculativeModel
End If
Contract.ThrowIfFalse(SpeculationAnalyzer.CanSpeculateOnNode(nodeToSpeculate))
Dim isAsNewClause = nodeToSpeculate.Kind = SyntaxKind.AsNewClause
If isAsNewClause Then
' Currently, there is no support for speculating on an AsNewClauseSyntax node.
' So we synthesize an EqualsValueSyntax with the inner NewExpression and speculate on this EqualsValueSyntax node.
Dim asNewClauseNode = DirectCast(nodeToSpeculate, AsNewClauseSyntax)
nodeToSpeculate = SyntaxFactory.EqualsValue(asNewClauseNode.NewExpression)
nodeToSpeculate = asNewClauseNode.CopyAnnotationsTo(nodeToSpeculate)
End If
speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(originalNode, nodeToSpeculate, originalSemanticModel)
If isAsNewClause Then
nodeToSpeculate = speculativeModel.SyntaxTree.GetRoot()
End If
Return speculativeModel
End Function
Protected Overrides Function TransformReducedNode(reducedNode As SyntaxNode, originalNode As SyntaxNode) As SyntaxNode
' Please see comments within the above GetSpeculativeSemanticModel method for details.
If originalNode.Kind = SyntaxKind.AsNewClause AndAlso reducedNode.Kind = SyntaxKind.EqualsValue Then
Return originalNode.ReplaceNode(DirectCast(originalNode, AsNewClauseSyntax).NewExpression, DirectCast(reducedNode, EqualsValueSyntax).Value)
End If
Dim originalMethod = TryCast(originalNode, MethodBlockBaseSyntax)
If originalMethod IsNot Nothing Then
Dim reducedMethod = DirectCast(reducedNode, MethodBlockBaseSyntax)
reducedMethod = reducedMethod.ReplaceNode(reducedMethod.BlockStatement, originalMethod.BlockStatement)
Return reducedMethod.ReplaceNode(reducedMethod.EndBlockStatement, originalMethod.EndBlockStatement)
End If
Return reducedNode
End Function
Protected Overrides Function GetNodesAndTokensToReduce(root As SyntaxNode, isNodeOrTokenOutsideSimplifySpans As Func(Of SyntaxNodeOrToken, Boolean)) As ImmutableArray(Of NodeOrTokenToReduce)
Return NodesAndTokensToReduceComputer.Compute(root, isNodeOrTokenOutsideSimplifySpans)
End Function
Protected Overrides Function CanNodeBeSimplifiedWithoutSpeculation(node As SyntaxNode) As Boolean
Return node IsNot Nothing AndAlso node.Parent IsNot Nothing AndAlso
TypeOf node Is VariableDeclaratorSyntax AndAlso
TypeOf node.Parent Is FieldDeclarationSyntax
End Function
Private Const s_BC50000_UnusedImportsClause As String = "BC50000"
Private Const s_BC50001_UnusedImportsStatement As String = "BC50001"
Protected Overrides Sub GetUnusedNamespaceImports(model As SemanticModel, namespaceImports As HashSet(Of SyntaxNode), cancellationToken As CancellationToken)
Dim root = model.SyntaxTree.GetRoot()
Dim diagnostics = model.GetDiagnostics(cancellationToken:=cancellationToken)
For Each diagnostic In diagnostics
If diagnostic.Id = s_BC50000_UnusedImportsClause OrElse diagnostic.Id = s_BC50001_UnusedImportsStatement Then
Dim node = root.FindNode(diagnostic.Location.SourceSpan)
Dim statement = TryCast(node, ImportsStatementSyntax)
Dim clause = TryCast(node, ImportsStatementSyntax)
If statement IsNot Nothing Or clause IsNot Nothing Then
namespaceImports.Add(node)
End If
End If
Next
End Sub
End Class
End Namespace
|
nguerrera/roslyn
|
src/Workspaces/VisualBasic/Portable/Simplification/VisualBasicSimplificationService.vb
|
Visual Basic
|
apache-2.0
| 10,859
|
'*******************************************************************************************'
' '
' Download Free Evaluation Version From: https://bytescout.com/download/web-installer '
' '
' Also available as Web API! Get free API Key https://app.pdf.co/signup '
' '
' Copyright © 2017-2020 ByteScout, Inc. All rights reserved. '
' https://www.bytescout.com '
' https://www.pdf.co '
'*******************************************************************************************'
Imports System.Windows.Forms
Public Partial Class PasswordDialog
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Public ReadOnly Property Password() As String
Get
Return textBoxPassword.Text
End Get
End Property
Private Sub btnOk_Click(sender As Object, e As EventArgs)
'DialogResult = DialogResult.OK;
'Close();
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs)
End Sub
Private Sub checkBoxHide_CheckedChanged(sender As Object, e As EventArgs)
If checkBoxHide.Checked Then
textBoxPassword.PasswordChar = "*"C
Else
textBoxPassword.PasswordChar = ControlChars.NullChar
End If
End Sub
End Class
|
bytescout/ByteScout-SDK-SourceCode
|
Spreadsheet SDK/VB.NET/View Spreadsheet/PasswordDialog.vb
|
Visual Basic
|
apache-2.0
| 1,643
|
'/////////////////////////////////////////////////////////
' LoginForm1.vb (Personal File Locker 2013 Project)
' Programmer: Dr. Aung Win Htut
' Written by Miscrosoft Visual Studio 2008
' These code is used to login by Username and Password
' Start Coding in 2011
' Update 1-3-2014
Imports System
Imports Microsoft.Win32
Public Class LoginForm1
Dim strUname As String = ""
Dim strPass As String = ""
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Dim newKey As RegistryKey
'Try to read User name and Password from Registry
Try
strUname = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\BluePhoenix\CipherCad2013\Serial", "Uname", "Error!")
strPass = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\BluePhoenix\CipherCad2013\Serial", "Pass", "Error!")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
'If Username Or Password is blank then (1) Create New Reg Key, (2) Set default Username = admin And default Password = admin in Reg
'Here You can use encryption algorithms to protect Username and Password
If strUname = "" Or strPass = "" Then
Try
newKey = My.Computer.Registry.CurrentUser.CreateSubKey("Software\BluePhoenix\CipherCad2013")
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\BluePhoenix\CipherCad2013\Serial", "Uname", "admin")
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\BluePhoenix\CipherCad2013\Serial", "Pass", "admin")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
'if Error then do the same as above blank case
'may be this is the very first time your program is running
'if u want to make it as trial you can set your first date to calculate time
ElseIf strUname = "Error!" Or strPass = "Error!" Then
Try
newKey = My.Computer.Registry.CurrentUser.CreateSubKey("Software\BluePhoenix\CipherCad2013")
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\BluePhoenix\CipherCad2013\Serial", "Uname", "admin")
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\BluePhoenix\CipherCad2013\Serial", "Pass", "admin")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End If
'if username and password OK then Start Activation Process
'if u want to make trial version (e.g. 30 days) then check additonal registry vale for date or usage times to launch activation of your choice
If txtUser.Text = strUname And txtPass.Text = strPass Then
Me.Hide()
frmActivate.Show()
'frmActivate.Hide()
Else
txtPass.Text = ""
txtUser.Text = ""
txtUser.Focus()
End If
'frmMain.Show()
End Sub
Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
Me.Close()
End Sub
Private Sub LoginForm1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim newKey As RegistryKey
'Try to read User name and Password from Registry
Try
strUname = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\BluePhoenix\CipherCad2013\Serial", "Uname", "Error!")
strPass = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\BluePhoenix\CipherCad2013\Serial", "Pass", "Error!")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
'If Username Or Password is blank then (1) Create New Reg Key, (2) Set default Username = admin And default Password = admin in Reg
If strUname = "" Or strPass = "" Then
Try
newKey = My.Computer.Registry.CurrentUser.CreateSubKey("Software\BluePhoenix\CipherCad2013")
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\BluePhoenix\CipherCad2013\Serial", "Uname", "admin")
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\BluePhoenix\CipherCad2013\Serial", "Pass", "admin")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
'if Error then do the same as above blank case
ElseIf strUname = "Error!" Or strPass = "Error!" Then
Try
newKey = My.Computer.Registry.CurrentUser.CreateSubKey("Software\BluePhoenix\CipherCad2013")
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\BluePhoenix\CipherCad2013\Serial", "Uname", "admin")
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\BluePhoenix\CipherCad2013\Serial", "Pass", "admin")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End If
End Sub
Private Sub btnChangeUnmae_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChangeUnmae.Click
'Call form as a dialog to change Username and Password
frmChangeUname.ShowDialog()
End Sub
End Class
'//// End of LoginForm1.vb ////////////
|
mmgreenhacker/CodeFinal
|
VB/Activation Test Project/CipherCad2011-Source/LoginForm1.vb
|
Visual Basic
|
mit
| 5,345
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.QuickInfo
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.QuickInfo
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.QuickInfo
Public Class SemanticQuickInfoSourceTests
Inherits AbstractSemanticQuickInfoSourceTests
Protected Overrides Function TestAsync(markup As String, ParamArray expectedResults() As Action(Of QuickInfoItem)) As Task
Return TestWithReferencesAsync(markup, Array.Empty(Of String)(), expectedResults)
End Function
Protected Shared Async Function TestSharedAsync(workspace As TestWorkspace, position As Integer, ParamArray expectedResults() As Action(Of QuickInfoItem)) As Task
Dim service = workspace.Services _
.GetLanguageServices(LanguageNames.VisualBasic) _
.GetService(Of QuickInfoService)
Await TestSharedAsync(workspace, service, position, expectedResults)
' speculative semantic model
Dim document = workspace.CurrentSolution.Projects.First().Documents.First()
If Await CanUseSpeculativeSemanticModelAsync(document, position) Then
Dim buffer = workspace.Documents.Single().GetTextBuffer()
Using edit = buffer.CreateEdit()
edit.Replace(0, buffer.CurrentSnapshot.Length, buffer.CurrentSnapshot.GetText())
edit.Apply()
End Using
Await TestSharedAsync(workspace, service, position, expectedResults)
End If
End Function
Private Shared Async Function TestSharedAsync(workspace As TestWorkspace, service As QuickInfoService, position As Integer, expectedResults() As Action(Of QuickInfoItem)) As Task
Dim info = Await service.GetQuickInfoAsync(
workspace.CurrentSolution.Projects.First().Documents.First(),
position, SymbolDescriptionOptions.Default, CancellationToken.None)
If expectedResults Is Nothing Then
Assert.Null(info)
Else
Assert.NotNull(info)
For Each expected In expectedResults
expected(info)
Next
End If
End Function
Private Shared Async Function TestFromXmlAsync(markup As String, ParamArray expectedResults As Action(Of QuickInfoItem)()) As Task
Using workspace = TestWorkspace.Create(markup)
Await TestSharedAsync(workspace, workspace.Documents.First().CursorPosition.Value, expectedResults)
End Using
End Function
Private Shared Async Function TestWithReferencesAsync(markup As String, metadataReferences As String(), ParamArray expectedResults() As Action(Of QuickInfoItem)) As Task
Dim code As String = Nothing
Dim position As Integer = Nothing
MarkupTestFile.GetPosition(markup, code, position)
Using workspace = TestWorkspace.CreateVisualBasic(code, Nothing, metadataReferences:=metadataReferences)
Await TestSharedAsync(workspace, position, expectedResults)
End Using
End Function
Private Async Function TestWithImportsAsync(markup As String, ParamArray expectedResults() As Action(Of QuickInfoItem)) As Task
Dim markupWithImports =
"Imports System" & vbCrLf &
"Imports System.Collections.Generic" & vbCrLf &
"Imports System.Linq" & vbCrLf &
markup
Await TestAsync(markupWithImports, expectedResults)
End Function
Private Async Function TestInClassAsync(markup As String, ParamArray expectedResults() As Action(Of QuickInfoItem)) As Task
Dim markupInClass =
"Class C" & vbCrLf &
markup & vbCrLf &
"End Class"
Await TestWithImportsAsync(markupInClass, expectedResults)
End Function
Private Async Function TestInMethodAsync(markup As String, ParamArray expectedResults() As Action(Of QuickInfoItem)) As Task
Dim markupInClass =
"Class C" & vbCrLf &
"Sub M()" & vbCrLf &
markup & vbCrLf &
"End Sub" & vbCrLf &
"End Class"
Await TestWithImportsAsync(markupInClass, expectedResults)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestInt32() As Task
Await TestInClassAsync("Dim i As $$Int32",
MainDescription("Structure System.Int32"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestInteger() As Task
Await TestInClassAsync("Dim i As $$Integer",
MainDescription("Structure System.Int32",
ExpectedClassifications(
Keyword("Structure"),
WhiteSpace(" "),
Identifier("System"),
Operators.Dot,
Struct("Int32"))))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestString() As Task
Await TestInClassAsync("Dim i As $$String",
MainDescription("Class System.String",
ExpectedClassifications(
Keyword("Class"),
WhiteSpace(" "),
Identifier("System"),
Operators.Dot,
[Class]("String"))))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestStringAtEndOfToken() As Task
Await TestInClassAsync("Dim i As String$$",
MainDescription("Class System.String"))
End Function
<WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestStringLiteral() As Task
Await TestInClassAsync("Dim i = ""cat""$$",
MainDescription("Class System.String"))
End Function
<WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestInterpolatedStringLiteral() As Task
Await TestInClassAsync("Dim i = $""cat""$$", MainDescription("Class System.String"))
Await TestInClassAsync("Dim i = $""c$$at""", MainDescription("Class System.String"))
Await TestInClassAsync("Dim i = $""$$cat""", MainDescription("Class System.String"))
Await TestInClassAsync("Dim i = $""cat {1$$ + 2} dog""", MainDescription("Structure System.Int32"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestListOfString() As Task
Await TestInClassAsync("Dim l As $$List(Of String)",
MainDescription("Class System.Collections.Generic.List(Of T)",
ExpectedClassifications(
Keyword("Class"),
WhiteSpace(" "),
Identifier("System"),
Operators.Dot,
Identifier("Collections"),
Operators.Dot,
Identifier("Generic"),
Operators.Dot,
[Class]("List"),
Punctuation.OpenParen,
Keyword("Of"),
WhiteSpace(" "),
TypeParameter("T"),
Punctuation.CloseParen)),
TypeParameterMap(vbCrLf & $"T {FeaturesResources.is_} String",
ExpectedClassifications(
WhiteSpace(vbCrLf),
TypeParameter("T"),
WhiteSpace(" "),
Text(FeaturesResources.is_),
WhiteSpace(" "),
Keyword("String"))))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestListOfT() As Task
Await TestWithImportsAsync(<Text>
Class C(Of T)
Dim l As $$List(Of T)
End Class
</Text>.NormalizedValue,
MainDescription("Class System.Collections.Generic.List(Of T)",
ExpectedClassifications(
Keyword("Class"),
WhiteSpace(" "),
Identifier("System"),
Operators.Dot,
Identifier("Collections"),
Operators.Dot,
Identifier("Generic"),
Operators.Dot,
[Class]("List"),
Punctuation.OpenParen,
Keyword("Of"),
WhiteSpace(" "),
TypeParameter("T"),
Punctuation.CloseParen)))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestListOfT2() As Task
Await TestWithImportsAsync(<Text>
Class C(Of T)
Dim l As Lis$$t(Of T)
End Class
</Text>.NormalizedValue,
MainDescription("Class System.Collections.Generic.List(Of T)"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestListOfT3() As Task
Await TestWithImportsAsync(<Text>
Class C(Of T)
Dim l As List$$(Of T)
End Class
</Text>.NormalizedValue,
MainDescription("Class System.Collections.Generic.List(Of T)"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestListOfT4() As Task
Await TestWithImportsAsync(<Text>
Class C(Of T)
Dim l As List $$(Of T)
End Class
</Text>.NormalizedValue,
Nothing)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDictionaryOfIntegerAndString() As Task
Await TestWithImportsAsync(<Text>
Class C
Dim d As $$Dictionary(Of Integer, String)
End Class
</Text>.NormalizedValue,
MainDescription("Class System.Collections.Generic.Dictionary(Of TKey, TValue)"),
TypeParameterMap(
Lines(vbCrLf & $"TKey {FeaturesResources.is_} Integer",
$"TValue {FeaturesResources.is_} String")))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDictionaryOfTAndU() As Task
Await TestWithImportsAsync(<Text>
Class C(Of T, U)
Dim d As $$Dictionary(Of T, U)
End Class
</Text>.NormalizedValue,
MainDescription("Class System.Collections.Generic.Dictionary(Of TKey, TValue)"),
TypeParameterMap(
Lines(vbCrLf & $"TKey {FeaturesResources.is_} T",
$"TValue {FeaturesResources.is_} U")))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestIEnumerableOfInteger() As Task
Await TestInClassAsync("Dim ie As $$IEnumerable(Of Integer)",
MainDescription("Interface System.Collections.Generic.IEnumerable(Of Out T)"),
TypeParameterMap(vbCrLf & $"T {FeaturesResources.is_} Integer"))
End Function
<WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestEvent() As Task
Await TestInMethodAsync("AddHandler System.Console.$$CancelKeyPress, AddressOf S",
MainDescription("Event Console.CancelKeyPress As ConsoleCancelEventHandler",
ExpectedClassifications(
Keyword("Event"),
WhiteSpace(" "),
[Class]("Console"),
Operators.Dot,
Identifier("CancelKeyPress"),
WhiteSpace(" "),
Keyword("As"),
WhiteSpace(" "),
[Delegate]("ConsoleCancelEventHandler"))))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestEventHandler() As Task
Await TestInClassAsync("Dim e As $$EventHandler",
MainDescription("Delegate Sub System.EventHandler(sender As Object, e As System.EventArgs)",
ExpectedClassifications(
Keyword("Delegate"),
WhiteSpace(" "),
Keyword("Sub"),
WhiteSpace(" "),
Identifier("System"),
Operators.Dot,
[Delegate]("EventHandler"),
Punctuation.OpenParen,
Identifier("sender"),
WhiteSpace(" "),
Keyword("As"),
WhiteSpace(" "),
Keyword("Object"),
Punctuation.Comma,
WhiteSpace(" "),
Identifier("e"),
WhiteSpace(" "),
Keyword("As"),
WhiteSpace(" "),
Identifier("System"),
Operators.Dot,
[Class]("EventArgs"),
Punctuation.CloseParen)))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestTypeParameter() As Task
Await TestAsync(StringFromLines("Class C(Of T)",
" Dim t As $$T",
"End Class"),
MainDescription($"T {FeaturesResources.in_} C(Of T)"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestNullableOfInteger() As Task
Await TestInClassAsync("Dim n As $$Nullable(Of Integer)",
MainDescription("Structure System.Nullable(Of T As Structure)"),
TypeParameterMap(vbCrLf & $"T {FeaturesResources.is_} Integer"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestGenericTypeDeclaredOnMethod1() As Task
Await TestAsync(<Text>
Class C
Shared Sub Meth1(Of T1)
Dim i As $$T1
End Sub
End Class
</Text>.NormalizedValue,
MainDescription($"T1 {FeaturesResources.in_} C.Meth1(Of T1)"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestGenericTypeDeclaredOnMethod2() As Task
Await TestAsync(<Text>
Class C
Shared Sub Meth1(Of T1 As Class)
Dim i As $$T1
End Sub
End Class
</Text>.NormalizedValue,
MainDescription($"T1 {FeaturesResources.in_} C.Meth1(Of T1 As Class)"))
End Function
<WorkItem(538732, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538732")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestParameter() As Task
Await TestWithImportsAsync(<Text>
Module C
Shared Sub Goo(Of T1 As Class)
Console.Wr$$ite(5)
End Sub
End Class
</Text>.NormalizedValue,
MainDescription($"Sub Console.Write(value As Integer) (+ 17 {FeaturesResources.overloads_})",
ExpectedClassifications(
Keyword("Sub"),
WhiteSpace(" "),
[Class]("Console"),
Operators.Dot,
Identifier("Write"),
Punctuation.OpenParen,
Identifier("value"),
WhiteSpace(" "),
Keyword("As"),
WhiteSpace(" "),
Keyword("Integer"),
Punctuation.CloseParen,
WhiteSpace(" "),
Punctuation.OpenParen,
Punctuation.Text("+"),
WhiteSpace(" "),
Text("17"),
WhiteSpace(" "),
Text(FeaturesResources.overloads_),
Punctuation.CloseParen)))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestOnFieldDeclaration() As Task
Await TestInClassAsync("Dim $$i As Int32",
MainDescription($"({FeaturesResources.field}) C.i As Integer"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestMinimal1() As Task
Await TestAsync(<Text>
Imports System.Collections.Generic
Class C
Dim p as New Li$$st(Of string)
End Class
</Text>.NormalizedValue,
MainDescription($"Sub List(Of String).New() (+ 2 {FeaturesResources.overloads_})"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestMinimal2() As Task
Await TestAsync(<Text>
Imports System.Collections.Generic
Class C
function $$P() as List(Of string)
End Class
</Text>.NormalizedValue,
MainDescription("Function C.P() As List(Of String)"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestAnd() As Task
Await TestAsync(<Text>
Imports System.Collections.Generic
Class C
sub s()
dim x as Boolean
x= true a$$nd False
end sub
End Class
</Text>.NormalizedValue,
MainDescription("Operator Boolean.And(left As Boolean, right As Boolean) As Boolean"))
End Function
<WorkItem(538822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538822")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDelegate() As Task
Await TestAsync(<Text>
Imports System
Class C
sub s()
dim F as F$$unc(of Integer, String)
end sub
End Class
</Text>.NormalizedValue,
MainDescription("Delegate Function System.Func(Of In T, Out TResult)(arg As T) As TResult"),
TypeParameterMap(
Lines(vbCrLf & $"T {FeaturesResources.is_} Integer",
$"TResult {FeaturesResources.is_} String")))
End Function
<WorkItem(538824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538824")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestOnDelegateInvocation() As Task
Await TestAsync(<Text>
Class Program
delegate sub D1()
shared sub Main()
dim d as D1
$$d()
end sub
end class</Text>.NormalizedValue,
MainDescription($"({FeaturesResources.local_variable}) d As D1"))
End Function
<WorkItem(538786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538786")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestOnGenericOverloads1() As Task
Await TestAsync(<Text>
Module C
Sub M()
End Sub
Sub M(Of T)()
End Sub
Sub M(Of T, U)()
End Sub
End Module
Class Test
Sub MySub()
C.$$M()
C.M(Of Integer)()
End Sub
End Class
</Text>.NormalizedValue,
MainDescription($"Sub C.M() (+ 2 {FeaturesResources.overloads_})"))
End Function
<WorkItem(538786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538786")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestOnGenericOverloads2() As Task
Await TestAsync(<Text>
Module C
Sub M()
End Sub
Sub M(Of T)()
End Sub
Sub M(Of T, U)()
End Sub
End Module
Class Test
Sub MySub()
C.M()
C.$$M(Of Integer)()
End Sub
End Class
</Text>.NormalizedValue,
MainDescription("Sub C.M(Of Integer)()"))
End Function
<WorkItem(538773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538773")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestOverriddenMethod() As Task
Await TestAsync(<Text>
Class A
Public Overridable Sub G()
End Sub
End Class
Class B
Inherits A
Public Overrides Sub G()
End Sub
End Class
Class C
Sub Test()
Dim x As New B
x.G$$()
End Sub
End Class
</Text>.NormalizedValue,
MainDescription($"Sub B.G() (+ 1 {FeaturesResources.overload})"))
End Function
<WorkItem(538918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538918")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestOnMe() As Task
Await TestAsync(<Text>
class C
Sub Test()
$$Me.Test()
End Sub
End class
</Text>.NormalizedValue,
MainDescription("Class C",
ExpectedClassifications(
Keyword("Class"),
WhiteSpace(" "),
[Class]("C"))))
End Function
<WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestOnArrayCreation1() As Task
Await TestAsync("
class C
Sub Test()
Dim a As Integer() = N$$ew Integer(3) { }
End Sub
End class",
MainDescription("Integer()"))
End Function
<WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestOnArrayCreation2() As Task
Await TestAsync(<Text>
class C
Sub Test()
Dim a As Integer() = New In$$teger(3) { }
End Sub
End class
</Text>.NormalizedValue,
MainDescription("Structure System.Int32"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDimInFieldDeclaration() As Task
Await TestInClassAsync("Dim$$ a As Integer", MainDescription("Structure System.Int32"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDimMultipleInFieldDeclaration() As Task
Await TestInClassAsync("$$Dim x As Integer, y As String", MainDescription(VBFeaturesResources.Multiple_Types))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDimInFieldDeclarationCustomType() As Task
Await TestAsync(<Text>
Module Program
Di$$m z As CustomClass
Private Class CustomClass
End Class
End Module
</Text>.NormalizedValue,
MainDescription("Class Program.CustomClass"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDimInLocalDeclaration() As Task
Await TestInMethodAsync("Dim$$ a As Integer", MainDescription("Structure System.Int32"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDimMultipleInLocalDeclaration() As Task
Await TestInMethodAsync("$$Dim x As Integer, y As String", MainDescription(VBFeaturesResources.Multiple_Types))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDimInLocalDeclarationCustomType() As Task
Await TestAsync(<Text>
Module Program
Sub Main(args As String())
D$$im z As CustomClass
End Sub
Private Class CustomClass
End Class
End Module
</Text>.NormalizedValue,
MainDescription("Class Program.CustomClass"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDefaultProperty1() As Task
Await TestAsync(<Text>
Class X
Public ReadOnly Property Goo As Y
Get
Return Nothing
End Get
End Property
End Class
Class Y
Public Default ReadOnly Property Item(ByVal a As Integer) As String
Get
Return "hi"
End Get
End Property
End Class
Module M1
Sub Main()
Dim a As String
Dim b As X
b = New X()
a = b.G$$oo(4)
End Sub
End Module
</Text>.NormalizedValue,
MainDescription("ReadOnly Property X.Goo As Y"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDefaultProperty2() As Task
Await TestAsync(<Text>
Class X
Public ReadOnly Property Goo As Y
Get
Return Nothing
End Get
End Property
End Class
Class Y
Public Default ReadOnly Property Item(ByVal a As Integer) As String
Get
Return "hi"
End Get
End Property
End Class
Module M1
Sub Main()
Dim a As String
Dim b As X
b = New X()
a = b.Goo.I$$tem(4)
End Sub
End Module
</Text>.NormalizedValue,
MainDescription("ReadOnly Property Y.Item(a As Integer) As String"))
End Function
<WorkItem(541582, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541582")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestLambdaExpression() As Task
Await TestAsync(<Text>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Module1
Sub Main(ByVal args As String())
Dim increment2 As Func(Of Integer, UInt16) = Function(x42)$$
Return x42 + 2
End Function
End Sub
End Module</Text>.NormalizedValue, Nothing)
End Function
<WorkItem(541353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541353")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestUnboundMethodInvocation() As Task
Await TestInMethodAsync("Me.Go$$o()", Nothing)
End Function
<WorkItem(541582, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541582")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestQuickInfoOnExtensionMethod() As Task
Await TestAsync(<Text><![CDATA[Imports System.Runtime.CompilerServices
Class Program
Private Shared Sub Main(args As String())
Dim values As Integer() = New Integer() {1}
Dim isArray As Boolean = 7.Co$$unt(values)
End Sub
End Class
Module MyExtensions
<Extension> _
Public Function Count(Of T)(o As T, items As IEnumerable(Of T)) As Boolean
Return True
End Function
End Module]]></Text>.NormalizedValue,
MainDescription($"<{VBFeaturesResources.Extension}> Function Integer.Count(items As IEnumerable(Of Integer)) As Boolean"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestQuickInfoOnExtensionMethodOverloads() As Task
Await TestAsync(<Text><![CDATA[Imports System.Runtime.CompilerServices
Class Program
Private Shared Sub Main(args As String())
Dim i as string = "1"
i.Test$$Ext()
End Sub
End Class
Module Ex
<Extension()>
Public Sub TestExt(Of T)(ex As T)
End Sub
<Extension()>
Public Sub TestExt(Of T)(ex As T, arg As T)
End Sub
<Extension()>
Public Sub TestExt(ex As String, arg As Integer)
End Sub
End Module]]></Text>.NormalizedValue,
MainDescription($"<{VBFeaturesResources.Extension}> Sub String.TestExt() (+ 2 {FeaturesResources.overloads_})"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestQuickInfoOnExtensionMethodOverloads2() As Task
Await TestAsync(<Text><![CDATA[Imports System.Runtime.CompilerServices
Class Program
Private Shared Sub Main(args As String())
Dim i as string = "1"
i.Test$$Ext()
End Sub
End Class
Module Ex
<Extension()>
Public Sub TestExt(Of T)(ex As T)
End Sub
<Extension()>
Public Sub TestExt(Of T)(ex As T, arg As T)
End Sub
<Extension()>
Public Sub TestExt(ex As Integer, arg As Integer)
End Sub
End Module]]></Text>.NormalizedValue,
MainDescription($"<{VBFeaturesResources.Extension}> Sub String.TestExt() (+ 1 {FeaturesResources.overload})"))
End Function
<WorkItem(541960, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541960")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDontRemoveAttributeSuffixAndProduceInvalidIdentifier1() As Task
Await TestAsync(<Text><![CDATA[
Imports System
Class _Attribute
Inherits Attribute
Dim x$$ As _Attribute
End Class]]></Text>.NormalizedValue,
MainDescription($"({FeaturesResources.field}) _Attribute.x As _Attribute"))
End Function
<WorkItem(541960, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541960")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDontRemoveAttributeSuffixAndProduceInvalidIdentifier2() As Task
Await TestAsync(<Text><![CDATA[
Imports System
Class ClassAttribute
Inherits Attribute
Dim x$$ As ClassAttribute
End Class]]></Text>.NormalizedValue,
MainDescription($"({FeaturesResources.field}) ClassAttribute.x As ClassAttribute"))
End Function
<WorkItem(541960, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541960")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDontRemoveAttributeSuffix1() As Task
Await TestAsync(<Text><![CDATA[
Imports System
Class Class1Attribute
Inherits Attribute
Dim x$$ As Class1Attribute
End Class]]></Text>.NormalizedValue,
MainDescription($"({FeaturesResources.field}) Class1Attribute.x As Class1Attribute"))
End Function
<WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestAttributeQuickInfoBindsToClassTest() As Task
Await TestAsync("
Imports System
''' <summary>
''' class comment
''' </summary>
<Some$$>
Class SomeAttribute
Inherits Attribute
''' <summary>
''' ctor comment
''' </summary>
Public Sub New()
End Sub
End Class
",
Documentation("class comment"))
End Function
<WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestAttributeConstructorQuickInfo() As Task
Await TestAsync("
Imports System
''' <summary>
''' class comment
''' </summary>
Class SomeAttribute
Inherits Attribute
''' <summary>
''' ctor comment
''' </summary>
Public Sub New()
Dim s = New Some$$Attribute()
End Sub
End Class
",
Documentation("ctor comment"))
End Function
<WorkItem(542613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542613")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestUnboundGeneric() As Task
Await TestAsync(<Text><![CDATA[
Imports System
Imports System.Collections.Generic
Class C
Sub M()
Dim t As Type = GetType(L$$ist(Of ))
End Sub
End Class]]></Text>.NormalizedValue,
MainDescription("Class System.Collections.Generic.List(Of T)"),
NoTypeParameterMap)
End Function
<WorkItem(543209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543209")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestQuickInfoForAnonymousType1() As Task
Await TestAsync(<Text><![CDATA[
Class C
Sub S
Dim product = $$New With {Key .Name = "", Key .Price = 0}
End Sub
End Class]]></Text>.NormalizedValue,
MainDescription("AnonymousType 'a"),
NoTypeParameterMap,
AnonymousTypes(vbCrLf & FeaturesResources.Types_colon & vbCrLf & $" 'a {FeaturesResources.is_} New With {{ Key .Name As String, Key .Price As Integer }}"))
End Function
<WorkItem(543226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543226")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestQuickInfoForAnonymousType2() As Task
Await TestAsync(<Text><![CDATA[
Imports System.Linq
Module Program
Sub Main(args As String())
Dim product = New With {Key .Name = "", Key .Price = 0}
Dim products = Enumerable.Repeat(product, 1)
Dim namePriceQuery = From prod In products
Select prod.$$Name, prod.Price
End Sub
End Module]]></Text>.NormalizedValue,
MainDescription("ReadOnly Property 'a.Name As String"),
NoTypeParameterMap,
AnonymousTypes(vbCrLf & FeaturesResources.Types_colon & vbCrLf & $" 'a {FeaturesResources.is_} New With {{ Key .Name As String, Key .Price As Integer }}"))
End Function
<WorkItem(543223, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543223")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestQuickInfoForAnonymousType3() As Task
Await TestAsync(<Text><![CDATA[
Class C
Sub S
Dim x = $$New With {Key .Goo = x}
End Sub
End Class
]]></Text>.NormalizedValue,
MainDescription("AnonymousType 'a"),
NoTypeParameterMap,
AnonymousTypes(vbCrLf & FeaturesResources.Types_colon & vbCrLf & $" 'a {FeaturesResources.is_} New With {{ Key .Goo As ? }}"))
End Function
<WorkItem(543242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543242")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestQuickInfoForUnboundLabel() As Task
Await TestAsync(<Text><![CDATA[
Option Infer On
Option Strict On
Public Class D
Public Sub goo()
GoTo $$oo
End Sub
End Class]]></Text>.NormalizedValue,
Nothing)
End Function
<WorkItem(543624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543624")>
<WorkItem(543275, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543275")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestQuickInfoForAnonymousDelegate1() As Task
Await TestAsync(<Text><![CDATA[
Imports System
Module Program
Sub Main
Dim $$a = Sub() Return
End Sub
End Module
]]></Text>.NormalizedValue,
MainDescription($"({FeaturesResources.local_variable}) a As 'a"),
AnonymousTypes(vbCrLf & FeaturesResources.Types_colon & vbCrLf & $" 'a {FeaturesResources.is_} Delegate Sub ()"))
End Function
<WorkItem(543624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543624")>
<WorkItem(543275, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543275")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestQuickInfoForAnonymousDelegate2() As Task
Await TestAsync(<Text><![CDATA[
Imports System
Module Program
Sub Main
Dim $$a = Function() 1
End Sub
End Module
]]></Text>.NormalizedValue,
MainDescription($"({FeaturesResources.local_variable}) a As 'a"),
AnonymousTypes(vbCrLf & FeaturesResources.Types_colon & vbCrLf & $" 'a {FeaturesResources.is_} Delegate Function () As Integer"))
End Function
<WorkItem(543624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543624")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestQuickInfoForAnonymousDelegate3() As Task
Await TestAsync(<Text><![CDATA[
Imports System
Module Program
Sub Main
Dim $$a = Function() New With {.Goo = "Goo"}
End Sub
End Module
]]></Text>.NormalizedValue,
MainDescription($"({FeaturesResources.local_variable}) a As 'a"),
AnonymousTypes(vbCrLf & FeaturesResources.Types_colon & vbCrLf &
$" 'a {FeaturesResources.is_} Delegate Function () As 'b" & vbCrLf &
$" 'b {FeaturesResources.is_} New With {{ .Goo As String }}"))
End Function
<WorkItem(543624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543624")>
<WorkItem(543275, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543275")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestQuickInfoForAnonymousDelegate4() As Task
Await TestAsync(<Text><![CDATA[
Imports System
Module Program
Sub Main
Dim $$a = Function(i As Integer) New With {.Sq = i * i, .M = Function(j As Integer) i * i}
End Sub
End Module
]]></Text>.NormalizedValue,
MainDescription($"({FeaturesResources.local_variable}) a As 'a"),
AnonymousTypes(vbCrLf & FeaturesResources.Types_colon & vbCrLf &
$" 'a {FeaturesResources.is_} Delegate Function (i As Integer) As 'b" & vbCrLf &
$" 'b {FeaturesResources.is_} New With {{ .Sq As Integer, .M As 'c }}" & vbCrLf &
$" 'c {FeaturesResources.is_} Delegate Function (j As Integer) As Integer"))
End Function
<WorkItem(543389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543389")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestImplicitMemberNameLocal1() As Task
Await TestAsync(<Text><![CDATA[
Imports System
Module Program
ReadOnly Property Prop As Long
Get
Pr$$op = 1
Dim a = New With {.id = Prop}
Return 1
End Get
End Property
End Module
]]></Text>.NormalizedValue,
MainDescription("ReadOnly Property Program.Prop As Long"))
End Function
<WorkItem(543389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543389")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestImplicitMemberNameLocal2() As Task
Await TestAsync(<Text><![CDATA[
Imports System
Module Program
ReadOnly Property Prop As Long
Get
Prop = 1
Dim a = New With {.id = Pr$$op}
Return 1
End Get
End Property
End Module
]]></Text>.NormalizedValue,
MainDescription("ReadOnly Property Program.Prop As Long"))
End Function
<WorkItem(543389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543389")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestImplicitMemberNameLocal3() As Task
Await TestAsync(<Text><![CDATA[
Imports System
Module Program
Function Goo() As Integer
Go$$o = 1
End Function
End Module
]]></Text>.NormalizedValue,
MainDescription("Function Program.Goo() As Integer"))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestBinaryConditionalExpression() As Task
Await TestInMethodAsync("Dim x = If$$(True, False)",
MainDescription($"If({VBWorkspaceResources.expression}, {VBWorkspaceResources.expressionIfNothing}) As Boolean"),
Documentation(VBWorkspaceResources.If_expression_evaluates_to_a_reference_or_Nullable_value_that_is_not_Nothing_the_function_returns_that_value_Otherwise_it_calculates_and_returns_expressionIfNothing))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestTernaryConditionalExpression() As Task
Await TestInMethodAsync("Dim x = If$$(True, ""Goo"", ""Bar"")",
MainDescription($"If({VBWorkspaceResources.condition} As Boolean, {VBWorkspaceResources.expressionIfTrue}, {VBWorkspaceResources.expressionIfFalse}) As String"),
Documentation(VBWorkspaceResources.If_condition_returns_True_the_function_calculates_and_returns_expressionIfTrue_Otherwise_it_returns_expressionIfFalse))
End Function
<WorkItem(957082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/957082")>
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestAddHandlerStatement() As Task
Await TestInMethodAsync("$$AddHandler goo, bar",
MainDescription($"AddHandler {VBWorkspaceResources.event_}, {VBWorkspaceResources.handler}"),
Documentation(VBWorkspaceResources.Associates_an_event_with_an_event_handler_delegate_or_lambda_expression_at_run_time),
SymbolGlyph(Glyph.Keyword))
End Function
<WorkItem(957082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/957082")>
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestRemoveHandlerStatement() As Task
Await TestInMethodAsync("$$RemoveHandler goo, bar",
MainDescription($"RemoveHandler {VBWorkspaceResources.event_}, {VBWorkspaceResources.handler}"),
Documentation(VBWorkspaceResources.Removes_the_association_between_an_event_and_an_event_handler_or_delegate_at_run_time),
SymbolGlyph(Glyph.Keyword))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestGetTypeExpression() As Task
Await TestInMethodAsync("Dim x = GetType$$(String)",
MainDescription("GetType(String) As Type"),
Documentation(VBWorkspaceResources.Returns_a_System_Type_object_for_the_specified_type_name))
End Function
<WorkItem(544140, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544140")>
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestGetXmlNamespaceExpression() As Task
Await TestWithReferencesAsync(
<text>
class C
sub M()
Dim x = GetXmlNamespace$$()
end sub()
end class
</text>.NormalizedValue,
{GetType(System.Xml.XmlAttribute).Assembly.Location, GetType(System.Xml.Linq.XAttribute).Assembly.Location},
MainDescription($"GetXmlNamespace([{VBWorkspaceResources.xmlNamespacePrefix}]) As Xml.Linq.XNamespace"),
Documentation(VBWorkspaceResources.Returns_the_System_Xml_Linq_XNamespace_object_corresponding_to_the_specified_XML_namespace_prefix))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestTryCastExpression() As Task
Await TestInMethodAsync("Dim x = TryCast$$(a, String)",
MainDescription($"TryCast({VBWorkspaceResources.expression}, String) As String"),
Documentation(VBWorkspaceResources.Introduces_a_type_conversion_operation_that_does_not_throw_an_exception_If_an_attempted_conversion_fails_TryCast_returns_Nothing_which_your_program_can_test_for))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDirectCastExpression() As Task
Await TestInMethodAsync("Dim x = DirectCast$$(a, String)",
MainDescription($"DirectCast({VBWorkspaceResources.expression}, String) As String"),
Documentation(VBWorkspaceResources.Introduces_a_type_conversion_operation_similar_to_CType_The_difference_is_that_CType_succeeds_as_long_as_there_is_a_valid_conversion_whereas_DirectCast_requires_that_one_type_inherit_from_or_implement_the_other_type))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCTypeCastExpression() As Task
Await TestInMethodAsync("Dim x = CType$$(a, String)",
MainDescription($"CType({VBWorkspaceResources.expression}, String) As String"),
Documentation(VBWorkspaceResources.Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCBoolExpression() As Task
Await TestInMethodAsync("Dim x = CBool$$(a)",
MainDescription($"CBool({VBWorkspaceResources.expression}) As Boolean"),
Documentation(String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "Boolean")))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCByteExpression() As Task
Await TestInMethodAsync("Dim x = CByte$$(a)",
MainDescription($"CByte({VBWorkspaceResources.expression}) As Byte"),
Documentation(String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "Byte")))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCCharExpression() As Task
Await TestInMethodAsync("Dim x = CChar$$(a)",
MainDescription($"CChar({VBWorkspaceResources.expression}) As Char"),
Documentation(String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "Char")))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCDateExpression() As Task
Await TestInMethodAsync("Dim x = CDate$$(a)",
MainDescription($"CDate({VBWorkspaceResources.expression}) As Date"),
Documentation(String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "Date")))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCDblExpression() As Task
Await TestInMethodAsync("Dim x = CDbl$$(a)",
MainDescription($"CDbl({VBWorkspaceResources.expression}) As Double"),
Documentation(String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "Double")))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCDecExpression() As Task
Await TestInMethodAsync("Dim x = CDec$$(a)",
MainDescription($"CDec({VBWorkspaceResources.expression}) As Decimal"),
Documentation(String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "Decimal")))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCIntExpression() As Task
Await TestInMethodAsync("Dim x = CInt$$(a)",
MainDescription($"CInt({VBWorkspaceResources.expression}) As Integer"),
Documentation(String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "Integer")))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCLngExpression() As Task
Await TestInMethodAsync("Dim x = CLng$$(a)",
MainDescription($"CLng({VBWorkspaceResources.expression}) As Long"),
Documentation(String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "Long")))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCObjExpression() As Task
Await TestInMethodAsync("Dim x = CObj$$(a)",
MainDescription($"CObj({VBWorkspaceResources.expression}) As Object"),
Documentation(String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "Object")))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCSByteExpression() As Task
Await TestInMethodAsync("Dim x = CSByte$$(a)",
MainDescription($"CSByte({VBWorkspaceResources.expression}) As SByte"),
Documentation(String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "SByte")))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCShortExpression() As Task
Await TestInMethodAsync("Dim x = CShort$$(a)",
MainDescription($"CShort({VBWorkspaceResources.expression}) As Short"),
Documentation(String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "Short")))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCSngExpression() As Task
Await TestInMethodAsync("Dim x = CSng$$(a)",
MainDescription($"CSng({VBWorkspaceResources.expression}) As Single"),
Documentation(String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "Single")))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCStrExpression() As Task
Await TestInMethodAsync("Dim x = CStr$$(a)",
MainDescription($"CStr({VBWorkspaceResources.expression}) As String"),
Documentation(String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "String")))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCUIntExpression() As Task
Await TestInMethodAsync("Dim x = CUInt$$(a)",
MainDescription($"CUInt({VBWorkspaceResources.expression}) As UInteger"),
Documentation(String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "UInteger")))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCULngExpression() As Task
Await TestInMethodAsync("Dim x = CULng$$(a)",
MainDescription($"CULng({VBWorkspaceResources.expression}) As ULong"),
Documentation(String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "ULong")))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCUShortExpression() As Task
Await TestInMethodAsync("Dim x = CUShort$$(a)",
MainDescription($"CUShort({VBWorkspaceResources.expression}) As UShort"),
Documentation(String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "UShort")))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestMidAssignmentStatement1() As Task
Await TestInMethodAsync("$$Mid(""goo"", 0) = ""bar""",
MainDescription($"Mid({VBWorkspaceResources.stringName}, {VBWorkspaceResources.startIndex}, [{VBWorkspaceResources.length}]) = {VBWorkspaceResources.stringExpression}"),
Documentation(VBWorkspaceResources.Replaces_a_specified_number_of_characters_in_a_String_variable_with_characters_from_another_string))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestMidAssignmentStatement2() As Task
Await TestInMethodAsync("$$Mid(""goo"", 0, 0) = ""bar""",
MainDescription($"Mid({VBWorkspaceResources.stringName}, {VBWorkspaceResources.startIndex}, [{VBWorkspaceResources.length}]) = {VBWorkspaceResources.stringExpression}"),
Documentation(VBWorkspaceResources.Replaces_a_specified_number_of_characters_in_a_String_variable_with_characters_from_another_string))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestConstantField() As Task
Await TestInClassAsync("const $$F = 1",
MainDescription($"({FeaturesResources.constant}) C.F As Integer = 1"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestMultipleConstantFields() As Task
Await TestInClassAsync("Public Const X As Double = 1.0, Y As Double = 2.0, $$Z As Double = 3.5",
MainDescription($"({FeaturesResources.constant}) C.Z As Double = 3.5"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestConstantDependencies() As Task
Await TestAsync(<Text><![CDATA[
Imports System
Class A
Public Const $$X As Integer = B.Z + 1
Public Const Y As Integer = 10
End Class
Class B
Public Const Z As Integer = A.Y + 1
End Class
]]></Text>.NormalizedValue,
MainDescription($"({FeaturesResources.constant}) A.X As Integer = B.Z + 1"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestConstantCircularDependencies() As Task
Await TestAsync(<Text><![CDATA[
Imports System
Class A
Public Const $$X As Integer = B.Z + 1
End Class
Class B
Public Const Z As Integer = A.X + 1
End Class
]]></Text>.NormalizedValue,
MainDescription($"({FeaturesResources.constant}) A.X As Integer = B.Z + 1"))
End Function
<WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestConstantOverflow() As Task
Await TestInClassAsync("Public Const $$Z As Integer = Integer.MaxValue + 1",
MainDescription($"({FeaturesResources.constant}) C.Z As Integer = Integer.MaxValue + 1"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestEnumInConstantField() As Task
Await TestAsync(<Text><![CDATA[
Public Class EnumTest
Private Enum Days
Sun
Mon
Tue
Wed
Thu
Fri
Sat
End Enum
Private Shared Sub Main()
Const $$x As Integer = CInt(Days.Sun)
End Sub
End Class
]]></Text>.NormalizedValue,
MainDescription($"({FeaturesResources.local_constant}) x As Integer = CInt(Days.Sun)"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestEnumInConstantField2() As Task
Await TestAsync(<Text><![CDATA[
Public Class EnumTest
Private Enum Days
Sun
Mon
Tue
Wed
Thu
Fri
Sat
End Enum
Private Shared Sub Main()
Const $$x As Days = Days.Sun
End Sub
End Class
]]></Text>.NormalizedValue,
MainDescription($"({FeaturesResources.local_constant}) x As Days = Days.Sun"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestConstantParameter() As Task
Await TestInClassAsync("Sub Bar(optional $$b as Integer = 1)",
MainDescription($"({FeaturesResources.parameter}) b As Integer = 1"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestConstantLocal() As Task
Await TestInMethodAsync("const $$loc = 1",
MainDescription($"({FeaturesResources.local_constant}) loc As Integer = 1"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestEnumValue1() As Task
Await TestInMethodAsync("Const $$sunday = DayOfWeek.Sunday",
MainDescription($"({FeaturesResources.local_constant}) sunday As DayOfWeek = DayOfWeek.Sunday"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestEnumValue2() As Task
Await TestInMethodAsync("Const $$v = AttributeTargets.Constructor or AttributeTargets.Class",
MainDescription($"({FeaturesResources.local_constant}) v As AttributeTargets = AttributeTargets.Constructor or AttributeTargets.Class"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestComplexConstantParameter() As Task
Await TestInClassAsync("Sub Bar(optional $$b as Integer = 1 + True)",
MainDescription($"({FeaturesResources.parameter}) b As Integer = 1 + True"))
End Function
<WorkItem(546849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546849")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestIndexedPropertyWithOptionalParameter() As Task
Await TestAsync(<Text><![CDATA[
Class Test
Public Property Prop(p1 As Integer, Optional p2 As Integer = 0) As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Sub Goo()
Dim x As New Test
x.Pr$$op(0) = 0
End Sub
End Class
]]></Text>.NormalizedValue,
MainDescription("Property Test.Prop(p1 As Integer, [p2 As Integer = 0]) As Integer"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestAwaitableMethod() As Task
Dim markup = <Workspace>
<Project Language="Visual Basic" CommonReferencesNet45="true">
<Document FilePath="SourceDocument">
Imports System.Threading.Tasks
Class C
Async Function goo() As Task
go$$o()
End Function
End Class
</Document>
</Project>
</Workspace>.ToString()
Dim description = <File><<%= VBFeaturesResources.Awaitable %>> Function C.goo() As Task</File>.ConvertTestSourceTag()
Await TestFromXmlAsync(markup, MainDescription(description))
End Function
<WorkItem(7100, "https://github.com/dotnet/roslyn/issues/7100")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestObjectWithOptionStrictOffIsntAwaitable() As Task
Dim markup = "
Option Strict Off
Class C
Function D() As Object
Return Nothing
End Function
Sub M()
D$$()
End Sub
End Class
"
Await TestAsync(markup, MainDescription("Function C.D() As Object"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestObsoleteItem() As Task
Await TestAsync(<Text><![CDATA[
Imports System
Class C
<Obsolete>
Sub Goo()
Go$$o()
End Sub
End Class
]]></Text>.NormalizedValue,
MainDescription($"({VBFeaturesResources.Deprecated}) Sub C.Goo()"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestEnumMemberNameFromMetadata() As Task
Dim code =
<Code>
Imports System
Class C
Sub M()
Dim c = ConsoleColor.Bla$$ck
End Sub
End Class
</Code>.NormalizedValue()
Await TestAsync(code,
MainDescription("ConsoleColor.Black = 0"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestEnumMemberNameFromSource1() As Task
Dim code =
<Code>
Enum Goo
A = 1 << 0
B = 1 << 1
C = 1 << 2
End Enum
Class C
Sub M()
Dim e = Goo.B$$
End Sub
End Class
</Code>.NormalizedValue()
Await TestAsync(code,
MainDescription("Goo.B = 1 << 1"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestEnumMemberNameFromSource2() As Task
Dim code =
<Code>
Enum Goo
A
B
C
End Enum
Class C
Sub M()
Dim e = Goo.B$$
End Sub
End Class
</Code>.NormalizedValue()
Await TestAsync(code,
MainDescription("Goo.B = 1"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")>
Public Async Function EnumNonDefaultUnderlyingType() As Task
Dim code =
<Code>
Enum Goo$$ As Byte
A
B
C
End Enum
</Code>.NormalizedValue()
Await TestAsync(code,
MainDescription("Enum Goo As Byte"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestTextOnlyDocComment() As Task
Await TestAsync(<text><![CDATA[
''' <summary>
'''goo
''' </summary>
Class C$$
End Class]]></text>.NormalizedValue(), Documentation("goo"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestTrimConcatMultiLine() As Task
Await TestAsync(<text><![CDATA[
''' <summary>
''' goo
''' bar
''' </summary>
Class C$$
End Class]]></text>.NormalizedValue(), Documentation("goo bar"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCref() As Task
Await TestAsync(<text><![CDATA[
''' <summary>
''' <see cref="C"/>
''' <seealso cref="C"/>
''' </summary>
Class C$$
End Class]]></text>.NormalizedValue(), Documentation("C C"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestExcludeTextOutsideSummaryBlock() As Task
Await TestAsync(<text><![CDATA[
''' red
''' <summary>
''' green
''' </summary>
''' yellow
Class C$$
End Class]]></text>.NormalizedValue(), Documentation("green"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestNewlineAfterPara() As Task
Await TestAsync(<text><![CDATA[
''' <summary>
''' <para>goo</para>
''' </summary>
Class C$$
End Class]]></text>.NormalizedValue(), Documentation("goo"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestParam() As Task
Await TestAsync(<text><![CDATA[
''' <summary></summary>
Public Class C
''' <typeparam name="T">A type parameter of <see cref="Goo(Of T) (string(), T)"/></typeparam>
''' <param name="args">First parameter of <see cref="Goo(Of T) (string(), T)"/></param>
''' <param name="otherParam">Another parameter of <see cref="Goo(Of T)(string(), T)"/></param>
Public Function Goo(Of T)(arg$$s As String(), otherParam As T)
End Function
End Class]]></text>.NormalizedValue(), Documentation("First parameter of C.Goo(Of T)(String(), T)"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestParam2() As Task
Await TestAsync(<text><![CDATA[
''' <summary></summary>
Public Class C
''' <typeparam name="T">A type parameter of <see cref="Goo(Of T) (string(), T)"/></typeparam>
''' <param name="args">First parameter of <see cref="Goo(Of T) (string(), T)"/></param>
''' <param name="otherParam">Another parameter of <see cref="Goo(Of T)(string(), T)"/></param>
Public Function Goo(Of T)(args As String(), otherP$$aram As T)
End Function
End Class]]></text>.NormalizedValue(), Documentation("Another parameter of C.Goo(Of T)(String(), T)"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestTypeParam() As Task
Await TestAsync(<text><![CDATA[
''' <summary></summary>
Public Class C
''' <typeparam name="T">A type parameter of <see cref="Goo(Of T) (string(), T)"/></typeparam>
''' <param name="args">First parameter of <see cref="Goo(Of T) (string(), T)"/></param>
''' <param name="otherParam">Another parameter of <see cref="Goo(Of T)(string(), T)"/></param>
Public Function Goo(Of T$$)( args as String(), otherParam as T)
End Function
End Class]]></text>.NormalizedValue(), Documentation("A type parameter of C.Goo(Of T)(String(), T)"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestUnboundCref() As Task
Await TestAsync(<text><![CDATA[
''' <summary></summary>
Public Class C
''' <typeparam name="T">A type parameter of <see cref="goo(Of T) (string, T)"/></typeparam>
Public Function Goo(Of T$$)( args as String(), otherParam as T)
End Function
End Class]]></text>.NormalizedValue(), Documentation("A type parameter of goo(Of T) (string, T)"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCrefInConstructor() As Task
Await TestAsync(<text><![CDATA[
Public Class TestClass
''' <summary>
''' This sample shows how to specify the <see cref="TestClass"/> constructor as a cref attribute.
''' </summary>
Public Sub N$$ew()
End Sub
End Class]]></text>.NormalizedValue(), Documentation("This sample shows how to specify the TestClass constructor as a cref attribute."))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCrefInConstructorOverloaded() As Task
Await TestAsync(<text><![CDATA[
Public Class TestClass
Public Sub New()
End Function
''' <summary>
''' This sample shows how to specify the <see cref="TestClass.New(Integer)"/> constructor as a cref attribute.
''' </summary>
Public Sub Ne$$w(value As Integer)
End Sub
End Class]]></text>.NormalizedValue(), Documentation("This sample shows how to specify the New(Integer) constructor as a cref attribute."))
End Function
<WorkItem(814191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/814191")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCrefInGenericMethod1() As Task
Await TestAsync(<text><![CDATA[
Public Class TestClass
''' <summary>
''' This sample shows how to specify the <see cref="GetGenericValue"/> method as a cref attribute.
''' </summary>
Public Shared Function GetGe$$nericValue(Of T)(para As T) As T
Return para
End Function
End Class]]></text>.NormalizedValue(), Documentation("This sample shows how to specify the TestClass.GetGenericValue(Of T)(T) method as a cref attribute."))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCrefInGenericMethod2() As Task
Await TestAsync(<text><![CDATA[
Public class TestClass
''' <summary>
''' This sample shows how to specify the <see cref="GetGenericValue(OfT)(T)"/> method as a cref attribute.
''' </summary>
Public Shared Function GetGe$$nericValue(Of T)(para As T) As T
Return para
End Function
End Class]]></text>.NormalizedValue(), Documentation("This sample shows how to specify the GetGenericValue(OfT)(T) method as a cref attribute."))
End Function
<WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCrefInMethodOverloading1() As Task
Await TestAsync(<text><![CDATA[
public class TestClass
Public Shared Function GetZero() As Integer
GetGenericVa$$lue()
Return GetGenericValue(5)
End Function
''' <summary>
''' This sample shows how to specify the <see cref="GetGenericValue(OfT)(T)"/> method as a cref attribute.
''' </summary>
Public Shared Function GetGenericValue(Of T)(para As T) As T
Return para
End Function
''' <summary>
''' This sample shows how to specify the <see cref="GetGenericValue()"/> method as a cref attribute.
''' </summary>
Public Shared Sub GetGenericValue()
End Sub
End Class]]></text>.NormalizedValue(), Documentation("This sample shows how to specify the TestClass.GetGenericValue() method as a cref attribute."))
End Function
<WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCrefInMethodOverloading2() As Task
Await TestAsync(<text><![CDATA[
public class TestClass
Public Shared Function GetZero() As Integer
GetGenericValue()
Return GetGe$$nericValue(5)
End Function
''' <summary>
''' This sample shows how to specify the <see cref="GetGenericValue(OfT)(T)"/> method as a cref attribute.
''' </summary>
Public Shared Function GetGenericValue(Of T)(para As T) As T
Return para
End Function
''' <summary>
''' This sample shows how to specify the <see cref="GetGenericValue()"/> method as a cref attribute.
''' </summary>
Public Shared Sub GetGenericValue()
End Sub
End Class]]></text>.NormalizedValue(), Documentation("This sample shows how to specify the GetGenericValue(OfT)(T) method as a cref attribute."))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestCrefInGenericType() As Task
Await TestAsync(<text><![CDATA[
''' <summary>
''' This sample shows how to specify the <see cref="GenericClass(Of T)"/> cref.
''' </summary>
Public Class Generic$$Class(Of T)
End Class]]></text>.NormalizedValue(),
Documentation("This sample shows how to specify the GenericClass(Of T) cref.",
ExpectedClassifications(
Text("This sample shows how to specify the"),
WhiteSpace(" "),
[Class]("GenericClass"),
Punctuation.OpenParen,
Keyword("Of"),
WhiteSpace(" "),
TypeParameter("T"),
Punctuation.CloseParen,
WhiteSpace(" "),
Text("cref."))))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestIntegerLiteral() As Task
Await TestInMethodAsync("Dim f = 37$$",
MainDescription("Structure System.Int32"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDateLiteral() As Task
Await TestInMethodAsync("Dim f = #8/23/1970 $$3:45:39 AM#",
MainDescription("Structure System.DateTime"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestTrueKeyword() As Task
Await TestInMethodAsync("Dim f = True$$",
MainDescription("Structure System.Boolean"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestFalseKeyword() As Task
Await TestInMethodAsync("Dim f = False$$",
MainDescription("Structure System.Boolean"))
End Function
<WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestNothingLiteral() As Task
Await TestInMethodAsync("Dim f As String = Nothing$$",
MainDescription("Class System.String"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestNothingLiteralWithNoType() As Task
Await TestInMethodAsync("Dim f = Nothing$$",
MainDescription("Class System.Object"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestNothingLiteralFieldDimOptionStrict() As Task
Await TestAsync("
Option Strict On
Class C
Dim f = Nothing$$
End Class",
MainDescription("Class System.Object"))
End Function
''' <Remarks>
''' As a part of fix for 756226, quick info for VB Await keyword now displays the type inferred from the AwaitExpression. This is C# behavior.
''' In Dev12, quick info for VB Await keyword was the syntactic help "Await <expression>".
''' In Roslyn, VB Syntactic quick info is Not yet Implemented. User story: 522342.
''' While implementing this story, determine the correct behavior for quick info on VB Await keyword (syntactic vs semantic) and update these tests.
''' </Remarks>
<WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(522342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522342")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestAwaitKeywordOnTaskReturningAsync() As Task
Dim markup =
<Workspace>
<Project Language="Visual Basic" CommonReferencesNet45="true">
<Document FilePath="SourceDocument">
Imports System.Threading.Tasks
Class C
Async Function goo() As Task
Aw$$ait goo()
End Function
End Class
</Document>
</Project>
</Workspace>.ToString()
Dim description = <File><%= FeaturesResources.Awaited_task_returns_no_value %></File>.ConvertTestSourceTag()
Await TestFromXmlAsync(markup, MainDescription(description))
End Function
<WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(522342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522342")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestAwaitKeywordOnGenericTaskReturningAsync() As Task
Dim markup = <Workspace>
<Project Language="Visual Basic" CommonReferencesNet45="true">
<Document FilePath="SourceDocument">
Imports System.Threading.Tasks
Class C
Async Function goo() As Task(Of Integer)
Dim x = Aw$$ait goo()
Return 42
End Function
End Class
</Document>
</Project>
</Workspace>.ToString()
Dim description = <File><%= String.Format(FeaturesResources.Awaited_task_returns_0, "Structure System.Int32") %></File>.ConvertTestSourceTag()
Await TestFromXmlAsync(markup, MainDescription(description))
End Function
<WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(522342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522342")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestAwaitKeywordOnTaskReturningAsync2() As Task
Dim markup = <Workspace>
<Project Language="Visual Basic" CommonReferencesNet45="true">
<Document FilePath="SourceDocument">
Imports System.Threading.Tasks
Class C
Async Sub Goo()
Aw$$ait Task.Delay(10)
End Sub
End Class
</Document>
</Project>
</Workspace>.ToString()
Dim description = <File><%= FeaturesResources.Awaited_task_returns_no_value %></File>.ConvertTestSourceTag()
Await TestFromXmlAsync(markup, MainDescription(description))
End Function
<WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(522342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522342")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestNestedAwaitKeywords1() As Task
Dim markup = <Workspace>
<Project Language="Visual Basic" CommonReferencesNet45="true">
<Document FilePath="SourceDocument">
Imports System
Imports System.Threading.Tasks
Class AsyncExample
Async Function AsyncMethod() As Task(Of Task(Of Integer))
Return NewMethod()
End Function
Private Shared Function NewMethod() As Task(Of Integer)
Throw New NotImplementedException()
End Function
Async Function UseAsync() As Task
Dim lambda As Func(Of Task(Of Integer)) = Async Function()
Return Await Await AsyncMethod()
End Function
Dim result = Await Await AsyncMethod()
Dim resultTask As Task(Of Task(Of Integer)) = AsyncMethod()
result = Await Awai$$t resultTask
result = Await lambda()
End Function
End Class
</Document>
</Project>
</Workspace>.ToString()
Dim description = <File><%= String.Format(FeaturesResources.Awaited_task_returns_0, $"<{VBFeaturesResources.Awaitable}> Class System.Threading.Tasks.Task(Of TResult)") %></File>.ConvertTestSourceTag()
Await TestFromXmlAsync(markup, MainDescription(description), TypeParameterMap(vbCrLf & $"TResult {FeaturesResources.is_} Integer"))
End Function
<WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(522342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522342")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestNestedAwaitKeywords2() As Task
Dim markup = <Workspace>
<Project Language="Visual Basic" CommonReferencesNet45="true">
<Document FilePath="SourceDocument">
Imports System
Imports System.Threading.Tasks
Class AsyncExample
Async Function AsyncMethod() As Task(Of Task(Of Integer))
Return NewMethod()
End Function
Private Shared Function NewMethod() As Task(Of Integer)
Throw New NotImplementedException()
End Function
Async Function UseAsync() As Task
Dim lambda As Func(Of Task(Of Integer)) = Async Function()
Return Await Await AsyncMethod()
End Function
Dim result = Await Await AsyncMethod()
Dim resultTask As Task(Of Task(Of Integer)) = AsyncMethod()
result = Awai$$t Await resultTask
result = Await lambda()
End Function
End Class
</Document>
</Project>
</Workspace>.ToString()
Dim description = <File><%= String.Format(FeaturesResources.Awaited_task_returns_0, "Structure System.Int32") %></File>.ConvertTestSourceTag()
Await TestFromXmlAsync(markup, MainDescription(description))
End Function
<WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337"), WorkItem(522342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522342")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestTaskType() As Task
Dim markup = <Workspace>
<Project Language="Visual Basic" CommonReferencesNet45="true">
<Document FilePath="SourceDocument">
Imports System
Imports System.Threading.Tasks
Class AsyncExample
Sub Goo()
Dim v as Tas$$k = Nothing
End Sub
End Class
</Document>
</Project>
</Workspace>.ToString()
Dim description = <File><<%= VBFeaturesResources.Awaitable %>> Class System.Threading.Tasks.Task</File>.ConvertTestSourceTag()
Await TestFromXmlAsync(markup, MainDescription(description))
End Function
<WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337"), WorkItem(522342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522342")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestTaskOfTType() As Task
Dim markup = <Workspace>
<Project Language="Visual Basic" CommonReferencesNet45="true">
<Document FilePath="SourceDocument">
Imports System
Imports System.Threading.Tasks
Class AsyncExample
Sub Goo()
Dim v as Tas$$k(Of Integer) = Nothing
End Sub
End Class
</Document>
</Project>
</Workspace>.ToString()
Dim description = <File><<%= VBFeaturesResources.Awaitable %>> Class System.Threading.Tasks.Task(Of TResult)</File>.ConvertTestSourceTag()
Await TestFromXmlAsync(markup, MainDescription(description), TypeParameterMap(vbCrLf & $"TResult {FeaturesResources.is_} Integer"))
End Function
<WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337"), WorkItem(522342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522342")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestAwaitablePrefixOnCustomAwaiter() As Task
Dim markup = <Workspace>
<Project Language="Visual Basic" CommonReferencesNet45="true">
<Document FilePath="SourceDocument">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.CompilerServices
Module Program
Sub Main(args As String())
Dim x As C$$
End Sub
End Module
Class C
Public Function GetAwaiter() As MyAwaiter
End Function
End Class
Public Class MyAwaiter
Implements INotifyCompletion
Public Property IsCompleted As Boolean
Public Sub GetResult()
End Sub
Public Sub OnCompleted(continuation As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
End Class
</Document>
</Project>
</Workspace>.ToString()
Dim description = <File><<%= VBFeaturesResources.Awaitable %>> Class C</File>.ConvertTestSourceTag()
Await TestFromXmlAsync(markup, MainDescription(description))
End Function
<WorkItem(792629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792629")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestGenericMethodWithConstraintsAtDeclaration() As Task
Await TestInClassAsync("Private Function Go$$o(Of TIn As Class, TOut)(arg As TIn) As TOut
Goo(Of TIn, TOut)(Nothing)
End Function",
MainDescription("Function C.Goo(Of TIn As Class, TOut)(arg As TIn) As TOut"))
End Function
<WorkItem(792629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792629")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestGenericMethodWithMultipleConstraintsAtDeclaration() As Task
Await TestInClassAsync("Private Function Go$$o(Of TIn As {IComparable, New}, TOut)(arg As TIn) As TOut
Goo(Of TIn, TOut)(Nothing)
End Function",
MainDescription("Function C.Goo(Of TIn As {IComparable, New}, TOut)(arg As TIn) As TOut"))
End Function
<WorkItem(792629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792629")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestUnConstructedGenericMethodWithConstraintsAtInvocation() As Task
Await TestInClassAsync("Private Function Goo(Of TIn As {Class, New}, TOut)(arg As TIn) As TOut
G$$oo(Of TIn, TOut)(Nothing)
End Function",
MainDescription("Function C.Goo(Of TIn As {Class, New}, TOut)(arg As TIn) As TOut"))
End Function
<WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestDocumentationInImportsDirectiveWithAlias() As Task
Dim markup = <Workspace>
<Project Language="Visual Basic" CommonReferencesNet45="true">
<Document FilePath="SourceDocument">
Imports I = IGoo
Class C
Implements I$$
Public Sub Bar() Implements IGoo.Bar
Throw New NotImplementedException()
End Sub
End Class
''' <summary>
''' summary for interface IGoo
''' </summary>
Interface IGoo
Sub Bar()
End Interface
</Document>
</Project>
</Workspace>.ToString()
Await TestFromXmlAsync(markup, MainDescription("Interface IGoo"), Documentation("summary for interface IGoo"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(4868, "https://github.com/dotnet/roslyn/issues/4868")>
Public Async Function TestQuickInfoExceptions() As Task
Await TestAsync("
Imports System
Namespace MyNs
Class MyException1
Inherits Exception
End Class
Class MyException2
Inherits Exception
End Class
Class TestClass
''' <exception cref=""MyException1""></exception>
''' <exception cref=""T:MyNs.MyException2""></exception>
''' <exception cref=""System.Int32""></exception>
''' <exception cref=""Double""></exception>
''' <exception cref=""Not_A_Class_But_Still_Displayed""></exception>
Sub M()
M$$()
End Sub
End Class
End Namespace
",
Exceptions($"{vbCrLf}{WorkspacesResources.Exceptions_colon}{vbCrLf} MyException1{vbCrLf} MyException2{vbCrLf} Integer{vbCrLf} Double{vbCrLf} Not_A_Class_But_Still_Displayed"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")>
Public Async Function TestQuickInfoCaptures() As Task
Await TestAsync("
Class C
Sub M(x As Integer)
Dim a As System.Action = Sub$$()
x = x + 1
End Sub
End Sub
End Class
",
Captures($"{vbCrLf}{WorkspacesResources.Variables_captured_colon} x"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")>
Public Async Function TestQuickInfoCaptures2() As Task
Await TestAsync("
Class C
Sub M(x As Integer)
Dim a As System.Action = S$$ub() x = x + 1
End Sub
End Class
",
Captures($"{vbCrLf}{WorkspacesResources.Variables_captured_colon} x"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")>
Public Async Function TestQuickInfoCaptures3() As Task
Await TestAsync("
Class C
Sub M(x As Integer)
Dim a As System.Action(Of Integer) = Functio$$n(a) x = x + 1
End Sub
End Class
",
Captures($"{vbCrLf}{WorkspacesResources.Variables_captured_colon} x"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")>
Public Async Function TestQuickInfoCaptures4() As Task
Await TestAsync("
Class C
Sub M(x As Integer)
Dim a As System.Action(Of Integer) = Functio$$n(a)
x = x + 1
End Function
End Sub
End Class
",
Captures($"{vbCrLf}{WorkspacesResources.Variables_captured_colon} x"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")>
Public Async Function TestQuickInfoCaptures5() As Task
Await TestAsync("
Class C
Sub M([Me] As Integer)
Dim x As Integer = 0
Dim a As System.Action(Of Integer) = Functio$$n(a)
M(1)
x = x + 1
[Me] = [Me] + 1
End Function
End Sub
End Class
",
Captures($"{vbCrLf}{WorkspacesResources.Variables_captured_colon} Me, [Me], x"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(1516, "https://github.com/dotnet/roslyn/issues/1516")>
Public Async Function TestQuickInfoWithNonStandardSeeAttributesAppear() As Task
Await TestAsync("
Class C
''' <summary>
''' <see cref=""System.String"" />
''' <see href=""http://microsoft.com"" />
''' <see langword=""Nothing"" />
''' <see unsupported-attribute=""cat"" />
''' </summary>
Sub M()
M$$()
End Sub
End Class
",
Documentation("String http://microsoft.com Nothing cat"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(410932, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=410932")>
Public Async Function TestGenericMethodInDocComment() As Task
Await TestWithImportsAsync(<Text><![CDATA[
Public Class Test
Function F(Of T)() As T
F(Of T)()
End Function
''' <summary>
''' <see cref="F$$(Of T)()"/>
''' </summary>
Public Sub S()
End Sub
End Class
]]></Text>.NormalizedValue,
MainDescription("Function Test.F(Of T)() As T"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")>
Public Async Function PropertyWithSameNameAsOtherType() As Task
Await TestAsync("
Imports ConsoleApp3.ConsoleApp
Module Program
Public B As A
Public A As B
Sub Main()
B = ConsoleApp.B.F$$()
End Sub
End Module
Namespace ConsoleApp
Class A
End Class
Class B
Public Shared Function F() As A
Return Nothing
End Function
End Class
End Namespace
",
MainDescription("Function ConsoleApp.B.F() As ConsoleApp.A"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")>
Public Async Function PropertyWithSameNameAsOtherType2() As Task
Await TestAsync("
Module Program
Public Bar As List(Of Bar)
Sub Main()
Tes$$t(Of Bar)()
End Sub
Sub Test(Of T)()
End Sub
End Module
Class Bar
End Class
",
MainDescription("Sub Program.Test(Of Bar)()"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(548762, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=548762")>
Public Async Function DefaultPropertyTransformation_01() As Task
Await TestAsync("
<System.Reflection.DefaultMember(""Item"")>
Class C1
Default Public Property Item(x As String) As String
Get
Return """"
End Get
Set(value As String)
End Set
End Property
End Class
Class C2
Public Property ViewData As C1
End Class
Class C3
Inherits C2
Sub Test()
View$$Data(""Title"") = ""About""
End Sub
End Class",
MainDescription("Property C2.ViewData As C1"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(548762, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=548762")>
Public Async Function DefaultPropertyTransformation_02() As Task
Await TestAsync("
<System.Reflection.DefaultMember(""Item"")>
Class C1
Default Public Property Item(x As String) As String
Get
Return """"
End Get
Set(value As String)
End Set
End Property
End Class
Class C2
Public Shared Property ViewData As C1
End Class
Class C3
Inherits C2
Sub Test()
View$$Data(""Title"") = ""About""
End Sub
End Class",
MainDescription("Property C2.ViewData As C1"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(548762, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=548762")>
Public Async Function DefaultPropertyTransformation_03() As Task
Await TestAsync("
<System.Reflection.DefaultMember(""Item"")>
Class C1
Default Public Property Item(x As String) As String
Get
Return """"
End Get
Set(value As String)
End Set
End Property
End Class
Class C2
Public Function ViewData As C1
Return Nothing
End Function
End Class
Class C3
Inherits C2
Sub Test()
View$$Data(""Title"") = ""About""
End Sub
End Class",
MainDescription("Function C2.ViewData() As C1"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(548762, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=548762")>
Public Async Function DefaultPropertyTransformation_04() As Task
Await TestAsync("
<System.Reflection.DefaultMember(""Item"")>
Class C1
Default Public Property Item(x As String) As String
Get
Return """"
End Get
Set(value As String)
End Set
End Property
End Class
Class C2
Public Shared Function ViewData As C1
Return Nothing
End Function
End Class
Class C3
Inherits C2
Sub Test()
View$$Data(""Title"") = ""About""
End Sub
End Class",
MainDescription("Function C2.ViewData() As C1"))
End Function
<WorkItem(30642, "https://github.com/dotnet/roslyn/issues/30642")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function BuiltInOperatorWithUserDefinedEquivalent() As Task
Await TestAsync(
"
class X
sub N(a as string, b as string)
dim v = a $$= b
end sub
end class",
MainDescription("Operator String.=(a As String, b As String) As Boolean"),
SymbolGlyph(Glyph.Operator))
End Function
<WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestGetAccessorDocumentation() As Task
Await TestAsync("
Class C
''' <summary>Summary for property Goo</summary>
Property Goo As Integer
G$$et
Return 0
End Get
Set(value As Integer)
End Set
End Property
End Class",
Documentation("Summary for property Goo"))
End Function
<WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")>
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestSetAccessorDocumentation() As Task
Await TestAsync("
Class C
''' <summary>Summary for property Goo</summary>
Property Goo As Integer
Get
Return 0
End Get
S$$et(value As Integer)
End Set
End Property
End Class",
Documentation("Summary for property Goo"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")>
Public Async Function QuickInfoOnIndexerOpenParen() As Task
Await TestAsync("
Class C
Default Public ReadOnly Property Item(ByVal index As Integer) As Integer
Get
Return 1
End Get
End Property
Sub M()
Dim x = New C()
Dim y = x$$(4)
End Sub
End Class",
MainDescription("ReadOnly Property C.Item(index As Integer) As Integer"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")>
Public Async Function QuickInfoOnIndexerCloseParen() As Task
Await TestAsync("
Class C
Default Public ReadOnly Property Item(ByVal index As Integer) As Integer
Get
Return 1
End Get
End Property
Sub M()
Dim x = New C()
Dim y = x(4$$)
End Sub
End Class",
MainDescription("ReadOnly Property C.Item(index As Integer) As Integer"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")>
Public Async Function QuickInfoOnIndexer_MissingOnRegularMethodCall() As Task
Await TestAsync("
Class C
Sub M()
M($$)
End Sub
End Class",
Nothing)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")>
Public Async Function QuickInfoOnIndexer_MissingOnArrayAccess() As Task
Await TestAsync("
Class C
Sub M()
Dim x(4) As Integer
Dim y = x(3$$)
End Sub
End Class",
MainDescription("Structure System.Int32"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")>
Public Async Function QuickInfoWithRemarksOnFunction() As Task
Await TestAsync("
Class C
''' <summary>
''' Summary text
''' </summary>
''' <remarks>
''' Remarks text
''' </remarks>
Function M() As Integer
Return $$M()
End Function
End Class",
MainDescription("Function C.M() As Integer"),
Documentation("Summary text"),
Remarks($"{vbCrLf}Remarks text"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")>
Public Async Function QuickInfoWithRemarksOnPropertyAccessor() As Task
Await TestAsync("
Class C
''' <summary>
''' Summary text
''' </summary>
''' <remarks>
''' Remarks text
''' </remarks>
ReadOnly Property M As Integer
$$Get
Return 0
End Get
End Property
End Class",
MainDescription("Property Get C.M() As Integer"),
Documentation("Summary text"),
Remarks($"{vbCrLf}Remarks text"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")>
Public Async Function QuickInfoWithReturnsOnFunction() As Task
Await TestAsync("
Class C
''' <summary>
''' Summary text
''' </summary>
''' <returns>
''' Returns text
''' </returns>
Function M() As Integer
Return $$M()
End Function
End Class",
MainDescription("Function C.M() As Integer"),
Documentation("Summary text"),
Returns($"{vbCrLf}{FeaturesResources.Returns_colon}{vbCrLf} Returns text"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")>
Public Async Function QuickInfoWithReturnsOnPropertyAccessor() As Task
Await TestAsync("
Class C
''' <summary>
''' Summary text
''' </summary>
''' <returns>
''' Returns text
''' </returns>
ReadOnly Property M As Integer
$$Get
Return 0
End Get
End Property
End Class",
MainDescription("Property Get C.M() As Integer"),
Documentation("Summary text"),
Returns($"{vbCrLf}{FeaturesResources.Returns_colon}{vbCrLf} Returns text"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")>
Public Async Function QuickInfoWithValueOnFunction() As Task
Await TestAsync("
Class C
''' <summary>
''' Summary text
''' </summary>
''' <value>
''' Value text
''' </value>
Function M() As Integer
Return $$M()
End Function
End Class",
MainDescription("Function C.M() As Integer"),
Documentation("Summary text"),
Value($"{vbCrLf}{FeaturesResources.Value_colon}{vbCrLf} Value text"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")>
Public Async Function QuickInfoWithValueOnPropertyAccessor() As Task
Await TestAsync("
Class C
''' <summary>
''' Summary text
''' </summary>
''' <value>
''' Value text
''' </value>
ReadOnly Property M As Integer
$$Get
Return 0
End Get
End Property
End Class",
MainDescription("Property Get C.M() As Integer"),
Documentation("Summary text"),
Value($"{vbCrLf}{FeaturesResources.Value_colon}{vbCrLf} Value text"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(57031, "https://github.com/dotnet/roslyn/issues/57031")>
Public Async Function QuickInfo_DotInInvocation() As Task
Await TestAsync("
Public Class C
Public Sub M(ByVal a As Integer)
End Sub
Public Sub M(ByVal a As Integer, ParamArray b As Integer())
End Sub
End Class
Class Program
Private Shared Sub Main()
Dim c = New C()
c$$.M(1, 2)
End Sub
End Class
",
MainDescription($"Sub C.M(a As Integer, ParamArray b As Integer()) (+ 1 {FeaturesResources.overload})"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(57031, "https://github.com/dotnet/roslyn/issues/57031")>
Public Async Function QuickInfo_BeforeMemberNameInInvocation() As Task
Await TestAsync("
Public Class C
Public Sub M(ByVal a As Integer)
End Sub
Public Sub M(ByVal a As Integer, ParamArray b As Integer())
End Sub
End Class
Class Program
Private Shared Sub Main()
Dim c = New C()
c.$$M(1, 2)
End Sub
End Class
",
MainDescription($"Sub C.M(a As Integer, ParamArray b As Integer()) (+ 1 {FeaturesResources.overload})"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
<WorkItem(57031, "https://github.com/dotnet/roslyn/issues/57031")>
Public Async Function QuickInfo_AfterMemberNameInInvocation() As Task
Await TestAsync("
Public Class C
Public Sub M(ByVal a As Integer)
End Sub
Public Sub M(ByVal a As Integer, ParamArray b As Integer())
End Sub
End Class
Class Program
Private Shared Sub Main()
Dim c = New C()
c.M$$(1, 2)
End Sub
End Class
",
MainDescription($"Sub C.M(a As Integer, ParamArray b As Integer()) (+ 1 {FeaturesResources.overload})"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestSingleTupleType() As Task
Await TestInClassAsync(
"sub M(t as (x as integer, y as string))
end sub
sub N()
$$M(nothing)
end sub",
MainDescription("Sub C.M(t As (x As Integer, y As String))"),
NoTypeParameterMap)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestMultipleTupleTypesSameType() As Task
Await TestInClassAsync(
"sub M(s As (x As Integer, y As String), t As (x As Integer, y As String)) { }
void N()
{
$$M(default)
}",
MainDescription("Sub C.M(s As 'a, t As 'a)"),
NoTypeParameterMap,
AnonymousTypes($"
{FeaturesResources.Types_colon}
'a {FeaturesResources.is_} (x As Integer, y As String)"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestMultipleTupleTypesDifferentTypes1() As Task
Await TestInClassAsync(
"sub M(s As (x As Integer, y As String), u As (a As Integer, b As String))
end sub
sub N()
$$M(nothing)
end sub",
MainDescription("Sub C.M(s As (x As Integer, y As String), u As (a As Integer, b As String))"),
NoTypeParameterMap)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestMultipleTupleTypesDifferentTypes2() As Task
Await TestInClassAsync(
"sub M(s As (x As Integer, y As String), t As (x As Integer, y As String), u As (a As Integer, b As String), v as (a As Integer, b As String))
end sub
sub N()
$$M(nothing)
end sub",
MainDescription("Sub C.M(s As 'a, t As 'a, u As 'b, v As 'b)"),
NoTypeParameterMap,
AnonymousTypes($"
{FeaturesResources.Types_colon}
'a {FeaturesResources.is_} (x As Integer, y As String)
'b {FeaturesResources.is_} (a As Integer, b As String)"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestMultipleTupleTypesDifferentTypes3() As Task
Await TestInClassAsync(
"sub M(s As (x As Integer, y As String), t As (x As Integer, y As String), u As (a As Integer, b As String))
end sub
sub N()
$$M(nothing)
end sub",
MainDescription("Sub C.M(s As 'a, t As 'a, u As 'b)"),
NoTypeParameterMap,
AnonymousTypes($"
{FeaturesResources.Types_colon}
'a {FeaturesResources.is_} (x As Integer, y As String)
'b {FeaturesResources.is_} (a As Integer, b As String)"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestMultipleTupleTypesInference() As Task
Await TestInClassAsync(
"function M(of T)(t as T) as T
end function
sub N()
dim x as (a As Integer, b As String) = nothing
$$M(x)
end sub",
MainDescription("Function C.M(Of 'a)(t As 'a) As 'a"),
NoTypeParameterMap,
AnonymousTypes($"
{FeaturesResources.Types_colon}
'a {FeaturesResources.is_} (a As Integer, b As String)"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestAnonymousTypeWithTupleTypesInference1() As Task
Await TestInClassAsync(
"function M(of T)(t as T) as T
end function
sub N()
dim x as new with { key .x = directcast(nothing, (a As Integer, b As String)) }
$$M(x)
end sub",
MainDescription("Function C.M(Of 'a)(t As 'a) As 'a"),
NoTypeParameterMap,
AnonymousTypes($"
{FeaturesResources.Types_colon}
'a {FeaturesResources.is_} New With {{ Key .x As (a As Integer, b As String) }}"))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
Public Async Function TestAnonymousTypeWithTupleTypesInference2() As Task
Await TestInClassAsync(
"function M(of T)(t as T) as T
end function
sub N()
dim x as new with { key .x = directcast(nothing, (a As Integer, b As String), key .y = directcast(nothing, (a As Integer, b As String)) }
$$M(x)
end sub",
MainDescription("Function C.M(Of 'a)(t As 'a) As 'a"),
NoTypeParameterMap,
AnonymousTypes($"
{FeaturesResources.Types_colon}
'a {FeaturesResources.is_} New With {{ Key .x As 'b, Key .y As 'b }}
'b {FeaturesResources.is_} (a As Integer, b As String)"))
End Function
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/EditorFeatures/VisualBasicTest/QuickInfo/SemanticQuickInfoSourceTests.vb
|
Visual Basic
|
mit
| 111,337
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a backing field of WithEvents property.
''' Attributes applied on the property syntax are applied on the backing field.
''' </summary>
Friend NotInheritable Class SourceWithEventsBackingFieldSymbol
Inherits SourceMemberFieldSymbol
Private _property As SourcePropertySymbol
Public Sub New([property] As SourcePropertySymbol,
syntaxRef As SyntaxReference,
name As String)
MyBase.New([property].ContainingSourceType,
syntaxRef,
name,
SourceMemberFlags.AccessibilityPrivate Or If([property].IsShared, SourceMemberFlags.Shared, SourceMemberFlags.None))
_property = [property]
End Sub
Public Overrides ReadOnly Property AssociatedSymbol As Symbol
Get
Return _property
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean
Get
Return True
End Get
End Property
Friend Overrides ReadOnly Property ImplicitlyDefinedBy(Optional membersInProgress As Dictionary(Of String, ArrayBuilder(Of Symbol)) = Nothing) As Symbol
Get
Return _property
End Get
End Property
Friend Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
MyBase.AddSynthesizedAttributes(compilationState, attributes)
Dim compilation = _property.DeclaringCompilation
Debug.Assert(Not Me.ContainingType.IsImplicitlyDeclared)
AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute(
WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor))
AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerBrowsableNeverAttribute())
AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute(
WellKnownMember.System_Runtime_CompilerServices_AccessedThroughPropertyAttribute__ctor,
ImmutableArray.Create(New TypedConstant(compilation.GetSpecialType(SpecialType.System_String),
TypedConstantKind.Primitive,
AssociatedSymbol.Name))))
End Sub
End Class
End Namespace
|
dsplaisted/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/Source/SourceWithEventsBackingFieldSymbol.vb
|
Visual Basic
|
apache-2.0
| 3,271
|
'*********************************************************
'
' Copyright (c) Microsoft. All rights reserved.
' This code is licensed under the MIT License (MIT).
' THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
' ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
' IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
' PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
'
'*********************************************************
Imports System
Imports System.Collections.Generic
Imports System.Globalization
Imports System.IO
Imports System.Threading
Imports System.Threading.Tasks
Imports SDKTemplate
Imports Windows.Networking.BackgroundTransfer
Imports Windows.Storage
Imports Windows.UI.Xaml
Imports Windows.UI.Xaml.Controls
Imports Windows.UI.Xaml.Navigation
Imports Windows.Web
Namespace Global.BackgroundTransfer
''' <summary>
''' An empty page that can be used on its own or navigated to within a Frame.
''' </summary>
Public NotInheritable Partial Class Scenario1_Download
Inherits Page
Implements IDisposable
' A pointer back to the main page. This is needed if you want to call methods in MainPage such
' as NotifyUser()
Private rootPage As MainPage = MainPage.Current
Private activeDownloads As List(Of DownloadOperation)
Private cts As CancellationTokenSource
Public Sub New()
cts = New CancellationTokenSource()
Me.InitializeComponent()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
If cts IsNot Nothing Then
cts.Dispose()
cts = Nothing
End If
GC.SuppressFinalize(Me)
End Sub
''' <summary>
''' Invoked when this page is about to be displayed in a Frame.
''' </summary>
''' <param name="e">Event data that describes how this page was reached. The Parameter
''' property is typically used to configure the page.</param>
Protected Async Overrides Sub OnNavigatedTo(e As NavigationEventArgs)
Await DiscoverActiveDownloadsAsync()
End Sub
' Enumerate the downloads that were going on in the background while the app was closed.
Private Async Function DiscoverActiveDownloadsAsync() As Task
activeDownloads = New List(Of DownloadOperation)()
Dim downloads As IReadOnlyList(Of DownloadOperation) = Nothing
Try
downloads = Await BackgroundDownloader.GetCurrentDownloadsAsync()
Catch ex As Exception
If Not IsExceptionHandled("Discovery error", ex) Then
Throw
End If
Return
End Try
Log("Loading background downloads: " & downloads.Count)
If downloads.Count > 0 Then
Dim tasks As List(Of Task) = New List(Of Task)()
For Each download In downloads
Log(String.Format(CultureInfo.CurrentCulture, "Discovered background download: {0}, Status: {1}", download.Guid, download.Progress.Status))
tasks.Add(HandleDownloadAsync(download, False))
Next
Await Task.WhenAll(tasks)
End If
End Function
Private Async Sub StartDownload(priority As BackgroundTransferPriority)
' Validating the URI is required since it was received from an untrusted source (user input).
' The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs.
' Note that when enabling the text box users may provide URIs to machines on the intrAnet that require
' the "Home or Work Networking" capability.
Dim source As Uri = Nothing
If Not Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, source) Then
rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage)
Return
End If
Dim destination As String = fileNameField.Text.Trim()
If String.IsNullOrWhiteSpace(destination) Then
rootPage.NotifyUser("A local file name is required.", NotifyType.ErrorMessage)
Return
End If
Dim destinationFile As StorageFile
Try
destinationFile = Await KnownFolders.PicturesLibrary.CreateFileAsync(destination, CreationCollisionOption.GenerateUniqueName)
Catch ex As FileNotFoundException
rootPage.NotifyUser("Error while creating file: " & ex.Message, NotifyType.ErrorMessage)
Return
End Try
Dim downloader As BackgroundDownloader = New BackgroundDownloader()
Dim download As DownloadOperation = downloader.CreateDownload(source, destinationFile)
Log(String.Format(CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}", source.AbsoluteUri, destinationFile.Name, priority, download.Guid))
download.Priority = priority
Await HandleDownloadAsync(download, True)
End Sub
Private Sub StartDownload_Click(sender As Object, e As RoutedEventArgs)
StartDownload(BackgroundTransferPriority.Default)
End Sub
Private Sub StartHighPriorityDownload_Click(sender As Object, e As RoutedEventArgs)
StartDownload(BackgroundTransferPriority.High)
End Sub
Private Sub PauseAll_Click(sender As Object, e As RoutedEventArgs)
Log("Downloads: " & activeDownloads.Count)
For Each download In activeDownloads
' DownloadOperation.Progress is updated in real-time while the operation is ongoing. Therefore,
' we must make a local copy so that we can have a consistent view of that ever-changing state
' throughout this Sub procedure's lifetime.
Dim currentProgress As BackgroundDownloadProgress = download.Progress
If currentProgress.Status = BackgroundTransferStatus.Running Then
download.Pause()
Log("Paused: " & download.Guid.ToString())
Else
Log(String.Format(CultureInfo.CurrentCulture, "Skipped: {0}, Status: {1}", download.Guid, currentProgress.Status))
End If
Next
End Sub
Private Sub ResumeAll_Click(sender As Object, e As RoutedEventArgs)
Log("Downloads: " & activeDownloads.Count)
For Each download In activeDownloads
' DownloadOperation.Progress is updated in real-time while the operation is ongoing. Therefore,
' we must make a local copy so that we can have a consistent view of that ever-changing state
' throughout this Sub procedure's lifetime.
Dim currentProgress As BackgroundDownloadProgress = download.Progress
If currentProgress.Status = BackgroundTransferStatus.PausedByApplication Then
download.Resume()
Log("Resumed: " & download.Guid.ToString())
Else
Log(String.Format(CultureInfo.CurrentCulture, "Skipped: {0}, Status: {1}", download.Guid, currentProgress.Status))
End If
Next
End Sub
Private Sub CancelAll_Click(sender As Object, e As RoutedEventArgs)
Log("Canceling Downloads: " & activeDownloads.Count)
cts.Cancel()
cts.Dispose()
cts = New CancellationTokenSource()
activeDownloads = New List(Of DownloadOperation)()
End Sub
' Note that this event is invoked on a background thread, so we cannot access the UI directly.
Private Sub DownloadProgress(download As DownloadOperation)
' DownloadOperation.Progress is updated in real-time while the operation is ongoing. Therefore,
' we must make a local copy so that we can have a consistent view of that ever-changing state
' throughout this Sub procedure's lifetime.
Dim currentProgress As BackgroundDownloadProgress = download.Progress
MarshalLog(String.Format(CultureInfo.CurrentCulture, "Progress: {0}, Status: {1}", download.Guid, currentProgress.Status))
Dim percent As Double = 100
If currentProgress.TotalBytesToReceive > 0 Then
percent = currentProgress.BytesReceived * 100 / currentProgress.TotalBytesToReceive
End If
MarshalLog(String.Format(CultureInfo.CurrentCulture, " - Transfered bytes: {0} of {1}, {2}%", currentProgress.BytesReceived, currentProgress.TotalBytesToReceive, percent))
If currentProgress.HasRestarted Then
MarshalLog(" - Download restarted")
End If
If currentProgress.HasResponseChanged Then
' We have received new response headers from the server.
' Be aware that GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP).
Dim response As ResponseInformation = download.GetResponseInformation()
Dim headersCount As Integer = If(response IsNot Nothing, response.Headers.Count, 0)
MarshalLog(" - Response updated; Header count: " & headersCount)
End If
End Sub
Private Async Function HandleDownloadAsync(download As DownloadOperation, start As Boolean) As Task
Try
LogStatus("Running: " & download.Guid.ToString(), NotifyType.StatusMessage)
activeDownloads.Add(download)
Dim progressCallback As Progress(Of DownloadOperation) = New Progress(Of DownloadOperation)(AddressOf DownloadProgress)
If start Then
Await download.StartAsync().AsTask(cts.Token, progressCallback)
Else
Await download.AttachAsync().AsTask(cts.Token, progressCallback)
End If
Dim response As ResponseInformation = download.GetResponseInformation()
' GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP).
Dim statusCode As String = If(response IsNot Nothing, response.StatusCode.ToString(), String.Empty)
LogStatus(String.Format(CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}", download.Guid, statusCode), NotifyType.StatusMessage)
Catch ex As TaskCanceledException
LogStatus("Canceled: " & download.Guid.ToString(), NotifyType.StatusMessage)
Catch ex As Exception
If Not IsExceptionHandled("Execution error", ex, download) Then
Throw
End If
Finally
activeDownloads.Remove(download)
End Try
End Function
Private Function IsExceptionHandled(title As String, ex As Exception, Optional download As DownloadOperation = Nothing) As Boolean
Dim [error] As WebErrorStatus = BackgroundTransferError.GetStatus(ex.HResult)
If [error] = WebErrorStatus.Unknown Then
Return False
End If
If download Is Nothing Then
LogStatus(String.Format(CultureInfo.CurrentCulture, "Error: {0}: {1}", title, [error]), NotifyType.ErrorMessage)
Else
LogStatus(String.Format(CultureInfo.CurrentCulture, "Error: {0} - {1}: {2}", download.Guid, title, [error]), NotifyType.ErrorMessage)
End If
Return True
End Function
' When operations happen on a background thread we have to marshal UI updates back to the UI thread.
Private Sub MarshalLog(value As String)
Dim ignore = Me.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, Sub()
Log(value)
End Sub)
End Sub
Private Sub Log(message As String)
outputField.Text &= message & vbCrLf
End Sub
Private Sub LogStatus(message As String, type As NotifyType)
rootPage.NotifyUser(message, type)
Log(message)
End Sub
End Class
End Namespace
|
huoxudong125/Windows-universal-samples
|
Samples/BackgroundTransfer/vb/BackgroundTransfer/Scenario1_Download.xaml.vb
|
Visual Basic
|
mit
| 12,282
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Operations
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration
Friend MustInherit Class AbstractEndConstructResult
Public MustOverride Sub Apply(textView As ITextView,
subjectBuffer As ITextBuffer,
caretPosition As Integer,
smartIndentationService As ISmartIndentationService,
undoHistoryRegistry As ITextUndoHistoryRegistry,
editorOperationsFactoryService As IEditorOperationsFactoryService)
Protected Sub SetIndentForFirstBlankLine(textView As ITextView, subjectBuffer As ITextBuffer, smartIndentationService As ISmartIndentationService, cursorLine As ITextSnapshotLine)
For lineNumber = cursorLine.LineNumber To subjectBuffer.CurrentSnapshot.LineCount
Dim line = subjectBuffer.CurrentSnapshot.GetLineFromLineNumber(lineNumber)
If String.IsNullOrWhiteSpace(line.GetText()) Then
Dim indent = textView.GetDesiredIndentation(smartIndentationService, line)
If indent.HasValue Then
textView.TryMoveCaretToAndEnsureVisible(New VirtualSnapshotPoint(line.Start, indent.Value))
Else
textView.TryMoveCaretToAndEnsureVisible(New VirtualSnapshotPoint(line.Start, 0))
End If
Return
End If
Next
End Sub
End Class
End Namespace
|
robinsedlaczek/roslyn
|
src/EditorFeatures/VisualBasic/EndConstructGeneration/AbstractEndConstructResult.vb
|
Visual Basic
|
apache-2.0
| 1,763
|
Imports TextAdventures.Quest.EditorControls
Imports TextAdventures.Quest.EditorController
Imports TextAdventures.Utility.Language.L
Public Class Editor
Private WithEvents m_controller As EditorController
Private m_elementEditors As Dictionary(Of String, WPFElementEditor)
Private m_currentEditor As WPFElementEditor
Private m_menu As TextAdventures.Quest.Controls.Menu
Private m_filename As String
Private m_currentElement As String
Private m_codeView As Boolean
Private m_lastSelection As String
Private m_currentEditorData As IEditorDataExtendedAttributeInfo
Private m_unsavedChanges As Boolean
Private WithEvents m_fileWatcher As System.IO.FileSystemWatcher
Private m_simpleMode As Boolean
Private m_editorStyle As EditorStyle = EditorStyle.TextAdventure
Private m_reloadingFromCodeView As Boolean
Private m_uiHidden As Boolean
Private m_splitHelper As TextAdventures.Utility.SplitterHelper
Public Event AddToRecent(filename As String, name As String)
Public Event Close()
Public Event Play(filename As String)
Public Event Loaded(name As String)
Public Event NewGame()
Public Event OpenGame()
Public Event PlayWalkthrough(filename As String, walkthrough As String, record As Boolean)
Public Event InitialiseFinished(success As Boolean)
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
BannerVisible = False
HideUI()
End Sub
Public Sub Initialise(ByRef filename As String)
m_menu.Visible = False
If Not m_uiHidden Then
HideUI()
End If
m_currentElement = Nothing
m_currentEditor = Nothing
m_filename = filename
If m_controller IsNot Nothing Then
m_controller.Uninitialise()
End If
m_controller = New EditorController()
m_unsavedChanges = False
InitialiseEditorControlsList()
ctlReloadBanner.Visible = False
m_controller.StartInitialise(filename)
End Sub
Private Sub m_controller_InitialiseFinished(sender As Object, e As EditorController.InitialiseResults) Handles m_controller.InitialiseFinished
BeginInvoke(Sub()
If e.Success Then
m_controller.UpdateTree()
Application.DoEvents()
Dim path As String = System.IO.Path.GetDirectoryName(m_filename)
Dim filter As String = System.IO.Path.GetFileName(m_filename)
m_fileWatcher = New System.IO.FileSystemWatcher(path, "*.aslx")
m_fileWatcher.EnableRaisingEvents = True
m_simpleMode = False
SetUpTree()
SetUpToolbar()
ctlLoading.UpdateStatus("Loading editors...")
SetUpEditors()
RaiseEvent AddToRecent(m_filename, m_controller.GameName)
EditorStyle = m_controller.EditorStyle
SimpleMode = (CInt(TextAdventures.Utility.Registry.GetSetting("Quest", "Settings", "EditorSimpleMode", 0)) = 1)
SetWordWrap(CInt(TextAdventures.Utility.Registry.GetSetting("Quest", "Settings", "EditorWordWrap", 0)) = 1)
m_splitHelper = New TextAdventures.Utility.SplitterHelper(splitMain, "Quest", "EditorSplitter")
m_splitHelper.LoadSplitterPositions()
m_menu.Visible = True
m_uiHidden = False
Me.SuspendLayout()
DisplayCodeView(False)
ctlLoading.Visible = False
splitMain.Visible = True
ctlTree.Visible = True
ctlToolbar.Visible = True
Me.ResumeLayout()
ctlTree.SetSelectedItem("game")
ctlTree.FocusOnTree()
SetWindowTitle()
ShowEditor("game")
End If
If m_reloadingFromCodeView Then
If Not e.Success Then
' Couldn't reload the file due to an error, so show code view again
m_menu.Visible = True
m_uiHidden = False
splitMain.Visible = True
ctlTree.Visible = True
ctlToolbar.Visible = True
ctlLoading.Visible = False
DisplayCodeView(True)
Else
ctlTree.TrySetSelectedItem(m_lastSelection)
End If
m_reloadingFromCodeView = False
Else
RaiseEvent InitialiseFinished(e.Success)
End If
ctlLoading.Clear()
End Sub)
End Sub
Private Sub InitialiseEditorControlsList()
EditorControls.ElementEditor.InitialiseEditorControls(m_controller)
End Sub
Public Sub SetMenu(menu As TextAdventures.Quest.Controls.Menu)
m_menu = menu
menu.AddMenuClickHandler("save", AddressOf Save)
menu.AddMenuClickHandler("saveas", AddressOf SaveAs)
menu.AddMenuClickHandler("undo", AddressOf Undo)
menu.AddMenuClickHandler("redo", AddressOf Redo)
menu.AddMenuClickHandler("addpage", AddressOf AddNewPage)
menu.AddMenuClickHandler("addobject", AddressOf AddNewObject)
menu.AddMenuClickHandler("addroom", AddressOf AddNewRoom)
menu.AddMenuClickHandler("addexit", AddressOf AddNewExit)
menu.AddMenuClickHandler("addverb", AddressOf AddNewVerb)
menu.AddMenuClickHandler("addcommand", AddressOf AddNewCommand)
menu.AddMenuClickHandler("addfunction", AddressOf AddNewFunction)
menu.AddMenuClickHandler("addtimer", AddressOf AddNewTimer)
menu.AddMenuClickHandler("addturnscript", AddressOf AddNewTurnScript)
menu.AddMenuClickHandler("addwalkthrough", AddressOf AddNewWalkthrough)
menu.AddMenuClickHandler("addlibrary", AddressOf AddNewLibrary)
menu.AddMenuClickHandler("addimpliedtype", AddressOf AddNewImpliedType)
menu.AddMenuClickHandler("addtemplate", AddressOf AddNewTemplate)
menu.AddMenuClickHandler("adddynamictemplate", AddressOf AddNewDynamicTemplate)
menu.AddMenuClickHandler("adddelegate", AddressOf AddNewDelegate)
menu.AddMenuClickHandler("addobjecttype", AddressOf AddNewObjectType)
menu.AddMenuClickHandler("addeditor", AddressOf AddNewEditor)
menu.AddMenuClickHandler("addjavascript", AddressOf AddNewJavascript)
menu.AddMenuClickHandler("play", AddressOf PlayGame)
menu.AddMenuClickHandler("close", AddressOf DoClose)
menu.AddMenuClickHandler("cut", AddressOf Cut)
menu.AddMenuClickHandler("copy", AddressOf Copy)
menu.AddMenuClickHandler("paste", AddressOf Paste)
menu.AddMenuClickHandler("delete", AddressOf Delete)
menu.AddMenuClickHandler("publish", AddressOf Publish)
menu.AddMenuClickHandler("find", AddressOf Find)
menu.AddMenuClickHandler("replace", AddressOf Replace)
menu.AddMenuClickHandler("simplemode", AddressOf ToggleSimpleMode)
menu.AddMenuClickHandler("codeview", AddressOf ToggleCodeView)
menu.AddMenuClickHandler("wordwrap", AddressOf ToggleWordWrap)
End Sub
Private Sub SetUpToolbar()
ctlToolbar.ResetToolbar()
ctlToolbar.AddButtonHandler("new", AddressOf CreateNew)
ctlToolbar.AddButtonHandler("open", AddressOf Open)
ctlToolbar.AddButtonHandler("save", AddressOf Save)
ctlToolbar.AddButtonHandler("undo", AddressOf Undo)
ctlToolbar.AddButtonHandler("redo", AddressOf Redo)
ctlToolbar.AddButtonHandler("addpage", AddressOf AddNewPage)
ctlToolbar.AddButtonHandler("addobject", AddressOf AddNewObject)
ctlToolbar.AddButtonHandler("addroom", AddressOf AddNewRoom)
ctlToolbar.AddButtonHandler("play", AddressOf PlayGame)
ctlToolbar.AddButtonHandler("cut", AddressOf Cut)
ctlToolbar.AddButtonHandler("copy", AddressOf Copy)
ctlToolbar.AddButtonHandler("paste", AddressOf Paste)
ctlToolbar.AddButtonHandler("delete", AddressOf Delete)
ctlToolbar.AddButtonHandler("find", AddressOf Find)
ctlToolbar.AddButtonHandler("replace", AddressOf Replace)
ctlToolbar.AddButtonHandler("code", AddressOf ToggleCodeView)
ctlToolbar.AddButtonHandler("logbug", AddressOf LogBug)
ctlToolbar.AddButtonHandler("help", AddressOf Help)
End Sub
Private Sub SetUpTree()
ctlTree.SetAvailableFilters(m_controller.AvailableFilters)
ctlTree.SetCanDragDelegate(AddressOf m_controller.CanMoveElement)
ctlTree.SetDoDragDelegate(AddressOf m_controller.MoveElement)
ctlTree.CollapseAdvancedNode()
ctlTree.ScrollToTop()
ctlTree.AddMenuClickHandler("addpage", AddressOf AddNewPage)
ctlTree.AddMenuClickHandler("addobject", AddressOf AddNewObject)
ctlTree.AddMenuClickHandler("addroom", AddressOf AddNewRoom)
ctlTree.AddMenuClickHandler("addexit", AddressOf AddNewExit)
ctlTree.AddMenuClickHandler("addverb", AddressOf AddNewVerb)
ctlTree.AddMenuClickHandler("addcommand", AddressOf AddNewCommand)
ctlTree.AddMenuClickHandler("addfunction", AddressOf AddNewFunction)
ctlTree.AddMenuClickHandler("addtimer", AddressOf AddNewTimer)
ctlTree.AddMenuClickHandler("addturnscript", AddressOf AddNewTurnScript)
ctlTree.AddMenuClickHandler("addwalkthrough", AddressOf AddNewWalkthrough)
ctlTree.AddMenuClickHandler("addlibrary", AddressOf AddNewLibrary)
ctlTree.AddMenuClickHandler("addimpliedtype", AddressOf AddNewImpliedType)
ctlTree.AddMenuClickHandler("addtemplate", AddressOf AddNewTemplate)
ctlTree.AddMenuClickHandler("adddynamictemplate", AddressOf AddNewDynamicTemplate)
ctlTree.AddMenuClickHandler("adddelegate", AddressOf AddNewDelegate)
ctlTree.AddMenuClickHandler("addobjecttype", AddressOf AddNewObjectType)
ctlTree.AddMenuClickHandler("addeditor", AddressOf AddNewEditor)
ctlTree.AddMenuClickHandler("addjavascript", AddressOf AddNewJavascript)
ctlTree.AddMenuClickHandler("cut", AddressOf Cut)
ctlTree.AddMenuClickHandler("copy", AddressOf Copy)
ctlTree.AddMenuClickHandler("paste", AddressOf Paste)
ctlTree.AddMenuClickHandler("delete", AddressOf Delete)
End Sub
Private Sub SetUpEditors()
UnloadEditors()
m_elementEditors = New Dictionary(Of String, WPFElementEditor)
For Each editor As String In m_controller.GetAllEditorNames()
Application.DoEvents()
AddEditor(editor)
Next
End Sub
Private Sub AddEditor(name As String)
' Get an EditorDefinition from the EditorController, then pass it in to the ElementEditor so it can initialise its
' tabs and subcontrols.
Dim editor As WPFElementEditor
editor = New WPFElementEditor
editor.Initialise(m_controller, m_controller.GetEditorDefinition(name))
editor.Visible = False
editor.Parent = pnlContent
editor.Dock = DockStyle.Fill
AddHandler editor.Dirty, AddressOf Editor_Dirty
m_elementEditors.Add(name, editor)
End Sub
Private Sub Editor_Dirty(sender As Object, args As DataModifiedEventArgs)
ctlToolbar.EnableUndo()
m_unsavedChanges = True
End Sub
Private Sub UnloadEditors()
If m_elementEditors Is Nothing Then Return
For Each editor As WPFElementEditor In m_elementEditors.Values
editor.Populate(Nothing)
editor.Uninitialise()
editor.Parent = Nothing
editor.Dispose()
RemoveHandler editor.Dirty, AddressOf Editor_Dirty
Next
m_elementEditors.Clear()
End Sub
Private Sub m_controller_AddedNode(sender As Object, e As AddedNodeEventArgs) Handles m_controller.AddedNode
Dim foreColor As Color = If(e.IsLibraryNode, SystemColors.ControlDarkDark, SystemColors.ControlText)
ctlTree.AddNode(e.Key, e.Text, e.Parent, foreColor, Nothing, e.Position)
End Sub
Private Sub m_controller_RemovedNode(sender As Object, e As RemovedNodeEventArgs) Handles m_controller.RemovedNode
ctlTree.RemoveNode(e.Key)
End Sub
Private Sub m_controller_RenamedNode(sender As Object, e As RenamedNodeEventArgs) Handles m_controller.RenamedNode
If m_currentElement = e.OldName Then
m_currentElement = e.NewName
RefreshCurrentElement()
End If
ctlTree.RenameNode(e.OldName, e.NewName)
ctlToolbar.RenameHistory(e.OldName, e.NewName)
End Sub
Private Sub m_controller_RetitledNode(sender As Object, e As RetitledNodeEventArgs) Handles m_controller.RetitledNode
If (m_currentElement = e.Key) Then
lblHeader.Text = e.NewTitle
End If
ctlTree.RetitleNode(e.Key, e.NewTitle)
ctlToolbar.RetitleHistory(e.Key, e.NewTitle)
End Sub
Private Sub m_controller_BeginTreeUpdate() Handles m_controller.BeginTreeUpdate
ctlTree.BeginUpdate()
End Sub
Private Sub m_controller_ClearTree() Handles m_controller.ClearTree
ctlTree.Clear()
End Sub
Private Sub m_controller_ElementUpdated(sender As Object, e As EditorController.ElementUpdatedEventArgs) Handles m_controller.ElementUpdated
If e.Element = m_currentElement Then
m_currentEditor.UpdateField(e.Attribute, e.NewValue, e.IsUndo)
End If
End Sub
Private Sub m_controller_ElementRefreshed(sender As Object, e As EditorController.ElementRefreshedEventArgs) Handles m_controller.ElementRefreshed
If e.Element = m_currentElement Then
RefreshCurrentElement()
End If
End Sub
Private Sub RefreshCurrentElement()
m_currentEditor.Populate(m_controller.GetEditorData(m_currentElement))
End Sub
Private Sub m_controller_EndTreeUpdate() Handles m_controller.EndTreeUpdate
ctlTree.EndUpdate()
End Sub
Private Sub m_controller_UndoListUpdated(sender As Object, e As EditorController.UpdateUndoListEventArgs) Handles m_controller.UndoListUpdated
ctlToolbar.UpdateUndoMenu(e.UndoList)
If e.UndoList.Count > 0 Then m_unsavedChanges = True
End Sub
Private Sub m_controller_RedoListUpdated(sender As Object, e As EditorController.UpdateUndoListEventArgs) Handles m_controller.RedoListUpdated
ctlToolbar.UpdateRedoMenu(e.UndoList)
If e.UndoList.Count > 0 Then m_unsavedChanges = True
End Sub
Private Sub m_controller_ShowMessage(sender As Object, e As ShowMessageEventArgs) Handles m_controller.ShowMessage
System.Windows.Forms.MessageBox.Show(e.Message)
End Sub
Private Sub ctlTree_FiltersUpdated() Handles ctlTree.FiltersUpdated
m_controller.UpdateFilterOptions(ctlTree.FilterSettings)
End Sub
Private Sub ctlTree_TreeGotFocus() Handles ctlTree.TreeGotFocus
SetMenuShortcutKeys()
End Sub
Private Sub ctlTree_TreeLostFocus() Handles ctlTree.TreeLostFocus
UnsetMenuShortcutKeys()
End Sub
Private Sub ctlTree_SelectionChanged(key As String) Handles ctlTree.SelectionChanged
ctlToolbar.AddHistory(key, m_controller.GetDisplayName(key))
ShowEditor(key)
End Sub
Private Sub SetMenuShortcutKeys()
m_menu.SetShortcut("cut", Keys.Control Or Keys.X)
m_menu.SetShortcut("copy", Keys.Control Or Keys.C)
m_menu.SetShortcut("paste", Keys.Control Or Keys.V)
m_menu.SetShortcut("delete", Keys.Delete)
End Sub
Private Sub UnsetMenuShortcutKeys()
m_menu.SetShortcut("cut", Keys.None)
m_menu.SetShortcut("copy", Keys.None)
m_menu.SetShortcut("paste", Keys.None)
m_menu.SetShortcut("delete", Keys.None)
End Sub
Private Sub ShowEditor(key As String)
If m_currentEditor IsNot Nothing Then
m_currentEditor.SaveData()
End If
Dim editorName As String = m_controller.GetElementEditorName(key)
If editorName Is Nothing Then
If m_currentEditor IsNot Nothing Then
m_currentEditor.Visible = False
End If
m_currentEditor = Nothing
BannerVisible = False
Else
Dim nextEditor As WPFElementEditor = m_elementEditors(editorName)
If Not m_currentEditor Is Nothing Then
If Not m_currentEditor.Equals(nextEditor) Then
m_currentEditor.Visible = False
End If
End If
m_currentEditor = nextEditor
m_currentElement = key
Dim data As IEditorData = m_controller.GetEditorData(key)
m_currentEditor.Populate(data)
nextEditor.Visible = True
Dim extendedData As IEditorDataExtendedAttributeInfo = TryCast(data, IEditorDataExtendedAttributeInfo)
If extendedData IsNot Nothing Then
m_currentEditorData = extendedData
BannerVisible = extendedData.IsLibraryElement
Dim filename As String = System.IO.Path.GetFileName(extendedData.Filename)
ctlBanner.AlertText = String.Format(T("EditorFromLibrary"), filename)
ctlBanner.ButtonText = T("EditorFromLibraryCopy")
Else
BannerVisible = False
End If
End If
lblHeader.Text = m_controller.GetDisplayName(key)
UpdateClipboardButtons()
End Sub
Private Function Save() As Boolean
If (m_filename.Length = 0) Then
Return SaveAs()
Else
Return Save(m_filename)
End If
End Function
Private Function SaveAs() As Boolean
' TO DO: If file is saved to a different folder, we should probably reinitialise as the
' available included libraries may have changed.
ctlSaveFile.FileName = m_filename
If ctlSaveFile.ShowDialog() = DialogResult.OK Then
m_filename = ctlSaveFile.FileName
SetWindowTitle()
Return Save(m_filename)
End If
Return False
End Function
Private Function Save(filename As String) As Boolean
Try
m_fileWatcher.EnableRaisingEvents = False
If m_codeView Then
ctlTextEditor.SaveFile(filename)
Else
If Not m_currentEditor Is Nothing Then
m_currentEditor.SaveData()
End If
System.IO.File.WriteAllText(filename, m_controller.Save())
End If
m_controller.Filename = filename
m_unsavedChanges = False
Return True
Catch ex As Exception
MsgBox(T("EditorUnableToSave") + Environment.NewLine + Environment.NewLine + ex.Message, MsgBoxStyle.Critical)
Return False
Finally
m_fileWatcher.EnableRaisingEvents = True
End Try
End Function
Private Sub ctlToolbar_HistoryClicked(Key As String) Handles ctlToolbar.HistoryClicked
If ctlTree.TrySetSelectedItemNoEvent(Key) Then
ShowEditor(Key)
End If
End Sub
Private Sub Undo()
If m_codeView Then
ctlTextEditor.Undo()
Else
If Not m_currentEditor Is Nothing Then
Dim thisElement As String = m_currentElement
m_currentEditor.SaveData()
m_controller.Undo()
If thisElement IsNot Nothing Then
ctlTree.TrySetSelectedItem(thisElement)
End If
End If
End If
End Sub
Private Sub Redo()
If m_codeView Then
ctlTextEditor.Redo()
Else
If Not m_currentEditor Is Nothing Then
Dim thisElement As String = m_currentElement
m_currentEditor.SaveData()
m_controller.Redo()
If thisElement IsNot Nothing Then
ctlTree.TrySetSelectedItem(thisElement)
End If
End If
End If
End Sub
Private Sub ctlToolbar_SaveCurrentEditor() Handles ctlToolbar.SaveCurrentEditor
If Not m_currentEditor Is Nothing Then
m_currentEditor.SaveData()
End If
End Sub
Private Sub ctlToolbar_UndoClicked(level As Integer) Handles ctlToolbar.UndoClicked
m_controller.Undo(level)
End Sub
Private Sub ctlToolbar_RedoClicked(level As Integer) Handles ctlToolbar.RedoClicked
m_controller.Redo(level)
End Sub
Private Sub ctlToolbar_UndoEnabled(enabled As Boolean) Handles ctlToolbar.UndoEnabled
If m_menu Is Nothing Then Return
m_menu.MenuEnabled("undo") = enabled
End Sub
Private Sub ctlToolbar_RedoEnabled(enabled As Boolean) Handles ctlToolbar.RedoEnabled
If m_menu Is Nothing Then Return
m_menu.MenuEnabled("redo") = enabled
End Sub
Private Function GetParentForCurrentSelection() As String
If m_controller.GetElementType(ctlTree.SelectedItem) = "object" AndAlso m_controller.GetObjectType(ctlTree.SelectedItem) = "object" Then
Return ctlTree.SelectedItem
Else
Return Nothing
End If
End Function
Private Sub AddNewElement(typeName As String, action As Action(Of String))
Dim result = PopupEditors.EditString(String.Format(T("EditorNewElement"), typeName), "")
If result.Cancelled Then Return
If Not ValidateInput(result.Result).IsValid Then Return
action(result.Result)
ctlTree.SetSelectedItem(result.Result)
End Sub
Private Sub AddNewObject()
Dim possibleParents = m_controller.GetPossibleNewObjectParentsForCurrentSelection(ctlTree.SelectedItem)
Dim result = GetNameAndParent(T("EditorNewObject"), possibleParents, True)
If result Is Nothing Then Return
m_controller.CreateNewObject(result.Value.Result, result.Value.ListResult, result.Value.AliasResult)
ctlTree.SetSelectedItem(result.Value.Result)
End Sub
Private Sub AddNewRoom()
Dim result = PopupEditors.EditString(T("EditorNewRoom"), "")
If result.Cancelled Then Return
If Not ValidateInput(result.Result).IsValid Then Return
m_controller.CreateNewRoom(result.Result, Nothing, Nothing)
ctlTree.SetSelectedItem(result.Result)
End Sub
Private Sub AddNewExit()
Dim newExit = m_controller.CreateNewExit(GetParentForCurrentSelection())
ctlTree.SetSelectedItem(newExit)
End Sub
Private Sub AddNewVerb()
Dim newVerb = m_controller.CreateNewVerb(GetParentForCurrentSelection(), True)
ctlTree.SetSelectedItem(newVerb)
End Sub
Private Sub AddNewCommand()
Dim newCommand = m_controller.CreateNewCommand(GetParentForCurrentSelection())
ctlTree.SetSelectedItem(newCommand)
End Sub
Private Sub AddNewFunction()
AddNewElement("function", AddressOf m_controller.CreateNewFunction)
End Sub
Private Sub AddNewTimer()
AddNewElement("timer", AddressOf m_controller.CreateNewTimer)
End Sub
Private Sub AddNewTurnScript()
Dim newTurnScript = m_controller.CreateNewTurnScript(GetParentForCurrentSelection())
ctlTree.SetSelectedItem(newTurnScript)
End Sub
Private Sub AddNewWalkthrough()
Dim possibleParents = m_controller.GetPossibleNewParentsForCurrentSelection(ctlTree.SelectedItem, "walkthrough")
Dim result = GetNameAndParent(T("EditorNewWalkthrough"), possibleParents, False)
If result Is Nothing Then Return
m_controller.CreateNewWalkthrough(result.Value.Result, result.Value.ListResult)
ctlTree.SetSelectedItem(result.Value.Result)
End Sub
Private Sub AddNewLibrary()
Dim newLibrary = m_controller.CreateNewIncludedLibrary()
ctlTree.SetSelectedItem(newLibrary)
End Sub
Private Sub AddNewTemplate()
Dim result = PopupEditors.EditString(T("EditorNewTemplate"), "")
If result.Cancelled Then Return
If Not ValidateInputTemplateName(result.Result) Then Return
Dim newTemplate = m_controller.CreateNewTemplate(result.Result)
ctlTree.SetSelectedItem(newTemplate)
End Sub
Private Sub AddNewDynamicTemplate()
AddNewElement("dynamic template", AddressOf m_controller.CreateNewDynamicTemplate)
End Sub
Private Sub AddNewObjectType()
AddNewElement("object type", AddressOf m_controller.CreateNewType)
End Sub
Private Sub AddNewJavascript()
Dim newJavascript = m_controller.CreateNewJavascript()
ctlTree.SetSelectedItem(newJavascript)
End Sub
' Intentionally unimplemented, as implied types are not editable in the Editor
Private Sub AddNewImpliedType()
Throw New NotImplementedException
End Sub
' Intentionally unimplemented, as editor elements are not editable in the Editor
Private Sub AddNewEditor()
Throw New NotImplementedException
End Sub
' Intentionally unimplemented, as delegate elements are not editable in the Editor
Private Sub AddNewDelegate()
Throw New NotImplementedException
End Sub
Private Sub AddNewPage()
Dim result = PopupEditors.EditString(T("EditorNewPage"), m_controller.GetUniqueElementName("Page1"))
If result.Cancelled Then Return
If Not ValidateInput(result.Result).IsValid Then Return
m_controller.CreateNewObject(result.Result, Nothing, Nothing)
ctlTree.SetSelectedItem(result.Result)
End Sub
Private Function GetNameAndParent(prompt As String, possibleParents As IEnumerable(Of String), allowAlias As Boolean) As PopupEditors.EditStringResult?
Dim noParent As String = T("EditorNotParents")
Dim result As PopupEditors.EditStringResult
If possibleParents Is Nothing Then
result = PopupEditors.EditString(prompt, "")
Else
Dim parentOptions As New List(Of String)
parentOptions.Add(noParent)
parentOptions.AddRange(possibleParents)
result = PopupEditors.EditStringWithDropdown(prompt, "", T("EditorParent"), parentOptions, parentOptions(1))
End If
If result.Cancelled Then Return Nothing
Dim validateResult = ValidateInput(result.Result, allowAlias)
If Not validateResult.IsValid Then
If Not allowAlias Or String.IsNullOrEmpty(validateResult.Alias) Then
Return Nothing
Else
result.Result = validateResult.ElementName
result.AliasResult = validateResult.Alias
End If
End If
If possibleParents IsNot Nothing And result.ListResult = noParent Then
result.ListResult = Nothing
End If
Return result
End Function
Private Class ValidateInputResult
Public ElementName As String
Public [Alias] As String
Public IsValid As Boolean
End Class
Private Function ValidateInput(input As String, Optional allowAlias As Boolean = False) As ValidateInputResult
Dim result As New ValidateInputResult
Dim validationResult = m_controller.CanAdd(input)
If validationResult.Valid Then
result.ElementName = input
result.IsValid = True
Return result
End If
If allowAlias And Not String.IsNullOrEmpty(validationResult.SuggestedName) Then
result.ElementName = validationResult.SuggestedName
result.Alias = input
result.IsValid = False
Return result
End If
PopupEditors.DisplayValidationError(validationResult, input, T("EditorUnableToAddEmement"))
result.IsValid = False
Return result
End Function
Private Function ValidateInputTemplateName(input As String) As Boolean
Dim result = m_controller.CanAddTemplate(input)
If result.Valid Then Return True
PopupEditors.DisplayValidationError(result, input, T("EditorUnableToAddTemplate"))
Return False
End Function
Public Function CreateNewGame() As String
Dim templates As Dictionary(Of String, TemplateData) = EditorController.GetAvailableTemplates()
Dim newGameWindow As New NewGameWindow
newGameWindow.SetAvailableTemplates(templates)
newGameWindow.ShowDialog()
If newGameWindow.Cancelled Then Return Nothing
Dim filename = newGameWindow.txtFilename.Text
Dim folder = System.IO.Path.GetDirectoryName(filename)
If Not System.IO.Directory.Exists(folder) Then
System.IO.Directory.CreateDirectory(folder)
End If
Dim initialFileText = EditorController.CreateNewGameFile(filename, newGameWindow.GetSelectedTemplate().Filename, newGameWindow.txtGameName.Text)
IO.File.WriteAllText(filename, initialFileText)
Return filename
End Function
Private Sub PlayGame()
If Not CheckGameIsSaved(Nothing) Then Return
RaiseEvent Play(m_filename)
End Sub
Private Sub DoClose()
CloseEditor(True, False)
End Sub
Public Function CloseEditor(raiseCloseEvent As Boolean, appIsExiting As Boolean) As Boolean
If Not CheckGameIsSaved(T("EditorSaveBeforeClosing")) Then Return False
If raiseCloseEvent Then RaiseEvent Close()
m_currentElement = Nothing
m_currentEditor = Nothing
m_currentEditorData = Nothing
If m_controller IsNot Nothing Then
m_controller.Uninitialise()
End If
m_controller = Nothing
If Not appIsExiting Then
UnloadEditors()
ctlTree.UnhookDelegates()
' uncomment for debugging memory leaks
'GC.Collect()
'GC.WaitForPendingFinalizers()
'GC.Collect()
End If
If Not appIsExiting Then
HideUI()
End If
Return True
End Function
Private Sub HideUI()
m_uiHidden = True
splitMain.Visible = False
ctlTree.Visible = False
ctlToolbar.Visible = False
ctlTextEditor.Visible = False
ctlLoading.Visible = True
ctlLoading.BringToFront()
End Sub
Private Sub Cut()
If m_codeView Then
ctlTextEditor.Cut()
Else
m_controller.CutElements({ctlTree.SelectedItem})
UpdateClipboardButtons()
End If
End Sub
Private Sub Copy()
If m_codeView Then
ctlTextEditor.Copy()
Else
m_controller.CopyElements({ctlTree.SelectedItem})
UpdateClipboardButtons()
End If
End Sub
Private Sub Paste()
If m_codeView Then
ctlTextEditor.Paste()
Else
m_controller.PasteElements(ctlTree.SelectedItem)
End If
End Sub
Private Sub Delete()
m_controller.DeleteElement(ctlTree.SelectedItem, True)
End Sub
Private Sub ToggleCodeView()
Dim unsavedPrompt = If(m_codeView,
T("EditorSaveBeforeLeavingCodeView"),
T("EditorSaveBeforeEditingThisGame"))
If Not CheckGameIsSaved(unsavedPrompt) Then Return
If Not m_codeView Then
m_lastSelection = ctlTree.SelectedItem
End If
DisplayCodeView(Not m_codeView)
If m_codeView Then
ctlTextEditor.LoadFile(m_filename)
ctlTextEditor.Focus()
SetWindowTitle()
Else
If ctlTextEditor.TextWasSaved Then
' file was changed in the text editor, so reload it
m_reloadingFromCodeView = True
Initialise(m_filename)
Else
SetWindowTitle()
End If
End If
If Not m_reloadingFromCodeView Then
UpdateClipboardButtons()
End If
End Sub
Private Sub DisplayCodeView(codeView As Boolean)
m_codeView = codeView
ctlToolbar.SetToggle("code", codeView)
ctlTextEditor.Visible = codeView
splitMain.Visible = Not codeView
ctlToolbar.CodeView = codeView
m_menu.MenuVisible("add") = Not codeView
m_menu.MenuVisible("find") = codeView
m_menu.MenuVisible("replace") = codeView
m_menu.MenuVisible("delete") = Not codeView
m_menu.MenuVisible("cut") = Not codeView
m_menu.MenuVisible("wordwrap") = codeView
m_menu.MenuEnabled("simplemode") = Not codeView
m_menu.MenuChecked("codeview") = codeView
m_menu.MenuEnabled("publish") = Not codeView
End Sub
Public Sub Redisplay()
DisplayCodeView(m_codeView)
UpdateClipboardButtons()
End Sub
Private Sub ctlTextEditor_UndoRedoEnabledUpdated(undoEnabled As Boolean, redoEnabled As Boolean) Handles ctlTextEditor.UndoRedoEnabledUpdated
ctlToolbar.UndoButtonEnabled = undoEnabled
ctlToolbar.RedoButtonEnabled = redoEnabled
If undoEnabled Or redoEnabled Then m_unsavedChanges = True
End Sub
Private Sub m_controller_RequestAddElement(sender As Object, e As RequestAddElementEventArgs) Handles m_controller.RequestAddElement
Select Case e.ElementType
Case "object"
Select Case e.ObjectType
Case "object"
AddNewObject()
Case "exit"
AddNewExit()
Case "command"
If e.Filter = "verb" Then
AddNewVerb()
Else
AddNewCommand()
End If
Case "turnscript"
AddNewTurnScript()
Case Else
Throw New ArgumentOutOfRangeException
End Select
Case "function"
AddNewFunction()
Case "timer"
AddNewTimer()
Case "walkthrough"
AddNewWalkthrough()
Case "include"
AddNewLibrary()
Case "implied"
AddNewImpliedType()
Case "template"
AddNewTemplate()
Case "dynamictemplate"
AddNewDynamicTemplate()
Case "delegate"
AddNewDelegate()
Case "type"
AddNewObjectType()
Case "editor"
AddNewEditor()
Case "javascript"
AddNewJavascript()
Case Else
Throw New ArgumentOutOfRangeException
End Select
End Sub
Private Sub m_controller_RequestEdit(sender As Object, e As RequestEditEventArgs) Handles m_controller.RequestEdit
ctlTree.SetSelectedItem(e.Key)
End Sub
Private Property BannerVisible As Boolean
Get
Return ctlBanner.Visible
End Get
Set(value As Boolean)
ctlBanner.Visible = value
pnlHeader.Height = If(value, 41, 18)
End Set
End Property
Private Sub ctlBanner_ButtonClicked() Handles ctlBanner.ButtonClicked
Dim thisElement As String = m_currentElement
m_controller.StartTransaction(String.Format(T("EditorCreateLocalCopy"), m_currentElement))
m_currentEditorData.MakeElementLocal()
m_controller.EndTransaction()
' Changing from library to non-library element (or vice-versa) will move the element in the tree,
' so re-select it
ctlTree.SetSelectedItem(thisElement)
End Sub
Private Sub UpdateClipboardButtons()
Dim canPaste As Boolean = m_codeView OrElse m_controller.CanPaste(ctlTree.SelectedItem)
m_menu.MenuEnabled("paste") = canPaste
ctlTree.SetMenuEnabled("paste", canPaste)
ctlToolbar.CanPaste = canPaste
Dim canCopy As Boolean = m_codeView OrElse m_controller.CanCopy(ctlTree.SelectedItem)
m_menu.MenuEnabled("copy") = canCopy
ctlTree.SetMenuEnabled("copy", canCopy)
ctlToolbar.CanCopy = canCopy
Dim canDelete As Boolean = (Not m_codeView) AndAlso m_controller.CanDelete(ctlTree.SelectedItem)
m_menu.MenuEnabled("delete") = canDelete
ctlTree.SetMenuEnabled("delete", canDelete)
ctlToolbar.CanDelete = canDelete
' Cut works again. The object is not cut out until it is pasted again. (SoonGames) (prior notification: "Cut" is disabled - see Issue Tracker #1062)
Dim canCut As Boolean = canCopy And canDelete
m_menu.MenuEnabled("cut") = canCut
ctlTree.SetMenuEnabled("cut", canCut)
ctlToolbar.CanCut = canCut
End Sub
Public Sub SetWindowTitle()
Dim title As String = System.IO.Path.GetFileName(m_filename)
If m_codeView Then
title += " [Code]"
End If
RaiseEvent Loaded(title)
End Sub
Private Sub CreateNew()
RaiseEvent NewGame()
End Sub
Private Sub Open()
RaiseEvent OpenGame()
End Sub
Public Function CheckGameIsSaved(prompt As String) As Boolean
If (Not m_codeView And m_unsavedChanges) Or (m_codeView And ctlTextEditor.IsModified) Then
Dim result As MsgBoxResult
If prompt Is Nothing Then
result = MsgBoxResult.Yes
Else
result = MsgBox(T("EditorUnsavedChanges") + Environment.NewLine + Environment.NewLine + prompt, MsgBoxStyle.YesNoCancel Or MsgBoxStyle.Exclamation)
End If
If result = MsgBoxResult.Yes Then
Dim saveOk As Boolean = Save()
If Not saveOk Then Return False
ElseIf result = MsgBoxResult.Cancel Then
Return False
End If
End If
Return True
End Function
Public Sub CancelUnsavedChanges()
m_unsavedChanges = False
End Sub
Private Sub LogBug()
LaunchURL("https://github.com/textadventures/quest/issues")
End Sub
Private Sub Help()
LaunchURL("http://docs.textadventures.co.uk/quest/")
End Sub
Private Sub LaunchURL(url As String)
Try
System.Diagnostics.Process.Start(url)
Catch ex As Exception
MsgBox(String.Format("Error launching {0}{1}{2}", url, Environment.NewLine + Environment.NewLine, ex.Message), MsgBoxStyle.Critical, "Quest")
End Try
End Sub
Private Sub Publish()
Dim frmPublish As New PublishWindow(m_filename, m_controller)
frmPublish.ShowDialog()
End Sub
Private Sub m_fileWatcher_Changed(sender As Object, e As System.IO.FileSystemEventArgs) Handles m_fileWatcher.Changed
BeginInvoke(Sub()
ctlReloadBanner.AlertText = String.Format(T("EditorModifiedOutside"), e.Name)
ctlReloadBanner.ButtonText = T("EditorReload")
ctlReloadBanner.Visible = True
End Sub)
End Sub
Private Sub ctlReloadBanner_ButtonClicked() Handles ctlReloadBanner.ButtonClicked
Reload()
End Sub
Private Sub Reload()
Dim lastSelection As String = Nothing
If Not m_codeView Then
lastSelection = ctlTree.SelectedItem
End If
Initialise(m_filename)
If lastSelection IsNot Nothing Then
ctlTree.TrySetSelectedItem(lastSelection)
End If
End Sub
Private Sub Find()
ctlTextEditor.Find()
End Sub
Private Sub Replace()
ctlTextEditor.Replace()
End Sub
Private Sub FindClose()
ctlTextEditor.FindClose()
End Sub
Private Sub m_controller_RequestRunWalkthrough(sender As Object, e As RequestRunWalkthroughEventArgs) Handles m_controller.RequestRunWalkthrough
If Not CheckGameIsSaved(Nothing) Then Return
RaiseEvent PlayWalkthrough(m_filename, e.Name, e.Record)
End Sub
Public Sub SetRecordedWalkthrough(name As String, steps As List(Of String))
m_controller.RecordWalkthrough(name, steps)
End Sub
Private Sub ToggleSimpleMode()
SimpleMode = Not m_menu.MenuChecked("simplemode")
End Sub
Public Property SimpleMode As Boolean
Get
Return m_simpleMode
End Get
Set(value As Boolean)
If (value <> m_simpleMode) Then
m_simpleMode = value
m_controller.SimpleMode = value
m_menu.MenuChecked("simplemode") = m_simpleMode
ctlToolbar.SimpleMode = value
SetMenuVisibility()
SetTreeMenuVisibility()
For Each editor As WPFElementEditor In m_elementEditors.Values
editor.SimpleMode = m_simpleMode
Next
TextAdventures.Utility.Registry.SaveSetting("Quest", "Settings", "EditorSimpleMode", If(m_simpleMode, 1, 0))
End If
End Set
End Property
Private Property EditorStyle As EditorStyle
Get
Return m_editorStyle
End Get
Set(value As EditorStyle)
If (value <> m_editorStyle) Then
m_editorStyle = value
SetMenuVisibility()
SetTreeMenuVisibility()
ctlToolbar.EditorStyle = value
End If
End Set
End Property
Private Sub SetMenuVisibility()
m_menu.MenuVisible("addpage") = (EditorStyle = EditorStyle.GameBook)
m_menu.MenuVisible("addobject") = (EditorStyle = EditorStyle.TextAdventure)
m_menu.MenuVisible("addroom") = (EditorStyle = EditorStyle.TextAdventure)
m_menu.MenuVisible("addexit") = (EditorStyle = EditorStyle.TextAdventure)
m_menu.MenuVisible("addverb") = (EditorStyle = EditorStyle.TextAdventure) And Not SimpleMode
m_menu.MenuVisible("addcommand") = (EditorStyle = EditorStyle.TextAdventure) And Not SimpleMode
m_menu.MenuVisible("addfunction") = Not SimpleMode
m_menu.MenuVisible("addtimer") = (EditorStyle = EditorStyle.TextAdventure) And Not SimpleMode
m_menu.MenuVisible("addturnscript") = (EditorStyle = EditorStyle.TextAdventure) And Not SimpleMode
m_menu.MenuVisible("addwalkthrough") = (EditorStyle = EditorStyle.TextAdventure) And Not SimpleMode
m_menu.MenuVisible("advanced") = (EditorStyle = EditorStyle.TextAdventure) And Not SimpleMode
m_menu.MenuVisible("codeview") = Not SimpleMode
End Sub
Private Sub SetTreeMenuVisibility()
ctlTree.ShowFilterBar = Not SimpleMode
ctlTree.SetMenuVisible("addpage", EditorStyle = EditorStyle.GameBook)
ctlTree.SetMenuVisible("addobject", EditorStyle = EditorStyle.TextAdventure)
ctlTree.SetMenuVisible("addroom", EditorStyle = EditorStyle.TextAdventure)
ctlTree.SetMenuVisible("addexit", EditorStyle = EditorStyle.TextAdventure)
ctlTree.SetMenuVisible("addverb", (EditorStyle = EditorStyle.TextAdventure) And Not SimpleMode)
ctlTree.SetMenuVisible("addcommand", (EditorStyle = EditorStyle.TextAdventure) And Not SimpleMode)
ctlTree.SetMenuVisible("addfunction", Not SimpleMode)
ctlTree.SetMenuVisible("addtimer", (EditorStyle = EditorStyle.TextAdventure) And Not SimpleMode)
ctlTree.SetMenuVisible("addturnscript", (EditorStyle = EditorStyle.TextAdventure) And Not SimpleMode)
ctlTree.SetMenuVisible("addwalkthrough", (EditorStyle = EditorStyle.TextAdventure) And Not SimpleMode)
ctlTree.SetMenuVisible("addlibrary", Not SimpleMode)
ctlTree.SetMenuVisible("addtemplate", (EditorStyle = EditorStyle.TextAdventure) And Not SimpleMode)
ctlTree.SetMenuVisible("adddynamictemplate", (EditorStyle = EditorStyle.TextAdventure) And Not SimpleMode)
ctlTree.SetMenuVisible("addobjecttype", (EditorStyle = EditorStyle.TextAdventure) And Not SimpleMode)
ctlTree.SetMenuVisible("addjavascript", Not SimpleMode)
ctlTree.SetMenuSeparatorVisible("separator1", True)
ctlTree.SetMenuSeparatorVisible("separator2", True)
ctlTree.SetMenuSeparatorVisible("separator3", (EditorStyle = EditorStyle.TextAdventure) And Not SimpleMode)
ctlTree.SetMenuSeparatorVisible("separator4", ((EditorStyle = EditorStyle.GameBook) Or (EditorStyle = EditorStyle.TextAdventure)) And Not SimpleMode)
ctlTree.SetMenuSeparatorVisible("separator5", ((EditorStyle = EditorStyle.GameBook) Or (EditorStyle = EditorStyle.TextAdventure)) And Not SimpleMode)
End Sub
Private Sub m_controller_LoadStatus(sender As Object, e As EditorController.LoadStatusEventArgs) Handles m_controller.LoadStatus
BeginInvoke(Sub() ctlLoading.UpdateStatus(e.Status))
End Sub
Private Sub m_controller_LibrariesUpdated(sender As Object, e As EditorController.LibrariesUpdatedEventArgs) Handles m_controller.LibrariesUpdated
BeginInvoke(Sub()
ctlReloadBanner.AlertText = T("EditorSaveGameAndClickReload")
ctlReloadBanner.Visible = True
End Sub)
End Sub
Private Sub SetWordWrap(turnOn As Boolean)
m_menu.MenuChecked("wordwrap") = turnOn
ctlTextEditor.WordWrap = turnOn
TextAdventures.Utility.Registry.SaveSetting("Quest", "Settings", "EditorWordWrap", If(ctlTextEditor.WordWrap, 1, 0))
End Sub
Private Sub ToggleWordWrap()
SetWordWrap(Not m_menu.MenuChecked("wordwrap"))
End Sub
Private Sub ctlTree_Load(sender As Object, e As EventArgs) Handles ctlTree.Load
End Sub
Private Sub StatusStrip1_ItemClicked(sender As Object, e As ToolStripItemClickedEventArgs) Handles StatusStrip1.ItemClicked
End Sub
Private Sub ctlReloadBanner_Load(sender As Object, e As EventArgs) Handles ctlReloadBanner.Load
End Sub
End Class
|
textadventures/quest
|
Editor/Editor.vb
|
Visual Basic
|
mit
| 47,809
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
Imports Microsoft.NetFramework.Analyzers
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Diagnostics
Namespace Microsoft.NetFramework.VisualBasic.Analyzers
''' <summary>
''' CA2232: Mark Windows Forms entry points with STAThread
''' </summary>
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Public NotInheritable Class BasicMarkWindowsFormsEntryPointsWithStaThreadAnalyzer
Inherits MarkWindowsFormsEntryPointsWithStaThreadAnalyzer
End Class
End Namespace
|
dotnet/roslyn-analyzers
|
src/NetAnalyzers/VisualBasic/Microsoft.NetFramework.Analyzers/BasicMarkWindowsFormsEntryPointsWithStaThread.vb
|
Visual Basic
|
mit
| 648
|
''' <summary>
''' Prefix: lbl
''' </summary>
Public Class myLabel
Inherits Label
End Class
|
mcdenis/AccentApplicator
|
AccentCS.App/myControls/myLabel.vb
|
Visual Basic
|
mit
| 99
|
Option Strict Off
Option Explicit On
Imports Rhino
Imports Rhino.Geometry
Imports Rhino.DocObjects
Imports Rhino.Collections
Imports GH_IO
Imports GH_IO.Serialization
Imports Grasshopper
Imports Grasshopper.Kernel
Imports Grasshopper.Kernel.Data
Imports Grasshopper.Kernel.Types
Imports System
Imports System.IO
Imports System.Xml
Imports System.Xml.Linq
Imports System.Linq
Imports System.Data
Imports System.Drawing
Imports System.Reflection
Imports System.Collections
Imports System.Windows.Forms
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Imports SAP2000v17
''' <summary>
''' This class will be instantiated on demand by the Script component.
''' </summary>
Public Class Script_Instance
Inherits GH_ScriptInstance
#Region "Utility functions"
''' <summary>Print a String to the [Out] Parameter of the Script component.</summary>
''' <param name="text">String to print.</param>
Private Sub Print(ByVal text As String)
__out.Add(text)
End Sub
''' <summary>Print a formatted String to the [Out] Parameter of the Script component.</summary>
''' <param name="format">String format.</param>
''' <param name="args">Formatting parameters.</param>
Private Sub Print(ByVal format As String, ByVal ParamArray args As Object())
__out.Add(String.Format(format, args))
End Sub
''' <summary>Print useful information about an object instance to the [Out] Parameter of the Script component. </summary>
''' <param name="obj">Object instance to parse.</param>
Private Sub Reflect(ByVal obj As Object)
__out.Add(GH_ScriptComponentUtilities.ReflectType_VB(obj))
End Sub
''' <summary>Print the signatures of all the overloads of a specific method to the [Out] Parameter of the Script component. </summary>
''' <param name="obj">Object instance to parse.</param>
Private Sub Reflect(ByVal obj As Object, ByVal method_name As String)
__out.Add(GH_ScriptComponentUtilities.ReflectType_VB(obj, method_name))
End Sub
#End Region
#Region "Members"
''' <summary>Gets the current Rhino document.</summary>
Private RhinoDocument As RhinoDoc
''' <summary>Gets the Grasshopper document that owns this script.</summary>
Private GrasshopperDocument as GH_Document
''' <summary>Gets the Grasshopper script component that owns this script.</summary>
Private Component As IGH_Component
''' <summary>
''' Gets the current iteration count. The first call to RunScript() is associated with Iteration=0.
''' Any subsequent call within the same solution will increment the Iteration count.
''' </summary>
Private Iteration As Integer
#End Region
''' <summary>
''' This procedure contains the user code. Input parameters are provided as ByVal arguments,
''' Output parameter are ByRef arguments. You don't have to assign output parameters,
''' they will have default values.
''' </summary>
Private Sub RunScript(ByVal x As List(Of Double), ByVal y As List(Of Double), ByVal z As List(Of Double), ByVal P As Object, ByRef A As Object)
If P = True Then
Dim mySapObject As cOAPI = Nothing
mySapObject = DirectCast(System.Runtime.InteropServices.Marshal.GetActiveObject("CSI.SAP2000.API.SapObject"), cOAPI)
Dim mySapModel As cSapModel = mySapObject.SapModel
mySapModel.AreaObj.AddByCoord(4, x.ToArray(), y.ToArray(), z.ToArray, "Area_GH", "Shearing_walls")
End If
End Sub
'<Custom additional code>
'</Custom additional code>
Private __err As New List(Of String)
Private __out As New List(Of String)
Private doc As RhinoDoc = RhinoDoc.ActiveDoc 'Legacy field.
Private owner As Grasshopper.Kernel.IGH_ActiveObject 'Legacy field.
Private runCount As Int32 'Legacy field.
Public Overrides Sub InvokeRunScript(ByVal owner As IGH_Component, _
ByVal rhinoDocument As Object, _
ByVal iteration As Int32, _
ByVal inputs As List(Of Object), _
ByVal DA As IGH_DataAccess)
'Prepare for a new run...
'1. Reset lists
Me.__out.Clear()
Me.__err.Clear()
'Current field assignments.
Me.Component = owner
Me.Iteration = iteration
Me.GrasshopperDocument = owner.OnPingDocument()
Me.RhinoDocument = TryCast(rhinoDocument, Rhino.RhinoDoc)
'Legacy field assignments
Me.owner = Me.Component
Me.runCount = Me.Iteration
Me.doc = Me.RhinoDocument
'2. Assign input parameters
Dim x As List(Of Double) = Nothing
If (inputs(0) IsNot Nothing) Then
x = GH_DirtyCaster.CastToList(Of Double)(inputs(0))
End If
Dim y As List(Of Double) = Nothing
If (inputs(1) IsNot Nothing) Then
y = GH_DirtyCaster.CastToList(Of Double)(inputs(1))
End If
Dim z As List(Of Double) = Nothing
If (inputs(2) IsNot Nothing) Then
z = GH_DirtyCaster.CastToList(Of Double)(inputs(2))
End If
Dim P As System.Object = Nothing
If (inputs(3) IsNot Nothing) Then
P = DirectCast(inputs(3), System.Object)
End If
'3. Declare output parameters
Dim A As System.Object = Nothing
'4. Invoke RunScript
Call RunScript(x, y, z, P, A)
Try
'5. Assign output parameters to component...
If (A IsNot Nothing) Then
If (GH_Format.TreatAsCollection(A)) Then
Dim __enum_A As IEnumerable = DirectCast(A, IEnumerable)
DA.SetDataList(1, __enum_A)
Else
If (TypeOf A Is Grasshopper.Kernel.Data.IGH_DataTree) Then
'merge tree
DA.SetDataTree(1, DirectCast(A, Grasshopper.Kernel.Data.IGH_DataTree))
Else
'assign direct
DA.SetData(1, A)
End If
End If
Else
DA.SetData(1, Nothing)
End If
Catch ex As Exception
__err.Add(String.Format("Script exception: {0}", ex.Message))
Finally
'Add errors and messages...
If (owner.Params.Output.Count > 0) Then
If (TypeOf owner.Params.Output(0) Is Grasshopper.Kernel.Parameters.Param_String) Then
Dim __errors_plus_messages As New List(Of String)
If (Me.__err IsNot Nothing) Then __errors_plus_messages.AddRange(Me.__err)
If (Me.__out IsNot Nothing) Then __errors_plus_messages.AddRange(Me.__out)
If (__errors_plus_messages.Count > 0) Then
DA.SetDataList(0, __errors_plus_messages)
End If
End If
End If
End Try
End Sub
End Class
|
Fablab-Sevilla/GH2SAP
|
REF/ImportMeshSAP_GH.vb
|
Visual Basic
|
mit
| 6,593
|
Public Class OLStylePickerDialogPointControl
Public styleSettings As New StyleProperties
Public vertixFlag As Boolean = True
Private Sub OLStylePickerDialogPointControl_Load(sender As Object, e As EventArgs) Handles MyBase.Load
loadValuesToControls()
End Sub
Sub loadValuesToControls()
'load existing settings
NumericUpDown1.Value = styleSettings.OLSize
NumericUpDown2.Value = styleSettings.OLStrokeWidth
NumericUpDown3.Value = styleSettings.OLVertices
NumericUpDown4.Value = styleSettings.OLRotation
ComboBox1.Text = styleSettings.OLRotationField
Button1.BackColor = styleSettings.OLStrokeColor
Button2.BackColor = styleSettings.OLFillColour
End Sub
Private Sub NumericUpDown1_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown1.ValueChanged
styleSettings.OLSize = NumericUpDown1.Value
End Sub
Private Sub NumericUpDown2_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown2.ValueChanged
styleSettings.OLStrokeWidth = NumericUpDown2.Value
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sColour As New ColorDialog
sColour.Color = styleSettings.OLStrokeColor
sColour.ShowDialog()
styleSettings.OLStrokeColor = sColour.Color
Button1.BackColor = sColour.Color
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim fColour As New ColorDialog
fColour.Color = styleSettings.OLFillColour
fColour.ShowDialog()
styleSettings.OLFillColour = fColour.Color
Button2.BackColor = fColour.Color
End Sub
Private Sub NumericUpDown3_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown3.ValueChanged
If vertixFlag Then
vertixFlag = False
'prevent shapes with 1 or 2 (these produce blank and a line)
If NumericUpDown3.Value = 1 Then
NumericUpDown3.Value = 3
End If
If NumericUpDown3.Value = 2 Then
NumericUpDown3.Value = 0
End If
If NumericUpDown3.Value > 0 Then
styleSettings.OLPointType = "RegularShape"
Else
styleSettings.OLPointType = "Circle"
End If
styleSettings.OLVertices = NumericUpDown3.Value
vertixFlag = True
End If
End Sub
Private Sub NumericUpDown4_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown4.ValueChanged
styleSettings.OLRotation = NumericUpDown4.Value
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
styleSettings.OLRotationField = ComboBox1.Text
End Sub
End Class
|
JohnWilcock/OL3Designer
|
OL3Designer/UserControls/OLStyles/OL3StylePicker/OLStylePickerDialogPointControl.vb
|
Visual Basic
|
mit
| 2,899
|
Imports System.Data
Partial Class rPresupuestos_Articulos
Inherits vis2formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0))
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0))
Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1))
Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))
Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4))
Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4))
Dim lcParametro5Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5))
Dim lcParametro6Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6))
Dim lcParametro6Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(6))
Dim lcParametro7Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(7))
Dim lcParametro7Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(7))
Dim lcParametro8Desde As String = cusAplicacion.goReportes.paParametrosIniciales(8)
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim loComandoSeleccionar As New StringBuilder()
'-------------------------------------------------------------------------------------------'
' 1 - Select Principal
'-------------------------------------------------------------------------------------------'
loComandoSeleccionar.AppendLine(" SELECT Articulos.Cod_Art, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art, ")
loComandoSeleccionar.AppendLine(" Articulos.Cod_Mar, ")
loComandoSeleccionar.AppendLine(" Presupuestos.Status, ")
loComandoSeleccionar.AppendLine(" Presupuestos.Documento, ")
loComandoSeleccionar.AppendLine(" Presupuestos.Cod_Pro, ")
loComandoSeleccionar.AppendLine(" Presupuestos.Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Presupuestos.Cod_Ven, ")
loComandoSeleccionar.AppendLine(" Renglones_Presupuestos.Renglon, ")
loComandoSeleccionar.AppendLine(" Renglones_Presupuestos.Cod_Alm, ")
'loComandoSeleccionar.AppendLine(" Renglones_Presupuestos.Can_Art1, ")
Select Case lcParametro8Desde
Case "Todos"
loComandoSeleccionar.AppendLine(" Renglones_Presupuestos.Can_Art1, ")
Case "Backorder"
loComandoSeleccionar.AppendLine(" Renglones_Presupuestos.Can_Pen1 AS Can_Art1, ")
Case "Procesado"
loComandoSeleccionar.AppendLine(" (Renglones_Presupuestos.Can_Art1 - Renglones_Presupuestos.Can_Pen1) AS Can_Art1, ")
End Select
loComandoSeleccionar.AppendLine(" Renglones_Presupuestos.Cod_Uni, ")
loComandoSeleccionar.AppendLine(" Renglones_Presupuestos.Precio1, ")
loComandoSeleccionar.AppendLine(" Renglones_Presupuestos.Por_Des, ")
loComandoSeleccionar.AppendLine(" Renglones_Presupuestos.Mon_Net ")
loComandoSeleccionar.AppendLine(" FROM Articulos, ")
loComandoSeleccionar.AppendLine(" Presupuestos, ")
loComandoSeleccionar.AppendLine(" Renglones_Presupuestos, ")
loComandoSeleccionar.AppendLine(" Proveedores, ")
loComandoSeleccionar.AppendLine(" Vendedores, ")
loComandoSeleccionar.AppendLine(" Almacenes, ")
loComandoSeleccionar.AppendLine(" Marcas ")
loComandoSeleccionar.AppendLine(" WHERE Articulos.Cod_Art = Renglones_Presupuestos.Cod_Art ")
loComandoSeleccionar.AppendLine(" And Presupuestos.Documento = Renglones_Presupuestos.Documento ")
loComandoSeleccionar.AppendLine(" And Articulos.Cod_Mar = Marcas.Cod_Mar ")
loComandoSeleccionar.AppendLine(" And Presupuestos.Cod_Pro = Proveedores.Cod_Pro ")
loComandoSeleccionar.AppendLine(" And Presupuestos.Cod_Ven = Vendedores.Cod_Ven")
loComandoSeleccionar.AppendLine(" And Almacenes.Cod_Alm = Renglones_Presupuestos.Cod_Alm ")
loComandoSeleccionar.AppendLine(" And Renglones_Presupuestos.Cod_Art Between " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" And " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" And Presupuestos.Fec_Ini Between " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" And " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" And Presupuestos.Cod_Pro Between " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" And " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" And Presupuestos.Cod_Ven Between " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" And " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" And Articulos.Cod_Mar Between " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" And " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" And Presupuestos.Status IN (" & lcParametro5Desde & ")")
loComandoSeleccionar.AppendLine(" And Renglones_Presupuestos.Cod_Alm Between " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" And " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" And Presupuestos.Cod_rev Between " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" And " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine("ORDER BY " & lcOrdenamiento)
'loComandoSeleccionar.AppendLine(" ORDER BY Renglones_Presupuestos.Cod_Art ")
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodos(loComandoSeleccionar.ToString(), "curReportes")
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rPresupuestos_Articulos", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrPresupuestos_Articulos.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' JJD: 01/11/08: Codigo inicial
'-------------------------------------------------------------------------------------------'
' JJD: 01/05/09: Ajuste al obtener el status desde Estatus_Mixto_Documento
'-------------------------------------------------------------------------------------------'
' CMS: 22/07/09: Filtro BackOrder, lo conllevo al anexo del campo Can_Pen1,
' verificacion de registros
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rPresupuestos_Articulos.aspx.vb
|
Visual Basic
|
mit
| 9,855
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.34209
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.MyNoisyApp.My.MySettings
Get
Return Global.MyNoisyApp.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
P2P-Nathan/OpsMgr-ElasticSearch-DataWarehouse
|
MyNoisyApp/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,926
|
Option Explicit On
Option Infer On
Option Strict On
#Region " --------------->> Imports/ usings "
Imports SSP.Base.StringHandling.Attributes
#End Region
Namespace DateTimeHandling.Enums
<CultureCode(StringHandling.CultureCodes.de_DE)>
Public Enum WeekDayNamesShortGerman
Mo = 1
Di = 2
Mi = 3
[Do] = 4
Fr = 5
Sa = 6
So = 7
End Enum
End Namespace
|
vanitas-mundi/Base
|
Base/DateTimeHandling/Enums/WeekDayNamesShortGerman.vb
|
Visual Basic
|
mit
| 386
|
Option Infer On
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim documents As SolidEdgeFramework.Documents = Nothing
Dim draftDocument As SolidEdgeDraft.DraftDocument = Nothing
Dim sheet As SolidEdgeDraft.Sheet = Nothing
Dim featureControlFrames As SolidEdgeFrameworkSupport.FeatureControlFrames = Nothing
Dim featureControlFrame As SolidEdgeFrameworkSupport.FeatureControlFrame = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
documents = application.Documents
draftDocument = CType(documents.Add("SolidEdge.DraftDocument"), SolidEdgeDraft.DraftDocument)
sheet = draftDocument.ActiveSheet
featureControlFrames = CType(sheet.FeatureControlFrames, SolidEdgeFrameworkSupport.FeatureControlFrames)
featureControlFrame = featureControlFrames.Add(0.1, 0.1, 0)
featureControlFrame.PrimaryFrame = "%FL%VB0.001%MC%VBA"
featureControlFrame.AddVertex(0.2, 0.2, 0)
Dim name = featureControlFrame.Name
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgeFrameworkSupport.FeatureControlFrame.Name.vb
|
Visual Basic
|
mit
| 1,844
|
Imports System.ServiceModel
Imports System.ServiceModel.Description
Imports System.ServiceModel.Web
<ServiceContract()>
Public Interface IHelloWorldService
<OperationContract()>
<Web.WebGet()>
Function SayHello(s As String) As String
End Interface
|
max4456/WCFService
|
slnSelfHost/prjSelfHost/IHelloWorldService.vb
|
Visual Basic
|
bsd-2-clause
| 255
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeStyle
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification.Simplifiers
Friend Class ExpressionSimplifier
Inherits AbstractVisualBasicSimplifier(Of ExpressionSyntax, ExpressionSyntax)
Public Shared ReadOnly Instance As New ExpressionSimplifier()
Private Sub New()
End Sub
Public Overrides Function TrySimplify(expression As ExpressionSyntax,
semanticModel As SemanticModel,
optionSet As OptionSet,
ByRef replacementNode As ExpressionSyntax,
ByRef issueSpan As TextSpan,
cancellationToken As CancellationToken) As Boolean
If TryReduceExplicitName(expression, semanticModel, replacementNode, issueSpan, optionSet, cancellationToken) Then
Return True
End If
Return TrySimplify(expression, semanticModel, replacementNode, issueSpan)
End Function
Private Shared Function TryReduceExplicitName(
expression As ExpressionSyntax,
semanticModel As SemanticModel,
<Out> ByRef replacementNode As ExpressionSyntax,
<Out> ByRef issueSpan As TextSpan,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As Boolean
replacementNode = Nothing
issueSpan = Nothing
If expression.Kind = SyntaxKind.SimpleMemberAccessExpression Then
Dim memberAccess = DirectCast(expression, MemberAccessExpressionSyntax)
Return TryReduce(memberAccess, semanticModel,
replacementNode,
issueSpan,
optionSet,
cancellationToken)
ElseIf TypeOf expression Is NameSyntax Then
Dim name = DirectCast(expression, NameSyntax)
Return NameSimplifier.Instance.TrySimplify(
name, semanticModel, optionSet,
replacementNode, issueSpan, cancellationToken)
End If
Return False
End Function
Private Shared Function TryReduce(
memberAccess As MemberAccessExpressionSyntax,
semanticModel As SemanticModel,
<Out()> ByRef replacementNode As ExpressionSyntax,
<Out()> ByRef issueSpan As TextSpan,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As Boolean
If memberAccess.Expression Is Nothing OrElse memberAccess.Name Is Nothing Then
Return False
End If
If memberAccess.HasAnnotations(SpecialTypeAnnotation.Kind) Then
replacementNode = SyntaxFactory.PredefinedType(
SyntaxFactory.Token(
GetPredefinedKeywordKind(SpecialTypeAnnotation.GetSpecialType(memberAccess.GetAnnotations(SpecialTypeAnnotation.Kind).First())))) _
.WithLeadingTrivia(memberAccess.GetLeadingTrivia())
issueSpan = memberAccess.Span
Return True
End If
' See https//github.com/dotnet/roslyn/issues/40974
'
' To be very safe, we only support simplifying code that bound to a symbol without any
' sort of problems. We could potentially relax this in the future. However, we would
' need to be very careful about the implications of us offering to fixup 'broken' code
' in a manner that might end up making things worse Or confusing the user.
Dim symbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, memberAccess)
If symbol Is Nothing Then
Return False
End If
If memberAccess.Expression.IsKind(SyntaxKind.MeExpression) AndAlso
Not SimplificationHelpers.ShouldSimplifyThisOrMeMemberAccessExpression(semanticModel, optionSet, symbol) Then
Return False
End If
If Not memberAccess.IsRightSideOfDot() Then
Dim aliasReplacement As IAliasSymbol = Nothing
If TryReplaceWithAlias(memberAccess, semanticModel, aliasReplacement) Then
Dim identifierToken = SyntaxFactory.Identifier(
memberAccess.GetLeadingTrivia(),
aliasReplacement.Name,
memberAccess.GetTrailingTrivia())
identifierToken = TryEscapeIdentifierToken(identifierToken)
replacementNode = SyntaxFactory.IdentifierName(identifierToken)
issueSpan = memberAccess.Span
' In case the alias name is the same as the last name of the alias target, we only include
' the left part of the name in the unnecessary span to Not confuse uses.
If memberAccess.Name.Identifier.ValueText = identifierToken.ValueText Then
issueSpan = memberAccess.Expression.Span
End If
Return True
End If
If PreferPredefinedTypeKeywordInMemberAccess(memberAccess, optionSet) Then
If (symbol IsNot Nothing AndAlso symbol.IsKind(SymbolKind.NamedType)) Then
Dim keywordKind = GetPredefinedKeywordKind(DirectCast(symbol, INamedTypeSymbol).SpecialType)
If keywordKind <> SyntaxKind.None Then
replacementNode = SyntaxFactory.PredefinedType(
SyntaxFactory.Token(
memberAccess.GetLeadingTrivia(),
keywordKind,
memberAccess.GetTrailingTrivia()))
replacementNode = replacementNode.WithAdditionalAnnotations(
New SyntaxAnnotation(NameOf(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess)))
issueSpan = memberAccess.Span
Return True
End If
End If
End If
End If
' a module name was inserted by the name expansion, so removing this should be tried first.
If memberAccess.HasAnnotation(SimplificationHelpers.SimplifyModuleNameAnnotation) Then
If TryOmitModuleName(memberAccess, semanticModel, symbol, replacementNode, issueSpan, cancellationToken) Then
Return True
End If
End If
replacementNode = memberAccess.GetNameWithTriviaMoved()
issueSpan = memberAccess.Expression.Span
If CanReplaceWithReducedName(memberAccess, replacementNode, semanticModel, symbol, cancellationToken) Then
Return True
End If
If TryOmitModuleName(memberAccess, semanticModel, symbol, replacementNode, issueSpan, cancellationToken) Then
Return True
End If
Return False
End Function
Private Overloads Shared Function TrySimplify(
expression As ExpressionSyntax,
semanticModel As SemanticModel,
<Out> ByRef replacementNode As ExpressionSyntax,
<Out> ByRef issueSpan As TextSpan
) As Boolean
replacementNode = Nothing
issueSpan = Nothing
Select Case expression.Kind
Case SyntaxKind.SimpleMemberAccessExpression
If True Then
Dim memberAccess = DirectCast(expression, MemberAccessExpressionSyntax)
Dim newLeft As ExpressionSyntax = Nothing
If TrySimplifyMemberAccessOrQualifiedName(memberAccess.Expression, memberAccess.Name, semanticModel, newLeft, issueSpan) Then
' replacement node might not be in it's simplest form, so add simplify annotation to it.
replacementNode = memberAccess.Update(memberAccess.Kind, newLeft, memberAccess.OperatorToken, memberAccess.Name).WithAdditionalAnnotations(Simplifier.Annotation)
' Ensure that replacement doesn't change semantics.
Return Not ReplacementChangesSemantics(memberAccess, replacementNode, semanticModel)
End If
Return False
End If
Case SyntaxKind.QualifiedName
If True Then
Dim qualifiedName = DirectCast(expression, QualifiedNameSyntax)
Dim newLeft As ExpressionSyntax = Nothing
If TrySimplifyMemberAccessOrQualifiedName(qualifiedName.Left, qualifiedName.Right, semanticModel, newLeft, issueSpan) Then
If Not TypeOf newLeft Is NameSyntax Then
Contract.Fail("QualifiedName Left = " + qualifiedName.Left.ToString() + " and QualifiedName Right = " + qualifiedName.Right.ToString() + " . Left is tried to be replaced with the PredefinedType " + replacementNode.ToString())
End If
' replacement node might not be in it's simplest form, so add simplify annotation to it.
replacementNode = qualifiedName.Update(DirectCast(newLeft, NameSyntax), qualifiedName.DotToken, qualifiedName.Right).WithAdditionalAnnotations(Simplifier.Annotation)
' Ensure that replacement doesn't change semantics.
Return Not ReplacementChangesSemantics(qualifiedName, replacementNode, semanticModel)
End If
Return False
End If
End Select
Return False
End Function
Private Shared Function ReplacementChangesSemantics(originalExpression As ExpressionSyntax, replacedExpression As ExpressionSyntax, semanticModel As SemanticModel) As Boolean
Dim speculationAnalyzer = New SpeculationAnalyzer(originalExpression, replacedExpression, semanticModel, CancellationToken.None)
Return speculationAnalyzer.ReplacementChangesSemantics()
End Function
' Note: The caller needs to verify that replacement doesn't change semantics of the original expression.
Private Shared Function TrySimplifyMemberAccessOrQualifiedName(
left As ExpressionSyntax,
right As ExpressionSyntax,
semanticModel As SemanticModel,
<Out()> ByRef replacementNode As ExpressionSyntax,
<Out()> ByRef issueSpan As TextSpan
) As Boolean
replacementNode = Nothing
issueSpan = Nothing
If left IsNot Nothing AndAlso right IsNot Nothing Then
Dim leftSymbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, left)
If leftSymbol IsNot Nothing AndAlso leftSymbol.Kind = SymbolKind.NamedType Then
Dim rightSymbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, right)
If rightSymbol IsNot Nothing AndAlso (rightSymbol.IsStatic OrElse rightSymbol.Kind = SymbolKind.NamedType) Then
' Static member access or nested type member access.
Dim containingType As INamedTypeSymbol = rightSymbol.ContainingType
Dim isInCref = left.Ancestors(ascendOutOfTrivia:=True).OfType(Of CrefReferenceSyntax)().Any()
' Crefs in VB , irrespective of the expression are parsed as QualifiedName (no MemberAccessExpression)
' Hence the Left can never be a PredefinedType (or anything other than NameSyntax)
If isInCref AndAlso TypeOf rightSymbol Is IMethodSymbol AndAlso Not containingType.SpecialType = SpecialType.None Then
Return False
End If
If containingType IsNot Nothing AndAlso Not containingType.Equals(leftSymbol) Then
Dim namedType = TryCast(leftSymbol, INamedTypeSymbol)
If namedType IsNot Nothing AndAlso
containingType.TypeArguments.Length <> 0 Then
Return False
End If
' We have a static member access or a nested type member access using a more derived type.
' Simplify syntax so as to use accessed member's most immediate containing type instead of the derived type.
replacementNode = containingType.GenerateTypeSyntax().WithLeadingTrivia(left.GetLeadingTrivia()).WithTrailingTrivia(left.GetTrailingTrivia()).WithAdditionalAnnotations(Simplifier.Annotation)
issueSpan = left.Span
Return True
End If
End If
End If
End If
Return False
End Function
Private Shared Function TryOmitModuleName(memberAccess As MemberAccessExpressionSyntax,
semanticModel As SemanticModel,
symbol As ISymbol,
<Out> ByRef replacementNode As ExpressionSyntax,
<Out> ByRef issueSpan As TextSpan,
cancellationToken As CancellationToken) As Boolean
If memberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) Then
Dim symbolForMemberAccess = semanticModel.GetSymbolInfo(DirectCast(memberAccess.Parent, MemberAccessExpressionSyntax), cancellationToken).Symbol
If symbolForMemberAccess.IsModuleMember Then
replacementNode = memberAccess.Expression.WithLeadingTrivia(memberAccess.GetLeadingTrivia())
issueSpan = memberAccess.Name.Span
Dim parent = DirectCast(memberAccess.Parent, MemberAccessExpressionSyntax)
Dim parentReplacement = parent.ReplaceNode(parent.Expression, replacementNode)
If CanReplaceWithReducedName(parent, parentReplacement, semanticModel, symbol, cancellationToken) Then
Return True
End If
End If
End If
Return False
End Function
Private Shared Function CanReplaceWithReducedName(
memberAccess As MemberAccessExpressionSyntax,
reducedNode As ExpressionSyntax,
semanticModel As SemanticModel,
symbol As ISymbol,
cancellationToken As CancellationToken
) As Boolean
If Not IsMeOrNamedTypeOrNamespace(memberAccess.Expression, semanticModel) Then
Return False
End If
' See if we can simplify a member access expression of the form E.M or E.M() to M or M()
Dim speculationAnalyzer = New SpeculationAnalyzer(memberAccess, reducedNode, semanticModel, cancellationToken)
If Not speculationAnalyzer.SymbolsForOriginalAndReplacedNodesAreCompatible() OrElse
speculationAnalyzer.ReplacementChangesSemantics() Then
Return False
End If
If memberAccess.Expression.IsKind(SyntaxKind.MyBaseExpression) Then
Dim enclosingNamedType = semanticModel.GetEnclosingNamedType(memberAccess.SpanStart, cancellationToken)
If enclosingNamedType IsNot Nothing AndAlso
Not enclosingNamedType.IsSealed AndAlso
symbol IsNot Nothing AndAlso
symbol.IsOverridable() Then
Return False
End If
End If
Return True
End Function
Private Shared Function IsMeOrNamedTypeOrNamespace(expression As ExpressionSyntax, semanticModel As SemanticModel) As Boolean
If expression.Kind = SyntaxKind.MeExpression Then
Return True
End If
Dim expressionInfo = semanticModel.GetSymbolInfo(expression)
If SimplificationHelpers.IsValidSymbolInfo(expressionInfo.Symbol) Then
If TypeOf expressionInfo.Symbol Is INamespaceOrTypeSymbol Then
Return True
End If
If expressionInfo.Symbol.IsThisParameter() Then
Return True
End If
End If
Return False
End Function
End Class
End Namespace
|
physhi/roslyn
|
src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/ExpressionSimplifier.vb
|
Visual Basic
|
apache-2.0
| 17,749
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.SignatureHelp
Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp
Public Class GetXmlNamespaceExpressionSignatureHelpProviderTests
Inherits AbstractVisualBasicSignatureHelpProviderTests
Public Sub New(workspaceFixture As VisualBasicTestWorkspaceFixture)
MyBase.New(workspaceFixture)
End Sub
Friend Overrides Function CreateSignatureHelpProvider() As ISignatureHelpProvider
Return New GetXmlNamespaceExpressionSignatureHelpProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationForGetType() As Task
Dim markup = <a><![CDATA[
Class C
Sub Foo()
Dim x = GetXmlNamespace($$
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem(
$"GetXmlNamespace([{XmlNamespacePrefix}]) As System.Xml.Linq.XNamespace",
ReturnsXNamespaceObject,
XMLNSToReturnObjectFor,
currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
End Class
End Namespace
|
ericfe-ms/roslyn
|
src/EditorFeatures/VisualBasicTest/SignatureHelp/GetXmlNamespaceExpressionSignatureHelpProviderTests.vb
|
Visual Basic
|
apache-2.0
| 1,723
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Shared.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.ComponentModelHost
Imports Microsoft.VisualStudio.LanguageServices.Implementation.DebuggerIntelliSense
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Projection
Imports Microsoft.VisualStudio.TextManager.Interop
Imports Microsoft.VisualStudio.Utilities
Imports TextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic
Friend Class VisualBasicDebuggerIntelliSenseContext
Inherits AbstractDebuggerIntelliSenseContext
Private innerMostContainingNodeIsExpression As Boolean = False
Sub New(wpfTextView As IWpfTextView,
vsTextView As IVsTextView,
debuggerBuffer As IVsTextLines,
contextBuffer As ITextBuffer,
currentStatementSpan As TextSpan(),
componentModel As IComponentModel,
serviceProvider As IServiceProvider)
MyBase.New(
wpfTextView,
vsTextView,
debuggerBuffer,
contextBuffer,
currentStatementSpan,
componentModel,
serviceProvider,
componentModel.GetService(Of IContentTypeRegistryService).GetContentType(ContentTypeNames.VisualBasicContentType))
End Sub
' Test constructor
Sub New(wpfTextView As IWpfTextView,
textBuffer As ITextBuffer,
span As TextSpan(),
componentModel As IComponentModel,
isImmediateWindow As Boolean)
MyBase.New(
wpfTextView,
textBuffer,
span,
componentModel,
componentModel.GetService(Of IContentTypeRegistryService).GetContentType(ContentTypeNames.VisualBasicContentType),
isImmediateWindow)
End Sub
Protected Overrides Function GetAdjustedContextPoint(contextPoint As Integer, document As Document) As Integer
Dim tree = document.GetVisualBasicSyntaxTreeAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None)
Dim token = tree.FindTokenOnLeftOfPosition(contextPoint, CancellationToken.None)
Dim containingNode = token.Parent.AncestorsAndSelf().Where(Function(s) TypeOf s Is ExpressionSyntax OrElse
TypeOf s Is MethodBaseSyntax OrElse
s.IsExecutableBlock()).FirstOrDefault()
If containingNode IsNot Nothing Then
If TypeOf containingNode Is ExpressionSyntax AndAlso Not IsRightSideOfLocalDeclaration(containingNode) Then
innerMostContainingNodeIsExpression = True
Return containingNode.Span.End
Else
Dim statement = containingNode.GetExecutableBlockStatements().FirstOrDefault()
If statement IsNot Nothing Then
Return statement.FullSpan.End
ElseIf TypeOf containingNode Is MethodBlockBaseSyntax
' Something like
' Sub Foo(o as integer)
' [| End Sub |]
Return DirectCast(containingNode, MethodBlockBaseSyntax).EndBlockStatement.SpanStart
Else
Return containingNode.Span.End
End If
End If
End If
Return token.FullSpan.End
End Function
Private Function IsRightSideOfLocalDeclaration(containingNode As SyntaxNode) As Boolean
' Right side of a variable declaration but not inside a lambda or query clause
Dim variableDeclarator = containingNode.GetAncestor(Of VariableDeclaratorSyntax)
If variableDeclarator IsNot Nothing Then
Dim methodBase = containingNode.GetAncestor(Of LambdaExpressionSyntax)()
Dim queryClause = containingNode.GetAncestor(Of QueryClauseSyntax)()
If (methodBase Is Nothing OrElse methodBase.DescendantNodes().Contains(variableDeclarator)) AndAlso
(queryClause Is Nothing OrElse queryClause.DescendantNodes().Contains(variableDeclarator)) Then
Dim equalsValueClause = containingNode.GetAncestor(Of EqualsValueSyntax)
Return equalsValueClause.IsChildNode(Of VariableDeclaratorSyntax)(Function(v) v.Initializer)
End If
End If
Return False
End Function
Protected Overrides Function GetPreviousStatementBufferAndSpan(contextPoint As Integer, document As Document) As ITrackingSpan
' This text can be validly inserted at the end of an expression context to allow
' intellisense to trigger a new expression context
Dim forceExpressionContext = ".__o("
If Not innerMostContainingNodeIsExpression Then
' We're after some statement, could be a for loop, using block, try block, etc, fake a
' local declaration on the following line
forceExpressionContext = vbCrLf + "Dim __o = "
End If
' Since VB is line-based, we're going to add
Dim previousTrackingSpan = ContextBuffer.CurrentSnapshot.CreateTrackingSpan(Span.FromBounds(0, contextPoint), SpanTrackingMode.EdgeNegative)
Dim buffer = ProjectionBufferFactoryService.CreateProjectionBuffer(
projectionEditResolver:=Nothing,
sourceSpans:={previousTrackingSpan, forceExpressionContext},
options:=ProjectionBufferOptions.None,
contentType:=Me.ContentType)
Return buffer.CurrentSnapshot.CreateTrackingSpan(0, buffer.CurrentSnapshot.Length, SpanTrackingMode.EdgeNegative)
End Function
Public Overrides ReadOnly Property CompletionStartsOnQuestionMark As Boolean
Get
Return True
End Get
End Property
Protected Overrides ReadOnly Property StatementTerminator As String
Get
Return vbCrLf
End Get
End Property
End Class
End Namespace
|
DavidKarlas/roslyn
|
src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicDebuggerIntelliSenseContext.vb
|
Visual Basic
|
apache-2.0
| 6,811
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Class BoundYieldStatement
''' <summary>
''' Suppresses RValue validation when constructing the node.
''' Must be used _only_ when performing lambda inference where RValue inconsistency on this node is intentinally allowed.
''' If such node makes into a regular bound tree it will be eventually rewritten (all Yields are rewritten at some point)
''' and that will trigger validation.
''' </summary>
Friend Sub New(syntax As VisualBasicSyntaxNode, expression As BoundExpression, hasErrors As Boolean, returnTypeIsBeingInferred As Boolean)
MyBase.New(BoundKind.YieldStatement, syntax, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
#If DEBUG Then
If Not returnTypeIsBeingInferred Then
Validate()
End If
#End If
End Sub
#If DEBUG Then
Private Sub Validate()
Expression.AssertRValue()
End Sub
#End If
End Class
End Namespace
|
DavidKarlas/roslyn
|
src/Compilers/VisualBasic/Portable/BoundTree/BoundYieldStatement.vb
|
Visual Basic
|
apache-2.0
| 1,528
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.GenerateOverrides
Imports Microsoft.CodeAnalysis.PickMembers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.GenerateOverrides
Public Class GenerateOverridesTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(Workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New GenerateOverridesCodeRefactoringProvider(DirectCast(parameters.fixProviderData, IPickMembersService))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)>
Public Async Function Test1() As Task
Await TestWithPickMembersDialogAsync(
"
class C
[||]
end class",
"
class C
Public Overrides Function Equals(obj As Object) As Boolean
Return MyBase.Equals(obj)
End Function
Public Overrides Function GetHashCode() As Integer
Return MyBase.GetHashCode()
End Function
Public Overrides Function ToString() As String
Return MyBase.ToString()
End Function
end class", {"Equals", "GetHashCode", "ToString"})
End Function
End Class
End Namespace
|
weltkante/roslyn
|
src/EditorFeatures/VisualBasicTest/GenerateOverrides/GenerateOverridesTests.vb
|
Visual Basic
|
apache-2.0
| 1,494
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryByVal
<ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicRemoveUnnecessaryByValCodeFixProvider
Inherits SyntaxEditorBasedCodeFixProvider
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) =
ImmutableArray.Create(IDEDiagnosticIds.RemoveUnnecessaryByValDiagnosticId)
Friend Overrides ReadOnly Property CodeFixCategory As CodeFixCategory = CodeFixCategory.CodeStyle
Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task
For Each diagnostic In context.Diagnostics
context.RegisterCodeFix(New MyCodeAction(
VisualBasicAnalyzersResources.Remove_ByVal,
Function(ct) FixAsync(context.Document, diagnostic, ct)),
diagnostic)
Next
Return Task.CompletedTask
End Function
Protected Overrides Async Function FixAllAsync(document As Document, diagnostics As ImmutableArray(Of Diagnostic), editor As SyntaxEditor, cancellationToken As CancellationToken) As Task
Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
For Each diagnostic In diagnostics
Dim node = DirectCast(root.FindNode(diagnostic.AdditionalLocations(0).SourceSpan), ParameterSyntax)
Dim tokenList = SyntaxFactory.TokenList(node.Modifiers.Where(Function(m) Not m.IsKind(SyntaxKind.ByValKeyword)))
editor.ReplaceNode(node, node.WithModifiers(tokenList))
Next
End Function
Private Class MyCodeAction
Inherits CustomCodeActions.DocumentChangeAction
Friend Sub New(title As String, createChangedDocument As Func(Of CancellationToken, Task(Of Document)))
MyBase.New(title, createChangedDocument)
End Sub
End Class
End Class
End Namespace
|
panopticoncentral/roslyn
|
src/Analyzers/VisualBasic/CodeFixes/RemoveUnnecessaryByVal/VisualBasicRemoveUnnecessaryByValCodeFixProvider.vb
|
Visual Basic
|
mit
| 2,844
|
#Region "Apache License"
'
' Licensed to the Apache Software Foundation (ASF) under one or more
' contributor license agreements. See the NOTICE file distributed with
' this work for additional information regarding copyright ownership.
' The ASF licenses this file to you under the Apache License, Version 2.0
' (the "License"); you may not use this file except in compliance with
' the License. You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
'
#End Region
Imports System
' Configure logging for this assembly using the 'SimpleApp.exe.log4net' file
<Assembly: log4net.Config.XmlConfigurator(ConfigFileExtension:="log4net", Watch:=True)>
' The following alias attribute can be used to capture the logging
' repository for the 'SimpleModule' assembly. Without specifying this
' attribute the logging configuration for the 'SimpleModule' assembly
' will be read from the 'SimpleModule.dll.log4net' file. When this
' attribute is specified the configuration will be shared with this
' assemby's configuration.
'<Assembly:log4net.Config.AliasRepository("SimpleModule")>
Namespace SimpleApp
Public Class EntryPoint
' Create a logger for use in this class
Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
' The main entry point for the application.
<STAThread()> Public Shared Sub Main(Byval args() As String)
If log.IsInfoEnabled Then log.Info(args)
If args.Length <> 2 Then
log.Error("Must supply 2 command line arguments")
Else
Dim left As Integer = Integer.Parse(args(0))
Dim right As Integer = Integer.Parse(args(1))
Dim result As Integer = 0
If log.IsDebugEnabled Then log.Debug("Adding [" & left & "] to [" & right & "]")
result = (new SimpleModule.Math()).Add(left, right)
If log.IsDebugEnabled Then log.Debug("Result [" & result & "]")
Console.Out.WriteLine(result)
If log.IsDebugEnabled Then log.Debug("Subtracting [" & right & "] from [" & left & "]")
result = (new SharedModule.Math()).Subtract(left, right)
If log.IsDebugEnabled Then log.Debug("Result [" & result & "]")
Console.Out.WriteLine(result)
End If
End Sub
End Class
End Namespace
|
Dagwaging/log4net
|
src/examples/vb/Repository/SimpleApp/EntryPoint.vb
|
Visual Basic
|
apache-2.0
| 2,591
|
Namespace ApplicationInformation
Public Class WoWFeesh
Inherits ApplicationInformationBase
Public Sub New()
_ApplicationName = "WoWFeesh"
_Name = "WoW Feesh"
_ServiceURL = nubServerServiceURL
_SourceDirectory = "C:\Projects\GitHub\WoWFeesh\bin\"
CreateControls()
End Sub
End Class
End Namespace
|
nublet/AutoUpdates
|
Updater/ApplicationInformation/WoWFeesh.vb
|
Visual Basic
|
mit
| 394
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class ReportSection
Inherits System.Windows.Forms.ScrollableControl
'Control overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Control Designer
Private components As System.ComponentModel.IContainer
' NOTE: The following procedure is required by the Component Designer
' It can be modified using the Component Designer. Do not modify it
' using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
components = New System.ComponentModel.Container()
End Sub
End Class
|
pagotti/vrx
|
Windows.Forms/Control/ReportSection.Designer.vb
|
Visual Basic
|
mit
| 989
|
Option Strict Off
Option Explicit On
Friend Class frmPriceSetList
Inherits System.Windows.Forms.Form
Dim gFilter As String
Dim gRS As ADODB.Recordset
Dim gFilterSQL As String
Dim gID As Integer
Private Sub loadLanguage()
rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1120 'Select a Stock Pricing Set|Checked
If rsLang.RecordCount Then Me.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : Me.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value
rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1080 'Search|Checked
If rsLang.RecordCount Then lbl.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : lbl.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value
rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1065 'New|Checked
If rsLang.RecordCount Then cmdNew.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : cmdNew.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value
rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1004 'Exit|Checked
If rsLang.RecordCount Then cmdExit.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : cmdExit.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value
rsHelp.filter = "Help_Section=0 AND Help_Form='" & Me.Name & "'"
'UPGRADE_ISSUE: Form property frmPriceSetList.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
If rsHelp.RecordCount Then Me.ToolTip1 = rsHelp.Fields("Help_ContextID").Value
End Sub
Public Function getItem() As Integer
cmdNew.Visible = False
loadLanguage()
Me.ShowDialog()
getItem = gID
End Function
Private Sub getNamespace()
End Sub
Private Sub cmdExit_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdExit.Click
Me.Close()
'* Check if pricesetlist was opened from stockitem
If Hold_text <> "" Then
frmStockItem.ShowDialog()
Else
End If
'*
End Sub
Private Sub cmdNamespace_Click()
frmFilter.loadFilter(gFilter)
getNamespace()
End Sub
Private Sub cmdNew_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdNew.Click
frmPriceSet.loadItem(0)
doSearch()
End Sub
Private Sub DataList1_DblClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles DataList1.DoubleClick
If cmdNew.Visible Then
If DataList1.BoundText <> "" Then
holdid = CInt(DataList1.BoundText)
frmPriceSet.loadItem(CInt(DataList1.BoundText))
End If
doSearch()
Else
If DataList1.BoundText = "" Then
gID = 0
Else
gID = CInt(DataList1.BoundText)
End If
Me.Close()
End If
End Sub
Private Sub DataList1_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As KeyPressEventArgs) Handles DataList1.KeyPress
Select Case eventArgs.KeyChar
Case ChrW(13)
DataList1_DblClick(DataList1, New System.EventArgs())
eventArgs.KeyChar = ChrW(0)
Case ChrW(27)
Me.Close()
eventArgs.KeyChar = ChrW(0)
End Select
End Sub
Private Sub frmPriceSetList_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
Select Case KeyAscii
Case System.Windows.Forms.Keys.Escape
KeyAscii = 0
cmdExit_Click(cmdExit, New System.EventArgs())
End Select
eventArgs.KeyChar = Chr(KeyAscii)
If KeyAscii = 0 Then
eventArgs.Handled = True
End If
End Sub
Private Sub frmPriceSetList_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
doSearch()
txthold.Text = frmStockItem._txtFields_7.Text
Hold_text = txthold.Text
End Sub
Private Sub frmPriceSetList_FormClosed(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
gRS.Close()
End Sub
Private Sub txtSearch_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtSearch.Enter
txtSearch.SelectionStart = 0
txtSearch.SelectionLength = 999
End Sub
Private Sub txtSearch_KeyDown(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyEventArgs) Handles txtSearch.KeyDown
Dim KeyCode As Short = eventArgs.KeyCode
Dim Shift As Short = eventArgs.KeyData \ &H10000
Select Case KeyCode
Case 40
Me.DataList1.Focus()
End Select
End Sub
Private Sub txtSearch_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtSearch.KeyPress
Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
Select Case KeyAscii
Case 13
doSearch()
KeyAscii = 0
End Select
eventArgs.KeyChar = Chr(KeyAscii)
If KeyAscii = 0 Then
eventArgs.Handled = True
End If
End Sub
Private Sub doSearch()
Dim sql As String
Dim lString As String
lString = Trim(txtSearch.Text)
lString = Replace(lString, " ", " ")
lString = Replace(lString, " ", " ")
lString = Replace(lString, " ", " ")
lString = Replace(lString, " ", " ")
lString = Replace(lString, " ", " ")
lString = Replace(lString, " ", " ")
If lString = "" Then
Else
lString = "WHERE (PriceSet_Name LIKE '%" & Replace(lString, " ", "%' AND PriceSet_Name LIKE '%") & "%')"
End If
gRS = getRS("SELECT DISTINCT PriceSetID, PriceSet_Name FROM [PriceSet] " & lString & " ORDER BY PriceSet_Name")
'Display the list of Titles in the DataCombo
DataList1.DataSource = gRS
DataList1.listField = "PriceSet_Name"
'Bind the DataCombo to the ADO Recordset
'UPGRADE_ISSUE: VBControlExtender property DataList1.DataSource is not supported at runtime. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="74E732F3-CAD8-417B-8BC9-C205714BB4A7"'
DataList1.DataSource = gRS
DataList1.boundColumn = "PriceSetID"
End Sub
End Class
|
nodoid/PointOfSale
|
VB/4PosBackOffice.NET/frmPriceSetList.vb
|
Visual Basic
|
mit
| 6,218
|
Imports Aspose.Cells.GridWeb.Data
Namespace Cells
Public Class ModifyCells
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
' If first visit, load GridWeb data
If Not Page.IsPostBack AndAlso Not GridWeb1.IsPostBack Then
LoadData()
Else
Label1.Text = ""
End If
End Sub
Private Sub LoadData()
' Clear GridWeb
GridWeb1.WorkSheets.Clear()
' Add a new sheet by name and put some info text in cells
Dim sheet As GridWorksheet = GridWeb1.WorkSheets.Add("Modify-Cells")
Dim cells As GridCells = sheet.Cells
cells("A1").PutValue("String Value:")
cells("A3").PutValue("Int Value:")
cells("A5").PutValue("Double Value:")
cells.SetColumnWidth(0, 30)
cells.SetColumnWidth(1, 20)
End Sub
Protected Sub btnModifyCellValue_Click(sender As Object, e As EventArgs)
AddStringValue()
AddIntValue()
AddDoubleValue()
End Sub
Private Sub AddStringValue()
' ExStart:AddCellStringValue
' Accessing the worksheet of the Grid that is currently active
Dim sheet As GridWorksheet = GridWeb1.WorkSheets(GridWeb1.ActiveSheetIndex)
' Accessing "B1" cell of the worksheet
Dim cell As GridCell = sheet.Cells("B1")
' Accessing the string value of "B1" cell
Label1.Text = cell.StringValue
' Modifying the string value of "B1" cell
cell.PutValue("Hello Aspose.Grid")
' ExEnd:AddCellStringValue
End Sub
Private Sub AddIntValue()
' ExStart:AddCellIntValue
' Accessing the worksheet of the Grid that is currently active
Dim sheet As GridWorksheet = GridWeb1.WorkSheets(GridWeb1.ActiveSheetIndex)
' Accessing "B3" cell of the worksheet
Dim cell As GridCell = sheet.Cells("B3")
' Putting a value in "B3" cell
cell.PutValue(30)
' ExEnd:AddCellIntValue
End Sub
Private Sub AddDoubleValue()
' ExStart:AddCellDoubleValue
' Accessing the worksheet of the Grid that is currently active
Dim sheet As GridWorksheet = GridWeb1.WorkSheets(GridWeb1.ActiveSheetIndex)
' Accessing "B5" cell of the worksheet
Dim cell As GridCell = sheet.Cells("B5")
' Putting a numeric value as string in "B5" cell that will be converted to a suitable data type automatically
cell.PutValue("19.4", True)
' ExEnd:AddCellDoubleValue
End Sub
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples.GridWeb/VisualBasic/Cells/ModifyCells.aspx.vb
|
Visual Basic
|
mit
| 2,825
|
'Программа демонстрирует принцип обучения коры возможности распространять идентификационные волны от паттернов вызванной активности
'
'Авторы:
' Алексей Редозубов aldrd@yahoo.com
' Дмитрий Шабанов shabanovd@gmail.com
'The MIT License (MIT)
'Copyright (c) 2014 Alexey Redozubov, Dmitriy Shabanov
'Permission is hereby granted, free of charge, to any person obtaining a copy
'of this software and associated documentation files (the "Software"), to deal
'in the Software without restriction, including without limitation the rights
'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
'copies of the Software, and to permit persons to whom the Software is
'furnished to do so, subject to the following conditions:
'The above copyright notice and this permission notice shall be included in
'all copies or substantial portions of the Software.
'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
'THE SOFTWARE.
Public Class Form1
' Dim TimeCheck(9) As double
' Размеры коры
Dim X_C As Integer = 150
Dim Y_C As Integer = 150
' Суммарная ритмическая активность
Dim NSer As Integer = 300
Dim CurPosA As Integer = 0
Dim AWave(NSer - 1) As Double
' Параметры для формирования картины серии состояний
Dim FPic As Boolean = False
Dim PicStart As Integer
Dim NPic As Integer = 16
Dim WPic As Integer = 4
Dim Bigpic As New Bitmap(X_C * WPic, Y_C * CInt(Math.Round(NPic / WPic) + 0.5))
' Текущий такт
Dim CT As Integer = 0
' Вероятность истинно спонтанного спайка
Dim Psp As Double = 0.02
' Кол-во типов нейронов
Dim N_Types As Integer = 2
' Расстояние слежения за активностью для ID (влево и вправо по горизонтали и вертикали)
Dim R_ID As Integer = 15
' Расстояние слежения за активностью для весов W (влево и вправо по горизонтали и вертикали)
Dim R_W As Integer = R_ID
' Радиус распространения активности. Связан с расчетом активности на синапсах (трогать аккуратно)
Dim RLAM As Integer = R_W
' шаблон распределения активности
Dim NLocalAM = 2 * RLAM + 1
Dim LocalAM(NLocalAM - 1, NLocalAM - 1)
' Параметр распространения активности. Дисперсия
Dim Sigma2LAM As Single = 5 ^ 2
' Период полураспада распределенной активности (тактов)
Dim TAhalf As Integer = 4
'Падение активности за один такт
Dim KA As Single = 1 / (2.0 ^ (1.0 / TAhalf))
' Площадь поля усреднения активности
Dim SReceptF As Integer = (RLAM * 2 + 1) ^ 2
' Минимальная активность для начала обсчета
Dim LAmin As Double = 0.008
' Предел активности для генерации спонтанных спайков
Dim LAmax As Double = 0.025
' Предел количества нейронов в релаксирующем состоянии для каждого из типов. Выше этого предела подавляется спонтанная активность.
Dim LImin(N_Types - 1) As Double
' Порог активации по идентификатору
Dim L_act As Double = 0.7
' количество волн, необходимых для консолидации
Dim NCons As Integer = 5
' Продолжительность пакета идентификационной активности
Dim T_ID As Integer = 10
' Продолжительность тишины
Dim T_Passive As Integer = T_ID * 4
Dim pic As New Bitmap(X_C, Y_C)
Dim Gpic As Graphics
' Кол-во нейронов в патерне вызванной активности
Dim NNPat As Integer = 15
' Радиус паттерна вызванной активности
Dim R_Pat As Integer = 6
' Общее количество паттернов
Dim NP As Integer = 5
' Количество активных паттернов в режиме волны
Dim NPC As Integer = 1
Structure Pattern
' Центры паттернов
Dim ix As Integer
Dim iy As Integer
Dim P(,) As Byte
End Structure
' Набор паттернов вызванной активности
Dim PatSet(NP - 1) As Pattern
Structure ID
' 0 - не консолидирован
' 1 - консолидирован
Dim ConsStatus As Integer
Dim NAct As Integer
Dim TCreat As Integer
Dim NP As Integer ' Номер паттерна для проверки во время отладки
Dim P(,) As Byte
End Structure
Structure Neuron
' Тип нейрона
Dim Type As Byte
' 0 - входной аксон
' 1 - нейрон первого уровня (волновой)
' 2 - нейрон второго уровня
' Текущий статус нейрона
Dim Status As Byte
' 0 - спокоен
' 1 - вызванная активность
' 2 - волновая активность
' 3 - первый такт волновой активности
' 4 - релаксация после волнового спайка
' 5 - спонтанная активность
' 6 - входной аксон
' 7 - состояние проверки на возможное участие в волновом идентификаторе
' Накопленная за время обучения синапсов активность
Dim AAccumSinapse As Single
' Накопленная за время обучения внесинаптических рецепторов активность
Dim AAccumExtraSinapse As Single
' Временное событие
Dim T As Integer
' Вызванный потенциал активности нерона в мощностном измерении
Dim EvokedA As Single
' Текущий статус обучения нейрона
Dim StatusL As Byte
' 0 - свободен
' 1 - фасилитация
' 2 - обучен
' 5 - не подлежит обучению (входной аксон)
' Временное событие обучения
Dim TL As Integer
' Набор картин идентификаторв индивидуальных для каждого нейрона
Dim ID As Collection
Dim ERR As Boolean
End Structure
' Кора
Dim Cortex(X_C - 1, Y_C - 1) As Neuron
' Число тактов накопления активности при синаптическом обучении
Dim T_SinapseLearn As Integer = T_Passive
' Число тактов накопления активности при внесинаптическом обучении
Dim T_ExtraSinapseLearn As Integer = 4 ' T_ID
' Набор полей последних состояний нейронов.
Dim CortexA(X_C - 1, Y_C - 1, T_SinapseLearn - 1) As Byte
' Текущая последовательность слоев
Dim LayersSequence(T_SinapseLearn - 1) As Integer
' Текущий слой
Dim CurLayer As Integer = 0
' Порог активации нейрона
Dim L_Spike As Single = 0.6
' Продолжительность вызванной активности
Dim T_EnvokedA As Integer = T_Passive * 1.5
' Синапсы
Dim N_Neurotransmitters As Integer = 2
' Таблица чувствительности синаптических и внесинаптических рецепторов к медиаторам, генерируемым аксонами нейронов разного типа
Dim SensTable(N_Types - 1, N_Types - 1, 0 To 1) As Byte
' Веса синапсов нейронов
Dim CortexW(X_C - 1, Y_C - 1, R_W * 2, R_W * 2) As Single
' Вторичная зона коры
Dim cortex2 As Form1 = Nothing
' Размеры туннеля
Dim TD As Integer = 30
' Координаты угла исходящего туннеля
Dim TX1 As Integer = X_C / 4
Dim TY1 As Integer = Y_C / 4
' Координаты угла входящего туннеля
Dim TX2 As Integer = X_C / 2
Dim TY2 As Integer = Y_C / 2
' Флаг включения обучения нейронов-детекторов
Dim FLearn As Boolean = False
' Время, отведенное на консолидацию
Dim T_L1 As Integer = 50
' Поле накопленной вызванной активности коры
Dim Field_A_Accum(X_C - 1, Y_C - 1) As Single
' Поле мгновенной активности коры
Dim Field_A(X_C - 1, Y_C - 1) As Single
' Поле вызванной активности коры
Dim Field_A_Evoced(X_C - 1, Y_C - 1) As Single
' Поле волновой активности коры
Dim Field_A_Wave(X_C - 1, Y_C - 1) As Single
' Поле плотности релаксирующих нейронов каждого из типов
Dim Field_A_Relax(X_C - 1, Y_C - 1, N_Types - 1) As Single
' Порог окружающей вызванной активности для возможности обучения
Dim L_ActL1 As Single = 0.15
' Порог активности на синапсах для возможности обучения
Dim L_ActLS As Single = (2 * R_W + 1) ^ 2 * 0.02
' Коэффициенты пространственной самоорганизации
' Порог умирания от одиночества
Dim L_GameLive_Low = 0.15
' Порог умирания от перенасыщения
Dim L_GameLive_high = 0.25
' Инициализация
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SetSens()
PatCreate()
CheckedListBox1.CheckOnClick = True
' Задание пороговых уровней плотности релаксирующих нейронов для подавления спонтанной активности
LImin(0) = 0.01
LImin(1) = 0.01
ComboBox1.SelectedIndex = 0
ComboBox2.SelectedIndex = 0
' Инициация нейронов коры
For ix = 0 To X_C - 1
For iy = 0 To Y_C - 1
With Cortex(ix, iy)
.Type = 0
.ID = New Collection
End With
Next
Next
Gpic = Graphics.FromImage(pic)
' Создание шаблона распространения активности
' Сумма всех точек дает единицу. Это позволяет устанавливать пороги для полей в процентах задействованных нейронов
Dim dx, dy As Single
For ix = 0 To NLocalAM - 1
For iy = 0 To NLocalAM - 1
dx = ix - RLAM
dy = iy - RLAM
LocalAM(ix, iy) = (1 / (2 * Math.PI * Sigma2LAM)) * Math.Exp(-1 / (2 * Sigma2LAM) * (dx ^ 2 + dy ^ 2))
Next
Next
End Sub
' Задание таблицы чувтвительности рецепторов
Private Sub SetSens()
' Волновые нейроны (тип 0):
' Медиатор аксона - A
' внесинаптические рецепторы - A
' синаптические рецепторы - B
' Нейроны детекторы (тип 1):
' Медиатор аксона - A, B
' внесинаптические рецепторы - ---
' синаптические рецепторы - A
' Формат таблицы
' тип передающего нейрона, тип принимающего, чувствительность внесинаптическая (0) - синаптическая (1)
SensTable(0, 0, 0) = 1
SensTable(0, 0, 1) = 0
SensTable(0, 1, 0) = 0
SensTable(0, 1, 1) = 1
SensTable(1, 0, 0) = 1
SensTable(1, 0, 1) = 1
SensTable(1, 1, 0) = 0
SensTable(1, 1, 1) = 0
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PatCreate()
End Sub
' Создание случайных паттернов вызванной активности
Private Sub PatCreate()
Dim dx, dy As Integer
CheckedListBox1.Items.Clear()
For i = 0 To X_C - 1
For j = 0 To Y_C - 1
pic.SetPixel(i, j, Color.Black)
Next
Next
For i = 0 To NP - 1
With PatSet(i)
.ix = (X_C - 3 * R_Pat) * Rnd() + R_Pat
.iy = (Y_C - 3 * R_Pat) * Rnd() + R_Pat
Dim Ang As Double
Dim R As Double
ReDim .P(R_Pat * 2, R_Pat * 2)
For j = 0 To NNPat - 1
Ang = 2 * Math.PI * Rnd()
R = R_Pat * Rnd()
dx = R * Math.Sin(Ang)
dy = R * Math.Cos(Ang)
.P(R_Pat + dx, R_Pat + dy) = 1
' Присвоение статуса входных волокон
Cortex(.ix + dx, .iy + dy).StatusL = 5
Next
For ix = 0 To 2 * R_Pat
For iy = 0 To 2 * R_Pat
If .P(ix, iy) = 1 Then
pic.SetPixel(.ix - R_Pat + ix, .iy - R_Pat + iy, Color.White)
End If
Next
Next
End With
CheckedListBox1.Items.Add(i)
Next
PictureBox1.Image = pic
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Wave()
End Sub
' 50 тактов волны
Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click
Dim NT As Integer = 50
For n = 0 To NT - 1
Wave()
Next
End Sub
' 200 тактов волны
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim NT As Integer = 200
For n = 0 To NT - 1
Wave()
Next
End Sub
' Такт волны
Public Sub Wave()
Dim AW As Double
Label1.Text = CT.ToString
Label1.Update()
' Расчет полей состояния коры
CalcFields()
' Отображение выбранного поля
Select Case ComboBox1.SelectedIndex
Case 0
Draw_ActAccum()
Case 1
Draw_FieldA()
Case 2
Draw_EvokedA()
Case 3
Draw_WaveA()
Case 4
Draw_RelaxA()
End Select
' Определяем переходы состояний нейронов
For ix = R_ID To X_C - R_ID - 1
For iy = R_ID To Y_C - R_ID - 1
With Cortex(ix, iy)
Select Case .Status
Case 0 ' покой
' определяем узнавание идентификатора, но не корректируем CortexA, а только меняем статус
S0(ix, iy)
If .Status = 0 Then
' Если возбуждения нет, уровень окружающей активности высок, но еще не достиг верхнего порога,
' а блокированных нейронов вокруг мало, то
' создаем кандидата на добавление в идентификатор
If Field_A(ix, iy) > LAmin And Field_A_Wave(ix, iy) < LAmax And Field_A_Relax(ix, iy, Cortex(ix, iy).Type) < LImin(Cortex(ix, iy).Type) Then
If Rnd() < Psp Then
.Status = 7
.T = CT + T_ExtraSinapseLearn
End If
End If
End If
Case 7
S0(ix, iy)
If .Status = 7 Then
If Field_A_Wave(ix, iy) > LAmax Then
' Сбрасываем состояние кандидата, если активность превышает порог
.Status = 0
Else
If CT > .T Then
' вызываем спонтанную активность и проводим ID обучение
Cortex(ix, iy).Status = 5
Cortex(ix, iy).T = CT
S1(ix, iy)
End If
End If
End If
Case 1 ' вызванная активность
' Сбрасываем вызванную активность по окончании пакета
If CT > .T Then
.Status = 0
End If
Case 2 ' пачка волновой активности
' если пачка закончилась, то переводим в состояние нечувствительности
If CT > .T Then
' задаем время релаксации тем больше, чем сильнее рядом вызванная активность
.T = CT + T_Passive ' * (1 + Field_A_Accum(ix, iy) / 0.02)
.Status = 4
.ERR = False
End If
Case 3 ' первый такт волновой активности
.Status = 2
Case 4 ' состояние нечувствительности
'
If CT > .T Then
.Status = 0
End If
Case 5 ' спонтанный спайк
.Status = 2
Case 6 ' Проекционная (входная) активность
End Select
End With
Next
Next
' Создаем картину активности нового временного слоя, соответсвующую статусам
AW = 0
' Сдвигаем текщий временной слой
CurLayer += 1
If CurLayer = T_SinapseLearn Then CurLayer = 0
For ix = R_ID To X_C - R_ID - 1
For iy = R_ID To Y_C - R_ID - 1
Select Case Cortex(ix, iy).Status
Case 1, 2, 3, 5, 6
CortexA(ix, iy, CurLayer) = 1
AW += 1
Case Else
CortexA(ix, iy, CurLayer) = 0
End Select
Next
Next
' График ритма
CurPosA += 1
If CurPosA = NSer Then CurPosA = 0
AWave(CurPosA) = AW / ((X_C - 2 * R_ID) * (Y_C - 2 * R_ID))
DrawChart()
' Проверяем на консолидацию или удаление идентификационных следов
' ----------------------------
Draw_Status()
CT += 1
If FPic Then
addpic()
End If
' Установка последовательности слоев (0 - текущий, 1 - предыдущий и т.д.)
Dim k As Integer = CurLayer
For i = 0 To T_SinapseLearn - 1
LayersSequence(i) = k
k -= 1
If k < 0 Then k = T_SinapseLearn - 1
Next
' Расчет накопленной по времени активности
Dim sum As Integer
For ix = R_ID To X_C - R_ID - 1
For iy = R_ID To Y_C - R_ID - 1
sum = 0
For i = 0 To T_ExtraSinapseLearn - 1
sum += CortexA(ix, iy, LayersSequence(i))
Next
If sum > 0 Then
Cortex(ix, iy).AAccumExtraSinapse = 1
Else
Cortex(ix, iy).AAccumExtraSinapse = 0
End If
For i = T_ExtraSinapseLearn To T_SinapseLearn - 1
sum += CortexA(ix, iy, LayersSequence(i))
Next
If sum > 0 Then
Cortex(ix, iy).AAccumSinapse = 1
Else
Cortex(ix, iy).AAccumSinapse = 0
End If
Next
Next
' Обучение
If FLearn Then
' Расчет вызванной активности
Calc_Evoked_Activity()
'MakePicFieldA()
' Обучение синаптических весов
' Задание фасилитации
LearnW1()
' Отмена фасилитации, исходя из условий выживания
'LearnW2()
Select Case ComboBox2.SelectedIndex
Case 0
Draw_Learn()
Case 1
Case 2
Case 3
Case 4
End Select
End If
' Проекция по волновому туннелю
TMove()
End Sub
' Расчет вызванной активности
Private Sub Calc_Evoked_Activity()
Dim x1, x2, sum, n1, n2 As Single
For ix = R_W To X_C - R_W - 1
For iy = R_W To Y_C - R_W - 1
With Cortex(ix, iy)
.EvokedA = 0
If .StatusL > 0 Then
sum = 0
n1 = 0
n2 = 0
For ix1 = 0 To 2 * R_W
For iy1 = 0 To 2 * R_W
x1 = Cortex(ix + ix1 - R_W, iy + iy1 - R_W).AAccumSinapse
x2 = CortexW(ix, iy, ix1, iy1)
sum += x1 * x2
n1 += x1
n2 += x2
Next
Next
If sum > 0 Then
.EvokedA = sum / Math.Sqrt(n1 * n2)
End If
If .EvokedA > L_Spike Then
If .Status <> 1 Then
.T = CT + T_EnvokedA
End If
.Status = 1
End If
End If
End With
Next
Next
End Sub
' Рассчет полей состояния коры
Private Sub CalcFields()
Dim x, y, T As Integer
Dim s As Single
For ix = 0 To X_C - 1
For iy = 0 To Y_C - 1
Field_A_Accum(ix, iy) = Field_A_Accum(ix, iy) * KA
Field_A(ix, iy) = 0
Field_A_Wave(ix, iy) = 0
Field_A_Evoced(ix, iy) = 0
For i = 0 To N_Types - 1
Field_A_Relax(ix, iy, i) = 0
Next
Next
Next
For ix = RLAM To X_C - RLAM - 1
For iy = RLAM To Y_C - RLAM - 1
Select Case Cortex(ix, iy).Status
Case 1, 6
For ix1 = 0 To NLocalAM - 1
For iy1 = 0 To NLocalAM - 1
x = ix + ix1 - RLAM
y = iy + iy1 - RLAM
s = LocalAM(ix1, iy1)
Field_A_Accum(x, y) += s
Field_A(x, y) += s
Field_A_Evoced(x, y) += s
Next
Next
Case 2, 3, 5
For ix1 = 0 To NLocalAM - 1
For iy1 = 0 To NLocalAM - 1
x = ix + ix1 - RLAM
y = iy + iy1 - RLAM
s = LocalAM(ix1, iy1)
Field_A(x, y) += s
Field_A_Wave(x, y) += s
Next
Next
Case 4
T = Cortex(ix, iy).Type
For ix1 = 0 To NLocalAM - 1
For iy1 = 0 To NLocalAM - 1
x = ix + ix1 - RLAM
y = iy + iy1 - RLAM
s = LocalAM(ix1, iy1)
Field_A_Relax(x, y, T) += s
Next
Next
End Select
Next
Next
End Sub
' Обучение синаптических весов
' Задание фасилитации
Private Sub LearnW1()
For ix = R_W To X_C - R_W - 1
For iy = R_W To Y_C - R_W - 1
If Cortex(ix, iy).Status = 2 And Field_A_Accum(ix, iy) > L_ActL1 And Field_A(ix, iy) > L_ActLS And Cortex(ix, iy).StatusL = 0 Then
Cortex(ix, iy).StatusL = 1
Cortex(ix, iy).TL = CT
' Фиксация кандидата в прототип
For ix1 = 0 To 2 * R_W
For iy1 = 0 To 2 * R_W
CortexW(ix, iy, ix1, iy1) = Cortex(ix + ix1 - R_W, iy + iy1 - R_W).AAccumSinapse '* SensTable(Cortex(ix + ix1 - R_W, iy + iy1 - R_W).Type, Cortex(ix, iy).Type, 1)
Next
Next
End If
Next
Next
End Sub
' S0
' Обработка нейрона в состоянии покоя
Private Sub S0(ByRef ix As Integer, ByRef iy As Integer)
' Выходим если уровень активности вокруг нейрона мал и не считаем все возможные слои
If Field_A(ix, iy) < LAmin Then Exit Sub
' Если уровень окружающей активности высок, то проверяем на необходимость волнового возбуждения
If Cortex(ix, iy).ID.Count > 0 Then
Dim sum, NN, NP, P As Integer
For Each S As ID In Cortex(ix, iy).ID
With S
sum = 0
NN = 0
NP = 0
For ix1 = ix - R_ID To ix + R_ID
For iy1 = iy - R_ID To iy + R_ID
P = .P(ix1 - ix + R_ID, iy1 - iy + R_ID)
' Учитывается соответсвие типов медиаторов и рецепторов
sum += Cortex(ix1, iy1).AAccumExtraSinapse * P * SensTable(Cortex(ix1 - ix + R_ID, iy1 - iy + R_ID).Type, Cortex(ix, iy).Type, 0)
NN += P
Next
Next
If sum / CDbl(NN) > L_act Then
' Если наступает волновое возбуждение разбираемся с консолидацией МРК
If .ConsStatus = 0 Then
.NAct += 1
If .NAct > NCons Then .ConsStatus = 1
End If
Cortex(ix, iy).Status = 3
Cortex(ix, iy).T = CT + T_ID
' для ускорения можно выйти из цикла, но это может нарушить консолидацию остальных слоев
If CheckedListBox1.CheckedItems.Count = 1 And CheckedListBox1.CheckedItems.Item(0) <> .NP Then Cortex(ix, iy).ERR = True
End If
End With
Next
End If
End Sub
' S1
' Создание метаботропного рецептивного кластера
Private Sub S1(ByRef ix As Integer, ByRef iy As Integer)
' Создаем образ окружающего паттерна (метаботропный рецептивный кластер)
Dim S As New ID
With S
.ConsStatus = 0
.NAct = 1
.TCreat = CT
ReDim .P(R_ID * 2, R_ID * 2)
For ix1 = ix - R_ID To ix + R_ID
For iy1 = iy - R_ID To iy + R_ID
' учитывем чувствительность к медиатору
.P(ix1 - ix + R_ID, iy1 - iy + R_ID) = Cortex(ix1, iy1).AAccumExtraSinapse * SensTable(Cortex(ix1 - ix + R_ID, iy1 - iy + R_ID).Type, Cortex(ix, iy).Type, 0)
Next
Next
' Заполняем к какому паттерну относится этот МК (для контроля)
If CheckedListBox1.CheckedItems.Count = 1 Then
.NP = CheckedListBox1.CheckedItems.Item(0)
Else
.NP = 0
End If
End With
Cortex(ix, iy).ID.Add(S)
End Sub
' Картина общего состояния коры (статус нейронов)
Private Sub Draw_Status()
For i = 0 To X_C - 1
For j = 0 To Y_C - 1
Select Case Cortex(i, j).Status
Case 0
pic.SetPixel(i, j, Color.Black)
Case 1 ' Вызванная активность
pic.SetPixel(i, j, Color.Orange)
Case 2 ' Спайки волны идентификатора
pic.SetPixel(i, j, Color.Gray)
If Cortex(i, j).ERR Then pic.SetPixel(i, j, Color.Red)
Case 3 ' Фронт волны идентификатора
pic.SetPixel(i, j, Color.White)
If Cortex(i, j).ERR Then pic.SetPixel(i, j, Color.Red)
Case 4 ' Нейроны в заторможенном состоянии
pic.SetPixel(i, j, Color.DarkBlue)
Case 5 ' Истинно спонтанный спайк
pic.SetPixel(i, j, Color.Green)
Case 6 ' Проекционная активность
pic.SetPixel(i, j, Color.Red)
End Select
Next
Next
' Если есть волновой туннель, то рисование его границ
If (Me.Text = "Form1" And Not (cortex2 Is Nothing)) Or Me.Text = "2" Then
Dim Pen As New Pen(Color.White, 1)
Dim i1, i2 As Integer
If Not (cortex2 Is Nothing) Then
i1 = TX1
i2 = TY1
Else
i1 = TX2
i2 = TY2
End If
Gpic.DrawLine(Pen, i1, i2, i1 + TD, i2)
Gpic.DrawLine(Pen, i1, i2 + TD, i1 + TD, i2 + TD)
Gpic.DrawLine(Pen, i1, i2, i1, i2 + TD)
Gpic.DrawLine(Pen, i1 + TD, i2, i1 + TD, i2 + TD)
End If
PictureBox1.Image = pic
PictureBox1.Update()
End Sub
' Картина вызванной активности
Private Sub Draw_EvokedA()
Dim pic1 As New Bitmap(X_C, Y_C)
Dim Y As Integer
For ix = 0 To X_C - 1
For iy = 0 To Y_C - 1
Y = Field_A_Evoced(ix, iy) / 0.08 * 255
If Y > 255 Then Y = 255
pic1.SetPixel(ix, iy, Color.FromArgb(Y, Y, Y))
Next
Next
PictureBox2.Image = pic1
PictureBox2.Update()
End Sub
' Картина накопленной активности
Private Sub Draw_ActAccum()
Dim pic1 As New Bitmap(X_C, Y_C)
Dim Y As Integer
For ix = 0 To X_C - 1
For iy = 0 To Y_C - 1
Y = Field_A_Accum(ix, iy) * 500
If Y > 255 Then Y = 255
pic1.SetPixel(ix, iy, Color.FromArgb(Y, Y, Y))
Next
Next
PictureBox2.Image = pic1
PictureBox2.Update()
End Sub
' Картина поля активности (размытая)
Private Sub Draw_FieldA()
Dim pic1 As New Bitmap(X_C, Y_C)
Dim Y As Integer
For ix = 0 To X_C - 1
For iy = 0 To Y_C - 1
Y = Field_A(ix, iy) / 0.08 * 255
If Y > 255 Then Y = 255
pic1.SetPixel(ix, iy, Color.FromArgb(Y, Y, Y))
Next
Next
PictureBox2.Image = pic1
PictureBox2.Update()
End Sub
' Картина релаксации
Private Sub Draw_RelaxA()
Dim pic1 As New Bitmap(X_C, Y_C)
Dim Y As Integer
For ix = 0 To X_C - 1
For iy = 0 To Y_C - 1
Y = Field_A_Relax(ix, iy, 0) / 0.04 * 255
If Y > 255 Then Y = 255
pic1.SetPixel(ix, iy, Color.FromArgb(Y, Y, Y))
Next
Next
PictureBox2.Image = pic1
PictureBox2.Update()
End Sub
' Картина поля волны (размытая)
Private Sub Draw_WaveA()
Dim pic1 As New Bitmap(X_C, Y_C)
Dim Y As Integer
For ix = 0 To X_C - 1
For iy = 0 To Y_C - 1
Y = Field_A_Wave(ix, iy) / 0.04 * 255
If Y > 255 Then Y = 255
pic1.SetPixel(ix, iy, Color.FromArgb(Y, Y, Y))
Next
Next
PictureBox2.Image = pic1
PictureBox2.Update()
End Sub
' Картина поля активности, усредненного по времении
Private Sub MakePicAAvg()
Dim pic1 As New Bitmap(X_C, Y_C)
Dim Y As Integer
For ix = 0 To X_C - 1
For iy = 0 To Y_C - 1
Y = Cortex(ix, iy).AAccumSinapse * 255
pic1.SetPixel(ix, iy, Color.FromArgb(Y, Y, Y))
Next
Next
PictureBox2.Image = pic1
PictureBox2.Update()
End Sub
' Картина состояния обучения
Private Sub Draw_Learn()
Dim pic1 As New Bitmap(X_C, Y_C)
For ix = 0 To X_C - 1
For iy = 0 To Y_C - 1
Select Case Cortex(ix, iy).StatusL
Case 0
pic1.SetPixel(ix, iy, Color.Black)
Case 1
If Cortex(ix, iy).Status = 1 Then
If Field_A_Accum(ix, iy) < L_GameLive_Low Then
pic1.SetPixel(ix, iy, Color.Blue)
End If
If Field_A_Accum(ix, iy) >= L_GameLive_Low And Field_A_Accum(ix, iy) < L_GameLive_high Then
pic1.SetPixel(ix, iy, Color.Green)
End If
If Field_A_Accum(ix, iy) >= L_GameLive_high Then
pic1.SetPixel(ix, iy, Color.Red)
End If
Else
pic1.SetPixel(ix, iy, Color.Yellow)
End If
Case 2
If Cortex(ix, iy).Status = 1 Then
pic1.SetPixel(ix, iy, Color.White)
Else
pic1.SetPixel(ix, iy, Color.DarkBlue)
End If
Case 5
pic1.SetPixel(ix, iy, Color.DarkMagenta)
End Select
Next
Next
PictureBox4.Image = pic1
PictureBox4.Update()
End Sub
Private Sub CheckedListBox1_MouseUp(sender As Object, e As MouseEventArgs) Handles CheckedListBox1.MouseUp
PatternsActivation()
End Sub
' Активация входных паттернов
Private Sub PatternsActivation()
For i = 0 To X_C - 1
For j = 0 To Y_C - 1
Cortex(i, j).Status = 0
CortexA(i, j, CurLayer) = 0
Next
Next
For Each item In CheckedListBox1.CheckedItems
With PatSet(item)
For ix = 0 To 2 * R_Pat
For iy = 0 To 2 * R_Pat
If .P(ix, iy) = 1 Then
Cortex(.ix - R_Pat + ix, .iy - R_Pat + iy).Status = 6
End If
Next
Next
End With
Next
Draw_Status()
PictureBox1.Image = pic
End Sub
' График суммарного ритма
Private Sub DrawChart()
Dim YSize = 40
Dim Y As Integer
Dim Amax = 0.05
Dim pic2 As New Bitmap(NSer, YSize)
Dim i As Integer = 0
For k = CurPosA + 1 To NSer - 1
Y = AWave(k) * (YSize - 1) / Amax
If Y >= YSize - 1 Then Y = YSize - 1
pic2.SetPixel(i, YSize - Y - 1, Color.Black)
i += 1
Next
For k = 0 To CurPosA
Y = AWave(k) * (YSize - 1) / Amax
If Y >= YSize - 1 Then Y = YSize - 1
pic2.SetPixel(i, YSize - Y - 1, Color.Black)
i += 1
Next
PictureBox3.Image = pic2
PictureBox3.Update()
End Sub
' вкл серии картинок
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
FPic = Not FPic
If FPic Then
Label2.Text = "вкл."
PicStart = CT
Else
Label2.Text = "выкл."
End If
End Sub
' Формирование серии картинок
Private Sub addpic()
Dim s As Integer = CT - PicStart - 1
Dim Y As Integer = Int(s / WPic)
Dim X As Integer = s - Y * WPic
X = X * X_C
Y = Y * Y_C
For ix = 0 To X_C - 1
For iy = 0 To Y_C - 1
Bigpic.SetPixel(X + ix, Y + iy, pic.GetPixel(ix, iy))
Next
Next
If s = NPic - 1 Then
FPic = False
Label2.Text = "выкл."
Label2.Update()
PictureBox1.Image = Bigpic
PictureBox1.Update()
Me.SetTopLevel(True)
MsgBox("")
End If
End Sub
' Проекция по волновому туннелю
Public Sub TMove()
If cortex2 Is Nothing Then Exit Sub
For ix = 0 To TD - 1
For iy = 0 To TD - 1
cortex2.Cortex(ix + TX2, iy + TY2).Status = Cortex(ix + TX1, iy + TY1).Status
cortex2.CortexA(ix + TX2, iy + TY2, cortex2.CurLayer) = CortexA(ix + TX1, iy + TY1, CurLayer)
cortex2.Cortex(ix + TX2, iy + TY2).T = Cortex(ix + TX1, iy + TY1).T
Next
Next
cortex2.Wave()
End Sub
' Создание волнового туннеля
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
cortex2 = New Form1
cortex2.Text = "2"
cortex2.Show()
End Sub
' Вкл/выкл обучения
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
FLearn = Not FLearn
If FLearn Then
Label3.Text = "вкл."
Else
Label3.Text = "выкл."
End If
End Sub
End Class
|
The-Logic-of-Thinking/demo-id-waves
|
Спонтанная активность/Form1.vb
|
Visual Basic
|
mit
| 42,442
|
Module Carrito
Public Sub setCarrito(ByRef dgv As DataGridView)
If formMain.carrito.Tables.Contains("Compras") Then
If Not formMain.carrito.Tables("Compras").Columns.Contains("Items") Then
For i = 0 To 5
formMain.carrito.Tables("Compras").Columns.Add(New DataColumn)
Next
formMain.carrito.Tables("Compras").Columns("column1").ColumnName = "id"
formMain.carrito.Tables("Compras").Columns("column2").ColumnName = "idItem"
formMain.carrito.Tables("Compras").Columns("column3").ColumnName = "Items"
formMain.carrito.Tables("Compras").Columns("column4").ColumnName = "Número"
formMain.carrito.Tables("Compras").Columns("column5").ColumnName = "Precio"
formMain.carrito.Tables("Compras").Columns("column6").ColumnName = "Forma de Pago"
End If
End If
dgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect
dgv.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
formMain.carrito.Tables("Compras").Columns("id").AutoIncrement = True
formMain.carrito.Tables("Compras").Columns("id").AutoIncrementSeed = 1
dgv.DataSource = formMain.carrito.Tables("Compras")
dgv.Columns("idItem").Visible = False
dgv.Columns("id").Visible = False
End Sub
Public Function setClienteCarrito(ByVal cliente As String, ByVal dni As String)
If formMain.userCarrito(1) = "" Or formMain.userCarrito(1) = dni Then
VistaCarrito.tbCliente.Text = cliente
formMain.userCarrito(0) = cliente
VistaCarrito.tbDNI.Text = "DNI: " & dni
formMain.userCarrito(1) = dni
VistaCarrito.tbFecha.Text = "Fecha: " & Now()
Return ("Correcto")
Else
VistaCarrito.tbCliente.Text = formMain.userCarrito(0)
VistaCarrito.tbDNI.Text = "DNI: " & formMain.userCarrito(1)
VistaCarrito.tbFecha.Text = "Fecha: " & DateTime.Now.ToString("dd/MM/yyyy")
Return ("AlreadySet")
End If
End Function
Public Sub agregarAlCarrito(ByRef Item As String, ByVal Numero As String, ByVal Precio As Double, ByVal FormaPago As String)
Dim idItem As Integer = obtenerID("Items", "nombre", Item)
formMain.carrito.Tables("Compras").Rows.Add(Nothing, idItem, Item, Numero, Precio, FormaPago)
End Sub
Public Sub quitarDelCarrito(ByVal id As Integer)
For i = 0 To formMain.carrito.Tables("Compras").Rows.Count - 1
If formMain.carrito.Tables("Compras").Rows(i).Item("id") = id Then
formMain.carrito.Tables("Compras").Rows.Remove(formMain.carrito.Tables("Compras").Rows(i))
Exit For
End If
Next
End Sub
Public Function cantidadItemsCarrito(ByVal item As String)
Dim contador As Integer = 0
For i = 0 To formMain.carrito.Tables("Compras").Rows.Count - 1
If formMain.carrito.Tables("Compras").Rows(i).Item("Items") = item Then
contador = contador + 1
End If
Next
Return (contador)
End Function
End Module
|
MontiQt/SaavedraSystem
|
Formularios Saavedra/Clases/Carrito.vb
|
Visual Basic
|
mit
| 3,407
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("MLP")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Deere & Company")>
<Assembly: AssemblyProduct("MLP")>
<Assembly: AssemblyCopyright("Copyright © Deere & Company 2013")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("3286abca-499f-4fbb-8cc4-111b2f1916df")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
RutledgePaulV/multilayer-perceptron-vb
|
My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,154
|
Imports bsc_gui.Helpers
Imports bsc_gui.ArgBuilder
Public Class BSCGUI
Dim mode As String
Public appArgs As ArgsList
' Proxy Init Module
Private Sub BSCGUI_Initialize()
lblStatus.Text = "Ready to pack!"
appArgs.setMode("e")
End Sub
' Loader
Private Sub BSCGUI_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BSCGUI_Initialize()
' Register event handlers! (https://stackoverflow.com/questions/24227158/)
AddHandler ctlInputFile.InFileSelected, AddressOf ArgBuilder.ctlInputFile_FileSelected
AddHandler ctlOutputFile.OutFileSelected, AddressOf ArgBuilder.ctlOutputFile_FileSelected
AddHandler ctlModeSelect.modeChanged, AddressOf ArgBuilder.ctlModeSelect_ModeChanged
AddHandler ctlPreprocOpts.preprocDisabled, AddressOf ArgBuilder.ctlPreProcOpts_PreprocDisabled
AddHandler ctlPreprocOpts.segmentsEnabled, AddressOf ArgBuilder.ctlPreProcOpts_SegmentsEnabled
AddHandler ctlPreprocOpts.structDataEnabled, AddressOf ArgBuilder.ctlPreProcOpts_StructDataEnabled
AddHandler ctlPreprocOpts.lzpDisabled, AddressOf ArgBuilder.ctlPreProcOpts_LZPDisabled
AddHandler ctlBlkSortingOpts.blkSizeChanged, AddressOf ArgBuilder.ctlBlkSortingOpts_BlkSizeChanged
AddHandler ctlBlkSortingOpts.contextChanged, AddressOf ArgBuilder.ctlBlkSortingOpts_ContextChanged
AddHandler ctlBlkSortingOpts.ctlAlgs.useSTChanged, AddressOf ArgBuilder.ctlAlgs_UseSTChanged
AddHandler ctlBlkSortingOpts.ctlAlgs.useCUDAChanged, AddressOf ArgBuilder.ctlAlgs_UseCUDAChanged
AddHandler ctlBlkSortingOpts.ctlAlgs.useEntropyCodeChanged, AddressOf ArgBuilder.ctlAlgs_UseEntropyCodeChanged
AddHandler ctlBlkSortingOpts.ctlAlgs.sTOrderChanged, AddressOf ArgBuilder.ctlAlgs_STOrderChanged
End Sub
' Handlers for exit / OK
Private Sub btnOK_Click() Handles ctlBtnGrpConfirm.ActionOK
' Build the CLI args based on events fired by all submodules
End Sub
Private Sub btnCancel_Click() Handles ctlBtnGrpConfirm.ActionCancel
Me.Close()
End Sub
' End Handlers for exit / OK
Private Sub prgBarTask_Click(sender As Object, e As EventArgs) Handles prgBarTask.Click
prgBarTask.Value = 64
End Sub
End Class
|
vaibhav-y/bsc-gui
|
bsc-gui/BSCGUI.vb
|
Visual Basic
|
apache-2.0
| 2,290
|
'------------------------------------------------------------------------------
' <auto-generated>
' 這段程式碼是由工具產生的。
' 執行階段版本:4.0.30319.42000
'
' 對這個檔案所做的變更可能會造成錯誤的行為,而且如果重新產生程式碼,
' 變更將會遺失。
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'注意: 這是自動產生的檔案,請勿直接修改它。若要進行變更,
' 或者您在這個檔案發生建置錯誤,請到專案設計工具
' (移至專案屬性或者在 [方案總管] 中按兩下 [My Project] 節點),
' 然後在 [應用程式] 索引標籤上進行變更。
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.AUCourseHelper_Teacher.frmTeacher
End Sub
End Class
End Namespace
|
AuCourseHelper/AuCourseHelper_PC
|
Teacher/My Project/Application.Designer.vb
|
Visual Basic
|
apache-2.0
| 1,540
|
Imports M_OrderLibrary
Imports System.Drawing
'PNG (Portable Network Graphics)
'Il formato PNG consente di usufruire di molti dei vantaggi offerti dal formato GIF, ma fornisce anche ulteriori funzionalità rispetto a tale formato. Analogamente ai file GIF, i file PNG vengono compressi senza alcuna perdita di informazioni. È possibile memorizzare nei file PNG colori con 8, 24 o 48 bit per pixel e scale di grigi con 1, 2, 4, 8 o 16 bit per pixel. I file GIF consentono di memorizzare solo 1, 2, 4 o 8 bit per pixel. È inoltre possibile memorizzare in un file PNG anche un valore alfa per ogni pixel, che consente di specificare il livello di fusione del colore di tale pixel con il colore dello sfondo.
'Il formato PNG rappresenta un miglioramento della capacità del formato GIF di visualizzare progressivamente un'immagine, ovvero di visualizzare approssimazioni sempre migliori di un'immagine mentre viene trasmessa attraverso una connessione di rete. È possibile memorizzare nei file PNG informazioni relative alla correzione gamma e alla correzione dei colori, in modo da consentire il rendering accurato delle immagini su svariate periferiche di visualizzazione.
Public Class LibFoto
Private Shared pathimage As String
Private Shared _variante As String
Public Shared Function LoadResourceImage(ByVal imageName As String) As Bitmap
Return New Bitmap(System.Reflection.Assembly.GetExecutingAssembly(). _
GetManifestResourceStream("M_Order." + imageName))
End Function
#If CONFIG = "Desktop" Then
Public Const imgEXT As String = ".jpg"
#Else
Public Const imgEXT As String = ".jpeg"
#End If
Public Shared Function SetFoto(ByVal pic As PictureBox, Optional ByVal variante As Integer = 0) As PictureBox
If LibSettings.MostraFoto Then
Try
If variante = 0 Then
_variante = ""
Else
_variante = "_" & variante.ToString.PadLeft(2, "0"c)
End If
pathimage = LibDb.FolderFoto & LibSettings.CodArticolo & _variante & imgEXT
If IO.File.Exists(pathimage) Then
pic.Image = New Bitmap(pathimage)
pic.SizeMode = PictureBoxSizeMode.CenterImage
'Il file rimarrà bloccato fino all'eliminazione dell'oggetto Bitmap
Else
'carica immagine vuota
pic.Image = LibFoto.LoadResourceImage("foto.jpeg")
pic.SizeMode = PictureBoxSizeMode.CenterImage
End If
Catch ex As Exception
'MessageBox.Show(ex.Message)
End Try
End If
Return pic
End Function
End Class
|
maslopop/morder4
|
M-Order/LibFoto.vb
|
Visual Basic
|
apache-2.0
| 2,737
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.