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
'Option Compare Text Imports System Imports System.IO Imports System.Linq Imports System.Collections.Generic Imports System.Collections.ObjectModel 'Imports Rstyx.Utilities.Files Namespace IO ''' <summary> Static utility methods for dealing with the file system and file or path names. </summary> Public NotInheritable Class FileUtils #Region "Private Fields" 'Private Logger As Rstyx.LoggingConsole.Logger = Rstyx.LoggingConsole.LogBox.getLogger(MyClass.GetType.FullName) Private Shared Logger As Rstyx.LoggingConsole.Logger = Rstyx.LoggingConsole.LogBox.getLogger("Rstyx.Utilities.Files.FileUtils") #End Region #Region "Constructor" Private Sub New 'Hides the Constructor End Sub #End Region #Region "Methods - File Search" ''' <summary> Returns a <see cref="System.IO.FileInfo"/> instance for the file that matches one of a given file filters and is found first in the Folders list. </summary> ''' <param name="FileFilters"> File filters without path (wildcards allowed), delimited by a given delimiter. </param> ''' <param name="Folders"> Folders that should be searched. Absolute or relative (but not "..\" or ".\"), delimited by a given delimiter. Embedded Environment variables (quoted by "%") are expanded. </param> ''' <param name="DelimiterRegEx"> The Delimiter for both the FileFilter and Folder lists (Regular Expression). Defaults to ";" (if it's <see langword="null"/>). </param> ''' <param name="SearchOptions"> Available System.IO.SearchOptions (mainly recursive or not). </param> ''' <returns> The full path of the found file, or <see langword="null"/>. </returns> ''' <exception cref="System.ArgumentNullException"> <paramref name="FileFilters"/> is <see langword="null"/> or empty or white space. </exception> ''' <exception cref="System.ArgumentNullException"> <paramref name="Folders"/> is <see langword="null"/> or empty or white space. </exception> Public Shared Function findFile(FileFilters As String, Folders As String, ByVal DelimiterRegEx As String, SearchOptions As System.IO.SearchOption ) As FileInfo Logger.logDebug(StringUtils.sprintf("findFile(): FileFilter: '%s', Verzeichnisse: '%s'.", FileFilters, Folders)) Dim foundFile As FileInfo = Nothing Dim FoundFiles As FileInfoCollection = findFiles(FileFilters, Folders, DelimiterRegEx, SearchOptions, OnlyOneFile:=True) ' Result If (FoundFiles.Count < 1) Then Logger.logDebug("findFile(): keine Datei gefunden!") Else foundFile = FoundFiles(0) Logger.logDebug(StringUtils.sprintf("findFile(): Datei gefunden: '%s'.", foundFile.FullName)) End If Return foundFile End Function ''' <summary> Searches for files in a list of directories, matching a list of file filters. </summary> ''' <param name="FileFilters"> File filters without path (wildcards allowed), delimited by a given delimiter. </param> ''' <param name="Folders"> Folders that should be searched. Absolute or relative (but not "..\" or ".\"), delimited by a given delimiter. Embedded Environment variables (quoted by "%") are expanded. </param> ''' <param name="DelimiterRegEx"> The Delimiter for both the FileFilter and Folder lists (Regular Expression). Defaults to ";" (if it's <see langword="null"/>). </param> ''' <param name="SearchOptions"> Available System.IO.SearchOptions (mainly recursive or not). </param> ''' <param name="OnlyOneFile"> If True, the search is canceled when the first file is found. Defaults to False. </param> ''' <returns> The resulting list with found files. </returns> ''' <exception cref="System.ArgumentNullException"> <paramref name="FileFilters"/> is <see langword="null"/> or empty or white space. </exception> ''' <exception cref="System.ArgumentNullException"> <paramref name="Folders"/> is <see langword="null"/> or empty or white space. </exception> Public Shared Function findFiles(FileFilters As String, Folders As String, ByVal DelimiterRegEx As String, SearchOptions As System.IO.SearchOption, Optional OnlyOneFile As Boolean = false ) As FileInfoCollection If (FileFilters.IsEmptyOrWhiteSpace()) Then Throw New System.ArgumentNullException("FileFilters", Rstyx.Utilities.Resources.Messages.FileUtils_NoFileFilter) If (Folders.IsEmptyOrWhiteSpace()) Then Throw New System.ArgumentNullException("Folders", Rstyx.Utilities.Resources.Messages.FileUtils_NoSearchDir) If (DelimiterRegEx.IsEmpty()) Then DelimiterRegEx = ";" Return findFiles(FileFilters.Split(DelimiterRegEx), Folders.Split(DelimiterRegEx), SearchOptions, OnlyOneFile) End Function ''' <summary> Searches for files in a list of directories, matching a list of file filters. </summary> ''' <param name="FileFilters"> File filters without path (wildcards allowed). </param> ''' <param name="Folders"> Folders that should be searched. Absolute or relative (but not "..\" or ".\"). Embedded Environment variables (quoted by "%") are expanded. </param> ''' <param name="SearchOptions"> Available System.IO.SearchOptions (mainly recursive or not). </param> ''' <param name="OnlyOneFile"> If True, the search is canceled when the first file is found. Defaults to False. </param> ''' <returns> The resulting list with found files. </returns> ''' <exception cref="System.ArgumentNullException"> <paramref name="FileFilters"/> is <see langword="null"/> or empty or white space. </exception> ''' <exception cref="System.ArgumentNullException"> <paramref name="Folders"/> is <see langword="null"/> or empty or white space. </exception> Public Shared Function findFiles(FileFilters As IEnumerable(Of String), Folders As IEnumerable(Of DirectoryInfo), SearchOptions As System.IO.SearchOption, Optional OnlyOneFile As Boolean = false ) As FileInfoCollection If (FileFilters Is Nothing) Then Throw New System.ArgumentNullException("FileFilters", Rstyx.Utilities.Resources.Messages.FileUtils_NoFileFilter) If (Folders Is Nothing) Then Throw New System.ArgumentNullException("Folders", Rstyx.Utilities.Resources.Messages.FileUtils_NoSearchDir) ' Unify list of folders. Dim StringFolders As New Collection(Of String) For Each di As DirectoryInfo In Folders StringFolders.Add(di.FullName) Next Return findFiles(FileFilters, StringFolders, SearchOptions, OnlyOneFile) End Function ''' <summary> Searches for files in a list of directories, matching a list of file filters. </summary> ''' <param name="FileFilters"> File filters without path (wildcards allowed). </param> ''' <param name="Folders"> Folders that should be searched. Absolute or relative (but not "..\" or ".\"). Embedded Environment variables (quoted by "%") are expanded. </param> ''' <param name="SearchOptions"> Available System.IO.SearchOptions (mainly recursive or not). </param> ''' <param name="OnlyOneFile"> If True, the search is canceled when the first file is found. Defaults to False. </param> ''' <returns> The resulting list with found files. </returns> ''' <exception cref="System.ArgumentNullException"> <paramref name="FileFilters"/> is <see langword="null"/> or empty or white space. </exception> ''' <exception cref="System.ArgumentNullException"> <paramref name="Folders"/> is <see langword="null"/> or empty or white space. </exception> Public Shared Function findFiles(FileFilters As IEnumerable(Of String), Folders As IEnumerable(Of String), SearchOptions As System.IO.SearchOption, Optional OnlyOneFile As Boolean = false ) As FileInfoCollection Dim FoundFiles As New FileInfoCollection() If (FileFilters Is Nothing) Then Throw New System.ArgumentNullException("FileFilters", Rstyx.Utilities.Resources.Messages.FileUtils_NoFileFilter) If (Folders Is Nothing) Then Throw New System.ArgumentNullException("Folders", Rstyx.Utilities.Resources.Messages.FileUtils_NoSearchDir) Dim oStopwatch As System.Diagnostics.Stopwatch = System.Diagnostics.Stopwatch.StartNew() ' Log Arguments Logger.logDebug("\nfindFiles(): Start search with these settings:") Logger.logDebug(StringUtils.sprintf("findFiles(): - Only one file: %s", OnlyOneFile)) Logger.logDebug(StringUtils.sprintf("findFiles(): - Options: %s", SearchOptions.ToString())) Logger.logDebug(StringUtils.sprintf("findFiles(): - FileFilters (%d):", FileFilters.Count)) For Each FileFilter As String in FileFilters Logger.logDebug(StringUtils.sprintf("findFiles(): - FileFilter: %s", FileFilter)) Next Logger.logDebug(StringUtils.sprintf("findFiles(): - Folders (%d):", Folders.Count)) For Each Folder As String in Folders Logger.logDebug(StringUtils.sprintf("findFiles(): - Folder: %s", Folder)) Next Logger.logDebug("") ' Find Files. findAddFiles(FoundFiles, FileFilters, Folders, SearchOptions, OnlyOneFile) oStopwatch.Stop() Logger.logDebug(StringUtils.sprintf("\nfindFiles(): Found %d files (in %.3f sec.)\n", FoundFiles.Count, oStopwatch.ElapsedMilliseconds/1000)) Return FoundFiles End Function ''' <summary> Backend of findFiles(): Searches for files in a list of directories, matching a list of file filters. </summary> ''' <param name="FoundFiles"> [Output] The Collection to add the found files to. If <see langword="null"/> it will be created. </param> ''' <param name="FileFilters"> File filters without path (wildcards allowed). </param> ''' <param name="Folders"> Folders that should be searched. Absolute or relative (but not "..\" or ".\"). Embedded Environment variables (quoted by "%") are expanded. </param> ''' <param name="SearchOptions"> Available System.IO.SearchOptions (mainly recursive or not). </param> ''' <param name="OnlyOneFile"> If True, the search is canceled when the first file is found. Defaults to False. </param> ''' <exception cref="System.ArgumentNullException"> <paramref name="FileFilters"/> is <see langword="null"/> or empty or white space. </exception> ''' <exception cref="System.ArgumentNullException"> <paramref name="Folders"/> is <see langword="null"/> or empty or white space. </exception> ''' <exception cref="System.ArgumentException"> <paramref name="FileFilters"/> doesn't contain any valid file filter. </exception> ''' <exception cref="System.ArgumentException"> <paramref name="Folders"/> doesn't contain any existent Folder. </exception> Private Shared Sub findAddFiles(ByRef FoundFiles As FileInfoCollection, FileFilters As IEnumerable(Of String), Folders As IEnumerable(Of String), SearchOptions As System.IO.SearchOption, Optional OnlyOneFile As Boolean = false ) ' Check Arguments If (FoundFiles Is Nothing) Then FoundFiles = New FileInfoCollection() If (FileFilters Is Nothing) Then Throw New System.ArgumentNullException("FileFilters", Rstyx.Utilities.Resources.Messages.FileUtils_NoFileFilter) If (Folders Is Nothing) Then Throw New System.ArgumentNullException("Folders", Rstyx.Utilities.Resources.Messages.FileUtils_NoSearchDir) ' Consolidate and check file filters. Dim ConsolidatedFileFilters As New Collection(Of String) For Each FileFilter As String in FileFilters FileFilter = FileFilter.Trim() If (FileFilter.IsEmptyOrWhiteSpace()) Then Logger.logDebug(Rstyx.Utilities.Resources.Messages.FileUtils_SearchIgnoresEmptyFileFilter) ElseIf (Not isValidFileNameFilter(FileFilter)) Then Logger.logWarning(StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.FileUtils_SearchIgnoresInvalidFileFilter, FileFilter)) ElseIf (ConsolidatedFileFilters.Contains(FileFilter)) Then Logger.logDebug(StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.FileUtils_SearchIgnoresRepeatedFileFilter, FileFilter)) Else ConsolidatedFileFilters.Add(FileFilter) End If Next If (ConsolidatedFileFilters.Count < 1) Then Throw New System.ArgumentException(Rstyx.Utilities.Resources.Messages.FileUtils_NoValidFileFilter, "FileFilters") ' Consolidate and check folder names (also expand environment variables). Dim ConsolidatedFolders As New Collection(Of String) For Each FolderName As String in Folders FolderName = Environment.ExpandEnvironmentVariables(FolderName.Trim()) If (Not Directory.Exists(FolderName)) Then If (FolderName.IsEmptyOrWhiteSpace()) Then Logger.logDebug(Rstyx.Utilities.Resources.Messages.FileUtils_SearchIgnoresEmptyFolderName) ElseIf (Not isValidFilePath(FolderName)) Then Logger.logWarning(StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.FileUtils_SearchIgnoresInvalidFolderName, FolderName)) Else Logger.logDebug(StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.FileUtils_SearchFolderNotFound, FolderName, Directory.GetCurrentDirectory())) End If ElseIf (ConsolidatedFolders.Contains(FolderName)) Then Logger.logDebug(StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.FileUtils_SearchIgnoresRepeatedFolderName, FolderName)) Else ConsolidatedFolders.Add(FolderName) End If Next If (ConsolidatedFolders.Count < 1) Then Throw New System.ArgumentException(Rstyx.Utilities.Resources.Messages.FileUtils_NoExistentFolderName, "Folders") ' Search each folder of given folder list. For Each FolderName As String in ConsolidatedFolders Dim Files() As FileInfo Dim SearchFinished As Boolean = False Dim SearchDir As DirectoryInfo = New DirectoryInfo(FolderName) Logger.logDebug(StringUtils.sprintf("\nfindAddFiles(): Suche in Verzeichnis: '%s'.", Path.GetFullPath(FolderName))) ' Search files of current folder. For Each FileFilter As String in ConsolidatedFileFilters Try ' Get the matching files of this directory, possibly inclusive subdirectories. Files = SearchDir.GetFiles(FileFilter, System.IO.SearchOption.TopDirectoryOnly) For Each fi As FileInfo in Files If (Not FoundFiles.Contains(fi)) Then FoundFiles.Add(fi) Logger.logDebug(StringUtils.sprintf("findAddFiles(): %6d. Datei gefunden: '%s'", FoundFiles.Count, FoundFiles(FoundFiles.Count - 1).FullName)) If (OnlyOneFile) Then SearchFinished = True Exit For End If End If Next Catch ex as System.Security.SecurityException Logger.logDebug(StringUtils.sprintf("findAddFiles(): SecurityException at processing files of %s.", FolderName)) Catch ex as System.UnauthorizedAccessException Logger.logDebug(StringUtils.sprintf("findAddFiles(): UnauthorizedAccessException at processing files of %s.", FolderName)) Catch ex as System.Exception Logger.logError(ex, StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.FileUtils_ErrorProcessingFolder, FolderName)) End Try If (SearchFinished) Then Exit For Next ' Optional: Search subfolders of current folder (*** recursive ***). If (Not SearchFinished AndAlso (SearchOptions = System.IO.SearchOption.AllDirectories)) Then Try ' Get all sub folders of this directory. Dim SubFolders() As DirectoryInfo = SearchDir.GetDirectories() If (SubFolders.Length > 0) Then ' Unify list of folders. Dim StringSubFolders As New Collection(Of String) For Each di As DirectoryInfo In SubFolders StringSubFolders.Add(di.FullName) Next findAddFiles(FoundFiles, ConsolidatedFileFilters, StringSubFolders, SearchOptions, OnlyOneFile) End If Catch ex as System.Security.SecurityException Logger.logDebug(StringUtils.sprintf("findAddFiles(): SecurityException at processing subfolders of %s.", FolderName)) Catch ex as System.UnauthorizedAccessException Logger.logDebug(StringUtils.sprintf("findAddFiles(): UnauthorizedAccessException at processing subfolders of %s.", FolderName)) Catch ex as System.Exception Logger.logError(ex, StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.FileUtils_ErrorProcessingSubFolders, FolderName)) End Try End If If (SearchFinished) Then Exit For Next End Sub #End Region #Region "Methods - File Name Handling" ''' <summary> Returns a desired part of a given file name string. </summary> ''' <param name="givenFilename"> File name, absolute or relative, file doesn't have to exist. </param> ''' <param name="desiredFilePart"> Determines the parts of the filename to return. </param> ''' <param name="Absolute"> If True, and a given file name is relative, it will be "rooted". If False, returned drive and directory may be empty. Defaults to True. </param> ''' <param name="ClassLength"> Number of characters to define the class name (at end of base name) - defaults to 2. </param> ''' <returns> A string with the desired parts of the input path name, or String.Empty on error. </returns> ''' <remarks> ''' <para> ''' I.e. for a given file name of "D:\daten\Test_QP\qp_ueb.dgn", the results are: ''' </para> ''' <para> ''' <list type="table"> ''' <listheader> <term> <b>desiredFilePart</b> </term> <description> Result </description></listheader> ''' <item> <term> FilePart.Drive </term> <description> D: </description></item> ''' <item> <term> FilePart.Dir </term> <description> D:\daten\Test_QP </description></item> ''' <item> <term> FilePart.Base </term> <description> qp_ueb </description></item> ''' <item> <term> FilePart.Ext </term> <description> dgn </description></item> ''' <item> <term> FilePart.Proj </term> <description> qp_u </description></item> ''' <item> <term> FilePart.Class </term> <description> eb </description></item> ''' <item> <term> FilePart.Base_Ext </term> <description> qp_ueb.dgn </description></item> ''' <item> <term> FilePart.Dir_Base </term> <description> D:\daten\Test_QP\qp_ueb </description></item> ''' <item> <term> FilePart.Dir_Base_Ext </term> <description> D:\daten\Test_QP\qp_ueb.dgn </description></item> ''' <item> <term> FilePart.Dir_Proj </term> <description> D:\daten\Test_QP\qp_u </description></item> ''' </list> ''' </para> ''' </remarks> Public Shared Function getFilePart(byVal givenFilename As String, _ byVal desiredFilePart As FilePart, _ byVal Optional Absolute As Boolean = true, _ byVal Optional ClassLength As Integer = 2) As String Dim extractedFilePart As String = String.Empty Try Dim msg As String = String.Empty Dim Drive As String = String.Empty Dim AbsolutePath As String = String.Empty Dim ParentFolder As String = String.Empty Dim FileName As String = String.Empty Dim BaseName As String = String.Empty Dim Extension As String = String.Empty Dim ProjectName As String = String.Empty Dim DgnClass As String = String.Empty Dim ProjectLength As Integer givenFilename = givenFilename.Replace("""", "") Logger.logDebug(StringUtils.sprintf("getFilePart(): gesuchter Namensteil: %s.", desiredFilePart.ToDisplayString())) Logger.logDebug(StringUtils.sprintf("getFilePart(): gegeben : %s.", givenFilename)) If (givenFilename.IsNotEmptyOrWhiteSpace()) Then 'Einzelteile normal AbsolutePath = If(Not Absolute, givenFilename, System.IO.Path.GetFullPath(givenFilename)) Drive = System.IO.Path.GetPathRoot(AbsolutePath).TrimEnd(Path.DirectorySeparatorChar) ParentFolder = System.IO.Path.GetDirectoryName(AbsolutePath) If (ParentFolder Is Nothing) Then ParentFolder = AbsolutePath End If ParentFolder = ParentFolder.TrimEnd(Path.DirectorySeparatorChar) FileName = System.IO.Path.GetFileName(givenFilename) BaseName = System.IO.Path.GetFileNameWithoutExtension(givenFilename) Extension = System.IO.Path.GetExtension(givenFilename).TrimStart("."c) 'Einzelteile iProjekt, iKlasse if (ClassLength < 0) then ClassLength = 2 If (BaseName.Length > (ProjectLength + ClassLength)) Then ProjectLength = BaseName.Length - ClassLength ProjectName = BaseName.left(ProjectLength) DgnClass = BaseName.right(ClassLength) End If 'Debug-Message msg = vbNewLine & _ "getFilePart(): AbsolutePath = " & AbsolutePath & vbNewLine & _ "getFilePart(): Drive = " & Drive & vbNewLine & _ "getFilePart(): ParentFolder = " & ParentFolder & vbNewLine & _ "getFilePart(): FileName = " & FileName & vbNewLine & _ "getFilePart(): BaseName = " & BaseName & vbNewLine & _ "getFilePart(): Extension = " & Extension & vbNewLine & _ "getFilePart(): ProjectName = " & ProjectName & vbNewLine & _ "getFilePart(): DgnClass = " & DgnClass 'Logger.logDebug(msg) 'Ergebnis zusammenstellen Select Case desiredFilePart Case FilePart.Drive: extractedFilePart = Drive Case FilePart.Dir: extractedFilePart = ParentFolder Case FilePart.Base: extractedFilePart = BaseName Case FilePart.Ext: extractedFilePart = Extension Case FilePart.Proj: extractedFilePart = ProjectName Case FilePart.Class: extractedFilePart = DgnClass Case FilePart.Base_Ext: extractedFilePart = FileName Case FilePart.Dir_Base: extractedFilePart = ParentFolder & Path.DirectorySeparatorChar & BaseName Case FilePart.Dir_Base_Ext: extractedFilePart = ParentFolder & Path.DirectorySeparatorChar & FileName Case FilePart.Dir_Proj: extractedFilePart = ParentFolder & Path.DirectorySeparatorChar & ProjectName Case Else extractedFilePart = "" Logger.logError(StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.FileUtils_InvalidFilepartEnumValue, desiredFilePart.ToDisplayString())) End Select End If Catch ex As System.NotSupportedException Logger.logDebug("getFilePart(): Der gegebene Pfad ist ungültig") Catch ex As System.ArgumentException Logger.logDebug("getFilePart(): Der gegebene Pfad ist ungültig") Catch ex As System.Exception Logger.logError(ex, StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.Global_UnexpectedErrorIn, System.Reflection.MethodBase.GetCurrentMethod().Name)) End Try Logger.logDebug(StringUtils.sprintf("getFilePart(): Ergebnis: %s.", extractedFilePart)) Return extractedFilePart End Function ''' <summary> Converts a file path that may contain wildcards to a Regular expression pattern. </summary> ''' <param name="FilePath"> Regular Windows file path (may contain wildcards). </param> ''' <returns> The Regular expression pattern which corresponds to the file path. </returns> Public Shared Function FilePath2RegExp(ByVal FilePath As String) As String Dim Pattern As String Pattern = FilePath.ReplaceWith("\\", "\\") Pattern = Pattern.ReplaceWith("[.(){}[\]$^]", "\$&") Pattern = Pattern.ReplaceWith("\?", ".") Pattern = Pattern.ReplaceWith("\*", ".*") Return Pattern End Function ''' <summary> Checks if a given file name is valid for file system operations. It doesn't have to exist. </summary> ''' <param name="FileName"> The file name to validate (without path). </param> ''' <returns> <see langword="true"/>, if file system or file name operations shouldn't complain about this name, otherwise <see langword="false"/>. </returns> ''' <remarks> ''' The given <paramref name="FileName"/> may not contain path separators. ''' This method doesn't check environment conditions. So, real file operations may fail due to security reasons ''' or a too long path because the used directory were too long. ''' </remarks> Public Shared Function isValidFileName(byVal FileName As String) As Boolean Dim isValid As Boolean = True If (FileName.IsEmptyOrWhiteSpace()) Then isValid = False ElseIf (FileName.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) >= 0) Then ' FileName contains invalid characters. isValid = False End If Return isValid End Function ''' <summary> Checks if a given file name filter seems to be valid. </summary> ''' <param name="FileNameFilter"> The file name filter to validate (without path). </param> ''' <returns> <see langword="true"/>, if file name filter operations shouldn't complain about this name filter, otherwise <see langword="false"/>. </returns> Public Shared Function isValidFileNameFilter(byVal FileNameFilter As String) As Boolean Dim isValid As Boolean = True If (FileNameFilter Is Nothing) Then isValid = False Else For Each TestChar As Char In System.IO.Path.GetInvalidFileNameChars() If (Not ((TestChar = "*") Or (TestChar = "?"))) Then If (FileNameFilter.Contains(TestChar)) Then isValid = False End If End If Next End If Return isValid End Function ''' <summary> Checks if a given file path is valid for file system operations. It doesn't have to exist. </summary> ''' <param name="FilePath"> The file path to validate (absolute or relative). </param> ''' <returns> <see langword="true"/>, if file system or path name operations shouldn't complain about this path, otherwise <see langword="false"/>. </returns> Public Shared Function isValidFilePath(byVal FilePath As String) As Boolean Dim isValid As Boolean = False Try Dim fi As New FileInfo(FilePath) isValid = True Catch e As Exception End Try Return isValid End Function ''' <summary> Replaces invalid characters in a given file name string. </summary> ''' <param name="FileName"> The file name without path. </param> ''' <param name="ReplaceString"> [Optional] The replace string for invalid characters (defaults to "_"). </param> ''' <returns> ''' The given <paramref name="FileName"/> if it's a valid file name, otherwise ''' a valid file name where invalid characters are replaced by <paramref name="ReplaceString"/>. ''' </returns> ''' <exception cref="System.ArgumentNullException"> <paramref name="FileName"/> is <see langword="null"/> or empty or white space. </exception> ''' <exception cref="System.FormatException"> Validation of <paramref name="FileName"/> has been tried, but failed. </exception> Public Shared Function validateFileNameSpelling(byVal FileName As String, Optional byVal ReplaceString As String = "_") As String If (FileName.IsEmptyOrWhiteSpace()) Then Throw New System.ArgumentNullException("FileName") ' Replace invalid characters if present. Dim InvalidFileNameChars() As Char = System.IO.Path.GetInvalidFileNameChars() If (FileName.IndexOfAny(InvalidFileNameChars) >= 0) Then ' FileName contains invalid characters. Dim invalidString As String For Each invalidChar As Char In InvalidFileNameChars invalidString = Char.Parse(invalidChar) If (invalidString.Length > 0) Then FileName = FileName.Replace(invalidString, ReplaceString) End If Next End If ' Throw exception if not successful. If (Not isValidFileName(FileName)) Then Throw New System.FormatException(StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.FileUtils_ErrorValidatingInvalidFileName, FileName)) End If Return FileName End Function ''' <summary> Replaces invalid characters in a given file path string. </summary> ''' <param name="FilePath"> The file path to validate (absolute or relative). </param> ''' <param name="ReplaceString"> [Optional] The replace string for invalid characters (defaults to "_"). </param> ''' <returns> ''' The given <paramref name="FilePath"/> if it's a valid file path, otherwise ''' a valid file path where invalid characters are replaced by <paramref name="ReplaceString"/>. ''' </returns> ''' <exception cref="System.ArgumentNullException"> <paramref name="FilePath"/> is <see langword="null"/> or empty or white space. </exception> ''' <exception cref="System.Security.SecurityException"> The caller does not have the required permission. </exception> ''' <exception cref="System.UnauthorizedAccessException"> Access to <paramref name="FilePath"/> is denied. </exception> ''' <exception cref="System.IO.PathTooLongException"> <paramref name="FilePath"/> is too long. </exception> ''' <exception cref="System.FormatException"> Validation of <paramref name="FilePath"/> has been tried, but failed. </exception> Public Shared Function validateFilePathSpelling(byVal FilePath As String, Optional byVal ReplaceString As String = "_") As String If (FilePath.IsEmptyOrWhiteSpace()) Then Throw New System.ArgumentNullException("FilePath") Try FilePath = FilePath.Trim() Dim fi As New FileInfo(FilePath) 'Catch e As System.Security.SecurityException ' Unsufficient rights Catch e As System.ArgumentException ' FilePath (is empty or white space or) ** contains invalid characters ** Dim invalidString As String For Each invalidChar As Char In System.IO.Path.GetInvalidPathChars() invalidString = Char.Parse(invalidChar) If (invalidString.Length > 0) Then FilePath = FilePath.Replace(invalidString, ReplaceString) End If Next ' Re-throw if not successful. If (Not isValidFilePath(FilePath)) Then Throw New System.FormatException(StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.FileUtils_ErrorValidatingInvalidFilePath, FilePath), e) End If 'Catch e As System.UnauthorizedAccessException ' Access denied Catch e As System.IO.PathTooLongException Throw New System.IO.PathTooLongException(StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.FileUtils_PathTooLong, FilePath), e) Catch e As System.NotSupportedException ' FilePath contains a colon (:) outside drive letter Dim Root As String = Path.GetPathRoot(FilePath) If (Root.IsEmpty()) Then FilePath = FilePath.Replace(":", ReplaceString) Else FilePath = Root & FilePath.Right(Root, False).Replace(":", ReplaceString) End If ' Re-throw if not successful. If (Not isValidFilePath(FilePath)) Then Throw New System.FormatException(StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.FileUtils_ErrorValidatingInvalidFilePath, FilePath), e) End If End Try Return FilePath End Function #End Region #Region "Enums" ''' <summary> Determines a File path partial string supported by <see cref="getFilePart" />. </summary> Public Enum FilePart As Byte ''' <summary> Drive letter, i.e.: "D:\daten\Test_QP\qp_ueb.dgn" =&gt; "D:" </summary> Drive = 0 ' "D:" ''' <summary> Directory, i.e.: "D:\daten\Test_QP\qp_ueb.dgn" =&gt; "D:\daten\Test_QP" </summary> Dir = 1 ' "D:\daten\Test_QP" ''' <summary> File base name, i.e.: "D:\daten\Test_QP\qp_ueb.dgn" =&gt; "qp_ueb" </summary> Base = 2 ' "qp_ueb" ''' <summary> File extension, i.e.: "D:\daten\Test_QP\qp_ueb.dgn" =&gt; "dgn" </summary> Ext = 3 ' "dgn" ''' <summary> DGN project name, i.e.: "D:\daten\Test_QP\qp_ueb.dgn" =&gt; "qp_u" </summary> Proj = 4 ' "qp_u" ''' <summary> DGN class, i.e.: "D:\daten\Test_QP\qp_ueb.dgn" =&gt; "eb" </summary> [Class] = 5 ' "eb" ''' <summary> File base name and extension, i.e.: "D:\daten\Test_QP\qp_ueb.dgn" =&gt; "qp_ueb.dgn" </summary> Base_Ext = 6 ' "qp_ueb.dgn" ''' <summary> Directory and File base name, i.e.: "D:\daten\Test_QP\qp_ueb.dgn" =&gt; "D:\daten\Test_QP\qp_ueb" </summary> Dir_Base = 7 ' "D:\daten\Test_QP\qp_ueb" ''' <summary> Full absolute path, i.e.: "D:\daten\Test_QP\qp_ueb.dgn" =&gt; "D:\daten\Test_QP\qp_ueb.dgn" </summary> Dir_Base_Ext = 8 ' "D:\daten\Test_QP\qp_ueb.dgn" ''' <summary> Directory and DGN project name, i.e.: "D:\daten\Test_QP\qp_ueb.dgn" =&gt; "D:\daten\Test_QP\qp_u" </summary> Dir_Proj = 9 ' "D:\daten\Test_QP\qp_u" End Enum #End Region End Class End Namespace ' for jEdit: :collapseFolds=2::tabSize=4::indentSize=4:
rschwenn/Rstyx.Utilities
Utilities/source/IO/FileUtils.vb
Visual Basic
mit
42,626
Imports System.Data Imports cusAplicacion Partial Class rTNotasEntregas_cAñoMes 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)) Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1)) Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2)) Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2)) 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.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5)) Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5)) Dim lcParametro6Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6)) Dim lcParametro7Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(7)) Dim lcParametro7Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(7)) Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden Dim lcComandoSeleccionar As New StringBuilder() lcComandoSeleccionar.AppendLine("SELECT ") lcComandoSeleccionar.AppendLine(" clientes.cod_cli,") lcComandoSeleccionar.AppendLine(" SUBSTRING(clientes.nom_cli,0,70) as nom_cli, ") lcComandoSeleccionar.AppendLine(" DatePart(MONTH,entregas.Fec_Ini) as num_mes," ) lcComandoSeleccionar.AppendLine(" DatePart(YEAR,entregas.Fec_Ini)as AÑO, ") lcComandoSeleccionar.AppendLine(" CASE WHEN DatePart(MONTH,entregas.Fec_Ini)=1 THEN 'ENE' ") lcComandoSeleccionar.AppendLine(" WHEN DatePart(MONTH,entregas.Fec_Ini)=2 THEN 'FEB' ") lcComandoSeleccionar.AppendLine(" WHEN DatePart(MONTH,entregas.Fec_Ini)=3 THEN 'MAR' ") lcComandoSeleccionar.AppendLine(" WHEN DatePart(MONTH,entregas.Fec_Ini)=4 THEN 'ABR' ") lcComandoSeleccionar.AppendLine(" WHEN DatePart(MONTH,entregas.Fec_Ini)=5 THEN 'MAY' ") lcComandoSeleccionar.AppendLine(" WHEN DatePart(MONTH,entregas.Fec_Ini)=6 THEN 'JUN' ") lcComandoSeleccionar.AppendLine(" WHEN DatePart(MONTH,entregas.Fec_Ini)=7 THEN 'JUL' ") lcComandoSeleccionar.AppendLine(" WHEN DatePart(MONTH,entregas.Fec_Ini)=8 THEN 'AGO' ") lcComandoSeleccionar.AppendLine(" WHEN DatePart(MONTH,entregas.Fec_Ini)=9 THEN 'SEP' ") lcComandoSeleccionar.AppendLine(" WHEN DatePart(MONTH,entregas.Fec_Ini)=10 THEN 'OCT' ") lcComandoSeleccionar.AppendLine(" WHEN DatePart(MONTH,entregas.Fec_Ini)=11 THEN 'NOV' ") lcComandoSeleccionar.AppendLine(" WHEN DatePart(MONTH,entregas.Fec_Ini)=12 THEN 'DIC' ") lcComandoSeleccionar.AppendLine(" END AS mes, ") lcComandoSeleccionar.AppendLine(" renglones_entregas.can_art1 as cant, ") lcComandoSeleccionar.AppendLine(" renglones_entregas.mon_net as monto ") lcComandoSeleccionar.AppendLine("INTO #temporal ") lcComandoSeleccionar.AppendLine("FROM ") lcComandoSeleccionar.AppendLine(" entregas, renglones_entregas, clientes, articulos" ) lcComandoSeleccionar.AppendLine(" WHERE ") lcComandoSeleccionar.AppendLine(" entregas.documento = renglones_entregas.documento ") lcComandoSeleccionar.AppendLine(" AND entregas.cod_cli = clientes.cod_cli") lcComandoSeleccionar.AppendLine(" AND renglones_entregas.cod_art = articulos.cod_art") 'lcComandoSeleccionar.AppendLine(" AND entregas.cod_ven = vendedores.cod_ven") 'lcComandoSeleccionar.AppendLine(" AND articulos.cod_dep = departamentos.cod_dep") 'lcComandoSeleccionar.AppendLine(" AND ordenes_compras.cod_pro = proveedores.cod_pro") 'lcComandoSeleccionar.AppendLine(" AND ordenes_compras.cod_tra = transportes.cod_tra ") 'lcComandoSeleccionar.AppendLine(" AND ordenes_compras.cod_mon = monedas.cod_mon ") lcComandoSeleccionar.AppendLine(" AND entregas.fec_ini BETWEEN " & lcParametro0Desde) lcComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta) lcComandoSeleccionar.AppendLine(" AND articulos.cod_art BETWEEN " & lcParametro1Desde) lcComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta) lcComandoSeleccionar.AppendLine(" AND entregas.cod_cli BETWEEN " & lcParametro2Desde) lcComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta) lcComandoSeleccionar.AppendLine(" AND entregas.cod_ven BETWEEN " & lcParametro3Desde) lcComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta) lcComandoSeleccionar.AppendLine(" AND articulos.cod_dep BETWEEN " & lcParametro4Desde) lcComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta) lcComandoSeleccionar.AppendLine(" AND articulos.cod_tip BETWEEN " & lcParametro5Desde) lcComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta) lcComandoSeleccionar.AppendLine(" AND entregas.status IN (" & lcParametro6Desde & ")") lcComandoSeleccionar.AppendLine(" AND entregas.cod_rev BETWEEN " & lcParametro7Desde) lcComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta) lcComandoSeleccionar.AppendLine(" SELECT ") lcComandoSeleccionar.AppendLine(" ROW_NUMBER() OVER(PARTITION BY cod_cli ORDER BY cod_cli, nom_cli, AÑO, num_mes ASC) AS 'Renglon', ") lcComandoSeleccionar.AppendLine(" cod_cli, ") lcComandoSeleccionar.AppendLine(" num_mes, ") lcComandoSeleccionar.AppendLine(" nom_cli, ") lcComandoSeleccionar.AppendLine(" AÑO, ") lcComandoSeleccionar.AppendLine(" MES, ") lcComandoSeleccionar.AppendLine(" SUM(cant) as cant_art1, ") lcComandoSeleccionar.AppendLine(" SUM(monto) as mon_net, ") lcComandoSeleccionar.AppendLine(" (SUM(monto))/30 as mon_dia, ") lcComandoSeleccionar.AppendLine(" (SUM(cant))/30 as cant_dia ") lcComandoSeleccionar.AppendLine(" FROM #temporal ") lcComandoSeleccionar.AppendLine("GROUP BY cod_cli, nom_cli, AÑO, num_mes, MES") lcComandoSeleccionar.AppendLine("ORDER BY " & lcOrdenamiento) Dim loServicios As New cusDatos.goDatos Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(lcComandoSeleccionar.ToString, "curReportes") loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rTNotasEntregas_cAñoMes", laDatosReporte) Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvrTNotasEntregas_cAñoMes.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 '-------------------------------------------------------------------------------------------' ' YJP: 21/05/09: Codigo inicial '-------------------------------------------------------------------------------------------'
kodeitsolutions/ef-reports
rTNotasEntregas_cAñoMes.aspx.vb
Visual Basic
mit
9,003
 Imports System.Runtime.InteropServices Namespace Monitor ''' <summary> ''' 监视器操作 ''' </summary> Public Class Monitor ''' <summary> ''' 获取指定句柄窗口所在的监视器句柄 ''' </summary> ''' <param name="hWnd">窗口句柄</param> ''' <param name="flag">监视器识别类型</param> ''' <returns></returns> Public Shared Function MonitorFromWindow(ByVal hWnd As System.IntPtr, ByVal flag As MONITOR_DEFAULTTO) As System.IntPtr Return Win32API.MonitorFromWindow(hWnd, flag) End Function ''' <summary> ''' 设置窗口为最大化 ''' </summary> ''' <param name="hWnd">窗口句柄</param> ''' <param name="lParam"></param> Public Shared Sub SetWindowToMax(ByVal hWnd As System.IntPtr, ByVal lParam As System.IntPtr) Dim mmi As Structures.Window.MINMAXINFO = Marshal.PtrToStructure(lParam, GetType(Structures.Window.MINMAXINFO)) ' 获取窗口所在位置的监视器信息 Dim targetScreen As System.Windows.Forms.Screen = System.Windows.Forms.Screen.FromHandle(hWnd) With mmi ' 设置窗口坐标 .ptMaxPosition.X = Math.Abs(targetScreen.WorkingArea.Left - targetScreen.Bounds.Left) .ptMaxPosition.Y = Math.Abs(targetScreen.WorkingArea.Top - targetScreen.Bounds.Top) ' 设置窗口尺寸 .ptMaxSize.X = targetScreen.WorkingArea.Width .ptMaxSize.Y = targetScreen.WorkingArea.Height ' 设置拖拽尺寸。这个必须要设置。即最大只能拖拽到全屏尺寸大小。 .ptMaxTrackSize.X = .ptMaxSize.X .ptMaxTrackSize.Y = .ptMaxSize.Y End With '' 获取最近的监视器句柄 'Dim hMonitor As System.IntPtr = MonitorFromWindow(hWnd, MONITOR_DEFAULTTO.MONITOR_DEFAULTTONEAREST) 'If (hMonitor <> System.IntPtr.Zero) Then ' Console.WriteLine(hMonitor) 'Else ' Console.WriteLine("TT") 'End If '' 获取监视器信息 'Dim info As Structures.Monitors.MONITORINFO = New Structures.Monitors.MONITORINFO() 'info.cbSize = Marshal.SizeOf(info.GetType()) 'Dim r As Boolean = Win32API.GetMonitorInfo(hMonitor, info) 'Dim rcWorkArea As Structures.Rectangle.RECT = info.rcWork 'Dim rcMonitorArea As Structures.Rectangle.RECT = info.rcMonitor 'mmi.ptMaxPosition.X = Math.Abs(rcWorkArea.left - rcMonitorArea.left) 'mmi.ptMaxPosition.Y = Math.Abs(rcWorkArea.top - rcMonitorArea.top) 'mmi.ptMaxSize.X = Math.Abs(rcWorkArea.right - rcWorkArea.left) 'mmi.ptMaxSize.Y = Math.Abs(rcWorkArea.bottom - rcWorkArea.top) Marshal.StructureToPtr(mmi, lParam, True) End Sub End Class End Namespace
sugartomato/AllProjects
ZS.Common/ZS.Common/Monitor/Monitor.vb
Visual Basic
apache-2.0
3,001
'*******************************************************************************************' ' ' ' 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.IO Imports System.Net Imports Newtonsoft.Json.Linq ' Please NOTE: In this sample we're assuming Cloud Api Server is hosted at "https://localhost". ' If it's not then please replace this with with your hosting url. Module Module1 ' Source PDF file const SourceFile as String = ".\sample.pdf" ' Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'. const Pages as String = "" ' PDF document password. Leave empty for unprotected documents. const Password as String = "" Sub Main() ' Create standard .NET web client instance Dim webClient As WebClient = New WebClient() ' 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE. ' * If you already have the direct file URL, skip to the step 3. ' Prepare URL for `Get Presigned URL` API call Dim query As string = Uri.EscapeUriString(string.Format( "https://localhost/file/upload/get-presigned-url?contenttype=application/octet-stream&name={0}", Path.GetFileName(SourceFile))) Try ' Execute request Dim response As string = webClient.DownloadString(query) ' Parse JSON response Dim json As JObject = JObject.Parse(response) If json("error").ToObject(Of Boolean) = False Then ' Get URL to use for the file upload Dim uploadUrl As string = json("presignedUrl").ToString() ' Get URL of uploaded file to use with later API calls Dim uploadedFileUrl As string = json("url").ToString() ' 2. UPLOAD THE FILE TO CLOUD. webClient.Headers.Add("content-type", "application/octet-stream") webClient.UploadFile(uploadUrl, "PUT", SourceFile) ' You can use UploadData() instead if your file is byte array or Stream ' 3. CONVERT UPLOADED PDF FILE TO JPEG ' Prepare URL for `PDF To JPEG` API call query = Uri.EscapeUriString(String.Format( "https://localhost/pdf/convert/to/jpg?password={0}&pages={1}&url={2}", Password, Pages, uploadedFileUrl)) ' Execute request response = webClient.DownloadString(query) ' Parse JSON response json = JObject.Parse(response) If json("error").ToObject(Of Boolean) = False Then ' Download generated JPEG files Dim page As Integer = 1 For Each token As JToken In json("urls") Dim resultFileUrl As string = token.ToString() Dim localFileName As String = String.Format(".\page{0}.jpg", page) webClient.DownloadFile(resultFileUrl, localFileName) Console.WriteLine("Downloaded ""{0}"".", localFileName) page = page + 1 Next Else Console.WriteLine(json("message").ToString()) End If End If Catch ex As WebException Console.WriteLine(ex.ToString()) End Try webClient.Dispose() Console.WriteLine() Console.WriteLine("Press any key...") Console.ReadKey() End Sub End Module
bytescout/ByteScout-SDK-SourceCode
Cloud API Server/PDF To Image API/VB.NET/Convert PDF To JPEG From Uploaded File/Module1.vb
Visual Basic
apache-2.0
3,885
' Copyright 2018 Google LLC ' ' 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 Google.Api.Ads.AdWords.Lib Imports Google.Api.Ads.AdWords.v201809 Imports DayOfWeek = Google.Api.Ads.AdWords.v201809.DayOfWeek Namespace Google.Api.Ads.AdWords.Examples.VB.v201809 ''' <summary> ''' This code example adds sitelinks to a campaign. To create a campaign, ''' run AddCampaign.vb. ''' </summary> Public Class AddSitelinks 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 AddSitelinks Console.WriteLine(codeExample.Description) Try Dim campaignId As Long = Long.Parse("INSERT_CAMPAIGN_ID_HERE") codeExample.Run(New AdWordsUser, campaignId) Catch e As Exception Console.WriteLine("An exception occurred while running this code example. {0}", ExampleUtilities.FormatException(e)) 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 adds sitelinks to a campaign. To create a campaign, run " & "AddCampaign.vb." End Get End Property ''' <summary> ''' Runs the code example. ''' </summary> ''' <param name="user">The AdWords user.</param> ''' <param name="campaignId">Id of the campaign with which sitelinks are associated. ''' </param> Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long) Using campaignExtensionSettingService As CampaignExtensionSettingService = DirectCast(user.GetService(AdWordsService.v201809.CampaignExtensionSettingService), CampaignExtensionSettingService) Dim customerService As CustomerService = DirectCast(user.GetService(AdWordsService.v201809.CustomerService), CustomerService) ' Find the matching customer and its time zone. The getCustomers method ' will return a single Customer object corresponding to the session's ' clientCustomerId. Dim customer As Customer = customerService.getCustomers()(0) Console.WriteLine("Found customer ID {0:###-###-####} with time zone '{1}'.", customer.customerId, customer.dateTimeZone) Dim extensions As New List(Of ExtensionFeedItem) ' Create your sitelinks. Dim sitelink1 As New SitelinkFeedItem() sitelink1.sitelinkText = "Store Hours" sitelink1.sitelinkFinalUrls = New UrlList() sitelink1.sitelinkFinalUrls.urls = New String() _ {"http://www.example.com/storehours"} extensions.Add(sitelink1) Dim startOfThanksGiving As New DateTime(DateTime.Now.Year, 11, 20, 0, 0, 0) Dim endOfThanksGiving As New DateTime(DateTime.Now.Year, 11, 27, 23, 59, 59) ' Add check to make sure we don't create a sitelink with end date in the ' past. If DateTime.Now < endOfThanksGiving Then ' Show the Thanksgiving specials link only from 20 - 27 Nov. Dim sitelink2 As New SitelinkFeedItem() sitelink2.sitelinkText = "Thanksgiving Specials" sitelink2.sitelinkFinalUrls = New UrlList() sitelink2.sitelinkFinalUrls.urls = New String() _ {"http://www.example.com/thanksgiving"} sitelink2.startTime = String.Format("{0}1120 000000 {1}", DateTime.Now.Year, customer.dateTimeZone) sitelink2.endTime = String.Format("{0}1127 235959 {1}", DateTime.Now.Year, customer.dateTimeZone) ' Target this sitelink for United States only. See ' https://developers.google.com/adwords/api/docs/appendix/geotargeting ' for valid geolocation codes. sitelink2.geoTargeting = New Location() sitelink2.geoTargeting.id = 2840 ' Restrict targeting only to people physically within the United States. ' Otherwise, this could also show to people interested in the United States ' but not physically located there. Dim geoTargetingRestriction As New FeedItemGeoRestriction() geoTargetingRestriction.geoRestriction = GeoRestriction.LOCATION_OF_PRESENCE sitelink2.geoTargetingRestriction = geoTargetingRestriction extensions.Add(sitelink2) End If ' Show the wifi details primarily for high end mobile users. Dim sitelink3 As New SitelinkFeedItem() sitelink3.sitelinkText = "Wifi available" sitelink3.sitelinkFinalUrls = New UrlList() sitelink3.sitelinkFinalUrls.urls = New String() _ {"http://www.example.com/mobile/wifi"} sitelink3.devicePreference = New FeedItemDevicePreference() sitelink3.devicePreference.devicePreference = 30001 extensions.Add(sitelink3) ' Show the happy hours link only during Mon - Fri 6PM to 9PM. Dim sitelink4 As New SitelinkFeedItem() sitelink4.sitelinkText = "Happy hours" sitelink4.sitelinkFinalUrls = New UrlList() sitelink4.sitelinkFinalUrls.urls = New String() _ {"http://www.example.com/happyhours"} extensions.Add(sitelink4) Dim schedule1 As New FeedItemSchedule() schedule1.dayOfWeek = DayOfWeek.MONDAY schedule1.startHour = 18 schedule1.startMinute = MinuteOfHour.ZERO schedule1.endHour = 21 schedule1.endMinute = MinuteOfHour.ZERO Dim schedule2 As New FeedItemSchedule() schedule2.dayOfWeek = DayOfWeek.TUESDAY schedule2.startHour = 18 schedule2.startMinute = MinuteOfHour.ZERO schedule2.endHour = 21 schedule2.endMinute = MinuteOfHour.ZERO Dim schedule3 As New FeedItemSchedule() schedule3.dayOfWeek = DayOfWeek.WEDNESDAY schedule3.startHour = 18 schedule3.startMinute = MinuteOfHour.ZERO schedule3.endHour = 21 schedule3.endMinute = MinuteOfHour.ZERO Dim schedule4 As New FeedItemSchedule() schedule4.dayOfWeek = DayOfWeek.THURSDAY schedule4.startHour = 18 schedule4.startMinute = MinuteOfHour.ZERO schedule4.endHour = 21 schedule4.endMinute = MinuteOfHour.ZERO Dim schedule5 As New FeedItemSchedule() schedule5.dayOfWeek = DayOfWeek.FRIDAY schedule5.startHour = 18 schedule5.startMinute = MinuteOfHour.ZERO schedule5.endHour = 21 schedule5.endMinute = MinuteOfHour.ZERO sitelink4.scheduling = New FeedItemSchedule() { _ schedule1, schedule2, schedule3, schedule4, schedule5 } ' Create your campaign extension settings. This associates the sitelinks ' to your campaign. Dim campaignExtensionSetting As New CampaignExtensionSetting() campaignExtensionSetting.campaignId = campaignId campaignExtensionSetting.extensionType = FeedType.SITELINK campaignExtensionSetting.extensionSetting = New ExtensionSetting() campaignExtensionSetting.extensionSetting.extensions = extensions.ToArray Dim extensionOperation As New CampaignExtensionSettingOperation() extensionOperation.operand = campaignExtensionSetting extensionOperation.operator = [Operator].ADD Try ' Add the extensions. Dim retVal As CampaignExtensionSettingReturnValue = campaignExtensionSettingService.mutate( New CampaignExtensionSettingOperation() _ {extensionOperation}) ' Display the results. If Not (retVal.value Is Nothing) AndAlso retVal.value.Length > 0 Then Dim newExtensionSetting As CampaignExtensionSetting = retVal.value(0) Console.WriteLine( "Extension setting with type = {0} was added to campaign ID {1}.", newExtensionSetting.extensionType, newExtensionSetting.campaignId) Else Console.WriteLine("No extension settings were created.") End If Catch e As Exception Throw New System.ApplicationException("Failed to create extension settings.", e) End Try End Using End Sub End Class End Namespace
googleads/googleads-dotnet-lib
examples/AdWords/Vb/v201809/Extensions/AddSitelinks.vb
Visual Basic
apache-2.0
10,548
'------------------------------------------------------------------------------ ' <auto-generated> ' 此代码由工具生成。 ' 运行时版本:4.0.30319.34209 ' ' 对此文件的更改可能会导致不正确的行为,并且如果 ' 重新生成代码,这些更改将会丢失。 ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace My.Resources '此类是由 StronglyTypedResourceBuilder '类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 '若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen '(以 /str 作为命令选项),或重新生成 VS 项目。 '''<summary> ''' 一个强类型的资源类,用于查找本地化的字符串等。 '''</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> ''' 返回此类使用的缓存的 ResourceManager 实例。 '''</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("VBConsumerTests.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' 使用此强类型资源类,为所有资源查找 ''' 重写当前线程的 CurrentUICulture 属性。 '''</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
longqinsi/ImmutableObjectGraph-Net40
VBConsumerTests/My Project/Resources.Designer.vb
Visual Basic
apache-2.0
2,733
' 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.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics.OverloadResolutionTestHelpers Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Namespace OverloadResolutionTestHelpers Friend Module Extensions Public Function ResolveMethodOverloading( instanceMethods As ImmutableArray(Of MethodSymbol), extensionMethods As ImmutableArray(Of MethodSymbol), typeArguments As ImmutableArray(Of TypeSymbol), arguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), binder As Binder, lateBindingIsAllowed As Boolean, Optional includeEliminatedCandidates As Boolean = False ) As OverloadResolution.OverloadResolutionResult Dim methods As ImmutableArray(Of MethodSymbol) If instanceMethods.IsDefaultOrEmpty Then methods = extensionMethods ElseIf extensionMethods.IsDefaultOrEmpty Then methods = instanceMethods Else methods = instanceMethods.Concat(extensionMethods) End If Dim methodGroup = New BoundMethodGroup(VisualBasicSyntaxTree.Dummy.GetRoot(Nothing), If(typeArguments.IsDefaultOrEmpty, Nothing, New BoundTypeArguments(VisualBasicSyntaxTree.Dummy.GetRoot(Nothing), typeArguments)), methods, LookupResultKind.Good, Nothing, QualificationKind.Unqualified) Return OverloadResolution.MethodInvocationOverloadResolution( methodGroup, arguments, argumentNames, binder, includeEliminatedCandidates:=includeEliminatedCandidates, lateBindingIsAllowed:=lateBindingIsAllowed, callerInfoOpt:=Nothing, useSiteDiagnostics:=Nothing) End Function End Module End Namespace Public Class OverloadResolutionTests Inherits BasicTestBase <Fact> Public Sub BasicTests() Dim optionStrictOn = <file> Option Strict On Class OptionStrictOn Shared Sub Context() End Sub End Class </file> Dim optionStrictOff = <file> Option Strict Off Class OptionStrictOff Shared Sub Context() End Sub End Class </file> Dim optionStrictOnTree = VisualBasicSyntaxTree.ParseText(optionStrictOn.Value) Dim optionStrictOffTree = VisualBasicSyntaxTree.ParseText(optionStrictOff.Value) Dim c1 = VisualBasicCompilation.Create("Test1", syntaxTrees:={VisualBasicSyntaxTree.ParseText(My.Resources.Resource.OverloadResolutionTestSource), optionStrictOnTree, optionStrictOffTree}, references:={MscorlibRef, SystemCoreRef}) Dim sourceModule = DirectCast(c1.Assembly.Modules(0), SourceModuleSymbol) Dim optionStrictOnContext = DirectCast(sourceModule.GlobalNamespace.GetTypeMembers("OptionStrictOn").Single().GetMembers("Context").Single(), SourceMethodSymbol) Dim optionStrictOffContext = DirectCast(sourceModule.GlobalNamespace.GetTypeMembers("OptionStrictOff").Single().GetMembers("Context").Single(), SourceMethodSymbol) Dim optionStrictOnBinder = BinderBuilder.CreateBinderForMethodBody(sourceModule, optionStrictOnTree, optionStrictOnContext) Dim optionStrictOffBinder = BinderBuilder.CreateBinderForMethodBody(sourceModule, optionStrictOffTree, optionStrictOffContext) Dim TestClass1 = c1.Assembly.GlobalNamespace.GetTypeMembers("TestClass1").Single() Dim TestClass1_M1 = TestClass1.GetMembers("M1").OfType(Of MethodSymbol)().Single() Dim TestClass1_M2 = TestClass1.GetMembers("M2").OfType(Of MethodSymbol)().Single() Dim TestClass1_M3 = TestClass1.GetMembers("M3").OfType(Of MethodSymbol)().Single() Dim TestClass1_M4 = TestClass1.GetMembers("M4").OfType(Of MethodSymbol)().Single() Dim TestClass1_M5 = TestClass1.GetMembers("M5").OfType(Of MethodSymbol)().Single() Dim TestClass1_M6 = TestClass1.GetMembers("M6").OfType(Of MethodSymbol)().Single() Dim TestClass1_M7 = TestClass1.GetMembers("M7").OfType(Of MethodSymbol)().Single() Dim TestClass1_M8 = TestClass1.GetMembers("M8").OfType(Of MethodSymbol)().Single() Dim TestClass1_M9 = TestClass1.GetMembers("M9").OfType(Of MethodSymbol)().Single() Dim TestClass1_M10 = TestClass1.GetMembers("M10").OfType(Of MethodSymbol)().Single() Dim TestClass1_M11 = TestClass1.GetMembers("M11").OfType(Of MethodSymbol)().Single() Dim TestClass1_M12 = TestClass1.GetMembers("M12").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_M13 = TestClass1.GetMembers("M13").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_M14 = TestClass1.GetMembers("M14").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_M15 = TestClass1.GetMembers("M15").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_M16 = TestClass1.GetMembers("M16").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_M17 = TestClass1.GetMembers("M17").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_M18 = TestClass1.GetMembers("M18").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_M19 = TestClass1.GetMembers("M19").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_M20 = TestClass1.GetMembers("M20").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_M21 = TestClass1.GetMembers("M21").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_M22 = TestClass1.GetMembers("M22").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_M23 = TestClass1.GetMembers("M23").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_M24 = TestClass1.GetMembers("M24").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_M25 = TestClass1.GetMembers("M25").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_M26 = TestClass1.GetMembers("M26").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_M27 = TestClass1.GetMembers("M27").OfType(Of MethodSymbol)().Single() Dim TestClass1_g = TestClass1.GetMembers("g").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_SM = TestClass1.GetMembers("SM").OfType(Of MethodSymbol)().Single() Dim TestClass1_SM1 = TestClass1.GetMembers("SM1").OfType(Of MethodSymbol)().Single() Dim TestClass1_ShortField = TestClass1.GetMembers("ShortField").OfType(Of FieldSymbol)().Single() Dim TestClass1_DoubleField = TestClass1.GetMembers("DoubleField").OfType(Of FieldSymbol)().Single() Dim TestClass1_ObjectField = TestClass1.GetMembers("ObjectField").OfType(Of FieldSymbol)().Single() Dim base = c1.Assembly.GlobalNamespace.GetTypeMembers("Base").Single() Dim baseExt = c1.Assembly.GlobalNamespace.GetTypeMembers("BaseExt").Single() Dim derived = c1.Assembly.GlobalNamespace.GetTypeMembers("Derived").Single() Dim derivedExt = c1.Assembly.GlobalNamespace.GetTypeMembers("DerivedExt").Single() Dim ext = c1.Assembly.GlobalNamespace.GetTypeMembers("Ext").Single() Dim ext1 = c1.Assembly.GlobalNamespace.GetTypeMembers("Ext1").Single() Dim base_M1 = base.GetMembers("M1").OfType(Of MethodSymbol)().Single() Dim base_M2 = base.GetMembers("M2").OfType(Of MethodSymbol)().Single() Dim base_M3 = base.GetMembers("M3").OfType(Of MethodSymbol)().Single() Dim base_M4 = base.GetMembers("M4").OfType(Of MethodSymbol)().Single() Dim base_M5 = base.GetMembers("M5").OfType(Of MethodSymbol)().Single() Dim base_M6 = base.GetMembers("M6").OfType(Of MethodSymbol)().Single() Dim base_M7 = base.GetMembers("M7").OfType(Of MethodSymbol)().Single() Dim base_M8 = base.GetMembers("M8").OfType(Of MethodSymbol)().Single() Dim base_M9 = base.GetMembers("M9").OfType(Of MethodSymbol)().Single() Dim base_M10 = baseExt.GetMembers("M10").OfType(Of MethodSymbol)().Single() Dim derived_M1 = derived.GetMembers("M1").OfType(Of MethodSymbol)().Single() Dim derived_M2 = derived.GetMembers("M2").OfType(Of MethodSymbol)().Single() Dim derived_M3 = derived.GetMembers("M3").OfType(Of MethodSymbol)().Single() Dim derived_M4 = derived.GetMembers("M4").OfType(Of MethodSymbol)().Single() Dim derived_M5 = derived.GetMembers("M5").OfType(Of MethodSymbol)().Single() Dim derived_M6 = derived.GetMembers("M6").OfType(Of MethodSymbol)().Single() Dim derived_M7 = derived.GetMembers("M7").OfType(Of MethodSymbol)().Single() Dim derived_M8 = derived.GetMembers("M8").OfType(Of MethodSymbol)().Single() Dim derived_M9 = derived.GetMembers("M9").OfType(Of MethodSymbol)().Single() Dim derived_M10 = derivedExt.GetMembers("M10").OfType(Of MethodSymbol)().Single() Dim derived_M11 = derivedExt.GetMembers("M11").OfType(Of MethodSymbol)().Single() Dim derived_M12 = derivedExt.GetMembers("M12").OfType(Of MethodSymbol)().Single() Dim ext_M11 = ext.GetMembers("M11").OfType(Of MethodSymbol)().Single() Dim ext_M12 = ext.GetMembers("M12").OfType(Of MethodSymbol)().Single() Dim ext_M13 = ext.GetMembers("M13").OfType(Of MethodSymbol)().ToArray() Dim ext_M14 = ext.GetMembers("M14").OfType(Of MethodSymbol)().Single() Dim ext_M15 = ext.GetMembers("M15").OfType(Of MethodSymbol)().Single() Dim ext_SM = ext.GetMembers("SM").OfType(Of MethodSymbol)().Single() Dim ext_SM1 = ext.GetMembers("SM1").OfType(Of MethodSymbol)().ToArray() Dim ext1_M14 = ext1.GetMembers("M14").OfType(Of MethodSymbol)().Single() Dim TestClass2 = c1.Assembly.GlobalNamespace.GetTypeMembers("TestClass2").Single() Dim TestClass2OfInteger = TestClass2.Construct(c1.GetSpecialType(System_Int32)) Dim TestClass2OfInteger_S1 = TestClass2OfInteger.GetMembers("S1").OfType(Of MethodSymbol)().ToArray() Dim TestClass2OfInteger_S2 = TestClass2OfInteger.GetMembers("S2").OfType(Of MethodSymbol)().ToArray() Dim TestClass2OfInteger_S3 = TestClass2OfInteger.GetMembers("S3").OfType(Of MethodSymbol)().ToArray() Dim TestClass2OfInteger_S4 = TestClass2OfInteger.GetMembers("S4").OfType(Of MethodSymbol)().ToArray() Dim TestClass2OfInteger_S5 = TestClass2OfInteger.GetMembers("S5").OfType(Of MethodSymbol)().ToArray() Dim TestClass2OfInteger_S6 = TestClass2OfInteger.GetMembers("S6").OfType(Of MethodSymbol)().ToArray() Dim _syntaxNode = optionStrictOffTree.GetVisualBasicRoot(Nothing) Dim [nothing] As BoundExpression = New BoundLiteral(_syntaxNode, ConstantValue.Nothing, Nothing) Dim intZero As BoundExpression = New BoundLiteral(_syntaxNode, ConstantValue.Create(0I), c1.GetSpecialType(System_Int32)) Dim longZero As BoundExpression = New BoundLiteral(_syntaxNode, ConstantValue.Create(0L), c1.GetSpecialType(System_Int64)) Dim unsignedOne As BoundExpression = New BoundLiteral(_syntaxNode, ConstantValue.Create(1UI), c1.GetSpecialType(System_UInt32)) Dim longConst As BoundExpression = New BoundConversion(_syntaxNode, New BoundLiteral(_syntaxNode, ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, ConstantValue.Create(-1L), c1.GetSpecialType(System_Int64), Nothing) Dim intVal As BoundExpression = New BoundUnaryOperator(_syntaxNode, UnaryOperatorKind.Minus, intZero, False, intZero.Type) Dim intArray As BoundExpression = New BoundRValuePlaceholder(_syntaxNode, c1.CreateArrayTypeSymbol(intZero.Type)) Dim TestClass1Val As BoundExpression = New BoundRValuePlaceholder(_syntaxNode, TestClass1) Dim omitted As BoundExpression = New BoundOmittedArgument(_syntaxNode, Nothing) Dim doubleConst As BoundExpression = New BoundConversion(_syntaxNode, New BoundLiteral(_syntaxNode, ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, ConstantValue.Create(0.0R), c1.GetSpecialType(System_Double), Nothing) Dim doubleVal As BoundExpression = New BoundUnaryOperator(_syntaxNode, UnaryOperatorKind.Minus, doubleConst, False, doubleConst.Type) Dim shortVal As BoundExpression = New BoundRValuePlaceholder(_syntaxNode, c1.GetSpecialType(System_Int16)) Dim ushortVal As BoundExpression = New BoundRValuePlaceholder(_syntaxNode, c1.GetSpecialType(System_UInt16)) Dim objectVal As BoundExpression = New BoundRValuePlaceholder(_syntaxNode, c1.GetSpecialType(System_Object)) Dim objectArray As BoundExpression = New BoundRValuePlaceholder(_syntaxNode, c1.CreateArrayTypeSymbol(objectVal.Type)) Dim shortField As BoundExpression = New BoundFieldAccess(_syntaxNode, Nothing, TestClass1_ShortField, True, TestClass1_ShortField.Type) Dim doubleField As BoundExpression = New BoundFieldAccess(_syntaxNode, Nothing, TestClass1_DoubleField, True, TestClass1_DoubleField.Type) Dim objectField As BoundExpression = New BoundFieldAccess(_syntaxNode, Nothing, TestClass1_ObjectField, True, TestClass1_ObjectField.Type) Dim stringVal As BoundExpression = New BoundRValuePlaceholder(_syntaxNode, c1.GetSpecialType(System_String)) Dim result As OverloadResolution.OverloadResolutionResult 'TestClass1.M1() result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={TestClass1_M1}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:=Nothing, argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M1, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'TestClass1.M1(Of TestClass1)() 'error BC32045: 'Public Shared Sub M1()' has no type parameters and so cannot have type arguments. result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={TestClass1_M1}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=(New TypeSymbol() {TestClass1}).AsImmutableOrNull(), arguments:=Nothing, argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.BadGenericArity, result.Candidates(0).State) Assert.Same(TestClass1_M1, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'TestClass1.M1(Nothing) 'error BC30057: Too many arguments to 'Public Shared Sub M1()'. result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M1)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={[nothing]}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentCountMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M1, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'TestClass1.M2() 'error BC32050: Type parameter 'T' for 'Public Shared Sub M2(Of T)()' cannot be inferred. result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M2)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:=Nothing, argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.TypeInferenceFailed, result.Candidates(0).State) Assert.Same(TestClass1_M2, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'TestClass1.M2(Of TestClass1)() result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M2)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=(New TypeSymbol() {TestClass1}).AsImmutableOrNull(), arguments:=Nothing, argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Equal(TestClass1_M2.Construct((New TypeSymbol() {TestClass1}).AsImmutableOrNull()), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'TestClass1.M3() result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M3)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:=Nothing, argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.True(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Equal(TestClass1_M3, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'TestClass1.M3(intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M3)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Equal(TestClass1_M3, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.True(result.Candidates(1).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Equal(TestClass1_M3, result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'TestClass1.M3(intArray) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M3)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intArray}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Equal(TestClass1_M3, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.True(result.Candidates(1).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(1).State) Assert.Equal(TestClass1_M3, result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'TestClass1.M3(Nothing) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M3)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={[nothing]}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Equal(TestClass1_M3, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.True(result.Candidates(1).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(1).State) Assert.Equal(TestClass1_M3, result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'TestClass1.M4(intVal, TestClass1Val) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M4)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, TestClass1Val}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M4, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) Assert.True(result.Candidates(0).ArgsToParamsOpt.IsDefault) 'error BC30311: Value of type 'TestClass1' cannot be converted to 'Integer'. 'TestClass1.M4(TestClass1Val, TestClass1Val) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M4)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={TestClass1Val, TestClass1Val}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M4, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'error BC30311: Value of type 'Integer' cannot be converted to 'TestClass1'. 'TestClass1.M4(intVal, intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M4)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M4, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'TestClass1.M4(intVal, y:=TestClass1Val) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M4)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, TestClass1Val}.AsImmutableOrNull(), argumentNames:={Nothing, "y"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M4, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) Assert.True(result.Candidates(0).ArgsToParamsOpt.SequenceEqual({0, 1}.AsImmutableOrNull())) 'TestClass1.M4(X:=intVal, y:=TestClass1Val) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M4)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, TestClass1Val}.AsImmutableOrNull(), argumentNames:={"X", "y"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M4, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) Assert.True(result.Candidates(0).ArgsToParamsOpt.SequenceEqual({0, 1}.AsImmutableOrNull())) 'TestClass1.M4(y:=TestClass1Val, x:=intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M4)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={TestClass1Val, intVal}.AsImmutableOrNull(), argumentNames:={"y", "x"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M4, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) Assert.True(result.Candidates(0).ArgsToParamsOpt.SequenceEqual({1, 0}.AsImmutableOrNull())) 'error BC30311: Value of type 'Integer' cannot be converted to 'TestClass1'. 'TestClass1.M4(y:=intVal, x:=intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M4)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:={"y", "x"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M4, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) Assert.True(result.Candidates(0).ArgsToParamsOpt.SequenceEqual({1, 0}.AsImmutableOrNull())) 'error BC30455: Argument not specified for parameter 'y' of 'Public Shared Sub M4(x As Integer, y As TestClass1)'. 'error BC30274: Parameter 'x' of 'Public Shared Sub M4(x As Integer, y As TestClass1)' already has a matching argument. 'TestClass1.M4(intVal, x:=intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M4)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:={Nothing, "x"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M4, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'error BC30455: Argument not specified for parameter 'y' of 'Public Shared Sub M4(x As Integer, y As TestClass1)'. 'error BC32021: Parameter 'x' in 'Public Shared Sub M4(x As Integer, y As TestClass1)' already has a matching omitted argument. 'TestClass1.M4(, x:=intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M4)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={omitted, intVal}.AsImmutableOrNull(), argumentNames:={Nothing, "x"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M4, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'error BC30455: Argument not specified for parameter 'y' of 'Public Shared Sub M4(x As Integer, y As TestClass1)'. 'error BC30274: Parameter 'x' of 'Public Shared Sub M4(x As Integer, y As TestClass1)' already has a matching argument. 'TestClass1.M4(x:=intVal, x:=intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M4)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:={"x", "x"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M4, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'error BC30455: Argument not specified for parameter 'x' of 'Public Shared Sub M4(x As Integer, y As TestClass1)'. 'error BC30272: 'z' is not a parameter of 'Public Shared Sub M4(x As Integer, y As TestClass1)'. 'TestClass1.M4(z:=intVal, y:=TestClass1Val) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M4)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, TestClass1Val}.AsImmutableOrNull(), argumentNames:={"z", "y"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M4, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'error BC30455: Argument not specified for parameter 'y' of 'Public Shared Sub M4(x As Integer, y As TestClass1)'. 'error BC30272: 'z' is not a parameter of 'Public Shared Sub M4(x As Integer, y As TestClass1)'. 'TestClass1.M4(z:=TestClass1Val, x:=intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M4)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={TestClass1Val, intVal}.AsImmutableOrNull(), argumentNames:={"z", "x"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M4, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'error BC30455: Argument not specified for parameter 'x' of 'Public Shared Sub M4(x As Integer, y As TestClass1)'. 'TestClass1.M4(, TestClass1Val) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M4)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={omitted, TestClass1Val}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M4, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'error BC30455: Argument not specified for parameter 'y' of 'Public Shared Sub M4(x As Integer, y As TestClass1)'. 'TestClass1.M4(intVal, ) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M4)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, omitted}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M4, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'error BC30587: Named argument cannot match a ParamArray parameter. 'TestClass1.M3(x:=intArray) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M3)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intArray}.AsImmutableOrNull(), argumentNames:={"x"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Same(TestClass1_M3, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(1).State) Assert.True(result.Candidates(1).IsExpandedParamArrayForm) Assert.Same(TestClass1_M3, result.Candidates(1).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'error BC30587: Named argument cannot match a ParamArray parameter. 'TestClass1.M3(x:=intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M3)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:={"x"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Same(TestClass1_M3, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(1).State) Assert.True(result.Candidates(1).IsExpandedParamArrayForm) Assert.Same(TestClass1_M3, result.Candidates(1).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'error BC30588: Omitted argument cannot match a ParamArray parameter. 'TestClass1.M5(intVal, ) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M5)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, omitted}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Same(TestClass1_M5, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(1).State) Assert.True(result.Candidates(1).IsExpandedParamArrayForm) Assert.Same(TestClass1_M5, result.Candidates(1).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'error BC30241: Named argument expected. 'TestClass1.M4(x:=intVal, TestClass1Val) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M4)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, TestClass1Val}.AsImmutableOrNull(), argumentNames:={"x", Nothing}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M4, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'error BC30057: Too many arguments to 'Public Shared Sub M2(Of T)()'. 'TestClass1.M2(Of TestClass1)(intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M2)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=(New TypeSymbol() {TestClass1}).AsImmutableOrNull(), arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentCountMismatch, result.Candidates(0).State) Assert.Equal(TestClass1_M2.Construct((New TypeSymbol() {TestClass1}).AsImmutableOrNull()), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'TestClass1.M6(shortVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M6)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={shortVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.False(result.Candidates(0).RequiresNarrowingConversion) Assert.False(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.False(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'error BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Single'. 'TestClass1.M6(doubleVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M6)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={doubleVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M6)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={doubleVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) Assert.False(result.BestResult.HasValue) 'TestClass1.M6(doubleConst) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M6)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={doubleConst}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.False(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'. 'TestClass1.M6(objectVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M6)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.False(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M6)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) Assert.False(result.BestResult.HasValue) 'TestClass1.M7(shortVal, shortVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={shortVal, shortVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.False(result.Candidates(0).RequiresNarrowingConversion) Assert.False(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.False(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'error BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Single'. 'TestClass1.M7(doubleVal, shortVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={doubleVal, shortVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={doubleVal, shortVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'error BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Single'. 'TestClass1.M7(shortVal, doubleVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={shortVal, doubleVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={shortVal, doubleVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'error BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Single'. 'TestClass1.M7(doubleVal, doubleVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={doubleVal, doubleVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={doubleVal, doubleVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'TestClass1.M7(doubleConst, shortVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={doubleConst, shortVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.False(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'TestClass1.M7(shortVal, doubleConst) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={shortVal, doubleConst}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.False(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'TestClass1.M7(doubleConst, doubleConst) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={doubleConst, doubleConst}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.False(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Single'. 'TestClass1.M7(objectVal, shortVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal, shortVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.False(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal, shortVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Single'. 'TestClass1.M7(shortVal, objectVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={shortVal, objectVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.False(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={shortVal, objectVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Single'. 'TestClass1.M7(objectVal, objectVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal, objectVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.False(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Single'. 'error BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Single'. 'TestClass1.M7(objectVal, doubleVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal, doubleVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'error BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Single'. 'TestClass1.M7(doubleConst, doubleVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={doubleConst, doubleVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Single'. 'TestClass1.M7(objectVal, doubleConst) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal, doubleConst}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'error BC32029: Option Strict On disallows narrowing from type 'Double' to type 'Short' in copying the value of 'ByRef' parameter 'x' back to the matching argument. 'TestClass1.M8(TestClass1.ShortField) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M8)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={shortField}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'TestClass1.M8((shortVal)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M8)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={shortVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.False(result.Candidates(0).RequiresNarrowingConversion) Assert.False(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.False(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'error BC32029: Option Strict On disallows narrowing from type 'Object' to type 'Short' in copying the value of 'ByRef' parameter 'x' back to the matching argument. 'TestClass1.M9(TestClass1.ShortField) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M9)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={shortField}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.False(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'TestClass1.M9((shortVal)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M9)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={shortVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.False(result.Candidates(0).RequiresNarrowingConversion) Assert.False(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.False(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'TestClass1.M10(doubleConst) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M10)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={doubleConst}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.False(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'error BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Single'. 'TestClass1.M10(TestClass1.DoubleField) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M10)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={doubleField}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Single'. 'TestClass1.M10(TestClass1.ObjectField) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M10)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectField}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.False(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'error BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Single'. 'TestClass1.M10((doubleVal)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M10)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={doubleVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'Option Strict On disallows implicit conversions from 'Object' to 'Single'. 'TestClass1.M10((objectVal)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M10)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.False(result.Candidates(0).RequiresNarrowingNotFromObject) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) 'TestClass1.M11(objectVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M11)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.True(result.Candidates(1).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'TestClass1.M11(objectArray) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M11)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectArray}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(1).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(1).State) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'TestClass1.M12(intVal, intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M12(0)), (TestClass1_M12(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M12(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M12(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M12(0)), (TestClass1_M12(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:={Nothing, "y"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M12(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M12(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'TestClass1.M13(intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M13(0)), (TestClass1_M13(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.True(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M13(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.True(result.Candidates(1).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentCountMismatch, result.Candidates(1).State) Assert.Same(TestClass1_M13(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M13(0)), (TestClass1_M13(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:={"a"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.True(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M13(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.True(result.Candidates(1).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentCountMismatch, result.Candidates(1).State) Assert.Same(TestClass1_M13(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'TestClass1.M13(intVal, intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M13(0)), (TestClass1_M13(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M13(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.True(result.Candidates(1).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M13(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M13(0)), (TestClass1_M13(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:={"a", "b"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(3, result.Candidates.Length) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M13(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.True(result.Candidates(1).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(1).State) Assert.Same(TestClass1_M13(0), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.True(result.Candidates(2).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(2).State) Assert.Same(TestClass1_M13(1), result.Candidates(2).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(2)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M13(1)), (TestClass1_M13(0))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.False(result.Candidates(1).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(1).State) Assert.Same(TestClass1_M13(0), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.True(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M13(1), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'TestClass1.M13(intVal, intVal, intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M13(0)), (TestClass1_M13(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M13(1), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.True(result.Candidates(1).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M13(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'Derived.M1(intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(derived_M1), (base_M1)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(base_M1, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(base_M1), (derived_M1)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(base_M1, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'Derived.M2(intVal, z:=stringVal) ' Should bind to Base.M2 result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(derived_M2), (base_M2)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, stringVal}.AsImmutableOrNull(), argumentNames:={Nothing, "z"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(derived_M2, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(base_M2, result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'Derived.M2(intVal, z:=stringVal) ' Should bind to Base.M2 result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(derived_M2), (base_M2)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, stringVal}.AsImmutableOrNull(), argumentNames:={Nothing, "z"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.RequiresNarrowing, result.Candidates(0).State) Assert.Same(derived_M2, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(base_M2, result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'derived.M3(intVal, z:=intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(derived_M3), (base_M3)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:={Nothing, "z"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(derived_M3, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'error BC30272: 'z' is not a parameter of 'Public Shared Overloads Sub M4(u As Integer, [v As Integer = 0], [w As Integer = 0])'. 'Derived.M4(intVal, z:=intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(derived_M4), (base_M4)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:={Nothing, "z"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(derived_M4, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'derived.M5(a:=objectVal) ' Should bind to Base.M5 result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(derived_M5), (base_M5)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal}.AsImmutableOrNull(), argumentNames:={"a"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.True(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(0).State) Assert.Same(derived_M5, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.Candidates(1).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(base_M5, result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'derived.M6(a:=objectVal) ' Should bind to Base.M6 result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(derived_M6), (base_M6)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal}.AsImmutableOrNull(), argumentNames:={"a"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentCountMismatch, result.Candidates(0).State) Assert.Same(derived_M6, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.True(result.Candidates(1).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(base_M6, result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'derived.M7(objectVal, objectVal) ' Should bind to Base.M7 result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(derived_M7), (base_M7)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal, objectVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(derived_M7, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.Candidates(1).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(base_M7, result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'derived.M8(objectVal, objectVal) ' Should bind to Derived.M8 result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(derived_M8), (base_M8)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal, objectVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(derived_M8, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.True(result.Candidates(1).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(derived_M8, result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'Derived.M9(a:=TestClass1Val, b:=1) ' Should bind to Derived.M9 result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(derived_M9), (base_M9)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={TestClass1Val, intVal}.AsImmutableOrNull(), argumentNames:={"a", "b"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.True(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(derived_M9, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'error BC30311: Value of type 'Integer' cannot be converted to 'TestClass1'. 'error BC30311: Value of type 'TestClass1' cannot be converted to 'Integer'. 'Derived.M9(a:=intVal, b:=TestClass1Val) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(derived_M9), (base_M9)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, TestClass1Val}.AsImmutableOrNull(), argumentNames:={"a", "b"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.True(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(derived_M9, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'Derived.M9(Nothing, Nothing) ' Should bind to Derived.M9 result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(derived_M9), (base_M9)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={[nothing], [nothing]}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.True(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(derived_M9, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) ' Calls BaseExt.M 'b.M10(intVal) Dim base_M10_Candidate = (base_M10.ReduceExtensionMethod(derived, 0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:=Nothing, extensionMethods:={base_M10_Candidate}.AsImmutableOrNull(), typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(base_M10_Candidate, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) ' Calls DerivedExt.M 'd.M10(intVal) Dim derived_M10_Candidate = (derived_M10.ReduceExtensionMethod(derived, 0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:=Nothing, extensionMethods:={base_M10_Candidate, derived_M10_Candidate}.AsImmutableOrNull(), typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(derived_M10_Candidate, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:=Nothing, extensionMethods:={derived_M10_Candidate, base_M10_Candidate}.AsImmutableOrNull(), typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(derived_M10_Candidate, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) ' Calls Ext.M11(derived, ...), because Ext.M11(I1, ...) is hidden since it extends ' an interface. 'd.M11(intVal) Dim derived_M11_Candidate = (derived_M11.ReduceExtensionMethod(derived, 0)) Dim i1_M11_Candidate = (ext_M11.ReduceExtensionMethod(derived, 0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:=Nothing, extensionMethods:={derived_M11_Candidate, i1_M11_Candidate}.AsImmutableOrNull(), typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(derived_M11_Candidate, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:=Nothing, extensionMethods:={i1_M11_Candidate, derived_M11_Candidate}.AsImmutableOrNull(), typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(derived_M11_Candidate, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) ' Calls derived.M12 since T.M12 target type is more generic. 'd.M12(10) Dim derived_M12_Candidate = (derived_M12.ReduceExtensionMethod(derived, 0)) Dim ext_M12_Candidate = (ext_M12.ReduceExtensionMethod(derived, 0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:=Nothing, extensionMethods:={derived_M12_Candidate, ext_M12_Candidate}.AsImmutableOrNull(), typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(derived_M12_Candidate, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:=Nothing, extensionMethods:={ext_M12_Candidate, derived_M12_Candidate}.AsImmutableOrNull(), typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(derived_M12_Candidate, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:=Nothing, extensionMethods:={ext_M12_Candidate}.AsImmutableOrNull(), typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(ext_M12_Candidate, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'tc2.S1(10, 10) ' Calls S1(U, T) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass2OfInteger_S1(0)), (TestClass2OfInteger_S1(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:={intVal.Type}.AsImmutableOrNull(), arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass2OfInteger_S1(0).OriginalDefinition, result.Candidates(0).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(1).State) Assert.Same(TestClass2OfInteger_S1(1).OriginalDefinition, result.Candidates(1).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass2OfInteger_S1(1)), (TestClass2OfInteger_S1(0))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:={intVal.Type}.AsImmutableOrNull(), arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass2OfInteger_S1(0).OriginalDefinition, result.Candidates(1).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(0).State) Assert.Same(TestClass2OfInteger_S1(1).OriginalDefinition, result.Candidates(0).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(result.BestResult.Value, result.Candidates(1)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass2OfInteger_S1(1)), (TestClass2OfInteger_S1(0))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:={intVal.Type}.AsImmutableOrNull(), arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:={"x", "y"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass2OfInteger_S1(0).OriginalDefinition, result.Candidates(1).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(0).State) Assert.Same(TestClass2OfInteger_S1(1).OriginalDefinition, result.Candidates(0).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'tc2.S2(10, 10) ' Calls S2(Integer, T) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass2OfInteger_S2(0)), (TestClass2OfInteger_S2(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass2OfInteger_S2(0).OriginalDefinition, result.Candidates(0).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(1).State) Assert.Same(TestClass2OfInteger_S2(1).OriginalDefinition, result.Candidates(1).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass2OfInteger_S2(1)), (TestClass2OfInteger_S2(0))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass2OfInteger_S2(0).OriginalDefinition, result.Candidates(1).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(0).State) Assert.Same(TestClass2OfInteger_S2(1).OriginalDefinition, result.Candidates(0).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(result.BestResult.Value, result.Candidates(1)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass2OfInteger_S2(0)), (TestClass2OfInteger_S2(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:={"x", "y"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass2OfInteger_S2(0).OriginalDefinition, result.Candidates(0).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(1).State) Assert.Same(TestClass2OfInteger_S2(1).OriginalDefinition, result.Candidates(1).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'M13(Of T, U)(x As T, y As U, z As T) 'intVal.M13(intVal, intVal) Dim ext_M13_0_Candidate = (ext_M13(0).ReduceExtensionMethod(intVal.Type, 0)) Dim ext_M13_1_Candidate = (ext_M13(1).ReduceExtensionMethod(intVal.Type, 0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:=Nothing, extensionMethods:={ext_M13_0_Candidate, ext_M13_1_Candidate}. AsImmutableOrNull(), typeArguments:={intVal.Type}.AsImmutableOrNull(), arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(0).State) Assert.Same(ext_M13_0_Candidate, result.Candidates(0).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(ext_M13_1_Candidate.OriginalDefinition, result.Candidates(1).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(result.BestResult.Value, result.Candidates(1)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:=Nothing, extensionMethods:={ext_M13_1_Candidate, ext_M13_0_Candidate}. AsImmutableOrNull(), typeArguments:={intVal.Type}.AsImmutableOrNull(), arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(1).State) Assert.Same(ext_M13_0_Candidate, result.Candidates(1).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(ext_M13_1_Candidate.OriginalDefinition, result.Candidates(0).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(result.BestResult.Value, result.Candidates(0)) ' Extension method precedence Dim derived_M11_Candidate_0 = (derived_M11.ReduceExtensionMethod(derived, 0)) Dim derived_M11_Candidate_1 = (derived_M11.ReduceExtensionMethod(derived, 1)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:=Nothing, extensionMethods:={derived_M11_Candidate_0, derived_M11_Candidate_1}.AsImmutableOrNull(), typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(derived_M11_Candidate_0, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(1).State) Assert.Same(derived_M11_Candidate_1, result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:=Nothing, extensionMethods:={derived_M11_Candidate_1, derived_M11_Candidate_0}.AsImmutableOrNull(), typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(derived_M11_Candidate_0, result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(0).State) Assert.Same(derived_M11_Candidate_1, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass2OfInteger_S3(0)), (TestClass2OfInteger_S3(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:={intVal.Type}.AsImmutableOrNull(), arguments:={intVal, intVal, intVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(0).State) Assert.Same(TestClass2OfInteger_S3(0).OriginalDefinition, result.Candidates(0).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass2OfInteger_S3(1).OriginalDefinition, result.Candidates(1).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.True(result.BestResult.HasValue) 'error BC30521: Overload resolution failed because no accessible 'M14' is most specific for these arguments: 'Extension(method) 'Public Sub M14(Of Integer)(y As Integer, z As Integer)' defined in 'Ext1': Not most specific. 'Extension(method) 'Public Sub M14(Of Integer)(y As Integer, z As Integer)' defined in 'Ext': Not most specific. 'intVal.M14(intVal, intVal) Dim ext_M14_Candidate = (ext_M14.ReduceExtensionMethod(intVal.Type, 0)) Dim ext1_M14_Candidate = (ext1_M14.ReduceExtensionMethod(intVal.Type, 0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:=Nothing, extensionMethods:={ext_M14_Candidate, ext1_M14_Candidate}. AsImmutableOrNull(), typeArguments:={intVal.Type}.AsImmutableOrNull(), arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(ext_M14_Candidate, result.Candidates(0).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(ext1_M14_Candidate, result.Candidates(1).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.False(result.BestResult.HasValue) 'error BC30521: Overload resolution failed because no accessible 'S4' is most specific for these arguments: 'Public Sub S4(Of Integer)(x As Integer, y() As Integer, z As TestClass2(Of Integer), v As Integer)': Not most specific. 'Public Sub S4(Of Integer)(x As Integer, y() As Integer, z As TestClass2(Of Integer), v As Integer)': Not most specific. 'tc2.S4(intVal, Nothing, Nothing, intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass2OfInteger_S4(0)), (TestClass2OfInteger_S4(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:={intVal.Type}.AsImmutableOrNull(), arguments:={intVal, [nothing], [nothing], intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass2OfInteger_S4(0).OriginalDefinition, result.Candidates(0).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass2OfInteger_S4(1).OriginalDefinition, result.Candidates(1).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.False(result.BestResult.HasValue) 'error BC30521: Overload resolution failed because no accessible 'S5' is most specific for these arguments: 'Public Sub S5(x As Integer, y As TestClass2(Of Integer()))': Not most specific. 'Public Sub S5(x As Integer, y As TestClass2(Of Integer))': Not most specific. 'tc2.S5(intVal, Nothing) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass2OfInteger_S5(0)), (TestClass2OfInteger_S5(1)), (TestClass2OfInteger_S5(2))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, [nothing]}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(3, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass2OfInteger_S5(0).OriginalDefinition, result.Candidates(0).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(1).State) Assert.Same(TestClass2OfInteger_S5(1).OriginalDefinition, result.Candidates(1).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(2).State) Assert.Same(TestClass2OfInteger_S5(2).OriginalDefinition, result.Candidates(2).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.False(result.BestResult.HasValue) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass2OfInteger_S5(0)), (TestClass2OfInteger_S5(1)), (TestClass2OfInteger_S5(2))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, [nothing]}.AsImmutableOrNull(), argumentNames:={"x", "y"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(3, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass2OfInteger_S5(0).OriginalDefinition, result.Candidates(0).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(1).State) Assert.Same(TestClass2OfInteger_S5(1).OriginalDefinition, result.Candidates(1).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(2).State) Assert.Same(TestClass2OfInteger_S5(2).OriginalDefinition, result.Candidates(2).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.False(result.BestResult.HasValue) 'intVal.M15(intVal, intVal) Dim ext_M15_Candidate = (ext_M15.ReduceExtensionMethod(intVal.Type, 0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:=Nothing, extensionMethods:={ext_M15_Candidate}. AsImmutableOrNull(), typeArguments:={intVal.Type}.AsImmutableOrNull(), arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(ext_M15_Candidate, result.Candidates(0).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'S6(x As T, ParamArray y As Integer()) 'tc2.S6(intVal, intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass2OfInteger_S6(0)), (TestClass2OfInteger_S6(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(4, result.Candidates.Length) Assert.False(result.Candidates(0).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass2OfInteger_S6(0).OriginalDefinition, result.Candidates(0).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.True(result.Candidates(1).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(1).State) Assert.Same(TestClass2OfInteger_S6(0).OriginalDefinition, result.Candidates(1).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.False(result.Candidates(2).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(2).State) Assert.Same(TestClass2OfInteger_S6(1).OriginalDefinition, result.Candidates(2).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.True(result.Candidates(3).IsExpandedParamArrayForm) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(3).State) Assert.Same(TestClass2OfInteger_S6(1).OriginalDefinition, result.Candidates(3).Candidate.UnderlyingSymbol.OriginalDefinition) Assert.Equal(result.BestResult.Value, result.Candidates(3)) 'M14(a As Integer) 'TestClass1.M14(shortVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M14(0)), (TestClass1_M14(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={shortVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M14(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(1).State) Assert.Same(TestClass1_M14(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M14(1)), (TestClass1_M14(0))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={shortVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M14(0), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(0).State) Assert.Same(TestClass1_M14(1), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'M15(a As Integer) 'TestClass1.M15(0) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M15(0)), (TestClass1_M15(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intZero}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M15(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(1).State) Assert.Same(TestClass1_M15(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M15(1)), (TestClass1_M15(0))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intZero}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M15(0), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(0).State) Assert.Same(TestClass1_M15(1), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'M16(a As Short) 'TestClass1.M16(0L) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M16(0)), (TestClass1_M16(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={longZero}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.False(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) Assert.Same(TestClass1_M16(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(1).State) Assert.True(result.Candidates(1).RequiresNarrowingConversion) Assert.True(result.Candidates(1).RequiresNarrowingNotFromNumericConstant) Assert.Same(TestClass1_M16(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'Option Strict Off 'error BC30519: Overload resolution failed because no accessible 'M16' can be called without a narrowing conversion: 'Public Shared Sub M16(a As System.TypeCode)': Argument matching parameter 'a' narrows from 'Long' to 'System.TypeCode'. 'Public Shared Sub M16(a As Short)': Argument matching parameter 'a' narrows from 'Long' to 'Short'. result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M16(0)), (TestClass1_M16(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={longZero}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.False(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) Assert.Same(TestClass1_M16(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.True(result.Candidates(1).RequiresNarrowingConversion) Assert.True(result.Candidates(1).RequiresNarrowingNotFromNumericConstant) Assert.Same(TestClass1_M16(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M16(1)), (TestClass1_M16(0))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={longZero}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.True(result.Candidates(0).RequiresNarrowingConversion) Assert.True(result.Candidates(0).RequiresNarrowingNotFromNumericConstant) Assert.Same(TestClass1_M16(1), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.True(result.Candidates(1).RequiresNarrowingConversion) Assert.False(result.Candidates(1).RequiresNarrowingNotFromNumericConstant) Assert.Same(TestClass1_M16(0), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'M16(a As System.TypeCode) 'TestClass1.M16(0) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M16(0)), (TestClass1_M16(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intZero}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.RequiresNarrowing, result.Candidates(0).State) Assert.Same(TestClass1_M16(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M16(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M16(1)), (TestClass1_M16(0))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intZero}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.False(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.RequiresNarrowing, result.Candidates(1).State) Assert.Same(TestClass1_M16(0), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M16(1), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'Byte 'TestClass1.M17(Nothing) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M17(0)), (TestClass1_M17(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={[nothing]}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M17(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(1).State) Assert.Same(TestClass1_M17(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M17(1)), (TestClass1_M17(0))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={[nothing]}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M17(0), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(0).State) Assert.Same(TestClass1_M17(1), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'Short 'TestClass1.M18(Nothing) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M18(0)), (TestClass1_M18(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={[nothing]}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M18(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(1).State) Assert.Same(TestClass1_M18(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M18(1)), (TestClass1_M18(0))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={[nothing]}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M18(0), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(0).State) Assert.Same(TestClass1_M18(1), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'Integer 'TestClass1.M19(Nothing) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M19(0)), (TestClass1_M19(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={[nothing]}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M19(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(1).State) Assert.Same(TestClass1_M19(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M19(1)), (TestClass1_M19(0))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={[nothing]}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M19(0), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(0).State) Assert.Same(TestClass1_M19(1), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'Long 'TestClass1.M20(Nothing) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M20(0)), (TestClass1_M20(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={[nothing]}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M20(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(1).State) Assert.Same(TestClass1_M20(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M20(1)), (TestClass1_M20(0))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={[nothing]}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M20(0), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(0).State) Assert.Same(TestClass1_M20(1), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'Integer 'TestClass1.M21(ushortVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M21(0)), (TestClass1_M21(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={ushortVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M21(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(1).State) Assert.Same(TestClass1_M21(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M21(1)), (TestClass1_M21(0))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={ushortVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M21(0), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(0).State) Assert.Same(TestClass1_M21(1), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) Dim numericTypesPrecedence = {System_SByte, System_Byte, System_Int16, System_UInt16, System_Int32, System_UInt32, System_Int64, System_UInt64, System_Decimal, System_Single, System_Double} Dim prev As SpecialType = 0 For i As Integer = 0 To numericTypesPrecedence.Length - 1 Step 1 Assert.InRange(numericTypesPrecedence(i), prev + 1, Integer.MaxValue) prev = numericTypesPrecedence(i) Next 'error BC30521: Overload resolution failed because no accessible 'M22' is most specific for these arguments: 'Public Shared Sub M22(a As SByte, b As Long)': Not most specific. 'Public Shared Sub M22(a As Byte, b As ULong)': Not most specific. 'TestClass1.M22(Nothing, Nothing) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M22(0)), (TestClass1_M22(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={[nothing], [nothing]}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M22(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M22(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M22(1)), (TestClass1_M22(0))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={[nothing], [nothing]}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M22(1), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M22(0), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'M23(a As Long) 'TestClass1.M23(intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M23(0)), (TestClass1_M23(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M23(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.RequiresNarrowing, result.Candidates(1).State) Assert.Same(TestClass1_M23(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M23(0)), (TestClass1_M23(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M23(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(1).State) Assert.True(result.Candidates(1).RequiresNarrowingConversion) Assert.True(result.Candidates(1).RequiresNarrowingNotFromNumericConstant) Assert.Same(TestClass1_M23(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'Option strict OFF: late call 'TestClass1.M23(objectVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M23(0)), (TestClass1_M23(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.True(result.ResolutionIsLateBound) Assert.True(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M23(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M23(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'Option strict ON ' error BC30518: Overload resolution failed because no accessible 'M23' can be called with these arguments: 'Public Shared Sub M23(a As Short)': Option Strict On disallows implicit conversions from 'Object' to 'Short'. 'Public Shared Sub M23(a As Long)': Option Strict On disallows implicit conversions from 'Object' to 'Long'. 'TestClass1.M23(objectVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M23(0)), (TestClass1_M23(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=False, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.True(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M23(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M23(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M23(0)), (TestClass1_M23(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=False, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.False(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M23(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(1).State) Assert.Same(TestClass1_M23(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'Option strict OFF 'warning BC42016: Implicit conversion from 'Object' to 'Short'. 'TestClass1.M24(objectVal, intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M24(0)), (TestClass1_M24(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.True(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ExtensionMethodVsLateBinding, result.Candidates(0).State) Assert.Same(TestClass1_M24(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M24(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'Option strict ON 'F:\ddp\Roslyn\Main\Open\Compilers\VisualBasic\Test\Semantics\OverloadResolutionTestSource.vb(549) : error BC30518: Overload resolution failed because no accessible 'M24' can be called with these arguments: 'Public Shared Sub M24(a As Short, b As Integer)': Option Strict On disallows implicit conversions from 'Object' to 'Short'. 'Public Shared Sub M24(a As Long, b As Short)': Option Strict On disallows implicit conversions from 'Object' to 'Long'. 'Public Shared Sub M24(a As Long, b As Short)': Option Strict On disallows implicit conversions from 'Integer' to 'Short'. 'TestClass1.M24(objectVal, intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M24(0)), (TestClass1_M24(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=False, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.True(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M24(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M24(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M24(0)), (TestClass1_M24(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={objectVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=False, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.False(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M24(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(1).State) Assert.Same(TestClass1_M24(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'M25(a As SByte) 'TestClass1.M25(-1L) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M25(0)), (TestClass1_M25(1)), (TestClass1_M25(2))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={longConst}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.True(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(3, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(0).State) Assert.Same(TestClass1_M25(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(1).State) Assert.Same(TestClass1_M25(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(2).State) Assert.Same(TestClass1_M25(2), result.Candidates(2).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(2)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M25(2)), (TestClass1_M25(0)), (TestClass1_M25(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={longConst}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.True(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(3, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M25(2), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(1).State) Assert.Same(TestClass1_M25(0), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(2).State) Assert.Same(TestClass1_M25(1), result.Candidates(2).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M25(1)), (TestClass1_M25(2)), (TestClass1_M25(0))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={longConst}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.True(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(3, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(0).State) Assert.Same(TestClass1_M25(1), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M25(2), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.LessApplicable, result.Candidates(2).State) Assert.Same(TestClass1_M25(0), result.Candidates(2).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'BC30518: Overload resolution failed because no accessible 'M26' can be called with these arguments: 'Public Shared Sub M26(a As Integer, b As Short)': Option Strict On disallows implicit conversions from 'Double' to 'Short'. 'Public Shared Sub M26(a As Short, b As Integer)': Option Strict On disallows implicit conversions from 'Double' to 'Integer'. 'TestClass1.M26(-1L, doubleVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M26(0)), (TestClass1_M26(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={longConst, doubleVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.True(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M26(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M26(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M26(1)), (TestClass1_M26(0))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={longConst, doubleVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.True(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M26(1), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M26(0), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'error BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Short'. 'TestClass1.M27(intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M27)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.True(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M27, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M27)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOnBinder) Assert.False(result.ResolutionIsLateBound) Assert.False(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M27, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'Sub M14(a As Long) 'TestClass1.M14(0L) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M14(0)), (TestClass1_M14(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={longZero}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.False(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.RequiresNarrowing, result.Candidates(0).State) Assert.Same(TestClass1_M14(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M14(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) Dim DoubleMaxValue As BoundExpression = New BoundConversion(_syntaxNode, New BoundLiteral(_syntaxNode, ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, ConstantValue.Create(Double.MaxValue), c1.GetSpecialType(System_Double), Nothing) Dim IntegerMaxValue As BoundExpression = New BoundConversion(_syntaxNode, New BoundLiteral(_syntaxNode, ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, ConstantValue.Create(Integer.MaxValue), c1.GetSpecialType(System_Int32), Nothing) Assert.True(c1.Options.CheckOverflow) 'error BC30439: Constant expression not representable in type 'Short'. 'TestClass1.M27(Integer.MaxValue) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M27)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={IntegerMaxValue}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M27, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'error BC30439: Constant expression not representable in type 'Short'. 'TestClass1.M27(Double.MaxValue) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M27)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={DoubleMaxValue}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M27, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'error BC30519: Overload resolution failed because no accessible 'M26' can be called without a narrowing conversion: 'Public Shared Sub M26(a As Integer, b As Short)': Argument matching parameter 'b' narrows from 'Integer' to 'Short'. 'Public Shared Sub M26(a As Short, b As Integer)': Argument matching parameter 'a' narrows from 'Integer' to 'Short'. 'TestClass1.M26(intVal, intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M26(0)), (TestClass1_M26(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={intVal, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.True(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M26(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M26(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'Overflow On - Sub M26(a As Integer, b As Short) 'TestClass1.M26(Integer.MaxValue, intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M26(0)), (TestClass1_M26(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={IntegerMaxValue, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.True(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M26(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M26(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'error BC30521: Overload resolution failed because no accessible 'g' is most specific for these arguments 'TestClass1.g(1UI) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_g(0)), (TestClass1_g(1)), (TestClass1_g(2))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={unsignedOne}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.False(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(3, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_g(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_g(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(2).State) Assert.Same(TestClass1_g(2), result.Candidates(2).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'Should bind to extension method 'TestClass1Val.SM(x:=intVal, y:=objectVal) Dim ext_SM_Candidate = (ext_SM.ReduceExtensionMethod(TestClass1Val.Type, 0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_SM)}.AsImmutableOrNull(), extensionMethods:={ext_SM_Candidate}.AsImmutableOrNull(), typeArguments:=Nothing, arguments:={intVal, objectVal}.AsImmutableOrNull(), argumentNames:={"x", "y"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.True(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(0).State) Assert.Same(TestClass1_SM, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(ext_SM_Candidate, result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(1)) 'error BC30519: Overload resolution failed because no accessible 'SM1' can be called without a narrowing conversion: 'Extension(method) 'Public Sub SM1(y As Object, x As Short)' defined in 'Ext': Argument matching parameter 'x' narrows from 'Integer' to 'Short'. 'Extension(method) 'Public Sub SM1(y As Double, x As Integer)' defined in 'Ext': Argument matching parameter 'y' narrows from 'Object' to 'Double'. 'TestClass1Val.SM1(x:=intVal, y:=objectVal) Dim ext_SM1_0_Candidate = (ext_SM1(0).ReduceExtensionMethod(TestClass1Val.Type, 0)) Dim ext_SM1_1_Candidate = (ext_SM1(1).ReduceExtensionMethod(TestClass1Val.Type, 0)) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_SM1)}.AsImmutableOrNull(), extensionMethods:={ext_SM1_0_Candidate, ext_SM1_1_Candidate}.AsImmutableOrNull(), typeArguments:=Nothing, arguments:={intVal, objectVal}.AsImmutableOrNull(), argumentNames:={"x", "y"}.AsImmutableOrNull(), lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.True(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(3, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Shadowed, result.Candidates(0).State) Assert.Same(TestClass1_SM1, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(ext_SM1_0_Candidate, result.Candidates(1).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(2).State) Assert.Same(ext_SM1_1_Candidate, result.Candidates(2).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) End Sub <Fact> Public Sub BasicTests2() Dim optionStrictOff = <file> Option Strict Off Class OptionStrictOff Shared Sub Context() End Sub End Class </file> Dim optionStrictOffTree = VisualBasicSyntaxTree.ParseText(optionStrictOff.Value) Dim c1 = VisualBasicCompilation.Create("Test1", syntaxTrees:={Parse(My.Resources.Resource.OverloadResolutionTestSource), optionStrictOffTree}, references:={TestReferences.NetFx.v4_0_21006.mscorlib}, options:=TestOptions.ReleaseExe.WithOverflowChecks(False)) Dim sourceModule = DirectCast(c1.Assembly.Modules(0), SourceModuleSymbol) Dim optionStrictOffContext = DirectCast(sourceModule.GlobalNamespace.GetTypeMembers("OptionStrictOff").Single().GetMembers("Context").Single(), SourceMethodSymbol) Dim optionStrictOffBinder = BinderBuilder.CreateBinderForMethodBody(sourceModule, optionStrictOffTree, optionStrictOffContext) Assert.False(c1.Options.CheckOverflow) Dim TestClass1 = c1.Assembly.GlobalNamespace.GetTypeMembers("TestClass1").Single() Dim TestClass1_M26 = TestClass1.GetMembers("M26").OfType(Of MethodSymbol)().ToArray() Dim TestClass1_M27 = TestClass1.GetMembers("M27").OfType(Of MethodSymbol)().Single() Dim _syntaxNode = optionStrictOffTree.GetVisualBasicRoot(Nothing) Dim _syntaxTree = optionStrictOffTree Dim DoubleMaxValue As BoundExpression = New BoundConversion(_syntaxNode, New BoundLiteral(_syntaxNode, ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, ConstantValue.Create(Double.MaxValue), c1.GetSpecialType(System_Double), Nothing) Dim IntegerMaxValue As BoundExpression = New BoundConversion(_syntaxNode, New BoundLiteral(_syntaxNode, ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, ConstantValue.Create(Integer.MaxValue), c1.GetSpecialType(System_Int32), Nothing) Dim intVal As BoundExpression = New BoundUnaryOperator(_syntaxNode, UnaryOperatorKind.Minus, IntegerMaxValue, False, IntegerMaxValue.Type) Dim result As OverloadResolution.OverloadResolutionResult 'Overflow Off 'TestClass1.M27(Integer.MaxValue) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M27)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={IntegerMaxValue}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M27, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(result.BestResult.Value, result.Candidates(0)) 'Overflow Off 'error BC30439: Constant expression not representable in type 'Short'. 'TestClass1.M27(Double.MaxValue) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M27)}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={DoubleMaxValue}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.Equal(1, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.ArgumentMismatch, result.Candidates(0).State) Assert.Same(TestClass1_M27, result.Candidates(0).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) 'Overflow Off 'error BC30519: Overload resolution failed because no accessible 'M26' can be called without a narrowing conversion: 'Public Shared Sub M26(a As Integer, b As Short)': Argument matching parameter 'b' narrows from 'Integer' to 'Short'. 'Public Shared Sub M26(a As Short, b As Integer)': Argument matching parameter 'a' narrows from 'Integer' to 'Short'. 'TestClass1.M26(Integer.MaxValue, intVal) result = ResolveMethodOverloading(includeEliminatedCandidates:=True, instanceMethods:={(TestClass1_M26(0)), (TestClass1_M26(1))}.AsImmutableOrNull(), extensionMethods:=Nothing, typeArguments:=Nothing, arguments:={IntegerMaxValue, intVal}.AsImmutableOrNull(), argumentNames:=Nothing, lateBindingIsAllowed:=True, binder:=optionStrictOffBinder) Assert.False(result.ResolutionIsLateBound) Assert.True(result.RemainingCandidatesRequireNarrowingConversion) Assert.Equal(2, result.Candidates.Length) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(0).State) Assert.Same(TestClass1_M26(0), result.Candidates(0).Candidate.UnderlyingSymbol) Assert.Equal(CandidateAnalysisResultState.Applicable, result.Candidates(1).State) Assert.Same(TestClass1_M26(1), result.Candidates(1).Candidate.UnderlyingSymbol) Assert.False(result.BestResult.HasValue) End Sub <Fact> Public Sub Bug4219() Dim compilationDef = <compilation name="Bug4219"> <file name="a.vb"> Option Strict On Module Program Sub Main() Dim a As A(Of Long, Integer) a.Goo(y:=1, x:=1) End Sub End Module Class A(Of T, S) Sub Goo(x As Integer, y As T) End Sub Sub Goo(y As Long, x As S) End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42104: Variable 'a' is used before it has been assigned a value. A null reference exception could result at runtime. a.Goo(y:=1, x:=1) ~ BC30521: Overload resolution failed because no accessible 'Goo' is most specific for these arguments: 'Public Sub Goo(x As Integer, y As Long)': Not most specific. 'Public Sub Goo(y As Long, x As Integer)': Not most specific. a.Goo(y:=1, x:=1) ~~~ </expected>) End Sub <WorkItem(545633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545633")> <Fact> Public Sub Bug14186a() Dim compilationDef = <compilation name="Bug14186a"> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class Bar Shared Sub Equal(Of T)(exp As IEnumerable(Of T), act As IEnumerable(Of T)) Console.Write("A;") End Sub Shared Sub Equal(Of T)(exp As T, act As T) Console.Write("B;") End Sub End Class Public Module Goo Sub Main() Dim goo As IEnumerable(Of Integer) = Nothing Bar.Equal(goo, goo) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, expectedOutput:="A;") End Sub <WorkItem(545633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545633")> <Fact> Public Sub Bug14186b() Dim compilationDef = <compilation name="Bug14186b"> <file name="a.vb"> Imports System.Collections.Generic Public Class Bar Shared Sub Equal(Of T)(exp As IEnumerable(Of T), act As T) End Sub Shared Sub Equal(Of T)(exp As T, act As IEnumerable(Of T)) End Sub End Class Public Module Goo Sub Main() Dim goo As IEnumerable(Of Integer) = Nothing Bar.Equal(goo, goo) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30518: Overload resolution failed because no accessible 'Equal' can be called with these arguments: 'Public Shared Sub Equal(Of T)(exp As IEnumerable(Of T), act As T)': Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error. 'Public Shared Sub Equal(Of T)(exp As T, act As IEnumerable(Of T))': Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error. Bar.Equal(goo, goo) ~~~~~ </expected>) End Sub <WorkItem(545633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545633")> <Fact> Public Sub Bug14186c() Dim compilationDef = <compilation name="Bug14186c"> <file name="a.vb"> Public Class Bar Shared Sub Equal(Of T)(exp As I1(Of T)) End Sub Shared Sub Equal(Of T)(exp As I2(Of T)) End Sub End Class Public Interface I1(Of T) End Interface Public Interface I2(Of T) End Interface Class P(Of T) Implements I1(Of T), I2(Of T) End Class Public Module Goo Sub Main() Dim goo As New P(Of Integer) Bar.Equal(goo) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30521: Overload resolution failed because no accessible 'Equal' is most specific for these arguments: 'Public Shared Sub Equal(Of Integer)(exp As I1(Of Integer))': Not most specific. 'Public Shared Sub Equal(Of Integer)(exp As I2(Of Integer))': Not most specific. Bar.Equal(goo) ~~~~~ </expected>) End Sub <WorkItem(545633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545633")> <Fact> Public Sub Bug14186d() Dim compilationDef = <compilation name="Bug14186d"> <file name="a.vb"> Imports System Public Class Bar Shared Sub Equal(Of T)(exp As I2(Of I2(Of T))) Console.Write("A;") End Sub Shared Sub Equal(Of T)(exp As I2(Of T)) Console.Write("B;") End Sub End Class Public Interface I2(Of T) End Interface Class P(Of T) Implements I2(Of I2(Of T)), I2(Of T) End Class Public Module Goo Sub Main() Dim goo As New P(Of Integer) Dim goo2 As I2(Of Integer) = goo Bar.Equal(goo2) Dim goo3 As I2(Of I2(Of Integer)) = goo Bar.Equal(goo3) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, expectedOutput:="B;A;") End Sub <WorkItem(545633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545633")> <Fact> Public Sub Bug14186e() Dim compilationDef = <compilation name="Bug14186e"> <file name="a.vb"> Imports System Public Class Bar Shared Sub Equal(Of T)(exp() As I2(Of T)) Console.Write("A;") End Sub Shared Sub Equal(Of T)(exp() As T) Console.Write("B;") End Sub End Class Public Interface I2(Of T) End Interface Public Module Goo Sub Main() Dim goo() As I2(Of Integer) = Nothing Bar.Equal(goo) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, expectedOutput:="A;") End Sub <Fact> Public Sub Diagnostics1() Dim compilationDef = <compilation name="OverloadResolutionDiagnostics"> <file name="a.vb"> Option Strict On Imports System.Console Module Module1 Sub Main() F1(Of Integer, Integer)() F1(Of Integer, Integer)(1, 2) F2(Of Integer)() F2(Of Integer)(1, 2) F3(Of Integer)() F3(Of Integer)(1, 2) F1(Of Integer)() F1(Of Integer)(1, 2) F4() F4(, , , ) F4(1, 2, , 4) F3(y:=1) F3(1, y:=2) F3(y:=1, z:=2) F4(y:=1, x:=2) F4(, y:=1) F3(x:=1, x:=2) F3(, x:=2) F3(1, x:=2) F4(x:=1, x:=2) F4(, x:=2) F4(1, x:=2) F5(x:=1, x:=2) F2(1) Dim g As System.Guid = Nothing F6(g, g) F6(y:=g, x:=g) F4(g, Nothing) F4(1, g) Dim l As Long = 1 Dim s As Short = 1 F3(l) F7(g) F7(s) F7((l)) F8(y:=Nothing) End Sub Sub F1(Of T)(x As Integer) End Sub Sub F2(Of T, S)(x As Integer) End Sub Sub F3(x As Integer) End Sub Sub F4(x As Integer, ParamArray y As Integer()) End Sub Sub F5(x As Integer, y As Integer) End Sub Sub F6(x As Integer, y As Long) End Sub Sub F7(ByRef x As Integer) End Sub Sub F8(ParamArray y As Integer()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32043: Too many type arguments to 'Public Sub F1(Of T)(x As Integer)'. F1(Of Integer, Integer)() ~~~~~~~~~~~~~~~~~~~~~ BC32043: Too many type arguments to 'Public Sub F1(Of T)(x As Integer)'. F1(Of Integer, Integer)(1, 2) ~~~~~~~~~~~~~~~~~~~~~ BC32042: Too few type arguments to 'Public Sub F2(Of T, S)(x As Integer)'. F2(Of Integer)() ~~~~~~~~~~~~ BC32042: Too few type arguments to 'Public Sub F2(Of T, S)(x As Integer)'. F2(Of Integer)(1, 2) ~~~~~~~~~~~~ BC32045: 'Public Sub F3(x As Integer)' has no type parameters and so cannot have type arguments. F3(Of Integer)() ~~~~~~~~~~~~ BC32045: 'Public Sub F3(x As Integer)' has no type parameters and so cannot have type arguments. F3(Of Integer)(1, 2) ~~~~~~~~~~~~ BC30455: Argument not specified for parameter 'x' of 'Public Sub F1(Of Integer)(x As Integer)'. F1(Of Integer)() ~~~~~~~~~~~~~~ BC30057: Too many arguments to 'Public Sub F1(Of Integer)(x As Integer)'. F1(Of Integer)(1, 2) ~ BC30455: Argument not specified for parameter 'x' of 'Public Sub F4(x As Integer, ParamArray y As Integer())'. F4() ~~ BC30455: Argument not specified for parameter 'x' of 'Public Sub F4(x As Integer, ParamArray y As Integer())'. F4(, , , ) ~~ BC30588: Omitted argument cannot match a ParamArray parameter. F4(, , , ) ~ BC30588: Omitted argument cannot match a ParamArray parameter. F4(, , , ) ~ BC30588: Omitted argument cannot match a ParamArray parameter. F4(, , , ) ~ BC30588: Omitted argument cannot match a ParamArray parameter. F4(1, 2, , 4) ~ BC30455: Argument not specified for parameter 'x' of 'Public Sub F3(x As Integer)'. F3(y:=1) ~~ BC30272: 'y' is not a parameter of 'Public Sub F3(x As Integer)'. F3(y:=1) ~ BC30272: 'y' is not a parameter of 'Public Sub F3(x As Integer)'. F3(1, y:=2) ~ BC30455: Argument not specified for parameter 'x' of 'Public Sub F3(x As Integer)'. F3(y:=1, z:=2) ~~ BC30272: 'y' is not a parameter of 'Public Sub F3(x As Integer)'. F3(y:=1, z:=2) ~ BC30272: 'z' is not a parameter of 'Public Sub F3(x As Integer)'. F3(y:=1, z:=2) ~ BC30587: Named argument cannot match a ParamArray parameter. F4(y:=1, x:=2) ~ BC30455: Argument not specified for parameter 'x' of 'Public Sub F4(x As Integer, ParamArray y As Integer())'. F4(, y:=1) ~~ BC30587: Named argument cannot match a ParamArray parameter. F4(, y:=1) ~ BC30274: Parameter 'x' of 'Public Sub F3(x As Integer)' already has a matching argument. F3(x:=1, x:=2) ~ BC32021: Parameter 'x' in 'Public Sub F3(x As Integer)' already has a matching omitted argument. F3(, x:=2) ~ BC30274: Parameter 'x' of 'Public Sub F3(x As Integer)' already has a matching argument. F3(1, x:=2) ~ BC30274: Parameter 'x' of 'Public Sub F4(x As Integer, ParamArray y As Integer())' already has a matching argument. F4(x:=1, x:=2) ~ BC32021: Parameter 'x' in 'Public Sub F4(x As Integer, ParamArray y As Integer())' already has a matching omitted argument. F4(, x:=2) ~ BC30274: Parameter 'x' of 'Public Sub F4(x As Integer, ParamArray y As Integer())' already has a matching argument. F4(1, x:=2) ~ BC30455: Argument not specified for parameter 'y' of 'Public Sub F5(x As Integer, y As Integer)'. F5(x:=1, x:=2) ~~ BC30274: Parameter 'x' of 'Public Sub F5(x As Integer, y As Integer)' already has a matching argument. F5(x:=1, x:=2) ~ BC32050: Type parameter 'S' for 'Public Sub F2(Of T, S)(x As Integer)' cannot be inferred. F2(1) ~~ BC32050: Type parameter 'T' for 'Public Sub F2(Of T, S)(x As Integer)' cannot be inferred. F2(1) ~~ BC30311: Value of type 'Guid' cannot be converted to 'Integer'. F6(g, g) ~ BC30311: Value of type 'Guid' cannot be converted to 'Long'. F6(g, g) ~ BC30311: Value of type 'Guid' cannot be converted to 'Long'. F6(y:=g, x:=g) ~ BC30311: Value of type 'Guid' cannot be converted to 'Integer'. F6(y:=g, x:=g) ~ BC30311: Value of type 'Guid' cannot be converted to 'Integer'. F4(g, Nothing) ~ BC30311: Value of type 'Guid' cannot be converted to 'Integer'. F4(1, g) ~ BC30512: Option Strict On disallows implicit conversions from 'Long' to 'Integer'. F3(l) ~ BC30311: Value of type 'Guid' cannot be converted to 'Integer'. F7(g) ~ BC32029: Option Strict On disallows narrowing from type 'Integer' to type 'Short' in copying the value of 'ByRef' parameter 'x' back to the matching argument. F7(s) ~ BC30512: Option Strict On disallows implicit conversions from 'Long' to 'Integer'. F7((l)) ~~~ BC30587: Named argument cannot match a ParamArray parameter. F8(y:=Nothing) ~ </expected>) End Sub <Fact> Public Sub Diagnostics2() Dim compilationDef = <compilation name="OverloadResolutionDiagnostics"> <file name="a.vb"> Option Strict On Imports System.Console Module Module1 Sub Main() Goo(Of Integer, Integer)() Goo(Of Integer, Integer)(1, 2) Goo(Of Integer)() Goo(Of Integer)(1, 2) Dim g As System.Guid = Nothing F1(g) F1(y:=1) F2(1, y:=1) F2(1, ) F3(1, , z:=1) F3(1, 1, x:=1) Goo(1) End Sub Sub Goo(Of T)(x As Integer) End Sub Sub Goo(Of S)(x As Long) End Sub Sub F1(x As Integer) End Sub Sub F1(x As Long) End Sub Sub F2(x As Long, ParamArray y As Integer()) End Sub Sub F2(x As Integer, a As Integer, ParamArray y As Integer()) End Sub Sub F3(x As Long, y As Integer, z As Long) End Sub Sub F3(x As Long, z As Long, y As Integer) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32087: Overload resolution failed because no accessible 'Goo' accepts this number of type arguments. Goo(Of Integer, Integer)() ~~~~~~~~~~~~~~~~~~~~~~~~ BC32087: Overload resolution failed because no accessible 'Goo' accepts this number of type arguments. Goo(Of Integer, Integer)(1, 2) ~~~~~~~~~~~~~~~~~~~~~~~~ BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments. Goo(Of Integer)() ~~~~~~~~~~~~~~~ BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments. Goo(Of Integer)(1, 2) ~~~~~~~~~~~~~~~ BC30518: Overload resolution failed because no accessible 'F1' can be called with these arguments: 'Public Sub F1(x As Integer)': Value of type 'Guid' cannot be converted to 'Integer'. 'Public Sub F1(x As Long)': Value of type 'Guid' cannot be converted to 'Long'. F1(g) ~~ BC30518: Overload resolution failed because no accessible 'F1' can be called with these arguments: 'Public Sub F1(x As Integer)': 'y' is not a method parameter. 'Public Sub F1(x As Integer)': Argument not specified for parameter 'x'. 'Public Sub F1(x As Long)': 'y' is not a method parameter. 'Public Sub F1(x As Long)': Argument not specified for parameter 'x'. F1(y:=1) ~~ BC30518: Overload resolution failed because no accessible 'F2' can be called with these arguments: 'Public Sub F2(x As Long, ParamArray y As Integer())': Named argument cannot match a ParamArray parameter. 'Public Sub F2(x As Integer, a As Integer, ParamArray y As Integer())': Named argument cannot match a ParamArray parameter. 'Public Sub F2(x As Integer, a As Integer, ParamArray y As Integer())': Argument not specified for parameter 'a'. F2(1, y:=1) ~~ BC30518: Overload resolution failed because no accessible 'F2' can be called with these arguments: 'Public Sub F2(x As Long, ParamArray y As Integer())': Omitted argument cannot match a ParamArray parameter. 'Public Sub F2(x As Integer, a As Integer, ParamArray y As Integer())': Argument not specified for parameter 'a'. F2(1, ) ~~ BC30518: Overload resolution failed because no accessible 'F3' can be called with these arguments: 'Public Sub F3(x As Long, y As Integer, z As Long)': Argument not specified for parameter 'y'. 'Public Sub F3(x As Long, z As Long, y As Integer)': Parameter 'z' already has a matching omitted argument. 'Public Sub F3(x As Long, z As Long, y As Integer)': Argument not specified for parameter 'y'. F3(1, , z:=1) ~~ BC30518: Overload resolution failed because no accessible 'F3' can be called with these arguments: 'Public Sub F3(x As Long, y As Integer, z As Long)': Parameter 'x' already has a matching argument. 'Public Sub F3(x As Long, y As Integer, z As Long)': Argument not specified for parameter 'z'. 'Public Sub F3(x As Long, z As Long, y As Integer)': Parameter 'x' already has a matching argument. 'Public Sub F3(x As Long, z As Long, y As Integer)': Argument not specified for parameter 'y'. F3(1, 1, x:=1) ~~ BC30518: Overload resolution failed because no accessible 'Goo' can be called with these arguments: 'Public Sub Goo(Of T)(x As Integer)': Type parameter 'T' cannot be inferred. 'Public Sub Goo(Of S)(x As Long)': Type parameter 'S' cannot be inferred. Goo(1) ~~~ </expected>) End Sub <Fact> Public Sub Diagnostics3() Dim compilationDef = <compilation name="OverloadResolutionDiagnostics"> <file name="a.vb"> Option Strict Off Imports System.Console Module Module1 Sub Main() Dim i As Integer = 0 F1(i) F2(i, i) F2(1, 1) End Sub Sub F1(x As Byte) End Sub Sub F1(x As SByte) End Sub Sub F1(ByRef x As Long) End Sub Sub F2(x As Integer, ParamArray y As Byte()) End Sub Sub F2(x As SByte, y As Integer) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30519: Overload resolution failed because no accessible 'F1' can be called without a narrowing conversion: 'Public Sub F1(x As Byte)': Argument matching parameter 'x' narrows from 'Integer' to 'Byte'. 'Public Sub F1(x As SByte)': Argument matching parameter 'x' narrows from 'Integer' to 'SByte'. 'Public Sub F1(ByRef x As Long)': Copying the value of 'ByRef' parameter 'x' back to the matching argument narrows from type 'Long' to type 'Integer'. F1(i) ~~ BC30519: Overload resolution failed because no accessible 'F2' can be called without a narrowing conversion: 'Public Sub F2(x As Integer, ParamArray y As Byte())': Argument matching parameter 'y' narrows from 'Integer' to 'Byte'. 'Public Sub F2(x As SByte, y As Integer)': Argument matching parameter 'x' narrows from 'Integer' to 'SByte'. F2(i, i) ~~ BC30519: Overload resolution failed because no accessible 'F2' can be called without a narrowing conversion: 'Public Sub F2(x As Integer, ParamArray y As Byte())': Argument matching parameter 'y' narrows from 'Integer' to 'Byte'. 'Public Sub F2(x As SByte, y As Integer)': Argument matching parameter 'x' narrows from 'Integer' to 'SByte'. F2(1, 1) ~~ </expected>) End Sub <Fact> Public Sub Diagnostics4() Dim compilationDef = <compilation name="OverloadResolutionDiagnostics"> <file name="a.vb"> Option Strict On Imports System.Console Module Module1 Sub Main() Dim i As Integer = 0 F1(i) F2(i, i) F2(1, 1) End Sub Sub F1(x As Byte) End Sub Sub F1(x As SByte) End Sub Sub F1(ByRef x As Long) End Sub Sub F2(x As Integer, ParamArray y As Byte()) End Sub Sub F2(x As SByte, y As Integer) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30518: Overload resolution failed because no accessible 'F1' can be called with these arguments: 'Public Sub F1(x As Byte)': Option Strict On disallows implicit conversions from 'Integer' to 'Byte'. 'Public Sub F1(x As SByte)': Option Strict On disallows implicit conversions from 'Integer' to 'SByte'. 'Public Sub F1(ByRef x As Long)': Option Strict On disallows narrowing from type 'Long' to type 'Integer' in copying the value of 'ByRef' parameter 'x' back to the matching argument. F1(i) ~~ BC30518: Overload resolution failed because no accessible 'F2' can be called with these arguments: 'Public Sub F2(x As Integer, ParamArray y As Byte())': Option Strict On disallows implicit conversions from 'Integer' to 'Byte'. 'Public Sub F2(x As SByte, y As Integer)': Option Strict On disallows implicit conversions from 'Integer' to 'SByte'. F2(i, i) ~~ BC30519: Overload resolution failed because no accessible 'F2' can be called without a narrowing conversion: 'Public Sub F2(x As Integer, ParamArray y As Byte())': Argument matching parameter 'y' narrows from 'Integer' to 'Byte'. 'Public Sub F2(x As SByte, y As Integer)': Argument matching parameter 'x' narrows from 'Integer' to 'SByte'. F2(1, 1) ~~ </expected>) End Sub <Fact> Public Sub Diagnostics5() Dim compilationDef = <compilation name="OverloadResolutionDiagnostics"> <file name="a.vb"> Imports System.Console Module Module1 Sub Main() Dim i As Integer = 0 F1(i) F2(i, i) F2(1, 1) End Sub Sub F1(x As Byte) End Sub Sub F1(x As SByte) End Sub Sub F1(ByRef x As Long) End Sub Sub F2(x As Integer, ParamArray y As Byte()) End Sub Sub F2(x As SByte, y As Integer) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30519: Overload resolution failed because no accessible 'F1' can be called without a narrowing conversion: 'Public Sub F1(x As Byte)': Argument matching parameter 'x' narrows from 'Integer' to 'Byte'. 'Public Sub F1(x As SByte)': Argument matching parameter 'x' narrows from 'Integer' to 'SByte'. 'Public Sub F1(ByRef x As Long)': Copying the value of 'ByRef' parameter 'x' back to the matching argument narrows from type 'Long' to type 'Integer'. F1(i) ~~ BC30519: Overload resolution failed because no accessible 'F2' can be called without a narrowing conversion: 'Public Sub F2(x As Integer, ParamArray y As Byte())': Argument matching parameter 'y' narrows from 'Integer' to 'Byte'. 'Public Sub F2(x As SByte, y As Integer)': Argument matching parameter 'x' narrows from 'Integer' to 'SByte'. F2(i, i) ~~ BC30519: Overload resolution failed because no accessible 'F2' can be called without a narrowing conversion: 'Public Sub F2(x As Integer, ParamArray y As Byte())': Argument matching parameter 'y' narrows from 'Integer' to 'Byte'. 'Public Sub F2(x As SByte, y As Integer)': Argument matching parameter 'x' narrows from 'Integer' to 'SByte'. F2(1, 1) ~~ </expected>) End Sub <Fact(), WorkItem(527622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527622")> Public Sub NoisyDiagnostics() Dim compilationDef = <compilation> <file name="a.vb"> Option Strict On Imports System.Console Module Module1 Sub Main() F4(y:=Nothing,) End Sub Sub F4(x As Integer, y As Integer()) End Sub End Module Class C Private Sub M() Dim x As String = F(:'BIND:"F(" End Sub Private Function F(arg As Integer) As String Return "Hello" End Function Private Function F(arg As String) As String Return "Goodbye" End Function End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30201: Expression expected. F4(y:=Nothing,) ~ BC30241: Named argument expected. F4(y:=Nothing,) ~ BC30198: ')' expected. Dim x As String = F(:'BIND:"F(" ~ BC30201: Expression expected. Dim x As String = F(:'BIND:"F(" ~ </expected>) End Sub <Fact> Public Sub Bug4263() Dim compilationDef = <compilation name="Bug4263"> <file name="a.vb"> Option Strict Off Module M Sub Main() Dim x As String Dim y As Object = Nothing x = Goo(y).ToLower() x = Goo((y)).ToLower() End Sub Sub Goo(ByVal x As String) End Sub Function Goo(ByVal ParamArray x As String()) As String return Nothing End Function End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30491: Expression does not produce a value. x = Goo(y).ToLower() ~~~~~~ BC30491: Expression does not produce a value. x = Goo((y)).ToLower() ~~~~~~~~ </expected>) compilationDef = <compilation name="Bug4263"> <file name="a.vb"> Option Strict Off Imports System Module M Sub Main() Dim x As String x = Goo(CObj(Nothing)).ToLower() x = Goo(CObj((Nothing))).ToLower() x = Goo(CType(Nothing, Object)).ToLower() x = Goo(DirectCast(Nothing, Object)).ToLower() x = Goo(TryCast(Nothing, Object)).ToLower() x = Goo(CType(CStr(Nothing), Object)).ToLower() x = Goo(CType(CType(Nothing, ValueType), Object)).ToLower() x = Goo(CType(CType(CType(Nothing, Derived()), Base()), Object)).ToLower() x = Goo(CType(CType(CType(Nothing, Derived), Derived), Object)).ToLower() x = Goo(CType(Nothing, String())).ToLower() End Sub Sub Goo(ByVal x As String) End Sub Function Goo(ByVal ParamArray x As String()) As String System.Console.WriteLine("Function") Return "" End Function End Module Class Base End Class Class Derived Inherits Base End Class </file> </compilation> compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ Function Function Function Function Function Function Function Function Function Function ]]>) compilationDef = <compilation name="Bug4263"> <file name="a.vb"> Imports System Module M Sub Main() Goo(CObj(Nothing)) End Sub Sub Goo(ByVal x As String) End Sub Function Goo(ByVal ParamArray x As String()) As String System.Console.WriteLine("Function") Return "" End Function End Module </file> </compilation> compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30518: Overload resolution failed because no accessible 'Goo' can be called with these arguments: 'Public Sub Goo(x As String)': Option Strict On disallows implicit conversions from 'Object' to 'String'. 'Public Function Goo(ParamArray x As String()) As String': Option Strict On disallows implicit conversions from 'Object' to 'String()'. Goo(CObj(Nothing)) ~~~ </expected>) compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42016: Implicit conversion from 'Object' to 'String()'. Goo(CObj(Nothing)) ~~~~~~~~~~~~~ </expected>) compilationDef = <compilation name="Bug4263"> <file name="a.vb"> Imports System Module M Sub Main() Dim x As String = (CObj(Nothing)) End Sub End Module </file> </compilation> compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Object' to 'String'. Dim x As String = (CObj(Nothing)) ~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(539850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539850")> <Fact> Public Sub TestConversionFromZeroLiteralToEnum() Dim compilationDef = <compilation name="TestConversionFromZeroLiteralToEnum"> <file name="Program.vb"> Imports System Module Program Sub Main() Console.WriteLine(Goo(0).ToLower()) End Sub Sub Goo(x As DayOfWeek) End Sub Function Goo(x As Object) As String Return "ABC" End Function End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On)) CompileAndVerify(compilation, expectedOutput:="abc") compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off)) CompileAndVerify(compilation, expectedOutput:="abc") End Sub <WorkItem(528006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528006")> <Fact()> Public Sub TestConversionFromZeroLiteralToNullableEnum() Dim compilationDef = <compilation name="TestConversionFromZeroLiteralToNullableEnum"> <file name="Program.vb"> Option Strict On Imports System Module Program Sub Main() Console.WriteLine(Goo(0).ToLower()) End Sub Function Goo(x As DayOfWeek?) As String Return "ABC" End Function End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On)) CompileAndVerify(compilation, expectedOutput:="abc") End Sub <WorkItem(528011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528011")> <Fact()> Public Sub TestInvocationWithNamedArgumentInLambda() Dim compilationDef = <compilation name="TestInvocationWithNamedArgumentInLambda"> <file name="Program.vb"> Imports System Class B Sub Goo(x As Integer, ParamArray z As Integer()) System.Console.WriteLine("B.Goo") End Sub End Class Class C Inherits B Overloads Sub Goo(y As Integer) System.Console.WriteLine("C.Goo") End Sub End Class Module M Sub Main() Dim p as New C() p.Goo(x:=1) ' This fails to compile in Dev10, but works in Roslyn End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On)) CompileAndVerify(compilation, expectedOutput:="B.Goo") compilationDef = <compilation name="TestInvocationWithNamedArgumentInLambda"> <file name="Program.vb"> Imports System Class B Sub Goo(x As Integer, ParamArray z As Integer()) End Sub End Class Class C Inherits B Overloads Sub Goo(y As Integer) End Sub End Class Class D Overloads Sub Goo(x As Integer) End Sub End Class Module M Sub Main() Console.WriteLine(Bar(Sub(p) p.Goo(x:=1)).ToLower()) End Sub Sub Bar(a As Action(Of C)) End Sub Function Bar(a As Action(Of D)) As String Return "ABC" End Function End Module </file> </compilation> compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On)) compilation.AssertTheseDiagnostics(<![CDATA[ BC30521: Overload resolution failed because no accessible 'Bar' is most specific for these arguments: 'Public Sub Bar(a As Action(Of C))': Not most specific. 'Public Function Bar(a As Action(Of D)) As String': Not most specific. Console.WriteLine(Bar(Sub(p) p.Goo(x:=1)).ToLower()) ~~~]]>) compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off)) compilation.AssertTheseDiagnostics(<![CDATA[ BC30521: Overload resolution failed because no accessible 'Bar' is most specific for these arguments: 'Public Sub Bar(a As Action(Of C))': Not most specific. 'Public Function Bar(a As Action(Of D)) As String': Not most specific. Console.WriteLine(Bar(Sub(p) p.Goo(x:=1)).ToLower()) ~~~]]>) End Sub <WorkItem(539994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539994")> <Fact> Public Sub MethodTypeParameterInferenceBadArg() ' Method type parameter inference should complete in the case where ' the type of a method argument is ErrorType but HasErrors=False. Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> Class C Sub M(Of T)(x As T, y As T) End Sub Sub N() Dim d As D = GetD() M("", d.F) End Sub End Class </file> </compilation>) Dim diagnostics = compilation.GetDiagnostics().ToArray() ' The actual errors are not as important as ensuring compilation completes. ' (Just returning successfully from GetDiagnostics() is sufficient in this case.) Dim anyErrors = diagnostics.Length > 0 Assert.True(anyErrors) End Sub <Fact()> Public Sub InaccessibleMethods() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Module2 Private Sub M1(x as Integer) End Sub Private Sub M1(x as Long) End Sub Private Sub M2(x as Integer) End Sub Private Sub M2(x as Long, y as Integer) End Sub End Module Module Module1 Sub Main() M1(1) 'BIND1:"M1(1)" M1(1, 2) 'BIND2:"M1(1, 2)" M2(1, 2) 'BIND3:"M2(1, 2)" End Sub End Module ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30390: 'Module2.Private Sub M1(x As Integer)' is not accessible in this context because it is 'Private'. M1(1) 'BIND1:"M1(1)" ~~ BC30517: Overload resolution failed because no 'M1' is accessible. M1(1, 2) 'BIND2:"M1(1, 2)" ~~ BC30390: 'Module2.Private Sub M2(x As Long, y As Integer)' is not accessible in this context because it is 'Private'. M2(1, 2) 'BIND3:"M2(1, 2)" ~~ </expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As InvocationExpressionSyntax = CompilationUtils.FindBindingText(Of InvocationExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo As SymbolInfo = semanticModel.GetSymbolInfo(node1) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) Assert.Null(symbolInfo.Symbol) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("Sub Module2.M1(x As System.Int32)", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) End If If True Then Dim node2 As InvocationExpressionSyntax = CompilationUtils.FindBindingText(Of InvocationExpressionSyntax)(compilation, "a.vb", 2) Dim symbolInfo As SymbolInfo = semanticModel.GetSymbolInfo(node2) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) Assert.Null(symbolInfo.Symbol) Assert.Equal(2, symbolInfo.CandidateSymbols.Length) Assert.Equal("Sub Module2.M1(x As System.Int32)", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal("Sub Module2.M1(x As System.Int64)", symbolInfo.CandidateSymbols(1).ToTestDisplayString()) End If If True Then Dim node3 As InvocationExpressionSyntax = CompilationUtils.FindBindingText(Of InvocationExpressionSyntax)(compilation, "a.vb", 3) Dim symbolInfo As SymbolInfo = semanticModel.GetSymbolInfo(node3) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) Assert.Null(symbolInfo.Symbol) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("Sub Module2.M2(x As System.Int64, y As System.Int32)", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) End If End Sub <Fact()> Public Sub InaccessibleProperties() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Module2 Private Property P1(x as Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Private Property P1(x as Long) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Private Property P2(x as Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Private Property P2(x as Long, y as Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Module Module Module1 Sub Main() P1(1)=1 'BIND1:"P1(1)" P1(1, 2)=1 'BIND2:"P1(1, 2)" P2(1, 2)=1 'BIND3:"P2(1, 2)" Dim x = P2(1) End Sub End Module ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30389: 'Module2.P1(x As Integer)' is not accessible in this context because it is 'Private'. P1(1)=1 'BIND1:"P1(1)" ~~ BC30517: Overload resolution failed because no 'P1' is accessible. P1(1, 2)=1 'BIND2:"P1(1, 2)" ~~ BC30389: 'Module2.P2(x As Long, y As Integer)' is not accessible in this context because it is 'Private'. P2(1, 2)=1 'BIND3:"P2(1, 2)" ~~ BC30389: 'Module2.P2(x As Integer)' is not accessible in this context because it is 'Private'. Dim x = P2(1) ~~ </expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As InvocationExpressionSyntax = CompilationUtils.FindBindingText(Of InvocationExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo As SymbolInfo = semanticModel.GetSymbolInfo(node1) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) Assert.Null(symbolInfo.Symbol) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("Property Module2.P1(x As System.Int32) As System.Int32", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) End If If True Then Dim node2 As InvocationExpressionSyntax = CompilationUtils.FindBindingText(Of InvocationExpressionSyntax)(compilation, "a.vb", 2) Dim symbolInfo As SymbolInfo = semanticModel.GetSymbolInfo(node2) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) Assert.Null(symbolInfo.Symbol) Assert.Equal(2, symbolInfo.CandidateSymbols.Length) Assert.Equal("Property Module2.P1(x As System.Int32) As System.Int32", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal("Property Module2.P1(x As System.Int64) As System.Int32", symbolInfo.CandidateSymbols(1).ToTestDisplayString()) End If If True Then Dim node3 As InvocationExpressionSyntax = CompilationUtils.FindBindingText(Of InvocationExpressionSyntax)(compilation, "a.vb", 3) Dim symbolInfo As SymbolInfo = semanticModel.GetSymbolInfo(node3) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) Assert.Null(symbolInfo.Symbol) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("Property Module2.P2(x As System.Int64, y As System.Int32) As System.Int32", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) End If End Sub <Fact, WorkItem(545574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545574")> Public Sub OverloadWithIntermediateDifferentMember1() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class A Shared Sub Goo(x As Integer) End Sub End Class Class B Inherits A Shadows Property Goo As Integer End Class Class C Inherits B Overloads Shared Function Goo(x As Object) As Object Return Nothing End Function Shared Sub Bar() Goo(1).ToString() End Sub End Class ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC40004: function 'Goo' conflicts with property 'Goo' in the base class 'B' and should be declared 'Shadows'. Overloads Shared Function Goo(x As Object) As Object ~~~ </expected>) End Sub <Fact, WorkItem(545574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545574")> Public Sub OverloadWithIntermediateDifferentMember2() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class A Shared Sub Goo(x As Integer) End Sub End Class Class B Inherits A Overloads Property Goo As Integer End Class Class C Inherits B Overloads Shared Function Goo(x As Object) As Object Return Nothing End Function Shared Sub Bar() Goo(1).ToString() End Sub End Class ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC40004: property 'Goo' conflicts with sub 'Goo' in the base class 'A' and should be declared 'Shadows'. Overloads Property Goo As Integer ~~~ BC40004: function 'Goo' conflicts with property 'Goo' in the base class 'B' and should be declared 'Shadows'. Overloads Shared Function Goo(x As Object) As Object ~~~ </expected>) End Sub <Fact, WorkItem(545574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545574")> Public Sub OverloadWithIntermediateDifferentMember3() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface A Sub Goo(x As Integer) End Interface Interface B Inherits A Shadows Property Goo As Integer End Interface Interface C Inherits B Overloads Function Goo(x As Object) As Object End Interface Class D Shared Sub Bar() Dim q As C = Nothing q.Goo(1).ToString() End Sub End Class ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC40004: function 'Goo' conflicts with property 'Goo' in the base interface 'B' and should be declared 'Shadows'. Overloads Function Goo(x As Object) As Object ~~~ </expected>) End Sub <Fact, WorkItem(545520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545520")> Public Sub OverloadSameSigBetweenFunctionAndSub() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class A Shared Function Goo() As Integer() Return Nothing End Function End Class Class B Inherits A Overloads Shared Sub Goo() End Sub Sub Main() Goo(1).ToString() End Sub End Class ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32016: 'Public Shared Overloads Sub Goo()' has no parameters and its return type cannot be indexed. Goo(1).ToString() ~~~ </expected>) End Sub <Fact, WorkItem(545520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545520")> Public Sub OverloadSameSigBetweenFunctionAndSub2() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class A Shared Function Goo() As Integer() Return Nothing End Function End Class Class B Inherits A Overloads Shared Sub Goo(optional a as integer = 3) End Sub Sub Main() Goo(1).ToString() End Sub End Class ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32016: 'Public Shared Overloads Sub Goo([a As Integer = 3])' has no parameters and its return type cannot be indexed. Goo(1).ToString() ~~~ BC30491: Expression does not produce a value. Goo(1).ToString() ~~~~~~ </expected>) End Sub <Fact, WorkItem(545520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545520")> Public Sub OverloadSameSigBetweenFunctionAndSub3() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class A Shared Function Goo() As Integer() Return Nothing End Function End Class Class B Inherits A Overloads Shared Sub Goo(ParamArray a as Integer()) End Sub Sub Main() Goo(1).ToString() End Sub End Class ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact, WorkItem(545520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545520")> Public Sub OverloadSameSigBetweenFunctionAndSub4() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Interface A Function Goo() As Integer() End Interface Interface B Sub Goo() End Interface Interface C Inherits A, B End Interface Module M1 Sub Main() Dim c As C = Nothing c.Goo(1).ToString() End Sub End Module ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments. c.Goo(1).ToString() ~~~ </expected>) End Sub <Fact, WorkItem(546129, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546129")> Public Sub SameMethodNameDifferentCase() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Test Sub Main() Dim a = New class1 Dim O As Object = 5 a.Bb(O) End Sub Friend Class class1 Public Overridable Sub Bb(ByRef y As String) End Sub Public Overridable Sub BB(ByRef y As Short) End Sub End Class End Module ]]></file> </compilation>) compilation.VerifyDiagnostics() End Sub <WorkItem(544657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544657")> <Fact()> Public Sub Regress14728() Dim compilationDef = <compilation name="Regress14728"> <file name="Program.vb"> Option Strict Off Module Module1 Sub Main() Dim o As New class1 o.CallLateBound("qq", "aa") End Sub Class class1 Private Shared CurrentCycle As Integer Sub CallLateBound(ByVal ParamArray prmarray1() As Object) LateBound(prmarray1.GetUpperBound(0), prmarray1) End Sub Sub LateBound(ByVal ScenDesc As String, ByVal ParamArray prm1() As Object) System.Console.WriteLine(ScenDesc + prm1(0)) End Sub End Class End Module </file> </compilation> Dim Compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off)) CompileAndVerify(Compilation, expectedOutput:="1qq") End Sub <Fact(), WorkItem(544657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544657")> Public Sub Regress14728Err() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Module Module1 Sub Main() Dim o As New class1 o.CallLateBound("qq", "aa") End Sub Class class1 Private Shared CurrentCycle As Integer Sub CallLateBound(ByVal ParamArray prmarray1() As Object) LateBound(prmarray1.GetUpperBound(0), prmarray1) End Sub Sub LateBound(ByVal ScenDesc As String, ByVal ParamArray prm1() As Object) System.Console.WriteLine(ScenDesc + prm1(0)) End Sub Sub LateBound() System.Console.WriteLine("hi") End Sub End Class End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off)) CompileAndVerify(compilation, expectedOutput:="1qq") End Sub <Fact, WorkItem(546747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546747")> Public Sub Bug16716_1() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ <ProvideMenuResource(1000, 1)> Public NotInheritable Class TNuggetPackage Sub Test() Dim z As New ProvideMenuResourceAttribute(1000, 1) End Sub End Class Public Class ProvideMenuResourceAttribute Inherits System.Attribute Public Sub New(x As Short, y As Integer) End Sub Public Sub New(x As String, y As Integer) End Sub End Class ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30519: Overload resolution failed because no accessible 'New' can be called without a narrowing conversion: 'Public Sub New(x As Short, y As Integer)': Argument matching parameter 'x' narrows from 'Integer' to 'Short'. 'Public Sub New(x As String, y As Integer)': Argument matching parameter 'x' narrows from 'Integer' to 'String'. Dim z As New ProvideMenuResourceAttribute(1000, 1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Dim TNuggetPackage = compilation.GetTypeByMetadataName("TNuggetPackage") Assert.Equal("Sub ProvideMenuResourceAttribute..ctor(x As System.Int16, y As System.Int32)", TNuggetPackage.GetAttributes()(0).AttributeConstructor.ToTestDisplayString()) End Sub <Fact, WorkItem(546747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546747")> Public Sub Bug16716_2() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ <ProvideMenuResource(1000, 1)> Public NotInheritable Class TNuggetPackage End Class Public Class ProvideMenuResourceAttribute Inherits System.Attribute Public Sub New(x As Short, y As String) End Sub Public Sub New(x As String, y As Short) End Sub End Class ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30519: Overload resolution failed because no accessible 'New' can be called without a narrowing conversion: 'Public Sub New(x As Short, y As String)': Argument matching parameter 'x' narrows from 'Integer' to 'Short'. 'Public Sub New(x As Short, y As String)': Argument matching parameter 'y' narrows from 'Integer' to 'String'. 'Public Sub New(x As String, y As Short)': Argument matching parameter 'x' narrows from 'Integer' to 'String'. 'Public Sub New(x As String, y As Short)': Argument matching parameter 'y' narrows from 'Integer' to 'Short'. <ProvideMenuResource(1000, 1)> ~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact, WorkItem(546747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546747")> Public Sub Bug16716_3() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ <ProvideMenuResource(1000, 1)> Public NotInheritable Class TNuggetPackage End Class Public Class ProvideMenuResourceAttribute Inherits System.Attribute Public Sub New(x As String, y As Short) End Sub End Class ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30934: Conversion from 'Integer' to 'String' cannot occur in a constant expression used as an argument to an attribute. <ProvideMenuResource(1000, 1)> ~~~~ ]]></expected>) End Sub <Fact, WorkItem(546875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546875"), WorkItem(530930, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530930")> Public Sub BigVisitor() Dim source = <compilation> <file name="a.vb"> Public Module Test Sub Main() Dim visitor As New ConcreteVisitor() visitor.Visit(New Class090()) End Sub End Module </file> </compilation> Dim libRef = TestReferences.SymbolsTests.BigVisitor Dim start = DateTime.UtcNow CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {libRef}).VerifyDiagnostics() Dim elapsed = DateTime.UtcNow - start Assert.InRange(elapsed.TotalSeconds, 0, 5) ' The key is seconds - not minutes - so feel free to loosen. End Sub <Fact> Public Sub CompareSymbolsOriginalDefinition() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices <Assembly: InternalsVisibleTo("Goo")> Public Class Test(Of t1, t2) Public Sub Add(x As t1) End Sub Friend Sub Add(x As t2) End Sub End Class ]]> </file> </compilation> Dim source2 = <compilation name="Goo"> <file name="b.vb"> Public Class Test2 Public Sub Main() Dim x = New Test(Of Integer, Integer)() x.Add(5) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib(source, TestOptions.ReleaseDll) Dim comp2 = CreateCompilationWithMscorlib(source2, references:={comp.EmitToImageReference()}) CompilationUtils.AssertTheseDiagnostics(comp2, <expected> BC30521: Overload resolution failed because no accessible 'Add' is most specific for these arguments: 'Public Sub Add(x As Integer)': Not most specific. 'Friend Sub Add(x As Integer)': Not most specific. x.Add(5) ~~~ </expected>) End Sub <Fact(), WorkItem(738688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/738688")> Public Sub Regress738688_1() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Module Module1 Class C0Base Overloads Shared Widening Operator CType(x As C0Base) As NullReferenceException System.Console.Write("CType1") Return Nothing End Operator End Class Class C0 Inherits C0Base Overloads Shared Widening Operator CType(x As C0) As NullReferenceException System.Console.Write("CType2") Return Nothing End Operator End Class Class C1Base Overloads Shared Widening Operator CType(x As C1Base) As NullReferenceException() System.Console.Write("CType3") Return Nothing End Operator End Class Class C1 Inherits C1Base Overloads Shared Widening Operator CType(x As C1) As NullReferenceException() System.Console.Write("CType4") Return Nothing End Operator End Class Sub Main() Dim x1 As Exception = New C0 Dim x2 As Exception() = New C1 End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off)) CompileAndVerify(compilation, expectedOutput:="CType2CType4") End Sub <Fact(), WorkItem(738688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/738688")> Public Sub Regress738688_2() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Module Module1 Sub Main() C2.goo(New C2) End Sub Class C2 Public Shared Widening Operator CType(x As C2) As C2() Return New C2() {} End Operator Public Shared Sub goo(x As String) End Sub Public Shared Sub goo(ParamArray y As C2()) Console.WriteLine(y.Length) End Sub End Class End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off)) CompileAndVerify(compilation, expectedOutput:="1") End Sub <Fact(), WorkItem(738688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/738688")> Public Sub Regress738688Err() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System.Collections Module Module1 Sub Main() cls2.Goo("qq", New cls2) End Sub End Module Interface IGetExpression End Interface Interface IExpression Inherits IGetExpression End Interface Class cls0 Implements IExpression End Class Class cls1 Implements IExpression Public Shared Widening Operator CType(x As cls1) As IExpression() System.Console.WriteLine("CType") Return Nothing End Operator End Class Class cls2 Inherits cls1 Public Shared Function Goo(x As String) As String Return x End Function Public Shared Function Goo(x As String, ByVal ParamArray params() As IGetExpression) As String System.Console.WriteLine("Goo") Return Nothing End Function End Class ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30521: Overload resolution failed because no accessible 'Goo' is most specific for these arguments: 'Public Shared Function Goo(x As String, ParamArray params As IGetExpression()) As String': Not most specific. cls2.Goo("qq", New cls2) ~~~ ]]></expected>) End Sub <Fact(), WorkItem(738688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/738688")> Public Sub Regress738688Err01() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Module Module1 Sub Main() C2.goo(New C2) End Sub Interface i1 End Interface Class C2 Implements i1 Public Shared Widening Operator CType(x As C2) As i1() Return New C2() {} End Operator ' uncommenting this will change results in VBC ' Public Shared Sub goo(x as string) ' End Sub Public Shared Sub goo(ParamArray y As i1()) Console.WriteLine(y.Length) End Sub End Class End Module ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30521: Overload resolution failed because no accessible 'goo' is most specific for these arguments: 'Public Shared Sub goo(ParamArray y As Module1.i1())': Not most specific. C2.goo(New C2) ~~~ ]]></expected>) End Sub <Fact(), WorkItem(32, "https://roslyn.codeplex.com/workitem/31")> Public Sub BugCodePlex_32() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim b As New B() b.Test(Function() 1) End Sub End Module Class A Sub Test(x As System.Func(Of Integer)) System.Console.WriteLine("A.Test") End Sub End Class Class B Inherits A Overloads Sub Test(Of T)(x As System.Linq.Expressions.Expression(Of System.Func(Of T))) System.Console.WriteLine("B.Test") End Sub End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(compilationDef, {SystemCoreRef}, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="A.Test") End Sub <Fact(), WorkItem(918579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918579"), WorkItem(34, "CodePlex")> Public Sub Bug918579_01() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim p As IDerived = New CTest() Dim x = p.X End Sub End Module Public Interface IBase1 ReadOnly Property X As Integer End Interface Public Interface IBase2 ReadOnly Property X As Integer End Interface Public Interface IDerived Inherits IBase1, IBase2 Overloads ReadOnly Property X As Integer End Interface Class CTest Implements IDerived Public ReadOnly Property IDerived_X As Integer Implements IDerived.X Get System.Console.WriteLine("IDerived_X") Return 0 End Get End Property Private ReadOnly Property IBase1_X As Integer Implements IBase1.X Get System.Console.WriteLine("IBase1_X") Return 0 End Get End Property Private ReadOnly Property IBase2_X As Integer Implements IBase2.X Get System.Console.WriteLine("IBase2_X") Return 0 End Get End Property End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="IDerived_X") End Sub <Fact(), WorkItem(918579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918579"), WorkItem(34, "CodePlex")> Public Sub Bug918579_02() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim p As IDerived = New CTest() Dim x = p.X(CInt(0)) x = p.X(CShort(0)) x = p.X(CLng(0)) End Sub End Module Public Interface IBase1 ReadOnly Property X(y As Integer) As Integer End Interface Public Interface IBase2 ReadOnly Property X(y As Short) As Integer End Interface Public Interface IDerived Inherits IBase1, IBase2 Overloads ReadOnly Property X(y As Long) As Integer End Interface Class CTest Implements IDerived Public ReadOnly Property IDerived_X(y As Long) As Integer Implements IDerived.X Get System.Console.WriteLine("IDerived_X") Return 0 End Get End Property Private ReadOnly Property IBase1_X(y As Integer) As Integer Implements IBase1.X Get System.Console.WriteLine("IBase1_X") Return 0 End Get End Property Private ReadOnly Property IBase2_X(y As Short) As Integer Implements IBase2.X Get System.Console.WriteLine("IBase2_X") Return 0 End Get End Property End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:= "IBase1_X IBase2_X IDerived_X") End Sub <Fact(), WorkItem(918579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918579"), WorkItem(34, "CodePlex")> Public Sub Bug918579_03() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() End Sub Sub Test(x as I3) x.M1() End Sub Sub Test(x as I4) x.M1() End Sub End Module Interface I1(Of T) Sub M1() End Interface Interface I2 Inherits I1(Of String) Shadows Sub M1(x as Integer) End Interface Interface I3 Inherits I2, I1(Of Integer) End Interface Interface I4 Inherits I1(Of Integer), I2 End Interface ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompileAndVerify(compilation) End Sub <Fact, WorkItem(1034429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1034429")> Public Sub Bug1034429() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Security.Permissions Public Class A Inherits Attribute Public Sub New(ByVal ParamArray p As SecurityAction) End Sub End Class Public Class B Inherits Attribute Public Sub New(ByVal p1 As Integer, ByVal ParamArray p2 As SecurityAction) End Sub End Class Public Class C Inherits Attribute Public Sub New(ByVal p1 As Integer, ByVal ParamArray p2 As SecurityAction, ByVal p3 As String) End Sub End Class Module Module1 <A(SecurityAction.Assert)> <B(p2:=SecurityAction.Assert, p1:=0)> <C(p3:="again", p2:=SecurityAction.Assert, p1:=0)> Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30050: ParamArray parameter must be an array. Public Sub New(ByVal ParamArray p As SecurityAction) ~ BC30050: ParamArray parameter must be an array. Public Sub New(ByVal p1 As Integer, ByVal ParamArray p2 As SecurityAction) ~~ BC30050: ParamArray parameter must be an array. Public Sub New(ByVal p1 As Integer, ByVal ParamArray p2 As SecurityAction, ByVal p3 As String) ~~ BC30192: End of parameter list expected. Cannot define parameters after a paramarray parameter. Public Sub New(ByVal p1 As Integer, ByVal ParamArray p2 As SecurityAction, ByVal p3 As String) ~~~~~~~~~~~~~~~~~~ BC31092: ParamArray parameters must have an array type. <A(SecurityAction.Assert)> ~ BC30455: Argument not specified for parameter 'p1' of 'Public Sub New(p1 As Integer, ParamArray p2 As SecurityAction)'. <B(p2:=SecurityAction.Assert, p1:=0)> ~ BC31092: ParamArray parameters must have an array type. <B(p2:=SecurityAction.Assert, p1:=0)> ~ BC30661: Field or property 'p2' is not found. <B(p2:=SecurityAction.Assert, p1:=0)> ~~ BC30661: Field or property 'p1' is not found. <B(p2:=SecurityAction.Assert, p1:=0)> ~~ BC30455: Argument not specified for parameter 'p1' of 'Public Sub New(p1 As Integer, ParamArray p2 As SecurityAction, p3 As String)'. <C(p3:="again", p2:=SecurityAction.Assert, p1:=0)> ~ BC30455: Argument not specified for parameter 'p2' of 'Public Sub New(p1 As Integer, ParamArray p2 As SecurityAction, p3 As String)'. <C(p3:="again", p2:=SecurityAction.Assert, p1:=0)> ~ BC30455: Argument not specified for parameter 'p3' of 'Public Sub New(p1 As Integer, ParamArray p2 As SecurityAction, p3 As String)'. <C(p3:="again", p2:=SecurityAction.Assert, p1:=0)> ~ BC30661: Field or property 'p3' is not found. <C(p3:="again", p2:=SecurityAction.Assert, p1:=0)> ~~ BC30661: Field or property 'p2' is not found. <C(p3:="again", p2:=SecurityAction.Assert, p1:=0)> ~~ BC30661: Field or property 'p1' is not found. <C(p3:="again", p2:=SecurityAction.Assert, p1:=0)> ~~ ]]></expected>) End Sub <Fact, WorkItem(2604, "https://github.com/dotnet/roslyn/issues/2604")> Public Sub FailureDueToAnErrorInALambda_01() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() M0(0, Function() doesntexist) M1(0, Function() doesntexist) M2(0, Function() doesntexist) End Sub Sub M0(x As Integer, y As System.Func(Of Integer)) End Sub Sub M1(x As Integer, y As System.Func(Of Integer)) End Sub Sub M1(x As Long, y As System.Func(Of Long)) End Sub Sub M2(x As Integer, y As System.Func(Of Integer)) End Sub Sub M2(x As c1, y As System.Func(Of Long)) End Sub End Module Class c1 End Class ]]> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30451: 'doesntexist' is not declared. It may be inaccessible due to its protection level. M0(0, Function() doesntexist) ~~~~~~~~~~~ BC30451: 'doesntexist' is not declared. It may be inaccessible due to its protection level. M1(0, Function() doesntexist) ~~~~~~~~~~~ BC30451: 'doesntexist' is not declared. It may be inaccessible due to its protection level. M2(0, Function() doesntexist) ~~~~~~~~~~~ ]]></expected>) End Sub <Fact, WorkItem(4587, "https://github.com/dotnet/roslyn/issues/4587")> Public Sub FailureDueToAnErrorInALambda_02() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Threading.Tasks Imports System.Linq Module Module1 Sub Main() End Sub Private Async Function GetDataAsync(cs As Characters, imax As Integer) As Task Dim Roles = Await cs.GetRoleAsync() Dim RoleTasks = Roles.Select( Async Function(role As Role) As Task Dim Lines = Await role.GetLines() If imax <= LinesKey Then Return Dim SentenceTasks = Lines.Select( Async Function(Sentence) As Task Dim Words = Await Sentence.GetWordsAsync() If imax <= WordsKey Then Return Dim WordTasks = Words.Select( Async Function(Word) As Task Dim Letters = Await Word.GetLettersAsync() If imax <= LettersKey Then Return Dim StrokeTasks = Letters.Select( Async Function(Stroke) As Task Dim endpoints = Await Stroke.GetEndpointsAsync() Await Task.WhenAll(endpoints.ToArray()) End Function) Await Task.WhenAll(StrokeTasks.ToArray()) End Function) Await Task.WhenAll(WordTasks.ToArray()) End Function) Await Task.WhenAll(SentenceTasks.ToArray()) End Function) End Function Function RetryAsync(Of T)(f As Func(Of Task(Of T))) As Task(Of T) Return f() End Function End Module Friend Class Characters Function GetRoleAsync() As Task(Of List(Of Role)) Return Nothing End Function End Class Class Role Function GetLines() As Task(Of List(Of Line)) Return Nothing End Function End Class Public Class Line End Class ]]> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib45AndVBRuntime(compilationDef, additionalRefs:={SystemCoreRef}, options:=TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30451: 'LinesKey' is not declared. It may be inaccessible due to its protection level. If imax <= LinesKey Then Return ~~~~~~~~ BC30456: 'GetWordsAsync' is not a member of 'Line'. Dim Words = Await Sentence.GetWordsAsync() ~~~~~~~~~~~~~~~~~~~~~~ BC30451: 'WordsKey' is not declared. It may be inaccessible due to its protection level. If imax <= WordsKey Then Return ~~~~~~~~ ]]></expected>) End Sub <Fact, WorkItem(4587, "https://github.com/dotnet/roslyn/issues/4587")> Public Sub FailureDueToAnErrorInALambda_03() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Threading.Tasks Imports System.Linq Module Module1 Sub Main() End Sub Private Async Function GetDataAsync(DeliveryWindow As DeliveryWindow, MaxDepth As Integer) As Task Dim Vendors = Await RetryAsync(Function() DeliveryWindow.GetVendorsAsync()) Dim VendorTasks = Vendors.Select(Async Function(vendor As DeliveryWindowVendor) As Task Dim Departments = Await RetryAsync(Async Function() Await vendor.GetDeliveryWindowDepartmentsAsync()) If MaxDepth <= DepartmentsKey Then Return End If Dim DepartmentTasks = Departments.Select(Async Function(Department) As Task Dim Vendor9s = Await RetryAsync(Async Function() Await Department.GetDeliveryWindowVendor9Async()) If MaxDepth <= Vendor9Key Then Return End If Dim Vendor9Tasks = Vendor9s.Select(Async Function(Vendor9) As Task Dim poTypes = Await RetryAsync(Async Function() Await Vendor9.GetDeliveryWindowPOTypesAsync()) If MaxDepth <= POTypesKey Then Return End If Dim POTypeTasks = poTypes.Select(Async Function(poType) As Task Dim pos = Await RetryAsync(Async Function() Await poType.GetDeliveryWindowPOAsync()) If MaxDepth <= POsKey Then Return End If Dim POTasks = pos.ToList() _ .Select(Async Function(po) As Task Await RetryAsync(Async Function() Await po.GetDeliveryWindowPOLineAsync()) End Function) _ .ToArray() Await Task.WhenAll(POTasks.ToArray()) End Function) Await Task.WhenAll(POTypeTasks.ToArray()) End Function) Await Task.WhenAll(Vendor9Tasks.ToArray()) End Function) Await Task.WhenAll(DepartmentTasks.ToArray()) End Function) Await Task.WhenAll(VendorTasks.ToArray()) End Function Function RetryAsync(Of T)(f As Func(Of Task(Of T))) As Task(Of T) Return f() End Function End Module Friend Class DeliveryWindow Function GetVendorsAsync() As Task(Of List(Of DeliveryWindowVendor)) Return Nothing End Function End Class Class DeliveryWindowVendor Function GetDeliveryWindowDepartmentsAsync() As Task(Of List(Of DeliveryWindowDepartments)) Return Nothing End Function End Class Public Class DeliveryWindowDepartments End Class ]]> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib45AndVBRuntime(compilationDef, additionalRefs:={SystemCoreRef}, options:=TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30451: 'DepartmentsKey' is not declared. It may be inaccessible due to its protection level. If MaxDepth <= DepartmentsKey Then ~~~~~~~~~~~~~~ BC30456: 'GetDeliveryWindowVendor9Async' is not a member of 'DeliveryWindowDepartments'. Dim Vendor9s = Await RetryAsync(Async Function() Await Department.GetDeliveryWindowVendor9Async()) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30451: 'Vendor9Key' is not declared. It may be inaccessible due to its protection level. If MaxDepth <= Vendor9Key Then ~~~~~~~~~~ ]]></expected>) End Sub <WorkItem(9341, "https://github.com/dotnet/roslyn/issues/9341")> <Fact()> Public Sub FailureDueToAnErrorInALambda_04() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Test Sub Main() Invoke( Sub() M1("error here") End Sub) End Sub Sub M1() End Sub Public Sub Invoke(callback As Action) End Sub Function Invoke(Of TResult)(callback As Func(Of TResult)) As TResult Return Nothing End Function End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30057: Too many arguments to 'Public Sub M1()'. M1("error here") ~~~~~~~~~~~~ </expected>) End Sub <Fact> <WorkItem(16478, "https://github.com/dotnet/roslyn/issues/16478")> Public Sub AmbiguousInference_01() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class Test Public Shared Sub Assert(Of T)(a As T, b As T) Console.WriteLine("Non collection") End Sub Public Shared Sub Assert(Of T)(a As IEnumerable(Of T), b As IEnumerable(Of T)) Console.WriteLine("Collection") End Sub Public Shared Sub Main() Dim a = {"A"} Dim b = New StringValues() Assert(a, b) Assert(b, a) End Sub Private Class StringValues Inherits List(Of String) Public Shared Widening Operator CType(values As String()) As StringValues Return New StringValues() End Operator Public Shared Widening Operator CType(value As StringValues) As String() Return {} End Operator End Class End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) CompileAndVerify(compilationDef, expectedOutput:= "Collection Collection") End Sub <Fact> <WorkItem(16478, "https://github.com/dotnet/roslyn/issues/16478")> Public Sub AmbiguousInference_02() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class Test Public Shared Sub Assert(Of T)(a As T, b As T) Console.WriteLine("Non collection") End Sub Public Shared Sub Main() Dim a = {"A"} Dim b = New StringValues() Assert(a, b) Assert(b, a) End Sub Private Class StringValues Inherits List(Of String) Public Shared Widening Operator CType(values As String()) As StringValues Return New StringValues() End Operator Public Shared Widening Operator CType(value As StringValues) As String() Return {} End Operator End Class End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36651: Data type(s) of the type parameter(s) in method 'Public Shared Sub Assert(Of T)(a As T, b As T)' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error. Assert(a, b) ~~~~~~ BC36651: Data type(s) of the type parameter(s) in method 'Public Shared Sub Assert(Of T)(a As T, b As T)' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error. Assert(b, a) ~~~~~~ </expected>) End Sub End Class End Namespace
kelltrick/roslyn
src/Compilers/VisualBasic/Test/Semantic/Semantics/OverloadResolution.vb
Visual Basic
apache-2.0
275,798
' 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.Composition Imports System.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.ApiDesignGuidelines.Analyzers ''' <summary> ''' CA1716: Identifiers should not match keywords ''' </summary> <ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]> Public NotInheritable Class BasicIdentifiersShouldNotMatchKeywordsFixer Inherits IdentifiersShouldNotMatchKeywordsFixer End Class End Namespace
mattwar/roslyn-analyzers
src/Microsoft.ApiDesignGuidelines.Analyzers/VisualBasic/BasicIdentifiersShouldNotMatchKeywords.Fixer.vb
Visual Basic
apache-2.0
747
Imports Microsoft.VisualStudio.Language Imports My.Resources Namespace Xeora.VSAddIn.IDE.Editor.Completion.SourceBuilder Public Class Translation Inherits BuilderBase Public Sub New(ByVal Directive As [Enum]) MyBase.New(Directive) End Sub Public Overrides Function Build() As Intellisense.Completion() Dim CompList As New Generic.List(Of Intellisense.Completion)() Dim LanguagesPath As String = IO.Path.Combine(MyBase.LocateTemplatesPath(PackageControl.IDEControl.DTE.ActiveDocument.Path), "..", "Languages") Me.Fill(CompList, LanguagesPath, False) If PackageControl.IDEControl.GetActiveItemDomainType() = Globals.ActiveDomainTypes.Child Then Dim DomainID As String = String.Empty Dim SearchDI As New IO.DirectoryInfo(LanguagesPath) Do SearchDI = SearchDI.Parent If Not SearchDI Is Nothing Then DomainID = SearchDI.Name SearchDI = SearchDI.Parent End If If Not SearchDI Is Nothing AndAlso ( String.Compare(SearchDI.Name, "Domains", True) = 0 OrElse String.Compare(SearchDI.Name, "Addons", True) = 0 ) Then Me.Fill(CompList, IO.Path.Combine(SearchDI.FullName, DomainID, "Languages"), True) If String.Compare(SearchDI.Name, "Domains", True) = 0 Then SearchDI = Nothing End If Loop Until SearchDI Is Nothing End If CompList.Sort(New CompletionComparer()) Return CompList.ToArray() End Function Public Overrides Function Builders() As Intellisense.Completion() Return New Intellisense.Completion() { New Intellisense.Completion("Create New Translation", "__CREATE.TRANSLATE__", String.Empty, Nothing, Nothing) } End Function Private Sub Fill(ByRef Container As Generic.List(Of Intellisense.Completion), ByVal LanguagesPath As String, ByVal IsParentSearch As Boolean) Dim cFStream As IO.FileStream = Nothing Try Dim TranslationFileNames As String() = IO.Directory.GetFiles(LanguagesPath, "*.xml") Dim TranslationCompile As New Generic.Dictionary(Of String, Integer) For Each TranslationFileName As String In TranslationFileNames Try cFStream = New IO.FileStream( TranslationFileName, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.ReadWrite) Dim xPathDocument As New Xml.XPath.XPathDocument(cFStream) Dim xPathNavigator As Xml.XPath.XPathNavigator = xPathDocument.CreateNavigator() Dim xPathIter As Xml.XPath.XPathNodeIterator xPathIter = xPathNavigator.Select("/language/translation") Do While xPathIter.MoveNext() Dim TransID As String = xPathIter.Current.GetAttribute("id", xPathIter.Current.NamespaceURI) If TranslationCompile.ContainsKey(TransID) Then _ TranslationCompile.Item(TransID) += 1 Else TranslationCompile.Add(TransID, 1) Loop Catch ex As Exception ' Just Handle Exceptions Finally If Not cFStream Is Nothing Then cFStream.Close() End Try Next For Each TransIDKey As String In TranslationCompile.Keys If TranslationCompile.Item(TransIDKey) = TranslationFileNames.Length AndAlso Not Me.IsExists(Container, TransIDKey) Then If Not IsParentSearch Then Container.Add( New Intellisense.Completion( TransIDKey, String.Format("{0}$", TransIDKey), String.Empty, Me.ProvideImageSource(IconResource.domain_level_translation), Nothing ) ) Else Container.Add( New Intellisense.Completion( TransIDKey, String.Format("{0}$", TransIDKey), String.Empty, Me.ProvideImageSource(IconResource.parent_level_translation), Nothing ) ) End If End If Next Catch ex As Exception ' Just Handle Exceptions End Try End Sub End Class End Namespace
xeora/v6
Tools/XeoraVSExtension/Xeora.VSAddIn/IDE/Editor/Completion/SourceBuilder/Translation.vb
Visual Basic
mit
5,182
' 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.VisualBasic.Indentation Imports Microsoft.CodeAnalysis.Wrapping.SeparatedSyntaxList Namespace Microsoft.CodeAnalysis.VisualBasic.Wrapping.SeparatedSyntaxList Partial Friend MustInherit Class AbstractVisualBasicSeparatedSyntaxListWrapper( Of TListSyntax As SyntaxNode, TListItemSyntax As SyntaxNode) Inherits AbstractSeparatedSyntaxListWrapper(Of TListSyntax, TListItemSyntax) Protected Sub New() MyBase.New(VisualBasicIndentationService.WithoutParameterAlignmentInstance) End Sub End Class End Namespace
nguerrera/roslyn
src/Features/VisualBasic/Portable/Wrapping/SeparatedSyntaxList/AbstractVisualBasicSeparatedSyntaxListWrapper.vb
Visual Basic
apache-2.0
753
' Copyright (c) 2015 ZZZ Projects. All rights reserved ' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods) ' Website: http://www.zzzprojects.com/ ' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927 ' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library Imports System.Collections.Generic Imports System.Data.SqlClient Imports System.Linq Public Module Extensions_646 ''' <summary> ''' An IDictionary&lt;string,object&gt; extension method that converts the @this to a SQL parameters. ''' </summary> ''' <param name="this">The @this to act on.</param> ''' <returns>@this as a SqlParameter[].</returns> <System.Runtime.CompilerServices.Extension> _ Public Function ToSqlParameters(this As IDictionary(Of String, Object)) As SqlParameter() Return this.[Select](Function(x) New SqlParameter(x.Key, x.Value)).ToArray() End Function End Module
huoxudong125/Z.ExtensionMethods
src (VB.NET)/Z.ExtensionMethods.VB/Z.Data/System.Collections.Generic.IDictionary[string, object]/IDictionary[string, object].ToSqlParameters.vb
Visual Basic
mit
982
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:2.0.50727.3082 ' ' 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", "9.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.WindowsApplication1.My.MySettings Get Return Global.WindowsApplication1.My.MySettings.Default End Get End Property End Module End Namespace
niikoo/NProj
Windows/Skole/Oppgave 16 - Rentesrente GUI/Oppgave 16 - Rentesrente GUI/My Project/Settings.Designer.vb
Visual Basic
apache-2.0
2,985
' 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.Composition Imports Microsoft.CodeAnalysis.Editor.GoToDefinition Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.GoToDefinition <ExportLanguageService(GetType(IGoToDefinitionService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicGoToDefinitionService Inherits AbstractGoToDefinitionService <ImportingConstructor> Public Sub New(<ImportMany> streamingPresenters As IEnumerable(Of Lazy(Of IStreamingFindUsagesPresenter))) MyBase.New(streamingPresenters) End Sub Protected Overrides Function FindRelatedExplicitlyDeclaredSymbol(symbol As ISymbol, compilation As Compilation) As ISymbol Return symbol.FindRelatedExplicitlyDeclaredSymbol(compilation) End Function End Class End Namespace
bbarry/roslyn
src/EditorFeatures/VisualBasic/GoToDefinition/VisualBasicGoToDefinitionService.vb
Visual Basic
apache-2.0
1,102
Imports System Imports System.Collections.Generic Imports System.IO Imports System.Linq Imports System.Runtime.InteropServices.WindowsRuntime Imports Windows.Foundation Imports Windows.Foundation.Collections Imports Windows.UI.Core Imports Windows.UI.Xaml Imports Windows.UI.Xaml.Controls Imports Windows.UI.Xaml.Controls.Primitives Imports Windows.UI.Xaml.Data Imports Windows.UI.Xaml.Input Imports Windows.UI.Xaml.Media Imports Windows.UI.Xaml.Navigation Namespace Global.SDKTemplate ''' <summary> ''' An empty page that can be used on its own or navigated to within a Frame. ''' </summary> Public NotInheritable Partial Class SecondaryPage Inherits Page Public Sub New() Me.InitializeComponent() End Sub Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs) Dim optedIn As Boolean = False If CType(e.Parameter, Boolean) Then optedIn = True End If Dim rootFrame As Frame = TryCast(Window.Current.Content, Frame) If rootFrame.CanGoBack AndAlso optedIn Then SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible Else SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed End If End Sub End Class End Namespace
japf/Windows-universal-samples
Samples/BackButton/vb/SecondaryPage.xaml.vb
Visual Basic
mit
1,443
' 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.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBVariableInitializerTests Inherits BasicTestBase <Fact> Public Sub PartialClass() Dim source = <compilation> <file name="a.vb"> Option strict on imports system partial Class C1 public f1 as integer = 23 public f3 As New C1() public f4, f5 As New C1() Public sub DumpFields() Console.WriteLine(f1) Console.WriteLine(f2) End Sub Public shared Sub Main(args() as string) Dim c as new C1 c.DumpFields() End sub End Class </file> <file name="b.vb"> Option strict on imports system partial Class C1 ' more lines to see a different span in the sequence points ... public f2 as integer = 42 End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("C1..ctor", <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=" 1, 41, D1, CA, DD, B0, B, 39, BE, 3C, 3D, 69, AA, 18, B3, 7A, F5, 65, C5, DD, "/> <file id="2" name="b.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="FE, FF, 3A, FC, 5E, 54, 7C, 6D, 96, 86, 5, B8, B6, FD, FC, 5F, 81, 51, AE, FA, "/> </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="6" startColumn="12" endLine="6" endColumn="30" document="1"/> <entry offset="0xf" startLine="7" startColumn="12" endLine="7" endColumn="26" document="1"/> <entry offset="0x1a" startLine="8" startColumn="12" endLine="8" endColumn="14" document="1"/> <entry offset="0x25" startLine="8" startColumn="16" endLine="8" endColumn="18" document="1"/> <entry offset="0x30" startLine="11" startColumn="36" endLine="11" endColumn="54" document="2"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x39"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <Fact> Public Sub AutoProperty1() Dim source = <compilation> <file> Interface I Property P As Integer End Interface Class C Implements I Property P As Integer = 1 Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P As Integer = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <Fact> Public Sub AutoProperty2() Dim source = <compilation> <file> Interface I Property P As Object End Interface Class C Implements I Property P = 1 Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <Fact> Public Sub AutoPropertyAsNew() Dim source = <compilation> <file> Interface I Property P As Integer End Interface Class C Implements I Property P As New Integer Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P As New Integer".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <Fact> Public Sub ArrayInitializedField() Dim source = <compilation> <file> Class C Dim F(1), G(2) As Integer End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F(1)".Length + 1 Dim expectedStart2 = " Dim F(1), ".Length + 1 Dim expectedEnd2 = " Dim F(1), G(2)".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> <entry startLine="2" startColumn=<%= expectedStart2 %> endLine="2" endColumn=<%= expectedEnd2 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <Fact> Public Sub ArrayInitializedLocal() Dim source = <compilation> <file> Class C Sub M Dim F(1), G(2) As Integer End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F(1)".Length + 1 Dim expectedStart2 = " Dim F(1), ".Length + 1 Dim expectedEnd2 = " Dim F(1), G(2)".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="3" startColumn=<%= expectedStart2 %> endLine="3" endColumn=<%= expectedEnd2 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <Fact> Public Sub FieldAsNewMultiInitializer() Dim source = <compilation> <file> Class C Dim F, G As New C() End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F".Length + 1 Dim expectedStart2 = " Dim F, ".Length + 1 Dim expectedEnd2 = " Dim F, G".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> <entry startLine="2" startColumn=<%= expectedStart2 %> endLine="2" endColumn=<%= expectedEnd2 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <Fact> Public Sub LocalAsNewMultiInitializer() Dim source = <compilation> <file> Class C Sub M Dim F, G As New C() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F".Length + 1 Dim expectedStart2 = " Dim F, ".Length + 1 Dim expectedEnd2 = " Dim F, G".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="3" startColumn=<%= expectedStart2 %> endLine="3" endColumn=<%= expectedEnd2 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <Fact> Public Sub FieldAsNewSingleInitializer() Dim source = <compilation> <file> Class C Dim F As New C() End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F As New C()".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <Fact> Public Sub LocalAsNewSingleInitializer() Dim source = <compilation> <file> Class C Sub M Dim F As New C() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F As New C()".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <Fact> Public Sub FieldInitializer() Dim source = <compilation> <file> Class C Dim F = 1 End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <Fact> Public Sub LocalInitializer() Dim source = <compilation> <file> Class C Sub M Dim F = 1 End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F = 1".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub End Class End Namespace
pdelvo/roslyn
src/Compilers/VisualBasic/Test/Emit/PDB/PDBVariableInitializerTests.vb
Visual Basic
apache-2.0
13,127
Public Class passwordForm Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click If passwordTextBox.Text = "admin" Then Me.Close() homeForm.TabControl1.SelectTab(3) Else MsgBox("The password you have entered is incorrect.", 0, "Wrong Password") End If End Sub Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged If CheckBox1.Checked = True Then passwordTextBox.UseSystemPasswordChar = False Else passwordTextBox.UseSystemPasswordChar = True End If End Sub Private Sub passwordTextBox_TextChanged(sender As Object, e As EventArgs) Handles passwordTextBox.TextChanged End Sub End Class
feedbo/feedbo
Feedbo/Form2.vb
Visual Basic
mit
830
'This code will delete views, filters and view templates from your Project Public Sub deleteElements() 'assigns document to the active document in use Dim document As Document = Me.ActiveUIDocument.Document ''get all the views and view template ids. Internally revit see view templates as view. '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '' original code. Doesn't actually get all views ' Dim viewidCollection As IEnumerable(Of ElementId) = From v As View In New FilteredElementCollector(document).OfCategory(BuiltInCategory.OST_Views).cast(Of view) ' Where v.ViewType = ViewType.AreaPlan Or _ ' v.ViewType = ViewType.CeilingPlan Or _ ' v.ViewType = ViewType.ColumnSchedule Or _ ' v.ViewType = ViewType.CostReport Or _ ' v.ViewType = ViewType.Detail Or _ ' v.ViewType = ViewType.DraftingView Or _ ' v.ViewType = ViewType.Legend Or _ ' v.ViewType = ViewType.LoadsReport Or _ ' v.ViewType = ViewType.PanelSchedule Or _ ' v.ViewType = ViewType.PresureLossReport Or _ ' v.ViewType = ViewType.Rendering Or _ ' v.ViewType = ViewType.Report Or _ ' v.ViewType = ViewType.Section Or _ ' v.ViewType = ViewType.ThreeD Or _ ' v.ViewType = ViewType.Walkthrough Or _ ' v.ViewType = ViewType.Elevation Or _ ' v.ViewType = ViewType.Undefined Or _ ' v.ViewType = ViewType.DrawingSheet Or _ ' v.IsTemplate ' Select v.Id '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 'updated code gets element ids of all views and view templates except project browser, system browser and active view as these cannot be deleted Dim viewCollection As list(Of ElementId) = (From v As View In New FilteredElementCollector(document).OfCategory(BuiltInCategory.OST_Views).cast(Of view) Where v.ViewType <> ViewType.ProjectBrowser And _ v.ViewType <> ViewType.SystemBrowser And _ v.ViewType <> ViewType.Internal And _ v.Id <> document.ActiveView.id Select v.id).tolist 'get all the view filter ids Dim filteridCollection As list(Of ElementId) = (New FilteredElementCollector(document) _ .ofclass(GetType(ParameterFilterElement)) _ .WhereElementIsNotElementType _ .ToElementids()).tolist 'Start a transaction CRITICAL without transactions Revit cannot update Using rvtTransaction As New Transaction(document,"Delete all views") rvtTransaction.Start() 'delete the views document.Delete(viewCollection) 'delete the filters document.Delete(filteridCollection) 'Commit the changes to the Revit File rvtTransaction.Commit End Using End Sub
Gytaco/RevitAPI
Macros/deleteElements/deleteElements.vb
Visual Basic
mit
2,934
Imports System.Threading Public Class CacheScope Implements IDisposable #Region "Properties" Private Shared _CacheLock As New Object() Private Shared _Caches As Dictionary(Of Integer, Cache) Private Shared ReadOnly Property Caches As Dictionary(Of Integer, Cache) Get If _Caches Is Nothing Then _Caches = New Dictionary(Of Integer, Cache)() End If Return _Caches End Get End Property Public Shared ReadOnly Property CurrentCache As Cache Get Dim value As Cache = Nothing Caches.TryGetValue(Thread.CurrentThread.ManagedThreadId, value) Return value End Get End Property #End Region #Region "Constructors" Public Sub New() If Not Caches.ContainsKey(Thread.CurrentThread.ManagedThreadId) Then SyncLock _CacheLock Caches(Thread.CurrentThread.ManagedThreadId) = New Cache(Me) End SyncLock End If End Sub #End Region #Region "IDisposable Support" Private _IsDisposed As Boolean ' To detect redundant calls Protected Overridable Sub Dispose(disposing As Boolean) If Not _IsDisposed Then Dim current = CurrentCache If current IsNot Nothing AndAlso current.Owner Is Me Then SyncLock _CacheLock Caches.Remove(Thread.CurrentThread.ManagedThreadId) End SyncLock End If End If _IsDisposed = True End Sub Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub #End Region End Class
Symmex/Snowflake
Source/Symmex.Snowflake.Caching/CacheScope.vb
Visual Basic
mit
1,685
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 dimensionStyles As SolidEdgeFrameworkSupport.DimensionStyles = Nothing Dim sheet As SolidEdgeDraft.Sheet = Nothing Dim datumTargets As SolidEdgeFrameworkSupport.DatumTargets = Nothing Dim datumTarget As SolidEdgeFrameworkSupport.DatumTarget = 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) dimensionStyles = CType(draftDocument.DimensionStyles, SolidEdgeFrameworkSupport.DimensionStyles) sheet = draftDocument.ActiveSheet datumTargets = CType(sheet.DatumTargets, SolidEdgeFrameworkSupport.DatumTargets) Dim style = datumTargets.Style datumTargets.Style = dimensionStyles.Item(2) style = datumTargets.Style 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.DatumTargets.Style.vb
Visual Basic
mit
1,882
Public Class SwitchTypeProperties Public Class Agilent87106D Private _maxSwitchPositions As Integer = 6 Property GetMaxSwitchPositions() As Integer Get Return _maxSwitchPositions End Get Set(ByVal value As Integer) _maxSwitchPositions = Value End Set End Property End Class Public Class RadiallRSeries Inherits Agilent87106D End Class End Class
wboxx1/85-EIS-PUMA
puma/src/Supporting Objects/SwitchTypeProperties.vb
Visual Basic
mit
482
'------------------------------------------------------------------------------ ' <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 <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.TestingGrounds.My.MySettings Get Return Global.TestingGrounds.My.MySettings.Default End Get End Property End Module End Namespace
Audiopolis/Gruppe21-prosjekt
TestingGrounds/TestingGrounds/My Project/Settings.Designer.vb
Visual Basic
mit
2,918
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("MajorWork")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("MajorWork")> <Assembly: AssemblyCopyright("Copyright © 2016")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("1bb25410-096b-4572-b197-7c70c927d024")> ' 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")>
SDDHSC/MajorWork
My Project/AssemblyInfo.vb
Visual Basic
mit
1,162
Imports System.Drawing.Drawing2D Namespace UI Public Class BouttonProduit Inherits Panel Private Const CS_DROPSHADOW As Integer = 131072 Protected Overrides Sub OnPaint(e As PaintEventArgs) Dim c2 As Color = Color.FromArgb(201, 197, 202) Dim c1 As Color = Color.FromArgb(174, 174, 174) Using b As New System.Drawing.Drawing2D.LinearGradientBrush(Me.ClientRectangle, c1, c2, Drawing2D.LinearGradientMode.ForwardDiagonal) e.Graphics.FillRectangle(b, Me.ClientRectangle) End Using Dim gp As GraphicsPath = GetPath(Me.ClientRectangle, 10) Me.Region = New Region(gp) End Sub Private Function GetPath(ByVal rc As Rectangle, ByVal r As Int32) As GraphicsPath Dim x As Int32 = rc.X, y As Int32 = rc.Y, w As Int32 = rc.Width, h As Int32 = rc.Height r = r << 1 Dim path As GraphicsPath = New GraphicsPath If r > 0 Then If (r > h) Then r = h If (r > w) Then r = w path.AddArc(x, y, r, r, 180, 90) path.AddArc(x + w - r, y, r, r, 270, 90) path.AddArc(x + w - r, y + h - r, r, r, 0, 90) path.AddArc(x, y + h - r, r, r, 90, 90) path.CloseFigure() Else path.AddRectangle(rc) End If Return path End Function End Class End Namespace
lepresk/HG
HG/UI/BouttonProduit.vb
Visual Basic
mit
1,484
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class frmReportClassListBySectionCode Inherits ComponentFactory.Krypton.Toolkit.KryptonForm '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.components = New System.ComponentModel.Container Dim ReportDataSource1 As Microsoft.Reporting.WinForms.ReportDataSource = New Microsoft.Reporting.WinForms.ReportDataSource Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmReportClassListBySectionCode)) Me.ClassSectionClassListBindingSource = New System.Windows.Forms.BindingSource(Me.components) Me.StatusStrip1 = New System.Windows.Forms.StatusStrip Me.ToolStripStatusLabel1 = New System.Windows.Forms.ToolStripStatusLabel Me.ReportViewer1 = New Microsoft.Reporting.WinForms.ReportViewer CType(Me.ClassSectionClassListBindingSource, System.ComponentModel.ISupportInitialize).BeginInit() Me.StatusStrip1.SuspendLayout() Me.SuspendLayout() ' 'ClassSectionClassListBindingSource ' Me.ClassSectionClassListBindingSource.DataSource = GetType(SMS.ClassSectionClassList) ' 'StatusStrip1 ' Me.StatusStrip1.Font = New System.Drawing.Font("Segoe UI", 8.25!) Me.StatusStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ToolStripStatusLabel1}) Me.StatusStrip1.Location = New System.Drawing.Point(0, 457) Me.StatusStrip1.Margin = New System.Windows.Forms.Padding(1) Me.StatusStrip1.Name = "StatusStrip1" Me.StatusStrip1.Padding = New System.Windows.Forms.Padding(1, 0, 16, 0) Me.StatusStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.ManagerRenderMode Me.StatusStrip1.Size = New System.Drawing.Size(658, 22) Me.StatusStrip1.TabIndex = 4 Me.StatusStrip1.Text = "StatusStrip1" ' 'ToolStripStatusLabel1 ' Me.ToolStripStatusLabel1.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.ToolStripStatusLabel1.Name = "ToolStripStatusLabel1" Me.ToolStripStatusLabel1.Size = New System.Drawing.Size(144, 17) Me.ToolStripStatusLabel1.Text = " ToolStripStatusLabel1" ' 'ReportViewer1 ' Me.ReportViewer1.Dock = System.Windows.Forms.DockStyle.Fill ReportDataSource1.Name = "SMS_ClassSectionClassList" ReportDataSource1.Value = Me.ClassSectionClassListBindingSource Me.ReportViewer1.LocalReport.DataSources.Add(ReportDataSource1) Me.ReportViewer1.LocalReport.ReportEmbeddedResource = "SMS.ReportClassListBySectionCode.rdlc" Me.ReportViewer1.Location = New System.Drawing.Point(0, 0) Me.ReportViewer1.Name = "ReportViewer1" Me.ReportViewer1.Size = New System.Drawing.Size(658, 457) Me.ReportViewer1.TabIndex = 5 ' 'frmReportClassListBySectionCode ' Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 16.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.SystemColors.GradientInactiveCaption Me.ClientSize = New System.Drawing.Size(658, 479) Me.Controls.Add(Me.ReportViewer1) Me.Controls.Add(Me.StatusStrip1) Me.Font = New System.Drawing.Font("Tahoma", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4) Me.Name = "frmReportClassListBySectionCode" Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "Report Class List" Me.WindowState = System.Windows.Forms.FormWindowState.Maximized CType(Me.ClassSectionClassListBindingSource, System.ComponentModel.ISupportInitialize).EndInit() Me.StatusStrip1.ResumeLayout(False) Me.StatusStrip1.PerformLayout() Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents StatusStrip1 As System.Windows.Forms.StatusStrip Friend WithEvents ToolStripStatusLabel1 As System.Windows.Forms.ToolStripStatusLabel Friend WithEvents ReportViewer1 As Microsoft.Reporting.WinForms.ReportViewer Friend WithEvents ClassSectionClassListBindingSource As System.Windows.Forms.BindingSource End Class
JeffreyAReyes/eSMS
Forms/FormsReports/frmReportClassListBySectionCode.Designer.vb
Visual Basic
mit
5,295
' 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.CompilerServices Imports CompilationCreationTestHelpers Imports Microsoft.CodeAnalysis.Test.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE Public Class LoadingEvents : Inherits BasicTestBase <Fact> Public Sub LoadNonGenericEvents() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.SymbolsTests.Events}) Dim globalNamespace = assemblies.ElementAt(1).GlobalNamespace Dim [class] = globalNamespace.GetMember(Of NamedTypeSymbol)("NonGeneric") CheckInstanceAndStaticEvents([class], "System.Action") End Sub <Fact> Public Sub LoadGenericEvents() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.SymbolsTests.Events}) Dim globalNamespace = assemblies.ElementAt(1).GlobalNamespace Dim [class] = globalNamespace.GetMember(Of NamedTypeSymbol)("Generic") CheckInstanceAndStaticEvents([class], "System.Action(Of T)") End Sub <Fact> Public Sub LoadClosedGenericEvents() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.SymbolsTests.Events}) Dim globalNamespace = assemblies.ElementAt(1).GlobalNamespace Dim [class] = globalNamespace.GetMember(Of NamedTypeSymbol)("ClosedGeneric") CheckInstanceAndStaticEvents([class], "System.Action(Of System.Int32)") End Sub <Fact> Public Sub Error_Regress40025DLL() Dim source = <compilation name="Error_Regress40025DLL1"> <file name="a.vb"> Module Program Sub Main() Dim d As Regress40025DLL.Regress40025DLL.AClass = nothing 'COMPILEERROR: BC30005, "ee" AddHandler d.ee, Nothing End Sub End Module </file> </compilation> Dim ref = MetadataReference.CreateFromImage(TestResources.General.Regress40025DLL.AsImmutableOrNull()) Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, {ref}, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(c1, <errors> BC30005: Reference required to assembly 'System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the definition for event 'Public Event ee As PlayRecordCallback'. Add one to your project. AddHandler d.ee, Nothing ~~~~ </errors>) Dim diagnostics = c1.GetDiagnostics() Assert.True(diagnostics.Any(Function(d) d.Code = ERRID.ERR_UnreferencedAssemblyEvent3)) For Each d In diagnostics If d.Code = ERRID.ERR_UnreferencedAssemblyEvent3 Then Dim actualAssemblyId = c1.GetUnreferencedAssemblyIdentities(d).Single() Dim expectedAssemblyId As AssemblyIdentity = Nothing AssemblyIdentity.TryParseDisplayName("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", expectedAssemblyId) Assert.Equal(actualAssemblyId, expectedAssemblyId) End If Next End Sub Private Shared Sub CheckInstanceAndStaticEvents([class] As NamedTypeSymbol, eventTypeDisplayString As String) Dim instanceEvent = [class].GetMember(Of EventSymbol)("InstanceEvent") Assert.Equal(SymbolKind.[Event], instanceEvent.Kind) Assert.[False](instanceEvent.IsShared) Assert.Equal(eventTypeDisplayString, instanceEvent.Type.ToTestDisplayString()) CheckAccessorShape(instanceEvent.AddMethod, instanceEvent) CheckAccessorShape(instanceEvent.RemoveMethod, instanceEvent) Dim staticEvent = [class].GetMember(Of EventSymbol)("StaticEvent") Assert.Equal(SymbolKind.[Event], staticEvent.Kind) Assert.[True](staticEvent.IsShared) Assert.Equal(eventTypeDisplayString, staticEvent.Type.ToTestDisplayString()) CheckAccessorShape(staticEvent.AddMethod, staticEvent) CheckAccessorShape(staticEvent.RemoveMethod, staticEvent) End Sub Private Shared Sub CheckAccessorShape(accessor As MethodSymbol, [event] As EventSymbol) Assert.Same([event], accessor.AssociatedSymbol) Select Case accessor.MethodKind Case MethodKind.EventAdd Assert.Same([event].AddMethod, accessor) Case MethodKind.EventRemove Assert.Same([event].RemoveMethod, accessor) Case Else Assert.[False](True, String.Format("Accessor {0} has unexpected MethodKind {1}", accessor, accessor.MethodKind)) End Select Assert.Equal([event].IsMustOverride, accessor.IsMustOverride) Assert.Equal([event].IsOverrides, accessor.IsOverrides) Assert.Equal([event].IsOverridable, accessor.IsOverridable) Assert.Equal([event].IsNotOverridable, accessor.IsNotOverridable) ' TODO: do we need to support Extern events? ' Assert.Equal([event].IsExtern, accessor.IsExtern) Assert.Equal(SpecialType.System_Void, accessor.ReturnType.SpecialType) Assert.Equal([event].Type, accessor.Parameters.Single().Type) End Sub <Fact> Public Sub LoadSignatureMismatchEvents() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.SymbolsTests.Events}) Dim globalNamespace = assemblies.ElementAt(1).GlobalNamespace Dim [class] = globalNamespace.GetMember(Of NamedTypeSymbol)("SignatureMismatch") Dim mismatchedAddEvent = [class].GetMember(Of EventSymbol)("AddMismatch") Dim mismatchedRemoveEvent = [class].GetMember(Of EventSymbol)("RemoveMismatch") Assert.NotEqual(mismatchedAddEvent.Type, mismatchedAddEvent.AddMethod.Parameters.Single().Type) Assert.NotEqual(mismatchedRemoveEvent.Type, mismatchedRemoveEvent.RemoveMethod.Parameters.Single().Type) End Sub <Fact> Public Sub LoadMissingParameterEvents() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.SymbolsTests.Events}) Dim globalNamespace = assemblies.ElementAt(1).GlobalNamespace Dim [class] = globalNamespace.GetMember(Of NamedTypeSymbol)("AccessorMissingParameter") Dim noParamAddEvent = [class].GetMember(Of EventSymbol)("AddNoParam") Dim noParamRemoveEvent = [class].GetMember(Of EventSymbol)("RemoveNoParam") Assert.Equal(0, noParamAddEvent.AddMethod.Parameters.Length) Assert.Equal(0, noParamRemoveEvent.RemoveMethod.Parameters.Length) End Sub <Fact> Public Sub LoadNonDelegateEvent() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.SymbolsTests.Events}) Dim globalNamespace = assemblies.ElementAt(1).GlobalNamespace Dim [class] = globalNamespace.GetMember(Of NamedTypeSymbol)("NonDelegateEvent") Dim nonDelegateEvent = [class].GetMember(Of EventSymbol)("NonDelegate") Assert.Equal(SpecialType.System_Int32, nonDelegateEvent.Type.SpecialType) End Sub <Fact> Public Sub TestExplicitImplementationSimple() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp}) Dim globalNamespace = assemblies.ElementAt(1).GlobalNamespace Dim [interface] = DirectCast(globalNamespace.GetTypeMembers("Interface").Single(), NamedTypeSymbol) Assert.Equal(TypeKind.[Interface], [interface].TypeKind) Dim interfaceEvent = DirectCast([interface].GetMembers("Event").Single(), EventSymbol) Dim [class] = DirectCast(globalNamespace.GetTypeMembers("Class").Single(), NamedTypeSymbol) Assert.Equal(TypeKind.[Class], [class].TypeKind) Assert.[True]([class].Interfaces.Contains([interface])) Dim classEvent = DirectCast([class].GetMembers("Interface.Event").Single(), EventSymbol) Dim explicitImpl = classEvent.ExplicitInterfaceImplementations.Single() Assert.Equal(interfaceEvent, explicitImpl) End Sub <Fact> Public Sub TestExplicitImplementationGeneric() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp}) Dim globalNamespace = assemblies.ElementAt(1).GlobalNamespace Dim [interface] = DirectCast(globalNamespace.GetTypeMembers("IGeneric").Single(), NamedTypeSymbol) Assert.Equal(TypeKind.[Interface], [interface].TypeKind) Dim interfaceEvent = DirectCast([interface].GetMembers("Event").Single(), EventSymbol) Dim [class] = DirectCast(globalNamespace.GetTypeMembers("Generic").Single(), NamedTypeSymbol) Assert.Equal(TypeKind.[Class], [class].TypeKind) Dim substitutedInterface = [class].Interfaces.Single() Assert.Equal([interface], substitutedInterface.ConstructedFrom) Dim substitutedInterfaceEvent = DirectCast(substitutedInterface.GetMembers("Event").Single(), EventSymbol) Assert.Equal(interfaceEvent, substitutedInterfaceEvent.OriginalDefinition) Dim classEvent = DirectCast([class].GetMembers("IGeneric<S>.Event").Single(), EventSymbol) Dim explicitImpl = classEvent.ExplicitInterfaceImplementations.Single() Assert.Equal(substitutedInterfaceEvent, explicitImpl) End Sub <Fact> Public Sub TestExplicitImplementationConstructed() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp}) Dim globalNamespace = assemblies.ElementAt(1).GlobalNamespace Dim [interface] = DirectCast(globalNamespace.GetTypeMembers("IGeneric").Single(), NamedTypeSymbol) Assert.Equal(TypeKind.[Interface], [interface].TypeKind) Dim interfaceEvent = DirectCast([interface].GetMembers("Event").Single(), EventSymbol) Dim [class] = DirectCast(globalNamespace.GetTypeMembers("Constructed").Single(), NamedTypeSymbol) Assert.Equal(TypeKind.[Class], [class].TypeKind) Dim substitutedInterface = [class].Interfaces.Single() Assert.Equal([interface], substitutedInterface.ConstructedFrom) Dim substitutedInterfaceEvent = DirectCast(substitutedInterface.GetMembers("Event").Single(), EventSymbol) Assert.Equal(interfaceEvent, substitutedInterfaceEvent.OriginalDefinition) Dim classEvent = DirectCast([class].GetMembers("IGeneric<System.Int32>.Event").Single(), EventSymbol) Dim explicitImpl = classEvent.ExplicitInterfaceImplementations.Single() Assert.Equal(substitutedInterfaceEvent, explicitImpl) End Sub <Fact> Public Sub TestExplicitImplementationDefRefDef() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp}) Dim globalNamespace = assemblies.ElementAt(1).GlobalNamespace Dim defInterface = DirectCast(globalNamespace.GetTypeMembers("Interface").Single(), NamedTypeSymbol) Assert.Equal(TypeKind.[Interface], defInterface.TypeKind) Dim defInterfaceEvent = DirectCast(defInterface.GetMembers("Event").Single(), EventSymbol) Dim refInterface = DirectCast(globalNamespace.GetTypeMembers("IGenericInterface").Single(), NamedTypeSymbol) Assert.Equal(TypeKind.[Interface], defInterface.TypeKind) Assert.[True](refInterface.Interfaces.Contains(defInterface)) Dim [class] = DirectCast(globalNamespace.GetTypeMembers("IndirectImplementation").Single(), NamedTypeSymbol) Assert.Equal(TypeKind.[Class], [class].TypeKind) Dim classInterfacesConstructedFrom = [class].Interfaces.[Select](Function(i) i.ConstructedFrom) Assert.Equal(2, classInterfacesConstructedFrom.Count()) Assert.Contains(defInterface, classInterfacesConstructedFrom) Assert.Contains(refInterface, classInterfacesConstructedFrom) Dim classEvent = DirectCast([class].GetMembers("Interface.Event").Single(), EventSymbol) Dim explicitImpl = classEvent.ExplicitInterfaceImplementations.Single() Assert.Equal(defInterfaceEvent, explicitImpl) End Sub <Fact> Public Sub TestTypeParameterPositions() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp}) Dim globalNamespace = assemblies.ElementAt(1).GlobalNamespace Dim outerInterface = DirectCast(globalNamespace.GetTypeMembers("IGeneric2").Single(), NamedTypeSymbol) Assert.Equal(1, outerInterface.Arity) Assert.Equal(TypeKind.[Interface], outerInterface.TypeKind) Dim outerInterfaceEvent = outerInterface.GetMembers().Where(Function(m) m.Kind = SymbolKind.[Event]).Single() Dim outerClass = DirectCast(globalNamespace.GetTypeMembers("Outer").Single(), NamedTypeSymbol) Assert.Equal(1, outerClass.Arity) Assert.Equal(TypeKind.[Class], outerClass.TypeKind) Dim innerInterface = DirectCast(outerClass.GetTypeMembers("IInner").Single(), NamedTypeSymbol) Assert.Equal(1, innerInterface.Arity) Assert.Equal(TypeKind.[Interface], innerInterface.TypeKind) Dim innerInterfaceEvent = innerInterface.GetMembers().Where(Function(m) m.Kind = SymbolKind.[Event]).Single() Dim innerClass1 = DirectCast(outerClass.GetTypeMembers("Inner1").Single(), NamedTypeSymbol) CheckInnerClassHelper(innerClass1, "IGeneric2<A>.Event", outerInterfaceEvent) Dim innerClass2 = DirectCast(outerClass.GetTypeMembers("Inner2").Single(), NamedTypeSymbol) CheckInnerClassHelper(innerClass2, "IGeneric2<T>.Event", outerInterfaceEvent) Dim innerClass3 = DirectCast(outerClass.GetTypeMembers("Inner3").Single(), NamedTypeSymbol) CheckInnerClassHelper(innerClass3, "Outer<T>.IInner<C>.Event", innerInterfaceEvent) Dim innerClass4 = DirectCast(outerClass.GetTypeMembers("Inner4").Single(), NamedTypeSymbol) CheckInnerClassHelper(innerClass4, "Outer<T>.IInner<T>.Event", innerInterfaceEvent) End Sub Private Shared Sub CheckInnerClassHelper(innerClass As NamedTypeSymbol, methodName As String, interfaceEvent As Symbol) Dim [interface] = interfaceEvent.ContainingType Assert.Equal(1, innerClass.Arity) Assert.Equal(TypeKind.[Class], innerClass.TypeKind) Assert.Equal([interface], innerClass.Interfaces.Single().ConstructedFrom) Dim innerClassEvent = DirectCast(innerClass.GetMembers(methodName).Single(), EventSymbol) Dim innerClassImplementingEvent = innerClassEvent.ExplicitInterfaceImplementations.Single() Assert.Equal(interfaceEvent, innerClassImplementingEvent.OriginalDefinition) Assert.Equal([interface], innerClassImplementingEvent.ContainingType.ConstructedFrom) End Sub End Class End Namespace
davkean/roslyn
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingEvents.vb
Visual Basic
apache-2.0
16,596
Imports ForceCapture.MWCredit45 Module Module1 Sub Main() 'Create Soap Client Dim creditSoapClient As New CreditSoapClient 'Create Credentials Object Dim merchantCredentials As New MerchantCredentials With { .MerchantName = "TEST MERCHANT", .MerchantSiteId = "XXXXXXXX", .MerchantKey = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" } 'Create PaymentData Object Dim paymentData As New PaymentData With { .Source = "KEYED", .CardNumber = "4012000033330026", .ExpirationDate = "1221", .CardHolder = "John Doe" } 'Create Request Object Dim forceCaptureRequest As New ForceCaptureRequest With { .Amount = "1.01", .AuthorizationCode = "ABC123", .InvoiceNumber = "INV1234", .RegisterNumber = "01", .CardAcceptorTerminalId = "01" } 'Process Request Dim transactionResponse45 As TransactionResponse45 transactionResponse45 = creditSoapClient.ForceCapture(merchantCredentials, paymentData, forceCaptureRequest) 'Display Results Console.WriteLine(" Force Capture Response: {0} Token: {1} Amount: ${2}", transactionResponse45.ApprovalStatus + vbNewLine, transactionResponse45.Token + vbNewLine, transactionResponse45.Amount + vbNewLine) Console.WriteLine("Press Any Key to Close") Console.ReadKey() End Sub End Module
Cayan-LLC/developer-docs
examples/merchantware/Credit/vb/ForceCapture/ForceCapture/Module1.vb
Visual Basic
apache-2.0
1,494
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class diaProb 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.components = New System.ComponentModel.Container Me.TableLayoutPanel1 = New System.Windows.Forms.TableLayoutPanel Me.OK_Button = New System.Windows.Forms.Button Me.Cancel_Button = New System.Windows.Forms.Button Me.timebar = New System.Windows.Forms.ProgressBar Me.Timer1 = New System.Windows.Forms.Timer(Me.components) Me.Label2 = New System.Windows.Forms.Label Me.timetell = New System.Windows.Forms.Label Me.Button2 = New System.Windows.Forms.Button Me.Button1 = New System.Windows.Forms.Button Me.rtfProblem = New System.Windows.Forms.RichTextBox Me.TableLayoutPanel1.SuspendLayout() Me.SuspendLayout() ' 'TableLayoutPanel1 ' Me.TableLayoutPanel1.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.TableLayoutPanel1.ColumnCount = 2 Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50.0!)) Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50.0!)) Me.TableLayoutPanel1.Controls.Add(Me.OK_Button, 0, 0) Me.TableLayoutPanel1.Controls.Add(Me.Cancel_Button, 1, 0) Me.TableLayoutPanel1.Location = New System.Drawing.Point(665, 138) Me.TableLayoutPanel1.Name = "TableLayoutPanel1" Me.TableLayoutPanel1.RowCount = 1 Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50.0!)) Me.TableLayoutPanel1.Size = New System.Drawing.Size(146, 29) Me.TableLayoutPanel1.TabIndex = 0 ' 'OK_Button ' Me.OK_Button.Anchor = System.Windows.Forms.AnchorStyles.None Me.OK_Button.Location = New System.Drawing.Point(3, 3) Me.OK_Button.Name = "OK_Button" Me.OK_Button.Size = New System.Drawing.Size(67, 23) Me.OK_Button.TabIndex = 0 Me.OK_Button.Text = "&OK" ' 'Cancel_Button ' Me.Cancel_Button.Anchor = System.Windows.Forms.AnchorStyles.None Me.Cancel_Button.DialogResult = System.Windows.Forms.DialogResult.Cancel Me.Cancel_Button.Location = New System.Drawing.Point(76, 3) Me.Cancel_Button.Name = "Cancel_Button" Me.Cancel_Button.Size = New System.Drawing.Size(67, 23) Me.Cancel_Button.TabIndex = 1 Me.Cancel_Button.Text = "C&ancel" ' 'timebar ' Me.timebar.Location = New System.Drawing.Point(9, 111) Me.timebar.Name = "timebar" Me.timebar.Size = New System.Drawing.Size(799, 23) Me.timebar.TabIndex = 2 Me.timebar.Value = 100 ' 'Timer1 ' Me.Timer1.Interval = 1000 ' 'Label2 ' Me.Label2.AutoSize = True Me.Label2.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label2.Location = New System.Drawing.Point(12, 147) Me.Label2.Name = "Label2" Me.Label2.Size = New System.Drawing.Size(127, 20) Me.Label2.TabIndex = 3 Me.Label2.Text = "Time Remaining:" ' 'timetell ' Me.timetell.AutoSize = True Me.timetell.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, CType((System.Drawing.FontStyle.Bold Or System.Drawing.FontStyle.Italic), System.Drawing.FontStyle), System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.timetell.Location = New System.Drawing.Point(135, 148) Me.timetell.Name = "timetell" Me.timetell.Size = New System.Drawing.Size(63, 20) Me.timetell.TabIndex = 4 Me.timetell.Text = "Label3" ' 'Button2 ' Me.Button2.Location = New System.Drawing.Point(204, 145) Me.Button2.Name = "Button2" Me.Button2.Size = New System.Drawing.Size(31, 23) Me.Button2.TabIndex = 6 Me.Button2.Text = "&+" Me.Button2.UseVisualStyleBackColor = True ' 'Button1 ' Me.Button1.Location = New System.Drawing.Point(241, 145) Me.Button1.Name = "Button1" Me.Button1.Size = New System.Drawing.Size(31, 23) Me.Button1.TabIndex = 7 Me.Button1.Text = "&-" Me.Button1.UseVisualStyleBackColor = True ' 'rtfProblem ' Me.rtfProblem.Location = New System.Drawing.Point(12, 12) Me.rtfProblem.Name = "rtfProblem" Me.rtfProblem.Size = New System.Drawing.Size(327, 93) Me.rtfProblem.TabIndex = 43 Me.rtfProblem.Text = "" ' 'diaProb ' Me.AcceptButton = Me.OK_Button Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.Color.White Me.CancelButton = Me.Cancel_Button Me.ClientSize = New System.Drawing.Size(823, 179) Me.Controls.Add(Me.rtfProblem) Me.Controls.Add(Me.Button1) Me.Controls.Add(Me.Button2) Me.Controls.Add(Me.timetell) Me.Controls.Add(Me.Label2) Me.Controls.Add(Me.timebar) Me.Controls.Add(Me.TableLayoutPanel1) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog Me.MaximizeBox = False Me.MinimizeBox = False Me.Name = "diaProb" Me.ShowInTaskbar = False Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "Question" Me.TableLayoutPanel1.ResumeLayout(False) Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents TableLayoutPanel1 As System.Windows.Forms.TableLayoutPanel Friend WithEvents OK_Button As System.Windows.Forms.Button Friend WithEvents Cancel_Button As System.Windows.Forms.Button Friend WithEvents timebar As System.Windows.Forms.ProgressBar Friend WithEvents Timer1 As System.Windows.Forms.Timer Friend WithEvents Label2 As System.Windows.Forms.Label Friend WithEvents timetell As System.Windows.Forms.Label Friend WithEvents Button2 As System.Windows.Forms.Button Friend WithEvents Button1 As System.Windows.Forms.Button Friend WithEvents rtfProblem As System.Windows.Forms.RichTextBox End Class
hgrimberg01/Jeopardized
Jeopardy!/diaprob.Designer.vb
Visual Basic
apache-2.0
7,570
Module IniFile '// VB Web Code Example '// www.vbweb.co.uk '// mod varable types for VB 2005 '//by M Jenkinson 20/2/2006 ' DLL declarations Private Declare Function GetPrivateProfileStringKey Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Integer, ByVal lpFileName As String) As Integer Private Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpString As String, ByVal lpFileName As String) As Long '// Functions Function GetFromINI(ByVal sSection As String, ByVal sKey As String, ByVal sDefault As String, ByVal sIniFile As String) Dim sBuffer As New String(Chr(0), 255), lRet As Long ' Fill String with 255 spaces ' Call DLL lRet = GetPrivateProfileStringKey(sSection, sKey, "", sBuffer, Len(sBuffer), sIniFile) If lRet = 0 Then ' DLL failed, save default If sDefault <> "" Then AddToINI(sSection, sKey, sDefault, sIniFile) GetFromINI = sDefault Else ' DLL successful ' return string GetFromINI = Left(sBuffer, InStr(sBuffer, Chr(0)) - 1) End If End Function '// Returns True if successful. If section does not '// exist it creates it. Function AddToINI(ByVal sSection As String, ByVal sKey As String, ByVal sValue As String, ByVal sIniFile As String) As Boolean Dim lRet As Long ' Call DLL lRet = WritePrivateProfileString(sSection, sKey, sValue, sIniFile) AddToINI = (lRet) End Function End Module
Sebandreas/utorrent-network-notifications
uTorrent Network Notifications Client/IniFile.vb
Visual Basic
bsd-2-clause
1,817
' ' DotNetNuke® - https://www.dnnsoftware.com ' Copyright (c) 2002-2018 ' by DotNetNuke Corporation ' ' 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. ' Imports System.Xml.Serialization Namespace DotNetNuke.UI.Utilities Public Class FunctionalityInfo Private _desc As String Private _functionality As ClientAPI.ClientFunctionality Private _excludes As BrowserCollection Private _supports As BrowserCollection <XmlAttribute("nm")> _ Public Property Functionality() As ClientAPI.ClientFunctionality Get Return _functionality End Get Set(ByVal Value As ClientAPI.ClientFunctionality) _functionality = Value End Set End Property <XmlAttribute("desc")> _ Public Property Desc() As String Get Return _desc End Get Set(ByVal Value As String) _desc = Value End Set End Property <XmlElement("excludes")> _ Public Property Excludes() As BrowserCollection Get Return _excludes End Get Set(ByVal Value As BrowserCollection) _excludes = Value End Set End Property <XmlElement("supports")> _ Public Property Supports() As BrowserCollection Get Return _supports End Get Set(ByVal Value As BrowserCollection) _supports = Value End Set End Property Public Function HasMatch(ByVal strAgent As String, ByVal strBrowser As String, ByVal dblVersion As Double) As Boolean Dim _hasMatch As Boolean = False 'Parse through the supported browsers to find a match _hasMatch = HasMatch(Supports, strAgent, strBrowser, dblVersion) 'If has Match check the excluded browsers to find a match If _hasMatch Then _hasMatch = Not HasMatch(Excludes, strAgent, strBrowser, dblVersion) End If Return _hasMatch End Function Private Function HasMatch(ByVal browsers As BrowserCollection, ByVal strAgent As String, ByVal strBrowser As String, ByVal dblVersion As Double) As Boolean Dim _hasMatch As Boolean = False 'Parse through the browsers to find a match based on name/minversion For Each browser As Browser In browsers 'Check by browser name and min version If (Not String.IsNullOrEmpty(browser.Name) AndAlso browser.Name.ToLower.Equals(strBrowser.ToLower) AndAlso browser.MinVersion <= dblVersion) Then _hasMatch = True Exit For End If 'Check for special browser name of "*" If (browser.Name = "*") Then _hasMatch = True Exit For End If Next If Not _hasMatch Then 'Parse through the browsers to find a match based on contains (more expensive so only try if NoMatch For Each browser As Browser In browsers 'Check if UserAgent contains the string (Contains) If Not String.IsNullOrEmpty(browser.Contains) Then If strAgent.ToLower().IndexOf(browser.Contains.ToLower()) > -1 Then _hasMatch = True Exit For End If End If Next End If Return _hasMatch End Function End Class End Namespace
RichardHowells/Dnn.Platform
DNN Platform/DotNetNuke.WebUtility/Browser Caps/FunctionalityInfo.vb
Visual Basic
mit
4,853
#Region "Microsoft.VisualBasic::802e5994cbe3c73822a32a86a1cba847, src\metadb\MoNA\NamespaceDoc.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: ' Class NamespaceDoc ' ' Constructor: (+1 Overloads) Sub New ' ' /********************************************************************************/ #End Region ''' <summary> ''' 这个模块是专门用于读取MoNA数据库文件的, 包括二级质谱图数据以及相对应的物质注释信息相关 ''' </summary> Friend NotInheritable Class NamespaceDoc Private Sub New() End Sub End Class
xieguigang/spectrum
src/metadb/MoNA/NamespaceDoc.vb
Visual Basic
mit
1,988
' 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 Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class NamespaceGlobalTests ' Global is the root of all namespace even set root namespace of compilation <Fact> Public Sub RootNSForGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace NS1 Public Class Class1 'Global.NS1.Class1 End Class End Namespace Class C1 'Global.C1 End Class </file> </compilation>) Dim opt = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace("RootNS") Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp2"> <file name="a.vb"> Namespace Global.Global.ns1 Class C2 End Class End Namespace Namespace [Global].ns1 Class C1 End Class End Namespace Class C1 'RootNS.C1 End Class </file> </compilation>, opt) ' While the root namespace is empty it means Global is the container CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "Class1", "NS1.Class1") CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", "C1") ' While set the root namespace of compilation to "RootNS" ,'RootNS' is inside global namespace Dim globalNS2 = compilation2.GlobalNamespace Dim rootNS2 = DirectCast(globalNS2.GetMembers("RootNS").Single(), NamespaceSymbol) CompilationUtils.VerifyIsGlobal(rootNS2.ContainingSymbol) ' The container of C1 Dim typeSymbol2C1 = CompilationUtils.VerifyGlobalNamespace(compilation2, "a.vb", "C1", "RootNS.Global.ns1.C1", "RootNS.C1") ' The container of C1 Dim symbolC2 = CompilationUtils.VerifyGlobalNamespace(compilation2, "a.vb", "C2", "[Global].ns1.C2") End Sub ' Empty Name Space is equal to Global while Root namespace is empty <Fact> Public Sub BC30179ERR_TypeConflict6_RootNSIsEmpty() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Class A End Class Namespace Global Class A 'invalid End Class End Namespace </file> </compilation>) ' While the root namespace is empty it means Global is the container Dim symbolA = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "A", {"A", "A"}, False) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <errors> BC30179: class 'A' and class 'A' conflict in namespace '&lt;Default&gt;'. Class A ~ </errors>) End Sub ' Set the root namespace of compilation to 'Global' <Fact> Public Sub RootNSIsGlobal() Dim opt = TestOptions.ReleaseDll.WithRootNamespace("Global") Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Class A End Class Namespace Global Class A Dim s As Global.Global.A Dim s1 As [Global].A Dim s2 As Global.A End Class End Namespace </file> </compilation>, opt) ' While the root namespace is Global it means [Global] Dim globalNS = compilation1.SourceModule.GlobalNamespace Dim nsGlobal = CompilationUtils.VerifyIsGlobal(globalNS.GetMembers("Global").Single, False) Assert.Equal("[Global]", nsGlobal.ToDisplayString()) Dim symbolA = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "A", "[Global].A", "A") CompilationUtils.AssertNoErrors(compilation1) End Sub <WorkItem(527731, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527731")> <Fact> Public Sub GlobalInSourceVsGlobalInOptions() Dim source = <compilation name="comp1"> <file name="a.vb"> Namespace [Global] End Namespace </file> </compilation> Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(source) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(source, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace("Global")) Dim globalNS1 = compilation1.SourceModule.GlobalNamespace.GetMembers().Single() Dim globalNS2 = compilation2.SourceModule.GlobalNamespace.GetMembers().Single() Assert.Equal("Global", globalNS1.Name) Assert.Equal("Global", globalNS2.Name) Assert.Single(compilation1.GlobalNamespace.GetMembers("Global").AsEnumerable()) Assert.Single(compilation2.GlobalNamespace.GetMembers("Global").AsEnumerable()) Assert.Empty(compilation1.GlobalNamespace.GetMembers("[Global]").AsEnumerable()) Assert.Empty(compilation2.GlobalNamespace.GetMembers("[Global]").AsEnumerable()) End Sub ' Global for Partial class <Fact> Public Sub PartialInGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Partial Class Class1 End Class </file> <file name="b.vb"> Namespace Global Public Class Class1 End Class End Namespace </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "Class1", {"Class1"}, False) CompilationUtils.VerifyGlobalNamespace(compilation1, "b.vb", "Class1", {"Class1"}, False) Dim symbolClass = compilation1.GlobalNamespace.GetMembers("Class1").Single() Assert.Equal(2, DirectCast(symbolClass, NamedTypeSymbol).Locations.Length) End Sub ' Using escaped names for Global <WorkItem(527731, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527731")> <Fact> Public Sub EscapedGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace [Global] Public Class Class1 End Class End Namespace Namespace Global Public Class Class1 'valid End Class End Namespace </file> </compilation>) Assert.Equal(1, compilation1.SourceModule.GlobalNamespace.GetMembers("Global").Length) Dim symbolClass = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "Class1", {"Class1", "[Global].Class1"}, False) End Sub ' Global is Not Case sensitive <Fact> Public Sub BC30179ERR_TypeConflict6_CaseSenGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace GLOBAL Class C1 End Class End Namespace Namespace global Class C1 'invalid End Class End Namespace </file> </compilation>) Dim symbolClass = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", {"C1", "C1"}, False) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <errors> BC30179: class 'C1' and class 'C1' conflict in namespace '&lt;Default&gt;'. Class C1 'invalid ~~ </errors>) End Sub ' Global for Imports <Fact> Public Sub BC36001ERR_NoGlobalExpectedIdentifier_ImportsGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Imports Global.[global]'invalid Imports Global.goo'invalid Imports Global 'invalid Imports a = [Global] 'valid Namespace [global] End Namespace Namespace goo End Namespace </file> </compilation>) Dim GlobalNSMember = compilation1.SourceModule.GlobalNamespace.GetMembers() Assert.True(GlobalNSMember(0).ContainingNamespace.IsGlobalNamespace) Assert.True(GlobalNSMember(1).ContainingNamespace.IsGlobalNamespace) CompilationUtils.AssertTheseParseDiagnostics(compilation1, <errors> BC36001: 'Global' not allowed in this context; identifier expected. Imports Global.[global]'invalid ~~~~~~ BC36001: 'Global' not allowed in this context; identifier expected. Imports Global.goo'invalid ~~~~~~ BC36001: 'Global' not allowed in this context; identifier expected. Imports Global 'invalid ~~~~~~ </errors>) End Sub ' Global for Alias name <Fact> Public Sub BC36001ERR_NoGlobalExpectedIdentifier_ImportsAliasGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Imports Global = System 'invalid Imports Global.[Global] = System 'invalid Imports [Global] = System 'valid </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC36001: 'Global' not allowed in this context; identifier expected. Imports Global = System 'invalid ~~~~~~ BC36001: 'Global' not allowed in this context; identifier expected. Imports Global.[Global] = System 'invalid ~~~~~~ BC40056: Namespace or type specified in the Imports 'Global.Global' 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. Imports Global.[Global] = System 'invalid ~~~~~~~~~~~~~~~ </errors>) End Sub ' Global can't be used as type <WorkItem(527728, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527728")> <Fact> Public Sub BC30183ERR_InvalidUseOfKeyword_GlobalAsType() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Imports System Class C1(Of T As Global) End Class Class C2 Inherits Global End Class Structure [Global] End Structure Class Global End Class </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "Global", {"[Global]", "[Global]", "C1(Of T As [Global])"}, False) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30182: Type expected. Class C1(Of T As Global) ~~~~~~ BC30182: Type expected. Inherits Global ~~~~~~ BC30179: structure '[Global]' and class 'Global' conflict in namespace '&lt;Default&gt;'. Structure [Global] ~~~~~~~~ BC30179: class 'Global' and structure 'Global' conflict in namespace '&lt;Default&gt;'. Class Global ~~~~~~ BC30183: Keyword is not valid as an identifier. Class Global ~~~~~~ </errors>) End Sub ' Global can't be used as identifier <WorkItem(527728, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527728")> <Fact> Public Sub BC30183ERR_InvalidUseOfKeyword_GlobalAsIdentifier() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Class Global(Of T As Class) End Class Class C1(Of Global As Class) End Class </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "Global", "[Global](Of T As Class)", "C1(Of [Global] As Class)") CompilationUtils.AssertTheseParseDiagnostics(compilation1, <errors> BC30183: Keyword is not valid as an identifier. Class Global(Of T As Class) ~~~~~~ BC30183: Keyword is not valid as an identifier. Class C1(Of Global As Class) ~~~~~~ </errors>) End Sub ' Global can't be used as Access Modifier <Fact> Public Sub BC30035ERR_Syntax_AccessModifier() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Global Class C1(of T as class) End Class </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", "C1(Of T As Class)") CompilationUtils.AssertTheseParseDiagnostics(compilation1, <errors> BC30188: Declaration expected. Global Class C1(of T as class) ~~~~~~ </errors>) End Sub ' Global namespace may not be nested in another namespace <WorkItem(539076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539076")> <Fact> Public Sub BC31544ERR_NestedGlobalNamespace_NestedGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace Global Namespace Global ' invalid Public Class c1 End Class End Namespace End Namespace </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1") Assert.Equal("[Global]", compilation1.SourceModule.GlobalNamespace.GetMembers().Single().ToDisplayString()) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <errors> BC31544: Global namespace may not be nested in another namespace. Namespace Global ' invalid ~~~~~~ </errors>) End Sub ' [Global] namespace could be nested in another namespace <Fact> Public Sub NestedEscapedGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace Global Namespace [Global] ' valid Public Class C1 End Class End Namespace End Namespace </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", "[Global].C1") CompilationUtils.AssertNoDeclarationDiagnostics(compilation1) End Sub ' Global in Fully qualified names <Fact> Public Sub FullyQualifiedOfGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Imports [Global].ns1 Namespace Global.Global.ns1 Class C1 End Class End Namespace Namespace [Global].ns1 Class C1 End Class End Namespace </file> <file name="b.vb"> Imports NS1.Global'valid NS1.Global considered NS1.[Global] Namespace NS1 Namespace [Global] Public Class C2 End Class End Namespace End Namespace </file> <file name="c.vb"> Namespace ns1.Global 'valid considered NS1.[Global] Public Class C2 End Class End Namespace </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", {"[Global].ns1.C1", "[Global].ns1.C1"}, False) CompilationUtils.VerifyGlobalNamespace(compilation1, "b.vb", "C2", "NS1.Global.C2") CompilationUtils.VerifyGlobalNamespace(compilation1, "c.vb", "C2", "NS1.Global.C2") CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30179: class 'C1' and class 'C1' conflict in namespace '[Global].ns1'. Class C1 ~~ BC40055: Casing of namespace name 'ns1' does not match casing of namespace name 'NS1' in 'b.vb'. Namespace ns1.Global 'valid considered NS1.[Global] ~~~ BC30179: class 'C2' and class 'C2' conflict in namespace 'NS1.Global'. Public Class C2 ~~ </errors>) End Sub ' Different types in global namespace <Fact> Public Sub DiffTypeInGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="comp1"> <file name="a.vb"> Namespace Global Class [Global] Class UserdefCls End Class Structure UserdefStruct End Structure End Class Module M1 End Module Enum E1 ONE End Enum End Namespace </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "UserdefCls", "[Global].UserdefCls") CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "UserdefStruct", "[Global].UserdefStruct") CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "M1", "M1") CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "E1", "E1") CompilationUtils.AssertNoErrors(compilation1) End Sub ' Access different fields with different access modifiers in Global <Fact> Public Sub DiffAccessInGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace Global Public Class C1 Private Class C2 End Class Friend Class C3 End Class End Class End Namespace </file> </compilation>) Dim symbolC1 = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", "C1") Dim symbolC2 = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C2", "C1.C2") Dim symbolC3 = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C3", "C1.C3") Assert.Equal(Accessibility.Public, symbolC1(0).DeclaredAccessibility) Assert.Equal(Accessibility.Private, symbolC2(0).DeclaredAccessibility) Assert.Equal(Accessibility.Friend, symbolC3(0).DeclaredAccessibility) End Sub ' Global works on Compilation <WorkItem(539077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539077")> <Fact> Public Sub BC30554ERR_AmbiguousInUnnamedNamespace1_GlobalOnCompilation() Dim opt1 = TestOptions.ReleaseDll.WithRootNamespace("NS1") Dim opt2 = TestOptions.ReleaseDll.WithRootNamespace("NS2") Dim opt3 = TestOptions.ReleaseDll.WithRootNamespace("NS3") Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace Global Public Class C1 Private Class C2 End Class Public Class C3 End Class End Class End Namespace </file> </compilation>, options:=opt1) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp2"> <file name="a.vb"> Namespace Global Public Class C1 Private Class C2 End Class Public Class C3 End Class End Class End Namespace </file> </compilation>, options:=opt2) Dim ref1 = New VisualBasicCompilationReference(compilation1) Dim ref2 = New VisualBasicCompilationReference(compilation2) Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp3"> <file name="a.vb"> Namespace NS1 Structure S1 Dim A As Global.C1.C2 ' invalid Dim B As Global.C1.C3 ' invalid End Structure End Namespace </file> </compilation>, options:=opt3) compilation3 = compilation3.AddReferences(ref1, ref2) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C2", "C1.C2") CompilationUtils.VerifyGlobalNamespace(compilation2, "a.vb", "C3", "C1.C3") CompilationUtils.AssertTheseDiagnostics(compilation3, <errors> BC30554: 'C1' is ambiguous. Dim A As Global.C1.C2 ' invalid ~~~~~~~~~ BC30554: 'C1' is ambiguous. Dim B As Global.C1.C3 ' invalid ~~~~~~~~~ </errors>) End Sub ' Define customer namespace same as namespace of the .NET Framework in Global <Fact> Public Sub DefSystemNSInGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace Global Namespace System Class C1 Dim A As System.Int32 ' valid End Class End Namespace End Namespace </file> </compilation>) Dim symbolC1 = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", "System.C1") CompilationUtils.AssertNoErrors(compilation1) End Sub <Fact> <WorkItem(545787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545787")> Public Sub NestedGlobalNS() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NestedGlobalNS"> <file name="a.vb"> Imports System Namespace N Namespace Global.M Class X 'BIND:"Class X" End Class End Namespace End Namespace </file> </compilation>) Dim model = GetSemanticModel(compilation, "a.vb") Dim typeStatementSyntax = CompilationUtils.FindBindingText(Of TypeStatementSyntax)(compilation, "a.vb", 0) Dim cls = DirectCast(model.GetDeclaredSymbol(typeStatementSyntax), NamedTypeSymbol) Assert.Equal("N.Global.M.X", cls.ToDisplayString()) End Sub <Fact> Public Sub Bug529716() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace Global Class C End Class End Namespace Namespace Global.Ns1 Class D End Class End Namespace </file> </compilation>) Dim [global] = compilation1.SourceModule.GlobalNamespace Dim classC = [global].GetTypeMembers("C").Single() Dim ns1 = DirectCast([global].GetMembers("Ns1").Single(), NamespaceSymbol) Dim classD = ns1.GetTypeMembers("D").Single() Assert.False(ns1.IsImplicitlyDeclared) For Each ref In [global].DeclaringSyntaxReferences Dim node = ref.GetSyntax() Assert.Equal(SyntaxKind.CompilationUnit, node.Kind) Next ' Since we never return something other than CompilationUnit as a declaring syntax for a Global namespace, ' the following assert should succeed. Assert.True([global].IsImplicitlyDeclared) End Sub End Class End Namespace
Giftednewt/roslyn
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/NamespaceGlobalTests.vb
Visual Basic
apache-2.0
28,675
' 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 On Option Explicit On Option Infer On Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend Module CompileTimeCalculations Friend Function UncheckedCLng(v As ULong) As Long Return CType(v, Long) End Function Friend Function UncheckedCLng(v As Double) As Long Return CType(v, Long) End Function Friend Function UncheckedCULng(v As Long) As ULong Return CType(v, ULong) End Function Friend Function UncheckedCULng(v As Integer) As ULong Return CType(v, ULong) End Function Friend Function UncheckedCULng(v As Double) As ULong Return CType(v, ULong) End Function Friend Function UncheckedCInt(v As ULong) As Integer Return CType(v, Integer) End Function Friend Function UncheckedCInt(v As Long) As Integer Return CType(v, Integer) End Function Friend Function UncheckedCUInt(v As ULong) As UInteger Return CType(v, UInteger) End Function Friend Function UncheckedCUInt(v As Long) As UInteger Return CType(v, UInteger) End Function Friend Function UncheckedCUInt(v As Integer) As UInteger Return CType(v, UInteger) End Function Friend Function UncheckedCShort(v As ULong) As Short Return CType(v, Short) End Function Friend Function UncheckedCShort(v As Long) As Short Return CType(v, Short) End Function Friend Function UncheckedCShort(v As Integer) As Short Return CType(v, Short) End Function Friend Function UncheckedCShort(v As UShort) As Short Return CType(v, Short) End Function Friend Function UncheckedCInt(v As UInteger) As Integer Return CType(v, Integer) End Function Friend Function UncheckedCShort(v As UInteger) As Short Return CType(v, Short) End Function Friend Function UncheckedCUShort(v As Short) As UShort Return CType(v, UShort) End Function Friend Function UncheckedCUShort(v As Integer) As UShort Return CType(v, UShort) End Function Friend Function UncheckedCUShort(v As Long) As UShort Return CType(v, UShort) End Function Friend Function UncheckedCByte(v As SByte) As Byte Return CType(v, Byte) End Function Friend Function UncheckedCByte(v As Integer) As Byte Return CType(v, Byte) End Function Friend Function UncheckedCByte(v As Long) As Byte Return CType(v, Byte) End Function Friend Function UncheckedCByte(v As UShort) As Byte Return CType(v, Byte) End Function Friend Function UncheckedCSByte(v As Byte) As SByte Return CType(v, SByte) End Function Friend Function UncheckedCSByte(v As Integer) As SByte Return CType(v, SByte) End Function Friend Function UncheckedCSByte(v As Long) As SByte Return CType(v, SByte) End Function Friend Function UncheckedMul(x As Integer, y As Integer) As Integer Return x * y End Function Friend Function UncheckedMul(x As Long, y As Long) As Long Return x * y End Function Friend Function UncheckedIntegralDiv(x As Long, y As Long) As Long If y = -1 Then Return UncheckedNegate(x) End If Return x \ y End Function Private Function UncheckedAdd(x As Integer, y As Integer) As Integer Return x + y End Function Private Function UncheckedAdd(x As Long, y As Long) As Long Return x + y End Function Private Function UncheckedAdd(x As ULong, y As ULong) As ULong Return x + y End Function Private Function UncheckedSub(x As Long, y As Long) As Long Return x - y End Function Private Function UncheckedSub(x As UInteger, y As UInteger) As UInteger Return x - y End Function Private Function UncheckedNegate(x As Long) As Long Return -x End Function Friend Function GetConstantValueAsInt64(ByRef value As ConstantValue) As Long Select Case (value.Discriminator) Case ConstantValueTypeDiscriminator.SByte : Return value.SByteValue Case ConstantValueTypeDiscriminator.Byte : Return value.ByteValue Case ConstantValueTypeDiscriminator.Int16 : Return value.Int16Value Case ConstantValueTypeDiscriminator.UInt16 : Return value.UInt16Value Case ConstantValueTypeDiscriminator.Int32 : Return value.Int32Value Case ConstantValueTypeDiscriminator.UInt32 : Return value.UInt32Value Case ConstantValueTypeDiscriminator.Int64 : Return value.Int64Value Case ConstantValueTypeDiscriminator.UInt64 : Return UncheckedCLng(value.UInt64Value) Case ConstantValueTypeDiscriminator.Char : Return AscW(value.CharValue) Case ConstantValueTypeDiscriminator.Boolean : Return If(value.BooleanValue, 1, 0) Case ConstantValueTypeDiscriminator.DateTime : Return value.DateTimeValue.Ticks Case Else : Throw ExceptionUtilities.UnexpectedValue(value.Discriminator) End Select End Function Friend Function GetConstantValue(type As ConstantValueTypeDiscriminator, value As Long) As ConstantValue Dim result As ConstantValue Select Case (type) Case ConstantValueTypeDiscriminator.SByte : result = ConstantValue.Create(UncheckedCSByte(value)) Case ConstantValueTypeDiscriminator.Byte : result = ConstantValue.Create(UncheckedCByte(value)) Case ConstantValueTypeDiscriminator.Int16 : result = ConstantValue.Create(UncheckedCShort(value)) Case ConstantValueTypeDiscriminator.UInt16 : result = ConstantValue.Create(UncheckedCUShort(value)) Case ConstantValueTypeDiscriminator.Int32 : result = ConstantValue.Create(UncheckedCInt(value)) Case ConstantValueTypeDiscriminator.UInt32 : result = ConstantValue.Create(UncheckedCUInt(value)) Case ConstantValueTypeDiscriminator.Int64 : result = ConstantValue.Create(value) Case ConstantValueTypeDiscriminator.UInt64 : result = ConstantValue.Create(UncheckedCULng(value)) Case ConstantValueTypeDiscriminator.Char : result = ConstantValue.Create(ChrW(UncheckedCInt(value))) Case ConstantValueTypeDiscriminator.Boolean : result = ConstantValue.Create(If(value = 0, False, True)) Case ConstantValueTypeDiscriminator.DateTime : result = ConstantValue.Create(New DateTime(value)) Case Else : Throw ExceptionUtilities.UnexpectedValue(type) End Select Debug.Assert(result.Discriminator = type) Return result End Function Friend Function NarrowIntegralResult( sourceValue As Long, sourceType As ConstantValueTypeDiscriminator, resultType As ConstantValueTypeDiscriminator, ByRef overflow As Boolean ) As Long Dim resultValue As Long = 0 Select Case (resultType) Case ConstantValueTypeDiscriminator.Boolean resultValue = If(sourceValue = 0, 0, 1) Return resultValue Case ConstantValueTypeDiscriminator.SByte resultValue = UncheckedCSByte(sourceValue) Case ConstantValueTypeDiscriminator.Byte resultValue = UncheckedCByte(sourceValue) Case ConstantValueTypeDiscriminator.Int16 resultValue = UncheckedCShort(sourceValue) Case ConstantValueTypeDiscriminator.UInt16 resultValue = UncheckedCUShort(sourceValue) Case ConstantValueTypeDiscriminator.Int32 resultValue = UncheckedCInt(sourceValue) Case ConstantValueTypeDiscriminator.UInt32 resultValue = UncheckedCUInt(sourceValue) Case ConstantValueTypeDiscriminator.Int64 resultValue = sourceValue Case ConstantValueTypeDiscriminator.UInt64 resultValue = sourceValue 'UncheckedCLng(UncheckedCULng(SourceValue)) Case ConstantValueTypeDiscriminator.Char resultValue = UncheckedCUShort(sourceValue) ' // ?? overflow? Case Else Throw ExceptionUtilities.UnexpectedValue(resultType) End Select If Not ConstantValue.IsBooleanType(sourceType) AndAlso (ConstantValue.IsUnsignedIntegralType(sourceType) Xor ConstantValue.IsUnsignedIntegralType(resultType)) Then ' // If source is a signed type and is a negative value or ' // target is a signed type and results in a negative ' // value, indicate overflow. If Not ConstantValue.IsUnsignedIntegralType(sourceType) Then If sourceValue < 0 Then overflow = True End If Else Debug.Assert(Not ConstantValue.IsUnsignedIntegralType(resultType), "Expected signed Target type!!!") If resultValue < 0 Then overflow = True End If End If End If If resultValue <> sourceValue Then overflow = True End If Return resultValue End Function Friend Function NarrowIntegralResult( sourceValue As Long, sourceType As SpecialType, resultType As SpecialType, ByRef overflow As Boolean ) As Long Return NarrowIntegralResult(sourceValue, sourceType.ToConstantValueDiscriminator(), resultType.ToConstantValueDiscriminator(), overflow) End Function ''' <summary> ''' Narrow a quadword result to a specific integral type, setting Overflow true ''' if the result value cannot be represented in the result type. ''' </summary> Friend Function NarrowIntegralResult( sourceValue As Long, sourceType As TypeSymbol, resultType As TypeSymbol, ByRef overflow As Boolean) As Long Debug.Assert(sourceType.IsIntegralType() OrElse sourceType.IsBooleanType() OrElse sourceType.IsCharType(), "Unexpected source type passed in to conversion function!!!") Return NarrowIntegralResult(sourceValue, sourceType.GetConstantValueTypeDiscriminator(), resultType.GetConstantValueTypeDiscriminator(), overflow) End Function Friend Function ConvertIntegralValue( sourceValue As Long, sourceType As ConstantValueTypeDiscriminator, targetType As ConstantValueTypeDiscriminator, ByRef integerOverflow As Boolean ) As ConstantValue Debug.Assert(ConstantValue.IsIntegralType(sourceType) OrElse ConstantValue.IsBooleanType(sourceType) OrElse ConstantValue.IsCharType(sourceType), "Unexpected source type passed in to conversion function!!!") If ConstantValue.IsIntegralType(targetType) OrElse ConstantValue.IsBooleanType(targetType) OrElse ConstantValue.IsCharType(targetType) Then Return GetConstantValue(targetType, NarrowIntegralResult(sourceValue, sourceType, targetType, integerOverflow)) End If If ConstantValue.IsStringType(targetType) Then 'This is correct only if the input type is Char. If ConstantValue.IsCharType(sourceType) Then Return ConstantValue.Create(New String(ChrW(UncheckedCInt(sourceValue)), 1)) End If End If If ConstantValue.IsFloatingType(targetType) Then Return ConvertFloatingValue( If(ConstantValue.IsUnsignedIntegralType(sourceType), CType(UncheckedCULng(sourceValue), Double), CType(sourceValue, Double)), targetType, integerOverflow) End If If ConstantValue.IsDecimalType(targetType) Then Dim resultValue As Decimal Dim sign As Boolean If Not ConstantValue.IsUnsignedIntegralType(sourceType) AndAlso sourceValue < 0 Then ' // Negative numbers need converted to positive and set the negative sign bit sign = True sourceValue = -sourceValue Else sign = False End If Dim lo32 As Integer = UncheckedCInt(sourceValue And &HFFFFFFFF) ' // We include the sign bit here because we negated a negative above, so the ' // only number that still has the sign bit set is the maximum negative number ' // (which has no positive counterpart) Dim mid32 As Integer = UncheckedCInt((sourceValue And &HFFFFFFFF00000000) >> 32) Dim hi32 As Integer = 0 Dim scale As Byte = 0 resultValue = New Decimal(lo32, mid32, hi32, sign, scale) Return ConvertDecimalValue(resultValue, targetType, integerOverflow) End If Throw ExceptionUtilities.Unreachable() End Function Friend Function ConvertFloatingValue( sourceValue As Double, targetType As ConstantValueTypeDiscriminator, ByRef integerOverflow As Boolean ) As ConstantValue Dim overflow As Boolean = False If (ConstantValue.IsBooleanType(targetType)) Then Return ConvertIntegralValue(If(sourceValue = 0.0, 0, 1), ConstantValueTypeDiscriminator.Int64, targetType, integerOverflow) End If If ConstantValue.IsIntegralType(targetType) OrElse ConstantValue.IsCharType(targetType) Then overflow = DetectFloatingToIntegralOverflow(sourceValue, ConstantValue.IsUnsignedIntegralType(targetType)) If Not overflow Then Dim integralValue As Long Dim temporary As Double Dim floor As Double Dim sourceIntegralType As ConstantValueTypeDiscriminator ' // VB has different rounding behavior than C by default. Ensure we ' // are using the right type of rounding temporary = sourceValue + 0.5 ' // We had a number that was equally close to 2 integers. ' // We need to return the even one. floor = Math.Floor(temporary) '[AlekseyT]: Using Math.IEEERemainder as a replacement for fmod. If floor <> temporary OrElse Math.IEEERemainder(temporary, 2.0) = 0 Then integralValue = If(IsUnsignedLongType(targetType), ConvertFloatingToUI64(floor), UncheckedCLng(floor)) Else integralValue = If(IsUnsignedLongType(targetType), ConvertFloatingToUI64(floor - 1.0), UncheckedCLng(floor - 1.0)) End If If sourceValue < 0 Then sourceIntegralType = ConstantValueTypeDiscriminator.Int64 Else sourceIntegralType = ConstantValueTypeDiscriminator.UInt64 End If Return ConvertIntegralValue(integralValue, sourceIntegralType, targetType, integerOverflow) End If End If If ConstantValue.IsFloatingType(targetType) Then Dim resultValue As Double = NarrowFloatingResult(sourceValue, targetType, overflow) ' // We have decided to ignore overflows in compile-time evaluation ' // of floating expressions. If targetType = ConstantValueTypeDiscriminator.Single Then Return ConstantValue.Create(CType(resultValue, Single)) End If Debug.Assert(targetType = ConstantValueTypeDiscriminator.Double) Return ConstantValue.Create(resultValue) End If If ConstantValue.IsDecimalType(targetType) Then Dim resultValue As Decimal Try resultValue = Convert.ToDecimal(sourceValue) Catch ex As OverflowException overflow = True End Try If Not overflow Then Return ConvertDecimalValue(resultValue, targetType, integerOverflow) End If End If If overflow Then Return ConstantValue.Bad End If Throw ExceptionUtilities.Unreachable() End Function Friend Function ConvertDecimalValue( sourceValue As Decimal, targetType As ConstantValueTypeDiscriminator, ByRef integerOverflow As Boolean ) As ConstantValue Dim overflow As Boolean = False If ConstantValue.IsIntegralType(targetType) OrElse ConstantValue.IsCharType(targetType) Then Dim isNegative As Boolean Dim scale As Byte Dim low, mid, high As UInteger sourceValue.GetBits(isNegative, scale, low, mid, high) If scale = 0 Then Dim resultValue As Long ' Easy case: no scale factor. overflow = high <> 0 If Not overflow Then resultValue = (CLng(mid) << 32) Or low Dim sourceIntegralType As ConstantValueTypeDiscriminator = Nothing If isNegative Then ' The source value is negative, so we need to negate the result value. ' If the result type is unsigned, or the result value is already ' large enough that it consumes the sign bit, then we have overflowed. If ConstantValue.IsUnsignedIntegralType(targetType) OrElse UncheckedCULng(resultValue) > &H8000000000000000UL Then overflow = True Else resultValue = UncheckedNegate(resultValue) sourceIntegralType = ConstantValueTypeDiscriminator.Int64 End If Else sourceIntegralType = ConstantValueTypeDiscriminator.UInt64 End If If Not overflow Then Return ConvertIntegralValue(resultValue, sourceIntegralType, targetType, integerOverflow) End If End If Else Dim resultValue As Double ' // No overflow possible resultValue = Decimal.ToDouble(sourceValue) Return ConvertFloatingValue(resultValue, targetType, integerOverflow) End If End If If ConstantValue.IsFloatingType(targetType) OrElse ConstantValue.IsBooleanType(targetType) Then Dim resultValue As Double ' // No overflow possible resultValue = Decimal.ToDouble(sourceValue) Return ConvertFloatingValue(resultValue, targetType, integerOverflow) End If If ConstantValue.IsDecimalType(targetType) Then Return ConstantValue.Create(sourceValue) End If If overflow Then Return ConstantValue.Bad End If Throw ExceptionUtilities.Unreachable() End Function Friend Function NarrowFloatingResult( value As Double, resultType As ConstantValueTypeDiscriminator, ByRef overflow As Boolean ) As Double If Double.IsNaN(value) Then overflow = True End If Select Case (resultType) Case ConstantValueTypeDiscriminator.Double Return value Case ConstantValueTypeDiscriminator.Single If value > Single.MaxValue OrElse value < Single.MinValue Then overflow = True End If Return CType(value, Single) Case Else Throw ExceptionUtilities.UnexpectedValue(resultType) End Select Return value End Function Friend Function NarrowFloatingResult( value As Double, resultType As SpecialType, ByRef overflow As Boolean ) As Double If Double.IsNaN(value) Then overflow = True End If Select Case resultType Case SpecialType.System_Double Return value Case SpecialType.System_Single If value > Single.MaxValue OrElse value < Single.MinValue Then overflow = True End If Return CType(value, Single) Case Else Throw ExceptionUtilities.UnexpectedValue(resultType) End Select Return value End Function Private Function DetectFloatingToIntegralOverflow( sourceValue As Double, isUnsigned As Boolean ) As Boolean If isUnsigned Then ' // this code is shared by fjitdef.h If sourceValue < &HF000000000000000UL Then If sourceValue > -1 Then Return False End If Else Dim temporary As Double = (sourceValue - &HF000000000000000UL) If temporary < &H7000000000000000L AndAlso UncheckedCLng(temporary) < &H1000000000000000L Then Return False End If End If Else ' // this code is shared by fjitdef.h If sourceValue < -&H7000000000000000L Then Dim temporary As Double = sourceValue - (-&H7000000000000000L) If temporary > -&H7000000000000000L AndAlso UncheckedCLng(temporary) > -&H1000000000000001L Then Return False End If Else If sourceValue > &H7000000000000000L Then Dim temporary As Double = (sourceValue - &H7000000000000000L) If temporary < &H7000000000000000L AndAlso UncheckedCLng(temporary) > &H1000000000000000L Then Return False End If Else Return False End If End If End If Return True End Function Private Function ConvertFloatingToUI64(sourceValue As Double) As Long ' // Conversion from double to uint64 is annoyingly implemented by the ' // VC++ compiler as (uint64)(int64)(double)val, so we have to do it by hand. Dim result As Long ' // code below stolen from jit... Dim two63 As Double = 2147483648.0 * 4294967296.0 If sourceValue < two63 Then result = UncheckedCLng(sourceValue) Else result = UncheckedAdd(UncheckedCLng(sourceValue - two63), &H8000000000000000) End If Return result End Function Private Function IsUnsignedLongType(type As ConstantValueTypeDiscriminator) As Boolean Return type = ConstantValueTypeDiscriminator.UInt64 End Function Friend Function TypeAllowsCompileTimeConversions(type As ConstantValueTypeDiscriminator) As Boolean Return TypeAllowsCompileTimeOperations(type) End Function Friend Function TypeAllowsCompileTimeOperations(type As ConstantValueTypeDiscriminator) As Boolean Select Case (type) Case ConstantValueTypeDiscriminator.Boolean, ConstantValueTypeDiscriminator.SByte, ConstantValueTypeDiscriminator.Byte, ConstantValueTypeDiscriminator.Int16, ConstantValueTypeDiscriminator.UInt16, ConstantValueTypeDiscriminator.Int32, ConstantValueTypeDiscriminator.UInt32, ConstantValueTypeDiscriminator.Int64, ConstantValueTypeDiscriminator.UInt64, ConstantValueTypeDiscriminator.Char, ConstantValueTypeDiscriminator.Decimal, ConstantValueTypeDiscriminator.Double, ConstantValueTypeDiscriminator.Single, ConstantValueTypeDiscriminator.DateTime, ConstantValueTypeDiscriminator.String Return True Case Else Return False End Select End Function Friend Function AdjustConstantValueFromMetadata(value As ConstantValue, targetType As TypeSymbol, isByRefParamValue As Boolean) As ConstantValue ' See MetaImport::DecodeValue in Dev10 compiler. If targetType Is Nothing OrElse targetType.IsErrorType() Then Return value End If Select Case value.Discriminator Case ConstantValueTypeDiscriminator.Int32 ' Adding the test for Object here is necessary in order to ' make something like "Optional Byref X As Object = 5" work. If targetType.IsIntrinsicType() OrElse targetType.IsEnumType() OrElse targetType.IsObjectType() OrElse (targetType.IsNullableType() AndAlso targetType.GetNullableUnderlyingType().IsIntrinsicType()) Then 'No change Exit Select End If If isByRefParamValue OrElse (Not targetType.IsTypeParameter() AndAlso Not targetType.IsArrayType() AndAlso targetType.IsReferenceType()) Then ' // REVIEW: are there other byref types besides Integer and enums ' // that might need to be handled here? ' // ByRef Integer, and ByRef Enum (that is stored as I4) ' // are pointer types, but optional values are not pointers ' // COM+ encodes pointer constants as I4's ' // CONSIDER LATER AnthonyL 8/21/00: Does this t_ref workaround move to I8 on a 64-bit machine? ' // MattGe: Back out part of 604868 to address build lab issue #4093 ' // Probably just need to #ifdef this differently for 64bit, but ' // will let Cameron decide. ' //Value.Integral = (__int32)*(WIN64_UNALIGNED void **)pvValue; If value.Int32Value = 0 Then value = ConstantValue.Nothing Else value = ConstantValue.Bad End If End If Case ConstantValueTypeDiscriminator.Int64 If targetType.IsDateTimeType() Then value = ConstantValue.Create(New DateTime(value.Int64Value)) End If End Select Return value End Function Friend Function Multiply( leftValue As Long, rightValue As Long, sourceType As SpecialType, resultType As SpecialType, ByRef integerOverflow As Boolean ) As Long Return Multiply(leftValue, rightValue, sourceType.ToConstantValueDiscriminator(), resultType.ToConstantValueDiscriminator(), integerOverflow) End Function Friend Function Multiply( leftValue As Long, rightValue As Long, sourceType As ConstantValueTypeDiscriminator, resultType As ConstantValueTypeDiscriminator, ByRef integerOverflow As Boolean ) As Long Dim ResultValue = NarrowIntegralResult( UncheckedMul(leftValue, rightValue), sourceType, resultType, integerOverflow) If ConstantValue.IsUnsignedIntegralType(resultType) Then If rightValue <> 0 AndAlso UncheckedCULng(ResultValue) / UncheckedCULng(rightValue) <> UncheckedCULng(leftValue) Then integerOverflow = True End If Else If (leftValue > 0 AndAlso rightValue > 0 AndAlso ResultValue <= 0) OrElse (leftValue < 0 AndAlso rightValue < 0 AndAlso ResultValue <= 0) OrElse (leftValue > 0 AndAlso rightValue < 0 AndAlso ResultValue >= 0) OrElse (leftValue < 0 AndAlso rightValue > 0 AndAlso ResultValue >= 0) OrElse (rightValue <> 0 AndAlso ResultValue / rightValue <> leftValue) Then integerOverflow = True End If End If Return ResultValue End Function End Module End Namespace
DustinCampbell/roslyn
src/Compilers/VisualBasic/Portable/Semantics/CompileTimeCalculations.vb
Visual Basic
apache-2.0
31,925
' 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.Generic Imports System.Collections.Immutable Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects 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 type or module declared in source. ''' Could be a class, structure, interface, delegate, enum, or module. ''' </summary> Partial Friend Class SourceNamedTypeSymbol Inherits SourceMemberContainerTypeSymbol Implements IAttributeTargetSymbol ' Type parameters (Nothing if not created yet) Private _lazyTypeParameters As ImmutableArray(Of TypeParameterSymbol) ' Attributes on type. Set once after construction. IsNull means not set. Protected m_lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) Private ReadOnly _corTypeId As SpecialType Private _lazyDocComment As String Private _lazyEnumUnderlyingType As NamedTypeSymbol ' Stores symbols for overriding WithEvents properties if we have such ' Overriding properties are created when a methods "Handles" is bound and can happen concurrently. ' We need this table to ensure that we create each override just once. Private _lazyWithEventsOverrides As ConcurrentDictionary(Of PropertySymbol, SynthesizedOverridingWithEventsProperty) Private _withEventsOverridesAreFrozen As Boolean ' method flags for the synthesized delegate methods Friend Const DelegateConstructorMethodFlags As SourceMemberFlags = SourceMemberFlags.MethodKindConstructor Friend Const DelegateCommonMethodFlags As SourceMemberFlags = SourceMemberFlags.Overridable Private _lazyLexicalSortKey As LexicalSortKey = LexicalSortKey.NotInitialized Private _lazyIsExtensibleInterface As ThreeState = ThreeState.Unknown Private _lazyIsExplicitDefinitionOfNoPiaLocalType As ThreeState = ThreeState.Unknown ''' <summary> ''' Information for ComClass specific analysis and metadata generation, created ''' once ComClassAttribute is encountered. ''' </summary> Private _comClassData As ComClassData ''' <summary> ''' Lazy CoClass type if the attribute is specified. Nothing if not. ''' </summary> Private _lazyCoClassType As TypeSymbol = ErrorTypeSymbol.UnknownResultType ''' <summary> ''' In case a cyclic dependency was detected during base type resolution ''' this field stores the diagnostic. ''' </summary> Protected m_baseCycleDiagnosticInfo As DiagnosticInfo = Nothing ' Create the type symbol and associated type parameter symbols. Most information ' is deferred until later. Friend Sub New(declaration As MergedTypeDeclaration, containingSymbol As NamespaceOrTypeSymbol, containingModule As SourceModuleSymbol) MyBase.New(declaration, containingSymbol, containingModule) ' check if this is one of the COR library types If containingSymbol.Kind = SymbolKind.Namespace AndAlso containingSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes AndAlso Me.DeclaredAccessibility = Accessibility.Public Then Dim emittedName As String = If(Me.GetEmittedNamespaceName(), Me.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)) Debug.Assert((Arity <> 0) = MangleName) emittedName = MetadataHelpers.BuildQualifiedName(emittedName, MetadataName) _corTypeId = SpecialTypes.GetTypeFromMetadataName(emittedName) Else _corTypeId = SpecialType.None End If If containingSymbol.Kind = SymbolKind.NamedType Then ' Nested types are never unified. _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.False End If End Sub Public Overrides ReadOnly Property SpecialType As SpecialType Get Return _corTypeId End Get End Property #Region "Completion" Protected Overrides Sub GenerateAllDeclarationErrorsImpl(cancellationToken As CancellationToken) #If DEBUG Then EnsureAllHandlesAreBound() #End If MyBase.GenerateAllDeclarationErrorsImpl(cancellationToken) _withEventsOverridesAreFrozen = True cancellationToken.ThrowIfCancellationRequested() PerformComClassAnalysis() cancellationToken.ThrowIfCancellationRequested() CheckBaseConstraints() cancellationToken.ThrowIfCancellationRequested() CheckInterfacesConstraints() End Sub #End Region #Region "Syntax" Friend Function GetTypeIdentifierToken(node As VisualBasicSyntaxNode) As SyntaxToken Select Case node.Kind Case SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock Return DirectCast(node, TypeBlockSyntax).BlockStatement.Identifier Case SyntaxKind.EnumBlock Return DirectCast(node, EnumBlockSyntax).EnumStatement.Identifier Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(node, DelegateStatementSyntax).Identifier Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String If _lazyDocComment Is Nothing Then ' NOTE: replace Nothing with empty comment Interlocked.CompareExchange( _lazyDocComment, GetDocumentationCommentForSymbol(Me, preferredCulture, expandIncludes, cancellationToken), Nothing) End If Return _lazyDocComment End Function ' Create a LocationSpecificBinder for the type. This is a binder that wraps the ' default binder for the type in a binder that will avoid checking constraints, ' for cases where constraint checking may result in a recursive binding attempt. Private Function CreateLocationSpecificBinderForType(tree As SyntaxTree, location As BindingLocation) As Binder Debug.Assert(location <> BindingLocation.None) Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, tree, Me) Return New LocationSpecificBinder(location, binder) End Function #End Region #Region "Members" Protected Overrides Sub AddDeclaredNonTypeMembers(membersBuilder As SourceMemberContainerTypeSymbol.MembersAndInitializersBuilder, diagnostics As DiagnosticBag) Dim accessModifiers As DeclarationModifiers = Nothing Dim foundModifiers As DeclarationModifiers Dim foundPartial As Boolean = False Dim nodeNameIsAlreadyDefined As Boolean = False Dim firstNode As VisualBasicSyntaxNode = Nothing Dim countMissingPartial = 0 For Each syntaxRef In SyntaxReferences Dim node = syntaxRef.GetVisualBasicSyntax() ' Set up a binder for this part of the type. Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, syntaxRef.SyntaxTree, Me) ' Script and implicit classes are syntactically represented by CompilationUnitSyntax or NamespaceBlockSyntax nodes. Dim staticInitializers As ArrayBuilder(Of FieldOrPropertyInitializer) = Nothing Dim instanceInitializers As ArrayBuilder(Of FieldOrPropertyInitializer) = Nothing foundModifiers = AddMembersInPart(binder, node, diagnostics, accessModifiers, membersBuilder, staticInitializers, instanceInitializers, nodeNameIsAlreadyDefined) If accessModifiers = Nothing Then accessModifiers = foundModifiers And DeclarationModifiers.AllAccessibilityModifiers End If If (foundModifiers And DeclarationModifiers.Partial) <> 0 Then If Not foundPartial Then firstNode = node foundPartial = True End If Else countMissingPartial += 1 If firstNode Is Nothing Then firstNode = node End If End If ' add the collected initializers for this (partial) type to the collections ' and free the array builders AddInitializers(membersBuilder.StaticInitializers, staticInitializers) AddInitializers(membersBuilder.InstanceInitializers, instanceInitializers) Next If Not nodeNameIsAlreadyDefined AndAlso countMissingPartial >= 2 Then ' Only check partials if no duplicate symbols were found and at least two class declarations are missing the partial keyword. For Each syntaxRef In SyntaxReferences ' Report a warning or error for all classes missing the partial modifier CheckDeclarationPart(syntaxRef.SyntaxTree, syntaxRef.GetVisualBasicSyntax(), firstNode, foundPartial, diagnostics) Next End If End Sub ' Declare all the non-type members in a single part of this type, and add them to the member list. Private Function AddMembersInPart(binder As Binder, node As VisualBasicSyntaxNode, diagBag As DiagnosticBag, accessModifiers As DeclarationModifiers, members As MembersAndInitializersBuilder, ByRef staticInitializers As ArrayBuilder(Of FieldOrPropertyInitializer), ByRef instanceInitializers As ArrayBuilder(Of FieldOrPropertyInitializer), ByRef nodeNameIsAlreadyDefined As Boolean) As DeclarationModifiers ' Check that the node's fully qualified name is not too long and that the type name is unique. CheckDeclarationNameAndTypeParameters(node, binder, diagBag, nodeNameIsAlreadyDefined) Dim foundModifiers = CheckDeclarationModifiers(node, binder, diagBag, accessModifiers) If TypeKind = TypeKind.Delegate Then ' add implicit delegate members (invoke, .ctor, begininvoke and endinvoke) If members.Members.Count = 0 Then Dim ctor As MethodSymbol = Nothing Dim beginInvoke As MethodSymbol = Nothing Dim endInvoke As MethodSymbol = Nothing Dim invoke As MethodSymbol = Nothing Dim parameters = DirectCast(node, DelegateStatementSyntax).ParameterList SourceDelegateMethodSymbol.MakeDelegateMembers(Me, node, parameters, binder, ctor, beginInvoke, endInvoke, invoke, diagBag) AddSymbolToMembers(ctor, members.Members) ' If this is a winmd compilation begin/endInvoke will be Nothing ' and we shouldn't add them to the symbol If beginInvoke IsNot Nothing Then AddSymbolToMembers(beginInvoke, members.Members) End If If endInvoke IsNot Nothing Then AddSymbolToMembers(endInvoke, members.Members) End If ' Invoke must always be the last member AddSymbolToMembers(invoke, members.Members) Else Debug.Assert(members.Members.Count = 4) End If ElseIf TypeKind = TypeKind.Enum Then Dim enumBlock = DirectCast(node, EnumBlockSyntax) AddEnumMembers(enumBlock, binder, diagBag, members) Else Dim typeBlock = DirectCast(node, TypeBlockSyntax) For Each memberSyntax In typeBlock.Members AddMember(memberSyntax, binder, diagBag, members, staticInitializers, instanceInitializers, reportAsInvalid:=False) Next End If Return foundModifiers End Function Private Function CheckDeclarationModifiers(node As VisualBasicSyntaxNode, binder As Binder, diagBag As DiagnosticBag, accessModifiers As DeclarationModifiers) As DeclarationModifiers Dim modifiers As SyntaxTokenList = Nothing Dim id As SyntaxToken = Nothing Dim foundModifiers = DecodeDeclarationModifiers(node, binder, diagBag, modifiers, id) If accessModifiers <> Nothing Then Dim newModifiers = foundModifiers And DeclarationModifiers.AllAccessibilityModifiers And Not accessModifiers ' Specified access '|1' for '|2' does not match the access '|3' specified on one of its other partial types. If newModifiers <> 0 Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_PartialTypeAccessMismatch3, newModifiers.ToAccessibility().ToDisplay(), id.ToString(), accessModifiers.ToAccessibility().ToDisplay()) End If End If If Me.IsNotInheritable Then ' 'MustInherit' cannot be specified for partial type '|1' because it cannot be combined with 'NotInheritable' ' specified for one of its other partial types. If (foundModifiers And DeclarationModifiers.MustInherit) <> 0 Then ' Generate error #30926 only if this (partial) declaration does not have both MustInherit and ' NotInheritable (in which case #31408 error must have been generated which should be enough in this ' case). If (foundModifiers And DeclarationModifiers.NotInheritable) = 0 Then ' Note: in case one partial declaration has both MustInherit & NotInheritable and other partial ' declarations have MustInherit, #31408 will be generated for the first one and #30926 for all ' others with MustInherit Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_PartialTypeBadMustInherit1, id.ToString()) End If End If End If Dim containingType = TryCast(Me.ContainingType, SourceNamedTypeSymbol) ' IsNested means this is in a Class or Module or Structure Dim isNested = containingType IsNot Nothing AndAlso Not containingType.IsNamespace If isNested Then Select Case containingType.DeclarationKind Case VisualBasic.Symbols.DeclarationKind.Module If (foundModifiers And DeclarationModifiers.InvalidInModule) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_ModuleCantUseTypeSpecifier1, diagBag, InvalidModifiersInModule) foundModifiers = (foundModifiers And (Not DeclarationModifiers.InvalidInModule)) End If Case VisualBasic.Symbols.DeclarationKind.Interface If (foundModifiers And DeclarationModifiers.InvalidInInterface) <> 0 Then Dim err As ERRID = ERRID.ERR_None Select Case Me.DeclarationKind Case VisualBasic.Symbols.DeclarationKind.Class err = ERRID.ERR_BadInterfaceClassSpecifier1 Case VisualBasic.Symbols.DeclarationKind.Delegate err = ERRID.ERR_BadInterfaceDelegateSpecifier1 Case VisualBasic.Symbols.DeclarationKind.Structure err = ERRID.ERR_BadInterfaceStructSpecifier1 Case VisualBasic.Symbols.DeclarationKind.Enum err = ERRID.ERR_BadInterfaceEnumSpecifier1 Case VisualBasic.Symbols.DeclarationKind.Interface ' For whatever reason, Dev10 does not report an error on [Friend] or [Public] modifier on an interface inside an interface. ' Need to handle this specially Dim invalidModifiers = DeclarationModifiers.InvalidInInterface And (Not (DeclarationModifiers.Friend Or DeclarationModifiers.Public)) If (foundModifiers And invalidModifiers) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_BadInterfaceInterfaceSpecifier1, diagBag, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SharedKeyword) foundModifiers = (foundModifiers And (Not invalidModifiers)) End If End Select If err <> ERRID.ERR_None Then binder.ReportModifierError(modifiers, err, diagBag, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.FriendKeyword, SyntaxKind.PublicKeyword, SyntaxKind.SharedKeyword) foundModifiers = (foundModifiers And (Not DeclarationModifiers.InvalidInInterface)) End If End If End Select Else If (foundModifiers And DeclarationModifiers.Private) <> 0 Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_PrivateTypeOutsideType) End If If (foundModifiers And DeclarationModifiers.Shadows) <> 0 Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_ShadowingTypeOutsideClass1, id.ToString()) foundModifiers = (foundModifiers And (Not DeclarationModifiers.Shadows)) End If End If ' Only nested type (not nested in a struct, nested in a class, etc. ) can be Protected. If (foundModifiers And DeclarationModifiers.Protected) <> 0 AndAlso (Not isNested OrElse containingType.DeclarationKind <> VisualBasic.Symbols.DeclarationKind.Class) Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_ProtectedTypeOutsideClass) foundModifiers = (foundModifiers And (Not DeclarationModifiers.Protected)) End If Return foundModifiers End Function Private Function DecodeDeclarationModifiers(node As VisualBasicSyntaxNode, binder As Binder, diagBag As DiagnosticBag, ByRef modifiers As SyntaxTokenList, ByRef id As SyntaxToken) As DeclarationModifiers Dim allowableModifiers = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Shadows Dim err = ERRID.ERR_None Dim typeBlock As TypeBlockSyntax Select Case node.Kind Case SyntaxKind.ModuleBlock err = ERRID.ERR_BadModuleFlags1 allowableModifiers = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Partial typeBlock = DirectCast(node, TypeBlockSyntax) modifiers = typeBlock.BlockStatement.Modifiers id = typeBlock.BlockStatement.Identifier Case SyntaxKind.ClassBlock err = ERRID.ERR_BadClassFlags1 allowableModifiers = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Shadows Or SourceMemberFlags.MustInherit Or SourceMemberFlags.NotInheritable Or SourceMemberFlags.Partial typeBlock = DirectCast(node, TypeBlockSyntax) modifiers = typeBlock.BlockStatement.Modifiers id = typeBlock.BlockStatement.Identifier Case SyntaxKind.StructureBlock err = ERRID.ERR_BadRecordFlags1 allowableModifiers = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Shadows Or SourceMemberFlags.Partial typeBlock = DirectCast(node, TypeBlockSyntax) modifiers = typeBlock.BlockStatement.Modifiers id = typeBlock.BlockStatement.Identifier Case SyntaxKind.InterfaceBlock err = ERRID.ERR_BadInterfaceFlags1 allowableModifiers = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Shadows Or SourceMemberFlags.Partial typeBlock = DirectCast(node, TypeBlockSyntax) modifiers = typeBlock.BlockStatement.Modifiers id = typeBlock.BlockStatement.Identifier Case SyntaxKind.EnumBlock err = ERRID.ERR_BadEnumFlags1 Dim enumBlock As EnumBlockSyntax = DirectCast(node, EnumBlockSyntax) modifiers = enumBlock.EnumStatement.Modifiers id = enumBlock.EnumStatement.Identifier Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement err = ERRID.ERR_BadDelegateFlags1 modifiers = DirectCast(node, DelegateStatementSyntax).Modifiers id = DirectCast(node, DelegateStatementSyntax).Identifier Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select If modifiers.Count <> 0 Then Dim foundFlags As SourceMemberFlags = binder.DecodeModifiers(modifiers, allowableModifiers, err, Nothing, diagBag).FoundFlags Return CType((foundFlags And SourceMemberFlags.DeclarationModifierFlagMask) >> SourceMemberFlags.DeclarationModifierFlagShift, DeclarationModifiers) End If Return Nothing End Function Private Sub CheckDeclarationNameAndTypeParameters(node As VisualBasicSyntaxNode, binder As Binder, diagBag As DiagnosticBag, ByRef nodeNameIsAlreadyDeclared As Boolean) ' Check that the node's fully qualified name is not too long. Only check declarations that create types. Dim id As SyntaxToken = GetTypeIdentifierToken(node) Binder.DisallowTypeCharacter(id, diagBag) Dim thisTypeIsEmbedded As Boolean = Me.IsEmbedded ' Check name for duplicate type declarations in this container Dim container = TryCast(Me.ContainingSymbol, NamespaceOrTypeSymbol) If container IsNot Nothing Then ' Get all type or namespace symbols with this name. Dim symbols As ImmutableArray(Of Symbol) If container.IsNamespace Then symbols = container.GetMembers(Me.Name) Else symbols = StaticCast(Of Symbol).From(container.GetTypeMembers(Me.Name)) End If Dim arity As Integer = Me.Arity For Each s In symbols If s IsNot Me Then Dim _3rdArg As Object Select Case s.Kind Case SymbolKind.Namespace If arity > 0 Then Continue For End If _3rdArg = DirectCast(s, NamespaceSymbol).GetKindText() Case SymbolKind.NamedType Dim contender = DirectCast(s, NamedTypeSymbol) If contender.Arity <> arity Then Continue For End If _3rdArg = contender.GetKindText() Case Else Continue For End Select If s.IsEmbedded Then ' We expect 'this' type not to be an embedded type in this ' case because otherwise it should be design time bug. Debug.Assert(Not thisTypeIsEmbedded) ' This non-embedded type conflicts with an embedded type or namespace Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_TypeClashesWithVbCoreType4, Me.GetKindText(), id.ToString, _3rdArg, s.Name) ElseIf thisTypeIsEmbedded Then ' Embedded type conflicts with non-embedded type or namespace. ' We should ignore non-embedded types in this case, as a proper ' diagnostic will be reported when the non-embedded type is processed. If s.Kind = SymbolKind.Namespace Then ' But we should report errors on the first namespace locations Dim errorReported As Boolean = False For Each location In s.Locations If location.IsInSource AndAlso Not DirectCast(location.SourceTree, VisualBasicSyntaxTree).IsEmbeddedSyntaxTree Then Binder.ReportDiagnostic(diagBag, location, ERRID.ERR_TypeClashesWithVbCoreType4, _3rdArg, s.Name, Me.GetKindText(), id.ToString) errorReported = True Exit For End If Next If errorReported Then Exit For End If End If Continue For ' continue analysis of the type if no errors were reported Else ' Neither of types is embedded. If (Me.ContainingType Is Nothing OrElse container.Locations.Length = 1 OrElse Not (TypeOf container Is SourceMemberContainerTypeSymbol) OrElse CType(container, SourceMemberContainerTypeSymbol).IsPartial) Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_TypeConflict6, Me.GetKindText(), id.ToString, _3rdArg, s.Name, container.GetKindText(), Me.ContainingSymbol.ToErrorMessageArgument(ERRID.ERR_TypeConflict6)) End If End If nodeNameIsAlreadyDeclared = True Exit For End If Next If Not nodeNameIsAlreadyDeclared AndAlso container.IsNamespace AndAlso Me.ContainingAssembly.Modules.Length > 1 Then ' Check for collision with types from added modules Dim containingNamespace = DirectCast(container, NamespaceSymbol) Dim mergedAssemblyNamespace = TryCast(Me.ContainingAssembly.GetAssemblyNamespace(containingNamespace), MergedNamespaceSymbol) If mergedAssemblyNamespace IsNot Nothing Then Dim targetQualifiedNamespaceName As String = If(Me.GetEmittedNamespaceName(), containingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)) Dim collision As NamedTypeSymbol = Nothing For Each constituent As NamespaceSymbol In mergedAssemblyNamespace.ConstituentNamespaces If constituent Is container Then Continue For End If If collision IsNot Nothing AndAlso collision.ContainingModule.Ordinal < constituent.ContainingModule.Ordinal Then Continue For End If Dim contenders As ImmutableArray(Of NamedTypeSymbol) = constituent.GetTypeMembers(Me.Name, arity) If contenders.Length = 0 Then Continue For End If Dim constituentQualifiedName As String = constituent.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) For Each namedType In contenders If namedType.DeclaredAccessibility = Accessibility.Public AndAlso namedType.MangleName = Me.MangleName Then ' Because namespaces are merged case-insensitively, ' we need to make sure that we have a match for ' full emitted name of the type. If String.Equals(Me.Name, namedType.Name, StringComparison.Ordinal) AndAlso String.Equals(targetQualifiedNamespaceName, If(namedType.GetEmittedNamespaceName(), constituentQualifiedName), StringComparison.Ordinal) Then collision = namedType Exit For End If End If Next Next If collision IsNot Nothing Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_CollisionWithPublicTypeInModule, Me, collision.ContainingModule) End If End If End If End If ' Check name against type parameters of immediate container Dim containingSourceType = TryCast(container, SourceNamedTypeSymbol) If containingSourceType IsNot Nothing AndAlso containingSourceType.TypeParameters.MatchesAnyName(Me.Name) Then ' "'|1' has the same name as a type parameter." Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_ShadowingGenericParamWithMember1, Me.Name) End If ' Check the source symbol type parameters for duplicates and shadowing CheckForDuplicateTypeParameters(TypeParameters, diagBag) End Sub Private Sub CheckDeclarationPart(tree As SyntaxTree, node As VisualBasicSyntaxNode, firstNode As VisualBasicSyntaxNode, foundPartial As Boolean, diagBag As DiagnosticBag) ' No error or warning on the first declaration If node Is firstNode Then Return End If ' Set up a binder for this part of the type. Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, tree, Me) ' all type declarations are treated as possible partial types. Because these type have different base classes ' we need to get the modifiers in different ways. ' class, interface, struct and module all are all derived from TypeBlockSyntax. ' delegate is derived from MethodBase Dim modifiers As SyntaxTokenList = Nothing Select Case node.Kind Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement modifiers = DirectCast(node, DelegateStatementSyntax).Modifiers Case SyntaxKind.EnumBlock modifiers = DirectCast(node, EnumBlockSyntax).EnumStatement.Modifiers Case SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock modifiers = DirectCast(node, TypeBlockSyntax).BlockStatement.Modifiers Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select Dim id As SyntaxToken = Nothing ' because this method was called before, we will pass a new (unused) instance of ' diagnostics to avoid duplicate error messages for the same nodes Dim unusedDiagnostics = DiagnosticBag.GetInstance() Dim foundModifiers = DecodeDeclarationModifiers(node, binder, unusedDiagnostics, modifiers, id) unusedDiagnostics.Free() If (foundModifiers And DeclarationModifiers.Partial) = 0 Then Dim errorCode = If(foundPartial, ERRID.WRN_TypeConflictButMerged6, ERRID.ERR_TypeConflict6) ' Ensure multiple class declarations all have partial. Report a warning if more than 2 declarations are missing partial. ' VB allows one class declaration with partial and one declaration without partial because designer generated code ' may not have specified partial. This allows user-code to force it. However, VB does not allow more than one declaration ' to not have partial as this would (erroneously) make what would have been a error (duplicate declarations) compile. Dim _6thArg As Object = Me.ContainingSymbol.ToErrorMessageArgument(errorCode) Dim identifier As String = GetTypeIdentifierToken(firstNode).ToString Dim nodeKindText = Me.GetKindText() Binder.ReportDiagnostic(diagBag, id, errorCode, nodeKindText, id.ToString, nodeKindText, identifier, Me.ContainingSymbol.GetKindText(), _6thArg) End If End Sub Private Sub AddEnumMembers(syntax As EnumBlockSyntax, bodyBinder As Binder, diagnostics As DiagnosticBag, members As MembersAndInitializersBuilder) Dim valField = New SynthesizedFieldSymbol( Me, Me, Me.EnumUnderlyingType, WellKnownMemberNames.EnumBackingFieldName, accessibility:=Accessibility.Public, isSpecialNameAndRuntimeSpecial:=True) AddMember(valField, bodyBinder, members, omitDiagnostics:=False) ' The previous enum constant used to calculate subsequent ' implicit enum constants. (This is the most recent explicit ' enum constant or the first implicit constant if no explicit values.) Dim otherSymbol As SourceEnumConstantSymbol = Nothing ' Offset from "otherSymbol". Dim otherSymbolOffset As Integer = 0 If syntax.Members.Count = 0 Then Binder.ReportDiagnostic(diagnostics, syntax.EnumStatement.Identifier, ERRID.ERR_BadEmptyEnum1, syntax.EnumStatement.Identifier.ValueText) Return End If For Each member In syntax.Members If member.Kind <> SyntaxKind.EnumMemberDeclaration Then ' skip invalid syntax Continue For End If Dim declaration = DirectCast(member, EnumMemberDeclarationSyntax) Dim symbol As SourceEnumConstantSymbol Dim valueOpt = declaration.Initializer If valueOpt IsNot Nothing Then symbol = SourceEnumConstantSymbol.CreateExplicitValuedConstant(Me, bodyBinder, declaration, diagnostics) Else symbol = SourceEnumConstantSymbol.CreateImplicitValuedConstant(Me, bodyBinder, declaration, otherSymbol, otherSymbolOffset, diagnostics) End If If (valueOpt IsNot Nothing) OrElse (otherSymbol Is Nothing) Then otherSymbol = symbol otherSymbolOffset = 1 Else otherSymbolOffset = otherSymbolOffset + 1 End If AddMember(symbol, bodyBinder, members, omitDiagnostics:=False) Next End Sub #End Region #Region "Type Parameters (phase 3)" Private Structure TypeParameterInfo Public Sub New( variance As VarianceKind, constraints As ImmutableArray(Of TypeParameterConstraint)) Me.Variance = variance Me.Constraints = constraints End Sub Public ReadOnly Variance As VarianceKind Public ReadOnly Constraints As ImmutableArray(Of TypeParameterConstraint) Public ReadOnly Property Initialized As Boolean Get Return Not Me.Constraints.IsDefault End Get End Property End Structure Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get If _lazyTypeParameters.IsDefault Then ImmutableInterlocked.InterlockedInitialize(_lazyTypeParameters, MakeTypeParameters()) End If Return _lazyTypeParameters End Get End Property ''' <summary> ''' Bind the constraint declarations for the given type parameter. ''' </summary> ''' <remarks> ''' The caller is expected to handle constraint checking and any caching of results. ''' </remarks> Friend Sub BindTypeParameterConstraints( typeParameter As SourceTypeParameterOnTypeSymbol, <Out()> ByRef variance As VarianceKind, <Out()> ByRef constraints As ImmutableArray(Of TypeParameterConstraint), diagnostics As DiagnosticBag) Dim unused = GetTypeMembersDictionary() ' forced nested types to be declared. Dim info As TypeParameterInfo = Nothing ' Go through all declarations, determining the type parameter information ' from each, and updating the type parameter and reporting errors. For Each syntaxRef In SyntaxReferences Dim tree = syntaxRef.SyntaxTree Dim syntaxNode = syntaxRef.GetVisualBasicSyntax() Dim allowVariance = False Select Case syntaxNode.Kind Case SyntaxKind.InterfaceBlock, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement allowVariance = True End Select Dim typeParameterList = GetTypeParameterListSyntax(syntaxNode) CreateTypeParameterInfoInPart(tree, typeParameter, typeParameterList, allowVariance, info, diagnostics) Next Debug.Assert(info.Initialized) variance = info.Variance constraints = info.Constraints End Sub ' Create all the type parameter information from the given declaration. Private Sub CreateTypeParameterInfoInPart(tree As SyntaxTree, typeParameter As SourceTypeParameterOnTypeSymbol, typeParamListSyntax As TypeParameterListSyntax, allowVarianceSpecifier As Boolean, ByRef info As TypeParameterInfo, diagBag As DiagnosticBag) Debug.Assert(typeParamListSyntax IsNot Nothing) Debug.Assert(typeParamListSyntax.Parameters.Count = Me.Arity) ' If this is false, something is really wrong with the declaration tree. ' Set up a binder for this part of the type. Dim binder As Binder = CreateLocationSpecificBinderForType(tree, BindingLocation.GenericConstraintsClause) Dim typeParamSyntax = typeParamListSyntax.Parameters(typeParameter.Ordinal) ' Handle type parameter identifier. Dim identSymbol = typeParamSyntax.Identifier Binder.DisallowTypeCharacter(identSymbol, diagBag, ERRID.ERR_TypeCharOnGenericParam) Dim name As String = identSymbol.ValueText ' Handle type parameter variance. Dim varianceKeyword = typeParamSyntax.VarianceKeyword Dim variance As VarianceKind = VarianceKind.None If varianceKeyword.Kind <> SyntaxKind.None Then If allowVarianceSpecifier Then variance = Binder.DecodeVariance(varianceKeyword) Else Binder.ReportDiagnostic(diagBag, varianceKeyword, ERRID.ERR_VarianceDisallowedHere) End If End If ' Handle constraints. Dim constraints = binder.BindTypeParameterConstraintClause(Me, typeParamSyntax.TypeParameterConstraintClause, diagBag) If info.Initialized Then If Not IdentifierComparison.Equals(typeParameter.Name, name) Then ' "Type parameter name '{0}' does not match the name '{1}' of the corresponding type parameter defined on one of the other partial types of '{2}'." Binder.ReportDiagnostic(diagBag, identSymbol, ERRID.ERR_PartialTypeTypeParamNameMismatch3, name, typeParameter.Name, Me.Name) End If If Not HaveSameConstraints(info.Constraints, constraints) Then ' "Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of '{0}'." Binder.ReportDiagnostic(diagBag, identSymbol, ERRID.ERR_PartialTypeConstraintMismatch1, Me.Name) End If Else info = New TypeParameterInfo(variance, constraints) End If End Sub Private Shared Function HaveSameConstraints(constraints1 As ImmutableArray(Of TypeParameterConstraint), constraints2 As ImmutableArray(Of TypeParameterConstraint)) As Boolean Dim n1 = constraints1.Length Dim n2 = constraints2.Length If n1 <> n2 Then Return False End If If (n1 = 0) AndAlso (n2 = 0) Then Return True End If If GetConstraintKind(constraints1) <> GetConstraintKind(constraints2) Then Return False End If ' Construct a HashSet<T> for one of the sets ' to allow O(n) comparison of the two sets. Dim constraintTypes1 = New HashSet(Of TypeSymbol) For Each constraint In constraints1 Dim constraintType = constraint.TypeConstraint If constraintType IsNot Nothing Then constraintTypes1.Add(constraintType) End If Next For Each constraint In constraints2 Dim constraintType = constraint.TypeConstraint If (constraintType IsNot Nothing) AndAlso Not constraintTypes1.Contains(constraintType) Then Return False End If Next Return True End Function Private Shared Function GetConstraintKind(constraints As ImmutableArray(Of TypeParameterConstraint)) As TypeParameterConstraintKind Dim kind = TypeParameterConstraintKind.None For Each constraint In constraints kind = kind Or constraint.Kind Next Return kind End Function Private Function MakeTypeParameters() As ImmutableArray(Of TypeParameterSymbol) Dim n = TypeDeclaration.Arity If n = 0 Then Return ImmutableArray(Of TypeParameterSymbol).Empty End If Dim typeParameters(0 To n - 1) As TypeParameterSymbol For i = 0 To n - 1 Dim syntaxRefBuilder = ArrayBuilder(Of SyntaxReference).GetInstance() Dim name As String = Nothing For Each syntaxRef In SyntaxReferences Dim tree = syntaxRef.SyntaxTree Dim syntaxNode = syntaxRef.GetVisualBasicSyntax() Dim typeParamListSyntax = GetTypeParameterListSyntax(syntaxNode).Parameters Debug.Assert(typeParamListSyntax.Count = n) Dim typeParamSyntax = typeParamListSyntax(i) If name Is Nothing Then name = typeParamSyntax.Identifier.ValueText End If syntaxRefBuilder.Add(tree.GetReference(typeParamSyntax)) Next Debug.Assert(name IsNot Nothing) Debug.Assert(syntaxRefBuilder.Count > 0) typeParameters(i) = New SourceTypeParameterOnTypeSymbol(Me, i, name, syntaxRefBuilder.ToImmutableAndFree()) Next Return typeParameters.AsImmutableOrNull() End Function Private Shared Function GetTypeParameterListSyntax(syntax As VisualBasicSyntaxNode) As TypeParameterListSyntax Select Case syntax.Kind Case SyntaxKind.StructureBlock, SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock Return DirectCast(syntax, TypeBlockSyntax).BlockStatement.TypeParameterList Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(syntax, DelegateStatementSyntax).TypeParameterList Case Else Return Nothing End Select End Function Friend Sub CheckForDuplicateTypeParameters(typeParameters As ImmutableArray(Of TypeParameterSymbol), diagBag As DiagnosticBag) If Not typeParameters.IsDefault Then Dim typeParameterSet As New HashSet(Of String)(IdentifierComparison.Comparer) ' Check for duplicate type parameters For i = 0 To typeParameters.Length - 1 Dim s = typeParameters(i) If Not typeParameterSet.Contains(s.Name) Then typeParameterSet.Add(s.Name) If ShadowsTypeParameter(s) Then Binder.ReportDiagnostic(diagBag, s.Locations(0), ERRID.WRN_ShadowingGenericParamWithParam1, s.Name) End If Else Binder.ReportDiagnostic(diagBag, s.Locations(0), ERRID.ERR_DuplicateTypeParamName1, s.Name) End If Next End If End Sub Private Function ShadowsTypeParameter(typeParameter As TypeParameterSymbol) As Boolean Dim name As String = typeParameter.Name Dim containingType As SourceNamedTypeSymbol If typeParameter.TypeParameterKind = TypeParameterKind.Method Then containingType = Me Else containingType = TryCast(Me.ContainingType, SourceNamedTypeSymbol) End If While containingType IsNot Nothing If containingType.TypeParameters.MatchesAnyName(name) Then Return True End If containingType = TryCast(containingType.ContainingType, SourceNamedTypeSymbol) End While Return False End Function #End Region #Region "Base Type and Interfaces (phase 4)" Private Sub MakeDeclaredBaseInPart(tree As SyntaxTree, syntaxNode As VisualBasicSyntaxNode, ByRef baseType As NamedTypeSymbol, basesBeingResolved As ConsList(Of Symbol), diagBag As DiagnosticBag) ' Set up a binder for this part of the type. Dim binder As Binder = CreateLocationSpecificBinderForType(tree, BindingLocation.BaseTypes) Select Case syntaxNode.Kind Case SyntaxKind.ClassBlock Dim inheritsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Inherits ' classes may have a base class Dim thisBase As NamedTypeSymbol = ValidateClassBase(inheritsSyntax, baseType, basesBeingResolved, binder, diagBag) If baseType Is Nothing Then baseType = thisBase End If Case SyntaxKind.StructureBlock Dim inheritsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Inherits CheckNoBase(inheritsSyntax, ERRID.ERR_StructCantInherit, diagBag) Case SyntaxKind.ModuleBlock Dim inheritsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Inherits CheckNoBase(inheritsSyntax, ERRID.ERR_ModuleCantInherit, diagBag) End Select End Sub Private Sub MakeDeclaredInterfacesInPart(tree As SyntaxTree, syntaxNode As VisualBasicSyntaxNode, interfaces As SetWithInsertionOrder(Of NamedTypeSymbol), basesBeingResolved As ConsList(Of Symbol), diagBag As DiagnosticBag) ' Set up a binder for this part of the type. Dim binder As Binder = CreateLocationSpecificBinderForType(tree, BindingLocation.BaseTypes) Select Case syntaxNode.Kind Case SyntaxKind.ClassBlock Dim implementsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Implements ' class may implement interfaces ValidateImplementedInterfaces(implementsSyntax, interfaces, basesBeingResolved, binder, diagBag) Case SyntaxKind.StructureBlock Dim implementsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Implements ' struct may implement interfaces ValidateImplementedInterfaces(implementsSyntax, interfaces, basesBeingResolved, binder, diagBag) Case SyntaxKind.InterfaceBlock Dim implementsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Inherits ' interface may inherit interfaces ValidateInheritedInterfaces(implementsSyntax, interfaces, basesBeingResolved, binder, diagBag) Case SyntaxKind.ModuleBlock Dim implementsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Implements CheckNoBase(implementsSyntax, ERRID.ERR_ModuleCantImplement, diagBag) End Select End Sub ' Check that there are no base declarations in the given list, and report the given error if any are found. Private Sub CheckNoBase(Of T As InheritsOrImplementsStatementSyntax)(baseDeclList As SyntaxList(Of T), errId As ERRID, diagBag As DiagnosticBag) If baseDeclList.Count > 0 Then For Each baseDecl In baseDeclList Binder.ReportDiagnostic(diagBag, baseDecl, errId) Next End If End Sub ' Validate the base class declared by a class, diagnosing errors. ' If a base class is found already in another partial, it is passed as baseInOtherPartial. ' Returns the base class if a good base class was found, otherwise Nothing. Private Function ValidateClassBase(inheritsSyntax As SyntaxList(Of InheritsStatementSyntax), baseInOtherPartial As NamedTypeSymbol, basesBeingResolved As ConsList(Of Symbol), binder As Binder, diagBag As DiagnosticBag) As NamedTypeSymbol If inheritsSyntax.Count = 0 Then Return Nothing ' Add myself to the set of classes whose bases are being resolved If basesBeingResolved Is Nothing Then basesBeingResolved = ConsList(Of Symbol).Empty.Prepend(Me) Else basesBeingResolved = basesBeingResolved.Prepend(Me) End If binder = New BasesBeingResolvedBinder(binder, basesBeingResolved) ' Get the first base class declared, and give errors for multiple base classes Dim baseClassSyntax As TypeSyntax = Nothing For Each baseDeclaration In inheritsSyntax If baseDeclaration.Kind = SyntaxKind.InheritsStatement Then Dim inheritsDeclaration = DirectCast(baseDeclaration, InheritsStatementSyntax) If baseClassSyntax IsNot Nothing OrElse inheritsDeclaration.Types.Count > 1 Then Binder.ReportDiagnostic(diagBag, inheritsDeclaration, ERRID.ERR_MultipleExtends) End If If baseClassSyntax Is Nothing AndAlso inheritsDeclaration.Types.Count > 0 Then baseClassSyntax = inheritsDeclaration.Types(0) End If End If Next If baseClassSyntax Is Nothing Then Return Nothing End If ' Bind the base class. Dim baseClassType = binder.BindTypeSyntax(baseClassSyntax, diagBag, suppressUseSiteError:=True, resolvingBaseType:=True) If baseClassType Is Nothing Then Return Nothing End If ' Check to make sure the base class is valid. Dim diagInfo As DiagnosticInfo = Nothing Select Case baseClassType.TypeKind Case TypeKind.TypeParameter Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_GenericParamBase2, "Class", Me.Name) Return Nothing Case TypeKind.Interface, TypeKind.Enum, TypeKind.Delegate, TypeKind.Structure, TypeKind.Module, TypeKind.Array ' array can't really occur Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_InheritsFromNonClass) Return Nothing Case TypeKind.Error, TypeKind.Unknown Return DirectCast(baseClassType, NamedTypeSymbol) Case TypeKind.Class If IsRestrictedBaseClass(baseClassType.SpecialType) Then Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_InheritsFromRestrictedType1, baseClassType) Return Nothing ElseIf DirectCast(baseClassType, NamedTypeSymbol).IsNotInheritable Then Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_InheritsFromCantInherit3, Me.Name, baseClassType.Name, baseClassType.GetKindText()) Return Nothing End If End Select ' The same base class can be declared in multiple partials, but not different ones If baseInOtherPartial IsNot Nothing Then If Not baseClassType.Equals(baseInOtherPartial) Then Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_BaseMismatchForPartialClass3, baseClassType, Me.Name, baseInOtherPartial) Return Nothing End If ElseIf Not baseClassType.IsErrorType() Then ' Verify that we don't have public classes inheriting from private ones, etc. AccessCheck.VerifyAccessExposureOfBaseClassOrInterface(Me, baseClassSyntax, baseClassType, diagBag) End If Return DirectCast(baseClassType, NamedTypeSymbol) End Function Private Sub ValidateInheritedInterfaces(baseSyntax As SyntaxList(Of InheritsStatementSyntax), basesInOtherPartials As SetWithInsertionOrder(Of NamedTypeSymbol), basesBeingResolved As ConsList(Of Symbol), binder As Binder, diagBag As DiagnosticBag) If baseSyntax.Count = 0 Then Return ' Add myself to the set of classes whose bases are being resolved If basesBeingResolved Is Nothing Then basesBeingResolved = ConsList(Of Symbol).Empty.Prepend(Me) Else basesBeingResolved = basesBeingResolved.Prepend(Me) End If binder = New BasesBeingResolvedBinder(binder, basesBeingResolved) ' give errors for multiple base classes Dim interfacesInThisPartial As New HashSet(Of NamedTypeSymbol)() For Each baseDeclaration In baseSyntax Dim types = DirectCast(baseDeclaration, InheritsStatementSyntax).Types For Each baseClassSyntax In types Dim typeSymbol = binder.BindTypeSyntax(baseClassSyntax, diagBag, suppressUseSiteError:=True) Dim namedType = TryCast(typeSymbol, NamedTypeSymbol) If namedType IsNot Nothing AndAlso interfacesInThisPartial.Contains(namedType) Then Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_DuplicateInInherits1, typeSymbol) Else If namedType IsNot Nothing Then interfacesInThisPartial.Add(namedType) End If ' Check to make sure the base interfaces are valid. Select Case typeSymbol.TypeKind Case TypeKind.TypeParameter Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_GenericParamBase2, "Interface", Me.Name) Continue For Case TypeKind.Unknown Continue For Case TypeKind.Interface, TypeKind.Error basesInOtherPartials.Add(namedType) If Not typeSymbol.IsErrorType() Then ' Make sure that we aren't exposing an interface with a restricted type, ' e.g. a public interface can't inherit from a private interface AccessCheck.VerifyAccessExposureOfBaseClassOrInterface(Me, baseClassSyntax, typeSymbol, diagBag) End If Case Else Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_InheritsFromNonInterface) Continue For End Select End If Next Next End Sub Private Sub ValidateImplementedInterfaces(baseSyntax As SyntaxList(Of ImplementsStatementSyntax), basesInOtherPartials As SetWithInsertionOrder(Of NamedTypeSymbol), basesBeingResolved As ConsList(Of Symbol), binder As Binder, diagBag As DiagnosticBag) If baseSyntax.Count = 0 Then Return If basesBeingResolved IsNot Nothing Then binder = New BasesBeingResolvedBinder(binder, basesBeingResolved) End If ' give errors for multiple base classes Dim interfacesInThisPartial As New HashSet(Of TypeSymbol)() For Each baseDeclaration In baseSyntax Dim types = DirectCast(baseDeclaration, ImplementsStatementSyntax).Types For Each baseClassSyntax In types Dim typeSymbol = binder.BindTypeSyntax(baseClassSyntax, diagBag, suppressUseSiteError:=True) If Not interfacesInThisPartial.Add(typeSymbol) Then Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_InterfaceImplementedTwice1, typeSymbol) Else ' Check to make sure the base interfaces are valid. Select Case typeSymbol.TypeKind Case TypeKind.TypeParameter Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_ImplementsGenericParam, "Interface", Me.Name) Continue For Case TypeKind.Unknown Continue For Case TypeKind.Interface, TypeKind.Error basesInOtherPartials.Add(DirectCast(typeSymbol, NamedTypeSymbol)) Case Else Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_BadImplementsType) Continue For End Select End If Next Next End Sub ' Determines if this type is one of the special types we can't inherit from Private Function IsRestrictedBaseClass(type As SpecialType) As Boolean Select Case type Case SpecialType.System_Array, SpecialType.System_Delegate, SpecialType.System_MulticastDelegate, SpecialType.System_Enum, SpecialType.System_ValueType Return True Case Else Return False End Select End Function Private Function AsPeOrRetargetingType(potentialBaseType As TypeSymbol) As NamedTypeSymbol Dim peType As NamedTypeSymbol = TryCast(potentialBaseType, Symbols.Metadata.PE.PENamedTypeSymbol) If peType Is Nothing Then peType = TryCast(potentialBaseType, Retargeting.RetargetingNamedTypeSymbol) End If Return peType End Function Friend Overrides Function MakeDeclaredBase(basesBeingResolved As ConsList(Of Symbol), diagnostics As DiagnosticBag) As NamedTypeSymbol ' For types nested in a source type symbol (not in a script class): ' before resolving the base type ensure that enclosing type's base type is already resolved Dim containingSourceType = TryCast(ContainingSymbol, SourceNamedTypeSymbol) If containingSourceType IsNot Nothing Then containingSourceType.GetDeclaredBaseSafe(If(basesBeingResolved, ConsList(Of Symbol).Empty).Prepend(Me)) End If Dim baseType As NamedTypeSymbol = Nothing ' Go through all the parts of this type, and declare the information in that part, ' reporting errors appropriately. For Each decl In Me.TypeDeclaration.Declarations If decl.HasBaseDeclarations Then Dim syntaxRef = decl.SyntaxReference MakeDeclaredBaseInPart(syntaxRef.SyntaxTree, syntaxRef.GetVisualBasicSyntax(), baseType, basesBeingResolved, diagnostics) End If Next Return baseType End Function Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As ConsList(Of Symbol), diagnostics As DiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) ' For types nested in a source type symbol (not in a script class): ' before resolving the base type ensure that enclosing type's base type is already resolved Dim containingSourceType = TryCast(ContainingSymbol, SourceNamedTypeSymbol) If containingSourceType IsNot Nothing AndAlso containingSourceType.IsInterface Then containingSourceType.GetDeclaredBaseInterfacesSafe(If(basesBeingResolved, ConsList(Of Symbol).Empty).Prepend(Me)) End If Dim interfaces As New SetWithInsertionOrder(Of NamedTypeSymbol) ' Go through all the parts of this type, and declare the information in that part, ' reporting errors appropriately. For Each syntaxRef In SyntaxReferences MakeDeclaredInterfacesInPart(syntaxRef.SyntaxTree, syntaxRef.GetVisualBasicSyntax(), interfaces, basesBeingResolved, diagnostics) Next Return interfaces.AsImmutable End Function Private Function GetInheritsLocation(base As NamedTypeSymbol) As Location Return GetInheritsOrImplementsLocation(base, True) End Function Protected Overrides Function GetInheritsOrImplementsLocation(base As NamedTypeSymbol, getInherits As Boolean) As Location Dim backupLocation As Location = Nothing For Each part In SyntaxReferences Dim typeBlock = DirectCast(part.GetSyntax(), TypeBlockSyntax) Dim inhDecl = If(getInherits, DirectCast(typeBlock.Inherits, IEnumerable(Of InheritsOrImplementsStatementSyntax)), DirectCast(typeBlock.Implements, IEnumerable(Of InheritsOrImplementsStatementSyntax))) Dim binder As Binder = CreateLocationSpecificBinderForType(part.SyntaxTree, BindingLocation.BaseTypes) Dim basesBeingResolved = ConsList(Of Symbol).Empty.Prepend(Me) binder = New BasesBeingResolvedBinder(binder, basesBeingResolved) Dim diag = New DiagnosticBag ' unused For Each t In inhDecl If backupLocation Is Nothing Then backupLocation = t.GetLocation() End If Dim types As SeparatedSyntaxList(Of TypeSyntax) = If(getInherits, DirectCast(t, InheritsStatementSyntax).Types, DirectCast(t, ImplementsStatementSyntax).Types) For Each typeSyntax In types Dim bt = binder.BindTypeSyntax(typeSyntax, diag, suppressUseSiteError:=True) If bt = base Then Return typeSyntax.GetLocation() End If Next Next Next ' In recursive or circular cases, the BindTypeSyntax fails to give the same result as the circularity ' removing algorithm does. In this case, use the entire Inherits or Implements statement as the location. Return backupLocation End Function Friend Overrides Function MakeAcyclicBaseType(diagnostics As DiagnosticBag) As NamedTypeSymbol Dim compilation As VisualBasicCompilation = Me.DeclaringCompilation Dim declaredBase As NamedTypeSymbol = Me.GetDeclaredBase(Nothing) If declaredBase IsNot Nothing Then Dim diag As DiagnosticInfo = If(m_baseCycleDiagnosticInfo, BaseTypeAnalysis.GetDependenceDiagnosticForBase(Me, declaredBase)) If diag IsNot Nothing Then Dim location = GetInheritsLocation(declaredBase) ' TODO: if there is a cycle dependency in base type we might want to ignore all ' other diagnostics collected so far because they may be incorrectly generated ' because of the cycle -- check and decide if we want to do so 'diagnostics.Clear() diagnostics.Add(New VBDiagnostic(diag, location)) Return New ExtendedErrorTypeSymbol(diag, False) End If End If Dim declaredOrDefaultBase As NamedTypeSymbol = declaredBase ' Get the default base type if none was declared If declaredOrDefaultBase Is Nothing AndAlso Me.SpecialType <> Microsoft.CodeAnalysis.SpecialType.System_Object Then Select Case TypeKind Case TypeKind.Submission ' check that System.Object is available. ' Although the submission semantically doesn't have a base class we need to emit one. ReportUseSiteDiagnosticsForBaseType(Me.DeclaringCompilation.GetSpecialType(SpecialType.System_Object), declaredBase, diagnostics) declaredOrDefaultBase = Nothing Case TypeKind.Class declaredOrDefaultBase = GetSpecialType(SpecialType.System_Object) Case TypeKind.Interface declaredOrDefaultBase = Nothing Case TypeKind.Enum declaredOrDefaultBase = GetSpecialType(SpecialType.System_Enum) Case TypeKind.Structure declaredOrDefaultBase = GetSpecialType(SpecialType.System_ValueType) Case TypeKind.Delegate declaredOrDefaultBase = GetSpecialType(SpecialType.System_MulticastDelegate) Case TypeKind.Module declaredOrDefaultBase = GetSpecialType(SpecialType.System_Object) Case Else Throw ExceptionUtilities.UnexpectedValue(TypeKind) End Select End If If declaredOrDefaultBase IsNot Nothing Then ReportUseSiteDiagnosticsForBaseType(declaredOrDefaultBase, declaredBase, diagnostics) End If Return declaredOrDefaultBase End Function Private Function GetSpecialType(type As SpecialType) As NamedTypeSymbol Return ContainingModule.ContainingAssembly.GetSpecialType(type) End Function Private Sub ReportUseSiteDiagnosticsForBaseType(baseType As NamedTypeSymbol, declaredBase As NamedTypeSymbol, diagnostics As DiagnosticBag) Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Dim current As NamedTypeSymbol = baseType Do If current.DeclaringCompilation Is Me.DeclaringCompilation Then Exit Do End If current.AddUseSiteDiagnostics(useSiteDiagnostics) current = current.BaseTypeNoUseSiteDiagnostics Loop While current IsNot Nothing If Not useSiteDiagnostics.IsNullOrEmpty Then Dim location As Location If declaredBase Is baseType Then location = GetInheritsLocation(baseType) Else Dim syntaxRef = SyntaxReferences.First() Dim syntax = syntaxRef.GetVisualBasicSyntax() ' script, submission and implicit classes have no identifier location: location = If(syntax.Kind = SyntaxKind.CompilationUnit OrElse syntax.Kind = SyntaxKind.NamespaceBlock, Locations(0), GetTypeIdentifierToken(syntax).GetLocation()) End If diagnostics.Add(location, useSiteDiagnostics) End If End Sub Friend Overrides Function MakeAcyclicInterfaces(diagnostics As DiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Dim declaredInterfaces As ImmutableArray(Of NamedTypeSymbol) = GetDeclaredInterfacesNoUseSiteDiagnostics(Nothing) Dim isInterface As Boolean = Me.IsInterfaceType() Dim result As ArrayBuilder(Of NamedTypeSymbol) = If(isInterface, ArrayBuilder(Of NamedTypeSymbol).GetInstance(), Nothing) For Each t In declaredInterfaces Dim diag = If(isInterface AndAlso Not t.IsErrorType(), GetDependenceDiagnosticForBase(Me, t), Nothing) If diag IsNot Nothing Then Dim location = GetInheritsLocation(t) diagnostics.Add(New VBDiagnostic(diag, location)) result.Add(New ExtendedErrorTypeSymbol(diag, False)) Else ' Error types were reported elsewhere. If Not t.IsErrorType() Then Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing If t.DeclaringCompilation IsNot Me.DeclaringCompilation Then t.AddUseSiteDiagnostics(useSiteDiagnostics) For Each [interface] In t.AllInterfacesNoUseSiteDiagnostics If [interface].DeclaringCompilation IsNot Me.DeclaringCompilation Then [interface].AddUseSiteDiagnostics(useSiteDiagnostics) End If Next End If If Not useSiteDiagnostics.IsNullOrEmpty Then Dim location = If(isInterface, GetInheritsLocation(t), GetInheritsOrImplementsLocation(t, getInherits:=False)) diagnostics.Add(location, useSiteDiagnostics) End If End If If isInterface Then result.Add(t) End If End If Next Return If(isInterface, result.ToImmutableAndFree, declaredInterfaces) End Function Friend Overrides Function GetDirectBaseTypeNoUseSiteDiagnostics(basesBeingResolved As ConsList(Of Symbol)) As NamedTypeSymbol Debug.Assert(Me.TypeKind <> TypeKind.Interface) If TypeKind = TypeKind.Enum Then ' Base type has the underlying type instead. Return GetSpecialType(SpecialType.System_Enum) ElseIf TypeKind = TypeKind.Delegate Then ' Base type has the underlying type instead. Return GetSpecialType(SpecialType.System_MulticastDelegate) Else If basesBeingResolved Is Nothing Then Return Me.BaseTypeNoUseSiteDiagnostics Else Return GetDeclaredBaseSafe(basesBeingResolved) End If End If End Function ''' <summary> ''' 'Safe' version of GetDeclaredBase takes into account bases being resolved to make sure ''' we avoid infinite loops in some scenarios. Note that the cycle is being broken not when ''' we detect it, but when we detect it on the 'smallest' type of the cycle, this brings stability ''' in multithreaded scenarios while still ensures that we don't loop more than twice. ''' </summary> Private Function GetDeclaredBaseSafe(basesBeingResolved As ConsList(Of Symbol)) As NamedTypeSymbol If m_baseCycleDiagnosticInfo IsNot Nothing Then ' We have already detected this type has a cycle and it was chosen ' to be the one which reports the problem and breaks the cycle Return Nothing End If Debug.Assert(basesBeingResolved.Any) If Me Is basesBeingResolved.Head Then ' This is a little tricky: the head of 'basesBeingResolved' represents the innermost ' type whose base is being resolved. That means if we start name lookup with that type ' as containing type and if we cannot find the name in its scope we want just to skip base ' type search and avoid any errors. We want this to happen only for that innermost type ' in base resolution chain. An example: ' ' Class A ' Class B ' Inherits D ' Lookup for 'D' starts in scope of 'B', we ' Class C ' are skipping diving into B's base class here ' End Class ' to make it possible to find A.D ' End Class ' Class D ' End Class ' End Class ' NOTE: that it the lookup is not the first indirect one, but B was found earlier ' during lookup process, we still can ignore B's base type because another ' error (B cannot reference itself in its Inherits clause) should be generated ' by this time, like in the following example: ' ' Class A ' Class B ' Inherits A.B.C ' <- error BC31447: Class 'A.B' cannot ' Class C ' reference itself in Inherits clause. ' End Class ' End Class ' Class D ' End Class ' End Class Return Nothing End If Dim diag As DiagnosticInfo = GetDependenceDiagnosticForBase(Me, basesBeingResolved) If diag Is Nothing Then Dim declaredBase As NamedTypeSymbol = GetDeclaredBase(basesBeingResolved) ' If we detected the cycle while calculating the declared base, return Nothing Return If(m_baseCycleDiagnosticInfo Is Nothing, declaredBase, Nothing) End If Dim prev = Interlocked.CompareExchange(m_baseCycleDiagnosticInfo, diag, Nothing) Debug.Assert(prev Is Nothing OrElse prev.GetMessage().Equals(diag.GetMessage())) Return Nothing End Function Friend Overrides Function GetDeclaredBaseInterfacesSafe(basesBeingResolved As ConsList(Of Symbol)) As ImmutableArray(Of NamedTypeSymbol) If m_baseCycleDiagnosticInfo IsNot Nothing Then ' We have already detected this type has a cycle and it was chosen ' to be the one which reports the problem and breaks the cycle Return Nothing End If Debug.Assert(basesBeingResolved.Any) If Me Is basesBeingResolved.Head Then Return Nothing End If Dim diag As DiagnosticInfo = GetDependenceDiagnosticForBase(Me, basesBeingResolved) If diag Is Nothing Then Dim declaredBases As ImmutableArray(Of NamedTypeSymbol) = GetDeclaredInterfacesNoUseSiteDiagnostics(basesBeingResolved) ' If we detected the cycle while calculating the declared base, return Nothing Return If(m_baseCycleDiagnosticInfo Is Nothing, declaredBases, ImmutableArray(Of NamedTypeSymbol).Empty) End If Dim prev = Interlocked.CompareExchange(m_baseCycleDiagnosticInfo, diag, Nothing) Debug.Assert(prev Is Nothing OrElse prev.GetMessage().Equals(diag.GetMessage())) Return Nothing End Function ''' <summary> ''' Do additional verification of base types the after acyclic base is found. This is ''' the chance to generate diagnostics that may require walking bases and as such ''' can be performed only after the base has been determined and cycles broken. ''' (For instance, checking constraints on Class B(Of T) Inherits A(Of B(Of T)).) ''' </summary> Private Sub CheckBaseConstraints() If (m_lazyState And StateFlags.ReportedBaseClassConstraintsDiagnostics) <> 0 Then Return End If Dim diagnostics As DiagnosticBag = Nothing Dim localBase = BaseTypeNoUseSiteDiagnostics If localBase IsNot Nothing Then ' Check constraints on the first declaration with explicit bases. Dim singleDeclaration = FirstDeclarationWithExplicitBases() If singleDeclaration IsNot Nothing Then Dim location = singleDeclaration.NameLocation diagnostics = DiagnosticBag.GetInstance() localBase.CheckAllConstraints(location, diagnostics) If IsGenericType Then ' Check that generic type does not derive from System.Attribute. ' This check must be done here instead of in ValidateClassBase to avoid infinite recursion when there are ' cycles in the inheritance chain. In Dev10/11, the error was reported on the inherited statement, now it ' is reported on the class statement. Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Dim isBaseType As Boolean = DeclaringCompilation.GetWellKnownType(WellKnownType.System_Attribute).IsBaseTypeOf(localBase, useSiteDiagnostics) diagnostics.Add(location, useSiteDiagnostics) If isBaseType Then ' WARNING: in case System_Attribute was not found or has errors, the above check may ' fail to detect inheritance from System.Attribute, but we assume that in this case ' another error will be generated anyway Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_GenericClassCannotInheritAttr) End If End If End If End If m_containingModule.AtomicSetFlagAndStoreDiagnostics(m_lazyState, StateFlags.ReportedBaseClassConstraintsDiagnostics, 0, diagnostics, CompilationStage.Declare) If diagnostics IsNot Nothing Then diagnostics.Free() End If End Sub ''' <summary> ''' Do additional verification of interfaces after acyclic interfaces are found. This is ''' the chance to generate diagnostics that may need to walk interfaces and as such ''' can be performed only after the interfaces have been determined and cycles broken. ''' (For instance, checking constraints on Class C(Of T) Implements I(Of C(Of T)).) ''' </summary> Private Sub CheckInterfacesConstraints() If (m_lazyState And StateFlags.ReportedInterfacesConstraintsDiagnostics) <> 0 Then Return End If Dim diagnostics As DiagnosticBag = Nothing Dim localInterfaces = InterfacesNoUseSiteDiagnostics If Not localInterfaces.IsEmpty Then ' Check constraints on the first declaration with explicit interfaces. Dim singleDeclaration = FirstDeclarationWithExplicitInterfaces() If singleDeclaration IsNot Nothing Then Dim location = singleDeclaration.NameLocation diagnostics = DiagnosticBag.GetInstance() For Each [interface] In localInterfaces [interface].CheckAllConstraints(location, diagnostics) Next End If End If If m_containingModule.AtomicSetFlagAndStoreDiagnostics(m_lazyState, StateFlags.ReportedInterfacesConstraintsDiagnostics, 0, diagnostics, CompilationStage.Declare) Then DeclaringCompilation.SymbolDeclaredEvent(Me) End If If diagnostics IsNot Nothing Then diagnostics.Free() End If End Sub ''' <summary> ''' Return the first Class declaration with explicit base classes to use for ''' checking base class constraints. Other type declarations (Structures, ''' Modules, Interfaces) are ignored since other errors will have been ''' reported if those types include bases. ''' </summary> Private Function FirstDeclarationWithExplicitBases() As SingleTypeDeclaration For Each decl In TypeDeclaration.Declarations Dim syntaxNode = decl.SyntaxReference.GetVisualBasicSyntax() Select Case syntaxNode.Kind Case SyntaxKind.ClassBlock If DirectCast(syntaxNode, TypeBlockSyntax).Inherits.Count > 0 Then Return decl End If End Select Next Return Nothing End Function ''' <summary> ''' Return the first Class, Structure, or Interface declaration with explicit interfaces ''' to use for checking interface constraints. Other type declarations (Modules) are ''' ignored since other errors will have been reported if those types include interfaces. ''' </summary> Private Function FirstDeclarationWithExplicitInterfaces() As SingleTypeDeclaration For Each decl In TypeDeclaration.Declarations Dim syntaxNode = decl.SyntaxReference.GetVisualBasicSyntax() Select Case syntaxNode.Kind Case SyntaxKind.ClassBlock, SyntaxKind.StructureBlock If DirectCast(syntaxNode, TypeBlockSyntax).Implements.Count > 0 Then Return decl End If Case SyntaxKind.InterfaceBlock If DirectCast(syntaxNode, TypeBlockSyntax).Inherits.Count > 0 Then Return decl End If End Select Next Return Nothing End Function #End Region #Region "Enums" ''' <summary> ''' For enum types, gets the underlying type. Returns null on all other ''' kinds of types. ''' </summary> Public Overrides ReadOnly Property EnumUnderlyingType As NamedTypeSymbol Get If Not Me.IsEnumType Then Return Nothing End If Dim underlyingType = Me._lazyEnumUnderlyingType If underlyingType Is Nothing Then Dim tempDiags = DiagnosticBag.GetInstance Dim blockRef = SyntaxReferences(0) Dim tree = blockRef.SyntaxTree Dim syntax = DirectCast(blockRef.GetSyntax, EnumBlockSyntax) Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, tree, Me) underlyingType = BindEnumUnderlyingType(syntax, binder, tempDiags) If Interlocked.CompareExchange(Me._lazyEnumUnderlyingType, underlyingType, Nothing) Is Nothing Then ContainingSourceModule.AddDiagnostics(tempDiags, CompilationStage.Declare) Else Debug.Assert(underlyingType = Me._lazyEnumUnderlyingType) underlyingType = Me._lazyEnumUnderlyingType End If tempDiags.Free() End If Debug.Assert(underlyingType IsNot Nothing) Return underlyingType End Get End Property Private Function BindEnumUnderlyingType(syntax As EnumBlockSyntax, bodyBinder As Binder, diagnostics As DiagnosticBag) As NamedTypeSymbol Dim underlyingType = syntax.EnumStatement.UnderlyingType If underlyingType IsNot Nothing AndAlso Not underlyingType.Type.IsMissing Then Dim type = bodyBinder.BindTypeSyntax(underlyingType.Type, diagnostics) If type.IsValidEnumUnderlyingType Then Return DirectCast(type, NamedTypeSymbol) Else Binder.ReportDiagnostic(diagnostics, underlyingType.Type, ERRID.ERR_InvalidEnumBase) End If End If Return bodyBinder.GetSpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32, syntax.EnumStatement.Identifier, diagnostics) End Function #End Region #Region "Attributes" Public ReadOnly Property DefaultAttributeLocation As AttributeLocation Implements IAttributeTargetSymbol.DefaultAttributeLocation Get Return AttributeLocation.Type End Get End Property Private Function GetAttributeDeclarations() As ImmutableArray(Of SyntaxList(Of AttributeListSyntax)) Dim result = TypeDeclaration.GetAttributeDeclarations() Debug.Assert(result.Length = 0 OrElse (Not Me.IsScriptClass AndAlso Not Me.IsImplicitClass)) ' Should be handled by above test. Return result End Function Private Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) If m_lazyCustomAttributesBag Is Nothing OrElse Not m_lazyCustomAttributesBag.IsSealed Then LoadAndValidateAttributes(OneOrMany.Create(GetAttributeDeclarations()), m_lazyCustomAttributesBag) End If Debug.Assert(m_lazyCustomAttributesBag.IsSealed) Return m_lazyCustomAttributesBag End Function ''' <summary> ''' Gets the attributes applied on this symbol. ''' Returns an empty array if there are no attributes. ''' </summary> Public NotOverridable Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me.GetAttributesBag().Attributes End Function Private Function GetDecodedWellKnownAttributeData() As CommonTypeWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.m_lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonTypeWellKnownAttributeData) End Function Friend Overrides ReadOnly Property HasCodeAnalysisEmbeddedAttribute As Boolean Get Dim data As TypeEarlyWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCodeAnalysisEmbeddedAttribute End Get End Property Friend Overrides ReadOnly Property HasVisualBasicEmbeddedAttribute As Boolean Get Dim data As TypeEarlyWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasVisualBasicEmbeddedAttribute End Get End Property Friend Overrides ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean Get If _lazyIsExtensibleInterface = ThreeState.Unknown Then _lazyIsExtensibleInterface = DecodeIsExtensibleInterface().ToThreeState() End If Return _lazyIsExtensibleInterface.Value End Get End Property Private Function DecodeIsExtensibleInterface() As Boolean If Me.IsInterfaceType() Then Dim data As TypeEarlyWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData() If data IsNot Nothing AndAlso data.HasAttributeForExtensibleInterface Then Return True End If For Each [interface] In Me.AllInterfacesNoUseSiteDiagnostics If [interface].IsExtensibleInterfaceNoUseSiteDiagnostics Then Return True End If Next End If Return False End Function ''' <summary> ''' Returns data decoded from early bound well-known attributes applied to the symbol or null if there are no applied attributes. ''' </summary> ''' <remarks> ''' Forces binding and decoding of attributes. ''' </remarks> Private Function GetEarlyDecodedWellKnownAttributeData() As TypeEarlyWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.m_lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsEarlyDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.EarlyDecodedWellKnownAttributeData, TypeEarlyWellKnownAttributeData) End Function Friend Overrides ReadOnly Property IsComImport As Boolean Get Dim data As TypeEarlyWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasComImportAttribute End Get End Property Friend Overrides ReadOnly Property CoClassType As TypeSymbol Get If _lazyCoClassType Is ErrorTypeSymbol.UnknownResultType Then If Not Me.IsInterface Then Interlocked.CompareExchange(_lazyCoClassType, Nothing, DirectCast(ErrorTypeSymbol.UnknownResultType, TypeSymbol)) Else Dim dummy As CommonTypeWellKnownAttributeData = GetDecodedWellKnownAttributeData() If _lazyCoClassType Is ErrorTypeSymbol.UnknownResultType Then ' if this is still ErrorTypeSymbol.UnknownResultType, interface ' does not have the attribute applied Interlocked.CompareExchange(_lazyCoClassType, Nothing, DirectCast(ErrorTypeSymbol.UnknownResultType, TypeSymbol)) End If End If End If Debug.Assert(_lazyCoClassType IsNot ErrorTypeSymbol.UnknownResultType) Debug.Assert(Me.IsInterface OrElse _lazyCoClassType Is Nothing) Return _lazyCoClassType End Get End Property Friend Overrides ReadOnly Property IsWindowsRuntimeImport As Boolean Get Dim typeData As CommonTypeWellKnownAttributeData = Me.GetDecodedWellKnownAttributeData() Return typeData IsNot Nothing AndAlso typeData.HasWindowsRuntimeImportAttribute End Get End Property Friend Overrides ReadOnly Property ShouldAddWinRTMembers As Boolean Get Return False End Get End Property Friend ReadOnly Property HasSecurityCriticalAttributes As Boolean Get Dim typeData As CommonTypeWellKnownAttributeData = Me.GetDecodedWellKnownAttributeData() Return typeData IsNot Nothing AndAlso typeData.HasSecurityCriticalAttributes End Get End Property ''' <summary> ''' Is System.Runtime.InteropServices.GuidAttribute applied to this type in code. ''' </summary> Friend Function HasGuidAttribute() As Boolean ' So far this information is used only by ComClass feature, therefore, I do not believe ' it is worth to intercept this attribute in DecodeWellKnownAttribute and cache the fact of attribute's ' presence and the guid value. If we start caching that information, implementation of this function ' should change to take advantage of the cache. Return GetAttributes().IndexOfAttribute(Me, AttributeDescription.GuidAttribute) > -1 End Function ''' <summary> ''' Is System.Runtime.InteropServices.ClassInterfaceAttribute applied to this type in code. ''' </summary> Friend Function HasClassInterfaceAttribute() As Boolean ' So far this information is used only by ComClass feature, therefore, I do not believe ' it is worth to intercept this attribute in DecodeWellKnownAttribute and cache the fact of attribute's ' presence and its data. If we start caching that information, implementation of this function ' should change to take advantage of the cache. Return GetAttributes().IndexOfAttribute(Me, AttributeDescription.ClassInterfaceAttribute) > -1 End Function ''' <summary> ''' Is System.Runtime.InteropServices.ComSourceInterfacesAttribute applied to this type in code. ''' </summary> Friend Function HasComSourceInterfacesAttribute() As Boolean ' So far this information is used only by ComClass feature, therefore, I do not believe ' it is worth to intercept this attribute in DecodeWellKnownAttribute and cache the fact of attribute's ' presence and the its data. If we start caching that information, implementation of this function ' should change to take advantage of the cache. Return GetAttributes().IndexOfAttribute(Me, AttributeDescription.ComSourceInterfacesAttribute) > -1 End Function Friend Overrides Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData Debug.Assert(arguments.AttributeType IsNot Nothing) Debug.Assert(Not arguments.AttributeType.IsErrorType()) Dim hasAnyDiagnostics As Boolean = False If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.VisualBasicEmbeddedAttribute) Then ' Handle Microsoft.VisualBasic.Embedded attribute Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().HasVisualBasicEmbeddedAttribute = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CodeAnalysisEmbeddedAttribute) Then ' Handle Microsoft.CodeAnalysis.Embedded attribute Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().HasCodeAnalysisEmbeddedAttribute = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ComImportAttribute) Then ' Handle ComImportAttribute Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().HasComImportAttribute = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ConditionalAttribute) Then ' Handle ConditionalAttribute Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then Dim conditionalSymbol As String = attrdata.GetConstructorArgument(Of String)(0, SpecialType.System_String) arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().AddConditionalSymbol(conditionalSymbol) Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If End If Dim boundAttribute As VisualBasicAttributeData = Nothing Dim obsoleteData As ObsoleteAttributeData = Nothing If EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(arguments, boundAttribute, obsoleteData) Then If obsoleteData IsNot Nothing Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().ObsoleteAttributeData = obsoleteData End If Return boundAttribute End If If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.AttributeUsageAttribute) Then ' Avoid decoding duplicate AttributeUsageAttribute. If Not arguments.HasDecodedData OrElse DirectCast(arguments.DecodedData, TypeEarlyWellKnownAttributeData).AttributeUsageInfo.IsNull Then ' Handle AttributeUsageAttribute: If this type is an attribute type then decode the AttributeUsageAttribute, otherwise ignore it. Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().AttributeUsageInfo = attrdata.DecodeAttributeUsageAttribute() Debug.Assert(Not DirectCast(arguments.DecodedData, TypeEarlyWellKnownAttributeData).AttributeUsageInfo.IsNull) ' NOTE: Native VB compiler does not validate the AttributeTargets argument to AttributeUsageAttribute, we do the same. Return If(Not hasAnyDiagnostics, attrdata, Nothing) End If End If Return Nothing End If If Me.IsInterfaceType() Then If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.InterfaceTypeAttribute) Then Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then Dim interfaceType As ComInterfaceType = Nothing If attrdata.DecodeInterfaceTypeAttribute(interfaceType) AndAlso (interfaceType And Cci.Constants.ComInterfaceType_InterfaceIsIDispatch) <> 0 Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData).HasAttributeForExtensibleInterface = True End If Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.TypeLibTypeAttribute) Then Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then Dim flags As Cci.TypeLibTypeFlags = attrdata.DecodeTypeLibTypeAttribute() If (flags And Cci.TypeLibTypeFlags.FNonExtensible) = 0 Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData).HasAttributeForExtensibleInterface = True End If Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If End If End If Return MyBase.EarlyDecodeWellKnownAttribute(arguments) End Function Friend NotOverridable Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Dim data As CommonTypeEarlyWellKnownAttributeData = Me.GetEarlyDecodedWellKnownAttributeData() Return If(data IsNot Nothing, data.ConditionalSymbols, ImmutableArray(Of String).Empty) End Function Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Dim lazyCustomAttributesBag = m_lazyCustomAttributesBag If lazyCustomAttributesBag IsNot Nothing AndAlso lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed Then Dim data = DirectCast(lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData, CommonTypeEarlyWellKnownAttributeData) Return If(data IsNot Nothing, data.ObsoleteAttributeData, Nothing) End If For Each decl In TypeDeclaration.Declarations If decl.HasAnyAttributes Then Return ObsoleteAttributeData.Uninitialized End If Next Return Nothing End Get End Property Friend NotOverridable Overrides Function GetAttributeUsageInfo() As AttributeUsageInfo Debug.Assert(Me.IsOrDerivedFromWellKnownClass(WellKnownType.System_Attribute, DeclaringCompilation, Nothing) OrElse Me.SpecialType = Microsoft.CodeAnalysis.SpecialType.System_Object) Dim data As TypeEarlyWellKnownAttributeData = Me.GetEarlyDecodedWellKnownAttributeData() If data IsNot Nothing AndAlso Not data.AttributeUsageInfo.IsNull Then Return data.AttributeUsageInfo Else Dim baseType = Me.BaseTypeNoUseSiteDiagnostics Return If(baseType IsNot Nothing, baseType.GetAttributeUsageInfo(), AttributeUsageInfo.Default) End If End Function Friend NotOverridable Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Dim data As CommonTypeWellKnownAttributeData = Me.GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasDeclarativeSecurity End Get End Property Friend NotOverridable Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.GetAttributesBag() Dim wellKnownAttributeData = DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonTypeWellKnownAttributeData) If wellKnownAttributeData IsNot Nothing Then Dim securityData As SecurityWellKnownAttributeData = wellKnownAttributeData.SecurityInformation If securityData IsNot Nothing Then Return securityData.GetSecurityAttributes(attributesBag.Attributes) End If End If Return SpecializedCollections.EmptyEnumerable(Of Microsoft.Cci.SecurityAttribute)() End Function Friend NotOverridable Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) Dim attrData = arguments.Attribute Debug.Assert(Not attrData.HasErrors) Debug.Assert(arguments.SymbolPart = AttributeLocation.None) ' If we start caching information about GuidAttribute here, implementation of HasGuidAttribute function should be changed accordingly. ' If we start caching information about ClassInterfaceAttribute here, implementation of HasClassInterfaceAttribute function should be changed accordingly. ' If we start caching information about ComSourceInterfacesAttribute here, implementation of HasComSourceInterfacesAttribute function should be changed accordingly. ' If we start caching information about ComVisibleAttribute here, implementation of GetComVisibleState function should be changed accordingly. If attrData.IsTargetAttribute(Me, AttributeDescription.TupleElementNamesAttribute) Then arguments.Diagnostics.Add(ERRID.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location) End If Dim decoded As Boolean = False Select Case Me.TypeKind Case TypeKind.Class If attrData.IsTargetAttribute(Me, AttributeDescription.CaseInsensitiveExtensionAttribute) Then arguments.Diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionOnlyAllowedOnModuleSubOrFunction), Me.Locations(0)) decoded = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.VisualBasicComClassAttribute) Then If Me.IsGenericType Then arguments.Diagnostics.Add(ERRID.ERR_ComClassOnGeneric, Me.Locations(0)) Else Interlocked.CompareExchange(_comClassData, New ComClassData(attrData), Nothing) End If decoded = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.DefaultEventAttribute) Then If attrData.CommonConstructorArguments.Length = 1 AndAlso attrData.CommonConstructorArguments(0).Kind = TypedConstantKind.Primitive Then Dim eventName = TryCast(attrData.CommonConstructorArguments(0).Value, String) If eventName IsNot Nothing AndAlso eventName.Length > 0 AndAlso Not FindDefaultEvent(eventName) Then arguments.Diagnostics.Add(ERRID.ERR_DefaultEventNotFound1, arguments.AttributeSyntaxOpt.GetLocation(), eventName) End If End If decoded = True End If Case TypeKind.Interface If attrData.IsTargetAttribute(Me, AttributeDescription.CoClassAttribute) Then Debug.Assert(Not attrData.CommonConstructorArguments.IsDefault AndAlso attrData.CommonConstructorArguments.Length = 1) Dim argument As TypedConstant = attrData.CommonConstructorArguments(0) Debug.Assert(argument.Kind = TypedConstantKind.Type) Debug.Assert(argument.Type IsNot Nothing) Debug.Assert(argument.Type.Equals(DeclaringCompilation.GetWellKnownType(WellKnownType.System_Type))) ' Note that 'argument.Value' may be Nothing in which case Roslyn will ' generate an error as if CoClassAttribute attribute was not defined on ' the interface; this behavior matches Dev11, but we should probably ' revise it later Interlocked.CompareExchange(Me._lazyCoClassType, DirectCast(argument.Value, TypeSymbol), DirectCast(ErrorTypeSymbol.UnknownResultType, TypeSymbol)) decoded = True End If Case TypeKind.Module If ContainingSymbol.Kind = SymbolKind.Namespace AndAlso attrData.IsTargetAttribute(Me, AttributeDescription.CaseInsensitiveExtensionAttribute) Then ' Already have an attribute, no need to add another one. SuppressExtensionAttributeSynthesis() decoded = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.VisualBasicComClassAttribute) Then ' Can't apply ComClassAttribute to a Module arguments.Diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_InvalidAttributeUsage2, AttributeDescription.VisualBasicComClassAttribute.Name, Me.Name), Me.Locations(0)) decoded = True End If End Select If Not decoded Then If attrData.IsTargetAttribute(Me, AttributeDescription.DefaultMemberAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasDefaultMemberAttribute = True ' Check that the explicit <DefaultMember(...)> argument matches the default property if any. Dim attributeValue = attrData.DecodeDefaultMemberAttribute() Dim defaultProperty = DefaultPropertyName If Not String.IsNullOrEmpty(defaultProperty) AndAlso Not IdentifierComparison.Equals(defaultProperty, attributeValue) Then arguments.Diagnostics.Add(ERRID.ERR_ConflictDefaultPropertyAttribute, Locations(0), Me) End If ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SerializableAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasSerializableAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ExcludeFromCodeCoverageAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasExcludeFromCodeCoverageAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SpecialNameAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasSpecialNameAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.StructLayoutAttribute) Then Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) Dim defaultAutoLayoutSize = If(Me.TypeKind = TypeKind.Structure, 1, 0) AttributeData.DecodeStructLayoutAttribute(Of CommonTypeWellKnownAttributeData, AttributeSyntax, VisualBasicAttributeData, AttributeLocation)( arguments, Me.DefaultMarshallingCharSet, defaultAutoLayoutSize, MessageProvider.Instance) If Me.IsGenericType Then arguments.Diagnostics.Add(ERRID.ERR_StructLayoutAttributeNotAllowed, arguments.AttributeSyntaxOpt.GetLocation(), Me) End If ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SuppressUnmanagedCodeSecurityAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasSuppressUnmanagedCodeSecurityAttribute = True ElseIf attrData.IsSecurityAttribute(Me.DeclaringCompilation) Then attrData.DecodeSecurityAttribute(Of CommonTypeWellKnownAttributeData)(Me, Me.DeclaringCompilation, arguments) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ClassInterfaceAttribute) Then attrData.DecodeClassInterfaceAttribute(arguments.AttributeSyntaxOpt, arguments.Diagnostics) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.InterfaceTypeAttribute) Then attrData.DecodeInterfaceTypeAttribute(arguments.AttributeSyntaxOpt, arguments.Diagnostics) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.GuidAttribute) Then attrData.DecodeGuidAttribute(arguments.AttributeSyntaxOpt, arguments.Diagnostics) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.WindowsRuntimeImportAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasWindowsRuntimeImportAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SecurityCriticalAttribute) OrElse attrData.IsTargetAttribute(Me, AttributeDescription.SecuritySafeCriticalAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasSecurityCriticalAttributes = True ElseIf _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.Unknown AndAlso attrData.IsTargetAttribute(Me, AttributeDescription.TypeIdentifierAttribute) Then _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.RequiredAttributeAttribute) Then Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) arguments.Diagnostics.Add(ERRID.ERR_CantUseRequiredAttribute, arguments.AttributeSyntaxOpt.GetLocation(), Me) End If End If MyBase.DecodeWellKnownAttribute(arguments) End Sub Friend Overrides ReadOnly Property IsExplicitDefinitionOfNoPiaLocalType As Boolean Get If _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.Unknown Then CheckPresenceOfTypeIdentifierAttribute() If _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.Unknown Then _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.False End If End If Debug.Assert(_lazyIsExplicitDefinitionOfNoPiaLocalType <> ThreeState.Unknown) Return _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.True End Get End Property Private Sub CheckPresenceOfTypeIdentifierAttribute() ' Have we already decoded well-known attributes? If Me.m_lazyCustomAttributesBag?.IsDecodedWellKnownAttributeDataComputed Then Return End If ' We want this function to be as cheap as possible, it is called for every top level type ' and we don't want to bind attributes attached to the declaration unless there is a chance ' that one of them is TypeIdentifier attribute. Dim attributeLists As ImmutableArray(Of SyntaxList(Of AttributeListSyntax)) = GetAttributeDeclarations() For Each list As SyntaxList(Of AttributeListSyntax) In attributeLists Dim sourceFile = ContainingSourceModule.TryGetSourceFile(list.Node.SyntaxTree) For Each attrList As AttributeListSyntax In list For Each attr As AttributeSyntax In attrList.Attributes If (sourceFile.QuickAttributeChecker.CheckAttribute(attr) And QuickAttributes.TypeIdentifier) <> 0 Then ' This attribute syntax might be an application of TypeIdentifierAttribute. ' Let's bind it. ' For simplicity we bind all attributes. GetAttributes() Return End If Next Next Next End Sub Private Function FindDefaultEvent(eventName As String) As Boolean Dim current As NamedTypeSymbol = Me Do For Each member As Symbol In current.GetMembers(eventName) If member.Kind = SymbolKind.Event AndAlso (member.DeclaredAccessibility = Accessibility.Public OrElse member.DeclaredAccessibility = Accessibility.Friend) Then ' We have a match so the default event is valid. Return True End If Next current = current.BaseTypeNoUseSiteDiagnostics Loop While current IsNot Nothing Return False End Function Friend Overrides Sub PostDecodeWellKnownAttributes( boundAttributes As ImmutableArray(Of VisualBasicAttributeData), allAttributeSyntaxNodes As ImmutableArray(Of AttributeSyntax), diagnostics As DiagnosticBag, symbolPart As AttributeLocation, decodedData As WellKnownAttributeData) Debug.Assert(Not boundAttributes.IsDefault) Debug.Assert(Not allAttributeSyntaxNodes.IsDefault) Debug.Assert(boundAttributes.Length = allAttributeSyntaxNodes.Length) Debug.Assert(symbolPart = AttributeLocation.None) ValidateStandardModuleAttribute(diagnostics) MyBase.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData) End Sub Private Sub ValidateStandardModuleAttribute(diagnostics As DiagnosticBag) ' If this type is a VB Module, touch the ctor for MS.VB.Globals.StandardModuleAttribute to ' produce any diagnostics related to that member and type. ' Dev10 reported a special diagnostic ERR_NoStdModuleAttribute if the constructor was missing. ' Roslyn now used the more general use site errors, which also reports diagnostics if the type or the constructor ' is missing. If Me.TypeKind = TypeKind.Module Then Dim useSiteError As DiagnosticInfo = Nothing Binder.ReportUseSiteErrorForSynthesizedAttribute(WellKnownMember.Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor, Me.DeclaringCompilation, Locations(0), diagnostics) End If End Sub Friend NotOverridable Overrides ReadOnly Property IsDirectlyExcludedFromCodeCoverage As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasExcludeFromCodeCoverageAttribute End Get End Property Friend NotOverridable Overrides ReadOnly Property HasSpecialName As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasSpecialNameAttribute End Get End Property Public NotOverridable Overrides ReadOnly Property IsSerializable As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasSerializableAttribute End Get End Property Private Function HasInstanceFields() As Boolean Dim members = Me.GetMembersUnordered() For i = 0 To members.Length - 1 Dim m = members(i) If Not m.IsShared And m.Kind = SymbolKind.Field Then Return True End If Next Return False End Function Friend NotOverridable Overrides ReadOnly Property Layout As TypeLayout Get Dim data = GetDecodedWellKnownAttributeData() If data IsNot Nothing AndAlso data.HasStructLayoutAttribute Then Return data.Layout End If If Me.TypeKind = TypeKind.Structure Then ' CLI spec 22.37.16: ' "A ValueType shall have a non-zero size - either by defining at least one field, or by providing a non-zero ClassSize" ' ' Dev11 compiler sets the value to 1 for structs with no fields and no size specified. ' It does not change the size value if it was explicitly specified to be 0, nor does it report an error. Return New TypeLayout(LayoutKind.Sequential, If(Me.HasInstanceFields(), 0, 1), alignment:=0) End If Return Nothing End Get End Property Friend ReadOnly Property HasStructLayoutAttribute As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasStructLayoutAttribute End Get End Property Friend Overrides ReadOnly Property MarshallingCharSet As CharSet Get Dim data = GetDecodedWellKnownAttributeData() Return If((data IsNot Nothing AndAlso data.HasStructLayoutAttribute), data.MarshallingCharSet, DefaultMarshallingCharSet) End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) Dim compilation = Me.DeclaringCompilation If Not String.IsNullOrEmpty(DefaultPropertyName) AndAlso Not HasDefaultMemberAttribute() Then Dim stringType = GetSpecialType(SpecialType.System_String) ' NOTE: used from emit, so shouldn't have gotten here if there were errors Debug.Assert(stringType.GetUseSiteErrorInfo() Is Nothing) AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Reflection_DefaultMemberAttribute__ctor, ImmutableArray.Create( New TypedConstant(stringType, TypedConstantKind.Primitive, DefaultPropertyName)))) End If If Me.TypeKind = TypeKind.Module Then 'TODO check that there's not a user supplied instance already. This attribute is AllowMultiple:=False. AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor)) End If If _comClassData IsNot Nothing Then If _comClassData.ClassId IsNot Nothing Then AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_InteropServices_GuidAttribute__ctor, ImmutableArray.Create( New TypedConstant(GetSpecialType(SpecialType.System_String), TypedConstantKind.Primitive, _comClassData.ClassId)))) End If AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_InteropServices_ClassInterfaceAttribute__ctorClassInterfaceType, ImmutableArray.Create( New TypedConstant(GetSpecialType(SpecialType.System_Int32), TypedConstantKind.Enum, CInt(ClassInterfaceType.None))))) Dim eventInterface As NamedTypeSymbol = _comClassData.GetSynthesizedEventInterface() If eventInterface IsNot Nothing Then Dim eventInterfaceName As String = eventInterface.Name Dim container1 As NamedTypeSymbol = Me Dim container2 As NamedTypeSymbol = container1.ContainingType While container2 IsNot Nothing eventInterfaceName = container1.Name & "+" & eventInterfaceName container1 = container2 container2 = container1.ContainingType End While eventInterfaceName = container1.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) & "+" & eventInterfaceName AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_InteropServices_ComSourceInterfacesAttribute__ctorString, ImmutableArray.Create( New TypedConstant(GetSpecialType(SpecialType.System_String), TypedConstantKind.Primitive, eventInterfaceName)))) End If End If Dim baseType As NamedTypeSymbol = Me.BaseTypeNoUseSiteDiagnostics If baseType IsNot Nothing Then If baseType.ContainsTupleNames() Then AddSynthesizedAttribute(attributes, compilation.SynthesizeTupleNamesAttribute(baseType)) End If End If End Sub Private Function HasDefaultMemberAttribute() As Boolean Dim attributesBag = GetAttributesBag() Dim wellKnownAttributeData = DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonTypeWellKnownAttributeData) Return (wellKnownAttributeData IsNot Nothing) AndAlso wellKnownAttributeData.HasDefaultMemberAttribute End Function #End Region Friend Function GetOrAddWithEventsOverride(baseProperty As PropertySymbol) As SynthesizedOverridingWithEventsProperty Dim overridesDict = Me._lazyWithEventsOverrides If overridesDict Is Nothing Then Interlocked.CompareExchange(Me._lazyWithEventsOverrides, New ConcurrentDictionary(Of PropertySymbol, SynthesizedOverridingWithEventsProperty), Nothing) overridesDict = Me._lazyWithEventsOverrides End If Dim result As SynthesizedOverridingWithEventsProperty = Nothing If overridesDict.TryGetValue(baseProperty, result) Then Return result Else ' we need to create a lambda here since we need to close over baseProperty ' we will however create a lambda only on a cache miss, hopefully not very often. Return overridesDict.GetOrAdd(baseProperty, Function() Debug.Assert(Not _withEventsOverridesAreFrozen) Return New SynthesizedOverridingWithEventsProperty(baseProperty, Me) End Function) End If End Function Friend NotOverridable Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) EnsureAllHandlesAreBound() Dim overridesDict = Me._lazyWithEventsOverrides If overridesDict IsNot Nothing Then Return overridesDict.Values End If Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)() End Function Private Sub EnsureAllHandlesAreBound() If Not _withEventsOverridesAreFrozen Then For Each member In Me.GetMembersUnordered() If member.Kind = SymbolKind.Method Then Dim notUsed = DirectCast(member, MethodSymbol).HandledEvents End If Next _withEventsOverridesAreFrozen = True End If End Sub Protected Overrides Sub AddEntryPointIfNeeded(membersBuilder As MembersAndInitializersBuilder) If Me.TypeKind = TypeKind.Class AndAlso Not Me.IsGenericType Then Dim mainTypeName As String = DeclaringCompilation.Options.MainTypeName If mainTypeName IsNot Nothing AndAlso IdentifierComparison.EndsWith(mainTypeName, Me.Name) AndAlso IdentifierComparison.Equals(mainTypeName, Me.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)) Then ' Must derive from Windows.Forms.Form Dim formClass As NamedTypeSymbol = DeclaringCompilation.GetWellKnownType(WellKnownType.System_Windows_Forms_Form) If formClass.IsErrorType() OrElse Not Me.IsOrDerivedFrom(formClass, useSiteDiagnostics:=Nothing) Then Return End If Dim entryPointMethodName As String = WellKnownMemberNames.EntryPointMethodName ' If we already have a child named 'Main', do not add a synthetic one. If membersBuilder.Members.ContainsKey(entryPointMethodName) Then Return End If If GetTypeMembersDictionary().ContainsKey(entryPointMethodName) Then Return End If ' We need to have a constructor that can be called without arguments. Dim symbols As ArrayBuilder(Of Symbol) = Nothing Dim haveSuitableConstructor As Boolean = False If membersBuilder.Members.TryGetValue(WellKnownMemberNames.InstanceConstructorName, symbols) Then For Each method As MethodSymbol In symbols If method.MethodKind = MethodKind.Constructor AndAlso method.ParameterCount = 0 Then haveSuitableConstructor = True Exit For End If Next If Not haveSuitableConstructor Then ' Do the second pass to check for optional parameters, etc., it will require binding parameter modifiers and probably types. For Each method As MethodSymbol In symbols If method.MethodKind = MethodKind.Constructor AndAlso method.CanBeCalledWithNoParameters() Then haveSuitableConstructor = True Exit For End If Next End If End If If haveSuitableConstructor Then Dim syntaxRef = SyntaxReferences.First() ' use arbitrary part Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, syntaxRef.SyntaxTree, Me) Dim entryPoint As New SynthesizedMainTypeEntryPoint(syntaxRef.GetVisualBasicSyntax(), Me) AddMember(entryPoint, binder, membersBuilder, omitDiagnostics:=True) End If End If End If End Sub End Class End Namespace
OmarTawfik/roslyn
src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol.vb
Visual Basic
apache-2.0
138,941
' 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.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class XmlCDataHighlighter Inherits AbstractKeywordHighlighter(Of XmlCDataSectionSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub addHighlights(xmlComment As XmlCDataSectionSyntax, highlights As List(Of TextSpan), cancellationToken As CancellationToken) With xmlComment If Not .ContainsDiagnostics AndAlso Not .HasAncestor(Of DocumentationCommentTriviaSyntax)() Then highlights.Add(.BeginCDataToken.Span) highlights.Add(.EndCDataToken.Span) End If End With End Sub End Class End Namespace
physhi/roslyn
src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/XmlCDataHighlighter.vb
Visual Basic
apache-2.0
1,366
' 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 Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax Partial Public Class TypeStatementSyntax Public ReadOnly Property Arity As Integer Get Return If(Me.TypeParameterList Is Nothing, 0, Me.TypeParameterList.Parameters.Count) End Get End Property ''' <summary> ''' Returns the keyword indicating the kind of declaration being made: "Class", "Structure", "Module", "Interface", etc. ''' </summary> Public MustOverride ReadOnly Property DeclarationKeyword As SyntaxToken ''' <summary> ''' Returns a copy of this <see cref="TypeStatementSyntax"/> with the <see cref="DeclarationKeyword"/> property changed to the ''' specified value. Returns this instance if the specified value is the same as the current value. ''' </summary> Public MustOverride Function WithDeclarationKeyword(keyword As SyntaxToken) As TypeStatementSyntax <EditorBrowsable(EditorBrowsableState.Never)> <Obsolete("This member is obsolete. Use DeclarationKeyword or a more specific property (e.g. ClassKeyword) instead.", True)> Public ReadOnly Property Keyword As SyntaxToken Get Return DeclarationKeyword End Get End Property <EditorBrowsable(EditorBrowsableState.Never)> <Obsolete("This member is obsolete. Use DeclarationKeyword or a more specific property (e.g. WithClassKeyword) instead.", True)> Public Function WithKeyword(keyword As SyntaxToken) As TypeStatementSyntax Return WithDeclarationKeyword(keyword) End Function End Class Partial Public Class ModuleStatementSyntax Public Overrides ReadOnly Property DeclarationKeyword As SyntaxToken Get Return ModuleKeyword End Get End Property Public Overrides Function WithDeclarationKeyword(keyword As SyntaxToken) As TypeStatementSyntax Return WithModuleKeyword(keyword) End Function <EditorBrowsable(EditorBrowsableState.Never)> <Obsolete("This member is obsolete.", True)> Public Shadows ReadOnly Property Keyword As SyntaxToken Get Return DeclarationKeyword End Get End Property <EditorBrowsable(EditorBrowsableState.Never)> <Obsolete("This member is obsolete.", True)> Public Shadows Function WithKeyword(keyword As SyntaxToken) As ModuleStatementSyntax Return WithModuleKeyword(keyword) End Function End Class Partial Public Class StructureStatementSyntax Public Overrides ReadOnly Property DeclarationKeyword As SyntaxToken Get Return StructureKeyword End Get End Property Public Overrides Function WithDeclarationKeyword(keyword As SyntaxToken) As TypeStatementSyntax Return WithStructureKeyword(keyword) End Function <EditorBrowsable(EditorBrowsableState.Never)> <Obsolete("This member is obsolete.", True)> Public Shadows ReadOnly Property Keyword As SyntaxToken Get Return DeclarationKeyword End Get End Property <EditorBrowsable(EditorBrowsableState.Never)> <Obsolete("This member is obsolete.", True)> Public Shadows Function WithKeyword(keyword As SyntaxToken) As StructureStatementSyntax Return WithStructureKeyword(keyword) End Function End Class Partial Public Class ClassStatementSyntax Public Overrides ReadOnly Property DeclarationKeyword As SyntaxToken Get Return ClassKeyword End Get End Property Public Overrides Function WithDeclarationKeyword(keyword As SyntaxToken) As TypeStatementSyntax Return WithClassKeyword(keyword) End Function <EditorBrowsable(EditorBrowsableState.Never)> <Obsolete("This member is obsolete.", True)> Public Shadows ReadOnly Property Keyword As SyntaxToken Get Return DeclarationKeyword End Get End Property <EditorBrowsable(EditorBrowsableState.Never)> <Obsolete("This member is obsolete.", True)> Public Shadows Function WithKeyword(keyword As SyntaxToken) As ClassStatementSyntax Return WithClassKeyword(keyword) End Function End Class Partial Public Class InterfaceStatementSyntax Public Overrides ReadOnly Property DeclarationKeyword As SyntaxToken Get Return InterfaceKeyword End Get End Property Public Overrides Function WithDeclarationKeyword(keyword As SyntaxToken) As TypeStatementSyntax Return WithInterfaceKeyword(keyword) End Function <EditorBrowsable(EditorBrowsableState.Never)> <Obsolete("This member is obsolete.", True)> Public Shadows ReadOnly Property Keyword As SyntaxToken Get Return DeclarationKeyword End Get End Property <EditorBrowsable(EditorBrowsableState.Never)> <Obsolete("This member is obsolete.", True)> Public Shadows Function WithKeyword(keyword As SyntaxToken) As InterfaceStatementSyntax Return WithInterfaceKeyword(keyword) End Function End Class End Namespace
robinsedlaczek/roslyn
src/Compilers/VisualBasic/Portable/Syntax/TypeStatementSyntax.vb
Visual Basic
apache-2.0
5,682
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenUnstructuredErrorHandling Inherits BasicTestBase <Fact()> Public Sub Erl_Property_SimpleBehaviourMultipleLabels() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main Try 10: Err.Raise(5) Console.writeline("Incorrect Code Path") 20: Console.writeline("No Error") Catch ex as exception Console.writeline(err.Number) Console.writeline(err.erl) End Try End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[5 10 ]]>) End Sub <Fact()> Public Sub Erl_Property_NestedTryCatch() 'The ERL is correct even though the error occurred within a nested try catch construct Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main Try 10: Try Err.Raise(5) Console.writeline("Incorrect Code Path") Catch ex as exception Console.writeline("Inner" & err.Number) Console.writeline(err.erl) End Try 20: Console.writeline("No Error") Catch ex as exception Console.writeline("Outer" & err.Number) Console.writeline(err.erl) End Try End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[Inner5 10 No Error]]>) End Sub <Fact()> Public Sub Erl_Property_NestedTryCatchNoPropagateToOuter() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main Try 10: Try 11: Err.Raise(5) Console.writeline("Incorrect Code Path") Catch ex as exception Console.writeline("Inner" & err.Number) Console.writeline(err.erl) End Try 20: Console.writeline("No Error") Catch ex as exception Console.writeline("Outer" & err.Number) Console.writeline(err.erl) End Try End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[Inner5 11 No Error]]>) End Sub <Fact()> Public Sub Erl_Property_DuplicateLabels() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main Try 10: Try 10: Err.Raise(5) Catch ex as exception End Try 20: Console.writeline("No Error") Catch ex as exception Console.writeline("Outer" & err.Number) Console.writeline(err.erl) End Try End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_MultiplyDefined1, "10").WithArguments("10")) End Sub <Fact()> Public Sub Erl_Property_NonSequentialLineNumbers() 'The line numbers do not need to be sequential Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main 10: Try 1: Err.Raise(5) Console.writeline("Incorrect Code Path") 20: Console.writeline("No Error") Catch ex as exception Console.writeline("Outer" & err.Number) Console.writeline(err.erl) End Try End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[Outer5 1 ]]>) End Sub <Fact()> Public Sub Erl_Property_LabelIntegerMaxValueValue() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main 1: Try 2147483647: Err.Raise(5) Console.writeline("Incorrect Code Path") 20: Console.writeline("No Error") Catch ex as exception Console.writeline("Outer" & err.Number) Console.writeline(err.erl) End Try End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[Outer5 2147483647 ]]>) End Sub <Fact()> Public Sub Erl_Property_LabelGreaterThanIntegerMaxValueValue() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main 1: Try 2147483648: Err.Raise(5) Console.writeline("Incorrect Code Path") 20: Console.writeline("No Error") Catch ex as exception Console.writeline("Outer" & err.Number) Console.writeline(err.erl) End Try End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[Outer5 0 ]]>) End Sub <Fact()> Public Sub Erl_Property_NonNumericLabels() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main Blah: Try Foo: Err.Raise(5) Console.writeline("Incorrect Code Path") Goo: Console.writeline("No Error") Catch ex as exception Console.writeline("Outer" & err.Number) Console.writeline(err.erl) End Try End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[Outer5 0 ]]>) End Sub <Fact()> Public Sub Erl_Property_NoLabels() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main Try Err.Raise(5) Console.writeline("Incorrect Code Path") Console.writeline("No Error") Catch ex as exception Console.writeline("Outer" & err.Number) Console.writeline(err.erl) End Try End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[Outer5 0 ]]>) End Sub <Fact()> Public Sub Erl_Property_ThrowExceptionInsteadOfErrorRaiseLambdaInvocation() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main Try 10: Dim x = SUB() Throw New exception ("Exception Instead Of Error") End Sub 20: x() 30: Console.writeline("No Error") Catch ex as exception Console.writeline("Outer" & err.Number) Console.writeline(err.erl) End Try End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[Outer5 20 ]]>) End Sub <Fact()> Public Sub Erl_Property_NestedLambdasAndLabelInLambdaSameLabelInCallerAndLambda() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main Try 10: Dim x = Sub() throw new exception ("Exception Instead Of Error") Console.writeline("Incorrect Code Path") End Sub Dim y = SUB() 30: x() Console.writeline("Incorrect Code Path") End Sub 20: y() 30: Console.writeline("Incorrect Code Path") Console.writeline("No Error") Catch ex as exception Console.writeline("Outer" & err.Number) Console.writeline(err.erl) End Try End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[Outer5 20 ]]>) End Sub <Fact()> Public Sub Erl_Property_OnErrorRetainsValueUntilCleared() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main 1: On error resume next Throw New Exception("test") 2: Console.writeline(Err.Number) Console.writeline(Err.Erl) 3: Console.writeline("Finish") Console.writeline(Err.Erl) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[5 1 Finish 1 ]]>) End Sub <Fact()> Public Sub Erl_Property_OnErrorRetainsValueUntilClearedWithClear() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main 1: On error resume next Throw New Exception("test") 2: Console.writeline(Err.Number) Console.writeline(Err.Erl) Err.Clear 3: Console.writeline("Finish") Console.writeline(Err.Erl) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[5 1 Finish 0 ]]>) End Sub <Fact()> Public Sub Erl_Property_UnhandledErrorDontBubbleUp() 'There is no label in main and the label from SubMethod is not bubbled up. Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main Try SubMethod() Catch Console.writeline("Finish") Console.writeline(Err.Erl) End Try End Sub Sub SubMethod 1: On error goto -1 Throw New Exception("test") 2: Console.writeline(Err.Number) Console.writeline(Err.Erl) Err.Clear End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[Finish 0 ]]>) End Sub <Fact()> Public Sub Erl_Property_InClassAndStructureTypes() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main Dim obj_c as new c1 obj_c.Method obj_C.p1= 1 Dim obj_s as new s1 obj_s.Method dim z= obj_s.P1 End Sub End Module Public Class C1 Sub Method() 1: On Error Resume Next Err.Raise(2) 2: Console.Writeline(Err.Erl) Err.Clear 3: Console.Writeline(Err.Erl) 'This should be 0 Err.Raise(2) Console.Writeline(Err.Erl) 'This should be 3 4: Console.Writeline(Err.Erl) 'This should still be 3 End Sub Public Property P1 as Integer Get return 1 End Get Set (v as Integer) 21: On Error Resume Next Err.Raise(2) 22: Console.Writeline(Err.Erl) Err.Clear 23: Console.Writeline(Err.Erl) 'This should be 0 Err.Raise(2) Console.Writeline(Err.Erl) 'This should be 3 24: Console.Writeline(Err.Erl) 'This should still be 3 End Set End Property End Class Public Structure S1 Shared x as integer =1 Sub Method() 11: On Error Resume Next Err.Raise(2) 12: Console.Writeline(Err.Erl) Err.Clear 13: Console.Writeline(Err.Erl) 'This should be 0 Err.Raise(2) Console.Writeline(Err.Erl) 'This should be 3 14: Console.Writeline(Err.Erl) 'This should still be 3 End Sub Public Readonly Property P1 Get 21: On Error Resume Next Err.Raise(2) 22: Console.Writeline(Err.Erl) Err.Clear 23: Console.Writeline(Err.Erl) 'This should be 0 Err.Raise(2) Console.Writeline(Err.Erl) 'This should be 3 24: Console.Writeline(Err.Erl) 'This should still be 3 End Get End Property End Structure ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[1 0 3 3 21 0 23 23 11 0 13 13 21 0 23 23 ]]>) End Sub <Fact()> Public Sub Erl_Property_InGenericType() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main Dim obj_c as new c1(of integer) obj_c.Method(of String) End Sub End Module Public Class C1(of t) Sub Method(of u) On error resume next 10: Err.Raise(3) 20: Console.Writeline(Err.erl) 30: Console.Writeline(Err.erl) err.Clear 40: Console.Writeline(Err.erl) End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[10 10 0 ]]>) End Sub <Fact()> Public Sub Erl_Property_InGenericTypeSharedMethod() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main c1(of integer).Method(of String) End Sub End Module Public Class C1(of t) Shared Sub Method(of u) On error resume next 10: Err.Raise(3) 20: Console.Writeline(Err.erl) 30: Console.Writeline(Err.erl) err.Clear 40: Console.Writeline(Err.erl) End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[10 10 0 ]]>) End Sub <Fact()> Public Sub Erl_Property_InheritenceScenario() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main Dim o as new c1 o.a Dim o2 as new derived o2.a Dim o3 as C1 = new derived o3.a End Sub End Module Public Class C1 overridable Sub A() 10: On error Resume next Err.Raise(10) 20: Console.Writeline(Err.Erl) End Sub End Class Public Class Derived : Inherits c1 Overrides Sub A() 21: On error Resume next Err.Raise(10) 22: Console.Writeline(Err.Erl) End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[10 21 21 ]]>) End Sub <Fact()> Public Sub Erl_Property_CallingMethodThroughInterface() 'Verify No problems with erl because of calling using interface Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main Dim i as ifoo = new c1 i.Testmethod End Sub End Module Public Class C1 : Implements Ifoo Sub T1 implements Ifoo.Testmethod On error resume next 10: Err.Raise(3) 20: Console.Writeline(Err.erl) 30: Console.Writeline(Err.erl) err.Clear 40: Console.Writeline(Err.erl) End Sub End Class Interface Ifoo Sub Testmethod() End Interface ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[10 10 0 ]]>) End Sub <Fact()> Public Sub Erl_Property_CallingMethodWithDelegate() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Public Delegate Sub DelSub() Sub main On error resume next 1: Dim d as DelSub d = addressof TestMethod d() 2: Console.Writeline(Err.Erl) End Sub Sub TestMethod() 21: On error Resume next Err.Raise(10) 22: Console.Writeline(Err.Erl) Err.Clear 23: Console.Writeline(Err.Erl) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[21 0 0 ]]>) End Sub <Fact()> Public Sub Erl_Property_CollectionInitializer() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main On error resume next 1: Dim d as new System.Collections.Generic.list(of C1) From {new c1 with {.p1=1}} 2: Console.Writeline(Err.Erl) 'This should be 0 End Sub End Module Class C1 Public Property P1 as integer Get Return 1 End Get Set( v as integer) 21: On error Resume next Err.Raise(10) 22: Console.Writeline(Err.Erl) Err.Clear 23: Console.Writeline(Err.Erl) End Set End Property End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[21 0 0 ]]>) End Sub <Fact()> Public Sub Erl_Property_MultipleHandlers() ' Known behavior with multiple handlers causing bogus out of memory exception ' Won't Fix the VB Runtime in Roslyn but captured the current behavior Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub Foo() On Error Resume Next 1: Err.Raise(5) 2: Console.WriteLine(Err.Erl) On Error GoTo 0 On Error GoTo 3 Err.Raise(6) 3: Console.WriteLine(Err.Erl) On Error GoTo 0 On Error GoTo 4 Err.Raise(7) 4: Console.WriteLine(Err.Erl) Console.WriteLine("Finish") End Sub Sub main() Try Foo() Catch ex As OutOfMemoryException Console.WriteLine("Expected Exception Occurred") End Try End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[1 2 Expected Exception Occurred ]]>) End Sub <Fact()> Public Sub Erl_Property_MultipleHandlersWithResume() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main On error goto Errhandler 1: Err.Raise(5) 2: On error Goto 0 On error Goto SecondHandler 3: Err.Raise(5) Exit Sub ErrHandler: Console.Writeline(Err.Erl) resume next exit sub SecondHandler: Console.Writeline(Err.Erl) resume next exit sub End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[1 3 ]]>) End Sub <Fact()> Public Sub Erl_Property_InvalidNumericLabel() 'More a test of Invalid Label but as the label is used for ERL I wanted to make sure that this didnt compile Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main On error Resume next -1:'Invalid Label Console.Writeline("Invalid Label") 0: 1: Err.Raise(5) Console.Writeline(Err.Erl) 2: On error Goto 0 On error Goto 3: Err.Raise(6) Console.Writeline(Err.Erl) 3: On error Goto 3: Err.Raise(7) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_Syntax, "-")) End Sub <Fact()> Public Sub Erl_Property_NoHandlerOnInner_WithDuplicateLabelInDifferentMethod() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main Try 1: Foo Exit Sub Catch 2: Console.Writeline(Err.Erl) End Try End Sub Sub Foo() 2: Err.raise(4) Console.Writeline("Incorrect Code Path") End Sub End Module]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[1 ]]>) End Sub <Fact()> Public Sub Erl_Property_TypeCharsOnLabels() 'More a test of Invalid Label but as the label is used for ERL I wanted to make sure that this didnt compile 'Using type characters which would be valid for numerics Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Module Module1 Sub main Try 1L: Foo Exit Sub Catch 2S: Console.Writeline(Err.Erl) End Try End Sub Sub Foo() Try 1%: Err.Raise(1) Exit Sub Catch Console.Writeline(Err.Erl) End Try End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_Syntax, "1L"), Diagnostic(ERRID.ERR_Syntax, "2S"), Diagnostic(ERRID.ERR_Syntax, "1%")) End Sub <Fact()> Public Sub Erl_Property_WithinAsyncMethods() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Imports System.Threading Imports System.Threading.Tasks Module Module1 Dim tcs As AutoResetEvent Sub main() 1: Async_Caller() Console.WriteLine(Err.Erl) End Sub Public async Sub Async_Caller() 11: Try tcs = New AutoResetEvent(False) Await Foob() tcs.WaitOne() Catch ex As Exception Console.WriteLine(Err.Erl) Throw End Try End Sub Async Function Foob() As task Try 21: Dim i = Await Test1() Catch ex As Exception Console.WriteLine(Err.Erl) Finally Console.WriteLine(Err.Erl) tcs.Set() End Try End Function Async Function Test1() As Task(Of Integer) 31: Err.Raise(5) Await Task.Delay(10) Return 1 End Function End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[21 0 0 ]]>) End Sub <Fact()> Public Sub Erl_Property_WithinAsyncMethods_Bug654704() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports Microsoft.VisualBasic Imports System.Threading Imports System.Threading.Tasks Module Module1 Dim tcs As AutoResetEvent Sub main() 1: Async_Caller() Console.WriteLine(Err.Erl) End Sub Public async Sub Async_Caller() 11: Try tcs = New AutoResetEvent(False) Await Foob() tcs.WaitOne() Catch ex As Exception Console.WriteLine(Err.Erl) Throw End Try End Sub Async Function Foob() As task Try 21: Dim i = Await Test1() Catch ex As Exception Console.WriteLine(Err.Erl) Finally Console.WriteLine(Err.Erl) tcs.Set() End Try End Function Async Function Test1() As Task(Of Integer) 31: Err.Raise(5) Return 1 End Function End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe) CompileAndVerify(compilation) End Sub <Fact()> Public Sub Erl_Property_WithinIteratorMethods() 'This is having try catches at each level and ensuring the Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Imports Microsoft.VisualBasic Module Module1 Sub main() 1: Try IteratorMethod() Catch Console.writeline("Exception") Console.writeline(Err.erl) End Try 'Normal Try NormalMethod() Catch Console.writeline("Exception") Console.writeline(Err.erl) End Try End Sub Public Sub NormalMethod() 110: 111: Try For Each i In abcdef() Next Catch Console.writeline("Exception") Console.WriteLine(Err.Erl) Throw End Try End Sub Function abcdef() As Integer() 120: 121: Try Err.Raise(5) Return {1, 2, 3} Catch Console.writeline("Exception") Console.WriteLine(Err.Erl) Throw End Try End Function Public Sub IteratorMethod() 10: 11: Try Dim x As New Scenario1 Dim index As Integer = 0 For Each i In x index += 1 Next Catch Console.writeline("Exception") Console.WriteLine(Err.Erl) Throw End Try End Sub End Module Public Class Scenario1 Implements IEnumerable(Of Integer) Public Iterator Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of Integer) Implements System.Collections.Generic.IEnumerable(Of Integer).GetEnumerator 20: 21: Try Throw New Exception("Test") Yield 10 Catch Console.writeline("Exception") Console.WriteLine(Err.Erl) Throw End Try 220: End Function Public Iterator Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator 29: 22: Try Throw New Exception("Test2") Yield 10 Catch Console.writeline("Exception") Console.WriteLine(Err.Erl) Throw End Try 30: End Function End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[Exception 21 Exception 11 Exception 1 Exception 121 Exception 111 Exception 1]]>) End Sub <Fact()> Public Sub Erl_Property_With_VBCore() 'Error Object Doesn't exist for VBCore - so this should generate correct diagnostics Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub main Try 10: Err.Raise(5) Console.writeline("Incorrect Code Path") 20: Console.writeline("No Error") Catch ex as exception Console.writeline(err.Number) Console.writeline(err.erl) End Try End Sub End Module ]]> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithReferences(source, references:={MscorlibRef, SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)).VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotDeclared1, "Err").WithArguments("Err"), Diagnostic(ERRID.ERR_NameNotDeclared1, "err").WithArguments("err"), Diagnostic(ERRID.ERR_NameNotDeclared1, "err").WithArguments("err")) End Sub <Fact()> Public Sub ERL_Property_CodeGenVerify() 'Simple Verification of IL to determine that Labels and types are as expected CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports Microsoft.VisualBasic Module Module1 Sub Main Try 10: Err.Raise(5) Console.writeline("Incorrect Code Path") 20: Console.writeline("No Error") Catch ex as exception Console.writeline(err.Number) Console.writeline(err.erl) End Try End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[5 10]]>). VerifyIL("Module1.Main", <![CDATA[{ // Code size 89 (0x59) .maxstack 6 .locals init (Integer V_0, System.Exception V_1) //ex .try { IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: call "Function Microsoft.VisualBasic.Information.Err() As Microsoft.VisualBasic.ErrObject" IL_0008: ldc.i4.5 IL_0009: ldnull IL_000a: ldnull IL_000b: ldnull IL_000c: ldnull IL_000d: callvirt "Sub Microsoft.VisualBasic.ErrObject.Raise(Integer, Object, Object, Object, Object)" IL_0012: ldstr "Incorrect Code Path" IL_0017: call "Sub System.Console.WriteLine(String)" IL_001c: ldc.i4.s 20 IL_001e: stloc.0 IL_001f: ldstr "No Error" IL_0024: call "Sub System.Console.WriteLine(String)" IL_0029: leave.s IL_0058 } catch System.Exception { IL_002b: dup IL_002c: ldloc.0 IL_002d: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception, Integer)" IL_0032: stloc.1 IL_0033: call "Function Microsoft.VisualBasic.Information.Err() As Microsoft.VisualBasic.ErrObject" IL_0038: callvirt "Function Microsoft.VisualBasic.ErrObject.get_Number() As Integer" IL_003d: call "Sub System.Console.WriteLine(Integer)" IL_0042: call "Function Microsoft.VisualBasic.Information.Err() As Microsoft.VisualBasic.ErrObject" IL_0047: callvirt "Function Microsoft.VisualBasic.ErrObject.get_Erl() As Integer" IL_004c: call "Sub System.Console.WriteLine(Integer)" IL_0051: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_0056: leave.s IL_0058 } IL_0058: ret } ]]>) End Sub End Class End Namespace
droyad/roslyn
src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenUnstructuredErrorHandling.vb
Visual Basic
apache-2.0
33,478
' 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.Shell.Interop Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic Friend Class VisualBasicProjectCodeModel Inherits AbstractProjectCodeModel Private ReadOnly _project As VisualBasicProjectShimWithServices Public Sub New(project As VisualBasicProjectShimWithServices, visualStudioWorkspace As VisualStudioWorkspace, serviceProvider As IServiceProvider) MyBase.New(project, visualStudioWorkspace, serviceProvider) Me._project = project End Sub Friend Overrides Function CanCreateFileCodeModelThroughProject(fileName As String) As Boolean Return _project.GetCurrentDocumentFromPath(fileName) IsNot Nothing End Function Friend Overrides Function CreateFileCodeModelThroughProject(fileName As String) As Object ' In the Dev11 VB code base, FileCodeModels were created eagerly when a VB SourceFile was created. ' In Roslyn, we'll take the same lazy approach that the Dev11 C# language service does. ' ' Essentially, the C# project system has two methods that the C# language service calls to ask the ' project system to create a FileCodeModel for a specific file name: ' ' * HRESULT CCSharpBuildMgrSite::CanCreateFileCodeModel(PCWSTR pszFileName, BOOL *pRetVal); ' * HRESULT CCSharpBuildMgrSite::CreateFileCodeModel(PCWSTR pszFileName, REFIID riid, void **ppObj)' ' ' If the project system can create a FileCodeModel it calls back into ICSharpProjectSite::CreateFileCodeModel ' with the correct "parent" object. ' ' Because the VB project system lacks these hooks, we simulate the same operations that those hooks perform. Dim document = _project.GetCurrentDocumentFromPath(fileName) If document Is Nothing Then Throw New ArgumentException(NameOf(fileName)) End If Dim itemId = document.GetItemId() If itemId = VSConstants.VSITEMID.Nil Then Throw New ArgumentException(NameOf(fileName)) Return Nothing End If Dim pvar As Object = Nothing If ErrorHandler.Failed(_project.Hierarchy.GetProperty(itemId, __VSHPROPID.VSHPROPID_ExtObject, pvar)) Then Throw New ArgumentException(NameOf(fileName)) End If Dim projectItem = TryCast(pvar, EnvDTE.ProjectItem) If projectItem Is Nothing Then Throw New ArgumentException(NameOf(fileName)) End If Dim fileCodeModel As EnvDTE.FileCodeModel = Nothing If ErrorHandler.Failed(_project.CreateFileCodeModel(projectItem.ContainingProject, projectItem, fileCodeModel)) Then Throw New ArgumentException(NameOf(fileName)) End If Return fileCodeModel End Function End Class End Namespace
MatthieuMEZIL/roslyn
src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicProjectCodeModel.vb
Visual Basic
apache-2.0
3,330
Option Infer On 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 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) Dim statusBarVisible = application.StatusBarVisible 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.Application.StatusBarVisible.vb
Visual Basic
mit
898
'------------------------------------------------------------------------------ ' <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("TestHarness.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
kiebor/OfficePlant
TestHarness/My Project/Resources.Designer.vb
Visual Basic
mit
2,778
Namespace Controls <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class PEBoolean Inherits System.Windows.Forms.UserControl 'UserControl 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.TableLayoutPanel1 = New System.Windows.Forms.TableLayoutPanel() Me.lblName = New DevComponents.DotNetBar.LabelX() Me.sbValue = New DevComponents.DotNetBar.Controls.SwitchButton() Me.TableLayoutPanel1.SuspendLayout() Me.SuspendLayout() ' 'TableLayoutPanel1 ' Me.TableLayoutPanel1.ColumnCount = 3 Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 125.0!)) Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 5.0!)) Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100.0!)) Me.TableLayoutPanel1.Controls.Add(Me.lblName, 0, 0) Me.TableLayoutPanel1.Controls.Add(Me.sbValue, 2, 0) Me.TableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill Me.TableLayoutPanel1.Location = New System.Drawing.Point(0, 0) Me.TableLayoutPanel1.Margin = New System.Windows.Forms.Padding(0) Me.TableLayoutPanel1.Name = "TableLayoutPanel1" Me.TableLayoutPanel1.RowCount = 1 Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100.0!)) Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!)) Me.TableLayoutPanel1.Size = New System.Drawing.Size(250, 23) Me.TableLayoutPanel1.TabIndex = 0 ' 'lblName ' ' ' ' Me.lblName.BackgroundStyle.CornerType = DevComponents.DotNetBar.eCornerType.Square Me.lblName.Dock = System.Windows.Forms.DockStyle.Fill Me.lblName.Location = New System.Drawing.Point(0, 0) Me.lblName.Margin = New System.Windows.Forms.Padding(0) Me.lblName.Name = "lblName" Me.lblName.Size = New System.Drawing.Size(125, 23) Me.lblName.TabIndex = 0 Me.lblName.Text = "LabelX1" ' 'sbValue ' ' ' ' Me.sbValue.BackgroundStyle.CornerType = DevComponents.DotNetBar.eCornerType.Square Me.sbValue.Dock = System.Windows.Forms.DockStyle.Fill Me.sbValue.Location = New System.Drawing.Point(130, 0) Me.sbValue.Margin = New System.Windows.Forms.Padding(0) Me.sbValue.Name = "sbValue" Me.sbValue.OffBackColor = System.Drawing.Color.Red Me.sbValue.OffText = "No" Me.sbValue.OffTextColor = System.Drawing.Color.White Me.sbValue.OnBackColor = System.Drawing.Color.Lime Me.sbValue.OnText = "Yes" Me.sbValue.Size = New System.Drawing.Size(120, 23) Me.sbValue.Style = DevComponents.DotNetBar.eDotNetBarStyle.StyleManagerControlled Me.sbValue.TabIndex = 1 ' 'PEBoolean ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.Controls.Add(Me.TableLayoutPanel1) Me.Margin = New System.Windows.Forms.Padding(0) Me.Name = "PEBoolean" Me.Size = New System.Drawing.Size(250, 23) Me.TableLayoutPanel1.ResumeLayout(False) Me.ResumeLayout(False) End Sub Private WithEvents TableLayoutPanel1 As System.Windows.Forms.TableLayoutPanel Private WithEvents lblName As DevComponents.DotNetBar.LabelX Private WithEvents sbValue As DevComponents.DotNetBar.Controls.SwitchButton End Class End Namespace
nublet/APRBase
APRBase/Controls/PropertyEditor/PEBoolean.Designer.vb
Visual Basic
mit
4,883
Partial Public Class Page1 Inherits PhoneApplicationPage Public Sub New() InitializeComponent() End Sub End Class
RaviChimmalgi/WCF-SOAP
TimeClockWP7/TimeClockWP7/Page1.xaml.vb
Visual Basic
apache-2.0
138
Imports BVSoftware.BVC5.Core Partial Class BVModules_Controls_EmailAddressEntry Inherits System.Web.UI.UserControl Private _tabIndex As Integer = -1 Public Property TabIndex() As Integer Get Return _tabIndex End Get Set(ByVal value As Integer) _tabIndex = value End Set End Property Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If SessionManager.IsUserAuthenticated Then Me.Visible = False Else Me.Visible = True If WebAppSettings.ForceEmailAddressOnAnonymousCheckout Then EmailAddressRequiredFieldValidator.Enabled = True Else EmailAddressRequiredFieldValidator.Enabled = False End If If Me.TabIndex <> -1 Then EmailTextBox.TabIndex = Me.TabIndex End If End If End Sub Public Function GetUserEmail() As String Return Me.EmailTextBox.Text End Function End Class
ajaydex/Scopelist_2015
BVModules/Controls/EmailAddressEntry.ascx.vb
Visual Basic
apache-2.0
1,066
' 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.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ' Binding of conversion operators is implemented in this part. Partial Friend Class Binder Private Function BindCastExpression( node As CastExpressionSyntax, diagnostics As DiagnosticBag ) As BoundExpression Dim result As BoundExpression Select Case node.Keyword.Kind Case SyntaxKind.CTypeKeyword result = BindCTypeExpression(node, diagnostics) Case SyntaxKind.DirectCastKeyword result = BindDirectCastExpression(node, diagnostics) Case SyntaxKind.TryCastKeyword result = BindTryCastExpression(node, diagnostics) Case Else Throw ExceptionUtilities.UnexpectedValue(node.Keyword.Kind) End Select Return result End Function Private Function BindCTypeExpression( node As CastExpressionSyntax, diagnostics As DiagnosticBag ) As BoundExpression Debug.Assert(node.Keyword.Kind = SyntaxKind.CTypeKeyword) Dim argument = BindValue(node.Expression, diagnostics) Dim targetType = BindTypeSyntax(node.Type, diagnostics) Return ApplyConversion(node, targetType, argument, isExplicit:=True, diagnostics) End Function Private Function BindDirectCastExpression( node As CastExpressionSyntax, diagnostics As DiagnosticBag ) As BoundExpression Debug.Assert(node.Keyword.Kind = SyntaxKind.DirectCastKeyword) Dim argument = BindValue(node.Expression, diagnostics) Dim targetType = BindTypeSyntax(node.Type, diagnostics) Return ApplyDirectCastConversion(node, argument, targetType, diagnostics) End Function Private Function ApplyDirectCastConversion( node As SyntaxNode, argument As BoundExpression, targetType As TypeSymbol, diagnostics As DiagnosticBag ) As BoundExpression Debug.Assert(argument.IsValue) ' Deal with erroneous arguments If (argument.HasErrors OrElse targetType.IsErrorType) Then argument = MakeRValue(argument, diagnostics) Return New BoundDirectCast(node, argument, conversionKind:=Nothing, type:=targetType, hasErrors:=True) End If ' Classify conversion Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Dim conv As ConversionKind = Conversions.ClassifyDirectCastConversion(argument, targetType, Me, useSiteDiagnostics) If diagnostics.Add(node, useSiteDiagnostics) Then ' Suppress any additional diagnostics diagnostics = New DiagnosticBag() End If If ReclassifyExpression(argument, SyntaxKind.DirectCastKeyword, node, conv, True, targetType, diagnostics) Then If argument.Syntax IsNot node Then ' If its an explicit conversion, we must have a bound node that corresponds to that syntax node for GetSemanticInfo. ' Insert an identity conversion if necessary. Debug.Assert(argument.Kind <> BoundKind.DirectCast, "Associated wrong node with conversion?") argument = New BoundDirectCast(node, argument, ConversionKind.Identity, targetType) End If Return argument Else argument = MakeRValue(argument, diagnostics) End If If argument.HasErrors Then Return New BoundDirectCast(node, argument, conv, targetType, hasErrors:=True) End If Dim sourceType = argument.Type If sourceType IsNot Nothing AndAlso sourceType.IsErrorType() Then Return New BoundDirectCast(node, argument, conv, targetType, hasErrors:=True) End If Debug.Assert(argument.IsNothingLiteral() OrElse (sourceType IsNot Nothing AndAlso Not sourceType.IsErrorType())) ' Check for special error conditions If Conversions.NoConversion(conv) Then If sourceType.IsValueType AndAlso sourceType.IsRestrictedType() AndAlso (targetType.IsObjectType() OrElse targetType.SpecialType = SpecialType.System_ValueType) Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_RestrictedConversion1, sourceType) Return New BoundDirectCast(node, argument, conv, targetType, hasErrors:=True) End If End If WarnOnNarrowingConversionBetweenSealedClassAndAnInterface(conv, argument.Syntax, sourceType, targetType, diagnostics) If Conversions.NoConversion(conv) Then ReportNoConversionError(argument.Syntax, sourceType, targetType, diagnostics) Return New BoundDirectCast(node, argument, conv, targetType, hasErrors:=True) End If If Conversions.IsIdentityConversion(conv) Then If targetType.IsFloatingType() Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_IdentityDirectCastForFloat) ElseIf targetType.IsValueType Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.WRN_ObsoleteIdentityDirectCastForValueType) End If End If Dim integerOverflow As Boolean = False Dim constantResult = Conversions.TryFoldConstantConversion( argument, targetType, integerOverflow) If constantResult IsNot Nothing Then Debug.Assert(Conversions.IsIdentityConversion(conv) OrElse conv = ConversionKind.WideningNothingLiteral OrElse sourceType.GetEnumUnderlyingTypeOrSelf().IsSameTypeIgnoringAll(targetType.GetEnumUnderlyingTypeOrSelf())) Debug.Assert(Not integerOverflow) Debug.Assert(Not constantResult.IsBad) Else constantResult = Conversions.TryFoldNothingReferenceConversion(argument, conv, targetType) End If Return New BoundDirectCast(node, argument, conv, constantResult, targetType) End Function Private Function BindTryCastExpression( node As CastExpressionSyntax, diagnostics As DiagnosticBag ) As BoundExpression Debug.Assert(node.Keyword.Kind = SyntaxKind.TryCastKeyword) Dim argument = BindValue(node.Expression, diagnostics) Dim targetType = BindTypeSyntax(node.Type, diagnostics) Return ApplyTryCastConversion(node, argument, targetType, diagnostics) End Function Private Function ApplyTryCastConversion( node As SyntaxNode, argument As BoundExpression, targetType As TypeSymbol, diagnostics As DiagnosticBag ) As BoundExpression Debug.Assert(argument.IsValue) ' Deal with erroneous arguments If (argument.HasErrors OrElse targetType.IsErrorType) Then argument = MakeRValue(argument, diagnostics) Return New BoundTryCast(node, argument, conversionKind:=Nothing, type:=targetType, hasErrors:=True) End If ' Classify conversion Dim conv As ConversionKind If targetType.IsReferenceType Then Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing conv = Conversions.ClassifyTryCastConversion(argument, targetType, Me, useSiteDiagnostics) If diagnostics.Add(node, useSiteDiagnostics) Then ' Suppress any additional diagnostics diagnostics = New DiagnosticBag() End If Else conv = Nothing End If If ReclassifyExpression(argument, SyntaxKind.TryCastKeyword, node, conv, True, targetType, diagnostics) Then If argument.Syntax IsNot node Then ' If its an explicit conversion, we must have a bound node that corresponds to that syntax node for GetSemanticInfo. ' Insert an identity conversion if necessary. Debug.Assert(argument.Kind <> BoundKind.TryCast, "Associated wrong node with conversion?") argument = New BoundTryCast(node, argument, ConversionKind.Identity, targetType) End If Return argument Else argument = MakeRValue(argument, diagnostics) End If If argument.HasErrors Then Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True) End If Dim sourceType = argument.Type If sourceType IsNot Nothing AndAlso sourceType.IsErrorType() Then Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True) End If Debug.Assert(argument.IsNothingLiteral() OrElse (sourceType IsNot Nothing AndAlso Not sourceType.IsErrorType())) ' Check for special error conditions If Conversions.NoConversion(conv) Then If targetType.IsValueType() Then Dim castSyntax = TryCast(node, CastExpressionSyntax) ReportDiagnostic(diagnostics, If(castSyntax IsNot Nothing, castSyntax.Type, node), ERRID.ERR_TryCastOfValueType1, targetType) Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True) ElseIf targetType.IsTypeParameter() AndAlso Not targetType.IsReferenceType Then Dim castSyntax = TryCast(node, CastExpressionSyntax) ReportDiagnostic(diagnostics, If(castSyntax IsNot Nothing, castSyntax.Type, node), ERRID.ERR_TryCastOfUnconstrainedTypeParam1, targetType) Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True) ElseIf sourceType.IsValueType AndAlso sourceType.IsRestrictedType() AndAlso (targetType.IsObjectType() OrElse targetType.SpecialType = SpecialType.System_ValueType) Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_RestrictedConversion1, sourceType) Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True) End If End If WarnOnNarrowingConversionBetweenSealedClassAndAnInterface(conv, argument.Syntax, sourceType, targetType, diagnostics) If Conversions.NoConversion(conv) Then ReportNoConversionError(argument.Syntax, sourceType, targetType, diagnostics) Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True) End If Dim constantResult = Conversions.TryFoldNothingReferenceConversion(argument, conv, targetType) Return New BoundTryCast(node, argument, conv, constantResult, targetType) End Function Private Function BindPredefinedCastExpression( node As PredefinedCastExpressionSyntax, diagnostics As DiagnosticBag ) As BoundExpression Dim targetType As SpecialType Select Case node.Keyword.Kind Case SyntaxKind.CBoolKeyword : targetType = SpecialType.System_Boolean Case SyntaxKind.CByteKeyword : targetType = SpecialType.System_Byte Case SyntaxKind.CCharKeyword : targetType = SpecialType.System_Char Case SyntaxKind.CDateKeyword : targetType = SpecialType.System_DateTime Case SyntaxKind.CDecKeyword : targetType = SpecialType.System_Decimal Case SyntaxKind.CDblKeyword : targetType = SpecialType.System_Double Case SyntaxKind.CIntKeyword : targetType = SpecialType.System_Int32 Case SyntaxKind.CLngKeyword : targetType = SpecialType.System_Int64 Case SyntaxKind.CObjKeyword : targetType = SpecialType.System_Object Case SyntaxKind.CSByteKeyword : targetType = SpecialType.System_SByte Case SyntaxKind.CShortKeyword : targetType = SpecialType.System_Int16 Case SyntaxKind.CSngKeyword : targetType = SpecialType.System_Single Case SyntaxKind.CStrKeyword : targetType = SpecialType.System_String Case SyntaxKind.CUIntKeyword : targetType = SpecialType.System_UInt32 Case SyntaxKind.CULngKeyword : targetType = SpecialType.System_UInt64 Case SyntaxKind.CUShortKeyword : targetType = SpecialType.System_UInt16 Case Else Throw ExceptionUtilities.UnexpectedValue(node.Keyword.Kind) End Select Return ApplyConversion(node, GetSpecialType(targetType, node.Keyword, diagnostics), BindValue(node.Expression, diagnostics), isExplicit:=True, diagnostics:=diagnostics) End Function ''' <summary> ''' This function must return a BoundConversion node in case of non-identity conversion. ''' </summary> Friend Function ApplyImplicitConversion( node As SyntaxNode, targetType As TypeSymbol, expression As BoundExpression, diagnostics As DiagnosticBag, Optional isOperandOfConditionalBranch As Boolean = False ) As BoundExpression Return ApplyConversion(node, targetType, expression, False, diagnostics, isOperandOfConditionalBranch:=isOperandOfConditionalBranch) End Function ''' <summary> ''' This function must return a BoundConversion node in case of explicit or non-identity conversion. ''' </summary> Private Function ApplyConversion( node As SyntaxNode, targetType As TypeSymbol, argument As BoundExpression, isExplicit As Boolean, diagnostics As DiagnosticBag, Optional isOperandOfConditionalBranch As Boolean = False, Optional explicitSemanticForConcatArgument As Boolean = False ) As BoundExpression Debug.Assert(node IsNot Nothing) Debug.Assert(Not isOperandOfConditionalBranch OrElse Not isExplicit) Debug.Assert(argument.IsValue()) ' Deal with erroneous arguments If targetType.IsErrorType Then argument = MakeRValueAndIgnoreDiagnostics(argument) If Not isExplicit AndAlso argument.Type.IsSameTypeIgnoringAll(targetType) Then Return argument End If Return New BoundConversion(node, argument, conversionKind:=Nothing, checked:=CheckOverflow, explicitCastInCode:=isExplicit, type:=targetType, hasErrors:=True) End If If argument.HasErrors Then ' Suppress any additional diagnostics produced by this function diagnostics = New DiagnosticBag() End If ' Classify conversion Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) Dim applyNullableIsTrueOperator As Boolean = False Dim isTrueOperator As OverloadResolution.OverloadResolutionResult = Nothing Dim result As BoundExpression Debug.Assert(Not isOperandOfConditionalBranch OrElse targetType.IsBooleanType()) Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing If isOperandOfConditionalBranch AndAlso targetType.IsBooleanType() Then Debug.Assert(Not isExplicit) conv = Conversions.ClassifyConversionOfOperandOfConditionalBranch(argument, targetType, Me, applyNullableIsTrueOperator, isTrueOperator, useSiteDiagnostics) If diagnostics.Add(node, useSiteDiagnostics) Then ' Suppress any additional diagnostics diagnostics = New DiagnosticBag() End If If isTrueOperator.BestResult.HasValue Then ' Apply IsTrue operator. Dim isTrue As BoundUserDefinedUnaryOperator = BindUserDefinedUnaryOperator(node, UnaryOperatorKind.IsTrue, argument, isTrueOperator, diagnostics) isTrue.SetWasCompilerGenerated() isTrue.UnderlyingExpression.SetWasCompilerGenerated() result = isTrue Else Dim intermediateTargetType As TypeSymbol If applyNullableIsTrueOperator Then ' Note, use site error will be reported by ApplyNullableIsTrueOperator later. Dim nullableOfT As NamedTypeSymbol = Compilation.GetSpecialType(SpecialType.System_Nullable_T) intermediateTargetType = Compilation.GetSpecialType(SpecialType.System_Nullable_T). Construct(ImmutableArray.Create(Of TypeSymbol)(targetType)) Else intermediateTargetType = targetType End If result = CreateConversionAndReportDiagnostic(node, argument, conv, isExplicit, intermediateTargetType, diagnostics) End If If applyNullableIsTrueOperator Then result = Binder.ApplyNullableIsTrueOperator(result, targetType) End If Else conv = Conversions.ClassifyConversion(argument, targetType, Me, useSiteDiagnostics) If diagnostics.Add(node, useSiteDiagnostics) Then ' Suppress any additional diagnostics diagnostics = New DiagnosticBag() End If result = CreateConversionAndReportDiagnostic(node, argument, conv, isExplicit, targetType, diagnostics, explicitSemanticForConcatArgument:=explicitSemanticForConcatArgument) End If Return result End Function Private Shared Function ApplyNullableIsTrueOperator(argument As BoundExpression, booleanType As TypeSymbol) As BoundNullableIsTrueOperator Debug.Assert(argument.Type.IsNullableOfBoolean() AndAlso booleanType.IsBooleanType()) Return New BoundNullableIsTrueOperator(argument.Syntax, argument, booleanType).MakeCompilerGenerated() End Function ''' <summary> ''' This function must return a BoundConversion node in case of non-identity conversion. ''' </summary> Private Function CreateConversionAndReportDiagnostic( tree As SyntaxNode, argument As BoundExpression, convKind As KeyValuePair(Of ConversionKind, MethodSymbol), isExplicit As Boolean, targetType As TypeSymbol, diagnostics As DiagnosticBag, Optional copybackConversionParamName As String = Nothing, Optional explicitSemanticForConcatArgument As Boolean = False ) As BoundExpression Debug.Assert(argument.IsValue()) ' We need to preserve any conversion that was explicitly written in code ' (so that GetSemanticInfo can find the syntax in the bound tree). Implicit identity conversion ' don't need representation in the bound tree (they would be optimized away in emit, but are so common ' that this is an important way to save both time and memory). If (Not isExplicit OrElse explicitSemanticForConcatArgument) AndAlso Conversions.IsIdentityConversion(convKind.Key) Then Debug.Assert(argument.Type.IsSameTypeIgnoringAll(targetType)) Debug.Assert(tree Is argument.Syntax) Return MakeRValue(argument, diagnostics) End If If (convKind.Key And ConversionKind.UserDefined) = 0 AndAlso ReclassifyExpression(argument, SyntaxKind.CTypeKeyword, tree, convKind.Key, isExplicit, targetType, diagnostics) Then argument = MakeRValue(argument, diagnostics) If isExplicit AndAlso argument.Syntax IsNot tree Then ' If its an explicit conversion, we must have a bound node that corresponds to that syntax node for GetSemanticInfo. ' Insert an identity conversion if necessary. Debug.Assert(argument.Kind <> BoundKind.Conversion, "Associated wrong node with conversion?") argument = New BoundConversion(tree, argument, ConversionKind.Identity, CheckOverflow, isExplicit, targetType) End If Return argument ElseIf Not argument.IsNothingLiteral() AndAlso argument.Kind <> BoundKind.ArrayLiteral Then argument = MakeRValue(argument, diagnostics) End If Debug.Assert(argument.Kind <> BoundKind.Conversion OrElse DirectCast(argument, BoundConversion).ExplicitCastInCode OrElse Not argument.IsNothingLiteral() OrElse TypeOf argument.Syntax.Parent Is BinaryExpressionSyntax OrElse TypeOf argument.Syntax.Parent Is UnaryExpressionSyntax OrElse TypeOf argument.Syntax.Parent Is TupleExpressionSyntax OrElse (TypeOf argument.Syntax.Parent Is AssignmentStatementSyntax AndAlso argument.Syntax.Parent.Kind <> SyntaxKind.SimpleAssignmentStatement), "Applying yet another conversion to an implicit conversion from NOTHING, probably MakeRValue was called too early.") Dim sourceType = argument.Type ' At this point if the expression is an array literal then the conversion must be user defined. Debug.Assert(argument.Kind <> BoundKind.ArrayLiteral OrElse (convKind.Key And ConversionKind.UserDefined) <> 0) Dim reportArrayLiteralElementNarrowingConversion = False If argument.Kind = BoundKind.ArrayLiteral Then ' The array will get the type from the input type of the user defined conversion. sourceType = convKind.Value.Parameters(0).Type ' If the conversion from the inferred element type to the source type of the user defined conversion is a narrowing conversion then ' skip to the user defined conversion. Conversion errors on the individual elements will be reported when the array literal is reclassified. If Not isExplicit AndAlso Conversions.IsNarrowingConversion(convKind.Key) AndAlso Conversions.IsNarrowingConversion(Conversions.ClassifyArrayLiteralConversion(DirectCast(argument, BoundArrayLiteral), sourceType, Me, Nothing)) Then reportArrayLiteralElementNarrowingConversion = True GoTo DoneWithDiagnostics End If End If If argument.HasErrors Then GoTo DoneWithDiagnostics End If If sourceType IsNot Nothing AndAlso sourceType.IsErrorType() Then GoTo DoneWithDiagnostics End If Debug.Assert(argument.IsNothingLiteral() OrElse (sourceType IsNot Nothing AndAlso Not sourceType.IsErrorType())) ' Check for special error conditions If Conversions.NoConversion(convKind.Key) Then If sourceType.IsValueType AndAlso sourceType.IsRestrictedType() AndAlso (targetType.IsObjectType() OrElse targetType.SpecialType = SpecialType.System_ValueType) Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_RestrictedConversion1, sourceType) Return New BoundConversion(tree, argument, convKind.Key, CheckOverflow, isExplicit, targetType, hasErrors:=True) End If End If WarnOnNarrowingConversionBetweenSealedClassAndAnInterface(convKind.Key, argument.Syntax, sourceType, targetType, diagnostics) ' Deal with implicit narrowing conversions If Not isExplicit AndAlso Conversions.IsNarrowingConversion(convKind.Key) AndAlso (convKind.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0 Then If copybackConversionParamName IsNot Nothing Then If OptionStrict = VisualBasic.OptionStrict.On Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_StrictArgumentCopyBackNarrowing3, copybackConversionParamName, sourceType, targetType) ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.WRN_ImplicitConversionCopyBack, copybackConversionParamName, sourceType, targetType) End If Else ' We have a narrowing conversion. This is how we might display it, depending on context: ' ERR_NarrowingConversionDisallowed2 "Option Strict On disallows implicit conversions from '|1' to '|2'." ' ERR_NarrowingConversionCollection2 "Option Strict On disallows implicit conversions from '|1' to '|2'; ' the Visual Basic 6.0 collection type is not compatible with the .NET Framework collection type." ' ERR_AmbiguousCastConversion2 "Option Strict On disallows implicit conversions from '|1' to '|2' because the conversion is ambiguous." ' The Collection error is for when one type is Microsoft.VisualBasic.Collection and ' the other type is named _Collection. ' The Ambiguous error is for when the conversion was classed as "Narrowing" for reasons of ambiguity. If OptionStrict = VisualBasic.OptionStrict.On Then If Not MakeVarianceConversionSuggestion(convKind.Key, argument.Syntax, sourceType, targetType, diagnostics, justWarn:=False) Then Dim err As ERRID = ERRID.ERR_NarrowingConversionDisallowed2 Const _Collection As String = "_Collection" If (convKind.Key And ConversionKind.VarianceConversionAmbiguity) <> 0 Then err = ERRID.ERR_AmbiguousCastConversion2 ElseIf (sourceType.IsMicrosoftVisualBasicCollection() AndAlso String.Equals(targetType.Name, _Collection, StringComparison.Ordinal)) OrElse (String.Equals(sourceType.Name, _Collection, StringComparison.Ordinal) AndAlso targetType.IsMicrosoftVisualBasicCollection()) Then ' Got both, so use the more specific error message err = ERRID.ERR_NarrowingConversionCollection2 End If ReportDiagnostic(diagnostics, argument.Syntax, err, sourceType, targetType) End If ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then ' Avoid reporting a warning if narrowing caused exclusively by "zero argument" relaxation ' for an Anonymous Delegate. Note, that dropping a return is widening. If (convKind.Key And ConversionKind.AnonymousDelegate) = 0 OrElse (convKind.Key And ConversionKind.DelegateRelaxationLevelMask) <> ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs Then If Not MakeVarianceConversionSuggestion(convKind.Key, argument.Syntax, sourceType, targetType, diagnostics, justWarn:=True) Then Dim wrnId1 As ERRID = ERRID.WRN_ImplicitConversionSubst1 Dim wrnId2 As ERRID = ERRID.WRN_ImplicitConversion2 If (convKind.Key And ConversionKind.VarianceConversionAmbiguity) <> 0 Then wrnId2 = ERRID.WRN_AmbiguousCastConversion2 End If ReportDiagnostic(diagnostics, argument.Syntax, wrnId1, ErrorFactory.ErrorInfo(wrnId2, sourceType, targetType)) End If End If End If End If End If If Conversions.NoConversion(convKind.Key) Then If Conversions.FailedDueToNumericOverflow(convKind.Key) Then Dim errorTargetType As TypeSymbol If (convKind.Key And ConversionKind.UserDefined) <> 0 AndAlso convKind.Value IsNot Nothing Then errorTargetType = convKind.Value.Parameters(0).Type Else errorTargetType = targetType End If ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_ExpressionOverflow1, errorTargetType) ElseIf isExplicit OrElse Not MakeVarianceConversionSuggestion(convKind.Key, argument.Syntax, sourceType, targetType, diagnostics, justWarn:=False) Then ReportNoConversionError(argument.Syntax, sourceType, targetType, diagnostics, copybackConversionParamName) End If Return New BoundConversion(tree, argument, convKind.Key, CheckOverflow, isExplicit, targetType, hasErrors:=True) End If DoneWithDiagnostics: If (convKind.Key And ConversionKind.UserDefined) <> 0 Then Return CreateUserDefinedConversion(tree, argument, convKind, isExplicit, targetType, reportArrayLiteralElementNarrowingConversion, diagnostics) End If If argument.HasErrors OrElse (sourceType IsNot Nothing AndAlso sourceType.IsErrorType()) Then Return New BoundConversion(tree, argument, convKind.Key, CheckOverflow, isExplicit, targetType, hasErrors:=True) End If Return CreatePredefinedConversion(tree, argument, convKind.Key, isExplicit, targetType, diagnostics) End Function Private Structure VarianceSuggestionTypeParameterInfo Private _isViable As Boolean Private _typeParameter As TypeParameterSymbol Private _derivedArgument As TypeSymbol Private _baseArgument As TypeSymbol Public Sub [Set](parameter As TypeParameterSymbol, derived As TypeSymbol, base As TypeSymbol) _typeParameter = parameter _derivedArgument = derived _baseArgument = base _isViable = True End Sub Public ReadOnly Property IsViable As Boolean Get Return _isViable End Get End Property Public ReadOnly Property TypeParameter As TypeParameterSymbol Get Return _typeParameter End Get End Property Public ReadOnly Property DerivedArgument As TypeSymbol Get Return _derivedArgument End Get End Property Public ReadOnly Property BaseArgument As TypeSymbol Get Return _baseArgument End Get End Property End Structure ''' <summary> ''' Returns True if error or warning was reported. ''' ''' This function is invoked on the occasion of a Narrowing or NoConversion. ''' It looks at the conversion. If the conversion could have been helped by variance in ''' some way, it reports an error/warning message to that effect and returns true. This ''' message is a substitute for whatever other conversion-failed message might have been displayed. ''' ''' Note: these variance-related messages will NOT show auto-correct suggestion of using CType. That's ''' because, in these cases, it's more likely than not that CType will fail, so it would be a bad suggestion ''' </summary> Private Function MakeVarianceConversionSuggestion( convKind As ConversionKind, location As SyntaxNode, sourceType As TypeSymbol, targetType As TypeSymbol, diagnostics As DiagnosticBag, justWarn As Boolean ) As Boolean If (convKind And ConversionKind.UserDefined) <> 0 Then Return False End If ' Variance scenario 2: Dim x As List(Of Animal) = New List(Of Tiger) ' "List(Of Tiger) cannot be converted to List(Of Animal). Consider using IEnumerable(Of Animal) instead." ' ' (1) If the user attempts a conversion to DEST which is a generic binding of one of the non-variant ' standard generic collection types List(Of D), Collection(Of D), ReadOnlyCollection(Of D), ' IList(Of D), ICollection(Of D) ' (2) and if the conversion failed (either ConversionNarrowing or ConversionError), ' (3) and if the source type SOURCE implemented/inherited exactly one binding ISOURCE=G(Of S) of that ' generic collection type G ' (4) and if there is a reference conversion from S to D ' (5) Then report "G(Of S) cannot be converted to G(Of D). Consider converting to IEnumerable(Of D) instead." If targetType.Kind <> SymbolKind.NamedType Then Return False End If Dim targetNamedType = DirectCast(targetType, NamedTypeSymbol) If Not targetNamedType.IsGenericType Then Return False End If Dim targetGenericDefinition As NamedTypeSymbol = targetNamedType.OriginalDefinition If targetGenericDefinition.SpecialType = SpecialType.System_Collections_Generic_IList_T OrElse targetGenericDefinition.SpecialType = SpecialType.System_Collections_Generic_ICollection_T OrElse targetGenericDefinition.SpecialType = SpecialType.System_Collections_Generic_IReadOnlyList_T OrElse targetGenericDefinition.SpecialType = SpecialType.System_Collections_Generic_IReadOnlyCollection_T OrElse targetGenericDefinition Is Compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_List_T) OrElse targetGenericDefinition Is Compilation.GetWellKnownType(WellKnownType.System_Collections_ObjectModel_Collection_T) OrElse targetGenericDefinition Is Compilation.GetWellKnownType(WellKnownType.System_Collections_ObjectModel_ReadOnlyCollection_T) Then Dim sourceTypeArgument As TypeSymbol = Nothing If targetGenericDefinition.IsInterfaceType() Then Dim matchingInterfaces As New HashSet(Of NamedTypeSymbol)() If IsOrInheritsFromOrImplementsInterface(sourceType, targetGenericDefinition, useSiteDiagnostics:=Nothing, matchingInterfaces:=matchingInterfaces) AndAlso matchingInterfaces.Count = 1 Then sourceTypeArgument = matchingInterfaces(0).TypeArgumentsNoUseSiteDiagnostics(0) End If Else Dim typeToCheck As TypeSymbol = sourceType Do If typeToCheck.OriginalDefinition Is targetGenericDefinition Then sourceTypeArgument = DirectCast(typeToCheck, NamedTypeSymbol).TypeArgumentsNoUseSiteDiagnostics(0) Exit Do End If typeToCheck = typeToCheck.BaseTypeNoUseSiteDiagnostics Loop While typeToCheck IsNot Nothing End If If sourceTypeArgument IsNot Nothing AndAlso Conversions.IsWideningConversion(Conversions.Classify_Reference_Array_TypeParameterConversion(sourceTypeArgument, targetNamedType.TypeArgumentsNoUseSiteDiagnostics(0), varianceCompatibilityClassificationDepth:=0, useSiteDiagnostics:=Nothing)) Then Dim iEnumerable_T As NamedTypeSymbol = Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T) If Not iEnumerable_T.IsErrorType() Then Dim suggestion As NamedTypeSymbol = iEnumerable_T.Construct(targetNamedType.TypeArgumentsNoUseSiteDiagnostics(0)) If justWarn Then ReportDiagnostic(diagnostics, location, ERRID.WRN_ImplicitConversionSubst1, ErrorFactory.ErrorInfo(ERRID.WRN_VarianceIEnumerableSuggestion3, sourceType, targetType, suggestion)) Else ReportDiagnostic(diagnostics, location, ERRID.ERR_VarianceIEnumerableSuggestion3, sourceType, targetType, suggestion) End If Return True End If End If End If ' Variance scenario 1: | Variance scenario 3: ' Dim x as IEnumerable(Of Tiger) = New List(Of Animal) | Dim x As IGoo(Of Animal) = New MyGoo ' "List(Of Animal) cannot be converted to | "MyGoo cannot be converted to IGoo(Of Animal). ' IEnumerable(Of Tiger) because 'Animal' is not derived | Consider changing the 'T' in the definition ' from 'Tiger', as required for the 'Out' generic | of interface IGoo(Of T) to an Out type ' parameter 'T' in 'IEnumerable(Of Out T)'" | parameter, Out T." ' | ' (1) If the user attempts a conversion to | (1) If the user attempts a conversion to some ' some target type DEST=G(Of D1,D2,...) which is | target type DEST=G(Of D1,D2,...) which is ' a generic instantiation of some variant interface/| a generic instantiation of some interface/delegate ' delegate type G(Of T1,T2,...), | type G(...), which NEED NOT be variant! ' (2) and if the conversion fails (Narrowing/Error), | (2) and if the type G is defined in source-code, ' (3) and if the source type SOURCE implements/ | not imported metadata. And the conversion fails. ' inherits exactly one binding INHSOURCE= | (3) And INHSOURCE=exactly one binding of G ' G(Of S1,S2,...) of that generic type G, | (4) And if ever difference is either Di/Si/Ti ' (4) and if the only differences between (D1,D2,...) | where Ti has In/Out variance, or is ' and (S1,S2,...) occur in positions "Di/Si" | Dj/Sj/Tj such that Tj has no variance and ' such that the corresponding Ti has either In | Dj has a CLR conversion to Sj or vice versa ' or Out variance | (5) Then pick the first difference Dj/Sj ' (5) Then pick on the one such difference Si/Di/Ti | (6) and report "SOURCE cannot be converted to ' (6) and report "SOURCE cannot be converted to DEST | DEST. Consider changing Tj in the definition ' because Si is not derived from Di, as required | of interface/delegate IGoo(Of T) to an ' for the 'In/Out' generic parameter 'T' in | In/Out type parameter, In/Out T". ' 'IEnumerable(Of Out T)'" | Dim matchingGenericInstantiation As NamedTypeSymbol ' (1) If the user attempts a conversion Select Case targetGenericDefinition.TypeKind Case TypeKind.Delegate If sourceType.OriginalDefinition Is targetGenericDefinition Then matchingGenericInstantiation = DirectCast(sourceType, NamedTypeSymbol) Else Return False End If Case TypeKind.Interface Dim matchingInterfaces As New HashSet(Of NamedTypeSymbol)() If IsOrInheritsFromOrImplementsInterface(sourceType, targetGenericDefinition, useSiteDiagnostics:=Nothing, matchingInterfaces:=matchingInterfaces) AndAlso matchingInterfaces.Count = 1 Then matchingGenericInstantiation = matchingInterfaces(0) Else Return False End If Case Else Return False End Select ' (3) and if the source type implemented exactly one binding of it... Dim source As NamedTypeSymbol = matchingGenericInstantiation Dim destination As NamedTypeSymbol = targetNamedType Dim oneVariantDifference As VarianceSuggestionTypeParameterInfo = Nothing ' for Di/Si/Ti Dim oneInvariantConvertibleDifference As TypeParameterSymbol = Nothing 'for Dj/Sj/Tj where Sj<Dj Dim oneInvariantReverseConvertibleDifference As TypeParameterSymbol = Nothing ' Dj/Sj/Tj where Dj<Sj Do Dim typeParameters As ImmutableArray(Of TypeParameterSymbol) = source.TypeParameters Dim sourceArguments As ImmutableArray(Of TypeSymbol) = source.TypeArgumentsNoUseSiteDiagnostics Dim destinationArguments As ImmutableArray(Of TypeSymbol) = destination.TypeArgumentsNoUseSiteDiagnostics For i As Integer = 0 To typeParameters.Length - 1 Dim sourceArg As TypeSymbol = sourceArguments(i) Dim destinationArg As TypeSymbol = destinationArguments(i) If sourceArg.IsSameTypeIgnoringAll(destinationArg) Then Continue For End If If sourceArg.IsErrorType() OrElse destinationArg.IsErrorType() Then Continue For End If Dim conv As ConversionKind = Nothing Select Case typeParameters(i).Variance Case VarianceKind.Out If sourceArg.IsValueType OrElse destinationArg.IsValueType Then oneVariantDifference.Set(typeParameters(i), sourceArg, destinationArg) Else conv = Conversions.Classify_Reference_Array_TypeParameterConversion(sourceArg, destinationArg, varianceCompatibilityClassificationDepth:=0, useSiteDiagnostics:=Nothing) If Not Conversions.IsWideningConversion(conv) Then If Not Conversions.IsNarrowingConversion(conv) OrElse (conv And ConversionKind.VarianceConversionAmbiguity) = 0 Then oneVariantDifference.Set(typeParameters(i), sourceArg, destinationArg) End If End If End If Case VarianceKind.In If sourceArg.IsValueType OrElse destinationArg.IsValueType Then oneVariantDifference.Set(typeParameters(i), destinationArg, sourceArg) Else conv = Conversions.Classify_Reference_Array_TypeParameterConversion(destinationArg, sourceArg, varianceCompatibilityClassificationDepth:=0, useSiteDiagnostics:=Nothing) If Not Conversions.IsWideningConversion(conv) Then If (targetNamedType.IsDelegateType AndAlso destinationArg.IsReferenceType AndAlso sourceArg.IsReferenceType) OrElse Not Conversions.IsNarrowingConversion(conv) OrElse (conv And ConversionKind.VarianceConversionAmbiguity) = 0 Then oneVariantDifference.Set(typeParameters(i), destinationArg, sourceArg) End If End If End If Case Else conv = Conversions.ClassifyDirectCastConversion(sourceArg, destinationArg, Nothing) If Conversions.IsWideningConversion(conv) Then oneInvariantConvertibleDifference = typeParameters(i) Else conv = Conversions.ClassifyDirectCastConversion(destinationArg, sourceArg, Nothing) If Conversions.IsWideningConversion(conv) Then oneInvariantReverseConvertibleDifference = typeParameters(i) Else Return False End If End If End Select Next source = source.ContainingType destination = destination.ContainingType Loop While source IsNot Nothing ' (5) If a Di/Si/Ti, and no Dj/Sj/Tj nor Dk/Sk/Tk, then report... If oneVariantDifference.IsViable AndAlso oneInvariantConvertibleDifference Is Nothing AndAlso oneInvariantReverseConvertibleDifference Is Nothing Then Dim containerFormatter As FormattedSymbol If oneVariantDifference.TypeParameter.ContainingType.IsDelegateType Then containerFormatter = CustomSymbolDisplayFormatter.DelegateSignature(oneVariantDifference.TypeParameter.ContainingSymbol) Else containerFormatter = CustomSymbolDisplayFormatter.ErrorNameWithKind(oneVariantDifference.TypeParameter.ContainingSymbol) End If If justWarn Then ReportDiagnostic(diagnostics, location, ERRID.WRN_ImplicitConversionSubst1, ErrorFactory.ErrorInfo(If(oneVariantDifference.TypeParameter.Variance = VarianceKind.Out, ERRID.WRN_VarianceConversionFailedOut6, ERRID.WRN_VarianceConversionFailedIn6), oneVariantDifference.DerivedArgument, oneVariantDifference.BaseArgument, oneVariantDifference.TypeParameter.Name, containerFormatter, sourceType, targetType)) Else ReportDiagnostic(diagnostics, location, If(oneVariantDifference.TypeParameter.Variance = VarianceKind.Out, ERRID.ERR_VarianceConversionFailedOut6, ERRID.ERR_VarianceConversionFailedIn6), oneVariantDifference.DerivedArgument, oneVariantDifference.BaseArgument, oneVariantDifference.TypeParameter.Name, containerFormatter, sourceType, targetType) End If Return True End If ' (5b) Otherwise, if a Dj/Sj/Tj and no Dk/Sk/Tk, and G came not from metadata, then report... If (oneInvariantConvertibleDifference IsNot Nothing OrElse oneInvariantReverseConvertibleDifference IsNot Nothing) AndAlso targetType.ContainingModule Is Compilation.SourceModule Then Dim oneInvariantDifference As TypeParameterSymbol If oneInvariantConvertibleDifference IsNot Nothing Then oneInvariantDifference = oneInvariantConvertibleDifference Else oneInvariantDifference = oneInvariantReverseConvertibleDifference End If Dim containerFormatter As FormattedSymbol If oneInvariantDifference.ContainingType.IsDelegateType Then containerFormatter = CustomSymbolDisplayFormatter.DelegateSignature(oneInvariantDifference.ContainingSymbol) Else containerFormatter = CustomSymbolDisplayFormatter.ErrorNameWithKind(oneInvariantDifference.ContainingSymbol) End If If justWarn Then ReportDiagnostic(diagnostics, location, ERRID.WRN_ImplicitConversionSubst1, ErrorFactory.ErrorInfo(If(oneInvariantConvertibleDifference IsNot Nothing, ERRID.WRN_VarianceConversionFailedTryOut4, ERRID.WRN_VarianceConversionFailedTryIn4), sourceType, targetType, oneInvariantDifference.Name, containerFormatter)) Else ReportDiagnostic(diagnostics, location, If(oneInvariantConvertibleDifference IsNot Nothing, ERRID.ERR_VarianceConversionFailedTryOut4, ERRID.ERR_VarianceConversionFailedTryIn4), sourceType, targetType, oneInvariantDifference.Name, containerFormatter) End If Return True End If Return False End Function Private Function CreatePredefinedConversion( tree As SyntaxNode, argument As BoundExpression, convKind As ConversionKind, isExplicit As Boolean, targetType As TypeSymbol, diagnostics As DiagnosticBag ) As BoundConversion Debug.Assert(Conversions.ConversionExists(convKind) AndAlso (convKind And ConversionKind.UserDefined) = 0) Dim sourceType = argument.Type ' Handle Anonymous Delegate conversion. If (convKind And ConversionKind.AnonymousDelegate) <> 0 Then ' Don't spend time building a narrowing relaxation stub if we already complained about the narrowing. If isExplicit OrElse OptionStrict <> VisualBasic.OptionStrict.On OrElse Conversions.IsWideningConversion(convKind) Then Debug.Assert(Not Conversions.IsIdentityConversion(convKind)) Debug.Assert(sourceType.IsDelegateType() AndAlso DirectCast(sourceType, NamedTypeSymbol).IsAnonymousType AndAlso targetType.IsDelegateType() AndAlso targetType.SpecialType <> SpecialType.System_MulticastDelegate) Dim boundLambdaOpt As BoundLambda = Nothing Dim relaxationReceiverPlaceholderOpt As BoundRValuePlaceholder = Nothing Dim methodToConvert As MethodSymbol = DirectCast(sourceType, NamedTypeSymbol).DelegateInvokeMethod If (convKind And ConversionKind.NeedAStub) <> 0 Then Dim relaxationBinder As Binder ' If conversion is explicit, use Option Strict Off. If isExplicit AndAlso Me.OptionStrict <> VisualBasic.OptionStrict.Off Then relaxationBinder = New OptionStrictOffBinder(Me) Else relaxationBinder = Me End If Debug.Assert(Not isExplicit OrElse relaxationBinder.OptionStrict = VisualBasic.OptionStrict.Off) boundLambdaOpt = relaxationBinder.BuildDelegateRelaxationLambda(tree, tree, argument, methodToConvert, Nothing, QualificationKind.QualifiedViaValue, DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod, convKind And ConversionKind.DelegateRelaxationLevelMask, isZeroArgumentKnownToBeUsed:=False, warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=False, diagnostics:=diagnostics, relaxationReceiverPlaceholder:=relaxationReceiverPlaceholderOpt) End If ' The conversion has the lambda stored internally to not clutter the bound tree with synthesized nodes ' in the first pass. Later the node get's rewritten into a delegate creation with the lambda if needed. Return New BoundConversion(tree, argument, convKind, False, isExplicit, Nothing, If(boundLambdaOpt Is Nothing, Nothing, New BoundRelaxationLambda(tree, boundLambdaOpt, relaxationReceiverPlaceholderOpt).MakeCompilerGenerated()), targetType) Else Debug.Assert(diagnostics.HasAnyErrors()) End If End If Dim integerOverflow As Boolean = False Dim constantResult = Conversions.TryFoldConstantConversion( argument, targetType, integerOverflow) If constantResult IsNot Nothing Then ' Overflow should have been detected at classification time. Debug.Assert(Not integerOverflow OrElse Not CheckOverflow) Debug.Assert(Not constantResult.IsBad) Else constantResult = Conversions.TryFoldNothingReferenceConversion(argument, convKind, targetType) End If Dim tupleElements As BoundConvertedTupleElements = CreateConversionForTupleElements(tree, sourceType, targetType, convKind, isExplicit) Return New BoundConversion(tree, argument, convKind, CheckOverflow, isExplicit, constantResult, tupleElements, targetType) End Function Private Function CreateConversionForTupleElements( tree As SyntaxNode, sourceType As TypeSymbol, targetType As TypeSymbol, convKind As ConversionKind, isExplicit As Boolean ) As BoundConvertedTupleElements If (convKind And ConversionKind.Tuple) <> 0 Then Dim ignore = DiagnosticBag.GetInstance() Dim sourceElementTypes = sourceType.GetNullableUnderlyingTypeOrSelf().GetElementTypesOfTupleOrCompatible() Dim targetElementTypes = targetType.GetNullableUnderlyingTypeOrSelf().GetElementTypesOfTupleOrCompatible() Dim placeholders = ArrayBuilder(Of BoundRValuePlaceholder).GetInstance(sourceElementTypes.Length) Dim converted = ArrayBuilder(Of BoundExpression).GetInstance(sourceElementTypes.Length) For i As Integer = 0 To sourceElementTypes.Length - 1 Dim placeholder = New BoundRValuePlaceholder(tree, sourceElementTypes(i)).MakeCompilerGenerated() placeholders.Add(placeholder) converted.Add(ApplyConversion(tree, targetElementTypes(i), placeholder, isExplicit, ignore)) Next ignore.Free() Return New BoundConvertedTupleElements(tree, placeholders.ToImmutableAndFree(), converted.ToImmutableAndFree()).MakeCompilerGenerated() End If Return Nothing End Function Private Function CreateUserDefinedConversion( tree As SyntaxNode, argument As BoundExpression, convKind As KeyValuePair(Of ConversionKind, MethodSymbol), isExplicit As Boolean, targetType As TypeSymbol, reportArrayLiteralElementNarrowingConversion As Boolean, diagnostics As DiagnosticBag ) As BoundConversion Debug.Assert((convKind.Key And ConversionKind.UserDefined) <> 0 AndAlso convKind.Value IsNot Nothing AndAlso convKind.Value.ParameterCount = 1 AndAlso Not convKind.Value.IsSub AndAlso Not convKind.Value.Parameters(0).IsByRef AndAlso convKind.Value.IsShared) ' Suppress any Option Strict diagnostics. Dim conversionBinder = New OptionStrictOffBinder(Me) Dim argumentSyntax = argument.Syntax Dim originalArgumentType As TypeSymbol = argument.Type Dim inType As TypeSymbol = convKind.Value.Parameters(0).Type Dim outType As TypeSymbol = convKind.Value.ReturnType Dim intermediateConv As ConversionKind Dim inOutConversionFlags As Byte = 0 If argument.Kind = BoundKind.ArrayLiteral Then ' For array literals, report Option Strict diagnostics for each element when reportArrayLiteralElementNarrowingConversion is true. Dim arrayLiteral = DirectCast(argument, BoundArrayLiteral) Dim arrayLiteralBinder = If(reportArrayLiteralElementNarrowingConversion, Me, conversionBinder) intermediateConv = Conversions.ClassifyArrayLiteralConversion(arrayLiteral, inType, arrayLiteralBinder, Nothing) argument = arrayLiteralBinder.ReclassifyArrayLiteralExpression(SyntaxKind.CTypeKeyword, tree, intermediateConv, isExplicit, arrayLiteral, inType, diagnostics) originalArgumentType = inType Else intermediateConv = Conversions.ClassifyPredefinedConversion(argument, inType, conversionBinder, Nothing) If Not Conversions.IsIdentityConversion(intermediateConv) Then #If DEBUG Then Dim oldArgument = argument #End If argument = conversionBinder.CreatePredefinedConversion(tree, argument, intermediateConv, isExplicit, inType, diagnostics). MakeCompilerGenerated() #If DEBUG Then Debug.Assert(oldArgument IsNot argument AndAlso argument.Kind = BoundKind.Conversion) #End If inOutConversionFlags = 1 End If End If ReportUseSiteError(diagnostics, tree, convKind.Value) ReportDiagnosticsIfObsolete(diagnostics, convKind.Value, tree) Debug.Assert(convKind.Value.IsUserDefinedOperator()) If Me.ContainingMember Is convKind.Value Then ReportDiagnostic(diagnostics, argumentSyntax, ERRID.WRN_RecursiveOperatorCall, convKind.Value) End If argument = New BoundCall(tree, method:=convKind.Value, methodGroupOpt:=Nothing, receiverOpt:=Nothing, arguments:=ImmutableArray.Create(Of BoundExpression)(argument), constantValueOpt:=Nothing, suppressObjectClone:=True, type:=outType).MakeCompilerGenerated() intermediateConv = Conversions.ClassifyPredefinedConversion(argument, targetType, conversionBinder, Nothing) If Not Conversions.IsIdentityConversion(intermediateConv) Then #If DEBUG Then Dim oldArgument = argument #End If argument = conversionBinder.CreatePredefinedConversion(tree, argument, intermediateConv, isExplicit, targetType, diagnostics). MakeCompilerGenerated() #If DEBUG Then Debug.Assert(oldArgument IsNot argument AndAlso argument.Kind = BoundKind.Conversion) #End If inOutConversionFlags = inOutConversionFlags Or CByte(2) End If argument = New BoundUserDefinedConversion(tree, argument, inOutConversionFlags, originalArgumentType).MakeCompilerGenerated() Return New BoundConversion(tree, argument, convKind.Key, CheckOverflow, isExplicit, DirectCast(Nothing, ConstantValue), targetType) End Function ''' <summary> ''' Handle expression reclassification, if any applicable. ''' ''' If function returns True, the "argument" parameter has been replaced ''' with result of reclassification (possibly an error node) and appropriate ''' diagnostic, if any, has been reported. ''' ''' If function returns false, the "argument" parameter must be unchanged and no ''' diagnostic should be reported. ''' ''' conversionSemantics can be one of these: ''' SyntaxKind.CTypeKeyword, SyntaxKind.DirectCastKeyword, SyntaxKind.TryCastKeyword ''' </summary> Private Function ReclassifyExpression( ByRef argument As BoundExpression, conversionSemantics As SyntaxKind, tree As SyntaxNode, convKind As ConversionKind, isExplicit As Boolean, targetType As TypeSymbol, diagnostics As DiagnosticBag ) As Boolean Debug.Assert(argument.Kind <> BoundKind.GroupTypeInferenceLambda) Select Case argument.Kind Case BoundKind.Parenthesized If argument.Type Is Nothing AndAlso Not argument.IsNothingLiteral() Then Dim parenthesized = DirectCast(argument, BoundParenthesized) Dim enclosed As BoundExpression = parenthesized.Expression ' Reclassify enclosed expression. If ReclassifyExpression(enclosed, conversionSemantics, enclosed.Syntax, convKind, isExplicit, targetType, diagnostics) Then argument = parenthesized.Update(enclosed, enclosed.Type) If conversionSemantics = SyntaxKind.CTypeKeyword Then argument = ApplyConversion(tree, targetType, argument, isExplicit, diagnostics) ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then argument = ApplyDirectCastConversion(tree, argument, targetType, diagnostics) ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then argument = ApplyTryCastConversion(tree, argument, targetType, diagnostics) Else Throw ExceptionUtilities.UnexpectedValue(conversionSemantics) End If Return True End If End If Case BoundKind.UnboundLambda argument = ReclassifyUnboundLambdaExpression(DirectCast(argument, UnboundLambda), conversionSemantics, tree, convKind, isExplicit, targetType, diagnostics) Return True Case BoundKind.QueryLambda argument = ReclassifyQueryLambdaExpression(DirectCast(argument, BoundQueryLambda), conversionSemantics, tree, convKind, isExplicit, targetType, diagnostics) Return True Case BoundKind.LateAddressOfOperator Dim addressOfExpression = DirectCast(argument, BoundLateAddressOfOperator) If targetType.TypeKind <> TypeKind.Delegate AndAlso targetType.TypeKind <> TypeKind.Error Then ' 'AddressOf' expression cannot be converted to '{0}' because '{0}' is not a delegate type. ReportDiagnostic(diagnostics, addressOfExpression.Syntax, ERRID.ERR_AddressOfNotDelegate1, targetType) End If argument = addressOfExpression.Update(addressOfExpression.Binder, addressOfExpression.MemberAccess, targetType) Return True Case BoundKind.AddressOfOperator Dim delegateResolutionResult As DelegateResolutionResult = Nothing Dim addressOfExpression = DirectCast(argument, BoundAddressOfOperator) If addressOfExpression.GetDelegateResolutionResult(targetType, delegateResolutionResult) Then diagnostics.AddRange(delegateResolutionResult.Diagnostics) Dim hasErrors = True If Conversions.ConversionExists(delegateResolutionResult.DelegateConversions) Then Dim reclassifyBinder As Binder ' If conversion is explicit, use Option Strict Off. If isExplicit AndAlso Me.OptionStrict <> VisualBasic.OptionStrict.Off Then reclassifyBinder = New OptionStrictOffBinder(Me) Else reclassifyBinder = Me End If Debug.Assert(Not isExplicit OrElse reclassifyBinder.OptionStrict = VisualBasic.OptionStrict.Off) argument = reclassifyBinder.ReclassifyAddressOf(addressOfExpression, delegateResolutionResult, targetType, diagnostics, isForHandles:=False, warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=Not isExplicit AndAlso tree.Kind <> SyntaxKind.ObjectCreationExpression) hasErrors = argument.HasErrors Debug.Assert(convKind = delegateResolutionResult.DelegateConversions) End If If argument.Kind <> BoundKind.DelegateCreationExpression Then If conversionSemantics = SyntaxKind.CTypeKeyword Then argument = New BoundConversion(tree, argument, convKind, False, isExplicit, targetType, hasErrors:=hasErrors) ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then argument = New BoundDirectCast(tree, argument, convKind, targetType, hasErrors:=hasErrors) ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then argument = New BoundTryCast(tree, argument, convKind, targetType, hasErrors:=hasErrors) Else Throw ExceptionUtilities.UnexpectedValue(conversionSemantics) End If End If Return True End If Case BoundKind.ArrayLiteral argument = ReclassifyArrayLiteralExpression(conversionSemantics, tree, convKind, isExplicit, DirectCast(argument, BoundArrayLiteral), targetType, diagnostics) Return True Case BoundKind.InterpolatedStringExpression argument = ReclassifyInterpolatedStringExpression(conversionSemantics, tree, convKind, isExplicit, DirectCast(argument, BoundInterpolatedStringExpression), targetType, diagnostics) Return argument.Kind = BoundKind.Conversion Case BoundKind.TupleLiteral Dim literal = DirectCast(argument, BoundTupleLiteral) argument = ReclassifyTupleLiteral(convKind, tree, isExplicit, literal, targetType, diagnostics) Return argument IsNot literal End Select Return False End Function Private Function ReclassifyUnboundLambdaExpression( unboundLambda As UnboundLambda, conversionSemantics As SyntaxKind, tree As SyntaxNode, convKind As ConversionKind, isExplicit As Boolean, targetType As TypeSymbol, diagnostics As DiagnosticBag ) As BoundExpression Dim targetDelegateType As NamedTypeSymbol ' the target delegate type; if targetType is Expression(Of D), then this is D, otherwise targetType or Nothing. Dim delegateInvoke As MethodSymbol If targetType.IsStrictSupertypeOfConcreteDelegate() Then ' covers Object, System.Delegate, System.MulticastDelegate ' Reclassify the lambda as an instance of an Anonymous Delegate. Dim anonymousDelegate As BoundExpression = ReclassifyUnboundLambdaExpression(unboundLambda, diagnostics) #If DEBUG Then Dim anonymousDelegateInfo As KeyValuePair(Of NamedTypeSymbol, ImmutableArray(Of Diagnostic)) = unboundLambda.InferredAnonymousDelegate Debug.Assert(anonymousDelegate.Type Is anonymousDelegateInfo.Key) ' If we have errors for the inference, we know that there is no conversion. If Not anonymousDelegateInfo.Value.IsDefault AndAlso anonymousDelegateInfo.Value.HasAnyErrors() Then Debug.Assert(Conversions.NoConversion(convKind) AndAlso (convKind And ConversionKind.DelegateRelaxationLevelMask) = 0) Else Debug.Assert(Conversions.NoConversion(convKind) OrElse (convKind And ConversionKind.DelegateRelaxationLevelMask) >= ConversionKind.DelegateRelaxationLevelWideningToNonLambda) End If #End If ' Now convert it to the target type. If conversionSemantics = SyntaxKind.CTypeKeyword Then Return ApplyConversion(tree, targetType, anonymousDelegate, isExplicit, diagnostics) ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then Return ApplyDirectCastConversion(tree, anonymousDelegate, targetType, diagnostics) ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then Return ApplyTryCastConversion(tree, anonymousDelegate, targetType, diagnostics) Else Throw ExceptionUtilities.UnexpectedValue(conversionSemantics) End If Else targetDelegateType = targetType.DelegateOrExpressionDelegate(Me) If targetDelegateType Is Nothing Then Debug.Assert((convKind And ConversionKind.DelegateRelaxationLevelMask) = 0) ReportDiagnostic(diagnostics, unboundLambda.Syntax, ERRID.ERR_LambdaNotDelegate1, targetType) delegateInvoke = Nothing ' No conversion Else delegateInvoke = targetDelegateType.DelegateInvokeMethod If delegateInvoke Is Nothing Then ReportDiagnostic(diagnostics, unboundLambda.Syntax, ERRID.ERR_LambdaNotDelegate1, targetDelegateType) delegateInvoke = Nothing ' No conversion ElseIf ReportDelegateInvokeUseSiteError(diagnostics, unboundLambda.Syntax, targetDelegateType, delegateInvoke) Then delegateInvoke = Nothing ' No conversion ElseIf unboundLambda.IsInferredDelegateForThisLambda(delegateInvoke.ContainingType) Then Dim inferenceDiagnostics As ImmutableArray(Of Diagnostic) = unboundLambda.InferredAnonymousDelegate.Value If Not inferenceDiagnostics.IsEmpty Then diagnostics.AddRange(inferenceDiagnostics) If inferenceDiagnostics.HasAnyErrors() Then delegateInvoke = Nothing ' No conversion End If End If End If Debug.Assert(delegateInvoke IsNot Nothing OrElse (convKind And ConversionKind.DelegateRelaxationLevelMask) = 0) End If End If Dim boundLambda As BoundLambda = Nothing If delegateInvoke IsNot Nothing Then boundLambda = unboundLambda.GetBoundLambda(New UnboundLambda.TargetSignature(delegateInvoke)) Debug.Assert(boundLambda IsNot Nothing) If boundLambda Is Nothing Then ' An unlikely case. Debug.Assert((convKind And ConversionKind.DelegateRelaxationLevelMask) = 0) ReportDiagnostic(diagnostics, unboundLambda.Syntax, If(unboundLambda.IsFunctionLambda, ERRID.ERR_LambdaBindingMismatch1, ERRID.ERR_LambdaBindingMismatch2), If(targetDelegateType.TypeKind = TypeKind.Delegate AndAlso targetDelegateType.IsFromCompilation(Me.Compilation), CType(CustomSymbolDisplayFormatter.DelegateSignature(targetDelegateType), Object), CType(targetDelegateType, Object))) End If End If If boundLambda Is Nothing Then Debug.Assert(Conversions.NoConversion(convKind)) Dim errorRecovery As BoundLambda = unboundLambda.BindForErrorRecovery() If conversionSemantics = SyntaxKind.CTypeKeyword Then Return New BoundConversion(tree, errorRecovery, convKind, False, isExplicit, targetType, hasErrors:=True) ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then Return New BoundDirectCast(tree, errorRecovery, convKind, targetType, hasErrors:=True) ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then Return New BoundTryCast(tree, errorRecovery, convKind, targetType, hasErrors:=True) Else Throw ExceptionUtilities.UnexpectedValue(conversionSemantics) End If End If Dim boundLambdaDiagnostics = boundLambda.Diagnostics Debug.Assert((convKind And ConversionKind.DelegateRelaxationLevelMask) >= boundLambda.DelegateRelaxation) Debug.Assert(Conversions.ClassifyMethodConversionForLambdaOrAnonymousDelegate(delegateInvoke, boundLambda.LambdaSymbol, Nothing) = MethodConversionKind.Identity OrElse ((convKind And ConversionKind.DelegateRelaxationLevelMask) <> ConversionKind.DelegateRelaxationLevelNone AndAlso boundLambda.MethodConversionKind <> MethodConversionKind.Identity)) Dim reportedAnError As Boolean = False If boundLambdaDiagnostics.Any() Then diagnostics.AddRange(boundLambdaDiagnostics) reportedAnError = boundLambdaDiagnostics.HasAnyErrors() End If Dim relaxationLambdaOpt As BoundLambda = Nothing If (convKind And ConversionKind.DelegateRelaxationLevelMask) = ConversionKind.DelegateRelaxationLevelInvalid AndAlso Not reportedAnError AndAlso Not boundLambda.HasErrors Then ' We don't try to infer return type of a lambda that has both Async and Iterator modifiers, let's suppress the ' signature mismatch error in this case. If unboundLambda.ReturnType IsNot Nothing OrElse unboundLambda.Flags <> (SourceMemberFlags.Async Or SourceMemberFlags.Iterator) Then Dim err As ERRID If unboundLambda.IsFunctionLambda Then err = ERRID.ERR_LambdaBindingMismatch1 Else err = ERRID.ERR_LambdaBindingMismatch2 End If ReportDiagnostic(diagnostics, unboundLambda.Syntax, err, If(targetDelegateType.TypeKind = TypeKind.Delegate AndAlso targetDelegateType.IsFromCompilation(Me.Compilation), CType(CustomSymbolDisplayFormatter.DelegateSignature(targetDelegateType), Object), CType(targetDelegateType, Object))) End If ElseIf Conversions.IsStubRequiredForMethodConversion(boundLambda.MethodConversionKind) Then Debug.Assert(Conversions.IsDelegateRelaxationSupportedFor(boundLambda.MethodConversionKind)) ' Need to produce a stub. ' First, we need to get an Anonymous Delegate of the same shape as the lambdaSymbol. Dim lambdaSymbol As LambdaSymbol = boundLambda.LambdaSymbol Dim anonymousDelegateType As NamedTypeSymbol = ConstructAnonymousDelegateSymbol(unboundLambda, (lambdaSymbol.Parameters.As(Of BoundLambdaParameterSymbol)), lambdaSymbol.ReturnType, diagnostics) ' Second, reclassify the bound lambda as an instance of the Anonymous Delegate. Dim anonymousDelegateInstance = New BoundConversion(tree, boundLambda, ConversionKind.Widening Or ConversionKind.Lambda, False, False, anonymousDelegateType) anonymousDelegateInstance.SetWasCompilerGenerated() ' Third, create a method group representing Invoke method of the instance of the Anonymous Delegate. Dim methodGroup = New BoundMethodGroup(unboundLambda.Syntax, Nothing, ImmutableArray.Create(anonymousDelegateType.DelegateInvokeMethod), LookupResultKind.Good, anonymousDelegateInstance, QualificationKind.QualifiedViaValue) methodGroup.SetWasCompilerGenerated() ' Fourth, create a lambda with the shape of the target delegate that calls the Invoke with appropriate conversions ' and drops parameters and/or return value, if needed, thus performing the relaxation. Dim relaxationBinder As Binder ' If conversion is explicit, use Option Strict Off. If isExplicit AndAlso Me.OptionStrict <> VisualBasic.OptionStrict.Off Then relaxationBinder = New OptionStrictOffBinder(Me) Else relaxationBinder = Me End If Debug.Assert(Not isExplicit OrElse relaxationBinder.OptionStrict = VisualBasic.OptionStrict.Off) relaxationLambdaOpt = relaxationBinder.BuildDelegateRelaxationLambda(unboundLambda.Syntax, delegateInvoke, methodGroup, boundLambda.DelegateRelaxation, isZeroArgumentKnownToBeUsed:=False, warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=Not isExplicit AndAlso tree.Kind <> SyntaxKind.ObjectCreationExpression, diagnostics:=diagnostics) End If If conversionSemantics = SyntaxKind.CTypeKeyword Then Return New BoundConversion(tree, boundLambda, convKind, False, isExplicit, Nothing, If(relaxationLambdaOpt Is Nothing, Nothing, New BoundRelaxationLambda(tree, relaxationLambdaOpt, receiverPlaceholderOpt:=Nothing).MakeCompilerGenerated()), targetType) ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then Return New BoundDirectCast(tree, boundLambda, convKind, relaxationLambdaOpt, targetType) ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then Return New BoundTryCast(tree, boundLambda, convKind, relaxationLambdaOpt, targetType) Else Throw ExceptionUtilities.UnexpectedValue(conversionSemantics) End If End Function Private Function ReclassifyQueryLambdaExpression( lambda As BoundQueryLambda, conversionSemantics As SyntaxKind, tree As SyntaxNode, convKind As ConversionKind, isExplicit As Boolean, targetType As TypeSymbol, diagnostics As DiagnosticBag ) As BoundExpression Debug.Assert(lambda.Type Is Nothing) ' the target delegate type; if targetType is Expression(Of D), then this is D, otherwise targetType or Nothing. Dim targetDelegateType As NamedTypeSymbol = targetType.DelegateOrExpressionDelegate(Me) If Conversions.NoConversion(convKind) Then If targetType.IsStrictSupertypeOfConcreteDelegate() AndAlso Not targetType.IsObjectType() Then ReportDiagnostic(diagnostics, lambda.Syntax, ERRID.ERR_LambdaNotCreatableDelegate1, targetType) Else If targetDelegateType Is Nothing Then ReportDiagnostic(diagnostics, lambda.Syntax, ERRID.ERR_LambdaNotDelegate1, targetType) Else Dim invoke As MethodSymbol = targetDelegateType.DelegateInvokeMethod If invoke Is Nothing Then ReportDiagnostic(diagnostics, lambda.Syntax, ERRID.ERR_LambdaNotDelegate1, targetDelegateType) ElseIf Not ReportDelegateInvokeUseSiteError(diagnostics, lambda.Syntax, targetDelegateType, invoke) Then ' Conversion could fail because we couldn't convert body of the lambda ' to the target delegate type. We want to report that error instead of ' lambda signature mismatch. If lambda.LambdaSymbol.ReturnType Is LambdaSymbol.ReturnTypePendingDelegate AndAlso Not invoke.IsSub AndAlso Conversions.FailedDueToQueryLambdaBodyMismatch(convKind) Then lambda = lambda.Update(lambda.LambdaSymbol, lambda.RangeVariables, ApplyImplicitConversion(lambda.Expression.Syntax, invoke.ReturnType, lambda.Expression, diagnostics, If(invoke.ReturnType.IsBooleanType, lambda.ExprIsOperandOfConditionalBranch, False)), exprIsOperandOfConditionalBranch:=False) Else ReportDiagnostic(diagnostics, lambda.Syntax, ERRID.ERR_LambdaBindingMismatch1, targetDelegateType) End If End If End If End If If conversionSemantics = SyntaxKind.CTypeKeyword Then Return New BoundConversion(tree, lambda, convKind, False, isExplicit, targetType, hasErrors:=True).MakeCompilerGenerated() ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then Return New BoundDirectCast(tree, lambda, convKind, targetType, hasErrors:=True).MakeCompilerGenerated() ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then Return New BoundTryCast(tree, lambda, convKind, targetType, hasErrors:=True).MakeCompilerGenerated() End If Throw ExceptionUtilities.UnexpectedValue(conversionSemantics) End If Dim delegateInvoke As MethodSymbol = targetDelegateType.DelegateInvokeMethod For Each delegateParam As ParameterSymbol In delegateInvoke.Parameters If delegateParam.IsByRef OrElse delegateParam.OriginalDefinition.Type.IsTypeParameter() Then Dim restrictedType As TypeSymbol = Nothing If delegateParam.Type.IsRestrictedTypeOrArrayType(restrictedType) Then ReportDiagnostic(diagnostics, lambda.LambdaSymbol.Parameters(delegateParam.Ordinal).Locations(0), ERRID.ERR_RestrictedType1, restrictedType) End If End If Next Dim delegateReturnType As TypeSymbol = delegateInvoke.ReturnType If delegateInvoke.OriginalDefinition.ReturnType.IsTypeParameter() Then Dim restrictedType As TypeSymbol = Nothing If delegateReturnType.IsRestrictedTypeOrArrayType(restrictedType) Then Dim location As SyntaxNode If lambda.Expression.Kind = BoundKind.RangeVariableAssignment Then location = DirectCast(lambda.Expression, BoundRangeVariableAssignment).Value.Syntax Else location = lambda.Expression.Syntax End If ReportDiagnostic(diagnostics, location, ERRID.ERR_RestrictedType1, restrictedType) End If End If If lambda.LambdaSymbol.ReturnType Is LambdaSymbol.ReturnTypePendingDelegate Then lambda = lambda.Update(lambda.LambdaSymbol, lambda.RangeVariables, ApplyImplicitConversion(lambda.Expression.Syntax, delegateReturnType, lambda.Expression, diagnostics, If(delegateReturnType.IsBooleanType(), lambda.ExprIsOperandOfConditionalBranch, False)), exprIsOperandOfConditionalBranch:=False) Else lambda = lambda.Update(lambda.LambdaSymbol, lambda.RangeVariables, lambda.Expression, exprIsOperandOfConditionalBranch:=False) End If If conversionSemantics = SyntaxKind.CTypeKeyword Then Return New BoundConversion(tree, lambda, convKind, False, isExplicit, targetType).MakeCompilerGenerated() ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then Return New BoundDirectCast(tree, lambda, convKind, targetType).MakeCompilerGenerated() ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then Return New BoundTryCast(tree, lambda, convKind, targetType).MakeCompilerGenerated() End If Throw ExceptionUtilities.UnexpectedValue(conversionSemantics) End Function Private Function ReclassifyInterpolatedStringExpression(conversionSemantics As SyntaxKind, tree As SyntaxNode, convKind As ConversionKind, isExplicit As Boolean, node As BoundInterpolatedStringExpression, targetType As TypeSymbol, diagnostics As DiagnosticBag) As BoundExpression If (convKind And ConversionKind.InterpolatedString) = ConversionKind.InterpolatedString Then Debug.Assert(targetType.Equals(Compilation.GetWellKnownType(WellKnownType.System_IFormattable)) OrElse targetType.Equals(Compilation.GetWellKnownType(WellKnownType.System_FormattableString))) Return New BoundConversion(tree, node, ConversionKind.InterpolatedString, False, isExplicit, targetType) End If Return node End Function Private Function ReclassifyTupleLiteral( convKind As ConversionKind, tree As SyntaxNode, isExplicit As Boolean, sourceTuple As BoundTupleLiteral, destination As TypeSymbol, diagnostics As DiagnosticBag) As BoundExpression ' We have a successful tuple conversion rather than producing a separate conversion node ' which is a conversion on top of a tuple literal, tuple conversion is an element-wise conversion of arguments. Dim isNullableTupleConversion = (convKind And ConversionKind.Nullable) <> 0 Debug.Assert(Not isNullableTupleConversion OrElse destination.IsNullableType()) Dim targetType = destination If isNullableTupleConversion Then targetType = destination.GetNullableUnderlyingType() End If Dim arguments = sourceTuple.Arguments If Not targetType.IsTupleOrCompatibleWithTupleOfCardinality(arguments.Length) Then Return sourceTuple End If If targetType.IsTupleType Then Dim destTupleType = DirectCast(targetType, TupleTypeSymbol) TupleTypeSymbol.ReportNamesMismatchesIfAny(targetType, sourceTuple, diagnostics) ' do not lose the original element names in the literal if different from names in the target ' Come back to this, what about locations? (https:'github.com/dotnet/roslyn/issues/11013) targetType = destTupleType.WithElementNames(sourceTuple.ArgumentNamesOpt) End If Dim convertedArguments = ArrayBuilder(Of BoundExpression).GetInstance(arguments.Length) Dim targetElementTypes As ImmutableArray(Of TypeSymbol) = targetType.GetElementTypesOfTupleOrCompatible() Debug.Assert(targetElementTypes.Length = arguments.Length, "converting a tuple literal to incompatible type?") For i As Integer = 0 To arguments.Length - 1 Dim argument = arguments(i) Dim destType = targetElementTypes(i) convertedArguments.Add(ApplyConversion(argument.Syntax, destType, argument, isExplicit, diagnostics)) Next Dim result As BoundExpression = New BoundConvertedTupleLiteral( sourceTuple.Syntax, sourceTuple.Type, convertedArguments.ToImmutableAndFree(), targetType) If sourceTuple.Type <> destination AndAlso convKind <> Nothing Then ' literal cast is applied to the literal result = New BoundConversion(sourceTuple.Syntax, result, convKind, checked:=False, explicitCastInCode:=isExplicit, type:=destination) End If ' If we had a cast in the code, keep conversion in the tree. ' even though the literal is already converted to the target type. If isExplicit Then result = New BoundConversion( tree, result, ConversionKind.Identity, checked:=False, explicitCastInCode:=isExplicit, type:=destination) End If Return result End Function Private Sub WarnOnNarrowingConversionBetweenSealedClassAndAnInterface( convKind As ConversionKind, location As SyntaxNode, sourceType As TypeSymbol, targetType As TypeSymbol, diagnostics As DiagnosticBag ) If Conversions.IsNarrowingConversion(convKind) Then Dim interfaceType As TypeSymbol = Nothing Dim classType As NamedTypeSymbol = Nothing If sourceType.IsInterfaceType() Then If targetType.IsClassType() Then interfaceType = sourceType classType = DirectCast(targetType, NamedTypeSymbol) End If ElseIf sourceType.IsClassType() AndAlso targetType.IsInterfaceType() Then interfaceType = targetType classType = DirectCast(sourceType, NamedTypeSymbol) End If If classType IsNot Nothing AndAlso interfaceType IsNot Nothing AndAlso classType.IsNotInheritable AndAlso Not classType.IsComImport() AndAlso Not Conversions.IsWideningConversion(Conversions.ClassifyDirectCastConversion(classType, interfaceType, Nothing)) Then ' Report specific warning if converting IEnumerable(Of XElement) to String. If (targetType.SpecialType = SpecialType.System_String) AndAlso IsIEnumerableOfXElement(sourceType, Nothing) Then ReportDiagnostic(diagnostics, location, ERRID.WRN_UseValueForXmlExpression3, sourceType, targetType, sourceType) Else ReportDiagnostic(diagnostics, location, ERRID.WRN_InterfaceConversion2, sourceType, targetType) End If End If End If End Sub Private Function IsIEnumerableOfXElement(type As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As Boolean Return type.IsOrImplementsIEnumerableOfXElement(Compilation, useSiteDiagnostics) End Function Private Sub ReportNoConversionError( location As SyntaxNode, sourceType As TypeSymbol, targetType As TypeSymbol, diagnostics As DiagnosticBag, Optional copybackConversionParamName As String = Nothing ) If sourceType.IsArrayType() AndAlso targetType.IsArrayType() Then Dim sourceArray = DirectCast(sourceType, ArrayTypeSymbol) Dim targetArray = DirectCast(targetType, ArrayTypeSymbol) Dim sourceElement = sourceArray.ElementType Dim targetElement = targetArray.ElementType If sourceArray.Rank <> targetArray.Rank Then ReportDiagnostic(diagnostics, location, ERRID.ERR_ConvertArrayRankMismatch2, sourceType, targetType) ElseIf sourceArray.IsSZArray <> targetArray.IsSZArray Then ReportDiagnostic(diagnostics, location, ERRID.ERR_TypeMismatch2, sourceType, targetType) ElseIf Not (sourceElement.IsErrorType() OrElse targetElement.IsErrorType()) Then Dim elemConv = Conversions.ClassifyDirectCastConversion(sourceElement, targetElement, Nothing) If Not Conversions.IsIdentityConversion(elemConv) AndAlso (targetElement.IsObjectType() OrElse targetElement.SpecialType = SpecialType.System_ValueType) AndAlso Not sourceElement.IsReferenceType() Then ReportDiagnostic(diagnostics, location, ERRID.ERR_ConvertObjectArrayMismatch3, sourceType, targetType, sourceElement) ElseIf Not Conversions.IsIdentityConversion(elemConv) AndAlso Not (Conversions.IsWideningConversion(elemConv) AndAlso (elemConv And (ConversionKind.Reference Or ConversionKind.Value Or ConversionKind.TypeParameter)) <> 0) Then ReportDiagnostic(diagnostics, location, ERRID.ERR_ConvertArrayMismatch4, sourceType, targetType, sourceElement, targetElement) Else ReportDiagnostic(diagnostics, location, ERRID.ERR_TypeMismatch2, sourceType, targetType) End If End If ElseIf sourceType.IsDateTimeType() AndAlso targetType.IsDoubleType() Then ReportDiagnostic(diagnostics, location, ERRID.ERR_DateToDoubleConversion) ElseIf targetType.IsDateTimeType() AndAlso sourceType.IsDoubleType() Then ReportDiagnostic(diagnostics, location, ERRID.ERR_DoubleToDateConversion) ElseIf targetType.IsCharType() AndAlso sourceType.IsIntegralType() Then ReportDiagnostic(diagnostics, location, ERRID.ERR_IntegralToCharTypeMismatch1, sourceType) ElseIf sourceType.IsCharType() AndAlso targetType.IsIntegralType() Then ReportDiagnostic(diagnostics, location, ERRID.ERR_CharToIntegralTypeMismatch1, targetType) ElseIf copybackConversionParamName IsNot Nothing Then ReportDiagnostic(diagnostics, location, ERRID.ERR_CopyBackTypeMismatch3, copybackConversionParamName, sourceType, targetType) ElseIf sourceType.IsInterfaceType() AndAlso targetType.IsValueType() AndAlso IsIEnumerableOfXElement(sourceType, Nothing) Then ReportDiagnostic(diagnostics, location, ERRID.ERR_TypeMismatchForXml3, sourceType, targetType, sourceType) Else ReportDiagnostic(diagnostics, location, ERRID.ERR_TypeMismatch2, sourceType, targetType) End If End Sub End Class End Namespace
mmitche/roslyn
src/Compilers/VisualBasic/Portable/Binding/Binder_Conversions.vb
Visual Basic
apache-2.0
102,177
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.18444 ' ' 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("JakMark.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
alzwded/JakMark
JakMark/My Project/Resources.Designer.vb
Visual Basic
bsd-2-clause
2,716
'============================================================================== ' MyGeneration.dOOdads ' ' SQLiteEntity.vb ' Version 5.0 ' Updated - 09/15/2005 '------------------------------------------------------------------------------ ' Copyright 2004, 2005 by MyGeneration Software. ' All Rights Reserved. ' ' Permission to use, copy, modify, and distribute this software and its ' documentation for any purpose and without fee is hereby granted, ' provided that the above copyright notice appear in all copies and that ' both that copyright notice and this permission notice appear in ' supporting documentation. ' ' MYGENERATION SOFTWARE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS ' SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY ' AND FITNESS, IN NO EVENT SHALL MYGENERATION SOFTWARE BE LIABLE FOR ANY ' SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ' WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, ' WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER ' TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE ' OR PERFORMANCE OF THIS SOFTWARE. '============================================================================== Imports System.Data Imports System.Data.Common Imports Finisar.SQLite Namespace MyGeneration.dOOdads Public Class SQLiteEntity Inherits BusinessEntity Friend Overrides Function ConvertIDbDataAdapter(ByVal dataAdapter As IDbDataAdapter) As DbDataAdapter Return CType(dataAdapter, DbDataAdapter) End Function Friend Overrides Function CreateDynamicQuery(ByVal entity As BusinessEntity) As DynamicQuery Return New SQLiteDynamicQuery(entity) End Function Friend Overloads Overrides Function CreateIDataParameter() As IDataParameter Return New SQLiteParameter End Function Friend Overloads Overrides Function CreateIDataParameter(ByVal name As String, ByVal value As Object) As IDataParameter Dim p As New SQLiteParameter p.ParameterName = name p.Value = value Return p End Function Friend Overrides Function CreateIDbCommand() As IDbCommand Return New SQLiteCommand End Function Friend Overrides Function CreateIDbConnection() As IDbConnection Return New SQLiteConnection End Function Friend Overrides Function CreateIDbDataAdapter() As IDbDataAdapter Return New SQLiteDataAdapter End Function #Region "@@IDENTITY Logic" ' Overloaded in the generated class Public Overridable Function GetAutoKeyColumns() As String Return "" End Function ' Called just before the Save() is truly executed Protected Overrides Sub HookupRowUpdateEvents(ByVal adapter As DbDataAdapter) ' We only bother hooking up the event if we have an AutoKey If Me.GetAutoKeyColumns().Length > 0 Then Dim da As SQLiteDataAdapter = CType(adapter, SQLiteDataAdapter) AddHandler da.RowUpdated, AddressOf OnRowUpdated End If End Sub ' If it's an Insert we fetch the @@Identity value and stuff it in the proper column Protected Sub OnRowUpdated(ByVal sender As Object, ByVal e As RowUpdatedEventArgs) Try If e.Status = UpdateStatus.[Continue] AndAlso e.StatementType = StatementType.Insert Then Dim txMgr As TransactionMgr = TransactionMgr.ThreadTransactionMgr() Dim s As String Dim seperator As Char = CType(";", Char) Dim identityCols As String() = Me.GetAutoKeyColumns().Split(seperator) Dim cmd As SQLiteCommand = New SQLiteCommand Dim col As String For Each col In identityCols cmd.CommandText = "SELECT last_insert_rowid()" ' We make sure we enlist in the ongoing transaction, otherwise, we ' would most likely deadlock txMgr.Enlist(cmd, Me) Dim o As Object = cmd.ExecuteScalar() ' Get the Identity Value txMgr.DeEnlist(cmd, Me) If Not o Is Nothing Then e.Row(col) = o End If Next e.Row.AcceptChanges() End If Catch ex As Exception End Try End Sub #End Region Protected Overrides Function _LoadFromRawSql(ByVal rawSql As String, ByVal ParamArray parameters() As Object) As IDbCommand Dim i As Integer = 0 Dim token As String = "" Dim sIndex As String = "" Dim param As String = "" Dim cmd As SQLiteCommand = New SQLiteCommand Dim o As Object For Each o In parameters sIndex = i.ToString() token = "{" + sIndex + "}" param = "@p" + sIndex rawSql = rawSql.Replace(token, param) Dim p As SQLiteParameter = New SQLiteParameter p.ParameterName = param p.Value = o cmd.Parameters.Add(p) i = i + 1 Next cmd.CommandText = rawSql Return cmd End Function End Class End Namespace
cafephin/mygeneration
src/doodads/VB.NET/MyGeneration.dOOdads/DbAdapters/SQLiteEntity.vb
Visual Basic
bsd-3-clause
5,672
Imports InfoSoftGlobal Partial Class UTF8Examples_DataXML Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim strXML As String ' Create an XML data document in a string variable strXML = "<chart caption='Monthly Sales Summary' subcaption='For the year 2008' " strXML = strXML + " xAxisName='Month' yAxisName='Sales' numberPrefix='$' showNames='1'" strXML = strXML + " showValues='0' showColumnShadow='1' animation='1'" strXML = strXML + " baseFontColor='666666' lineColor='FF5904' lineAlpha='85'" strXML = strXML + " valuePadding='10' labelDisplay='rotate' useRoundEdges='1'>" strXML = strXML + "<set label='januári' value='17400' />" strXML = strXML + "<set label='Fevruários' value='19800' />" strXML = strXML + "<set label='مارس' value='21800' />" strXML = strXML + "<set label='أبريل' value='23800' />" strXML = strXML + "<set label='五月' value='29600' />" strXML = strXML + "<set label='六月' value='27600' />" strXML = strXML + "<set label='תִּשׁרִי' value='31800' />" strXML = strXML + "<set label='Marešwān' value='39700' />" strXML = strXML + "<set label='settèmbre' value='37800' />" strXML = strXML + "<set label='ottàgono' value='21900' />" strXML = strXML + "<set label='novèmbre' value='32900' />" strXML = strXML + "<set label='décembre' value='39800' />" strXML = strXML + "<styles><definition><style name='myCaptionFont' type='font' size='12'/></definition>" strXML = strXML + "<application><apply toObject='datalabels' styles='myCaptionFont' /></application></styles>" strXML = strXML + "</chart>" Literal1.Text = FusionCharts.RenderChart("../FusionCharts/Column2D.swf", "", strXML, "myFirst", "500", "400", False, False) End Sub End Class
TechFor/agile
public/js/FusionCharts/Code/VB_NET/UTF8Examples/DataXML.aspx.vb
Visual Basic
bsd-3-clause
1,997
' 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 Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class CodeVariableTests Inherits AbstractCodeVariableTests #Region "GetStartPoint() tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint1() Dim code = <Code> Class C Dim i$$ As Integer End Class </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=9, absoluteOffset:=17, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20))) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_Attribute() Dim code = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim i$$ As Integer End Class </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=9, absoluteOffset:=49, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31))) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_EnumMember() Dim code = <Code> Enum E A$$ End Enum </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5))) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_EnumMember_Attribute() Dim code = <Code> Enum E &lt;System.CLSCompliant(True)&gt; A$$ End Enum </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31))) End Sub #End Region #Region "GetEndPoint() tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint1() Dim code = <Code> Class C Dim i$$ As Integer End Class </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=10, absoluteOffset:=18, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20))) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_Attribute() Dim code = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim i$$ As Integer End Class </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=40, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=40, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=10, absoluteOffset:=50, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20))) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_EnumMember() Dim code = <Code> Enum E A$$ End Enum </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5))) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_EnumMember_Attribute() Dim code = <Code> Enum E &lt;System.CLSCompliant(True)&gt; A$$ End Enum </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=39, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=39, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5))) End Sub #End Region #Region "Access tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess1() Dim code = <Code> Class C Dim $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess2() Dim code = <Code> Class C Private $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess3() Dim code = <Code> Class C Protected $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProtected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess4() Dim code = <Code> Class C Protected Friend $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess5() Dim code = <Code> Class C Friend $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess6() Dim code = <Code> Class C Public $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess7() Dim code = <Code> Enum E $$Foo End Enum </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Comment tests" <WorkItem(638909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638909")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment1() Dim code = <Code> Class C ' Foo Dim $$i As Integer End Class </Code> Dim result = " Foo" TestComment(code, result) End Sub #End Region #Region "ConstKind tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind1() Dim code = <Code> Enum E $$Foo End Enum </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind2() Dim code = <Code> Class C Dim $$x As Integer End Class </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind3() Dim code = <Code> Class C Const $$x As Integer End Class </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind4() Dim code = <Code> Class C ReadOnly $$x As Integer End Class </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind5() Dim code = <Code> Class C ReadOnly Const $$x As Integer End Class </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub #End Region #Region "InitExpression tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression1() Dim code = <Code> Class C Dim i$$ As Integer = 42 End Class </Code> TestInitExpression(code, "42") End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression2() Dim code = <Code> Class C Const $$i As Integer = 19 + 23 End Class </Code> TestInitExpression(code, "19 + 23") End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression3() Dim code = <Code> Enum E $$i = 19 + 23 End Enum </Code> TestInitExpression(code, "19 + 23") End Sub #End Region #Region "IsConstant tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant1() Dim code = <Code> Enum E $$Foo End Enum </Code> TestIsConstant(code, True) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant2() Dim code = <Code> Class C Dim $$x As Integer End Class </Code> TestIsConstant(code, False) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant3() Dim code = <Code> Class C Const $$x As Integer = 0 End Class </Code> TestIsConstant(code, True) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant4() Dim code = <Code> Class C ReadOnly $$x As Integer = 0 End Class </Code> TestIsConstant(code, True) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant5() Dim code = <Code> Class C WithEvents $$x As Integer End Class </Code> TestIsConstant(code, False) End Sub #End Region #Region "IsShared tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared1() Dim code = <Code> Class C Dim $$x As Integer End Class </Code> TestIsShared(code, False) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared2() Dim code = <Code> Class C Shared $$x As Integer End Class </Code> TestIsShared(code, True) End Sub #End Region #Region "Name tests" <WorkItem(638224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638224")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName_EnumMember() Dim code = <Code> Enum SomeEnum A$$ End Enum </Code> TestName(code, "A") End Sub #End Region #Region "Prototype tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_UniqueSignature() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature, "F:N.C.x") End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName1() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "Private C.x") End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName2() Dim code = <Code> Namespace N Class C(Of T) Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "Private C(Of T).x") End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName3() Dim code = <Code> Namespace N Class C Public ReadOnly $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "Public C.x") End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName_InitExpression() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "Private C.x = 42") End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_FullName1() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "Private N.C.x") End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_FullName2() Dim code = <Code> Namespace N Class C(Of T) Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "Private N.C(Of T).x") End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_FullName_InitExpression() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "Private N.C.x = 42") End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_NoName() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeNoName, "Private ") End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_NoName_InitExpression() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeNoName Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "Private = 42") End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_NoName_InitExpression_Type() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeNoName Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "Private As Integer = 42") End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpression_Type_ForAsNew() ' Amusingly, this will *crash* Dev10. Dim code = <Code> Namespace N Class C Dim $$x As New System.Text.StringBuilder End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "Private x As System.Text.StringBuilder") End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Type() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "Private x As Integer") End Sub #End Region #Region "Type tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType1() Dim code = <Code> Class C Dim $$a As Integer End Class </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "Integer", .AsFullName = "System.Int32", .CodeTypeFullName = "System.Int32", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt }) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType2() Dim code = <Code> Class C WithEvents $$a As Object End Class </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "Object", .AsFullName = "System.Object", .CodeTypeFullName = "System.Object", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefObject }) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType3() Dim code = <Code> Class C Private $$a As New Object End Class </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "Object", .AsFullName = "System.Object", .CodeTypeFullName = "System.Object", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefObject }) End Sub #End Region #Region "AddAttribute tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> Imports System Class C Dim $$foo As Integer End Class </Code> Dim expected = <Code><![CDATA[ Imports System Class C <Serializable()> Dim foo As Integer End Class ]]></Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WorkItem(1087167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087167")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code><![CDATA[ Imports System Class C <Serializable> Dim $$foo As Integer End Class ]]></Code> Dim expected = <Code><![CDATA[ Imports System Class C <Serializable> <CLSCompliant(True)> Dim foo As Integer End Class ]]></Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code><![CDATA[ Imports System Class C ''' &lt;summary&gt;&lt;/summary&gt; Dim $$foo As Integer End Class ]]></Code> Dim expected = <Code><![CDATA[ Imports System Class C ''' &lt;summary&gt;&lt;/summary&gt; <CLSCompliant(True)> Dim foo As Integer End Class ]]></Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True"}) End Function #End Region #Region "Set Access tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess1() As Task Dim code = <Code> Enum E $$Foo End Enum </Code> Dim expected = <Code> Enum E Foo End Enum </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess2() As Task Dim code = <Code> Enum E $$Foo End Enum </Code> Dim expected = <Code> Enum E Foo End Enum </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess3() As Task Dim code = <Code> Enum E $$Foo End Enum </Code> Dim expected = <Code> Enum E Foo End Enum </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate, ThrowsArgumentException(Of EnvDTE.vsCMAccess)()) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess1() As Task Dim code = <Code> Class C Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C Public i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess2() As Task Dim code = <Code> Class C Public $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess3() As Task Dim code = <Code> Class C Private $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess4() As Task Dim code = <Code> Class C Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess5() As Task Dim code = <Code> Class C Public $$i As Integer End Class </Code> Dim expected = <Code> Class C Protected Friend i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess6() As Task Dim code = <Code> Class C #Region "Foo" Dim x As Integer #End Region Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C #Region "Foo" Dim x As Integer #End Region Public i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess7() As Task Dim code = <Code> Class C #Region "Foo" Dim x As Integer #End Region Public $$i As Integer End Class </Code> Dim expected = <Code> Class C #Region "Foo" Dim x As Integer #End Region Protected Friend i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess8() As Task Dim code = <Code> Class C #Region "Foo" Dim x As Integer #End Region Public $$i As Integer End Class </Code> Dim expected = <Code> Class C #Region "Foo" Dim x As Integer #End Region Dim i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess9() As Task Dim code = <Code> Class C #Region "Foo" Dim $$x As Integer #End Region End Class </Code> Dim expected = <Code> Class C #Region "Foo" Public x As Integer #End Region End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess10() As Task Dim code = <Code> Class C #Region "Foo" Public $$x As Integer #End Region End Class </Code> Dim expected = <Code> Class C #Region "Foo" Dim x As Integer #End Region End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess11() As Task Dim code = <Code> Class C #Region "Foo" Public $$x As Integer #End Region End Class </Code> Dim expected = <Code> Class C #Region "Foo" Protected Friend x As Integer #End Region End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess12() As Task Dim code = <Code><![CDATA[ Class C #Region "Foo" <Bar> Public $$x As Integer #End Region End Class ]]></Code> Dim expected = <Code><![CDATA[ Class C #Region "Foo" <Bar> Protected Friend x As Integer #End Region End Class ]]></Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess13() As Task Dim code = <Code> Class C #Region "Foo" ' Comment comment comment Public $$x As Integer #End Region End Class </Code> Dim expected = <Code> Class C #Region "Foo" ' Comment comment comment Protected Friend x As Integer #End Region End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess14() As Task Dim code = <Code><![CDATA[ Class C #Region "Foo" ''' <summary> ''' Comment comment comment ''' </summary> Public $$x As Integer #End Region End Class ]]></Code> Dim expected = <Code><![CDATA[ Class C #Region "Foo" ''' <summary> ''' Comment comment comment ''' </summary> Protected Friend x As Integer #End Region End Class ]]></Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess15() As Task Dim code = <Code> Class C Dim $$x As Integer End Class </Code> Dim expected = <Code> Class C Private WithEvents x As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate Or EnvDTE.vsCMAccess.vsCMAccessWithEvents) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess16() As Task Dim code = <Code> Class C Private WithEvents $$x As Integer End Class </Code> Dim expected = <Code> Class C Dim x As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function #End Region #Region "Set ConstKind tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind1() As Task Dim code = <Code> Enum $$Foo End Enum </Code> Dim expected = <Code> Enum Foo End Enum </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone, ThrowsNotImplementedException(Of EnvDTE80.vsCMConstKind)) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind2() As Task Dim code = <Code> Enum $$Foo End Enum </Code> Dim expected = <Code> Enum Foo End Enum </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly, ThrowsNotImplementedException(Of EnvDTE80.vsCMConstKind)) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind3() As Task Dim code = <Code> Enum $$Foo End Enum </Code> Dim expected = <Code> Enum Foo End Enum </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst, ThrowsNotImplementedException(Of EnvDTE80.vsCMConstKind)) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind4() As Task Dim code = <Code> Class C Dim $$x As Integer End Class </Code> Dim expected = <Code> Class C Dim x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind5() As Task Dim code = <Code> Class C Shared $$x As Integer End Class </Code> Dim expected = <Code> Class C Shared x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind6() As Task Dim code = <Code> Class C Dim $$x As Integer End Class </Code> Dim expected = <Code> Class C Const x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind7() As Task Dim code = <Code> Class C Const $$x As Integer End Class </Code> Dim expected = <Code> Class C Dim x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind8() As Task Dim code = <Code> Class C Dim $$x As Integer End Class </Code> Dim expected = <Code> Class C ReadOnly x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind9() As Task Dim code = <Code> Class C ReadOnly $$x As Integer End Class </Code> Dim expected = <Code> Class C Dim x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function #End Region #Region "Set InitExpression tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression1() As Task Dim code = <Code> Class C Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer = 42 End Class </Code> Await TestSetInitExpression(code, expected, "42") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression2() As Task Dim code = <Code> Class C Dim $$i As Integer, j As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer = 42, j As Integer End Class </Code> Await TestSetInitExpression(code, expected, "42") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression3() As Task Dim code = <Code> Class C Dim i As Integer, $$j As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer, j As Integer = 42 End Class </Code> Await TestSetInitExpression(code, expected, "42") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression4() As Task ' The result below is a bit silly, but that's what the legacy Code Model does. Dim code = <Code> Class C Dim $$o As New Object End Class </Code> Dim expected = <Code> Class C Dim o As New Object = 42 End Class </Code> Await TestSetInitExpression(code, expected, "42") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression5() As Task Dim code = <Code> Class C Const $$i As Integer = 0 End Class </Code> Dim expected = <Code> Class C Const i As Integer = 19 + 23 End Class </Code> Await TestSetInitExpression(code, expected, "19 + 23") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression6() As Task Dim code = <Code> Class C Const $$i As Integer = 0 End Class </Code> Dim expected = <Code> Class C Const i As Integer End Class </Code> Await TestSetInitExpression(code, expected, "") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression7() As Task Dim code = <Code> Enum E $$Foo End Enum </Code> Dim expected = <Code> Enum E Foo = 42 End Enum </Code> Await TestSetInitExpression(code, expected, "42") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression8() As Task Dim code = <Code> Enum E $$Foo = 0 End Enum </Code> Dim expected = <Code> Enum E Foo = 42 End Enum </Code> Await TestSetInitExpression(code, expected, "42") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression9() As Task Dim code = <Code> Enum E $$Foo = 0 End Enum </Code> Dim expected = <Code> Enum E Foo End Enum </Code> Await TestSetInitExpression(code, expected, Nothing) End Function #End Region #Region "Set IsConstant tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant1() As Task Dim code = <Code> Class C Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C Const i As Integer End Class </Code> Await TestSetIsConstant(code, expected, True) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant2() As Task Dim code = <Code> Class C Const $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetIsConstant(code, expected, False) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant3() As Task Dim code = <Code> Class C ReadOnly $$i As Integer End Class </Code> Dim expected = <Code> Class C Const i As Integer End Class </Code> Await TestSetIsConstant(code, expected, True) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant4() As Task Dim code = <Code> Class C ReadOnly $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetIsConstant(code, expected, False) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant5() As Task Dim code = <Code> Module C Dim $$i As Integer End Module </Code> Dim expected = <Code> Module C Const i As Integer End Module </Code> Await TestSetIsConstant(code, expected, True) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant6() As Task Dim code = <Code> Enum E $$Foo End Enum </Code> Dim expected = <Code> Enum E Foo End Enum </Code> Await TestSetIsConstant(code, expected, True, ThrowsNotImplementedException(Of Boolean)) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant7() As Task Dim code = <Code> Enum E $$Foo End Enum </Code> Dim expected = <Code> Enum E Foo End Enum </Code> Await TestSetIsConstant(code, expected, False, ThrowsNotImplementedException(Of Boolean)) End Function #End Region #Region "Set IsShared tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared1() As Task Dim code = <Code> Class C Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C Shared i As Integer End Class </Code> Await TestSetIsShared(code, expected, True) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared2() As Task Dim code = <Code> Class C Shared $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetIsShared(code, expected, False) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared3() As Task Dim code = <Code> Class C Private $$i As Integer End Class </Code> Dim expected = <Code> Class C Private Shared i As Integer End Class </Code> Await TestSetIsShared(code, expected, True) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared4() As Task Dim code = <Code> Class C Private Shared $$i As Integer End Class </Code> Dim expected = <Code> Class C Private i As Integer End Class </Code> Await TestSetIsShared(code, expected, False) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared5() As Task Dim code = <Code> Module C Dim $$i As Integer End Module </Code> Dim expected = <Code> Module C Dim i As Integer End Module </Code> Await TestSetIsShared(code, expected, True, ThrowsNotImplementedException(Of Boolean)) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared6() As Task Dim code = <Code> Enum E $$Foo End Enum </Code> Dim expected = <Code> Enum E Foo End Enum </Code> Await TestSetIsShared(code, expected, True, ThrowsNotImplementedException(Of Boolean)) End Function #End Region #Region "Set Name tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> Class C Dim $$Foo As Integer End Class </Code> Dim expected = <Code> Class C Dim Bar As Integer End Class </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName2() As Task Dim code = <Code> Class C #Region "Foo" Dim $$Foo As Integer #End Region End Class </Code> Dim expected = <Code> Class C #Region "Foo" Dim Bar As Integer #End Region End Class </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region #Region "Set Type tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType1() As Task Dim code = <Code> Class C Dim $$a As Integer End Class </Code> Dim expected = <Code> Class C Dim a As Double End Class </Code> Await TestSetTypeProp(code, expected, "double") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType2() As Task Dim code = <Code> Class C Dim $$a, b As Integer End Class </Code> Dim expected = <Code> Class C Dim a, b As Double End Class </Code> Await TestSetTypeProp(code, expected, "double") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType3() As Task Dim code = <Code> Class C Private $$a As New Object End Class </Code> Dim expected = <Code> Class C Private a As New String End Class </Code> Await TestSetTypeProp(code, expected, "String") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType4() As Task Dim code = <Code> Class C Private $$a As New Object, x As Integer = 0 End Class </Code> Dim expected = <Code> Class C Private a As New String, x As Integer = 0 End Class </Code> Await TestSetTypeProp(code, expected, "String") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType5() As Task Dim code = <Code> Class C Private a As New Object, x$$ As Integer = 0 End Class </Code> Dim expected = <Code> Class C Private a As New Object, x As String = 0 End Class </Code> Await TestSetTypeProp(code, expected, "String") End Function #End Region Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
amcasey/roslyn
src/VisualStudio/Core/Test/CodeModel/VisualBasic/CodeVariableTests.vb
Visual Basic
apache-2.0
56,244
' 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 Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim <[UseExportProvider]> Public Class WorkspaceChangedEventTests <WpfTheory> <CombinatorialData> Public Async Function AddingASingleSourceFileRaisesDocumentAdded(addInBatch As Boolean) As Task Using environment = New TestEnvironment() Dim project = environment.ProjectFactory.CreateAndAddToWorkspace("Project", LanguageNames.CSharp) Dim workspaceChangeEvents = New WorkspaceChangeWatcher(environment) Using If(addInBatch, project.CreateBatchScope(), Nothing) project.AddSourceFile("Z:\Test.vb") End Using Dim change = Assert.Single(Await workspaceChangeEvents.GetNewChangeEventsAsync()) Assert.Equal(WorkspaceChangeKind.DocumentAdded, change.Kind) Assert.Equal(project.Id, change.ProjectId) Assert.Equal(environment.Workspace.CurrentSolution.Projects.Single().DocumentIds.Single(), change.DocumentId) End Using End Function <WpfFact> Public Async Function AddingTwoDocumentsInBatchRaisesProjectChanged() As Task Using environment = New TestEnvironment() Dim project = environment.ProjectFactory.CreateAndAddToWorkspace("Project", LanguageNames.CSharp) Dim workspaceChangeEvents = New WorkspaceChangeWatcher(environment) Using project.CreateBatchScope() project.AddSourceFile("Z:\Test1.vb") project.AddSourceFile("Z:\Test2.vb") End Using Dim change = Assert.Single(Await workspaceChangeEvents.GetNewChangeEventsAsync()) Assert.Equal(WorkspaceChangeKind.ProjectChanged, change.Kind) Assert.Equal(project.Id, change.ProjectId) Assert.Null(change.DocumentId) End Using End Function <WpfTheory> <CombinatorialData> Public Async Function AddingASingleAdditionalFileInABatchRaisesDocumentAdded(addInBatch As Boolean) As Task Using environment = New TestEnvironment() Dim project = environment.ProjectFactory.CreateAndAddToWorkspace("Project", LanguageNames.CSharp) Dim workspaceChangeEvents = New WorkspaceChangeWatcher(environment) Using If(addInBatch, project.CreateBatchScope(), Nothing) project.AddAdditionalFile("Z:\Test.vb") End Using Dim change = Assert.Single(Await workspaceChangeEvents.GetNewChangeEventsAsync()) Assert.Equal(WorkspaceChangeKind.AdditionalDocumentAdded, change.Kind) Assert.Equal(project.Id, change.ProjectId) Assert.Equal(environment.Workspace.CurrentSolution.Projects.Single().AdditionalDocumentIds.Single(), change.DocumentId) End Using End Function <WpfTheory> <CombinatorialData> Public Async Function AddingASingleMetadataReferenceRaisesProjectChanged(addInBatch As Boolean) As Task Using environment = New TestEnvironment() Dim project = environment.ProjectFactory.CreateAndAddToWorkspace("Project", LanguageNames.CSharp) Dim workspaceChangeEvents = New WorkspaceChangeWatcher(environment) Using If(addInBatch, project.CreateBatchScope(), Nothing) project.AddMetadataReference("Z:\Test.dll", MetadataReferenceProperties.Assembly) End Using Dim change = Assert.Single(Await workspaceChangeEvents.GetNewChangeEventsAsync()) Assert.Equal(WorkspaceChangeKind.ProjectChanged, change.Kind) Assert.Equal(project.Id, change.ProjectId) Assert.Null(change.DocumentId) End Using End Function <WpfFact> <WorkItem(34309, "https://github.com/dotnet/roslyn/issues/34309")> Public Async Function StartingAndEndingBatchWithNoChangesDoesNothing() As Task Using environment = New TestEnvironment() Dim project = environment.ProjectFactory.CreateAndAddToWorkspace("Project", LanguageNames.CSharp) Dim workspaceChangeEvents = New WorkspaceChangeWatcher(environment) Dim startingSolution = environment.Workspace.CurrentSolution project.CreateBatchScope().Dispose() Assert.Empty(Await workspaceChangeEvents.GetNewChangeEventsAsync()) Assert.Same(startingSolution, environment.Workspace.CurrentSolution) End Using End Function End Class End Namespace
genlu/roslyn
src/VisualStudio/Core/Test/ProjectSystemShim/VisualStudioProjectTests/WorkspaceChangedEventTests.vb
Visual Basic
mit
5,137
' 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.Xml.Linq Imports Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion Imports Microsoft.CodeAnalysis.BraceCompletion.AbstractBraceCompletionService Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticCompletion Public Class AutomaticInterpolatedStringExpressionCompletionTests Inherits AbstractAutomaticBraceCompletionTests <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Sub TestCreation() Using session = CreateSession("$$") Assert.NotNull(session) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Sub TestInvalidLocation_String() Dim code = <code>Class C Dim s As String = "$$ End Class</code> Using session = CreateSession(code) Assert.Null(session) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Sub TestInvalidLocation_Comment() Dim code = <code>Class C ' $$ End Class</code> Using session = CreateSession(code) Assert.Null(session) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Sub TestInvalidLocation_DocComment() Dim code = <code>Class C ''' $$ End Class</code> Using session = CreateSession(code) Assert.Null(session) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Sub TestAfterDollarSign() Dim code = <code>Class C Sub M() Dim s = $$$ End Sub End Class</code> Using session = CreateSession(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Sub Friend Overloads Shared Function CreateSession(code As XElement) As Holder Return CreateSession(code.NormalizedValue()) End Function Friend Overloads Shared Function CreateSession(code As String) As Holder Return AbstractAutomaticBraceCompletionTests.CreateSession( TestWorkspace.CreateVisualBasic(code), DoubleQuote.OpenCharacter, DoubleQuote.CloseCharacter) End Function End Class End Namespace
AmadeusW/roslyn
src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticInterpolatedStringExpressionCompletionTests.vb
Visual Basic
apache-2.0
2,858
Imports SistFoncreagro.BussinessEntities Public Interface IProveedorDetalleCotizacionRepository Sub SaveProveedorDetalleCotizacion(ByVal proveedorDetalleCoti As ProveedorDetalleCotizacion) Sub SaveProveedorDetalleCotizacion1(ByVal proveedorDetalleCoti As List(Of ProveedorDetalleCotizacion)) Sub UpdateProveedorDetalleCotizacion(ByVal proveedorDetalleCoti As ProveedorDetalleCotizacion) Sub UpdateProveedorDetalleCotizacion1(ByVal proveedorDetalleCoti As List(Of ProveedorDetalleCotizacion)) Sub DeleteProveedor(ByVal proveedorDetCot As ProveedorDetalleCotizacion) Sub DeleteProveedor1(ByVal proveedorDetCot As List(Of ProveedorDetalleCotizacion)) Function GetAllFromProveedorDetalleCotizacionByIdDetalleReqCotizacion(ByVal idDetalleReqCotizacion As Int32) As List(Of ProveedorDetalleCotizacion) Sub UpdateIgvCotizacion(ByVal IdDetalleRequerimiento As Int32, ByVal valor As Boolean) End Interface
crackper/SistFoncreagro
SistFoncreagro.DataAccess/IProveedorDetalleCotizacionRepository.vb
Visual Basic
mit
932
Imports System.ComponentModel Imports System.Drawing Imports System.Windows.Forms Imports Telerik.Reporting Imports Telerik.Reporting.Drawing Partial Public Class RepNota26 Inherits Telerik.Reporting.Report Public Sub New() InitializeComponent() End Sub End Class
crackper/SistFoncreagro
SistFoncreagro.Report/RepNota26.vb
Visual Basic
mit
284
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class formExtras 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.components = New System.ComponentModel.Container() Me.DataGridView1 = New System.Windows.Forms.DataGridView() Me.MonthCalendar1 = New System.Windows.Forms.MonthCalendar() Me.RadioButton1 = New System.Windows.Forms.RadioButton() Me.RadioButton2 = New System.Windows.Forms.RadioButton() Me.PictureBox1 = New System.Windows.Forms.PictureBox() Me.SIDlbl = New System.Windows.Forms.Label() Me.S_ID = New System.Windows.Forms.TextBox() Me.NAMElbl = New System.Windows.Forms.Label() Me.IDNOlbl = New System.Windows.Forms.Label() Me.BHAWANlbl = New System.Windows.Forms.Label() Me.ROOMNOlbl = New System.Windows.Forms.Label() Me.SNAME = New System.Windows.Forms.Label() Me.ID = New System.Windows.Forms.Label() Me.ROOM = New System.Windows.Forms.Label() Me.BHAWAN = New System.Windows.Forms.Label() Me.I1lbl = New System.Windows.Forms.Label() Me.I2lbl = New System.Windows.Forms.Label() Me.I3lbl = New System.Windows.Forms.Label() Me.I4lbl = New System.Windows.Forms.Label() Me.I5lbl = New System.Windows.Forms.Label() Me.ICODE1 = New System.Windows.Forms.TextBox() Me.ICODE2 = New System.Windows.Forms.TextBox() Me.ICODE3 = New System.Windows.Forms.TextBox() Me.ICODE5 = New System.Windows.Forms.TextBox() Me.ICODE4 = New System.Windows.Forms.TextBox() Me.Label15 = New System.Windows.Forms.Label() Me.Confirm = New System.Windows.Forms.Button() Me.Clear = New System.Windows.Forms.Button() Me.Button3 = New System.Windows.Forms.Button() Me.ItemNameHeadlbl = New System.Windows.Forms.Label() Me.INAME1 = New System.Windows.Forms.Label() Me.INAME2 = New System.Windows.Forms.Label() Me.INAME4 = New System.Windows.Forms.Label() Me.INAME3 = New System.Windows.Forms.Label() Me.INAME5 = New System.Windows.Forms.Label() Me.PRICE5 = New System.Windows.Forms.Label() Me.PRICE4 = New System.Windows.Forms.Label() Me.PRICE3 = New System.Windows.Forms.Label() Me.PRICE2 = New System.Windows.Forms.Label() Me.PRICE1 = New System.Windows.Forms.Label() Me.Label6 = New System.Windows.Forms.Label() Me.QTY1 = New System.Windows.Forms.TextBox() Me.QTY2 = New System.Windows.Forms.TextBox() Me.QTY3 = New System.Windows.Forms.TextBox() Me.QTY4 = New System.Windows.Forms.TextBox() Me.QTY5 = New System.Windows.Forms.TextBox() Me.Label1 = New System.Windows.Forms.Label() Me.TAX5 = New System.Windows.Forms.Label() Me.TAX4 = New System.Windows.Forms.Label() Me.TAX3 = New System.Windows.Forms.Label() Me.TAX2 = New System.Windows.Forms.Label() Me.TAX1 = New System.Windows.Forms.Label() Me.PrintDocument1 = New System.Drawing.Printing.PrintDocument() Me.curr_qty1 = New System.Windows.Forms.Label() Me.curr_qty2 = New System.Windows.Forms.Label() Me.curr_qty4 = New System.Windows.Forms.Label() Me.curr_qty3 = New System.Windows.Forms.Label() Me.curr_qty5 = New System.Windows.Forms.Label() Me.lblQtyInStore = New System.Windows.Forms.Label() Me.Timer1 = New System.Windows.Forms.Timer(Me.components) Me.countdown = New System.Windows.Forms.Label() Me.Label2 = New System.Windows.Forms.Label() Me.Sub_total = New System.Windows.Forms.Label() Me.Button1 = New System.Windows.Forms.Button() Me.PrintDocument2 = New System.Drawing.Printing.PrintDocument() Me.Button2 = New System.Windows.Forms.Button() Me.pit2 = New System.Windows.Forms.TextBox() Me.Label3 = New System.Windows.Forms.Label() CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'DataGridView1 ' Me.DataGridView1.AllowUserToAddRows = False Me.DataGridView1.AllowUserToDeleteRows = False Me.DataGridView1.AllowUserToResizeRows = False Me.DataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize Me.DataGridView1.Location = New System.Drawing.Point(18, 12) Me.DataGridView1.Name = "DataGridView1" Me.DataGridView1.RowHeadersVisible = False Me.DataGridView1.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.AutoSizeToFirstHeader Me.DataGridView1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical Me.DataGridView1.ShowEditingIcon = False Me.DataGridView1.Size = New System.Drawing.Size(655, 349) Me.DataGridView1.TabIndex = 101 ' 'MonthCalendar1 ' Me.MonthCalendar1.Location = New System.Drawing.Point(684, 13) Me.MonthCalendar1.Name = "MonthCalendar1" Me.MonthCalendar1.TabIndex = 100 ' 'RadioButton1 ' Me.RadioButton1.AutoSize = True Me.RadioButton1.Checked = True Me.RadioButton1.Location = New System.Drawing.Point(918, 67) Me.RadioButton1.Name = "RadioButton1" Me.RadioButton1.Size = New System.Drawing.Size(71, 17) Me.RadioButton1.TabIndex = 200 Me.RadioButton1.TabStop = True Me.RadioButton1.Text = "Day Wise" Me.RadioButton1.UseVisualStyleBackColor = True ' 'RadioButton2 ' Me.RadioButton2.AutoSize = True Me.RadioButton2.Location = New System.Drawing.Point(918, 102) Me.RadioButton2.Name = "RadioButton2" Me.RadioButton2.Size = New System.Drawing.Size(82, 17) Me.RadioButton2.TabIndex = 201 Me.RadioButton2.Text = "Month Wise" Me.RadioButton2.UseVisualStyleBackColor = True ' 'PictureBox1 ' Me.PictureBox1.Location = New System.Drawing.Point(685, 186) Me.PictureBox1.Name = "PictureBox1" Me.PictureBox1.Size = New System.Drawing.Size(227, 175) Me.PictureBox1.TabIndex = 4 Me.PictureBox1.TabStop = False ' 'SIDlbl ' Me.SIDlbl.AutoSize = True Me.SIDlbl.Location = New System.Drawing.Point(27, 386) Me.SIDlbl.Name = "SIDlbl" Me.SIDlbl.Size = New System.Drawing.Size(25, 13) Me.SIDlbl.TabIndex = 5 Me.SIDlbl.Text = "SID" ' 'S_ID ' Me.S_ID.Location = New System.Drawing.Point(107, 383) Me.S_ID.Name = "S_ID" Me.S_ID.Size = New System.Drawing.Size(100, 20) Me.S_ID.TabIndex = 0 ' 'NAMElbl ' Me.NAMElbl.AutoSize = True Me.NAMElbl.Location = New System.Drawing.Point(27, 425) Me.NAMElbl.Name = "NAMElbl" Me.NAMElbl.Size = New System.Drawing.Size(38, 13) Me.NAMElbl.TabIndex = 7 Me.NAMElbl.Text = "NAME" ' 'IDNOlbl ' Me.IDNOlbl.AutoSize = True Me.IDNOlbl.Location = New System.Drawing.Point(27, 467) Me.IDNOlbl.Name = "IDNOlbl" Me.IDNOlbl.Size = New System.Drawing.Size(34, 13) Me.IDNOlbl.TabIndex = 9 Me.IDNOlbl.Text = "IDNO" ' 'BHAWANlbl ' Me.BHAWANlbl.AutoSize = True Me.BHAWANlbl.Location = New System.Drawing.Point(27, 505) Me.BHAWANlbl.Name = "BHAWANlbl" Me.BHAWANlbl.Size = New System.Drawing.Size(55, 13) Me.BHAWANlbl.TabIndex = 11 Me.BHAWANlbl.Text = "BHAWAN" ' 'ROOMNOlbl ' Me.ROOMNOlbl.AutoSize = True Me.ROOMNOlbl.Location = New System.Drawing.Point(27, 544) Me.ROOMNOlbl.Name = "ROOMNOlbl" Me.ROOMNOlbl.Size = New System.Drawing.Size(62, 13) Me.ROOMNOlbl.TabIndex = 13 Me.ROOMNOlbl.Text = "ROOM NO." ' 'SNAME ' Me.SNAME.AutoSize = True Me.SNAME.Location = New System.Drawing.Point(104, 425) Me.SNAME.Name = "SNAME" Me.SNAME.Size = New System.Drawing.Size(17, 13) Me.SNAME.TabIndex = 14 Me.SNAME.Text = """""" ' 'ID ' Me.ID.AutoSize = True Me.ID.Location = New System.Drawing.Point(104, 464) Me.ID.Name = "ID" Me.ID.Size = New System.Drawing.Size(17, 13) Me.ID.TabIndex = 15 Me.ID.Text = """""" ' 'ROOM ' Me.ROOM.AutoSize = True Me.ROOM.Location = New System.Drawing.Point(104, 544) Me.ROOM.Name = "ROOM" Me.ROOM.Size = New System.Drawing.Size(17, 13) Me.ROOM.TabIndex = 17 Me.ROOM.Text = """""" ' 'BHAWAN ' Me.BHAWAN.AutoSize = True Me.BHAWAN.Location = New System.Drawing.Point(104, 505) Me.BHAWAN.Name = "BHAWAN" Me.BHAWAN.Size = New System.Drawing.Size(17, 13) Me.BHAWAN.TabIndex = 16 Me.BHAWAN.Text = """""" ' 'I1lbl ' Me.I1lbl.AutoSize = True Me.I1lbl.Location = New System.Drawing.Point(248, 401) Me.I1lbl.Name = "I1lbl" Me.I1lbl.Size = New System.Drawing.Size(42, 13) Me.I1lbl.TabIndex = 18 Me.I1lbl.Text = "ITEM 1" ' 'I2lbl ' Me.I2lbl.AutoSize = True Me.I2lbl.Location = New System.Drawing.Point(248, 440) Me.I2lbl.Name = "I2lbl" Me.I2lbl.Size = New System.Drawing.Size(42, 13) Me.I2lbl.TabIndex = 19 Me.I2lbl.Text = "ITEM 2" ' 'I3lbl ' Me.I3lbl.AutoSize = True Me.I3lbl.Location = New System.Drawing.Point(248, 479) Me.I3lbl.Name = "I3lbl" Me.I3lbl.Size = New System.Drawing.Size(42, 13) Me.I3lbl.TabIndex = 20 Me.I3lbl.Text = "ITEM 3" ' 'I4lbl ' Me.I4lbl.AutoSize = True Me.I4lbl.Location = New System.Drawing.Point(248, 520) Me.I4lbl.Name = "I4lbl" Me.I4lbl.Size = New System.Drawing.Size(42, 13) Me.I4lbl.TabIndex = 21 Me.I4lbl.Text = "ITEM 4" ' 'I5lbl ' Me.I5lbl.AutoSize = True Me.I5lbl.Location = New System.Drawing.Point(248, 559) Me.I5lbl.Name = "I5lbl" Me.I5lbl.Size = New System.Drawing.Size(42, 13) Me.I5lbl.TabIndex = 22 Me.I5lbl.Text = "ITEM 5" ' 'ICODE1 ' Me.ICODE1.Enabled = False Me.ICODE1.Location = New System.Drawing.Point(329, 398) Me.ICODE1.Name = "ICODE1" Me.ICODE1.Size = New System.Drawing.Size(100, 20) Me.ICODE1.TabIndex = 1 ' 'ICODE2 ' Me.ICODE2.Enabled = False Me.ICODE2.Location = New System.Drawing.Point(329, 437) Me.ICODE2.Name = "ICODE2" Me.ICODE2.Size = New System.Drawing.Size(100, 20) Me.ICODE2.TabIndex = 3 ' 'ICODE3 ' Me.ICODE3.Enabled = False Me.ICODE3.Location = New System.Drawing.Point(329, 476) Me.ICODE3.Name = "ICODE3" Me.ICODE3.Size = New System.Drawing.Size(100, 20) Me.ICODE3.TabIndex = 5 ' 'ICODE5 ' Me.ICODE5.Enabled = False Me.ICODE5.Location = New System.Drawing.Point(329, 558) Me.ICODE5.Name = "ICODE5" Me.ICODE5.Size = New System.Drawing.Size(100, 20) Me.ICODE5.TabIndex = 9 ' 'ICODE4 ' Me.ICODE4.Enabled = False Me.ICODE4.Location = New System.Drawing.Point(329, 519) Me.ICODE4.Name = "ICODE4" Me.ICODE4.Size = New System.Drawing.Size(100, 20) Me.ICODE4.TabIndex = 7 ' 'Label15 ' Me.Label15.AutoSize = True Me.Label15.Location = New System.Drawing.Point(775, 379) Me.Label15.Name = "Label15" Me.Label15.Size = New System.Drawing.Size(29, 13) Me.Label15.TabIndex = 33 Me.Label15.Text = "QTY" ' 'Confirm ' Me.Confirm.Location = New System.Drawing.Point(128, 629) Me.Confirm.Name = "Confirm" Me.Confirm.Size = New System.Drawing.Size(162, 41) Me.Confirm.TabIndex = 11 Me.Confirm.Text = "CONFIRM BILL" Me.Confirm.UseVisualStyleBackColor = True ' 'Clear ' Me.Clear.Location = New System.Drawing.Point(376, 629) Me.Clear.Name = "Clear" Me.Clear.Size = New System.Drawing.Size(157, 41) Me.Clear.TabIndex = 35 Me.Clear.Text = "CLEAR" Me.Clear.UseVisualStyleBackColor = True ' 'Button3 ' Me.Button3.Location = New System.Drawing.Point(778, 629) Me.Button3.Name = "Button3" Me.Button3.Size = New System.Drawing.Size(134, 41) Me.Button3.TabIndex = 36 Me.Button3.Text = "DELETE TRANSACTION" Me.Button3.UseVisualStyleBackColor = True ' 'ItemNameHeadlbl ' Me.ItemNameHeadlbl.AutoSize = True Me.ItemNameHeadlbl.Location = New System.Drawing.Point(449, 379) Me.ItemNameHeadlbl.Name = "ItemNameHeadlbl" Me.ItemNameHeadlbl.Size = New System.Drawing.Size(67, 13) Me.ItemNameHeadlbl.TabIndex = 37 Me.ItemNameHeadlbl.Text = "ITEM NAME" ' 'INAME1 ' Me.INAME1.AutoSize = True Me.INAME1.Location = New System.Drawing.Point(449, 402) Me.INAME1.Name = "INAME1" Me.INAME1.Size = New System.Drawing.Size(17, 13) Me.INAME1.TabIndex = 38 Me.INAME1.Text = """""" ' 'INAME2 ' Me.INAME2.AutoSize = True Me.INAME2.Location = New System.Drawing.Point(449, 441) Me.INAME2.Name = "INAME2" Me.INAME2.Size = New System.Drawing.Size(17, 13) Me.INAME2.TabIndex = 39 Me.INAME2.Text = """""" ' 'INAME4 ' Me.INAME4.AutoSize = True Me.INAME4.Location = New System.Drawing.Point(449, 519) Me.INAME4.Name = "INAME4" Me.INAME4.Size = New System.Drawing.Size(17, 13) Me.INAME4.TabIndex = 41 Me.INAME4.Text = """""" ' 'INAME3 ' Me.INAME3.AutoSize = True Me.INAME3.Location = New System.Drawing.Point(449, 480) Me.INAME3.Name = "INAME3" Me.INAME3.Size = New System.Drawing.Size(17, 13) Me.INAME3.TabIndex = 40 Me.INAME3.Text = """""" ' 'INAME5 ' Me.INAME5.AutoSize = True Me.INAME5.Location = New System.Drawing.Point(449, 560) Me.INAME5.Name = "INAME5" Me.INAME5.Size = New System.Drawing.Size(17, 13) Me.INAME5.TabIndex = 42 Me.INAME5.Text = """""" ' 'PRICE5 ' Me.PRICE5.AutoSize = True Me.PRICE5.Location = New System.Drawing.Point(566, 560) Me.PRICE5.Name = "PRICE5" Me.PRICE5.Size = New System.Drawing.Size(17, 13) Me.PRICE5.TabIndex = 47 Me.PRICE5.Text = """""" ' 'PRICE4 ' Me.PRICE4.AutoSize = True Me.PRICE4.Location = New System.Drawing.Point(566, 519) Me.PRICE4.Name = "PRICE4" Me.PRICE4.Size = New System.Drawing.Size(17, 13) Me.PRICE4.TabIndex = 46 Me.PRICE4.Text = """""" ' 'PRICE3 ' Me.PRICE3.AutoSize = True Me.PRICE3.Location = New System.Drawing.Point(566, 480) Me.PRICE3.Name = "PRICE3" Me.PRICE3.Size = New System.Drawing.Size(17, 13) Me.PRICE3.TabIndex = 45 Me.PRICE3.Text = """""" ' 'PRICE2 ' Me.PRICE2.AutoSize = True Me.PRICE2.Location = New System.Drawing.Point(566, 441) Me.PRICE2.Name = "PRICE2" Me.PRICE2.Size = New System.Drawing.Size(17, 13) Me.PRICE2.TabIndex = 44 Me.PRICE2.Text = """""" ' 'PRICE1 ' Me.PRICE1.AutoSize = True Me.PRICE1.Location = New System.Drawing.Point(566, 402) Me.PRICE1.Name = "PRICE1" Me.PRICE1.Size = New System.Drawing.Size(17, 13) Me.PRICE1.TabIndex = 43 Me.PRICE1.Text = """""" ' 'Label6 ' Me.Label6.AutoSize = True Me.Label6.Location = New System.Drawing.Point(549, 379) Me.Label6.Name = "Label6" Me.Label6.Size = New System.Drawing.Size(68, 13) Me.Label6.TabIndex = 48 Me.Label6.Text = "ITEM PRICE" ' 'QTY1 ' Me.QTY1.Enabled = False Me.QTY1.Location = New System.Drawing.Point(772, 395) Me.QTY1.Name = "QTY1" Me.QTY1.Size = New System.Drawing.Size(57, 20) Me.QTY1.TabIndex = 2 ' 'QTY2 ' Me.QTY2.Enabled = False Me.QTY2.Location = New System.Drawing.Point(772, 434) Me.QTY2.Name = "QTY2" Me.QTY2.Size = New System.Drawing.Size(57, 20) Me.QTY2.TabIndex = 4 ' 'QTY3 ' Me.QTY3.Enabled = False Me.QTY3.Location = New System.Drawing.Point(772, 473) Me.QTY3.Name = "QTY3" Me.QTY3.Size = New System.Drawing.Size(57, 20) Me.QTY3.TabIndex = 6 ' 'QTY4 ' Me.QTY4.Enabled = False Me.QTY4.Location = New System.Drawing.Point(772, 516) Me.QTY4.Name = "QTY4" Me.QTY4.Size = New System.Drawing.Size(57, 20) Me.QTY4.TabIndex = 8 ' 'QTY5 ' Me.QTY5.Enabled = False Me.QTY5.Location = New System.Drawing.Point(772, 555) Me.QTY5.Name = "QTY5" Me.QTY5.Size = New System.Drawing.Size(57, 20) Me.QTY5.TabIndex = 10 ' 'Label1 ' Me.Label1.AutoSize = True Me.Label1.Location = New System.Drawing.Point(655, 379) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(59, 13) Me.Label1.TabIndex = 207 Me.Label1.Text = "TAX ( in %)" ' 'TAX5 ' Me.TAX5.AutoSize = True Me.TAX5.Location = New System.Drawing.Point(672, 560) Me.TAX5.Name = "TAX5" Me.TAX5.Size = New System.Drawing.Size(17, 13) Me.TAX5.TabIndex = 206 Me.TAX5.Text = """""" ' 'TAX4 ' Me.TAX4.AutoSize = True Me.TAX4.Location = New System.Drawing.Point(672, 519) Me.TAX4.Name = "TAX4" Me.TAX4.Size = New System.Drawing.Size(17, 13) Me.TAX4.TabIndex = 205 Me.TAX4.Text = """""" ' 'TAX3 ' Me.TAX3.AutoSize = True Me.TAX3.Location = New System.Drawing.Point(672, 480) Me.TAX3.Name = "TAX3" Me.TAX3.Size = New System.Drawing.Size(17, 13) Me.TAX3.TabIndex = 204 Me.TAX3.Text = """""" ' 'TAX2 ' Me.TAX2.AutoSize = True Me.TAX2.Location = New System.Drawing.Point(672, 441) Me.TAX2.Name = "TAX2" Me.TAX2.Size = New System.Drawing.Size(17, 13) Me.TAX2.TabIndex = 203 Me.TAX2.Text = """""" ' 'TAX1 ' Me.TAX1.AutoSize = True Me.TAX1.Location = New System.Drawing.Point(672, 402) Me.TAX1.Name = "TAX1" Me.TAX1.Size = New System.Drawing.Size(17, 13) Me.TAX1.TabIndex = 202 Me.TAX1.Text = """""" ' 'PrintDocument1 ' ' 'curr_qty1 ' Me.curr_qty1.AutoSize = True Me.curr_qty1.Location = New System.Drawing.Point(861, 400) Me.curr_qty1.Name = "curr_qty1" Me.curr_qty1.Size = New System.Drawing.Size(17, 13) Me.curr_qty1.TabIndex = 208 Me.curr_qty1.Text = """""" Me.curr_qty1.Visible = False ' 'curr_qty2 ' Me.curr_qty2.AutoSize = True Me.curr_qty2.Location = New System.Drawing.Point(861, 437) Me.curr_qty2.Name = "curr_qty2" Me.curr_qty2.Size = New System.Drawing.Size(17, 13) Me.curr_qty2.TabIndex = 209 Me.curr_qty2.Text = """""" Me.curr_qty2.Visible = False ' 'curr_qty4 ' Me.curr_qty4.AutoSize = True Me.curr_qty4.Location = New System.Drawing.Point(861, 513) Me.curr_qty4.Name = "curr_qty4" Me.curr_qty4.Size = New System.Drawing.Size(17, 13) Me.curr_qty4.TabIndex = 211 Me.curr_qty4.Text = """""" Me.curr_qty4.Visible = False ' 'curr_qty3 ' Me.curr_qty3.AutoSize = True Me.curr_qty3.Location = New System.Drawing.Point(861, 476) Me.curr_qty3.Name = "curr_qty3" Me.curr_qty3.Size = New System.Drawing.Size(17, 13) Me.curr_qty3.TabIndex = 210 Me.curr_qty3.Text = """""" Me.curr_qty3.Visible = False ' 'curr_qty5 ' Me.curr_qty5.AutoSize = True Me.curr_qty5.Location = New System.Drawing.Point(861, 558) Me.curr_qty5.Name = "curr_qty5" Me.curr_qty5.Size = New System.Drawing.Size(17, 13) Me.curr_qty5.TabIndex = 212 Me.curr_qty5.Text = """""" Me.curr_qty5.Visible = False ' 'lblQtyInStore ' Me.lblQtyInStore.AutoSize = True Me.lblQtyInStore.Location = New System.Drawing.Point(849, 379) Me.lblQtyInStore.Name = "lblQtyInStore" Me.lblQtyInStore.Size = New System.Drawing.Size(83, 13) Me.lblQtyInStore.TabIndex = 213 Me.lblQtyInStore.Text = "QTY IN STORE" Me.lblQtyInStore.Visible = False ' 'Timer1 ' ' 'countdown ' Me.countdown.AutoSize = True Me.countdown.Location = New System.Drawing.Point(944, 226) Me.countdown.Name = "countdown" Me.countdown.Size = New System.Drawing.Size(0, 13) Me.countdown.TabIndex = 214 Me.countdown.Visible = False ' 'Label2 ' Me.Label2.AutoSize = True Me.Label2.Location = New System.Drawing.Point(749, 600) Me.Label2.Name = "Label2" Me.Label2.Size = New System.Drawing.Size(76, 13) Me.Label2.TabIndex = 215 Me.Label2.Text = "SUB TOTAL : " ' 'Sub_total ' Me.Sub_total.AutoSize = True Me.Sub_total.ForeColor = System.Drawing.Color.Red Me.Sub_total.Location = New System.Drawing.Point(836, 600) Me.Sub_total.Name = "Sub_total" Me.Sub_total.Size = New System.Drawing.Size(0, 13) Me.Sub_total.TabIndex = 216 ' 'Button1 ' Me.Button1.Location = New System.Drawing.Point(627, 629) Me.Button1.Name = "Button1" Me.Button1.Size = New System.Drawing.Size(123, 41) Me.Button1.TabIndex = 218 Me.Button1.Text = "PRINT BILL" Me.Button1.UseVisualStyleBackColor = True ' 'PrintDocument2 ' ' 'Button2 ' Me.Button2.Location = New System.Drawing.Point(925, 142) Me.Button2.Name = "Button2" Me.Button2.Size = New System.Drawing.Size(71, 40) Me.Button2.TabIndex = 219 Me.Button2.Text = "Query ON/OFF" Me.Button2.UseVisualStyleBackColor = True ' 'pit2 ' Me.pit2.Location = New System.Drawing.Point(127, 557) Me.pit2.Name = "pit2" Me.pit2.Size = New System.Drawing.Size(100, 20) Me.pit2.TabIndex = 220 ' 'Label3 ' Me.Label3.AutoSize = True Me.Label3.Location = New System.Drawing.Point(27, 565) Me.Label3.Name = "Label3" Me.Label3.Size = New System.Drawing.Size(24, 13) Me.Label3.TabIndex = 221 Me.Label3.Text = "PIT" ' 'formExtras ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.AutoSize = True Me.ClientSize = New System.Drawing.Size(804, 582) Me.Controls.Add(Me.Label3) Me.Controls.Add(Me.pit2) Me.Controls.Add(Me.Button2) Me.Controls.Add(Me.Button1) Me.Controls.Add(Me.Sub_total) Me.Controls.Add(Me.Label2) Me.Controls.Add(Me.countdown) Me.Controls.Add(Me.lblQtyInStore) Me.Controls.Add(Me.curr_qty5) Me.Controls.Add(Me.curr_qty4) Me.Controls.Add(Me.curr_qty3) Me.Controls.Add(Me.curr_qty2) Me.Controls.Add(Me.curr_qty1) Me.Controls.Add(Me.Label1) Me.Controls.Add(Me.TAX5) Me.Controls.Add(Me.TAX4) Me.Controls.Add(Me.TAX3) Me.Controls.Add(Me.TAX2) Me.Controls.Add(Me.TAX1) Me.Controls.Add(Me.Label6) Me.Controls.Add(Me.PRICE5) Me.Controls.Add(Me.PRICE4) Me.Controls.Add(Me.PRICE3) Me.Controls.Add(Me.PRICE2) Me.Controls.Add(Me.PRICE1) Me.Controls.Add(Me.INAME5) Me.Controls.Add(Me.INAME4) Me.Controls.Add(Me.INAME3) Me.Controls.Add(Me.INAME2) Me.Controls.Add(Me.INAME1) Me.Controls.Add(Me.ItemNameHeadlbl) Me.Controls.Add(Me.Button3) Me.Controls.Add(Me.Clear) Me.Controls.Add(Me.Confirm) Me.Controls.Add(Me.Label15) Me.Controls.Add(Me.QTY5) Me.Controls.Add(Me.QTY4) Me.Controls.Add(Me.QTY3) Me.Controls.Add(Me.QTY2) Me.Controls.Add(Me.QTY1) Me.Controls.Add(Me.ICODE5) Me.Controls.Add(Me.ICODE4) Me.Controls.Add(Me.ICODE3) Me.Controls.Add(Me.ICODE2) Me.Controls.Add(Me.ICODE1) Me.Controls.Add(Me.I5lbl) Me.Controls.Add(Me.I4lbl) Me.Controls.Add(Me.I3lbl) Me.Controls.Add(Me.I2lbl) Me.Controls.Add(Me.I1lbl) Me.Controls.Add(Me.ROOM) Me.Controls.Add(Me.BHAWAN) Me.Controls.Add(Me.ID) Me.Controls.Add(Me.SNAME) Me.Controls.Add(Me.ROOMNOlbl) Me.Controls.Add(Me.BHAWANlbl) Me.Controls.Add(Me.IDNOlbl) Me.Controls.Add(Me.NAMElbl) Me.Controls.Add(Me.S_ID) Me.Controls.Add(Me.SIDlbl) Me.Controls.Add(Me.PictureBox1) Me.Controls.Add(Me.RadioButton2) Me.Controls.Add(Me.RadioButton1) Me.Controls.Add(Me.MonthCalendar1) Me.Controls.Add(Me.DataGridView1) Me.Name = "formExtras" Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "Extras" CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents DataGridView1 As System.Windows.Forms.DataGridView Friend WithEvents MonthCalendar1 As System.Windows.Forms.MonthCalendar Friend WithEvents RadioButton1 As System.Windows.Forms.RadioButton Friend WithEvents RadioButton2 As System.Windows.Forms.RadioButton Friend WithEvents PictureBox1 As System.Windows.Forms.PictureBox Friend WithEvents SIDlbl As System.Windows.Forms.Label Friend WithEvents S_ID As System.Windows.Forms.TextBox Friend WithEvents NAMElbl As System.Windows.Forms.Label Friend WithEvents IDNOlbl As System.Windows.Forms.Label Friend WithEvents BHAWANlbl As System.Windows.Forms.Label Friend WithEvents ROOMNOlbl As System.Windows.Forms.Label Friend WithEvents SNAME As System.Windows.Forms.Label Friend WithEvents ID As System.Windows.Forms.Label Friend WithEvents ROOM As System.Windows.Forms.Label Friend WithEvents BHAWAN As System.Windows.Forms.Label Friend WithEvents I1lbl As System.Windows.Forms.Label Friend WithEvents I2lbl As System.Windows.Forms.Label Friend WithEvents I3lbl As System.Windows.Forms.Label Friend WithEvents I4lbl As System.Windows.Forms.Label Friend WithEvents I5lbl As System.Windows.Forms.Label Friend WithEvents ICODE1 As System.Windows.Forms.TextBox Friend WithEvents ICODE2 As System.Windows.Forms.TextBox Friend WithEvents ICODE3 As System.Windows.Forms.TextBox Friend WithEvents ICODE5 As System.Windows.Forms.TextBox Friend WithEvents ICODE4 As System.Windows.Forms.TextBox Friend WithEvents Label15 As System.Windows.Forms.Label Friend WithEvents Confirm As System.Windows.Forms.Button Friend WithEvents Clear As System.Windows.Forms.Button Friend WithEvents Button3 As System.Windows.Forms.Button Friend WithEvents ItemNameHeadlbl As System.Windows.Forms.Label Friend WithEvents INAME1 As System.Windows.Forms.Label Friend WithEvents INAME2 As System.Windows.Forms.Label Friend WithEvents INAME4 As System.Windows.Forms.Label Friend WithEvents INAME3 As System.Windows.Forms.Label Friend WithEvents INAME5 As System.Windows.Forms.Label Friend WithEvents PRICE5 As System.Windows.Forms.Label Friend WithEvents PRICE4 As System.Windows.Forms.Label Friend WithEvents PRICE3 As System.Windows.Forms.Label Friend WithEvents PRICE2 As System.Windows.Forms.Label Friend WithEvents PRICE1 As System.Windows.Forms.Label Friend WithEvents Label6 As System.Windows.Forms.Label Friend WithEvents QTY1 As System.Windows.Forms.TextBox Friend WithEvents QTY2 As System.Windows.Forms.TextBox Friend WithEvents QTY3 As System.Windows.Forms.TextBox Friend WithEvents QTY4 As System.Windows.Forms.TextBox Friend WithEvents QTY5 As System.Windows.Forms.TextBox Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents TAX5 As System.Windows.Forms.Label Friend WithEvents TAX4 As System.Windows.Forms.Label Friend WithEvents TAX3 As System.Windows.Forms.Label Friend WithEvents TAX2 As System.Windows.Forms.Label Friend WithEvents TAX1 As System.Windows.Forms.Label Friend WithEvents PrintDocument1 As System.Drawing.Printing.PrintDocument Friend WithEvents curr_qty1 As System.Windows.Forms.Label Friend WithEvents curr_qty2 As System.Windows.Forms.Label Friend WithEvents curr_qty4 As System.Windows.Forms.Label Friend WithEvents curr_qty3 As System.Windows.Forms.Label Friend WithEvents curr_qty5 As System.Windows.Forms.Label Friend WithEvents lblQtyInStore As System.Windows.Forms.Label Friend WithEvents Timer1 As System.Windows.Forms.Timer Friend WithEvents countdown As System.Windows.Forms.Label Friend WithEvents Label2 As System.Windows.Forms.Label Friend WithEvents Sub_total As System.Windows.Forms.Label Friend WithEvents Button1 As System.Windows.Forms.Button Friend WithEvents PrintDocument2 As System.Drawing.Printing.PrintDocument Friend WithEvents Button2 As System.Windows.Forms.Button Friend WithEvents pit2 As System.Windows.Forms.TextBox Friend WithEvents Label3 As System.Windows.Forms.Label End Class
SSMS-Pilani/Mess-Management-System
Mess Management System/formExtras.Designer.vb
Visual Basic
mit
31,824
' This file was generated by CSLA Object Generator - CslaGenFork v4.5 ' ' Filename: DocEditGetter ' ObjectType: DocEditGetter ' CSLAType: UnitOfWork Imports System Imports Csla Imports DocStore.Business.Admin Namespace DocStore.Business ''' <summary> ''' DocEditGetter (creator and getter unit of work pattern).<br/> ''' This is a generated base class of <see cref="DocEditGetter"/> business object. ''' This class is a root object that implements the Unit of Work pattern. ''' </summary> <Serializable> Public Partial Class DocEditGetter Inherits ReadOnlyBase(Of DocEditGetter) #Region " Business Properties " ''' <summary> ''' Maintains metadata about unit of work (child) <see cref="Doc"/> property. ''' </summary> Public Shared ReadOnly DocProperty As PropertyInfo(Of Doc) = RegisterProperty(Of Doc)(Function(p) p.Doc, "Doc") ''' <summary> ''' Gets the Doc object (unit of work child property). ''' </summary> ''' <value>The Doc.</value> Public Property Doc As Doc Get Return GetProperty(DocProperty) End Get Private Set(ByVal value As Doc) LoadProperty(DocProperty, value) End Set End Property ''' <summary> ''' Maintains metadata about unit of work (child) <see cref="DocClassNVL"/> property. ''' </summary> Public Shared ReadOnly DocClassNVLProperty As PropertyInfo(Of DocClassNVL) = RegisterProperty(Of DocClassNVL)(Function(p) p.DocClassNVL, "Doc Class NVL") ''' <summary> ''' Gets the Doc Class NVL object (unit of work child property). ''' </summary> ''' <value>The Doc Class NVL.</value> Public Property DocClassNVL As DocClassNVL Get Return GetProperty(DocClassNVLProperty) End Get Private Set(ByVal value As DocClassNVL) LoadProperty(DocClassNVLProperty, value) End Set End Property ''' <summary> ''' Maintains metadata about unit of work (child) <see cref="DocTypeNVL"/> property. ''' </summary> Public Shared ReadOnly DocTypeNVLProperty As PropertyInfo(Of DocTypeNVL) = RegisterProperty(Of DocTypeNVL)(Function(p) p.DocTypeNVL, "Doc Type NVL") ''' <summary> ''' Gets the Doc Type NVL object (unit of work child property). ''' </summary> ''' <value>The Doc Type NVL.</value> Public Property DocTypeNVL As DocTypeNVL Get Return GetProperty(DocTypeNVLProperty) End Get Private Set(ByVal value As DocTypeNVL) LoadProperty(DocTypeNVLProperty, value) End Set End Property ''' <summary> ''' Maintains metadata about unit of work (child) <see cref="DocStatusNVL"/> property. ''' </summary> Public Shared ReadOnly DocStatusNVLProperty As PropertyInfo(Of DocStatusNVL) = RegisterProperty(Of DocStatusNVL)(Function(p) p.DocStatusNVL, "Doc Status NVL") ''' <summary> ''' Gets the Doc Status NVL object (unit of work child property). ''' </summary> ''' <value>The Doc Status NVL.</value> Public Property DocStatusNVL As DocStatusNVL Get Return GetProperty(DocStatusNVLProperty) End Get Private Set(ByVal value As DocStatusNVL) LoadProperty(DocStatusNVLProperty, value) End Set End Property ''' <summary> ''' Maintains metadata about unit of work (child) <see cref="UserNVL"/> property. ''' </summary> Public Shared ReadOnly UserNVLProperty As PropertyInfo(Of UserNVL) = RegisterProperty(Of UserNVL)(Function(p) p.UserNVL, "User NVL") ''' <summary> ''' Gets the User NVL object (unit of work child property). ''' </summary> ''' <value>The User NVL.</value> Public Property UserNVL As UserNVL Get Return GetProperty(UserNVLProperty) End Get Private Set(ByVal value As UserNVL) LoadProperty(UserNVLProperty, value) End Set End Property #End Region #Region " Factory Methods " ''' <summary> ''' Factory method. Creates a new <see cref="DocEditGetter"/> unit of objects. ''' </summary> ''' <returns>A reference to the created <see cref="DocEditGetter"/> unit of objects.</returns> Public Shared Function NewDocEditGetter() As DocEditGetter ' DataPortal_Fetch is used as ReadOnlyBase<T> doesn't allow the use of DataPortal_Create. Return DataPortal.Fetch(Of DocEditGetter)(New Criteria1(true, New Integer())) End Function ''' <summary> ''' Factory method. Loads a <see cref="DocEditGetter"/> unit of objects, based on given parameters. ''' </summary> ''' <param name="docID">The DocID parameter of the DocEditGetter to fetch.</param> ''' <returns>A reference to the fetched <see cref="DocEditGetter"/> unit of objects.</returns> Public Shared Function GetDocEditGetter(docID As Integer) As DocEditGetter Return DataPortal.Fetch(Of DocEditGetter)(New Criteria1(false, docID)) End Function ''' <summary> ''' Factory method. Asynchronously creates a new <see cref="DocEditGetter"/> unit of objects. ''' </summary> ''' <param name="callback">The completion callback method.</param> Public Shared Sub NewDocEditGetter(callback As EventHandler(Of DataPortalResult(Of DocEditGetter))) ' DataPortal_Fetch is used as ReadOnlyBase<T> doesn't allow the use of DataPortal_Create. DataPortal.BeginFetch(Of DocEditGetter)(New Criteria1(true, New Integer()), Sub(o, e) If e.Error IsNot Nothing Then Throw e.Error End If If Not DocClassNVL.IsCached Then DocClassNVL.SetCache(e.Object.DocClassNVL) End If If Not DocTypeNVL.IsCached Then DocTypeNVL.SetCache(e.Object.DocTypeNVL) End If If Not DocStatusNVL.IsCached Then DocStatusNVL.SetCache(e.Object.DocStatusNVL) End If If Not UserNVL.IsCached Then UserNVL.SetCache(e.Object.UserNVL) End If callback(o, e) End Sub) End Sub ''' <summary> ''' Factory method. Asynchronously loads a <see cref="DocEditGetter"/> unit of objects, based on given parameters. ''' </summary> ''' <param name="docID">The DocID parameter of the DocEditGetter to fetch.</param> ''' <param name="callback">The completion callback method.</param> Public Shared Sub GetDocEditGetter(docID As Integer, callback As EventHandler(Of DataPortalResult(Of DocEditGetter))) DataPortal.BeginFetch(Of DocEditGetter)(New Criteria1(false, docID), Sub(o, e) If e.Error IsNot Nothing Then Throw e.Error End If If Not DocClassNVL.IsCached Then DocClassNVL.SetCache(e.Object.DocClassNVL) End If If Not DocTypeNVL.IsCached Then DocTypeNVL.SetCache(e.Object.DocTypeNVL) End If If Not DocStatusNVL.IsCached Then DocStatusNVL.SetCache(e.Object.DocStatusNVL) End If If Not UserNVL.IsCached Then UserNVL.SetCache(e.Object.UserNVL) End If callback(o, e) End Sub) End Sub #End Region #Region " Constructor " ''' <summary> ''' Initializes a new instance of the <see cref="DocEditGetter"/> class. ''' </summary> ''' <remarks> Do not use to create a Unit of Work. Use factory methods instead.</remarks> <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New() ' Use factory methods and do not use direct creation. End Sub #End Region #Region " Criteria " ''' <summary> ''' Criteria1 criteria. ''' </summary> <Serializable> Protected Class Criteria1 Inherits CriteriaBase(Of Criteria1) ''' <summary> ''' Maintains metadata about <see cref="CreateDoc"/> property. ''' </summary> Public Shared ReadOnly CreateDocProperty As PropertyInfo(Of Boolean) = RegisterProperty(Of Boolean)(Function(p) p.CreateDoc, "Create Doc") ''' <summary> ''' Gets or sets the Create Doc. ''' </summary> ''' <value>The Create Doc.</value> Public Property CreateDoc As Boolean Get Return ReadProperty(CreateDocProperty) End Get Set LoadProperty(CreateDocProperty, value) End Set End Property ''' <summary> ''' Maintains metadata about <see cref="DocID"/> property. ''' </summary> Public Shared ReadOnly DocIDProperty As PropertyInfo(Of Integer) = RegisterProperty(Of Integer)(Function(p) p.DocID, "Doc ID") ''' <summary> ''' Gets or sets the Doc ID. ''' </summary> ''' <value>The Doc ID.</value> Public Property DocID As Integer Get Return ReadProperty(DocIDProperty) End Get Set LoadProperty(DocIDProperty, value) End Set End Property ''' <summary> ''' Initializes a new instance of the <see cref="Criteria1"/> class. ''' </summary> ''' <remarks> A parameterless constructor is required by the MobileFormatter.</remarks> <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New() End Sub ''' <summary> ''' Initializes a new instance of the <see cref="Criteria1"/> class. ''' </summary> ''' <param name="p_createDoc">The CreateDoc.</param> ''' <param name="p_docID">The DocID.</param> Public Sub New(p_createDoc As Boolean, p_docID As Integer) CreateDoc = p_createDoc DocID = p_docID End Sub ''' <summary> ''' Determines whether the specified <see cref="System.Object"/> is equal to this instance. ''' </summary> ''' <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> ''' <returns><c>True</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns> Public Overrides Function Equals(obj As object) As Boolean If TypeOf obj Is Criteria1 Then Dim c As Criteria1 = obj If Not CreateDoc.Equals(c.CreateDoc) Then Return False End If If Not DocID.Equals(c.DocID) Then Return False End If Return True End If Return False End Function ''' <summary> ''' Returns a hash code for this instance. ''' </summary> ''' <returns>An hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> Public Overrides Function GetHashCode() As Integer Return String.Concat("Criteria1", CreateDoc.ToString(), DocID.ToString()).GetHashCode() End Function End Class #End Region #Region " Data Access " ''' <summary> ''' Creates or loads a <see cref="DocEditGetter"/> unit of objects, based on given criteria. ''' </summary> ''' <param name="crit">The create/fetch criteria.</param> Protected Overloads Sub DataPortal_Fetch(crit As Criteria1) If crit.CreateDoc Then LoadProperty(DocProperty, Doc.NewDoc()) Else LoadProperty(DocProperty, Doc.GetDoc(crit.DocID)) End If LoadProperty(DocClassNVLProperty, DocClassNVL.GetDocClassNVL()) LoadProperty(DocTypeNVLProperty, DocTypeNVL.GetDocTypeNVL()) LoadProperty(DocStatusNVLProperty, DocStatusNVL.GetDocStatusNVL()) LoadProperty(UserNVLProperty, UserNVL.GetUserNVL()) End Sub #End Region End Class End Namespace
CslaGenFork/CslaGenFork
trunk/CoverageTest/Plain/Plain-WIN-VB/DocStore.Business/DocEditGetter.Designer.vb
Visual Basic
mit
13,369
Imports BVSoftware.Bvc5.Core Imports System.Collections.ObjectModel Partial Class BVModules_Themes_Foundation4_Responsive_ContentBlocks_Side_Menu_view Inherits Content.BVModule Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load LoadMenu() End Sub Private Sub LoadMenu() Me.TitlePlaceHolder.Controls.Clear() Dim title As String = SettingsManager.GetSetting("Title") If title.Trim.Length > 0 Then Me.TitlePlaceHolder.Controls.Add(New LiteralControl("<h4>" & title & "</h4>")) End If Me.MenuControl.Controls.Clear() MenuControl.EnableViewState = False Dim links As Collection(Of Content.ComponentSettingListItem) links = SettingsManager.GetSettingList("Links") If links IsNot Nothing Then Me.MenuControl.Controls.Add(New LiteralControl("<ul class=""side-nav"">")) For Each l As Content.ComponentSettingListItem In links AddSingleLink(l) Next Me.MenuControl.Controls.Add(New LiteralControl("</ul>")) End If End Sub Private Sub AddSingleLink(ByVal l As Content.ComponentSettingListItem) Me.MenuControl.Controls.Add(New LiteralControl("<li>")) Dim m As New HyperLink m.ToolTip = l.Setting4 m.Text = l.Setting1 m.NavigateUrl = l.Setting2 If l.Setting3 = "1" Then m.Target = "_blank" End If m.EnableViewState = False Me.MenuControl.Controls.Add(m) Me.MenuControl.Controls.Add(New LiteralControl("</li>")) End Sub End Class
ajaydex/Scopelist_2015
BVModules/Themes/Foundation4 Responsive/ContentBlocks/Side Menu/view.ascx.vb
Visual Basic
apache-2.0
1,649
' Copyright 2016 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 Esri.ArcGISRuntime Imports Esri.ArcGISRuntime.Mapping Imports System.Threading Namespace AccessLoadStatus Partial Public Class AccessLoadStatusVB Public Sub New() InitializeComponent() ' Create the UI, setup the control references and execute initialization Initialize() End Sub Private Sub Initialize() ' Create new Map with basemap Dim myMap As New Map(Basemap.CreateImagery()) ' Register to handle loading status changes AddHandler myMap.LoadStatusChanged, AddressOf OnMapsLoadStatusChanged ' Provide used Map to the MapView myMapView.Map = myMap End Sub Private Sub OnMapsLoadStatusChanged(sender As Object, e As LoadStatusEventArgs) ' Update the load status information Dispatcher.BeginInvoke( New ThreadStart( Function() InlineAssignHelper( loadStatusLabel.Content, String.Format("Maps' load status : {0}", e.Status.ToString())))) End Sub Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T target = value Return value End Function End Class End Namespace
Arc3D/arcgis-runtime-samples-dotnet
src/WPF/ArcGISRuntime.WPF.Samples/Samples/Map/AccessLoadStatus/AccessLoadStatusVB.xaml.vb
Visual Basic
apache-2.0
1,860
Imports Aspose.Email.Outlook ' 'This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Email for .NET API reference 'when the project is build. Please check https://Docs.nuget.org/consume/nuget-faq for more information. 'If you do not wish to use NuGet, you can manually download Aspose.Email for .NET API from http://www.aspose.com/downloads, 'install it and then add its reference to this project. For any issues, questions or suggestions 'please feel free to contact us using http://www.aspose.com/community/forums/default.aspx ' Namespace Aspose.Email.Examples.VisualBasic.Email.Outlook Class GetTheTextAndRTFBodies Public Shared Sub Run() Dim dataDir As String = RunExamples.GetDataDir_Outlook() ' Load mail message Dim msg As MapiMessage = MapiMessage.FromMailMessage(dataDir & Convert.ToString("Message.eml")) Dim itemBase As MapiMessageItemBase = New MapiMessage() ' Text body If itemBase.Body IsNot Nothing Then Console.WriteLine(msg.Body) Else Console.WriteLine("There's no text body.") End If ' RTF body If itemBase.BodyRtf IsNot Nothing Then Console.WriteLine(msg.BodyRtf) Else Console.WriteLine("There's no RTF body.") End If End Sub End Class End Namespace
maria-shahid-aspose/Aspose.Email-for-.NET
Examples/VisualBasic/Outlook/GetTheTextAndRTFBodies.vb
Visual Basic
mit
1,439
Imports DlhSoft.Windows.Controls ''' <summary> ''' Interaction logic for MainWindow.xaml ''' </summary> Partial Public Class MainWindow Inherits Window Public Sub New() InitializeComponent() Dim item0 As GanttChartItem = GanttChartDataGrid.Items(0) Dim item1 As GanttChartItem = GanttChartDataGrid.Items(1) item1.Start = Date.Today.Add(TimeSpan.Parse("08:00:00")) item1.Finish = Date.Today.Add(TimeSpan.Parse("16:00:00")) item1.CompletedFinish = Date.Today.Add(TimeSpan.Parse("12:00:00")) item1.AssignmentsContent = "Resource 1" Dim item2 As GanttChartItem = GanttChartDataGrid.Items(2) item2.Start = Date.Today.AddDays(1).Add(TimeSpan.Parse("08:00:00")) item2.Finish = Date.Today.AddDays(2).Add(TimeSpan.Parse("16:00:00")) item2.AssignmentsContent = "Resource 1, Resource 2" item2.Predecessors.Add(New PredecessorItem With {.Item = item1}) Dim item3 As GanttChartItem = GanttChartDataGrid.Items(3) item3.Predecessors.Add(New PredecessorItem With {.Item = item0, .DependencyType = DependencyType.StartStart}) Dim item4 As GanttChartItem = GanttChartDataGrid.Items(4) item4.Start = Date.Today.Add(TimeSpan.Parse("08:00:00")) item4.Finish = Date.Today.AddDays(2).Add(TimeSpan.Parse("12:00:00")) item4.AssignmentsContent = "Resource 1" Dim item6 As GanttChartItem = GanttChartDataGrid.Items(6) item6.Start = Date.Today.Add(TimeSpan.Parse("08:00:00")) item6.Finish = Date.Today.AddDays(3).Add(TimeSpan.Parse("12:00:00")) item6.AssignmentsContent = "Resource 1" Dim item7 As GanttChartItem = GanttChartDataGrid.Items(7) item7.Start = Date.Today.AddDays(4) item7.IsMilestone = True item7.Predecessors.Add(New PredecessorItem With {.Item = item4}) item7.Predecessors.Add(New PredecessorItem With {.Item = item6}) item7.AssignmentsContent = "Resource 2" ' Optionally, set LevelingPrority values to be considered upon leveling resources (default is zero). ' item6.LevelingPriority = 1000 For i As Integer = 3 To 25 GanttChartDataGrid.Items.Add(New GanttChartItem With {.Content = "Task " & i, .Indentation = If(i Mod 3 = 0, 0, 1), .Start = Date.Today.AddDays(If(i <= 8, (i - 4) * 2, i - 8)), .Finish = Date.Today.AddDays((If(i <= 8, (i - 4) * 2 + (If(i > 8, 6, 1)), i - 2)) + 2), .CompletedFinish = Date.Today.AddDays(If(i <= 8, (i - 4) * 2, i - 8)).AddDays(If(i Mod 6 = 4, 3, 0)), .AssignmentsContent = If(i Mod 3 = 0, "Resource 2", "Resource 1")}) Next i End Sub Private theme As String = "Generic-bright" Public Sub New(theme As String) Me.New() Me.theme = theme ApplyTemplate() End Sub Public Overrides Sub OnApplyTemplate() LoadTheme() MyBase.OnApplyTemplate() End Sub Private Sub LoadTheme() If theme Is Nothing OrElse theme = "Default" OrElse theme = "Aero" Then Return End If Dim themeResourceDictionary = New ResourceDictionary With {.Source = New Uri("/" & Me.GetType().Assembly.GetName().Name & ";component/Themes/" & theme & ".xaml", UriKind.Relative)} GanttChartDataGrid.Resources.MergedDictionaries.Add(themeResourceDictionary) End Sub Private Sub OptimizeWorkButton_Click(sender As Object, e As RoutedEventArgs) If StartOnDatePicker.SelectedDate IsNot Nothing Then GanttChartDataGrid.OptimizeWork(CBool(DependenciesOnlyButton.IsChecked), CBool(IncludeStartedTasksButton.IsChecked), CDate(StartOnDatePicker.SelectedDate)) Else GanttChartDataGrid.OptimizeWork(CBool(DependenciesOnlyButton.IsChecked), CBool(IncludeStartedTasksButton.IsChecked)) End If End Sub Private Sub LevelResourcesButton_Click(sender As Object, e As RoutedEventArgs) If StartOnDatePicker.SelectedDate IsNot Nothing Then GanttChartDataGrid.LevelResources(CBool(IncludeStartedTasksButton.IsChecked), CDate(StartOnDatePicker.SelectedDate)) Else GanttChartDataGrid.LevelResources(CBool(IncludeStartedTasksButton.IsChecked)) End If End Sub End Class
DlhSoftTeam/GanttChartLightLibrary-Demos
GanttChartLightLibraryDemos/Demos/Samples/WPF-VisualBasic/GanttChartDataGrid/WorkOptimizations/MainWindow.xaml.vb
Visual Basic
mit
4,242
Public Class frmLogin Private Sub btnLogin_Click(sender As System.Object, e As System.EventArgs) Handles btnLogin.Click mGRCData = New GRCSec.GridcoinData txtMessage.Text = GetSessionGuid() Dim bLogged As Boolean = mGRCData.Authenticate(txtMessage.Text, txtUserName.Text, GetMd5String(txtPassword.Text)) If bLogged Then Me.Hide() txtMessage.Text = "" Try mfrmTicketList.Show() Catch ex As Exception End Try Else txtMessage.Text = "Authentication Failed - " + GetSessionGuid() End If End Sub Private Sub btnLogOff_Click(sender As System.Object, e As System.EventArgs) Handles btnLogOff.Click txtMessage.Text = "Logged Out" mGRCData.LogOff(GetSessionGuid) End Sub Private Sub frmLogin_Activated(sender As Object, e As System.EventArgs) Handles Me.Activated txtUserName.Focus() End Sub Private Sub frmLogin_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing e.Cancel = True Me.Hide() End Sub Private Sub frmLogin_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load Try txtMessage.Text = "" + GetSessionGuid() If mGRCData.IsAuthenticated(GetSessionGuid) Then mfrmTicketList.Show() Me.Dispose() End If If UserAgent() Like "*iphone*" Then Me.Width = Me.Width - 100 btnRegister.Left = btnRegister.Left - 50 btnLogOff.Left = btnLogOff.Left - 100 txtUserName.Width = txtUserName.Width - 100 txtPassword.Width = txtPassword.Width - 100 End If Me.Top = 0 txtUserName.Focus() Catch ex As Exception Dim sErr As String sErr = ex.Message End Try End Sub Private Sub btnRegister_Click(sender As System.Object, e As System.EventArgs) Handles btnRegister.Click Dim r As New frmRegister r.Show() End Sub Private Sub txtMessage_Click(sender As System.Object, e As System.EventArgs) Handles txtMessage.Click End Sub Private Sub btnRecoverPass_Click(sender As System.Object, e As System.EventArgs) Handles btnRecoverPass.Click Dim bSuccess As Boolean mGRCData = New GRCSec.GridcoinData If Len(txtUserName.Text) = 0 Then MsgBox("Username must be known", MsgBoxStyle.Critical) Exit Sub End If bSuccess = mGRCData.RecoverPassword(txtUserName.Text) If bSuccess Then MsgBox("Your password has been recovered and a message has been sent to your inbox. ", MsgBoxStyle.Exclamation) Exit Sub Else MsgBox("Unable to recover password. Possible reasons: Bad e-mail address on file.", MsgBoxStyle.Critical) Exit Sub End If End Sub End Class
Lederstrumpf/Gridcoin-Research
contrib/Installer/boinc/boinc/frmLogin.vb
Visual Basic
mit
3,039
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Public Class CSharpSignatureHelpCommandHandlerTests <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestCreateAndDismiss() Using state = TestState.CreateCSharpTestState( <Document> class C { void Foo() { Foo$$ } } </Document>) state.SendTypeChars("(") state.AssertSelectedSignatureHelpItem(displayText:="void C.Foo()") state.SendTypeChars(")") state.AssertNoSignatureHelpSession() End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TypingUpdatesParameters() Using state = TestState.CreateCSharpTestState( <Document> class C { void Foo(int i, string j) { Foo$$ } } </Document>) state.SendTypeChars("(") state.AssertSelectedSignatureHelpItem(displayText:="void C.Foo(int i, string j)", selectedParameter:="int i") state.SendTypeChars("1,") state.AssertSelectedSignatureHelpItem(displayText:="void C.Foo(int i, string j)", selectedParameter:="string j") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TypingChangeParameterByNavigating() Using state = TestState.CreateCSharpTestState( <Document> class C { void Foo(int i, string j) { Foo(1$$ } } </Document>) state.SendTypeChars(",") state.AssertSelectedSignatureHelpItem(displayText:="void C.Foo(int i, string j)", selectedParameter:="string j") state.SendLeftKey() state.AssertSelectedSignatureHelpItem(displayText:="void C.Foo(int i, string j)", selectedParameter:="int i") state.SendRightKey() state.AssertSelectedSignatureHelpItem(displayText:="void C.Foo(int i, string j)", selectedParameter:="string j") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub NavigatingOutOfSpanDismissesSignatureHelp() Using state = TestState.CreateCSharpTestState( <Document> class C { void Foo() { Foo($$) } } </Document>) state.SendInvokeSignatureHelp() state.AssertSelectedSignatureHelpItem(displayText:="void C.Foo()") state.SendRightKey() state.AssertNoSignatureHelpSession() End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestNestedCalls() Using state = TestState.CreateCSharpTestState( <Document> class C { void Bar() { } void Foo() { Foo$$ } } </Document>) state.SendTypeChars("(") state.AssertSelectedSignatureHelpItem(displayText:="void C.Foo()") state.SendTypeChars("Bar(") state.AssertSelectedSignatureHelpItem(displayText:="void C.Bar()") state.SendTypeChars(")") state.AssertSelectedSignatureHelpItem(displayText:="void C.Foo()") End Using End Sub <WorkItem(544547)> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestNoSigHelpOnGenericNamespace() Using state = TestState.CreateCSharpTestState( <Document> namespace global::F$$ </Document>) state.SendTypeChars("<") state.AssertNoSignatureHelpSession() End Using End Sub <WorkItem(544547)> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestSigHelpOnExtraSpace() Using state = TestState.CreateCSharpTestState( <Document> class G&lt;S, T&gt; { }; class C { void Foo() { G&lt;int, $$ } } </Document>) state.SendInvokeSignatureHelp() state.AssertSignatureHelpSession() End Using End Sub <WorkItem(544551)> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestFilterOnNamedParameters1() Using state = TestState.CreateCSharpTestState( <Document> class C { public void M(int first, int second) { } public void M(int third) { } } class Program { void Main() { new C().M(first$$ } } </Document>) state.SendInvokeSignatureHelp() state.AssertSignatureHelpSession() state.AssertSelectedSignatureHelpItem("void C.M(int third)") Assert.Equal(2, state.CurrentSignatureHelpPresenterSession.SignatureHelpItems.Count) state.SendTypeChars(":") state.AssertSignatureHelpSession() state.AssertSelectedSignatureHelpItem("void C.M(int first, int second)") Assert.Equal(1, state.CurrentSignatureHelpPresenterSession.SignatureHelpItems.Count) ' Keep the same item selected when the colon is deleted, but now both items are ' available again. state.SendBackspace() state.AssertSignatureHelpSession() state.AssertSelectedSignatureHelpItem("void C.M(int first, int second)") Assert.Equal(2, state.CurrentSignatureHelpPresenterSession.SignatureHelpItems.Count) End Using End Sub <WorkItem(545488)> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestKeepSelectedItemWhenNoneAreViable() Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Program { static void Main(string[] args) { F$$ } static void F(int i) { } static void F(string s) { } } ]]></Document>) state.SendTypeChars("(") state.AssertSignatureHelpSession() state.AssertSelectedSignatureHelpItem("void Program.F(int i)") Assert.Equal(2, state.CurrentSignatureHelpPresenterSession.SignatureHelpItems.Count) state.SendTypeChars(""""",") state.AssertSignatureHelpSession() state.AssertSelectedSignatureHelpItem("void Program.F(int i)") Assert.Equal(2, state.CurrentSignatureHelpPresenterSession.SignatureHelpItems.Count) End Using End Sub <WorkItem(691648)> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestKeepSelectedItemAfterComma() Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { M$$ } void M(int i) { } void M(int i, int j) { } void M(int i, int j, int k) { } } ]]></Document>) state.SendTypeChars("(") state.AssertSignatureHelpSession() state.AssertSelectedSignatureHelpItem("void C.M()") Assert.Equal(4, state.CurrentSignatureHelpPresenterSession.SignatureHelpItems.Count) state.SendUpKey() state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)") state.SendTypeChars("1, ") state.AssertSelectedSignatureHelpItem("void C.M(int i, int j, int k)") End Using End Sub <WorkItem(819063)> <WorkItem(843508)> <WorkItem(636117)> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestSessionMaintainedDuringIndexerErrorToleranceTransition() Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Program { void M(int x) { string s = "Test"; s$$ } } ]]></Document>) state.SendTypeChars("[") state.AssertSignatureHelpSession() state.AssertSelectedSignatureHelpItem("char string[int index]") state.SendTypeChars("x") state.AssertSignatureHelpSession() state.AssertSelectedSignatureHelpItem("char string[int index]") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestSigHelpInLinkedFiles() Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"> class C { void M() { M2($$); } #if Proj1 void M2(int x) { } #endif #if Proj2 void M2(string x) { } #endif } </Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>) Dim documents = state.Workspace.Documents Dim linkDocument = documents.Single(Function(d) d.IsLinkFile) state.SendInvokeSignatureHelp() state.AssertSelectedSignatureHelpItem("void C.M2(int x)") state.SendEscape() state.Workspace.SetDocumentContext(linkDocument.Id) state.SendInvokeSignatureHelp() state.AssertSelectedSignatureHelpItem("void C.M2(string x)") End Using End Sub <WorkItem(1060850)> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestSigHelpNotDismissedAfterQuote() Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { } void M(string s) { M($$); } } ]]></Document>) state.SendInvokeSignatureHelp() state.AssertSelectedSignatureHelpItem("void C.M()") state.SendTypeChars("""") state.AssertSignatureHelpSession() state.AssertSelectedSignatureHelpItem("void C.M(string s)") End Using End Sub <WorkItem(1060850)> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestSigHelpDismissedAfterComment() Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { } void M(string s) { M($$); } } ]]></Document>) state.SendInvokeSignatureHelp() state.AssertSelectedSignatureHelpItem("void C.M()") state.SendTypeChars("//") state.AssertNoSignatureHelpSession() End Using End Sub End Class End Namespace
DavidKarlas/roslyn
src/EditorFeatures/Test2/IntelliSense/CSharpSignatureHelpCommandHandlerTests.vb
Visual Basic
apache-2.0
11,673
' 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.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the "Custom Event" keyword in type declaration contexts ''' </summary> Friend Class CustomEventKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As IEnumerable(Of RecommendedKeyword) ' Custom Event cannot appear in interfaces If context.IsTypeMemberDeclarationKeywordContext Then Dim modifiers = context.ModifierCollectionFacts If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Event) AndAlso modifiers.CustomKeyword.Kind = SyntaxKind.None Then Return SpecializedCollections.SingletonEnumerable( New RecommendedKeyword("Custom Event", VBFeaturesResources.Specifies_that_an_event_has_additional_specialized_code_for_adding_handlers_removing_handlers_and_raising_events)) End If End If Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)() End Function End Class End Namespace
jmarolf/roslyn
src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/CustomEventKeywordRecommender.vb
Visual Basic
mit
1,660
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions Public Class KeyKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function KeyNotInStatementTest() As Task Await VerifyRecommendationsMissingAsync(<MethodBody>|</MethodBody>, "Key") End Function <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function KeyNotAfterArrayInitializerSquiggleTest() As Task Await VerifyRecommendationsMissingAsync(<MethodBody>Dim x = {|</MethodBody>, "Key") End Function <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function KeyNotAfterArrayInitializerCommaTest() As Task Await VerifyRecommendationsMissingAsync(<MethodBody>Dim x = {0, |</MethodBody>, "Key") End Function <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function KeyNotAfterAsTest() As Task Await VerifyRecommendationsMissingAsync(<MethodBody>Dim x As |</MethodBody>, "Key") End Function <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function KeyInAnonymousInitializer1Test() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Dim x As New With {|</MethodBody>, "Key") End Function <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function KeyInAnonymousInitializer2Test() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Dim x As New With {.Goo = 2, |</MethodBody>, "Key") End Function <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function KeyInAnonymousExpression1Test() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = New With {|</MethodBody>, "Key") End Function <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function KeyInAnonymousExpression2Test() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = New With {.Goo = 2, |</MethodBody>, "Key") End Function ''' <remark>Yes, "Onymous" is a word.</remark> <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function KeyNotInOnymousInitializerTest() As Task Await VerifyRecommendationsMissingAsync(<MethodBody>Dim x As New Goo With {|</MethodBody>, "Key") End Function ''' <remark>Yes, "Onymous" is a word.</remark> <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function KeyNotInOnymousExpressionTest() As Task Await VerifyRecommendationsMissingAsync(<MethodBody>Dim x = New Goo With {|</MethodBody>, "Key") End Function End Class End Namespace
mmitche/roslyn
src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/KeyKeywordRecommenderTests.vb
Visual Basic
apache-2.0
3,219
' 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.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Notification Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.VisualStudio.LanguageServices.Implementation.ExtractInterface Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ExtractInterface Public Class ExtractInterfaceViewModelTests <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_InterfaceNameIsSameAsPassedIn() Dim markup = <Text><![CDATA[ class $$MyClass { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("IMyClass", viewModel.InterfaceName) Dim monitor = New PropertyChangedTestMonitor(viewModel) monitor.AddExpectation(Function() viewModel.GeneratedName) monitor.AddExpectation(Function() viewModel.FileName) viewModel.InterfaceName = "IMyClassChanged" Assert.Equal("IMyClassChanged.cs", viewModel.FileName) Assert.Equal("IMyClassChanged", viewModel.GeneratedName) monitor.VerifyExpectations() monitor.Detach() End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_FileNameHasExpectedExtension() Dim markup = <Text><![CDATA[ class $$MyClass { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("IMyClass.cs", viewModel.FileName) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_GeneratedNameInGlobalNamespace() Dim markup = <Text><![CDATA[ class $$MyClass { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("IMyClass", viewModel.GeneratedName) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_GeneratedNameInNestedNamespaces() Dim markup = <Text><![CDATA[ namespace Outer { namespace Inner { class $$MyClass { public void Foo() { } } } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass", defaultNamespace:="Outer.Inner") Assert.Equal("Outer.Inner.IMyClass", viewModel.GeneratedName) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_GeneratedNameWithTypeParameters() Dim markup = <Text><![CDATA[ namespace Outer { namespace Inner { class $$MyClass<X, Y> { public void Foo(X x, Y y) { } } } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass", defaultNamespace:="Outer.Inner", generatedNameTypeParameterSuffix:="<X, Y>") Assert.Equal("Outer.Inner.IMyClass<X, Y>", viewModel.GeneratedName) viewModel.InterfaceName = "IMyClassChanged" Assert.Equal("Outer.Inner.IMyClassChanged<X, Y>", viewModel.GeneratedName) End Sub <Fact> <WorkItem(716122), Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_GeneratedNameIsGeneratedFromTrimmedInterfaceName() Dim markup = <Text><![CDATA[ namespace Ns { class C$$ { public void Foo() { } } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IC", defaultNamespace:="Ns") viewModel.InterfaceName = " IC2 " Assert.Equal("Ns.IC2", viewModel.GeneratedName) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_MembersCheckedByDefault() Dim markup = <Text><![CDATA[ class $$MyClass { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") Assert.True(viewModel.MemberContainers.Single().IsChecked) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_InterfaceNameChangesUpdateGeneratedName() Dim markup = <Text><![CDATA[ class $$MyClass { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") Dim monitor = New PropertyChangedTestMonitor(viewModel) monitor.AddExpectation(Function() viewModel.GeneratedName) viewModel.InterfaceName = "IMyClassChanged" Assert.Equal("IMyClassChanged", viewModel.GeneratedName) monitor.VerifyExpectations() monitor.Detach() End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_InterfaceNameChangesUpdateFileName() Dim markup = <Text><![CDATA[ class $$MyClass { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") Dim monitor = New PropertyChangedTestMonitor(viewModel) monitor.AddExpectation(Function() viewModel.FileName) viewModel.InterfaceName = "IMyClassChanged" Assert.Equal("IMyClassChanged.cs", viewModel.FileName) monitor.VerifyExpectations() monitor.Detach() End Sub <Fact> <WorkItem(716122), Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_FileNameIsGeneratedFromTrimmedInterfaceName() Dim markup = <Text><![CDATA[ public class C$$ { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IC") viewModel.InterfaceName = " IC2 " Assert.Equal("IC2.cs", viewModel.FileName) End Sub <Fact> <WorkItem(716122), Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_InterfaceNameIsTrimmedOnSubmit() Dim markup = <Text><![CDATA[ public class C$$ { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IC") viewModel.InterfaceName = " IC2 " Dim submitSucceeded = viewModel.TrySubmit() Assert.True(submitSucceeded, String.Format("Submit failed unexpectedly.")) End Sub <Fact> <WorkItem(716122), Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_FileNameIsTrimmedOnSubmit() Dim markup = <Text><![CDATA[ public class C$$ { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IC") viewModel.FileName = " IC2.cs " Dim submitSucceeded = viewModel.TrySubmit() Assert.True(submitSucceeded, String.Format("Submit failed unexpectedly.")) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_FileNameChangesDoNotUpdateInterfaceName() Dim markup = <Text><![CDATA[ class $$MyClass { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") Dim monitor = New PropertyChangedTestMonitor(viewModel, strict:=True) monitor.AddExpectation(Function() viewModel.FileName) viewModel.FileName = "IMyClassChanged.cs" Assert.Equal("IMyClass", viewModel.InterfaceName) monitor.VerifyExpectations() monitor.Detach() End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_SuccessfulCommit() Dim markup = <Text><![CDATA[ class $$MyClass { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") Dim submitSucceeded = viewModel.TrySubmit() Assert.True(submitSucceeded, String.Format("Submit failed unexpectedly.")) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_SuccessfulCommit_NonemptyStrictSubsetOfMembersSelected() Dim markup = <Text><![CDATA[ class $$MyClass { public void Foo() { } public void Bar() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") viewModel.MemberContainers.First().IsChecked = False Dim submitSucceeded = viewModel.TrySubmit() Assert.True(submitSucceeded, String.Format("Submit failed unexpectedly.")) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_FailedCommit_InterfaceNameConflict() Dim markup = <Text><![CDATA[ class $$MyClass { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass", conflictingTypeNames:=New List(Of String) From {"IMyClass"}) Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_FailedCommit_InterfaceNameNotAnIdentifier() Dim markup = <Text><![CDATA[ class $$MyClass { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") viewModel.InterfaceName = "SomeNamespace.IMyClass" Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_FailedCommit_BadFileExtension() Dim markup = <Text><![CDATA[ class $$MyClass { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") viewModel.FileName = "FileName.vb" Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_FailedCommit_BadFileName() Dim markup = <Text><![CDATA[ class $$MyClass { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") viewModel.FileName = "Bad*FileName.cs" Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_FailedCommit_BadFileName2() Dim markup = <Text><![CDATA[ class $$MyClass { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") viewModel.FileName = "?BadFileName.cs" Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_FailedCommit_NoMembersSelected() Dim markup = <Text><![CDATA[ class $$MyClass { public void Foo() { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") viewModel.MemberContainers.Single().IsChecked = False Dim submitSucceeded = viewModel.TrySubmit() Assert.False(submitSucceeded) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_MemberDisplay_Method() Dim markup = <Text><![CDATA[ using System; class $$MyClass { public void Foo<T>(T t, System.Diagnostics.CorrelationManager v, ref int w, Nullable<System.Int32> x = 7, string y = "hi", params int[] z) { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("Foo<T>(T, CorrelationManager, ref int, [int?], [string], params int[])", viewModel.MemberContainers.Single().MemberName) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_MemberDisplay_Property() Dim markup = <Text><![CDATA[ using System; class $$MyClass { public int Foo { get { return 5; } set { } } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("Foo", viewModel.MemberContainers.Where(Function(c) c.MemberSymbol.IsKind(SymbolKind.Property)).Single().MemberName) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_MemberDisplay_Indexer() Dim markup = <Text><![CDATA[ using System; class $$MyClass { public int this[Nullable<Int32> x, string y = "hi"] { get { return 1; } set { } } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("this[int?, [string]]", viewModel.MemberContainers.Where(Function(c) c.MemberSymbol.IsKind(SymbolKind.Property)).Single().MemberName) End Sub <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Sub ExtractInterface_MembersSorted() Dim markup = <Text><![CDATA[ public class $$MyClass { public void Foo(string s) { } public void Foo(int i) { } public void Foo(int i, string s) { } public void Foo() { } public void Foo(int i, int i2) { } }"]]></Text> Dim viewModel = GetViewModel(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal(5, viewModel.MemberContainers.Count) Assert.Equal("Foo()", viewModel.MemberContainers.ElementAt(0).MemberName) Assert.Equal("Foo(int)", viewModel.MemberContainers.ElementAt(1).MemberName) Assert.Equal("Foo(int, int)", viewModel.MemberContainers.ElementAt(2).MemberName) Assert.Equal("Foo(int, string)", viewModel.MemberContainers.ElementAt(3).MemberName) Assert.Equal("Foo(string)", viewModel.MemberContainers.ElementAt(4).MemberName) End Sub Private Function GetViewModel(markup As XElement, languageName As String, defaultInterfaceName As String, Optional defaultNamespace As String = "", Optional generatedNameTypeParameterSuffix As String = "", Optional conflictingTypeNames As List(Of String) = Nothing, Optional isValidIdentifier As Boolean = True) As ExtractInterfaceDialogViewModel Dim workspaceXml = <Workspace> <Project Language=<%= languageName %> CommonReferences="true"> <Document><%= markup.NormalizedValue.Replace(vbCrLf, vbLf) %></Document> </Project> </Workspace> Using workspace = TestWorkspaceFactory.CreateWorkspace(workspaceXml) Dim doc = workspace.Documents.Single() Dim workspaceDoc = workspace.CurrentSolution.GetDocument(doc.Id) If (Not doc.CursorPosition.HasValue) Then Assert.True(False, "Missing caret location in document.") End If Dim token = workspaceDoc.GetSyntaxTreeAsync().Result.GetTouchingWord(doc.CursorPosition.Value, workspaceDoc.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), CancellationToken.None) Dim symbol = workspaceDoc.GetSemanticModelAsync().Result.GetDeclaredSymbol(token.Parent) Dim extractableMembers = DirectCast(symbol, INamedTypeSymbol).GetMembers().Where(Function(s) Not (TypeOf s Is IMethodSymbol) OrElse DirectCast(s, IMethodSymbol).MethodKind <> MethodKind.Constructor) Return New ExtractInterfaceDialogViewModel( workspaceDoc.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), glyphService:=Nothing, notificationService:=New TestNotificationService(), defaultInterfaceName:=defaultInterfaceName, extractableMembers:=extractableMembers.ToList(), conflictingTypeNames:=If(conflictingTypeNames, New List(Of String)), defaultNamespace:=defaultNamespace, generatedNameTypeParameterSuffix:=generatedNameTypeParameterSuffix, languageName:=doc.Project.Language, fileExtension:=If(languageName = LanguageNames.CSharp, ".cs", ".vb")) End Using End Function End Class End Namespace
v-codeel/roslyn
src/VisualStudio/Core/Test/ExtractInterface/ExtractInterfaceViewModelTests.vb
Visual Basic
apache-2.0
17,861
' 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.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Composition Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEvent <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.GenerateEvent), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.GenerateEnumMember)> Partial Friend Class GenerateEventCodeFixProvider Inherits CodeFixProvider Friend Const BC30401 As String = "BC30401" ' error BC30401: 'foo' cannot implement 'E' because there is no matching event on interface 'MyInterface'. Friend Const BC30590 As String = "BC30590" ' error BC30590: Event 'MyEvent' cannot be found. Friend Const BC30456 As String = "BC30456" ' error BC30456: 'x' is not a member of 'y'. Friend Const BC30451 As String = "BC30451" ' error BC30451: 'x' is not declared, it may be inaccessible due to its protection level. Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return ImmutableArray.Create(BC30401, BC30590, BC30456, BC30451) End Get End Property Public NotOverridable Overrides Async Function RegisterCodeFixesAsync(context As CodeFixContext) As Task Dim root = Await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(False) Dim token = root.FindToken(context.Span.Start) If Not token.Span.IntersectsWith(context.Span) Then Return End If Dim result As CodeAction = Nothing For Each node In token.GetAncestors(Of SyntaxNode).Where(Function(c) c.Span.IntersectsWith(context.Span) AndAlso IsCandidate(c)) Dim qualifiedName = TryCast(node, QualifiedNameSyntax) If qualifiedName IsNot Nothing Then result = Await GenerateEventFromImplementsAsync(context.Document, qualifiedName, context.CancellationToken).ConfigureAwait(False) End If Dim handlesClauseItem = TryCast(node, HandlesClauseItemSyntax) If handlesClauseItem IsNot Nothing Then result = Await GenerateEventFromHandlesAsync(context.Document, handlesClauseItem, context.CancellationToken).ConfigureAwait(False) End If Dim handlerStatement = TryCast(node, AddRemoveHandlerStatementSyntax) If handlerStatement IsNot Nothing Then result = Await GenerateEventFromAddRemoveHandlerAsync(context.Document, handlerStatement, context.CancellationToken).ConfigureAwait(False) End If If result IsNot Nothing Then context.RegisterCodeFix(result, context.Diagnostics) Return End If Next End Function Private Async Function GenerateEventFromAddRemoveHandlerAsync(document As Document, handlerStatement As AddRemoveHandlerStatementSyntax, cancellationToken As CancellationToken) As Task(Of CodeAction) Dim semanticModel = Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False) Dim handlerExpression = GetHandlerExpression(handlerStatement) Dim delegateSymbol As IMethodSymbol = Nothing If Not TryGetDelegateSymbol(handlerExpression, semanticModel, delegateSymbol, cancellationToken) Then Return Nothing End If Dim eventExpression = handlerStatement.EventExpression Dim eventSymbol = semanticModel.GetSymbolInfo(eventExpression, cancellationToken).GetAnySymbol() If eventSymbol IsNot Nothing Then Return Nothing End If Dim containingSymbol = semanticModel.GetEnclosingNamedType(handlerStatement.SpanStart, cancellationToken) If containingSymbol Is Nothing Then Return Nothing End If Dim targetType As INamedTypeSymbol = Nothing Dim actualEventName As String = Nothing If Not TryGetNameAndTargetType(eventExpression, containingSymbol, semanticModel, targetType, actualEventName, cancellationToken) Then Return Nothing End If If Not ResolveTargetType(targetType, semanticModel) Then Return Nothing End If ' Target type may be in other project so we need to find its source definition Dim sourceDefinition = Await SymbolFinder.FindSourceDefinitionAsync(targetType, document.Project.Solution, cancellationToken).ConfigureAwait(False) targetType = TryCast(sourceDefinition, INamedTypeSymbol) If targetType Is Nothing Then Return Nothing End If Return Await GenerateCodeAction(document, semanticModel, delegateSymbol, actualEventName, targetType, cancellationToken).ConfigureAwait(False) End Function Private Shared Async Function GenerateCodeAction(document As Document, semanticModel As SemanticModel, delegateSymbol As IMethodSymbol, actualEventName As String, targetType As INamedTypeSymbol, cancellationToken As CancellationToken) As Task(Of CodeAction) Dim codeGenService = document.Project.Solution.Workspace.Services.GetLanguageServices(targetType.Language).GetService(Of ICodeGenerationService) Dim semanticFactService = document.Project.Solution.Workspace.Services.GetLanguageServices(targetType.Language).GetService(Of ISemanticFactsService) Dim syntaxFactService = document.Project.Solution.Workspace.Services.GetLanguageServices(targetType.Language).GetService(Of ISyntaxFactsService) Dim eventHandlerName As String = actualEventName + "Handler" Dim existingSymbols = Await SymbolFinder.FindSourceDeclarationsAsync( document.Project.Solution, eventHandlerName, Not syntaxFactService.IsCaseSensitive, SymbolFilter.Type, cancellationToken).ConfigureAwait(False) If existingSymbols.Any(Function(existingSymbol) existingSymbol IsNot Nothing _ AndAlso existingSymbol.ContainingNamespace Is targetType.ContainingNamespace) Then ' There already exists a delegate that matches the event handler name Return Nothing End If If semanticFactService.SupportsParameterizedEvents Then ' We also need to generate the delegate type Dim delegateType = CodeGenerationSymbolFactory.CreateDelegateTypeSymbol(Nothing, Accessibility.Public, Nothing, semanticModel.Compilation.GetSpecialType(SpecialType.System_Void), name:=eventHandlerName, parameters:=delegateSymbol.GetParameters()) Dim generatedEvent = CodeGenerationSymbolFactory.CreateEventSymbol(attributes:=SpecializedCollections.EmptyList(Of AttributeData)(), accessibility:=Accessibility.Public, modifiers:=Nothing, explicitInterfaceSymbol:=Nothing, type:=delegateType, name:=actualEventName, parameterList:=TryCast(delegateSymbol, IMethodSymbol).Parameters) Return New GenerateEventCodeAction(document.Project.Solution, targetType, generatedEvent, delegateType, codeGenService, CodeGenerationOptions.Default) Else Dim generatedEvent = CodeGenerationSymbolFactory.CreateEventSymbol(attributes:=SpecializedCollections.EmptyList(Of AttributeData)(), accessibility:=Accessibility.Public, modifiers:=Nothing, explicitInterfaceSymbol:=Nothing, type:=Nothing, name:=actualEventName, parameterList:=delegateSymbol.GetParameters()) Return New GenerateEventCodeAction(document.Project.Solution, TryCast(targetType, INamedTypeSymbol), generatedEvent, Nothing, codeGenService, CodeGenerationOptions.Default) End If End Function Private Function GetHandlerExpression(handlerStatement As AddRemoveHandlerStatementSyntax) As ExpressionSyntax Dim unaryExpression = TryCast(handlerStatement.DelegateExpression.DescendantNodesAndSelf().Where(Function(n) n.IsKind(SyntaxKind.AddressOfExpression)).FirstOrDefault, UnaryExpressionSyntax) If unaryExpression Is Nothing Then Return handlerStatement.DelegateExpression Else Return unaryExpression.Operand End If End Function Private Function TryGetDelegateSymbol(handlerExpression As ExpressionSyntax, semanticModel As SemanticModel, ByRef delegateSymbol As IMethodSymbol, cancellationToken As CancellationToken) As Boolean delegateSymbol = TryCast(semanticModel.GetSymbolInfo(handlerExpression, cancellationToken).GetAnySymbol(), IMethodSymbol) If delegateSymbol Is Nothing Then Dim typeSymbol = TryCast(semanticModel.GetTypeInfo(handlerExpression, cancellationToken).Type, INamedTypeSymbol) If typeSymbol IsNot Nothing AndAlso typeSymbol.DelegateInvokeMethod IsNot Nothing Then delegateSymbol = typeSymbol.DelegateInvokeMethod Else Return False End If End If If delegateSymbol.Arity <> 0 AndAlso delegateSymbol.TypeArguments.Any(Function(n) n.TypeKind = TypeKind.TypeParameter) Then Return False End If Return True End Function Private Function ResolveTargetType(ByRef targetType As INamedTypeSymbol, semanticModel As SemanticModel) As Boolean If targetType Is Nothing OrElse Not (targetType.TypeKind = TypeKind.Class OrElse targetType.TypeKind = TypeKind.Interface) OrElse targetType.IsAnonymousType Then Return False End If targetType = DirectCast(targetType.GetSymbolKey().Resolve(semanticModel.Compilation).Symbol, INamedTypeSymbol) If targetType Is Nothing Then Return False End If Return True End Function Private Function TryGetNameAndTargetType(eventExpression As ExpressionSyntax, containingSymbol As INamedTypeSymbol, semanticModel As SemanticModel, ByRef targetType As INamedTypeSymbol, ByRef actualEventName As String, cancellationToken As CancellationToken) As Boolean Dim eventType As INamedTypeSymbol = Nothing If TypeOf eventExpression Is IdentifierNameSyntax Then actualEventName = CType(eventExpression, IdentifierNameSyntax).Identifier.ValueText ElseIf TypeOf eventExpression Is MemberAccessExpressionSyntax Then Dim memberAccess = CType(eventExpression, MemberAccessExpressionSyntax) Dim qualifier As ExpressionSyntax = Nothing Dim arity As Integer memberAccess.DecomposeName(qualifier, actualEventName, arity) eventType = TryCast(semanticModel.GetTypeInfo(qualifier, cancellationToken).Type, INamedTypeSymbol) Else Return False End If If eventExpression.DescendantTokens().Where(Function(n) n.IsKind(SyntaxKind.MeKeyword, SyntaxKind.MyClassKeyword)).Any Then targetType = containingSymbol Return True ElseIf eventExpression.DescendantTokens().Where(Function(n) n.IsKind(SyntaxKind.MyBaseKeyword)).Any Then targetType = containingSymbol.BaseType Return True ElseIf TypeOf eventExpression Is IdentifierNameSyntax Then targetType = containingSymbol Return True ElseIf TypeOf eventExpression Is MemberAccessExpressionSyntax Then If eventType IsNot Nothing Then targetType = eventType Return True End If End If Return False End Function Private Shared Function IsCandidate(node As SyntaxNode) As Boolean Return TypeOf node Is HandlesClauseItemSyntax OrElse TypeOf node Is QualifiedNameSyntax OrElse TypeOf node Is AddRemoveHandlerStatementSyntax End Function Private Async Function GenerateEventFromImplementsAsync(document As Document, node As QualifiedNameSyntax, cancellationToken As CancellationToken) As Task(Of CodeAction) If node.Right.IsMissing Then Return Nothing End If ' We must be trying to implement an event If node.IsParentKind(SyntaxKind.ImplementsClause) AndAlso node.Parent.IsParentKind(SyntaxKind.EventStatement) Then ' Does this name already bind? Dim semanticModel = Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False) Dim nameToGenerate = semanticModel.GetSymbolInfo(node).Symbol If nameToGenerate IsNot Nothing Then Return Nothing End If Dim targetType = TryCast(Await SymbolFinder.FindSourceDefinitionAsync(semanticModel.GetSymbolInfo(node.Left).Symbol, document.Project.Solution, cancellationToken).ConfigureAwait(False), INamedTypeSymbol) If targetType Is Nothing OrElse (targetType.TypeKind <> TypeKind.Interface AndAlso targetType.TypeKind <> TypeKind.Class) Then Return Nothing End If Dim boundEvent = TryCast(semanticModel.GetDeclaredSymbol(node.Parent.Parent, cancellationToken), IEventSymbol) If boundEvent Is Nothing Then Return Nothing End If Dim codeGenService = document.Project.Solution.Workspace.Services.GetLanguageServices(targetType.Language).GetService(Of ICodeGenerationService) Dim actualEventName = node.Right.Identifier.ValueText Dim semanticFactService = document.Project.Solution.Workspace.Services.GetLanguageServices(targetType.Language).GetService(Of ISemanticFactsService) If semanticFactService.SupportsParameterizedEvents Then ' If we support parameterized events (C#) and it's an event declaration with a parameter list ' (not a type), we need to generate a delegate type in the C# file. Dim eventSyntax = node.GetAncestor(Of EventStatementSyntax)() If eventSyntax.ParameterList IsNot Nothing Then Dim eventType = TryCast(boundEvent.Type, INamedTypeSymbol) If eventType Is Nothing Then Return Nothing End If Dim returnType = If(eventType.DelegateInvokeMethod IsNot Nothing, eventType.DelegateInvokeMethod.ReturnType, semanticModel.Compilation.GetSpecialType(SpecialType.System_Void)) Dim parameters As IList(Of IParameterSymbol) = If(eventType.DelegateInvokeMethod IsNot Nothing, eventType.DelegateInvokeMethod.Parameters, SpecializedCollections.EmptyList(Of IParameterSymbol)()) Dim eventHandlerType = CodeGenerationSymbolFactory.CreateDelegateTypeSymbol(eventType.GetAttributes(), eventType.DeclaredAccessibility, Nothing, returnType, actualEventName + "EventHandler", eventType.TypeParameters, parameters) Dim generatedEvent = CodeGenerationSymbolFactory.CreateEventSymbol(boundEvent.GetAttributes(), boundEvent.DeclaredAccessibility, modifiers:=Nothing, type:=eventHandlerType, explicitInterfaceSymbol:=Nothing, name:=actualEventName, parameterList:=boundEvent.GetParameters()) Return New GenerateEventCodeAction(document.Project.Solution, targetType, generatedEvent, eventHandlerType, codeGenService, New CodeGenerationOptions()) End If End If ' C# with no delegate type or VB Dim generatedMember = CodeGenerationSymbolFactory.CreateEventSymbol(boundEvent, name:=actualEventName) Return New GenerateEventCodeAction(document.Project.Solution, targetType, generatedMember, Nothing, codeGenService, New CodeGenerationOptions()) End If Return Nothing End Function Private Async Function GenerateEventFromHandlesAsync(document As Document, handlesClauseItem As HandlesClauseItemSyntax, cancellationToken As CancellationToken) As Task(Of CodeAction) If handlesClauseItem.IsMissing OrElse handlesClauseItem.EventContainer.IsMissing OrElse handlesClauseItem.EventMember.IsMissing Then Return Nothing End If Dim semanticModel = Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False) ' Does this handlesClauseItem actually bind? Dim symbol = semanticModel.GetSymbolInfo(handlesClauseItem, cancellationToken).Symbol If symbol IsNot Nothing Then Return Nothing End If Dim targetType As INamedTypeSymbol = Nothing Dim keywordEventContainer = TryCast(handlesClauseItem.EventContainer, KeywordEventContainerSyntax) If keywordEventContainer IsNot Nothing Then ' Me/MyClass/MyBase Dim containingSymbol = semanticModel.GetEnclosingNamedType(handlesClauseItem.SpanStart, cancellationToken) If containingSymbol Is Nothing Then Return Nothing End If If keywordEventContainer.Keyword.IsKind(SyntaxKind.MeKeyword, SyntaxKind.MyClassKeyword) Then targetType = containingSymbol ElseIf keywordEventContainer.Keyword.IsKind(SyntaxKind.MyBaseKeyword) Then targetType = containingSymbol.BaseType End If Else ' Withevents property. We'll generate into its type. Dim withEventsProperty = TryCast(semanticModel.GetSymbolInfo(handlesClauseItem.EventContainer, cancellationToken).Symbol, IPropertySymbol) If withEventsProperty Is Nothing OrElse Not withEventsProperty.IsWithEvents Then Return Nothing End If targetType = TryCast(Await SymbolFinder.FindSourceDefinitionAsync(withEventsProperty.Type, document.Project.Solution, cancellationToken).ConfigureAwait(False), INamedTypeSymbol) End If targetType = TryCast(Await SymbolFinder.FindSourceDefinitionAsync(targetType, document.Project.Solution, cancellationToken).ConfigureAwait(False), INamedTypeSymbol) If targetType Is Nothing OrElse Not (targetType.TypeKind = TypeKind.Class OrElse targetType.TypeKind = TypeKind.Interface) OrElse targetType.IsAnonymousType Then Return Nothing End If ' Our target type may be from a CSharp file, in which case we should resolve it to our VB compilation. Dim originalTargetType = targetType targetType = DirectCast(targetType.GetSymbolKey().Resolve(semanticModel.Compilation).Symbol, INamedTypeSymbol) If targetType Is Nothing Then Return Nothing End If If semanticModel.LookupSymbols(handlesClauseItem.SpanStart, container:=targetType, name:=handlesClauseItem.EventMember.Identifier.ValueText). Any(Function(x) x.MatchesKind(SymbolKind.Event) AndAlso x.Name = handlesClauseItem.EventMember.Identifier.ValueText) Then Return Nothing End If If targetType.GetMembers(handlesClauseItem.EventMember.Identifier.ValueText).Any() Then Return Nothing End If Dim codeGenService = document.Project.Solution.Workspace.Services.GetLanguageServices(originalTargetType.Language).GetService(Of ICodeGenerationService) ' Let's bind the method declaration so we can get its parameters. Dim boundMethod = semanticModel.GetDeclaredSymbol(handlesClauseItem.GetAncestor(Of MethodStatementSyntax)(), cancellationToken) If boundMethod Is Nothing Then Return Nothing End If Dim actualEventName = handlesClauseItem.EventMember.Identifier.ValueText Dim semanticFactService = document.Project.Solution.Workspace.Services.GetLanguageServices(originalTargetType.Language).GetService(Of ISemanticFactsService) If semanticFactService.SupportsParameterizedEvents Then ' We need to generate the delegate, too. Dim delegateType = CodeGenerationSymbolFactory.CreateDelegateTypeSymbol(Nothing, Accessibility.Public, Nothing, semanticModel.Compilation.GetSpecialType(SpecialType.System_Void), name:=actualEventName + "Handler", parameters:=boundMethod.GetParameters()) Dim generatedEvent = CodeGenerationSymbolFactory.CreateEventSymbol(attributes:=SpecializedCollections.EmptyList(Of AttributeData)(), accessibility:=Accessibility.Public, modifiers:=Nothing, explicitInterfaceSymbol:=Nothing, type:=delegateType, name:=actualEventName, parameterList:=TryCast(boundMethod, IMethodSymbol).Parameters) Return New GenerateEventCodeAction(document.Project.Solution, originalTargetType, generatedEvent, delegateType, codeGenService, New CodeGenerationOptions()) Else Dim generatedEvent = CodeGenerationSymbolFactory.CreateEventSymbol(attributes:=SpecializedCollections.EmptyList(Of AttributeData)(), accessibility:=Accessibility.Public, modifiers:=Nothing, explicitInterfaceSymbol:=Nothing, type:=Nothing, name:=actualEventName, parameterList:=boundMethod.GetParameters()) Return New GenerateEventCodeAction(document.Project.Solution, TryCast(originalTargetType, INamedTypeSymbol), generatedEvent, Nothing, codeGenService, CodeGenerationOptions.Default) End If End Function End Class End Namespace
MatthieuMEZIL/roslyn
src/Features/VisualBasic/Portable/CodeFixes/GenerateEvent/GenerateEventCodeFixProvider.vb
Visual Basic
apache-2.0
24,610
Namespace DAL.Cache Public Module _Cache Private _CharacterInstance As Models.CharacterInstance = Nothing Private _CacheLocation As String = "" Public ReadOnly Property CacheLocation As String Get If _CacheLocation.IsNotSet() Then _CacheLocation = APRBase.Settings.Directory(APRBase.BaseDirectory.DropBox) If _CacheLocation.IsSet() AndAlso IO.Directory.Exists(_CacheLocation) Then _CacheLocation = "{0}\Applications\Cache\WoWEquip\".FormatWith(_CacheLocation) Else _CacheLocation = "{0}Cache\".FormatWith(APRBase.Settings.Directory(APRBase.BaseDirectory.ExecutingAssembly)) End If If Not IO.Directory.Exists(_CacheLocation) Then IO.Directory.CreateDirectory(_CacheLocation) End If End If Return _CacheLocation End Get End Property Public ReadOnly Property CharacterInstance As Models.CharacterInstance Get If _CharacterInstance Is Nothing Then _CharacterInstance = New Models.CharacterInstance() End If Return _CharacterInstance End Get End Property Public Sub Close() Using APRBase.Performance.StartCounter("DAL.Cache", "Close") APRBase.Data.JSON.SaveSingle(Of Models.CharacterInstance)("{0}CharacterInstance.JSON".FormatWith(CacheLocation), _CharacterInstance) Character.Close() End Using End Sub Public Sub Open() Using APRBase.Performance.StartCounter("DAL.Cache", "Open") _CharacterInstance = APRBase.Data.JSON.LoadSingle(Of Models.CharacterInstance)("{0}CharacterInstance.JSON".FormatWith(CacheLocation)) Character.Open() End Using End Sub End Module End Namespace
nublet/WoWEquip
DAL/_Cache.vb
Visual Basic
mit
2,041
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.18444 ' ' 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("_01.OddOrEvenIntegers.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
VanyaD/CSharp-Part1
OperatorsAndExpressionsHomework/01. OddOrEvenIntegers/My Project/Resources.Designer.vb
Visual Basic
mit
2,730
Namespace Visualisation Partial Public Class Message Implements IFixedWidthWriteable #Region " Private Methods " Private Sub PostConstruction() Dim lst_Values As New List(Of String)(Values) Dim max_Length As Integer = 0 For i As Integer = 0 To lst_Values.Count - 1 If String.IsNullOrEmpty(lst_Values(i)) Then lst_Values.RemoveAt(i) If i >= lst_Values.Count - 1 Then Exit For Else i -= 1 Else lst_Values(i) = lst_Values(i).Replace(Environment.NewLine, SPACE) max_Length = Math.Max(max_Length, lst_Values(i).Length) End If Next Values = lst_Values.ToArray() m_DisplayTitle = String.Concat("-- ", Title, " --") m_MaxLength = max_Length End Sub #End Region #Region " ICommandsFormatted Implementation " Private Function FixedWidthWrite( _ ByVal intoWidth As Integer, _ ByRef writer As ICommandsOutputWriter, _ ByRef idealWidth As Integer _ ) As ICommandsOutputWriter _ Implements IFixedWidthWriteable.Write Dim maxLength As Integer = System.Math.Min(MaxLength, intoWidth) idealWidth = Math.Max(idealWidth, MaxLength) ' Write the Messages Title Dim messageTitle As String = DisplayTitle If messageTitle.Length < intoWidth Then maxLength = System.Math.Max(maxLength, messageTitle.Length) writer.Write(messageTitle, Type) writer.Write(New String(HYPHEN, maxLength - messageTitle.Length), Type) Else While writer.FixedWidthWrite(messageTitle, intoWidth, Type) writer.TerminateLine() End While End If writer.TerminateLine() ' End ' Write the Messages For i As Integer = 0 To Values.Length - 1 Dim valueToWrite As String = Values(i) If valueToWrite.Length < intoWidth Then writer.Write(valueToWrite, Type) Else While writer.FixedWidthWrite(valueToWrite, intoWidth, Type) writer.TerminateLine() End While End If writer.TerminateLine() Next Return writer End Function #End Region #Region " Public Shared Methods " Public Shared Function Create( _ ByVal title As String, _ ByVal type As InformationType, _ ByVal ParamArray values As String() _ ) As Message If String.IsNullOrEmpty(title) Then Select Case type Case InformationType.[Debug] title = DEBUG_TITLE Case InformationType.[Error] title = ERROR_TITLE Case InformationType.Information title = INFORMATION_TITLE Case InformationType.Performance title = PERFORMANCE_TITLE Case InformationType.Question title = QUESTION_TITLE Case InformationType.Success title = SUCCESS_TITLE Case InformationType.Warning title = WARNING_TITLE Case Else title = String.Empty End Select End If Return New Message(title, type, Values) End Function #End Region End Class End Namespace
thiscouldbejd/Leviathan
_Visualisation/Partials/Message.vb
Visual Basic
mit
2,966
Imports System.Data Partial Class fPagos_Cheque_BOD_GPV 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 loComandoSeleccionar As New StringBuilder() loComandoSeleccionar.AppendLine(" SELECT Pagos.Cod_Pro, ") loComandoSeleccionar.AppendLine(" COALESCE(Bancos.nom_Ban,'') AS Cod_Ban, ") loComandoSeleccionar.AppendLine(" COALESCE(Detalles_Pagos.num_doc,'') as cheque, ") loComandoSeleccionar.AppendLine(" Proveedores.Nom_Pro, ") loComandoSeleccionar.AppendLine(" Proveedores.Rif, ") loComandoSeleccionar.AppendLine(" Proveedores.Nit, ") loComandoSeleccionar.AppendLine(" Proveedores.Dir_Fis, ") loComandoSeleccionar.AppendLine(" Proveedores.Telefonos, ") loComandoSeleccionar.AppendLine(" Proveedores.Fax, ") loComandoSeleccionar.AppendLine(" Pagos.Documento, ") loComandoSeleccionar.AppendLine(" CAST(DAY(Pagos.Fec_Ini) AS VARCHAR) +' de ' + ") loComandoSeleccionar.AppendLine(" (CASE MONTH(Pagos.Fec_Ini) ") loComandoSeleccionar.AppendLine(" WHEN 1 THEN 'Enero' ") loComandoSeleccionar.AppendLine(" WHEN 2 THEN 'Febrero' ") loComandoSeleccionar.AppendLine(" WHEN 3 THEN 'Marzo' ") loComandoSeleccionar.AppendLine(" WHEN 4 THEN 'Abril' ") loComandoSeleccionar.AppendLine(" WHEN 5 THEN 'Mayo' ") loComandoSeleccionar.AppendLine(" WHEN 6 THEN 'Junio' ") loComandoSeleccionar.AppendLine(" WHEN 7 THEN 'Julio' ") loComandoSeleccionar.AppendLine(" WHEN 8 THEN 'Agosto' ") loComandoSeleccionar.AppendLine(" WHEN 9 THEN 'Septiembre' ") loComandoSeleccionar.AppendLine(" WHEN 10 THEN 'Octubre' ") loComandoSeleccionar.AppendLine(" WHEN 11 THEN 'Noviembre' ") loComandoSeleccionar.AppendLine(" ELSE 'Diciembre' ") loComandoSeleccionar.AppendLine(" END) as Mes_Dia, ") loComandoSeleccionar.AppendLine(" CAST(YEAR(Pagos.Fec_Ini) AS VARCHAR) as año, ") loComandoSeleccionar.AppendLine(" Pagos.Fec_Ini, ") loComandoSeleccionar.AppendLine(" Pagos.Fec_Fin, ") loComandoSeleccionar.AppendLine(" Pagos.Mon_Bru As Mon_Bru_Enc, ") loComandoSeleccionar.AppendLine(" (Pagos.Mon_Des * -1) As Mon_Des, ") loComandoSeleccionar.AppendLine(" Pagos.Mon_Net As Mon_Net_Enc, ") loComandoSeleccionar.AppendLine(" (Pagos.Mon_Ret * -1) As Mon_Ret_Enc, ") loComandoSeleccionar.AppendLine(" Pagos.Comentario As Comentario, ") loComandoSeleccionar.AppendLine(" Renglones_Pagos.Cod_Tip As Cod_Tip, ") loComandoSeleccionar.AppendLine(" Case Renglones_Pagos.Factura ") loComandoSeleccionar.AppendLine(" WHEN '' THEN Renglones_Pagos.doc_ori ") loComandoSeleccionar.AppendLine(" ELSE Renglones_Pagos.Factura ") loComandoSeleccionar.AppendLine(" END As Doc_Ori, ") loComandoSeleccionar.AppendLine(" '' AS Documento_Afectado, ") loComandoSeleccionar.AppendLine(" Renglones_Pagos.Renglon As Renglon, ") loComandoSeleccionar.AppendLine(" Renglones_Pagos.Mon_Bru As Mon_Bru, ") loComandoSeleccionar.AppendLine(" Renglones_Pagos.Mon_Imp As Mon_Imp, ") loComandoSeleccionar.AppendLine(" CASE Renglones_Pagos.tip_doc ") loComandoSeleccionar.AppendLine(" WHEN 'Debito' THEN Renglones_Pagos.Mon_Abo ") loComandoSeleccionar.AppendLine(" ELSE Renglones_Pagos.Mon_Abo* -1 ") loComandoSeleccionar.AppendLine(" END As Mon_Abo, ") loComandoSeleccionar.AppendLine(" Renglones_Pagos.Mon_Net As Mon_Net_Ren, ") loComandoSeleccionar.AppendLine(" CAST('' as char(400)) As Mon_Let ") loComandoSeleccionar.AppendLine("FROM Pagos ") loComandoSeleccionar.AppendLine(" LEFT JOIN Detalles_Pagos ON Detalles_pagos.documento = Pagos.documento") loComandoSeleccionar.AppendLine(" AND Detalles_Pagos.renglon = '1' ") loComandoSeleccionar.AppendLine(" AND Detalles_Pagos.tip_ope = 'Cheque' ") loComandoSeleccionar.AppendLine(" LEFT JOIN Bancos ON Bancos.cod_ban = Detalles_Pagos.cod_ban ") loComandoSeleccionar.AppendLine(" JOIN Renglones_Pagos ON Pagos.Documento = Renglones_Pagos.Documento ") loComandoSeleccionar.AppendLine(" JOIN Proveedores ON Pagos.Cod_Pro = Proveedores.Cod_Pro ") loComandoSeleccionar.AppendLine(" WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal) loComandoSeleccionar.AppendLine("UNION ALL ") loComandoSeleccionar.AppendLine("SELECT Pagos.Cod_Pro, ") loComandoSeleccionar.AppendLine(" Proveedores.Nom_Pro, ") loComandoSeleccionar.AppendLine(" COALESCE(Bancos.nom_Ban,'') AS Cod_Ban, ") loComandoSeleccionar.AppendLine(" COALESCE(Detalles_Pagos.num_doc,'') as cheque, ") loComandoSeleccionar.AppendLine(" Proveedores.Rif, ") loComandoSeleccionar.AppendLine(" Proveedores.Nit, ") loComandoSeleccionar.AppendLine(" Proveedores.Dir_Fis, ") loComandoSeleccionar.AppendLine(" Proveedores.Telefonos, ") loComandoSeleccionar.AppendLine(" Proveedores.Fax, ") loComandoSeleccionar.AppendLine(" Pagos.Documento, ") loComandoSeleccionar.AppendLine(" CAST(DAY(Pagos.Fec_Ini) AS VARCHAR) +' de ' + ") loComandoSeleccionar.AppendLine(" (CASE MONTH(Pagos.Fec_Ini) ") loComandoSeleccionar.AppendLine(" WHEN 1 THEN 'Enero' ") loComandoSeleccionar.AppendLine(" WHEN 2 THEN 'Febrero' ") loComandoSeleccionar.AppendLine(" WHEN 3 THEN 'Marzo' ") loComandoSeleccionar.AppendLine(" WHEN 4 THEN 'Abril' ") loComandoSeleccionar.AppendLine(" WHEN 5 THEN 'Mayo' ") loComandoSeleccionar.AppendLine(" WHEN 6 THEN 'Junio' ") loComandoSeleccionar.AppendLine(" WHEN 7 THEN 'Julio' ") loComandoSeleccionar.AppendLine(" WHEN 8 THEN 'Agosto' ") loComandoSeleccionar.AppendLine(" WHEN 9 THEN 'Septiembre' ") loComandoSeleccionar.AppendLine(" WHEN 10 THEN 'Octubre' ") loComandoSeleccionar.AppendLine(" WHEN 11 THEN 'Noviembre' ") loComandoSeleccionar.AppendLine(" ELSE 'Diciembre' ") loComandoSeleccionar.AppendLine(" END) as Mes_Dia, ") loComandoSeleccionar.AppendLine(" CAST(YEAR(Pagos.Fec_Ini) AS VARCHAR) as año, ") loComandoSeleccionar.AppendLine(" Pagos.Fec_Ini, ") loComandoSeleccionar.AppendLine(" Pagos.Fec_Fin, ") loComandoSeleccionar.AppendLine(" Pagos.Mon_Bru As Mon_Bru_Enc, ") loComandoSeleccionar.AppendLine(" (Pagos.Mon_Des * -1) As Mon_Des, ") loComandoSeleccionar.AppendLine(" Pagos.Mon_Net As Mon_Net_Enc, ") loComandoSeleccionar.AppendLine(" (Pagos.Mon_Ret * -1) As Mon_Ret_Enc, ") loComandoSeleccionar.AppendLine(" Pagos.Comentario As Comentario, ") loComandoSeleccionar.AppendLine(" retenciones_documentos.cla_des As Cod_Tip, ") loComandoSeleccionar.AppendLine(" retenciones_documentos.Doc_des As Doc_Ori, ") loComandoSeleccionar.AppendLine(" RTRIM(CASE Cuentas_Pagar.factura ") loComandoSeleccionar.AppendLine(" WHEN '' THEN Cuentas_Pagar.documento ") loComandoSeleccionar.AppendLine(" ELSE Cuentas_Pagar.factura ") loComandoSeleccionar.AppendLine(" END) +'/'+ RTRIM(Cuentas_Pagar.cod_tip) AS Documento_Afectado, ") loComandoSeleccionar.AppendLine(" retenciones_documentos.Renglon As Renglon, ") loComandoSeleccionar.AppendLine(" retenciones_documentos.Mon_Bru As Mon_Bru, ") loComandoSeleccionar.AppendLine(" retenciones_documentos.Mon_Imp As Mon_Imp, ") loComandoSeleccionar.AppendLine(" retenciones_documentos.Mon_RET*-1 As Mon_Abo, ") loComandoSeleccionar.AppendLine(" retenciones_documentos.Mon_Net As Mon_Net_Ren, ") loComandoSeleccionar.AppendLine(" CAST('' as char(400)) As Mon_Let ") loComandoSeleccionar.AppendLine("FROM pagos ") loComandoSeleccionar.AppendLine(" LEFT JOIN Detalles_Pagos ON Detalles_pagos.documento = Pagos.documento") loComandoSeleccionar.AppendLine(" AND Detalles_Pagos.renglon = '1' ") loComandoSeleccionar.AppendLine(" AND Detalles_Pagos.tip_ope = 'Cheque' ") loComandoSeleccionar.AppendLine(" LEFT JOIN Bancos ON Bancos.cod_ban = Detalles_Pagos.cod_ban ") loComandoSeleccionar.AppendLine(" JOIN retenciones_documentos ON retenciones_documentos.documento = Pagos.Documento ") loComandoSeleccionar.AppendLine(" AND retenciones_documentos.origen = 'pagos' ") loComandoSeleccionar.AppendLine(" JOIN Cuentas_Pagar ON Cuentas_Pagar.documento = retenciones_documentos.doc_ori ") loComandoSeleccionar.AppendLine(" AND Cuentas_Pagar.cod_tip = retenciones_documentos.cla_ori ") loComandoSeleccionar.AppendLine(" JOIN Proveedores ON Pagos.Cod_Pro = Proveedores.Cod_Pro ") loComandoSeleccionar.AppendLine(" WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal) 'Me.mEscribirConsulta(loComandoSeleccionar.ToString()) Dim loServicios As New cusDatos.goDatos Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes") Dim lnMontoNumero As Decimal For Each loFilas As DataRow In laDatosReporte.Tables(0).Rows lnMontoNumero = CDec(loFilas.Item("Mon_Net_Enc")) loFilas.Item("Mon_Let") = goServicios.mConvertirMontoLetras(lnMontoNumero) Next loFilas loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("fPagos_Cheque_BOD_GPV", laDatosReporte) Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvfPagos_Cheque_BOD_GPV.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: 10/09/15: Codigo inicial '-------------------------------------------------------------------------------------------' ' EAG: 16/09/15: Agregar las retenciones al select a través de un union all '-------------------------------------------------------------------------------------------'
kodeitsolutions/ef-reports
fPagos_Cheque_BOD_GPV.aspx.vb
Visual Basic
mit
11,940
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class MaskForm 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() components = New System.ComponentModel.Container Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(800, 450) Me.Text = "Form1" End Sub End Class
xieguigang/MassSpectrum-toolkits
src/mzkit/ControlLibrary/Message/MaskForm.Designer.vb
Visual Basic
mit
1,123
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class frmTempConverter 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.cmdEnd = New System.Windows.Forms.Button() Me.cmdClear = New System.Windows.Forms.Button() Me.cmdConvert = New System.Windows.Forms.Button() Me.txtInputTemp = New System.Windows.Forms.TextBox() Me.txtDisplayTemp = New System.Windows.Forms.Label() Me.lblInputTemp = New System.Windows.Forms.Label() Me.lblInfo = New System.Windows.Forms.Label() Me.lblCelciusTemp = New System.Windows.Forms.Label() Me.SuspendLayout() ' 'cmdEnd ' Me.cmdEnd.BackColor = System.Drawing.Color.Red Me.cmdEnd.Cursor = System.Windows.Forms.Cursors.Default Me.cmdEnd.Font = New System.Drawing.Font("Arial", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.cmdEnd.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdEnd.Location = New System.Drawing.Point(231, 321) Me.cmdEnd.Name = "cmdEnd" Me.cmdEnd.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdEnd.Size = New System.Drawing.Size(129, 49) Me.cmdEnd.TabIndex = 13 Me.cmdEnd.Text = "END" Me.cmdEnd.UseVisualStyleBackColor = False ' 'cmdClear ' Me.cmdClear.BackColor = System.Drawing.Color.Red Me.cmdClear.Cursor = System.Windows.Forms.Cursors.Default Me.cmdClear.Font = New System.Drawing.Font("Arial", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.cmdClear.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdClear.Location = New System.Drawing.Point(26, 321) Me.cmdClear.Name = "cmdClear" Me.cmdClear.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdClear.Size = New System.Drawing.Size(145, 49) Me.cmdClear.TabIndex = 12 Me.cmdClear.Text = "CLEAR" Me.cmdClear.UseVisualStyleBackColor = False ' 'cmdConvert ' Me.cmdConvert.BackColor = System.Drawing.Color.Red Me.cmdConvert.Cursor = System.Windows.Forms.Cursors.Default Me.cmdConvert.Font = New System.Drawing.Font("Arial", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.cmdConvert.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdConvert.Location = New System.Drawing.Point(61, 188) Me.cmdConvert.Name = "cmdConvert" Me.cmdConvert.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdConvert.Size = New System.Drawing.Size(249, 49) Me.cmdConvert.TabIndex = 11 Me.cmdConvert.Text = "Convert" Me.cmdConvert.UseVisualStyleBackColor = False ' 'txtInputTemp ' Me.txtInputTemp.AcceptsReturn = True Me.txtInputTemp.BackColor = System.Drawing.SystemColors.Window Me.txtInputTemp.Cursor = System.Windows.Forms.Cursors.IBeam Me.txtInputTemp.Font = New System.Drawing.Font("Arial", 24.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.txtInputTemp.ForeColor = System.Drawing.SystemColors.WindowText Me.txtInputTemp.Location = New System.Drawing.Point(243, 103) Me.txtInputTemp.MaxLength = 0 Me.txtInputTemp.Name = "txtInputTemp" Me.txtInputTemp.RightToLeft = System.Windows.Forms.RightToLeft.No Me.txtInputTemp.Size = New System.Drawing.Size(111, 44) Me.txtInputTemp.TabIndex = 10 Me.txtInputTemp.Text = " " Me.txtInputTemp.TextAlign = System.Windows.Forms.HorizontalAlignment.Center ' 'txtDisplayTemp ' Me.txtDisplayTemp.BackColor = System.Drawing.SystemColors.Control Me.txtDisplayTemp.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D Me.txtDisplayTemp.Cursor = System.Windows.Forms.Cursors.Default Me.txtDisplayTemp.FlatStyle = System.Windows.Forms.FlatStyle.Popup Me.txtDisplayTemp.Font = New System.Drawing.Font("Arial", 24.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.txtDisplayTemp.ForeColor = System.Drawing.SystemColors.ControlText Me.txtDisplayTemp.Location = New System.Drawing.Point(243, 252) Me.txtDisplayTemp.Name = "txtDisplayTemp" Me.txtDisplayTemp.RightToLeft = System.Windows.Forms.RightToLeft.No Me.txtDisplayTemp.Size = New System.Drawing.Size(111, 41) Me.txtDisplayTemp.TabIndex = 15 Me.txtDisplayTemp.Text = " " Me.txtDisplayTemp.TextAlign = System.Drawing.ContentAlignment.TopCenter ' 'lblInputTemp ' Me.lblInputTemp.BackColor = System.Drawing.Color.SpringGreen Me.lblInputTemp.Cursor = System.Windows.Forms.Cursors.Default Me.lblInputTemp.Font = New System.Drawing.Font("Arial", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblInputTemp.ForeColor = System.Drawing.SystemColors.ControlText Me.lblInputTemp.Location = New System.Drawing.Point(29, 106) Me.lblInputTemp.Name = "lblInputTemp" Me.lblInputTemp.RightToLeft = System.Windows.Forms.RightToLeft.No Me.lblInputTemp.Size = New System.Drawing.Size(204, 41) Me.lblInputTemp.TabIndex = 9 Me.lblInputTemp.Text = "Enter Temperature:" Me.lblInputTemp.TextAlign = System.Drawing.ContentAlignment.MiddleCenter ' 'lblInfo ' Me.lblInfo.BackColor = System.Drawing.Color.SpringGreen Me.lblInfo.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D Me.lblInfo.Cursor = System.Windows.Forms.Cursors.Default Me.lblInfo.FlatStyle = System.Windows.Forms.FlatStyle.Popup Me.lblInfo.Font = New System.Drawing.Font("Arial", 18.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblInfo.ForeColor = System.Drawing.SystemColors.ControlText Me.lblInfo.Location = New System.Drawing.Point(29, 21) Me.lblInfo.Name = "lblInfo" Me.lblInfo.RightToLeft = System.Windows.Forms.RightToLeft.No Me.lblInfo.Size = New System.Drawing.Size(325, 77) Me.lblInfo.TabIndex = 8 Me.lblInfo.Text = " " Me.lblInfo.TextAlign = System.Drawing.ContentAlignment.TopCenter ' 'lblCelciusTemp ' Me.lblCelciusTemp.Font = New System.Drawing.Font("Arial", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblCelciusTemp.Location = New System.Drawing.Point(29, 265) Me.lblCelciusTemp.Name = "lblCelciusTemp" Me.lblCelciusTemp.Size = New System.Drawing.Size(214, 21) Me.lblCelciusTemp.TabIndex = 16 Me.lblCelciusTemp.Text = "Celcius Temperature:" ' 'frmTempConverter ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.Color.SpringGreen Me.ClientSize = New System.Drawing.Size(399, 402) Me.Controls.Add(Me.lblCelciusTemp) Me.Controls.Add(Me.cmdEnd) Me.Controls.Add(Me.cmdClear) Me.Controls.Add(Me.cmdConvert) Me.Controls.Add(Me.txtInputTemp) Me.Controls.Add(Me.txtDisplayTemp) Me.Controls.Add(Me.lblInputTemp) Me.Controls.Add(Me.lblInfo) Me.Name = "frmTempConverter" Me.Text = "Temperature Converter" Me.ResumeLayout(False) Me.PerformLayout() End Sub Public WithEvents cmdEnd As System.Windows.Forms.Button Public WithEvents cmdClear As System.Windows.Forms.Button Public WithEvents cmdConvert As System.Windows.Forms.Button Public WithEvents txtInputTemp As System.Windows.Forms.TextBox Public WithEvents txtDisplayTemp As System.Windows.Forms.Label Public WithEvents lblInputTemp As System.Windows.Forms.Label Public WithEvents lblInfo As System.Windows.Forms.Label Friend WithEvents lblCelciusTemp As System.Windows.Forms.Label End Class
miguel2192/CSC-162
Rodriguez_Temp/runningTotal/Form1.Designer.vb
Visual Basic
mit
9,002
Imports System.ComponentModel Imports System.Drawing Imports System.Windows.Forms Imports Telerik.Reporting Imports Telerik.Reporting.Drawing Partial Public Class RepVentas Inherits Telerik.Reporting.Report Public Sub New() InitializeComponent() End Sub End Class
crackper/SistFoncreagro
SistFoncreagro.Report/RepVentas.vb
Visual Basic
mit
284
#Region "Microsoft.VisualBasic::61e0147fa38169752ac130c10d9b9558, src\metadb\FormulaSearch.Extensions\AtomGroups\Others.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: ' Class Others ' ' Properties: nitro_group ' ' /********************************************************************************/ #End Region Imports BioNovoGene.BioDeep.Chemoinformatics.Formula Public Class Others Public Shared ReadOnly Property nitro_group As Formula = FormulaScanner.ScanFormula("NO2") End Class
xieguigang/MassSpectrum-toolkits
src/metadb/FormulaSearch.Extensions/AtomGroups/Others.vb
Visual Basic
mit
1,931
Namespace Http Namespace Type3 ''' <summary> ''' An http server with an async I/O model implemented via SocketAsyncEventArgs (.NET 3.5+). Utilizes a special async model designed for the Socket class which consists of a shared buffer and pre-allocated object pool for async state objects to avoid object instantiation and memory thrashing/fragmentation during every http request. ''' The MSDN code example for this pattern is very poor. The issues (and solution) are explained in the Background section in this tutorial: http://www.codeproject.com/Articles/83102/C-SocketAsyncEventArgs-High-Performance-Socket-Cod?fid=1573061 ''' </summary> ''' <remarks></remarks> Public Class Server End Class End Namespace End Namespace
perrybutler/rapid-server
rapidserverlib/Http.Type3.vb
Visual Basic
mit
790
' 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.Globalization Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Editor.Commands Imports Microsoft.CodeAnalysis.Editor.CSharp.Formatting Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Text.Projection Imports Microsoft.VisualStudio.Utilities Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Public Class CSharpCompletionCommandHandlerTests <WorkItem(541201, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541201")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TabCommitsWithoutAUniqueMatch() As Task Using state = TestState.CreateCSharpTestState( <Document> $$ </Document>) state.SendTypeChars("using System.Ne") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Net", isHardSelected:=True) state.SendTypeChars("x") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Net", isSoftSelected:=True) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("using System.Net", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAtEndOfFile() As Task Using state = TestState.CreateCSharpTestState( <Document>$$</Document>) state.SendTypeChars("us") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("using", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotAtStartOfExistingWord() As Task Using state = TestState.CreateCSharpTestState( <Document>$$using</Document>) state.SendTypeChars("u") Await state.AssertNoCompletionSession() Assert.Contains("using", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMSCorLibTypes() As Task Using state = TestState.CreateCSharpTestState( <Document> using System; class c : $$ </Document>) state.SendTypeChars("A") Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll(displayText:={"Attribute", "Exception", "IDisposable"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFiltering1() As Task Using state = TestState.CreateCSharpTestState( <Document> using System; class c { $$ </Document>) state.SendTypeChars("Sy") Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll(displayText:={"OperatingSystem", "System", "SystemException"})) Assert.False(state.CompletionItemsContainsAny(displayText:={"Exception", "Activator"})) End Using End Function ' NOTE(cyrusn): This should just be a unit test for SymbolCompletionProvider. However, I'm ' just porting the integration tests to here for now. <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMultipleTypes() As Task Using state = TestState.CreateCSharpTestState( <Document> class C { $$ } struct S { } enum E { } interface I { } delegate void D(); </Document>) state.SendTypeChars("C") Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll(displayText:={"C", "S", "E", "I", "D"})) End Using End Function ' NOTE(cyrusn): This should just be a unit test for KeywordCompletionProvider. However, I'm ' just porting the integration tests to here for now. <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInEmptyFile() As Task Using state = TestState.CreateCSharpTestState( <Document> $$ </Document>) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll(displayText:={"abstract", "class", "namespace"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotAfterTypingDotAfterIntegerLiteral() As Task Using state = TestState.CreateCSharpTestState( <Document> class c { void M() { 3$$ } } </Document>) state.SendTypeChars(".") Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterExplicitInvokeAfterDotAfterIntegerLiteral() As Task Using state = TestState.CreateCSharpTestState( <Document> class c { void M() { 3.$$ } } </Document>) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll({"ToString"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEnterIsConsumed() As Task Using state = TestState.CreateCSharpTestState( <Document> class Class1 { void Main(string[] args) { $$ } }</Document>) state.SendTypeChars("System.TimeSpan.FromMin") state.SendReturn() Await state.WaitForAsynchronousOperationsAsync() Assert.Equal(<text> class Class1 { void Main(string[] args) { System.TimeSpan.FromMinutes } }</text>.NormalizedValue, state.GetDocumentText()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDescription1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; /// <summary> /// TestDocComment /// </summary> class TestException : Exception { } class MyException : $$]]></Document>) state.SendTypeChars("Test") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(description:="class TestException" & vbCrLf & "TestDocComment") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestObjectCreationPreselection1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System.Collections.Generic; class C { public void Goo() { List<int> list = new$$ } }]]></Document>) state.SendTypeChars(" ") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="List<int>", isHardSelected:=True) Assert.True(state.CompletionItemsContainsAll(displayText:={"LinkedList<>", "List<>", "System"})) state.SendTypeChars("Li") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="List<int>", isHardSelected:=True) Assert.True(state.CompletionItemsContainsAll(displayText:={"LinkedList<>", "List<>"})) Assert.False(state.CompletionItemsContainsAny(displayText:={"System"})) state.SendTypeChars("n") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="LinkedList<>", isHardSelected:=True) state.SendBackspace() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="List<int>", isHardSelected:=True) state.SendTab() Assert.Contains("new List<int>", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDeconstructionDeclaration() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { var ($$ } }]]></Document>) state.SendTypeChars("i") Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDeconstructionDeclaration2() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { var (a, $$ } }]]></Document>) state.SendTypeChars("i") Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDeconstructionDeclaration3() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { var ($$) = (1, 2); } }]]></Document>) state.SendTypeChars("i") Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedDeconstructionDeclarationWithVar() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { (var a$$) = (1, 2); } }]]></Document>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem(displayText:="as", isHardSelected:=False) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedDeconstructionDeclarationWithVarAfterComma() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { (var a, var a$$) = (1, 2); } }]]></Document>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem(displayText:="as", isHardSelected:=False) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedVarDeconstructionDeclarationWithVar() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { (var a, var ($$)) = (1, 2); } }]]></Document>) state.SendTypeChars("a") Await state.AssertNoCompletionSession() state.SendTypeChars(", a") Await state.AssertNoCompletionSession() Assert.Contains("(var a, var (a, a)) = ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestVarDeconstructionDeclarationWithVar() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { $$ } }]]></Document>) state.SendTypeChars("va") Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True) state.SendTypeChars(" (a") Await state.AssertNoCompletionSession() state.SendTypeChars(", a") Await state.AssertNoCompletionSession() Assert.Contains("var (a, a", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedDeconstructionDeclarationWithSymbol() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { ($$) = (1, 2); } }]]></Document>) state.SendTypeChars("vari") Await state.AssertSelectedCompletionItem(displayText:="Variable", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("(Variable ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertNoCompletionSession() state.SendTypeChars("x, vari") Await state.AssertSelectedCompletionItem(displayText:="Variable", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("(Variable x, Variable ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedDeconstructionDeclarationWithInt() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Integer { public void Goo() { ($$) = (1, 2); } }]]></Document>) state.SendTypeChars("int") Await state.AssertSelectedCompletionItem(displayText:="int", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("(int ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertNoCompletionSession() state.SendTypeChars("x, int") Await state.AssertSelectedCompletionItem(displayText:="int", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("(int x, int ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestIncompleteParenthesizedDeconstructionDeclaration() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { ($$ } }]]></Document>) state.SendTypeChars("va") Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendTypeChars(", va") Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendTypeChars(")") Assert.Contains("(var a, var a)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestIncompleteParenthesizedDeconstructionDeclaration2() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { ($$) } }]]></Document>) state.SendTypeChars("va") Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendTypeChars(", va") Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendReturn() Assert.Contains("(var a, var a", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackspaceInIncompleteParenthesizedDeconstructionDeclaration() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { (var as$$ } }]]></Document>) state.Workspace.Options = state.Workspace.Options.WithChangedOption( CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True) state.SendBackspace() ' This completion is hard-selected because the suggestion mode never triggers on backspace ' See issue https://github.com/dotnet/roslyn/issues/15302 Await state.AssertSelectedCompletionItem(displayText:="as", isHardSelected:=True) state.SendTypeChars(", var as") state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendTypeChars(")") Await state.AssertNoCompletionSession() Assert.Contains("(var as, var a)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackspaceInParenthesizedDeconstructionDeclaration() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { (var as$$) } }]]></Document>) state.Workspace.Options = state.Workspace.Options.WithChangedOption( CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True) state.SendBackspace() ' This completion is hard-selected because the suggestion mode never triggers on backspace ' See issue https://github.com/dotnet/roslyn/issues/15302 Await state.AssertSelectedCompletionItem(displayText:="as", isHardSelected:=True) state.SendTypeChars(", var as") state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendReturn() Await state.AssertNoCompletionSession() Assert.Contains("(var as, var a", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(17256, "https://github.com/dotnet/roslyn/issues/17256")> Public Async Function TestThrowExpression() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public object Goo() { return null ?? throw new$$ } }]]></Document>) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="Exception", isHardSelected:=True) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(17256, "https://github.com/dotnet/roslyn/issues/17256")> Public Async Function TestThrowStatement() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public object Goo() { throw new$$ } }]]></Document>) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="Exception", isHardSelected:=True) End Using End Function <WpfFact> Public Async Function TestNonTrailingNamedArgumentInCSharp7_1() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" LanguageVersion="CSharp7_1" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"> class C { public void M() { int better = 2; M(a: 1, $$) } public void M(int a, int bar, int c) { } } </Document> </Project> </Workspace>) state.SendTypeChars("b") Await state.AssertSelectedCompletionItem(displayText:="bar:", isHardSelected:=True) state.SendTypeChars("e") Await state.AssertSelectedCompletionItem(displayText:="bar:", isSoftSelected:=True) End Using End Function <WpfFact> Public Async Function TestNonTrailingNamedArgumentInCSharp7_2() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" LanguageVersion="CSharp7_2" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"> class C { public void M() { int better = 2; M(a: 1, $$) } public void M(int a, int bar, int c) { } } </Document> </Project> </Workspace>) state.SendTypeChars("b") Await state.AssertSelectedCompletionItem(displayText:="better", isHardSelected:=True) state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="bar:", isHardSelected:=True) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="better", isHardSelected:=True) state.SendTypeChars(", ") Assert.Contains("M(a: 1, better,", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")> Public Async Function TestDefaultSwitchLabel() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void M(object o) { switch (o) { default: goto $$ } } }]]></Document>) state.SendTypeChars("d") Await state.AssertSelectedCompletionItem(displayText:="default", isHardSelected:=True) state.SendTypeChars(";") Assert.Contains("goto default;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")> Public Async Function TestGotoOrdinaryLabel() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void M(object o) { label1: goto $$ } }]]></Document>) state.SendTypeChars("l") Await state.AssertSelectedCompletionItem(displayText:="label1", isHardSelected:=True) state.SendTypeChars(";") Assert.Contains("goto label1;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")> Public Async Function TestEscapedDefaultLabel() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void M(object o) { @default: goto $$ } }]]></Document>) state.SendTypeChars("d") Await state.AssertSelectedCompletionItem(displayText:="@default", isHardSelected:=True) state.SendTypeChars(";") Assert.Contains("goto @default;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")> Public Async Function TestEscapedDefaultLabel2() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void M(object o) { switch (o) { default: @default: goto $$ } } }]]></Document>) state.SendTypeChars("d") Await state.AssertSelectedCompletionItem(displayText:="default", isHardSelected:=True) state.SendTypeChars(";") Assert.Contains("goto default;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")> Public Async Function TestEscapedDefaultLabelWithoutSwitch() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void M(object o) { @default: goto $$ } }]]></Document>) state.SendTypeChars("d") Await state.AssertSelectedCompletionItem(displayText:="@default", isHardSelected:=True) state.SendTypeChars(";") Assert.Contains("goto @default;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestSymbolInTupleLiteral() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void Fo() { ($$) } }]]></Document>) state.SendTypeChars("F") Await state.AssertSelectedCompletionItem(displayText:="Fo", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("(F:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestSymbolInTupleLiteralAfterComma() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void Fo() { (x, $$) } }]]></Document>) state.SendTypeChars("F") Await state.AssertSelectedCompletionItem(displayText:="Fo", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("(x, F:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function ColonInTupleNameInTupleLiteral() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = ($$ } }]]></Document>) state.SendTypeChars("fi") Await state.AssertSelectedCompletionItem(displayText:="first:", isHardSelected:=True) Assert.Equal("first", state.CurrentCompletionPresenterSession.SelectedItem.FilterText) state.SendTypeChars(":") Assert.Contains("(first:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function ColonInExactTupleNameInTupleLiteral() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = ($$ } }]]></Document>) state.SendTypeChars("first") Await state.AssertSelectedCompletionItem(displayText:="first:", isHardSelected:=True) Assert.Equal("first", state.CurrentCompletionPresenterSession.SelectedItem.FilterText) state.SendTypeChars(":") Assert.Contains("(first:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function ColonInTupleNameInTupleLiteralAfterComma() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = (0, $$ } }]]></Document>) state.SendTypeChars("se") Await state.AssertSelectedCompletionItem(displayText:="second:", isHardSelected:=True) Assert.Equal("second", state.CurrentCompletionPresenterSession.SelectedItem.FilterText) state.SendTypeChars(":") Assert.Contains("(0, second:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function TabInTupleNameInTupleLiteral() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = ($$ } }]]></Document>) state.SendTypeChars("fi") Await state.AssertSelectedCompletionItem(displayText:="first:", isHardSelected:=True) Assert.Equal("first", state.CurrentCompletionPresenterSession.SelectedItem.FilterText) state.SendTab() state.SendTypeChars(":") state.SendTypeChars("0") Assert.Contains("(first:0", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function TabInExactTupleNameInTupleLiteral() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = ($$ } }]]></Document>) state.SendTypeChars("first") Await state.AssertSelectedCompletionItem(displayText:="first:", isHardSelected:=True) Assert.Equal("first", state.CurrentCompletionPresenterSession.SelectedItem.FilterText) state.SendTab() state.SendTypeChars(":") state.SendTypeChars("0") Assert.Contains("(first:0", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function TabInTupleNameInTupleLiteralAfterComma() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = (0, $$ } }]]></Document>) state.SendTypeChars("se") Await state.AssertSelectedCompletionItem(displayText:="second:", isHardSelected:=True) Assert.Equal("second", state.CurrentCompletionPresenterSession.SelectedItem.FilterText) state.SendTab() state.SendTypeChars(":") state.SendTypeChars("1") Assert.Contains("(0, second:1", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestKeywordInTupleLiteral() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { ($$) } }]]></Document>) state.SendTypeChars("i") Await state.AssertSelectedCompletionItem(displayText:="int", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("(i:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestTupleType() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { ($$) } }]]></Document>) state.SendTypeChars("i") Await state.AssertSelectedCompletionItem(displayText:="int", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("(int ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestDefaultKeyword() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { switch(true) { $$ } } }]]></Document>) state.SendTypeChars("def") Await state.AssertSelectedCompletionItem(displayText:="default", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("default:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestParenthesizedExpression() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void Fo() { ($$) } }]]></Document>) state.SendTypeChars("F") Await state.AssertSelectedCompletionItem(displayText:="Fo", isHardSelected:=True) state.SendTypeChars(".") Assert.Contains("(Fo.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestInvocationExpression() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo(int Alice) { Goo($$) } }]]></Document>) state.SendTypeChars("A") Await state.AssertSelectedCompletionItem(displayText:="Alice", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("Goo(Alice:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestInvocationExpressionAfterComma() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo(int Alice, int Bob) { Goo(1, $$) } }]]></Document>) state.SendTypeChars("B") Await state.AssertSelectedCompletionItem(displayText:="Bob", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("Goo(1, Bob:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestCaseLabel() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void Fo() { switch (1) { case $$ } } }]]></Document>) state.SendTypeChars("F") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Fo", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("case Fo:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(543268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543268")> Public Async Function TestTypePreselection1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ partial class C { } partial class C { $$ }]]></Document>) state.SendTypeChars("C") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="C", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertCompletionSession() End Using End Function <WorkItem(543519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543519")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNewPreselectionAfterVar() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { var c = $$ } }]]></Document>) state.SendTypeChars("new ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(543559, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543559")> <WorkItem(543561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543561")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEscapedIdentifiers() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class @return { void goo() { $$ } } ]]></Document>) state.SendTypeChars("@") Await state.AssertNoCompletionSession() state.SendTypeChars("r") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="@return", isHardSelected:=True) state.SendTab() Assert.Contains("@return", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(543771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543771")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitUniqueItem1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { static void Main(string[] args) { Console.WriteL$$(); } }]]></Document>) state.SendCommitUniqueCompletionListItem() Await state.AssertNoCompletionSession() Assert.Contains("WriteLine()", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(543771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543771")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitUniqueItem2() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { static void Main(string[] args) { Console.WriteL$$ine(); } }]]></Document>) state.SendCommitUniqueCompletionListItem() Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitForUsingDirective1() As Task Using state = TestState.CreateCSharpTestState( <Document> $$ </Document>) state.SendTypeChars("using Sys") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True) state.SendTypeChars("(") Await state.AssertNoCompletionSession() Assert.Contains("using Sys(", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitForUsingDirective2() As Task Using state = TestState.CreateCSharpTestState( <Document> $$ </Document>) state.SendTypeChars("using Sys") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True) state.SendTypeChars(".") Await state.AssertCompletionSession() Assert.Contains("using System.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitForUsingDirective3() As Task Using state = TestState.CreateCSharpTestState( <Document> $$ </Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendTypeChars("using Sys") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True) state.SendTypeChars(";") Await state.AssertNoCompletionSession() state.AssertMatchesTextStartingAtLine(1, "using System;") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitForUsingDirective4() As Task Using state = TestState.CreateCSharpTestState( <Document> $$ </Document>) state.SendTypeChars("using Sys") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() Assert.Contains("using Sys ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function KeywordsIncludedInObjectCreationCompletion() As Task Using state = TestState.CreateCSharpTestState( <Document> class C { void Goo() { string s = new$$ } } </Document>) state.SendTypeChars(" ") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="string", isHardSelected:=True) Assert.True(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(c) c.DisplayText = "int")) End Using End Function <WorkItem(544293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544293")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NoKeywordsOrSymbolsAfterNamedParameter() As Task Using state = TestState.CreateCSharpTestState( <Document> class Goo { void Test() { object m = null; Method(obj:m, $$ } void Method(object obj, int num = 23, string str = "") { } } </Document>) state.SendTypeChars("a") Await state.AssertCompletionSession() Assert.True(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "num:")) Assert.False(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "System")) Assert.False(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(c) c.DisplayText = "int")) End Using End Function <WorkItem(544017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544017")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionTriggeredOnSpace() As Task Using state = TestState.CreateCSharpTestState( <Document> enum Numeros { Uno, Dos } class Goo { void Bar(int a, Numeros n) { } void Baz() { Bar(0$$ } } </Document>) state.SendTypeChars(", ") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Numeros", isHardSelected:=True) Assert.Equal(1, state.CurrentCompletionPresenterSession.CompletionItems.Where(Function(c) c.DisplayText = "Numeros").Count()) End Using End Function <WorkItem(479078, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/479078")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionTriggeredOnSpaceForNullables() As Task Using state = TestState.CreateCSharpTestState( <Document> enum Numeros { Uno, Dos } class Goo { void Bar(int a, Numeros? n) { } void Baz() { Bar(0$$ } } </Document>) state.SendTypeChars(", ") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Numeros", isHardSelected:=True) Assert.Equal(1, state.CurrentCompletionPresenterSession.CompletionItems.Where(Function(c) c.DisplayText = "Numeros").Count()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionTriggeredOnDot() As Task Using state = TestState.CreateCSharpTestState( <Document> enum Numeros { Uno, Dos } class Goo { void Bar() { Numeros num = $$ } } </Document>) state.SendTypeChars("Nu.") Await state.WaitForAsynchronousOperationsAsync() Assert.Contains("Numeros num = Numeros.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionNotTriggeredOnOtherCommitCharacters() As Task Await EnumCompletionNotTriggeredOn("+"c) Await EnumCompletionNotTriggeredOn("{"c) Await EnumCompletionNotTriggeredOn(" "c) Await EnumCompletionNotTriggeredOn(";"c) End Function Private Async Function EnumCompletionNotTriggeredOn(c As Char) As Task Using state = TestState.CreateCSharpTestState( <Document> enum Numeros { Uno, Dos } class Goo { void Bar() { Numeros num = $$ } } </Document>) state.SendTypeChars("Nu") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Numeros", isHardSelected:=True) state.SendTypeChars(c.ToString()) Await state.WaitForAsynchronousOperationsAsync() Assert.NotEqual("Numberos", state.CurrentCompletionPresenterSession?.SelectedItem?.DisplayText) Assert.Contains(String.Format("Numeros num = Nu{0}", c), state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(544296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544296")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestVerbatimNamedIdentifierFiltering() As Task Using state = TestState.CreateCSharpTestState( <Document> class Program { void Goo(int @int) { Goo($$ } } </Document>) state.SendTypeChars("i") Await state.AssertCompletionSession() Assert.True(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "@int:")) state.SendTypeChars("n") Await state.WaitForAsynchronousOperationsAsync() Assert.True(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "@int:")) state.SendTypeChars("t") Await state.WaitForAsynchronousOperationsAsync() Assert.True(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "@int:")) End Using End Function <WorkItem(543687, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543687")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoPreselectInInvalidObjectCreationLocation() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { void Test() { $$ } } class Bar { } class Goo<T> : IGoo<T> { } interface IGoo<T> { }]]> </Document>) state.SendTypeChars("IGoo<Bar> a = new ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(544925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544925")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestQualifiedEnumSelection() As Task Using state = TestState.CreateCSharpTestState( <Document> using System; class Program { void Main() { Environment.GetFolderPath$$ } } </Document>) state.SendTypeChars("(") state.SendTab() Await state.WaitForAsynchronousOperationsAsync() Assert.Contains("Environment.SpecialFolder", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(545070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545070")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTextChangeSpanWithAtCharacter() As Task Using state = TestState.CreateCSharpTestState( <Document> public class @event { $$@event() { } } </Document>) state.SendTypeChars("public ") Await state.AssertNoCompletionSession() Assert.Contains("public @event", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDoNotInsertColonSoThatUserCanCompleteOutAVariableNameThatDoesNotCurrentlyExist_IE_TheCyrusCase() As Task Using state = TestState.CreateCSharpTestState( <Document> using System.Threading; class Program { static void Main(string[] args) { Goo($$) } void Goo(CancellationToken cancellationToken) { } } </Document>) state.SendTypeChars("can") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("Goo(cancellationToken)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function #If False Then <Scenario Name="Verify correct intellisense selection on ENTER"> <SetEditorText> <![CDATA[class Class1 { void Main(string[] args) { // } }]]> </SetEditorText> <PlaceCursor Marker="//" /> <SendKeys>var a = System.TimeSpan.FromMin{ENTER}{(}</SendKeys> <VerifyEditorContainsText> <![CDATA[class Class1 { void Main(string[] args) { var a = System.TimeSpan.FromMinutes( } }]]> </VerifyEditorContainsText> </Scenario> #End If <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeNamedPropertyCompletionCommitWithTab() As Task Using state = TestState.CreateCSharpTestState( <Document> class MyAttribute : System.Attribute { public string Name { get; set; } } [MyAttribute($$ public class Goo { } </Document>) state.SendTypeChars("Nam") state.SendTab() Await state.AssertNoCompletionSession() Assert.Equal("[MyAttribute(Name =", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeNamedPropertyCompletionCommitWithEquals() As Task Using state = TestState.CreateCSharpTestState( <Document> class MyAttribute : System.Attribute { public string Name { get; set; } } [MyAttribute($$ public class Goo { } </Document>) state.SendTypeChars("Nam=") Await state.AssertNoCompletionSession() Assert.Equal("[MyAttribute(Name =", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeNamedPropertyCompletionCommitWithSpace() As Task Using state = TestState.CreateCSharpTestState( <Document> class MyAttribute : System.Attribute { public string Name { get; set; } } [MyAttribute($$ public class Goo { } </Document>) state.SendTypeChars("Nam ") Await state.AssertNoCompletionSession() Assert.Equal("[MyAttribute(Name ", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(545590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545590")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOverrideDefaultParameter() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public virtual void Goo<S>(S x = default(S)) { } } class D : C { override $$ } ]]></Document>) state.SendTypeChars(" Goo") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("public override void Goo<S>(S x = default(S))", state.SubjectBuffer.CurrentSnapshot.GetText(), StringComparison.Ordinal) End Using End Function <WorkItem(545664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545664")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestArrayAfterOptionalParameter() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class A { public virtual void Goo(int x = 0, int[] y = null) { } } class B : A { public override void Goo(int x = 0, params int[] y) { } } class C : B { override$$ } ]]></Document>) state.SendTypeChars(" Goo") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains(" public override void Goo(int x = 0, int[] y = null)", state.SubjectBuffer.CurrentSnapshot.GetText(), StringComparison.Ordinal) End Using End Function <WorkItem(545967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545967")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestVirtualSpaces() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public string P { get; set; } void M() { var v = new C {$$ }; } } ]]></Document>) state.SendReturn() Assert.True(state.TextView.Caret.InVirtualSpace) Assert.Equal(12, state.TextView.Caret.Position.VirtualSpaces) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("P", isSoftSelected:=True) state.SendDownKey() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("P", isHardSelected:=True) state.SendTab() Await state.WaitForAsynchronousOperationsAsync() Assert.Equal(" P", state.GetLineFromCurrentCaretPosition().GetText()) Dim bufferPosition = state.TextView.Caret.Position.BufferPosition Assert.Equal(13, bufferPosition.Position - bufferPosition.GetContainingLine().Start.Position) Assert.False(state.TextView.Caret.InVirtualSpace) End Using End Function <WorkItem(546561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546561")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNamedParameterAgainstMRU() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Program { void Goo(string s) { } static void Main() { $$ } } ]]></Document>) ' prime the MRU state.SendTypeChars("string") state.SendTab() Await state.AssertNoCompletionSession() ' Delete what we just wrote. state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendEscape() Await state.AssertNoCompletionSession() ' ensure we still select the named param even though 'string' is in the MRU. state.SendTypeChars("Goo(s") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("s:") End Using End Function <WorkItem(546403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546403")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMissingOnObjectCreationAfterVar1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class A { void Goo() { var v = new$$ } } ]]></Document>) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(546403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546403")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMissingOnObjectCreationAfterVar2() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class A { void Goo() { var v = new $$ } } ]]></Document>) state.SendTypeChars("X") Await state.AssertCompletionSession() Assert.False(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "X")) End Using End Function <WorkItem(546917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546917")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEnumInSwitch() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ enum Numeros { } class C { void M() { Numeros n; switch (n) { case$$ } } } ]]></Document>) state.SendTypeChars(" ") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Numeros") End Using End Function <WorkItem(547016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547016")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAmbiguityInLocalDeclaration() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public int W; public C() { $$ W = 0; } } ]]></Document>) state.SendTypeChars("w") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="W") End Using End Function <WorkItem(530835, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530835")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompletionFilterSpanCaretBoundary() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void Method() { $$ } } ]]></Document>) state.SendTypeChars("Met") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Method") state.SendLeftKey() state.SendLeftKey() state.SendLeftKey() state.SendTypeChars("new") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Method", isSoftSelected:=True) End Using End Function <WorkItem(5487, "https://github.com/dotnet/roslyn/issues/5487")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitCharTypedAtTheBeginingOfTheFilterSpan() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public bool Method() { if ($$ } } ]]></Document>) state.SendTypeChars("Met") Await state.AssertCompletionSession() state.SendLeftKey() state.SendLeftKey() state.SendLeftKey() Await state.AssertSelectedCompletionItem(isSoftSelected:=True) state.SendTypeChars("!") Await state.AssertNoCompletionSession() Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("if (!Met", state.GetLineTextFromCaretPosition().Trim()) Assert.Equal("M", state.GetCaretPoint().BufferPosition.GetChar()) End Using End Function <WorkItem(622957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/622957")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBangFiltersInDocComment() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; /// $$ /// TestDocComment /// </summary> class TestException : Exception { } ]]></Document>) state.SendTypeChars("<") Await state.AssertCompletionSession() state.SendTypeChars("!") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("!--") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function InvokeCompletionDoesNotFilter() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Method() { string$$ } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("string") state.CompletionItemsContainsAll({"integer", "Method"}) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function InvokeBeforeWordDoesNotSelect() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Method() { $$string } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("AccessViolationException") state.CompletionItemsContainsAll({"integer", "Method"}) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function InvokeCompletionSelectsWithoutRegardToCaretPosition() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Method() { s$$tring } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("string") state.CompletionItemsContainsAll({"integer", "Method"}) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TabAfterQuestionMark() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Method() { ?$$ } } ]]></Document>) state.SendTab() Await state.WaitForAsynchronousOperationsAsync() Assert.Equal(state.GetLineTextFromCaretPosition(), " ?" + vbTab) End Using End Function <WorkItem(657658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657658")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PreselectionIgnoresBrackets() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { $$ static void Main(string[] args) { } }]]></Document>) state.SendTypeChars("static void F<T>(int a, Func<T, int> b) { }") state.SendEscape() state.TextView.Caret.MoveTo(New VisualStudio.Text.SnapshotPoint(state.SubjectBuffer.CurrentSnapshot, 220)) state.SendTypeChars("F") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("F<>") End Using End Function <WorkItem(672474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672474")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvokeSnippetCommandDismissesCompletion() As Task Using state = TestState.CreateCSharpTestState( <Document>$$</Document>) state.SendTypeChars("us") Await state.AssertCompletionSession() state.SendInsertSnippetCommand() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(672474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672474")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSurroundWithCommandDismissesCompletion() As Task Using state = TestState.CreateCSharpTestState( <Document>$$</Document>) state.SendTypeChars("us") Await state.AssertCompletionSession() state.SendSurroundWithCommand() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(737239, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737239")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function LetEditorHandleOpenParen() As Task Dim expected = <Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { List<int> x = new List<int>( } }]]></Document>.Value.Replace(vbLf, vbCrLf) Using state = TestState.CreateCSharpTestState(<Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { List<int> x = new$$ } }]]></Document>) state.SendTypeChars(" ") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("List<int>") state.SendTypeChars("(") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal(expected, state.GetDocumentText()) End Using End Function <WorkItem(785637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/785637")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitMovesCaretToWordEnd() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Main() { M$$ain } } ]]></Document>) state.SendCommitUniqueCompletionListItem() Await state.WaitForAsynchronousOperationsAsync() Assert.Equal(state.GetLineFromCurrentCaretPosition().End, state.GetCaretPoint().BufferPosition) End Using End Function <WorkItem(775370, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775370")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function MatchingConsidersAtSign() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Main() { $$ } } ]]></Document>) state.SendTypeChars("var @this = ""goo""") state.SendReturn() state.SendTypeChars("string str = this.ToString();") state.SendReturn() state.SendTypeChars("str = @th") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("@this") End Using End Function <WorkItem(865089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/865089")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeFilterTextRemovesAttributeSuffix() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ [$$] class AtAttribute : System.Attribute { }]]></Document>) state.SendTypeChars("At") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("At") Assert.Equal("At", state.CurrentCompletionPresenterSession.SelectedItem.FilterText) End Using End Function <WorkItem(852578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/852578")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PreselectExceptionOverSnippet() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { Exception goo() { return new $$ } }]]></Document>) state.SendTypeChars(" ") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("Exception") End Using End Function <WorkItem(868286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/868286")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitNameAfterAlias() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using goo = System$$]]></Document>) state.SendTypeChars(".act<") Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(1, "using goo = System.Action<") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompletionInLinkedFiles() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Thing2"> <Document FilePath="C.cs"> class C { void M() { $$ } #if Thing1 void Thing1() { } #elif Thing2 void Thing2() { } #endif } </Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Thing1"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>) Dim documents = state.Workspace.Documents Dim linkDocument = documents.Single(Function(d) d.IsLinkFile) state.SendTypeChars("Thing1") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("Thing1") state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendEscape() state.Workspace.SetDocumentContext(linkDocument.Id) state.SendTypeChars("Thing1") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("Thing1") Assert.True(state.CurrentCompletionPresenterSession.SelectedItem.Tags.Contains(CompletionTags.Warning)) state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendTypeChars("M") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("M") Assert.False(state.CurrentCompletionPresenterSession.SelectedItem.Tags.Contains(CompletionTags.Warning)) End Using End Function <WorkItem(951726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951726")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function DismissUponSave() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { $$ }]]></Document>) state.SendTypeChars("voi") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("void") state.SendSave() Await state.AssertNoCompletionSession() state.AssertMatchesTextStartingAtLine(3, " voi") End Using End Function <WorkItem(930254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930254")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NoCompletionWithBoxSelection() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { {|Selection:$$int x;|} {|Selection:int y;|} }]]></Document>) state.SendInvokeCompletionList() Await state.AssertNoCompletionSession() state.SendTypeChars("goo") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(839555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839555")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TriggeredOnHash() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ $$]]></Document>) state.SendTypeChars("#") Await state.AssertCompletionSession() End Using End Function <WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function RegionCompletionCommitTriggersFormatting_1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { $$ }]]></Document>) state.SendTypeChars("#reg") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("region") state.SendReturn() Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(3, " #region") End Using End Function <WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function RegionCompletionCommitTriggersFormatting_2() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { $$ }]]></Document>) state.SendTypeChars("#reg") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("region") state.SendTypeChars(" ") Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(3, " #region ") End Using End Function <WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EndRegionCompletionCommitTriggersFormatting_2() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { #region NameIt $$ }]]></Document>) state.SendTypeChars("#endreg") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("endregion") state.SendReturn() Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(4, " #endregion ") End Using End Function Private Class SlowProvider Inherits CommonCompletionProvider Public checkpoint As Checkpoint = New Checkpoint() Public Overrides Async Function ProvideCompletionsAsync(context As CompletionContext) As Task Await checkpoint.Task.ConfigureAwait(False) End Function Friend Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean Return True End Function End Class <WorkItem(1015893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1015893")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function BackspaceDismissesIfComputationIsIncomplete() As Task Dim slowProvider = New SlowProvider() Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void goo() { goo($$ } }]]></Document>, {slowProvider}) state.SendTypeChars("f") state.SendBackspace() ' Send a backspace that goes beyond the session's applicable span ' before the model computation has finished. Then, allow the ' computation to complete. There should still be no session. state.SendBackspace() slowProvider.checkpoint.Release() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(1065600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065600")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitUniqueItemWithBoxSelection() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void goo(int x) { [|$$ |] } }]]></Document>) state.SendReturn() state.TextView.Selection.Mode = VisualStudio.Text.Editor.TextSelectionMode.Box state.SendCommitUniqueCompletionListItem() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(1594, "https://github.com/dotnet/roslyn/issues/1594")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NoPreselectionOnSpaceWhenAbuttingWord() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Program { void Main() { Program p = new $$Program(); } }]]></Document>) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(1594, "https://github.com/dotnet/roslyn/issues/1594")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SpacePreselectionAtEndOfFile() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Program { void Main() { Program p = new $$]]></Document>) state.SendTypeChars(" ") Await state.AssertCompletionSession() End Using End Function <WorkItem(1659, "https://github.com/dotnet/roslyn/issues/1659")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function DismissOnSelectAllCommand() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void goo(int x) { $$]]></Document>) ' Note: the caret is at the file, so the Select All command's movement ' of the caret to the end of the selection isn't responsible for ' dismissing the session. state.SendInvokeCompletionList() Await state.AssertCompletionSession() state.SendSelectAll() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionCommitAndFormatAreSeparateUndoTransactions() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void goo(int x) { int doodle; $$]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendTypeChars("doo;") Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(6, " doodle;") state.SendUndo() Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(6, "doo;") End Using End Function <WorkItem(4978, "https://github.com/dotnet/roslyn/issues/4978")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SessionNotStartedWhenCaretNotMappableIntoSubjectBuffer() As Task ' In inline diff view, typing delete next to a "deletion", ' can cause our CommandChain to be called with a subjectbuffer ' and TextView such that the textView's caret can't be mapped ' into our subject buffer. ' ' To test this, we create a projection buffer with 2 source ' spans: one of "text" content type and one based on a C# ' buffer. We create a TextView with that projection as ' its buffer, setting the caret such that it maps only ' into the "text" buffer. We then call the completion ' command handlers with commandargs based on that TextView ' but with the C# buffer as the SubjectBuffer. Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void goo(int x) {$$ /********/ int doodle; } }]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) Dim textBufferFactoryService = state.GetExportedValue(Of ITextBufferFactoryService)() Dim contentTypeService = state.GetExportedValue(Of IContentTypeRegistryService)() Dim contentType = contentTypeService.GetContentType(ContentTypeNames.CSharpContentType) Dim textViewFactory = state.GetExportedValue(Of ITextEditorFactoryService)() Dim editorOperationsFactory = state.GetExportedValue(Of IEditorOperationsFactoryService)() Dim otherBuffer = textBufferFactoryService.CreateTextBuffer("text", contentType) Dim otherExposedSpan = otherBuffer.CurrentSnapshot.CreateTrackingSpan(0, 4, SpanTrackingMode.EdgeExclusive, TrackingFidelityMode.Forward) Dim subjectBufferExposedSpan = state.SubjectBuffer.CurrentSnapshot.CreateTrackingSpan(0, state.SubjectBuffer.CurrentSnapshot.Length, SpanTrackingMode.EdgeExclusive, TrackingFidelityMode.Forward) Dim projectionBufferFactory = state.GetExportedValue(Of IProjectionBufferFactoryService)() Dim projection = projectionBufferFactory.CreateProjectionBuffer(Nothing, New Object() {otherExposedSpan, subjectBufferExposedSpan}.ToList(), ProjectionBufferOptions.None) Using disposableView As DisposableTextView = textViewFactory.CreateDisposableTextView(projection) disposableView.TextView.Caret.MoveTo(New SnapshotPoint(disposableView.TextView.TextBuffer.CurrentSnapshot, 0)) Dim editorOperations = editorOperationsFactory.GetEditorOperations(disposableView.TextView) state.CompletionCommandHandler.ExecuteCommand(New DeleteKeyCommandArgs(disposableView.TextView, state.SubjectBuffer), Sub() editorOperations.Delete()) Await state.AssertNoCompletionSession() End Using End Using End Function <WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround1() As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void goo(int x) { string.$$]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendTypeChars("is") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("IsInterned") End Using End Using End Function <WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround2() As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void goo(int x) { string.$$]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendTypeChars("ı") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem() End Using End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselection1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System.Threading; class Program { void Cancel(int x, CancellationToken cancellationToken) { Cancel(x + 1, cancellationToken: $$) } }]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True) Await state.AssertSelectedCompletionItem("cancellationToken", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselection2() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Program { static void Main(string[] args) { int aaz = 0; args = $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendTypeChars("a") Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True) Await state.AssertSelectedCompletionItem("args", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselection_DoesNotOverrideEnumPreselection() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ enum E { } class Program { static void Main(string[] args) { E e; e = $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True) Await state.AssertSelectedCompletionItem("E", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselection_DoesNotOverrideEnumPreselection2() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ enum E { A } class Program { static void Main(string[] args) { E e = E.A; if (e == $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True) Await state.AssertSelectedCompletionItem("E", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselection3() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class D {} class Program { static void Main(string[] args) { int cw = 7; D cx = new D(); D cx2 = $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendTypeChars("c") Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True) Await state.AssertSelectedCompletionItem("cx", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselectionLocalsOverType() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class A {} class Program { static void Main(string[] args) { A cx = new A(); A cx2 = $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendTypeChars("c") Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True) Await state.AssertSelectedCompletionItem("cx", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselectionParameterOverMethod() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Program { bool f; void goo(bool x) { } void Main(string[] args) { goo($$) // Not "Equals" } }]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True) Await state.AssertSelectedCompletionItem("f", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/6942"), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselectionConvertibility1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ abstract class C {} class D : C {} class Program { static void Main(string[] args) { D cx = new D(); C cx2 = $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendTypeChars("c") Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True) Await state.AssertSelectedCompletionItem("cx", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselectionLocalOverProperty() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Program { public int aaa { get; } void Main(string[] args) { int aaq; int y = a$$ } }]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True) Await state.AssertSelectedCompletionItem("aaq", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(12254, "https://github.com/dotnet/roslyn/issues/12254")> Public Async Function TestGenericCallOnTypeContainingAnonymousType() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System.Linq; class Program { static void Main(string[] args) { new[] { new { x = 1 } }.ToArr$$ } }]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendInvokeCompletionList() state.SendTypeChars("(") Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True) state.AssertMatchesTextStartingAtLine(7, "new[] { new { x = 1 } }.ToArray(") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselectionSetterValuey() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Program { int _x; int X { set { _x = $$ } } }]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True) Await state.AssertSelectedCompletionItem("value", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(12530, "https://github.com/dotnet/roslyn/issues/12530")> Public Async Function TestAnonymousTypeDescription() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System.Linq; class Program { static void Main(string[] args) { new[] { new { x = 1 } }.ToArr$$ } }]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(description:= "(extension) 'a[] System.Collections.Generic.IEnumerable<'a>.ToArray<'a>() Anonymous Types: 'a is new { int x }") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRecursiveGenericSymbolKey() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System.Collections.Generic; class Program { static void ReplaceInList<T>(List<T> list, T oldItem, T newItem) { $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendTypeChars("list") state.SendTypeChars(".") Await state.AssertCompletionSession() state.SendTypeChars("Add") Await state.AssertSelectedCompletionItem("Add", description:="void List<T>.Add(T item)") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitNamedParameterWithColon() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System.Collections.Generic; class Program { static void Main(int args) { Main(args$$ } }]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendInvokeCompletionList() state.SendTypeChars(":") Await state.AssertNoCompletionSession() Assert.Contains("args:", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(13481, "https://github.com/dotnet/roslyn/issues/13481")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackspaceSelection1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { static void Main() { DateTimeOffset$$ } } ]]></Document>) state.Workspace.Options = state.Workspace.Options.WithChangedOption( CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True) For Each c In "Offset" state.SendBackspace() Await state.WaitForAsynchronousOperationsAsync() Next Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("DateTime") End Using End Function <WorkItem(13481, "https://github.com/dotnet/roslyn/issues/13481")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackspaceSelection2() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { static void Main() { DateTimeOffset.$$ } } ]]></Document>) state.Workspace.Options = state.Workspace.Options.WithChangedOption( CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True) For Each c In "Offset." state.SendBackspace() Await state.WaitForAsynchronousOperationsAsync() Next Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("DateTime") End Using End Function <WorkItem(14465, "https://github.com/dotnet/roslyn/issues/14465")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypingNumberShouldNotDismiss1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void Moo1() { new C()$$ } } ]]></Document>) state.SendTypeChars(".") Await state.AssertCompletionSession() state.SendTypeChars("1") Await state.AssertSelectedCompletionItem("Moo1") End Using End Function <WorkItem(14085, "https://github.com/dotnet/roslyn/issues/14085")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypingDoesNotOverrideExactMatch() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System.IO; class C { void Moo1() { string path = $$ } } ]]></Document>) state.SendTypeChars("Path") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("Path") End Using End Function <WorkItem(14085, "https://github.com/dotnet/roslyn/issues/14085")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function MRUOverTargetTyping() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System.IO; using System.Threading.Tasks; class C { async Task Moo() { await Moo().$$ } } ]]></Document>) state.SendTypeChars("Configure") state.SendTab() For i = 1 To "ConfigureAwait".Length state.SendBackspace() Next state.SendInvokeCompletionList() Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("ConfigureAwait") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function MovingCaretToStartSoftSelects() As Task Using state = TestState.CreateCSharpTestState( <Document> using System; class C { void M() { $$ } } </Document>) state.SendTypeChars("Conso") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Console", isHardSelected:=True) For Each ch In "Conso" state.SendLeftKey() Next Await state.AssertSelectedCompletionItem(displayText:="Console", isHardSelected:=False) state.SendRightKey() Await state.AssertSelectedCompletionItem(displayText:="Console", isHardSelected:=True) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoBlockOnCompletionItems1() As Task Dim tcs = New TaskCompletionSource(Of Boolean) Using state = TestState.CreateCSharpTestState( <Document> using $$ </Document>, {New TaskControlledCompletionProvider(tcs.Task)}) state.Workspace.Options = state.Workspace.Options.WithChangedOption( CompletionOptions.BlockForCompletionItems, LanguageNames.CSharp, False) state.SendTypeChars("Sys.") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertNoCompletionSession() Assert.Contains("Sys.", state.GetLineTextFromCaretPosition()) tcs.SetResult(True) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoBlockOnCompletionItems2() As Task Using state = TestState.CreateCSharpTestState( <Document> using $$ </Document>, {New TaskControlledCompletionProvider(Task.FromResult(True))}) state.Workspace.Options = state.Workspace.Options.WithChangedOption( CompletionOptions.BlockForCompletionItems, LanguageNames.CSharp, False) state.SendTypeChars("Sys") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() state.SendTypeChars(".") Assert.Contains("System.", state.GetLineTextFromCaretPosition()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoBlockOnCompletionItems4() As Task Dim tcs = New TaskCompletionSource(Of Boolean) Using state = TestState.CreateCSharpTestState( <Document> using $$ </Document>, {New TaskControlledCompletionProvider(tcs.Task)}) state.Workspace.Options = state.Workspace.Options.WithChangedOption( CompletionOptions.BlockForCompletionItems, LanguageNames.CSharp, False) state.SendTypeChars("Sys") state.SendCommitUniqueCompletionListItem() Await Task.Delay(250) Await state.AssertNoCompletionSession(block:=False) Assert.Contains("Sys", state.GetLineTextFromCaretPosition()) Assert.DoesNotContain("System", state.GetLineTextFromCaretPosition()) tcs.SetResult(True) Await state.WaitForAsynchronousOperationsAsync() Await state.AssertNoCompletionSession() Assert.Contains("System", state.GetLineTextFromCaretPosition()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoBlockOnCompletionItems3() As Task Dim tcs = New TaskCompletionSource(Of Boolean) Using state = TestState.CreateCSharpTestState( <Document> using $$ </Document>, {New TaskControlledCompletionProvider(tcs.Task)}) state.Workspace.Options = state.Workspace.Options.WithChangedOption( CompletionOptions.BlockForCompletionItems, LanguageNames.CSharp, False) state.SendTypeChars("Sys") state.SendCommitUniqueCompletionListItem() Await Task.Delay(250) Await state.AssertNoCompletionSession(block:=False) Assert.Contains("Sys", state.GetLineTextFromCaretPosition()) Assert.DoesNotContain("System", state.GetLineTextFromCaretPosition()) state.SendTypeChars("a") tcs.SetResult(True) Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() Assert.Contains("Sysa", state.GetLineTextFromCaretPosition()) End Using End Function Private Class TaskControlledCompletionProvider Inherits CompletionProvider Private ReadOnly _task As Task Public Sub New(task As Task) _task = task End Sub Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task Return _task End Function End Class <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Filters_EmptyList1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System.IO; using System.Threading.Tasks; class C { async Task Moo() { var x = asd$$ } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Dim filters = state.CurrentCompletionPresenterSession.CompletionItemFilters Dim dict = New Dictionary(Of CompletionItemFilter, Boolean) For Each f In filters dict(f) = False Next dict(CompletionItemFilter.InterfaceFilter) = True Dim args = New CompletionItemFilterStateChangedEventArgs(dict.ToImmutableDictionary()) state.CurrentCompletionPresenterSession.RaiseFiltersChanged(args) Await state.WaitForAsynchronousOperationsAsync() Assert.Null(state.CurrentCompletionPresenterSession.SelectedItem) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Filters_EmptyList2() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System.IO; using System.Threading.Tasks; class C { async Task Moo() { var x = asd$$ } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Dim filters = state.CurrentCompletionPresenterSession.CompletionItemFilters Dim dict = New Dictionary(Of CompletionItemFilter, Boolean) For Each f In filters dict(f) = False Next dict(CompletionItemFilter.InterfaceFilter) = True Dim args = New CompletionItemFilterStateChangedEventArgs(dict.ToImmutableDictionary()) state.CurrentCompletionPresenterSession.RaiseFiltersChanged(args) Await state.WaitForAsynchronousOperationsAsync() Assert.Null(state.CurrentCompletionPresenterSession.SelectedItem) state.SendTab() Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Filters_EmptyList3() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System.IO; using System.Threading.Tasks; class C { async Task Moo() { var x = asd$$ } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Dim filters = state.CurrentCompletionPresenterSession.CompletionItemFilters Dim dict = New Dictionary(Of CompletionItemFilter, Boolean) For Each f In filters dict(f) = False Next dict(CompletionItemFilter.InterfaceFilter) = True Dim args = New CompletionItemFilterStateChangedEventArgs(dict.ToImmutableDictionary()) state.CurrentCompletionPresenterSession.RaiseFiltersChanged(args) Await state.WaitForAsynchronousOperationsAsync() Assert.Null(state.CurrentCompletionPresenterSession.SelectedItem) state.SendReturn() Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Filters_EmptyList4() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System.IO; using System.Threading.Tasks; class C { async Task Moo() { var x = asd$$ } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Dim filters = state.CurrentCompletionPresenterSession.CompletionItemFilters Dim dict = New Dictionary(Of CompletionItemFilter, Boolean) For Each f In filters dict(f) = False Next dict(CompletionItemFilter.InterfaceFilter) = True Dim args = New CompletionItemFilterStateChangedEventArgs(dict.ToImmutableDictionary()) state.CurrentCompletionPresenterSession.RaiseFiltersChanged(args) Await state.WaitForAsynchronousOperationsAsync() Assert.Null(state.CurrentCompletionPresenterSession.SelectedItem) state.SendTypeChars(".") Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(15881, "https://github.com/dotnet/roslyn/issues/15881")> Public Async Function CompletionAfterDotBeforeAwaitTask() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System.Threading.Tasks; class C { async Task Moo() { Task.$$ await Task.Delay(50); } } ]]></Document>) state.SendInvokeCompletionList() Await state.AssertCompletionSession() End Using End Function <WorkItem(14704, "https://github.com/dotnet/roslyn/issues/14704")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function BackspaceTriggerSubstringMatching() As Task Using state = TestState.CreateCSharpTestState( <Document> using System; class Program { static void Main(string[] args) { if (Environment$$ } } </Document>) Dim key = New OptionKey(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp) state.Workspace.Options = state.Workspace.Options.WithChangedOption(key, True) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="Environment", isHardSelected:=True) End Using End Function <WorkItem(16236, "https://github.com/dotnet/roslyn/issues/16236")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeNamedParameterEqualsItemCommittedOnSpace() As Task Using state = TestState.CreateCSharpTestState( <Document> [A($$)] class AAttribute: Attribute { public string Skip { get; set; } } </Document>) state.SendTypeChars("Skip") Await state.AssertCompletionSession() state.SendTypeChars(" ") Await state.AssertNoCompletionSession() Assert.Equal("[A(Skip )]", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(362890, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=362890")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFilteringAfterSimpleInvokeShowsAllItemsMatchingFilter() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ enum Color { Red, Green, Blue } class C { void M() { Color.Re$$d } } ]]></Document>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Red") state.CompletionItemsContainsAll(displayText:={"Red", "Green", "Blue", "Equals"}) Dim filters = state.CurrentCompletionPresenterSession.CompletionItemFilters Dim dict = New Dictionary(Of CompletionItemFilter, Boolean) For Each f In filters dict(f) = False Next dict(CompletionItemFilter.EnumFilter) = True Dim args = New CompletionItemFilterStateChangedEventArgs(dict.ToImmutableDictionary()) state.CurrentCompletionPresenterSession.RaiseFiltersChanged(args) Await state.AssertSelectedCompletionItem("Red") state.CompletionItemsContainsAll(displayText:={"Red", "Green", "Blue"}) Assert.False(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "Equals")) For Each f In filters dict(f) = False Next args = New CompletionItemFilterStateChangedEventArgs(dict.ToImmutableDictionary()) state.CurrentCompletionPresenterSession.RaiseFiltersChanged(args) Await state.AssertSelectedCompletionItem("Red") state.CompletionItemsContainsAll(displayText:={"Red", "Green", "Blue", "Equals"}) End Using End Function <WorkItem(16236, "https://github.com/dotnet/roslyn/issues/16236")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NameCompletionSorting() As Task Using state = TestState.CreateCSharpTestState( <Document> interface ISyntaxFactsService {} class C { void M() { ISyntaxFactsService $$ } } </Document>) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Dim expectedOrder = { "syntaxFactsService", "syntaxFacts", "factsService", "syntax", "service" } state.AssertItemsInOrder(expectedOrder) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestLargeChangeBrokenUpIntoSmallTextChanges() Dim provider = New MultipleChangeCompletionProvider() Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { void goo() { return $$ } }]]></Document>, {provider}) Dim testDocument = state.Workspace.Documents(0) Dim textBuffer = testDocument.TextBuffer Dim snapshotBeforeCommit = textBuffer.CurrentSnapshot provider.SetInfo(snapshotBeforeCommit.GetText(), testDocument.CursorPosition.Value) ' First send a space to trigger out special completion provider. state.SendInvokeCompletionList() state.SendTab() ' Verify that we see the entire change Dim finalText = textBuffer.CurrentSnapshot.GetText() Assert.Equal( "using NewUsing; using System; class C { void goo() { return InsertedItem } }", finalText) ' This should have happened as two text changes to the buffer. Dim changes = snapshotBeforeCommit.Version.Changes Assert.Equal(2, changes.Count) Dim actualChanges = changes.ToArray() Dim firstChange = actualChanges(0) Assert.Equal(New Span(0, 0), firstChange.OldSpan) Assert.Equal("using NewUsing;", firstChange.NewText) Dim secondChange = actualChanges(1) Assert.Equal(New Span(testDocument.CursorPosition.Value, 0), secondChange.OldSpan) Assert.Equal("InsertedItem", secondChange.NewText) ' Make sure new edits happen after the text that was inserted. state.SendTypeChars("1") finalText = textBuffer.CurrentSnapshot.GetText() Assert.Equal( "using NewUsing; using System; class C { void goo() { return InsertedItem1 } }", finalText) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestLargeChangeBrokenUpIntoSmallTextChanges2() Dim provider = New MultipleChangeCompletionProvider() Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { void goo() { return Custom$$ } }]]></Document>, {provider}) Dim testDocument = state.Workspace.Documents(0) Dim textBuffer = testDocument.TextBuffer Dim snapshotBeforeCommit = textBuffer.CurrentSnapshot provider.SetInfo(snapshotBeforeCommit.GetText(), testDocument.CursorPosition.Value) ' First send a space to trigger out special completion provider. state.SendInvokeCompletionList() state.SendTab() ' Verify that we see the entire change Dim finalText = textBuffer.CurrentSnapshot.GetText() Assert.Equal( "using NewUsing; using System; class C { void goo() { return InsertedItem } }", finalText) ' This should have happened as two text changes to the buffer. Dim changes = snapshotBeforeCommit.Version.Changes Assert.Equal(2, changes.Count) Dim actualChanges = changes.ToArray() Dim firstChange = actualChanges(0) Assert.Equal(New Span(0, 0), firstChange.OldSpan) Assert.Equal("using NewUsing;", firstChange.NewText) Dim secondChange = actualChanges(1) Assert.Equal(New Span(testDocument.CursorPosition.Value - "Custom".Length, "Custom".Length), secondChange.OldSpan) Assert.Equal("InsertedItem", secondChange.NewText) ' Make sure new edits happen after the text that was inserted. state.SendTypeChars("1") finalText = textBuffer.CurrentSnapshot.GetText() Assert.Equal( "using NewUsing; using System; class C { void goo() { return InsertedItem1 } }", finalText) End Using End Sub <WorkItem(296512, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=296512")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRegionDirectiveIndentation() As Task Using state = TestState.CreateCSharpTestState( <Document> class C { $$ } </Document>, includeFormatCommandHandler:=True) state.SendTypeChars("#") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("#", state.GetLineFromCurrentCaretPosition().GetText()) Await state.AssertNoCompletionSession() state.SendTypeChars("reg") Await state.AssertSelectedCompletionItem(displayText:="region") state.SendReturn() Await state.AssertNoCompletionSession() Assert.Equal(" #region", state.GetLineFromCurrentCaretPosition().GetText()) Assert.Equal(state.GetLineFromCurrentCaretPosition().End, state.GetCaretPoint().BufferPosition) state.SendReturn() Assert.Equal("", state.GetLineFromCurrentCaretPosition().GetText()) state.SendTypeChars("#") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("#", state.GetLineFromCurrentCaretPosition().GetText()) Await state.AssertNoCompletionSession() state.SendTypeChars("endr") Await state.AssertSelectedCompletionItem(displayText:="endregion") state.SendReturn() Await state.AssertNoCompletionSession() Assert.Equal(" #endregion", state.GetLineFromCurrentCaretPosition().GetText()) Assert.Equal(state.GetLineFromCurrentCaretPosition().End, state.GetCaretPoint().BufferPosition) End Using End Function Private Class MultipleChangeCompletionProvider Inherits CompletionProvider Private _text As String Private _caretPosition As Integer Public Sub SetInfo(text As String, caretPosition As Integer) _text = text _caretPosition = caretPosition End Sub Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task context.AddItem(CompletionItem.Create( "CustomItem", rules:=CompletionItemRules.Default.WithMatchPriority(1000))) Return SpecializedTasks.EmptyTask End Function Public Overrides Function ShouldTriggerCompletion(text As SourceText, caretPosition As Integer, trigger As CompletionTrigger, options As OptionSet) As Boolean Return True End Function Public Overrides Function GetChangeAsync(document As Document, item As CompletionItem, commitKey As Char?, cancellationToken As CancellationToken) As Task(Of CompletionChange) Dim newText = "using NewUsing; using System; class C { void goo() { return InsertedItem" Dim change = CompletionChange.Create( New TextChange(New TextSpan(0, _caretPosition), newText)) Return Task.FromResult(change) End Function <WorkItem(15348, "https://github.com/dotnet/roslyn/issues/15348")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterCasePatternSwitchLabel() As Task Using state = TestState.CreateCSharpTestState( <Document> class C { void M() { object o = 1; switch(o) { case int i: $$ break; } } } </Document>) state.SendTypeChars("this") Await state.AssertSelectedCompletionItem(displayText:="this", isHardSelected:=True) End Using End Function End Class End Class End Namespace
robinsedlaczek/roslyn
src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb
Visual Basic
apache-2.0
134,217
Imports bv.winclient.BasePanel Imports bv.winclient.Core Imports EIDSS.model.Resources Public Class SpeciesTypeDetail Inherits GenericReferenceDetail Public Sub New() MyBase.New() Me.gvReference.OptionsCustomization.AllowFilter = False Me.FormID = "A29" HelpTopicID = "Species_Type_Reference_Editor" End Sub Protected Overrides Sub DefineBinding() 'baseDataSet.Tables("HACodes").DefaultView.RowFilter = String.Format("intHACode<>{0}", CType(HACode.Human, Integer)) MyBase.DefineBinding() If (HACodeMask And (HACode.Livestock Or HACode.Avian)) = (HACode.Livestock Or HACode.Avian) Then RefView.RowFilter = String.Format("intHACode = {0} or intHACode = {1}", CType(HACode.Livestock, Integer), CType(HACode.Avian, Integer)) ElseIf (HACodeMask And HACode.Livestock) = HACode.Livestock Then RefView.RowFilter = String.Format("intHACode = {0}", CType(HACode.Livestock, Integer)) ElseIf (HACodeMask And HACode.Avian) = HACode.Avian Then RefView.RowFilter = String.Format("intHACode = {0}", CType(HACode.Avian, Integer)) End If End Sub Protected Overrides ReadOnly Property HACodeMask() As Integer Get If (Not StartUpParameters Is Nothing AndAlso StartUpParameters.ContainsKey("HACodeMask")) Then Return CInt(StartUpParameters("HACodeMask")) End If Return HACode.Avian Or HACode.Livestock End Get End Property Protected Overrides ReadOnly Property ReferenceDbService() As BaseDbService Get Return New SpeciesType_DB End Get End Property Protected Overrides ReadOnly Property MandatoryFields() As String Get Return "strDefault,name,intHACode" End Get End Property Protected Overrides ReadOnly Property CanDeleteProc() As String Get Return "spSpeciesTypeReference_CanDelete" End Get End Property Protected Overrides ReadOnly Property MainCaption() As String Get Return EidssMessages.Get("lblSpeciesTypeMainCaption") '"Species Type Reference Editor" End Get End Property Protected Overrides ReadOnly Property CodeCaption() As String Get Return EidssMessages.Get("lblSpeciesTypeCodeCaption") '"Code" End Get End Property Protected Overrides ReadOnly Property CodeField() As String Get Return "strCode" End Get End Property #Region "Main form interface" Private Shared m_Parent As Control Public Shared Sub Register(ByVal ParentControl As System.Windows.Forms.Control) m_Parent = ParentControl Dim category As MenuAction = MenuActionManager.Instance.FindAction("MenuReferencies", MenuActionManager.Instance.System, 950) Dim ma As MenuAction = New MenuAction(AddressOf ShowMe, MenuActionManager.Instance, category, "MenuSpeciesTypeReferenceEditor", 940, False, model.Enums.MenuIconsSmall.References, -1) ma.SelectPermission = PermissionHelper.SelectPermission(EIDSS.model.Enums.EIDSSPermissionObject.Reference) ma.Name = "btnSpeciesTypeReferenceEditor" End Sub Public Shared Sub ShowMe() BaseFormManager.ShowNormal(New SpeciesTypeDetail, Nothing) End Sub #End Region End Class
EIDSS/EIDSS-Legacy
EIDSS v6.1/vb/EIDSS/EIDSS_Admin/LookupForms/SpeciesTypeDetail.vb
Visual Basic
bsd-2-clause
3,453
' ' (C) Copyright 2003-2011 by Autodesk, Inc. ' ' Permission to use, copy, modify, and distribute this software in ' object code form for any purpose and without fee is hereby granted, ' provided that the above copyright notice appears in all copies and ' that both that copyright notice and the limited warranty and ' restricted rights notice below appear in all supporting ' documentation. ' ' AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. ' AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF ' MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. ' DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE ' UNINTERRUPTED OR ERROR FREE. ' ' Use, duplication, or disclosure by the U.S. Government is subject to ' restrictions set forth in FAR 52.227-19 (Commercial Computer ' Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) ' (Rights in Technical Data and Computer Software), as applicable. ' 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("")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("")> <Assembly: AssemblyCopyright("")> <Assembly: AssemblyTrademark("")> <Assembly: CLSCompliant(True)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("4FB10252-6C3B-4553-B0E3-2CC98A791FAD")> ' 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.*")>
AMEE/revit
samples/Revit 2012 SDK/Samples/Viewers/AnalyticalViewer/VB.NET/AssemblyInfo.vb
Visual Basic
bsd-3-clause
1,958
Imports Com.Aspose.Barcode.Api Imports Com.Aspose.Barcode.Model Namespace ManagingRecognition.WithoutCloudStorage Class ReadBarcodeFromLocalFile Public Shared Sub Run() 'ExStart:1 'Instantiate Aspose BarCode Cloud API SDK Dim barcodeApi As New BarcodeApi(Common.APP_KEY, Common.APP_SID, Common.BASEPATH) 'Set input file name Dim name As [String] = "sample-barcode.jpeg" 'The barcode type. 'If this parameter is empty, autodetection of all supported types is used. Dim type As [String] = "" 'Set mode for checksum validation during recognition Dim checksumValidation As [String] = "" 'Set if FNC symbol stripping should be performed. Dim stripFnc As Boolean = True 'Set recognition of rotated barcode Dim rotationAngle As System.Nullable(Of Integer) = Nothing 'Set the image file url Dim url As [String] = Nothing Dim file As Byte() = System.IO.File.ReadAllBytes(Common.GetDataDir + name) Try 'invoke Aspose.BarCode Cloud SDK API to read barcode from local image Dim apiResponse As BarcodeResponseList = barcodeApi.PostBarcodeRecognizeFromUrlorContent(type, checksumValidation, stripFnc, rotationAngle, url, file) If apiResponse IsNot Nothing Then For Each barcode As Barcode In apiResponse.Barcodes Console.WriteLine("Codetext: " + barcode.BarcodeValue + vbLf & "Type: " + barcode.BarcodeType) Next Console.WriteLine("Read Barcode from Local Image, Done!") End If Catch ex As Exception Console.WriteLine("error:" + ex.Message + vbLf + ex.StackTrace) End Try 'ExEnd:1 End Sub End Class End Namespace
farooqsheikhpk/Aspose.BarCode-for-Cloud
Examples/DotNET/VisualBasic/ManagingRecognition/WithoutCloudStorage/ReadBarcodeFromLocalFile.vb
Visual Basic
mit
1,959
' 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.CodeFixes Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.QualifyMemberAccess Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.QualifyMemberAccess Partial Public Class QualifyMemberAccessTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (New VisualBasicQualifyMemberAccessDiagnosticAnalyzer(), New VisualBasicQualifyMemberAccessCodeFixProvider()) End Function Private Function TestAsyncWithOption(code As String, expected As String, opt As PerLanguageOption(Of CodeStyleOption(Of Boolean))) As Task Return TestAsyncWithOptionAndNotification(code, expected, opt, NotificationOption.Error) End Function Private Function TestAsyncWithOptionAndNotification(code As String, expected As String, opt As PerLanguageOption(Of CodeStyleOption(Of Boolean)), notification As NotificationOption) As Task Return TestInRegularAndScriptAsync(code, expected, options:=[Option](opt, True, notification)) End Function Private Function TestMissingAsyncWithOption(code As String, opt As PerLanguageOption(Of CodeStyleOption(Of Boolean))) As Task Return TestMissingAsyncWithOptionAndNotification(code, opt, NotificationOption.Error) End Function Private Function TestMissingAsyncWithOptionAndNotification(code As String, opt As PerLanguageOption(Of CodeStyleOption(Of Boolean)), notification As NotificationOption) As Task Return TestMissingInRegularAndScriptAsync(code, New TestParameters(options:=[Option](opt, True, notification))) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyFieldAccess_LHS() As Task Await TestAsyncWithOption( "Class C : Dim i As Integer : Sub M() : [|i|] = 1 : End Sub : End Class", "Class C : Dim i As Integer : Sub M() : Me.i = 1 : End Sub : End Class", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyFieldAccess_RHS() As Task Await TestAsyncWithOption( "Class C : Dim i As Integer : Sub M() : Dim x = [|i|] : End Sub : End Class", "Class C : Dim i As Integer : Sub M() : Dim x = Me.i : End Sub : End Class", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyFieldAccess_MethodArgument() As Task Await TestAsyncWithOption( "Class C : Dim i As Integer : Sub M(ii As Integer) : M([|i|]) : End Sub : End Class", "Class C : Dim i As Integer : Sub M(ii As Integer) : M(Me.i) : End Sub : End Class", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyFieldAccess_ChainedAccess() As Task Await TestAsyncWithOption( "Class C : Dim i As Integer : Sub M() : Dim s = [|i|].ToString() : End Sub : End Class", "Class C : Dim i As Integer : Sub M() : Dim s = Me.i.ToString() : End Sub : End Class", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyFieldAccess_ConditionalAccess() As Task Await TestAsyncWithOption( "Class C : Dim s As String : Sub M() : Dim x = [|s|]?.ToString() : End Sub : End Class", "Class C : Dim s As String : Sub M() : Dim x = Me.s?.ToString() : End Sub : End Class", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyFieldAccess_OnAutoPropertyBackingField() As Task Await TestAsyncWithOption( "Class C : Property I As Integer : Sub M() : [|_I|] = 1 : End Sub : End Class", "Class C : Property I As Integer : Sub M() : Me._I = 1 : End Sub : End Class", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyFieldAccess_OnBase() As Task Await TestAsyncWithOption(" Class Base Protected i As Integer End Class Class Derived Inherits Base Sub M() [|i|] = 1 End Sub End Class ", " Class Base Protected i As Integer End Class Class Derived Inherits Base Sub M() Me.i = 1 End Sub End Class ", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyFieldAccess_InObjectInitializer() As Task Await TestAsyncWithOption(" Class C Protected i As Integer = 1 Sub M() Dim test = New System.Collections.Generic.List(Of Integer) With { [|i|] } End Sub End Class ", " Class C Protected i As Integer = 1 Sub M() Dim test = New System.Collections.Generic.List(Of Integer) With { Me.i } End Sub End Class ", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyFieldAccess_InCollectionInitializer() As Task Await TestAsyncWithOption(" Class C Protected i As Integer = 1 Sub M() Dim test = New System.Collections.Generic.List(Of Integer) With { [|i|] } End Sub End Class ", " Class C Protected i As Integer = 1 Sub M() Dim test = New System.Collections.Generic.List(Of Integer) With { Me.i } End Sub End Class ", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyFieldAccess_NotSuggestedOnInstance() As Task Await TestMissingAsyncWithOption( "Class C : Dim i As Integer : Sub M(c As C) : c.[|i|] = 1 : End Sub : End Class", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyFieldAccess_NotSuggestedOnShared() As Task Await TestMissingAsyncWithOption( "Class C : Shared i As Integer : Sub M() : [|i|] = 1 : End Sub : End Class", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyFieldAccess_NotSuggestedOnSharedWithMe() As Task Await TestMissingAsyncWithOption( "Class C : Shared i As Integer : Sub M() : Me.[|i|] = 1 : End Sub : End Class", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyFieldAccess_NotSuggestedInModule() As Task Await TestMissingAsyncWithOption( "Module C : Dim i As Integer : Sub M() : [|i|] = 1 : End Sub : End Module", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyFieldAccess_NotSuggestedOnLocalVarInObjectInitializer() As Task Await TestMissingAsyncWithOption( "Class C Sub M() Dim i = 1 Dim test = New System.Collections.Generic.List(Of Integer) With { [|i|] } End Sub End Module", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyFieldAccess_NotSuggestedOnLocalVarInCollectionInitializer() As Task Await TestMissingAsyncWithOption( "Class C Sub M() Dim i = 1 Dim test = New System.Collections.Generic.List(Of Integer) With { [|i|] } End Sub End Module", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyPropertyAccess_LHS() As Task Await TestAsyncWithOption( "Class C : Property i As Integer : Sub M() : [|i|] = 1 : End Sub : End Class", "Class C : Property i As Integer : Sub M() : Me.i = 1 : End Sub : End Class", CodeStyleOptions.QualifyPropertyAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyPropertyAccess_RHS() As Task Await TestAsyncWithOption( "Class C : Property i As Integer : Sub M() : Dim x = [|i|] : End Sub : End Class", "Class C : Property i As Integer : Sub M() : Dim x = Me.i : End Sub : End Class", CodeStyleOptions.QualifyPropertyAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyPropertyAccess_MethodArgument() As Task Await TestAsyncWithOption( "Class C : Property i As Integer : Sub M(ii As Integer) : M([|i|]) : End Sub : End Class", "Class C : Property i As Integer : Sub M(ii As Integer) : M(Me.i) : End Sub : End Class", CodeStyleOptions.QualifyPropertyAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyPropertyAccess_ChainedAccess() As Task Await TestAsyncWithOption( "Class C : Property i As Integer : Sub M() : Dim s = [|i|].ToString() : End Sub : End Class", "Class C : Property i As Integer : Sub M() : Dim s = Me.i.ToString() : End Sub : End Class", CodeStyleOptions.QualifyPropertyAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyPropertyAccess_ConditionalAccess() As Task Await TestAsyncWithOption( "Class C : Property s As String : Sub M() : Dim x = [|s|]?.ToString() : End Sub : End Class", "Class C : Property s As String : Sub M() : Dim x = Me.s?.ToString() : End Sub : End Class", CodeStyleOptions.QualifyPropertyAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyPropertyAccess_OnBase() As Task Await TestAsyncWithOption(" Class Base Protected Property i As Integer End Class Class Derived Inherits Base Sub M() [|i|] = 1 End Sub End Class ", " Class Base Protected Property i As Integer End Class Class Derived Inherits Base Sub M() Me.i = 1 End Sub End Class ", CodeStyleOptions.QualifyPropertyAccess) End Function <WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyPropertyAccess_InObjectInitializer() As Task Await TestAsyncWithOption(" Class C Protected Property i As Integer Sub M() Dim test = New System.Collections.Generic.List(Of Integer) With { [|i|] } End Sub End Class ", " Class C Protected Property i As Integer Sub M() Dim test = New System.Collections.Generic.List(Of Integer) With { Me.i } End Sub End Class ", CodeStyleOptions.QualifyPropertyAccess) End Function <WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyPropertyAccess_InCollectionInitializer() As Task Await TestAsyncWithOption(" Class C Protected Property i As Integer Sub M() Dim test = New System.Collections.Generic.List(Of Integer) With { [|i|] } End Sub End Class ", " Class C Protected Property i As Integer Sub M() Dim test = New System.Collections.Generic.List(Of Integer) With { Me.i } End Sub End Class ", CodeStyleOptions.QualifyPropertyAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyPropertyAccess_NotSuggestedOnInstance() As Task Await TestMissingAsyncWithOption( "Class C : Property i As Integer : Sub M(c As C) : c.[|i|] = 1 : End Sub : End Class", CodeStyleOptions.QualifyPropertyAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyPropertyAccess_NotSuggestedOnShared() As Task Await TestMissingAsyncWithOption( "Class C : Shared Property i As Integer : Sub M() : [|i|] = 1 : End Sub : End Class", CodeStyleOptions.QualifyPropertyAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyMethodAccess_FunctionCallWithReturnType() As Task Await TestAsyncWithOption( "Class C : Function M() As Integer : Return [|M|]() : End Function : End Class", "Class C : Function M() As Integer : Return Me.M() : End Function : End Class", CodeStyleOptions.QualifyMethodAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyMethodAccess_ChainedAccess() As Task Await TestAsyncWithOption( "Class C : Function M() As String : Return [|M|]().ToString() : End Function : End Class", "Class C : Function M() As String : Return Me.M().ToString() : End Function : End Class", CodeStyleOptions.QualifyMethodAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyMethodAccess_ConditionalAccess() As Task Await TestAsyncWithOption( "Class C : Function M() As String : Return [|M|]()?.ToString() : End Function : End Class", "Class C : Function M() As String : Return Me.M()?.ToString() : End Function : End Class", CodeStyleOptions.QualifyMethodAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyMethodAccess_EventSubscription1() As Task Await TestAsyncWithOption(" Imports System Class C Event e As EventHandler Sub Handler(sender As Object, args As EventArgs) AddHandler e, AddressOf [|Handler|] End Sub End Class", " Imports System Class C Event e As EventHandler Sub Handler(sender As Object, args As EventArgs) AddHandler e, AddressOf Me.Handler End Sub End Class", CodeStyleOptions.QualifyMethodAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyMethodAccess_EventSubscription2() As Task Await TestAsyncWithOption(" Imports System Class C Event e As EventHandler Sub Handler(sender As Object, args As EventArgs) AddHandler e, New EventHandler(AddressOf [|Handler|]) End Sub End Class", " Imports System Class C Event e As EventHandler Sub Handler(sender As Object, args As EventArgs) AddHandler e, New EventHandler(AddressOf Me.Handler) End Sub End Class", CodeStyleOptions.QualifyMethodAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyMethodAccess_OnBase() As Task Await TestAsyncWithOption(" Class Base Protected Sub Method() End Sub End Class Class Derived Inherits Base Sub M() [|Method|]() End Sub End Class ", " Class Base Protected Sub Method() End Sub End Class Class Derived Inherits Base Sub M() Me.Method() End Sub End Class ", CodeStyleOptions.QualifyMethodAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyMethodAccess_NotSuggestedOnInstance() As Task Await TestMissingAsyncWithOption( "Class C : Sub M(c As C) : c.[|M|]() : End Sub : End Class", CodeStyleOptions.QualifyMethodAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyMethodAccess_NotSuggestedOnShared() As Task Await TestMissingAsyncWithOption( "Class C : Shared Sub Method() : End Sub : Sub M() : [|Method|]() : End Sub : End Class", CodeStyleOptions.QualifyMethodAccess) End Function <WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyMethodAccess_NotSuggestedOnLocalVarInObjectInitializer() As Task Await TestMissingAsyncWithOption( "Class C Sub M() Dim i = 1 Dim test = New System.Collections.Generic.List(Of Integer) With { [|i|] } End Sub End Module", CodeStyleOptions.QualifyMethodAccess) End Function <WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyMethodAccess_NotSuggestedOnLocalVarInCollectionInitializer() As Task Await TestMissingAsyncWithOption( "Class C Sub M() Dim i = 1 Dim test = New System.Collections.Generic.List(Of Integer) With { [|i|] } End Sub End Module", CodeStyleOptions.QualifyMethodAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/7587"), Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyEventAccess_AddHandler() As Task Await TestAsyncWithOption(" Imports System Class C Event e As EventHandler Sub Handler(sender As Object, args As EventArgs) AddHandler [|e|], AddressOf Handler End Function End Class", " Imports System Class C Event e As EventHandler Sub Handler(sender As Object, args As EventArgs) AddHandler Me.e, AddressOf Handler End Function End Class", CodeStyleOptions.QualifyEventAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/7587"), Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyEventAccess_OnBase() As Task Await TestAsyncWithOption(" Imports System Class Base Protected Event e As EventHandler End Class Class Derived Inherits Base Sub Handler(sender As Object, args As EventArgs) AddHandler [|e|], AddressOf Handler End Function End Class", " Imports System Class Base Protected Event e As EventHandler End Class Class Derived Inherits Base Sub Handler(sender As Object, args As EventArgs) AddHandler Me.e, AddressOf Handler End Function End Class", CodeStyleOptions.QualifyEventAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyEventAccess_NotSuggestedOnInstance() As Task Await TestMissingAsyncWithOption(" Imports System Class C Event e As EventHandler Sub M(c As C) AddHandler c.[|e|], AddressOf Handler End Sub Sub Handler(sender As Object, args As EventArgs) End Function End Class", CodeStyleOptions.QualifyEventAccess) End Function <WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyEventAccess_NotSuggestedOnShared() As Task Await TestMissingAsyncWithOption(" Imports System Class C Shared Event e As EventHandler Sub Handler(sender As Object, args As EventArgs) AddHandler [|e|], AddressOf Handler End Function End Class", CodeStyleOptions.QualifyEventAccess) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyMemberAccessOnNotificationOptionSilent() As Task Await TestAsyncWithOptionAndNotification( "Class C : Property I As Integer : Sub M() : [|I|] = 1 : End Sub : End Class", "Class C : Property I As Integer : Sub M() : Me.I = 1 : End Sub : End Class", CodeStyleOptions.QualifyPropertyAccess, NotificationOption.Silent) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyMemberAccessOnNotificationOptionInfo() As Task Await TestAsyncWithOptionAndNotification( "Class C : Property I As Integer : Sub M() : [|I|] = 1 : End Sub : End Class", "Class C : Property I As Integer : Sub M() : Me.I = 1 : End Sub : End Class", CodeStyleOptions.QualifyPropertyAccess, NotificationOption.Suggestion) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyMemberAccessOnNotificationOptionWarning() As Task Await TestAsyncWithOptionAndNotification( "Class C : Property I As Integer : Sub M() : [|I|] = 1 : End Sub : End Class", "Class C : Property I As Integer : Sub M() : Me.I = 1 : End Sub : End Class", CodeStyleOptions.QualifyPropertyAccess, NotificationOption.Warning) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function QualifyMemberAccessOnNotificationOptionError() As Task Await TestAsyncWithOptionAndNotification( "Class C : Property I As Integer : Sub M() : [|I|] = 1 : End Sub : End Class", "Class C : Property I As Integer : Sub M() : Me.I = 1 : End Sub : End Class", CodeStyleOptions.QualifyPropertyAccess, NotificationOption.Error) End Function <WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function DoNotReportToQualify_IfMyBaseQualificationOnField() As Task Await TestMissingAsyncWithOption(" Class Base Protected Field As Integer End Class Class Derived Inherits Base Sub M() [|MyBase.Field|] = 0 End Sub End Class ", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function DoNotReportToQualify_IfMyClassQualificationOnField() As Task Await TestMissingAsyncWithOption(" Class C Private ReadOnly Field As Integer Sub M() [|MyClass.Field|] = 0 End Sub End Class ", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function DoNotReportToQualify_IfMyBaseQualificationOnProperty() As Task Await TestMissingAsyncWithOption(" Class Base Protected Overridable ReadOnly Property P As Integer End Class Class Derived Inherits Base Protected Overrides ReadOnly Property P As Integer Get Return [|MyBase.P|] End Get End Class ", CodeStyleOptions.QualifyPropertyAccess) End Function <WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function DoNotReportToQualify_IfMyClassQualificationOnProperty() As Task Await TestMissingAsyncWithOption(" Class C Dim i As Integer Protected Overridable ReadOnly Property P As Integer Sub M() Me.i = [|MyClass.P|] End Sub End Class ", CodeStyleOptions.QualifyPropertyAccess) End Function <WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function DoNotReportToQualify_IfMyBaseQualificationOnMethod() As Task Await TestMissingAsyncWithOption(" Class Base Protected Overridable Sub M End Sub End Class Class Derived Inherits Base Protected Overrides Sub M() Get Return [|MyBase.M|]() End Get End Class ", CodeStyleOptions.QualifyMethodAccess) End Function <WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function DoNotReportToQualify_IfMyClassQualificationOnMethod() As Task Await TestMissingAsyncWithOption(" Class C Protected Overridable Sub M() End Sub Sub M2() [|MyClass.M|]() End Sub End Class ", CodeStyleOptions.QualifyMethodAccess) End Function <WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function DoNotReportToQualify_IfInStaticContext1() As Task Await TestMissingAsyncWithOption(" Class C Private Value As String Shared Sub Test() Console.WriteLine([|Value|]) End Sub End Class ", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function DoNotReportToQualify_IfInStaticContext2() As Task Await TestMissingAsyncWithOption(" Class C Private Value As String Private Shared Field As String = NameOf([|Value|]) End Class ", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(32093, "https://github.com/dotnet/roslyn/issues/32093")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function DoNotReportToQualify_IfInBaseConstructor() As Task Await TestMissingAsyncWithOption(" Public Class Base Public ReadOnly Property Foo As String Public Sub New(ByVal foo As String) End Sub End Class Public Class Derived Inherits Base Public Sub New() MyBase.New(NameOf([|Foo|])) End Sub End Class", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(22776, "https://github.com/dotnet/roslyn/issues/22776")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function DoNotReportToQualify_InObjectInitializer1() As Task Await TestMissingAsyncWithOption(" class C Public Foo As Integer Sub Bar() Dim c = New C() With { [|.Foo = 1|] } End Sub End Class ", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(22776, "https://github.com/dotnet/roslyn/issues/22776")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function DoNotReportToQualify_InObjectInitializer2() As Task Await TestMissingAsyncWithOption(" class C Public Property Foo As Integer Sub Bar() Dim c = New C() With { [|.Foo|] = 1 } End Sub End Class ", CodeStyleOptions.QualifyFieldAccess) End Function <WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function DoNotReportToQualify_InAttribute1() As Task Await TestMissingAsyncWithOption(" Imports System Class MyAttribute Inherits Attribute Public Sub New(name as String) End Sub End Class <My(NameOf([|Goo|]))> Class C Private Property Goo As String End Class ", CodeStyleOptions.QualifyPropertyAccess) End Function <WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function DoNotReportToQualify_InAttribute2() As Task Await TestMissingAsyncWithOption(" Imports System Class MyAttribute Inherits Attribute Public Sub New(name as String) End Sub End Class Class C <My(NameOf([|Goo|]))> Private Property Goo As String End Class ", CodeStyleOptions.QualifyPropertyAccess) End Function <WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function DoNotReportToQualify_InAttribute3() As Task Await TestMissingAsyncWithOption(" Imports System Class MyAttribute Inherits Attribute Public Sub New(name as String) End Sub End Class Class C Private Property Goo As String <My(NameOf([|Goo|]))> Private Bar As Integer End Class ", CodeStyleOptions.QualifyPropertyAccess) End Function <WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)> Public Async Function DoNotReportToQualify_InAttribute4() As Task Await TestMissingAsyncWithOption(" Imports System Class MyAttribute Inherits Attribute Public Sub New(name as String) End Sub End Class Class C Private Property Goo As String Sub X(<My(NameOf([|Goo|]))>v as integer) End Sub End Class ", CodeStyleOptions.QualifyPropertyAccess) End Function End Class End Namespace
aelij/roslyn
src/EditorFeatures/VisualBasicTest/QualifyMemberAccess/QualifyMemberAccessTests.vb
Visual Basic
apache-2.0
33,012
' 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.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub SimpleArrayCreation_PrimitiveType() Dim source = <![CDATA[ Class C Public Sub F() Dim a = New String(0) {}'BIND:"New String(0) {}" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.String()) (Syntax: 'New String(0) {}') Dimension Sizes(1): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '0') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0) (Syntax: '0') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '0') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub SimpleArrayCreation_UserDefinedType() Dim source = <![CDATA[ Class M End Class Class C Public Sub F() Dim a = New M() {}'BIND:"New M() {}" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: M()) (Syntax: 'New M() {}') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'New M() {}') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub SimpleArrayCreation_ConstantDimension() Dim source = <![CDATA[ Class M End Class Class C Public Sub F() Const dimension As Integer = 1 Dim a = New M(dimension) {}'BIND:"New M(dimension) {}" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: M()) (Syntax: 'New M(dimension) {}') Dimension Sizes(1): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'dimension') Left: ILocalReferenceExpression: dimension (OperationKind.LocalReferenceExpression, Type: System.Int32, Constant: 1) (Syntax: 'dimension') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'dimension') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub SimpleArrayCreation_NonConstantDimension() Dim source = <![CDATA[ Class M End Class Class C Public Sub F(dimension As Integer) Dim a = New M(dimension) {}'BIND:"New M(dimension) {}" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: M()) (Syntax: 'New M(dimension) {}') Dimension Sizes(1): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, IsImplicit) (Syntax: 'dimension') Left: IParameterReferenceExpression: dimension (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'dimension') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'dimension') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub SimpleArrayCreation_DimensionWithImplicitConversion() Dim source = <![CDATA[ Imports System Class M End Class Class C Public Sub F(dimension As UInt16) Dim a = New M(dimension) {}'BIND:"New M(dimension) {}" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: M()) (Syntax: 'New M(dimension) {}') Dimension Sizes(1): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, IsImplicit) (Syntax: 'dimension') Left: IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Int32) (Syntax: 'dimension') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceExpression: dimension (OperationKind.ParameterReferenceExpression, Type: System.UInt16) (Syntax: 'dimension') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'dimension') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub SimpleArrayCreation_DimensionWithExplicitConversion() Dim source = <![CDATA[ Class M End Class Class C Public Sub F(dimension As Object) Dim a = New M(DirectCast(dimension, Integer)) {}'BIND:"New M(DirectCast(dimension, Integer)) {}" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: M()) (Syntax: 'New M(Direc ... nteger)) {}') Dimension Sizes(1): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, IsImplicit) (Syntax: 'DirectCast( ... n, Integer)') Left: IConversionExpression (Explicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Int32) (Syntax: 'DirectCast( ... n, Integer)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceExpression: dimension (OperationKind.ParameterReferenceExpression, Type: System.Object) (Syntax: 'dimension') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'DirectCast( ... n, Integer)') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationWithInitializer_PrimitiveType() Dim source = <![CDATA[ Class C Public Sub F(dimension As Object) Dim a = New String() {String.Empty}'BIND:"New String() {String.Empty}" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.String()) (Syntax: 'New String( ... ring.Empty}') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New String( ... ring.Empty}') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{String.Empty}') Element Values(1): IFieldReferenceExpression: System.String.Empty As System.String (Static) (OperationKind.FieldReferenceExpression, Type: System.String) (Syntax: 'String.Empty') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationWithInitializer_WithExplicitDimension() Dim source = <![CDATA[ Class C Public Sub F() Dim a = New C(1) {New C, Nothing}'BIND:"New C(1) {New C, Nothing}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: C()) (Syntax: 'New C(1) {N ... C, Nothing}') Dimension Sizes(1): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') Initializer: IArrayInitializer (2 elements) (OperationKind.ArrayInitializer) (Syntax: '{New C, Nothing}') Element Values(2): IObjectCreationExpression (Constructor: Sub C..ctor()) (OperationKind.ObjectCreationExpression, Type: C) (Syntax: 'New C') Arguments(0) Initializer: null IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: C, Constant: null) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationWithInitializerErrorCase_WithIncorrectExplicitDimension() Dim source = <![CDATA[ Class C Public Sub F() Dim a = New C(2) {New C}'BIND:"New C(2) {New C}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: C(), IsInvalid) (Syntax: 'New C(2) {New C}') Dimension Sizes(1): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '2') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '2') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '{New C}') Element Values(1): IObjectCreationExpression (Constructor: Sub C..ctor()) (OperationKind.ObjectCreationExpression, Type: C, IsInvalid) (Syntax: 'New C') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30567: Array initializer is missing 2 elements. Dim a = New C(2) {New C}'BIND:"New C(2) {New C}" ~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationWithInitializerErrorCase_WithNonConstantExpressionExplicitDimension() Dim source = <![CDATA[ Class C Public Sub F() Dim x = New Integer(2) {1, 2, 3} x = New Integer(x(0)) {1, 2}'BIND:"New Integer(x(0)) {1, 2}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32(), IsInvalid) (Syntax: 'New Integer(x(0)) {1, 2}') Dimension Sizes(1): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, IsImplicit) (Syntax: 'x(0)') Left: IArrayElementReferenceExpression (OperationKind.ArrayElementReferenceExpression, Type: System.Int32) (Syntax: 'x(0)') Array reference: ILocalReferenceExpression: x (OperationKind.LocalReferenceExpression, Type: System.Int32()) (Syntax: 'x') Indices(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0) (Syntax: '0') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'x(0)') Initializer: IArrayInitializer (2 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '{1, 2}') Element Values(2): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30949: Array initializer cannot be specified for a non constant dimension; use the empty initializer '{}'. x = New Integer(x(0)) {1, 2}'BIND:"New Integer(x(0)) {1, 2}" ~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationWithInitializer_UserDefinedType() Dim source = <![CDATA[ Class M End Class Class C Public Sub F(dimension As Object) Dim a = New M() {New M}'BIND:"New M() {New M}" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: M()) (Syntax: 'New M() {New M}') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New M() {New M}') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{New M}') Element Values(1): IObjectCreationExpression (Constructor: Sub M..ctor()) (OperationKind.ObjectCreationExpression, Type: M) (Syntax: 'New M') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationWithInitializer_ImplicitlyTyped() Dim source = <![CDATA[ Class M End Class Class C Public Sub F(dimension As Object) Dim a = {New M}'BIND:"{New M}" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: M()) (Syntax: '{New M}') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '{New M}') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer, IsImplicit) (Syntax: '{New M}') Element Values(1): IObjectCreationExpression (Constructor: Sub M..ctor()) (OperationKind.ObjectCreationExpression, Type: M) (Syntax: 'New M') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of CollectionInitializerSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationWithInitializer_ImplicitlyTypedWithoutInitializerAndDimension() Dim source = <![CDATA[ Class C Public Sub F() Dim a = {}'BIND:"Dim a = {}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Dim a = {}') IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'a') Variables: Local_1: a As System.Object() Initializer: IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Object()) (Syntax: '{}') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '{}') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer, IsImplicit) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationWithInitializer_MultipleInitializersWithConversions() Dim source = <![CDATA[ Class C Public Sub F() Dim a = "" Dim b = {"hello", a, Nothing}'BIND:"{"hello", a, Nothing}" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.String()) (Syntax: '{"hello", a, Nothing}') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '{"hello", a, Nothing}') Initializer: IArrayInitializer (3 elements) (OperationKind.ArrayInitializer, IsImplicit) (Syntax: '{"hello", a, Nothing}') Element Values(3): ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "hello") (Syntax: '"hello"') ILocalReferenceExpression: a (OperationKind.LocalReferenceExpression, Type: System.String) (Syntax: 'a') IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.String, Constant: null) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of CollectionInitializerSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub MultiDimensionalArrayCreation() Dim source = <![CDATA[ Class C Public Sub F() Dim b As Byte(,,) = New Byte(0, 1, 2) {}'BIND:"New Byte(0, 1, 2) {}" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Byte(,,)) (Syntax: 'New Byte(0, 1, 2) {}') Dimension Sizes(3): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '0') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0) (Syntax: '0') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '0') IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '2') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '2') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub MultiDimensionalArrayCreation_WithInitializer() Dim source = <![CDATA[ Class C Public Sub F() Dim b As Byte(,,) = New Byte(,,) {{{1, 2, 3}}, {{4, 5, 6}}}'BIND:"New Byte(,,) {{{1, 2, 3}}, {{4, 5, 6}}}" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Byte(,,)) (Syntax: 'New Byte(,, ... {4, 5, 6}}}') Dimension Sizes(3): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Byte(,, ... {4, 5, 6}}}') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Byte(,, ... {4, 5, 6}}}') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'New Byte(,, ... {4, 5, 6}}}') Initializer: IArrayInitializer (2 elements) (OperationKind.ArrayInitializer) (Syntax: '{{{1, 2, 3} ... {4, 5, 6}}}') Element Values(2): IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{{1, 2, 3}}') Element Values(1): IArrayInitializer (3 elements) (OperationKind.ArrayInitializer) (Syntax: '{1, 2, 3}') Element Values(3): IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Byte, Constant: 1) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Byte, Constant: 2) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Byte, Constant: 3) (Syntax: '3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 3) (Syntax: '3') IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{{4, 5, 6}}') Element Values(1): IArrayInitializer (3 elements) (OperationKind.ArrayInitializer) (Syntax: '{4, 5, 6}') Element Values(3): IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Byte, Constant: 4) (Syntax: '4') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 4) (Syntax: '4') IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Byte, Constant: 5) (Syntax: '5') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 5) (Syntax: '5') IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Byte, Constant: 6) (Syntax: '6') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 6) (Syntax: '6') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationOfSingleDimensionalArrays() Dim source = <![CDATA[ Class C Public Sub F() Dim a = {{1, 2, 3}, {4, 5, 6}}'BIND:"{{1, 2, 3}, {4, 5, 6}}" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32(,)) (Syntax: '{{1, 2, 3}, {4, 5, 6}}') Dimension Sizes(2): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '{{1, 2, 3}, {4, 5, 6}}') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '{{1, 2, 3}, {4, 5, 6}}') Initializer: IArrayInitializer (2 elements) (OperationKind.ArrayInitializer, IsImplicit) (Syntax: '{{1, 2, 3}, {4, 5, 6}}') Element Values(2): IArrayInitializer (3 elements) (OperationKind.ArrayInitializer) (Syntax: '{1, 2, 3}') Element Values(3): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 3) (Syntax: '3') IArrayInitializer (3 elements) (OperationKind.ArrayInitializer) (Syntax: '{4, 5, 6}') Element Values(3): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 4) (Syntax: '4') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 5) (Syntax: '5') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 6) (Syntax: '6') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of CollectionInitializerSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationOfMultiDimensionalArrays() Dim source = <![CDATA[ Class C Public Sub F() Dim a As Integer()(,) = New Integer(0)(,) {}'BIND:"New Integer(0)(,) {}" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32()(,)) (Syntax: 'New Integer(0)(,) {}') Dimension Sizes(1): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '0') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0) (Syntax: '0') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '0') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationOfMultiDimensionalArrays_MultipleExplicitNonConstantDimensions() Dim source = <![CDATA[ Class C Public Sub F(x As Integer()) Dim y = New Integer(x(0), x(1)) {}'BIND:"New Integer(x(0), x(1)) {}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32(,)) (Syntax: 'New Integer ... ), x(1)) {}') Dimension Sizes(2): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, IsImplicit) (Syntax: 'x(0)') Left: IArrayElementReferenceExpression (OperationKind.ArrayElementReferenceExpression, Type: System.Int32) (Syntax: 'x(0)') Array reference: IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32()) (Syntax: 'x') Indices(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0) (Syntax: '0') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'x(0)') IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, IsImplicit) (Syntax: 'x(1)') Left: IArrayElementReferenceExpression (OperationKind.ArrayElementReferenceExpression, Type: System.Int32) (Syntax: 'x(1)') Array reference: IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32()) (Syntax: 'x') Indices(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'x(1)') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationOfMultiDimensionalArrays_MultipleExplicitConstantDimensions() Dim source = <![CDATA[ Class C Public Sub F() Dim y = New Integer(1, 1) {}'BIND:"New Integer(1, 1) {}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32(,)) (Syntax: 'New Integer(1, 1) {}') Dimension Sizes(2): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationOfMultiDimensionalArraysErrorCase_InitializerMissingElements() Dim source = <![CDATA[ Class C Public Sub F() Dim y = New Integer(1, 1) {{}}'BIND:"New Integer(1, 1) {{}}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32(,), IsInvalid) (Syntax: 'New Integer(1, 1) {{}}') Dimension Sizes(2): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '{{}}') Element Values(1): IArrayInitializer (0 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30567: Array initializer is missing 1 elements. Dim y = New Integer(1, 1) {{}}'BIND:"New Integer(1, 1) {{}}" ~~~~ BC30567: Array initializer is missing 2 elements. Dim y = New Integer(1, 1) {{}}'BIND:"New Integer(1, 1) {{}}" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationOfMultiDimensionalArraysErrorCase_InitializerMissingElements02() Dim source = <![CDATA[ Class C Public Sub F() Dim y = New Integer(1, 1) {{}, {}}'BIND:"New Integer(1, 1) {{}, {}}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32(,), IsInvalid) (Syntax: 'New Integer ... 1) {{}, {}}') Dimension Sizes(2): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') Initializer: IArrayInitializer (2 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '{{}, {}}') Element Values(2): IArrayInitializer (0 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '{}') Element Values(0) IArrayInitializer (0 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30567: Array initializer is missing 2 elements. Dim y = New Integer(1, 1) {{}, {}}'BIND:"New Integer(1, 1) {{}, {}}" ~~ BC30567: Array initializer is missing 2 elements. Dim y = New Integer(1, 1) {{}, {}}'BIND:"New Integer(1, 1) {{}, {}}" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationOfMultiDimensionalArraysErrorCase_InitializerMissingElements03() Dim source = <![CDATA[ Class C Public Sub F() Dim y = New Integer(1, 1) {{1, 2}}'BIND:"New Integer(1, 1) {{1, 2}}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32(,), IsInvalid) (Syntax: 'New Integer ... 1) {{1, 2}}') Dimension Sizes(2): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '{{1, 2}}') Element Values(1): IArrayInitializer (2 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '{1, 2}') Element Values(2): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30567: Array initializer is missing 1 elements. Dim y = New Integer(1, 1) {{1, 2}}'BIND:"New Integer(1, 1) {{1, 2}}" ~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationOfMultiDimensionalArraysErrorCase_InitializerMissingElements04() Dim source = <![CDATA[ Class C Public Sub F() Dim y = New Integer(1, 1) {{1, 2}, {}}'BIND:"New Integer(1, 1) {{1, 2}, {}}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32(,), IsInvalid) (Syntax: 'New Integer ... {1, 2}, {}}') Dimension Sizes(2): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') Initializer: IArrayInitializer (2 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '{{1, 2}, {}}') Element Values(2): IArrayInitializer (2 elements) (OperationKind.ArrayInitializer) (Syntax: '{1, 2}') Element Values(2): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') IArrayInitializer (0 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30567: Array initializer is missing 2 elements. Dim y = New Integer(1, 1) {{1, 2}, {}}'BIND:"New Integer(1, 1) {{1, 2}, {}}" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationOfMultiDimensionalArrays_InitializerWithNestedArrayInitializers() Dim source = <![CDATA[ Class C Public Sub F() Dim y = New Integer(1, 1) {{1, 2}, {1, 2}}'BIND:"New Integer(1, 1) {{1, 2}, {1, 2}}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32(,)) (Syntax: 'New Integer ... 2}, {1, 2}}') Dimension Sizes(2): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') Initializer: IArrayInitializer (2 elements) (OperationKind.ArrayInitializer) (Syntax: '{{1, 2}, {1, 2}}') Element Values(2): IArrayInitializer (2 elements) (OperationKind.ArrayInitializer) (Syntax: '{1, 2}') Element Values(2): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') IArrayInitializer (2 elements) (OperationKind.ArrayInitializer) (Syntax: '{1, 2}') Element Values(2): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationOfImplicitlyTypedMultiDimensionalArrays_WithInitializer() Dim source = <![CDATA[ Class C Public Sub F() Dim a = {{{{1, 2}}}, {{{3, 4}}}}'BIND:"{{{{1, 2}}}, {{{3, 4}}}}" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32(,,,)) (Syntax: '{{{{1, 2}}}, {{{3, 4}}}}') Dimension Sizes(4): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '{{{{1, 2}}}, {{{3, 4}}}}') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '{{{{1, 2}}}, {{{3, 4}}}}') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '{{{{1, 2}}}, {{{3, 4}}}}') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '{{{{1, 2}}}, {{{3, 4}}}}') Initializer: IArrayInitializer (2 elements) (OperationKind.ArrayInitializer, IsImplicit) (Syntax: '{{{{1, 2}}}, {{{3, 4}}}}') Element Values(2): IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{{{1, 2}}}') Element Values(1): IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{{1, 2}}') Element Values(1): IArrayInitializer (2 elements) (OperationKind.ArrayInitializer) (Syntax: '{1, 2}') Element Values(2): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{{{3, 4}}}') Element Values(1): IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{{3, 4}}') Element Values(1): IArrayInitializer (2 elements) (OperationKind.ArrayInitializer) (Syntax: '{3, 4}') Element Values(2): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 3) (Syntax: '3') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 4) (Syntax: '4') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of CollectionInitializerSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationErrorCase_MissingDimension() Dim source = <![CDATA[ Class C Public Sub F() Dim a = New String(1,) {}'BIND:"New String(1,) {}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.String(,), IsInvalid) (Syntax: 'New String(1,) {}') Dimension Sizes(2): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '') Left: IInvalidExpression (OperationKind.InvalidExpression, Type: ?, IsInvalid) (Syntax: '') Children(0) Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30306: Array subscript expression missing. Dim a = New String(1,) {}'BIND:"New String(1,) {}" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationErrorCase_InvalidInitializer() Dim source = <![CDATA[ Class C Public Sub F() Dim a = New C() {1}'BIND:"New C() {1}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: C(), IsInvalid) (Syntax: 'New C() {1}') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'New C() {1}') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '{1}') Element Values(1): IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: C, IsInvalid) (Syntax: '1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'Integer' cannot be converted to 'C'. Dim a = New C() {1}'BIND:"New C() {1}" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationErrorCase_MissingExplicitCast() Dim source = <![CDATA[ Class C Public Sub F(c As C) Dim a = New C(c) {}'BIND:"New C(c) {}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: C(), IsInvalid) (Syntax: 'New C(c) {}') Dimension Sizes(1): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'c') Left: IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Int32, IsInvalid) (Syntax: 'c') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C, IsInvalid) (Syntax: 'c') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'c') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'C' cannot be converted to 'Integer'. Dim a = New C(c) {}'BIND:"New C(c) {}" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreation_InvocationExpressionAsDimension() Dim source = <![CDATA[ Class C Public Sub F(c As C) Dim a = New C(M()) {}'BIND:"New C(M()) {}" End Sub Public Function M() As Integer Return 1 End Function End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: C()) (Syntax: 'New C(M()) {}') Dimension Sizes(1): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, IsImplicit) (Syntax: 'M()') Left: IInvocationExpression ( Function C.M() As System.Int32) (OperationKind.InvocationExpression, Type: System.Int32) (Syntax: 'M()') Instance Receiver: IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: C, IsImplicit) (Syntax: 'M') Arguments(0) Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'M()') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreation_InvocationExpressionWithConversionAsDimension() Dim source = <![CDATA[ Option Strict On Class C Public Sub F(c As C) Dim a = New C(DirectCast(M(), Integer)) {}'BIND:"New C(DirectCast(M(), Integer)) {}" End Sub Public Function M() As Object Return 1 End Function End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: C()) (Syntax: 'New C(Direc ... nteger)) {}') Dimension Sizes(1): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, IsImplicit) (Syntax: 'DirectCast(M(), Integer)') Left: IConversionExpression (Explicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Int32) (Syntax: 'DirectCast(M(), Integer)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationExpression ( Function C.M() As System.Object) (OperationKind.InvocationExpression, Type: System.Object) (Syntax: 'M()') Instance Receiver: IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: C, IsImplicit) (Syntax: 'M') Arguments(0) Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'DirectCast(M(), Integer)') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationErrorCase_InvocationExpressionAsDimension() Dim source = <![CDATA[ Option Strict On Class C Public Sub F(c As C) Dim a = New C(M()) {}'BIND:"New C(M()) {}" End Sub Public Function M() As Object Return 1 End Function End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: C(), IsInvalid) (Syntax: 'New C(M()) {}') Dimension Sizes(1): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M()') Left: IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Int32, IsInvalid) (Syntax: 'M()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationExpression ( Function C.M() As System.Object) (OperationKind.InvocationExpression, Type: System.Object, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'M()') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'. Dim a = New C(M()) {}'BIND:"New C(M()) {}" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreationErrorCase_InvocationExpressionWithConversionAsDimension() Dim source = <![CDATA[ Option Strict On Class C Public Sub F(c As C) Dim a = New C(DirectCast(M(), Integer)) {}'BIND:"New C(DirectCast(M(), Integer)) {}" End Sub Public Function M() As C Return New C End Function End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: C(), IsInvalid) (Syntax: 'New C(Direc ... nteger)) {}') Dimension Sizes(1): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'DirectCast(M(), Integer)') Left: IConversionExpression (Explicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Int32, IsInvalid) (Syntax: 'DirectCast(M(), Integer)') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationExpression ( Function C.M() As C) (OperationKind.InvocationExpression, Type: C, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'DirectCast(M(), Integer)') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer) (Syntax: '{}') Element Values(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'C' cannot be converted to 'Integer'. Dim a = New C(DirectCast(M(), Integer)) {}'BIND:"New C(DirectCast(M(), Integer)) {}" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")> Public Sub ArrayCreation_DeclarationWithExplicitDimension() Dim source = <![CDATA[ Class C Public Sub F() Dim x(2) As Integer'BIND:"Dim x(2) As Integer" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Dim x(2) As Integer') IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'x(2)') Variables: Local_1: x As System.Int32() Initializer: IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32()) (Syntax: 'x(2)') Dimension Sizes(1): IBinaryOperatorExpression (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '2') Left: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '2') Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub End Class End Namespace
jkotas/roslyn
src/Compilers/VisualBasic/Test/Semantic/IOperation/IOperationTests_ArrayCreationAndInitializer.vb
Visual Basic
apache-2.0
64,838
' Copyright (c) 2015 ZZZ Projects. All rights reserved ' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods) ' Website: http://www.zzzprojects.com/ ' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927 ' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library Public Module Extensions_380 ''' <summary> ''' An object extension method that converts the @this to an int 32. ''' </summary> ''' <param name="this">The @this to act on.</param> ''' <returns>@this as an int.</returns> <System.Runtime.CompilerServices.Extension> _ Public Function ToInt32(this As Object) As Integer Return Convert.ToInt32(this) End Function End Module
mario-loza/Z.ExtensionMethods
src (VB.NET)/Z.ExtensionMethods.VB/Z.Core/System.Object/Convert/ToValueType/Object.ToInt32.vb
Visual Basic
mit
767
'*******************************************************************************************' ' ' ' 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 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("GetCellColor VB.NET")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("GetCellColor VB.NET")> <Assembly: AssemblyCopyright("Copyright © 2009")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("6885b402-1dae-4935-993a-0ff4154d40f6")> ' 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")>
bytescout/ByteScout-SDK-SourceCode
Spreadsheet SDK/VB.NET/Get Cell Color/My Project/AssemblyInfo.vb
Visual Basic
apache-2.0
2,131
' 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.Implementation.IntelliSense Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Moq Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <UseExportProvider> <Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Class ModelTests Public Class Model End Class Private Class TestModelComputation Inherits ModelComputation(Of Model) Public Sub New(threadingContext As IThreadingContext, controller As IController(Of Model)) MyBase.New(threadingContext, controller, TaskScheduler.Default) End Sub Friend Shared Function Create(threadingContext As IThreadingContext, Optional controller As IController(Of Model) = Nothing) As TestModelComputation If controller Is Nothing Then Dim mock = New Mock(Of IController(Of Model))(MockBehavior.Strict) controller = mock.Object End If Return New TestModelComputation(threadingContext, controller) End Function Friend Sub Wait() WaitForController() End Sub End Class <WpfFact> Public Sub ChainingTaskStartsAsyncOperation() Dim threadingContext = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider().GetExportedValue(Of IThreadingContext) Dim controller = New Mock(Of IController(Of Model))(MockBehavior.Strict) controller.Setup(Function(c) c.BeginAsyncOperation("", Nothing, It.IsAny(Of String), It.IsAny(Of Integer))).Returns(EmptyAsyncToken.Instance) Dim modelComputation = TestModelComputation.Create(threadingContext, controller:=controller.Object) modelComputation.ChainTaskAndNotifyControllerWhenFinished(Function(m) m) controller.Verify(Sub(c) c.BeginAsyncOperation( It.IsAny(Of String), Nothing, It.IsAny(Of String), It.IsAny(Of Integer))) End Sub <WpfFact> Public Sub ChainingTaskThatCompletesNotifiesController() Dim threadingContext = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider().GetExportedValue(Of IThreadingContext) Dim model = New Model() Dim controller = New Mock(Of IController(Of Model))(MockBehavior.Strict) controller.Setup(Function(c) c.BeginAsyncOperation("", Nothing, It.IsAny(Of String), It.IsAny(Of Integer))).Returns(EmptyAsyncToken.Instance) controller.Setup(Sub(c) c.OnModelUpdated(model, True)) Dim modelComputation = TestModelComputation.Create(threadingContext, controller:=controller.Object) modelComputation.ChainTaskAndNotifyControllerWhenFinished(Function(m) model) modelComputation.Wait() controller.Verify(Sub(c) c.OnModelUpdated(model, True)) End Sub <WpfFact> Public Sub ControllerIsOnlyUpdatedAfterLastTaskCompletes() Dim threadingContext = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider().GetExportedValue(Of IThreadingContext) Dim model = New Model() Dim controller = New Mock(Of IController(Of Model))(MockBehavior.Strict) controller.Setup(Function(c) c.BeginAsyncOperation("", Nothing, It.IsAny(Of String), It.IsAny(Of Integer))).Returns(EmptyAsyncToken.Instance) controller.Setup(Sub(c) c.OnModelUpdated(model, True)) Dim modelComputation = TestModelComputation.Create(threadingContext, controller:=controller.Object) Dim gate = New Object Monitor.Enter(gate) modelComputation.ChainTaskAndNotifyControllerWhenFinished(Function(m) SyncLock gate Return Nothing End SyncLock End Function) modelComputation.ChainTaskAndNotifyControllerWhenFinished(Function(m) model) Monitor.Exit(gate) modelComputation.Wait() controller.Verify(Sub(c) c.OnModelUpdated(model, True), Times.Once) End Sub <WpfFact> Public Async Function ControllerIsNotUpdatedIfComputationIsCancelled() As Task Dim threadingContext = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider().GetExportedValue(Of IThreadingContext) Dim controller = New Mock(Of IController(Of Model))(MockBehavior.Strict) Dim token = New Mock(Of IAsyncToken)(MockBehavior.Strict) controller.Setup(Function(c) c.BeginAsyncOperation( It.IsAny(Of String), Nothing, It.IsAny(Of String), It.IsAny(Of Integer))).Returns(token.Object) Dim modelComputation = TestModelComputation.Create(threadingContext, controller:=controller.Object) Dim model = New Model() Dim checkpoint1 = New Checkpoint Dim checkpoint2 = New Checkpoint Dim checkpoint3 = New Checkpoint token.Setup(Sub(t) t.Dispose()).Callback(Sub() checkpoint3.Release()) modelComputation.ChainTaskAndNotifyControllerWhenFinished(Function(m, c) checkpoint1.Release() checkpoint2.Task.Wait() c.ThrowIfCancellationRequested() Return Task.FromResult(model) End Function) Await checkpoint1.Task modelComputation.Stop() checkpoint2.Release() Await checkpoint3.Task controller.Verify(Sub(c) c.OnModelUpdated(model, True), Times.Never) End Function End Class End Namespace
physhi/roslyn
src/EditorFeatures/Test2/IntelliSense/ModelTests.vb
Visual Basic
apache-2.0
6,741
' 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.Implementation.AutomaticCompletion Imports Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion.Sessions Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.VisualStudio.Text.BraceCompletion Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticCompletion.Sessions Friend Class InterpolationCompletionSession Inherits AbstractTokenBraceCompletionSession Public Sub New(syntaxFactsService As ISyntaxFactsService) MyBase.New(syntaxFactsService, SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken) End Sub Public Overrides Function CheckOpeningPoint(session As IBraceCompletionSession, cancellationToken As CancellationToken) As Boolean Dim snapshot = session.SubjectBuffer.CurrentSnapshot Dim position = session.OpeningPoint.GetPosition(snapshot) Dim token = snapshot.FindToken(position, cancellationToken) Return token.IsKind(SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken) OrElse (token.IsKind(SyntaxKind.CloseBraceToken) AndAlso token.Parent.IsKind(SyntaxKind.Interpolation)) End Function Public Overrides Function AllowOverType(session As IBraceCompletionSession, cancellationToken As CancellationToken) As Boolean Return CheckClosingTokenKind(session, cancellationToken) End Function Public Shared Function IsContext(document As Document, position As Integer, cancellationToken As CancellationToken) As Boolean If position = 0 Then Return False End If ' Check to see if the character to the left of the position is an open curly brace. Note that we have to ' count braces to ensure that the character isn't actually an escaped brace. Dim text = document.GetTextSynchronously(cancellationToken) Dim index = position - 1 Dim openCurlyCount = 0 For index = index To 0 Step -1 If text(index) = "{"c Then openCurlyCount += 1 Else Exit For End If Next If openCurlyCount Mod 2 > 0 Then Return False End If ' Next, check to see if the token we're typing is part of an existing interpolated string. ' Dim tree = document.GetSyntaxTreeSynchronously(cancellationToken) Dim token = tree.GetRoot(cancellationToken).FindTokenOnRightOfPosition(position) If Not token.Span.IntersectsWith(position) Then Return False End If Return token.IsKind(SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken) OrElse (token.IsKind(SyntaxKind.CloseBraceToken) AndAlso token.Parent.IsKind(SyntaxKind.Interpolation)) End Function End Class End Namespace
jmarolf/roslyn
src/EditorFeatures/VisualBasic/AutomaticCompletion/Sessions/InterpolationCompletionSession.vb
Visual Basic
mit
3,238
' 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.Editor.Implementation.AutomaticCompletion.Sessions Imports Microsoft.CodeAnalysis.LanguageServices Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticCompletion.Sessions Friend Class CurlyBraceCompletionSession Inherits AbstractTokenBraceCompletionSession Public Sub New(syntaxFactsService As ISyntaxFactsService) MyBase.New(syntaxFactsService, SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken) End Sub End Class End Namespace
jmarolf/roslyn
src/EditorFeatures/VisualBasic/AutomaticCompletion/Sessions/CurlyBraceCompletionSession.vb
Visual Basic
mit
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 Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SimplifyTypeNames Public Class SimplifyTypeNamesTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInDocument() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32 Dim i1 As {|FixAllInDocument:System.Int32|} = 0 Dim s1 As System.Int16 = 0 Dim i2 As System.Int32 = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32 Dim i1 As System.Int32 = 0 Dim s1 As System.Int16 = 0 Dim i2 As System.Int32 = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32 Dim i1 As System.Int32 = 0 Dim s1 As System.Int16 = 0 Dim i2 As System.Int32 = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As Integer, y As Short) As Integer Dim i1 As Integer = 0 Dim s1 As Short = 0 Dim i2 As Integer = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32 Dim i1 As System.Int32 = 0 Dim s1 As System.Int16 = 0 Dim i2 As System.Int32 = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32 Dim i1 As System.Int32 = 0 Dim s1 As System.Int16 = 0 Dim i2 As System.Int32 = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected, options:=PreferIntrinsicPredefinedTypeEverywhere()) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInProject() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32 Dim i1 As {|FixAllInProject:System.Int32|} = 0 Dim s1 As System.Int16 = 0 Dim i2 As System.Int32 = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32 Dim i1 As System.Int32 = 0 Dim s1 As System.Int16 = 0 Dim i2 As System.Int32 = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32 Dim i1 As System.Int32 = 0 Dim s1 As System.Int16 = 0 Dim i2 As System.Int32 = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As Integer, y As Short) As Integer Dim i1 As Integer = 0 Dim s1 As Short = 0 Dim i2 As Integer = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As Integer, y As Short) As Integer Dim i1 As Integer = 0 Dim s1 As Short = 0 Dim i2 As Integer = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32 Dim i1 As System.Int32 = 0 Dim s1 As System.Int16 = 0 Dim i2 As System.Int32 = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected, options:=PreferIntrinsicPredefinedTypeEverywhere()) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInSolution() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32 Dim i1 As {|FixAllInSolution:System.Int32|} = 0 Dim s1 As System.Int16 = 0 Dim i2 As System.Int32 = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32 Dim i1 As System.Int32 = 0 Dim s1 As System.Int16 = 0 Dim i2 As System.Int32 = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32 Dim i1 As System.Int32 = 0 Dim s1 As System.Int16 = 0 Dim i2 As System.Int32 = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As Integer, y As Short) As Integer Dim i1 As Integer = 0 Dim s1 As Short = 0 Dim i2 As Integer = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As Integer, y As Short) As Integer Dim i1 As Integer = 0 Dim s1 As Short = 0 Dim i2 As Integer = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class Program Private Shared Function F(x As Integer, y As Short) As Integer Dim i1 As Integer = 0 Dim s1 As Short = 0 Dim i2 As Integer = 0 Return i1 + s1 + i2 End Function End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected, options:=PreferIntrinsicPredefinedTypeEverywhere()) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInSolution_SimplifyMemberAccess() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class ProgramA Dim x As Integer = 0 Dim y As Integer = 0 Dim z As Integer = 0 Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32 Dim i1 As System.Int32 = Me.x Dim s1 As System.Int16 = Me.y Dim i2 As System.Int32 = Me.z {|FixAllInSolution:System.Console.Write|}(i1 + s1 + i2) System.Console.WriteLine(i1 + s1 + i2) Dim ex As System.Exception = Nothing Return i1 + s1 + i2 End Function End Class Class ProgramB Dim x2 As Integer = 0 Dim y2 As Integer = 0 Dim z2 As Integer = 0 Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32 Dim i1 As System.Int32 = Me.x2 Dim s1 As System.Int16 = Me.y2 Dim i2 As System.Int32 = Me.z2 System.Console.Write(i1 + s1 + i2) System.Console.WriteLine(i1 + s1 + i2) Dim ex As System.Exception = Nothing Return i1 + s1 + i2 End Function End Class ]]> </Document> <Document><![CDATA[ Imports System Class ProgramA2 Dim x As Integer = 0 Dim y As Integer = 0 Dim z As Integer = 0 Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32 Dim i1 As System.Int32 = Me.x Dim s1 As System.Int16 = Me.y Dim i2 As System.Int32 = Me.z System.Console.Write(i1 + s1 + i2) System.Console.WriteLine(i1 + s1 + i2) Dim ex As System.Exception = Nothing Return i1 + s1 + i2 End Function End Class Class ProgramB2 Dim x2 As Integer = 0 Dim y2 As Integer = 0 Dim z2 As Integer = 0 Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32 Dim i1 As System.Int32 = Me.x2 Dim s1 As System.Int16 = Me.y2 Dim i2 As System.Int32 = Me.z2 System.Console.Write(i1 + s1 + i2) System.Console.WriteLine(i1 + s1 + i2) Dim ex As System.Exception = Nothing Return i1 + s1 + i2 End Function End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class ProgramA3 Dim x As Integer = 0 Dim y As Integer = 0 Dim z As Integer = 0 Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32 Dim i1 As System.Int32 = Me.x Dim s1 As System.Int16 = Me.y Dim i2 As System.Int32 = Me.z System.Console.Write(i1 + s1 + i2) System.Console.WriteLine(i1 + s1 + i2) Dim ex As System.Exception = Nothing Return i1 + s1 + i2 End Function End Class Class ProgramB3 Dim x2 As Integer = 0 Dim y2 As Integer = 0 Dim z2 As Integer = 0 Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32 Dim i1 As System.Int32 = Me.x2 Dim s1 As System.Int16 = Me.y2 Dim i2 As System.Int32 = Me.z2 System.Console.Write(i1 + s1 + i2) System.Console.WriteLine(i1 + s1 + i2) Dim ex As System.Exception = Nothing Return i1 + s1 + i2 End Function End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Imports System Class ProgramA Dim x As Integer = 0 Dim y As Integer = 0 Dim z As Integer = 0 Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32 Dim i1 As System.Int32 = Me.x Dim s1 As System.Int16 = Me.y Dim i2 As System.Int32 = Me.z Console.Write(i1 + s1 + i2) Console.WriteLine(i1 + s1 + i2) Dim ex As System.Exception = Nothing Return i1 + s1 + i2 End Function End Class Class ProgramB Dim x2 As Integer = 0 Dim y2 As Integer = 0 Dim z2 As Integer = 0 Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32 Dim i1 As System.Int32 = Me.x2 Dim s1 As System.Int16 = Me.y2 Dim i2 As System.Int32 = Me.z2 Console.Write(i1 + s1 + i2) Console.WriteLine(i1 + s1 + i2) Dim ex As System.Exception = Nothing Return i1 + s1 + i2 End Function End Class ]]> </Document> <Document><![CDATA[ Imports System Class ProgramA2 Dim x As Integer = 0 Dim y As Integer = 0 Dim z As Integer = 0 Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32 Dim i1 As System.Int32 = Me.x Dim s1 As System.Int16 = Me.y Dim i2 As System.Int32 = Me.z Console.Write(i1 + s1 + i2) Console.WriteLine(i1 + s1 + i2) Dim ex As System.Exception = Nothing Return i1 + s1 + i2 End Function End Class Class ProgramB2 Dim x2 As Integer = 0 Dim y2 As Integer = 0 Dim z2 As Integer = 0 Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32 Dim i1 As System.Int32 = Me.x2 Dim s1 As System.Int16 = Me.y2 Dim i2 As System.Int32 = Me.z2 Console.Write(i1 + s1 + i2) Console.WriteLine(i1 + s1 + i2) Dim ex As System.Exception = Nothing Return i1 + s1 + i2 End Function End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Imports System Class ProgramA3 Dim x As Integer = 0 Dim y As Integer = 0 Dim z As Integer = 0 Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32 Dim i1 As System.Int32 = Me.x Dim s1 As System.Int16 = Me.y Dim i2 As System.Int32 = Me.z Console.Write(i1 + s1 + i2) Console.WriteLine(i1 + s1 + i2) Dim ex As System.Exception = Nothing Return i1 + s1 + i2 End Function End Class Class ProgramB3 Dim x2 As Integer = 0 Dim y2 As Integer = 0 Dim z2 As Integer = 0 Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32 Dim i1 As System.Int32 = Me.x2 Dim s1 As System.Int16 = Me.y2 Dim i2 As System.Int32 = Me.z2 Console.Write(i1 + s1 + i2) Console.WriteLine(i1 + s1 + i2) Dim ex As System.Exception = Nothing Return i1 + s1 + i2 End Function End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function End Class End Namespace
aelij/roslyn
src/EditorFeatures/VisualBasicTest/SimplifyTypeNames/SimplifyTypeNamesTests_FixAllTests.vb
Visual Basic
apache-2.0
18,731
' 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.Composition Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.UseIsNullCheck Namespace Microsoft.CodeAnalysis.VisualBasic.UseIsNullCheck <ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicUseIsNullCheckCodeFixProvider Inherits AbstractUseIsNullCheckCodeFixProvider Protected Overrides Function GetIsNullTitle() As String Return VBFeaturesResources.use_Is_Nothing_check End Function Protected Overrides Function GetIsNotNullTitle() As String Return VBFeaturesResources.use_IsNot_Nothing_check End Function Protected Overrides Function CreateIsNullCheck(argument As SyntaxNode) As SyntaxNode Return SyntaxFactory.IsExpression( DirectCast(argument, ExpressionSyntax).Parenthesize(), SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword))).Parenthesize() End Function Protected Overrides Function CreateIsNotNullCheck(notExpression As SyntaxNode, argument As SyntaxNode) As SyntaxNode Return SyntaxFactory.IsNotExpression( DirectCast(argument, ExpressionSyntax).Parenthesize(), SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword))).Parenthesize() End Function End Class End Namespace
pdelvo/roslyn
src/Features/VisualBasic/Portable/UseIsNullCheck/VisualBasicUseIsNullCheckCodeFixProvider.vb
Visual Basic
apache-2.0
1,632
' 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.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting Friend NotInheritable Class RetargetingPropertySymbol Inherits PropertySymbol ''' <summary> ''' Owning RetargetingModuleSymbol. ''' </summary> Private ReadOnly _retargetingModule As RetargetingModuleSymbol ''' <summary> ''' The underlying PropertySymbol, cannot be another RetargetingPropertySymbol. ''' </summary> Private ReadOnly _underlyingProperty As PropertySymbol Private _lazyParameters As ImmutableArray(Of ParameterSymbol) Private _lazyCustomModifiers As CustomModifiersTuple ''' <summary> ''' Retargeted custom attributes ''' </summary> ''' <remarks></remarks> Private _lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData) Private _lazyExplicitInterfaceImplementations As ImmutableArray(Of PropertySymbol) Private _lazyUseSiteErrorInfo As DiagnosticInfo = ErrorFactory.EmptyErrorInfo ' Indicates unknown state. Public Sub New(retargetingModule As RetargetingModuleSymbol, underlyingProperty As PropertySymbol) Debug.Assert(retargetingModule IsNot Nothing) Debug.Assert(underlyingProperty IsNot Nothing) If TypeOf underlyingProperty Is RetargetingPropertySymbol Then Throw New ArgumentException() End If _retargetingModule = retargetingModule _underlyingProperty = underlyingProperty End Sub Private ReadOnly Property RetargetingTranslator As RetargetingModuleSymbol.RetargetingSymbolTranslator Get Return _retargetingModule.RetargetingTranslator End Get End Property Public ReadOnly Property UnderlyingProperty As PropertySymbol Get Return _underlyingProperty End Get End Property Public ReadOnly Property RetargetingModule As RetargetingModuleSymbol Get Return _retargetingModule End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return _underlyingProperty.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property IsWithEvents As Boolean Get Return _underlyingProperty.IsWithEvents End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return RetargetingTranslator.Retarget(_underlyingProperty.ContainingSymbol) End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return _underlyingProperty.DeclaredAccessibility End Get End Property Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return RetargetingTranslator.GetRetargetedAttributes(_underlyingProperty, _lazyCustomAttributes) End Function Friend Overrides Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState) As IEnumerable(Of VisualBasicAttributeData) Return RetargetingTranslator.RetargetAttributes(_underlyingProperty.GetCustomAttributesToEmit(compilationState)) End Function Public Overrides ReadOnly Property GetMethod As MethodSymbol Get Return If(_underlyingProperty.GetMethod Is Nothing, Nothing, RetargetingTranslator.Retarget(_underlyingProperty.GetMethod)) End Get End Property Public Overrides ReadOnly Property SetMethod As MethodSymbol Get Return If(_underlyingProperty.SetMethod Is Nothing, Nothing, RetargetingTranslator.Retarget(_underlyingProperty.SetMethod)) End Get End Property Friend Overrides ReadOnly Property AssociatedField As FieldSymbol Get Return If(_underlyingProperty.AssociatedField Is Nothing, Nothing, RetargetingTranslator.Retarget(_underlyingProperty.AssociatedField)) End Get End Property Public Overrides ReadOnly Property IsDefault As Boolean Get Return _underlyingProperty.IsDefault End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return _underlyingProperty.IsMustOverride End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return _underlyingProperty.IsNotOverridable End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return _underlyingProperty.IsOverridable End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return _underlyingProperty.IsOverrides End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return _underlyingProperty.IsOverloads End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return _underlyingProperty.IsShared End Get End Property Public Overrides ReadOnly Property Name As String Get Return _underlyingProperty.Name End Get End Property Public Overrides ReadOnly Property MetadataName As String Get Return _underlyingProperty.MetadataName End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return _underlyingProperty.HasSpecialName End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return _underlyingProperty.ObsoleteAttributeData End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _underlyingProperty.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return _underlyingProperty.DeclaringSyntaxReferences End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get If _lazyParameters.IsDefault Then ImmutableInterlocked.InterlockedCompareExchange(_lazyParameters, RetargetParameters(), Nothing) End If Return _lazyParameters End Get End Property Public Overrides ReadOnly Property ParameterCount As Integer Get Return _underlyingProperty.ParameterCount End Get End Property Private Function RetargetParameters() As ImmutableArray(Of ParameterSymbol) Dim list = _underlyingProperty.Parameters Dim count = list.Length If count = 0 Then Return ImmutableArray(Of ParameterSymbol).Empty Else Dim parameters = New ParameterSymbol(count - 1) {} For i As Integer = 0 To count - 1 parameters(i) = RetargetingParameterSymbol.CreatePropertyParameter(Me, list(i)) Next Return parameters.AsImmutableOrNull() End If End Function Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return _underlyingProperty.ReturnsByRef End Get End Property Public Overrides ReadOnly Property Type As TypeSymbol Get Return RetargetingTranslator.Retarget(_underlyingProperty.Type, RetargetOptions.RetargetPrimitiveTypesByTypeCode) End Get End Property Public Overrides ReadOnly Property TypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return CustomModifiersTuple.TypeCustomModifiers End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return CustomModifiersTuple.RefCustomModifiers End Get End Property Private ReadOnly Property CustomModifiersTuple As CustomModifiersTuple Get Return RetargetingTranslator.RetargetModifiers(_underlyingProperty.TypeCustomModifiers, _underlyingProperty.RefCustomModifiers, _lazyCustomModifiers) End Get End Property Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention Get Return _underlyingProperty.CallingConvention End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of PropertySymbol) Get If _lazyExplicitInterfaceImplementations.IsDefault Then ImmutableInterlocked.InterlockedCompareExchange( _lazyExplicitInterfaceImplementations, Me.RetargetExplicitInterfaceImplementations(), Nothing) End If Return _lazyExplicitInterfaceImplementations End Get End Property Private Function RetargetExplicitInterfaceImplementations() As ImmutableArray(Of PropertySymbol) Dim impls = Me.UnderlyingProperty.ExplicitInterfaceImplementations If impls.IsEmpty Then Return impls End If Dim builder = ArrayBuilder(Of PropertySymbol).GetInstance() For i = 0 To impls.Length - 1 Dim retargeted = Me.RetargetingModule.RetargetingTranslator.Retarget(impls(i), PropertySignatureComparer.RetargetedExplicitPropertyImplementationComparer) If retargeted IsNot Nothing Then builder.Add(retargeted) End If Next Return builder.ToImmutableAndFree() End Function Friend Overrides Function GetUseSiteErrorInfo() As DiagnosticInfo If _lazyUseSiteErrorInfo Is ErrorFactory.EmptyErrorInfo Then _lazyUseSiteErrorInfo = CalculateUseSiteErrorInfo() End If Return _lazyUseSiteErrorInfo End Function Friend Overrides ReadOnly Property IsMyGroupCollectionProperty As Boolean Get Return _underlyingProperty.IsMyGroupCollectionProperty End Get End Property Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean Get Return _underlyingProperty.HasRuntimeSpecialName End Get End Property ''' <remarks> ''' This is for perf, not for correctness. ''' </remarks> Friend Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation Get Return Nothing End Get End Property Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return _underlyingProperty.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function End Class End Namespace
mmitche/roslyn
src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingPropertySymbol.vb
Visual Basic
apache-2.0
12,415
' 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.VisualStudio.LanguageServices.Implementation.SolutionExplorer Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.SolutionExplorer Public Class RuleSetDocumentExtensionsTests <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub AdjustSingleNonExistentRule() Dim startingRuleSet = <RuleSet Name="MyRules" Description="A bunch of rules"> </RuleSet> Dim document = New XDocument(startingRuleSet) document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Error) Dim expectedRuleSet = <RuleSet Name="MyRules" Description="A bunch of rules"> <Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer"> <Rule Id="Test001" Action="Error"/> </Rules> </RuleSet> Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub AdjustSingleExistentRule() Dim startingRuleSet = <RuleSet Name="MyRules" Description="A bunch of rules"> <Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer"> <Rule Id="Test001" Action="Error"/> </Rules> </RuleSet> Dim document = New XDocument(startingRuleSet) document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Warn) Dim expectedRuleSet = <RuleSet Name="MyRules" Description="A bunch of rules"> <Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer"> <Rule Id="Test001" Action="Warn"/> </Rules> </RuleSet> Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub AdjustSingleRuleUnderDifferentAnalyzer() Dim startingRuleSet = <RuleSet Name="MyRules" Description="A bunch of rules"> <Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer"> <Rule Id="Test001" Action="Error"/> </Rules> </RuleSet> Dim document = New XDocument(startingRuleSet) document.SetSeverity("Beta.Analyzer", "Test001", ReportDiagnostic.Warn) Dim expectedRuleSet = <RuleSet Name="MyRules" Description="A bunch of rules"> <Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer"> <Rule Id="Test001" Action="Warn"/> </Rules> <Rules AnalyzerId="Beta.Analyzer" RuleNamespace="Alpha.Analyzer"> <Rule Id="Test001" Action="Warn"/> </Rules> </RuleSet> Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub AdjustMultipleRules() Dim startingRuleSet = <RuleSet Name="MyRules" Description="A bunch of rules"> <Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer"> <Rule Id="Test001" Action="Warn"/> </Rules> <Rules AnalyzerId="Beta.Analyzer" RuleNamespace="Alpha.Analyzer"> <Rule Id="Test001" Action="Warn"/> </Rules> </RuleSet> Dim document = New XDocument(startingRuleSet) document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Error) Dim expectedRuleSet = <RuleSet Name="MyRules" Description="A bunch of rules"> <Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer"> <Rule Id="Test001" Action="Error"/> </Rules> <Rules AnalyzerId="Beta.Analyzer" RuleNamespace="Alpha.Analyzer"> <Rule Id="Test001" Action="Error"/> </Rules> </RuleSet> Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub RemoveSingleNonExistentRule() Dim startingRuleSet = <RuleSet Name="MyRules" Description="A bunch of rules"> </RuleSet> Dim document = New XDocument(startingRuleSet) document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Default) Dim expectedRuleSet = <RuleSet Name="MyRules" Description="A bunch of rules"> <Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer"> </Rules> </RuleSet> Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub RemoveSingleExistentRule() Dim startingRuleSet = <RuleSet Name="MyRules" Description="A bunch of rules"> <Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer"> <Rule Id="Test001" Action="Error"/> </Rules> </RuleSet> Dim document = New XDocument(startingRuleSet) document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Default) Dim expectedRuleSet = <RuleSet Name="MyRules" Description="A bunch of rules"> <Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer"> </Rules> </RuleSet> Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub RemoveMultipleRules() Dim startingRuleSet = <RuleSet Name="MyRules" Description="A bunch of rules"> <Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer"> <Rule Id="Test001" Action="Warn"/> </Rules> <Rules AnalyzerId="Beta.Analyzer" RuleNamespace="Alpha.Analyzer"> <Rule Id="Test001" Action="Warn"/> </Rules> </RuleSet> Dim document = New XDocument(startingRuleSet) document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Default) Dim expectedRuleSet = <RuleSet Name="MyRules" Description="A bunch of rules"> <Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer"> </Rules> <Rules AnalyzerId="Beta.Analyzer" RuleNamespace="Alpha.Analyzer"> </Rules> </RuleSet> Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value) End Sub End Class End Namespace
mmitche/roslyn
src/VisualStudio/Core/Test/SolutionExplorer/RuleSetDocumentExtensionsTests.vb
Visual Basic
apache-2.0
7,601
'------------------------------------------------------------------------------ ' <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 ParamRepBalanceComprobacionXarea '''<summary> '''Control ImageButton2. '''</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 ImageButton2 As Global.System.Web.UI.WebControls.ImageButton '''<summary> '''Control RadDatePicker1. '''</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 RadDatePicker1 As Global.Telerik.Web.UI.RadDatePicker '''<summary> '''Control RadComboBox1. '''</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 RadComboBox1 As Global.Telerik.Web.UI.RadComboBox '''<summary> '''Control RadioButtonList1. '''</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 RadioButtonList1 As Global.System.Web.UI.WebControls.RadioButtonList '''<summary> '''Control RadioButtonList2. '''</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 RadioButtonList2 As Global.System.Web.UI.WebControls.RadioButtonList '''<summary> '''Control ImageButton1. '''</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 ImageButton1 As Global.System.Web.UI.WebControls.ImageButton '''<summary> '''Control odsProyecto. '''</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 odsProyecto As Global.System.Web.UI.WebControls.ObjectDataSource '''<summary> '''Control RadAjaxLoadingPanel1. '''</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 RadAjaxLoadingPanel1 As Global.Telerik.Web.UI.RadAjaxLoadingPanel '''<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/Contabilidad/Formularios/ParamRepBalanceComprobacionXarea.aspx.designer.vb
Visual Basic
mit
3,636
Public Class MathOfQuiz ' Create a Random object called randomizer ' to generate random numbers. Private randomizer As New Random() ' These integer variables store the numbers ' for the addition problem. Private addend1 As Integer Private addend2 As Integer ' These integer variables store the numbers ' for the subtraction problem. Private minuend As Integer Private subtrahend As Integer ' These integer variables store the numbers ' for the multiplication problem. Private multiplicand As Integer Private multiplier As Integer ' These integer variables store the numbers ' for the division problem. Private dividend As Integer Private divisor As Integer ' This integer variable keeps track of the ' remaining time. Private timeLeft As Integer ''' <summary> ''' Call the StartTheQuiz() method and enable ''' the Start button. ''' </summary> Private Sub startButton_Click(sender As Object, e As EventArgs) Handles startButton.Click StartTheQuiz() startButton.Enabled = False End Sub ''' <summary> ''' Start the quiz by filling in all of the problem ''' values and starting the timer. ''' </summary> Public Sub StartTheQuiz() ' Fill in the addition problem. ' Generate two random numbers to add. ' Store the values in the variables 'addend1' and 'addend2'. addend1 = randomizer.[Next](51) addend2 = randomizer.[Next](51) ' Convert the two randomly generated numbers ' into strings so that they can be displayed ' in the label controls. plusLeftLabel.Text = addend1.ToString() plusRightLabel.Text = addend2.ToString() ' 'sum' is the name of the NumericUpDown control. ' This step makes sure its value is zero before ' adding any values to it. sum.Value = 0 ' Fill in the subtraction problem. minuend = randomizer.[Next](1, 101) subtrahend = randomizer.[Next](1, minuend) minusLeftLabel.Text = minuend.ToString() minusRightLabel.Text = subtrahend.ToString() difference.Value = 0 ' Fill in the multiplication problem. multiplicand = randomizer.[Next](2, 11) multiplier = randomizer.[Next](2, 11) timesLeftLabel.Text = multiplicand.ToString() timesRightLabel.Text = multiplier.ToString() product.Value = 0 ' Fill in the division problem. divisor = randomizer.[Next](2, 11) Dim temporaryQuotient As Integer = randomizer.[Next](2, 11) dividend = divisor * temporaryQuotient dividedLeftLabel.Text = dividend.ToString() dividedRightLabel.Text = divisor.ToString() quotient.Value = 0 ' Start the timer. timeLeft = 30 timeLabel.Text = "30 seconds" timer1.Start() End Sub Private Sub timer1_Tick(sender As Object, e As EventArgs) Handles timer1.Tick If CheckTheAnswer() Then ' If CheckTheAnswer() returns true, then the user ' got the answer right. Stop the timer ' and show a MessageBox. timer1.[Stop]() MessageBox.Show("You got all the answers right!", "Congratulations!") startButton.Enabled = True ElseIf timeLeft > 0 Then ' If CheckTheAnswer() return false, keep counting ' down. Decrease the time left by one second and ' display the new time left by updating the ' Time Left label. timeLeft -= 1 timeLabel.Text = timeLeft & " seconds" Else ' If the user ran out of time, stop the timer, show ' a MessageBox, and fill in the answers. timer1.[Stop]() timeLabel.Text = "Time's up!" MessageBox.Show("You didn't finish in time.", "Sorry!") sum.Value = addend1 + addend2 difference.Value = minuend - subtrahend product.Value = multiplicand * multiplier quotient.Value = dividend \ divisor startButton.Enabled = True End If End Sub ''' <summary> ''' Check the answers to see if the user got everything right. ''' </summary> ''' <returns>True if the answers are correct, false otherwise.</returns> Private Function CheckTheAnswer() As Boolean If (addend1 + addend2 = sum.Value) AndAlso (minuend - subtrahend = difference.Value) AndAlso (multiplicand * multiplier = product.Value) AndAlso (dividend \ divisor = quotient.Value) Then Return True Else Return False End If End Function ''' <summary> ''' Modify the behavior of the NumericUpDown control ''' to make it easier to enter numeric values for ''' the quiz. ''' </summary> Private Sub answer_Enter(sender As Object, e As EventArgs) Handles sum.Enter, quotient.Enter, product.Enter, difference.Enter ' Select the whole answer in the NumericUpDown control. Dim answerBox As NumericUpDown = TryCast(sender, NumericUpDown) If answerBox IsNot Nothing Then Dim lengthOfAnswer As Integer = answerBox.Value.ToString().Length answerBox.[Select](0, lengthOfAnswer) End If End Sub Private Sub MathOfQuiz_Load(sender As Object, e As EventArgs) Handles MyBase.Load MsgBox("Discontinued.") Me.Close() End Sub End Class
jdc20181/BeffsBrowser
Archive/ArcadeArchive/MathQuizArchive.vb
Visual Basic
mit
5,533
Option Strict On Module Module1 Sub Main() End Sub End Module
winny-/CPS-240
Homework/HWK 6/HWK 6/Module1.vb
Visual Basic
mit
77
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Welcome 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.components = New System.ComponentModel.Container() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Welcome)) Me.AxWindowsMediaPlayer1 = New AxWMPLib.AxWindowsMediaPlayer() Me.PictureBox1 = New System.Windows.Forms.PictureBox() Me.HuraProgressBar1 = New Computer_Helper.HuraProgressBar() Me.Timer1 = New System.Windows.Forms.Timer(Me.components) CType(Me.AxWindowsMediaPlayer1, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'AxWindowsMediaPlayer1 ' Me.AxWindowsMediaPlayer1.Enabled = True Me.AxWindowsMediaPlayer1.Location = New System.Drawing.Point(254, 142) Me.AxWindowsMediaPlayer1.Name = "AxWindowsMediaPlayer1" Me.AxWindowsMediaPlayer1.OcxState = CType(resources.GetObject("AxWindowsMediaPlayer1.OcxState"), System.Windows.Forms.AxHost.State) Me.AxWindowsMediaPlayer1.Size = New System.Drawing.Size(10, 10) Me.AxWindowsMediaPlayer1.TabIndex = 0 Me.AxWindowsMediaPlayer1.Visible = False ' 'PictureBox1 ' Me.PictureBox1.BackgroundImage = Global.Computer_Helper.My.Resources.Resources.Computer_icon Me.PictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center Me.PictureBox1.Dock = System.Windows.Forms.DockStyle.Fill Me.PictureBox1.Location = New System.Drawing.Point(0, 0) Me.PictureBox1.Name = "PictureBox1" Me.PictureBox1.Size = New System.Drawing.Size(577, 323) Me.PictureBox1.TabIndex = 1 Me.PictureBox1.TabStop = False ' 'HuraProgressBar1 ' Me.HuraProgressBar1.BaseColour = System.Drawing.Color.FromArgb(CType(CType(255, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(255, Byte), Integer)) Me.HuraProgressBar1.BorderColour = System.Drawing.Color.FromArgb(CType(CType(190, Byte), Integer), CType(CType(190, Byte), Integer), CType(CType(190, Byte), Integer)) Me.HuraProgressBar1.FontColour = System.Drawing.Color.FromArgb(CType(CType(50, Byte), Integer), CType(CType(50, Byte), Integer), CType(CType(50, Byte), Integer)) Me.HuraProgressBar1.Location = New System.Drawing.Point(12, 296) Me.HuraProgressBar1.Maximum = 100 Me.HuraProgressBar1.Name = "HuraProgressBar1" Me.HuraProgressBar1.ProgressColour = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(170, Byte), Integer), CType(CType(220, Byte), Integer)) Me.HuraProgressBar1.SecondColour = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(170, Byte), Integer), CType(CType(250, Byte), Integer)) Me.HuraProgressBar1.Size = New System.Drawing.Size(553, 21) Me.HuraProgressBar1.TabIndex = 2 Me.HuraProgressBar1.Text = "HuraProgressBar1" Me.HuraProgressBar1.TwoColour = True Me.HuraProgressBar1.Value = 0 ' 'Timer1 ' Me.Timer1.Enabled = True ' 'Welcome ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(577, 323) Me.Controls.Add(Me.HuraProgressBar1) Me.Controls.Add(Me.PictureBox1) Me.Controls.Add(Me.AxWindowsMediaPlayer1) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.Name = "Welcome" Me.Opacity = 0.6R Me.Text = "Welcome" CType(Me.AxWindowsMediaPlayer1, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) End Sub Friend WithEvents AxWindowsMediaPlayer1 As AxWMPLib.AxWindowsMediaPlayer Friend WithEvents PictureBox1 As System.Windows.Forms.PictureBox Friend WithEvents HuraProgressBar1 As Computer_Helper.HuraProgressBar Friend WithEvents Timer1 As System.Windows.Forms.Timer End Class
MJGC-Jonathan/ComputerHelper
Computer Helper/Computer Helper/Welcome.Designer.vb
Visual Basic
mit
5,166
 Imports System.Threading.Thread Imports GrblPanel.GrblIF Imports System.Xml Partial Class GrblGui Public Class GrblOffsets Private _gui As GrblGui Private _wtgForGrbl As Boolean = False Private _collecting As Boolean = False Private _offsets As New List(Of String) Public Sub New(ByRef gui As GrblGui) _gui = gui AddHandler _gui.Connected, AddressOf GrblConnected End Sub Public Sub enableOffsets(ByVal action As Boolean) _gui.gbStatus.Enabled = action If action = True Then _gui.grblPort.addRcvDelegate(AddressOf _gui.showGrblOffsets) Else _gui.grblPort.deleteRcvDelegate(AddressOf _gui.showGrblOffsets) End If End Sub Public Sub ClearParams() ' empty the list of parameters _offsets.Clear() End Sub Public Sub AddOffset(ByVal data As String) ' Add a raw parameter line to the list _offsets.Add(data) End Sub Public Sub SaveOffsets() ' Save the Work and TLO offsets to a file of users' choice If Not _gui.sfdOffsets.ShowDialog() = System.Windows.Forms.DialogResult.OK Then Return End If Dim settings As XmlWriterSettings = New Xml.XmlWriterSettings settings.Indent = True settings.NewLineOnAttributes = True Dim writer As XmlWriter = XmlWriter.Create(_gui.sfdOffsets.FileName, settings) Dim ctls As Control() writer.WriteStartElement("WorkOffsets") For Each id As String In {"G54", "G55", "G56", "G57", "G58", "G59"} writer.WriteStartElement(id) For Each axis As String In {"X", "Y", "Z"} ctls = _gui.tpOffsets.Controls.Find("tbOffsets" + id + axis, True) writer.WriteAttributeString(axis, ctls(0).Text) Next writer.WriteEndElement() ' End an offset Next ' Do TLO as special writer.WriteStartElement("G43") ctls = _gui.tpOffsets.Controls.Find("tbOffsetsG43Z", True) writer.WriteAttributeString("Z", ctls(0).Text) writer.WriteEndElement() writer.WriteEndElement() ' End WorkOffsets writer.Close() End Sub Public Sub LoadOffsets() ' Load Work and TLO Offsets ' This lets the user double click on values for which there is a fixture etc. for quick set up If Not _gui.ofdOffsets.ShowDialog() = System.Windows.Forms.DialogResult.OK Then Return End If Dim reader As Xml.XmlReader = XmlReader.Create(_gui.ofdOffsets.FileName) Dim ctls As Control() While reader.Read Select Case reader.NodeType Case XmlNodeType.Element If reader.HasAttributes Then ' This finds only the nodes we need Dim offsetName As String = reader.Name While reader.MoveToNextAttribute ctls = _gui.tpOffsets.Controls.Find("tbOffsets" + offsetName + reader.Name, True) ctls(0).Text = reader.Value End While End If End Select End While End Sub Property OffsetsWtgForGrbl As Boolean ' Used to enable watch for $ parameters Get Return _wtgForGrbl End Get Set(value As Boolean) _wtgForGrbl = value End Set End Property Property CollectingOffsets As Boolean ' True is we are collecting params from response stream Get Return _collecting End Get Set(value As Boolean) _collecting = value End Set End Property ReadOnly Property Offsets As List(Of String) Get Return _offsets End Get End Property Private Sub GrblConnected() ' Handles GrblGui.Connected Event ' We are now connected so ask for Offset data OffsetsWtgForGrbl = True gcode.sendGCodeLine("$#") End Sub End Class Private Sub btnOffsetsZero_Click(sender As Object, e As EventArgs) Handles btnOffsetsG43Zero.Click, btnOffsetsG55Zero.Click, btnOffsetsG56Zero.Click, btnOffsetsG57Zero.Click, btnOffsetsG58Zero.Click, btnOffsetsG59Zero.Click, btnOffsetsG28Set.Click, btnOffsetsG30Set.Click, btnOffsetsG54Zero.Click Dim btn As Button = sender Dim index As String = "" Dim tag As String = DirectCast(btn.Tag, String) tag = tag.Substring(0, 3) ' Set the Offset to zero If tag.StartsWith("G5") Then Select Case tag Case "G54" index = "P1" Case "G55" index = "P2" Case "G56" index = "P3" Case "G57" index = "P4" Case "G58" index = "P5" Case "G59" index = "P6" End Select gcode.sendGCodeLine("G10 L2 " + index + " X0 Y0 Z0") ElseIf tag.StartsWith("G28") Or tag.StartsWith("G30") Then ' set G28 or G30 to current Machine Position gcode.sendGCodeLine(tag.Substring(0, 3) + ".1") ElseIf tag.StartsWith("G43") Then gcode.sendGCodeLine("G43.1 Z0") End If ' Get new values btnOffsetsRetrieve_Click(Nothing, Nothing) End Sub Private Sub tbOffsets_DoubleClick(sender As Object, e As EventArgs) Handles tbOffsetsG43Z.DoubleClick, tbOffsetsG54X.DoubleClick, tbOffsetsG54Y.DoubleClick, tbOffsetsG54Z.DoubleClick, tbOffsetsG55X.DoubleClick, tbOffsetsG55Y.DoubleClick, tbOffsetsG55Z.DoubleClick, tbOffsetsG56X.DoubleClick, tbOffsetsG56Y.DoubleClick, tbOffsetsG56Z.DoubleClick, tbOffsetsG57X.DoubleClick, tbOffsetsG57Y.DoubleClick, tbOffsetsG57Z.DoubleClick, tbOffsetsG58X.DoubleClick, tbOffsetsG58Y.DoubleClick, tbOffsetsG58Z.DoubleClick, tbOffsetsG59X.DoubleClick, tbOffsetsG59Y.DoubleClick, tbOffsetsG59Z.DoubleClick ' Set a specific offset and axis to entered value Dim tb As TextBox = sender Dim index As String = "" Dim tag As String = DirectCast(tb.Tag, String) SendOffsets(tag, tb.Text) End Sub ''' <summary> ''' Send Offset info to Grbl ''' </summary> ''' <param name="tag"></param> ''' <param name="value"></param> Public Sub SendOffsets(tag As String, value As String) ' also called from GrblGui ProcessKeyCommand for Enter key processing Dim index As String = "" Dim axis As String = tag(3) If tag.Contains("G5") Then Select Case tag.Substring(0, 3) ' Get the offset value Case "G54" index = "P1" Case "G55" index = "P2" Case "G56" index = "P3" Case "G57" index = "P4" Case "G58" index = "P5" Case "G59" index = "P6" End Select gcode.sendGCodeLine("G10 L2 " + index + " " + axis + value) Sleep(400) ' Have to wait for EEProm write btnOffsetsRetrieve_Click(Nothing, Nothing) End If If tag.Contains("G43") Then gcode.sendGCodeLine("G43.1" + axis + value) Sleep(400) ' Have to wait for EEProm write btnOffsetsRetrieve_Click(Nothing, Nothing) End If End Sub ''' <summary> ''' Set an offset to current machine coordinates ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> Private Sub btnSetOffset_Click(sender As Object, e As EventArgs) Handles btnSetOffsetG54.Click, btnSetOffsetG55.Click, btnSetOffsetG56.Click, btnSetOffsetG57.Click, btnSetOffsetG58.Click, btnSetOffsetG59.Click Dim btn As Button = sender Dim index As String = "" Dim tag As String = DirectCast(btn.Tag, String) Dim XValue As String = tbOffSetsMachX.Text.ToString Dim YValue As String = tbOffSetsMachY.Text.ToString Dim ZValue As String = tbOffSetsMachZ.Text.ToString Select Case tag.Substring(0, 3) ' Get the offset value Case "G54" index = "P1" Case "G55" index = "P2" Case "G56" index = "P3" Case "G57" index = "P4" Case "G58" index = "P5" Case "G59" index = "P6" End Select gcode.sendGCodeLine("G10 L2 " + index + " " + "X" + XValue + "Y" + YValue + "Z" + ZValue) ' Get new values btnOffsetsRetrieve_Click(Nothing, Nothing) End Sub Private Sub btnOffsetsRetrieve_Click(sender As Object, e As EventArgs) Handles btnOffsetsRetrieve.Click, btnSettingsRetrieveLocations.Click ' Ask Grbl to send us the present offsets offsets.OffsetsWtgForGrbl = True offsets.ClearParams() gcode.sendGCodeLine("$#") End Sub Public Sub showGrblOffsets(ByVal data As String) If data.Length < 3 Then Return End If ' Extract anything with a [<n> into array If offsets.OffsetsWtgForGrbl Then If data(0) = "[" And (data(1) = "G" Or data(1) = "T") Then offsets.AddOffset(data) offsets.CollectingOffsets = True ElseIf offsets.CollectingOffsets And data(0) <> "[" Then ' we are done collecting parameters, time to display them offsets.OffsetsWtgForGrbl = False offsets.CollectingOffsets = False ShowOffsets() End If End If End Sub Public Sub ShowOffsets() ' TODO move into offsets class, needs ref to grblgui object ' Populate the Offsets display Dim label As String Dim axes As String() Dim tb As Control() For Each line In offsets.Offsets line = line.Remove(0, 1) ' remove the leading [ line = line.Remove(line.Length - 3, 3) ' remove the trailing "] <vbLf>" label = line.Substring(0, 3) line = line.Remove(0, 4) ' finally remove the label: axes = line.Split(",") Select Case label Case "G28", "G30" Dim i As Integer = 0 For Each axi In {"X", "Y", "Z"} tb = tabPgSettings.Controls.Find("tbOffsets" + label + axi, True) tb(0).Text = axes(i) i += 1 Next Case "G54", "G55", "G56", "G57", "G58", "G59" Dim i As Integer = 0 For Each axi In {"X", "Y", "Z"} tb = tpOffsets.Controls.Find("tbOffsets" + label + axi, True) tb(0).Text = axes(i) i += 1 Next Case "TLO" tb = tpOffsets.Controls.Find("tbOffsets" + "G43" + "Z", True) tb(0).Text = axes(0) End Select Next End Sub Private Sub btnOffsetsSave_Click(sender As Object, e As EventArgs) Handles btnOffsetsSave.Click ' Save Work and TLO offsets offsets.SaveOffsets() End Sub Private Sub btnOffsetsLoad_Click(sender As Object, e As EventArgs) Handles btnOffsetsLoad.Click ' Load offsets from user specified file offsets.LoadOffsets() End Sub End Class
gerritv/Grbl-Panel
Grbl-Panel/GrblOffsets.vb
Visual Basic
mit
12,938
#Region "License" ' The MIT License (MIT) ' ' Copyright (c) 2018 Richard L King (TradeWright Software Systems) ' ' 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. #End Region Public Class RealtimeBarEventArgs Inherits AbstractEventArgsWithTimestamp Public Property Bar As Bar Public Property RequestId As Integer Public Sub New(timestamp As DateTime, reqId As Integer, bar As TradeWright.IBAPI.Bar) MyBase.New() Me._Timestamp = timestamp Me.RequestId = reqId Me.Bar = bar End Sub End Class
tradewright/tradewright-twsapi
src/IBApi/EventArgs/RealtimeBarEventArgs.vb
Visual Basic
mit
1,557
Imports System Imports Csla Namespace TestProject.Business Public Partial Class DocTypeList #Region " OnDeserialized actions " ' ''' <summary> ' ''' This method is called on a newly deserialized object ' ''' after deserialization is complete. ' ''' </summary> ' Protected Overrides Sub OnDeserialized() ' MyBase.OnDeserialized() ' add your custom OnDeserialized actions here. ' End Sub #End Region #Region " Custom Object Authorization " ' Private Shared Sub AddObjectAuthorizationRulesExtend() ' Throw New NotImplementedException() ' End Sub #End Region #Region " Implementation of DataPortal Hooks " ' Private Sub OnFetchPre(args As DataPortalHookArgs) ' Throw New NotImplementedException() ' End Sub ' Private Sub OnFetchPost(args As DataPortalHookArgs) ' Throw New NotImplementedException() ' End Sub #End Region End Class End Namespace
CslaGenFork/CslaGenFork
trunk/CoverageTest/TestProject/VB/TestProject.Business/DocTypeList.vb
Visual Basic
mit
1,110
' 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 Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Module VisualBasicCodeGenerationHelpers Friend Sub AddAccessibilityModifiers( accessibility As Accessibility, tokens As ArrayBuilder(Of SyntaxToken), destination As CodeGenerationDestination, options As CodeGenerationOptions, nonStructureAccessibility As Accessibility) options = If(options, CodeGenerationOptions.Default) If Not options.GenerateDefaultAccessibility Then If destination = CodeGenerationDestination.StructType AndAlso accessibility = Accessibility.Public Then Return End If If destination <> CodeGenerationDestination.StructType AndAlso accessibility = nonStructureAccessibility Then Return End If End If Select Case accessibility Case Accessibility.Public tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) Case Accessibility.Protected tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.Private tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) Case Accessibility.Internal tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) Case Accessibility.ProtectedAndInternal tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.ProtectedOrInternal tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) End Select End Sub Public Function InsertAtIndex(members As SyntaxList(Of StatementSyntax), member As StatementSyntax, index As Integer) As SyntaxList(Of StatementSyntax) Dim result = New List(Of StatementSyntax)(members) ' then insert the new member. result.Insert(index, member) Return SyntaxFactory.List(result) End Function Public Function GenerateImplementsClause(explicitInterfaceOpt As ISymbol) As ImplementsClauseSyntax If explicitInterfaceOpt IsNot Nothing AndAlso explicitInterfaceOpt.ContainingType IsNot Nothing Then Dim type = explicitInterfaceOpt.ContainingType.GenerateTypeSyntax() If TypeOf type Is NameSyntax Then Return SyntaxFactory.ImplementsClause( interfaceMembers:=SyntaxFactory.SingletonSeparatedList( SyntaxFactory.QualifiedName( DirectCast(type, NameSyntax), explicitInterfaceOpt.Name.ToIdentifierName()))) End If End If Return Nothing End Function Public Function EnsureLastElasticTrivia(Of T As StatementSyntax)(statement As T) As T Dim lastToken = statement.GetLastToken(includeZeroWidth:=True) If lastToken.TrailingTrivia.Any(Function(trivia) trivia.IsElastic()) Then Return statement End If Return statement.WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker) End Function Public Function FirstMember(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.FirstOrDefault() End Function Public Function FirstMethod(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.LastOrDefault(Function(m) TypeOf m Is MethodBlockBaseSyntax OrElse TypeOf m Is MethodStatementSyntax) End Function Public Function LastField(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.LastOrDefault(Function(m) m.Kind = SyntaxKind.FieldDeclaration) End Function Public Function LastConstructor(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.LastOrDefault(Function(m) m.Kind = SyntaxKind.ConstructorBlock OrElse m.Kind = SyntaxKind.SubNewStatement) End Function Public Function LastMethod(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.LastOrDefault(Function(m) TypeOf m Is MethodBlockBaseSyntax OrElse TypeOf m Is MethodStatementSyntax) End Function Public Function LastOperator(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration Return members.LastOrDefault(Function(m) m.Kind = SyntaxKind.OperatorBlock OrElse m.Kind = SyntaxKind.OperatorStatement) End Function Private Function AfterDeclaration(Of TDeclaration As SyntaxNode)( declarationList As SyntaxList(Of TDeclaration), options As CodeGenerationOptions, [next] As Func(Of SyntaxList(Of TDeclaration), TDeclaration)) As Func(Of SyntaxList(Of TDeclaration), TDeclaration) options = If(options, CodeGenerationOptions.Default) Return Function(list) If [next] IsNot Nothing Then Return [next](list) End If Return Nothing End Function End Function Private Function BeforeDeclaration(Of TDeclaration As SyntaxNode)( declarationList As SyntaxList(Of TDeclaration), options As CodeGenerationOptions, [next] As Func(Of SyntaxList(Of TDeclaration), TDeclaration)) As Func(Of SyntaxList(Of TDeclaration), TDeclaration) options = If(options, CodeGenerationOptions.Default) Return Function(list) If [next] IsNot Nothing Then Return [next](list) End If Return Nothing End Function End Function Public Function Insert(Of TDeclaration As SyntaxNode)( declarationList As SyntaxList(Of TDeclaration), declaration As TDeclaration, options As CodeGenerationOptions, availableIndices As IList(Of Boolean), Optional after As Func(Of SyntaxList(Of TDeclaration), TDeclaration) = Nothing, Optional before As Func(Of SyntaxList(Of TDeclaration), TDeclaration) = Nothing) As SyntaxList(Of TDeclaration) after = AfterDeclaration(declarationList, options, after) before = BeforeDeclaration(declarationList, options, before) Dim index = GetInsertionIndex( declarationList, declaration, options, availableIndices, VisualBasicDeclarationComparer.WithoutNamesInstance, VisualBasicDeclarationComparer.WithNamesInstance, after, before) If availableIndices IsNot Nothing Then availableIndices.Insert(index, True) End If Return declarationList.Insert(index, declaration) End Function Public Function GetDestination(destination As SyntaxNode) As CodeGenerationDestination If destination IsNot Nothing Then Select Case destination.Kind Case SyntaxKind.ClassBlock Return CodeGenerationDestination.ClassType Case SyntaxKind.CompilationUnit Return CodeGenerationDestination.CompilationUnit Case SyntaxKind.EnumBlock Return CodeGenerationDestination.EnumType Case SyntaxKind.InterfaceBlock Return CodeGenerationDestination.InterfaceType Case SyntaxKind.ModuleBlock Return CodeGenerationDestination.ModuleType Case SyntaxKind.NamespaceBlock Return CodeGenerationDestination.Namespace Case SyntaxKind.StructureBlock Return CodeGenerationDestination.StructType Case Else Return CodeGenerationDestination.Unspecified End Select End If Return CodeGenerationDestination.Unspecified End Function Public Function ConditionallyAddDocumentationCommentTo(Of TSyntaxNode As SyntaxNode)( node As TSyntaxNode, symbol As ISymbol, options As CodeGenerationOptions, Optional cancellationToken As CancellationToken = Nothing) As TSyntaxNode If Not options.GenerateDocumentationComments OrElse node.GetLeadingTrivia().Any(Function(t) t.IsKind(SyntaxKind.DocumentationCommentTrivia)) Then Return node End If Dim comment As String = Nothing Dim result = If(TryGetDocumentationComment(symbol, "'''", comment, cancellationToken), node.WithPrependedLeadingTrivia(SyntaxFactory.ParseLeadingTrivia(comment)) _ .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker), node) Return result End Function End Module End Namespace
reaction1989/roslyn
src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicCodeGenerationHelpers.vb
Visual Basic
apache-2.0
10,130
Imports System.ComponentModel Imports DevExpress.XtraGrid Imports DevExpress.XtraGrid.Views.Base Imports DevExpress.XtraGrid.Columns Imports DevExpress.XtraGrid.Views.Grid Imports DevExpress.XtraGrid.Views.Grid.ViewInfo Imports bv.winclient.BasePanel Imports bv.common.Resources Public Class BasePagedXtraListForm Inherits BasePagedListForm #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) 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. Friend WithEvents PagedXtraGrid1 As bv.common.win.PagedXtraGrid Friend WithEvents cmdSearch1 As DevExpress.XtraEditors.SimpleButton Friend WithEvents cmdNew1 As DevExpress.XtraEditors.SimpleButton Friend WithEvents cmdEdit1 As DevExpress.XtraEditors.SimpleButton Friend WithEvents cmdDelete1 As DevExpress.XtraEditors.SimpleButton Friend WithEvents cmdClose1 As DevExpress.XtraEditors.SimpleButton Friend WithEvents cmdRefresh1 As DevExpress.XtraEditors.SimpleButton '<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(BasePagedXtraListForm)) Dim DefaultGridStyle1 As bv.common.win.DefaultGridStyle = New bv.common.win.DefaultGridStyle Me.cmdSearch1 = New DevExpress.XtraEditors.SimpleButton Me.cmdNew1 = New DevExpress.XtraEditors.SimpleButton Me.cmdEdit1 = New DevExpress.XtraEditors.SimpleButton Me.cmdDelete1 = New DevExpress.XtraEditors.SimpleButton Me.PagedXtraGrid1 = New bv.common.win.PagedXtraGrid Me.cmdClose1 = New DevExpress.XtraEditors.SimpleButton Me.cmdRefresh1 = New DevExpress.XtraEditors.SimpleButton CType(Me.PagedXtraGrid1, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.PagedXtraGrid1.Grid, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'cmdSearch1 ' Me.cmdSearch1.AccessibleDescription = Nothing Me.cmdSearch1.AccessibleName = Nothing resources.ApplyResources(Me.cmdSearch1, "cmdSearch1") Me.cmdSearch1.BackgroundImage = Nothing Me.cmdSearch1.Image = Global.bv.common.win.My.Resources.Resources.Show_Hide_Search Me.cmdSearch1.Name = "cmdSearch1" ' 'cmdNew1 ' Me.cmdNew1.AccessibleDescription = Nothing Me.cmdNew1.AccessibleName = Nothing resources.ApplyResources(Me.cmdNew1, "cmdNew1") Me.cmdNew1.BackgroundImage = Nothing Me.cmdNew1.Image = Global.bv.common.win.My.Resources.Resources.add Me.cmdNew1.Name = "cmdNew1" ' 'cmdEdit1 ' Me.cmdEdit1.AccessibleDescription = Nothing Me.cmdEdit1.AccessibleName = Nothing resources.ApplyResources(Me.cmdEdit1, "cmdEdit1") Me.cmdEdit1.BackgroundImage = Nothing Me.cmdEdit1.Image = Global.bv.common.win.My.Resources.Resources.edit Me.cmdEdit1.Name = "cmdEdit1" ' 'cmdDelete1 ' Me.cmdDelete1.AccessibleDescription = Nothing Me.cmdDelete1.AccessibleName = Nothing resources.ApplyResources(Me.cmdDelete1, "cmdDelete1") Me.cmdDelete1.BackgroundImage = Nothing Me.cmdDelete1.Image = Global.bv.common.win.My.Resources.Resources.Delete_Remove Me.cmdDelete1.Name = "cmdDelete1" ' 'PagedXtraGrid1 ' Me.PagedXtraGrid1.AccessibleDescription = Nothing Me.PagedXtraGrid1.AccessibleName = Nothing resources.ApplyResources(Me.PagedXtraGrid1, "PagedXtraGrid1") Me.PagedXtraGrid1.Appearance.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!) Me.PagedXtraGrid1.Appearance.Options.UseFont = True Me.PagedXtraGrid1.BackgroundImage = Nothing Me.PagedXtraGrid1.CurrentPage = 1 ' ' ' Me.PagedXtraGrid1.Grid.AccessibleDescription = Nothing Me.PagedXtraGrid1.Grid.AccessibleName = Nothing Me.PagedXtraGrid1.Grid.Anchor = CType(resources.GetObject("PagedXtraGrid1.Grid.Anchor"), System.Windows.Forms.AnchorStyles) Me.PagedXtraGrid1.Grid.BackgroundImage = Nothing Me.PagedXtraGrid1.Grid.BackgroundImageLayout = CType(resources.GetObject("PagedXtraGrid1.Grid.BackgroundImageLayout"), System.Windows.Forms.ImageLayout) Me.PagedXtraGrid1.Grid.DataMember = resources.GetString("PagedXtraGrid1.Grid.DataMember") Me.PagedXtraGrid1.Grid.Dock = CType(resources.GetObject("PagedXtraGrid1.Grid.Dock"), System.Windows.Forms.DockStyle) Me.PagedXtraGrid1.Grid.EmbeddedNavigator.AccessibleDescription = Nothing Me.PagedXtraGrid1.Grid.EmbeddedNavigator.AccessibleName = Nothing Me.PagedXtraGrid1.Grid.EmbeddedNavigator.AllowHtmlTextInToolTip = CType(resources.GetObject("PagedXtraGrid1.Grid.EmbeddedNavigator.AllowHtmlTextInToolTip"), DevExpress.Utils.DefaultBoolean) Me.PagedXtraGrid1.Grid.EmbeddedNavigator.Anchor = CType(resources.GetObject("PagedXtraGrid1.Grid.EmbeddedNavigator.Anchor"), System.Windows.Forms.AnchorStyles) Me.PagedXtraGrid1.Grid.EmbeddedNavigator.BackgroundImage = Nothing Me.PagedXtraGrid1.Grid.EmbeddedNavigator.BackgroundImageLayout = CType(resources.GetObject("PagedXtraGrid1.Grid.EmbeddedNavigator.BackgroundImageLayout"), System.Windows.Forms.ImageLayout) Me.PagedXtraGrid1.Grid.EmbeddedNavigator.ImeMode = CType(resources.GetObject("PagedXtraGrid1.Grid.EmbeddedNavigator.ImeMode"), System.Windows.Forms.ImeMode) Me.PagedXtraGrid1.Grid.EmbeddedNavigator.TextLocation = CType(resources.GetObject("PagedXtraGrid1.Grid.EmbeddedNavigator.TextLocation"), DevExpress.XtraEditors.NavigatorButtonsTextLocation) Me.PagedXtraGrid1.Grid.EmbeddedNavigator.ToolTip = resources.GetString("PagedXtraGrid1.Grid.EmbeddedNavigator.ToolTip") Me.PagedXtraGrid1.Grid.EmbeddedNavigator.ToolTipIconType = CType(resources.GetObject("PagedXtraGrid1.Grid.EmbeddedNavigator.ToolTipIconType"), DevExpress.Utils.ToolTipIconType) Me.PagedXtraGrid1.Grid.EmbeddedNavigator.ToolTipTitle = resources.GetString("PagedXtraGrid1.Grid.EmbeddedNavigator.ToolTipTitle") Me.PagedXtraGrid1.Grid.Font = Nothing Me.PagedXtraGrid1.Grid.ImeMode = CType(resources.GetObject("PagedXtraGrid1.Grid.ImeMode"), System.Windows.Forms.ImeMode) Me.PagedXtraGrid1.Grid.Location = CType(resources.GetObject("PagedXtraGrid1.Grid.Location"), System.Drawing.Point) Me.PagedXtraGrid1.Grid.MainView = Me.PagedXtraGrid1.MainView Me.PagedXtraGrid1.Grid.Name = "m_grid" Me.PagedXtraGrid1.Grid.RightToLeft = CType(resources.GetObject("PagedXtraGrid1.Grid.RightToLeft"), System.Windows.Forms.RightToLeft) Me.PagedXtraGrid1.Grid.Size = CType(resources.GetObject("PagedXtraGrid1.Grid.Size"), System.Drawing.Size) Me.PagedXtraGrid1.Grid.TabIndex = CType(resources.GetObject("PagedXtraGrid1.Grid.TabIndex"), Integer) Me.PagedXtraGrid1.Grid.ViewCollection.AddRange(New DevExpress.XtraGrid.Views.Base.BaseView() {Me.PagedXtraGrid1.MainView}) Me.PagedXtraGrid1.GridStyle = DefaultGridStyle1 Me.PagedXtraGrid1.Name = "PagedXtraGrid1" Me.PagedXtraGrid1.PageCount = 0 Me.PagedXtraGrid1.PageSize = 50 Me.PagedXtraGrid1.ReadOnly = True Me.PagedXtraGrid1.SearchControl = "bv.common.win.XtraSearchPanel" Me.PagedXtraGrid1.SearchPanelDocStyle = System.Windows.Forms.DockStyle.Top Me.PagedXtraGrid1.SearchParameters = Nothing Me.PagedXtraGrid1.SortCondition = Nothing Me.PagedXtraGrid1.StaticFilterCondition = Nothing ' 'cmdClose1 ' Me.cmdClose1.AccessibleDescription = Nothing Me.cmdClose1.AccessibleName = Nothing resources.ApplyResources(Me.cmdClose1, "cmdClose1") Me.cmdClose1.BackgroundImage = Nothing Me.cmdClose1.Image = Global.bv.common.win.My.Resources.Resources.Close Me.cmdClose1.Name = "cmdClose1" ' 'cmdRefresh1 ' Me.cmdRefresh1.AccessibleDescription = Nothing Me.cmdRefresh1.AccessibleName = Nothing resources.ApplyResources(Me.cmdRefresh1, "cmdRefresh1") Me.cmdRefresh1.BackgroundImage = Nothing Me.cmdRefresh1.Image = Global.bv.common.win.My.Resources.Resources.refresh Me.cmdRefresh1.Name = "cmdRefresh1" ' 'BasePagedXtraListForm ' Me.AccessibleDescription = Nothing Me.AccessibleName = Nothing resources.ApplyResources(Me, "$this") Me.BackgroundImage = Nothing Me.Controls.Add(Me.cmdRefresh1) Me.Controls.Add(Me.cmdClose1) Me.Controls.Add(Me.PagedXtraGrid1) Me.Controls.Add(Me.cmdSearch1) Me.Controls.Add(Me.cmdNew1) Me.Controls.Add(Me.cmdEdit1) Me.Controls.Add(Me.cmdDelete1) Me.Name = "BasePagedXtraListForm" Me.Sizable = True Me.Controls.SetChildIndex(Me.cmdDelete1, 0) Me.Controls.SetChildIndex(Me.cmdEdit1, 0) Me.Controls.SetChildIndex(Me.cmdNew1, 0) Me.Controls.SetChildIndex(Me.cmdSearch1, 0) Me.Controls.SetChildIndex(Me.PagedXtraGrid1, 0) Me.Controls.SetChildIndex(Me.cmdClose1, 0) Me.Controls.SetChildIndex(Me.cmdRefresh1, 0) CType(Me.PagedXtraGrid1.Grid, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.PagedXtraGrid1, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) End Sub #End Region #Region "BaseFormList overrides methods" Public Overrides Function Activate() As System.Windows.Forms.Control If (Not m_DataLoaded) Then If TypeOf Me Is ISearchable Then CType(Me, ISearchable).LoadSearchPanel() End If LoadData(Nothing) End If BringToFront() Return Me End Function Protected Overrides Sub InitButtons() cmdSearch = cmdSearch1 cmdSearch.Visible = Me.ShowSearchButton cmdEdit = cmdEdit1 cmdEdit.Visible = Me.ShowEditButton cmdNew = cmdNew1 cmdNew.Visible = Me.ShowNewButton cmdDelete = cmdDelete1 cmdDelete.Visible = Me.ShowDeleteButton cmdClose = cmdClose1 cmdRefresh = cmdRefresh1 If (Me.State And BusinessObjectState.SelectObject) <> 0 Then cmdEdit.Text = BvMessages.Get("btnSelect", "Select") cmdEdit1.Image = Global.bv.common.win.My.Resources.Resources.Select2 cmdEdit.Visible = True cmdDelete.Visible = False cmdNew.Visible = False 'ShowSearchButton = True 'ShowSearch = True Else cmdNew.Visible = cmdNew.Visible And Not BaseFormManager.ReadOnly cmdDelete.Visible = cmdDelete.Visible And Not BaseFormManager.ReadOnly If Not EditButtonText Is Nothing AndAlso Me.EditButtonText <> "" Then cmdEdit1.Text = EditButtonText End If End If If Not PermissionObject Is Nothing Then If Me.Permissions.CanInsert = False Then cmdNew.Enabled = False End If If Me.Permissions.CanDelete = False Then cmdDelete.Enabled = False End If If Me.Permissions.CanUpdate = False AndAlso (Me.State And BusinessObjectState.SelectObject) = 0 Then cmdEdit.Text = BvMessages.Get("btnView", "View") cmdEdit1.Image = Global.bv.common.win.My.Resources.Resources.View1 End If cmdNew.Visible = cmdNew.Visible AndAlso Permissions.GetButtonVisibility(DefaultButtonType.[New]) cmdDelete.Visible = cmdDelete.Visible AndAlso Permissions.GetButtonVisibility(DefaultButtonType.Delete) cmdEdit.Visible = cmdEdit.Visible AndAlso Permissions.GetButtonVisibility(DefaultButtonType.Edit) End If If cmdEdit.Visible And cmdEdit.Enabled Then cmdEdit.Select() ElseIf cmdNew.Visible AndAlso cmdNew.Enabled Then cmdNew.Select() ElseIf cmdSearch.Visible AndAlso cmdSearch.Enabled Then cmdSearch.Select() ElseIf cmdDelete.Visible AndAlso cmdDelete.Enabled Then cmdDelete.Select() Else Me.Select() End If End Sub Public Overrides Function GetSelectedRows() As DataRow() If Me.PagedXtraGrid1 Is Nothing OrElse Me.PagedXtraGrid1.Grid Is Nothing OrElse Me.PagedXtraGrid1.Grid.MainView Is Nothing Then Return Nothing Dim gv As GridView = CType(Me.PagedXtraGrid1.Grid.MainView, GridView) If gv Is Nothing Then Return Nothing If gv.GetSelectedRows() Is Nothing Then Return Nothing Dim selRowsInxexes As Integer() = gv.GetSelectedRows() If selRowsInxexes Is Nothing Then Return Nothing ' creating an empty list Dim Rows(selRowsInxexes.Length - 1) As DataRow ' adding selected rows to the list Dim I As Integer Dim k As Integer = 0 For I = 0 To selRowsInxexes.Length - 1 If (selRowsInxexes(I) >= 0) Then Rows(k) = (gv.GetDataRow(selRowsInxexes(I))) k += 1 End If Next If k = 0 Then Return Nothing Return Rows End Function Public Overrides Function GetDataset() As DataSet If PagedGrid Is Nothing Then Return Nothing 'Dim AdditionalFilter As String = "" 'If BaseSettings.ShowEmptyListOnSearch _ ' AndAlso (State And BusinessObjectState.SelectObject) = 0 _ ' AndAlso Me.ShowSearch = True _ ' AndAlso Utils.IsEmpty(PagedGrid.FilterCondition) _ ' AndAlso Utils.IsEmpty(PagedGrid.FromCondition) Then ' AdditionalFilter = "0 = 1" 'Me.KeyFieldName + " IS NULL " 'End If Dim RecordCount As Integer = 0 Dim ds As DataSet = Nothing If Not DbService Is Nothing Then If PagedGrid.SortCondition Is Nothing Then PagedGrid.SortCondition = PagedGrid.DefaultSortCondition End If ds = DbService.GetPagedList(PagedGrid.PageSize, PagedGrid.CurrentPage - 1, PagedGrid.FilterCondition, PagedGrid.FromCondition, PagedGrid.SortCondition, RecordCount) '+ AdditionalFilter Else Dim params() As Object params = New Object() { _ PagedGrid.PageSize, PagedGrid.CurrentPage - 1, PagedGrid.FilterCondition, PagedGrid.FromCondition, PagedGrid.SortCondition, RecordCount} Dim o As Object = ClassLoader.LoadClass(ObjectName + "_DB") Dim typeArray(5) As Type Dim m_listMethod As Reflection.MethodInfo = o.GetType().GetMethod("GetPagedList") o = m_listMethod.Invoke(o, params) If Not o Is Nothing Then ds = CType(o, DataSet) RecordCount = CInt(params(5)) End If End If If RecordCount < PagedGrid.PageSize Then If PagedGrid.CurrentPage > 1 Then PagedGrid.CurrentPage = 1 Return GetDataset() End If PagedGrid.PageCount = 0 Else PagedGrid.PageCount = (RecordCount + PagedGrid.PageSize - 1) \ PagedGrid.PageSize End If Return ds End Function #End Region #Region "Public properies" Public Overrides Property MultiSelect() As Boolean Get Return MyBase.MultiSelect End Get Set(ByVal Value As Boolean) MyBase.MultiSelect = Value CType(PagedXtraGrid1.Grid.MainView, GridView).OptionsSelection.MultiSelect = m_MultiSelect End Set End Property Public Overrides ReadOnly Property Grid() As Object Get If PagedXtraGrid1 Is Nothing Then Return Nothing Return PagedXtraGrid1.DataGrid End Get End Property <DesignerSerializationVisibility(DesignerSerializationVisibility.Content), Localizable(True)> _ Public ReadOnly Property Columns() As GridColumnCollection Get If PagedXtraGrid1 Is Nothing Then Return Nothing Return PagedXtraGrid1.Columns End Get End Property Private m_ContextMenu As ContextMenu Public Property GridContextMenu() As ContextMenu Get Return m_ContextMenu End Get Set(ByVal Value As ContextMenu) m_ContextMenu = Value PagedXtraGrid1.DataGrid.ContextMenu = ContextMenu End Set End Property Public ReadOnly Property DataGrid() As PagedXtraGrid Get Return Me.PagedXtraGrid1 End Get End Property #End Region #Region "Public methods" #End Region #Region "Protected methods" Public Overrides ReadOnly Property PagedGrid() As BasePagedDataGrid Get Return Me.PagedXtraGrid1 End Get End Property 'Private m_Repository As DevExpress.XtraEditors.Repository.PersistentRepository = New DevExpress.XtraEditors.Repository.PersistentRepository '<DesignerSerializationVisibility(DesignerSerializationVisibility.Content)> _ 'Public Property ExternalRepository() As DevExpress.XtraEditors.Repository.PersistentRepository ' Get ' Return m_Repository ' End Get ' Set(ByVal Value As DevExpress.XtraEditors.Repository.PersistentRepository) ' 'Me.Grid.ExternalRepository = Value ' If Not Value Is Nothing Then ' For i As Integer = 0 To Value.Items.Count ' Dim item As New DevExpress.XtraEditors.Repository.RepositoryItem ' m_Repository.Items.Add(Value.Items(i)) ' Next ' End If ' 'PagedXtraGrid1.Grid.ExternalRepository = m_Repository ' End Set 'End Property '<DesignerSerializationVisibility(DesignerSerializationVisibility.Content)> _ 'Public Property ExternalRepository() As DevExpress.XtraEditors.Repository.PersistentRepository ' Get ' Return Nothing 'PagedXtraGrid1.ExternalRepository ' End Get ' Set(ByVal Value As DevExpress.XtraEditors.Repository.PersistentRepository) ' PagedXtraGrid1.ExternalRepository = Value ' End Set 'End Property '<DesignerSerializationVisibility(DesignerSerializationVisibility.Content), Localizable(True)> _ 'Public ReadOnly Property RepositoryItems() As DevExpress.XtraEditors.Repository.RepositoryItemCollection ' Get ' If PagedXtraGrid1 Is Nothing Then Return Nothing ' Return PagedXtraGrid1.RepositoryItems ' End Get 'End Property #End Region #Region "Private methods" #End Region Protected Overrides Sub ResizeForm() If Not Visible Then Return If Me.DesignMode Then Me.PagedXtraGrid1.Width = Me.Width Me.PagedXtraGrid1.Height = Me.Height - Me.PagedXtraGrid1.Top - cmdClose1.Height - 16 End If ArrangeButtons(Me.Height - cmdClose1.Height - 8, "BottomButtons", cmdClose1.Height) ArrangeButtons(cmdDelete1.Top, "BottomButtons", cmdDelete1.Height) End Sub Private Sub BasePagedXtraListForm_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Resize ResizeForm() End Sub Protected Overrides Sub DefineBinding() MyBase.DefineBinding() Dim xgcGrid As DevExpress.XtraGrid.GridControl Dim xgvView As DevExpress.XtraGrid.Views.Grid.GridView xgcGrid = CType(Me.Grid, DevExpress.XtraGrid.GridControl) xgvView = CType(xgcGrid.FocusedView, DevExpress.XtraGrid.Views.Grid.GridView) xgvView.OptionsCustomization.BeginUpdate() xgvView.OptionsCustomization.AllowColumnMoving = False xgvView.OptionsCustomization.AllowColumnResizing = True xgvView.OptionsCustomization.AllowFilter = False xgvView.OptionsCustomization.AllowGroup = False xgvView.OptionsCustomization.AllowRowSizing = False xgvView.OptionsCustomization.AllowSort = True xgvView.OptionsCustomization.EndUpdate() 'For i As Integer = 0 To CType(CType(Grid, DevExpress.XtraGrid.GridControl).MainView, DevExpress.XtraGrid.Views.Grid.GridView).Columns.Count - 1 ' CType(CType(Grid, DevExpress.XtraGrid.GridControl).MainView, DevExpress.XtraGrid.Views.Grid.GridView).Columns(i).VisibleIndex = i 'Next End Sub Protected ReadOnly Property MainView() As DevExpress.XtraGrid.Views.Grid.GridView Get Return (Me.PagedXtraGrid1.MainGridView) End Get End Property Private Sub BasePagedXtraListForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim firstCol As DevExpress.XtraGrid.Columns.GridColumn firstCol = GetFirstVisibleAndSortableColumn() If Not firstCol Is Nothing Then PagedXtraGrid1.m_Sorting = True firstCol.SortIndex = 0 If Not Utils.IsEmpty(firstCol.FieldName) Then PagedXtraGrid1.SortCondition = String.Format("fn_{0}_SelectList.", Me.ObjectName) + firstCol.FieldName If firstCol.SortOrder = DevExpress.Data.ColumnSortOrder.Descending Then PagedXtraGrid1.SortCondition += " DESC" End If Else PagedXtraGrid1.SortCondition = Nothing End If PagedXtraGrid1.m_Sorting = False MainView.FocusedRowHandle = 0 End If End Sub Protected Overrides Function IsRowClicked(ByVal x As Integer, ByVal y As Integer) As Boolean If Not Grid Is Nothing Then Dim chi As New GridHitInfo() chi = MainView.CalcHitInfo(New System.Drawing.Point(x, y)) Return chi.InRow End If Return False End Function Public Function GetFirstVisibleAndSortableColumn() As DevExpress.XtraGrid.Columns.GridColumn Dim firstCol As GridColumn = Nothing Dim minVisibleIndex As Integer = 0 If Not DefaultSortColumn Is Nothing AndAlso DefaultSortColumn.VisibleIndex >= 0 Then Return DefaultSortColumn End If For i As Integer = 0 To Columns.Count - 1 If (firstCol Is Nothing AndAlso (Columns(i).VisibleIndex < 0 OrElse Columns(i).OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.False)) Then Continue For End If If (firstCol Is Nothing OrElse _ (Columns(i).VisibleIndex < firstCol.VisibleIndex AndAlso Columns(i).VisibleIndex >= 0)) _ AndAlso Columns(i).OptionsColumn.AllowSort <> DevExpress.Utils.DefaultBoolean.False _ Then firstCol = Columns(i) End If Next Return firstCol End Function 'Protected Sub cmdRefresh1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRefresh1.Click ' If LockHandler() Then ' Try ' 'PagedGrid.CurrentPage = 0 ' LoadData() ' Finally ' UnlockHandler() ' End Try ' End If 'End Sub Public Overrides Sub BaseForm_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) If Me.ActiveControl Is Me.PagedXtraGrid1 AndAlso PagedXtraGrid1.ActiveControl Is PagedXtraGrid1.Grid AndAlso Me.MainView.FocusedRowHandle >= 0 Then If e.KeyCode = Keys.Enter Then e.Handled = True e.SuppressKeyPress = True MyBase.EditRecord() Return End If End If MyBase.BaseForm_KeyDown(sender, e) End Sub Private m_DefaultSortColumn As GridColumn <Browsable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Localizable(False)> _ Public Property DefaultSortColumn() As GridColumn Get Return m_DefaultSortColumn End Get Set(ByVal Value As GridColumn) m_DefaultSortColumn = Value End Set End Property Protected Overrides Sub TableAdded(ByVal sender As Object, ByVal e As CollectionChangeEventArgs) If DesignMode Then Exit Sub If e.Action = CollectionChangeAction.Add Then MainView.Columns.Clear() For i As Integer = Columns.Count - 1 To 0 Step -1 MainView.Columns.Add(Columns(i)) Next End If MyBase.TableAdded(sender, e) End Sub End Class
EIDSS/EIDSS-Legacy
EIDSS v5/vb/Shared/bvwin_common/BaseForms/BasePagedXtraListForm.vb
Visual Basic
bsd-2-clause
25,971
'------------------------------------------------------------------------------ ' <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.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("ClassToWiki.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
wdssmq/zblogasp
凌乱的快速生成Wiki/ClassToWiki/My Project/Resources.Designer.vb
Visual Basic
mit
2,782
' 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations Public Class CharsetModifierKeywordRecommenderTests Inherits RecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AutoAfterDeclareTest() VerifyRecommendationsContain(<ClassDeclaration>Declare |</ClassDeclaration>, "Auto") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AnsiAfterDeclareTest() VerifyRecommendationsContain(<ClassDeclaration>Declare |</ClassDeclaration>, "Ansi") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub UnicodeAfterDeclareTest() VerifyRecommendationsContain(<ClassDeclaration>Declare |</ClassDeclaration>, "Unicode") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AutoNotAfterAnotherCharsetModifier1Test() VerifyRecommendationsMissing(<ClassDeclaration>Declare Ansi |</ClassDeclaration>, "Auto") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AutoNotAfterAnotherCharsetModifier2Test() VerifyRecommendationsMissing(<ClassDeclaration>Declare Auto |</ClassDeclaration>, "Auto") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AutoNotAfterAnotherCharsetModifier3Test() VerifyRecommendationsMissing(<ClassDeclaration>Declare Unicode |</ClassDeclaration>, "Auto") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterColonTest() VerifyRecommendationsMissing(<ClassDeclaration>Declare : |</ClassDeclaration>, "Unicode") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <ClassDeclaration>Declare |</ClassDeclaration>, "Unicode") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <ClassDeclaration>Declare _ |</ClassDeclaration>, "Unicode") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <ClassDeclaration>Declare _ ' Test |</ClassDeclaration>, "Unicode") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuationt() VerifyRecommendationsContain( <ClassDeclaration>Declare _ |</ClassDeclaration>, "Unicode") End Sub End Class End Namespace
sharwell/roslyn
src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/CharsetModifierKeywordRecommenderTests.vb
Visual Basic
mit
3,491
' 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. Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.UnitTests <UseExportProvider> Public Class ActiveStatementTrackingServiceTests Inherits EditingTestBase <Fact, WorkItem(846042, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846042")> Public Sub MovedOutsideOfMethod1() Dim src1 = " Class C Shared Sub Main(args As String()) <AS:0>Goo(1)</AS:0> End Sub End Class " Dim src2 = " Class C Shared Sub Main(args As String()) <AS:0>End Sub</AS:0> Private Shared Sub Goo() ' tracking span moves to another method as the user types around it <TS:0>Goo(1)</TS:0> End Sub End Class " Dim edits = GetTopEdits(src1, src2) Dim active = GetActiveStatements(src1, src2) edits.VerifyRudeDiagnostics(active) End Sub <Fact> Public Sub MovedOutsideOfMethod2() Dim src1 = " Class C Shared Sub Main(args As String()) <AS:0>Goo(1)</AS:0> End Sub End Class " Dim src2 = " Class C Shared Sub Main(args As String()) <AS:0>Goo(1)</AS:0> End Sub Private Shared Sub Goo() <TS:0>Goo(2)</TS:0> End Sub End Class " Dim edits = GetTopEdits(src1, src2) Dim active = GetActiveStatements(src1, src2) edits.VerifyRudeDiagnostics(active) End Sub <Fact> Public Sub MovedOutsideOfLambda1() Dim src1 = " Class C Shared Sub Main(args As String()) Dim a = Sub() <AS:0>Goo(1)</AS:0> End Sub End Sub End Class " Dim src2 = " Class C Shared Sub Main(args As String()) Dim a = Sub() <AS:0>End Sub</AS:0> <TS:0>Goo(1)</TS:0> End Sub End Class " Dim edits = GetTopEdits(src1, src2) Dim active = GetActiveStatements(src1, src2) edits.VerifyRudeDiagnostics(active) End Sub <Fact> Public Sub MovedOutsideOfLambda2() Dim src1 = " Class C Sub Main() Dim a = Sub() <AS:0>Goo(1)</AS:0> End Sub Dim b = Sub() Goo(2) End Sub End Sub End Class " Dim src2 = " Class C Sub Main() Dim a = Sub() <AS:0>Goo(1)</AS:0> End Sub Dim b = Sub() <TS:0>Goo(2)</TS:0> End Sub End Sub End Class " Dim edits = GetTopEdits(src1, src2) Dim active = GetActiveStatements(src1, src2) edits.VerifyRudeDiagnostics(active) End Sub End Class End Namespace
physhi/roslyn
src/EditorFeatures/VisualBasicTest/EditAndContinue/ActiveStatementTrackingServiceTests.vb
Visual Basic
apache-2.0
2,888
' 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.InteropServices Imports System.Text Imports System.Threading 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 type other than an array, a type parameter. ''' </summary> Friend MustInherit Class NamedTypeSymbol Inherits TypeSymbol Implements INamedTypeSymbol ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ' Changes to the public interface of this class should remain synchronized with the C# version. ' Do not make any changes to the public interface without making the corresponding change ' to the C# version. ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ''' <summary> ''' Returns the arity of this type, or the number of type parameters it takes. ''' A non-generic type has zero arity. ''' </summary> Public MustOverride ReadOnly Property Arity As Integer ''' <summary> ''' Returns the type parameters that this type has. If this is a non-generic type, ''' returns an empty ImmutableArray. ''' </summary> Public MustOverride ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) ''' <summary> ''' Returns the type arguments that have been substituted for the type parameters. ''' If nothing has been substituted for a give type parameters, ''' then the type parameter itself is consider the type argument. ''' </summary> Public ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get Return TypeArgumentsNoUseSiteDiagnostics End Get End Property Friend MustOverride ReadOnly Property TypeArgumentsNoUseSiteDiagnostics As ImmutableArray(Of TypeSymbol) Friend Function TypeArgumentsWithDefinitionUseSiteDiagnostics(<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ImmutableArray(Of TypeSymbol) Dim result = TypeArgumentsNoUseSiteDiagnostics For Each typeArgument In result typeArgument.OriginalDefinition.AddUseSiteDiagnostics(useSiteDiagnostics) Next Return result End Function Friend Function TypeArgumentWithDefinitionUseSiteDiagnostics(index As Integer, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As TypeSymbol Dim result = TypeArgumentsNoUseSiteDiagnostics(index) result.OriginalDefinition.AddUseSiteDiagnostics(useSiteDiagnostics) Return result End Function ''' <summary> ''' Returns the type symbol that this type was constructed from. This type symbol ''' has the same containing type, but has type arguments that are the same ''' as the type parameters (although its containing type might not). ''' </summary> Public MustOverride ReadOnly Property ConstructedFrom As NamedTypeSymbol ''' <summary> ''' For enum types, gets the underlying type. Returns null on all other ''' kinds of types. ''' </summary> Public Overridable ReadOnly Property EnumUnderlyingType As NamedTypeSymbol Get Return Nothing End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return TryCast(Me.ContainingSymbol, NamedTypeSymbol) End Get End Property ''' <summary> ''' For implicitly declared delegate types returns the EventSymbol that caused this ''' delegate type to be generated. ''' For all other types returns null. ''' Note, the set of possible associated symbols might be expanded in the future to ''' reflect changes in the languages. ''' </summary> Public Overridable ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing End Get End Property ''' <summary> ''' Returns True for one of the types from a set of Structure types if ''' that set represents a cycle. This property is intended for flow ''' analysis only since it is only implemented for source types, ''' and only returns True for one of the types within a cycle, not all. ''' </summary> Friend Overridable ReadOnly Property KnownCircularStruct As Boolean Get Return False End Get End Property ''' <summary> ''' Is this a NoPia local type explicitly declared in source, i.e. ''' top level type with a TypeIdentifier attribute on it? ''' </summary> Friend Overridable ReadOnly Property IsExplicitDefinitionOfNoPiaLocalType As Boolean Get Return False End Get End Property ''' <summary> ''' Returns true and a string from the first GuidAttribute on the type, ''' the string might be null or an invalid guid representation. False, ''' if there is no GuidAttribute with string argument. ''' </summary> Friend Overridable Function GetGuidString(ByRef guidString As String) As Boolean Return GetGuidStringDefaultImplementation(guidString) End Function ' Named types have the arity suffix added to the metadata name. Public Overrides ReadOnly Property MetadataName As String Get ' CLR generally allows names with dots, however some APIs like IMetaDataImport ' can only return full type names combined with namespaces. ' see: http://msdn.microsoft.com/en-us/library/ms230143.aspx (IMetaDataImport::GetTypeDefProps) ' When working with such APIs, names with dots become ambiguous since metadata ' consumer cannot figure where namespace ends and actual type name starts. ' Therefore it is a good practice to avoid type names with dots. Debug.Assert(Me.IsErrorType OrElse Not (TypeOf Me Is SourceNamedTypeSymbol) OrElse Not Name.Contains("."), "type name contains dots: " + Name) Return If(MangleName, MetadataHelpers.ComposeAritySuffixedMetadataName(Name, Arity), Name) End Get End Property ''' <summary> ''' Should the name returned by Name property be mangled with [`arity] suffix in order to get metadata name. ''' Must return False for a type with Arity == 0. ''' </summary> ''' <remarks> ''' Default implementation to force consideration of appropriate implementation for each new subclass ''' </remarks> Friend MustOverride ReadOnly Property MangleName As Boolean ''' <summary> ''' True if this symbol has a special name (metadata flag SpecialName is set). ''' </summary> Friend MustOverride ReadOnly Property HasSpecialName As Boolean ''' <summary> ''' True if this type is considered serializable (metadata flag Serializable is set). ''' </summary> Friend MustOverride ReadOnly Property IsSerializable As Boolean ''' <summary> ''' Type layout information (ClassLayout metadata and layout kind flags). ''' </summary> Friend MustOverride ReadOnly Property Layout As TypeLayout ''' <summary> ''' The default charset used for type marshalling. ''' Can be changed via <see cref="DefaultCharSetAttribute"/> applied on the containing module. ''' </summary> Protected ReadOnly Property DefaultMarshallingCharSet As CharSet Get Return If(EffectiveDefaultMarshallingCharSet, CharSet.Ansi) End Get End Property ''' <summary> ''' Marshalling charset of string data fields within the type (string formatting flags in metadata). ''' </summary> Friend MustOverride ReadOnly Property MarshallingCharSet As CharSet ''' <summary> ''' For delegate types, gets the delegate's invoke method. Returns null on ''' all other kinds of types. Note that is is possible to have an ill-formed ''' delegate type imported from metadata which does not have an Invoke method. ''' Such a type will be classified as a delegate but its DelegateInvokeMethod ''' would be null. ''' </summary> Public Overridable ReadOnly Property DelegateInvokeMethod As MethodSymbol Get If TypeKind <> TypeKind.Delegate Then Return Nothing End If Dim methods As ImmutableArray(Of Symbol) = GetMembers(WellKnownMemberNames.DelegateInvokeName) If methods.Length <> 1 Then Return Nothing End If Dim method = TryCast(methods(0), MethodSymbol) 'EDMAURER we used to also check 'method.IsOverridable' because section 13.6 'of the CLI spec dictates that it be virtual, but real world 'working metadata has been found that contains an Invoke method that is 'marked as virtual but not newslot (both of those must be combined to 'meet the definition of virtual). Rather than weaken the check 'I've removed it, as the Dev10 C# compiler makes no check, and we don't 'stand to gain anything by having it. 'Return If(method IsNot Nothing AndAlso method.IsOverridable, method, Nothing) Return method End Get End Property ''' <summary> ''' Returns true if this type was declared as requiring a derived class; ''' i.e., declared with the "MustInherit" modifier. Always true for interfaces. ''' </summary> Public MustOverride ReadOnly Property IsMustInherit As Boolean ''' <summary> ''' Returns true if this type does not allow derived types; i.e., declared ''' with the NotInheritable modifier, or else declared as a Module, Structure, ''' Enum, or Delegate. ''' </summary> Public MustOverride ReadOnly Property IsNotInheritable As Boolean ''' <summary> ''' If this property returns false, it is certain that there are no extension ''' methods inside this type. If this property returns true, it is highly likely ''' (but not certain) that this type contains extension methods. This property allows ''' the search for extension methods to be narrowed much more quickly. ''' ''' !!! Note that this property can mutate during lifetime of the symbol !!! ''' !!! from True to False, as we learn more about the type. !!! ''' </summary> Public MustOverride ReadOnly Property MightContainExtensionMethods As Boolean Implements INamedTypeSymbol.MightContainExtensionMethods ''' <summary> ''' Returns True if the type is marked by 'Microsoft.VisualBasic.Embedded' attribute. ''' </summary> Friend MustOverride ReadOnly Property HasEmbeddedAttribute As Boolean ''' <summary> ''' A Named type is an extensible interface if both the following are true: ''' (a) It is an interface type and ''' (b) It is either marked with 'TypeLibTypeAttribute( flags w/o TypeLibTypeFlags.FNonExtensible )' attribute OR ''' is marked with 'InterfaceTypeAttribute( flags with ComInterfaceType.InterfaceIsIDispatch )' attribute OR ''' inherits from an extensible interface type. ''' Member resolution for Extensible interfaces is late bound, i.e. members are resolved at run time by looking up the identifier on the actual run-time type of the expression. ''' </summary> Friend MustOverride ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean ''' <summary> ''' This method is an entry point for the Binder to collect extension methods with the given name ''' declared within this named type. Overriden by RetargetingNamedTypeSymbol. ''' </summary> Friend Overridable Sub AppendProbableExtensionMethods(name As String, methods As ArrayBuilder(Of MethodSymbol)) If Me.MightContainExtensionMethods Then For Each member As Symbol In Me.GetMembers(name) If member.Kind = SymbolKind.Method Then Dim method = DirectCast(member, MethodSymbol) If method.MayBeReducibleExtensionMethod Then methods.Add(method) End If End If Next End If End Sub ''' <summary> ''' This method is called for a type within a namespace when we are building a map of extension methods ''' for the whole (compilation merged or module level) namespace. ''' ''' The 'appendThrough' parameter allows RetargetingNamespaceSymbol to delegate majority of the work ''' to the underlying named type symbols, but still add RetargetingMethodSymbols to the map. ''' </summary> Friend Overridable Sub BuildExtensionMethodsMap( map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)), appendThrough As NamespaceSymbol ) If Me.MightContainExtensionMethods Then Debug.Assert(False, "Possibly using inefficient implementation of AppendProbableExtensionMethods(map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)))") appendThrough.BuildExtensionMethodsMap(map, From name As String In Me.MemberNames Select New KeyValuePair(Of String, ImmutableArray(Of Symbol))(name, Me.GetMembers(name))) End If End Sub Friend Overridable Sub GetExtensionMethods( methods As ArrayBuilder(Of MethodSymbol), appendThrough As NamespaceSymbol, Name As String ) If Me.MightContainExtensionMethods Then Dim candidates = Me.GetSimpleNonTypeMembers(Name) For Each member In candidates appendThrough.AddMemeberIfExtension(methods, member) Next End If End Sub ''' <summary> ''' This is an entry point for the Binder. Its purpose is to add names of viable extension methods declared ''' in this type to nameSet parameter. ''' </summary> Friend Overridable Overloads Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder) AddExtensionMethodLookupSymbolsInfo(nameSet, options, originalBinder, appendThrough:=Me) End Sub ''' <summary> ''' Add names of viable extension methods declared in this type to nameSet parameter. ''' ''' The 'appendThrough' parameter allows RetargetingNamedTypeSymbol to delegate majority of the work ''' to the underlying named type symbol, but still perform viability check on RetargetingMethodSymbol. ''' </summary> Friend Overridable Overloads Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder, appendThrough As NamedTypeSymbol) If Me.MightContainExtensionMethods Then Debug.Assert(False, "Possibly using inefficient implementation of AppendExtensionMethodNames(nameSet As HashSet(Of String), options As LookupOptions, originalBinder As Binder, appendThrough As NamespaceOrTypeSymbol)") appendThrough.AddExtensionMethodLookupSymbolsInfo(nameSet, options, originalBinder, From name As String In Me.MemberNames Select New KeyValuePair(Of String, ImmutableArray(Of Symbol))(name, Me.GetMembers(name))) End If End Sub ''' <summary> ''' Get the instance constructors for this type. ''' </summary> Public ReadOnly Property InstanceConstructors As ImmutableArray(Of MethodSymbol) Get Return GetConstructors(Of MethodSymbol)(includeInstance:=True, includeShared:=False) End Get End Property ''' <summary> ''' Get the shared constructors for this type. ''' </summary> Public ReadOnly Property SharedConstructors As ImmutableArray(Of MethodSymbol) Get Return GetConstructors(Of MethodSymbol)(includeInstance:=False, includeShared:=True) End Get End Property ''' <summary> ''' Get the instance and shared constructors for this type. ''' </summary> Public ReadOnly Property Constructors As ImmutableArray(Of MethodSymbol) Get Return GetConstructors(Of MethodSymbol)(includeInstance:=True, includeShared:=True) End Get End Property Private Function GetConstructors(Of TMethodSymbol As {IMethodSymbol, Class})(includeInstance As Boolean, includeShared As Boolean) As ImmutableArray(Of TMethodSymbol) Debug.Assert(includeInstance OrElse includeShared) Dim instanceCandidates As ImmutableArray(Of Symbol) = If(includeInstance, GetMembers(WellKnownMemberNames.InstanceConstructorName), ImmutableArray(Of Symbol).Empty) Dim sharedCandidates As ImmutableArray(Of Symbol) = If(includeShared, GetMembers(WellKnownMemberNames.StaticConstructorName), ImmutableArray(Of Symbol).Empty) If instanceCandidates.IsEmpty AndAlso sharedCandidates.IsEmpty Then Return ImmutableArray(Of TMethodSymbol).Empty End If Dim constructors As ArrayBuilder(Of TMethodSymbol) = ArrayBuilder(Of TMethodSymbol).GetInstance() For Each candidate In instanceCandidates If candidate.Kind = SymbolKind.Method Then Dim method As TMethodSymbol = TryCast(candidate, TMethodSymbol) Debug.Assert(method IsNot Nothing) Debug.Assert(method.MethodKind = MethodKind.Constructor) constructors.Add(method) End If Next For Each candidate In sharedCandidates If candidate.Kind = SymbolKind.Method Then Dim method As TMethodSymbol = TryCast(candidate, TMethodSymbol) Debug.Assert(method IsNot Nothing) Debug.Assert(method.MethodKind = MethodKind.StaticConstructor) constructors.Add(method) End If Next Return constructors.ToImmutableAndFree() End Function ''' <summary> ''' Returns true if this type is known to be a reference type. It is never the case ''' that IsReferenceType and IsValueType both return true. However, for an unconstrained ''' type parameter, IsReferenceType and IsValueType will both return false. ''' </summary> Public Overrides ReadOnly Property IsReferenceType As Boolean Get ' TODO: Is this correct for VB Module? Return TypeKind <> TypeKind.Enum AndAlso TypeKind <> TypeKind.Structure AndAlso TypeKind <> TypeKind.Error End Get End Property ''' <summary> ''' Returns true if this type is known to be a value type. It is never the case ''' that IsReferenceType and IsValueType both return true. However, for an unconstrained ''' type parameter, IsReferenceType and IsValueType will both return false. ''' </summary> Public Overrides ReadOnly Property IsValueType As Boolean Get ' TODO: Is this correct for VB Module? Return TypeKind = TypeKind.Enum OrElse TypeKind = TypeKind.Structure End Get End Property ''' <summary> ''' Returns True if this types has Arity >= 1 and Construct can be called. This is primarily useful ''' when deal with error cases. ''' </summary> Friend MustOverride ReadOnly Property CanConstruct As Boolean ''' <summary> ''' Returns a constructed type given its type arguments. ''' </summary> Public Function Construct(ParamArray typeArguments() As TypeSymbol) As NamedTypeSymbol Return Construct(typeArguments.AsImmutableOrNull()) End Function ''' <summary> ''' Returns a constructed type given its type arguments. ''' </summary> Public Function Construct(typeArguments As IEnumerable(Of TypeSymbol)) As NamedTypeSymbol Return Construct(typeArguments.AsImmutableOrNull()) End Function ''' <summary> ''' Construct a new type from this type, substituting the given type arguments for the ''' type parameters. This method should only be called if this named type does not have ''' any substitutions applied for its own type arguments with exception of alpha-rename ''' substitution (although it's container might have substitutions applied). ''' </summary> ''' <param name="typeArguments">A set of type arguments to be applied. Must have the same length ''' as the number of type parameters that this type has.</param> Public MustOverride Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As NamedTypeSymbol ''' <summary> Checks for validity of Construct(...) on this type with these type arguments. </summary> Protected Sub CheckCanConstructAndTypeArguments(typeArguments As ImmutableArray(Of TypeSymbol)) 'This helper is used by Public APIs to perform validation. This exception is part of the public 'contract of Construct() If Not CanConstruct OrElse Me IsNot ConstructedFrom Then Throw New InvalidOperationException() End If ' Check type arguments typeArguments.CheckTypeArguments(Me.Arity) End Sub ''' <summary> ''' Construct a new type from this type definition, substituting the given type arguments for the ''' type parameters. This method should only be called on the OriginalDefinition. Unlike previous ''' Construct method, this overload supports type parameter substitution on this type and any number ''' of its containing types. See comments for TypeSubstitution type for more information. ''' </summary> Friend Function Construct(substitution As TypeSubstitution) As NamedTypeSymbol Debug.Assert(Me.IsDefinition) Debug.Assert(Me.IsOrInGenericType()) If substitution Is Nothing Then Return Me End If Debug.Assert(substitution.IsValidToApplyTo(Me)) ' Validate the map for use of alpha-renamed type parameters. substitution.ThrowIfSubstitutingToAlphaRenamedTypeParameter() Return DirectCast(InternalSubstituteTypeParameters(substitution), NamedTypeSymbol) End Function ''' <summary> ''' Returns an unbound generic type of this generic named type. ''' </summary> Public Function ConstructUnboundGenericType() As NamedTypeSymbol Return Me.AsUnboundGenericType() End Function ''' <summary> ''' Returns Default property name for the type. ''' If there is no default property name, then Nothing is returned. ''' </summary> Friend MustOverride ReadOnly Property DefaultPropertyName As String ''' <summary> ''' If this is a generic type instantiation or a nested type of a generic type instantiation, ''' return TypeSubstitution for this construction. Nothing otherwise. ''' Returned TypeSubstitution should target OriginalDefinition of the symbol. ''' </summary> Friend MustOverride ReadOnly Property TypeSubstitution As TypeSubstitution ' These properties of TypeRef, NamespaceOrType, or Symbol must be overridden. ''' <summary> ''' Gets the name of this symbol. ''' </summary> Public MustOverride Overrides ReadOnly Property Name As String ''' <summary> ''' Collection of names of members declared within this type. ''' </summary> Public MustOverride ReadOnly Property MemberNames As IEnumerable(Of String) ''' <summary> ''' Returns true if the type is a Script class. ''' It might be an interactive submission class or a Script class in a csx file. ''' </summary> Public Overridable ReadOnly Property IsScriptClass As Boolean Get Return False End Get End Property ''' <summary> ''' Returns true if the type is a submission class. ''' </summary> Public Overridable ReadOnly Property IsSubmissionClass As Boolean Get Return False End Get End Property ''' <summary> ''' Returns true if the type is the implicit class that holds onto invalid global members (like methods or ''' statements in a non script file). ''' </summary> Public Overridable ReadOnly Property IsImplicitClass As Boolean Get Return False End Get End Property ''' <summary> ''' Get all the members of this symbol. ''' </summary> ''' <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members, ''' returns an empty ImmutableArray. Never returns Nothing.</returns> Public MustOverride Overrides Function GetMembers() As ImmutableArray(Of Symbol) ''' <summary> ''' Get all the members of this symbol that have a particular name. ''' </summary> ''' <returns>An ImmutableArray containing all the members of this symbol with the given name. If there are ''' no members with this name, returns an empty ImmutableArray. Never returns Nothing.</returns> Public MustOverride Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol) ''' <summary> ''' Get all the members of this symbol that are types. ''' </summary> ''' <returns>An ImmutableArray containing all the types that are members of this symbol. If this symbol has no type members, ''' returns an empty ImmutableArray. Never returns Nothing.</returns> Public MustOverride Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol) ''' <summary> ''' Get all the members of this symbol that are types that have a particular name, and any arity. ''' </summary> ''' <returns>An ImmutableArray containing all the types that are members of this symbol with the given name. ''' If this symbol has no type members with this name, ''' returns an empty ImmutableArray. Never returns Nothing.</returns> Public MustOverride Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol) ''' <summary> ''' Get all the members of this symbol that are types that have a particular name and arity. ''' </summary> ''' <returns>An ImmutableArray containing all the types that are members of this symbol with the given name and arity. ''' If this symbol has no type members with this name and arity, ''' returns an empty ImmutableArray. Never returns Nothing.</returns> Public MustOverride Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol) ''' <summary> ''' Get this accessibility that was declared on this symbol. For symbols that do ''' not have accessibility declared on them, returns NotApplicable. ''' </summary> Public MustOverride Overrides ReadOnly Property DeclaredAccessibility As Accessibility ''' <summary> ''' Supports visitor pattern. ''' </summary> Friend Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult Return visitor.VisitNamedType(Me, arg) End Function ' Only the compiler can created NamedTypeSymbols. Friend Sub New() End Sub ''' <summary> ''' Gets the kind of this symbol. ''' </summary> Public Overrides ReadOnly Property Kind As SymbolKind ' Cannot seal this method because of the ErrorSymbol. Get Return SymbolKind.NamedType End Get End Property ''' <summary> ''' Returns a flag indicating whether this symbol is ComImport. ''' </summary> ''' <remarks> ''' A type can me marked as a ComImport type in source by applying the <see cref="System.Runtime.InteropServices.ComImportAttribute"/> ''' </remarks> Friend MustOverride ReadOnly Property IsComImport As Boolean ''' <summary> ''' If CoClassAttribute was applied to the type returns the type symbol for the argument. ''' Type symbol may be an error type if the type was not found. Otherwise returns Nothing ''' </summary> Friend MustOverride ReadOnly Property CoClassType As TypeSymbol ''' <summary> ''' Returns a sequence of preprocessor symbols specified in <see cref="ConditionalAttribute"/> applied on this symbol, or null if there are none. ''' </summary> Friend MustOverride Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) ''' <summary> ''' Returns a flag indicating whether this symbol has at least one applied conditional attribute. ''' </summary> ''' <remarks> ''' Forces binding and decoding of attributes. ''' NOTE: Conditional symbols on base type must be inherited by derived type, but the native VB compiler doesn't do so. We maintain comptability. ''' </remarks> Friend ReadOnly Property IsConditional As Boolean Get Return Me.GetAppliedConditionalSymbols().Any() End Get End Property Friend Overridable ReadOnly Property AreMembersImplicitlyDeclared As Boolean Get Return False End Get End Property ''' <summary> ''' Gets the associated <see cref="AttributeUsageInfo"/> for an attribute type. ''' </summary> Friend MustOverride Function GetAttributeUsageInfo() As AttributeUsageInfo ''' <summary> ''' Declaration security information associated with this type, or null if there is none. ''' </summary> Friend MustOverride Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) ''' <summary> ''' True if the type has declarative security information (HasSecurity flags). ''' </summary> Friend MustOverride ReadOnly Property HasDeclarativeSecurity As Boolean 'This represents the declared base type and base interfaces, once bound. Private _lazyDeclaredBase As NamedTypeSymbol = ErrorTypeSymbol.UnknownResultType Private _lazyDeclaredInterfaces As ImmutableArray(Of NamedTypeSymbol) = Nothing ''' <summary> ''' NamedTypeSymbol calls derived implementations of this method when declared base type ''' is needed for the first time. ''' ''' basesBeingResolved are passed if there are any types already have their bases resolved ''' so that the derived implementation could avoid infinite recursion ''' </summary> Friend MustOverride Function MakeDeclaredBase(basesBeingResolved As ConsList(Of Symbol), diagnostics As DiagnosticBag) As NamedTypeSymbol ''' <summary> ''' NamedTypeSymbol calls derived implementations of this method when declared interfaces ''' are needed for the first time. ''' ''' basesBeingResolved are passed if there are any types already have their bases resolved ''' so that the derived implementation could avoid infinite recursion ''' </summary> Friend MustOverride Function MakeDeclaredInterfaces(basesBeingResolved As ConsList(Of Symbol), diagnostics As DiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) ''' <summary> ''' Base type as "declared". ''' Declared base type may contain circularities. ''' ''' If DeclaredBase must be accessed while other DeclaredBases are being resolved, ''' the bases that are being resolved must be specified here to prevent potential infinite recursion. ''' </summary> Friend Overridable Function GetDeclaredBase(basesBeingResolved As ConsList(Of Symbol)) As NamedTypeSymbol If _lazyDeclaredBase Is ErrorTypeSymbol.UnknownResultType Then Dim diagnostics = DiagnosticBag.GetInstance() AtomicStoreReferenceAndDiagnostics(_lazyDeclaredBase, MakeDeclaredBase(basesBeingResolved, diagnostics), diagnostics, ErrorTypeSymbol.UnknownResultType) diagnostics.Free() End If Return _lazyDeclaredBase End Function Friend Overridable Function GetSimpleNonTypeMembers(name As String) As ImmutableArray(Of Symbol) Return GetMembers(name) End Function Private Sub AtomicStoreReferenceAndDiagnostics(Of T As Class)(ByRef variable As T, value As T, diagBag As DiagnosticBag, Optional comparand As T = Nothing) Debug.Assert(value IsNot comparand) If diagBag Is Nothing OrElse diagBag.IsEmptyWithoutResolution Then Interlocked.CompareExchange(variable, value, comparand) Else Dim sourceModule = TryCast(Me.ContainingModule, SourceModuleSymbol) If sourceModule IsNot Nothing Then sourceModule.AtomicStoreReferenceAndDiagnostics(variable, value, diagBag, CompilationStage.Declare, comparand) End If End If End Sub Friend Sub AtomicStoreArrayAndDiagnostics(Of T)(ByRef variable As ImmutableArray(Of T), value As ImmutableArray(Of T), diagBag As DiagnosticBag) Debug.Assert(Not value.IsDefault) If diagBag Is Nothing OrElse diagBag.IsEmptyWithoutResolution Then ImmutableInterlocked.InterlockedCompareExchange(variable, value, Nothing) Else Dim sourceModule = TryCast(Me.ContainingModule, SourceModuleSymbol) If sourceModule IsNot Nothing Then sourceModule.AtomicStoreArrayAndDiagnostics(variable, value, diagBag, CompilationStage.Declare) End If End If End Sub ''' <summary> ''' Interfaces as "declared". ''' Declared interfaces may contain circularities. ''' ''' If DeclaredInterfaces must be accessed while other DeclaredInterfaces are being resolved, ''' the bases that are being resolved must be specified here to prevent potential infinite recursion. ''' </summary> Friend Overridable Function GetDeclaredInterfacesNoUseSiteDiagnostics(basesBeingResolved As ConsList(Of Symbol)) As ImmutableArray(Of NamedTypeSymbol) If _lazyDeclaredInterfaces.IsDefault Then Dim diagnostics = DiagnosticBag.GetInstance() AtomicStoreArrayAndDiagnostics(_lazyDeclaredInterfaces, MakeDeclaredInterfaces(basesBeingResolved, diagnostics), diagnostics) diagnostics.Free() End If Return _lazyDeclaredInterfaces End Function Friend Function GetDeclaredInterfacesWithDefinitionUseSiteDiagnostics(basesBeingResolved As ConsList(Of Symbol), <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ImmutableArray(Of NamedTypeSymbol) Dim result = GetDeclaredInterfacesNoUseSiteDiagnostics(basesBeingResolved) For Each iface In result iface.OriginalDefinition.AddUseSiteDiagnostics(useSiteDiagnostics) Next Return result End Function Friend Function GetDirectBaseInterfacesNoUseSiteDiagnostics(basesBeingResolved As ConsList(Of Symbol)) As ImmutableArray(Of NamedTypeSymbol) If Me.TypeKind = TypeKind.Interface Then If basesBeingResolved Is Nothing Then Return Me.InterfacesNoUseSiteDiagnostics Else Return GetDeclaredBaseInterfacesSafe(basesBeingResolved) End If Else Return ImmutableArray(Of NamedTypeSymbol).Empty End If End Function Friend Overridable Function GetDeclaredBaseInterfacesSafe(basesBeingResolved As ConsList(Of Symbol)) As ImmutableArray(Of NamedTypeSymbol) Debug.Assert(basesBeingResolved.Any) If basesBeingResolved.Contains(Me) Then Return Nothing End If Return GetDeclaredInterfacesNoUseSiteDiagnostics(If(basesBeingResolved, ConsList(Of Symbol).Empty).Prepend(Me)) End Function ''' <summary> ''' NamedTypeSymbol calls derived implementations of this method when acyclic base type ''' is needed for the first time. ''' This method typically calls GetDeclaredBase, filters for ''' illegal cycles and other conditions before returning result as acyclic. ''' </summary> Friend MustOverride Function MakeAcyclicBaseType(diagnostics As DiagnosticBag) As NamedTypeSymbol ''' <summary> ''' NamedTypeSymbol calls derived implementations of this method when acyclic base interfaces ''' are needed for the first time. ''' This method typically calls GetDeclaredInterfaces, filters for ''' illegal cycles and other conditions before returning result as acyclic. ''' </summary> Friend MustOverride Function MakeAcyclicInterfaces(diagnostics As DiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Private _lazyBaseType As NamedTypeSymbol = ErrorTypeSymbol.UnknownResultType Private _lazyInterfaces As ImmutableArray(Of NamedTypeSymbol) ''' <summary> ''' Base type. ''' Could be Nothing for Interfaces or Object. ''' </summary> Friend NotOverridable Overrides ReadOnly Property BaseTypeNoUseSiteDiagnostics As NamedTypeSymbol Get If Me._lazyBaseType Is ErrorTypeSymbol.UnknownResultType Then ' force resolution of bases in containing type ' to make base resolution errors more deterministic If ContainingType IsNot Nothing Then Dim tmp = ContainingType.BaseTypeNoUseSiteDiagnostics End If Dim diagnostics = DiagnosticBag.GetInstance Dim acyclicBase = Me.MakeAcyclicBaseType(diagnostics) AtomicStoreReferenceAndDiagnostics(Me._lazyBaseType, acyclicBase, diagnostics, ErrorTypeSymbol.UnknownResultType) diagnostics.Free() End If Return Me._lazyBaseType End Get End Property ''' <summary> ''' Interfaces that are implemented or inherited (if current type is interface itself). ''' </summary> Friend NotOverridable Overrides ReadOnly Property InterfacesNoUseSiteDiagnostics As ImmutableArray(Of NamedTypeSymbol) Get If Me._lazyInterfaces.IsDefault Then Dim diagnostics As DiagnosticBag = DiagnosticBag.GetInstance Dim acyclicInterfaces As ImmutableArray(Of NamedTypeSymbol) = Me.MakeAcyclicInterfaces(diagnostics) AtomicStoreArrayAndDiagnostics(Me._lazyInterfaces, acyclicInterfaces, diagnostics) diagnostics.Free() End If Return Me._lazyInterfaces End Get End Property ''' <summary> ''' Returns declared base type or actual base type if already known ''' This is only used by cycle detection code so that it can observe when cycles are broken ''' while not forcing actual Base to be realized. ''' </summary> Friend Function GetBestKnownBaseType() As NamedTypeSymbol 'NOTE: we can be at race with another thread here. ' the worst thing that can happen though, is that error on same cycle may be reported twice ' if two threads analyse the same cycle at the same time but start from different ends. ' ' For now we decided that this is something we can live with. Dim base = Me._lazyBaseType If base IsNot ErrorTypeSymbol.UnknownResultType Then Return base End If Return GetDeclaredBase(Nothing) End Function ''' <summary> ''' Returns declared interfaces or actual Interfaces if already known ''' This is only used by cycle detection code so that it can observe when cycles are broken ''' while not forcing actual Interfaces to be realized. ''' </summary> Friend Function GetBestKnownInterfacesNoUseSiteDiagnostics() As ImmutableArray(Of NamedTypeSymbol) Dim interfaces = Me._lazyInterfaces If Not interfaces.IsDefault Then Return interfaces End If Return GetDeclaredInterfacesNoUseSiteDiagnostics(Nothing) End Function ''' <summary> ''' True iff this type or some containing type has type parameters. ''' </summary> Public ReadOnly Property IsGenericType As Boolean Implements INamedTypeSymbol.IsGenericType Get Dim p As NamedTypeSymbol = Me Do While p IsNot Nothing If (p.Arity <> 0) Then Return True End If p = p.ContainingType Loop Return False End Get End Property ''' <summary> ''' Get the original definition of this symbol. If this symbol is derived from another ''' symbol by (say) type substitution, this gets the original symbol, as it was defined ''' in source or metadata. ''' </summary> Public Overridable Shadows ReadOnly Property OriginalDefinition As NamedTypeSymbol Get ' Default implements returns Me. Return Me End Get End Property Protected NotOverridable Overrides ReadOnly Property OriginalTypeSymbolDefinition As TypeSymbol Get Return Me.OriginalDefinition End Get End Property ''' <summary> ''' Should return full emitted namespace name for a top level type if the name ''' might be different in case from containing namespace symbol full name, Nothing otherwise. ''' </summary> Friend Overridable Function GetEmittedNamespaceName() As String Return Nothing End Function ''' <summary> ''' Does this type implement all the members of the given interface. Does not include members ''' of interfaces that iface inherits, only direct members. ''' </summary> Friend Function ImplementsAllMembersOfInterface(iface As NamedTypeSymbol) As Boolean Dim implementationMap = ExplicitInterfaceImplementationMap For Each ifaceMember In iface.GetMembersUnordered() If ifaceMember.RequiresImplementation() AndAlso Not implementationMap.ContainsKey(ifaceMember) Then Return False End If Next Return True End Function Friend Overrides Function GetUseSiteErrorInfo() As DiagnosticInfo If Me.IsDefinition Then Return MyBase.GetUseSiteErrorInfo() End If ' Doing check for constructed types here in order to share implementation across ' constructed non-error and error type symbols. ' Check definition. Dim definitionErrorInfo As DiagnosticInfo = DeriveUseSiteErrorInfoFromType(Me.OriginalDefinition) If definitionErrorInfo IsNot Nothing AndAlso definitionErrorInfo.Code = ERRID.ERR_UnsupportedType1 Then Return definitionErrorInfo End If ' Check type arguments. Dim argsErrorInfo As DiagnosticInfo = DeriveUseSiteErrorInfoFromTypeArguments() Return MergeUseSiteErrorInfo(definitionErrorInfo, argsErrorInfo) End Function Private Function DeriveUseSiteErrorInfoFromTypeArguments() As DiagnosticInfo Dim argsErrorInfo As DiagnosticInfo = Nothing For Each arg As TypeSymbol In Me.TypeArgumentsNoUseSiteDiagnostics Dim errorInfo As DiagnosticInfo = DeriveUseSiteErrorInfoFromType(arg) If errorInfo IsNot Nothing Then If errorInfo.Code = ERRID.ERR_UnsupportedType1 Then Return errorInfo End If If argsErrorInfo Is Nothing Then argsErrorInfo = errorInfo End If End If Next Return argsErrorInfo End Function ''' <summary> ''' True if this is a reference to an <em>unbound</em> generic type. These occur only ''' within a <code>GetType</code> expression. A generic type is considered <em>unbound</em> ''' if all of the type argument lists in its fully qualified name are empty. ''' Note that the type arguments of an unbound generic type will be returned as error ''' types because they do not really have type arguments. An unbound generic type ''' yields null for its BaseType and an empty result for its Interfaces. ''' </summary> Public Overridable ReadOnly Property IsUnboundGenericType As Boolean Get Return False End Get End Property ''' <summary> ''' Force all declaration errors to be generated. ''' </summary> Friend MustOverride Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) ''' <summary> ''' Return compiler generated nested types that are created at Declare phase, but not exposed through GetMembers and the like APIs. ''' Should return Nothing if there are no such types. ''' </summary> Friend Overridable Function GetSynthesizedNestedTypes() As IEnumerable(Of Microsoft.Cci.INestedTypeDefinition) Return Nothing End Function ''' <summary> ''' True if the type is a Windows runtime type. ''' </summary> ''' <remarks> ''' A type can me marked as a Windows runtime type in source by applying the WindowsRuntimeImportAttribute. ''' WindowsRuntimeImportAttribute is a pseudo custom attribute defined as an internal class in System.Runtime.InteropServices.WindowsRuntime namespace. ''' This is needed to mark Windows runtime types which are redefined in mscorlib.dll and System.Runtime.WindowsRuntime.dll. ''' These two assemblies are special as they implement the CLR's support for WinRT. ''' </remarks> Friend MustOverride ReadOnly Property IsWindowsRuntimeImport As Boolean ''' <summary> ''' True if the type should have its WinRT interfaces projected onto .NET types and ''' have missing .NET interface members added to the type. ''' </summary> Friend MustOverride ReadOnly Property ShouldAddWinRTMembers As Boolean ''' <summary> ''' Requires less computation than <see cref="TypeSymbol.TypeKind"/>== <see cref="TypeKind.Interface"/>. ''' </summary> ''' <remarks> ''' Metadata types need to compute their base types in order to know their TypeKinds, And that can lead ''' to cycles if base types are already being computed. ''' </remarks> ''' <returns>True if this Is an interface type.</returns> Friend MustOverride ReadOnly Property IsInterface As Boolean #Region "INamedTypeSymbol" Private ReadOnly Property INamedTypeSymbol_Arity As Integer Implements INamedTypeSymbol.Arity Get Return Me.Arity End Get End Property Private ReadOnly Property INamedTypeSymbol_ConstructedFrom As INamedTypeSymbol Implements INamedTypeSymbol.ConstructedFrom Get Return Me.ConstructedFrom End Get End Property Private ReadOnly Property INamedTypeSymbol_DelegateInvokeMethod As IMethodSymbol Implements INamedTypeSymbol.DelegateInvokeMethod Get Return Me.DelegateInvokeMethod End Get End Property Private ReadOnly Property INamedTypeSymbol_EnumUnderlyingType As INamedTypeSymbol Implements INamedTypeSymbol.EnumUnderlyingType Get Return Me.EnumUnderlyingType End Get End Property Private ReadOnly Property INamedTypeSymbol_MemberNames As IEnumerable(Of String) Implements INamedTypeSymbol.MemberNames Get Return Me.MemberNames End Get End Property Private ReadOnly Property INamedTypeSymbol_IsUnboundGenericType As Boolean Implements INamedTypeSymbol.IsUnboundGenericType Get Return Me.IsUnboundGenericType End Get End Property Private ReadOnly Property INamedTypeSymbol_OriginalDefinition As INamedTypeSymbol Implements INamedTypeSymbol.OriginalDefinition Get Return Me.OriginalDefinition End Get End Property Private ReadOnly Property INamedTypeSymbol_TypeArguments As ImmutableArray(Of ITypeSymbol) Implements INamedTypeSymbol.TypeArguments Get Return StaticCast(Of ITypeSymbol).From(Me.TypeArgumentsNoUseSiteDiagnostics) End Get End Property Private ReadOnly Property INamedTypeSymbol_TypeParameters As ImmutableArray(Of ITypeParameterSymbol) Implements INamedTypeSymbol.TypeParameters Get Return StaticCast(Of ITypeParameterSymbol).From(Me.TypeParameters) End Get End Property Private ReadOnly Property INamedTypeSymbol_IsScriptClass As Boolean Implements INamedTypeSymbol.IsScriptClass Get Return Me.IsScriptClass End Get End Property Private ReadOnly Property INamedTypeSymbol_IsImplicitClass As Boolean Implements INamedTypeSymbol.IsImplicitClass Get ' TODO (tomat): Return False End Get End Property Private Function INamedTypeSymbol_Construct(ParamArray arguments() As ITypeSymbol) As INamedTypeSymbol Implements INamedTypeSymbol.Construct For Each arg In arguments arg.EnsureVbSymbolOrNothing(Of TypeSymbol)("typeArguments") Next Return Construct(arguments.Cast(Of TypeSymbol).ToArray()) End Function Private Function INamedTypeSymbol_ConstructUnboundGenericType() As INamedTypeSymbol Implements INamedTypeSymbol.ConstructUnboundGenericType Return ConstructUnboundGenericType() End Function Private ReadOnly Property INamedTypeSymbol_InstanceConstructors As ImmutableArray(Of IMethodSymbol) Implements INamedTypeSymbol.InstanceConstructors Get Return GetConstructors(Of IMethodSymbol)(includeInstance:=True, includeShared:=False) End Get End Property Private ReadOnly Property INamedTypeSymbol_StaticConstructors As ImmutableArray(Of IMethodSymbol) Implements INamedTypeSymbol.StaticConstructors Get Return GetConstructors(Of IMethodSymbol)(includeInstance:=False, includeShared:=True) End Get End Property Private ReadOnly Property INamedTypeSymbol_Constructors As ImmutableArray(Of IMethodSymbol) Implements INamedTypeSymbol.Constructors Get Return GetConstructors(Of IMethodSymbol)(includeInstance:=True, includeShared:=True) End Get End Property Private ReadOnly Property INamedTypeSymbol_AssociatedSymbol As ISymbol Implements INamedTypeSymbol.AssociatedSymbol Get Return Me.AssociatedSymbol End Get End Property #End Region #Region "ISymbol" Protected Overrides ReadOnly Property ISymbol_IsAbstract As Boolean Get Return Me.IsMustInherit End Get End Property Protected Overrides ReadOnly Property ISymbol_IsSealed As Boolean Get Return Me.IsNotInheritable End Get End Property Public Overrides Sub Accept(visitor As SymbolVisitor) visitor.VisitNamedType(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult Return visitor.VisitNamedType(Me) End Function Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor) visitor.VisitNamedType(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult Return visitor.VisitNamedType(Me) End Function #End Region End Class End Namespace
wschae/roslyn
src/Compilers/VisualBasic/Portable/Symbols/NamedTypeSymbol.vb
Visual Basic
apache-2.0
55,703