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
Namespace Introduction Public Class FirstApplication Public Shared Sub Run() ' ExStart:1 ' The path to the documents directory. Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType) Try ' Create a License object Dim license As New License() ' Set the license of Aspose.Cells to avoid the evaluation limitations license.SetLicense(dataDir & Convert.ToString("Aspose.Cells.lic")) Catch ex As Exception Console.WriteLine(ex.Message) End Try ' Instantiate a Workbook object that represents Excel file. Dim wb As New Workbook() ' When you create a new workbook, a default "Sheet1" is added to the workbook. Dim sheet As Worksheet = wb.Worksheets(0) ' Access the "A1" cell in the sheet. Dim cell As Cell = sheet.Cells("A1") ' Input the "Hello World!" text into the "A1" cell cell.PutValue("Hello World!") ' Save the Excel file. wb.Save(dataDir & Convert.ToString("MyBook_out.xlsx"), SaveFormat.Excel97To2003) ' ExEnd:1 End Sub End Class End Namespace
maria-shahid-aspose/Aspose.Cells-for-.NET
Examples/VisualBasic/Introduction/FirstApplication.vb
Visual Basic
mit
1,319
'------------------------------------------------------------------------------ ' <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("vbHTML_editor.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
Hadesxz/VB-codes
vbHTML editor/vbHTML editor/My Project/Resources.Designer.vb
Visual Basic
mit
2,722
Module Module1 Function Filter(a As Double(), b As Double(), signal As Double()) As Double() Dim result(signal.Length - 1) As Double For i = 1 To signal.Length Dim tmp = 0.0 For j = 1 To b.Length If i - j < 0 Then Continue For End If tmp += b(j - 1) * signal(i - j) Next For j = 2 To a.Length If i - j < 0 Then Continue For End If tmp -= a(j - 1) * result(i - j) Next tmp /= a(0) result(i - 1) = tmp Next Return result End Function Sub Main() Dim a() As Double = {1.0, -0.000000000000000277555756, 0.333333333, -1.85037171E-17} Dim b() As Double = {0.16666667, 0.5, 0.5, 0.16666667} Dim signal() As Double = { -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589 } Dim result = Filter(a, b, signal) For i = 1 To result.Length Console.Write("{0,11:F8}", result(i - 1)) Console.Write(If(i Mod 5 <> 0, ", ", vbNewLine)) Next End Sub End Module
ncoe/rosetta
Apply_a_digital_filter_(direct_form_II_transposed)/Visual Basic .NET/DigitalFilter/Module1.vb
Visual Basic
mit
1,524
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class MSSelector 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 '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(MSSelector)) Me.RtRangeSelector1 = New ControlLibrary.RtRangeSelector() Me.ContextMenuStrip1 = New System.Windows.Forms.ContextMenuStrip(Me.components) Me.ResetToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.PinToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripMenuItem2 = New System.Windows.Forms.ToolStripSeparator() Me.TICToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.BPCToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripMenuItem1 = New System.Windows.Forms.ToolStripSeparator() Me.FilterMs2ToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ContextMenuStrip1.SuspendLayout() Me.SuspendLayout() ' 'RtRangeSelector1 ' Me.RtRangeSelector1.ContextMenuStrip = Me.ContextMenuStrip1 Me.RtRangeSelector1.Dock = System.Windows.Forms.DockStyle.Fill Me.RtRangeSelector1.FillColor = System.Drawing.Color.Blue Me.RtRangeSelector1.Location = New System.Drawing.Point(0, 0) Me.RtRangeSelector1.Name = "RtRangeSelector1" Me.RtRangeSelector1.rtmax = 0R Me.RtRangeSelector1.rtmin = 0R Me.RtRangeSelector1.SelectedColor = System.Drawing.Color.Green Me.RtRangeSelector1.Size = New System.Drawing.Size(621, 241) Me.RtRangeSelector1.TabIndex = 0 ' 'ContextMenuStrip1 ' Me.ContextMenuStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ResetToolStripMenuItem, Me.PinToolStripMenuItem, Me.ToolStripMenuItem2, Me.TICToolStripMenuItem, Me.BPCToolStripMenuItem, Me.ToolStripMenuItem1, Me.FilterMs2ToolStripMenuItem}) Me.ContextMenuStrip1.Name = "ContextMenuStrip1" Me.ContextMenuStrip1.Size = New System.Drawing.Size(126, 126) ' 'ResetToolStripMenuItem ' Me.ResetToolStripMenuItem.Image = CType(resources.GetObject("ResetToolStripMenuItem.Image"), System.Drawing.Image) Me.ResetToolStripMenuItem.Name = "ResetToolStripMenuItem" Me.ResetToolStripMenuItem.Size = New System.Drawing.Size(125, 22) Me.ResetToolStripMenuItem.Text = "Reset" ' 'PinToolStripMenuItem ' Me.PinToolStripMenuItem.Image = CType(resources.GetObject("PinToolStripMenuItem.Image"), System.Drawing.Image) Me.PinToolStripMenuItem.Name = "PinToolStripMenuItem" Me.PinToolStripMenuItem.Size = New System.Drawing.Size(125, 22) Me.PinToolStripMenuItem.Text = "Pin" Me.PinToolStripMenuItem.ToolTipText = "Pin of RT Range" ' 'ToolStripMenuItem2 ' Me.ToolStripMenuItem2.Name = "ToolStripMenuItem2" Me.ToolStripMenuItem2.Size = New System.Drawing.Size(122, 6) ' 'TICToolStripMenuItem ' Me.TICToolStripMenuItem.Checked = True Me.TICToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked Me.TICToolStripMenuItem.Name = "TICToolStripMenuItem" Me.TICToolStripMenuItem.Size = New System.Drawing.Size(125, 22) Me.TICToolStripMenuItem.Text = "TIC" ' 'BPCToolStripMenuItem ' Me.BPCToolStripMenuItem.Name = "BPCToolStripMenuItem" Me.BPCToolStripMenuItem.Size = New System.Drawing.Size(125, 22) Me.BPCToolStripMenuItem.Text = "BPC" ' 'ToolStripMenuItem1 ' Me.ToolStripMenuItem1.Name = "ToolStripMenuItem1" Me.ToolStripMenuItem1.Size = New System.Drawing.Size(122, 6) ' 'FilterMs2ToolStripMenuItem ' Me.FilterMs2ToolStripMenuItem.Image = CType(resources.GetObject("FilterMs2ToolStripMenuItem.Image"), System.Drawing.Image) Me.FilterMs2ToolStripMenuItem.Name = "FilterMs2ToolStripMenuItem" Me.FilterMs2ToolStripMenuItem.Size = New System.Drawing.Size(125, 22) Me.FilterMs2ToolStripMenuItem.Text = "Filter Ms2" ' 'MSSelector ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.Controls.Add(Me.RtRangeSelector1) Me.Name = "MSSelector" Me.Size = New System.Drawing.Size(621, 241) Me.ContextMenuStrip1.ResumeLayout(False) Me.ResumeLayout(False) End Sub Friend WithEvents RtRangeSelector1 As RtRangeSelector Friend WithEvents ContextMenuStrip1 As ContextMenuStrip Friend WithEvents ResetToolStripMenuItem As ToolStripMenuItem Friend WithEvents PinToolStripMenuItem As ToolStripMenuItem Friend WithEvents ToolStripMenuItem2 As ToolStripSeparator Friend WithEvents TICToolStripMenuItem As ToolStripMenuItem Friend WithEvents BPCToolStripMenuItem As ToolStripMenuItem Friend WithEvents ToolStripMenuItem1 As ToolStripSeparator Friend WithEvents FilterMs2ToolStripMenuItem As ToolStripMenuItem Private components As System.ComponentModel.IContainer End Class
xieguigang/MassSpectrum-toolkits
src/mzkit/ControlLibrary/MSSelector.Designer.vb
Visual Basic
mit
6,025
'Licensed under MIT. Imports System.Net Module Module1 Sub Main() Dim keywords, sites As String Dim response As String Dim IsHijacked As Boolean = False Using file As New System.IO.StreamReader("keywords.txt") keywords = file.ReadToEnd().Replace(vbCrLf, ";").Replace(",", ";") file.Close() : End Using Using file As New System.IO.StreamReader("websites.txt") sites = file.ReadToEnd().Replace(vbCrLf, ";").Replace(",", ";") file.Close() : End Using Dim currentsite As String Do Until sites = "" currentsite = Mid(sites, 1, InStr(sites, ";") - 1) response = GetStringFromUrl(currentsite) If Mid(response, 1, 6) <> "ERROR:" Then If IfMatchw(response, keywords, True) Then Console.WriteLine(currentsite + " is hijacked.") IsHijacked = True End If Else Console.WriteLine("Failed to get contents from " + currentsite) End If sites = Mid(sites, InStr(sites, ";") + 1) Loop If IsHijacked = False Then Console.WriteLine("No hijack was found during this test.") End If Console.WriteLine("Press ENTER to exit.") Console.ReadLine() End Sub Function GetStringFromUrl(url As String) As String Using wc As New WebClient wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.91 Safari/537.36") Console.WriteLine("Testing:" + url) Try Return System.Text.Encoding.UTF8.GetString(wc.DownloadData(url)) Catch ex As Exception Return ("ERROR:" + ex.Message) End Try End Using End Function Function IfMatchw(q As String, list As String, Optional CaseNotSensitive As Boolean = False) As Boolean If CaseNotSensitive = True Then q = UCase(q) list = UCase(list) End If Dim kw As String Do Until list = "" kw = Mid(list, 1, InStr(list, ";") - 1) If InStr(q, kw) > 0 Then Return True list = Mid(list, InStr(list, ";") + 1) Loop Return False End Function End Module
TianyiChen/HTTP-hijack-test-tool
main.vb
Visual Basic
mit
2,361
'------------------------------------------------------------------------------ ' <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 'NOTE: This file is auto-generated; do not modify it directly. To make changes, ' or if you encounter build errors in this file, go to the Project Designer ' (go to Project Properties or double-click the My Project node in ' Solution Explorer), and make changes on the Application tab. ' Partial Friend Class MyApplication <Global.System.Diagnostics.DebuggerStepThroughAttribute()> _ Public Sub New() MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows) Me.IsSingleInstance = false Me.EnableVisualStyles = true Me.SaveMySettingsOnExit = true Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses End Sub <Global.System.Diagnostics.DebuggerStepThroughAttribute()> _ Protected Overrides Sub OnCreateMainForm() Me.MainForm = Global.guinet_demo.Form1 End Sub End Class End Namespace
PascalRode/GuiNETdemo
guinet_demo/My Project/Application.Designer.vb
Visual Basic
mit
1,479
Imports System.ComponentModel Imports System.ComponentModel.DataAnnotations Imports System.Globalization #Region "Models" <PropertiesMustMatch("Password", "ConfirmPassword", ErrorMessage:="The password and confirmation password do not match.")> _ Public Class SubscribeRemoteModel #Region "Private Members" Private userNameValue As String Private passwordValue As String Private confirmPasswordValue As String Private secretQuestionValue As String Private secretAnswerValue As String Private emailAddressValue As String #End Region #Region "Accessors" <Required()> _ <DataType(DataType.Text)> _ <DisplayName("Username")> _ Public Property UserName() As String Get Return userNameValue End Get Set(ByVal value As String) userNameValue = value End Set End Property <Required()> _ <DataType(DataType.Password)> _ <DisplayName("Password")> _ Public Property Password() As String Get Return passwordValue End Get Set(ByVal value As String) passwordValue = value End Set End Property <Required()> _ <DataType(DataType.Password)> _ <DisplayName("Again?")> _ Public Property ConfirmPassword() As String Get Return confirmPasswordValue End Get Set(ByVal value As String) confirmPasswordValue = value End Set End Property <Required()> _ <DataType(DataType.Text)> _ <DisplayName("Question")> _ Public Property SecretQuestion() As String Get Return secretQuestionValue End Get Set(ByVal value As String) secretQuestionValue = value End Set End Property <Required()> _ <DataType(DataType.Text)> _ <DisplayName("Answer")> _ Public Property SecretAnswer() As String Get Return secretAnswerValue End Get Set(ByVal value As String) secretAnswerValue = value End Set End Property <Required()> _ <DataType(DataType.EmailAddress)> _ <DisplayName("Email")> _ Public Property EmailAddress() As String Get Return emailAddressValue End Get Set(ByVal value As String) emailAddressValue = value End Set End Property #End Region End Class <PropertiesMustMatch("Password", "ConfirmPassword", ErrorMessage:="The password and confirmation password do not match.")> _ Public Class SubscribeLocalModel #Region "Private Members" Private userNameValue As String Private passwordValue As String Private confirmPasswordValue As String Private secretQuestionValue As String Private secretAnswerValue As String Private emailAddressValue As String Private firstNameValue As String Private lastNameValue As String Private streetAddressValue As String Private cityValue As String Private provinceValue As IEnumerable(Of SelectListItem) Private countryValue As String Private postalCodeValue As String Private ccNumberValue As String Private ccvValue As String Private expirationMonthValue As Integer Private expirationYearValue As Integer #End Region #Region "Accessors" <Required()> _ <DataType(DataType.Text)> _ <DisplayName("Username")> _ Public Property UserName() As String Get Return userNameValue End Get Set(ByVal value As String) userNameValue = value End Set End Property <Required()> _ <DataType(DataType.Password)> _ <DisplayName("Password")> _ Public Property Password() As String Get Return passwordValue End Get Set(ByVal value As String) passwordValue = value End Set End Property <Required()> _ <DataType(DataType.Password)> _ <DisplayName("Again?")> _ Public Property ConfirmPassword() As String Get Return confirmPasswordValue End Get Set(ByVal value As String) confirmPasswordValue = value End Set End Property <Required()> _ <DataType(DataType.Text)> _ <DisplayName("Question")> _ Public Property SecretQuestion() As String Get Return secretQuestionValue End Get Set(ByVal value As String) secretQuestionValue = value End Set End Property <Required()> _ <DataType(DataType.Text)> _ <DisplayName("Answer")> _ Public Property SecretAnswer() As String Get Return secretAnswerValue End Get Set(ByVal value As String) secretAnswerValue = value End Set End Property <Required()> _ <DataType(DataType.EmailAddress)> _ <DisplayName("Email")> _ Public Property EmailAddress() As String Get Return emailAddressValue End Get Set(ByVal value As String) emailAddressValue = value End Set End Property <Required()> _ <DataType(DataType.Text)> _ <DisplayName("First Name")> _ Public Property FirstName() As String Get Return firstNameValue End Get Set(ByVal value As String) firstNameValue = value End Set End Property <Required()> _ <DataType(DataType.Text)> _ <DisplayName("Last Name")> _ Public Property LastName() As String Get Return lastNameValue End Get Set(ByVal value As String) lastNameValue = value End Set End Property <Required()> _ <DataType(DataType.Text)> _ <DisplayName("Street Address")> _ Public Property StreetAddress() As String Get Return streetAddressValue End Get Set(ByVal value As String) streetAddressValue = value End Set End Property <Required()> _ <DataType(DataType.Text)> _ <DisplayName("City")> _ Public Property City() As String Get Return cityValue End Get Set(ByVal value As String) cityValue = value End Set End Property <Required()> _ <DisplayName("Province")> _ Public Property Province() As IEnumerable(Of SelectListItem) Get Return provinceValue End Get Set(ByVal value As IEnumerable(Of SelectListItem)) provinceValue = value End Set End Property <Required()> _ <DataType(DataType.Text)> _ <DisplayName("Country")> _ Public Property Country() As String Get Return countryValue End Get Set(ByVal value As String) countryValue = value End Set End Property <Required()> _ <DataType(DataType.Text)> _ <DisplayName("Postal Code")> _ Public Property PostalCode() As String Get Return postalCodeValue End Get Set(ByVal value As String) postalCodeValue = value End Set End Property <Required()> _ <DataType(DataType.Text)> _ <DisplayName("CC Number")> _ <DefaultValue("1")> _ Public Property CreditCardNumber() As String Get Return ccNumberValue End Get Set(ByVal value As String) ccNumberValue = value End Set End Property <Required()> _ <DataType(DataType.Text)> _ <DisplayName("CCV")> _ <StringLength(3)> _ Public Property CCV() As String Get Return ccvValue End Get Set(ByVal value As String) ccvValue = value End Set End Property <Required()> _ <DataType(DataType.Text)> _ <DisplayName("Exp. Month")> _ Public Property ExpirationMonth() As Integer Get Return expirationMonthValue End Get Set(ByVal value As Integer) expirationMonthValue = value End Set End Property <Required()> _ <DataType(DataType.Text)> _ <DisplayName("Exp. Year")> _ Public Property ExpirationYear() As Integer Get Return expirationYearValue End Get Set(ByVal value As Integer) expirationYearValue = value End Set End Property #End Region End Class #End Region Public Class Province Private nameValue As String Private provinceCodeValue As String Public Property Name() As String Get Return nameValue End Get Set(ByVal value As String) nameValue = value End Set End Property Public Property ProvinceCode() As String Get Return provinceCodeValue End Get Set(ByVal value As String) provinceCodeValue = value End Set End Property End Class
hewittj/chargify-dot-net
Source/Chargify.MVC/Models/SubscriptionModels.vb
Visual Basic
mit
8,940
'Copyright 2019 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 Microsoft.VisualBasic Imports System Imports System.Collections.Generic Imports System.Text Namespace GlobeFlyTool Public Class PointZ Public x As Double Public y As Double Public z As Double Public Sub New() x = 0 y = 0 z = 0 End Sub Public Sub New(ByVal x As Double, ByVal y As Double, ByVal z As Double) Me.x = x Me.y = y Me.z = z End Sub Public Function Norm() As Double Dim val As Double = Math.Sqrt((Me.x * Me.x) + (Me.y * Me.y) + (Me.z * Me.z)) Return val End Function Public Shared Operator +(ByVal p1 As PointZ, ByVal p2 As PointZ) As PointZ Dim newPoint As New PointZ() newPoint.x = p1.x + p2.x newPoint.y = p1.y + p2.y newPoint.z = p1.z + p2.z Return newPoint End Operator Public Shared Operator -(ByVal p1 As PointZ, ByVal p2 As PointZ) As PointZ Dim newPoint As New PointZ() newPoint.x = p1.x - p2.x newPoint.y = p1.y - p2.y newPoint.z = p1.z - p2.z Return newPoint End Operator Public Shared Operator *(ByVal p As PointZ, ByVal factor As Double) As PointZ Dim newPoint As New PointZ(factor * p.x, factor * p.y, factor * p.z) Return newPoint End Operator End Class End Namespace
Esri/arcobjects-sdk-community-samples
Net/3D/GlobeFlyTool/VBNet/PointZ.vb
Visual Basic
apache-2.0
1,754
'//////////////////////////////////////////////////////////////////////// ' Copyright 2001-2015 Aspose Pty Ltd. All Rights Reserved. ' ' This file is part of Aspose.Imaging. The source code in this file ' is only intended as a supplement to the documentation, and is provided ' "as is", without warranty of any kind, either expressed or implied. '//////////////////////////////////////////////////////////////////////// Imports Aspose.Cloud Imports System Namespace Aspose.Cells.Cloud.Examples.Workbook Friend Class ConvertWorkbookToAnotherFormatWithoutStorage Shared Sub Main() Dim dataDir As String = Common.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType) Dim input As String = "sample1.xlsx" Dim output As String = "output.pdf" Dim outPath As String = "cellsOut/" Common.StorageService.File.UploadFile(dataDir &input, input, storage:= Common.STORAGE) Common.CellsService.Workbook.ExportWorkbook(input, WorkbookExportFormat.Pdf, String.Empty, False, Common.FOLDER, outPath & output, storage:= Common.STORAGE) Common.StorageService.File.DownloadFile(outPath & output, dataDir & output, storage:=Common.STORAGE) End Sub End Class End Namespace
farooqsheikhpk/Aspose.Cells-for-Cloud
Examples/DotNet/VisualBasic/Workbook/ConvertWorkbookToAnotherFormatWithoutStorage.vb
Visual Basic
mit
1,220
' 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 Imports System.Xml.Linq Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBLambdaTests Inherits BasicTestBase <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SimpleLambda() Dim source = <compilation> <file name="a.vb"> Class C Delegate Function D() As Object Public Sub Main() Dim d as D = Function() 1 d() End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugDll) compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="E5-7C-24-B4-CD-54-7D-DA-7A-48-2F-D1-A4-B6-D2-EB-5C-95-CA-B4"/> </files> <methods> <method containingType="C" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <lambda offset="13"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="4" startColumn="5" endLine="4" endColumn="22" document="1"/> <entry offset="0x1" startLine="5" startColumn="13" endLine="5" endColumn="34" document="1"/> <entry offset="0x26" startLine="6" startColumn="9" endLine="6" endColumn="12" document="1"/> <entry offset="0x2d" startLine="7" startColumn="5" endLine="7" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2e"> <currentnamespace name=""/> <local name="d" il_index="0" il_start="0x0" il_end="0x2e" attributes="0"/> </scope> </method> <method containingType="C+_Closure$__" name="_Lambda$__2-0"> <customDebugInfo> <encLocalSlotMap> <slot kind="21" offset="13"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="22" endLine="5" endColumn="32" document="1"/> <entry offset="0x1" startLine="5" startColumn="33" endLine="5" endColumn="34" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xc"> <importsforward declaringType="C" methodName="Main"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LambdaMethod() Dim source = <compilation> <file><![CDATA[ Imports System Module M1 Class C1(Of G) Public Sub Print(Of TPrint)(x As TPrint) Console.Write(x.ToString()) End Sub Public Shared Sub PrintShared(Of TPrint)(x As TPrint, y As G) Console.Write(x.ToString()) Console.Write(y.ToString()) End Sub Public Sub Goo(Of TFun1, TFun2)(p As TFun1, p1 As TFun2, p3 As Integer) Dim d1 As Action(Of Integer, Integer) = Sub(lifted As Integer, notLifted As Integer) Dim iii As Integer = lifted + notlifted Console.WriteLine(iii) Dim d2 As Action(Of TFun1) = Sub(X As TFun1) lifted = lifted + 1 C1(Of TFun2).PrintShared(Of TFun1)(X, p1) End Sub d2.Invoke(p) End Sub d1.Invoke(5, 5) End Sub End Class Public Sub Main() Dim inst As New C1(Of Integer) inst.Goo(Of Integer, Integer)(42, 333, 432) End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugExe) compilation.VerifyPdb("M1+C1`1+_Closure$__3-1`2._Lambda$__0", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="M1" methodName="Main"/> <methods> <method containingType="M1+C1`1+_Closure$__3-1`2" name="_Lambda$__0" parameterNames="lifted, notLifted"> <customDebugInfo> <encLocalSlotMap> <slot kind="30" offset="57"/> <slot kind="0" offset="127"/> <slot kind="0" offset="234"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="17" endLine="16" endColumn="61" document="1"/> <entry offset="0x1" hidden="true" document="1"/> <entry offset="0x15" startLine="17" startColumn="25" endLine="17" endColumn="60" document="1"/> <entry offset="0x1e" startLine="18" startColumn="21" endLine="18" endColumn="43" document="1"/> <entry offset="0x25" startLine="20" startColumn="25" endLine="24" endColumn="32" document="1"/> <entry offset="0x32" startLine="26" startColumn="21" endLine="26" endColumn="33" document="1"/> <entry offset="0x3f" startLine="27" startColumn="17" endLine="27" endColumn="24" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x40"> <importsforward declaringType="M1" methodName="Main"/> <local name="$VB$Closure_0" il_index="0" il_start="0x0" il_end="0x40" attributes="0"/> <local name="iii" il_index="1" il_start="0x0" il_end="0x40" attributes="0"/> <local name="d2" il_index="2" il_start="0x0" il_end="0x40" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> <WorkItem(544000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544000")> Public Sub TestLambdaNameStability() Dim source = <compilation> <file> Imports System Public Class C Public Sub M(a as action) const x as integer = 1 M( Sub() const y as integer = 2 const z as integer = 3 Console.WriteLine(x + y + z) end Sub ) end sub end class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll) Dim actual1 As XElement = GetPdbXml(compilation) Dim actual2 As XElement = GetPdbXml(compilation) AssertXml.Equal(actual1, actual2) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestFunctionValueLocalOfLambdas() Dim source = <compilation> <file> Module Module1 Sub Main() Dim x = Function() dim r = 23 Return r End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("Module1+_Closure$__._Lambda$__0-0", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="Module1" methodName="Main"/> <methods> <method containingType="Module1+_Closure$__" name="_Lambda$__0-0"> <customDebugInfo> <encLocalSlotMap> <slot kind="21" offset="8"/> <slot kind="0" offset="44"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="17" endLine="5" endColumn="27" document="1"/> <entry offset="0x1" startLine="6" startColumn="25" endLine="6" endColumn="31" document="1"/> <entry offset="0x4" startLine="7" startColumn="21" endLine="7" endColumn="29" document="1"/> <entry offset="0x8" startLine="8" startColumn="12" endLine="8" endColumn="24" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xa"> <importsforward declaringType="Module1" methodName="Main"/> <local name="r" il_index="1" il_start="0x0" il_end="0xa" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PartiallyDefinedClass_1() Dim source = <compilation> <file name="a.vb"> Imports System Partial Class C Public m1 As Func(Of Integer) = Function() 1 Sub Main() End Sub End Class </file> <file name="b.vb"> Imports System Partial Class C Public m2 As Func(Of Integer) = Function() 2 End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugDll) ' Check two distinct lambda offsets for m1 and m2 compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="E9-8A-62-CA-DC-E3-2B-C4-4B-06-D5-97-3C-77-18-2E-6F-67-EE-15"/> <file id="2" name="b.vb" language="VB" checksumAlgorithm="SHA1" checksum="A1-36-22-63-B1-FC-DD-52-E1-86-92-E9-1A-7D-68-5A-C5-74-27-69"/> </files> <methods> <method containingType="C" name=".ctor"> <customDebugInfo> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset="-26"/> <lambda offset="-12"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x7" startLine="3" startColumn="12" endLine="3" endColumn="49" document="1"/> <entry offset="0x31" startLine="3" startColumn="12" endLine="3" endColumn="49" document="2"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x5c"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> <method containingType="C" name="Main"> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="15" document="1"/> <entry offset="0x1" startLine="6" startColumn="5" endLine="6" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="C" methodName=".ctor"/> </scope> </method> <method containingType="C+_Closure$__" name="_Lambda$__0-0"> <customDebugInfo> <encLocalSlotMap> <slot kind="21" offset="-26"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="37" endLine="3" endColumn="47" document="1"/> <entry offset="0x1" startLine="3" startColumn="48" endLine="3" endColumn="49" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="C" methodName=".ctor"/> </scope> </method> <method containingType="C+_Closure$__" name="_Lambda$__0-1"> <customDebugInfo> <encLocalSlotMap> <slot kind="21" offset="-12"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="37" endLine="3" endColumn="47" document="2"/> <entry offset="0x1" startLine="3" startColumn="48" endLine="3" endColumn="49" document="2"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="C" methodName=".ctor"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PartiallyDefinedClass_2() Dim source = <compilation> <file name="a.vb"> Imports System Partial Class C Public m1 As Func(Of Integer) = Function() 1 Sub Main() End Sub End Class Partial Class C Public m2 As Func(Of Integer) = Function() 2 End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugDll) ' Check two distinct lambda offsets for m1 and m2 compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="CC-04-2E-86-CE-51-76-57-53-27-C4-A0-42-3C-DA-FC-6A-91-4A-39"/> </files> <methods> <method containingType="C" name=".ctor"> <customDebugInfo> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset="-26"/> <lambda offset="-12"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x7" startLine="3" startColumn="12" endLine="3" endColumn="49" document="1"/> <entry offset="0x31" startLine="10" startColumn="12" endLine="10" endColumn="49" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x5c"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> <method containingType="C" name="Main"> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="15" document="1"/> <entry offset="0x1" startLine="6" startColumn="5" endLine="6" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="C" methodName=".ctor"/> </scope> </method> <method containingType="C+_Closure$__" name="_Lambda$__0-0"> <customDebugInfo> <encLocalSlotMap> <slot kind="21" offset="-26"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="37" endLine="3" endColumn="47" document="1"/> <entry offset="0x1" startLine="3" startColumn="48" endLine="3" endColumn="49" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="C" methodName=".ctor"/> </scope> </method> <method containingType="C+_Closure$__" name="_Lambda$__0-1"> <customDebugInfo> <encLocalSlotMap> <slot kind="21" offset="-12"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="37" endLine="10" endColumn="47" document="1"/> <entry offset="0x1" startLine="10" startColumn="48" endLine="10" endColumn="49" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="C" methodName=".ctor"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PartiallyDefinedClass_3() Dim source = <compilation> <file name="a.vb"> Imports System Partial Class C2 Public Shared m1 As Func(Of Integer) = Function() 1 End Class </file> <file name="b.vb"> Imports System Partial Class C2 Shared Sub New() End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugDll) compilation.VerifyPdb( <symbols> <files> <file id="1" name="b.vb" language="VB" checksumAlgorithm="SHA1" checksum="37-E0-06-E1-03-09-97-5A-F5-8F-79-EE-92-BC-7C-63-A6-EB-FF-D4"/> <file id="2" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="D2-29-EA-DE-F7-E6-E9-BC-A0-CE-E4-FB-93-74-05-37-16-D8-89-F1"/> </files> <methods> <method containingType="C2" name=".cctor"> <customDebugInfo> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <lambda offset="-12"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="21" document="1"/> <entry offset="0x1" startLine="3" startColumn="19" endLine="3" endColumn="56" document="2"/> <entry offset="0x16" startLine="4" startColumn="5" endLine="4" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x17"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> <method containingType="C2+_Closure$__" name="_Lambda$__2-0"> <customDebugInfo> <encLocalSlotMap> <slot kind="21" offset="-12"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="3" startColumn="44" endLine="3" endColumn="54" document="2"/> <entry offset="0x1" startLine="3" startColumn="55" endLine="3" endColumn="56" document="2"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="C2" methodName=".cctor"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery() Dim source = <compilation> <file><![CDATA[ Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1, 2, 3} End Function Sub Main() System.Diagnostics.Debug.Assert(False) Dim q = From x In Nums() Order By x Descending Group y = x * 10, z = x * 100 By evenOdd = x Mod 2 Into s = Sum(y + 12345), z = Sum(y + 56789) q.ToArray() Dim qq = From x As Long In Nums() Order By x Descending qq.ToArray() End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.VerifyDiagnostics() compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="47" document="1"/> <entry offset="0x1" startLine="6" startColumn="9" endLine="6" endColumn="25" document="1"/> <entry offset="0x15" startLine="7" startColumn="5" endLine="7" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x17"> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x17" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="54"/> <slot kind="0" offset="286"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="101"/> <lambda offset="174"/> <lambda offset="141"/> <lambda offset="131"/> <lambda offset="216"/> <lambda offset="236"/> <lambda offset="298"/> <lambda offset="342"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="15" document="1"/> <entry offset="0x1" startLine="12" startColumn="13" endLine="15" endColumn="64" document="1"/> <entry offset="0xa1" startLine="17" startColumn="9" endLine="17" endColumn="20" document="1"/> <entry offset="0xa8" startLine="19" startColumn="13" endLine="20" endColumn="38" document="1"/> <entry offset="0x100" startLine="22" startColumn="9" endLine="22" endColumn="21" document="1"/> <entry offset="0x107" startLine="23" startColumn="5" endLine="23" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x108"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x108" attributes="0"/> <local name="qq" il_index="1" il_start="0x0" il_end="0x108" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="x"> <sequencePoints> <entry offset="0x0" startLine="13" startColumn="26" endLine="13" endColumn="27" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="x"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="60" endLine="14" endColumn="67" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x4"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="x"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="27" endLine="14" endColumn="33" document="1"/> <entry offset="0x4" startLine="14" startColumn="39" endLine="14" endColumn="46" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xe"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-3" parameterNames="evenOdd, $VB$ItAnonymous"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x1" startLine="15" startColumn="30" endLine="15" endColumn="44" document="1"/> <entry offset="0x2b" startLine="15" startColumn="50" endLine="15" endColumn="64" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x5b"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-4" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="34" endLine="15" endColumn="43" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xd"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-5" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="54" endLine="15" endColumn="63" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xd"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-6" parameterNames="x"> <sequencePoints> <entry offset="0x0" startLine="19" startColumn="25" endLine="19" endColumn="32" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-7" parameterNames="x"> <sequencePoints> <entry offset="0x0" startLine="20" startColumn="26" endLine="20" endColumn="27" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_01() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() x = New List(Of Integer)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.VerifyDiagnostics() compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="61"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="14" endColumn="37" document="1"/> <entry offset="0x30" startLine="15" startColumn="9" endLine="15" endColumn="36" document="1"/> <entry offset="0x3c" startLine="16" startColumn="5" endLine="16" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3d"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x3d" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x3d" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_02() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 As Long In Nums(), rangeVar2 As Long In Nums() x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.VerifyDiagnostics() compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="76"/> <lambda offset="116"/> <lambda offset="105"/> <lambda offset="61"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="14" endColumn="74" document="1"/> <entry offset="0x7d" startLine="15" startColumn="9" endLine="15" endColumn="35" document="1"/> <entry offset="0x89" startLine="16" startColumn="5" endLine="16" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8a"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x8a" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x8a" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="28" endLine="14" endColumn="35" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="68" endLine="14" endColumn="74" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2f"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="57" endLine="14" endColumn="64" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_03() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Let rangeVar2 = rangeVar1 * 2 x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="115"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="15" endColumn="42" document="1"/> <entry offset="0x30" startLine="16" startColumn="9" endLine="16" endColumn="35" document="1"/> <entry offset="0x3c" startLine="17" startColumn="5" endLine="17" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3d"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x3d" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x3d" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="29" endLine="15" endColumn="42" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xa"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_04() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Let rangeVar2 As Long = rangeVar1 * 2, rangeVar3 = rangeVar1 + rangeVar2 x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="123"/> <lambda offset="150"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="15" endColumn="85" document="1"/> <entry offset="0x59" startLine="16" startColumn="9" endLine="16" endColumn="35" document="1"/> <entry offset="0x65" startLine="17" startColumn="5" endLine="17" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x66"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x66" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x66" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="37" endLine="15" endColumn="50" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xb"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="64" endLine="15" endColumn="85" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x20"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_05() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Select rangeVar2 = rangeVar1 * 2 x = New List(Of Integer)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.VerifyDiagnostics() compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="118"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="15" endColumn="45" document="1"/> <entry offset="0x30" startLine="16" startColumn="9" endLine="16" endColumn="36" document="1"/> <entry offset="0x3c" startLine="17" startColumn="5" endLine="17" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3d"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x3d" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x3d" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="32" endLine="15" endColumn="45" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x4"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_06() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Select rangeVar1 * 2 x = New List(Of Integer)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="106"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="15" endColumn="33" document="1"/> <entry offset="0x30" startLine="16" startColumn="9" endLine="16" endColumn="36" document="1"/> <entry offset="0x3c" startLine="17" startColumn="5" endLine="17" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3d"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x3d" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x3d" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="20" endLine="15" endColumn="33" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x4"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_07() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Select rangeVar2 = rangeVar1 * 2, rangeVar3 = rangeVar1 / 2 x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="118"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="15" endColumn="72" document="1"/> <entry offset="0x30" startLine="16" startColumn="9" endLine="16" endColumn="35" document="1"/> <entry offset="0x3c" startLine="17" startColumn="5" endLine="17" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3d"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x3d" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x3d" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="32" endLine="15" endColumn="45" document="1"/> <entry offset="0x3" startLine="15" startColumn="59" endLine="15" endColumn="72" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x15"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_08() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Join rangeVar2 As Long In Nums() On rangeVar1 Equals rangeVar2 x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="101"/> <lambda offset="160"/> <lambda offset="177"/> <lambda offset="86"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="15" endColumn="67" document="1"/> <entry offset="0xa6" startLine="16" startColumn="9" endLine="16" endColumn="35" document="1"/> <entry offset="0xb2" startLine="17" startColumn="5" endLine="17" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xb3"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0xb3" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0xb3" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="53" endLine="14" endColumn="60" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="41" endLine="15" endColumn="50" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="58" endLine="15" endColumn="67" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_09() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Join rangeVar2 In Nums() Join rangeVar3 In Nums() On rangeVar3 Equals rangeVar2 On rangeVar1 Equals rangeVar2 And rangeVar3 + 1 Equals rangeVar1 + 1 x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="225"/> <lambda offset="242"/> <lambda offset="154"/> <lambda offset="293"/> <lambda offset="310"/> <lambda offset="86"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="17" endColumn="106" document="1"/> <entry offset="0xf3" startLine="18" startColumn="9" endLine="18" endColumn="35" document="1"/> <entry offset="0xff" startLine="19" startColumn="5" endLine="19" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x100"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x100" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x100" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="63" endLine="16" endColumn="72" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="rangeVar3"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="46" endLine="16" endColumn="55" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-3" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="17" startColumn="41" endLine="17" endColumn="50" document="1"/> <entry offset="0x1" startLine="17" startColumn="93" endLine="17" endColumn="106" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xa"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-4" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="17" startColumn="58" endLine="17" endColumn="67" document="1"/> <entry offset="0x6" startLine="17" startColumn="72" endLine="17" endColumn="85" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x14"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_10() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Group Join rangeVar2 As Long In Nums() On rangeVar1 Equals rangeVar2 Into Group x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="107"/> <lambda offset="166"/> <lambda offset="183"/> <lambda offset="86"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="16" endColumn="48" document="1"/> <entry offset="0xa6" startLine="17" startColumn="9" endLine="17" endColumn="35" document="1"/> <entry offset="0xb2" startLine="18" startColumn="5" endLine="18" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xb3"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0xb3" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0xb3" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="59" endLine="14" endColumn="66" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="41" endLine="15" endColumn="50" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="58" endLine="15" endColumn="67" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_11() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Group Join rangeVar2 As Long In Nums() Group Join rangeVar3 As Long In Nums() On rangeVar3 Equals rangeVar2 Into Sum(rangeVar3) On rangeVar1 Equals rangeVar2 Into Sum(rangeVar2) x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="107"/> <lambda offset="188"/> <lambda offset="258"/> <lambda offset="275"/> <lambda offset="167"/> <lambda offset="336"/> <lambda offset="388"/> <lambda offset="405"/> <lambda offset="86"/> <lambda offset="462"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="19" endColumn="57" document="1"/> <entry offset="0x145" startLine="20" startColumn="9" endLine="20" endColumn="35" document="1"/> <entry offset="0x151" startLine="21" startColumn="5" endLine="21" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x152"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x152" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x152" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="59" endLine="14" endColumn="66" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="rangeVar3"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="63" endLine="15" endColumn="70" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="69" endLine="16" endColumn="78" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-3" parameterNames="rangeVar3"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="52" endLine="16" endColumn="61" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-4" parameterNames="rangeVar2, $VB$ItAnonymous"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x1" startLine="17" startColumn="47" endLine="17" endColumn="61" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x31"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-5" parameterNames="rangeVar3"> <sequencePoints> <entry offset="0x0" startLine="17" startColumn="51" endLine="17" endColumn="60" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-6" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="18" startColumn="41" endLine="18" endColumn="50" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-7" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="18" startColumn="58" endLine="18" endColumn="67" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-8" parameterNames="rangeVar1, $VB$ItAnonymous"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x1" startLine="19" startColumn="43" endLine="19" endColumn="57" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x31"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-9" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="19" startColumn="47" endLine="19" endColumn="56" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_12() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Group Join rangeVar2 In Nums() On rangeVar1 Equals rangeVar2 And rangeVar2 + 1 Equals rangeVar1 + 1 Into Group, Sum = Sum(rangeVar2), Count() x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="158"/> <lambda offset="175"/> <lambda offset="86"/> <lambda offset="284"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="16" endColumn="79" document="1"/> <entry offset="0x7d" startLine="17" startColumn="9" endLine="17" endColumn="35" document="1"/> <entry offset="0x89" startLine="18" startColumn="5" endLine="18" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8a"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x8a" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x8a" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="41" endLine="15" endColumn="50" document="1"/> <entry offset="0x1" startLine="15" startColumn="93" endLine="15" endColumn="106" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xa"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="58" endLine="15" endColumn="67" document="1"/> <entry offset="0x1" startLine="15" startColumn="72" endLine="15" endColumn="85" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xa"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="rangeVar1, $VB$ItAnonymous"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x2" startLine="16" startColumn="56" endLine="16" endColumn="70" document="1"/> <entry offset="0x2c" startLine="16" startColumn="72" endLine="16" endColumn="79" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x38"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-3" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="60" endLine="16" endColumn="69" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_13() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums(), rangeVar2 In Nums() Where rangeVar1 = rangeVar2 OrElse rangeVar1 < rangeVar2 + 1 x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="100"/> <lambda offset="61"/> <lambda offset="126"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="15" endColumn="73" document="1"/> <entry offset="0x7d" startLine="16" startColumn="9" endLine="16" endColumn="35" document="1"/> <entry offset="0x89" startLine="17" startColumn="5" endLine="17" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8a"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x8a" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x8a" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="52" endLine="14" endColumn="58" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x6"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="19" endLine="15" endColumn="73" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x22"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_14() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums(), rangeVar2 In Nums() Skip While rangeVar1 = rangeVar2 OrElse rangeVar1 < rangeVar2 + 1 x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="100"/> <lambda offset="61"/> <lambda offset="131"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="15" endColumn="78" document="1"/> <entry offset="0x7d" startLine="16" startColumn="9" endLine="16" endColumn="35" document="1"/> <entry offset="0x89" startLine="17" startColumn="5" endLine="17" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8a"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x8a" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x8a" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="52" endLine="14" endColumn="58" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x6"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="24" endLine="15" endColumn="78" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x22"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_15() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums(), rangeVar2 In Nums() Take While rangeVar1 = rangeVar2 OrElse rangeVar1 < rangeVar2 + 1 x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="100"/> <lambda offset="61"/> <lambda offset="131"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="15" endColumn="78" document="1"/> <entry offset="0x7d" startLine="16" startColumn="9" endLine="16" endColumn="35" document="1"/> <entry offset="0x89" startLine="17" startColumn="5" endLine="17" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8a"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x8a" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x8a" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="52" endLine="14" endColumn="58" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x6"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="24" endLine="15" endColumn="78" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x22"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_16() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Skip 1 x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="15" endColumn="19" document="1"/> <entry offset="0xd" startLine="16" startColumn="9" endLine="16" endColumn="35" document="1"/> <entry offset="0x19" startLine="17" startColumn="5" endLine="17" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x1a"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x1a" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x1a" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_17() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Take 1 x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="15" endColumn="19" document="1"/> <entry offset="0xd" startLine="16" startColumn="9" endLine="16" endColumn="35" document="1"/> <entry offset="0x19" startLine="17" startColumn="5" endLine="17" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x1a"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x1a" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x1a" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_18() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums(), rangeVar2 In Nums() Group By rangeVar1 Into Group x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="100"/> <lambda offset="61"/> <lambda offset="129"/> <lambda offset="120"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="16" endColumn="23" document="1"/> <entry offset="0xa1" startLine="17" startColumn="9" endLine="17" endColumn="35" document="1"/> <entry offset="0xad" startLine="18" startColumn="5" endLine="18" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xae"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0xae" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0xae" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="52" endLine="14" endColumn="58" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x6"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="22" endLine="15" endColumn="31" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_19() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums(), rangeVar2 In Nums() Group By rangeVar2 = rangeVar1 * 2 Into Sum(rangeVar2) x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="100"/> <lambda offset="61"/> <lambda offset="141"/> <lambda offset="120"/> <lambda offset="177"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="16" endColumn="32" document="1"/> <entry offset="0xa1" startLine="17" startColumn="9" endLine="17" endColumn="35" document="1"/> <entry offset="0xad" startLine="18" startColumn="5" endLine="18" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xae"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0xae" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0xae" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="52" endLine="14" endColumn="58" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x6"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="34" endLine="15" endColumn="47" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x9"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-3" parameterNames="rangeVar2, $VB$ItAnonymous"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x1" startLine="16" startColumn="18" endLine="16" endColumn="32" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x31"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-4" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="22" endLine="16" endColumn="31" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_20() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums(), rangeVar2 In Nums() Group By rangeVar2 = rangeVar1 * 2, rangeVar3 = rangeVar1 / 2 Into Group, Sum = Sum(rangeVar2), Count() x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="100"/> <lambda offset="61"/> <lambda offset="141"/> <lambda offset="120"/> <lambda offset="217"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="16" endColumn="54" document="1"/> <entry offset="0xa1" startLine="17" startColumn="9" endLine="17" endColumn="35" document="1"/> <entry offset="0xad" startLine="18" startColumn="5" endLine="18" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xae"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0xae" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0xae" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="52" endLine="14" endColumn="58" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x6"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="34" endLine="15" endColumn="47" document="1"/> <entry offset="0x8" startLine="15" startColumn="61" endLine="15" endColumn="74" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x1f"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-3" parameterNames="$VB$It, $VB$ItAnonymous"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0xd" startLine="16" startColumn="31" endLine="16" endColumn="45" document="1"/> <entry offset="0x37" startLine="16" startColumn="47" endLine="16" endColumn="54" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x43"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-4" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="35" endLine="16" endColumn="44" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_21() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Aggregate rangeVar2 As Long In Nums() Into Sum(rangeVar2 / 3) x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="130"/> <lambda offset="119"/> <lambda offset="159"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="16" endColumn="36" document="1"/> <entry offset="0x30" startLine="17" startColumn="9" endLine="17" endColumn="35" document="1"/> <entry offset="0x3c" startLine="18" startColumn="5" endLine="18" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3d"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x3d" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x3d" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="13" endLine="16" endColumn="36" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x5e"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="33" endLine="15" endColumn="40" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="22" endLine="16" endColumn="35" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xd"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_22() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Aggregate rangeVar2 As Long In Nums(), rangeVar3 In Nums() Into Sum = Sum(rangeVar2 * rangeVar3) x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="130"/> <lambda offset="119"/> <lambda offset="151"/> <lambda offset="99"/> <lambda offset="186"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="16" endColumn="50" document="1"/> <entry offset="0x30" startLine="17" startColumn="9" endLine="17" endColumn="35" document="1"/> <entry offset="0x3c" startLine="18" startColumn="5" endLine="18" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3d"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x3d" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x3d" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="13" endLine="16" endColumn="50" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xab"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="33" endLine="15" endColumn="40" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="65" endLine="15" endColumn="71" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x6"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-4" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="28" endLine="16" endColumn="49" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xf"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_23() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Select 1 Aggregate rangeVar2 As Long In Nums() Into Sum(rangeVar2 / 3) x = New List(Of Double)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="106"/> <lambda offset="152"/> <lambda offset="141"/> <lambda offset="181"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="17" endColumn="36" document="1"/> <entry offset="0x59" startLine="18" startColumn="9" endLine="18" endColumn="35" document="1"/> <entry offset="0x65" startLine="19" startColumn="5" endLine="19" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x66"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x66" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x66" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="20" endLine="15" endColumn="21" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="$VB$ItAnonymous"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="13" endLine="17" endColumn="36" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x58"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="33" endLine="16" endColumn="40" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-3" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="17" startColumn="22" endLine="17" endColumn="35" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xd"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_24() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Aggregate rangeVar2 In Nums() Into Sum = Sum(rangeVar2), Count() x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="122"/> <lambda offset="99"/> <lambda offset="157"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="16" endColumn="47" document="1"/> <entry offset="0x59" startLine="17" startColumn="9" endLine="17" endColumn="35" document="1"/> <entry offset="0x65" startLine="18" startColumn="5" endLine="18" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x66"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x66" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x66" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="13" endLine="15" endColumn="42" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xc"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x6" startLine="16" startColumn="24" endLine="16" endColumn="38" document="1"/> <entry offset="0x35" startLine="16" startColumn="40" endLine="16" endColumn="47" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x46"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="28" endLine="16" endColumn="37" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_25() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Aggregate rangeVar2 As Long In Nums(), rangeVar3 In Nums() Into Sum = Sum(rangeVar3), Count() x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="130"/> <lambda offset="119"/> <lambda offset="151"/> <lambda offset="99"/> <lambda offset="99"/> <lambda offset="186"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="16" endColumn="47" document="1"/> <entry offset="0x59" startLine="17" startColumn="9" endLine="17" endColumn="35" document="1"/> <entry offset="0x65" startLine="18" startColumn="5" endLine="18" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x66"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x66" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x66" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="13" endLine="15" endColumn="71" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x82"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="33" endLine="15" endColumn="40" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="65" endLine="15" endColumn="71" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x6"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-4" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x6" startLine="16" startColumn="24" endLine="16" endColumn="38" document="1"/> <entry offset="0x35" startLine="16" startColumn="40" endLine="16" endColumn="47" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x46"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-5" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="28" endLine="16" endColumn="37" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_26() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Aggregate rangeVar2 As Long In Nums() Join rangeVar3 In Nums() On rangeVar2 Equals rangeVar3 Into Sum = Sum(rangeVar3), Count() x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="130"/> <lambda offset="119"/> <lambda offset="165"/> <lambda offset="182"/> <lambda offset="137"/> <lambda offset="99"/> <lambda offset="220"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="16" endColumn="47" document="1"/> <entry offset="0x59" startLine="17" startColumn="9" endLine="17" endColumn="35" document="1"/> <entry offset="0x65" startLine="18" startColumn="5" endLine="18" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x66"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x66" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x66" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="13" endLine="15" endColumn="105" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xab"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="33" endLine="15" endColumn="40" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="79" endLine="15" endColumn="88" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-3" parameterNames="rangeVar3"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="96" endLine="15" endColumn="105" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-5" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x6" startLine="16" startColumn="24" endLine="16" endColumn="38" document="1"/> <entry offset="0x35" startLine="16" startColumn="40" endLine="16" endColumn="47" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x46"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-6" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="28" endLine="16" endColumn="37" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_27() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Select 2 Aggregate rangeVar2 In Nums() Into Sum = Sum(rangeVar2), Count() x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB" /> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="106"/> <lambda offset="144"/> <lambda offset="121"/> <lambda offset="179"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="17" endColumn="47" document="1"/> <entry offset="0x82" startLine="18" startColumn="9" endLine="18" endColumn="35" document="1"/> <entry offset="0x8e" startLine="19" startColumn="5" endLine="19" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8f"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x8f" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x8f" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="20" endLine="15" endColumn="21" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="$VB$ItAnonymous"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="13" endLine="16" endColumn="42" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x6"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="$VB$Group"> <sequencePoints> <entry offset="0x0" startLine="17" startColumn="24" endLine="17" endColumn="38" document="1"/> <entry offset="0x2a" startLine="17" startColumn="40" endLine="17" endColumn="47" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x36"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-3" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="17" startColumn="28" endLine="17" endColumn="37" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_28() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Select 3 Aggregate rangeVar2 As Long In Nums(), rangeVar3 In Nums() Into Sum = Sum(rangeVar3), Count() x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB" /> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="106"/> <lambda offset="152"/> <lambda offset="141"/> <lambda offset="173"/> <lambda offset="121"/> <lambda offset="121"/> <lambda offset="208"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="17" endColumn="47" document="1"/> <entry offset="0x82" startLine="18" startColumn="9" endLine="18" endColumn="35" document="1"/> <entry offset="0x8e" startLine="19" startColumn="5" endLine="19" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8f"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x8f" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x8f" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="20" endLine="15" endColumn="21" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="$VB$ItAnonymous"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="13" endLine="16" endColumn="71" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7c"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="33" endLine="16" endColumn="40" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-3" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="65" endLine="16" endColumn="71" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x6"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-5" parameterNames="$VB$Group"> <sequencePoints> <entry offset="0x0" startLine="17" startColumn="24" endLine="17" endColumn="38" document="1"/> <entry offset="0x2a" startLine="17" startColumn="40" endLine="17" endColumn="47" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x36"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-6" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="17" startColumn="28" endLine="17" endColumn="37" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_29() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim q As IEnumerable Dim x As Object q = From rangeVar1 In Nums() Select 3 Aggregate rangeVar2 As Long In Nums() Join rangeVar3 In Nums() On rangeVar2 Equals rangeVar3 Into Sum = Sum(rangeVar3), Count() x = New List(Of Object)(q) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB" /> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="0" offset="34"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="106"/> <lambda offset="152"/> <lambda offset="141"/> <lambda offset="187"/> <lambda offset="204"/> <lambda offset="159"/> <lambda offset="121"/> <lambda offset="242"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="14" startColumn="9" endLine="17" endColumn="47" document="1"/> <entry offset="0x82" startLine="18" startColumn="9" endLine="18" endColumn="35" document="1"/> <entry offset="0x8e" startLine="19" startColumn="5" endLine="19" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8f"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="q" il_index="0" il_start="0x0" il_end="0x8f" attributes="0"/> <local name="x" il_index="1" il_start="0x0" il_end="0x8f" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="15" startColumn="20" endLine="15" endColumn="21" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="$VB$ItAnonymous"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="13" endLine="16" endColumn="105" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xa5"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-2" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="33" endLine="16" endColumn="40" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-3" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="79" endLine="16" endColumn="88" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-4" parameterNames="rangeVar3"> <sequencePoints> <entry offset="0x0" startLine="16" startColumn="96" endLine="16" endColumn="105" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-6" parameterNames="$VB$Group"> <sequencePoints> <entry offset="0x0" startLine="17" startColumn="24" endLine="17" endColumn="38" document="1"/> <entry offset="0x2a" startLine="17" startColumn="40" endLine="17" endColumn="47" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x36"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-7" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="17" startColumn="28" endLine="17" endColumn="37" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_30() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim x As Object x = Aggregate rangeVar1 As Long In Nums() Into Sum(rangeVar1 / 3) End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB" /> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="49"/> <lambda offset="89"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="12" startColumn="9" endLine="13" endColumn="36" document="1"/> <entry offset="0x5e" startLine="14" startColumn="5" endLine="14" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x5f"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="x" il_index="0" il_start="0x0" il_end="0x5f" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="12" startColumn="33" endLine="12" endColumn="40" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="13" startColumn="22" endLine="13" endColumn="35" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xd"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(824944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824944")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_31() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Function Nums() As IEnumerable(Of Integer) Return {1} End Function Sub Main() Dim x As Object x = Aggregate rangeVar1 In Nums(), rangeVar2 As Long In Nums() Into Sum = Sum(rangeVar2), Count() End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb( <symbols> <files> <file id="1" name="" language="VB" /> </files> <methods> <method containingType="Module1" name="Nums"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="-1"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="6" startColumn="5" endLine="6" endColumn="47" document="1"/> <entry offset="0x1" startLine="7" startColumn="9" endLine="7" endColumn="19" document="1"/> <entry offset="0xe" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x10"> <namespace name="System.Collections" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <namespace name="System.Linq" importlevel="file"/> <currentnamespace name=""/> <local name="Nums" il_index="0" il_start="0x0" il_end="0x10" attributes="0"/> </scope> </method> <method containingType="Module1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> <slot kind="temp"/> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset="81"/> <lambda offset="70"/> <lambda offset="29"/> <lambda offset="116"/> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="15" document="1"/> <entry offset="0x1" startLine="12" startColumn="9" endLine="13" endColumn="47" document="1"/> <entry offset="0x8a" startLine="14" startColumn="5" endLine="14" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x8b"> <importsforward declaringType="Module1" methodName="Nums"/> <local name="x" il_index="0" il_start="0x0" il_end="0x8b" attributes="0"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-0" parameterNames="rangeVar1"> <sequencePoints> <entry offset="0x0" startLine="12" startColumn="65" endLine="12" endColumn="71" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x2f"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-1" parameterNames="rangeVar2"> <sequencePoints> <entry offset="0x0" startLine="12" startColumn="54" endLine="12" endColumn="61" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x3"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> <method containingType="Module1+_Closure$__" name="_Lambda$__1-3" parameterNames="$VB$It"> <sequencePoints> <entry offset="0x0" startLine="13" startColumn="28" endLine="13" endColumn="37" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x7"> <importsforward declaringType="Module1" methodName="Nums"/> </scope> </method> </methods> </symbols>) End Sub <WorkItem(841361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/841361")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SequencePointsInAQuery_32() Dim source = <compilation> <file><![CDATA[ Imports System.Collections Imports System.Collections.Generic Imports System.Linq Module Module1 Sub Main() Dim x = From a in {1, 2, 3} Let b = a * a Select b End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.DebugDll) compilation.AssertTheseDiagnostics(<expected></expected>) compilation.VerifyPdb("Module1+_Closure$__._Lambda$__0-0", <symbols> <files> <file id="1" name="" language="VB" /> </files> <methods> <method containingType="Module1+_Closure$__" name="_Lambda$__0-0" parameterNames="a"> <sequencePoints> <entry offset="0x0" startLine="8" startColumn="25" endLine="8" endColumn="30" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xa"> <importsforward declaringType="Module1" methodName="Main"/> </scope> </method> </methods> </symbols>) End Sub End Class End Namespace
AdamSpeight2008/roslyn-AdamSpeight2008
src/Compilers/VisualBasic/Test/Emit/PDB/PDBLambdaTests.vb
Visual Basic
apache-2.0
185,013
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Completion.SuggestionMode Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Public Class SuggestionModeCompletionProviderTests Inherits AbstractVisualBasicCompletionProviderTests Public Sub New(workspaceFixture As VisualBasicTestWorkspaceFixture) MyBase.New(workspaceFixture) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration1() As Task Dim markup = <a>Class C $$ End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration2() As Task Dim markup = <a>Class C Public $$ End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration3() As Task Dim markup = <a>Module M Public $$ End Module</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration4() As Task Dim markup = <a>Structure S Public $$ End Structure</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration5() As Task Dim markup = <a>Class C WithEvents $$ End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration6() As Task Dim markup = <a>Class C Protected Friend $$ End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration1() As Task Dim markup = <a>Class C Public Sub Bar($$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration2() As Task Dim markup = <a>Class C Public Sub Bar(Optional goo as Integer, $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration3() As Task Dim markup = <a>Class C Public Sub Bar(Optional $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration4() As Task Dim markup = <a>Class C Public Sub Bar(Optional x $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration5() As Task Dim markup = <a>Class C Public Sub Bar(Optional x As $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration6() As Task Dim markup = <a>Class C Public Sub Bar(Optional x As Integer $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration7() As Task Dim markup = <a>Class C Public Sub Bar(ByVal $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration8() As Task Dim markup = <a>Class C Public Sub Bar(ByVal x $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration9() As Task Dim markup = <a>Class C Sub Goo $$ End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration10() As Task Dim markup = <a>Class C Public Property SomeProp $$ End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectClause1() As Task Dim markup = <a>Class z Sub bar() Dim a = New Integer(1, 2, 3) {} Dim goo = From z In a Select $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectClause2() As Task Dim markup = <a>Class z Sub bar() Dim a = New Integer(1, 2, 3) {} Dim goo = From z In a Select 1, $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestForStatement1() As Task Dim markup = <a>Class z Sub bar() For $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestForStatement2() As Task Dim markup = <a>Class z Sub bar() For $$ = 1 To 10 Next End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <WorkItem(545351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545351")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBuilderWhenOptionExplicitOff() As Task Dim markup = <a>Option Explicit Off Class C1 Sub M() Console.WriteLine($$ End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(546659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546659")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestUsingStatement() As Task Dim markup = <a> Class C1 Sub M() Using $$ End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(734596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734596")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOptionExplicitOffStatementLevel1() As Task Dim markup = <a> Option Explicit Off Class C1 Sub M() $$ End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(734596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734596")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOptionExplicitOffStatementLevel2() As Task Dim markup = <a> Option Explicit Off Class C1 Sub M() a = $$ End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(960416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960416")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestReadonlyField() As Task Dim markup = <a> Class C1 Readonly $$ Sub M() End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceDeclarationName_Unqualified() As Task Dim markup = <a> Namespace $$ End Namespace </a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceDeclarationName_Qualified() As Task Dim markup = <a> Namespace A.$$ End Namespace </a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PartialClassName() As Task Dim markup = <a>Partial Class $$</a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PartialStructureName() As Task Dim markup = <a>Partial Structure $$</a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PartialInterfaceName() As Task Dim markup = <a>Partial Interface $$</a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PartialModuleName() As Task Dim markup = <a>Partial Module $$</a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TupleType() As Task Dim markup = <a> Class C Sub M() Dim t As (a$$, b) End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TupleTypeAfterComma() As Task Dim markup = <a> Class C Sub M() Dim t As (a, b$$) End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function Private Function VerifyNotBuilderAsync(markup As XElement, Optional triggerInfo As CompletionTrigger? = Nothing, Optional useDebuggerOptions As Boolean = False) As Task Return VerifySuggestionModeWorkerAsync(markup, isBuilder:=False, triggerInfo:=triggerInfo, useDebuggerOptions:=useDebuggerOptions) End Function Private Function VerifyBuilderAsync(markup As XElement, Optional triggerInfo As CompletionTrigger? = Nothing, Optional useDebuggerOptions As Boolean = False) As Task Return VerifySuggestionModeWorkerAsync(markup, isBuilder:=True, triggerInfo:=triggerInfo, useDebuggerOptions:=useDebuggerOptions) End Function Private Async Function VerifySuggestionModeWorkerAsync(markup As XElement, isBuilder As Boolean, triggerInfo As CompletionTrigger?, Optional useDebuggerOptions As Boolean = False) As Task Dim code As String = Nothing Dim position As Integer = 0 MarkupTestFile.GetPosition(markup.NormalizedValue, code, position) Using workspaceFixture = New VisualBasicTestWorkspaceFixture() Try Dim options = If(useDebuggerOptions, (workspaceFixture.GetWorkspace(ExportProvider)).Options.WithDebuggerCompletionOptions(), (workspaceFixture.GetWorkspace(ExportProvider)).Options) Dim document1 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular) Await CheckResultsAsync(document1, position, isBuilder, triggerInfo, options) If Await CanUseSpeculativeSemanticModelAsync(document1, position) Then Dim document2 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular, cleanBeforeUpdate:=False) Await CheckResultsAsync(document2, position, isBuilder, triggerInfo, options) End If Finally workspaceFixture.DisposeAfterTest() End Try End Using End Function Private Overloads Async Function CheckResultsAsync(document As Document, position As Integer, isBuilder As Boolean, triggerInfo As CompletionTrigger?, options As OptionSet) As Task triggerInfo = If(triggerInfo, CompletionTrigger.CreateInsertionTrigger("a"c)) Dim service = GetCompletionService(document.Project) Dim provider = Assert.Single(service.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty)) Dim context = Await service.GetTestAccessor().GetContextAsync( provider, document, position, triggerInfo.Value, options, CancellationToken.None) If isBuilder Then Assert.NotNull(context) Assert.NotNull(context.SuggestionModeItem) Else If context IsNot Nothing Then Assert.True(context.SuggestionModeItem Is Nothing, "group.Builder = " & If(context.SuggestionModeItem IsNot Nothing, context.SuggestionModeItem.DisplayText, "null")) End If End If End Function Friend Overrides Function GetCompletionProviderType() As Type Return GetType(VisualBasicSuggestionModeCompletionProvider) End Function End Class End Namespace
reaction1989/roslyn
src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/SuggestionModeCompletionProviderTests.vb
Visual Basic
apache-2.0
14,864
' 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.Classification Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Classification Partial Friend Class Worker Private Class DocumentationCommentClassifier Private _worker As Worker Sub New(worker As Worker) _worker = worker End Sub Friend Sub Classify(documentationComment As DocumentationCommentTriviaSyntax) If Not _worker._textSpan.OverlapsWith(documentationComment.Span) Then Return End If For Each xmlNode In documentationComment.Content Dim childFullSpan = xmlNode.FullSpan If childFullSpan.Start > _worker._textSpan.End Then Return ElseIf childFullSpan.End < _worker._textSpan.Start Then Continue For End If ClassifyXmlNode(xmlNode) Next End Sub Private Sub ClassifyXmlNode(node As XmlNodeSyntax) If node Is Nothing Then Return End If Select Case node.Kind Case SyntaxKind.XmlText ClassifyXmlText(DirectCast(node, XmlTextSyntax)) Case SyntaxKind.XmlElement ClassifyElement(DirectCast(node, XmlElementSyntax)) Case SyntaxKind.XmlEmptyElement ClassifyEmptyElement(DirectCast(node, XmlEmptyElementSyntax)) Case SyntaxKind.XmlName ClassifyXmlName(DirectCast(node, XmlNameSyntax)) Case SyntaxKind.XmlString ClassifyString(DirectCast(node, XmlStringSyntax)) Case SyntaxKind.XmlComment ClassifyComment(DirectCast(node, XmlCommentSyntax)) Case SyntaxKind.XmlCDataSection ClassifyCData(DirectCast(node, XmlCDataSectionSyntax)) Case SyntaxKind.XmlProcessingInstruction ClassifyProcessingInstruction(DirectCast(node, XmlProcessingInstructionSyntax)) End Select End Sub Private Sub ClassifyXmlTrivia(trivialList As SyntaxTriviaList, Optional whitespaceClassificationType As String = Nothing) For Each t In trivialList Select Case t.Kind() Case SyntaxKind.DocumentationCommentExteriorTrivia ClassifyExteriorTrivia(t) Case SyntaxKind.WhitespaceTrivia If whitespaceClassificationType IsNot Nothing Then _worker.AddClassification(t, whitespaceClassificationType) End If End Select Next End Sub Private Sub ClassifyExteriorTrivia(trivia As SyntaxTrivia) ' Note: The exterior trivia can contain whitespace (usually leading) and we want to avoid classifying it. ' PERFORMANCE: ' While the call to SyntaxTrivia.ToString() looks Like an allocation, it isn't. ' The SyntaxTrivia green node holds the string text of the trivia in a field And ToString() ' just returns a reference to that. Dim text = trivia.ToString() Dim spanStart As Integer? = Nothing For index = 0 To text.Length - 1 Dim ch = text(index) If spanStart IsNot Nothing AndAlso Char.IsWhiteSpace(ch) Then Dim span = TextSpan.FromBounds(spanStart.Value, spanStart.Value + index) _worker.AddClassification(span, ClassificationTypeNames.XmlDocCommentDelimiter) spanStart = Nothing ElseIf spanStart Is Nothing AndAlso Not Char.IsWhiteSpace(ch) Then spanStart = trivia.Span.Start + index End If Next ' Add a final classification if we hadn't encountered anymore whitespace at the end If spanStart IsNot Nothing Then Dim span = TextSpan.FromBounds(spanStart.Value, trivia.Span.End) _worker.AddClassification(span, ClassificationTypeNames.XmlDocCommentDelimiter) End If End Sub Private Sub AddXmlClassification(token As SyntaxToken, classificationType As String) If token.HasLeadingTrivia Then ClassifyXmlTrivia(token.LeadingTrivia, classificationType) End If _worker.AddClassification(token, classificationType) If token.HasTrailingTrivia Then ClassifyXmlTrivia(token.TrailingTrivia, classificationType) End If End Sub Private Sub ClassifyXmlTextTokens(textTokens As SyntaxTokenList) For Each token In textTokens If token.HasLeadingTrivia Then ClassifyXmlTrivia(token.LeadingTrivia, whitespaceClassificationType:=ClassificationTypeNames.XmlDocCommentText) End If ClassifyXmlTextToken(token) If token.HasTrailingTrivia Then ClassifyXmlTrivia(token.TrailingTrivia, whitespaceClassificationType:=ClassificationTypeNames.XmlDocCommentText) End If Next token End Sub Private Sub ClassifyXmlTextToken(token As SyntaxToken) If token.Kind = SyntaxKind.XmlEntityLiteralToken Then _worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentEntityReference) ElseIf token.Kind() <> SyntaxKind.DocumentationCommentLineBreakToken Then Select Case token.Parent.Kind Case SyntaxKind.XmlText _worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentText) Case SyntaxKind.XmlString _worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentAttributeValue) Case SyntaxKind.XmlComment _worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentComment) Case SyntaxKind.XmlCDataSection _worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentCDataSection) Case SyntaxKind.XmlProcessingInstruction _worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentProcessingInstruction) End Select End If End Sub Private Sub ClassifyXmlName(node As XmlNameSyntax) Dim classificationType As String If TypeOf node.Parent Is BaseXmlAttributeSyntax Then classificationType = ClassificationTypeNames.XmlDocCommentAttributeName ElseIf TypeOf node.Parent Is XmlProcessingInstructionSyntax Then classificationType = ClassificationTypeNames.XmlDocCommentProcessingInstruction Else classificationType = ClassificationTypeNames.XmlDocCommentName End If Dim prefix = node.Prefix If prefix IsNot Nothing Then AddXmlClassification(prefix.Name, classificationType) AddXmlClassification(prefix.ColonToken, classificationType) End If AddXmlClassification(node.LocalName, classificationType) End Sub Private Sub ClassifyElement(xmlElementSyntax As XmlElementSyntax) ClassifyElementStart(xmlElementSyntax.StartTag) For Each xmlNode In xmlElementSyntax.Content ClassifyXmlNode(xmlNode) Next ClassifyElementEnd(xmlElementSyntax.EndTag) End Sub Private Sub ClassifyElementStart(node As XmlElementStartTagSyntax) AddXmlClassification(node.LessThanToken, ClassificationTypeNames.XmlDocCommentDelimiter) ClassifyXmlNode(node.Name) ' Note: In xml doc comments, attributes can only _be_ attributes. ' there are no expression holes here. For Each attribute In node.Attributes ClassifyBaseXmlAttribute(TryCast(attribute, BaseXmlAttributeSyntax)) Next AddXmlClassification(node.GreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter) End Sub Private Sub ClassifyElementEnd(node As XmlElementEndTagSyntax) AddXmlClassification(node.LessThanSlashToken, ClassificationTypeNames.XmlDocCommentDelimiter) ClassifyXmlNode(node.Name) AddXmlClassification(node.GreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter) End Sub Private Sub ClassifyEmptyElement(node As XmlEmptyElementSyntax) AddXmlClassification(node.LessThanToken, ClassificationTypeNames.XmlDocCommentDelimiter) ClassifyXmlNode(node.Name) ' Note: In xml doc comments, attributes can only _be_ attributes. ' there are no expression holes here. For Each attribute In node.Attributes ClassifyBaseXmlAttribute(TryCast(attribute, BaseXmlAttributeSyntax)) Next AddXmlClassification(node.SlashGreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter) End Sub Private Sub ClassifyBaseXmlAttribute(attribute As BaseXmlAttributeSyntax) If attribute IsNot Nothing Then Select Case attribute.Kind Case SyntaxKind.XmlAttribute ClassifyAttribute(DirectCast(attribute, XmlAttributeSyntax)) Case SyntaxKind.XmlCrefAttribute ClassifyCrefAttribute(DirectCast(attribute, XmlCrefAttributeSyntax)) Case SyntaxKind.XmlNameAttribute ClassifyNameAttribute(DirectCast(attribute, XmlNameAttributeSyntax)) End Select End If End Sub Private Sub ClassifyAttribute(attribute As XmlAttributeSyntax) ClassifyXmlNode(attribute.Name) AddXmlClassification(attribute.EqualsToken, ClassificationTypeNames.XmlDocCommentDelimiter) ClassifyXmlNode(attribute.Value) End Sub Private Sub ClassifyCrefAttribute(attribute As XmlCrefAttributeSyntax) ClassifyXmlNode(attribute.Name) AddXmlClassification(attribute.EqualsToken, ClassificationTypeNames.XmlDocCommentDelimiter) AddXmlClassification(attribute.StartQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes) _worker.ClassifyNode(attribute.Reference) AddXmlClassification(attribute.EndQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes) End Sub Private Sub ClassifyNameAttribute(attribute As XmlNameAttributeSyntax) ClassifyXmlNode(attribute.Name) AddXmlClassification(attribute.EqualsToken, ClassificationTypeNames.XmlDocCommentDelimiter) AddXmlClassification(attribute.StartQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes) _worker.ClassifyNode(attribute.Reference) AddXmlClassification(attribute.EndQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes) End Sub Private Sub ClassifyXmlText(xmlTextSyntax As XmlTextSyntax) ClassifyXmlTextTokens(xmlTextSyntax.TextTokens) End Sub Private Sub ClassifyString(node As XmlStringSyntax) AddXmlClassification(node.StartQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes) ClassifyXmlTextTokens(node.TextTokens) AddXmlClassification(node.EndQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes) End Sub Private Sub ClassifyComment(node As XmlCommentSyntax) AddXmlClassification(node.LessThanExclamationMinusMinusToken, ClassificationTypeNames.XmlDocCommentDelimiter) ClassifyXmlTextTokens(node.TextTokens) AddXmlClassification(node.MinusMinusGreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter) End Sub Private Sub ClassifyCData(node As XmlCDataSectionSyntax) AddXmlClassification(node.BeginCDataToken, ClassificationTypeNames.XmlDocCommentDelimiter) ClassifyXmlTextTokens(node.TextTokens) AddXmlClassification(node.EndCDataToken, ClassificationTypeNames.XmlDocCommentDelimiter) End Sub Private Sub ClassifyProcessingInstruction(node As XmlProcessingInstructionSyntax) AddXmlClassification(node.LessThanQuestionToken, ClassificationTypeNames.XmlDocCommentProcessingInstruction) AddXmlClassification(node.Name, ClassificationTypeNames.XmlDocCommentProcessingInstruction) ClassifyXmlTextTokens(node.TextTokens) AddXmlClassification(node.QuestionGreaterThanToken, ClassificationTypeNames.XmlDocCommentProcessingInstruction) End Sub End Class End Class End Namespace
DavidKarlas/roslyn
src/Workspaces/VisualBasic/Portable/Classification/Worker.DocumentationCommentClassifier.vb
Visual Basic
apache-2.0
14,128
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.UseCompoundAssignment Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UseCompoundAssignment <ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicUseCompoundAssignmentCodeFixProvider Inherits AbstractUseCompoundAssignmentCodeFixProvider(Of SyntaxKind, AssignmentStatementSyntax, ExpressionSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() MyBase.New(Kinds) End Sub Protected Overrides Function Token(kind As SyntaxKind) As SyntaxToken Return SyntaxFactory.Token(kind) End Function Protected Overrides Function Assignment( assignmentOpKind As SyntaxKind, left As ExpressionSyntax, syntaxToken As SyntaxToken, right As ExpressionSyntax) As AssignmentStatementSyntax Return SyntaxFactory.AssignmentStatement(assignmentOpKind, left, syntaxToken, right) End Function Protected Overrides Function Increment(left As ExpressionSyntax) As ExpressionSyntax Throw ExceptionUtilities.Unreachable End Function Protected Overrides Function Decrement(left As ExpressionSyntax) As ExpressionSyntax Throw ExceptionUtilities.Unreachable End Function End Class End Namespace
ErikSchierboom/roslyn
src/Analyzers/VisualBasic/CodeFixes/UseCompoundAssignment/VisualBasicUseCompoundAssignmentCodeFixProvider.vb
Visual Basic
apache-2.0
1,857
' 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 Partial Friend Class BoundRangeCaseClause #If DEBUG Then Private Sub Validate() ValidateValueAndCondition(LowerBoundOpt, LowerBoundConditionOpt, BinaryOperatorKind.GreaterThanOrEqual) ValidateValueAndCondition(UpperBoundOpt, UpperBoundConditionOpt, BinaryOperatorKind.LessThanOrEqual) End Sub #End If End Class End Namespace
OmarTawfik/roslyn
src/Compilers/VisualBasic/Portable/BoundTree/BoundRangeCaseClause.vb
Visual Basic
apache-2.0
585
Imports SistFoncreagro.BussinessEntities Imports SistFoncreagro.DataAccess Public Class DetEjerPresupBL : Implements IDetEjerPresupBL Dim factoryrepository As IDetEjerPresupRepository Public Sub New() factoryrepository = New DetEjerPresupRepository End Sub Public Sub DeleteDetEjerPresup(ByVal _id As Integer) Implements IDetEjerPresupBL.DeleteDetEjerPresup factoryrepository.DeleteDetEjerPresup(_id) End Sub Public Function GetAllFromDetEjerPresup() As System.Collections.Generic.List(Of BussinessEntities.DetEjerPresup) Implements IDetEjerPresupBL.GetAllFromDetEjerPresup Return factoryrepository.GetAllFromDetEjerPresup End Function Public Function GetDetEjerPresupByIdDetEjerPresup(ByVal _id As Integer) As BussinessEntities.DetEjerPresup Implements IDetEjerPresupBL.GetDetEjerPresupByIdDetEjerPresup Return factoryrepository.GetDetEjerPresupByIdDetEjerPresup(_id) End Function Public Sub SaveDetEjerPresup(ByVal _DetEjerPresup As BussinessEntities.DetEjerPresup) Implements IDetEjerPresupBL.SaveDetEjerPresup factoryrepository.SaveDetEjerPresup(_DetEjerPresup) End Sub Public Sub SaveDetEjerPresup1(ByVal _DetEjerPresup As System.Collections.Generic.List(Of BussinessEntities.DetEjerPresup)) Implements IDetEjerPresupBL.SaveDetEjerPresup1 factoryrepository.SaveDetEjerPresup1(_DetEjerPresup) End Sub End Class
crackper/SistFoncreagro
SistFoncreagro.BussinesLogic/DetEjerPresupBL.vb
Visual Basic
mit
1,426
#Region "Microsoft.VisualBasic::fd75e5e8119765167c3223ccd89a232c, src\mzmath\ms2_math-core\Spectra\GlobalAlignment.vb" ' Author: ' ' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.) ' ' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD. ' ' ' MIT License ' ' ' Permission is hereby granted, free of charge, to any person obtaining a copy ' of this software and associated documentation files (the "Software"), to deal ' in the Software without restriction, including without limitation the rights ' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ' copies of the Software, and to permit persons to whom the Software is ' furnished to do so, subject to the following conditions: ' ' The above copyright notice and this permission notice shall be included in all ' copies or substantial portions of the Software. ' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ' SOFTWARE. ' /********************************************************************************/ ' Summaries: ' Module GlobalAlignment ' ' Properties: ppm20 ' ' Function: Align, AlignMatrix, SharedPeakCount, TopPeaks, TwoDirectionSSM ' ' ' /********************************************************************************/ #End Region Imports System.Runtime.CompilerServices Imports BioNovoGene.Analytical.MassSpectrometry.Math.Ms1 Imports Microsoft.VisualBasic.Language.Default Imports Microsoft.VisualBasic.Linq Imports Microsoft.VisualBasic.Math Imports Microsoft.VisualBasic.Math.Extensions Imports Microsoft.VisualBasic.Math.LinearAlgebra Namespace Spectra ''' <summary> ''' Global alignment of two MS/MS matrix. ''' </summary> Public Module GlobalAlignment Public ReadOnly Property ppm20 As [Default](Of Tolerance) = Tolerance.PPM(20) '''' <summary> '''' ### shared peak count '''' '''' In the matrix ``M``, ``i`` and ``j`` are positions, where ``i`` is the '''' horizontal coordinate And ``j`` Is the vertical coordinate. For Each '''' cell in the matrix, a score Is calculated (Si,j). If the two compared '''' masses are a match, Then ``C`` the cost Is equal To 0. However, If '''' the two masses are outside the designated ppm Error window, '''' then the cost Is equal to 1. '''' </summary> '''' <param name="query"></param> '''' <param name="subject"></param> '''' <returns></returns> 'Public Function NWGlobalAlign(query As LibraryMatrix, subject As LibraryMatrix, Optional tolerance As Tolerance = Nothing) As GlobalAlign(Of ms2)() ' Dim massEquals As IEquals(Of ms2) ' Dim empty As New ms2 With { ' .mz = -1, ' .intensity = -1, ' .quantity = -1 ' } ' With tolerance Or da3 ' massEquals = Function(q, s) ' Return .Assert(q.mz, s.mz) ' End Function ' End With ' With New NeedlemanWunsch(Of ms2)(query, subject, massEquals, empty, Function(ms2) ms2.ToString.First).Compute() ' Return .PopulateAlignments.ToArray ' End With 'End Function ''' <summary> ''' 取出响应度前<paramref name="top"/>个数量的质谱图碎片 ''' </summary> ''' <param name="spectra"></param> ''' <param name="top%"></param> ''' <returns></returns> ''' <MethodImpl(MethodImplOptions.AggressiveInlining)> <Extension> Public Function TopPeaks(spectra As LibraryMatrix, top%) As IEnumerable(Of ms2) Return spectra _ .OrderByDescending(Function(mz) mz.quantity) _ .Take(top) End Function ''' <summary> ''' 只计算响应度最高的前<paramref name="top"/>个二级碎片之中的相同mz的碎片数量 ''' </summary> ''' <param name="query"></param> ''' <param name="subject"></param> ''' <param name="tolerance"></param> ''' <param name="top%"></param> ''' <returns></returns> Public Function SharedPeakCount(query As LibraryMatrix, subject As LibraryMatrix, Optional tolerance As Tolerance = Nothing, Optional top% = 10) As Integer Dim q As ms2() = query.TopPeaks(top).ToArray Dim s As ms2() = subject.TopPeaks(top).ToArray With tolerance Or Tolerance.DefaultTolerance Dim share As Integer = s _ .Where(Function(mz As ms2) Dim find As ms2 = q _ .Where(Function(frag) Return .Assert(frag.mz, mz.mz) End Function) _ .FirstOrDefault Return Not find Is Nothing End Function) _ .Count Return share End With End Function ''' <summary> ''' xy分别为预测或者标准品的结果数据,无顺序之分 ''' </summary> ''' <param name="x"></param> ''' <param name="y"></param> ''' <returns></returns> ''' <MethodImpl(MethodImplOptions.AggressiveInlining)> Public Function TwoDirectionSSM(x As ms2(), y As ms2(), tolerance As Tolerance) As (forward#, reverse#) Return (GlobalAlignment.Align(x, y, tolerance), GlobalAlignment.Align(y, x, tolerance)) End Function ''' <summary> ''' 以<paramref name="ref"/>为基准,从<paramref name="query"/>之中选择出对应的<see cref="ms2.mz"/>信号响应信息,完成对齐操作 ''' </summary> ''' <param name="query"></param> ''' <param name="ref"></param> ''' <returns></returns> Public Function Align(query As ms2(), ref As ms2(), Optional tolerance As Tolerance = Nothing) As Double Dim q As Vector = query.AlignMatrix(ref, tolerance Or ppm20).Shadows!intensity Dim s As Vector = ref.Shadows!intensity Return SSM(q / q.Max, s / s.Max) End Function ''' <summary> ''' 在ref之中找不到对应的mz,则into为零 ''' </summary> ''' <param name="query"></param> ''' <param name="ref"></param> ''' <param name="tolerance"></param> ''' <returns></returns> <Extension> Public Function AlignMatrix(query As ms2(), ref As ms2(), tolerance As Tolerance) As ms2() Return ref _ .Select(Function(mz) ' 2017-10-29 ' ' 当找不到的时候,会返回一个空的structure对象,这个时候intensity为零 ' 所以在这个Linq表达式中,后面不需要使用Where来删除对象了 Dim subject = query _ .Where(Function(q) tolerance(q.mz, mz.mz)) _ .Shadows If subject.Length = 0 Then ' With single intensity ZERO Return New ms2 With { .mz = mz.mz, .intensity = 0, .quantity = 0 } Else ' 返回响应值最大的 Return subject(Which.Max(subject!intensity)) End If End Function) _ .ToArray End Function End Module End Namespace
xieguigang/spectrum
src/mzmath/ms2_math-core/Spectra/GlobalAlignment.vb
Visual Basic
mit
8,525
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My.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", "2.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.Refactoring.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/HTML5
SemanticHTMLHomework/01. Refactoring/My Project/Resources.Designer.vb
Visual Basic
mit
2,704
'------------------------------------------------------------------------------ ' <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 'NOTE: This file is auto-generated; do not modify it directly. To make changes, ' or if you encounter build errors in this file, go to the Project Designer ' (go to Project Properties or double-click the My Project node in ' Solution Explorer), and make changes on the Application tab. ' Partial Friend Class MyApplication <Global.System.Diagnostics.DebuggerStepThroughAttribute()> _ Public Sub New() MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows) Me.IsSingleInstance = false Me.EnableVisualStyles = true Me.SaveMySettingsOnExit = true Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses End Sub <Global.System.Diagnostics.DebuggerStepThroughAttribute()> _ Protected Overrides Sub OnCreateMainForm() Me.MainForm = Global.CalcPlumber.FormMainCP End Sub End Class End Namespace
SnowShock35/CalcPlumber
CalcPlumber/CalcPlumber/My Project/Application.Designer.vb
Visual Basic
mit
1,482
Imports System.Reflection Imports System.Runtime.CompilerServices 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. <Assembly: AssemblyTitle("CreateStructuralFrame")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyConfiguration("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("CreateStructuralFrame")> <Assembly: AssemblyCopyright("Copyright © 2015")> <Assembly: AssemblyTrademark("")> <Assembly: AssemblyCulture("")> ' Setting ComVisible to false makes the types in this assembly not visible ' to COM components. If you need to access a type in this assembly from ' COM, set the ComVisible attribute to true on that type. <Assembly: ComVisible(False)> ' The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("8e50d08b-8c03-40b5-81c3-3f1acf0d6e79")> ' 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")>
SolidEdgeCommunity/Samples
Assembly/CreateStructuralFrame/vb/CreateStructuralFrame/My Project/AssemblyInfo.vb
Visual Basic
mit
1,404
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class changeloghh 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() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(changeloghh)) Me.HuraForm1 = New Computer_Helper.HuraForm() Me.RichTextBox1 = New System.Windows.Forms.RichTextBox() Me.HuraButton2 = New Computer_Helper.HuraButton() Me.HuraButton1 = New Computer_Helper.HuraButton() Me.HuraForm1.SuspendLayout() Me.SuspendLayout() ' 'HuraForm1 ' Me.HuraForm1.AccentColor = System.Drawing.Color.FromArgb(CType(CType(255, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(255, Byte), Integer)) Me.HuraForm1.BackColor = System.Drawing.Color.FromArgb(CType(CType(255, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(255, Byte), Integer)) Me.HuraForm1.ColorScheme = Computer_Helper.HuraForm.ColorSchemes.Dark Me.HuraForm1.Controls.Add(Me.RichTextBox1) Me.HuraForm1.Controls.Add(Me.HuraButton2) Me.HuraForm1.Controls.Add(Me.HuraButton1) Me.HuraForm1.Dock = System.Windows.Forms.DockStyle.Fill Me.HuraForm1.Font = New System.Drawing.Font("Segoe UI", 9.5!) Me.HuraForm1.ForeColor = System.Drawing.Color.Gray Me.HuraForm1.Location = New System.Drawing.Point(0, 0) Me.HuraForm1.Name = "HuraForm1" Me.HuraForm1.Size = New System.Drawing.Size(663, 327) Me.HuraForm1.TabIndex = 0 Me.HuraForm1.Text = "Change Log" ' 'RichTextBox1 ' Me.RichTextBox1.BackColor = System.Drawing.SystemColors.Control Me.RichTextBox1.BorderStyle = System.Windows.Forms.BorderStyle.None Me.RichTextBox1.Cursor = System.Windows.Forms.Cursors.Default Me.RichTextBox1.Location = New System.Drawing.Point(12, 29) Me.RichTextBox1.Name = "RichTextBox1" Me.RichTextBox1.ReadOnly = True Me.RichTextBox1.Size = New System.Drawing.Size(639, 286) Me.RichTextBox1.TabIndex = 4 Me.RichTextBox1.Text = resources.GetString("RichTextBox1.Text") ' 'HuraButton2 ' Me.HuraButton2.BackColor = System.Drawing.Color.Transparent Me.HuraButton2.BaseColour = System.Drawing.Color.White Me.HuraButton2.BorderColour = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(170, Byte), Integer), CType(CType(220, Byte), Integer)) Me.HuraButton2.Font = New System.Drawing.Font("Segoe UI", 12.0!, System.Drawing.FontStyle.Bold) Me.HuraButton2.FontColour = System.Drawing.Color.FromArgb(CType(CType(150, Byte), Integer), CType(CType(150, Byte), Integer), CType(CType(150, Byte), Integer)) Me.HuraButton2.ForeColor = System.Drawing.Color.Black Me.HuraButton2.HoverColour = System.Drawing.Color.FromArgb(CType(CType(255, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(255, Byte), Integer)) Me.HuraButton2.Location = New System.Drawing.Point(608, 3) Me.HuraButton2.Name = "HuraButton2" Me.HuraButton2.PressedColour = System.Drawing.Color.FromArgb(CType(CType(245, Byte), Integer), CType(CType(245, Byte), Integer), CType(CType(245, Byte), Integer)) Me.HuraButton2.ProgressColour = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(191, Byte), Integer), CType(CType(255, Byte), Integer)) Me.HuraButton2.Size = New System.Drawing.Size(23, 20) Me.HuraButton2.TabIndex = 3 Me.HuraButton2.Text = "-" ' 'HuraButton1 ' Me.HuraButton1.BackColor = System.Drawing.Color.Transparent Me.HuraButton1.BaseColour = System.Drawing.Color.White Me.HuraButton1.BorderColour = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(170, Byte), Integer), CType(CType(220, Byte), Integer)) Me.HuraButton1.Font = New System.Drawing.Font("Segoe UI", 12.0!, System.Drawing.FontStyle.Bold) Me.HuraButton1.FontColour = System.Drawing.Color.FromArgb(CType(CType(150, Byte), Integer), CType(CType(150, Byte), Integer), CType(CType(150, Byte), Integer)) Me.HuraButton1.ForeColor = System.Drawing.Color.Black Me.HuraButton1.HoverColour = System.Drawing.Color.FromArgb(CType(CType(255, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(255, Byte), Integer)) Me.HuraButton1.Location = New System.Drawing.Point(637, 3) Me.HuraButton1.Name = "HuraButton1" Me.HuraButton1.PressedColour = System.Drawing.Color.FromArgb(CType(CType(245, Byte), Integer), CType(CType(245, Byte), Integer), CType(CType(245, Byte), Integer)) Me.HuraButton1.ProgressColour = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(191, Byte), Integer), CType(CType(255, Byte), Integer)) Me.HuraButton1.Size = New System.Drawing.Size(23, 20) Me.HuraButton1.TabIndex = 2 Me.HuraButton1.Text = "X" ' 'changeloghh ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(663, 327) Me.Controls.Add(Me.HuraForm1) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.Name = "changeloghh" Me.Text = "Change Log" Me.HuraForm1.ResumeLayout(False) Me.ResumeLayout(False) End Sub Friend WithEvents HuraForm1 As Computer_Helper.HuraForm Friend WithEvents HuraButton2 As Computer_Helper.HuraButton Friend WithEvents HuraButton1 As Computer_Helper.HuraButton Friend WithEvents RichTextBox1 As System.Windows.Forms.RichTextBox End Class
MJGC-Jonathan/ComputerHelper
Computer Helper/Computer Helper/changeloghh.Designer.vb
Visual Basic
mit
6,660
Imports NeuralNetwork.Activation Imports System.Xml Module NetworkOperation Public Sub loadTrainingData() 'load testing inputs Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(form_main.tb_input.Text) MyReader.TextFieldType = FileIO.FieldType.Delimited MyReader.SetDelimiters(",") ReDim TrainingMode.inputData(TrainingMode.numInputLines - 1, TrainingMode.numInputs - 1) Dim i As Integer = 0 Dim currentRow As String() While Not MyReader.EndOfData Try currentRow = MyReader.ReadFields() Dim currentField As String Dim j As Integer = 0 For Each currentField In currentRow TrainingMode.inputData(i, j) = currentField j += 1 Next i += 1 Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException MsgBox("Line " & ex.Message & "is not valid and will be skipped.") End Try End While End Using 'load expected outputs Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(form_main.tb_output.Text) MyReader.TextFieldType = FileIO.FieldType.Delimited MyReader.SetDelimiters(",") ReDim TrainingMode.expectedOutputs(TrainingMode.numOutputLines - 1, TrainingMode.expectedOutputsPerLine - 1) Dim i As Integer = 0 Dim currentRow As String() While Not MyReader.EndOfData Try currentRow = MyReader.ReadFields() Dim currentField As String Dim j As Integer = 0 For Each currentField In currentRow TrainingMode.expectedOutputs(i, j) = currentField j += 1 Next i += 1 Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException MsgBox("Line " & ex.Message & "is not valid and will be skipped.") End Try End While End Using End Sub Private Sub layerCalculate(network As BackpropagationNetwork, layerIndex As Integer) Dim currentLayer As Layer = network.Layers(layerIndex) Dim prevLayer As Layer = network.Layers(layerIndex - 1) Dim sum(currentLayer.NeuronCount - 1) As Double 'Pre-populate sums with bias values For i = 0 To currentLayer.NeuronCount - 1 sum(i) = currentLayer.Bias(i) Next 'calculate each node's sum For currentNeuronInCurrentLayer = 0 To currentLayer.NeuronCount - 1 For currentNeuronInPrevLayer = 0 To prevLayer.NeuronCount - 1 sum(currentNeuronInCurrentLayer) += prevLayer.Outputs(currentNeuronInPrevLayer) * prevLayer.Weights(currentNeuronInPrevLayer, currentNeuronInCurrentLayer) Next Next currentLayer.Inputs = sum 'calcute the function value (output) using an activation function Dim functionValue(currentLayer.NeuronCount - 1) As Double For i = 0 To currentLayer.NeuronCount - 1 functionValue(i) = ActivationFunctions.Evaluate(currentLayer.ActivationFunction, sum(i)) Next currentLayer.Outputs = functionValue End Sub Public Sub networkCalculate(networkToCalculate As BackpropagationNetwork) Dim i As Integer = 0 For Each layer In networkToCalculate.Layers If layer.LayerType = ILayer.LayerType_.Input Then 'do nothing Else layerCalculate(networkToCalculate, i) End If i += 1 Next End Sub Public Function trainNetwork(ByRef network As BackpropagationNetwork, learningRate As Double, momentum As Double) As Double Dim exampleError(numInputLines - 1) As Double For ex = 0 To numInputLines - 1 'for each example 'run the network once to get output values network.Layers(0).Outputs = Util.Array.GetRow(ex, inputData) networkCalculate(network) 'do error calculation For l = network.LayerCount - 1 To 1 Step -1 'for each layer (exept input layer), calculate the error, starting from the back Dim currentLayer As Layer = network.Layers(l) Dim prevLayer As Layer = network.Layers(l - 1) If network.Layers(l).LayerType = ILayer.LayerType_.Output Then For k = 0 To network.LastLayer.NeuronCount - 1 'for each output neuron Dim diff As Double diff = network.LastLayer.Outputs(k) - expectedOutputs(ex, k) exampleError(ex) += diff ^ 2 Dim delta_k As Double delta_k = diff * ActivationFunctions.EvaluateDerivative(network.Layers(l).ActivationFunction, network.Layers(l).Inputs(k)) 'the formula for delta_k network.Layers(l).Deltas(k) = delta_k Next Else 'hidden layer For i = 1 To network.Layers(l).NeuronCount - 1 'for each neuron in the current layer 'for each neuron in the next layer (the layer nearer to the output), calculate the delta_j_tempSum (for use in calculating delta_j) Dim delta_j_tempSum As Double = 0 For j = 0 To network.Layers(l + 1).NeuronCount - 1 delta_j_tempSum += network.Layers(l + 1).Deltas(j) * network.Layers(l).Weights(i, j) Next Dim delta_j As Double delta_j = ActivationFunctions.EvaluateDerivative(network.Layers(l).ActivationFunction, network.Layers(l).Inputs(i)) * delta_j_tempSum 'the formula for delta_j network.Layers(l).Deltas(i) = delta_j Next End If Next 'update the weights For layer = 2 To network.LayerCount - 1 'for each layer (except input layer) Dim currentLayer As Layer = network.Layers(layer) Dim prevLayer As Layer = network.Layers(layer - 1) For i = 0 To prevLayer.NeuronCount - 1 'for each neuron in the previous layer For j = 0 To currentLayer.NeuronCount - 1 'each neuron in the current layer prevLayer.WeightDeltas(i, j) = learningRate * currentLayer.Deltas(j) * prevLayer.Outputs(i) prevLayer.Weights(i, j) -= prevLayer.WeightDeltas(i, j) + momentum * prevLayer.PreviousWeightDeltas(i, j) prevLayer.PreviousWeightDeltas(i, j) = prevLayer.WeightDeltas(i, j) Next Next Next If form_main.chk_updateBias.Checked Then For layer = 1 To network.LayerCount - 1 'for each layer (except input layer) For i = 0 To network.Layers(layer).NeuronCount - 1 'each neuron in the current layer network.Layers(layer).BiasDeltas(i) = learningRate * network.Layers(layer).Deltas(i) network.Layers(layer).Bias(i) -= network.Layers(layer).BiasDeltas(i) + momentum * network.Layers(layer).PreviousBiasDeltas(i) network.Layers(layer).PreviousBiasDeltas(i) = network.Layers(layer).BiasDeltas(i) Next Next End If Next Dim exampleErrorSum As Double For i = 0 To numInputLines - 1 exampleErrorSum += exampleError(i) Next Dim MSE As Double = exampleErrorSum / numInputLines Dim RMSE As Double = Math.Sqrt(MSE) Return RMSE End Function Public Sub Save(network As BackpropagationNetwork, FilePath As String) Dim settings As New XmlWriterSettings settings.Indent = True Dim writer As XmlWriter = XmlWriter.Create(FilePath, settings) With writer .WriteComment("Backpropagation Neural Network, created " & Date.Now().ToString) .WriteStartElement("Network") .WriteStartElement("Network-Parameters") .WriteElementString("numInputs", numInputs.ToString) .WriteElementString("LayerCount", network.LayerCount.ToString) .WriteElementString("numOutputs", numOutputs.ToString) .WriteStartElement("Layers") Dim l As Integer = 0 For Each layer As Layer In network.Layers .WriteStartElement("Layer") .WriteAttributeString("Index", l.ToString) .WriteAttributeString("NeuronCount", layer.NeuronCount.ToString) .WriteAttributeString("Type", layer.LayerType.ToString) .WriteAttributeString("ActivationFunction", layer.ActivationFunction.ToString) .WriteEndElement() 'Layer l += 1 Next .WriteEndElement() 'Layers .WriteEndElement() 'Network-Parameters ' Weights and biases .WriteStartElement("Weights-and-Biases") For layer = 0 To network.LayerCount - 1 'for each layer Dim currentLayer As Layer = network.Layers(layer) .WriteStartElement("Layer") .WriteAttributeString("Index", layer.ToString) For i = 0 To currentLayer.NeuronCount - 1 .WriteStartElement("Neuron") .WriteAttributeString("Index", i.ToString) .WriteAttributeString("Bias", currentLayer.Bias(i).ToString) If layer = network.LayerCount - 1 Then 'then we are at the output layer - it has no weights saved, so skip to prevent NPE 'do nothing Else Dim nextLayer As Layer = network.Layers(layer + 1) For j = 0 To nextLayer.NeuronCount - 1 .WriteStartElement("Connection") .WriteAttributeString("Index", j.ToString) .WriteString(currentLayer.Weights(i, j).ToString()) .WriteEndElement() 'Connection Next End If .WriteEndElement() 'Neuron Next .WriteEndElement() 'layer Next .WriteEndElement() 'Weights-and-Biases .WriteEndElement() 'Network .Close() End With End Sub Private doc As XmlDocument = Nothing Public Function Load(ByRef network As BackpropagationNetwork, FilePath As String) As Boolean On Error GoTo ErrorCode If FilePath = Nothing Then Return False End If doc = New XmlDocument doc.Load(FilePath) Dim BasePath As String, numLayers As Integer, NeuronPath As String BasePath = "Network/Network-Parameters/" numLayers = CInt(xPathValue(BasePath & "LayerCount")) BasePath &= "Layers/Layer" 'create layers For l = 0 To numLayers - 1 Dim neuronCount As Integer = CInt(xPathValue((BasePath & "[@Index='") + l.ToString() + "']/@NeuronCount")) Dim activationFunction As ActivationFunction = [Enum].Parse(GetType(ActivationFunction), xPathValue((BasePath & "[@Index='") + l.ToString() + "']/@ActivationFunction")) Dim layerType As ILayer.LayerType_ = [Enum].Parse(GetType(ILayer.LayerType_), xPathValue((BasePath & "[@Index='") + l.ToString() + "']/@Type")) network.AddLayer(New Layer(neuronCount, activationFunction, layerType)) Next 'assign weights and biases 'first assign random values and then re-assign new values (lazy). This avoids the NRE. Dim i As Integer = 0 For Each layer As Layer In network.Layers If layer.LayerType = ILayer.LayerType_.Output Then Exit For End If layer.GenerateWeights(network, i) i += 1 Next For Each layer As Layer In network.Layers layer.GenerateBias(network) Next 'now assign new values For layer = 0 To network.LayerCount - 1 'for each layer BasePath = "Network/Weights-and-Biases/Layer[@Index='" & layer.ToString & "']/" Dim currentLayer As Layer = network.Layers(layer) For i = 0 To currentLayer.NeuronCount - 1 NeuronPath = "Neuron[@Index='" + i.ToString + "']/@Bias" currentLayer.Bias(i) = CDbl(xPathValue(BasePath & NeuronPath)) If layer = network.LayerCount - 1 Then 'then we are at the output layer - it has no weights saved, so skip to prevent error 'do nothing Else Dim nextLayer As Layer = network.Layers(layer + 1) For j = 0 To nextLayer.NeuronCount - 1 Dim connectionPath As String connectionPath = "Neuron[@Index='" + i.ToString + "']/Connection[@Index='" + j.ToString + "']" currentLayer.Weights(i, j) = CDbl(xPathValue(BasePath & connectionPath)) Next End If Next Next doc = Nothing Return True ErrorCode: Return False End Function Private Function xPathValue(xPath As String) As String Dim node As XmlNode = doc.SelectSingleNode(xPath) If node Is Nothing Then Throw New ArgumentException("Cannot find specified node", xPath) End If Return node.InnerText End Function End Module
Mierzen/Neural-Network
Neural Network/NetworkOperation.vb
Visual Basic
mit
13,977
<Serializable()> Public Class OscopeMeas Private _numFunctions As Integer = 2 Private _pathLossFile(_numFunctions - 1) As String Private _antennaFactorFile(_numFunctions - 1) As String Private _name As String Private _sampleRate As Double Private _sampleRateUnits As String Private _memoryDepth As Double Private _memoryDepthUnits As String Private _timePerDivision As Double Private _timePerDivisionUnits As String Private _replayDelayMs As String Private _maxOscopeMiss As Integer = 50 Private _oscopeMission(_maxOscopeMiss - 1) As OscopeMiss Private _measState(_maxOscopeMiss - 1) As MeasState Property GetMeasState() As MeasState() Get Return _measState End Get Set(ByVal value As MeasState()) _measState = Value End Set End Property Property GetOscopeMission() As OscopeMiss() Get Return _oscopeMission End Get Set(ByVal value As OscopeMiss()) _oscopeMission = Value End Set End Property 'Private OscopeMission As New OscopeMission 'Property getOscopeMission() As OscopeMission ' Get ' Return OscopeMission ' End Get ' Set(ByVal Value As OscopeMission) ' OscopeMission = Value ' End Set 'End Property Property GetPathLossFile() As String() Get Return _pathLossFile End Get Set(ByVal value As String()) _pathLossFile = Value End Set End Property Property GetAntennaFactorFile() As String() Get Return _antennaFactorFile End Get Set(ByVal value As String()) _antennaFactorFile = Value End Set End Property Property GetName() As String Get Return _name End Get Set(ByVal value As String) _name = Value End Set End Property Property GetsampleRate() As Double Get Return _sampleRate End Get Set(ByVal value As Double) _sampleRate = Value End Set End Property Property GetsampleRateUnits() As String Get Return _sampleRateUnits End Get Set(ByVal value As String) _sampleRateUnits = Value End Set End Property Property GetmemoryDepth() As Double Get Return _memoryDepth End Get Set(ByVal value As Double) _memoryDepth = Value End Set End Property Property GetmemoryDepthUnits() As String Get Return _memoryDepthUnits End Get Set(ByVal value As String) _memoryDepthUnits = Value End Set End Property Property GettimePerDivision() As Double Get Return _timePerDivision End Get Set(ByVal value As Double) _timePerDivision = Value End Set End Property Property GettimePerDivisionUnits() As String Get Return _timePerDivisionUnits End Get Set(ByVal value As String) _timePerDivisionUnits = Value End Set End Property Property GetreplayDelayMs() As String Get Return _replayDelayMs End Get Set(ByVal value As String) _replayDelayMs = Value End Set End Property End Class
wboxx1/85-EIS-PUMA
puma/src/Supporting Objects/OscopeMeas.vb
Visual Basic
mit
3,470
Imports Com.Aspose.OCR.Api Imports Com.Aspose.OCR.Model Namespace ExtractingManagingOCR.CloudStorage Class ExtractOCRorHOCRTextFromURLImage Public Shared Sub Run() 'ExStart:1 'Instantiate Aspose OCR Cloud API SDK Dim ocrApi As New OcrApi(Common.APP_KEY, Common.APP_SID, Common.BASEPATH) 'Set the image file name Dim name As [String] = "Sampleocr.bmp" 'Set the image file url. Dim url As [String] = "https://dl.dropboxusercontent.com/s/zj35mqdouoxy3rs/Sampleocr.bmp" 'Set the language of the document. Dim language As [String] = "English" 'Set the spelling correction is used. Dim useDefaultDictionaries As [Boolean] = True 'Set the local file (if any) Dim file As Byte() = Nothing Try 'invoke Aspose.OCR Cloud SDK API to extract image text from url Dim apiResponse As OCRResponse = ocrApi.PostOcrFromUrlOrContent(url, language, useDefaultDictionaries, file) If apiResponse IsNot Nothing Then 'download generated barcode from cloud storage Console.WriteLine("Text :: " + apiResponse.Text) Console.WriteLine("Extract OCR or HOCR Text from Image URL, 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.OCR-for-Cloud
Examples/DotNET/VisualBasic/ExtractingManagingOCR/WithoutCloudStorage/ExtractOCRorHOCRTextFromURLImage.vb
Visual Basic
mit
1,587
'*******************************************************************************************' ' ' ' 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 Bytescout.BarCode Module Module1 Sub Main() ' Create and activate barcode generator instance Using barcode As New Barcode("demo", "demo") ' Set barcode type barcode.Symbology = SymbologyType.QRCode ' Inputs Dim inpEmail = New QrCodeMessageTemplate With { .Message = "Here goes sample message...!" } ' Set barcode value barcode.Value = inpEmail.ToString() ' Save generated barcode barcode.SaveImage("result.png") ' Open generated barcode image with associated application Process.Start("result.png") End Using End Sub End Module
bytescout/ByteScout-SDK-SourceCode
BarCode SDK/VB.NET/QR Code With Message/Module1.vb
Visual Basic
apache-2.0
1,698
' The variable referenced in this property is defined in the CSLAHelper20.vb file <Category(" General Options - Business Object"), _ Description("The prefix for the member variables.")> _ Public Property MemberPrefix() As String Get Return m_MemberPrefix End Get Set(ByVal Value As String) m_MemberPrefix = Value End Set End Property ' The variable referenced in this property is defined in the CSLAHelper20.vb file <Category(" General Options - Business Object"), _ Description("Namespace.")> _ Public Property ObjectNameSpace() As String Get Return m_NameSpace End Get Set(ByVal Value As String) m_NameSpace = Value End Set End Property ' The variable referenced in this property is defined in the CSLAHelper20.vb file <Category(" General Options - Business Object"), _ Description("Camel-case member variables.")> _ Public Property CamelCaseMemberVars() As Boolean Get Return m_CamelCaseMemberVars End Get Set(ByVal Value As Boolean) m_CamelCaseMemberVars = Value End Set End Property ' The variable referenced in this property is defined in the CSLAHelper20.vb file <Category(" General Options - Business Object"), _ Description("Use SmartDate instead of Date.")> _ Public Property UseSmartDate() As Boolean Get Return m_UseSmartDate End Get Set(ByVal Value As Boolean) m_UseSmartDate = Value End Set End Property ' ' The variable referenced in this property is defined in the CSLAHelper20.vb file ' <Category(" General Options - Business Object"), _ ' Description("Business object reacts to non-zero return values from stored procedures.")> _ ' Public Property UseSP_ReturnValue() As Boolean ' Get ' Return m_UseSP_ReturnValue ' End Get ' Set(ByVal Value As Boolean) ' m_UseSP_ReturnValue = Value ' End Set ' End Property ' The variable referenced in this property is defined in the CSLAHelper20.vb file <Category(" General Options - Business Object"), _ Description("Generate Business Object Class.")> _ Public Property Generate_Class() As Boolean Get Return m_GenClass End Get Set(ByVal Value As Boolean) m_GenClass = Value End Set End Property ' ' The variable referenced in this property is defined in the CSLAHelper20.vb file ' <Category(" General Options - Business Object"), _ ' Description("Create an Exists method within the Business Object.")> _ ' Public Property Implement_Exists() As Boolean ' Get ' Return m_Implement_Exists ' End Get ' Set(ByVal Value As Boolean) ' m_Implement_Exists = Value ' End Set ' End Property ' The variable referenced in this property is defined in the CSLAHelper20.vb file <Category(" General Options - Business Object"), _ Description("Allow anonymous access when no access controls exist.")> _ Public Property AnonymousAccess() As Boolean Get Return m_AnonymousAccess End Get Set(ByVal Value As Boolean) m_AnonymousAccess = Value End Set End Property ' The variable referenced in this property is defined in the CSLAHelper20.vb file <Category(" General Options - Business Object"), _ Description("Add comments to generated code.")> _ Public Property AddComments() As Boolean Get Return m_AddComments End Get Set(ByVal Value As Boolean) m_AddComments = Value End Set End Property
MarimerLLC/cslacontrib
branches/2010.11.001/CodeGenTemplates/CodeSmith/CSLAExpress/VB/Properties/GeneralOptionsObject/BasicOptionsObject.vb
Visual Basic
mit
3,583
'*******************************************************************************************' ' ' ' 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.Diagnostics Imports System.Drawing Imports System.IO Imports Bytescout.Spreadsheet Class Program Friend Shared Sub Main(args As String()) ' Create new spreadsheet (or open existing) Dim doc As New Spreadsheet() doc.RegistrationName = "demo" doc.RegistrationKey = "demo" ' Add worksheet Dim worksheet As Worksheet = doc.Worksheets.Add() ' Put background image on the worksheet worksheet.BackgroundPicture = Image.FromFile("image1.jpg") ' Save document doc.SaveAs("output.xls") ' Close spreadsheet doc.Close() ' Open generated XLS document in default application Process.Start("output.xls") doc.Dispose() End Sub End Class
bytescout/ByteScout-SDK-SourceCode
Spreadsheet SDK/VB.NET/Add Background Image/Program.vb
Visual Basic
apache-2.0
1,761
' 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 Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Emit.NoPia Friend NotInheritable Class EmbeddedParameter Inherits EmbeddedTypesManager.CommonEmbeddedParameter Public Sub New(containingPropertyOrMethod As EmbeddedTypesManager.CommonEmbeddedMember, underlyingParameter As ParameterSymbol) MyBase.New(containingPropertyOrMethod, underlyingParameter) Debug.Assert(underlyingParameter.IsDefinition) End Sub Protected Overrides Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState) As IEnumerable(Of VisualBasicAttributeData) Return UnderlyingParameter.GetCustomAttributesToEmit(compilationState) End Function Protected Overrides ReadOnly Property HasDefaultValue As Boolean Get Return UnderlyingParameter.HasMetadataConstantValue End Get End Property Protected Overrides Function GetDefaultValue(context As EmitContext) As MetadataConstant Return UnderlyingParameter.GetMetadataConstantValue(context) End Function Protected Overrides ReadOnly Property IsIn As Boolean Get Return UnderlyingParameter.IsMetadataIn End Get End Property Protected Overrides ReadOnly Property IsOut As Boolean Get Return UnderlyingParameter.IsMetadataOut End Get End Property Protected Overrides ReadOnly Property IsOptional As Boolean Get Return UnderlyingParameter.IsMetadataOptional End Get End Property Protected Overrides ReadOnly Property IsMarshalledExplicitly As Boolean Get Return UnderlyingParameter.IsMarshalledExplicitly End Get End Property Protected Overrides ReadOnly Property MarshallingInformation As Cci.IMarshallingInformation Get Return UnderlyingParameter.MarshallingInformation End Get End Property Protected Overrides ReadOnly Property MarshallingDescriptor As ImmutableArray(Of Byte) Get Return UnderlyingParameter.MarshallingDescriptor End Get End Property Protected Overrides ReadOnly Property Name As String Get Return UnderlyingParameter.MetadataName End Get End Property Protected Overrides ReadOnly Property UnderlyingParameterTypeInformation As Cci.IParameterTypeInformation Get Return DirectCast(UnderlyingParameter, Cci.IParameterTypeInformation) End Get End Property Protected Overrides ReadOnly Property Index As UShort Get Return CUShort(UnderlyingParameter.Ordinal) End Get End Property End Class End Namespace
amcasey/roslyn
src/Compilers/VisualBasic/Portable/Emit/NoPia/EmbeddedParameter.vb
Visual Basic
apache-2.0
3,259
' 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.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports VB = Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class ForeachTest : Inherits BasicTestBase <Fact> Public Sub SimpleForeachTest() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="SimpleForeachTest"> <file name="a.vb"> Imports System Class C Shared Sub Main() Dim arr As String() = New String(1) {} arr(0) = "one" arr(1) = "two" For Each s As String In arr Console.WriteLine(s) Next End Sub End Class </file> </compilation>, OutputKind.ConsoleApplication) SemanticInfoTypeTestForeach(compilation1, 1, "String()", "String()") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="s", ReadInsideSymbol:="arr, s", ReadOutsideSymbol:="arr", WrittenInsideSymbol:="s", WrittenOutsideSymbol:="arr", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="arr", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub ' Narrowing conversions from the elements in group to element are evaluated and performed at run time <Fact> Public Sub NarrowConversions() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="NarrowConversions"> <file name="a.vb"> Option Strict On Imports System Class C Shared Sub Main() For Each number As Integer In New Long() {45, 3} Console.WriteLine(number) Next End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Long()", "Long()") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="number", ReadInsideSymbol:="number", ReadOutsideSymbol:="", WrittenInsideSymbol:="number", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) Dim verifyItem As ForEachStatementInfo = Me.VerifyForeachSemanticInfo(compilation1, 1) Assert.Equal("Public Overloads Function GetEnumerator() As System.Collections.IEnumerator", verifyItem.GetEnumeratorMethod.ToString) Assert.Equal("Function MoveNext() As Boolean", verifyItem.MoveNextMethod.ToString) Assert.Equal("ReadOnly Property Current As Object", verifyItem.CurrentProperty.ToString) Assert.Equal("Sub Dispose()", verifyItem.DisposeMethod.ToString) End Sub ' Narrowing conversions from the elements in group to element are evaluated and performed at run time <Fact> Public Sub NarrowConversions_2() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="NarrowConversions"> <file name="a.vb"> Option Strict On Imports System Class C Shared Sub Main() For Each number As Integer In New Long() {9876543210} Console.WriteLine(number) Next End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Long()", "Long()") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="number", ReadInsideSymbol:="number", ReadOutsideSymbol:="", WrittenInsideSymbol:="number", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub ' Using the iteration variable in the collection expression <WorkItem(542234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542234")> <Fact> Public Sub IterationVarInCollectionExpression() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="IterationVarInCollectionExpression"> <file name="a.vb"> Option Infer On Class C Shared Sub Main() For Each x As S In If(True, x, 1) Next End Sub End Class Public Structure S End Structure </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Object", "System.Collections.IEnumerable") GetDeclareSymbolTestForeach(compilation1, Nothing) AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x", ReadInsideSymbol:="x", ReadOutsideSymbol:="", WrittenInsideSymbol:="x", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) Me.ClassfiConversionTestForeach(compilation1, 1) Dim verifyItem As ForEachStatementInfo = Me.VerifyForeachSemanticInfo(compilation1, 1) Assert.Equal("Function GetEnumerator() As System.Collections.IEnumerator", verifyItem.GetEnumeratorMethod.ToString) Assert.Equal("Function MoveNext() As Boolean", verifyItem.MoveNextMethod.ToString) Assert.Equal("ReadOnly Property Current As Object", verifyItem.CurrentProperty.ToString) Assert.Equal("Sub Dispose()", verifyItem.DisposeMethod.ToString) End Sub ' Using the iteration variable in the collection expression <Fact> Public Sub IterationVarInCollectionExpression_1() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="IterationVarInCollectionExpression"> <file name="a.vb"> Class C Public Shared Sub Main() For Each x As Integer In New Integer() {x + 5, x + 6, x + 7} System.Console.WriteLine(x) Next End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Integer()", "Integer()") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x", ReadInsideSymbol:="x", ReadOutsideSymbol:="", WrittenInsideSymbol:="x", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub ' Traversing items in 'Nothing' <Fact> Public Sub TraversingNothingStrictOn() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="TraversingNothing"> <file name="a.vb"> Option Infer Off Option Strict On Class C Shared Sub Main() For Each item In Nothing Next End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "<nothing>", "Object") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="", ReadInsideSymbol:="", ReadOutsideSymbol:="", WrittenInsideSymbol:="", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub ' Traversing items in 'Nothing' <Fact()> Public Sub TraversingNothingStrictOff() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="TraversingNothing"> <file name="a.vb"> Option Strict Off Class C Shared Sub Main() For Each item In Nothing Next End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "<nothing>", "System.Collections.IEnumerable") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="item", ReadInsideSymbol:="", ReadOutsideSymbol:="", WrittenInsideSymbol:="item", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) Dim verifyItem = VerifyForeachSemanticInfo(compilation1) Assert.NotNull(verifyItem.GetEnumeratorMethod) Assert.NotNull(verifyItem.MoveNextMethod) Assert.NotNull(verifyItem.CurrentProperty) Assert.NotNull(verifyItem.DisposeMethod) End Sub ' Nested ForEach can use a var declared in the outer ForEach <WorkItem(542080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542080")> <WorkItem(542234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542234")> <Fact> Public Sub NestedForeach() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="NestedForeach"> <file name="a.vb"> Class C Shared Sub Main() Dim c(3)() As Integer For Each x As Integer() In c ReDim x(3) For i As Integer = 0 To 3 x(i) = i Next For Each y As Integer In x System.Console.WriteLine (y) Next Next End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Integer()()", "Integer()()") GetDeclareSymbolTestForeach(compilation1, Nothing) AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="i, x, y", ReadInsideSymbol:="c, i, x, y", ReadOutsideSymbol:="", WrittenInsideSymbol:="i, x, y", WrittenOutsideSymbol:="c", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="c", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) SemanticInfoTypeTestForeach(compilation1, 2, "Integer()", "Integer()") GetDeclareSymbolTestForeach(compilation1, Nothing, 2) AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="y", ReadInsideSymbol:="x, y", ReadOutsideSymbol:="c, i, x", WrittenInsideSymbol:="y", WrittenOutsideSymbol:="c, i, x", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="x", DataFlowsOutSymbol:="", index:=2) AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True, index:=2) ClassfiConversionTestForeach(compilation1, 2) VerifyForeachSemanticInfo(compilation1, 2) End Sub ' Inner foreach loop referencing the outer foreach loop iteration variable <WorkItem(542080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542080")> <Fact> Public Sub NestedForeach_1() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="NestedForeach_1"> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x System.Console.WriteLine(y) Next Next End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "String()", "String()") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x, y", ReadInsideSymbol:="S, x, y", ReadOutsideSymbol:="", WrittenInsideSymbol:="x, y", WrittenOutsideSymbol:="S", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="S", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) SemanticInfoTypeTestForeach(compilation1, 2, "String", "String") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="y", ReadInsideSymbol:="x, y", ReadOutsideSymbol:="S", WrittenInsideSymbol:="y", WrittenOutsideSymbol:="S, x", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="x", DataFlowsOutSymbol:="", index:=2) AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True, index:=2) ClassfiConversionTestForeach(compilation1, 2) VerifyForeachSemanticInfo(compilation1, 2) End Sub ' Breaking from nested Loops <Fact> Public Sub BreakFromForeach() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="BreakFromForeach"> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x If y = "B"c Then Exit For Else System.Console.WriteLine(y) End If Next Next End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "String()", "String()") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x, y", ReadInsideSymbol:="S, x, y", ReadOutsideSymbol:="", WrittenInsideSymbol:="x, y", WrittenOutsideSymbol:="S", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="S", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) SemanticInfoTypeTestForeach(compilation1, 2, "String", "String") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="y", ReadInsideSymbol:="x, y", ReadOutsideSymbol:="S", WrittenInsideSymbol:="y", WrittenOutsideSymbol:="S, x", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="x", DataFlowsOutSymbol:="", index:=2) AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True, index:=2) ClassfiConversionTestForeach(compilation1, 2) VerifyForeachSemanticInfo(compilation1, 2) End Sub ' Continuing for nested Loops <WorkItem(542234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542234")> <Fact> Public Sub ContinueInForeach() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="ContinueInForeach"> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x If y = "B"c Then Continue For End If System.Console.WriteLine(y) Next y Next x End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "String()", "String()") GetDeclareSymbolTestForeach(compilation1, Nothing) AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x, y", ReadInsideSymbol:="S, x, y", ReadOutsideSymbol:="", WrittenInsideSymbol:="x, y", WrittenOutsideSymbol:="S", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="S", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) SemanticInfoTypeTestForeach(compilation1, 2, "String", "String") GetDeclareSymbolTestForeach(compilation1, Nothing, 2) AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="y", ReadInsideSymbol:="x, y", ReadOutsideSymbol:="S", WrittenInsideSymbol:="y", WrittenOutsideSymbol:="S, x", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="x", DataFlowsOutSymbol:="", index:=2) AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True, index:=2) ClassfiConversionTestForeach(compilation1, 2) VerifyForeachSemanticInfo(compilation1, 2) End Sub ' Query expression works in foreach <Fact()> Public Sub QueryExpressionInForeach() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="QueryExpressionInForeach"> <file name="a.vb"> Imports System Imports System.Linq Option Infer On Class C Public Shared Sub Main() For Each x In From w In New Integer() {1, 2, 3} Select z = w.ToString() System.Console.WriteLine(x.ToLower()) Next End Sub End Class </file> </compilation>, references:={TestBase.LinqAssemblyRef}) SemanticInfoTypeTestForeach(compilation1, 1, "System.Collections.Generic.IEnumerable(Of String)", "System.Collections.Generic.IEnumerable(Of String)") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="w, x, z", ReadInsideSymbol:="w, x", ReadOutsideSymbol:="", WrittenInsideSymbol:="w, x, z", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub ' No confusion in a foreach statement when from is a value type <Fact> Public Sub ReDimFrom() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="ReDimFrom"> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim src = New System.Collections.ArrayList() src.Add(New from(1)) For Each x As from In src System.Console.WriteLine(x.X) Next End Sub End Class Public Structure from Dim X As Integer Public Sub New(x as Integer) X = x End Sub End Structure </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "System.Collections.ArrayList", "System.Collections.ArrayList") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x", ReadInsideSymbol:="src, x", ReadOutsideSymbol:="src", WrittenInsideSymbol:="x", WrittenOutsideSymbol:="src", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="src", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub <Fact> Public Sub BC30302ERR_TypeCharWithType1() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation> <file name="c.vb"> Option Infer On Class C Shared Sub Main() For Each x% In New Integer() {1, 1} Next For Each x&amp; In New Long() {1, 1} Next For Each x! In New Double() {1, 1} Next For Each x# In New Double() {1, 1} Next For Each x@ In New Decimal() {1, 1} Next 'COMPILEERROR: BC30302 For Each x% As Long In New Long() {1, 1, 1} Next For Each x# As Single In New Double() {1, 1, 1} Next For Each x@ As Decimal In New Decimal() {1, 1, 1} Next For Each x! As Object In New Long() {1, 1, 1} Next End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Integer()", "Integer()") SemanticInfoTypeTestForeach(compilation1, 2, "Long()", "Long()") SemanticInfoTypeTestForeach(compilation1, 3, "Double()", "Double()") SemanticInfoTypeTestForeach(compilation1, 4, "Double()", "Double()") SemanticInfoTypeTestForeach(compilation1, 5, "Decimal()", "Decimal()") SemanticInfoTypeTestForeach(compilation1, 6, "Long()", "Long()") SemanticInfoTypeTestForeach(compilation1, 7, "Double()", "Double()") SemanticInfoTypeTestForeach(compilation1, 8, "Decimal()", "Decimal()") SemanticInfoTypeTestForeach(compilation1, 9, "Long()", "Long()") For i As Integer = 1 To 9 AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x", ReadInsideSymbol:="", ReadOutsideSymbol:="", WrittenInsideSymbol:="x", WrittenOutsideSymbol:="x, x, x, x, x, x, x, x", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="", index:=i) AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True, index:=i) ClassfiConversionTestForeach(compilation1, i) VerifyForeachSemanticInfo(compilation1, i) Next End Sub <Fact> Public Sub BC30039ERR_LoopControlMustNotBeProperty() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="LoopControlMustNotBeProperty"> <file name="a.vb"> Option Infer On Imports System Class C Inherits B Property P() As Integer Shadows F As Integer Sub Method1(A As Integer, ByRef B As Integer) ' error For Each P In new Integer(){1} Next ' warning For Each F In Integer(){2} Next For Each Me.F In Integer(){3} Next For Each MyBase.F In {4} Next For Each A In {5} Next For Each B In {6} Next End Sub Shared Sub Main() End Sub End Class Class B Public F As Integer End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Integer()", "Integer()") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="", ReadInsideSymbol:="Me", ReadOutsideSymbol:="B, Me", WrittenInsideSymbol:="", WrittenOutsideSymbol:="A, B, Me", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="Me", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub <Fact> Public Sub BC30277ERR_TypecharNoMatch2_2() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="TypecharNoMatch2"> <file name="a.vb"> Class C Public Shared Sub Main() 'declare with explicit type, use in next with a type char") For Each x As Integer In New Integer() {1, 1, 1} 'COMPILEERROR: BC30277, "x#" Next x# For Each [me] As Integer In New Integer() {1, 1, 1} Next me% End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Integer()", "Integer()") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x", ReadInsideSymbol:="", ReadOutsideSymbol:="", WrittenInsideSymbol:="x", WrittenOutsideSymbol:="me", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) SemanticInfoTypeTestForeach(compilation1, 2, "Integer()", "Integer()") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="me", ReadInsideSymbol:="", ReadOutsideSymbol:="", WrittenInsideSymbol:="me", WrittenOutsideSymbol:="x", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="", index:=2) AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True, index:=2) ClassfiConversionTestForeach(compilation1, 2) VerifyForeachSemanticInfo(compilation1, 2) End Sub <Fact> Public Sub BC30288ERR_DuplicateLocals1_1() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="DuplicateLocals1"> <file name="a.vb"> Class C Shared Sub Main() For Each x As Integer In New Integer() {1, 2, 3} Dim x As Integer Next End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Integer()", "Integer()") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x, x", ReadInsideSymbol:="", ReadOutsideSymbol:="", WrittenInsideSymbol:="x", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub <WorkItem(542234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542234")> <Fact> Public Sub BC30290ERR_LocalSameAsFunc_1() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="LocalSameAsFunc"> <file name="a.vb"> Class C Shared Sub Main() End Sub Function goo() 'COMPILEERROR: BC30290, For Each goo As Integer In New Integer() {1, 2, 3} Next End Function Sub goo1() For Each goo1 As Integer In New Integer() {1, 2, 3} Next End SUB End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Integer()", "Integer()") GetDeclareSymbolTestForeach(compilation1, Nothing) AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="goo", ReadInsideSymbol:="", ReadOutsideSymbol:="", WrittenInsideSymbol:="goo", WrittenOutsideSymbol:="Me", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) SemanticInfoTypeTestForeach(compilation1, 2, "Integer()", "Integer()") GetDeclareSymbolTestForeach(compilation1, Nothing, 2) AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="goo1", ReadInsideSymbol:="", ReadOutsideSymbol:="", WrittenInsideSymbol:="goo1", WrittenOutsideSymbol:="Me", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="", index:=2) AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True, index:=2) ClassfiConversionTestForeach(compilation1, 2) VerifyForeachSemanticInfo(compilation1, 2) End Sub <Fact> Public Sub BC30311ERR_TypeMismatch2_1() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Sub Main() For Each x As Integer In New Exception() {Nothing, Nothing} Next End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Exception()", "Exception()") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x", ReadInsideSymbol:="", ReadOutsideSymbol:="", WrittenInsideSymbol:="x", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub <Fact> Public Sub BC30311ERR_TypeMismatch2_2() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim numbers2D As Integer()() = New Integer()() {New Integer() {1, 2}, New Integer() {1, 2}} For Each x As Integer In numbers2D System.Console.Write("{0} ", x) Next End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Integer()()", "Integer()()") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x", ReadInsideSymbol:="numbers2D, x", ReadOutsideSymbol:="", WrittenInsideSymbol:="x", WrittenOutsideSymbol:="numbers2D", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="numbers2D", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub <Fact> Public Sub BC30369ERR_BadInstanceMemberAccess_3() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Sub Main() For Each x As Integer In F(x) Next End Sub Private Sub F(x As Integer) End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Void", "Void") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x", ReadInsideSymbol:="x", ReadOutsideSymbol:="", WrittenInsideSymbol:="x", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub <Fact> Public Sub BC30369ERR_BadInstanceMemberAccess_4() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Shared Sub Main() For Each x As Integer In F(x) Next End Sub Private Function F(x As Integer) As Object Return New Object() End Function End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Object", "Object") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x", ReadInsideSymbol:="x", ReadOutsideSymbol:="", WrittenInsideSymbol:="x", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub <WorkItem(542083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542083")> <Fact> Public Sub BC30369ERR_BadInstanceMemberAccess_5() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Property P1(ByVal x As Integer) As integer Get Return x +5 End Get Set(ByVal Value As integer) End Set End Property Public Shared Sub Main() For Each x As integer In New integer() {P1(x), P1(x), P1(x)} Next End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Integer()", "Integer()") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x", ReadInsideSymbol:="x", ReadOutsideSymbol:="", WrittenInsideSymbol:="x", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub <Fact> Public Sub BC30369ERR_BadInstanceMemberAccess_6() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() For Each x As Integer In New Integer() {goo(x), goo(x), goo(x)} Next End Sub Function goo(ByRef x As Integer) As Integer x = 10 Return x + 10 End Function End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Integer()", "Integer()") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x", ReadInsideSymbol:="x", ReadOutsideSymbol:="", WrittenInsideSymbol:="x", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub <Fact> Public Sub BC30532ERR_DateToDoubleConversion_1() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="DateToDoubleConversion"> <file name="a.vb"> Imports System Class C Shared Sub Main() For Each x As Double In New Date() {#12:00:00 AM#} Next End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Date()", "Date()") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x", ReadInsideSymbol:="", ReadOutsideSymbol:="", WrittenInsideSymbol:="x", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub <WorkItem(542234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542234")> <Fact()> Public Sub BC32006ERR_CharToIntegralTypeMismatch1_1() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="CharToIntegralTypeMismatch1"> <file name="a.vb"> Imports System Imports System.Linq Class C Shared Sub Main() For Each x As Integer In From c In "abc" Select c Next End Sub End Class Public Structure S End Structure </file> </compilation>, references:={TestBase.LinqAssemblyRef}) SemanticInfoTypeTestForeach(compilation1, 1, "System.Collections.Generic.IEnumerable(Of Char)", "System.Collections.Generic.IEnumerable(Of Char)") GetDeclareSymbolTestForeach(compilation1, Nothing) AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="c, c, x", ReadInsideSymbol:="c", ReadOutsideSymbol:="", WrittenInsideSymbol:="c, c, x", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub <Fact> Public Sub BC32023ERR_ForEachCollectionDesignPattern1_1() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="ForEachCollectionDesignPattern1"> <file name="a.vb"> Class C Shared Sub Main() For Each x As Integer In If(x, x, x) Next End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "Integer", "Integer") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="x", ReadInsideSymbol:="x", ReadOutsideSymbol:="", WrittenInsideSymbol:="x", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub <WorkItem(542234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542234")> <Fact> Public Sub VarDeclOutOfForeach() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="VarDeclOutOfForeach"> <file name="a.vb"> Option Strict On Option Infer On Public Class MyClass1 Public Shared Sub Main() Dim z As String For Each z In "" Next End Sub End Class </file> </compilation>) SemanticInfoTypeTestForeach(compilation1, 1, "String", "String") GetDeclareSymbolTestForeach(compilation1, Nothing) AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="", ReadInsideSymbol:="", ReadOutsideSymbol:="", WrittenInsideSymbol:="z", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub ' No confusion in a foreach statement when from is a value type <WorkItem(542081, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542081")> <Fact> Public Sub LambdaAsIteration() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="LambdaAsIteration"> <file name="a.vb"> Imports System Class C Public Shared Sub Main() Dim x As Action For Each x In New Action() {Sub() Console.WriteLine("hello")} x.Invoke() Next End Sub End Class </file> </compilation>) compilation1.VerifyDiagnostics() SemanticInfoTypeTestForeach(compilation1, 1, "System.Action()", "System.Action()") AnalyzeRegionDataFlowTestForeach(compilation1, VariablesDeclaredSymbol:="", ReadInsideSymbol:="x", ReadOutsideSymbol:="", WrittenInsideSymbol:="x", WrittenOutsideSymbol:="", AlwaysAssignedSymbol:="", DataFlowsInSymbol:="", DataFlowsOutSymbol:="") AnalyzeRegionControlFlowTestForeach(compilation1, EntryPoints:=0, ExitPoints:=0, EndPointIsReachable:=True) ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub <Fact> Public Sub CollectionHasNoDifferentConvertedTypeForDesignPatternMatch() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="CollectionHasConvertedType"> <file name="a.vb"> Option Strict On Option Infer On Imports System Imports System.Collections Public Class SomethingEnumerable Implements IEnumerable Public Function GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Return Nothing End Function End Class Class C1 Public Shared Sub Main() Dim myCollection As SomethingEnumerable = nothing For Each element In myCollection Console.WriteLine("goo") Next End Sub End Class </file> </compilation>) compilation1.VerifyDiagnostics() SemanticInfoTypeTestForeach(compilation1, 1, "SomethingEnumerable", "SomethingEnumerable") ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub <Fact> Public Sub CollectionHasConvertedTypeIEnumerable() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="CollectionHasConvertedType"> <file name="a.vb"> Option Strict On Option Infer On Imports System Imports System.Collections Public Class SomethingEnumerable Implements IEnumerable Public Function GetEnumerator2() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Return Nothing End Function End Class Class C1 Public Shared Sub Main() Dim myCollection As SomethingEnumerable = nothing For Each element In myCollection Console.WriteLine("goo") Next End Sub End Class </file> </compilation>) compilation1.VerifyDiagnostics() SemanticInfoTypeTestForeach(compilation1, 1, "SomethingEnumerable", "System.Collections.IEnumerable") ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub <Fact> Public Sub CollectionHasConvertedTypeGenericIEnumerable() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="CollectionHasConvertedType"> <file name="a.vb"> Option Strict On Option Infer On Imports System Imports System.Collections.Generic Public Interface IBetterEnumerable(Of T) Inherits IEnumerable(Of T) End Interface Public Class SomethingEnumerable(Of T) Implements IEnumerable(Of T) Public Function GetEnumerator1() As System.Collections.Generic.IEnumerator(Of T) Implements System.Collections.Generic.IEnumerable(Of T).GetEnumerator Return Nothing End Function Public Function GetEnumerator2() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Return Nothing End Function End Class Class C1 Public Shared Sub Main() Dim myCollection3 As SomethingEnumerable(Of String) = nothing For Each element In myCollection3 Console.WriteLine("goo") Next End Sub End Class </file> </compilation>) compilation1.VerifyDiagnostics() SemanticInfoTypeTestForeach(compilation1, 1, "SomethingEnumerable(Of String)", "System.Collections.Generic.IEnumerable(Of String)") ClassfiConversionTestForeach(compilation1) VerifyForeachSemanticInfo(compilation1) End Sub <Fact> Public Sub GetDeclaredSymbolOfForEachStatement() Dim compilation1 = CreateCompilationWithMscorlib40( <compilation name="CollectionHasConvertedType"> <file name="a.vb"> Option Strict On Option Infer On Imports System Imports System.Collection Class C1 Public Shared Sub Main() For Each element1 In new List() Next For Each element2 as Object In new List() Next End Sub End Class </file> </compilation>) GetDeclareSymbolTestForeach(compilation1, Nothing, 1) GetDeclareSymbolTestForeach(compilation1, Nothing, 2) End Sub <WorkItem(667616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667616")> <Fact> Public Sub PortableLibraryStringForEach() Dim comp = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Public Class C Public Sub Test(s As String) For Each c In s Next End Sub End Class </file> </compilation>, {MscorlibRefPortable}) comp.VerifyDiagnostics() Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim loopSyntax = tree.GetRoot().DescendantNodes().OfType(Of ForEachStatementSyntax)().Single() Dim loopInfo = model.GetForEachStatementInfo(loopSyntax) Assert.Equal(Of ISymbol)(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerable__GetEnumerator), loopInfo.GetEnumeratorMethod) Assert.Equal(Of ISymbol)(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__Current), loopInfo.CurrentProperty) Assert.Equal(Of ISymbol)(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext), loopInfo.MoveNextMethod) Assert.Equal(Of ISymbol)(comp.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), loopInfo.DisposeMethod) ' The spec says that the element type is object. ' Therefore, we should infer object for "var". Assert.Equal(SpecialType.System_Object, loopInfo.CurrentProperty.Type.SpecialType) ' However, to match dev11, we actually infer "char" for "var". Dim typeInfo = model.GetTypeInfo(DirectCast(loopSyntax.ControlVariable, IdentifierNameSyntax)) Assert.Equal(SpecialType.System_Char, typeInfo.Type.SpecialType) Assert.Equal(typeInfo.Type, typeInfo.ConvertedType) Dim conv = model.GetConversion(loopSyntax.ControlVariable) Assert.Equal(ConversionKind.Identity, conv.Kind) End Sub <WorkItem(667616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667616")> <Fact> Public Sub PortableLibraryStringForEach_ExplicitCast() Dim comp = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Public Class C Public Sub Test(s As Object) For Each c In DirectCast(s, String) Next End Sub End Class </file> </compilation>, {MscorlibRefPortable}) comp.VerifyDiagnostics() Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim loopSyntax = tree.GetRoot().DescendantNodes().OfType(Of ForEachStatementSyntax)().Single() Dim loopInfo = model.GetForEachStatementInfo(loopSyntax) Assert.Equal(Of ISymbol)(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerable__GetEnumerator), loopInfo.GetEnumeratorMethod) Assert.Equal(Of ISymbol)(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__Current), loopInfo.CurrentProperty) Assert.Equal(Of ISymbol)(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext), loopInfo.MoveNextMethod) Assert.Equal(Of ISymbol)(comp.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), loopInfo.DisposeMethod) ' The spec says that the element type is object. ' Therefore, we should infer object for "var". Assert.Equal(SpecialType.System_Object, loopInfo.CurrentProperty.Type.SpecialType) ' However, to match dev11, we actually infer "char" for "var". Dim typeInfo = model.GetTypeInfo(DirectCast(loopSyntax.ControlVariable, IdentifierNameSyntax)) Assert.Equal(SpecialType.System_Char, typeInfo.Type.SpecialType) Assert.Equal(typeInfo.Type, typeInfo.ConvertedType) Dim conv = model.GetConversion(loopSyntax.ControlVariable) Assert.Equal(ConversionKind.Identity, conv.Kind) End Sub <WorkItem(529956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529956")> <Fact> Public Sub CastArrayToIEnumerable() Dim source = <compilation> <file name="a.vb"> Imports System Imports System.Collections Public Class C Public Shared Widening Operator CType(s As String) As C Return New C() End Operator End Class Module Program Sub Main(args As String()) For Each x As C In args Next For Each x As C In DirectCast(args, IEnumerable) Next End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) comp.AssertNoDiagnostics() Dim udc = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMember(Of MethodSymbol)(WellKnownMemberNames.ImplicitConversionName) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim loopSyntaxes = tree.GetRoot().DescendantNodes().OfType(Of ForEachStatementSyntax)().ToArray() Assert.Equal(2, loopSyntaxes.Length) Dim loopInfo0 = model.GetForEachStatementInfo(loopSyntaxes(0)) Assert.Equal(comp.GetSpecialType(SpecialType.System_Array), loopInfo0.GetEnumeratorMethod.ContainingType) ' Unlike C#, the spec doesn't say that arrays use IEnumerable Assert.Equal(Of ISymbol)(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__Current), loopInfo0.CurrentProperty) Assert.Equal(Of ISymbol)(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext), loopInfo0.MoveNextMethod) Assert.Equal(Of ISymbol)(comp.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose), loopInfo0.DisposeMethod) Assert.Equal(SpecialType.System_String, loopInfo0.ElementType.SpecialType) Assert.Equal(udc, loopInfo0.ElementConversion.Method) Assert.Equal(ConversionKind.NarrowingReference, loopInfo0.CurrentConversion.Kind) Dim loopInfo1 = model.GetForEachStatementInfo(loopSyntaxes(1)) Assert.Equal(Of ISymbol)(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerable__GetEnumerator), loopInfo1.GetEnumeratorMethod) ' No longer using System.Array method. Assert.Equal(loopInfo0.CurrentProperty, loopInfo1.CurrentProperty) Assert.Equal(loopInfo0.MoveNextMethod, loopInfo1.MoveNextMethod) Assert.Equal(loopInfo0.DisposeMethod, loopInfo1.DisposeMethod) Assert.Equal(SpecialType.System_Object, loopInfo1.ElementType.SpecialType) ' No longer string. Assert.Null(loopInfo1.ElementConversion.Method) ' No longer using UDC. Assert.Equal(ConversionKind.Identity, loopInfo1.CurrentConversion.Kind) ' Now identity End Sub Private Function SemanticInfoTypeTestForeach(compilation As VisualBasicCompilation, index As Integer, ParamArray names As String()) As SemanticInfoSummary Dim node = GetForEachStatement(compilation, index) Dim expression = node.Expression Dim model = GetModel(compilation) Dim semanticInfo = model.GetSemanticInfoSummary(expression) If "<nothing>" = names(0) Then Assert.Null(semanticInfo.Type) Else Assert.Equal(names(0), semanticInfo.Type.ToDisplayString()) End If If names.Count > 1 Then Assert.Equal(names(1), semanticInfo.ConvertedType.ToDisplayString()) If names(0) = "Object" Then If names(1) = "Object" Then Assert.True(Conversions.IsIdentityConversion(semanticInfo.ImplicitConversion.Kind)) Else Assert.True(Conversions.IsNarrowingConversion(semanticInfo.ImplicitConversion.Kind)) End If Else Assert.True(Conversions.IsWideningConversion(semanticInfo.ImplicitConversion.Kind)) End If Else Assert.Equal(names(0), semanticInfo.ConvertedType.ToDisplayString()) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) End If Return semanticInfo End Function Private Function GetDeclareSymbolTestForeach(compilation As VisualBasicCompilation, symName As String, Optional index As Integer = 1) As Symbol Dim node = GetForEachStatement(compilation, index) Dim model = GetModel(compilation) Dim symbol = model.GetDeclaredSymbolFromSyntaxNode(node) If symName Is Nothing Then Assert.Null(symbol) Else Assert.NotNull(symbol) Assert.Equal(symName.ToLowerInvariant(), symbol.Name.ToLowerInvariant()) End If Return symbol End Function Private Function AnalyzeRegionDataFlowTestForeach(compilation As VisualBasicCompilation, VariablesDeclaredSymbol As String, ReadInsideSymbol As String, ReadOutsideSymbol As String, WrittenInsideSymbol As String, WrittenOutsideSymbol As String, AlwaysAssignedSymbol As String, DataFlowsInSymbol As String, DataFlowsOutSymbol As String, Optional index As Integer = 1) As DataFlowAnalysis Dim node = GetForEachBlock(compilation, index) Dim model = GetModel(compilation) Dim analyze = model.AnalyzeDataFlow(node, node) Assert.Equal(VariablesDeclaredSymbol, GetSymbolNamesSortedAndJoined(analyze.VariablesDeclared)) Assert.Equal(ReadInsideSymbol, GetSymbolNamesSortedAndJoined(analyze.ReadInside)) Assert.Equal(ReadOutsideSymbol, GetSymbolNamesSortedAndJoined(analyze.ReadOutside)) Assert.Equal(WrittenInsideSymbol, GetSymbolNamesSortedAndJoined(analyze.WrittenInside)) Assert.Equal(WrittenOutsideSymbol, GetSymbolNamesSortedAndJoined(analyze.WrittenOutside)) Assert.Equal(AlwaysAssignedSymbol, GetSymbolNamesSortedAndJoined(analyze.AlwaysAssigned)) Assert.Equal(DataFlowsInSymbol, GetSymbolNamesSortedAndJoined(analyze.DataFlowsIn)) Assert.Equal(DataFlowsOutSymbol, GetSymbolNamesSortedAndJoined(analyze.DataFlowsOut)) Return analyze End Function Private Function AnalyzeRegionControlFlowTestForeach( compilation As VisualBasicCompilation, Optional EntryPoints As Integer = 0, Optional ExitPoints As Integer = 0, Optional EndPointIsReachable As Boolean = True, Optional index As Integer = 1) As ControlFlowAnalysis Dim node = GetForEachBlock(compilation, index) Dim model = GetModel(compilation) Dim analyze = model.AnalyzeControlFlow(node, node) Assert.Equal(EntryPoints, analyze.EntryPoints.Count) Assert.Equal(ExitPoints, analyze.ExitPoints.Count) Assert.Equal(EndPointIsReachable, analyze.EndPointIsReachable) Return analyze End Function Private Function ClassfiConversionTestForeach(compilation As VisualBasicCompilation, Optional index As Integer = 1) As Conversion Dim node = GetForEachStatement(compilation, index) Dim expression = node.Expression Dim model = GetModel(compilation) Dim semanticInfo = model.GetSemanticInfoSummary(expression) If semanticInfo.ConvertedType Is Nothing Then Return Nothing End If Dim conv = model.ClassifyConversion(expression, semanticInfo.ConvertedType) If (conv.Kind = ConversionKind.Identity) Then Assert.True(conv.Exists) Assert.True(conv.IsIdentity) End If If (semanticInfo.Type IsNot Nothing AndAlso semanticInfo.ConvertedType IsNot Nothing AndAlso semanticInfo.Type.ToDisplayString() <> "?" AndAlso semanticInfo.Type.ToDisplayString() <> "Void" AndAlso semanticInfo.ConvertedType.ToDisplayString() <> "?" AndAlso semanticInfo.ConvertedType.ToDisplayString() <> "Void") Then Assert.Equal(conv.Kind, semanticInfo.ImplicitConversion.Kind) End If Return conv End Function Private Function GetSymbolNamesSortedAndJoined(Of T As ISymbol)(symbols As IEnumerable(Of T)) As String Return String.Join(", ", symbols.Select(Function(symbol) symbol.Name).OrderBy(Function(name) name)) End Function Private Function GetModel(compilation As VisualBasicCompilation) As SemanticModel Dim tree = compilation.SyntaxTrees.First Dim model = compilation.GetSemanticModel(tree) Return model End Function Private Function GetForEachStatement(compilation As VisualBasicCompilation, index As Integer) As ForEachStatementSyntax Dim tree = compilation.SyntaxTrees.First Dim node = tree.FindNodeOrTokenByKind(SyntaxKind.ForEachStatement, index).AsNode() Dim ForEachStatement = TryCast(node, ForEachStatementSyntax) Return ForEachStatement End Function Private Function GetForEachBlock(compilation As VisualBasicCompilation, index As Integer) As ForEachBlockSyntax Dim tree = compilation.SyntaxTrees.First Dim node = tree.FindNodeOrTokenByKind(SyntaxKind.ForEachBlock, index).AsNode() Return DirectCast(node, ForEachBlockSyntax) End Function Private Function VerifyForeachSemanticInfo(compilation As VisualBasicCompilation, Optional index As Integer = 1) As ForEachStatementInfo Dim node = GetForEachBlock(compilation, index) Dim semanticModel = GetModel(compilation) Dim foreachStatementInfo = semanticModel.GetForEachStatementInfo(node) 'Assert.Null(foreachStatementInfo.CurrentProperty) 'Assert.Null(foreachStatementInfo.DisposeMethod) 'Assert.Null(foreachStatementInfo.GetEnumeratorMethod) 'Assert.Null(foreachStatementInfo.MoveNextMethod) Return (foreachStatementInfo) End Function 'Private Function GetVariableDeclarator(compilation As VisualBasicCompilation, index As Integer) As VariableDeclaratorSyntax ' Dim node = GetForEachStatement(compilation, index) ' Dim VariableDeclarator = node.DescendantNodes.Select(Function(x) TryCast(x, VariableDeclaratorSyntax)).Where(Function(x) x IsNot Nothing).ToList() ' Assert.True(VariableDeclarator.Count() <= 1) ' Return If(VariableDeclarator.Count = 1, VariableDeclarator.First(), Nothing) 'End Function End Class End Namespace
AlekseyTs/roslyn
src/Compilers/VisualBasic/Test/Semantic/Semantics/ForeachTest.vb
Visual Basic
mit
64,162
' 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 Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a preprocessing conditional compilation symbol. ''' </summary> Friend NotInheritable Class PreprocessingSymbol Inherits Symbol Implements IPreprocessingSymbol Private ReadOnly _name As String Friend Sub New(name As String) MyBase.New() _name = name End Sub Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return GetDeclaringSyntaxReferenceHelper(Of VisualBasicSyntaxNode)(Locations) End Get End Property Public Overrides ReadOnly Property Kind As SymbolKind Get Return SymbolKind.Preprocessing End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Nothing End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.NotApplicable End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Nothing End Get End Property Public Overrides Function Equals(obj As Object) As Boolean If obj Is Me Then Return True ElseIf obj Is Nothing Then Return False End If Dim other As PreprocessingSymbol = TryCast(obj, PreprocessingSymbol) Return other IsNot Nothing AndAlso IdentifierComparison.Equals(Me.Name, other.Name) End Function Public Overrides Function GetHashCode() As Integer Return Me.Name.GetHashCode() End Function Public Overloads Overrides Sub Accept(visitor As SymbolVisitor) Throw New NotSupportedException() End Sub Public Overloads Overrides Sub Accept(visitor As VisualBasicSymbolVisitor) Throw New NotSupportedException() End Sub Public Overloads Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult Throw New NotSupportedException() End Function Public Overloads Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult Throw New NotSupportedException() End Function Friend Overloads Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult Throw New NotSupportedException() End Function End Class End Namespace
REALTOBIZ/roslyn
src/Compilers/VisualBasic/Portable/Symbols/PreprocessingSymbol.vb
Visual Basic
apache-2.0
4,158
'------------------------------------------------------------------------------ ' <auto-generated> ' Dieser Code wurde von einem Tool generiert. ' Laufzeitversion:4.0.30319.42000 ' ' Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn ' der Code erneut generiert wird. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace My.Resources 'Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert '-Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert. 'Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen 'mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu. '''<summary> ''' Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. '''</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> ''' Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird. '''</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("rsaSecLib.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle ''' Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden. '''</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
master-m1000/rsaSecLib
rsaSecLib/rsaSecLib/My Project/Resources.Designer.vb
Visual Basic
mit
2,938
Imports Aspose.Cloud Namespace Document.SplitResources Class SplitToNewPDFs Public Shared Sub Run() Dim inputfile As String = "doc-sample.doc" ' Upload input file from local directory to Cloud Storage Common.UploadFile(inputfile, String.Empty) ' Split all Pages to new PDFs Dim wordsSplitResultResponse As WordsSplitResultResponse = Common.WordsService.SplitDocument(inputfile, SplitDocumentFormat.Pdf, 1, 2, Common.FOLDER) Console.WriteLine((Convert.ToString(vbLf) & inputfile) + " splitted successfully to new PDFs") End Sub End Class End Namespace
farooqsheikhpk/Aspose_Words_Cloud
Examples/DotNET/SDK/VisualBasic/Document/SplitResources/SplitToNewPDFs.vb
Visual Basic
mit
653
''' <summary></summary> ''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated> ''' <generator-date>10/02/2014 15:39:04</generator-date> ''' <generator-functions>1</generator-functions> ''' <generator-source>Leviathan\Windows\Generated\InputInterface.tt</generator-source> ''' <generator-template>Text-Templates\Classes\VB_Object.tt</generator-template> ''' <generator-version>1</generator-version> Partial Public Class InputInterface Inherits System.Windows.Window #Region " Public Constructors " ''' <summary>Default Constructor</summary> Public Sub New() MyBase.New() m_Handler = New Leviathan.Commands.SuggestedCommandHandler m_Cache = Leviathan.Caching.Simple.GetInstance(GetType(Leviathan.Commands.ControlCommands).GetHashCode(), True) m_ExecutingThreads = New List(Of System.Threading.Thread) m_ExecutingWindows = New List(Of OutputInterface) m_COLOUR_ACTIVE_TEXT = Windows.Media.Color.FromArgb(255, 245, 245, 245) m_COLOUR_NONACTIVE_TEXT = Windows.Media.Color.FromArgb(255, 150, 150, 150) m_RecentCommands = New List(Of String)(New String() {Nothing}) m_CacheList = New System.Collections.Generic.List(Of String) m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (1 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String _ ) MyBase.New() Prompt = _Prompt m_Handler = New Leviathan.Commands.SuggestedCommandHandler m_Cache = Leviathan.Caching.Simple.GetInstance(GetType(Leviathan.Commands.ControlCommands).GetHashCode(), True) m_ExecutingThreads = New List(Of System.Threading.Thread) m_ExecutingWindows = New List(Of OutputInterface) m_COLOUR_ACTIVE_TEXT = Windows.Media.Color.FromArgb(255, 245, 245, 245) m_COLOUR_NONACTIVE_TEXT = Windows.Media.Color.FromArgb(255, 150, 150, 150) m_RecentCommands = New List(Of String)(New String() {Nothing}) m_CacheList = New System.Collections.Generic.List(Of String) m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (2 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler _ ) MyBase.New() Prompt = _Prompt Handler = _Handler m_Cache = Leviathan.Caching.Simple.GetInstance(GetType(Leviathan.Commands.ControlCommands).GetHashCode(), True) m_ExecutingThreads = New List(Of System.Threading.Thread) m_ExecutingWindows = New List(Of OutputInterface) m_COLOUR_ACTIVE_TEXT = Windows.Media.Color.FromArgb(255, 245, 245, 245) m_COLOUR_NONACTIVE_TEXT = Windows.Media.Color.FromArgb(255, 150, 150, 150) m_RecentCommands = New List(Of String)(New String() {Nothing}) m_CacheList = New System.Collections.Generic.List(Of String) m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (3 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache m_ExecutingThreads = New List(Of System.Threading.Thread) m_ExecutingWindows = New List(Of OutputInterface) m_COLOUR_ACTIVE_TEXT = Windows.Media.Color.FromArgb(255, 245, 245, 245) m_COLOUR_NONACTIVE_TEXT = Windows.Media.Color.FromArgb(255, 150, 150, 150) m_RecentCommands = New List(Of String)(New String() {Nothing}) m_CacheList = New System.Collections.Generic.List(Of String) m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (4 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread m_ExecutingThreads = New List(Of System.Threading.Thread) m_ExecutingWindows = New List(Of OutputInterface) m_COLOUR_ACTIVE_TEXT = Windows.Media.Color.FromArgb(255, 245, 245, 245) m_COLOUR_NONACTIVE_TEXT = Windows.Media.Color.FromArgb(255, 150, 150, 150) m_RecentCommands = New List(Of String)(New String() {Nothing}) m_CacheList = New System.Collections.Generic.List(Of String) m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (5 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread, _ ByVal _ExecutingThreads As List(Of System.Threading.Thread) _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread ExecutingThreads = _ExecutingThreads m_ExecutingWindows = New List(Of OutputInterface) m_COLOUR_ACTIVE_TEXT = Windows.Media.Color.FromArgb(255, 245, 245, 245) m_COLOUR_NONACTIVE_TEXT = Windows.Media.Color.FromArgb(255, 150, 150, 150) m_RecentCommands = New List(Of String)(New String() {Nothing}) m_CacheList = New System.Collections.Generic.List(Of String) m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (6 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread, _ ByVal _ExecutingThreads As List(Of System.Threading.Thread), _ ByVal _ExecutingWindows As List(Of OutputInterface) _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread ExecutingThreads = _ExecutingThreads ExecutingWindows = _ExecutingWindows m_COLOUR_ACTIVE_TEXT = Windows.Media.Color.FromArgb(255, 245, 245, 245) m_COLOUR_NONACTIVE_TEXT = Windows.Media.Color.FromArgb(255, 150, 150, 150) m_RecentCommands = New List(Of String)(New String() {Nothing}) m_CacheList = New System.Collections.Generic.List(Of String) m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (7 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread, _ ByVal _ExecutingThreads As List(Of System.Threading.Thread), _ ByVal _ExecutingWindows As List(Of OutputInterface), _ ByVal _COLOUR_ACTIVE_TEXT As System.Windows.Media.Color _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread ExecutingThreads = _ExecutingThreads ExecutingWindows = _ExecutingWindows COLOUR_ACTIVE_TEXT = _COLOUR_ACTIVE_TEXT m_COLOUR_NONACTIVE_TEXT = Windows.Media.Color.FromArgb(255, 150, 150, 150) m_RecentCommands = New List(Of String)(New String() {Nothing}) m_CacheList = New System.Collections.Generic.List(Of String) m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (8 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread, _ ByVal _ExecutingThreads As List(Of System.Threading.Thread), _ ByVal _ExecutingWindows As List(Of OutputInterface), _ ByVal _COLOUR_ACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _COLOUR_NONACTIVE_TEXT As System.Windows.Media.Color _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread ExecutingThreads = _ExecutingThreads ExecutingWindows = _ExecutingWindows COLOUR_ACTIVE_TEXT = _COLOUR_ACTIVE_TEXT COLOUR_NONACTIVE_TEXT = _COLOUR_NONACTIVE_TEXT m_RecentCommands = New List(Of String)(New String() {Nothing}) m_CacheList = New System.Collections.Generic.List(Of String) m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (9 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread, _ ByVal _ExecutingThreads As List(Of System.Threading.Thread), _ ByVal _ExecutingWindows As List(Of OutputInterface), _ ByVal _COLOUR_ACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _COLOUR_NONACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _RecentCommands As System.Collections.Generic.List(Of String) _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread ExecutingThreads = _ExecutingThreads ExecutingWindows = _ExecutingWindows COLOUR_ACTIVE_TEXT = _COLOUR_ACTIVE_TEXT COLOUR_NONACTIVE_TEXT = _COLOUR_NONACTIVE_TEXT RecentCommands = _RecentCommands m_CacheList = New System.Collections.Generic.List(Of String) m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (10 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread, _ ByVal _ExecutingThreads As List(Of System.Threading.Thread), _ ByVal _ExecutingWindows As List(Of OutputInterface), _ ByVal _COLOUR_ACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _COLOUR_NONACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _RecentCommands As System.Collections.Generic.List(Of String), _ ByVal _RecentCommandPosition As System.Int32 _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread ExecutingThreads = _ExecutingThreads ExecutingWindows = _ExecutingWindows COLOUR_ACTIVE_TEXT = _COLOUR_ACTIVE_TEXT COLOUR_NONACTIVE_TEXT = _COLOUR_NONACTIVE_TEXT RecentCommands = _RecentCommands RecentCommandPosition = _RecentCommandPosition m_CacheList = New System.Collections.Generic.List(Of String) m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (11 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread, _ ByVal _ExecutingThreads As List(Of System.Threading.Thread), _ ByVal _ExecutingWindows As List(Of OutputInterface), _ ByVal _COLOUR_ACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _COLOUR_NONACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _RecentCommands As System.Collections.Generic.List(Of String), _ ByVal _RecentCommandPosition As System.Int32, _ ByVal _CacheList As System.Collections.Generic.List(Of String) _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread ExecutingThreads = _ExecutingThreads ExecutingWindows = _ExecutingWindows COLOUR_ACTIVE_TEXT = _COLOUR_ACTIVE_TEXT COLOUR_NONACTIVE_TEXT = _COLOUR_NONACTIVE_TEXT RecentCommands = _RecentCommands RecentCommandPosition = _RecentCommandPosition CacheList = _CacheList m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (12 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread, _ ByVal _ExecutingThreads As List(Of System.Threading.Thread), _ ByVal _ExecutingWindows As List(Of OutputInterface), _ ByVal _COLOUR_ACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _COLOUR_NONACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _RecentCommands As System.Collections.Generic.List(Of String), _ ByVal _RecentCommandPosition As System.Int32, _ ByVal _CacheList As System.Collections.Generic.List(Of String), _ ByVal _CachePosition As System.Int32 _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread ExecutingThreads = _ExecutingThreads ExecutingWindows = _ExecutingWindows COLOUR_ACTIVE_TEXT = _COLOUR_ACTIVE_TEXT COLOUR_NONACTIVE_TEXT = _COLOUR_NONACTIVE_TEXT RecentCommands = _RecentCommands RecentCommandPosition = _RecentCommandPosition CacheList = _CacheList CachePosition = _CachePosition m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (13 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread, _ ByVal _ExecutingThreads As List(Of System.Threading.Thread), _ ByVal _ExecutingWindows As List(Of OutputInterface), _ ByVal _COLOUR_ACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _COLOUR_NONACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _RecentCommands As System.Collections.Generic.List(Of String), _ ByVal _RecentCommandPosition As System.Int32, _ ByVal _CacheList As System.Collections.Generic.List(Of String), _ ByVal _CachePosition As System.Int32, _ ByVal _ExecutedThreadsCount As System.Int32 _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread ExecutingThreads = _ExecutingThreads ExecutingWindows = _ExecutingWindows COLOUR_ACTIVE_TEXT = _COLOUR_ACTIVE_TEXT COLOUR_NONACTIVE_TEXT = _COLOUR_NONACTIVE_TEXT RecentCommands = _RecentCommands RecentCommandPosition = _RecentCommandPosition CacheList = _CacheList CachePosition = _CachePosition ExecutedThreadsCount = _ExecutedThreadsCount m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (14 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread, _ ByVal _ExecutingThreads As List(Of System.Threading.Thread), _ ByVal _ExecutingWindows As List(Of OutputInterface), _ ByVal _COLOUR_ACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _COLOUR_NONACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _RecentCommands As System.Collections.Generic.List(Of String), _ ByVal _RecentCommandPosition As System.Int32, _ ByVal _CacheList As System.Collections.Generic.List(Of String), _ ByVal _CachePosition As System.Int32, _ ByVal _ExecutedThreadsCount As System.Int32, _ ByVal _SingleCharacterWidth As System.Double _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread ExecutingThreads = _ExecutingThreads ExecutingWindows = _ExecutingWindows COLOUR_ACTIVE_TEXT = _COLOUR_ACTIVE_TEXT COLOUR_NONACTIVE_TEXT = _COLOUR_NONACTIVE_TEXT RecentCommands = _RecentCommands RecentCommandPosition = _RecentCommandPosition CacheList = _CacheList CachePosition = _CachePosition ExecutedThreadsCount = _ExecutedThreadsCount SingleCharacterWidth = _SingleCharacterWidth m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (15 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread, _ ByVal _ExecutingThreads As List(Of System.Threading.Thread), _ ByVal _ExecutingWindows As List(Of OutputInterface), _ ByVal _COLOUR_ACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _COLOUR_NONACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _RecentCommands As System.Collections.Generic.List(Of String), _ ByVal _RecentCommandPosition As System.Int32, _ ByVal _CacheList As System.Collections.Generic.List(Of String), _ ByVal _CachePosition As System.Int32, _ ByVal _ExecutedThreadsCount As System.Int32, _ ByVal _SingleCharacterWidth As System.Double, _ ByVal _SingleLineHeight As System.Double _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread ExecutingThreads = _ExecutingThreads ExecutingWindows = _ExecutingWindows COLOUR_ACTIVE_TEXT = _COLOUR_ACTIVE_TEXT COLOUR_NONACTIVE_TEXT = _COLOUR_NONACTIVE_TEXT RecentCommands = _RecentCommands RecentCommandPosition = _RecentCommandPosition CacheList = _CacheList CachePosition = _CachePosition ExecutedThreadsCount = _ExecutedThreadsCount SingleCharacterWidth = _SingleCharacterWidth SingleLineHeight = _SingleLineHeight m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (16 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread, _ ByVal _ExecutingThreads As List(Of System.Threading.Thread), _ ByVal _ExecutingWindows As List(Of OutputInterface), _ ByVal _COLOUR_ACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _COLOUR_NONACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _RecentCommands As System.Collections.Generic.List(Of String), _ ByVal _RecentCommandPosition As System.Int32, _ ByVal _CacheList As System.Collections.Generic.List(Of String), _ ByVal _CachePosition As System.Int32, _ ByVal _ExecutedThreadsCount As System.Int32, _ ByVal _SingleCharacterWidth As System.Double, _ ByVal _SingleLineHeight As System.Double, _ ByVal _InputBoxCharacterWidth As System.Int32 _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread ExecutingThreads = _ExecutingThreads ExecutingWindows = _ExecutingWindows COLOUR_ACTIVE_TEXT = _COLOUR_ACTIVE_TEXT COLOUR_NONACTIVE_TEXT = _COLOUR_NONACTIVE_TEXT RecentCommands = _RecentCommands RecentCommandPosition = _RecentCommandPosition CacheList = _CacheList CachePosition = _CachePosition ExecutedThreadsCount = _ExecutedThreadsCount SingleCharacterWidth = _SingleCharacterWidth SingleLineHeight = _SingleLineHeight InputBoxCharacterWidth = _InputBoxCharacterWidth m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (17 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread, _ ByVal _ExecutingThreads As List(Of System.Threading.Thread), _ ByVal _ExecutingWindows As List(Of OutputInterface), _ ByVal _COLOUR_ACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _COLOUR_NONACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _RecentCommands As System.Collections.Generic.List(Of String), _ ByVal _RecentCommandPosition As System.Int32, _ ByVal _CacheList As System.Collections.Generic.List(Of String), _ ByVal _CachePosition As System.Int32, _ ByVal _ExecutedThreadsCount As System.Int32, _ ByVal _SingleCharacterWidth As System.Double, _ ByVal _SingleLineHeight As System.Double, _ ByVal _InputBoxCharacterWidth As System.Int32, _ ByVal _Window_Locked As System.Boolean _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread ExecutingThreads = _ExecutingThreads ExecutingWindows = _ExecutingWindows COLOUR_ACTIVE_TEXT = _COLOUR_ACTIVE_TEXT COLOUR_NONACTIVE_TEXT = _COLOUR_NONACTIVE_TEXT RecentCommands = _RecentCommands RecentCommandPosition = _RecentCommandPosition CacheList = _CacheList CachePosition = _CachePosition ExecutedThreadsCount = _ExecutedThreadsCount SingleCharacterWidth = _SingleCharacterWidth SingleLineHeight = _SingleLineHeight InputBoxCharacterWidth = _InputBoxCharacterWidth Window_Locked = _Window_Locked m_COLOUR_UNLOCKED_BORDER = Windows.Media.Color.FromArgb(255, 26, 26, 26) m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (18 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread, _ ByVal _ExecutingThreads As List(Of System.Threading.Thread), _ ByVal _ExecutingWindows As List(Of OutputInterface), _ ByVal _COLOUR_ACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _COLOUR_NONACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _RecentCommands As System.Collections.Generic.List(Of String), _ ByVal _RecentCommandPosition As System.Int32, _ ByVal _CacheList As System.Collections.Generic.List(Of String), _ ByVal _CachePosition As System.Int32, _ ByVal _ExecutedThreadsCount As System.Int32, _ ByVal _SingleCharacterWidth As System.Double, _ ByVal _SingleLineHeight As System.Double, _ ByVal _InputBoxCharacterWidth As System.Int32, _ ByVal _Window_Locked As System.Boolean, _ ByVal _COLOUR_UNLOCKED_BORDER As System.Windows.Media.Color _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread ExecutingThreads = _ExecutingThreads ExecutingWindows = _ExecutingWindows COLOUR_ACTIVE_TEXT = _COLOUR_ACTIVE_TEXT COLOUR_NONACTIVE_TEXT = _COLOUR_NONACTIVE_TEXT RecentCommands = _RecentCommands RecentCommandPosition = _RecentCommandPosition CacheList = _CacheList CachePosition = _CachePosition ExecutedThreadsCount = _ExecutedThreadsCount SingleCharacterWidth = _SingleCharacterWidth SingleLineHeight = _SingleLineHeight InputBoxCharacterWidth = _InputBoxCharacterWidth Window_Locked = _Window_Locked COLOUR_UNLOCKED_BORDER = _COLOUR_UNLOCKED_BORDER m_COLOUR_LOCKED_BORDER = Windows.Media.Color.FromArgb(255, 52, 26, 26) InitializeComponent() End Sub ''' <summary>Parametered Constructor (19 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread, _ ByVal _ExecutingThreads As List(Of System.Threading.Thread), _ ByVal _ExecutingWindows As List(Of OutputInterface), _ ByVal _COLOUR_ACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _COLOUR_NONACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _RecentCommands As System.Collections.Generic.List(Of String), _ ByVal _RecentCommandPosition As System.Int32, _ ByVal _CacheList As System.Collections.Generic.List(Of String), _ ByVal _CachePosition As System.Int32, _ ByVal _ExecutedThreadsCount As System.Int32, _ ByVal _SingleCharacterWidth As System.Double, _ ByVal _SingleLineHeight As System.Double, _ ByVal _InputBoxCharacterWidth As System.Int32, _ ByVal _Window_Locked As System.Boolean, _ ByVal _COLOUR_UNLOCKED_BORDER As System.Windows.Media.Color, _ ByVal _COLOUR_LOCKED_BORDER As System.Windows.Media.Color _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread ExecutingThreads = _ExecutingThreads ExecutingWindows = _ExecutingWindows COLOUR_ACTIVE_TEXT = _COLOUR_ACTIVE_TEXT COLOUR_NONACTIVE_TEXT = _COLOUR_NONACTIVE_TEXT RecentCommands = _RecentCommands RecentCommandPosition = _RecentCommandPosition CacheList = _CacheList CachePosition = _CachePosition ExecutedThreadsCount = _ExecutedThreadsCount SingleCharacterWidth = _SingleCharacterWidth SingleLineHeight = _SingleLineHeight InputBoxCharacterWidth = _InputBoxCharacterWidth Window_Locked = _Window_Locked COLOUR_UNLOCKED_BORDER = _COLOUR_UNLOCKED_BORDER COLOUR_LOCKED_BORDER = _COLOUR_LOCKED_BORDER InitializeComponent() End Sub ''' <summary>Parametered Constructor (20 Parameters)</summary> Public Sub New( _ ByVal _Prompt As System.String, _ ByVal _Handler As Leviathan.Commands.SuggestedCommandHandler, _ ByVal _Cache As Leviathan.Caching.Simple, _ ByVal _InputChangedThread As System.Threading.Thread, _ ByVal _ExecutingThreads As List(Of System.Threading.Thread), _ ByVal _ExecutingWindows As List(Of OutputInterface), _ ByVal _COLOUR_ACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _COLOUR_NONACTIVE_TEXT As System.Windows.Media.Color, _ ByVal _RecentCommands As System.Collections.Generic.List(Of String), _ ByVal _RecentCommandPosition As System.Int32, _ ByVal _CacheList As System.Collections.Generic.List(Of String), _ ByVal _CachePosition As System.Int32, _ ByVal _ExecutedThreadsCount As System.Int32, _ ByVal _SingleCharacterWidth As System.Double, _ ByVal _SingleLineHeight As System.Double, _ ByVal _InputBoxCharacterWidth As System.Int32, _ ByVal _Window_Locked As System.Boolean, _ ByVal _COLOUR_UNLOCKED_BORDER As System.Windows.Media.Color, _ ByVal _COLOUR_LOCKED_BORDER As System.Windows.Media.Color, _ ByVal _Opacity_Locked As System.Boolean _ ) MyBase.New() Prompt = _Prompt Handler = _Handler Cache = _Cache InputChangedThread = _InputChangedThread ExecutingThreads = _ExecutingThreads ExecutingWindows = _ExecutingWindows COLOUR_ACTIVE_TEXT = _COLOUR_ACTIVE_TEXT COLOUR_NONACTIVE_TEXT = _COLOUR_NONACTIVE_TEXT RecentCommands = _RecentCommands RecentCommandPosition = _RecentCommandPosition CacheList = _CacheList CachePosition = _CachePosition ExecutedThreadsCount = _ExecutedThreadsCount SingleCharacterWidth = _SingleCharacterWidth SingleLineHeight = _SingleLineHeight InputBoxCharacterWidth = _InputBoxCharacterWidth Window_Locked = _Window_Locked COLOUR_UNLOCKED_BORDER = _COLOUR_UNLOCKED_BORDER COLOUR_LOCKED_BORDER = _COLOUR_LOCKED_BORDER Opacity_Locked = _Opacity_Locked InitializeComponent() End Sub #End Region #Region " Class Plumbing/Interface Code " #Region " Thread-Safe Updates Implementation " #Region " Private Variables " ''' <summary></summary> ''' <remarks></remarks> Private ExecutingThreads_LOCK As New System.Object ''' <summary></summary> ''' <remarks></remarks> Private ExecutingThreads_HASVALUE As System.Boolean #End Region #Region " Public Update Methods " Public Function ThreadSafeUpdateExecutingThreads( _ ByVal _ExecutingThreads As List(Of System.Threading.Thread) _ ) As Boolean SyncLock ExecutingThreads_LOCK If Not ExecutingThreads_HASVALUE OrElse Not Leviathan.Comparison.Comparer.AreEqual(ExecutingThreads, _ExecutingThreads) Then ExecutingThreads = _ExecutingThreads ExecutingThreads_HASVALUE = True Return True Else Return False End If End SyncLock End Function #End Region #End Region #End Region #Region " Public Constants " ''' <summary>Public Shared Reference to the Name of the Property: Prompt</summary> ''' <remarks></remarks> Public Const PROPERTY_PROMPT As String = "Prompt" ''' <summary>Public Shared Reference to the Name of the Property: Handler</summary> ''' <remarks></remarks> Public Const PROPERTY_HANDLER As String = "Handler" ''' <summary>Public Shared Reference to the Name of the Property: Cache</summary> ''' <remarks></remarks> Public Const PROPERTY_CACHE As String = "Cache" ''' <summary>Public Shared Reference to the Name of the Property: InputChangedThread</summary> ''' <remarks></remarks> Public Const PROPERTY_INPUTCHANGEDTHREAD As String = "InputChangedThread" ''' <summary>Public Shared Reference to the Name of the Property: ExecutingThreads</summary> ''' <remarks></remarks> Public Const PROPERTY_EXECUTINGTHREADS As String = "ExecutingThreads" ''' <summary>Public Shared Reference to the Name of the Property: ExecutingWindows</summary> ''' <remarks></remarks> Public Const PROPERTY_EXECUTINGWINDOWS As String = "ExecutingWindows" ''' <summary>Public Shared Reference to the Name of the Property: COLOUR_ACTIVE_TEXT</summary> ''' <remarks></remarks> Public Const PROPERTY_COLOUR_ACTIVE_TEXT As String = "COLOUR_ACTIVE_TEXT" ''' <summary>Public Shared Reference to the Name of the Property: COLOUR_NONACTIVE_TEXT</summary> ''' <remarks></remarks> Public Const PROPERTY_COLOUR_NONACTIVE_TEXT As String = "COLOUR_NONACTIVE_TEXT" ''' <summary>Public Shared Reference to the Name of the Property: RecentCommands</summary> ''' <remarks></remarks> Public Const PROPERTY_RECENTCOMMANDS As String = "RecentCommands" ''' <summary>Public Shared Reference to the Name of the Property: RecentCommandPosition</summary> ''' <remarks></remarks> Public Const PROPERTY_RECENTCOMMANDPOSITION As String = "RecentCommandPosition" ''' <summary>Public Shared Reference to the Name of the Property: CacheList</summary> ''' <remarks></remarks> Public Const PROPERTY_CACHELIST As String = "CacheList" ''' <summary>Public Shared Reference to the Name of the Property: CachePosition</summary> ''' <remarks></remarks> Public Const PROPERTY_CACHEPOSITION As String = "CachePosition" ''' <summary>Public Shared Reference to the Name of the Property: ExecutedThreadsCount</summary> ''' <remarks></remarks> Public Const PROPERTY_EXECUTEDTHREADSCOUNT As String = "ExecutedThreadsCount" ''' <summary>Public Shared Reference to the Name of the Property: SingleCharacterWidth</summary> ''' <remarks></remarks> Public Const PROPERTY_SINGLECHARACTERWIDTH As String = "SingleCharacterWidth" ''' <summary>Public Shared Reference to the Name of the Property: SingleLineHeight</summary> ''' <remarks></remarks> Public Const PROPERTY_SINGLELINEHEIGHT As String = "SingleLineHeight" ''' <summary>Public Shared Reference to the Name of the Property: InputBoxCharacterWidth</summary> ''' <remarks></remarks> Public Const PROPERTY_INPUTBOXCHARACTERWIDTH As String = "InputBoxCharacterWidth" ''' <summary>Public Shared Reference to the Name of the Property: Window_Locked</summary> ''' <remarks></remarks> Public Const PROPERTY_WINDOW_LOCKED As String = "Window_Locked" ''' <summary>Public Shared Reference to the Name of the Property: COLOUR_UNLOCKED_BORDER</summary> ''' <remarks></remarks> Public Const PROPERTY_COLOUR_UNLOCKED_BORDER As String = "COLOUR_UNLOCKED_BORDER" ''' <summary>Public Shared Reference to the Name of the Property: COLOUR_LOCKED_BORDER</summary> ''' <remarks></remarks> Public Const PROPERTY_COLOUR_LOCKED_BORDER As String = "COLOUR_LOCKED_BORDER" ''' <summary>Public Shared Reference to the Name of the Property: Opacity_Locked</summary> ''' <remarks></remarks> Public Const PROPERTY_OPACITY_LOCKED As String = "Opacity_Locked" #End Region #Region " Private Variables " ''' <summary>Private Data Storage Variable for Property: Prompt</summary> ''' <remarks></remarks> Private m_Prompt As System.String ''' <summary>Private Data Storage Variable for Property: Handler</summary> ''' <remarks></remarks> Private WithEvents m_Handler As Leviathan.Commands.SuggestedCommandHandler ''' <summary>Private Data Storage Variable for Property: Cache</summary> ''' <remarks></remarks> Private WithEvents m_Cache As Leviathan.Caching.Simple ''' <summary>Private Data Storage Variable for Property: InputChangedThread</summary> ''' <remarks></remarks> Private m_InputChangedThread As System.Threading.Thread ''' <summary>Private Data Storage Variable for Property: ExecutingThreads</summary> ''' <remarks></remarks> Private m_ExecutingThreads As List(Of System.Threading.Thread) ''' <summary>Private Data Storage Variable for Property: ExecutingWindows</summary> ''' <remarks></remarks> Private m_ExecutingWindows As List(Of OutputInterface) ''' <summary>Private Data Storage Variable for Property: COLOUR_ACTIVE_TEXT</summary> ''' <remarks></remarks> Private m_COLOUR_ACTIVE_TEXT As System.Windows.Media.Color ''' <summary>Private Data Storage Variable for Property: COLOUR_NONACTIVE_TEXT</summary> ''' <remarks></remarks> Private m_COLOUR_NONACTIVE_TEXT As System.Windows.Media.Color ''' <summary>Private Data Storage Variable for Property: RecentCommands</summary> ''' <remarks></remarks> Private m_RecentCommands As System.Collections.Generic.List(Of String) ''' <summary>Private Data Storage Variable for Property: RecentCommandPosition</summary> ''' <remarks></remarks> Private m_RecentCommandPosition As System.Int32 ''' <summary>Private Data Storage Variable for Property: CacheList</summary> ''' <remarks></remarks> Private m_CacheList As System.Collections.Generic.List(Of String) ''' <summary>Private Data Storage Variable for Property: CachePosition</summary> ''' <remarks></remarks> Private m_CachePosition As System.Int32 ''' <summary>Private Data Storage Variable for Property: ExecutedThreadsCount</summary> ''' <remarks></remarks> Private m_ExecutedThreadsCount As System.Int32 ''' <summary>Private Data Storage Variable for Property: SingleCharacterWidth</summary> ''' <remarks></remarks> Private m_SingleCharacterWidth As System.Double ''' <summary>Private Data Storage Variable for Property: SingleLineHeight</summary> ''' <remarks></remarks> Private m_SingleLineHeight As System.Double ''' <summary>Private Data Storage Variable for Property: InputBoxCharacterWidth</summary> ''' <remarks></remarks> Private m_InputBoxCharacterWidth As System.Int32 ''' <summary>Private Data Storage Variable for Property: Window_Locked</summary> ''' <remarks></remarks> Private m_Window_Locked As System.Boolean ''' <summary>Private Data Storage Variable for Property: COLOUR_UNLOCKED_BORDER</summary> ''' <remarks></remarks> Private m_COLOUR_UNLOCKED_BORDER As System.Windows.Media.Color ''' <summary>Private Data Storage Variable for Property: COLOUR_LOCKED_BORDER</summary> ''' <remarks></remarks> Private m_COLOUR_LOCKED_BORDER As System.Windows.Media.Color ''' <summary>Private Data Storage Variable for Property: Opacity_Locked</summary> ''' <remarks></remarks> Private m_Opacity_Locked As System.Boolean #End Region #Region " Public Properties " ''' <summary>Provides Access to the Property: Prompt</summary> ''' <remarks></remarks> Public Property Prompt() As System.String Get Return m_Prompt End Get Set(value As System.String) m_Prompt = value End Set End Property ''' <summary>Provides Access to the Property: Handler</summary> ''' <remarks></remarks> Public Property Handler() As Leviathan.Commands.SuggestedCommandHandler Get Return m_Handler End Get Set(value As Leviathan.Commands.SuggestedCommandHandler) m_Handler = value End Set End Property ''' <summary>Provides Access to the Property: Cache</summary> ''' <remarks></remarks> Public Property Cache() As Leviathan.Caching.Simple Get Return m_Cache End Get Set(value As Leviathan.Caching.Simple) m_Cache = value End Set End Property ''' <summary>Provides Access to the Property: InputChangedThread</summary> ''' <remarks></remarks> Public Property InputChangedThread() As System.Threading.Thread Get Return m_InputChangedThread End Get Set(value As System.Threading.Thread) m_InputChangedThread = value End Set End Property ''' <summary>Provides Access to the Property: ExecutingThreads</summary> ''' <remarks></remarks> Public Property ExecutingThreads() As List(Of System.Threading.Thread) Get Return m_ExecutingThreads End Get Set(value As List(Of System.Threading.Thread)) m_ExecutingThreads = value End Set End Property ''' <summary>Provides Access to the Property: ExecutingWindows</summary> ''' <remarks></remarks> Public Property ExecutingWindows() As List(Of OutputInterface) Get Return m_ExecutingWindows End Get Set(value As List(Of OutputInterface)) m_ExecutingWindows = value End Set End Property ''' <summary>Provides Access to the Property: COLOUR_ACTIVE_TEXT</summary> ''' <remarks></remarks> Public Property COLOUR_ACTIVE_TEXT() As System.Windows.Media.Color Get Return m_COLOUR_ACTIVE_TEXT End Get Set(value As System.Windows.Media.Color) m_COLOUR_ACTIVE_TEXT = value End Set End Property ''' <summary>Provides Access to the Property: COLOUR_NONACTIVE_TEXT</summary> ''' <remarks></remarks> Public Property COLOUR_NONACTIVE_TEXT() As System.Windows.Media.Color Get Return m_COLOUR_NONACTIVE_TEXT End Get Set(value As System.Windows.Media.Color) m_COLOUR_NONACTIVE_TEXT = value End Set End Property ''' <summary>Provides Access to the Property: RecentCommands</summary> ''' <remarks></remarks> Public Property RecentCommands() As System.Collections.Generic.List(Of String) Get Return m_RecentCommands End Get Set(value As System.Collections.Generic.List(Of String)) m_RecentCommands = value End Set End Property ''' <summary>Provides Access to the Property: RecentCommandPosition</summary> ''' <remarks></remarks> Public Property RecentCommandPosition() As System.Int32 Get Return m_RecentCommandPosition End Get Set(value As System.Int32) m_RecentCommandPosition = value End Set End Property ''' <summary>Provides Access to the Property: CacheList</summary> ''' <remarks></remarks> Public Property CacheList() As System.Collections.Generic.List(Of String) Get Return m_CacheList End Get Set(value As System.Collections.Generic.List(Of String)) m_CacheList = value End Set End Property ''' <summary>Provides Access to the Property: CachePosition</summary> ''' <remarks></remarks> Public Property CachePosition() As System.Int32 Get Return m_CachePosition End Get Set(value As System.Int32) m_CachePosition = value End Set End Property ''' <summary>Provides Access to the Property: ExecutedThreadsCount</summary> ''' <remarks></remarks> Public Property ExecutedThreadsCount() As System.Int32 Get Return m_ExecutedThreadsCount End Get Set(value As System.Int32) m_ExecutedThreadsCount = value End Set End Property ''' <summary>Provides Access to the Property: SingleCharacterWidth</summary> ''' <remarks></remarks> Public Property SingleCharacterWidth() As System.Double Get Return m_SingleCharacterWidth End Get Set(value As System.Double) m_SingleCharacterWidth = value End Set End Property ''' <summary>Provides Access to the Property: SingleLineHeight</summary> ''' <remarks></remarks> Public Property SingleLineHeight() As System.Double Get Return m_SingleLineHeight End Get Set(value As System.Double) m_SingleLineHeight = value End Set End Property ''' <summary>Provides Access to the Property: InputBoxCharacterWidth</summary> ''' <remarks></remarks> Public Property InputBoxCharacterWidth() As System.Int32 Get Return m_InputBoxCharacterWidth End Get Set(value As System.Int32) m_InputBoxCharacterWidth = value End Set End Property ''' <summary>Provides Access to the Property: Window_Locked</summary> ''' <remarks></remarks> Public Property Window_Locked() As System.Boolean Get Return m_Window_Locked End Get Set(value As System.Boolean) m_Window_Locked = value End Set End Property ''' <summary>Provides Access to the Property: COLOUR_UNLOCKED_BORDER</summary> ''' <remarks></remarks> Public Property COLOUR_UNLOCKED_BORDER() As System.Windows.Media.Color Get Return m_COLOUR_UNLOCKED_BORDER End Get Set(value As System.Windows.Media.Color) m_COLOUR_UNLOCKED_BORDER = value End Set End Property ''' <summary>Provides Access to the Property: COLOUR_LOCKED_BORDER</summary> ''' <remarks></remarks> Public Property COLOUR_LOCKED_BORDER() As System.Windows.Media.Color Get Return m_COLOUR_LOCKED_BORDER End Get Set(value As System.Windows.Media.Color) m_COLOUR_LOCKED_BORDER = value End Set End Property ''' <summary>Provides Access to the Property: Opacity_Locked</summary> ''' <remarks></remarks> Public Property Opacity_Locked() As System.Boolean Get Return m_Opacity_Locked End Get Set(value As System.Boolean) m_Opacity_Locked = value End Set End Property #End Region End Class
thiscouldbejd/Leviathan
Windows/Generated/InputInterface.vb
Visual Basic
mit
43,860
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("VbDefault")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("VbDefault")> <Assembly: AssemblyCopyright("Copyright © 2012")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("6b17ea4c-2b3f-4b3f-b3c8-367ef7513a4e")> ' 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")>
patridge/VB-default-tests
VbDefault/My Project/AssemblyInfo.vb
Visual Basic
mit
1,136
Imports System.IO Imports System.Runtime.InteropServices Module Example <STAThread()> _ Sub Main() Dim objApplication As SolidEdgeFramework.Application = Nothing Dim objPartDocument As SolidEdgePart.PartDocument = Nothing Dim objStudyOwner As SolidEdgePart.StudyOwner = Nothing Dim objStudy As SolidEdgePart.Study = Nothing Dim objConstraintOwner As SolidEdgePart.ConstraintOwner = Nothing Try OleMessageFilter.Register() ' Connect to Solid Edge objApplication = Marshal.GetActiveObject("SolidEdge.Application") objPartDocument = objApplication.ActiveDocument objStudyOwner = objPartDocument.StudyOwner objStudyOwner.GetActiveStudy(objStudy) objStudy.GetConstraintOwner(objConstraintOwner) Catch ex As Exception Console.WriteLine(ex.Message) Finally OleMessageFilter.Revoke() End Try End Sub End Module
SolidEdgeCommunity/docs
docfx_project/snippets/SolidEdgePart.Study.GetConstraintOwner.vb
Visual Basic
mit
1,003
'------------------------------------------------------------------------------ ' <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", "15.1.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(sender As Global.System.Object, 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.DTIContentManagementTester.My.MySettings Get Return Global.DTIContentManagementTester.My.MySettings.Default End Get End Property End Module End Namespace
Micmaz/DTIControls
DTIContentManagement/DTIContentManagementTester/My Project/Settings.Designer.vb
Visual Basic
mit
2,930
Namespace Cisco ''' <summary>Cisco IP-Phone Input Item</summary> ''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated> ''' <generator-date>08/02/2014 18:06:16</generator-date> ''' <generator-functions>1</generator-functions> ''' <generator-source>Caerus\_Cisco\Voice\Generated\CiscoIPPhoneInputItem.tt</generator-source> ''' <generator-template>Text-Templates\Classes\VB_Object.tt</generator-template> ''' <generator-version>1</generator-version> <System.CodeDom.Compiler.GeneratedCode("Caerus\_Cisco\Voice\Generated\CiscoIPPhoneInputItem.tt", "1")> _ Partial Public Class CiscoIPPhoneInputItem Inherits System.Web.UI.WebControls.WebControl Implements System.IFormattable #Region " Public Constructors " ''' <summary>Default Constructor</summary> Public Sub New() MyBase.New() End Sub ''' <summary>Parametered Constructor (1 Parameters)</summary> Public Sub New( _ ByVal _DisplayName As System.String _ ) MyBase.New() DisplayName = _DisplayName End Sub ''' <summary>Parametered Constructor (2 Parameters)</summary> Public Sub New( _ ByVal _DisplayName As System.String, _ ByVal _QueryStringParamater As System.String _ ) MyBase.New() DisplayName = _DisplayName QueryStringParamater = _QueryStringParamater End Sub ''' <summary>Parametered Constructor (3 Parameters)</summary> Public Sub New( _ ByVal _DisplayName As System.String, _ ByVal _QueryStringParamater As System.String, _ ByVal _InputFlags As System.String _ ) MyBase.New() DisplayName = _DisplayName QueryStringParamater = _QueryStringParamater InputFlags = _InputFlags End Sub ''' <summary>Parametered Constructor (4 Parameters)</summary> Public Sub New( _ ByVal _DisplayName As System.String, _ ByVal _QueryStringParamater As System.String, _ ByVal _InputFlags As System.String, _ ByVal _DefaultValue As System.String _ ) MyBase.New() DisplayName = _DisplayName QueryStringParamater = _QueryStringParamater InputFlags = _InputFlags DefaultValue = _DefaultValue End Sub #End Region #Region " Class Plumbing/Interface Code " #Region " IFormattable Implementation " #Region " Public Constants " ''' <summary>Public Shared Reference to the Name of the Property: AsString</summary> ''' <remarks></remarks> Public Const PROPERTY_ASSTRING As String = "AsString" #End Region #Region " Public Properties " ''' <summary></summary> ''' <remarks></remarks> Public ReadOnly Property AsString() As System.String Get Return Me.ToString() End Get End Property #End Region #Region " Public Shared Methods " #End Region #Region " Public Methods " Public Overloads Overrides Function ToString() As String Return Me.ToString(String.Empty, Nothing) End Function Public Overloads Function ToString( _ ByVal format As String _ ) As String Return String.Empty End Function Public Overloads Function ToString( _ ByVal format As String, _ ByVal formatProvider As System.IFormatProvider _ ) As String Implements System.IFormattable.ToString Return String.Empty End Function #End Region #End Region #End Region #Region " Public Constants " ''' <summary>Public Shared Reference to the Name of the Property: DisplayName</summary> ''' <remarks></remarks> Public Const PROPERTY_DISPLAYNAME As String = "DisplayName" ''' <summary>Public Shared Reference to the Name of the Property: QueryStringParamater</summary> ''' <remarks></remarks> Public Const PROPERTY_QUERYSTRINGPARAMATER As String = "QueryStringParamater" ''' <summary>Public Shared Reference to the Name of the Property: InputFlags</summary> ''' <remarks></remarks> Public Const PROPERTY_INPUTFLAGS As String = "InputFlags" ''' <summary>Public Shared Reference to the Name of the Property: DefaultValue</summary> ''' <remarks></remarks> Public Const PROPERTY_DEFAULTVALUE As String = "DefaultValue" #End Region #Region " Private Variables " ''' <summary>Private Data Storage Variable for Property: DisplayName</summary> ''' <remarks></remarks> Private m_DisplayName As System.String ''' <summary>Private Data Storage Variable for Property: QueryStringParamater</summary> ''' <remarks></remarks> Private m_QueryStringParamater As System.String ''' <summary>Private Data Storage Variable for Property: InputFlags</summary> ''' <remarks></remarks> Private m_InputFlags As System.String ''' <summary>Private Data Storage Variable for Property: DefaultValue</summary> ''' <remarks></remarks> Private m_DefaultValue As System.String #End Region #Region " Public Properties " ''' <summary>Provides Access to the Property: DisplayName</summary> ''' <remarks></remarks> Public Property DisplayName() As System.String Get Return m_DisplayName End Get Set(value As System.String) m_DisplayName = value End Set End Property ''' <summary>Provides Access to the Property: QueryStringParamater</summary> ''' <remarks></remarks> Public Property QueryStringParamater() As System.String Get Return m_QueryStringParamater End Get Set(value As System.String) m_QueryStringParamater = value End Set End Property ''' <summary>Provides Access to the Property: InputFlags</summary> ''' <remarks></remarks> Public Property InputFlags() As System.String Get Return m_InputFlags End Get Set(value As System.String) m_InputFlags = value End Set End Property ''' <summary>Provides Access to the Property: DefaultValue</summary> ''' <remarks></remarks> Public Property DefaultValue() As System.String Get Return m_DefaultValue End Get Set(value As System.String) m_DefaultValue = value End Set End Property #End Region End Class End Namespace
thiscouldbejd/Caerus
_Cisco/Voice/Generated/CiscoIPPhoneInputItem.vb
Visual Basic
mit
6,132
Imports System.Threading Public Class Form1 Private tread As Thread Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load End Sub Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click tread = New Thread(AddressOf DoShit) tread.Start() Timer1.Start() End Sub Private fgt As String Public Sub RecDir(Dirt As String) For Each File As String In My.Computer.FileSystem.GetFiles(Dirt) If File.ToLower.Contains("stuxnet") Then MsgBox("we find stux.net == done! " & File) Else fgt = File End If Next For Each Dir As String In My.Computer.FileSystem.GetDirectories(Dirt) Try RecDir(Dir) Catch ex As Exception End Try Next End Sub Private Sub DoShit() RecDir("C:\") End Sub Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick Label1.Text = fgt End Sub End Class
ParityHF/Stuxnet-Remover
Stuxnet Remover/Form1.vb
Visual Basic
mit
1,209
Imports Nemiro.OAuth Public Class ExternalLoginResult Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load preResult.InnerHtml = "" Dim result As AuthorizationResult = OAuthWeb.VerifyAuthorization() preResult.InnerHtml += String.Format("Provider: {0}<br />", result.ProviderName) If result.IsSuccessfully Then 'preResult.InnerHtml += "Успешно!<br /><br /><textarea style=""width:500px;"" rows=""15"">" + New JavaScriptSerializer().Serialize(result.UserInfo) + "</textarea><br /><br />" Dim user As UserInfo = result.UserInfo preResult.InnerHtml += String.Format("User ID: {0}<br />", user.UserId) preResult.InnerHtml += String.Format("Name: {0}<br />", user.DisplayName) preResult.InnerHtml += String.Format("Email: {0}", user.Email) Else preResult.InnerHtml += result.ErrorInfo.ToString() If result.ErrorInfo.InnerException IsNot Nothing Then If result.ErrorInfo.GetType() Is GetType(RequestException) Then preResult.InnerHtml += CType(result.ErrorInfo, RequestException).RequestResult.ToString() & "<br /><br />" preResult.InnerHtml += result.ErrorInfo.InnerException.ToString() Else preResult.InnerHtml += result.ErrorInfo.InnerException.ToString() End If End If End If End Sub End Class
alekseynemiro/nemiro.oauth.dll
examples/Test/Test.VB.AspWebForms/ExternalLoginResult.aspx.vb
Visual Basic
apache-2.0
1,411
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Form3 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() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Form3)) Me.TabControl1 = New System.Windows.Forms.TabControl() Me.SuspendLayout() ' 'TabControl1 ' Me.TabControl1.Dock = System.Windows.Forms.DockStyle.Fill Me.TabControl1.Location = New System.Drawing.Point(0, 0) Me.TabControl1.Name = "TabControl1" Me.TabControl1.SelectedIndex = 0 Me.TabControl1.Size = New System.Drawing.Size(1008, 729) Me.TabControl1.TabIndex = 0 ' 'Form3 ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(1008, 729) Me.Controls.Add(Me.TabControl1) Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.MinimumSize = New System.Drawing.Size(1024, 768) Me.Name = "Form3" Me.Text = "SolZeWeb" Me.WindowState = System.Windows.Forms.FormWindowState.Maximized Me.ResumeLayout(False) End Sub Friend WithEvents TabControl1 As TabControl End Class
SolZe/SolZeWeb
Form3.Designer.vb
Visual Basic
apache-2.0
2,173
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("UO_UniCommand")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("UO_UniCommand")> <Assembly: AssemblyCopyright("Copyright © 2012")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("c42fd1d1-b80c-4fe6-bf38-1fe8ca0230f6")> ' 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")>
RocketSoftware/multivalue-lab
U2/Demos/U2-Toolkit/.NET Samples/samples/VB.NET/UniVerse/UO_UniCommand/My Project/AssemblyInfo.vb
Visual Basic
mit
1,144
' 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.Reflection Public Module Extensions_333 ''' <summary> ''' A T extension method that shallow copy. ''' </summary> ''' <typeparam name="T">Generic type parameter.</typeparam> ''' <param name="this">The @this to act on.</param> ''' <returns>A T.</returns> <System.Runtime.CompilerServices.Extension> _ Public Function ShallowCopy(Of T)(this As T) As T Dim method As MethodInfo = this.[GetType]().GetMethod("MemberwiseClone", BindingFlags.NonPublic Or BindingFlags.Instance) Return DirectCast(method.Invoke(this, Nothing), T) End Function End Module
zzzprojects/Z.ExtensionMethods
src (VB.NET)/Z.ExtensionMethods.VB/Z.Core/System.Object/Cloning/Object.ShallowCopy.vb
Visual Basic
mit
962
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp <ExportSignatureHelpProvider("MidAssignmentSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]> Partial Friend Class MidAssignmentSignatureHelpProvider Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of AssignmentStatementSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function GetIntrinsicOperatorDocumentationAsync(node As AssignmentStatementSyntax, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation)) Return New ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))({New MidAssignmentDocumentation()}) End Function Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean Return token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) AndAlso token.Parent.Kind = SyntaxKind.ArgumentList AndAlso token.Parent.IsParentKind(SyntaxKind.MidExpression) AndAlso token.Parent.Parent.IsParentKind(SyntaxKind.MidAssignmentStatement) End Function Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean Return ch = "("c OrElse ch = ","c End Function Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean Return False End Function Protected Overrides Function IsArgumentListToken(node As AssignmentStatementSyntax, token As SyntaxToken) As Boolean Return node.Left.IsKind(SyntaxKind.MidExpression) AndAlso DirectCast(node.Left, MidExpressionSyntax).ArgumentList.Span.Contains(token.SpanStart) AndAlso DirectCast(node.Left, MidExpressionSyntax).ArgumentList.CloseParenToken <> token End Function Protected Overrides Function GetCurrentArgumentStateWorker(node As SyntaxNode, position As Integer) As SignatureHelpState Return MyBase.GetCurrentArgumentStateWorker(DirectCast(DirectCast(node, AssignmentStatementSyntax).Left, MidExpressionSyntax).ArgumentList, position) End Function End Class End Namespace
davkean/roslyn
src/Features/VisualBasic/Portable/SignatureHelp/MidAssignmentSignatureHelpProvider.vb
Visual Basic
apache-2.0
2,906
' 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.Semantics Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17607, "https://github.com/dotnet/roslyn/issues/17607")> Public Sub InvalidVariableDeclarationStatement() Dim source = <![CDATA[ Class Program Public Shared Sub Main(args As String()) Dim x, 1 As Integer'BIND:"Dim x, 1 As Integer" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationStatement (2 declarations) (OperationKind.VariableDeclarationStatement, IsInvalid) (Syntax: 'Dim x, 1 As Integer') IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'x') Variables: Local_1: x As System.Int32 Initializer: null IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration, IsInvalid) (Syntax: '') Variables: Local_1: As System.Int32 Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'x'. Dim x, 1 As Integer'BIND:"Dim x, 1 As Integer" ~ BC30203: Identifier expected. Dim x, 1 As Integer'BIND:"Dim x, 1 As Integer" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17607, "https://github.com/dotnet/roslyn/issues/17607")> Public Sub InvalidSwitchStatementExpression() Dim source = <![CDATA[ Class Program Public Shared Sub Main(args As String()) Select Case Program'BIND:"Select Case Program" Case 1 End Select End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ISwitchStatement (1 cases) (OperationKind.SwitchStatement, IsInvalid) (Syntax: 'Select Case ... End Select') Switch expression: IOperation: (OperationKind.None, IsInvalid) (Syntax: 'Program') Sections: ISwitchCase (1 case clauses, 1 statements) (OperationKind.SwitchCase) (Syntax: 'Case 1') Clauses: ISingleValueCaseClause (CaseKind.SingleValue) (OperationKind.CaseClause) (Syntax: '1') Value: null Body: IBlockStatement (0 statements) (OperationKind.BlockStatement) (Syntax: 'Case 1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30109: 'Program' is a class type and cannot be used as an expression. Select Case Program'BIND:"Select Case Program" ~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of SelectBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17607, "https://github.com/dotnet/roslyn/issues/17607")> Public Sub InvalidSwitchStatementCaseLabel() Dim source = <![CDATA[ Class Program Public Shared Sub Main(args As String()) Dim x = New Program() Select Case x.ToString()'BIND:"Select Case x.ToString()" Case x Exit Select End Select End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ISwitchStatement (1 cases) (OperationKind.SwitchStatement, IsInvalid) (Syntax: 'Select Case ... End Select') Switch expression: IInvocationExpression (virtual Function System.Object.ToString() As System.String) (OperationKind.InvocationExpression, Type: System.String) (Syntax: 'x.ToString()') Instance Receiver: ILocalReferenceExpression: x (OperationKind.LocalReferenceExpression, Type: Program) (Syntax: 'x') Arguments(0) Sections: ISwitchCase (1 case clauses, 1 statements) (OperationKind.SwitchCase, IsInvalid) (Syntax: 'Case x ... Exit Select') Clauses: ISingleValueCaseClause (CaseKind.SingleValue) (OperationKind.CaseClause, IsInvalid) (Syntax: 'x') Value: null Body: IBlockStatement (1 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: 'Case x ... Exit Select') IBranchStatement (BranchKind.Break, Label: exit) (OperationKind.BranchStatement) (Syntax: 'Exit Select') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'Program' cannot be converted to 'String'. Case x ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of SelectBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17607, "https://github.com/dotnet/roslyn/issues/17607")> Public Sub InvalidIfStatement() Dim source = <![CDATA[ Class Program Public Shared Sub Main(args As String()) Dim x = New Program() If x = Nothing Then'BIND:"If x = Nothing Then" End If End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IIfStatement (OperationKind.IfStatement, IsInvalid) (Syntax: 'If x = Noth ... End If') Condition: IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x = Nothing') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IBinaryOperatorExpression (BinaryOperatorKind.Equals, Checked) (OperationKind.BinaryOperatorExpression, Type: ?, IsInvalid) (Syntax: 'x = Nothing') Left: ILocalReferenceExpression: x (OperationKind.LocalReferenceExpression, Type: Program, IsInvalid) (Syntax: 'x') Right: IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: Program, Constant: null, IsInvalid, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: null, Constant: null, IsInvalid) (Syntax: 'Nothing') IfTrue: IBlockStatement (0 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: 'If x = Noth ... End If') IfFalse: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30452: Operator '=' is not defined for types 'Program' and 'Program'. If x = Nothing Then'BIND:"If x = Nothing Then" ~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MultiLineIfBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17607, "https://github.com/dotnet/roslyn/issues/17607")> Public Sub InvalidIfElseIfStatement() Dim source = <![CDATA[ Class Program Public Shared Sub Main(args As String()) Dim x = New Program() If Then'BIND:"If Then" ElseIf x Then x Else End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IIfStatement (OperationKind.IfStatement, IsInvalid) (Syntax: 'If Then'BIN ... Else') Condition: IInvalidExpression (OperationKind.InvalidExpression, Type: null, IsInvalid) (Syntax: '') Children(0) IfTrue: IBlockStatement (0 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: 'If Then'BIN ... Else') IfFalse: IIfStatement (OperationKind.IfStatement, IsInvalid) (Syntax: 'ElseIf x Th ... x') Condition: IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceExpression: x (OperationKind.LocalReferenceExpression, Type: Program, IsInvalid) (Syntax: 'x') IfTrue: IBlockStatement (1 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: 'ElseIf x Th ... x') IExpressionStatement (OperationKind.ExpressionStatement, IsInvalid) (Syntax: 'x') Expression: IInvalidExpression (OperationKind.InvalidExpression, Type: ?, IsInvalid) (Syntax: 'x') Children(1): ILocalReferenceExpression: x (OperationKind.LocalReferenceExpression, Type: Program, IsInvalid) (Syntax: 'x') IfFalse: IBlockStatement (0 statements) (OperationKind.BlockStatement) (Syntax: 'Else') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30081: 'If' must end with a matching 'End If'. If Then'BIND:"If Then" ~~~~~~~ BC30201: Expression expected. If Then'BIND:"If Then" ~ BC30311: Value of type 'Program' cannot be converted to 'Boolean'. ElseIf x Then ~ BC30454: Expression is not a method. x ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MultiLineIfBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17607, "https://github.com/dotnet/roslyn/issues/17607")> Public Sub InvalidForStatement_MissingConditionAndStep() Dim source = <![CDATA[ Module Program Sub Main(args As String()) For i As Integer = 0'BIND:"For i As Integer = 0" Next i End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopStatement (LoopKind.ForTo) (OperationKind.LoopStatement, IsInvalid) (Syntax: 'For i As In ... Next i') Locals: Local_1: i As System.Int32 LoopControlVariable: ILocalReferenceExpression: i (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'i As Integer') InitialValue: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') LimitValue: IInvalidExpression (OperationKind.InvalidExpression, Type: null, IsInvalid) (Syntax: '') Children(0) StepValue: IConversionExpression (Explicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: 'For i As In ... Next i') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'For i As In ... Next i') Body: IBlockStatement (0 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: 'For i As In ... Next i') NextVariables(1): ILocalReferenceExpression: i (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'i') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30035: Syntax error. For i As Integer = 0'BIND:"For i As Integer = 0" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17607, "https://github.com/dotnet/roslyn/issues/17607")> Public Sub InvalidForStatement_MissingConditionAndInitialization() Dim source = <![CDATA[ Module Program Sub Main(args As String()) For Step (Method() + 1)'BIND:"For Step (Method() + 1)" Next End Sub Private Function Method() As Integer Return 0 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopStatement (LoopKind.ForTo) (OperationKind.LoopStatement, IsInvalid) (Syntax: 'For Step (M ... Next') Locals: Local_1: As System.Object LoopControlVariable: ILocalReferenceExpression: (OperationKind.LocalReferenceExpression, Type: System.Object, IsInvalid) (Syntax: '') InitialValue: IInvalidExpression (OperationKind.InvalidExpression, Type: null, IsInvalid) (Syntax: '') Children(0) LimitValue: IInvalidExpression (OperationKind.InvalidExpression, Type: null, IsInvalid) (Syntax: '') Children(0) StepValue: IConversionExpression (Explicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsInvalid) (Syntax: 'For Step (M ... Next') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'For Step (M ... Next') Body: IBlockStatement (0 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: 'For Step (M ... Next') NextVariables(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30035: Syntax error. For Step (Method() + 1)'BIND:"For Step (Method() + 1)" ~ BC30035: Syntax error. For Step (Method() + 1)'BIND:"For Step (Method() + 1)" ~ BC30201: Expression expected. For Step (Method() + 1)'BIND:"For Step (Method() + 1)" ~ BC30249: '=' expected. For Step (Method() + 1)'BIND:"For Step (Method() + 1)" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17607, "https://github.com/dotnet/roslyn/issues/17607")> Public Sub InvalidForStatement_InvalidConditionAndStep() Dim source = <![CDATA[ Module Program Sub Main(args As String()) For i As Integer = 0 To Program Step x'BIND:"For i As Integer = 0 To Program Step x" Next i End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IForToLoopStatement (LoopKind.ForTo) (OperationKind.LoopStatement, IsInvalid) (Syntax: 'For i As In ... Next i') Locals: Local_1: i As System.Int32 LoopControlVariable: ILocalReferenceExpression: i (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'i As Integer') InitialValue: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0) (Syntax: '0') LimitValue: IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Program') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IOperation: (OperationKind.None, IsInvalid) (Syntax: 'Program') StepValue: IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidExpression (OperationKind.InvalidExpression, Type: ?, IsInvalid) (Syntax: 'x') Children(0) Body: IBlockStatement (0 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: 'For i As In ... Next i') NextVariables(1): ILocalReferenceExpression: i (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'i') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30108: 'Program' is a type and cannot be used as an expression. For i As Integer = 0 To Program Step x'BIND:"For i As Integer = 0 To Program Step x" ~~~~~~~ BC30451: 'x' is not declared. It may be inaccessible due to its protection level. For i As Integer = 0 To Program Step x'BIND:"For i As Integer = 0 To Program Step x" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17607, "https://github.com/dotnet/roslyn/issues/17607")> Public Sub InvalidGotoStatement_MissingLabel() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Select Case args.Length Case 1 GoTo Label1'BIND:"GoTo Label1" End Select End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IInvalidStatement (OperationKind.InvalidStatement, IsInvalid) (Syntax: 'GoTo Label1') Children(1): IInvalidExpression (OperationKind.InvalidExpression, Type: null, IsInvalid) (Syntax: 'Label1') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30132: Label 'Label1' is not defined. GoTo Label1'BIND:"GoTo Label1" ~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of GoToStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17607, "https://github.com/dotnet/roslyn/issues/17607")> Public Sub InvalidExitStatement_OutsideLoopOrSwitch() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Exit For'BIND:"Exit For" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IInvalidStatement (OperationKind.InvalidStatement, IsInvalid) (Syntax: 'Exit For') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30096: 'Exit For' can only appear inside a 'For' statement. Exit For'BIND:"Exit For" ~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ExitStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17607, "https://github.com/dotnet/roslyn/issues/17607")> Public Sub InvalidContinueStatement_OutsideLoopOrSwitch() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Continue'BIND:"Continue" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IInvalidStatement (OperationKind.InvalidStatement, IsInvalid) (Syntax: 'Continue') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30782: 'Continue Do' can only appear inside a 'Do' statement. Continue'BIND:"Continue" ~~~~~~~~ BC30781: 'Continue' must be followed by 'Do', 'For' or 'While'. Continue'BIND:"Continue" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ContinueStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17607, "https://github.com/dotnet/roslyn/issues/17607")> Public Sub InvalidCaseStatement_OutsideSwitchBlock() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Case 0'BIND:"Case 0" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IOperation: (OperationKind.None, IsInvalid) (Syntax: 'Case 0') Children(1): ISingleValueCaseClause (CaseKind.SingleValue) (OperationKind.CaseClause, IsInvalid) (Syntax: '0') Value: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30072: 'Case' can only appear inside a 'Select Case' statement. Case 0'BIND:"Case 0" ~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of CaseStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17607, "https://github.com/dotnet/roslyn/issues/17607")> Public Sub InvalidElseIfStatement_NoPrecedingIfStatement() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) ElseIf args.Length = 0'BIND:"ElseIf args.Length = 0" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IInvalidStatement (OperationKind.InvalidStatement, IsInvalid) (Syntax: 'ElseIf args.Length = 0') Children(1): IBinaryOperatorExpression (BinaryOperatorKind.Equals, Checked) (OperationKind.BinaryOperatorExpression, Type: System.Boolean, IsInvalid) (Syntax: 'args.Length = 0') Left: IPropertyReferenceExpression: ReadOnly Property System.Array.Length As System.Int32 (OperationKind.PropertyReferenceExpression, Type: System.Int32, IsInvalid) (Syntax: 'args.Length') Instance Receiver: IParameterReferenceExpression: args (OperationKind.ParameterReferenceExpression, Type: System.String(), IsInvalid) (Syntax: 'args') Right: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36005: 'ElseIf' must be preceded by a matching 'If' or 'ElseIf'. ElseIf args.Length = 0'BIND:"ElseIf args.Length = 0" ~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ElseIfStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub End Class End Namespace
CaptainHayashi/roslyn
src/Compilers/VisualBasic/Test/Semantic/IOperation/IOperationTests_InvalidStatement.vb
Visual Basic
apache-2.0
22,305
Public Class BitBliter #Region " BitBlt Declaration" Private Declare Auto Function BitBlt Lib "GDI32.DLL" ( _ ByVal hdcDest As IntPtr, _ ByVal nXDest As Integer, _ ByVal nYDest As Integer, _ ByVal nWidth As Integer, _ ByVal nHeight As Integer, _ ByVal hdcSrc As IntPtr, _ ByVal nXSrc As Integer, _ ByVal nYSrc As Integer, _ ByVal dwRop As Int32) As Boolean #End Region #Region " Members " ' Public Holders Private MemGrp As Graphics Private MemHdc As IntPtr Private LastSize As Size Private Copied As Boolean #End Region #Region " Interface " 'Interface Public Sub Copy(ByVal srcGraphics As Graphics, ByVal Size As Size) LastSize = Size ' Saving so we'l know how to Paste ' check if already copied If Copied Then DisposeObjects() ' so old objects are disposed ' Creating a temporary Bitmap to create objects of Dim srcBmp As New Bitmap(Size.Width, Size.Height, srcGraphics) ' Creating Objects MemGrp = Graphics.FromImage(srcBmp) 'Create a Graphics object MemHdc = MemGrp.GetHdc 'Get the Device Context '>>> get the picture <<< MyBitBlt(srcGraphics, MemHdc, Size.Width, Size.Height) ' Dispose of the BMP srcBmp.Dispose() Copied = True End Sub Public Sub Paste(ByVal TargetGraphics As Graphics, ByVal X As Integer, ByVal Y As Integer) Dim TargetHdc As IntPtr = TargetGraphics.GetHdc MyBitBlt(MemHdc, TargetHdc, LastSize.Width, LastSize.Height, X, Y) TargetGraphics.ReleaseHdc(TargetHdc) End Sub #End Region #Region " Internals " Const SRCCOPY As Integer = &HCC0020 ' Wraping things up Private Sub MyBitBlt(ByVal SourceGraphics As Graphics, ByVal TargetHDC As IntPtr, ByVal width As Integer, ByVal Height As Integer) ' Creating a DeviceContext to capture from Dim SourceHDC As IntPtr = SourceGraphics.GetHdc ' Blitting (Copying) the data BitBlt(TargetHDC, 0, 0, width, Height, SourceHDC, 0, 0, SRCCOPY) ' Releasing the Device context used SourceGraphics.ReleaseHdc(SourceHDC) End Sub Private Sub MyBitBlt(ByVal SourceHDC As IntPtr, ByVal TargetHDC As IntPtr, ByVal width As Integer, ByVal Height As Integer, ByVal PosX As Integer, ByVal PosY As Integer) ' Copying data to a specific position on the target Device Context BitBlt(TargetHDC, PosX, PosY, width, Height, SourceHDC, 0, 0, SRCCOPY) End Sub ' Cleanning Up ' Before Destroying this class, dispose of objects to reclaim memory Protected Overrides Sub Finalize() DisposeObjects() MyBase.Finalize() End Sub ' Disposing of objects Private Sub DisposeObjects() MemGrp.ReleaseHdc(MemHdc) ' Release Device Context MemGrp.Dispose() ' Disposing of Graphics object End Sub #End Region End Class
tomasbrod/Gridcoin-Research
contrib/Installer/boinc/boinc/GRCWireFrameCopierClass.vb
Visual Basic
mit
2,975
' 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.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports ProprietaryTestResources = Microsoft.CodeAnalysis.Test.Resources.Proprietary Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE Public Class TypeForwarders : Inherits BasicTestBase <Fact> Public Sub Test1() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences( {TestResources.SymbolsTests.TypeForwarders.TypeForwarder, TestResources.SymbolsTests.TypeForwarders.TypeForwarderLib, TestResources.SymbolsTests.TypeForwarders.TypeForwarderBase, ProprietaryTestResources.NetFX.v4_0_21006.mscorlib}) TestTypeForwarderHelper(assemblies) End Sub Private Sub TestTypeForwarderHelper(assemblies() As AssemblySymbol) Dim module1 = DirectCast(assemblies(0).Modules(0), PEModuleSymbol) Dim module2 = DirectCast(assemblies(1).Modules(0), PEModuleSymbol) Dim assembly2 = DirectCast(assemblies(1), MetadataOrSourceAssemblySymbol) Dim assembly3 = DirectCast(assemblies(2), MetadataOrSourceAssemblySymbol) Dim derived1 = DirectCast(module1.GlobalNamespace.GetMembers("Derived").Single(), NamedTypeSymbol) Dim base1 = derived1.BaseType BaseTypeResolution.AssertBaseType(base1, "Base") Dim derived4 = DirectCast(module1.GlobalNamespace.GetMembers("GenericDerived").Single(), NamedTypeSymbol) Dim base4 = derived4.BaseType BaseTypeResolution.AssertBaseType(base4, "GenericBase(Of K)") Dim derived6 = DirectCast(module1.GlobalNamespace.GetMembers("GenericDerived1").Single(), NamedTypeSymbol) Dim base6 = derived6.BaseType BaseTypeResolution.AssertBaseType(base6, "GenericBase(Of K).NestedGenericBase(Of L)") Assert.Equal(assembly3, base1.ContainingAssembly) Assert.Equal(assembly3, base4.ContainingAssembly) Assert.Equal(assembly3, base6.ContainingAssembly) Assert.Equal(base1, module1.TypeRefHandleToTypeMap(CType(module1.Module.GetBaseTypeOfTypeOrThrow(DirectCast(derived1, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Assert.True(module1.TypeRefHandleToTypeMap.Values.Contains(DirectCast(base4.OriginalDefinition, TypeSymbol))) Assert.True(module1.TypeRefHandleToTypeMap.Values.Contains(DirectCast(base6.OriginalDefinition, TypeSymbol))) Assert.Equal(base1, assembly2.CachedTypeByEmittedName(base1.ToTestDisplayString())) Assert.Equal(base4.OriginalDefinition, assembly2.CachedTypeByEmittedName("GenericBase`1")) Assert.Equal(2, assembly2.EmittedNameToTypeMapCount) Assert.Equal(base1, assembly3.CachedTypeByEmittedName(base1.ToTestDisplayString())) Assert.Equal(base4.OriginalDefinition, assembly3.CachedTypeByEmittedName("GenericBase`1")) Assert.Equal(2, assembly3.EmittedNameToTypeMapCount) Dim derived2 = DirectCast(module2.GlobalNamespace.GetMembers("Derived").Single(), NamedTypeSymbol) Dim base2 = derived2.BaseType BaseTypeResolution.AssertBaseType(base2, "Base") Assert.Same(base1, base2) Dim derived3 = DirectCast(module2.GlobalNamespace.GetMembers("GenericDerived").Single(), NamedTypeSymbol) Dim base3 = derived3.BaseType BaseTypeResolution.AssertBaseType(base3, "GenericBase(Of S)") Dim derived5 = DirectCast(module2.GlobalNamespace.GetMembers("GenericDerived1").Single(), NamedTypeSymbol) Dim base5 = derived5.BaseType BaseTypeResolution.AssertBaseType(base5, "GenericBase(Of S1).NestedGenericBase(Of S2)") End Sub <Fact> Public Sub TypeInNamespace() Dim comp = VisualBasicCompilation.Create("Dummy", references:={MscorlibRef, SystemCoreRef}) Dim corlibAssembly = comp.GetReferencedAssemblySymbol(MscorlibRef) Assert.NotNull(corlibAssembly) Dim systemCoreAssembly = comp.GetReferencedAssemblySymbol(SystemCoreRef) Assert.NotNull(systemCoreAssembly) Const funcTypeMetadataName As String = "System.Func`1" ' mscorlib contains this type, so we should be able to find it without looking in referenced assemblies. Dim funcType = corlibAssembly.GetTypeByMetadataName(funcTypeMetadataName, includeReferences:=False, isWellKnownType:=True) Assert.NotNull(funcType) Assert.NotEqual(TypeKind.Error, funcType.TypeKind) Assert.Equal(corlibAssembly, funcType.ContainingAssembly) ' System.Core forwards to mscorlib for System.Func`1. Assert.Equal(funcType, systemCoreAssembly.ResolveForwardedType(funcTypeMetadataName)) ' The compilation assembly references both mscorlib and System.Core, but finding ' System.Func`1 in both isn't ambiguous because one forwards to the other. Assert.Equal(funcType, comp.Assembly.GetTypeByMetadataName(funcTypeMetadataName, includeReferences:=True, isWellKnownType:=True)) End Sub ''' <summary> ''' pe1 -> pe3; pe2 -> pe3 ''' </summary> <Fact> Public Sub Diamond() Dim il1 = <![CDATA[ .assembly extern pe3 { } .assembly pe1 { } .class extern forwarder Base { .assembly extern pe3 } ]]> Dim il2 = <![CDATA[ .assembly extern pe3 { } .assembly pe2 { } .class extern forwarder Base { .assembly extern pe3 } ]]> Dim il3 = <![CDATA[ .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly pe3 { } .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } ]]> Dim vb = <compilation name="TypeForwarders"> <file name="a.vb"> Option Strict On Class Derived Inherits Base End Class </file> </compilation> Dim ref1 = CompileIL(il1.Value, appendDefaultHeader:=False) Dim ref2 = CompileIL(il2.Value, appendDefaultHeader:=False) Dim ref3 = CompileIL(il3.Value, appendDefaultHeader:=False) Dim compilation = CreateCompilationWithMscorlibAndReferences(vb, {ref1, ref2, ref3}) Dim ilAssembly1 = compilation.GetReferencedAssemblySymbol(ref1) Assert.NotNull(ilAssembly1) Assert.Equal("pe1", ilAssembly1.Name) Dim ilAssembly2 = compilation.GetReferencedAssemblySymbol(ref2) Assert.NotNull(ilAssembly2) Assert.Equal("pe2", ilAssembly2.Name) Dim ilAssembly3 = compilation.GetReferencedAssemblySymbol(ref3) Assert.NotNull(ilAssembly3) Assert.Equal("pe3", ilAssembly3.Name) Dim baseType = ilAssembly3.GetTypeByMetadataName("Base") Assert.NotNull(baseType) Assert.False(baseType.IsErrorType()) Assert.Equal(baseType, ilAssembly1.ResolveForwardedType("Base")) Assert.Equal(baseType, ilAssembly2.ResolveForwardedType("Base")) Dim derivedType = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Derived") Assert.Equal(baseType, derivedType.BaseType) ' All forwards resolve to the same type, so there's no issue. compilation.VerifyDiagnostics() End Sub ''' <summary> ''' pe1 -> pe2 -> pe1 ''' </summary> <Fact> Public Sub Cycle1() Dim il1 = <![CDATA[ .assembly extern pe2 { } .assembly pe1 { } .class extern forwarder Base { .assembly extern pe2 } ]]> Dim il2 = <![CDATA[ .assembly extern pe1 { } .assembly pe2 { } .class extern forwarder Base { .assembly extern pe1 } ]]> Dim vb = <compilation name="TypeForwarders"> <file name="a.vb"> Option Strict On Class Derived Inherits Base End Class </file> </compilation> Dim ref1 = CompileIL(il1.Value, appendDefaultHeader:=False) Dim ref2 = CompileIL(il2.Value, appendDefaultHeader:=False) Dim compilation = CreateCompilationWithMscorlibAndReferences(vb, {ref1, ref2}) Dim ilAssembly1 = compilation.GetReferencedAssemblySymbol(ref1) Assert.NotNull(ilAssembly1) Assert.Equal("pe1", ilAssembly1.Name) Dim ilAssembly2 = compilation.GetReferencedAssemblySymbol(ref2) Assert.NotNull(ilAssembly2) Assert.Equal("pe2", ilAssembly2.Name) Assert.Null(ilAssembly1.GetTypeByMetadataName("Base")) Assert.Null(ilAssembly2.GetTypeByMetadataName("Base")) ' NOTE: the type isn't actually defined in any of the referenced assemblies, ' so lookup fails. ' CONSIDER: Dev10 actually reports ERR_AmbiguousInUnnamedNamespace1 instead of ERR_ForwardedTypeUnavailable3, ' but that seems less accurate. compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_ForwardedTypeUnavailable3, "Base").WithArguments("Base", "TypeForwarders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), Diagnostic(ERRID.ERR_TypeFwdCycle2, "Base").WithArguments("Base", "pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")) End Sub ''' <summary> ''' pe1 -> pe2 -> pe3 -> pe1 ''' </summary> <Fact> Public Sub Cycle2() Dim il1 = <![CDATA[ .assembly extern pe2 { } .assembly pe1 { } .class extern forwarder Base { .assembly extern pe2 } ]]> Dim il2 = <![CDATA[ .assembly extern pe3 { } .assembly pe2 { } .class extern forwarder Base { .assembly extern pe3 } ]]> Dim il3 = <![CDATA[ .assembly extern pe1 { } .assembly pe3 { } .class extern forwarder Base { .assembly extern pe1 } ]]> Dim vb = <compilation name="TypeForwarders"> <file name="a.vb"> Option Strict On Class Derived Shared Sub Main() Dim b = new Base() End Sub End Class </file> </compilation> Dim ref1 = CompileIL(il1.Value, appendDefaultHeader:=False) Dim ref2 = CompileIL(il2.Value, appendDefaultHeader:=False) Dim ref3 = CompileIL(il3.Value, appendDefaultHeader:=False) Dim compilation = CreateCompilationWithMscorlibAndReferences(vb, {ref1, ref2, ref3}) Dim ilAssembly1 = compilation.GetReferencedAssemblySymbol(ref1) Assert.NotNull(ilAssembly1) Assert.Equal("pe1", ilAssembly1.Name) Dim ilAssembly2 = compilation.GetReferencedAssemblySymbol(ref2) Assert.NotNull(ilAssembly2) Assert.Equal("pe2", ilAssembly2.Name) Dim ilAssembly3 = compilation.GetReferencedAssemblySymbol(ref3) Assert.NotNull(ilAssembly3) Assert.Equal("pe3", ilAssembly3.Name) Assert.Null(ilAssembly1.GetTypeByMetadataName("Base")) Assert.Null(ilAssembly2.GetTypeByMetadataName("Base")) Assert.Null(ilAssembly3.GetTypeByMetadataName("Base")) ' NOTE: the type isn't actually defined in any of the referenced assemblies, ' so lookup fails. ' CONSIDER: Dev10 actually reports ERR_AmbiguousInUnnamedNamespace1 instead of ERR_ForwardedTypeUnavailable3, ' but that seems less accurate. compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_ForwardedTypeUnavailable3, "Base").WithArguments("Base", "TypeForwarders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "pe3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), Diagnostic(ERRID.ERR_TypeFwdCycle2, "Base").WithArguments("Base", "pe3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")) End Sub ''' <summary> ''' pe1 -> pe2 -> pe1; pe3 -> pe4 ''' </summary> <Fact> Public Sub Cycle3() Dim il1 = <![CDATA[ .assembly extern pe2 { } .assembly pe1 { } .class extern forwarder Base { .assembly extern pe2 } ]]> Dim il2 = <![CDATA[ .assembly extern pe1 { } .assembly pe2 { } .class extern forwarder Base { .assembly extern pe1 } ]]> Dim il3 = <![CDATA[ .assembly extern pe4 { } .assembly pe3 { } .class extern forwarder Base { .assembly extern pe4 } ]]> Dim il4 = <![CDATA[ .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly pe4 { } .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } ]]> Dim vb = <compilation name="TypeForwarders"> <file name="a.vb"> Option Strict On Class Derived Inherits Base End Class </file> </compilation> Dim ref1 = CompileIL(il1.Value, appendDefaultHeader:=False) Dim ref2 = CompileIL(il2.Value, appendDefaultHeader:=False) Dim ref3 = CompileIL(il3.Value, appendDefaultHeader:=False) Dim ref4 = CompileIL(il4.Value, appendDefaultHeader:=False) Dim compilation = CreateCompilationWithMscorlibAndReferences(vb, {ref1, ref2, ref3, ref4}) Dim ilAssembly1 = compilation.GetReferencedAssemblySymbol(ref1) Assert.NotNull(ilAssembly1) Assert.Equal("pe1", ilAssembly1.Name) Dim ilAssembly2 = compilation.GetReferencedAssemblySymbol(ref2) Assert.NotNull(ilAssembly2) Assert.Equal("pe2", ilAssembly2.Name) Dim ilAssembly3 = compilation.GetReferencedAssemblySymbol(ref3) Assert.NotNull(ilAssembly3) Assert.Equal("pe3", ilAssembly3.Name) Dim ilAssembly4 = compilation.GetReferencedAssemblySymbol(ref4) Assert.NotNull(ilAssembly4) Assert.Equal("pe4", ilAssembly4.Name) Dim baseType = ilAssembly4.GetTypeByMetadataName("Base") Assert.NotNull(baseType) Assert.False(baseType.IsErrorType()) Assert.Null(ilAssembly1.GetTypeByMetadataName("Base")) Assert.True(ilAssembly1.ResolveForwardedType("Base").IsErrorType()) Assert.Null(ilAssembly2.GetTypeByMetadataName("Base")) Assert.True(ilAssembly2.ResolveForwardedType("Base").IsErrorType()) Assert.Equal(baseType, ilAssembly3.ResolveForwardedType("Base")) Dim derivedType = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Derived") Assert.Equal(baseType, derivedType.BaseType) ' Find the type even though there's a cycle. compilation.VerifyDiagnostics() End Sub ''' <summary> ''' pe1 -> pe2 -> pe1; pe3 depends upon the cyclic type. ''' </summary> ''' <remarks> ''' Only produced when the infinitely forwarded type is consumed via a metadata symbol ''' </remarks> <Fact> Public Sub ERR_TypeFwdCycle2() Dim il1 = <![CDATA[ .assembly extern pe2 { } .assembly pe1 { } .class extern forwarder Cycle { .assembly extern pe2 } ]]> Dim il2 = <![CDATA[ .assembly extern pe1 { } .assembly pe2 { } .class extern forwarder Cycle { .assembly extern pe1 } ]]> Dim il3 = <![CDATA[ .assembly extern pe1 { } .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly pe3 { } .class public auto ansi beforefieldinit UseSite extends [mscorlib]System.Object { .method public hidebysig instance class [pe1]Cycle Foo() cil managed { ldnull ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Test ]]> Dim vb = <compilation name="TypeForwarders"> <file name="a.vb"> Option Strict On Class Derived Shared Sub Main() Dim us as New UseSite() us.Foo() End Sub End Class </file> </compilation> Dim ref1 = CompileIL(il1.Value, appendDefaultHeader:=False) Dim ref2 = CompileIL(il2.Value, appendDefaultHeader:=False) Dim ref3 = CompileIL(il3.Value, appendDefaultHeader:=False) Dim compilation = CreateCompilationWithMscorlibAndReferences(vb, {ref1, ref2, ref3}) Dim ilAssembly1 = compilation.GetReferencedAssemblySymbol(ref1) Assert.NotNull(ilAssembly1) Assert.Equal("pe1", ilAssembly1.Name) Dim ilAssembly2 = compilation.GetReferencedAssemblySymbol(ref2) Assert.NotNull(ilAssembly2) Assert.Equal("pe2", ilAssembly2.Name) Dim ilAssembly3 = compilation.GetReferencedAssemblySymbol(ref3) Assert.NotNull(ilAssembly3) Assert.Equal("pe3", ilAssembly3.Name) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_TypeFwdCycle2, "us.Foo()").WithArguments("Cycle", "pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")) End Sub ''' <summary> ''' pe1 -> pe2 -> pe1 ''' </summary> <Fact> Public Sub SpecialTypeCycle() Dim il1 = <![CDATA[ .assembly extern pe2 { } .assembly pe1 { } .class extern forwarder System.String { .assembly extern pe2 } ]]> Dim il2 = <![CDATA[ .assembly extern pe1 { } .assembly pe2 { } .class extern forwarder System.String { .assembly extern pe1 } ]]> Dim vb = <compilation name="TypeForwarders"> <file name="a.vb"> Option Strict On Class Derived Property P As System.String Get Return Nothing End Get Set(ByVal value As System.String) End Set End Property End Class </file> </compilation> Dim ref1 = CompileIL(il1.Value, appendDefaultHeader:=False) Dim ref2 = CompileIL(il2.Value, appendDefaultHeader:=False) Dim compilation = CreateCompilationWithMscorlibAndReferences(vb, {ref1, ref2}) Dim ilAssembly1 = compilation.GetReferencedAssemblySymbol(ref1) Assert.NotNull(ilAssembly1) Assert.Equal("pe1", ilAssembly1.Name) Dim ilAssembly2 = compilation.GetReferencedAssemblySymbol(ref2) Assert.NotNull(ilAssembly2) Assert.Equal("pe2", ilAssembly2.Name) Assert.Null(ilAssembly1.GetTypeByMetadataName("System.String")) Assert.Null(ilAssembly2.GetTypeByMetadataName("System.String")) ' NOTE: We have a reference to the real System.String, so the cycle doesn't cause problems. compilation.VerifyDiagnostics() End Sub ''' <summary> ''' pe1 -> pe2. ''' </summary> <Fact> Public Sub Generic() Dim il1 = <![CDATA[ .assembly extern pe2 { } .assembly pe1 { } .class extern forwarder Generic`1 { .assembly extern pe2 } ]]> Dim il2 = <![CDATA[ .assembly extern mscorlib { } .assembly pe2 { } .class public auto ansi beforefieldinit Generic`1<T> extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Generic`1 ]]> Dim vb = <compilation name="TypeForwarders"> <file name="a.vb"> Option Strict On Class Derived Shared Sub Main() Dim g as new Generic(Of Integer)() End Sub End Class </file> </compilation> Dim ref1 = CompileIL(il1.Value, appendDefaultHeader:=False) Dim ref2 = CompileIL(il2.Value, appendDefaultHeader:=False) CreateCompilationWithMscorlibAndReferences(vb, {ref1, ref2}).VerifyDiagnostics() End Sub ''' <summary> ''' pe1 -> pe2. ''' </summary> <Fact> Public Sub Nested() Dim il1 = <![CDATA[ .assembly extern pe2 { } .assembly pe1 { } .class extern forwarder Outer { .assembly extern pe2 } .class extern Inner { .class extern Outer } ]]> Dim il2 = <![CDATA[ .assembly extern mscorlib { } .assembly pe2 { } .class public auto ansi beforefieldinit Outer extends [mscorlib]System.Object { .class auto ansi nested public beforefieldinit Inner extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Inner .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Outer ]]> Dim vb = <compilation name="TypeForwarders"> <file name="a.vb"> Option Strict On Class Derived Shared Sub Main() Dim o as new Outer() Dim i as new Outer.Inner() End Sub End Class </file> </compilation> Dim ref1 = CompileIL(il1.Value, appendDefaultHeader:=False) Dim ref2 = CompileIL(il2.Value, appendDefaultHeader:=False) CreateCompilationWithMscorlibAndReferences(vb, {ref1, ref2}).VerifyDiagnostics() End Sub <Fact> Public Sub LookupMissingForwardedType() Dim il1 = <![CDATA[ .assembly extern pe2 { } .assembly extern mscorlib { } .assembly pe1 { } .class extern forwarder Outer { .assembly extern pe2 } .class extern Inner { .class extern Outer } .class extern forwarder Generic`1 { .assembly extern pe2 } ]]> Dim vb = <compilation name="TypeForwarders"> <file name="a.vb"> Option Strict On Class Test ReadOnly Property P As Outer Get Return Nothing End Get End Property Function M() As Outer.Inner Return Nothing End Function Private F As Outer.Inner(Of String) Private G0 As Generic Private G1 As Generic(Of Integer) Private G2 As Generic(Of Integer, Integer) End Class </file> </compilation> Dim ref1 = CompileIL(il1.Value, appendDefaultHeader:=False) CreateCompilationWithMscorlibAndReferences(vb, {ref1}).VerifyDiagnostics( Diagnostic(ERRID.ERR_ForwardedTypeUnavailable3, "Outer").WithArguments("Outer", "TypeForwarders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), Diagnostic(ERRID.ERR_ForwardedTypeUnavailable3, "Outer").WithArguments("Outer", "TypeForwarders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), Diagnostic(ERRID.ERR_ForwardedTypeUnavailable3, "Outer").WithArguments("Outer", "TypeForwarders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), Diagnostic(ERRID.ERR_UndefinedType1, "Generic").WithArguments("Generic"), Diagnostic(ERRID.ERR_ForwardedTypeUnavailable3, "Generic(Of Integer)").WithArguments("Generic", "TypeForwarders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), Diagnostic(ERRID.ERR_UndefinedType1, "Generic(Of Integer, Integer)").WithArguments("Generic")) End Sub <Fact> Public Sub LookupMissingForwardedTypeIgnoringCase() Dim il1 = <![CDATA[ .assembly extern pe2 { } .assembly pe1 { } .class extern forwarder UPPER { .assembly extern pe2 } .class extern forwarder lower.mIxEd { .assembly extern pe2 } ]]> Dim vb = <compilation name="TypeForwarders"> <file name="a.vb"> Option Strict On Class Test Private F1 As upper Private F2 As uPPeR Private F3 As LOWER.mixed Private F4 As lOwEr.MIXED End Class </file> </compilation> Dim ref1 = CompileIL(il1.Value, appendDefaultHeader:=False) CreateCompilationWithMscorlibAndReferences(vb, {ref1}).VerifyDiagnostics( Diagnostic(ERRID.ERR_ForwardedTypeUnavailable3, "upper").WithArguments("upper", "TypeForwarders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), Diagnostic(ERRID.ERR_ForwardedTypeUnavailable3, "uPPeR").WithArguments("uPPeR", "TypeForwarders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), Diagnostic(ERRID.ERR_ForwardedTypeUnavailable3, "LOWER.mixed").WithArguments("LOWER.mixed", "TypeForwarders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), Diagnostic(ERRID.ERR_ForwardedTypeUnavailable3, "lOwEr.MIXED").WithArguments("lOwEr.MIXED", "TypeForwarders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")) End Sub <Fact> Public Sub NamespacesOnlyMentionedInForwarders() Dim il1 = <![CDATA[ .assembly extern pe2 { } .assembly extern mscorlib { } .assembly pe1 { } .class extern forwarder T0 { .assembly extern pe2 } .class extern forwarder Ns.T1 { .assembly extern pe2 } .class extern forwarder Ns.Ms.T2 { .assembly extern pe2 } ]]> ' NOTE: case doesn't match Dim vb = <compilation name="TypeForwarders"> <file name="a.vb"> Option Strict On Class Test Private F0 As t0 Private F1 As ns.t1 Private F2 As ns.ms.t2 Private F3 As ns.ms.ls.t3 Private F4 As nope Private F5 As ns.nope Private F6 As ns.ms.nope Private F7 As ns.ms.ls.nope End Class </file> </compilation> Dim ref1 = CompileIL(il1.Value, appendDefaultHeader:=False) Dim compilation = CreateCompilationWithMscorlibAndReferences(vb, {ref1}) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_ForwardedTypeUnavailable3, "t0").WithArguments("t0", "TypeForwarders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), Diagnostic(ERRID.ERR_ForwardedTypeUnavailable3, "ns.t1").WithArguments("ns.t1", "TypeForwarders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), Diagnostic(ERRID.ERR_ForwardedTypeUnavailable3, "ns.ms.t2").WithArguments("ns.ms.t2", "TypeForwarders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), Diagnostic(ERRID.ERR_UndefinedType1, "ns.ms.ls.t3").WithArguments("ns.ms.ls.t3"), Diagnostic(ERRID.ERR_UndefinedType1, "nope").WithArguments("nope"), Diagnostic(ERRID.ERR_UndefinedType1, "ns.nope").WithArguments("ns.nope"), Diagnostic(ERRID.ERR_UndefinedType1, "ns.ms.nope").WithArguments("ns.ms.nope"), Diagnostic(ERRID.ERR_UndefinedType1, "ns.ms.ls.nope").WithArguments("ns.ms.ls.nope")) Dim actualNamespaces = EnumerateNamespaces(compilation).Where(Function(ns) Not ns.StartsWith("System", StringComparison.Ordinal) AndAlso Not ns.StartsWith("Microsoft", StringComparison.Ordinal)) Dim expectedNamespaces = {"Ns", "Ns.Ms"} Assert.True(actualNamespaces.SetEquals(expectedNamespaces, EqualityComparer(Of String).Default)) End Sub <Fact> Public Sub NamespacesMentionedInForwarders() Dim il1 = <![CDATA[ .assembly extern pe2 { } .assembly extern mscorlib { } .assembly pe1 { } .class extern forwarder N1.N2.N3.T { .assembly extern pe2 } .class public auto ansi beforefieldinit N1.N2.T extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class N1.N2.T ]]> ' NOTE: case doesn't match Dim vb = <compilation name="TypeForwarders"> <file name="a.vb"> Option Strict On Namespace N1 Class Test Private T0 As n2.t Private T1 As n2.n3.t Private T2 As n1.n2.t Private T3 As n1.n2.n3.t End Class End Namespace </file> </compilation> Dim ref1 = CompileIL(il1.Value, appendDefaultHeader:=False) Dim compilation = CreateCompilationWithMscorlibAndReferences(vb, {ref1}) ' TODO: it would be nice if we could report ERR_ForwardedTypeUnavailable3 in the first ' case as well (see DevDiv #14280). compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_UndefinedType1, "n2.n3.t").WithArguments("n2.n3.t"), Diagnostic(ERRID.ERR_ForwardedTypeUnavailable3, "n1.n2.n3.t").WithArguments("n1.n2.n3.t", "TypeForwarders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")) Dim actualNamespaces = EnumerateNamespaces(compilation).Where(Function(ns) Not ns.StartsWith("System", StringComparison.Ordinal) AndAlso Not ns.StartsWith("Microsoft", StringComparison.Ordinal)) Dim expectedNamespaces = {"N1", "N1.N2", "N1.N2.N3"} Assert.True(actualNamespaces.SetEquals(expectedNamespaces, EqualityComparer(Of String).Default)) End Sub Private Shared Function EnumerateNamespaces(comp As VisualBasicCompilation) As IEnumerable(Of String) Return EnumerateNamespaces(comp.GlobalNamespace, "") End Function Private Shared Function EnumerateNamespaces([namespace] As NamespaceSymbol, baseName As String) As IEnumerable(Of String) Dim result As New List(Of String) For Each child In [namespace].GetNamespaceMembers() Dim childName = If(String.IsNullOrEmpty(baseName), child.Name, baseName + "." + child.Name) result.Add(childName) Dim seq = EnumerateNamespaces(child, childName) result.AddRange(seq) Next Return result End Function <Fact> Public Sub TypeForwardedToAttribute() Dim source = <compilation name="TypeForwarders"> <file name="a.vb"> &lt;Assembly: System.Runtime.CompilerServices.TypeForwardedTo(GetType(Forwarded))&gt; Class Forwarded End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseDll) ' Attribute is erased. This is an intentional change in behavior by comparison to Dev12. Dim verifier = CompileAndVerify(compilation, sourceSymbolValidator:=Sub(moduleSymbol) Assert.Equal(1, moduleSymbol.ContainingAssembly.GetAttributes(AttributeDescription.TypeForwardedToAttribute).Count) End Sub, symbolValidator:=Sub(moduleSymbol) Assert.Equal(0, moduleSymbol.ContainingAssembly.GetAttributes(AttributeDescription.TypeForwardedToAttribute).Count) End Sub) Using metadata = ModuleMetadata.CreateFromImage(verifier.EmittedAssemblyData) ' No entries in the ExportedType table. Dim peReader = metadata.Module.GetMetadataReader() Assert.Equal(0, peReader.GetTableRowCount(TableIndex.ExportedType)) End Using End Sub <Fact> Public Sub TypeForwarderInAModule() Dim forwardedTypes = <compilation name="ForwarderTargetAssembly"> <file name="a.vb"> Public Class CF1 End Class </file> </compilation> Dim forwardedTypesCompilation = CreateCompilationWithMscorlib(forwardedTypes, TestOptions.ReleaseDll) Dim netmod = <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(GetType(CF1))> ]]></file> </compilation> Dim modCompilation = CreateCompilationWithMscorlibAndReferences(netmod, {New VisualBasicCompilationReference(forwardedTypesCompilation)}, TestOptions.ReleaseModule) Dim modRef = modCompilation.EmitToImageReference() Dim app = <compilation> <file name="a.vb"><![CDATA[ public class Test End class ]]></file> </compilation> Dim appCompilation = CreateCompilationWithMscorlibAndReferences(app, {modRef}, TestOptions.ReleaseDll) Dim peModule = DirectCast(appCompilation.Assembly.Modules(1), PEModuleSymbol) Dim metadata = peModule.Module Dim metadataReader = metadata.GetMetadataReader() Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)) Dim token As EntityHandle = metadata.GetTypeRef(metadata.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM") Assert.True(token.IsNil) CompileAndVerify(appCompilation, symbolValidator:=Sub(m) Dim peReader1 = DirectCast(m, PEModuleSymbol).Module.GetMetadataReader() Assert.Equal(0, peReader1.GetTableRowCount(TableIndex.ExportedType)) Assert.Equal(0, m.ContainingAssembly.GetAttributes(AttributeDescription.TypeForwardedToAttribute).Count) End Sub ).VerifyDiagnostics() Dim ilSource1 = <![CDATA[ .assembly extern ForwarderTargetAssembly { .ver 0:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .class extern forwarder CF1 { .assembly extern ForwarderTargetAssembly } .module mod.netmodule // MVID: {C39224E6-1B32-4C27-98ED-8F2FE3CC5358} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00840000 ]]> Dim ilBytes As ImmutableArray(Of Byte) = Nothing Using reference = SharedCompilationUtils.IlasmTempAssembly(ilSource1.Value, appendDefaultHeader:=False) ilBytes = ReadFromFile(reference.Path) End Using Dim modRef1 = ModuleMetadata.CreateFromImage(ilBytes).GetReference() appCompilation = CreateCompilationWithMscorlibAndReferences(app, {modRef1, New VisualBasicCompilationReference(forwardedTypesCompilation)}, TestOptions.ReleaseDll) peModule = DirectCast(appCompilation.Assembly.Modules(1), PEModuleSymbol) metadata = peModule.Module metadataReader = metadata.GetMetadataReader() Assert.Equal(1, metadataReader.GetTableRowCount(TableIndex.ExportedType)) ValidateExportedTypeRow(metadataReader.ExportedTypes.First(), metadataReader, "CF1") token = metadata.GetTypeRef(metadata.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM") Assert.True(token.IsNil) 'could the type ref be located? If not then the attribute's not there. ' Exported types in .Net module cause PEVerify to fail. CompileAndVerify(appCompilation, verify:=False, symbolValidator:=Sub(m) Dim metadataReader1 = DirectCast(m, PEModuleSymbol).Module.GetMetadataReader() Assert.Equal(1, metadataReader1.GetTableRowCount(TableIndex.ExportedType)) ValidateExportedTypeRow(metadataReader1.ExportedTypes.First(), metadataReader1, "CF1") ' Attributes should not actually be emitted. Assert.Equal(0, m.ContainingAssembly.GetAttributes(AttributeDescription.TypeForwardedToAttribute).Count()) End Sub ).VerifyDiagnostics() Dim ilSource2 = <![CDATA[ .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern Microsoft.VisualBasic { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 10:0:0:0 } .assembly extern ForwarderTargetAssembly { .ver 0:0:0:0 } .module mod.netmodule // MVID: {EFC6E215-2156-4ACE-A787-67C58990AEB5} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0002 // WINDOWS_GUI .corflags 0x00000001 // ILONLY // Image base: 0x00980000 .custom ([mscorlib]System.Runtime.CompilerServices.AssemblyAttributesGoHereM) instance void [mscorlib]System.Runtime.CompilerServices.TypeForwardedToAttribute::.ctor(class [mscorlib]System.Type) = {type(class 'CF1, ForwarderTargetAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null')} ]]> Using reference = SharedCompilationUtils.IlasmTempAssembly(ilSource2.Value, appendDefaultHeader:=False) ilBytes = ReadFromFile(reference.Path) End Using Dim modRef2 = ModuleMetadata.CreateFromImage(ilBytes).GetReference() appCompilation = CreateCompilationWithMscorlibAndReferences(app, {modRef2, New VisualBasicCompilationReference(forwardedTypesCompilation)}, TestOptions.ReleaseDll) peModule = DirectCast(appCompilation.Assembly.Modules(1), PEModuleSymbol) metadata = peModule.Module metadataReader = metadata.GetMetadataReader() Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)) token = metadata.GetTypeRef(metadata.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM") Assert.False(token.IsNil) 'could the type ref be located? If not then the attribute's not there. Assert.Equal(1, metadataReader.CustomAttributes.Count) CompileAndVerify(appCompilation, symbolValidator:=Sub(m) Dim metadataReader1 = DirectCast(m, PEModuleSymbol).Module.GetMetadataReader() Assert.Equal(0, metadataReader1.GetTableRowCount(TableIndex.ExportedType)) ' Attributes should not actually be emitted. Assert.Equal(0, m.ContainingAssembly.GetAttributes(AttributeDescription.TypeForwardedToAttribute).Count()) End Sub ).VerifyDiagnostics() appCompilation = CreateCompilationWithMscorlibAndReferences(app, {modRef1, New VisualBasicCompilationReference(forwardedTypesCompilation)}, TestOptions.ReleaseModule) Dim appModule = ModuleMetadata.CreateFromImage(appCompilation.EmitToArray()).Module metadataReader = appModule.GetMetadataReader() Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)) token = appModule.GetTypeRef(appModule.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM") Assert.True(token.IsNil) 'could the type ref be located? If not then the attribute's not there. appCompilation = CreateCompilationWithMscorlibAndReferences(app, {modRef1}, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(appCompilation, <expected> BC30652: Reference required to assembly 'ForwarderTargetAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'CF1'. Add one to your project. </expected>) End Sub Private Shared Sub ValidateExportedTypeRow(exportedTypeHandle As ExportedTypeHandle, reader As MetadataReader, expectedFullName As String) Dim exportedTypeRow As ExportedType = reader.GetExportedType(exportedTypeHandle) Dim split = expectedFullName.Split("."c) Dim numParts As Integer = split.Length Assert.InRange(numParts, 1, Integer.MaxValue) Dim expectedType = split(numParts - 1) Dim expectedNamespace = String.Join(".", split, 0, numParts - 1) If expectedFullName.Contains("+"c) Then Assert.Equal(0, exportedTypeRow.Attributes And TypeAttributesMissing.Forwarder) Assert.Equal(0, exportedTypeRow.GetTypeDefinitionId()) Assert.Equal(expectedType.Split("+"c).Last(), reader.GetString(exportedTypeRow.Name)) 'Only the actual type name. Assert.Equal("", reader.GetString(exportedTypeRow.Namespace)) 'Empty - presumably there's enough info on the containing type. Assert.Equal(HandleKind.ExportedType, exportedTypeRow.Implementation.Kind) Else Assert.Equal(System.Reflection.TypeAttributes.NotPublic Or TypeAttributesMissing.Forwarder, ExportedTypeRow.Attributes) Assert.Equal(0, exportedTypeRow.GetTypeDefinitionId()) Assert.Equal(expectedType, reader.GetString(exportedTypeRow.Name)) Assert.Equal(expectedNamespace, reader.GetString(exportedTypeRow.Namespace)) Assert.Equal(HandleKind.AssemblyReference, ExportedTypeRow.Implementation.Kind) End If End Sub <Fact> Public Sub TypeForwarderInAModule2() Dim forwardedTypes = <compilation name="ForwarderTargetAssembly"> <file name="a.vb"> Public Class CF1 Public Class CF2 End Class Private Class CF3 End Class End Class </file> </compilation> Dim forwardedTypesCompilation = CreateCompilationWithMscorlib(forwardedTypes, TestOptions.ReleaseDll) Dim ilSource = <![CDATA[ .assembly extern ForwarderTargetAssembly { .ver 0:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .class extern forwarder CF1 { .assembly extern ForwarderTargetAssembly } .module mod.netmodule // MVID: {C39224E6-1B32-4C27-98ED-8F2FE3CC5358} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00840000 ]]> Dim ilBytes As ImmutableArray(Of Byte) = Nothing Using reference = SharedCompilationUtils.IlasmTempAssembly(ilSource.Value, appendDefaultHeader:=False) ilBytes = ReadFromFile(reference.Path) End Using Dim modRef = ModuleMetadata.CreateFromImage(ilBytes).GetReference() Dim app = <compilation> <file name="a.vb"><![CDATA[ public class Test End class ]]></file> </compilation> Dim appCompilation = CreateCompilationWithMscorlibAndReferences(app, {modRef, New VisualBasicCompilationReference(forwardedTypesCompilation)}, TestOptions.ReleaseDll) ' Exported types in .Net module cause PEVerify to fail. CompileAndVerify(appCompilation, verify:=False, symbolValidator:=Sub(m) Dim peReader1 = DirectCast(m, PEModuleSymbol).Module.GetMetadataReader() Assert.Equal(2, peReader1.GetTableRowCount(TableIndex.ExportedType)) ValidateExportedTypeRow(peReader1.ExportedTypes.First(), peReader1, "CF1") ValidateExportedTypeRow(peReader1.ExportedTypes(1), peReader1, "CF1+CF2") End Sub ).VerifyDiagnostics() End Sub <Fact> Public Sub MetadataTypeReferenceResolutionThroughATypeForwardedByCompilation() Dim cA_v1 = CreateCompilationWithMscorlib( <compilation name="A"> <file name="a.vb"><![CDATA[ public class Forwarded(Of T) End class ]]></file> </compilation>, TestOptions.ReleaseDll) Dim cB = CreateCompilationWithMscorlibAndReferences( <compilation name="B"> <file name="a.vb"><![CDATA[ Public Class B Inherits Forwarded(Of Integer) End class ]]></file> </compilation>, {New VisualBasicCompilationReference(cA_v1)}, TestOptions.ReleaseDll) Dim cB_ImageRef = cB.EmitToImageReference() Dim cC_v1 = CreateCompilationWithMscorlib( <compilation name="C"> <file name="a.vb"><![CDATA[ public class Forwarded(Of T) End class ]]></file> </compilation>, TestOptions.ReleaseDll) Dim cC_v1_ImageRef = cC_v1.EmitToImageReference() Dim cA_v3 = CreateCompilationWithMscorlibAndReferences( <compilation name="A"> <file name="a.vb"><![CDATA[ ]]></file> </compilation>, {ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.TypeForwarders.Forwarded).GetReference(), New VisualBasicCompilationReference(cC_v1)}, TestOptions.ReleaseDll) Dim cC_v2 = CreateCompilationWithMscorlib( <compilation name="C"> <file name="a.vb"><![CDATA[ public class Forwarded(Of T) End class ]]></file> </compilation>, TestOptions.ReleaseDll) Dim ref1 = New MetadataReference() { New VisualBasicCompilationReference(cA_v3) } Dim ref2 = New MetadataReference() { New VisualBasicCompilationReference(cB), cB_ImageRef } Dim ref3 = New MetadataReference() { New VisualBasicCompilationReference(cC_v1), New VisualBasicCompilationReference(cC_v2), cC_v1_ImageRef } For Each r1 In ref1 For Each r2 In ref2 For Each r3 In ref3 Dim context = CreateCompilationWithMscorlibAndReferences( <compilation> <file name="a.vb"><![CDATA[ ]]></file> </compilation>, {r1, r2, r3}, TestOptions.ReleaseDll) Dim forwarded = context.GetTypeByMetadataName("Forwarded`1") Dim resolved = context.GetTypeByMetadataName("B").BaseType.OriginalDefinition Assert.NotNull(forwarded) Assert.False(resolved.IsErrorType()) Assert.Same(forwarded, resolved) Next Next Next End Sub End Class End Namespace
KashishArora/Roslyn
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/TypeForwarders.vb
Visual Basic
apache-2.0
47,716
' 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 CodeEventTests Inherits AbstractCodeEventTests #Region "GetStartPoint() tests" <WorkItem(639075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639075")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_SimpleEvent() Dim code = <Code> Class C Event E$$(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:=25)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=11, absoluteOffset:=19, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=25))) End Sub <WorkItem(639075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639075")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_SimpleEventWithAttributes() Dim code = <Code> Class C &lt;System.CLSCompliant(True)&gt; Event E$$(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:=25)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=11, absoluteOffset:=51, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31))) End Sub <WorkItem(639075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639075")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_CustomEvent() Dim code = <Code> Class C Custom Event $$E As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=51, lineLength:=48)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=1, absoluteOffset:=51, lineLength:=48)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=41)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=41)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=18, absoluteOffset:=26, lineLength:=41)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=9, absoluteOffset:=59, lineLength:=48)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=41)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=41))) End Sub <WorkItem(639075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639075")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_CustomEventWithAttributes() Dim code = <Code> Class C &lt;System.CLSCompliant(True)&gt; Custom Event $$E As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event 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:=4, lineOffset:=1, absoluteOffset:=83, lineLength:=48)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=4, lineOffset:=1, absoluteOffset:=83, lineLength:=48)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=41)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=18, absoluteOffset:=58, lineLength:=41)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=4, lineOffset:=9, absoluteOffset:=91, lineLength:=48)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=41)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31))) End Sub #End Region #Region "GetEndPoint() tests" <WorkItem(639075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639075")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_SimpleEvent() Dim code = <Code> Class C Event E$$(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:=26, absoluteOffset:=34, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=26, absoluteOffset:=34, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=26, absoluteOffset:=34, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=26, absoluteOffset:=34, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=12, absoluteOffset:=20, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=26, absoluteOffset:=34, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=26, absoluteOffset:=34, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=26, absoluteOffset:=34, lineLength:=25))) End Sub <WorkItem(639075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639075")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_SimpleEventWithAttributes() Dim code = <Code> Class C &lt;System.CLSCompliant(True)&gt; Event E$$(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:=26, absoluteOffset:=66, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=26, absoluteOffset:=66, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=26, absoluteOffset:=66, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=3, lineOffset:=26, absoluteOffset:=66, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=12, absoluteOffset:=52, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=26, absoluteOffset:=66, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=26, absoluteOffset:=66, lineLength:=25)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=26, absoluteOffset:=66, lineLength:=25))) End Sub <WorkItem(639075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639075")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_CustomEvent() Dim code = <Code> Class C Custom Event $$E As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=11, lineOffset:=5, absoluteOffset:=290, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=11, lineOffset:=5, absoluteOffset:=290, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=42, absoluteOffset:=50, lineLength:=41)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=42, absoluteOffset:=50, lineLength:=41)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=19, absoluteOffset:=27, lineLength:=41)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=11, lineOffset:=5, absoluteOffset:=290, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=11, lineOffset:=14, absoluteOffset:=299, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=11, lineOffset:=14, absoluteOffset:=299, lineLength:=13))) End Sub <WorkItem(639075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639075")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_CustomEventWithAttributes() Dim code = <Code> Class C &lt;System.CLSCompliant(True)&gt; Custom Event $$E As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event 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:=12, lineOffset:=5, absoluteOffset:=322, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=12, lineOffset:=5, absoluteOffset:=322, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=42, absoluteOffset:=82, lineLength:=41)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=3, lineOffset:=42, absoluteOffset:=82, lineLength:=41)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=19, absoluteOffset:=59, lineLength:=41)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=12, lineOffset:=5, absoluteOffset:=322, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=12, lineOffset:=14, absoluteOffset:=331, lineLength:=13)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=12, lineOffset:=14, absoluteOffset:=331, lineLength:=13))) End Sub #End Region #Region "Access tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess1() Dim code = <Code> Class C Event $$E As System.EventHandler End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess2() Dim code = <Code> Class C Private Event $$E As System.EventHandler 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 Event $$E As System.EventHandler 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 Event $$E As System.EventHandler 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 Event $$E As System.EventHandler 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 Event $$E As System.EventHandler End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Attributes" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes_SimpleEvent() Dim code = <Code> Imports System Class C1 &lt;CLSCompliant(False)&gt; Public Event $$E1() End Class </Code> TestAttributes(code, IsElement("CLSCompliant")) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes_CustomEvent() Dim code = <Code> Imports System Class C1 &lt;CLSCompliant(False)&gt; Public Custom Event $$E2 As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent End Event End Class </Code> TestAttributes(code, IsElement("CLSCompliant")) End Sub #End Region #Region "IsPropertyStyleEvent tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsPropertyStyleEvent1() Dim code = <Code> Class C Event $$Foo(i As Integer) End Class </Code> TestIsPropertyStyleEvent(code, False) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsPropertyStyleEvent2() Dim code = <Code> Class C Event E$$ As System.EventHandler End Class </Code> TestIsPropertyStyleEvent(code, False) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsPropertyStyleEvent3() Dim code = <Code> Class C Custom Event $$Foo As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </Code> TestIsPropertyStyleEvent(code, True) End Sub #End Region #Region "IsShared tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared1() Dim code = <Code> Class C Event $$Foo(i 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 Event $$Foo(i As Integer) End Class </Code> TestIsShared(code, True) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared3() Dim code = <Code> Class C Custom Event $$Foo As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </Code> TestIsShared(code, False) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared4() Dim code = <Code> Class C Shared Custom Event $$Foo As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </Code> TestIsShared(code, True) End Sub #End Region #Region "Name tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName1() Dim code = <Code> Class C Event $$Foo As System.EventHandler End Class </Code> TestName(code, "Foo") End Sub #End Region #Region "OverrideKind tests" <WorkItem(150349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150349")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_SimpleEvent() Dim code = <Code> Class C Event $$E() End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone) End Sub <WorkItem(150349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150349")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_CustomEvent() Dim code = <Code> Class C Custom Event $$E As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone) End Sub #End Region #Region "Type tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType1() Dim code = <Code> Class C Event $$E(i As Integer) End Class </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "C.EEventHandler", .AsFullName = "C.EEventHandler", .CodeTypeFullName = "C.EEventHandler", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefCodeType }) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType2() Dim code = <Code> Class C Event $$E As System.EventHandler End Class </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "System.EventHandler", .AsFullName = "System.EventHandler", .CodeTypeFullName = "System.EventHandler", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefCodeType }) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType3() Dim code = <Code> Class C Custom Event $$E As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "System.EventHandler", .AsFullName = "System.EventHandler", .CodeTypeFullName = "System.EventHandler", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefCodeType }) End Sub #End Region #Region "AddAttribute tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_SimpleEvent() As Task Dim code = <Code> Imports System Class C Public Event $$E() End Class </Code> Dim expected = <Code> Imports System Class C &lt;Serializable()&gt; Public Event E() End Class </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_CustomEvent() As Task Dim code = <Code> Imports System Class C Public Custom Event $$E As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent End Event End Class </Code> Dim expected = <Code> Imports System Class C &lt;Serializable()&gt; Public Custom Event E As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent End Event End Class </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_SimpleEvent_BelowDocComment() As Task Dim code = <Code> Imports System Class C ''' &lt;summary&gt;&lt;/summary&gt; Public Event $$E() End Class </Code> Dim expected = <Code> Imports System Class C ''' &lt;summary&gt;&lt;/summary&gt; &lt;CLSCompliant(true)&gt; Public Event E() End Class </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true"}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_CustomEvent_BelowDocComment() As Task Dim code = <Code> Imports System Class C ''' &lt;summary&gt;&lt;/summary&gt; Public Custom Event $$E As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent End Event End Class </Code> Dim expected = <Code> Imports System Class C ''' &lt;summary&gt;&lt;/summary&gt; &lt;CLSCompliant(true)&gt; Public Custom Event E As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent End Event End Class </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true"}) 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 Event $$Foo(i As Integer) End Class </Code> Dim expected = <Code> Class C Event Foo(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 TestSetIsShared2() As Task Dim code = <Code> Class C Event $$Foo(i As Integer) End Class </Code> Dim expected = <Code> Class C Shared Event Foo(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 TestSetIsShared3() As Task Dim code = <Code> Class C Shared Event $$Foo(i As Integer) End Class </Code> Dim expected = <Code> Class C Shared Event Foo(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 Shared Event $$Foo(i As Integer) End Class </Code> Dim expected = <Code> Class C Event Foo(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> Class C Custom Event $$Foo As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </Code> Dim expected = <Code> Class C Custom Event Foo As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </Code> Await TestSetIsShared(code, expected, False) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared6() As Task Dim code = <Code> Class C Custom Event $$Foo As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </Code> Dim expected = <Code> Class C Shared Custom Event Foo As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </Code> Await TestSetIsShared(code, expected, True) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared7() As Task Dim code = <Code> Class C Shared Custom Event $$Foo As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </Code> Dim expected = <Code> Class C Shared Custom Event Foo As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </Code> Await TestSetIsShared(code, expected, True) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared8() As Task Dim code = <Code> Class C Shared Custom Event $$Foo As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </Code> Dim expected = <Code> Class C Custom Event Foo As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </Code> Await TestSetIsShared(code, expected, False) 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 Event $$Foo As System.EventHandler End Class </Code> Dim expected = <Code> Class C Event Bar As System.EventHandler 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 Event $$E(i As Integer) End Class </Code> Dim expected = <Code> Class C Event E(i As Integer) End Class </Code> Await TestSetTypeProp(code, expected, CType(Nothing, EnvDTE.CodeTypeRef), ThrowsArgumentException(Of EnvDTE.CodeTypeRef)) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType2() As Task Dim code = <Code> Class C Event $$E(i As Integer) End Class </Code> Dim expected = <Code> Class C Event E As System.EventHandler End Class </Code> Await TestSetTypeProp(code, expected, "System.EventHandler") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType3() As Task Dim code = <Code> Class C Event $$E As System.EventHandler End Class </Code> Dim expected = <Code> Class C Event E As System.ConsoleCancelEventHandler End Class </Code> Await TestSetTypeProp(code, expected, "System.ConsoleCancelEventHandler") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType4() As Task Dim code = <Code> Class C Custom Event $$E As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </Code> Dim expected = <Code> Class C Custom Event E As System.ConsoleCancelEventHandler AddHandler(value As System.ConsoleCancelEventHandler) End AddHandler RemoveHandler(value As System.ConsoleCancelEventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.ConsoleCancelEventArgs) End RaiseEvent End Event End Class </Code> Await TestSetTypeProp(code, expected, "System.ConsoleCancelEventHandler") 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/CodeEventTests.vb
Visual Basic
apache-2.0
37,936
'-------------------------------------------------------------------------------------------' ' Inicio del codigo '-------------------------------------------------------------------------------------------' '-------------------------------------------------------------------------------------------' ' Inicio de clase "rGConceptos_Detallado" '-------------------------------------------------------------------------------------------' Partial Class rGConceptos_Detallado Inherits vis2formularios.frmReporte Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0)) Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0)) Dim lcParametro1Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1)) Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden Dim loComandoSeleccionar As New StringBuilder() loComandoSeleccionar.AppendLine("") loComandoSeleccionar.AppendLine("SELECT Grupos_Conceptos.Cod_Gru AS Cod_Gru, ") loComandoSeleccionar.AppendLine(" Grupos_Conceptos.Nom_Gru AS Nom_Gru, ") loComandoSeleccionar.AppendLine(" Grupos_Conceptos.Status AS Status, ") loComandoSeleccionar.AppendLine(" Grupos_Conceptos.Comentario AS Comentario, ") loComandoSeleccionar.AppendLine(" (CASE WHEN Grupos_Conceptos.Status = 'A'") loComandoSeleccionar.AppendLine(" THEN 'Activo' ") loComandoSeleccionar.AppendLine(" ELSE 'Inactivo' ") loComandoSeleccionar.AppendLine(" END) AS Estatus,") loComandoSeleccionar.AppendLine(" Conceptos_Nomina.cod_con AS cod_con,") loComandoSeleccionar.AppendLine(" Conceptos_Nomina.nom_con AS nom_con") loComandoSeleccionar.AppendLine("FROM Grupos_Conceptos") loComandoSeleccionar.AppendLine(" LEFT JOIN Renglones_Grupos_Conceptos") loComandoSeleccionar.AppendLine(" ON Renglones_Grupos_Conceptos.cod_gru = Grupos_Conceptos.Cod_Gru") loComandoSeleccionar.AppendLine(" LEFT JOIN Conceptos_Nomina") loComandoSeleccionar.AppendLine(" ON Conceptos_Nomina.cod_con = Renglones_Grupos_Conceptos.cod_con") loComandoSeleccionar.AppendLine("WHERE Grupos_Conceptos.Cod_Gru BETWEEN " & lcParametro0Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta) loComandoSeleccionar.AppendLine(" AND Grupos_Conceptos.Status IN (" & lcParametro1Desde & ")") loComandoSeleccionar.AppendLine("ORDER BY " & lcOrdenamiento) loComandoSeleccionar.AppendLine("") loComandoSeleccionar.AppendLine("") loComandoSeleccionar.AppendLine("") Dim loServicios As New cusDatos.goDatos 'Me.mEscribirConsulta(loComandoSeleccionar.ToString()) Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString(), "curReportes") loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rGConceptos_Detallado", laDatosReporte) Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvrGConceptos_Detallado.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 ' '-------------------------------------------------------------------------------------------' ' RJG: 16/02/13: Codigo inicial ' '-------------------------------------------------------------------------------------------'
kodeitsolutions/ef-reports
Reportes - Nomina/rGConceptos_Detallado.aspx.vb
Visual Basic
mit
4,214
Imports Microsoft.VisualBasic Imports System.IO Imports Aspose.Cells Namespace Data.Handling.Find Public Class FindingCellsContainingFormula Public Shared Sub Run() ' ExStart:1 ' The path to the documents directory. Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType) ' Creating a file stream containing the Excel file to be opened Dim fstream As New FileStream(dataDir & "book1.xls", FileMode.Open) ' Opening the Excel file through the file stream Dim workbook As New Workbook(fstream) ' Accessing the first worksheet in the Excel file Dim worksheet As Worksheet = workbook.Worksheets(0) ' Finding the cell containing the specified formula Dim cell As Cell = worksheet.Cells.FindFormula("=SUM(A5:A10)", Nothing) ' Printing the name of the cell found after searching worksheet System.Console.WriteLine("Name of the cell containing formula: " & cell.Name) ' Closing the file stream to free all resources fstream.Close() ' ExEnd:1 End Sub End Class End Namespace
maria-shahid-aspose/Aspose.Cells-for-.NET
Examples/VisualBasic/Data/Handling/Find/FindingCellsContainingFormula.vb
Visual Basic
mit
1,242
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My.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", "2.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("_04.CSSTutorial.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
Ico093/TelerikAcademy
CSS/Homework/03.CSSLayout/CSSLayout/04.CSSTutorial/My Project/Resources.Designer.vb
Visual Basic
mit
2,704
Imports System Imports System.Runtime.InteropServices Namespace Examples Friend Class Program <STAThread> Shared Sub Main(ByVal args() As String) Dim application As SolidEdgeFramework.Application = Nothing Dim insightXT As SolidEdgeFramework.SolidEdgeInsightXT = 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) insightXT = application.SolidEdgeInsightXT Dim filename = "F:\009431.par" Dim itemId As String = Nothing Dim itemRev As String = Nothing insightXT.GetDocumentUID(filename, itemId, itemRev) 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.SolidEdgeInsightXT.GetDocumentUID.vb
Visual Basic
mit
1,161
Imports BVSoftware.Bvc5.Core.Content Imports BVSoftware.Bvc5.Core Imports System.Collections.ObjectModel Partial Class BVModules_Offers_Free_Shipping_Edit Inherits OfferTemplate Private Const _freeShippingProducts As String = "FreeShippingProducts" Private Shared _ShippingMethodId As String = "ShippingMethodId" Public Overrides Sub Cancel() End Sub Public Overloads Overrides Sub Initialize() LoadMethods() Dim settings As Collection(Of ComponentSettingListItem) = SettingsManager.GetSettingList(_freeShippingProducts) Dim purchasedProducts As New Collection(Of String) For Each setting As ComponentSettingListItem In settings purchasedProducts.Add(setting.Setting1) Next settings = Nothing BindFreeShippingGrid(purchasedProducts) ViewState(_freeShippingProducts) = purchasedProducts OrderQuantityTextBox.Text = SettingsManager.GetIntegerSetting("OrderQuantity") If CInt(OrderQuantityTextBox.Text) = 0 Then OrderQuantityTextBox.Text = "1" End If OrderTotalTextBox.Text = SettingsManager.GetDecimalSetting("OrderTotal").ToString("c") If Decimal.Parse(OrderTotalTextBox.Text, System.Globalization.NumberStyles.Currency) = 0 Then Dim val As Decimal = 0.01D OrderTotalTextBox.Text = val.ToString("c") End If Dim orderTotalMax As Decimal = SettingsManager.GetDecimalSetting("OrderTotalMax") If orderTotalMax = Decimal.MaxValue OrElse orderTotalMax = 0 Then OrderTotalMaxTextBox.Text = String.Empty Else OrderTotalMaxTextBox.Text = orderTotalMax.ToString("c") End If Dim selectedId As String = SettingsManager.GetSetting(_ShippingMethodId) If Me.lstMethods.Items.FindByValue(selectedId) IsNot Nothing Then Me.lstMethods.ClearSelection() Me.lstMethods.Items.FindByValue(selectedId).Selected = True End If End Sub Private Sub LoadMethods() Me.lstMethods.DataSource = BVSoftware.Bvc5.Core.Shipping.ShippingMethod.FindAll() Me.lstMethods.DataTextField = "Name" Me.lstMethods.DataValueField = "bvin" Me.lstMethods.DataBind() End Sub Protected Sub BindFreeShippingGrid(ByRef products As Collection(Of String)) Dim actualProducts As New Collection(Of Catalog.Product) Dim undeletedProducts As New Collection(Of String) ' If product was deleted, it must be removed from the offer For Each product As String In products Dim actualProduct As Catalog.Product = Catalog.InternalProduct.FindByBvin(product) If actualProduct IsNot Nothing Then actualProducts.Add(Catalog.InternalProduct.FindByBvin(product)) undeletedProducts.Add(product) End If Next products = undeletedProducts FreeShippingGridView.DataSource = actualProducts FreeShippingGridView.DataKeyNames = New String() {"bvin"} FreeShippingGridView.DataBind() End Sub Protected Sub AddFreeShippingImageButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles AddFreeShippingImageButton.Click Dim products As Collection(Of String) = CType(ViewState(_freeShippingProducts), Collection(Of String)) If products Is Nothing Then products = New Collection(Of String) End If For Each product As String In FreeShippingProductPicker.SelectedProducts If Not products.Contains(product) Then products.Add(product) End If Next ViewState(_freeShippingProducts) = products BindFreeShippingGrid(products) End Sub Protected Sub RemoveFreeShippingImageButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles RemoveFreeShippingImageButton.Click Dim products As Collection(Of String) = CType(ViewState(_freeShippingProducts), Collection(Of String)) If products IsNot Nothing Then For Each row As GridViewRow In FreeShippingGridView.Rows If row.RowType = DataControlRowType.DataRow Then Dim checkbox As CheckBox = DirectCast(row.Cells(0).FindControl("SelectedCheckBox"), CheckBox) If checkbox.Checked Then If products.Contains(FreeShippingGridView.DataKeys(row.RowIndex).Value) Then products.Remove(FreeShippingGridView.DataKeys(row.RowIndex).Value) End If End If End If Next End If ViewState(_freeShippingProducts) = products BindFreeShippingGrid(products) End Sub Public Overrides Sub Save() SettingsManager.SaveSetting(_ShippingMethodId, lstMethods.SelectedValue, "bvsoftware", "Offer", "FreeShippingByCategory") 'first clear out our product list Dim products As Collection(Of String) = ViewState(_freeShippingProducts) If products IsNot Nothing Then SettingsManager.DeleteSettingList(_freeShippingProducts) For Each product As String In products Dim item As New ComponentSettingListItem() item.Setting1 = product SettingsManager.InsertSettingListItem(_freeShippingProducts, item, "bvsoftware", "Offer", "Free Shipping") Next End If SettingsManager.SaveIntegerSetting("OrderQuantity", CInt(OrderQuantityTextBox.Text), "bvsoftware", "Offer", "Free Shipping") SettingsManager.SaveDecimalSetting("OrderTotal", Decimal.Parse(OrderTotalTextBox.Text, System.Globalization.NumberStyles.Currency), "bvsoftware", "Offer", "Free Shipping") Dim val As Decimal = 0 If Decimal.TryParse(OrderTotalMaxTextBox.Text, System.Globalization.NumberStyles.Currency, System.Threading.Thread.CurrentThread.CurrentUICulture, val) Then If val <= 0 Then val = Decimal.MaxValue End If Else val = Decimal.MaxValue End If SettingsManager.SaveDecimalSetting("OrderTotalMax", val, "bvsoftware", "Offer", "Free Shipping") End Sub Protected Sub OrderTotalCustomValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles OrderTotalCustomValidator.ServerValidate, OrderTotalMaxCustomValidator.ServerValidate If Decimal.TryParse(args.Value, System.Globalization.NumberStyles.Currency, Threading.Thread.CurrentThread.CurrentUICulture, Nothing) Then args.IsValid = True Else args.IsValid = False End If End Sub Protected Sub OrderTotalMaxCustomValidator2_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles OrderTotalMaxCustomValidator2.ServerValidate Dim orderTotalMin As Decimal = 0 Dim orderTotalMax As Decimal = 0 If Decimal.TryParse(OrderTotalTextBox.Text, System.Globalization.NumberStyles.Currency, Threading.Thread.CurrentThread.CurrentUICulture, orderTotalMin) Then If Decimal.TryParse(OrderTotalMaxTextBox.Text, System.Globalization.NumberStyles.Currency, Threading.Thread.CurrentThread.CurrentUICulture, orderTotalMax) Then If orderTotalMax <= orderTotalMin Then args.IsValid = False End If End If End If End Sub End Class
ajaydex/Scopelist_2015
BVModules/Offers/Free Shipping/Edit.ascx.vb
Visual Basic
apache-2.0
7,565
Namespace Question <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class IntegerScreen Inherits PDA.Screens.Question.NumericScreen 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) If disposing AndAlso components IsNot Nothing Then components.Dispose() 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. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.pnlAnswerArea.SuspendLayout() Me.SuspendLayout() ' 'btnPeriod ' Me.btnPeriod.Visible = False ' 'IntegerScreen ' Me.AutoScaleDimensions = New System.Drawing.SizeF(96.0!, 96.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi Me.ClientSize = New System.Drawing.Size(240, 294) Me.Location = New System.Drawing.Point(0, 0) Me.Name = "IntegerScreen" Me.Text = "IntegerScreen" Me.WindowState = System.Windows.Forms.FormWindowState.Maximized Me.pnlAnswerArea.ResumeLayout(False) Me.ResumeLayout(False) End Sub End Class End Namespace
QMDevTeam/QMPDA
QM.PDA.Screens/Question/IntegerScreen.Designer.vb
Visual Basic
apache-2.0
1,708
Imports System Imports Microsoft.VisualBasic Imports ChartDirector Public Class hlinearmeterorientation Implements DemoModule 'Name of demo module Public Function getName() As String Implements DemoModule.getName Return "H-Linear Meter Orientation" End Function 'Number of charts produced in this demo module Public Function getNoOfCharts() As Integer Implements DemoModule.getNoOfCharts Return 4 End Function 'Main code for creating charts Public Sub createChart(viewer As WinChartViewer, chartIndex As Integer) _ Implements DemoModule.createChart ' The value to display on the meter Dim value As Double = 74.25 ' Create a LinearMeter object of size 250 x 75 pixels with very light grey (0xeeeeee) ' backgruond and a light grey (0xccccccc) 3-pixel thick rounded frame Dim m As LinearMeter = New LinearMeter(250, 75, &Heeeeee, &Hcccccc) m.setRoundedFrame(Chart.Transparent) m.setThickFrame(3) ' This example demonstrates putting the text labels at the top or bottom. This is by setting ' the label alignment, scale position and label position. Dim alignment() As Integer = {Chart.Top, Chart.Top, Chart.Bottom, Chart.Bottom} Dim meterYPos() As Integer = {23, 23, 34, 34} Dim labelYPos() As Integer = {61, 61, 15, 15} ' Set the scale region m.setMeter(14, meterYPos(chartIndex), 218, 20, alignment(chartIndex)) ' Set meter scale from 0 - 100, with a tick every 10 units m.setScale(0, 100, 10) ' Add a smooth color scale at the default position Dim smoothColorScale() As Double = {0, &H6666ff, 25, &H00bbbb, 50, &H00ff00, 75, &Hffff00, _ 100, &Hff0000} m.addColorScale(smoothColorScale) ' Add a blue (0x0000cc) pointer at the specified value m.addPointer(value, &H0000cc) ' ' In this example, some charts have the "Temperauture" label on the left side and the value ' readout on the right side, and some charts have the reverse ' If chartIndex Mod 2 = 0 Then ' Add a label on the left side using 8pt Arial Bold font m.addText(10, labelYPos(chartIndex), "Temperature C", "Arial Bold", 8, _ Chart.TextColor, Chart.Left) ' Add a text box on the right side. Display the value using white (0xffffff) 8pt Arial ' Bold font on a black (0x000000) background with depressed rounded border. Dim t As ChartDirector.TextBox = m.addText(235, labelYPos(chartIndex), m.formatValue( _ value, "2"), "Arial Bold", 8, &Hffffff, Chart.Right) t.setBackground(&H000000, &H000000, -1) t.setRoundedCorners(3) Else ' Add a label on the right side using 8pt Arial Bold font m.addText(237, labelYPos(chartIndex), "Temperature C", "Arial Bold", 8, _ Chart.TextColor, Chart.Right) ' Add a text box on the left side. Display the value using white (0xffffff) 8pt Arial ' Bold font on a black (0x000000) background with depressed rounded border. Dim t As ChartDirector.TextBox = m.addText(11, labelYPos(chartIndex), m.formatValue( _ value, "2"), "Arial Bold", 8, &Hffffff, Chart.Left) t.setBackground(&H000000, &H000000, -1) t.setRoundedCorners(3) End If ' Output the chart viewer.Chart = m End Sub End Class
jojogreen/Orbital-Mechanix-Suite
NetWinCharts/VBNetWinCharts/hlinearmeterorientation.vb
Visual Basic
apache-2.0
3,541
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Roslyn.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports System.Threading.Tasks Imports System.Threading Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SymbolMatcherTests Inherits EditAndContinueTestBase <Fact> Public Sub ConcurrentAccess() Dim source = " Class A Dim F As B Property P As D Sub M(a As A, b As B, s As S, i As I) : End Sub Delegate Sub D(s As S) Class B : End Class Structure S : End Structure Interface I : End Interface End Class Class B Function M(Of T, U)() As A Return Nothing End Function Event E As D Delegate Sub D(s As S) Structure S : End Structure Interface I : End Interface End Class" Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() compilation0.VerifyDiagnostics() Dim builder = New List(Of Symbol)() Dim type = compilation1.GetMember(Of NamedTypeSymbol)("A") builder.Add(type) builder.AddRange(type.GetMembers()) type = compilation1.GetMember(Of NamedTypeSymbol)("B") builder.Add(type) builder.AddRange(type.GetMembers()) Dim members = builder.ToImmutableArray() Assert.True(members.Length > 10) For i = 0 To 10 - 1 Dim matcher = CreateMatcher(compilation1, compilation0) Dim tasks(10) As Task For j = 0 To tasks.Length - 1 Dim startAt As Integer = i + j + 1 tasks(j) = Task.Run(Sub() MatchAll(matcher, members, startAt) Thread.Sleep(10) End Sub) Next Task.WaitAll(tasks) Next End Sub Private Shared Sub MatchAll(matcher As VisualBasicSymbolMatcher, members As ImmutableArray(Of Symbol), startAt As Integer) Dim n As Integer = members.Length For i = 0 To n - 1 Dim member = members((i + startAt) Mod n) Dim other = matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IDefinition)) Assert.NotNull(other) Next End Sub <Fact> Public Sub TypeArguments() Dim source = " Class A(Of T) Class B(Of U) Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of Object).S) As A(Of V) Return Nothing End Function Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of V).S) As A(Of V) Return Nothing End Function End Class Structure S End Structure End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() compilation0.VerifyDiagnostics() Dim matcher = CreateMatcher(compilation1, compilation0) Dim members = compilation1.GetMember(Of NamedTypeSymbol)("A.B").GetMembers("M") Assert.Equal(members.Length, 2) For Each member In members Dim other = matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IMethodDefinition)) Assert.NotNull(other) Next End Sub <Fact> Public Sub Constraints() Dim source = " Interface I(Of T AS I(Of T)) End Interface Class C Shared Sub M(Of T As I(Of T))(o As I(Of T)) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source) Dim matcher = CreateMatcher(compilation1, compilation0) Dim member = compilation1.GetMember(Of MethodSymbol)("C.M") Dim other = matcher.MapDefinition(member.GetCciAdapter()) Assert.NotNull(other) End Sub <Fact> Public Sub CustomModifiers() Dim ilSource = " .class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object modopt(A) [] F(int32 modopt(object) p) { } } " Dim metadataRef = CompileIL(ilSource) Dim source = " Class B Inherits A Public Overrides Function F(p As Integer) As Object() Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, references:={metadataRef}) Dim compilation1 = compilation0.Clone() compilation0.VerifyDiagnostics() Dim member1 = compilation1.GetMember(Of MethodSymbol)("B.F") Assert.Equal(DirectCast(member1.ReturnType, ArrayTypeSymbol).CustomModifiers.Length, 1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim other = DirectCast(matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) Assert.Equal(DirectCast(other.ReturnType, ArrayTypeSymbol).CustomModifiers.Length, 1) End Sub <Fact> Public Sub VaryingCompilationReferences() Dim libSource = " Public Class D End Class " Dim source = " Public Class C Public Sub F(a As D) End Sub End Class " Dim lib0 = CreateCompilationWithMscorlib40({libSource}, options:=TestOptions.DebugDll, assemblyName:="Lib") Dim lib1 = CreateCompilationWithMscorlib40({libSource}, options:=TestOptions.DebugDll, assemblyName:="Lib") Dim compilation0 = CreateCompilationWithMscorlib40({source}, {lib0.ToMetadataReference()}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source).WithReferences(MscorlibRef, lib1.ToMetadataReference()) Dim matcher = CreateMatcher(compilation1, compilation0) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim mf1 = matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol() Assert.Equal(f0, mf1) End Sub <WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")> <Fact> Public Sub PreviousType_ArrayType() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As Integer = 0 End Sub Class D : End Class End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x() As D = Nothing End Sub Class D : End Class End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim elementType = compilation1.GetMember(Of TypeSymbol)("C.D") Dim member = compilation1.CreateArrayTypeSymbol(elementType) Dim other = matcher.MapReference(member.GetCciAdapter()) Assert.NotNull(other) End Sub <WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")> <Fact> Public Sub NoPreviousType_ArrayType() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As Integer = 0 End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x() As D = Nothing End Sub Class D : End Class End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim elementType = compilation1.GetMember(Of TypeSymbol)("C.D") Dim member = compilation1.CreateArrayTypeSymbol(elementType) Dim other = matcher.MapReference(member.GetCciAdapter()) ' For a newly added type, there is no match in the previous generation. Assert.Null(other) End Sub <WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")> <Fact> Public Sub NoPreviousType_GenericType() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Class C Shared Sub M() Dim x As Integer = 0 End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Class C Shared Sub M() Dim x As List(Of D) = Nothing End Sub Class D : End Class Dim y As List(Of D) End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim member = compilation1.GetMember(Of FieldSymbol)("C.y") Dim other = matcher.MapReference(DirectCast(member.Type.GetCciAdapter(), Cci.ITypeReference)) ' For a newly added type, there is no match in the previous generation. Assert.Null(other) End Sub <Fact> Public Sub HoistedAnonymousTypes() Dim source0 = " Imports System Class C Shared Sub F() Dim x1 = New With { .A = 1 } Dim x2 = New With { .B = 1 } Dim y = New Func(Of Integer)(Function() x1.A + x2.B) End Sub End Class " Dim source1 = " Imports System Class C Shared Sub F() Dim x1 = New With { .A = 1 } Dim x2 = New With { .C = 1 } Dim y = New Func(Of Integer)(Function() x1.A + x2.C) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll) Dim peRef0 = compilation0.EmitToImageReference() Dim peAssemblySymbol0 = DirectCast(CreateCompilationWithMscorlib40({""}, {peRef0}).GetReferencedAssemblySymbol(peRef0), PEAssemblySymbol) Dim peModule0 = DirectCast(peAssemblySymbol0.Modules(0), PEModuleSymbol) Dim reader0 = peModule0.Module.MetadataReader Dim decoder0 = New MetadataDecoder(peModule0) Dim anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0) Assert.Equal("VB$AnonymousType_0", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("A", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal("VB$AnonymousType_1", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("B", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal(2, anonymousTypeMap0.Count) Dim compilation1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim testData = New CompilationTestData() compilation1.EmitToArray(testData:=testData) Dim peAssemblyBuilder = DirectCast(testData.Module, PEAssemblyBuilder) Dim c = compilation1.GetMember(Of NamedTypeSymbol)("C") Dim displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single() Assert.Equal("_Closure$__1-0", displayClass.Name) Dim emitContext = New EmitContext(peAssemblyBuilder, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) Dim fields = displayClass.GetFields(emitContext).ToArray() Dim x1 = fields(0) Dim x2 = fields(1) Assert.Equal("$VB$Local_x1", x1.Name) Assert.Equal("$VB$Local_x2", x2.Name) Dim matcher = New VisualBasicSymbolMatcher( anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0) Dim mappedX1 = DirectCast(matcher.MapDefinition(x1), Cci.IFieldDefinition) Dim mappedX2 = DirectCast(matcher.MapDefinition(x2), Cci.IFieldDefinition) Assert.Equal("$VB$Local_x1", mappedX1.Name) Assert.Null(mappedX2) End Sub <Fact> Public Sub HoistedAnonymousTypes_Complex() Dim source0 = " Imports System Class C Shared Sub F() Dim x1 = { New With { .A = New With { .X = 1 } } } Dim x2 = { New With { .A = New With { .Y = 1 } } } Dim y = New Func(Of Integer)(Function() x1(0).A.X + x2(0).A.Y) End Sub End Class " Dim source1 = " Imports System Class C Shared Sub F() Dim x1 = { New With { .A = New With { .X = 1 } } } Dim x2 = { New With { .A = New With { .Z = 1 } } } Dim y = New Func(Of Integer)(Function() x1(0).A.X + x2(0).A.Z) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll) Dim peRef0 = compilation0.EmitToImageReference() Dim peAssemblySymbol0 = DirectCast(CreateCompilationWithMscorlib40({""}, {peRef0}).GetReferencedAssemblySymbol(peRef0), PEAssemblySymbol) Dim peModule0 = DirectCast(peAssemblySymbol0.Modules(0), PEModuleSymbol) Dim reader0 = peModule0.Module.MetadataReader Dim decoder0 = New MetadataDecoder(peModule0) Dim anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0) Assert.Equal("VB$AnonymousType_0", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("A", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal("VB$AnonymousType_1", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("X", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal("VB$AnonymousType_2", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("Y", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal(3, anonymousTypeMap0.Count) Dim compilation1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim testData = New CompilationTestData() compilation1.EmitToArray(testData:=testData) Dim peAssemblyBuilder = DirectCast(testData.Module, PEAssemblyBuilder) Dim c = compilation1.GetMember(Of NamedTypeSymbol)("C") Dim displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single() Assert.Equal("_Closure$__1-0", displayClass.Name) Dim emitContext = New EmitContext(peAssemblyBuilder, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) Dim fields = displayClass.GetFields(emitContext).ToArray() Dim x1 = fields(0) Dim x2 = fields(1) Assert.Equal("$VB$Local_x1", x1.Name) Assert.Equal("$VB$Local_x2", x2.Name) Dim matcher = New VisualBasicSymbolMatcher( anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0) Dim mappedX1 = DirectCast(matcher.MapDefinition(x1), Cci.IFieldDefinition) Dim mappedX2 = DirectCast(matcher.MapDefinition(x2), Cci.IFieldDefinition) Assert.Equal("$VB$Local_x1", mappedX1.Name) Assert.Null(mappedX2) End Sub <Fact> Public Sub HoistedAnonymousDelegate() Dim source0 = " Imports System Class C Shared Sub F() Dim x1 = Function(a As Integer) 1 Dim x2 = Function(b As Integer) 1 Dim y = New Func(Of Integer)(Function() x1(1) + x2(1)) End Sub End Class " Dim source1 = " Imports System Class C Shared Sub F() Dim x1 = Function(a As Integer) 1 Dim x2 = Function(c As Integer) 1 Dim y = New Func(Of Integer)(Function() x1(1) + x2(1)) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll) Dim peRef0 = compilation0.EmitToImageReference() Dim peAssemblySymbol0 = DirectCast(CreateCompilationWithMscorlib40({""}, {peRef0}).GetReferencedAssemblySymbol(peRef0), PEAssemblySymbol) Dim peModule0 = DirectCast(peAssemblySymbol0.Modules(0), PEModuleSymbol) Dim reader0 = peModule0.Module.MetadataReader Dim decoder0 = New MetadataDecoder(peModule0) Dim anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0) Assert.Equal("VB$AnonymousDelegate_0", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create( New AnonymousTypeKeyField("A", isKey:=False, ignoreCase:=True), New AnonymousTypeKeyField(AnonymousTypeDescriptor.FunctionReturnParameterName, isKey:=False, ignoreCase:=True)), isDelegate:=True)).Name) Assert.Equal("VB$AnonymousDelegate_1", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create( New AnonymousTypeKeyField("B", isKey:=False, ignoreCase:=True), New AnonymousTypeKeyField(AnonymousTypeDescriptor.FunctionReturnParameterName, isKey:=False, ignoreCase:=True)), isDelegate:=True)).Name) Assert.Equal(2, anonymousTypeMap0.Count) Dim compilation1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim testData = New CompilationTestData() compilation1.EmitToArray(testData:=testData) Dim peAssemblyBuilder = DirectCast(testData.Module, PEAssemblyBuilder) Dim c = compilation1.GetMember(Of NamedTypeSymbol)("C") Dim displayClasses = peAssemblyBuilder.GetSynthesizedTypes(c).ToArray() Assert.Equal("_Closure$__1-0", displayClasses(0).Name) Assert.Equal("_Closure$__", displayClasses(1).Name) Dim emitContext = New EmitContext(peAssemblyBuilder, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) Dim fields = displayClasses(0).GetFields(emitContext).ToArray() Dim x1 = fields(0) Dim x2 = fields(1) Assert.Equal("$VB$Local_x1", x1.Name) Assert.Equal("$VB$Local_x2", x2.Name) Dim matcher = New VisualBasicSymbolMatcher( anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0) Dim mappedX1 = DirectCast(matcher.MapDefinition(x1), Cci.IFieldDefinition) Dim mappedX2 = DirectCast(matcher.MapDefinition(x2), Cci.IFieldDefinition) Assert.Equal("$VB$Local_x1", mappedX1.Name) Assert.Null(mappedX2) End Sub <Fact> Public Sub Method_RenameParameter() Dim source0 = " Class C Public Function X(a As Integer) As Integer Return a End Function End Class " Dim source1 = " Class C Public Function X(b As Integer) As Integer Return b End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) Assert.NotNull(other) End Sub <Fact> Public Sub TupleField_TypeChange() Dim source0 = " Class C { Public x As (a As Integer, b As Integer) }" Dim source1 = " Class C { Public x As (a As Integer, b As Boolean) }" Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("C.x") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleField_NameChange() Dim source0 = " Class C { Public x As (a As Integer, b As Integer) }" Dim source1 = " Class C { Public x As (a As Integer, c As Integer) }" Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("C.x") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceFieldSymbol) Assert.NotNull(otherSymbol) Assert.Equal("C.x As (a As System.Int32, b As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleMethod_TypeToNoTupleChange() Dim source0 = " Class C Public Function X() As (a As Integer, b As Integer) Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As Integer() Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types should not match: one is tuple and another is not. Assert.Null(other) End Sub <Fact> Public Sub TupleMethod_TypeFromNoTupleChange() Dim source0 = " Class C Public Function X() As Integer() Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As (a As Integer, b As Boolean) Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types should not match: one is tuple and another is not. Assert.Null(other) End Sub <Fact> Public Sub TupleMethod_TypeChange() Dim source0 = " Class C Public Function X() As (a As Integer, b As Integer) Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As (a As Integer, b As Boolean) Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleMethod_NameChange() Dim source0 = " Class C Public Function X() As (a As Integer, b As Integer) Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As (a As Integer, c As Integer) Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceMemberMethodSymbol) Assert.NotNull(otherSymbol) Assert.Equal("Function C.X() As (a As System.Int32, b As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleProperty_TypeChange() Dim source0 = " Class C Public ReadOnly Property X As (a As Integer, b As Integer) Get Return Nothing End Get End Property End Class " Dim source1 = " Class C Public ReadOnly Property X As (a As Integer, b As Boolean) Get Return Nothing End Get End Property End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of PropertySymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleProperty_NameChange() Dim source0 = " Class C Public ReadOnly Property X As (a As Integer, b As Integer) Get Return Nothing End Get End Property End Class " Dim source1 = " Class C Public ReadOnly Property X As (a As Integer, c As Integer) Get Return Nothing End Get End Property End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of PropertySymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourcePropertySymbol) Assert.NotNull(otherSymbol) Assert.Equal("ReadOnly Property C.X As (a As System.Int32, b As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleStructField_TypeChange() Dim source0 = " Public Structure Vector Public Coordinates As (x As Integer, y As Integer) End Structure " Dim source1 = " Public Structure Vector Public Coordinates As (x As Integer, y As Integer, z As Integer) End Structure " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("Vector.Coordinates") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleStructField_NameChange() Dim source0 = " Public Structure Vector Public Coordinates As (x As Integer, y As Integer) End Structure " Dim source1 = " Public Structure Vector Public Coordinates As (x As Integer, z As Integer) End Structure " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("Vector.Coordinates") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceFieldSymbol) Assert.NotNull(otherSymbol) Assert.Equal("Vector.Coordinates As (x As System.Int32, y As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleDelegate_TypeChange() Dim source0 = " Public Class C Public Delegate Function F() As (Integer, Integer) End Class " Dim source1 = " Public Class C Public Delegate Function F() As (Integer, Boolean) End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of SourceNamedTypeSymbol)("C.F") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Tuple delegate defines a type. We should be able to match old and new types by name. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceNamedTypeSymbol) Assert.NotNull(otherSymbol) Assert.Equal("C.F", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleDelegate_NameChange() Dim source0 = " Public Class C Public Delegate Function F() As (x as Integer, y as Integer) End Class " Dim source1 = " Public Class C Public Delegate Function F() As (x as Integer, z as Integer) End Class" Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of SourceNamedTypeSymbol)("C.F") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceNamedTypeSymbol) Assert.NotNull(otherSymbol) Assert.Equal("C.F", otherSymbol.ToTestDisplayString()) End Sub End Class End Namespace
eriawan/roslyn
src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/SymbolMatcherTests.vb
Visual Basic
apache-2.0
34,990
'Copyright 2013 Esri 'Licensed under the Apache License, Version 2.0 (the "License"); 'You may not use this file except in compliance with the License. 'You may obtain a copy of the License at 'http://www.apache.org/licenses/LICENSE-2.0 'Unless required by applicable law or agreed to in writing, software 'distributed under the License is distributed on an "AS IS" BASIS, 'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 'See the License for the specific language governing permissions and 'limitations under the License. Imports System.Net Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Documents Imports System.Windows.Input Imports System.Windows.Media Imports System.Windows.Media.Animation Imports System.Windows.Shapes Namespace GlassVB Partial Public Class App Inherits Application Public Sub New() AddHandler Me.Startup, AddressOf Application_Startup AddHandler Me.Exit, AddressOf Application_Exit AddHandler Me.UnhandledException, AddressOf Application_UnhandledException InitializeComponent() End Sub Private Sub Application_Startup(ByVal sender As Object, ByVal e As StartupEventArgs) Me.RootVisual = New MainPage() End Sub Private Sub Application_Exit(ByVal sender As Object, ByVal e As EventArgs) End Sub Private Sub Application_UnhandledException(ByVal sender As Object, ByVal e As ApplicationUnhandledExceptionEventArgs) ' If the app is running outside of the debugger then report the exception using ' the browser's exception mechanism. On IE this will display it a yellow alert ' icon in the status bar and Firefox will display a script error. If Not Debugger.IsAttached Then ' NOTE: This will allow the application to continue running after an exception has been thrown ' but not handled. ' For production applications this error handling should be replaced with something that will ' report the error to the website and stop the application. e.Handled = True Deployment.Current.Dispatcher.BeginInvoke(Sub() ReportErrorToDOM(e)) End If End Sub Private Sub ReportErrorToDOM(ByVal e As ApplicationUnhandledExceptionEventArgs) Try Dim errorMsg As String = e.ExceptionObject.Message + e.ExceptionObject.StackTrace errorMsg = errorMsg.Replace(""""c, "'"c).Replace(vbCrLf, vbLf) System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(""Unhandled Error in Silverlight Application " & errorMsg & """);") Catch e1 As Exception End Try End Sub End Class End Namespace
Esri/arcgis-templates-silverlight
src/GlassVB/GlassVB/Application.xaml.vb
Visual Basic
apache-2.0
2,650
Imports System Imports System.Drawing Imports System.Collections Imports System.ComponentModel Imports System.Windows.Forms Imports System.Diagnostics Imports System.IO Imports System.Xml Imports AnimatGuiCtrls.Controls Imports AnimatGUI.DataObjects Namespace Collections Public Class SystemTypes Inherits AnimatCollectionBase Public Sub New(ByVal doParent As Framework.DataObject) MyBase.New(doParent) End Sub Default Public Property Item(ByVal index As Integer) As System.Type Get Return CType(List(index), System.Type) End Get Set(ByVal Value As System.Type) List(index) = Value End Set End Property Public Function Add(ByVal value As System.Type) As Integer Me.IsDirty = True Return List.Add(value) End Function 'Add Public Function IndexOf(ByVal value As System.Type) As Integer Return List.IndexOf(value) End Function 'IndexOf Public Sub Insert(ByVal index As Integer, ByVal value As System.Type) Me.IsDirty = True List.Insert(index, value) End Sub 'Insert Public Sub Remove(ByVal value As System.Type) Me.IsDirty = True List.Remove(value) End Sub 'Remove Public Function Contains(ByVal value As System.Type) As Boolean ' If value is not of type Int16, this will return false. Return List.Contains(value) End Function 'Contains Protected Overrides Sub OnInsert(ByVal index As Integer, ByVal value As [Object]) If Not TypeOf (value) Is System.Type Then Throw New ArgumentException("value must be of type System.Type.", "value") End If End Sub 'OnInsert Protected Overrides Sub OnRemove(ByVal index As Integer, ByVal value As [Object]) If Not TypeOf (value) Is System.Type Then Throw New ArgumentException("value must be of type System.Type.", "value") End If End Sub 'OnRemove Protected Overrides Sub OnSet(ByVal index As Integer, ByVal oldValue As [Object], ByVal newValue As [Object]) If Not TypeOf (newValue) Is System.Type Then Throw New ArgumentException("newValue must be of type System.Type.", "newValue") End If End Sub 'OnSet Protected Overrides Sub OnValidate(ByVal value As [Object]) If Not TypeOf (value) Is System.Type Then Throw New ArgumentException("value must be of type System.Type.") End If End Sub 'OnValidate End Class 'NodesCollection Public Class SortedSystemTypes Inherits AnimatDictionaryBase Public Sub New(ByVal doParent As Framework.DataObject) MyBase.New(doParent) End Sub Default Public Property Item(ByVal key As [String]) As System.Type Get Return CType(Dictionary(key), System.Type) End Get Set(ByVal Value As System.Type) Dictionary(key) = Value End Set End Property Public ReadOnly Property Keys() As ICollection Get Return Dictionary.Keys End Get End Property Public ReadOnly Property Values() As ICollection Get Return Dictionary.Values End Get End Property Public Sub Add(ByVal key As [String], ByVal value As System.Type) Me.IsDirty = True Dictionary.Add(key, value) End Sub 'Add Public Function Contains(ByVal key As [String]) As Boolean Return Dictionary.Contains(key) End Function 'Contains Public Sub Remove(ByVal key As [String]) Me.IsDirty = True Dictionary.Remove(key) End Sub 'Remove Protected Overrides Sub OnInsert(ByVal key As [Object], ByVal value As [Object]) If Not key.GetType() Is Type.GetType("System.String") Then Throw New ArgumentException("key must be of type String.", "key") End If If Not TypeOf (value) Is System.Type Then Throw New ArgumentException("value must be of type System.Type.", "value") End If Dim diImage As System.Type = DirectCast(value, System.Type) End Sub 'OnInsert Protected Overrides Sub OnRemove(ByVal key As [Object], ByVal value As [Object]) If Not key.GetType() Is Type.GetType("System.String") Then Throw New ArgumentException("key must be of type String.", "key") End If End Sub 'OnRemove Protected Overrides Sub OnSet(ByVal key As [Object], ByVal oldValue As [Object], ByVal newValue As [Object]) If Not key.GetType() Is Type.GetType("System.String") Then Throw New ArgumentException("key must be of type String.", "key") End If If Not TypeOf (newValue) Is System.Type Then Throw New ArgumentException("newValue must be of type System.Type.", "newValue") End If End Sub 'OnSet Protected Overrides Sub OnValidate(ByVal key As [Object], ByVal value As [Object]) If Not key.GetType() Is Type.GetType("System.String") Then Throw New ArgumentException("key must be of type String.", "key") End If If Not TypeOf (value) Is System.Type Then Throw New ArgumentException("value must be of type System.Type.", "value") End If End Sub 'OnValidate End Class End Namespace
NeuroRoboticTech/AnimatLabPublicSource
Libraries/AnimatGUI/Collections/SystemTypes.vb
Visual Basic
bsd-3-clause
5,940
' 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.Cci Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Emit Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend Class EventSymbol Implements Cci.IEventDefinition Private Iterator Function IEventDefinitionAccessors(context As EmitContext) As IEnumerable(Of Cci.IMethodReference) Implements Cci.IEventDefinition.GetAccessors CheckDefinitionInvariant() Dim addMethod = Me.AddMethod Debug.Assert(addMethod IsNot Nothing) If addMethod.ShouldInclude(context) Then Yield addMethod End If Dim removeMethod = Me.RemoveMethod Debug.Assert(removeMethod IsNot Nothing) If removeMethod.ShouldInclude(context) Then Yield removeMethod End If Dim raiseMethod = Me.RaiseMethod If raiseMethod IsNot Nothing AndAlso raiseMethod.ShouldInclude(context) Then Yield raiseMethod End If End Function Private ReadOnly Property IEventDefinitionAdder As Cci.IMethodReference Implements Cci.IEventDefinition.Adder Get CheckDefinitionInvariant() Dim addMethod As MethodSymbol = Me.AddMethod Debug.Assert(addMethod IsNot Nothing) Return addMethod End Get End Property Private ReadOnly Property IEventDefinitionRemover As Cci.IMethodReference Implements Cci.IEventDefinition.Remover Get CheckDefinitionInvariant() Dim removeMethod As MethodSymbol = Me.RemoveMethod Debug.Assert(removeMethod IsNot Nothing) Return removeMethod End Get End Property Private ReadOnly Property IEventDefinitionIsRuntimeSpecial As Boolean Implements Cci.IEventDefinition.IsRuntimeSpecial Get CheckDefinitionInvariant() Return HasRuntimeSpecialName End Get End Property Friend Overridable ReadOnly Property HasRuntimeSpecialName As Boolean Get CheckDefinitionInvariant() Return False End Get End Property Private ReadOnly Property IEventDefinitionIsSpecialName As Boolean Implements Cci.IEventDefinition.IsSpecialName Get CheckDefinitionInvariant() Return Me.HasSpecialName End Get End Property Private ReadOnly Property IEventDefinitionCaller As Cci.IMethodReference Implements Cci.IEventDefinition.Caller Get CheckDefinitionInvariant() Return Me.RaiseMethod End Get End Property Private Overloads Function IEventDefinitionGetType(context As EmitContext) As Cci.ITypeReference Implements Cci.IEventDefinition.GetType Return (DirectCast(context.Module, PEModuleBuilder)).Translate(Me.Type, syntaxNodeOpt:=DirectCast(context.SyntaxNodeOpt, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Private ReadOnly Property IEventDefinitionContainingTypeDefinition As Cci.ITypeDefinition Implements Cci.IEventDefinition.ContainingTypeDefinition Get CheckDefinitionInvariant() Return Me.ContainingType End Get End Property Private ReadOnly Property IEventDefinitionVisibility As Cci.TypeMemberVisibility Implements Cci.IEventDefinition.Visibility Get CheckDefinitionInvariant() Return PEModuleBuilder.MemberVisibility(Me) End Get End Property Private Function ITypeMemberReferenceGetContainingType(context As EmitContext) As Cci.ITypeReference Implements Cci.ITypeMemberReference.GetContainingType CheckDefinitionInvariant() Return Me.ContainingType End Function Friend Overrides Sub IReferenceDispatch(visitor As Cci.MetadataVisitor) ' Implements Cci.IReference.Dispatch CheckDefinitionInvariant() visitor.Visit(DirectCast(Me, Cci.IEventDefinition)) End Sub Friend Overrides Function IReferenceAsDefinition(context As EmitContext) As Cci.IDefinition 'Implements Cci.IReference.AsDefinition CheckDefinitionInvariant() Return Me End Function Private ReadOnly Property IEventDefinitionName As String Implements Cci.IEventDefinition.Name Get CheckDefinitionInvariant() Return Me.MetadataName End Get End Property End Class End Namespace
brettfo/roslyn
src/Compilers/VisualBasic/Portable/Emit/EventSymbolAdapter.vb
Visual Basic
apache-2.0
4,969
'*******************************************************************************************' ' ' ' 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 Bytescout.PDFExtractor Imports System.IO Module Module1 Sub Main() ' Create Bytescout.PDFExtractor.TextExtractor instance Dim extractor = New TextExtractor() extractor.RegistrationName = "demo" extractor.RegistrationKey = "demo" ' Get PDF files Dim pdfFiles() = Directory.GetFiles(".", "*.pdf") For Each file As String In pdfFiles ' Load document extractor.LoadDocumentFromFile(file) ' Save extracted text to .txt file extractor.SaveTextToFile(Path.ChangeExtension(file, ".txt")) ' Reset the extractor before load another file extractor.Reset() Next ' Cleanup extractor.Dispose() End Sub End Module
bytescout/ByteScout-SDK-SourceCode
Premium Suite/VB.NET/Pdf files batch processing with pdf extractor sdk/Module1.vb
Visual Basic
apache-2.0
1,752
Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Public Class ArrayExpansionTests : Inherits VisualBasicResultProviderTestBase <Fact> Public Sub MultiDimensionalArrays() Dim source = " Class C Dim _2d(,) as Integer = {{1,2},{3, 4}} Dim _3d(,,)(,) as Integer = {{{_2d}}} End Class " Dim assembly = GetAssembly(source) Dim typeC = assembly.GetType("C") Dim children = GetChildren(FormatResult("c", CreateDkmClrValue(Activator.CreateInstance(typeC)))) Verify(children, EvalResult("_2d", "{Length=4}", "Integer(,)", "c._2d", DkmEvaluationResultFlags.Expandable), EvalResult("_3d", "{Length=1}", "Integer(,,)(,)", "c._3d", DkmEvaluationResultFlags.Expandable)) children = GetChildren(children(1)) Verify(children, EvalResult("(0, 0, 0)", "{Length=4}", "Integer(,)", "c._3d(0, 0, 0)", DkmEvaluationResultFlags.Expandable)) children = GetChildren(children(0)) Verify(children, EvalResult("(0, 0)", "1", "Integer", "c._3d(0, 0, 0)(0, 0)"), EvalResult("(0, 1)", "2", "Integer", "c._3d(0, 0, 0)(0, 1)"), EvalResult("(1, 0)", "3", "Integer", "c._3d(0, 0, 0)(1, 0)"), EvalResult("(1, 1)", "4", "Integer", "c._3d(0, 0, 0)(1, 1)")) End Sub End Class End Namespace
DavidKarlas/roslyn
src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/ArrayExpansionTests.vb
Visual Basic
apache-2.0
1,505
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Friend NotInheritable Class RemoveHandlerStatementDocumentation Inherits AbstractAddRemoveHandlerStatementDocumentation Public Overrides ReadOnly Property DocumentationText As String Get Return VBWorkspaceResources.RemovesEventAssociation End Get End Property Public Overrides Function GetParameterDocumentation(index As Integer) As String Select Case index Case 0 Return VBWorkspaceResources.EventToDisassociate Case 1 Return VBWorkspaceResources.EventHandlerToDisassociate Case Else Throw New ArgumentException("index") End Select End Function Public Overrides ReadOnly Property PrefixParts As IEnumerable(Of SymbolDisplayPart) Get Return {New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, "RemoveHandler"), New SymbolDisplayPart(SymbolDisplayPartKind.Space, Nothing, " ")} End Get End Property End Class End Namespace
akoeplinger/roslyn
src/Workspaces/VisualBasic/Portable/Utilities/IntrinsicOperators/RemoveHandlerStatementDocumentation.vb
Visual Basic
apache-2.0
1,587
' 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.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Rename Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicSimplificationService Private Class Expander Inherits VisualBasicSyntaxRewriter Private ReadOnly _semanticModel As SemanticModel Private ReadOnly _expandInsideNode As Func(Of SyntaxNode, Boolean) Private ReadOnly _expandParameter As Boolean Private ReadOnly _cancellationToken As CancellationToken Private ReadOnly _annotationForReplacedAliasIdentifier As SyntaxAnnotation Public Sub New( semanticModel As SemanticModel, expandInsideNode As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken, Optional expandParameter As Boolean = False, Optional aliasReplacementAnnotation As SyntaxAnnotation = Nothing) MyBase.New(visitIntoStructuredTrivia:=True) _semanticModel = semanticModel _expandInsideNode = expandInsideNode _cancellationToken = cancellationToken _expandParameter = expandParameter _annotationForReplacedAliasIdentifier = aliasReplacementAnnotation End Sub Public Overrides Function Visit(node As SyntaxNode) As SyntaxNode If _expandInsideNode Is Nothing OrElse _expandInsideNode(node) Then Return MyBase.Visit(node) End If Return node End Function Private Function AddCast(expression As ExpressionSyntax, targetType As ITypeSymbol, oldExpression As ExpressionSyntax) As ExpressionSyntax Dim semanticModel = _semanticModel If expression.SyntaxTree IsNot oldExpression.SyntaxTree Then Dim specAnalyzer = New SpeculationAnalyzer(oldExpression, expression, _semanticModel, _cancellationToken) semanticModel = specAnalyzer.SpeculativeSemanticModel If semanticModel Is Nothing Then Return expression End If expression = specAnalyzer.ReplacedExpression End If Return AddCast(expression, targetType, semanticModel) End Function Private Shared Function AddCast(expression As ExpressionSyntax, targetType As ITypeSymbol, semanticModel As SemanticModel) As ExpressionSyntax Dim wasCastAdded As Boolean = False Dim result = expression.CastIfPossible(targetType, expression.SpanStart, semanticModel, wasCastAdded) If wasCastAdded Then result = result.Parenthesize() End If Return result End Function Private Function AddCasts(expression As ExpressionSyntax, typeInfo As TypeInfo, conversion As Conversion, oldExpression As ExpressionSyntax) As ExpressionSyntax Dim result = expression If typeInfo.Type IsNot Nothing AndAlso typeInfo.Type.IsAnonymousDelegateType() AndAlso conversion.IsUserDefined AndAlso conversion.IsWidening AndAlso conversion.MethodSymbol IsNot Nothing AndAlso conversion.MethodSymbol.Parameters.Length > 0 Then Dim conversionType = conversion.MethodSymbol.Parameters(0).Type If conversionType IsNot Nothing Then result = AddCast(result, conversionType, oldExpression) End If End If If typeInfo.ConvertedType IsNot Nothing Then result = AddCast(result, typeInfo.ConvertedType, oldExpression) End If ' If we didn't add a cast, at least parenthesize the expression. If result Is expression Then result = result.Parenthesize() End If Return result End Function Public Overrides Function VisitParameter(node As ParameterSyntax) As SyntaxNode Dim newNode = DirectCast(MyBase.VisitParameter(node), ParameterSyntax) If newNode IsNot Nothing AndAlso newNode.AsClause Is Nothing AndAlso _expandParameter Then Dim newNodeSymbol = _semanticModel.GetDeclaredSymbol(node) If newNodeSymbol IsNot Nothing AndAlso newNodeSymbol.Kind = SymbolKind.Parameter Then Dim symbolType = newNodeSymbol.Type If symbolType IsNot Nothing Then Dim typeSyntax = symbolType.GenerateTypeSyntax(True) Dim asClause = SyntaxFactory.SimpleAsClause(typeSyntax).NormalizeWhitespace() If newNode.Default Is Nothing Then Dim newAsClause = asClause.WithTrailingTrivia(newNode.Identifier.GetTrailingTrivia()) Dim newIdentifier = newNode.Identifier.WithTrailingTrivia({SyntaxFactory.WhitespaceTrivia(" ")}.ToSyntaxTriviaList()) Return SyntaxFactory.Parameter(newNode.AttributeLists, newNode.Modifiers, newIdentifier, newAsClause, newNode.Default) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If Return SyntaxFactory.Parameter(newNode.AttributeLists, newNode.Modifiers, newNode.Identifier, asClause, newNode.Default).WithAdditionalAnnotations(Simplifier.Annotation) End If End If End If Return newNode End Function Public Overrides Function VisitAssignmentStatement(node As AssignmentStatementSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newAssignment = DirectCast(MyBase.VisitAssignmentStatement(node), AssignmentStatementSyntax) Dim typeInfo = _semanticModel.GetTypeInfo(node.Right) Dim conversion = _semanticModel.GetConversion(node.Right) Dim newExpression = AddCasts(newAssignment.Right, typeInfo, conversion, node.Right) newAssignment = newAssignment _ .WithRight(newExpression) _ .WithAdditionalAnnotations(Simplifier.Annotation) Return newAssignment End Function Public Overrides Function VisitExpressionStatement(node As ExpressionStatementSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newExpressionStatement = DirectCast(MyBase.VisitExpressionStatement(node), ExpressionStatementSyntax) If newExpressionStatement.Expression.IsKind(SyntaxKind.InvocationExpression) Then ' move all leading trivia before the call keyword Dim leadingTrivia = newExpressionStatement.GetLeadingTrivia() newExpressionStatement = newExpressionStatement.WithLeadingTrivia({SyntaxFactory.WhitespaceTrivia(" ")}.ToSyntaxTriviaList()) Dim callStatement = SyntaxFactory.CallStatement(newExpressionStatement.Expression) _ .WithLeadingTrivia(leadingTrivia) _ .WithAdditionalAnnotations(Simplifier.Annotation) ' copy over annotations, if any. callStatement = newExpressionStatement.CopyAnnotationsTo(callStatement) Return callStatement End If Return newExpressionStatement End Function Public Overrides Function VisitEqualsValue(node As EqualsValueSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newEqualsValue = DirectCast(MyBase.VisitEqualsValue(node), EqualsValueSyntax) If node.Value IsNot Nothing AndAlso Not node.Value.IsMissing AndAlso newEqualsValue.Value IsNot Nothing AndAlso Not newEqualsValue.IsMissing Then Dim typeInfo = _semanticModel.GetTypeInfo(node.Value) Dim conversion = _semanticModel.GetConversion(node.Value) Dim newValue = AddCasts(newEqualsValue.Value, typeInfo, conversion, node.Value) newEqualsValue = newEqualsValue _ .WithValue(newValue) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If Return newEqualsValue End Function Public Overrides Function VisitInvocationExpression(node As InvocationExpressionSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newInvocationExpression = DirectCast(MyBase.VisitInvocationExpression(node), InvocationExpressionSyntax) ' the argument for redim needs to be an LValue and therefore cannot be a cast or parenthesized expression. If node.IsParentKind(SyntaxKind.ReDimKeyword) Then Return newInvocationExpression End If If newInvocationExpression.ArgumentList Is Nothing Then Dim trailingTrivia = newInvocationExpression.GetTrailingTrivia() newInvocationExpression = newInvocationExpression _ .WithTrailingTrivia(SyntaxTriviaList.Empty) _ .WithArgumentList(SyntaxFactory.ArgumentList().WithTrailingTrivia(trailingTrivia)) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If If (node.Expression.Kind = SyntaxKind.SimpleMemberAccessExpression) Then Dim memberAccess = DirectCast(node.Expression, MemberAccessExpressionSyntax) Dim targetSymbol = SimplificationHelpers.GetOriginalSymbolInfo(_semanticModel, memberAccess.Name) If (Not targetSymbol Is Nothing And targetSymbol.IsReducedExtension()) Then newInvocationExpression = RewriteExtensionMethodInvocation(node, newInvocationExpression, DirectCast(node.Expression, MemberAccessExpressionSyntax).Expression, DirectCast(newInvocationExpression.Expression, MemberAccessExpressionSyntax).Expression, DirectCast(targetSymbol, IMethodSymbol)) End If End If Return newInvocationExpression End Function Private Function RewriteExtensionMethodInvocation( originalNode As InvocationExpressionSyntax, rewrittenNode As InvocationExpressionSyntax, oldThisExpression As ExpressionSyntax, thisExpression As ExpressionSyntax, reducedExtensionMethod As IMethodSymbol) As InvocationExpressionSyntax Dim expression = RewriteExtensionMethodInvocation(rewrittenNode, oldThisExpression, thisExpression, reducedExtensionMethod, typeNameFormatWithoutGenerics) Dim binding = _semanticModel.GetSpeculativeSymbolInfo(originalNode.SpanStart, expression, SpeculativeBindingOption.BindAsExpression) If (Not binding.Symbol Is Nothing) Then Return expression End If ' The previous binding did not work. So we are going to include the type arguments as well Return RewriteExtensionMethodInvocation(rewrittenNode, oldThisExpression, thisExpression, reducedExtensionMethod, typeNameFormatWithGenerics) End Function Private Function RewriteExtensionMethodInvocation( originalNode As InvocationExpressionSyntax, oldThisExpression As ExpressionSyntax, thisExpression As ExpressionSyntax, reducedExtensionMethod As IMethodSymbol, symbolDisplayFormat As SymbolDisplayFormat) As InvocationExpressionSyntax Dim containingType = reducedExtensionMethod.ContainingType.ToDisplayString(symbolDisplayFormat) Dim oldMemberAccess = DirectCast(originalNode.Expression, MemberAccessExpressionSyntax) Dim newMemberAccess = SyntaxFactory.SimpleMemberAccessExpression(SyntaxFactory.ParseExpression(containingType), oldMemberAccess.OperatorToken, oldMemberAccess.Name).WithLeadingTrivia(thisExpression.GetFirstToken().LeadingTrivia) ' Copies the annotation for the member access expression newMemberAccess = originalNode.Expression.CopyAnnotationsTo(newMemberAccess).WithAdditionalAnnotations(Simplifier.Annotation) Dim typeInfo = _semanticModel.GetTypeInfo(oldThisExpression) Dim conversion = _semanticModel.GetConversion(oldThisExpression) Dim castedThisExpression = AddCasts(thisExpression, typeInfo, conversion, oldThisExpression) Dim thisArgument = SyntaxFactory.SimpleArgument(castedThisExpression) _ .WithLeadingTrivia(SyntaxTriviaList.Empty) _ .WithAdditionalAnnotations(Simplifier.Annotation) thisArgument = DirectCast(originalNode.Expression, MemberAccessExpressionSyntax).Expression.CopyAnnotationsTo(thisArgument) Dim arguments = originalNode.ArgumentList.Arguments.Insert(0, thisArgument) Dim replacementNode = SyntaxFactory.InvocationExpression( newMemberAccess, originalNode.ArgumentList.WithArguments(arguments)) Return originalNode.CopyAnnotationsTo(replacementNode).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function VisitObjectCreationExpression(node As ObjectCreationExpressionSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newObjectCreationExpression = DirectCast(MyBase.VisitObjectCreationExpression(node), ObjectCreationExpressionSyntax) If newObjectCreationExpression.ArgumentList Is Nothing Then Dim trailingTrivia = newObjectCreationExpression.Type.GetTrailingTrivia() newObjectCreationExpression = newObjectCreationExpression _ .WithType(newObjectCreationExpression.Type.WithTrailingTrivia(SyntaxTriviaList.Empty)) _ .WithArgumentList(SyntaxFactory.ArgumentList().WithTrailingTrivia(trailingTrivia)) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If Return newObjectCreationExpression End Function Public Overrides Function VisitSimpleArgument(node As SimpleArgumentSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newSimpleArgument = DirectCast(MyBase.VisitSimpleArgument(node), SimpleArgumentSyntax) ' We need to be careful here. if this is a local, field or property passed to a ByRef argument, we shouldn't ' parenthesize to avoid breaking copy-back semantics. Dim symbol = _semanticModel.GetSymbolInfo(node.Expression, _cancellationToken).Symbol If symbol IsNot Nothing Then If symbol.MatchesKind(SymbolKind.Local, SymbolKind.Field, SymbolKind.Property) Then Dim parameter = node.DetermineParameter(_semanticModel, cancellationToken:=_cancellationToken) If parameter IsNot Nothing AndAlso parameter.RefKind <> RefKind.None Then Return newSimpleArgument End If End If End If If newSimpleArgument.Expression.Kind = SyntaxKind.AddressOfExpression Then Return newSimpleArgument End If Dim typeInfo = _semanticModel.GetTypeInfo(node.Expression) Dim conversion = _semanticModel.GetConversion(node.Expression) Dim newExpression = AddCasts(newSimpleArgument.Expression, typeInfo, conversion, node.Expression) newSimpleArgument = newSimpleArgument _ .WithExpression(newExpression) _ .WithAdditionalAnnotations(Simplifier.Annotation) Return newSimpleArgument End Function Public Overrides Function VisitGenericName(node As GenericNameSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newNode = DirectCast(MyBase.VisitGenericName(node), SimpleNameSyntax) Return VisitSimpleName(newNode, node) End Function Public Overrides Function VisitSingleLineLambdaExpression(node As SingleLineLambdaExpressionSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim baseSingleLineLambda = DirectCast(MyBase.VisitSingleLineLambdaExpression(node), SingleLineLambdaExpressionSyntax) Dim newSingleLineLambda = baseSingleLineLambda _ .Parenthesize() Return newSingleLineLambda End Function Public Overrides Function VisitQualifiedName(node As QualifiedNameSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim rewrittenQualifiedName = MyBase.VisitQualifiedName(node) Dim symbolForQualifiedName = _semanticModel.GetSymbolInfo(node).Symbol If symbolForQualifiedName.IsConstructor Then symbolForQualifiedName = symbolForQualifiedName.ContainingSymbol End If If symbolForQualifiedName.IsModuleMember Then Dim symbolForLeftPart = _semanticModel.GetSymbolInfo(node.Left).Symbol If Not symbolForQualifiedName.ContainingType.Equals(symbolForLeftPart) Then ' <rewritten_left>.<module_name>.<rewritten_right> Dim moduleIdentifierToken = SyntaxFactory.Identifier(symbolForQualifiedName.ContainingType.Name) moduleIdentifierToken = TryEscapeIdentifierToken(moduleIdentifierToken, _semanticModel) Dim qualifiedNameWithModuleName = rewrittenQualifiedName.CopyAnnotationsTo(SyntaxFactory.QualifiedName( SyntaxFactory.QualifiedName(DirectCast(rewrittenQualifiedName, QualifiedNameSyntax).Left, SyntaxFactory.IdentifierName(moduleIdentifierToken)) _ .WithAdditionalAnnotations(Simplifier.Annotation, SimplificationHelpers.SimplifyModuleNameAnnotation), DirectCast(rewrittenQualifiedName, QualifiedNameSyntax).Right)) If symbolForQualifiedName.Equals(_semanticModel.GetSpeculativeSymbolInfo(node.SpanStart, qualifiedNameWithModuleName, SpeculativeBindingOption.BindAsExpression).Symbol) Then rewrittenQualifiedName = qualifiedNameWithModuleName End If End If End If Return rewrittenQualifiedName End Function Public Overrides Function VisitMemberAccessExpression(node As MemberAccessExpressionSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim rewrittenMemberAccess = MyBase.VisitMemberAccessExpression(node) Dim symbolForMemberAccess = _semanticModel.GetSymbolInfo(node).Symbol If symbolForMemberAccess.IsModuleMember Then Dim symbolForLeftPart = _semanticModel.GetSymbolInfo(node.Expression).Symbol If Not symbolForMemberAccess.ContainingType.Equals(symbolForLeftPart) Then ' <rewritten_left>.<module_name>.<rewritten_right> Dim moduleIdentifierToken = SyntaxFactory.Identifier(symbolForMemberAccess.ContainingType.Name) moduleIdentifierToken = TryEscapeIdentifierToken(moduleIdentifierToken, _semanticModel) Dim memberAccessWithModuleName = rewrittenMemberAccess.CopyAnnotationsTo( SyntaxFactory.SimpleMemberAccessExpression( SyntaxFactory.SimpleMemberAccessExpression( DirectCast(rewrittenMemberAccess, MemberAccessExpressionSyntax).Expression, node.OperatorToken, SyntaxFactory.IdentifierName(moduleIdentifierToken)) _ .WithAdditionalAnnotations(Simplifier.Annotation, SimplificationHelpers.SimplifyModuleNameAnnotation), node.OperatorToken, DirectCast(rewrittenMemberAccess, MemberAccessExpressionSyntax).Name)) If symbolForMemberAccess.Equals(_semanticModel.GetSpeculativeSymbolInfo(node.SpanStart, memberAccessWithModuleName, SpeculativeBindingOption.BindAsExpression).Symbol) Then rewrittenMemberAccess = memberAccessWithModuleName End If End If End If Return rewrittenMemberAccess End Function Public Overrides Function VisitIdentifierName(node As IdentifierNameSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newNode = DirectCast(MyBase.VisitIdentifierName(node), SimpleNameSyntax) Return VisitSimpleName(newNode, node) End Function Private Function VisitSimpleName(rewrittenSimpleName As SimpleNameSyntax, originalSimpleName As SimpleNameSyntax) As ExpressionSyntax _cancellationToken.ThrowIfCancellationRequested() Dim identifier = rewrittenSimpleName.Identifier Dim newNode As ExpressionSyntax = rewrittenSimpleName ' ' 1. if this identifier is an alias, we'll expand it here and replace the node completely. ' If originalSimpleName.Kind = SyntaxKind.IdentifierName Then Dim aliasInfo = _semanticModel.GetAliasInfo(DirectCast(originalSimpleName, IdentifierNameSyntax)) If aliasInfo IsNot Nothing Then Dim aliasTarget = aliasInfo.Target If aliasTarget.IsNamespace() AndAlso DirectCast(aliasTarget, INamespaceSymbol).IsGlobalNamespace Then Return rewrittenSimpleName End If ' if the enclosing expression is a typeof expression that already contains open type we cannot ' we need to insert an open type as well. Dim typeOfExpression = originalSimpleName.GetAncestor(Of TypeOfExpressionSyntax)() If typeOfExpression IsNot Nothing AndAlso IsTypeOfUnboundGenericType(_semanticModel, typeOfExpression) Then aliasTarget = DirectCast(aliasTarget, INamedTypeSymbol).ConstructUnboundGenericType() End If ' the expanded form replaces the current identifier name. Dim replacement = FullyQualifyIdentifierName( aliasTarget, newNode, originalSimpleName, replaceNode:=True) _ .WithAdditionalAnnotations(Simplifier.Annotation) If replacement.Kind = SyntaxKind.QualifiedName Then Dim qualifiedReplacement = DirectCast(replacement, QualifiedNameSyntax) Dim newIdentifier = identifier.CopyAnnotationsTo(qualifiedReplacement.Right.Identifier) If Me._annotationForReplacedAliasIdentifier IsNot Nothing Then newIdentifier = newIdentifier.WithAdditionalAnnotations(Me._annotationForReplacedAliasIdentifier) End If Dim aliasAnnotationInfo = AliasAnnotation.Create(aliasInfo.Name) newIdentifier = newIdentifier.WithAdditionalAnnotations(aliasAnnotationInfo) replacement = replacement.ReplaceNode( qualifiedReplacement.Right, qualifiedReplacement.Right.WithIdentifier(newIdentifier)) replacement = newNode.CopyAnnotationsTo(replacement) Return replacement End If Throw New NotImplementedException() End If End If Dim symbol = _semanticModel.GetSymbolInfo(originalSimpleName.Identifier).Symbol If symbol Is Nothing Then Return newNode End If ' ' 2. If it's an attribute, make sure the identifier matches the attribute's class name without the attribute suffix. ' If originalSimpleName.GetAncestor(Of AttributeSyntax)() IsNot Nothing Then If symbol.IsConstructor() AndAlso symbol.ContainingType.IsAttribute() Then symbol = symbol.ContainingType Dim name = symbol.Name Debug.Assert(name.StartsWith(originalSimpleName.Identifier.ValueText)) ' Note, VB can't escape attribute names like C#, so we actually need to expand to the symbol name ' without a suffix, see http://msdn.microsoft.com/en-us/library/aa711866(v=vs.71).aspx Dim newName = String.Empty If name.TryGetWithoutAttributeSuffix(isCaseSensitive:=False, result:=newName) Then If identifier.ValueText <> newName Then identifier = If(identifier.IsBracketed(), identifier.CopyAnnotationsTo(SyntaxFactory.BracketedIdentifier(identifier.LeadingTrivia, newName, identifier.TrailingTrivia)), identifier.CopyAnnotationsTo(SyntaxFactory.Identifier(identifier.LeadingTrivia, newName, identifier.TrailingTrivia))) End If ' if the user already used the Attribute suffix in the attribute, we'll maintain it. If identifier.ValueText = name Then identifier = identifier.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation) End If End If End If End If ' ' 3. Always try to escape keyword identifiers ' identifier = TryEscapeIdentifierToken(identifier, Me._semanticModel) If identifier <> rewrittenSimpleName.Identifier Then Select Case newNode.Kind Case SyntaxKind.IdentifierName, SyntaxKind.GenericName newNode = DirectCast(newNode, SimpleNameSyntax).WithIdentifier(identifier).WithAdditionalAnnotations(Simplifier.Annotation) Case Else Throw New NotImplementedException() End Select End If Dim parent = originalSimpleName.Parent ' do not complexify further for location where only simple names are allowed If (TypeOf (parent) Is FieldInitializerSyntax) OrElse ((TypeOf (parent) Is DeclarationStatementSyntax) AndAlso Not TypeOf (parent) Is InheritsOrImplementsStatementSyntax) OrElse (TypeOf (parent) Is MemberAccessExpressionSyntax AndAlso parent.Kind <> SyntaxKind.SimpleMemberAccessExpression) OrElse (parent.Kind = SyntaxKind.SimpleMemberAccessExpression AndAlso originalSimpleName.IsRightSideOfDot()) OrElse (parent.Kind = SyntaxKind.QualifiedName AndAlso originalSimpleName.IsRightSideOfQualifiedName()) Then Return TryAddTypeArgumentToIdentifierName(newNode, symbol) End If ' ' 4. If this is a standalone identifier or the left side of a qualified name or member access try to fully qualify it ' ' we need to treat the constructor as type name, so just get the containing type. If symbol.IsConstructor() AndAlso parent.Kind = SyntaxKind.ObjectCreationExpression Then symbol = symbol.ContainingType End If ' if it's a namespace or type name, fully qualify it. If symbol.Kind = SymbolKind.NamedType OrElse symbol.Kind = SymbolKind.Namespace Then Return FullyQualifyIdentifierName( DirectCast(symbol, INamespaceOrTypeSymbol), newNode, originalSimpleName, replaceNode:=False) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If ' if it's a member access, we're fully qualifying the left side and make it a member access. If symbol.Kind = SymbolKind.Method OrElse symbol.Kind = SymbolKind.Field OrElse symbol.Kind = SymbolKind.Property Then If symbol.IsStatic OrElse (TypeOf (parent) Is CrefReferenceSyntax) Then newNode = FullyQualifyIdentifierName( symbol, newNode, originalSimpleName, replaceNode:=False) Else Dim left As ExpressionSyntax If _semanticModel.GetEnclosingNamedType(originalSimpleName.SpanStart, _cancellationToken) IsNot symbol.ContainingType Then left = SyntaxFactory.MyBaseExpression() Else left = SyntaxFactory.MeExpression() End If Dim identifiersLeadingTrivia = newNode.GetLeadingTrivia() newNode = TryAddTypeArgumentToIdentifierName(newNode, symbol) newNode = SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, SyntaxFactory.Token(SyntaxKind.DotToken), DirectCast(newNode, SimpleNameSyntax).WithoutLeadingTrivia()) _ .WithLeadingTrivia(identifiersLeadingTrivia) End If newNode = newNode.WithAdditionalAnnotations(Simplifier.Annotation) End If Return newNode End Function Private Function TryAddTypeArgumentToIdentifierName( newNode As ExpressionSyntax, symbol As ISymbol) As ExpressionSyntax If newNode.Kind = SyntaxKind.IdentifierName AndAlso symbol.Kind = SymbolKind.Method Then If DirectCast(symbol, IMethodSymbol).TypeArguments.Length <> 0 Then Dim typeArguments = DirectCast(symbol, IMethodSymbol).TypeArguments newNode = SyntaxFactory.GenericName( DirectCast(newNode, IdentifierNameSyntax).Identifier, SyntaxFactory.TypeArgumentList( SyntaxFactory.SeparatedList(typeArguments.Select(Function(p) SyntaxFactory.ParseTypeName(p.ToDisplayParts(typeNameFormatWithGenerics).ToDisplayString()))))) _ .WithLeadingTrivia(newNode.GetLeadingTrivia()) _ .WithTrailingTrivia(newNode.GetTrailingTrivia()) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If End If Return newNode End Function Private Function FullyQualifyIdentifierName( symbol As ISymbol, rewrittenNode As ExpressionSyntax, originalNode As ExpressionSyntax, replaceNode As Boolean ) As ExpressionSyntax Debug.Assert(Not replaceNode OrElse rewrittenNode.Kind = SyntaxKind.IdentifierName) ' TODO: use and expand Generate*Syntax(isymbol) to not depend on symbol display any more. ' See GenerateExpressionSyntax(); Dim result = rewrittenNode ' only if this symbol has a containing type or namespace there is work for us to do. If replaceNode OrElse symbol.ContainingType IsNot Nothing OrElse symbol.ContainingNamespace IsNot Nothing Then Dim symbolForQualification = If(replaceNode, symbol, symbol.ContainingSymbol) rewrittenNode = TryAddTypeArgumentToIdentifierName(rewrittenNode, symbol) Dim displayParts = symbolForQualification.ToDisplayParts(typeNameFormatWithGenerics) Dim left As ExpressionSyntax = SyntaxFactory.ParseTypeName(displayParts.ToDisplayString()) ' symbol display always includes module names in the qualification, but this can sometimes break code ' (see bug 529837). ' if we don't get back the same symbol for the full qualification, then we'll omit the module name. If symbol.IsModuleMember Then Dim newSymbol = _semanticModel.GetSpeculativeSymbolInfo(originalNode.SpanStart, left, SpeculativeBindingOption.BindAsExpression).Symbol If Not symbolForQualification.Equals(newSymbol) Then displayParts = symbolForQualification.ContainingSymbol.ToDisplayParts(typeNameFormatWithGenerics) left = SyntaxFactory.ParseTypeName(displayParts.ToDisplayString()) End If End If If replaceNode Then result = left _ .WithLeadingTrivia(rewrittenNode.GetLeadingTrivia()) _ .WithTrailingTrivia(rewrittenNode.GetTrailingTrivia()) Debug.Assert( symbol.Equals(_semanticModel.GetSpeculativeSymbolInfo(originalNode.SpanStart, result, SpeculativeBindingOption.BindAsExpression).Symbol)) Return result End If ' now create syntax for the combination of left and right syntax, or a simple replacement in case of an identifier Dim parent = originalNode.Parent Dim leadingTrivia = rewrittenNode.GetLeadingTrivia() rewrittenNode = rewrittenNode.WithoutLeadingTrivia() Select Case parent.Kind Case SyntaxKind.QualifiedName Dim qualifiedParent = DirectCast(parent, QualifiedNameSyntax) result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.QualifiedName( DirectCast(left, NameSyntax), DirectCast(rewrittenNode, SimpleNameSyntax))) Case SyntaxKind.SimpleMemberAccessExpression Dim memberAccessParent = DirectCast(parent, MemberAccessExpressionSyntax) result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, memberAccessParent.OperatorToken, DirectCast(rewrittenNode, SimpleNameSyntax))) Case Else Debug.Assert(TypeOf (rewrittenNode) Is SimpleNameSyntax) If SyntaxFacts.IsInNamespaceOrTypeContext(originalNode) OrElse TypeOf (parent) Is CrefReferenceSyntax Then Dim right = DirectCast(rewrittenNode, SimpleNameSyntax) result = rewrittenNode.CopyAnnotationsTo(SyntaxFactory.QualifiedName(DirectCast(left, NameSyntax), right.WithAdditionalAnnotations(Simplifier.SpecialTypeAnnotation))) Else result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, DirectCast(left, ExpressionSyntax), SyntaxFactory.Token(SyntaxKind.DotToken), DirectCast(rewrittenNode, SimpleNameSyntax))) End If End Select result = result.WithLeadingTrivia(leadingTrivia) End If Return result End Function Private Function IsTypeOfUnboundGenericType(semanticModel As SemanticModel, typeOfExpression As TypeOfExpressionSyntax) As Boolean If typeOfExpression IsNot Nothing Then Dim type = TryCast(semanticModel.GetTypeInfo(typeOfExpression.Type, _cancellationToken).Type, INamedTypeSymbol) ' It's possible the immediate type might not be an unbound type, such as typeof(A<>.B). So walk through ' parent types too Do While type IsNot Nothing If type.IsUnboundGenericType Then Return True End If type = type.ContainingType Loop End If Return False End Function Public Overrides Function VisitLabelStatement(node As LabelStatementSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newLabelStatement = DirectCast(MyBase.VisitLabelStatement(node), LabelStatementSyntax) Dim escapedLabelToken = TryEscapeIdentifierToken(newLabelStatement.LabelToken, Me._semanticModel) If newLabelStatement.LabelToken <> escapedLabelToken Then newLabelStatement = newLabelStatement.WithLabelToken(escapedLabelToken) End If Return newLabelStatement End Function End Class End Class End Namespace
DavidKarlas/roslyn
src/Workspaces/VisualBasic/Portable/Simplification/VisualBasicSimplificationService.Expander.vb
Visual Basic
apache-2.0
40,054
Imports System Public Module modmain Sub Main() Console.WriteLine ("Hello World!") End Sub End Module
chinmayshah99/helloworld
visual-basic/hello.vb
Visual Basic
mit
119
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.18331 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.VBAddCategory.My.MySettings Get Return Global.VBAddCategory.My.MySettings.Default End Get End Property End Module End Namespace
age-killer/Electronic-invoice-document-processing
MailSort_CSHARP/packages/Independentsoft.Exchange.3.0.400/Tutorial/VBAddCategory/My Project/Settings.Designer.vb
Visual Basic
mit
2,932
Imports System.Collections.ObjectModel Imports System.Collections.Specialized Imports System.ComponentModel Imports LampCommon <DefaultEvent("JobClick")> Public Class MultiJobViewer Public Event JobClick(sender As Object, e As JobClickedEventArgs) Public Event ApproveClick(sender As Object, job As LampJobEventArgs) Public Event ViewDrawingClick(sender As Object, job As LampJobEventArgs) Public Event AdvancedClick(sender As Object, job As LampJobEventArgs) Private Sub ApproveClickHandler(sender As Object, job As LampJobEventArgs) RaiseEvent ApproveClick(Me, job) End Sub Private Sub ViewDrawingClickHandler(sender As Object, job As LampJobEventArgs) RaiseEvent ViewDrawingClick(Me, job) End Sub Private Sub AdvancedHandler(sender As Object, job As LampJobEventArgs) RaiseEvent AdvancedClick(Me, job) End Sub Public ReadOnly Property Jobs As ObservableCollection(Of LampJob) Private _columns As Integer = 1 Public Property Columns As Integer Get Return _columns End Get Set(value As Integer) _columns = value UpdateViewers(Nothing, Nothing) End Set End Property Private _rows As Integer = 3 Public Property Rows As Integer Get Return _rows End Get Set(value As Integer) _rows = value UpdateViewers(Nothing, Nothing) End Set End Property Private _jobCursor As Cursor = Windows.Forms.Cursors.Hand Public Property JobCursor As Cursor Get Return _jobCursor End Get Set(value As Cursor) _jobCursor = value For Each item As TemplateDisplay In TableLayoutPanel1.Controls item.Cursor = value Next End Set End Property Sub New() ' This call is required by the designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. Jobs = New ObservableCollection(Of LampJob) AddHandler Jobs.CollectionChanged, AddressOf UpdateViewers End Sub Private Sub UpdateViewers(sender As Object, e As NotifyCollectionChangedEventArgs) If _suspend Then Return End If SuspendLayout() TableLayoutPanel1.Controls.Clear() TableLayoutPanel1.RowCount = 0 TableLayoutPanel1.RowStyles.Clear() For i = 1 To Rows TableLayoutPanel1.RowStyles.Add(New RowStyle(SizeType.Percent, 1 / Rows)) Next TableLayoutPanel1.RowCount = Rows TableLayoutPanel1.ColumnCount = Columns TableLayoutPanel1.ColumnStyles.Clear() For i = 1 To Columns TableLayoutPanel1.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 1 / Columns)) Next If Jobs.Count > 0 Then For Each job In Jobs Dim newViewer As New JobDisplay() With { .Job = job, .Dock = DockStyle.Fill } AddHandler newViewer.Click, AddressOf HandleJobClicked AddHandler newViewer.AdvancedClick, AddressOf AdvancedHandler AddHandler newViewer.ViewDrawingClicks, AddressOf ViewDrawingClickHandler TableLayoutPanel1.Controls.Add(newViewer) Next lblNoTemplates.Visible = False Else lblNoTemplates.Visible = True End If ResumeLayout() End Sub Private Sub HandleJobClicked(sender As Object, e As EventArgs) Dim item As JobDisplay = sender HandleJobClicked(New JobClickedEventArgs(item.Job)) End Sub Public Sub HandleJobClicked(args As JobClickedEventArgs) RaiseEvent JobClick(Me, args) End Sub Public Sub StopLoading() TableLayoutPanel2.Visible = False End Sub Public Sub ShowLoading() TableLayoutPanel2.Visible = True LoadingPictureBox.Visible = True End Sub Private _suspend As Boolean = False Public Sub Suspend() _suspend = True End Sub Public Sub EndSuspend(Optional doUpdate As Boolean = True) _suspend = False If doUpdate Then UpdateViewers(Nothing, Nothing) End If End Sub ' enable double buffering Protected Overrides ReadOnly Property CreateParams As CreateParams Get Dim baseParams = MyBase.CreateParams baseParams.ExStyle = baseParams.ExStyle Or &H2000000 ' magic number that enables double buffering Return baseParams End Get End Property End Class Public Class JobClickedEventArgs Inherits EventArgs Public Property Job As LampJob Public Sub New(job As LampJob) Me.Job = job End Sub End Class
KameQuazi/Software-Major-Assignment-2k18
LampClient/controls/jobs/MultiJobViewer.vb
Visual Basic
mit
4,852
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.17929 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.serial_communication.My.MySettings Get Return Global.serial_communication.My.MySettings.Default End Get End Property End Module End Namespace
mmgreenhacker/CodeFinal
serial communication/serial communication/My Project/Settings.Designer.vb
Visual Basic
mit
2,930
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class frmOptions 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.grpOptions = New System.Windows.Forms.GroupBox() Me.radForbidden = New System.Windows.Forms.RadioButton() Me.radHard = New System.Windows.Forms.RadioButton() Me.radEasy = New System.Windows.Forms.RadioButton() Me.cmdStart = New System.Windows.Forms.Button() Me.grpOptions.SuspendLayout() Me.SuspendLayout() ' 'grpOptions ' Me.grpOptions.Controls.Add(Me.radForbidden) Me.grpOptions.Controls.Add(Me.radHard) Me.grpOptions.Controls.Add(Me.radEasy) Me.grpOptions.Location = New System.Drawing.Point(24, 12) Me.grpOptions.Name = "grpOptions" Me.grpOptions.Size = New System.Drawing.Size(217, 99) Me.grpOptions.TabIndex = 0 Me.grpOptions.TabStop = False Me.grpOptions.Text = "Where do you want to start?" ' 'radForbidden ' Me.radForbidden.AutoSize = True Me.radForbidden.Location = New System.Drawing.Point(17, 68) Me.radForbidden.Name = "radForbidden" Me.radForbidden.Size = New System.Drawing.Size(72, 17) Me.radForbidden.TabIndex = 2 Me.radForbidden.TabStop = True Me.radForbidden.Text = "Forbidden" Me.radForbidden.UseVisualStyleBackColor = True ' 'radHard ' Me.radHard.AutoSize = True Me.radHard.Location = New System.Drawing.Point(17, 45) Me.radHard.Name = "radHard" Me.radHard.Size = New System.Drawing.Size(48, 17) Me.radHard.TabIndex = 1 Me.radHard.TabStop = True Me.radHard.Text = "Hard" Me.radHard.UseVisualStyleBackColor = True ' 'radEasy ' Me.radEasy.AutoSize = True Me.radEasy.Location = New System.Drawing.Point(17, 22) Me.radEasy.Name = "radEasy" Me.radEasy.Size = New System.Drawing.Size(48, 17) Me.radEasy.TabIndex = 0 Me.radEasy.TabStop = True Me.radEasy.Text = "Easy" Me.radEasy.UseVisualStyleBackColor = True ' 'cmdStart ' Me.cmdStart.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.cmdStart.Location = New System.Drawing.Point(166, 117) Me.cmdStart.Name = "cmdStart" Me.cmdStart.Size = New System.Drawing.Size(75, 23) Me.cmdStart.TabIndex = 1 Me.cmdStart.Text = "Start" Me.cmdStart.UseVisualStyleBackColor = True ' 'frmOptions ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.Color.White Me.ClientSize = New System.Drawing.Size(270, 145) Me.Controls.Add(Me.cmdStart) Me.Controls.Add(Me.grpOptions) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog Me.MaximizeBox = False Me.MinimizeBox = False Me.Name = "frmOptions" Me.Text = "Maze: Options" Me.grpOptions.ResumeLayout(False) Me.grpOptions.PerformLayout() Me.ResumeLayout(False) End Sub Friend WithEvents grpOptions As System.Windows.Forms.GroupBox Friend WithEvents radHard As System.Windows.Forms.RadioButton Friend WithEvents radEasy As System.Windows.Forms.RadioButton Friend WithEvents cmdStart As System.Windows.Forms.Button Friend WithEvents radForbidden As System.Windows.Forms.RadioButton End Class
cessnao3/orientation-client
Maze UNPUBLISHED/finalProject/frmOptions.Designer.vb
Visual Basic
mit
4,358
'------------------------------------------------------------------------------ ' <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("TallerGrupo05.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
TallerGrupoVisual05/pruebaPV0005
TallerGrupo05/TallerGrupo05/My Project/Resources.Designer.vb
Visual Basic
mit
2,718
' 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 Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements Imports Microsoft.VisualStudio.LanguageServices.Implementation.Interop Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class CSharpFileCodeModelTests Inherits AbstractFileCodeModelTests <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestEnumerationWithCountAndItem() As Task Dim code = <Code> namespace N { } class C { } interface I { } struct S { } enum E { } delegate void D(); </Code> Using workspaceAndFileCodeModel = Await CreateCodeModelTestStateAsync(GetWorkspaceDefinition(code)) Dim codeElements = workspaceAndFileCodeModel.FileCodeModel.CodeElements Dim count = codeElements.Count Assert.Equal(6, count) Dim expectedKinds = {EnvDTE.vsCMElement.vsCMElementNamespace, EnvDTE.vsCMElement.vsCMElementClass, EnvDTE.vsCMElement.vsCMElementInterface, EnvDTE.vsCMElement.vsCMElementStruct, EnvDTE.vsCMElement.vsCMElementEnum, EnvDTE.vsCMElement.vsCMElementDelegate} Dim expectedNames = {"N", "C", "I", "S", "E", "D"} For i = 0 To count - 1 Dim element = codeElements.Item(i + 1) Assert.Equal(expectedKinds(i), element.Kind) Assert.Equal(expectedNames(i), element.Name) Next Dim j As Integer For Each element As EnvDTE.CodeElement In codeElements Assert.Equal(expectedKinds(j), element.Kind) Assert.Equal(expectedNames(j), element.Name) j += 1 Next End Using End Function <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAssemblyLevelAttribute() As Task Dim code = <Code> [assembly: Foo(0, true, S = "x")] class FooAttribute : System.Attribute { public FooAttribute(int i, bool b) { } public string S { get { return string.Empty; } set { } } } </Code> Using workspaceAndFileCodeModel = Await CreateCodeModelTestStateAsync(GetWorkspaceDefinition(code)) Dim codeElements = workspaceAndFileCodeModel.FileCodeModel.CodeElements Dim count = codeElements.Count Assert.Equal(2, count) Dim codeAttribute = TryCast(codeElements.Item(1), EnvDTE80.CodeAttribute2) Assert.NotNull(codeAttribute) Assert.Same(workspaceAndFileCodeModel.FileCodeModel, codeAttribute.Parent) Assert.Equal("Foo", codeAttribute.Name) Assert.Equal("FooAttribute", codeAttribute.FullName) Assert.Equal("assembly", codeAttribute.Target) Assert.Equal("0, true, S = ""x""", codeAttribute.Value) Dim arguments = codeAttribute.Arguments Assert.Equal(3, arguments.Count) Dim arg1 = TryCast(arguments.Item(1), EnvDTE80.CodeAttributeArgument) Assert.NotNull(arg1) Assert.Equal("", arg1.Name) Assert.Equal("0", arg1.Value) Dim arg2 = TryCast(arguments.Item(2), EnvDTE80.CodeAttributeArgument) Assert.NotNull(arg2) Assert.Equal("", arg2.Name) Assert.Equal("true", arg2.Value) Dim arg3 = TryCast(arguments.Item(3), EnvDTE80.CodeAttributeArgument) Assert.NotNull(arg3) Assert.Equal("S", arg3.Name) Assert.Equal("""x""", arg3.Value) End Using End Function <WorkItem(150349)> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function NoChildrenForInvalidMembers() As Task Dim code = <Code> void M() { } int P { get { return 42; } } event System.EventHandler E; class C { } </Code> Await TestChildren(code, IsElement("C")) End Function #Region "AddAttribute tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> [assembly: System.CLSCompliant(true)] class C { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "true"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> [assembly: System.CLSCompliant(true)] class C { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "true", .Position = "C"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute3() As Task Dim code = <Code> $$[assembly: System.Reflection.AssemblyCompany("Microsoft")] </Code> Dim expected = <Code> [assembly: System.Reflection.AssemblyCompany("Microsoft")] [assembly: System.CLSCompliant(true)] </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "true", .Position = -1}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute4() As Task Dim code = <Code> $$[assembly: System.Reflection.AssemblyCompany("Microsoft")] class C { } </Code> Dim expected = <Code> [assembly: System.Reflection.AssemblyCompany("Microsoft")] [assembly: System.CLSCompliant(true)] class C { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "true", .Position = -1}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute5() As Task Dim code = <Code> $$[assembly: System.Reflection.AssemblyCompany("Microsoft")] [assembly: System.Reflection.AssemblyCopyright("2012")] class C { } </Code> Dim expected = <Code> [assembly: System.Reflection.AssemblyCompany("Microsoft")] [assembly: System.Reflection.AssemblyCopyright("2012")] [assembly: System.CLSCompliant(true)] class C { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "true", .Position = -1}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute6() As Task Dim code = <Code> /// &lt;summary&gt;&lt;/summary&gt; class $$C { } </Code> Dim expected = <Code> [assembly: System.CLSCompliant(true)] /// &lt;summary&gt;&lt;/summary&gt; class C { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "true"}) End Function #End Region #Region "AddClass tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class B { } class C { } </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class B { } class C { } </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass3() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } class B { } </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B", .Position = "C"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass4() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } class B { } </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B", .Position = "C"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass5() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } class B : C { } </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B", .Position = "C", .Bases = {"C"}}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass6() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } class B : C { } </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B", .Position = "C", .Bases = "C"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass7() As Task Dim code = <Code> interface $$I { } </Code> Dim expected = <Code> interface I { } class C : I { } </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "C", .Position = "I", .Bases = {"I"}}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass8() As Task Dim code = <Code> interface $$I { } </Code> Dim expected = <Code> interface I { } class C : I { } </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "C", .Position = "I", .Bases = "I"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass9() As Task Dim code = <Code> class B { } interface $$I { } </Code> Dim expected = <Code> class B { } interface I { } class C : B, I { } </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "C", .Position = "I", .Bases = "B", .ImplementedInterfaces = "I"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass10() As Task Dim code = <Code> class B { } interface $$IFoo { } interface IBar { } </Code> Dim expected = <Code> class B { } interface IFoo { } interface IBar { } class C : B, IFoo, IBar { } </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "C", .Position = "IBar", .Bases = "B", .ImplementedInterfaces = {"IFoo", "IBar"}}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass_Stress() As Task Dim code = <Code> class B { } interface $$IFoo { } interface IBar { } </Code> Await TestOperation(code, Sub(fileCodeModel) For i = 1 To 100 Dim name = $"C{i}" Dim newClass = fileCodeModel.AddClass(name, Position:=-1, Bases:="B", ImplementedInterfaces:={"IFoo", "IBar"}) Assert.NotNull(newClass) Assert.Equal(name, newClass.Name) Next End Sub) End Function #End Region #Region "AddDelegate tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddDelegate1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> delegate void D(); class C { } </Code> Await TestAddDelegate(code, expected, New DelegateData With {.Name = "D", .Type = "void"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddDelegate2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } delegate int D(); </Code> Await TestAddDelegate(code, expected, New DelegateData With {.Name = "D", .Type = "int", .Position = "C"}) End Function #End Region #Region "AddEnum tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddEnum1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> enum E { } class C { } </Code> Await TestAddEnum(code, expected, New EnumData With {.Name = "E"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddEnum2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } enum E { } </Code> Await TestAddEnum(code, expected, New EnumData With {.Name = "E", .Position = "C"}) End Function #End Region #Region "AddImport tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImport1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> using System; class C { } </Code> Await TestAddImport(code, expected, New ImportData With {.[Namespace] = "System"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImport2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> using S = System; class C { } </Code> Await TestAddImport(code, expected, New ImportData With {.[Namespace] = "System", .Alias = "S"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImport3() As Task Dim code = <Code> using System.Collections.Generic; class $$C { } </Code> Dim expected = <Code> using System; using System.Collections.Generic; class C { } </Code> Await TestAddImport(code, expected, New ImportData With {.[Namespace] = "System"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImport4() As Task Dim code = <Code> using System.Collections.Generic; class $$C { } </Code> Dim expected = <Code> using System.Collections.Generic; using System; class C { } </Code> Await TestAddImport(code, expected, New ImportData With {.[Namespace] = "System", .Position = -1}) End Function #End Region #Region "AddInterface tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddInterface1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> interface I { } class C { } </Code> Await TestAddInterface(code, expected, New InterfaceData With {.Name = "I"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddInterface2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } interface I { } </Code> Await TestAddInterface(code, expected, New InterfaceData With {.Name = "I", .Position = "C"}) End Function #End Region #Region "AddNamespace tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> namespace N { } class C { } </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> namespace N { } class C { } </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N", .Position = 0}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace3() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } namespace N { } </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N", .Position = "C"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace4() As Task Dim code = <Code>$$</Code> Dim expected = <Code> namespace N { } </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace5() As Task Dim code = <Code> $$using System; </Code> Dim expected = <Code> using System; namespace N { } </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace6() As Task Dim code = <Code> $$using System; </Code> Dim expected = <Code> using System; namespace N { } </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N", .Position = 0}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace7() As Task Dim code = <Code> $$using System; </Code> Dim expected = <Code> using System; namespace N { } </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N", .Position = Type.Missing}) End Function #End Region #Region "AddStruct tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddStruct1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> struct S { } class C { } </Code> Await TestAddStruct(code, expected, New StructData With {.Name = "S"}) End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddStruct2() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> class C { } struct S { } </Code> Await TestAddStruct(code, expected, New StructData With {.Name = "S", .Position = "C"}) End Function #End Region #Region "Remove tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemove1() As Task Dim code = <Code> class $$C { } </Code> Dim expected = <Code> </Code> Await TestRemoveChild(code, expected, "C") End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemove2() As Task Dim code = <Code> /// &lt;summary&gt; /// /// &lt;/summary&gt; class $$C { } </Code> Dim expected = <Code> </Code> Await TestRemoveChild(code, expected, "C") End Function #End Region <WorkItem(921220)> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestClosedDocument() As Task Dim code = <Code> class $$C { void M() { } } </Code> Using state = Await CreateCodeModelTestStateAsync(GetWorkspaceDefinition(code)) Dim codeClass = state.GetCodeElementAtCursor(Of EnvDTE80.CodeClass2) Assert.Equal(1, codeClass.Members.OfType(Of EnvDTE80.CodeFunction2)().Count()) Dim project = state.VisualStudioWorkspace.CurrentSolution.Projects.First() Dim documentId = project.DocumentIds.First() state.VisualStudioWorkspace.CloseDocument(documentId) Dim newSolution = state.VisualStudioWorkspace.CurrentSolution.RemoveDocument(documentId) state.VisualStudioWorkspace.TryApplyChanges(newSolution) ' throws COMException with HResult = E_FAIL Assert.Throws(Of System.Runtime.InteropServices.COMException)( Sub() Dim count = codeClass.Members.OfType(Of EnvDTE80.CodeFunction2)().Count() End Sub) End Using End Function <WorkItem(1980, "https://github.com/dotnet/roslyn/issues/1980")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestCreateUnknownElementForConversionOperator() As Task Dim oldCode = <Code> class D { public static implicit operator D(double d) { return new D(); } } </Code> Dim changedCode = <Code> class D { } </Code> Dim changedDefinition = <Workspace> <Project Language=<%= LanguageName %> CommonReferences="true"> <Document><%= changedCode.Value %></Document> </Project> </Workspace> Using originalWorkspaceAndFileCodeModel = Await CreateCodeModelTestStateAsync(GetWorkspaceDefinition(oldCode)) Using changedworkspace = Await TestWorkspaceFactory.CreateWorkspaceAsync(changedDefinition, exportProvider:=VisualStudioTestExportProvider.ExportProvider) Dim originalDocument = originalWorkspaceAndFileCodeModel.Workspace.CurrentSolution.GetDocument(originalWorkspaceAndFileCodeModel.Workspace.Documents(0).Id) Dim originalTree = Await originalDocument.GetSyntaxTreeAsync() Dim changeDocument = changedworkspace.CurrentSolution.GetDocument(changedworkspace.Documents(0).Id) Dim changeTree = Await changeDocument.GetSyntaxTreeAsync() Dim codeModelEvent = originalWorkspaceAndFileCodeModel.CodeModelService.CollectCodeModelEvents(originalTree, changeTree) Dim fileCodeModel = originalWorkspaceAndFileCodeModel.FileCodeModelObject Dim element As EnvDTE.CodeElement = Nothing Dim parentElement As Object = Nothing fileCodeModel.GetElementsForCodeModelEvent(codeModelEvent.First(), element, parentElement) Assert.NotNull(element) Assert.NotNull(parentElement) Dim unknownCodeFunction = TryCast(element, EnvDTE.CodeFunction) Assert.Equal(unknownCodeFunction.Name, "implicit operator D") End Using End Using End Function <WorkItem(925569)> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestChangeClassNameAndGetNameOfChildFunction() As Task Dim code = <Code> class C { void M() { } } </Code> Await TestOperation(code, Sub(fileCodeModel) Dim codeClass = TryCast(fileCodeModel.CodeElements.Item(1), EnvDTE.CodeClass) Assert.NotNull(codeClass) Assert.Equal("C", codeClass.Name) Dim codeFunction = TryCast(codeClass.Members.Item(1), EnvDTE.CodeFunction) Assert.NotNull(codeFunction) Assert.Equal("M", codeFunction.Name) codeClass.Name = "NewClassName" Assert.Equal("NewClassName", codeClass.Name) Assert.Equal("M", codeFunction.Name) End Sub) End Function <WorkItem(858153)> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestCodeElements_PropertyAccessor() As Task Dim code = <code> class C { int P { get { return 0; } } } </code> Await TestOperation(code, Sub(fileCodeModel) Dim classC = TryCast(fileCodeModel.CodeElements.Item(1), EnvDTE.CodeClass) Assert.NotNull(classC) Assert.Equal("C", classC.Name) Dim propertyP = TryCast(classC.Members.Item(1), EnvDTE.CodeProperty) Assert.NotNull(propertyP) Assert.Equal("P", propertyP.Name) Dim getter = propertyP.Getter Assert.NotNull(getter) Dim searchedGetter = fileCodeModel.CodeElementFromPoint(getter.StartPoint, EnvDTE.vsCMElement.vsCMElementFunction) Dim parent = TryCast(getter.Collection.Parent, EnvDTE.CodeProperty) Assert.NotNull(parent) Assert.Equal("P", parent.Name) ' This assert is very important! ' ' We are testing that we don't regress a bug where a property accessor creates its ' parent incorrectly such that *existing* Code Model objects for its parent ("P") get a different ' NodeKey that makes the existing objects invalid. If the bug regresses, the line below will ' fail with an ArguementException when trying to use propertyP's NodeKey to lookup its node. ' (Essentially, its NodeKey will be {C.P,2} rather than {C.P,1}). Assert.Equal("P", propertyP.Name) ' Sanity: ensure that the NodeKeys are correct Dim member1 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(parent) Dim member2 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(propertyP) Assert.Equal("C.P", member1.NodeKey.Name) Assert.Equal(1, member1.NodeKey.Ordinal) Assert.Equal("C.P", member2.NodeKey.Name) Assert.Equal(1, member2.NodeKey.Ordinal) End Sub) End Function <WorkItem(858153)> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestCodeElements_EventAccessor() As Task Dim code = <code> class C { event System.EventHandler E { add { } remove { } } } </code> Await TestOperation(code, Sub(fileCodeModel) Dim classC = TryCast(fileCodeModel.CodeElements.Item(1), EnvDTE.CodeClass) Assert.NotNull(classC) Assert.Equal("C", classC.Name) Dim eventE = TryCast(classC.Members.Item(1), EnvDTE80.CodeEvent) Assert.NotNull(eventE) Assert.Equal("E", eventE.Name) Dim adder = eventE.Adder Assert.NotNull(adder) Dim searchedAdder = fileCodeModel.CodeElementFromPoint(adder.StartPoint, EnvDTE.vsCMElement.vsCMElementFunction) Dim parent = TryCast(adder.Collection.Parent, EnvDTE80.CodeEvent) Assert.NotNull(parent) Assert.Equal("E", parent.Name) ' This assert is very important! ' ' We are testing that we don't regress a bug where an event accessor creates its ' parent incorrectly such that *existing* Code Model objects for its parent ("P") get a different ' NodeKey that makes the existing objects invalid. If the bug regresses, the line below will ' fail with an ArguementException when trying to use propertyP's NodeKey to lookup its node. ' (Essentially, its NodeKey will be {C.E,2} rather than {C.E,1}). Assert.Equal("E", eventE.Name) ' Sanity: ensure that the NodeKeys are correct Dim member1 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(parent) Dim member2 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(eventE) Assert.Equal("C.E", member1.NodeKey.Name) Assert.Equal(1, member1.NodeKey.Ordinal) Assert.Equal("C.E", member2.NodeKey.Name) Assert.Equal(1, member2.NodeKey.Ordinal) End Sub) End Function Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.CSharp End Get End Property End Class End Namespace
HellBrick/roslyn
src/VisualStudio/Core/Test/CodeModel/CSharp/FileCodeModelTests.vb
Visual Basic
apache-2.0
30,914
' | Version 10.2 ' | Copyright 2014 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.ArcGIS.Mobile Imports Esri.ArcGIS.Mobile.FeatureCaching Imports Esri.ArcGIS.Mobile.Geometries Imports System.Windows.Forms Imports System Imports System.Drawing Imports MobileControls.EditControl Imports MobileControls Imports Esri.ArcGISTemplates Public Class EditFeaturesMapAction Inherits Esri.ArcGIS.Mobile.WinForms.MapAction Public Event SyncLayer(layerName As String) Public Event GetWorkorder() Public currentWO As String Public currentCrew As String Public currentText As String Private m_GPSStatus As Boolean = False Private m_Snapped As Boolean = False Private WithEvents m_cboCreateLayers As ComboBox Private m_LongString As String = " " Public Event RaiseMessage(ByVal Message As String) 'Private m_RadioOnTwo As Boolean = True 'Private m_FLay as Esri.ArcGIS.Mobile.FeatureCaching.FeatureSource Private m_btn As Button 'Ink Collector 'Edit panel to capture redlines attributes Private WithEvents m_EditPanel As MobileControls.EditControl Private m_mousePosition As Coordinate ' stores current mouse position 'For Multipart 'Private m_CoordsList As List(Of CoordinateCollection) Private m_CoordsCurrent As CoordinateCollection ' stores all coordinates used in drawing the measure line Private m_lineColor As Color = Color.Red Private m_LayerName As String 'Private m_DoubleTapToFinish As Boolean = False 'Private m_PointAtTapOnly As Boolean = False Private m_SketchMode As String Private m_ShowCombo As Boolean = True Private m_LineWidth As Integer = 5 Private m_PointWidth As Integer = 5 Public Event checkGPS() Private m_GPSVal As GPSLocationDetails Private m_Fnt As System.Drawing.Font Private m_FntSize As Single Private m_DT As FeatureDataTable Private WithEvents m_Map As Esri.ArcGIS.Mobile.WinForms.Map Public Property ManualSetMap As Esri.ArcGIS.Mobile.WinForms.Map Get Return Map End Get Set(value As Esri.ArcGIS.Mobile.WinForms.Map) m_Map = value End Set End Property Protected Overrides Sub OnSetMap(ByVal map As Esri.ArcGIS.Mobile.WinForms.Map) MyBase.OnSetMap(map) ' m_Map = map End Sub #Region "Public Methods" Public Sub reorderEditBtns() m_EditPanel.relocatebtns() End Sub Public Sub New() MyBase.New() 'for Multipart 'm_CoordsList = New List(Of CoordinateCollection) m_CoordsCurrent = New CoordinateCollection m_LineWidth = CInt(GlobalsFunctions.appConfig.EditControlOptions.SketchLineWidth) m_PointWidth = CInt(GlobalsFunctions.appConfig.EditControlOptions.SketchPointWidth) End Sub Public Property GPSStatus As Boolean Get Return m_GPSStatus End Get Set(ByVal value As Boolean) m_GPSStatus = value If m_EditPanel IsNot Nothing Then m_EditPanel.GPSStatus = value End If End Set End Property 'Private Delegate Function addMapButtonDelegate() As Boolean Public Function addMapButton() As Boolean Try 'If m_Map.InvokeRequired Then ' m_Map.Invoke(New addMapButtonDelegate(AddressOf addMapButton)) ' Return True 'End If Dim TopX As Integer Dim TopY As Integer 'Create and add the button to toggle the redline map action If m_btn Is Nothing Then 'Create a new button m_btn = New Button With m_btn 'Set the buttons look and feel .BackColor = System.Drawing.SystemColors.Info .BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch .FlatAppearance.BorderSize = 0 .FlatStyle = System.Windows.Forms.FlatStyle.Flat .BackgroundImage = My.Resources.Pen .Name = "btnRedline" .Size = New System.Drawing.Size(50, 50) .UseVisualStyleBackColor = False 'Locate the button 'TopX = m_map.Width - 80 TopX = m_Map.Width - 80 TopY = 85 .Location = New System.Drawing.Point(TopX, TopY) 'Add the handler for relocating the button 'AddHandler m_map.Resize, AddressOf resize AddHandler m_Map.Resize, AddressOf resize 'Add a handler for the click event AddHandler .MouseClick, AddressOf InkBtnClick End With If m_cboCreateLayers Is Nothing Then m_cboCreateLayers = New ComboBox m_cboCreateLayers.Visible = False m_cboCreateLayers.ForeColor = Drawing.Color.White m_cboCreateLayers.BackColor = Drawing.Color.DarkBlue m_cboCreateLayers.DropDownStyle = ComboBoxStyle.DropDownList ' m_cboCreateLayers.DropDownHeight = 300 m_cboCreateLayers.Font = m_Fnt m_cboCreateLayers.Width = 200 m_cboCreateLayers.Left = m_btn.Left - m_cboCreateLayers.Width - 10 m_cboCreateLayers.Top = CInt(m_btn.Top + (m_btn.Height / 2) - (m_cboCreateLayers.Height / 2)) ' AddHandler m_cboCreateLayers.SelectedIndexChanged, AddressOf m_cboCreateLayers_SelectedIndexChanged ' AddHandler m_cboCreateLayers.MouseDoubleClick, AddressOf m_cboCreateLayers_MouseDoubleClick 'Locate it to the left of the button and add to the map 'm_map.Controls.Add(m_cboCreateLayers) m_Map.Controls.Add(m_cboCreateLayers) m_cboCreateLayers.Visible = False End If 'Add the button to the map m_Map.Controls.Add(m_btn) 'm_map.Controls.Add(m_btn) End If Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing Return False End Try Return True End Function Public Function InitControl(ByVal container As Control, Optional ByVal LayerName As String = "") As Boolean Try Single.TryParse(GlobalsFunctions.appConfig.ApplicationSettings.FontSize, m_FntSize) If Not IsNumeric(m_FntSize) Then m_FntSize = 10 ElseIf m_FntSize = 0 Then m_FntSize = 10 End If m_Fnt = New System.Drawing.Font("Microsoft Sans Serif", m_FntSize, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 0) ''Get the redline layer 'Dim pMblLay As Esri.ArcGIS.Mobile.FeatureCaching.MobileCacheMapLayer 'pMblLay = CType(Map.MapLayers(m_LayerName), MobileCacheMapLayer) ''Return if it was not found 'If pMblLay Is Nothing Then ' m_map.Controls.Remove(m_btn) ' Return False 'End If addMapButton() 'Create the form is not already created If m_EditPanel Is Nothing Then 'Create a new edit control m_EditPanel = New MobileControls.EditControl(m_Map, Nothing) 'Fill the container m_EditPanel.Dock = DockStyle.Fill 'Tell the panel to draw the geometry m_EditPanel.DrawGeo = False m_EditPanel.Height = container.Parent.Height 'Clear the controls on the container container.Controls.Clear() 'Add the edit panel container.Dock = DockStyle.Fill container.Controls.Add(m_EditPanel) container.Refresh() container.Update() m_EditPanel.ResumeLayout(True) m_EditPanel.Refresh() m_EditPanel.Update() 'Create a new row on the panel End If ''Set the layer to a global 'pMblLay.Visible = True 'm_FLay = CType(pMblLay.Layer, Esri.ArcGIS.Mobile.FeatureCaching.FeatureSource) 'If m_FLay Is Nothing Then ' m_map.Controls.Remove(m_btn) ' Return False 'End If LoadCreateLayers() If m_cboCreateLayers.Items.Count > 0 Then SetCurrentEditLayer(CType(m_cboCreateLayers.SelectedItem, MobileConfigClass.MobileConfigMobileMapConfigEditControlOptionsLayersLayer)) End If AddHandler m_Map.MapPaint, AddressOf MapPaint Return True Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing End Try End Function #End Region #Region "Private Methods" Private Sub SetCurrentEditLayer(ByVal editOptions As MobileConfigClass.MobileConfigMobileMapConfigEditControlOptionsLayersLayer) Try If editOptions Is Nothing Then Return Dim pFSwDef As FeatureSourceWithDef = GlobalsFunctions.GetFeatureSource(editOptions.Name, m_Map) If pFSwDef Is Nothing Then Try MsgBox(String.Format(GlobalsFunctions.appConfig.ApplicationSettings.UIComponents.LayerNotFound, editOptions.Name)) Catch ex As Exception MsgBox(GlobalsFunctions.appConfig.ApplicationSettings.UIComponents.LayerNotFound & " " & editOptions.Name) End Try Return End If If pFSwDef.FeatureSource Is Nothing Then Try MsgBox(String.Format(GlobalsFunctions.appConfig.ApplicationSettings.UIComponents.LayerNotFound, editOptions.Name)) Catch ex As Exception MsgBox(GlobalsFunctions.appConfig.ApplicationSettings.UIComponents.LayerNotFound & " " & editOptions.Name) End Try Return End If Dim sd As MobileCacheMapLayerDefinition = GlobalsFunctions.GetLayerDefinition(m_Map, pFSwDef) sd.Visibility = True 'pMpLay.Visible = True m_DT = pFSwDef.FeatureSource.GetDataTable() m_SketchMode = editOptions.SketchMode If m_SketchMode.ToUpper = "Freehand".ToUpper And pFSwDef.FeatureSource.GeometryType <> GeometryType.Point Then m_EditPanel.GPSButtonVisible = False Else m_EditPanel.GPSButtonVisible = True End If If editOptions.SketchColor <> "" Then m_lineColor = System.Drawing.Color.FromArgb(Int32.Parse(editOptions.SketchColor.Replace("#", ""), Globalization.NumberStyles.HexNumber)) End If m_EditPanel.setCurrentRecord(pFSwDef.FeatureSource.GetDataTable.NewRow, editOptions) 'Create a new row ' SetNewRowToEditPanel() If Me.Active Then If m_SketchMode.ToUpper = "Freehand".ToUpper And pFSwDef.FeatureSource.GeometryType <> GeometryType.Point Then m_Map.Cursor = New Cursor(My.Resources.Freehand.Handle) Else m_Map.Cursor = New Cursor(My.Resources.target.Handle) End If End If pFSwDef = Nothing Catch ex As Exception Dim st As New StackTrace MsgBox(editOptions.Name & vbCrLf & st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing End Try End Sub 'Private Sub SetNewRowToEditPanel() ' If m_DT IsNot Nothing Then ' 'Create a new row ' Dim pDR As DataRow = m_DT.NewRow ' m_EditPanel.setCurrentRecord(CType(pDR, FeatureDataRow), m_ed) ' End If 'End Sub Private Sub LoadCreateLayers() Try m_LongString = "" 'Load the inspection types to the inspection dropdown If m_cboCreateLayers Is Nothing Then Return If GlobalsFunctions.appConfig.EditControlOptions Is Nothing Then Return If GlobalsFunctions.appConfig.EditControlOptions.Layers Is Nothing Then Return If GlobalsFunctions.appConfig.EditControlOptions.Layers.Layer Is Nothing Then Return If GlobalsFunctions.appConfig.EditControlOptions.Layers.Layer.Count = 0 Then Return RemoveHandler m_cboCreateLayers.SelectedIndexChanged, AddressOf m_cboCreateLayers_SelectedIndexChanged For Each createLay In GlobalsFunctions.appConfig.EditControlOptions.Layers.Layer If createLay.AllowNew.ToUpper() = "TRUE" Then If createLay.Name.Length > m_LongString.Length Then m_LongString = createLay.Name End If m_cboCreateLayers.Items.Add(createLay) End If Next m_cboCreateLayers.SelectedItem = m_cboCreateLayers.Items(0) ' m_cboCreateLayers.DataSource = GlobalsFunctions.appConfig.EditControlOptions.Layers.Layer 'm_cboCreateLayers.Visible = True m_cboCreateLayers.DisplayMember = "DisplayText" 'm_cboCreateLayers.ValueMember = "EditTool" If GlobalsFunctions.appConfig.EditControlOptions.Layers.Layer.Count = 1 Then ' m_cboCreateLayers.Visible = False m_ShowCombo = False End If AddHandler m_cboCreateLayers.SelectedIndexChanged, AddressOf m_cboCreateLayers_SelectedIndexChanged Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing End Try End Sub #End Region #Region "Events" Private Sub m_cboCreateLayers_DropDown(ByVal sender As Object, ByVal e As System.EventArgs) Handles m_cboCreateLayers.DropDown Dim g As Graphics = m_cboCreateLayers.CreateGraphics For i = 0 To 4 ' m_layCBO.Width = m_layCBO.Width + 40 ' m_cboCreateLayers.Height = m_cboCreateLayers.Height + 5 Dim pFnt As System.Drawing.Font = New System.Drawing.Font(m_cboCreateLayers.Font.Name, m_cboCreateLayers.Font.Size + i, System.Drawing.FontStyle.Bold) m_cboCreateLayers.Font = pFnt m_cboCreateLayers.Width = g.MeasureString(m_LongString, pFnt).Width - 35 m_cboCreateLayers.Left = m_btn.Left - m_cboCreateLayers.Width - 10 m_cboCreateLayers.Top = CInt(m_btn.Top + (m_btn.Height / 2) - (m_cboCreateLayers.Height / 2)) Next g.Dispose() g = Nothing ' End If End Sub Private Sub m_cboCreateLayers_DropDownClosed(ByVal sender As Object, ByVal e As System.EventArgs) Handles m_cboCreateLayers.DropDownClosed Dim g As Graphics = m_cboCreateLayers.CreateGraphics m_cboCreateLayers.Width = g.MeasureString(m_cboCreateLayers.Text, m_Fnt).Width + 50 m_cboCreateLayers.Font = m_Fnt m_cboCreateLayers.Left = m_btn.Left - m_cboCreateLayers.Width - 10 m_cboCreateLayers.Top = CInt(m_btn.Top + (m_btn.Height / 2) - (m_cboCreateLayers.Height / 2)) g.Dispose() g = Nothing End Sub Private Sub m_cboCreateLayers_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles m_cboCreateLayers.Enter End Sub Private Sub m_cboCreateLayers_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles m_cboCreateLayers.MouseClick End Sub Private Sub m_cboCreateLayers_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles m_cboCreateLayers.SelectedIndexChanged If (m_CoordsCurrent IsNot Nothing) Then m_CoordsCurrent.Clear() End If 'for Multipart 'If (m_CoordsList IsNot Nothing) Then ' m_CoordsList.Clear() 'End If SetCurrentEditLayer(m_cboCreateLayers.SelectedItem) 'Create a new row 'SetNewRowToEditPanel() m_Map.Invalidate() End Sub 'Private Sub CreateFinished() ' Try ' 'Convert the stoke to a mobile geo ' Dim pGeo As Geometry = Nothing ' If m_DT.FeatureSource.GeometryType = GeometryType.Polygon Then 'And m_CoordsCurrent.Count > 2 Then ' 'pGeo = New Polygon(m_CoordsList) ' ElseIf m_DT.FeatureSource.GeometryType = GeometryType.Polyline Then 'And m_CoordsCurrent.Count >= 2 Then ' pGeo = New Polyline(m_CoordsList) ' Else ' If m_CoordsList IsNot Nothing Then ' If m_CoordsList.Count > 0 Then ' If m_CoordsList(0).Count = 1 Then ' pGeo = New Esri.ArcGIS.Mobile.Geometries.Point(m_CoordsList(0)(0)) ' ElseIf m_CoordsList(0).Count > 1 Then ' pGeo = New Esri.ArcGIS.Mobile.Geometries.Multipoint(m_CoordsList(0)) ' End If ' End If ' End If ' End If ' ' ' 'If there is not shape, prompt the user and exit ' If pGeo Is Nothing Then ' Map.Invalidate() ' 'delete the strokes ' Return ' End If ' Try ' 'Try to set the geometry from the stroke to the edit panel ' m_EditPanel.Geometry = pGeo ' 'Cleanup ' pGeo = Nothing ' Catch ex As Exception ' 'Capture a invalid geometry ' 'delete the strokes ' 'm_coordinates.Clear() ' 'Prompt the user ' Dim st As New StackTrace ' MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) ' st = Nothing ' 'Clean up and return ' pGeo = Nothing ' Map.Invalidate() ' Return ' End Try ' 'The geometry was save to the edit panel, delete the strokes ' 'm_coordinates.Clear() ' 'refresh the map ' ' Map.Refresh() ' Catch ex As Exception ' Dim st As New StackTrace ' MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) ' st = Nothing ' Return ' End Try 'End Sub Private Sub UpdateGeoWithCoordinate() Try 'Convert the stoke to a mobile geo Dim pGeo As Geometry = Nothing If m_DT Is Nothing Then Return If m_DT.FeatureSource.GeometryType = GeometryType.Polygon Then 'For Multipart 'pGeo = New Polygon(m_CoordsList) 'm_CoordsCurrent = New CoordinateCollection 'If UCase(m_SketchMode) <> UCase("FreeHand") And ActionInProgress Then ' m_CoordsCurrent = New CoordinateCollection ' m_CoordsList.Add(m_CoordsCurrent) 'End If pGeo = New Polygon(m_CoordsCurrent.Clone) If UCase(m_SketchMode) = UCase("FreeHand") And ActionInProgress Then Else ActionInProgress = False End If ElseIf m_DT.FeatureSource.GeometryType = GeometryType.Polyline Then 'For Multipart 'pGeo = New Polyline(m_CoordsList) 'm_CoordsCurrent = New CoordinateCollection 'If UCase(m_SketchMode) <> UCase("FreeHand") And ActionInProgress Then ' m_CoordsCurrent = New CoordinateCollection ' m_CoordsList.Add(m_CoordsCurrent) 'End If pGeo = New Polyline(m_CoordsCurrent.Clone) If UCase(m_SketchMode) = UCase("FreeHand") And ActionInProgress Then Else ActionInProgress = False End If ElseIf m_DT.FeatureSource.GeometryType = GeometryType.Point Then 'For Multipart 'If m_CoordsList.Count = 1 Then ' If m_CoordsList(0).Count = 1 Then ' pGeo = New Esri.ArcGIS.Mobile.Geometries.Point(m_CoordsList(0)(0)) ' ElseIf m_CoordsList.Count > 1 Then ' pGeo = New Esri.ArcGIS.Mobile.Geometries.Multipoint(m_CoordsList(0)) ' End If 'End If If m_CoordsCurrent.Count = 1 Then pGeo = New Esri.ArcGIS.Mobile.Geometries.Point(m_CoordsCurrent(0).Clone) End If ActionInProgress = False End If ' 'If there is not shape, prompt the user and exit If pGeo Is Nothing Then m_Map.Invalidate() 'delete the strokes ' m_CoordsList.Clear() m_CoordsCurrent.Clear() Return End If Try 'Try to set the geometry from the stroke to the edit panel m_EditPanel.Geometry = pGeo 'Cleanup pGeo = Nothing Catch ex As Exception 'Capture a invalid geometry 'delete the strokes 'm_CoordsList.Clear() m_CoordsCurrent.Clear() 'Prompt the user Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing 'Clean up and return pGeo = Nothing m_Map.Invalidate() Return End Try 'The geometry was save to the edit panel, delete the strokes 'm_CoordsList.Clear() 'm_CoordsCurrent.Clear() 'refresh the map m_Map.Invalidate() Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing Return End Try End Sub Private Sub MouseDoubleClick(ByVal sender As Object, ByVal e As Esri.ArcGIS.Mobile.MapMouseEventArgs) If UCase(m_SketchMode) <> UCase("FreeHand") And ActionInProgress Then 'Used for multipart geo ' CreateFinished() End If End Sub Protected Overrides Sub OnMapMouseUp(ByVal e As Esri.ArcGIS.Mobile.MapMouseEventArgs) MyBase.OnMapMouseUp(e) If m_DT Is Nothing Then Return If UCase(m_SketchMode) = UCase("FreeHand") And ActionInProgress And m_DT.FeatureSource.GeometryType <> GeometryType.Point Then UpdateGeoWithCoordinate() 'm_CoordsCurrent = New CoordinateCollection() 'm_CoordsList.Add(m_CoordsCurrent) Map.Invalidate() m_Map.Cursor = New Cursor(My.Resources.Freehand.Handle) ' signal to other mapactions that the action is completed ActionInProgress = False ElseIf ActionInProgress Then 'm_map.Cursor = New Cursor(My.Resources.target.Handle) 'UpdateGeoWithCoordinate() End If End Sub Protected Overrides Sub OnMapMouseMove(ByVal e As Esri.ArcGIS.Mobile.MapMouseEventArgs) 'MyBase.OnMapMouseMove(e) m_mousePosition = e.MapCoordinate If ActionInProgress = False Then Return If (m_CoordsCurrent.Count < 1) Then Return End If If UCase(m_SketchMode).ToUpper = UCase("FreeHand").ToUpper And m_DT.FeatureSource.GeometryType <> GeometryType.Point Then If m_DT.FeatureSource.GeometryType = GeometryType.Polygon Then If (m_CoordsCurrent.Count < 2) Then Return End If m_CoordsCurrent.Insert(m_CoordsCurrent.Count - 1, m_mousePosition) Else m_CoordsCurrent.Add(m_mousePosition) End If If (Map IsNot Nothing) Then Map.Invalidate() End If End If End Sub Protected Overrides Sub OnMapMouseDown(ByVal e As Esri.ArcGIS.Mobile.MapMouseEventArgs) ' MyBase.OnMapMouseDown(e) Map.Focus() If m_DT Is Nothing Then Return If (e.MapCoordinate Is Nothing) Then Return End If If UCase(m_SketchMode).ToUpper = UCase("FreeHand").ToUpper Then m_CoordsCurrent.Clear() ActionInProgress = True End If 'If ActionInProgress And m_PointAtTapOnly = True Then ' m_coordinates.Insert(m_coordinates.Count - 1, m_mousePosition) ' If (Map IsNot Nothing) Then ' Map.Invalidate() ' End If 'Els-eIf ActionInProgress And m_DoubleTapToFinish = False Then ' ActionInProgress = False ' RedlineFinished() ' m_map.Cursor = New Cursor(My.Resources.redline.Handle) 'Else ' signal to other mapactions that the action is executing addCoordToGeo(e.MapCoordinate) UpdateGeoWithCoordinate() Map.Invalidate() End Sub Private Sub MapPaint(ByVal sender As Object, ByVal e As Esri.ArcGIS.Mobile.WinForms.MapPaintEventArgs) If m_DT Is Nothing Then Return If m_DT.FeatureSource.GeometryType = GeometryType.Point Or m_DT.FeatureSource.GeometryType = GeometryType.Multipoint Then 'for Multipart 'For Each coord As CoordinateCollection In m_CoordsList ' For Each crd In coord ' e.Display.DrawPoint(New Pen(m_lineColor, m_PointWidth), New SolidBrush(m_lineColor), m_PointWidth, crd) ' Next 'Next For Each crd In m_CoordsCurrent e.MapSurface.DrawPoint(New Pen(m_lineColor, m_PointWidth), New SolidBrush(m_lineColor), m_PointWidth, crd) Next Else If m_CoordsCurrent.Count > 0 Then If m_CoordsCurrent.Count = 1 Then e.MapSurface.DrawPoint(New Pen(m_lineColor, m_PointWidth), New SolidBrush(m_lineColor), m_PointWidth, m_CoordsCurrent(0)) Else If m_CoordsCurrent.Count = 2 Then If m_CoordsCurrent(0).EquivalentTo(m_CoordsCurrent(1)) Then e.MapSurface.DrawPoint(New Pen(m_lineColor, m_PointWidth), New SolidBrush(m_lineColor), m_PointWidth, m_CoordsCurrent(0)) Else e.MapSurface.DrawPolyline(New Pen(m_lineColor, m_LineWidth), m_CoordsCurrent) e.MapSurface.DrawPoint(New Pen(m_lineColor, m_PointWidth), New SolidBrush(m_lineColor), m_PointWidth, m_CoordsCurrent(m_CoordsCurrent.Count - 1)) End If Else e.MapSurface.DrawPolyline(New Pen(m_lineColor, m_LineWidth), m_CoordsCurrent) e.MapSurface.DrawPoint(New Pen(m_lineColor, m_PointWidth), New SolidBrush(m_lineColor), m_PointWidth, m_CoordsCurrent(m_CoordsCurrent.Count - 1)) End If End If End If 'End If 'for Multipart 'For Each coord As CoordinateCollection In m_CoordsList ' If coord.Count = 0 Then Continue For ' If coord.Count = 1 Then ' e.Display.DrawPoint(New Pen(m_lineColor, m_PointWidth), New SolidBrush(m_lineColor), m_PointWidth, coord(0)) ' Continue For ' End If ' If coord.Count = 2 Then ' If coord(0).EquivalentTo(coord(1)) Then ' e.Display.DrawPoint(New Pen(m_lineColor, m_PointWidth), New SolidBrush(m_lineColor), m_PointWidth, coord(0)) ' Continue For ' End If ' End If ' 'Dim g As Graphics = e.Graphics ' 'If m_DT.FeatureSource.GeometryType = GeometryType.Polygon Then ' ' If m_coordinates.Count > 3 Then ' ' e.Display.DrawPolygon(New Pen(m_lineColor, m_lineWidth), Nothing, m_coordinates) ' ' End If ' 'ElseIf m_DT.FeatureSource.GeometryType = GeometryType.Polygon Then ' e.Display.DrawPolyline(New Pen(m_lineColor, m_LineWidth), coord) ' e.Display.DrawPoint(New Pen(m_lineColor, m_PointWidth), New SolidBrush(m_lineColor), m_PointWidth, coord(coord.Count - 1)) ' 'End If 'Next End If End Sub Protected Overrides Sub OnActiveChanged(ByVal active As Boolean) If active Then AddHandler Map.MouseDoubleClick, AddressOf MouseDoubleClick AddHandler Map.KeyUp, AddressOf MapKeyUp AddHandler Map.KeyDown, AddressOf MapKeyDown ' AddHandler Map.Paint, AddressOf MapPaint ' m_map.Cursor = New Cursor(My.Resources.redline.Handle) ' Else RemoveHandler Map.MouseDoubleClick, AddressOf MouseDoubleClick RemoveHandler Map.KeyUp, AddressOf MapKeyUp RemoveHandler Map.KeyDown, AddressOf MapKeyDown ' RemoveHandler Map.Paint, AddressOf MapPaint m_Map.Cursor = Cursors.Default 'm_CoordsList = New List(Of CoordinateCollection) ' m_CoordsCurrent = New CoordinateCollection Map.Invalidate() ' signal to other mapactions that the action is completed ActionInProgress = False End If MyBase.OnActiveChanged(active) End Sub Private Sub MapKeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) MyBase.OnMapKeyDown(e) If e.KeyValue = 27 Then ' m_CoordsList = New List(Of CoordinateCollection) m_CoordsCurrent = New CoordinateCollection Map.Invalidate() ActionInProgress = False Return End If End Sub Private Sub MapKeyUp(ByVal sender As Object, ByVal e As KeyEventArgs) MyBase.OnMapKeyUp(e) End Sub Private Sub resize() Try 'Relocate the button If m_btn IsNot Nothing And m_Map IsNot Nothing Then m_btn.Location = New System.Drawing.Point(m_Map.Width - 80, 85) End If m_cboCreateLayers.Width = 200 m_cboCreateLayers.Left = m_btn.Left - m_cboCreateLayers.Width - 10 m_cboCreateLayers.Top = CInt(m_btn.Top + (m_btn.Height / 2) - (m_cboCreateLayers.Height / 2)) Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing End Try End Sub 'Private Sub CreateFeaturesMapAction_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed ' 'Try ' ' If Map IsNot Nothing Then ' ' RemoveHandler Map.MapPaint, AddressOf MapPaint ' ' End If ' ' 'Remove the button from the map ' ' If m_btn IsNot Nothing Then ' ' If m_btn.Parent IsNot Nothing Then ' ' m_btn.Parent.Controls.Remove(m_btn) ' ' End If ' ' End If ' ' 'Release the other objects ' ' If m_EditPanel IsNot Nothing Then ' ' m_EditPanel.Dispose() ' ' End If ' ' m_EditPanel = Nothing ' 'Catch ex As Exception ' ' Dim st As New StackTrace ' ' MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) ' ' st = Nothing ' ' Return ' 'End Try 'End Sub Private Sub CreateFeaturesMapAction_StatusChanged(ByVal sender As Object, ByVal e As Esri.ArcGIS.Mobile.WinForms.MapActionStatusChangedEventArgs) Handles Me.StatusChanged Try 'Check the map actions status If e.StatusId = Esri.ArcGIS.Mobile.WinForms.MapAction.Activated Then 'If the button has been created, update the buttons image If m_btn IsNot Nothing Then m_btn.BackgroundImage = My.Resources.penDown m_cboCreateLayers.Visible = m_ShowCombo End If If m_DT IsNot Nothing Then If m_SketchMode.ToUpper = "Freehand".ToUpper And m_DT.FeatureSource.GeometryType <> GeometryType.Point Then m_Map.Cursor = New Cursor(My.Resources.Freehand.Handle) Else m_Map.Cursor = New Cursor(My.Resources.target.Handle) End If End If ElseIf e.StatusId = Esri.ArcGIS.Mobile.WinForms.MapAction.Deactivated Then 'If the button has been created, update the buttons image If m_btn IsNot Nothing Then m_btn.BackgroundImage = My.Resources.Pen m_cboCreateLayers.Visible = False End If End If Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing Return End Try End Sub Public Sub InkBtnClick(ByVal sender As Object, ByVal e As MouseEventArgs) Try 'Release or assign the map action If m_Map.MapAction Is Me Then m_Map.MapAction = Nothing Else m_Map.MapAction = Me End If Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing End Try End Sub #End Region Public Property GPSLocation() As GPSLocationDetails Get Return m_GPSVal End Get Set(ByVal value As GPSLocationDetails) Try m_GPSVal = value If (m_GPSVal IsNot Nothing) Then ' MsgBox("") Dim newCoord As Coordinate If m_GPSVal.SpatialReference Is Nothing Then newCoord = m_Map.SpatialReference.FromGps(m_GPSVal.Coordinate) ElseIf m_GPSVal.SpatialReference.FactoryCode <> m_Map.SpatialReference.FactoryCode Then newCoord = m_Map.SpatialReference.FromGps(m_GPSVal.Coordinate) 'Me.Geometry = New Esri.ArcGIS.Mobile.Geometries.Point(m_Map.SpatialReference.FromDegreeMinuteSecond(m_GPSVal.LongitudeToDegreeMinutesSeconds), m_Map.SpatialReference.FromDegreeMinuteSecond(m_GPSVal.LatitudeToDegreeMinutesSeconds)) 'Me.Geometry = m_GPSVal() Else newCoord = m_GPSVal.Coordinate End If addCoordToGeo(newCoord) UpdateGeoWithCoordinate() m_EditPanel.EnableGPS(GlobalsFunctions.m_GPS.GpsConnection.IsOpen) Map.Invalidate() End If Catch ex As Exception End Try End Set End Property Private Sub addCoordToGeo(ByVal newCoord As Coordinate) If m_DT Is Nothing Then Return If m_CoordsCurrent Is Nothing Then m_CoordsCurrent = New CoordinateCollection End If If m_Snapped Then Try m_CoordsCurrent.Clear() 'm_CoordsList.Clear() m_Snapped = False Catch ex As Exception End Try End If If UCase(m_SketchMode).ToUpper = UCase("FreeHand").ToUpper And m_DT.FeatureSource.GeometryType <> GeometryType.Point Then ' m_CoordsCurrent = New CoordinateCollection m_CoordsCurrent.Clear() 'm_CoordsList.Add(m_CoordsCurrent) End If If (m_CoordsCurrent.Count = 0) Then ' m_CoordsList.Add(m_CoordsCurrent) m_CoordsCurrent.Add(newCoord) If m_DT.FeatureSource.GeometryType = GeometryType.Polygon Then m_CoordsCurrent.Add(newCoord) End If 'If (Map IsNot Nothing) Then ' Map.Invalidate() 'End If 'ElseIf (m_coordinates.Count = 2) Then ' If (m_measureMethod = EsriMeasureMethod.MultiPoint) Then ' m_coordinates.Insert(1, e.MapCoordinate) ' End If 'ElseIf (m_measureMethod = EsriMeasureMethod.MultiPoint) Then ' m_coordinates.Insert(m_coordinates.Count - 1, e.MapCoordinate) Else If m_DT.FeatureSource.GeometryType = GeometryType.Polygon Then If m_CoordsCurrent(m_CoordsCurrent.Count - 1).X = newCoord.X And m_CoordsCurrent(m_CoordsCurrent.Count - 1).Y = newCoord.Y Then ' MsgBox("SameCoord:") Else m_CoordsCurrent.Insert(m_CoordsCurrent.Count - 1, newCoord) End If ElseIf m_DT.FeatureSource.GeometryType = GeometryType.Point Then ' m_CoordsList.Add(m_CoordsCurrent) m_CoordsCurrent.Clear() m_CoordsCurrent.Add(newCoord) Else m_CoordsCurrent.Add(newCoord) End If 'm_coordinates.Add(m_mousePosition) 'If (Map IsNot Nothing) Then ' Map.Invalidate() 'End If End If End Sub Private Sub m_EditPanel_CheckGPS() Handles m_EditPanel.CheckGPS RaiseEvent checkGPS() 'm_EditPanel.GPSLocation = m_GPSVal End Sub Private Sub m_EditPanel_ContextMenuChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles m_EditPanel.ContextMenuChanged End Sub Private Sub m_EditPanel_getWorkorder() Handles m_EditPanel.GetWorkorder RaiseEvent GetWorkorder() m_EditPanel.currentWO = currentWO m_EditPanel.currentCrew = currentCrew m_EditPanel.currentWOText = currentText End Sub Private Sub m_EditPanel_RaiseMessage(ByVal Message As String) Handles m_EditPanel.RaiseMessage RaiseEvent RaiseMessage(Message) End Sub Private Sub m_EditPanel_RecordClear() Handles m_EditPanel.RecordClear m_CoordsCurrent.Clear() ' m_CoordsList.Clear() End Sub Private Sub m_EditPanel_RecordSaved(ByVal LayerName As String, ByVal pGeo As Esri.ArcGIS.Mobile.Geometries.Geometry, ByVal OID As Integer) Handles m_EditPanel.RecordSaved m_CoordsCurrent.Clear() ' m_CoordsList.Clear() ' MsgBox("Record Saved", MsgBoxStyle.Information) RaiseEvent RaiseMessage(GlobalsFunctions.appConfig.EditControlOptions.UIComponents.SavedMessage) End Sub Private Sub m_EditPanel_RecordSnapped(ByVal geo As Esri.ArcGIS.Mobile.Geometries.Geometry) Handles m_EditPanel.RecordSnapped m_CoordsCurrent.Clear() ' m_CoordsList.Clear() m_CoordsCurrent = geo.Parts(0).Clone 'For Each prt In geo.Parts ' m_CoordsList.Add(prt.Clone) 'Next m_Snapped = True Map.Invalidate() End Sub Protected Overrides Sub Finalize() MyBase.Finalize() Try If Map IsNot Nothing Then RemoveHandler Map.MapPaint, AddressOf MapPaint End If 'Remove the button from the map If m_btn IsNot Nothing Then If m_btn.Parent IsNot Nothing Then m_btn.Parent.Controls.Remove(m_btn) End If End If 'Release the other objects If m_EditPanel IsNot Nothing Then m_EditPanel.Dispose() End If m_EditPanel = Nothing Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing Return End Try End Sub Private Sub m_EditPanel_SyncLayer(layerName As String) Handles m_EditPanel.SyncLayer RaiseEvent SyncLayer(layerName) End Sub End Class
Esri/water-utility-mobile-map
EditFeaturesMapAction/EditFeaturesMapAction.vb
Visual Basic
apache-2.0
42,393
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Option Strict Off Imports Microsoft.CodeAnalysis.CodeFixes.Suppression Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Suppression Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Suppression Public Class VisualBasicSuppressionAllCodeTests Inherits AbstractSuppressionAllCodeTests Protected Overrides Function CreateWorkspaceFromFileAsync(definition As String, parseOptions As ParseOptions) As Threading.Tasks.Task(Of TestWorkspace) Return VisualBasicWorkspaceFactory.CreateWorkspaceFromFileAsync(definition, DirectCast(parseOptions, VisualBasicParseOptions)) End Function Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of Analyzer, ISuppressionFixProvider) Return New Tuple(Of Analyzer, ISuppressionFixProvider)(New Analyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningOnEveryNodes() As Threading.Tasks.Task Await TestPragmaAsync(TestResource.AllInOneVisualBasicCode, VisualBasicParseOptions.Default, verifier:=Function(t) t.IndexOf("#Disable Warning", StringComparison.Ordinal) >= 0) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionWithAttributeOnEveryNodes() As Threading.Tasks.Task Dim facts = New VisualBasicSyntaxFactsService() Await TestSuppressionWithAttributeAsync( TestResource.AllInOneVisualBasicCode, VisualBasicParseOptions.Default, digInto:=Function(n) Dim member = facts.GetContainingMemberDeclaration(n, n.Span.Start) If member Is Nothing OrElse member Is n Then Return True End If Return Not TypeOf n Is StatementSyntax End Function, verifier:=Function(t) t.IndexOf("SuppressMessage", StringComparison.Ordinal) >= 0) End Function End Class End Namespace
HellBrick/roslyn
src/EditorFeatures/VisualBasicTest/Diagnostics/Suppression/SuppressionAllCodeTests.vb
Visual Basic
apache-2.0
2,575
'*******************************************************************************************' ' ' ' 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 ' Direct URL of PDF file to get information Const SourceFileURL As String = "https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/pdf-info/sample.pdf" ' Comma-separated list of barcode types to search. ' See valid barcode types in the documentation https://secure.bytescout.com/cloudapi.html#api-Default-barcodeReadFromUrlGet Const BarcodeTypes As String = "Code128,Code39,Interleaved2of5,EAN13" ' Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'. Const Pages As String = "" Sub Main() ' Create standard .NET web client instance Dim webClient As WebClient = New WebClient() ' Prepare URL for `PDF Info` API call Dim query As String = Uri.EscapeUriString(String.Format( "https://localhost/pdf/info?url={0}", SourceFileURL)) 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 ' Display PDF document information For Each token As JToken In json("info") Dim [property] as JProperty = token Console.WriteLine("{0}: {1}", [property].Name, [property].Value) Next Else Console.WriteLine(json("message").ToString()) 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 Information API/VB.NET/Get PDF Info From URL/Module1.vb
Visual Basic
apache-2.0
2,776
Option Strict On Namespace Xeora.Web.Site.Setting Public Class Settings Implements [Shared].IDomain.ISettings Private _XPathStream As IO.StringReader = Nothing Private _XPathNavigator As Xml.XPath.XPathNavigator Private _Configurations As Configurations Private _Services As Services Private _URLMappings As URLMapping Public Sub New(ByVal ConfigurationContent As String) If ConfigurationContent Is Nothing OrElse ConfigurationContent.Trim().Length = 0 Then Throw New System.Exception([Global].SystemMessages.CONFIGURATIONCONTENT & "!") End If Dim xPathDoc As Xml.XPath.XPathDocument Try ' Performance Optimization Me._XPathStream = New IO.StringReader(ConfigurationContent) xPathDoc = New Xml.XPath.XPathDocument(Me._XPathStream) Me._XPathNavigator = xPathDoc.CreateNavigator() ' !-- Catch ex As system.Exception Me.Dispose(True) Throw End Try Me._Configurations = New Configurations(Me._XPathNavigator) Me._Services = New Services(Me._XPathNavigator) Me._URLMappings = New URLMapping(Me._XPathNavigator) End Sub Public ReadOnly Property Configurations() As [Shared].IDomain.ISettings.IConfigurations Implements [Shared].IDomain.ISettings.Configurations Get Return Me._Configurations End Get End Property Public ReadOnly Property Services() As [Shared].IDomain.ISettings.IServices Implements [Shared].IDomain.ISettings.Services Get Return Me._Services End Get End Property Public ReadOnly Property URLMappings() As [Shared].IDomain.ISettings.IURLMappings Implements [Shared].IDomain.ISettings.URLMappings Get Return Me._URLMappings End Get End Property Private disposedValue As Boolean = False ' To detect redundant calls ' IDisposable Protected Overridable Sub Dispose(ByVal disposing As Boolean) If Not Me.disposedValue Then Me._XPathStream.Close() : GC.SuppressFinalize(Me._XPathStream) Me.disposedValue = True End Sub #Region " IDisposable Support " ' This code added by Visual Basic to correctly implement the disposable pattern. Public Sub Dispose() Implements IDisposable.Dispose ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. Dispose(True) GC.SuppressFinalize(Me) End Sub #End Region End Class End Namespace
xeora/XeoraCube
Framework/Xeora.Web/Site/Domain/Setting/Settings.vb
Visual Basic
mit
2,796
Imports System.Collections.Generic Imports System.Linq Imports Tests.Model Public Module CompilerServices Public Function CompareString(ByVal db As ITestDataContext) As IEnumerable(Of Person) Return From p In db.Person Where p.FirstName = "John" Select p End Function End Module
ronnyek/linq2db
Tests/VisualBasic/CompilerServices.vb
Visual Basic
mit
314
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertIfToSwitch Partial Friend NotInheritable Class VisualBasicConvertIfToSwitchCodeRefactoringProvider Private Shared ReadOnly s_operatorMap As Dictionary(Of BinaryOperatorKind, (CaseClauseKind As SyntaxKind, OperatorTokenKind As SyntaxKind)) = New Dictionary(Of BinaryOperatorKind, (SyntaxKind, SyntaxKind))() From { {BinaryOperatorKind.NotEquals, (SyntaxKind.CaseNotEqualsClause, SyntaxKind.LessThanGreaterThanToken)}, {BinaryOperatorKind.LessThan, (SyntaxKind.CaseLessThanClause, SyntaxKind.LessThanToken)}, {BinaryOperatorKind.GreaterThan, (SyntaxKind.CaseGreaterThanClause, SyntaxKind.GreaterThanToken)}, {BinaryOperatorKind.LessThanOrEqual, (SyntaxKind.CaseLessThanOrEqualClause, SyntaxKind.LessThanEqualsToken)}, {BinaryOperatorKind.GreaterThanOrEqual, (SyntaxKind.CaseGreaterThanOrEqualClause, SyntaxKind.GreaterThanEqualsToken)} } Public Overrides Function CreateSwitchExpressionStatement(target As SyntaxNode, sections As ImmutableArray(Of AnalyzedSwitchSection)) As SyntaxNode Throw ExceptionUtilities.Unreachable End Function Public Overrides Function CreateSwitchStatement(ifStatement As ExecutableStatementSyntax, expression As SyntaxNode, sectionList As IEnumerable(Of SyntaxNode)) As SyntaxNode Return VisualBasicSyntaxGenerator.Instance.SwitchStatement(expression, sectionList) End Function Public Overrides Function AsSwitchSectionStatements(operation As IOperation) As IEnumerable(Of SyntaxNode) Dim node = operation.Syntax Return If(node.IsStatementContainerNode(), node.GetStatements(), SpecializedCollections.SingletonEnumerable(node)) End Function Public Overrides Function AsSwitchLabelSyntax(label As AnalyzedSwitchLabel) As SyntaxNode Debug.Assert(label.Guards.IsDefaultOrEmpty) Return AsCaseClauseSyntax(label.Pattern).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker) End Function Private Shared Function AsCaseClauseSyntax(pattern As AnalyzedPattern) As CaseClauseSyntax Return pattern.TypeSwitch( Function(p As AnalyzedPattern.Constant) SyntaxFactory.SimpleCaseClause(p.ExpressionSyntax), Function(p As AnalyzedPattern.Range) SyntaxFactory.RangeCaseClause(p.LowerBound, p.HigherBound), Function(p As AnalyzedPattern.Relational) Dim relationalOperator = s_operatorMap(p.OperatorKind) Return SyntaxFactory.RelationalCaseClause( relationalOperator.CaseClauseKind, SyntaxFactory.Token(SyntaxKind.IsKeyword), SyntaxFactory.Token(relationalOperator.OperatorTokenKind), p.Value) End Function, Function(p) As CaseClauseSyntax Throw ExceptionUtilities.UnexpectedValue(p) End Function) End Function End Class End Namespace
abock/roslyn
src/Features/VisualBasic/Portable/ConvertIfToSwitch/VisualBasicConvertIfToSwitchCodeRefactoringProvider.Rewriting.vb
Visual Basic
mit
3,543
' 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.CodeQuality.Analyzers.ApiDesignGuidelines Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Namespace Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines ''' <summary> ''' CA1711: Identifiers should not have incorrect suffix ''' </summary> <ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]> Public NotInheritable Class BasicIdentifiersShouldNotHaveIncorrectSuffixFixer Inherits IdentifiersShouldNotHaveIncorrectSuffixFixer End Class End Namespace
mavasani/roslyn-analyzers
src/NetAnalyzers/VisualBasic/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/BasicIdentifiersShouldNotHaveIncorrectSuffix.Fixer.vb
Visual Basic
apache-2.0
731
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class EnumTests Inherits BasicTestBase ' The value of first enumerator, and the value of each successive enumerator <Fact> Public Sub ValueOfFirst() Dim text = <compilation name="C"> <file name="a.vb"> Enum Suits ValueA ValueB ValueC ValueD End Enum </file> </compilation> VerifyEnumsValue(text, "Suits", 0, 1, 2, 3) End Sub ' The value can be explicated initialized <Fact> Public Sub ExplicateInit() Dim text = <compilation name="C"> <file name="a.vb"> Public Enum Suits ValueA = -1 ValueB = 2 ValueC = 3 ValueD = 4 End Enum </file> </compilation> VerifyEnumsValue(text, "Suits", -1, 2, 3, 4) End Sub ' The value can be explicated and implicit initialized <Fact> Public Sub MixedInit() Dim text = <compilation name="C"> <file name="a.vb"> Public Enum Suits ValueA ValueB = 10 ValueC ValueD End Enum </file> </compilation> VerifyEnumsValue(text, "Suits", 0, 10, 11, 12) End Sub ' Using shared field of an enum member does not cause evaluation cycle <Fact> Public Sub MixedInitShared() Dim text = <compilation name="C"> <file name="a.vb"> Public Enum Suits ValueA ValueB = 10 ValueC = Suits.ValueC.ValueB + 1 ValueD End Enum </file> </compilation> VerifyEnumsValue(text, "Suits", 0, 10, 11, 12) End Sub ' Enumerator initializers must be of integral or enumeration type <WorkItem(539945, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539945")> <Fact> Public Sub OutOfUnderlyingRange() Dim text = <compilation name="C"> <file name="a.vb"> Option Strict Off Public Enum Suits As Byte ValueA = "3" ' Can't implicitly convert ValueB = 2.2 ' Can implicitly convert ValueC = 257 ' Out of underlying range End Enum </file> </compilation> ' There are diagnostics for these values (see EnumErrorsInValues test), ' but as long as the value is constant (including the needed conversion), the constant value is used ' (see conversion of 2.2 vs. conversion of "3"). Dim fields = VerifyEnumsValue(text, "Suits", SpecialType.System_Byte, Nothing, CByte(2), Nothing) fields.First.DeclaringCompilation.AssertTheseDiagnostics( <expected> BC30060: Conversion from 'String' to 'Byte' cannot occur in a constant expression. ValueA = "3" ' Can't implicitly convert ~~~ BC30439: Constant expression not representable in type 'Byte'. ValueC = 257 ' Out of underlying range ~~~ </expected>) text = <compilation name="C"> <file name="a.vb"> Option Strict On Public Enum Suits As Byte ValueA = "3" ' Can't implicitly convert ValueB = 2.2 ' Can't implicitly convert: [Option Strict On] disallows implicit conversion ValueC = 257 ' Out of underlying range End Enum </file> </compilation> ' There are diagnostics for these values (see EnumErrorsInValues test), ' but as long as the value is constant (including the needed conversion), the constant value is used ' (see conversion of 2.2 vs. conversion of "3"). fields = VerifyEnumsValue(text, "Suits", SpecialType.System_Byte, Nothing, CByte(2), Nothing) fields.First.DeclaringCompilation.AssertTheseDiagnostics( <expected> BC30512: Option Strict On disallows implicit conversions from 'String' to 'Byte'. ValueA = "3" ' Can't implicitly convert ~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Byte'. ValueB = 2.2 ' Can't implicitly convert: [Option Strict On] disallows implicit conversion ~~~ BC30439: Constant expression not representable in type 'Byte'. ValueC = 257 ' Out of underlying range ~~~ </expected>) text = <compilation name="C"> <file name="a.vb"> Enum Suits As Short a b c d = -65536 e f End Enum </file> </compilation> fields = VerifyEnumsValue(text, "Suits", SpecialType.System_Int16, CShort(0), CShort(1), CShort(2), Nothing, Nothing, Nothing) fields.First.DeclaringCompilation.AssertTheseDiagnostics( <expected> BC30439: Constant expression not representable in type 'Short'. d = -65536 ~~~~~~ </expected>) End Sub <Fact> Public Sub EnumErrorsInValues() Dim text = <compilation name="C"> <file name="a.vb"> Public Enum Suits As Byte ValueA = "3" ' Can't implicitly convert ValueB = 2.2 ' Can implicitly convert ValueC = 257 ' Out of underlying range End Enum </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) CompilationUtils.AssertTheseDiagnostics(comp, <errors> BC30060: Conversion from 'String' to 'Byte' cannot occur in a constant expression. ValueA = "3" ' Can't implicitly convert ~~~ BC30439: Constant expression not representable in type 'Byte'. ValueC = 257 ' Out of underlying range ~~~ </errors>) comp = CompilationUtils.CreateCompilationWithMscorlib40(text, options:=TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(comp, <errors> BC30512: Option Strict On disallows implicit conversions from 'String' to 'Byte'. ValueA = "3" ' Can't implicitly convert ~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Byte'. ValueB = 2.2 ' Can implicitly convert ~~~ BC30439: Constant expression not representable in type 'Byte'. ValueC = 257 ' Out of underlying range ~~~ </errors>) End Sub <Fact()> Public Sub ExplicitAssociated() Dim text = <compilation name="C"> <file name="a.vb"> Class C(Of T) Const field As Integer = 100 Private Enum TestEnum A B = A ' another member C = D ' another member D = CByte(11) ' type can be implicitly converted to underlying type F = 3 + 5 ' expression G = field ' const field TestEnum ' its own type name var ' contextual keyword T ' Type parameter End Enum Private Enum EnumB B = TestEnum.T End Enum End Class </file> </compilation> VerifyEnumsValue(text, "C.TestEnum", 0, 0, 11, 11, 8, 100, 101, 102, 103) VerifyEnumsValue(text, "C.EnumB", 103) text = <compilation name="C"> <file name="a.vb"> Class c1 Public Shared StaticField As Integer = 10 Public Shared ReadOnly ReadonlyField As Integer = 100 Private Enum EnumTest A = StaticField B = ReadonlyField End Enum End Class </file> </compilation> VerifyEnumsValue(text, "c1.EnumTest", SpecialType.System_Int32, Nothing, Nothing) End Sub ' No enum-body <Fact> Public Sub NoEnumBody() Dim text = <compilation name="C"> <file name="a.vb"> Enum Figure End Enum </file> </compilation> VerifyEnumsValue(text, "Figure") End Sub ' No identifier <Fact> Public Sub BC30203ERR_ExpectedIdentifier_NoIDForEnum() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="BadEmptyEnum1"> <file name="a.vb"> Enum One Two Three End Enum </file> </compilation>) CompilationUtils.AssertTheseParseDiagnostics(comp, <ERRORS> BC30203: Identifier expected. Enum ~ </ERRORS>) End Sub <Fact> Public Sub EnumTypeCharMismatch() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="EnumTypeCharMismatch"> <file name="a.vb"> Enum E As Integer X Y = E.X% Z = E.X$ End Enum </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <ERRORS> BC30277: Type character '$' does not match declared data type 'Integer'. Z = E.X$ ~~ </ERRORS>) End Sub <Fact> Public Sub EnumTypeCharMismatch1() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="EnumTypeCharMismatch"> <file name="a.vb"> Imports System Module M1 Enum E As Integer X = Int32%.MinValue Y = E%.X Z = E$.X End Enum End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <ERRORS> BC30277: Type character '$' does not match declared data type 'Integer'. Z = E$.X ~~ </ERRORS>) End Sub ' Same identifier for enum members <Fact> Public Sub SameIDForEnum() Dim text = <compilation name="C"> <file name="a.vb"> Enum TestEnum One One End Enum </file> </compilation> VerifyEnumsValue(text, "TestEnum", 0, 1) End Sub ' Modifiers for enum <WorkItem(539944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539944")> <Fact> Public Sub BC30396ERR_BadEnumFlags1_ModifiersForEnum() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Class Program Protected Enum Figure1 One = 1 End Enum ' OK New Public Enum Figure2 Zero = 0 End Enum ' new + protection modifier is Not OK Private MustInherit Enum Figure3 Zero End Enum ' abstract not valid Private Private Enum Figure4 One = 1 End Enum ' Duplicate modifier is not OK Private Public Enum Figure5 End Enum ' More than one protection modifiers is not OK Private NotInheritable Enum Figure0 Zero End Enum ' sealed not valid Private Shadows Enum Figure Zero End Enum ' OK End Class </file> </compilation>) Dim expectedErrors1 = <errors> BC30035: Syntax error. New Public Enum Figure2 ~~~ BC30188: Declaration expected. Zero = 0 ~~~~ BC30184: 'End Enum' must be preceded by a matching 'Enum'. End Enum ' new + protection modifier is Not OK ~~~~~~~~ BC30396: 'MustInherit' is not valid on an Enum declaration. Private MustInherit Enum Figure3 ~~~~~~~~~~~ BC30178: Specifier is duplicated. Private Private Enum Figure4 ~~~~~~~ BC30176: Only one of 'Public', 'Private', 'Protected', 'Friend', 'Protected Friend', or 'Private Protected' can be specified. Private Public Enum Figure5 ~~~~~~ BC30280: Enum 'Figure5' must contain at least one member. Private Public Enum Figure5 ~~~~~~~ BC30396: 'NotInheritable' is not valid on an Enum declaration. Private NotInheritable Enum Figure0 ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub ' Modifiers for enum member <Fact> Public Sub ModifiersForEnumMember() Dim text = <compilation name="C"> <file name="a.vb"> Enum ColorA Public Red End Enum </file> </compilation> VerifyEnumsValue(text, "ColorA") text = <compilation name="C"> <file name="a.vb"> Enum ColorA Private Sub goo() End Sub End Enum </file> </compilation> VerifyEnumsValue(text, "ColorA") End Sub ' Flag Attribute and Enumerate a Enum <Fact> Public Sub FlagOnEnum() Dim text = <compilation name="C"> <file name="a.vb"> &lt;System.Flags&gt; Public Enum Suits ValueA = 1 ValueB = 2 ValueC = 4 ValueD = 8 Combi = ValueA Or ValueB End Enum </file> </compilation> VerifyEnumsValue(text, "Suits", 1, 2, 4, 8, 3) End Sub ' Customer Attribute on Enum declaration <Fact> Public Sub AttributeOnEnum() Dim text = <compilation name="C"> <file name="a.vb"> Class Attr1 Inherits System.Attribute End Class &lt;Attr1&gt; _ Enum Figure One Two Three End Enum </file> </compilation> VerifyEnumsValue(text, "Figure", 0, 1, 2) End Sub <Fact()> Public Sub ConvertOnEnum() Dim text = <compilation name="C"> <file name="a.vb"> Imports System Class c1 Public Enum Suits ValueA = 1 ValueB = 2 ValueC = 4 ValueD = 2 ValueE = 2 End Enum Shared Sub Main() Dim S As Suits = CType(2, Suits) Console.WriteLine(S.ToString()) ' ValueE Dim S1 As Suits = CType(-1, Suits) Console.WriteLine(S1.ToString()) ' 255 End Sub End Class </file> </compilation> VerifyEnumsValue(text, "c1.Suits", 1, 2, 4, 2, 2) Dim expectedOutput = <![CDATA[ ValueE -1 ]]> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(text, TestOptions.ReleaseExe) CompileAndVerify(comp, expectedOutput) End Sub ' Enum used in switch <Fact> Public Sub SwitchInEnum() Dim text = <compilation name="C"> <file name="a.vb"> Class c1 Public Enum Suits ValueA = 2 ValueB ValueC = 2 End Enum Public Sub Main() Dim s As Suits Select Case s Case Suits.ValueA Exit Select Case Suits.ValueB Exit Select Case Suits.ValueC Exit Select Case Else Exit Select End Select End Sub End Class </file> </compilation> VerifyEnumsValue(text, "c1.Suits", 2, 3, 2) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) CompilationUtils.AssertTheseDeclarationDiagnostics(comp, <errors></errors>) End Sub ' The literal 0 implicitly converts to any enum type. <Fact> Public Sub ZeroInEnum() Dim text = <compilation name="C"> <file name="a.vb"> Imports System Class c1 Private Enum Gender As Byte Male = 2 End Enum Public Shared Sub Main(args As String()) Dim s As Gender = 0 Console.WriteLine(s) s = -0 Console.WriteLine(s) s = 0.0 Console.WriteLine(s) End Sub End Class </file> </compilation> CompileAndVerify(text, expectedOutput:="0" & Environment.NewLine & "0" & Environment.NewLine & "0" & Environment.NewLine) End Sub ' Derived. <Fact> Public Sub BC30628ERR_StructCantInherit_DerivedFromEnum() Dim text = <compilation name="C"> <file name="a.vb"> Public Enum Suits ValueA = 2 ValueB ValueC = 2 End Enum Structure S1 Inherits Suits End Structure Interface I1 Inherits Suits End Interface </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) CompilationUtils.AssertTheseDeclarationDiagnostics(comp, <errors> BC30628: Structures cannot have 'Inherits' statements. Inherits Suits ~~~~~~~~~~~~~~ BC30354: Interface can inherit only from another interface. Inherits Suits ~~~~~ </errors>) End Sub ' Enums can Not be declared in nested enum declaration <WorkItem(539943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539943")> <Fact> Public Sub BC30619ERR_InvInsideEndsEnum_NestedFromEnum() Dim text = <compilation name="C"> <file name="a.vb"> Public Enum Num Enum Figure Zero End Enum End Enum </file> </compilation> VerifyEnumsValue(text, "Num") VerifyEnumsValue(text, "Figure", 0) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) CompilationUtils.AssertTheseDiagnostics(comp, <errors> BC30185: 'Enum' must end with a matching 'End Enum'. Public Enum Num ~~~~~~~~~~~~~~~ BC30280: Enum 'Num' must contain at least one member. Public Enum Num ~~~ BC30619: Statement cannot appear within an Enum body. End of Enum assumed. Enum Figure ~~~~~~~~~~~ BC30184: 'End Enum' must be preceded by a matching 'Enum'. End Enum ~~~~~~~~ </errors>) End Sub ' Enums can be declared anywhere <Fact> Public Sub DeclEnum() Dim text = <compilation name="C"> <file name="a.vb"> Namespace ns Enum Gender Male End Enum End Namespace Structure B Private Enum Gender Male End Enum End Structure </file> </compilation> VerifyEnumsValue(text, "ns.Gender", 0) VerifyEnumsValue(text, "B.Gender", 0) End Sub ' Enums obey local scope rules <Fact> Public Sub DeclEnum_01() Dim text = <compilation name="C"> <file name="a.vb"> Namespace ns Enum E1 yes = 1 no = yes - 1 End Enum Public Class mine Public Enum E1 yes = 1 no = yes - 1 End Enum End Class End Namespace </file> </compilation> VerifyEnumsValue(text, "ns.E1", 1, 0) VerifyEnumsValue(text, "ns.mine.E1", 1, 0) End Sub <Fact()> Public Sub NullableOfEnum() Dim text = <compilation name="C"> <file name="a.vb"> Enum EnumB As Long Num = 1000 End Enum Class c1 Public Shared Sub Main() Dim a As EnumB = 0 Dim c As System.Nullable(Of EnumB) = Nothing a = CType(c, EnumB) End Sub End Class </file> </compilation> VerifyEnumsValue(text, "EnumB", 1000L) CompileAndVerify(text) End Sub ' Operator on null and enum <Fact> Public Sub OperatorOnNullableAndEnum() Dim text = <compilation name="C"> <file name="a.vb"> class c1 Private e As MyEnum = Nothing And MyEnum.One End Class enum MyEnum One End Enum </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) CompilationUtils.AssertTheseDeclarationDiagnostics(comp, <errors></errors>) End Sub ' Operator on enum <Fact> Public Sub OperatorOnEnum() Dim text = <compilation name="C"> <file name="a.vb"> Class c1 Public Shared Sub Main(args As String()) Dim e1 As Enum1 = e1 + 5L Dim e2 As Enum2 = e1 + e2 e1 = Enum1.A1 + Enum1.B1 Dim b1 As Boolean = e1 = 1 Dim b7 As Boolean = e1 = e2 e1 += 1 ' OK e2 -= 1 ' OK e1 = e1 Xor Enum1.A1 ' OK e1 = e1 Xor Enum1.B1 ' OK End Sub End Class Public Enum Enum1 A1 = 1 B1 = 2 End Enum Public Enum Enum2 As Byte A2 B2 End Enum </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) CompilationUtils.AssertTheseDeclarationDiagnostics(comp, <errors></errors>) End Sub ' Operator on enum member <Fact> Public Sub OperatorOnEnumMember() Dim text = <compilation name="C"> <file name="a.vb"> Imports System Class c1 Public Shared Sub Main(args As String()) Dim s As E = E.one Dim b1 = E.three &gt; E.two Dim b2 = E.three &lt; E.two Dim b3 = E.three = E.two Dim b4 = E.three &lt;&gt; E.two Dim b5 = s &gt; E.two Dim b6 = s &lt; E.two Dim b7 = s = E.two Dim b8 = s &lt;&gt; E.two Console.WriteLine(b1) Console.WriteLine(b2) Console.WriteLine(b3) Console.WriteLine(b4) Console.WriteLine(b5) Console.WriteLine(b6) Console.WriteLine(b7) Console.WriteLine(b8) End Sub End Class Public Enum E one = 1 two = 2 three = 3 End Enum </file> </compilation> CompileAndVerify(text, expectedOutput:="True" & Environment.NewLine & "False" & Environment.NewLine & "False" & Environment.NewLine & "True" & Environment.NewLine & "False" & Environment.NewLine & "True" & Environment.NewLine & "False" & Environment.NewLine & "True" & Environment.NewLine) End Sub ' CLS-Compliant <Fact> Public Sub CLSCompliantOnEnum() Dim text = <compilation name="C"> <file name="a.vb"> &lt;Assembly: System.CLSCompliant(True)&gt; Public Class c1 Public Enum COLORS As UInteger RED GREEN BLUE End Enum End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) VerifyEnumsValue(comp, "c1.COLORS", SpecialType.System_UInt32, 0UI, 1UI, 2UI) End Sub ' No Base type after 'As' <WorkItem(528031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528031")> <Fact> Public Sub BC30182ERR_UnrecognizedType_NoUnderlyingTypeForEnum() Dim text = <compilation name="C"> <file name="a.vb"> Public Enum Figure As One Two Three End Enum </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) CompilationUtils.AssertTheseParseDiagnostics(comp, <errors> BC30182: Type expected. Public Enum Figure As ~ </errors>) VerifyEnumsValue(comp, "Figure", SpecialType.System_Int32, 0, 1, 2) End Sub ' All integral type could be as BASE type <WorkItem(539945, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539945")> <Fact> Public Sub BC30650ERR_InvalidEnumBase_BaseType() Dim text = <compilation name="C"> <file name="a.vb"> Public Enum Figure As System.Int64 One Two Three End Enum </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) CompilationUtils.AssertTheseDeclarationDiagnostics(comp, <errors></errors>) VerifyEnumsValue(comp, "Figure", SpecialType.System_Int64, CLng(0), CLng(1), CLng(2)) text = <compilation name="C"> <file name="a.vb"> Class C End Class Enum Figure As C One Two Three End Enum </file> </compilation> comp = CompilationUtils.CreateCompilationWithMscorlib40(text) CompilationUtils.AssertTheseDeclarationDiagnostics(comp, <errors> BC30650: Enums must be declared as an integral type. Enum Figure As C ~ </errors>) VerifyEnumsValue(comp, "Figure", SpecialType.System_Int32, 0, 1, 2) End Sub ' 'partial' as Enum name <Fact> Public Sub partialAsEnumName() Dim text = <compilation name="C"> <file name="a.vb"> Partial Class EnumPartial Friend Enum [partial] ONE End Enum Dim M As [partial] End Class </file> </compilation> VerifyEnumsValue(text, "EnumPartial.partial", 0) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim classEnum = TryCast(comp.SourceModule.GlobalNamespace.GetMembers("EnumPartial").Single(), NamedTypeSymbol) Dim member = TryCast(classEnum.GetMembers("M").Single(), FieldSymbol) Assert.Equal(TypeKind.Enum, member.Type.TypeKind) End Sub ' Enum as an optional parameter <Fact()> Public Sub EnumAsOptionalParameter() Dim text = <compilation name="C"> <file name="a.vb"> Enum ABC a b c End Enum Class c1 Public Function Goo(Optional o As ABC = ABC.a Or ABC.b) As Integer Return 0 End Function Public Function Moo(Optional o As Object = ABC.a) As Integer Return 1 End Function End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) CompilationUtils.AssertTheseDeclarationDiagnostics(comp, <errors></errors>) End Sub <WorkItem(540427, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540427")> <Fact> Public Sub EnumInitializerCircularReference() Dim text = <compilation name="C"> <file name="a.vb"> Enum Enum1 A = B + 1 B End Enum </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40(text).VerifyDiagnostics(Diagnostic(ERRID.ERR_CircularEvaluation1, "A").WithArguments("A")) End Sub <WorkItem(540526, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540526")> <Fact> Public Sub EnumBadMember() Dim text = <compilation> <file name="a.vb"> Enum E [A End Enum </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40(text).VerifyDiagnostics( Diagnostic(ERRID.ERR_MissingEndEnum, "Enum E"), Diagnostic(ERRID.ERR_InvInsideEndsEnum, ""), Diagnostic(ERRID.ERR_MissingEndBrack, "[A"), Diagnostic(ERRID.ERR_InvalidEndEnum, "End Enum"), Diagnostic(ERRID.ERR_BadEmptyEnum1, "E").WithArguments("E")) End Sub <WorkItem(540526, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540526")> <Fact> Public Sub EnumBadMember2() Dim text = <compilation> <file name="a.vb"> Enum E goo: End Enum </file> </compilation> CompilationUtils.CreateCompilationWithMscorlib40(text).VerifyDiagnostics( Diagnostic(ERRID.ERR_InvInsideEnum, "goo:")) End Sub <WorkItem(540557, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540557")> <Fact> Public Sub EnumInDifferentFile() Dim text = <compilation name="C"> <file name="a.vb"> Imports System Imports Color Module M1 Dim passed As Boolean Dim m_clr As Color Property Clr As Color Get Return m_clr End Get Set(value As Color) m_clr = value End Set End Property End Module </file> <file name="color.vb"> Public Enum Color red green blue End Enum </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(text) CompilationUtils.AssertNoErrors(comp) Dim globalNS = comp.SourceModule.GlobalNamespace Dim M1 = DirectCast(globalNS.GetMembers("M1").First(), TypeSymbol) Dim Clr = DirectCast(M1.GetMembers("Clr").First(), PropertySymbol) Dim Color = Clr.Type Assert.Equal("Color", Color.Name) End Sub <Fact> Public Sub EnumMemberInitMustBeConstant() Dim text = <compilation name="C"> <file name="a.vb"> Imports System Class A Public Const X As Integer = 1 End Class Class B Sub New(x As Action) End Sub Sub New(x As Integer) End Sub Public Const X As Integer = 2 End Class Class C Sub New(x As Integer) End Sub Public Const X As Integer = 3 End Class Class D Sub New(x As Func(Of Integer)) End Sub Public Const X As Integer = 4 End Class Module M Public Enum Bar As Integer ValueWorks1 = new C(23).X ValueWorks2 = new A().X ValueWorks3 = 23 + new A().X ValueWorks4 = if(nothing, 23) ValueWorks5 = if(23 = 42, 23, 42) ValueWorks6 = if(new A().X = 0, 23, 42) ValueWorks7 = if(new A(), nothing).X ValueWorks8 = if(23 = 42, 23, new A().X) ValueWorks9 = if(23 = 42, new A().X, 42) ValueWorks10 = New B(Sub() Exit Sub).X ValueWorks11 = New D(Function() 23).X ValueDoesntWork1 = goo() End Enum Public Function goo() As Integer Return 23 End Function public sub main() end sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(text) CompilationUtils.AssertTheseDiagnostics(comp, <errors> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. ValueWorks1 = new C(23).X ~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. ValueWorks2 = new A().X ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. ValueWorks3 = 23 + new A().X ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. ValueWorks6 = if(new A().X = 0, 23, 42) ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. ValueWorks7 = if(new A(), nothing).X ~~~~~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. ValueWorks8 = if(23 = 42, 23, new A().X) ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. ValueWorks9 = if(23 = 42, new A().X, 42) ~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. ValueWorks10 = New B(Sub() Exit Sub).X ~~~~~~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. ValueWorks11 = New D(Function() 23).X ~~~~~~~~~~~~~~~~~~~~~~ BC30059: Constant expression is required. ValueDoesntWork1 = goo() ~~~~~ </errors>) End Sub ''' bug 8151 <Fact> Public Sub EnumMemberWithNonConstInitializationAndSelfDependency() Dim text = <compilation name="C"> <file name="a.vb"> Imports System Class D Sub New(x As Func(Of Integer)) End Sub Public Const X As Integer = 4 End Class Module M Public Enum Bar As Integer ValueDoesntWork2 ValueDoesntWork3 = New D(Function() ValueDoesntWork2).X ValueDoesntWork4 = New D(Function() ValueDoesntWork4).X End Enum public sub main() end sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(text) CompilationUtils.AssertTheseDiagnostics(comp, <errors> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. ValueDoesntWork3 = New D(Function() ValueDoesntWork2).X ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30500: Constant 'ValueDoesntWork4' cannot depend on its own value. ValueDoesntWork4 = New D(Function() ValueDoesntWork4).X ~~~~~~~~~~~~~~~~ </errors>) End Sub ' The value can be used off an enum member <WorkItem(541364, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541364")> <Fact> Public Sub EnumUseQualified() Dim text = <compilation name="C"> <file name="a.vb"> Enum Y X Y = Y.X End Enum </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) CompilationUtils.AssertTheseDiagnostics(comp, <errors> </errors>) VerifyEnumsValue(text, "Y", 0, 0) End Sub <WorkItem(750553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750553")> <Fact> Public Sub InvalidEnumUnderlyingType() Dim text = <compilation> <file name="a.vb"> Class C(Of T As Structure) Enum E As T A End Enum End Class </file> </compilation> Dim errors = <errors> BC30650: Enums must be declared as an integral type. Enum E As T ~ </errors> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) comp.AssertTheseDiagnostics(errors) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree) Dim diagnostics = model.GetDeclarationDiagnostics() AssertTheseDiagnostics(diagnostics, errors) Dim decl = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of EnumBlockSyntax).Single() Dim symbol = model.GetDeclaredSymbol(decl) Dim type = symbol.EnumUnderlyingType Assert.Equal(type.SpecialType, SpecialType.System_Int32) End Sub <Fact, WorkItem(895284, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/895284")> Public Sub CircularDefinition_Explicit() ' Bug#895284 Roslyn gives extra error BC30060: ' Conversion from 'E2' to 'Integer' cannot occur in a constant expression. ' Per field Dim source = <compilation> <file name="a.vb"> Enum E1 M10 = 1 M11 = CType(M10, Integer) + 1 M12 = CType(M11, Integer) + 1 End Enum Enum E2 M20 = CType(M22, Integer) + 1 M21 = CType(M20, Integer) + 1 M22 = CType(M21, Integer) + 1 End Enum </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors> BC30500: Constant 'M20' cannot depend on its own value. M20 = CType(M22, Integer) + 1 ~~~ BC30060: Conversion from 'E2' to 'Integer' cannot occur in a constant expression. M21 = CType(M20, Integer) + 1 ~~~ BC30060: Conversion from 'E2' to 'Integer' cannot occur in a constant expression. M22 = CType(M21, Integer) + 1 ~~~ </errors>) End Sub <Fact> Public Sub CircularDefinitionManyMembers_Implicit() ' Enum E ' M0 = Mn + 1 ' M1 ' ... ' Mn ' End Enum Dim source = GenerateEnum(6000, Function(i, n) If(i = 0, String.Format("M{0} + 1", n - 1), "")) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors> BC30500: Constant 'M0' cannot depend on its own value. M0 = M5999 + 1 ~~ </errors>) End Sub <Fact, WorkItem(123937, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems#_a=edit&id=123937"), WorkItem(886047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/886047")> Public Sub CircularDefinitionManyMembers_Explicit() ' Enum E ' M0 = Mn + 1 ' M1 = M0 + 1 ' ... ' Mn = Mn-1 + 1 ' End Enum ' Dev12 crashes at ~300 members. Const bug123937IsFixed = False Dim count As Integer = 2 If bug123937IsFixed Then count = 6000 End If Dim source = GenerateEnum(count, Function(i, n) String.Format("M{0} + 1", If(i = 0, n - 1, i - 1))) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(source) ' Note, native compiler doesn't report BC30060, we should try to suppress it too. comp.AssertTheseDiagnostics(<errors> BC30500: Constant 'M0' cannot depend on its own value. M0 = M1 + 1 ~~ BC30060: Conversion from 'E' to 'Integer' cannot occur in a constant expression. M1 = M0 + 1 ~~ </errors>) End Sub <Fact, WorkItem(123937, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems#_a=edit&id=123937"), WorkItem(886047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/886047")> Public Sub InvertedDefinitionManyMembers_Explicit() ' Enum E ' M0 = M1 - 1 ' M1 = M2 - 1 ' ... ' Mn = n ' End Enum ' Dev12 crashes at ~300 members. Const bug123937IsFixed = False Dim count As Integer = 20 If bug123937IsFixed Then count = 6000 End If Dim source = GenerateEnum(count, Function(i, n) If(i < n - 1, String.Format("M{0} - 1", i + 1), i.ToString())) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors/>) End Sub ''' <summary> ''' Generate: ''' <code> ''' Enum E ''' M0 = ... ''' M1 = ... ''' ... ''' Mn = ... ''' End Enum ''' </code> ''' </summary> Private Shared Function GenerateEnum(n As Integer, getMemberValue As Func(Of Integer, Integer, String)) As XElement Dim builder As New StringBuilder() builder.AppendLine("Enum E") For i = 0 To n - 1 builder.Append(String.Format(" M{0}", i)) Dim value = getMemberValue(i, n) If Not String.IsNullOrEmpty(value) Then builder.Append(" = ") builder.Append(value) End If builder.AppendLine() Next builder.AppendLine("End Enum") Return <compilation> <file name="a.vb"><%= builder.ToString() %></file> </compilation> End Function Private Shared Function VerifyEnumsValue(text As XElement, enumName As String, ParamArray expectedEnumValues As Object()) As List(Of Symbol) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) Return VerifyEnumsValue(comp, enumName, If(expectedEnumValues.Any() AndAlso expectedEnumValues.First().GetType() Is GetType(Long), SpecialType.System_Int64, SpecialType.System_Int32), expectedEnumValues) End Function Private Shared Function VerifyEnumsValue(text As XElement, enumName As String, underlyingType As SpecialType, ParamArray expectedEnumValues As Object()) As List(Of Symbol) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) Return VerifyEnumsValue(comp, enumName, underlyingType, expectedEnumValues) End Function Private Shared Function VerifyEnumsValue(comp As VisualBasicCompilation, enumName As String, underlyingType As SpecialType, ParamArray expectedEnumValues As Object()) As List(Of Symbol) Dim symEnum = TryCast(GetSymbolByFullName(comp, enumName), NamedTypeSymbol) Assert.NotNull(symEnum) Dim type = symEnum.EnumUnderlyingType Assert.NotNull(type) Assert.Equal(underlyingType, type.SpecialType) Dim fields = symEnum.GetMembers().OfType(Of FieldSymbol).Cast(Of Symbol)() Assert.Equal(expectedEnumValues.Length, fields.Count - 1) For count = 0 To fields.Count - 1 Dim field = DirectCast(fields(count), FieldSymbol) Dim fieldDefinition = DirectCast(field.GetCciAdapter(), Cci.IFieldDefinition) If count = 0 Then Assert.Equal(field.Name, "value__") Assert.False(field.IsShared) Assert.False(field.IsConst) Assert.False(field.IsReadOnly) Assert.Equal(field.DeclaredAccessibility, Accessibility.Public) Assert.Equal(field.Type.SpecialType, underlyingType) Assert.True(fieldDefinition.IsSpecialName) Assert.True(fieldDefinition.IsRuntimeSpecial) Else Assert.Equal(expectedEnumValues(count - 1), field.ConstantValue) Assert.True(field.IsShared) Assert.True(field.IsConst) Assert.False(fieldDefinition.IsSpecialName) Assert.False(fieldDefinition.IsRuntimeSpecial) End If Next Return fields.ToList() End Function Private Shared Function GetSymbolByFullName(compilation As VisualBasicCompilation, memberName As String) As Symbol Dim names As String() = memberName.Split("."c) Dim currentSymbol As Symbol = compilation.GlobalNamespace For Each name In names Assert.True(TypeOf currentSymbol Is NamespaceOrTypeSymbol, String.Format("{0} does not have members", currentSymbol.ToDisplayString())) Dim currentContainer = DirectCast(currentSymbol, NamespaceOrTypeSymbol) Dim members = currentContainer.GetMembers(name) Assert.True(members.Length > 0, String.Format("No members named {0} inside {1}", name, currentSymbol.ToDisplayString())) Assert.True(members.Length <= 1, String.Format("Multiple members named {0} inside {1}", name, currentSymbol.ToDisplayString())) currentSymbol = members.First() Next Return currentSymbol End Function <WorkItem(45625, "https://github.com/dotnet/roslyn/issues/45625")> <Fact> Public Sub UseSiteError_01() Dim sourceA = " public class A End Class " Dim comp = CreateCompilation(sourceA, assemblyName:="UseSiteError_sourceA") Dim refA = comp.EmitToImageReference() Dim sourceB = " public class B( Of T) public enum E F end enum end class public class C public const F as B(Of A).E = Nothing end class " comp = CreateCompilation(sourceB, references:={refA}) Dim refB = comp.EmitToImageReference() Dim sourceC = " class Program Shared Sub Main() const x As Integer = CType(Not C.F, Integer) System.Console.WriteLine(x) End Sub end class " comp = CreateCompilation(sourceC, references:={refB}) comp.AssertTheseDiagnostics( <expected> BC30652: Reference required to assembly 'UseSiteError_sourceA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'A'. Add one to your project. const x As Integer = CType(Not C.F, Integer) ~~~ </expected>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree) Dim expr = tree.GetRoot().DescendantNodes().Single(Function(n) n.Kind() = SyntaxKind.NotExpression) Dim value = model.GetConstantValue(expr) Assert.True(value.HasValue) Assert.Equal(-1, value.Value) End Sub <WorkItem(45625, "https://github.com/dotnet/roslyn/issues/45625")> <Fact> Public Sub UseSiteError_02() Dim sourceA = " public class A End Class " Dim comp = CreateCompilation(sourceA, assemblyName:="UseSiteError_sourceA") Dim refA = comp.EmitToImageReference() Dim sourceB = " public class B( Of T) public enum E F end enum end class public class C public const F as B(Of A).E = Nothing end class " comp = CreateCompilation(sourceB, references:={refA}) Dim refB = comp.EmitToImageReference() Dim sourceC = " Option Infer On class Program Shared Sub Main() Dim x = Not C.F System.Console.WriteLine(x) End Sub end class " comp = CreateCompilation(sourceC, references:={refB}, options:=TestOptions.ReleaseExe) comp.AssertTheseDiagnostics( <expected> BC30652: Reference required to assembly 'UseSiteError_sourceA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'A'. Add one to your project. Dim x = Not C.F ~~~ </expected>) comp = CreateCompilation(sourceC, references:={refB}, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics( <expected> BC30652: Reference required to assembly 'UseSiteError_sourceA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'A'. Add one to your project. Dim x = Not C.F ~~~ </expected>) End Sub End Class End Namespace
panopticoncentral/roslyn
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/EnumTests.vb
Visual Basic
mit
48,633
' 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.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitRedimStatement(node As BoundRedimStatement) As BoundNode ' NOTE: bound redim statement node represents a group of redim clauses; each of ' those can be considered as a standalone statement. This rewrite just returns ' the rewritten redim clause in case there is only one of them or groups ' rewritten redim clauses into bound statement list node if there are more ' ' This rewrite cannot be done later because we specify property access in VisitRedimClause ' which need to be rewritten by call rewriter. We also want to see original property access ' nodes to be able to enforce correct UseTwice semantics If node.Clauses.Length = 1 Then Return Me.Visit(node.Clauses(0)) Else Dim statements = New BoundStatement(node.Clauses.Length - 1) {} For i = 0 To node.Clauses.Length - 1 statements(i) = DirectCast(Me.Visit(node.Clauses(i)), BoundStatement) Next Return New BoundStatementList(node.Syntax, statements.AsImmutableOrNull()) End If End Function End Class End Namespace
AmadeusW/roslyn
src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_Redim.vb
Visual Basic
apache-2.0
1,838
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class TLSE_dialog Inherits System.Windows.Forms.Form 'Form remplace la méthode Dispose pour nettoyer la liste des composants. <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 'Requise par le Concepteur Windows Form Private components As System.ComponentModel.IContainer 'REMARQUE : la procédure suivante est requise par le Concepteur Windows Form 'Elle peut être modifiée à l'aide du Concepteur Windows Form. 'Ne la modifiez pas à l'aide de l'éditeur de code. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.valu_pandialogpos = New System.Windows.Forms.NumericUpDown() Me.Panel_tlse = New System.Windows.Forms.Panel() Me.Icon_reference_panel = New System.Windows.Forms.PictureBox() Me.Icon_reference = New System.Windows.Forms.PictureBox() Me.Panel_dialog = New System.Windows.Forms.Panel() Me.Text_TLSE_dialog = New System.Windows.Forms.Label() Me.Panel_Cancel = New System.Windows.Forms.Panel() Me.Cancel_Button = New System.Windows.Forms.Label() Me.Panel_OK = New System.Windows.Forms.Panel() Me.OK_Button = New System.Windows.Forms.Label() CType(Me.valu_pandialogpos, System.ComponentModel.ISupportInitialize).BeginInit() Me.Panel_tlse.SuspendLayout() CType(Me.Icon_reference_panel, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.Icon_reference, System.ComponentModel.ISupportInitialize).BeginInit() Me.Panel_dialog.SuspendLayout() Me.Panel_Cancel.SuspendLayout() Me.Panel_OK.SuspendLayout() Me.SuspendLayout() ' 'valu_pandialogpos ' Me.valu_pandialogpos.Location = New System.Drawing.Point(12, 588) Me.valu_pandialogpos.Name = "valu_pandialogpos" Me.valu_pandialogpos.Size = New System.Drawing.Size(80, 20) Me.valu_pandialogpos.TabIndex = 99 Me.valu_pandialogpos.Visible = False ' 'Panel_tlse ' Me.Panel_tlse.BackColor = System.Drawing.Color.Transparent Me.Panel_tlse.Controls.Add(Me.Icon_reference_panel) Me.Panel_tlse.Location = New System.Drawing.Point(106, 33) Me.Panel_tlse.Name = "Panel_tlse" Me.Panel_tlse.Size = New System.Drawing.Size(676, 540) Me.Panel_tlse.TabIndex = 98 ' 'Icon_reference_panel ' Me.Icon_reference_panel.BackColor = System.Drawing.Color.Transparent Me.Icon_reference_panel.Location = New System.Drawing.Point(18, 17) Me.Icon_reference_panel.Name = "Icon_reference_panel" Me.Icon_reference_panel.Size = New System.Drawing.Size(54, 50) Me.Icon_reference_panel.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize Me.Icon_reference_panel.TabIndex = 8 Me.Icon_reference_panel.TabStop = False Me.Icon_reference_panel.Visible = False ' 'Icon_reference ' Me.Icon_reference.BackColor = System.Drawing.Color.Transparent Me.Icon_reference.Location = New System.Drawing.Point(38, 50) Me.Icon_reference.Name = "Icon_reference" Me.Icon_reference.Size = New System.Drawing.Size(54, 50) Me.Icon_reference.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize Me.Icon_reference.TabIndex = 97 Me.Icon_reference.TabStop = False Me.Icon_reference.Visible = False ' 'Panel_dialog ' Me.Panel_dialog.BackColor = System.Drawing.Color.Transparent Me.Panel_dialog.BackgroundImage = Global.Tomodachi_Life_Save_Editor.My.Resources.Resources.bg_dialog Me.Panel_dialog.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch Me.Panel_dialog.Controls.Add(Me.Text_TLSE_dialog) Me.Panel_dialog.Controls.Add(Me.Panel_Cancel) Me.Panel_dialog.Controls.Add(Me.Panel_OK) Me.Panel_dialog.Location = New System.Drawing.Point(190, 124) Me.Panel_dialog.Name = "Panel_dialog" Me.Panel_dialog.Size = New System.Drawing.Size(435, 315) Me.Panel_dialog.TabIndex = 96 ' 'Text_TLSE_dialog ' Me.Text_TLSE_dialog.BackColor = System.Drawing.Color.Transparent Me.Text_TLSE_dialog.Cursor = System.Windows.Forms.Cursors.Hand Me.Text_TLSE_dialog.Dock = System.Windows.Forms.DockStyle.Top Me.Text_TLSE_dialog.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Text_TLSE_dialog.Location = New System.Drawing.Point(0, 0) Me.Text_TLSE_dialog.Name = "Text_TLSE_dialog" Me.Text_TLSE_dialog.Size = New System.Drawing.Size(435, 271) Me.Text_TLSE_dialog.TabIndex = 1 Me.Text_TLSE_dialog.Text = "Tomodachi Life" Me.Text_TLSE_dialog.TextAlign = System.Drawing.ContentAlignment.MiddleCenter ' 'Panel_Cancel ' Me.Panel_Cancel.BackColor = System.Drawing.Color.Transparent Me.Panel_Cancel.BackgroundImage = Global.Tomodachi_Life_Save_Editor.My.Resources.Resources.bg_buttons_large Me.Panel_Cancel.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch Me.Panel_Cancel.Controls.Add(Me.Cancel_Button) Me.Panel_Cancel.Location = New System.Drawing.Point(266, 274) Me.Panel_Cancel.Name = "Panel_Cancel" Me.Panel_Cancel.Size = New System.Drawing.Size(80, 23) Me.Panel_Cancel.TabIndex = 3 Me.Panel_Cancel.Visible = False ' 'Cancel_Button ' Me.Cancel_Button.BackColor = System.Drawing.Color.Transparent Me.Cancel_Button.Cursor = System.Windows.Forms.Cursors.Hand Me.Cancel_Button.Dock = System.Windows.Forms.DockStyle.Fill Me.Cancel_Button.Location = New System.Drawing.Point(0, 0) Me.Cancel_Button.Name = "Cancel_Button" Me.Cancel_Button.Size = New System.Drawing.Size(80, 23) Me.Cancel_Button.TabIndex = 0 Me.Cancel_Button.Text = "Cancel" Me.Cancel_Button.TextAlign = System.Drawing.ContentAlignment.MiddleCenter ' 'Panel_OK ' Me.Panel_OK.BackColor = System.Drawing.Color.Transparent Me.Panel_OK.BackgroundImage = Global.Tomodachi_Life_Save_Editor.My.Resources.Resources.bg_buttons_large Me.Panel_OK.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch Me.Panel_OK.Controls.Add(Me.OK_Button) Me.Panel_OK.Location = New System.Drawing.Point(89, 274) Me.Panel_OK.Name = "Panel_OK" Me.Panel_OK.Size = New System.Drawing.Size(80, 23) Me.Panel_OK.TabIndex = 2 Me.Panel_OK.Visible = False ' 'OK_Button ' Me.OK_Button.BackColor = System.Drawing.Color.Transparent Me.OK_Button.Cursor = System.Windows.Forms.Cursors.Hand Me.OK_Button.Dock = System.Windows.Forms.DockStyle.Fill Me.OK_Button.Location = New System.Drawing.Point(0, 0) Me.OK_Button.Name = "OK_Button" Me.OK_Button.Size = New System.Drawing.Size(80, 23) Me.OK_Button.TabIndex = 0 Me.OK_Button.Text = "OK" Me.OK_Button.TextAlign = System.Drawing.ContentAlignment.MiddleCenter ' 'TLSE_dialog ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(889, 654) Me.Controls.Add(Me.valu_pandialogpos) Me.Controls.Add(Me.Icon_reference) Me.Controls.Add(Me.Panel_dialog) Me.Controls.Add(Me.Panel_tlse) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None Me.MaximizeBox = False Me.MinimizeBox = False Me.Name = "TLSE_dialog" Me.ShowInTaskbar = False Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "TLSE_dialog" Me.TransparencyKey = System.Drawing.SystemColors.Control CType(Me.valu_pandialogpos, System.ComponentModel.ISupportInitialize).EndInit() Me.Panel_tlse.ResumeLayout(False) Me.Panel_tlse.PerformLayout() CType(Me.Icon_reference_panel, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.Icon_reference, System.ComponentModel.ISupportInitialize).EndInit() Me.Panel_dialog.ResumeLayout(False) Me.Panel_Cancel.ResumeLayout(False) Me.Panel_OK.ResumeLayout(False) Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents valu_pandialogpos As NumericUpDown Friend WithEvents Icon_reference As PictureBox Friend WithEvents Panel_dialog As Panel Friend WithEvents Text_TLSE_dialog As Label Friend WithEvents Panel_Cancel As Panel Friend WithEvents Cancel_Button As Label Friend WithEvents Panel_OK As Panel Friend WithEvents OK_Button As Label Friend WithEvents Panel_tlse As Panel Friend WithEvents Icon_reference_panel As PictureBox End Class
Brionjv/Tomodachi-Life-Save-Editor
Project EX/Tomodachi Life Save Editor/TLSE_dialog.Designer.vb
Visual Basic
mit
9,433
'**************************************************************************** '* Archie Jacobs '* Manufacturing Automation, LLC '* support@advancedhmi.com '* 12-JUN-11 '* '* Copyright 2011 Archie Jacobs '* '* Distributed under the GNU General Public License (www.gnu.org) '* '* This program is free software; you can redistribute it and/or '* as published by the Free Software Foundation; either version 2 '* of the License, or (at your option) any later version. '* '* This program is distributed in the hope that it will be useful, '* but WITHOUT ANY WARRANTY; without even the implied warranty of '* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the '* GNU General Public License for more details. '* You should have received a copy of the GNU General Public License '* along with this program; if not, write to the Free Software '* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. '* '* 12-JUN-11 Created '* 31-DEC-11 Added BooleanDisplay property '* 28-SEP-12 Catch specific PLCDriverException when trying to subscribe '* 29-JAN-13 Added KeypadMinValue and KeypadMaxValue '* 10-JUL-13 Added Value property '**************************************************************************** Public Class BasicLabel Inherits System.Windows.Forms.Label Public Event ValueChanged As EventHandler #Region "Basic Properties" Private SavedBackColor As System.Drawing.Color '* Remove Text from the property window so users do not attempt to use it <System.ComponentModel.Browsable(False)> _ Public Overrides Property Text As String Get Return MyBase.Text End Get Set(value As String) MyBase.Text = value End Set End Property '****************************************************************************************** '* Use the base control's text property and make it visible as a property on the designer '****************************************************************************************** Private m_Value As String Public Property Value As String Get Return m_Value End Get Set(ByVal value As String) If value <> m_Value Then m_Value = value UpdateText() '* Be sure error handler doesn't revert back to an incorrect text OriginalText = MyBase.Text OnvalueChanged(EventArgs.Empty) End If End Set End Property '********************************** '* Prefix and suffixes to text '********************************** Private m_Prefix As String Public Property ValuePrefix() As String Get Return m_Prefix End Get Set(ByVal value As String) m_Prefix = value UpdateText() Invalidate() End Set End Property Private _Suffix As String Public Property ValueSuffix() As String Get Return _Suffix End Get Set(ByVal value As String) _Suffix = value UpdateText() Invalidate() End Set End Property '*************************************************************** '* Property - Highlight Color '*************************************************************** Private _Highlightcolor As Drawing.Color = Drawing.Color.Red <System.ComponentModel.Category("Appearance")> _ Public Property HighlightColor() As Drawing.Color Get Return _Highlightcolor End Get Set(ByVal value As Drawing.Color) _Highlightcolor = value End Set End Property Private _HighlightKeyChar As String = "!" <System.ComponentModel.Category("Appearance")> _ Public Property HighlightKeyCharacter() As String Get Return _HighlightKeyChar End Get Set(ByVal value As String) _HighlightKeyChar = value End Set End Property Private m_Format As String Public Property NumericFormat() As String Get Return m_Format End Get Set(ByVal value As String) m_Format = value End Set End Property Private m_ValueScaleFactor As Double = 1 Public Property ValueScaleFactor() As Double Get Return m_ValueScaleFactor End Get Set(ByVal value As Double) m_ValueScaleFactor = value 'TODO: Does not refresh in designmode 'Text = MyBase.Text End Set End Property Public Enum BooleanDisplayOption TrueFalse YesNo OnOff End Enum Private m_BooleanDisplay As BooleanDisplayOption Public Property BooleanDisplay() As BooleanDisplayOption Get Return m_BooleanDisplay End Get Set(ByVal value As BooleanDisplayOption) m_BooleanDisplay = value End Set End Property #End Region #Region "PLC Related Properties" '***************************************************** '* Property - Component to communicate to PLC through '***************************************************** Private m_CommComponent As AdvancedHMIDrivers.IComComponent <System.ComponentModel.Description("Driver Instance for data reading and writing")> _ <System.ComponentModel.Category("PLC Properties")> _ Public Property CommComponent() As AdvancedHMIDrivers.IComComponent Get Return m_CommComponent End Get Set(ByVal value As AdvancedHMIDrivers.IComComponent) If m_CommComponent IsNot value Then If SubScriptions IsNot Nothing Then SubScriptions.UnsubscribeAll() End If m_CommComponent = value SubscribeToCommDriver() End If End Set End Property Private _PollRate As Integer Public Property PollRate() As Integer Get Return _PollRate End Get Set(ByVal value As Integer) _PollRate = value End Set End Property Private m_KeypadText As String Public Property KeypadText() As String Get Return m_KeypadText End Get Set(ByVal value As String) m_KeypadText = value End Set End Property Private m_KeypadFont As Font = New Font("Arial", 10) Public Property KeypadFont() As Font Get Return m_KeypadFont End Get Set(ByVal value As Font) m_KeypadFont = value End Set End Property Private m_KeypadForeColor As Color = Color.WhiteSmoke Public Property KeypadFontColor() As Color Get Return m_KeypadForeColor End Get Set(ByVal value As Color) m_KeypadForeColor = value End Set End Property Private m_KeypadWidth As Integer = 300 Public Property KeypadWidth() As Integer Get Return m_KeypadWidth End Get Set(ByVal value As Integer) m_KeypadWidth = value End Set End Property '* 29-JAN-13 Private m_KeypadMinValue As Double Public Property KeypadMinValue As Double Get Return m_KeypadMinValue End Get Set(value As Double) m_KeypadMinValue = value End Set End Property Private m_KeypadMaxValue As Double Public Property KeypadMaxValue As Double Get Return m_KeypadMaxValue End Get Set(value As Double) m_KeypadMaxValue = value End Set End Property Private m_KeypadScaleFactor As Double = 1 <System.ComponentModel.DefaultValue(1)> _ Public Property KeypadScaleFactor() As Double Get Return m_KeypadScaleFactor End Get Set(ByVal value As Double) m_KeypadScaleFactor = value End Set End Property Private m_KeypadAlphaNumeric As Boolean Property KeypadAlpahNumeric As Boolean Get Return m_KeypadAlphaNumeric End Get Set(value As Boolean) m_KeypadAlphaNumeric = value End Set End Property Private m_SuppressErrorDisplay As Boolean <System.ComponentModel.DefaultValue(False)> _ Public Property SuppressErrorDisplay As Boolean Get Return m_SuppressErrorDisplay End Get Set(value As Boolean) m_SuppressErrorDisplay = value End Set End Property '***************************************** '* Property - Address in PLC to Link to '***************************************** Private m_PLCAddressValue As String = "" <System.ComponentModel.Category("PLC Properties")> _ Public Property PLCAddressValue() As String Get Return m_PLCAddressValue End Get Set(ByVal value As String) If m_PLCAddressValue <> value Then m_PLCAddressValue = value '* When address is changed, re-subscribe to new address SubscribeToCommDriver() End If End Set End Property '***************************************** '* Property - Address in PLC to Link to '***************************************** Private InvertVisible As Boolean Private m_PLCAddressVisible As String = "" <System.ComponentModel.Category("PLC Properties")> _ Public Property PLCAddressVisible() As String Get Return m_PLCAddressVisible End Get Set(ByVal value As String) If m_PLCAddressVisible <> value Then m_PLCAddressVisible = value '* When address is changed, re-subscribe to new address SubscribeToCommDriver() End If End Set End Property '***************************************** '* Property - Address in PLC to Write Data To '***************************************** Private m_PLCAddressKeypad As String = "" <System.ComponentModel.Category("PLC Properties")> _ Public Property PLCAddressKeypad() As String Get Return m_PLCAddressKeypad End Get Set(ByVal value As String) If m_PLCAddressKeypad <> value Then m_PLCAddressKeypad = value End If End Set End Property #End Region #Region "Private Methods" Private Sub UpdateText() '* True/False comes from driver, change if BooleanDisplay is different 31-DEC-11 If (m_Value = "True" Or m_Value = "False") And m_BooleanDisplay <> BooleanDisplayOption.TrueFalse Then If Value = "True" Then If m_BooleanDisplay = BooleanDisplayOption.OnOff Then MyBase.Text = "On" If m_BooleanDisplay = BooleanDisplayOption.YesNo Then MyBase.Text = "Yes" Else If m_BooleanDisplay = BooleanDisplayOption.OnOff Then MyBase.Text = "Off" If m_BooleanDisplay = BooleanDisplayOption.YesNo Then MyBase.Text = "No" End If End If '* If suffix has already been added, then removed 17-OCT-11 'If _Suffix IsNot Nothing AndAlso _Suffix <> "" AndAlso value.IndexOf(_Suffix) > 0 Then Text = value.Substring(0, value.IndexOf(_Suffix)) If m_Format <> "" And (Not DesignMode) Then Try '* 31-MAY-13 Dim v As Single If Single.TryParse(m_Value, v) Then MyBase.Text = m_Prefix & Format(CSng(v) * m_ValueScaleFactor, m_Format) & _Suffix End If Catch exC As InvalidCastException If MyBase.Text = "Check NumericFormat and variable type" Then MyBase.Text = "----" Else MyBase.Text = Value End If Catch ex As Exception MyBase.Text = "Check NumericFormat and variable type" End Try Else '* Highlight in red if a Highlightcharacter found mark is in text If InStr(Value, _HighlightKeyChar) > 0 Then If MyBase.BackColor <> _Highlightcolor Then SavedBackColor = MyBase.BackColor MyBase.BackColor = _Highlightcolor Else If SavedBackColor <> Nothing Then MyBase.BackColor = SavedBackColor End If If m_ValueScaleFactor = 1 Then MyBase.Text = m_Prefix & m_Value & _Suffix Else Try MyBase.Text = Value * m_ValueScaleFactor & _Suffix Catch ex As Exception DisplayError("Scale Factor Error - " & ex.Message) End Try End If End If End Sub #End Region #Region "Events" '******************************************************************** '* When an instance is added to the form, set the comm component '* property. If a comm component does not exist, add one to the form '******************************************************************** Protected Overrides Sub OnCreateControl() MyBase.OnCreateControl() If Me.DesignMode Then '******************************************************** '* Search for AdvancedHMIDrivers.IComComponent component '* in the Designer Host Container '* If one exists, set the client of this component to it '******************************************************** Dim i As Integer While m_CommComponent Is Nothing And i < Me.Site.Container.Components.Count If Me.Site.Container.Components(i).GetType.GetInterface("AdvancedHMIDrivers.IComComponent") IsNot Nothing Then m_CommComponent = Me.Site.Container.Components(i) i += 1 End While '*************************************************** '* If no comm component was found, then add one and '* point the CommComponent property to it '*************************************************** If m_CommComponent Is Nothing Then Me.Site.Container.Add(New AdvancedHMIDrivers.EthernetIPforCLXCom) m_CommComponent = Me.Site.Container.Components(Me.Site.Container.Components.Count - 1) End If Else SubscribeToCommDriver() End If End Sub Public Sub New() MyBase.new() Value = "BasicLabel" If (MyBase.ForeColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.ControlText) Or ForeColor = Color.FromArgb(0, 0, 0)) Then ForeColor = System.Drawing.Color.WhiteSmoke End If End Sub Protected Overrides Sub OnHandleCreated(e As System.EventArgs) MyBase.OnHandleCreated(e) 'If ForeColor.R = Me.Parent.BackColor.R And ForeColor.G = Me.Parent.BackColor.G And ForeColor.B = Me.Parent.BackColor.B Then ' ForeColor = Drawing.Color.FromArgb(Not Me.ForeColor.R, Not Me.ForeColor.G, Not Me.ForeColor.B) 'End If End Sub '**************************************************************** '* UserControl overrides dispose to clean up the component list. '**************************************************************** Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing Then If SubScriptions IsNot Nothing Then SubScriptions.dispose() End If End If Finally MyBase.Dispose(disposing) End Try End Sub Protected Overridable Sub OnvalueChanged(ByVal e As EventArgs) RaiseEvent ValueChanged(Me, e) End Sub #End Region #Region "Subscribing and PLC data receiving" Private SubScriptions As SubscriptionHandler '******************************************************************************* '* Subscribe to addresses in the Comm(PLC) Driver '* This code will look at properties to find the "PLCAddress" + property name '* '******************************************************************************* Private Sub SubscribeToCommDriver() If Not DesignMode And IsHandleCreated Then '* Create a subscription handler object If SubScriptions Is Nothing Then SubScriptions = New SubscriptionHandler SubScriptions.CommComponent = m_CommComponent AddHandler SubScriptions.DisplayError, AddressOf DisplaySubscribeError End If '* Check through the properties looking for PLCAddress***, then see if the suffix matches an existing property Dim p() As Reflection.PropertyInfo = Me.GetType().GetProperties For i As Integer = 0 To p.Length - 1 '* Does this property start with "PLCAddress"? If p(i).Name.IndexOf("PLCAddress", StringComparison.CurrentCultureIgnoreCase) = 0 Then '* Get the property value Dim PLCAddress As String = p(i).GetValue(Me, Nothing) If PLCAddress <> "" Then '* Get the text in the name after PLCAddress Dim PropertyToWrite As String = p(i).Name.Substring(10) Dim j As Integer = 0 '* See if there is a corresponding property with the extracted name While j < p.Length AndAlso p(j).Name <> PropertyToWrite j += 1 End While '* If the proprty was found, then subscribe to the PLC Address If j < p.Length Then SubScriptions.SubscribeTo(PLCAddress, AddressOf PolledDataReturned, PropertyToWrite) End If End If End If Next End If End Sub '*************************************** '* Call backs for returned data '*************************************** Private OriginalText As String Private Sub PolledDataReturned(ByVal sender As Object, ByVal e As SubscriptionHandlerEventArgs) If e.PLCComEventArgs.ErrorId = 0 Then Try If e.PLCComEventArgs.Values IsNot Nothing AndAlso e.PLCComEventArgs.Values.Count > 0 Then '* 13-NOV-14 Changed from Convert.ChangeType to CTypeDynamic because a 0/1 would not convert to boolean '* Write the value to the property that came from the end of the PLCAddress... property name Me.GetType().GetProperty(e.SubscriptionDetail.PropertyNameToSet). _ SetValue(Me, CTypeDynamic(e.PLCComEventArgs.Values(0), _ Me.GetType().GetProperty(e.SubscriptionDetail.PropertyNameToSet).PropertyType), Nothing) End If Catch ex As Exception DisplayError("INVALID VALUE!" & ex.Message) End Try Else DisplayError("Com Error " & e.PLCComEventArgs.ErrorId & "." & e.PLCComEventArgs.ErrorMessage) End If End Sub #End Region #Region "Error Display" Private Sub DisplaySubscribeError(ByVal sender As Object, ByVal e As MfgControl.AdvancedHMI.Drivers.Common.PlcComEventArgs) DisplayError(e.ErrorMessage) End Sub '******************************************************** '* Show an error via the text property for a short time '******************************************************** Private ErrorDisplayTime As System.Windows.Forms.Timer Private ErrorLock As New Object Private Sub DisplayError(ByVal ErrorMessage As String) If Not m_SuppressErrorDisplay Then '* Create the error display timer If ErrorDisplayTime Is Nothing Then ErrorDisplayTime = New System.Windows.Forms.Timer AddHandler ErrorDisplayTime.Tick, AddressOf ErrorDisplay_Tick ErrorDisplayTime.Interval = 5000 End If '* Save the text to return to SyncLock (ErrorLock) If Not ErrorDisplayTime.Enabled Then ErrorDisplayTime.Enabled = True OriginalText = MyBase.Text MyBase.Text = ErrorMessage End If End SyncLock End If End Sub '************************************************************************************** '* Return the text back to its original after displaying the error for a few seconds. '************************************************************************************** Private Sub ErrorDisplay_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) 'UpdateText() SyncLock (ErrorLock) MyBase.Text = OriginalText 'If ErrorDisplayTime IsNot Nothing Then ErrorDisplayTime.Enabled = False ' ErrorIsDisplayed = False End SyncLock 'RemoveHandler ErrorDisplayTime.Tick, AddressOf ErrorDisplay_Tick 'ErrorDisplayTime.Dispose() 'ErrorDisplayTime = Nothing 'End If End Sub #End Region #Region "Keypad popup for data entry" Private WithEvents KeypadPopUp As MfgControl.AdvancedHMI.Controls.IKeyboard Private Sub KeypadPopUp_ButtonClick(ByVal sender As Object, ByVal e As MfgControl.AdvancedHMI.Controls.KeyPadEventArgs) Handles KeypadPopUp.ButtonClick If e.Key = "Quit" Then KeypadPopUp.Visible = False ElseIf e.Key = "Enter" Then If m_CommComponent Is Nothing Then DisplayError("CommComponent Property not set") Else If KeypadPopUp.Value <> "" Then '* 29-JAN-13 - Validate value if a Min/Max was specified Try If m_KeypadMaxValue <> m_KeypadMinValue Then If KeypadPopUp.Value < m_KeypadMinValue Or KeypadPopUp.Value > m_KeypadMaxValue Then MsgBox("Value must be >" & m_KeypadMinValue & " and <" & m_KeypadMaxValue) Exit Sub End If End If Catch ex As Exception MsgBox("Failed to validate value. " & ex.Message) Exit Sub End Try Try '* 29-JAN-13 - reduced code and checked for divide by 0 If KeypadScaleFactor = 1 Or KeypadScaleFactor = 0 Then m_CommComponent.Write(m_PLCAddressKeypad, KeypadPopUp.Value) Else m_CommComponent.Write(m_PLCAddressKeypad, CDbl(KeypadPopUp.Value) / m_KeypadScaleFactor) End If Catch ex As Exception MsgBox("Failed to write value - " & ex.Message) End Try End If KeypadPopUp.Visible = False End If End If End Sub '*********************************************************** '* If labeled is clicked, pop up a keypad for data entry '*********************************************************** Protected Overrides Sub OnClick(e As System.EventArgs) MyBase.OnClick(e) If m_PLCAddressKeypad <> "" And Enabled Then If KeypadPopUp Is Nothing Then If m_KeypadAlphaNumeric Then KeypadPopUp = New MfgControl.AdvancedHMI.Controls.AlphaKeyboard(m_KeypadWidth) Else KeypadPopUp = New MfgControl.AdvancedHMI.Controls.Keypad(m_KeypadWidth) End If KeypadPopUp.StartPosition = Windows.Forms.FormStartPosition.CenterScreen KeypadPopUp.TopMost = True End If '*************************** '*Set the font and forecolor '**************************** 'KeypadPopUp.Font = New Font("Arial", 16, FontStyle.Bold, GraphicsUnit.Point) If m_KeypadFont IsNot Nothing Then KeypadPopUp.Font = m_KeypadFont 'If m_KeypadForeColor IsNot Nothing Then KeypadPopUp.ForeColor = m_KeypadForeColor 'End If KeypadPopUp.Text = m_KeypadText KeypadPopUp.Value = "" KeypadPopUp.Visible = True End If End Sub #End Region End Class
bgreer5050/AdvancedHMI
AdvancedHMIControls/Controls/BasicLabel.vb
Visual Basic
mit
24,771
#Region "Microsoft.VisualBasic::fed4d313795705fb87f2097fa282ba4f, src\mzmath\TargetedMetabolomics\LinearQuantitative\Models\StandardCurve.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 StandardCurve ' ' Properties: [IS], blankControls, isValid, isWeighted, linear ' name, points, requireISCalibration ' ' Function: CreateLinearRegression, ToString ' ' ' /********************************************************************************/ #End Region Imports System.Drawing Imports System.Runtime.CompilerServices Imports BioNovoGene.Analytical.MassSpectrometry.Math.LinearQuantitative.Linear Imports Microsoft.VisualBasic.ComponentModel.Collection.Generic Imports Microsoft.VisualBasic.ComponentModel.DataSourceModel.Repository Imports Microsoft.VisualBasic.Data.Bootstrapping Imports Microsoft.VisualBasic.Language Imports Microsoft.VisualBasic.Linq Imports Microsoft.VisualBasic.Math.LinearAlgebra Namespace LinearQuantitative ''' <summary> ''' The linear model of the targeted metabolism model data.(标准曲线模型) ''' </summary> Public Class StandardCurve : Implements INamedValue ''' <summary> ''' The metabolite name or database id ''' </summary> ''' <returns></returns> Public Property name As String Implements IKeyedEntity(Of String).Key ''' <summary> ''' 该代谢物的线性回归模型 ''' </summary> ''' <returns></returns> Public Property linear As IFitted Public Property points As ReferencePoint() Public Property blankControls As Double() ''' <summary> ''' The internal standards ''' </summary> ''' <returns></returns> Public Property [IS] As [IS] ''' <summary> ''' This linear model is required calibration by internal standards or not? ''' (在进行线性回归计算的时候是否需要内标校正?) ''' </summary> ''' <returns></returns> Public ReadOnly Property requireISCalibration As Boolean <MethodImpl(MethodImplOptions.AggressiveInlining)> Get Return Not [IS] Is Nothing AndAlso Not [IS].ID.StringEmpty AndAlso [IS].CIS > 0 End Get End Property Public ReadOnly Property isWeighted As Boolean Get Return TypeOf linear Is WeightedFit End Get End Property Public ReadOnly Property isValid As Boolean Get Return Not linear.CorrelationCoefficient.IsNaNImaginary End Get End Property Public Overrides Function ToString() As String Return $"[{name}] {linear}" End Function <MethodImpl(MethodImplOptions.AggressiveInlining)> Public Shared Function CreateLinearRegression(points As IEnumerable(Of PointF), maxDeletions%, ByRef removed As List(Of PointF)) As IFitted Dim deletes As New List(Of PointF)(removed.SafeQuery) Dim rawPoints As PointF() = points.ToArray Dim fit As IFitted = rawPoints.AutoPointDeletion( weighted:=Function(X) 1 / (X ^ 2), max:=maxDeletions, removed:=deletes, keepsLowestPoint:=True, removesZeroY:=True ) If fit Is Nothing Then ' 完全没有线性 Return New FitResult With { .ErrorTest = rawPoints _ .Select(Function(p) Return DirectCast(New TestPoint With {.X = p.X, .Y = p.Y, .Yfit = 99999999}, IFitError) End Function) _ .ToArray, .RMSE = 9999999, .SSE = 9999999, .SSR = 9999999, .Polynomial = New Polynomial With {.Factors = New Double() {0, 0}} } ElseIf fit.R2 < 0.95 Then deletes = New List(Of PointF)(removed.SafeQuery) fit = rawPoints.AutoPointDeletion( weighted:=Function(X) 1 / (X ^ 2), max:=maxDeletions, removed:=deletes, keepsLowestPoint:=False, removesZeroY:=True ) End If removed = deletes Return fit End Function End Class End Namespace
xieguigang/MassSpectrum-toolkits
src/mzmath/TargetedMetabolomics/LinearQuantitative/Models/StandardCurve.vb
Visual Basic
mit
5,954
Imports System.ServiceProcess <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class ServiceMain Inherits System.ServiceProcess.ServiceBase 'UserService 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 ' The main entry point for the process <MTAThread()> _ <System.Diagnostics.DebuggerNonUserCode()> _ Shared Sub Main() Dim ServicesToRun() As System.ServiceProcess.ServiceBase ' More than one NT Service may run within the same process. To add ' another service to this process, change the following line to ' create a second service object. For example, ' ' ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1, New MySecondUserService} ' ServicesToRun = New System.ServiceProcess.ServiceBase() {New ServiceMain} System.ServiceProcess.ServiceBase.Run(ServicesToRun) End Sub 'Required by the Component Designer Private components As System.ComponentModel.IContainer ' NOTE: The following procedure is required by the Component Designer ' It can be modified using the Component Designer. ' Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container Me.timTicker = New System.Windows.Forms.Timer(Me.components) ' 'Service1 ' Me.ServiceName = "Service1" End Sub Friend WithEvents timTicker As System.Windows.Forms.Timer End Class
jamend/BeyondProxima.vb
ProximaTicker/ServiceMain.designer.vb
Visual Basic
mit
1,913
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' La información general de un ensamblado se controla mediante el siguiente ' conjunto de atributos. Cambie estos valores de atributo para modificar la información ' asociada con un ensamblado. ' Revisar los valores de los atributos del ensamblado <Assembly: AssemblyTitle("ProyectoParcial")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("ProyectoParcial")> <Assembly: AssemblyCopyright("Copyright © 2016")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM. <Assembly: Guid("d526b2b2-4f8e-4261-9624-a014523c57f6")> ' La información de versión de un ensamblado consta de los cuatro valores siguientes: ' ' Versión principal ' Versión secundaria ' Número de compilación ' Revisión ' ' Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión ' mediante el carácter '*', como se muestra a continuación: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")>
Danesas/Proyecto-PV-2016
Parcial1/ProyectoParcial/ProyectoParcial/My Project/AssemblyInfo.vb
Visual Basic
mit
1,282
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Operations Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CommentSelection <[UseExportProvider]> Public Class VisualBasicCommentSelectionTests <WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)> Public Sub Comment1() Dim code = <code>Module Program [|Sub Main(args As String()) 'already commented End Sub|] End Module</code> Dim expected = <code>Module Program 'Sub Main(args As String()) ' 'already commented 'End Sub End Module</code> InvokeCommentOperationOnSelectionAfterReplacingLfToCrLf(code.Value, expected.Value, Operation.Comment) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)> Public Sub UncommentAndFormat1() Dim code = <code>Module Program [| ' Sub Main ( args As String ()) ' ' End Sub |] End Module</code> Dim expected = <code>Module Program Sub Main(args As String()) End Sub End Module</code> InvokeCommentOperationOnSelectionAfterReplacingLfToCrLf(code.Value, expected.Value, Operation.Uncomment) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)> Public Sub UncommentAndFormat2() Dim code = <code>Module Program [| ' Sub Main ( args As String ()) |] [| ' |] [| ' End Sub |] End Module</code> Dim expected = <code>Module Program Sub Main(args As String()) End Sub End Module</code> InvokeCommentOperationOnSelectionAfterReplacingLfToCrLf(code.Value, expected.Value, Operation.Uncomment) End Sub Private Shared Sub InvokeCommentOperationOnSelectionAfterReplacingLfToCrLf(code As String, expected As String, operation As Operation) ' do this since xml value put only vbLf code = code.Replace(vbLf, vbCrLf) expected = expected.Replace(vbLf, vbCrLf) Dim codeWithoutMarkup As String = Nothing Dim spans As ImmutableArray(Of TextSpan) = Nothing MarkupTestFile.GetSpans(code, codeWithoutMarkup, spans) Using workspace = TestWorkspace.CreateVisualBasic(codeWithoutMarkup) Dim doc = workspace.Documents.First() SetupSelection(doc.GetTextView(), spans.Select(Function(s) Span.FromBounds(s.Start, s.End))) Dim commandHandler = New CommentUncommentSelectionCommandHandler( workspace.ExportProvider.GetExportedValue(Of ITextUndoHistoryRegistry), workspace.ExportProvider.GetExportedValue(Of IEditorOperationsFactoryService)) Dim textView = doc.GetTextView() Dim textBuffer = doc.GetTextBuffer() commandHandler.ExecuteCommand(textView, textBuffer, operation, TestCommandExecutionContext.Create()) Assert.Equal(expected, doc.TextBuffer.CurrentSnapshot.GetText()) End Using End Sub Private Shared Sub SetupSelection(textView As IWpfTextView, spans As IEnumerable(Of Span)) Dim snapshot = textView.TextSnapshot If spans.Count() = 1 Then textView.Selection.Select(New SnapshotSpan(snapshot, spans.Single()), isReversed:=False) textView.Caret.MoveTo(New SnapshotPoint(snapshot, spans.Single().End)) Else textView.Selection.Mode = TextSelectionMode.Box textView.Selection.Select(New VirtualSnapshotPoint(snapshot, spans.First().Start), New VirtualSnapshotPoint(snapshot, spans.Last().End)) textView.Caret.MoveTo(New SnapshotPoint(snapshot, spans.Last().End)) End If End Sub End Class End Namespace
aelij/roslyn
src/EditorFeatures/VisualBasicTest/CommentSelection/VisualBasicCommentSelectionTests.vb
Visual Basic
apache-2.0
4,659
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Section Inherits QM.PDA.Screens.BaseForm 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) If disposing AndAlso components IsNot Nothing Then components.Dispose() 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. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Section)) Me.ScreenHeader = New QM.PDA.Screens.ScreenHeader Me.lblSection = New System.Windows.Forms.Label Me.pnlAnswerArea = New System.Windows.Forms.Panel Me.SuspendLayout() ' 'btnNext ' resources.ApplyResources(Me.btnNext, "btnNext") ' 'btnBack ' resources.ApplyResources(Me.btnBack, "btnBack") ' 'mnuGPS ' resources.ApplyResources(Me.mnuGPS, "mnuGPS") ' 'mnuTools ' resources.ApplyResources(Me.mnuTools, "mnuTools") ' 'mnuToolsSeparator ' resources.ApplyResources(Me.mnuToolsSeparator, "mnuToolsSeparator") ' 'mnuChangeSubject ' resources.ApplyResources(Me.mnuChangeSubject, "mnuChangeSubject") ' 'mnuChangeQuestionnaire ' resources.ApplyResources(Me.mnuChangeQuestionnaire, "mnuChangeQuestionnaire") ' 'mnuChangeStudy ' resources.ApplyResources(Me.mnuChangeStudy, "mnuChangeStudy") ' 'mnuChangeBlockSeparator ' resources.ApplyResources(Me.mnuChangeBlockSeparator, "mnuChangeBlockSeparator") ' 'mnuLogout ' resources.ApplyResources(Me.mnuLogout, "mnuLogout") ' 'ScreenHeader ' resources.ApplyResources(Me.ScreenHeader, "ScreenHeader") Me.ScreenHeader.Name = "ScreenHeader" ' 'lblSection ' resources.ApplyResources(Me.lblSection, "lblSection") Me.lblSection.Name = "lblSection" ' 'pnlAnswerArea ' resources.ApplyResources(Me.pnlAnswerArea, "pnlAnswerArea") Me.pnlAnswerArea.Name = "pnlAnswerArea" ' 'Section ' Me.AutoScaleDimensions = New System.Drawing.SizeF(96.0!, 96.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi resources.ApplyResources(Me, "$this") Me.Controls.Add(Me.ScreenHeader) Me.Controls.Add(Me.lblSection) Me.Controls.Add(Me.pnlAnswerArea) Me.Name = "Section" Me.WindowState = System.Windows.Forms.FormWindowState.Maximized Me.Controls.SetChildIndex(Me.pnlAnswerArea, 0) Me.Controls.SetChildIndex(Me.lblSection, 0) Me.Controls.SetChildIndex(Me.ScreenHeader, 0) Me.ResumeLayout(False) End Sub Private WithEvents ScreenHeader As Screens.ScreenHeader Private WithEvents lblSection As System.Windows.Forms.Label Friend WithEvents pnlAnswerArea As System.Windows.Forms.Panel End Class
QMDevTeam/QMPDA
QM.PDA.App/Section.Designer.vb
Visual Basic
apache-2.0
3,581
Public Class Constants Public Const APP_NAME As String = "ClassifierClient" ' data files Public Const BUILDER_DATA As String = "BuilderDataSource.xml" Public Const BUILDER_DATA_PATCH As String = "BuilderDataSourcePatch.xml" Public Const DEVICE_DATA As String = "DeviceDataSource.xml" Public Const DEVICE_DATA_PATCH As String = "DeviceDataSourcePatch.xml" Public Const DEVICE_UA As String = "mobi.openddr.classifier.client" Public Const DEVICE_TOSTRING_FORMAT As String = "Id='{0}', ParentId='{1}', Type='{2}', Pattern={3}, Attributes={4}" Public Const HTTP_PREFIX As String = "http" Public Const RELEASE_VERSION As String = "1.0.4-SNAPSHOT" ' TODO could we crop this for the assembly info? Public Const SIMPLE As String = "simple" Public Const USER_AGENT_SPLIT As String = " |-|_|/|\\|\[|\]|\(|\)|;" Public Const VERSION_FORMAT As String = "Version : {0}, Build : {1}" Public Const CONFIG_ERROR_FORMAT As String = "Error in configuration file '{0}' : {1}." Public Const CONFIG_ERROR_CONN_FORMAT As String = "Error in configuration file '{0}' : ConnectionString entry for OpenDDR is missing." Public Const FILE_ERROR_FORMAT As String = "File '{0}' not found." Public Const WEB_ERROR_FORMAT As String = "Web exception : {0}." End Class
OpenDDRmobi/openddr-vb
Client/Constants.vb
Visual Basic
apache-2.0
1,307
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Snakey 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.pnlicon = New System.Windows.Forms.PictureBox() Me.pgbottom = New System.Windows.Forms.Panel() Me.pullside = New System.Windows.Forms.Timer(Me.components) Me.pullbs = New System.Windows.Forms.Timer(Me.components) Me.closebutton = New System.Windows.Forms.Panel() Me.lbtitletext = New System.Windows.Forms.Label() Me.pgtoplcorner = New System.Windows.Forms.Panel() Me.pgtoprcorner = New System.Windows.Forms.Panel() Me.length = New System.Windows.Forms.Label() Me.speed = New System.Windows.Forms.Label() Me.rollupbutton = New System.Windows.Forms.Panel() Me.score = New System.Windows.Forms.Label() Me.pullbottom = New System.Windows.Forms.Timer(Me.components) Me.minimizebutton = New System.Windows.Forms.Panel() Me.pgleft = New System.Windows.Forms.Panel() Me.pgbottomlcorner = New System.Windows.Forms.Panel() Me.pgbottomrcorner = New System.Windows.Forms.Panel() Me.pgright = New System.Windows.Forms.Panel() Me.tmr = New System.Windows.Forms.Timer(Me.components) Me.pgcontents = New System.Windows.Forms.Panel() Me.titlebar = New System.Windows.Forms.Panel() CType(Me.pnlicon, System.ComponentModel.ISupportInitialize).BeginInit() Me.pgleft.SuspendLayout() Me.pgright.SuspendLayout() Me.pgcontents.SuspendLayout() Me.titlebar.SuspendLayout() Me.SuspendLayout() ' 'pnlicon ' Me.pnlicon.BackColor = System.Drawing.Color.Transparent Me.pnlicon.Image = Global.ShiftOS.My.Resources.Resources.iconTextPad Me.pnlicon.Location = New System.Drawing.Point(8, 8) Me.pnlicon.Name = "pnlicon" Me.pnlicon.Size = New System.Drawing.Size(16, 16) Me.pnlicon.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage Me.pnlicon.TabIndex = 24 Me.pnlicon.TabStop = False Me.pnlicon.Visible = False ' 'pgbottom ' Me.pgbottom.BackColor = System.Drawing.Color.Gray Me.pgbottom.Dock = System.Windows.Forms.DockStyle.Bottom Me.pgbottom.Location = New System.Drawing.Point(2, 505) Me.pgbottom.Name = "pgbottom" Me.pgbottom.Size = New System.Drawing.Size(669, 2) Me.pgbottom.TabIndex = 33 ' 'pullside ' Me.pullside.Interval = 1 ' 'pullbs ' Me.pullbs.Interval = 1 ' 'closebutton ' Me.closebutton.BackColor = System.Drawing.Color.Black Me.closebutton.Location = New System.Drawing.Point(302, 3) Me.closebutton.Name = "closebutton" Me.closebutton.Size = New System.Drawing.Size(22, 22) Me.closebutton.TabIndex = 20 ' 'lbtitletext ' Me.lbtitletext.AutoSize = True Me.lbtitletext.BackColor = System.Drawing.Color.Transparent Me.lbtitletext.Font = New System.Drawing.Font("Microsoft Sans Serif", 11.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lbtitletext.Location = New System.Drawing.Point(26, 7) Me.lbtitletext.Name = "lbtitletext" Me.lbtitletext.Size = New System.Drawing.Size(63, 18) Me.lbtitletext.TabIndex = 19 Me.lbtitletext.Text = "Snakey" ' 'pgtoplcorner ' Me.pgtoplcorner.BackColor = System.Drawing.Color.Red Me.pgtoplcorner.Dock = System.Windows.Forms.DockStyle.Left Me.pgtoplcorner.Location = New System.Drawing.Point(0, 0) Me.pgtoplcorner.Name = "pgtoplcorner" Me.pgtoplcorner.Size = New System.Drawing.Size(2, 30) Me.pgtoplcorner.TabIndex = 17 ' 'pgtoprcorner ' Me.pgtoprcorner.BackColor = System.Drawing.Color.Red Me.pgtoprcorner.Dock = System.Windows.Forms.DockStyle.Right Me.pgtoprcorner.Location = New System.Drawing.Point(671, 0) Me.pgtoprcorner.Name = "pgtoprcorner" Me.pgtoprcorner.Size = New System.Drawing.Size(2, 30) Me.pgtoprcorner.TabIndex = 16 ' 'length ' Me.length.AutoSize = True Me.length.BackColor = System.Drawing.Color.Transparent Me.length.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(238, Byte)) Me.length.ForeColor = System.Drawing.Color.White Me.length.Location = New System.Drawing.Point(574, 15) Me.length.Name = "length" Me.length.Size = New System.Drawing.Size(76, 20) Me.length.TabIndex = 13 Me.length.Text = "Length: 5" ' 'speed ' Me.speed.AutoSize = True Me.speed.BackColor = System.Drawing.Color.Transparent Me.speed.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(238, Byte)) Me.speed.ForeColor = System.Drawing.Color.White Me.speed.Location = New System.Drawing.Point(288, 15) Me.speed.Name = "speed" Me.speed.Size = New System.Drawing.Size(73, 20) Me.speed.TabIndex = 12 Me.speed.Text = "Speed: 1" ' 'rollupbutton ' Me.rollupbutton.BackColor = System.Drawing.Color.Black Me.rollupbutton.Location = New System.Drawing.Point(274, 3) Me.rollupbutton.Name = "rollupbutton" Me.rollupbutton.Size = New System.Drawing.Size(22, 22) Me.rollupbutton.TabIndex = 22 ' 'score ' Me.score.AutoSize = True Me.score.BackColor = System.Drawing.Color.Transparent Me.score.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(238, Byte)) Me.score.ForeColor = System.Drawing.Color.White Me.score.Location = New System.Drawing.Point(25, 15) Me.score.Name = "score" Me.score.Size = New System.Drawing.Size(100, 20) Me.score.TabIndex = 11 Me.score.Text = "Total Points: " ' 'pullbottom ' Me.pullbottom.Interval = 1 ' 'minimizebutton ' Me.minimizebutton.BackColor = System.Drawing.Color.Black Me.minimizebutton.Location = New System.Drawing.Point(246, 5) Me.minimizebutton.Name = "minimizebutton" Me.minimizebutton.Size = New System.Drawing.Size(22, 22) Me.minimizebutton.TabIndex = 24 ' 'pgleft ' Me.pgleft.BackColor = System.Drawing.Color.Gray Me.pgleft.Controls.Add(Me.pgbottomlcorner) Me.pgleft.Dock = System.Windows.Forms.DockStyle.Left Me.pgleft.Location = New System.Drawing.Point(0, 30) Me.pgleft.Name = "pgleft" Me.pgleft.Size = New System.Drawing.Size(2, 477) Me.pgleft.TabIndex = 31 ' 'pgbottomlcorner ' Me.pgbottomlcorner.BackColor = System.Drawing.Color.Red Me.pgbottomlcorner.Dock = System.Windows.Forms.DockStyle.Bottom Me.pgbottomlcorner.Location = New System.Drawing.Point(0, 475) Me.pgbottomlcorner.Name = "pgbottomlcorner" Me.pgbottomlcorner.Size = New System.Drawing.Size(2, 2) Me.pgbottomlcorner.TabIndex = 14 ' 'pgbottomrcorner ' Me.pgbottomrcorner.BackColor = System.Drawing.Color.Red Me.pgbottomrcorner.Dock = System.Windows.Forms.DockStyle.Bottom Me.pgbottomrcorner.Location = New System.Drawing.Point(0, 475) Me.pgbottomrcorner.Name = "pgbottomrcorner" Me.pgbottomrcorner.Size = New System.Drawing.Size(2, 2) Me.pgbottomrcorner.TabIndex = 15 ' 'pgright ' Me.pgright.BackColor = System.Drawing.Color.Gray Me.pgright.Controls.Add(Me.pgbottomrcorner) Me.pgright.Dock = System.Windows.Forms.DockStyle.Right Me.pgright.Location = New System.Drawing.Point(671, 30) Me.pgright.Name = "pgright" Me.pgright.Size = New System.Drawing.Size(2, 477) Me.pgright.TabIndex = 32 ' 'tmr ' Me.tmr.Enabled = True Me.tmr.Interval = 50 ' 'pgcontents ' Me.pgcontents.BackColor = System.Drawing.Color.Black Me.pgcontents.Controls.Add(Me.length) Me.pgcontents.Controls.Add(Me.speed) Me.pgcontents.Controls.Add(Me.score) Me.pgcontents.Dock = System.Windows.Forms.DockStyle.Fill Me.pgcontents.Location = New System.Drawing.Point(0, 30) Me.pgcontents.Name = "pgcontents" Me.pgcontents.Size = New System.Drawing.Size(673, 477) Me.pgcontents.TabIndex = 30 ' 'titlebar ' Me.titlebar.BackColor = System.Drawing.Color.Gray Me.titlebar.Controls.Add(Me.minimizebutton) Me.titlebar.Controls.Add(Me.pnlicon) Me.titlebar.Controls.Add(Me.rollupbutton) Me.titlebar.Controls.Add(Me.closebutton) Me.titlebar.Controls.Add(Me.lbtitletext) Me.titlebar.Controls.Add(Me.pgtoplcorner) Me.titlebar.Controls.Add(Me.pgtoprcorner) Me.titlebar.Dock = System.Windows.Forms.DockStyle.Top Me.titlebar.ForeColor = System.Drawing.Color.White Me.titlebar.Location = New System.Drawing.Point(0, 0) Me.titlebar.Name = "titlebar" Me.titlebar.Size = New System.Drawing.Size(673, 30) Me.titlebar.TabIndex = 29 ' 'Snakey ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(673, 507) Me.Controls.Add(Me.pgbottom) Me.Controls.Add(Me.pgleft) Me.Controls.Add(Me.pgright) Me.Controls.Add(Me.pgcontents) Me.Controls.Add(Me.titlebar) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None Me.MaximumSize = New System.Drawing.Size(673, 507) Me.MinimumSize = New System.Drawing.Size(673, 507) Me.Name = "Snakey" Me.Text = "Snakey" CType(Me.pnlicon, System.ComponentModel.ISupportInitialize).EndInit() Me.pgleft.ResumeLayout(False) Me.pgright.ResumeLayout(False) Me.pgcontents.ResumeLayout(False) Me.pgcontents.PerformLayout() Me.titlebar.ResumeLayout(False) Me.titlebar.PerformLayout() Me.ResumeLayout(False) End Sub Friend WithEvents pnlicon As System.Windows.Forms.PictureBox Friend WithEvents pgbottom As System.Windows.Forms.Panel Friend WithEvents pullside As System.Windows.Forms.Timer Friend WithEvents pullbs As System.Windows.Forms.Timer Friend WithEvents closebutton As System.Windows.Forms.Panel Friend WithEvents lbtitletext As System.Windows.Forms.Label Friend WithEvents pgtoplcorner As System.Windows.Forms.Panel Friend WithEvents pgtoprcorner As System.Windows.Forms.Panel Friend WithEvents length As System.Windows.Forms.Label Friend WithEvents speed As System.Windows.Forms.Label Friend WithEvents rollupbutton As System.Windows.Forms.Panel Friend WithEvents score As System.Windows.Forms.Label Friend WithEvents pullbottom As System.Windows.Forms.Timer Friend WithEvents minimizebutton As System.Windows.Forms.Panel Friend WithEvents pgleft As System.Windows.Forms.Panel Friend WithEvents pgbottomlcorner As System.Windows.Forms.Panel Friend WithEvents pgbottomrcorner As System.Windows.Forms.Panel Friend WithEvents pgright As System.Windows.Forms.Panel Friend WithEvents tmr As System.Windows.Forms.Timer Friend WithEvents pgcontents As System.Windows.Forms.Panel Friend WithEvents titlebar As System.Windows.Forms.Panel End Class
TheUltimateHacker/ShiftOS
ShiftOS/Snakey.Designer.vb
Visual Basic
apache-2.0
12,841
'Copyright 2019 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 Microsoft.VisualBasic Imports System Imports System.Collections.Generic Imports System.Text Imports System.IO Imports ESRI.ArcGIS.esriSystem Imports ESRI.ArcGIS.Framework Namespace SelectionSample Public Class ToggleDockWinBtn Inherits ESRI.ArcGIS.Desktop.AddIns.Button Public Sub New() End Sub Protected Overrides Sub OnClick() Dim dockWindow As ESRI.ArcGIS.Framework.IDockableWindow dockWindow = SelectionExtension.GetSelectionCountWindow() If dockWindow Is Nothing Then Return End If dockWindow.Show((Not dockWindow.IsVisible())) End Sub Protected Overrides Sub OnUpdate() Me.Enabled = SelectionExtension.IsExtensionEnabled() End Sub End Class End Namespace
Esri/arcobjects-sdk-community-samples
Net/Framework/SelectionAddInSample/VBNet/ToggleDockWinBtn.vb
Visual Basic
apache-2.0
1,273
' ' 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 Imports System.IO Imports System.Web.Caching Imports System.Xml.Serialization Imports System.Xml.XPath Namespace DotNetNuke.UI.Utilities <Serializable(), XmlRoot("capabilities")> _ Public Class BrowserCaps #Region "Private Members" Private m_objFunctionality As FunctionalityCollection Private m_objFunctionalityDict As Hashtable Private Const CLIENTAPI_CACHE_KEY As String = "ClientAPICaps" #End Region #Region "Public Properties" <XmlElement("functionality")> _ Public Property Functionality() As FunctionalityCollection Get Return m_objFunctionality End Get Set(ByVal Value As FunctionalityCollection) m_objFunctionality = Value End Set End Property Public ReadOnly Property FunctionalityDictionary() As Hashtable Get If m_objFunctionalityDict Is Nothing Then m_objFunctionalityDict = New Hashtable End If Return m_objFunctionalityDict End Get End Property #End Region #Region "Private Shared Methods" Private Shared Function GetBrowser(ByVal objNav As XPathNavigator) As Browser Dim objBrowser As New Browser() objBrowser.Contains = objNav.GetAttribute("contains", "") objBrowser.Name = objNav.GetAttribute("nm", "") Dim strMinVersion As String = objNav.GetAttribute("minversion", "") 'If Not String.IsNullOrEmpty(strMinVersion) Then '.NET 2.0 specific If Len(strMinVersion) > 0 Then objBrowser.MinVersion = Double.Parse(strMinVersion) End If Return objBrowser End Function #End Region #Region "Shared Methods" Public Shared Function GetBrowserCaps() As BrowserCaps Dim objCaps As BrowserCaps = CType(DataCache.GetCache(CLIENTAPI_CACHE_KEY), BrowserCaps) Dim objFunc As FunctionalityInfo = Nothing If (objCaps Is Nothing) Then Dim strPath As String = String.Empty Try strPath = System.Web.HttpContext.Current.Server.MapPath(ClientAPI.ScriptPath & "/ClientAPICaps.config") Catch ex As Exception 'ignore error - worried about people with reverse proxies and such... End Try Dim objDoc As XPathDocument = Nothing Dim objReader As FileStream = Nothing Dim tr As TextReader = Nothing Dim fileExists As Boolean = File.Exists(strPath) Try objCaps = New BrowserCaps() objCaps.Functionality = New FunctionalityCollection() If fileExists Then 'Create a FileStream for the Config file objReader = New FileStream(strPath, FileMode.Open, FileAccess.Read, FileShare.Read) objDoc = New XPathDocument(objReader) Else tr = New StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("ClientAPICaps.config")) objDoc = New XPathDocument(tr) End If If Not objDoc Is Nothing Then For Each objNavFunc As XPathNavigator In objDoc.CreateNavigator.Select("//functionality") objFunc = New FunctionalityInfo() objFunc.Functionality = DirectCast(System.Enum.Parse(GetType(ClientAPI.ClientFunctionality), objNavFunc.GetAttribute("nm", "")), ClientAPI.ClientFunctionality) objFunc.Desc = objNavFunc.GetAttribute("desc", "") objFunc.Supports = New BrowserCollection() For Each objNavSupports As XPathNavigator In objNavFunc.CreateNavigator.Select("supports/browser") objFunc.Supports.Add(GetBrowser(objNavSupports)) Next objFunc.Excludes = New BrowserCollection() For Each objNavExcludes As XPathNavigator In objNavFunc.CreateNavigator.Select("excludes/browser") objFunc.Excludes.Add(GetBrowser(objNavExcludes)) Next objCaps.Functionality.Add(objFunc) Next End If Catch ex As Exception Throw ex Finally If Not objReader Is Nothing Then objReader.Close() End If If Not tr Is Nothing Then tr.Close() End If End Try ' Set back into Cache If fileExists Then DataCache.SetCache(CLIENTAPI_CACHE_KEY, objCaps, New CacheDependency(strPath)) End If End If Return objCaps End Function #End Region End Class End Namespace
RichardHowells/Dnn.Platform
DNN Platform/DotNetNuke.WebUtility/Browser Caps/BrowserCaps.vb
Visual Basic
mit
6,531
' Copyright 2013, Google Inc. All Rights Reserved. ' ' Licensed under the Apache License, Version 2.0 (the "License"); ' you may not use this file except in compliance with the License. ' You may obtain a copy of the License at ' ' http://www.apache.org/licenses/LICENSE-2.0 ' ' Unless required by applicable law or agreed to in writing, software ' distributed under the License is distributed on an "AS IS" BASIS, ' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ' See the License for the specific language governing permissions and ' limitations under the License. ' Author: api.anash@gmail.com (Anash P. Oommen) Imports Google.Api.Ads.AdWords.Lib Imports Google.Api.Ads.AdWords.Util Imports Google.Api.Ads.AdWords.v201306 Imports System Imports System.Collections.Generic Imports System.IO Namespace Google.Api.Ads.AdWords.Examples.VB.v201306 ''' <summary> ''' This code example adds a text ad, and shows how to handle a policy ''' violation. ''' ''' Tags: AdGroupAdService.mutate ''' </summary> Public Class HandlePolicyViolationError 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 HandlePolicyViolationError Console.WriteLine(codeExample.Description) Try Dim adGroupId As Long = Long.Parse("INSERT_ADGROUP_ID_HERE") codeExample.Run(New AdWordsUser, adGroupId) Catch ex As Exception Console.WriteLine("An exception occurred while running this code example. {0}", _ ExampleUtilities.FormatException(ex)) End Try End Sub ''' <summary> ''' Returns a description about the code example. ''' </summary> Public Overrides ReadOnly Property Description() As String Get Return "This code example adds a text ad, and shows how to handle a policy violation." End Get End Property ''' <summary> ''' Runs the code example. ''' </summary> ''' <param name="user">The AdWords user.</param> ''' <param name="adGroupId">Id of the ad group to which ads are added. ''' </param> Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long) ' Get the AdGroupAdService. Dim service As AdGroupAdService = user.GetService( _ AdWordsService.v201306.AdGroupAdService) ' Create the text ad. Dim textAd As New TextAd textAd.headline = "Luxury Cruise to Mars" textAd.description1 = "Visit the Red Planet in style." textAd.description2 = "Low-gravity fun for everyone!!" textAd.displayUrl = "www.example.com" textAd.url = "http://www.example.com" Dim textadGroupAd As New AdGroupAd textadGroupAd.adGroupId = adGroupId textadGroupAd.ad = textAd ' Create the operations. Dim textAdOperation As New AdGroupAdOperation textAdOperation.operator = [Operator].ADD textAdOperation.operand = textadGroupAd Try Dim retVal As AdGroupAdReturnValue = Nothing ' Setup two arrays, one to hold the list of all operations to be ' validated, and another to hold the list of operations that cannot be ' fixed after validation. Dim allOperations As New List(Of AdGroupAdOperation) Dim operationsToBeRemoved As New List(Of AdGroupAdOperation) allOperations.Add(textAdOperation) Try ' Validate the operations. service.RequestHeader.validateOnly = True retVal = service.mutate(allOperations.ToArray) Catch ex As AdWordsApiException Dim innerException As ApiException = TryCast(ex.ApiException, ApiException) If (innerException Is Nothing) Then Throw New Exception("Failed to retrieve ApiError. See inner exception for more " & _ "details.", ex) End If ' Examine each ApiError received from the server. For Each apiError As ApiError In innerException.errors Dim index As Integer = ErrorUtilities.GetOperationIndex(apiError.fieldPath) If (index = -1) Then ' This API error is not associated with an operand, so we cannot ' recover from this error by removing one or more operations. ' Rethrow the exception for manual inspection. Throw End If ' Handle policy violation errors. If TypeOf apiError Is PolicyViolationError Then Dim policyError As PolicyViolationError = apiError If policyError.isExemptable Then ' If the policy violation error is exemptable, add an exemption ' request. Dim exemptionRequests As New List(Of ExemptionRequest) If (Not allOperations.Item(index).exemptionRequests Is Nothing) Then exemptionRequests.AddRange(allOperations.Item(index).exemptionRequests) End If Dim exemptionRequest As New ExemptionRequest exemptionRequest.key = policyError.key exemptionRequests.Add(exemptionRequest) allOperations.Item(index).exemptionRequests = exemptionRequests.ToArray Else ' Policy violation error is not exemptable, remove this ' operation from the list of operations. operationsToBeRemoved.Add(allOperations.Item(index)) End If Else ' This is not a policy violation error, remove this operation ' from the list of operations. operationsToBeRemoved.Add(allOperations.Item(index)) End If Next ' Remove all operations that aren't exemptable. For Each operation As AdGroupAdOperation In operationsToBeRemoved allOperations.Remove(operation) Next End Try If (allOperations.Count > 0) Then ' Perform the operations exemptible of a policy violation. service.RequestHeader.validateOnly = False retVal = service.mutate(allOperations.ToArray) ' Display the results. If ((Not retVal Is Nothing) AndAlso (Not retVal.value Is Nothing) _ AndAlso (retVal.value.Length > 0)) Then For Each newAdGroupAd As AdGroupAd In retVal.value Console.WriteLine("New ad with id = ""{0}"" and displayUrl = ""{1}"" was created.", _ newAdGroupAd.ad.id, newAdGroupAd.ad.displayUrl) Next Else Console.WriteLine("No ads were created.") End If Else Console.WriteLine("There are no ads to create after policy violation checks.") End If Catch ex As Exception Throw New System.ApplicationException("Failed to create Ad(s).", ex) End Try End Sub End Class End Namespace
akilb/googleads-adwords-dotnet-lib
examples/adwords/VB/v201306/ErrorHandling/HandlePolicyViolationError.vb
Visual Basic
apache-2.0
7,041
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEndConstruct <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.GenerateEndConstruct), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.FixIncorrectExitContinue)> Friend Class GenerateEndConstructCodeFixProvider Inherits CodeFixProvider Friend Const BC30025 As String = "BC30025" ' error BC30025: Property missing 'End Property'. Friend Const BC30026 As String = "BC30026" ' error BC30026: 'End Sub' expected. Friend Const BC30027 As String = "BC30027" ' error BC30027: 'End Function' expected. Friend Const BC30081 As String = "BC30081" ' error BC30081: 'If' must end with a matching 'End If' Friend Const BC30082 As String = "BC30082" ' error BC30082: 'While' must end with a matching 'End While'. Friend Const BC30083 As String = "BC30083" ' error BC30083: 'Do' must end with a matching 'Loop'. Friend Const BC30084 As String = "BC30084" ' error BC30084: 'For' must end with a matching 'Next'. Friend Const BC30085 As String = "BC30085" ' error BC30085: 'With' must end with a matching 'End With'. Friend Const BC30185 As String = "BC30185" ' error BC30185: 'Enum' must end with a matching 'End Enum'. Friend Const BC30253 As String = "BC30253" ' error BC30253: 'Interface' must end with a matching 'End Interface'. Friend Const BC30384 As String = "BC30384" ' error BC30384: 'Try' must end with a matching 'End Try'. Friend Const BC30481 As String = "BC30481" ' error BC30481: 'Class' statement must end with a matching 'End Class'. Friend Const BC30624 As String = "BC30624" ' error BC30624: 'Structure' statement must end with a matching 'End Structure'. Friend Const BC30625 As String = "BC30625" ' error BC30625: 'Module' statement must end with a matching 'End Module'. Friend Const BC30626 As String = "BC30626" ' error BC30626: 'Namespace' statement must end with a matching 'End Namespace'. Friend Const BC30631 As String = "BC30631" ' error BC30631: 'Get' statement must end with a matching 'End Get'. Friend Const BC30633 As String = "BC30633" ' error BC30633: 'Set' statement must end with a matching 'End Set'. Friend Const BC30675 As String = "BC30675" ' error BC30675: 'SyncLock' statement must end with a matching 'End SyncLock'. Friend Const BC31114 As String = "BC31114" ' error BC31114: 'Custom Event' must end with a matching 'End Event'. Friend Const BC31115 As String = "BC31115" ' error BC31115: 'AddHandler' declaration must end with a matching 'End AddHandler'. Friend Const BC31116 As String = "BC31116" ' error BC31116: 'RemoveHandler' declaration must end with a matching 'End RemoveHandler'. Friend Const BC31117 As String = "BC31117" ' error BC31117: 'RaiseEvent' declaration must end with a matching 'End RaiseEvent'. Friend Const BC36008 As String = "BC36008" ' error BC36008: 'Using' must end with a matching 'End Using'. <ImportingConstructor> Public Sub New() End Sub Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return ImmutableArray.Create(BC30025, BC30026, BC30027, BC30081, BC30082, BC30083, BC30084, BC30085, BC30185, BC30253, BC30384, BC30481, BC30624, BC30625, BC30626, BC30631, BC30633, BC30675, BC31114, BC31115, BC31116, BC31117, BC36008) End Get End Property Public Overrides Function GetFixAllProvider() As FixAllProvider ' Fix All is not supported by this code fix ' https://github.com/dotnet/roslyn/issues/34473 Return Nothing End Function 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 beginStatement = token.GetAncestors(Of SyntaxNode) _ .FirstOrDefault(Function(c) c.Span.IntersectsWith(context.Span) AndAlso IsCandidate(c)) If beginStatement Is Nothing OrElse beginStatement.Parent Is Nothing Then Return End If Dim endStatement = GetEndStatement(beginStatement.Parent) If endStatement Is Nothing OrElse Not endStatement.IsMissing Then Return End If If endStatement.Parent.Kind = SyntaxKind.PropertyBlock Then context.RegisterCodeFix( New MyCodeAction( VBFeaturesResources.Insert_the_missing_End_Property_statement, Function(c) GeneratePropertyEndConstructAsync(context.Document, DirectCast(endStatement.Parent, PropertyBlockSyntax), c)), context.Diagnostics) Return End If If endStatement.Kind = SyntaxKind.EndGetStatement OrElse endStatement.Kind = SyntaxKind.EndSetStatement Then If endStatement?.Parent?.Parent.Kind = SyntaxKind.PropertyBlock Then context.RegisterCodeFix( New MyCodeAction( VBFeaturesResources.Insert_the_missing_End_Property_statement, Function(c) GeneratePropertyEndConstructAsync(context.Document, DirectCast(endStatement.Parent.Parent, PropertyBlockSyntax), c)), context.Diagnostics) Return End If End If context.RegisterCodeFix( New MyCodeAction( GetDescription(endStatement), Function(c) GenerateEndConstructAsync(context.Document, endStatement, c)), context.Diagnostics) End Function Private Shared Function IsCandidate(node As SyntaxNode) As Boolean If node Is Nothing Then Return False End If Dim begin = GetBeginStatement(node.Parent) If begin Is Nothing Then Return False End If Return begin.Span.Contains(node.Span) End Function Private Shared Function GetBeginStatement(node As SyntaxNode) As SyntaxNode Return node.TypeSwitch( (Function(n As MultiLineIfBlockSyntax) n.IfStatement), (Function(n As UsingBlockSyntax) n.UsingStatement), (Function(n As StructureBlockSyntax) n.BlockStatement), (Function(n As ModuleBlockSyntax) n.BlockStatement), (Function(n As NamespaceBlockSyntax) n.NamespaceStatement), (Function(n As ClassBlockSyntax) n.BlockStatement), (Function(n As InterfaceBlockSyntax) n.BlockStatement), (Function(n As EnumBlockSyntax) n.EnumStatement), (Function(n As WhileBlockSyntax) n.WhileStatement), (Function(n As WithBlockSyntax) n.WithStatement), (Function(n As SyncLockBlockSyntax) n.SyncLockStatement), (Function(n As DoLoopBlockSyntax) n.DoStatement), (Function(n As ForOrForEachBlockSyntax) n.ForOrForEachStatement), (Function(n As TryBlockSyntax) DirectCast(n, SyntaxNode)), (Function(n As MethodBlockBaseSyntax) n.BlockStatement), (Function(n As PropertyBlockSyntax) n.PropertyStatement)) End Function Private Shared Function GetEndStatement(node As SyntaxNode) As SyntaxNode Return node.TypeSwitch( (Function(n As MultiLineIfBlockSyntax) DirectCast(n.EndIfStatement, SyntaxNode)), (Function(n As UsingBlockSyntax) n.EndUsingStatement), (Function(n As StructureBlockSyntax) n.EndBlockStatement), (Function(n As ModuleBlockSyntax) n.EndBlockStatement), (Function(n As NamespaceBlockSyntax) n.EndNamespaceStatement), (Function(n As ClassBlockSyntax) n.EndBlockStatement), (Function(n As InterfaceBlockSyntax) n.EndBlockStatement), (Function(n As EnumBlockSyntax) n.EndEnumStatement), (Function(n As WhileBlockSyntax) n.EndWhileStatement), (Function(n As WithBlockSyntax) n.EndWithStatement), (Function(n As SyncLockBlockSyntax) n.EndSyncLockStatement), (Function(n As DoLoopBlockSyntax) n.LoopStatement), (Function(n As ForOrForEachBlockSyntax) n.NextStatement), (Function(n As TryBlockSyntax) n.EndTryStatement), (Function(n As MethodBlockBaseSyntax) n.EndBlockStatement), (Function(n As PropertyBlockSyntax) n.EndPropertyStatement)) End Function Private Async Function GeneratePropertyEndConstructAsync(document As Document, node As PropertyBlockSyntax, cancellationToken As CancellationToken) As Task(Of Document) ' Make sure the PropertyBlock has End Property Dim updatedProperty = node If node.EndPropertyStatement.IsMissing Then updatedProperty = node.WithEndPropertyStatement(SyntaxFactory.EndPropertyStatement()) End If ' Make sure any existing setters or getters have their End Dim getter = updatedProperty.Accessors.FirstOrDefault(Function(a) a.Kind = SyntaxKind.GetAccessorBlock) If getter IsNot Nothing AndAlso getter.EndBlockStatement.IsMissing Then updatedProperty = updatedProperty.ReplaceNode(getter, getter.WithEndBlockStatement(SyntaxFactory.EndGetStatement())) End If Dim setter = updatedProperty.Accessors.FirstOrDefault(Function(a) a.Kind = SyntaxKind.SetAccessorBlock) If setter IsNot Nothing AndAlso setter.EndBlockStatement.IsMissing Then updatedProperty = updatedProperty.ReplaceNode(setter, setter.WithEndBlockStatement(SyntaxFactory.EndSetStatement())) End If Dim gen = document.GetLanguageService(Of SyntaxGenerator)() If getter Is Nothing AndAlso Not updatedProperty.PropertyStatement.Modifiers.Any(SyntaxKind.WriteOnlyKeyword) Then updatedProperty = DirectCast(gen.WithGetAccessorStatements(updatedProperty, Array.Empty(Of SyntaxNode)()), PropertyBlockSyntax) End If If setter Is Nothing AndAlso Not updatedProperty.PropertyStatement.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) Then updatedProperty = DirectCast(gen.WithSetAccessorStatements(updatedProperty, Array.Empty(Of SyntaxNode)()), PropertyBlockSyntax) End If Dim updatedDocument = Await document.ReplaceNodeAsync(node, updatedProperty.WithAdditionalAnnotations(Formatter.Annotation), cancellationToken).ConfigureAwait(False) Return updatedDocument End Function Public Function GetDescription(node As SyntaxNode) As String Dim endBlockSyntax = TryCast(node, EndBlockStatementSyntax) If endBlockSyntax IsNot Nothing Then Return String.Format(VBFeaturesResources.Insert_the_missing_0, "End " + SyntaxFacts.GetText(endBlockSyntax.BlockKeyword.Kind)) End If Dim loopStatement = TryCast(node, LoopStatementSyntax) If loopStatement IsNot Nothing Then Return String.Format(VBFeaturesResources.Insert_the_missing_0, SyntaxFacts.GetText(SyntaxKind.LoopKeyword)) End If Return String.Format(VBFeaturesResources.Insert_the_missing_0, SyntaxFacts.GetText(SyntaxKind.NextKeyword)) End Function Private Async Function GenerateEndConstructAsync(document As Document, endStatement As SyntaxNode, cancellationToken As CancellationToken) As Task(Of Document) If endStatement.Kind = SyntaxKind.EndEnumStatement Then ' InvInsideEndsEnum Dim nextNode = endStatement.Parent.GetLastToken().GetNextToken().Parent If nextNode IsNot Nothing Then Dim diagnostics = nextNode.GetDiagnostics() If diagnostics.SingleOrDefault(Function(d) d.Id = "BC30619") IsNot Nothing Then Dim updatedParent = DirectCast(endStatement.Parent, EnumBlockSyntax).WithEndEnumStatement(SyntaxFactory.EndEnumStatement()) Dim updatedDocument = Await document.ReplaceNodeAsync(endStatement.Parent, updatedParent.WithAdditionalAnnotations(Formatter.Annotation), cancellationToken).ConfigureAwait(False) Return updatedDocument End If End If End If Return Await InsertEndConstructAsync(document, endStatement, cancellationToken).ConfigureAwait(False) End Function Private Async Function InsertEndConstructAsync(document As Document, endStatement As SyntaxNode, cancellationToken As CancellationToken) As Task(Of Document) Dim text = Await document.GetTextAsync(cancellationToken).ConfigureAwait(False) Dim stringToAppend As String = Nothing Dim endBlock = TryCast(endStatement, EndBlockStatementSyntax) If endBlock IsNot Nothing Then stringToAppend = vbCrLf + "End " + SyntaxFacts.GetText(endBlock.BlockKeyword.Kind) + vbCrLf End If Dim nextStatement = TryCast(endStatement, NextStatementSyntax) If nextStatement IsNot Nothing Then stringToAppend = vbCrLf & SyntaxFacts.GetText(nextStatement.NextKeyword.Kind) & vbCrLf End If Dim loopStatement = TryCast(endStatement, LoopStatementSyntax) If loopStatement IsNot Nothing Then stringToAppend = vbCrLf & SyntaxFacts.GetText(loopStatement.LoopKeyword.Kind) & vbCrLf End If Dim insertionPoint = GetBeginStatement(endStatement.Parent).FullSpan.End Dim updatedText = text.WithChanges(New TextChange(TextSpan.FromBounds(insertionPoint, insertionPoint), stringToAppend)) Dim updatedDocument = document.WithText(updatedText) Dim tree = Await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) updatedDocument = Await updatedDocument.ReplaceNodeAsync(tree, tree.WithAdditionalAnnotations(Formatter.Annotation), cancellationToken).ConfigureAwait(False) Return updatedDocument End Function Private Class MyCodeAction Inherits CodeAction.DocumentChangeAction Public Sub New(title As String, createChangedDocument As Func(Of CancellationToken, Task(Of Document))) MyBase.New(title, createChangedDocument) End Sub End Class End Class End Namespace
aelij/roslyn
src/Features/VisualBasic/Portable/CodeFixes/GenerateEndConstruct/GenerateEndConstructCodeFixProvider.vb
Visual Basic
apache-2.0
15,667
Imports bv.common.Core Imports bv.common.Objects Imports System.Data Imports System.Data.Common Imports System.Collections.Generic Imports System.Data.SqlClient Namespace Core Public Class AuditManager Private Shared m_AsyncConnection As IDbConnection Private Shared m_AsyncConnectionManager As ConnectionManager Private Shared m_DontUseFiltation As Boolean = False Public Shared Property DontUseFiltation() As Boolean Get Return m_DontUseFiltation End Get Set(ByVal value As Boolean) m_DontUseFiltation = True End Set End Property Public Shared ReadOnly Property Connection() As IDbConnection Get If m_AsyncConnection Is Nothing Then If (Not ConnectionManager.DefaultInstance Is Nothing) Then m_AsyncConnectionManager = ConnectionManager.CreateNew(ConnectionManager.DefaultInstance.SQLServer, _ ConnectionManager.DefaultInstance.SQLDatabase, _ ConnectionManager.DefaultInstance.SQLUser, _ ConnectionManager.DefaultInstance.SQLPassword, ConnectionManager.DefaultInstance.SQLConnectionString) m_AsyncConnectionManager.UseAsyncConnection = True Else m_AsyncConnectionManager = ConnectionManager.CreateNew(True) End If m_AsyncConnection = m_AsyncConnectionManager.Connection ' m_AsyncConnectionManager.Owner = "Audit manager" End If Return m_AsyncConnection End Get End Property Public Shared Function CreateAuditEvent(ByVal auditData As AuditObject, ByVal transaction As IDbTransaction, Optional ByVal throwExceptionOnError As Boolean = False) As Object Dim cmd As IDbCommand = BaseDbService.CreateSPCommand("dbo.spAudit_CreateNewEvent", transaction.Connection, transaction) Dim params As New Dictionary(Of String, Object) params.Add("@idfsDataAuditEventType", CLng(auditData.EventType)) params.Add("@idfsDataAuditObjectType", auditData.Name) params.Add("@strMainObjectTable", auditData.AuditTable) params.Add("@strReason", auditData.Reason) If Not Utils.IsEmpty(auditData.Key) Then params.Add("@idfsMainObject", auditData.Key) End If StoredProcParamsCache.CreateParameters(cmd, params) BaseDbService.ExecCommand(cmd, transaction.Connection, transaction, throwExceptionOnError) auditData.LastAuditEventID = BaseDbService.GetParamValue(cmd, "@idfDataAuditEvent") Return auditData.LastAuditEventID End Function Public Shared Sub ClearAuditContext(ByVal transaction As IDbTransaction, ByVal Connection As IDbConnection) Dim cmd As IDbCommand If transaction Is Nothing OrElse transaction.Connection Is Nothing Then cmd = BaseDbService.CreateSPCommand("dbo.spClearContextData", Connection) Else cmd = BaseDbService.CreateSPCommand("dbo.spClearContextData", transaction.Connection, transaction) End If If cmd.Connection Is Nothing Then Return Dim params As New Dictionary(Of String, Object) params.Add("@ClearEventID", False) params.Add("@ClearDataAuditEvent", True) StoredProcParamsCache.CreateParameters(cmd, params) BaseDbService.ExecCommand(cmd, cmd.Connection, transaction, True) End Sub 'Private Class AsyncAuditData ' Public Sub New(ByVal cmd As SqlCommand, ByVal auditData As AuditObject) ' Command = cmd ' AuditObject = auditData ' End Sub ' Public Command As SqlCommand ' Public AuditObject As AuditObject 'End Class Public Shared Sub StartReplicationAsync(ByVal auditData As AuditObject) If auditData Is Nothing Then Return End If If Utils.IsEmpty(auditData.LastAuditEventID) Then Return End If If Not auditData.EventLog Is Nothing Then Try auditData.EventLog.CheckNotificationService() auditData.EventLog.StartReplication() Catch ex As Exception Dbg.Debug("error during replication after async filtration: {0}", ex.Message) Dbg.Debug("-> table{0}", auditData.Name) Dbg.Debug("->stack trace: {0}", ex.StackTrace.ToString) Dbg.Trace() End Try End If End Sub 'Private Shared Sub HandleCallback(ByVal result As IAsyncResult) ' Dim data As AsyncAuditData = CType(result.AsyncState, AsyncAuditData) ' Try ' SyncLock m_AsyncConnection ' Dim recordAffected As Integer = data.Command.EndExecuteNonQuery(result) ' Dbg.Debug("Async filtration is finished for object {0} {1}", data.AuditObject.Name, Utils.Str(data.AuditObject.Key)) ' If data.Command.Connection.State = ConnectionState.Open Then ' AndAlso s_ExecutingCount > 0 ' data.Command.Connection.Close() ' End If ' End SyncLock ' Catch ex As Exception ' Dbg.Debug("error during async filtration: {0}", ex.Message) ' Dbg.Debug("-> table{0}", data.AuditObject.Name) ' Dbg.Debug("->stack trace: {0}", ex.StackTrace.ToString) ' Dbg.Trace() ' Finally ' If Not data.AuditObject.EventLog Is Nothing Then ' Try ' data.AuditObject.EventLog.CheckNotificationService() ' data.AuditObject.EventLog.StartReplication() ' Catch ex As Exception ' Dbg.Debug("error during replication after async filtration: {0}", ex.Message) ' Dbg.Debug("-> table{0}", data.AuditObject.Name) ' Dbg.Debug("->stack trace: {0}", ex.StackTrace.ToString) ' Dbg.Trace() ' End Try ' End If ' End Try 'End Sub End Class End Namespace
EIDSS/EIDSS-Legacy
EIDSS v6/vb/Shared/bv_dbcommon/DbService/AuditManager.vb
Visual Basic
bsd-2-clause
6,889
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.Navigation Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.GeneratedCodeRecognition Imports Microsoft.CodeAnalysis.Navigation Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities.GoToHelpers Friend Module GoToTestHelpers Public ReadOnly Catalog As ComposableCatalog = TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic.WithParts( GetType(MockDocumentNavigationServiceFactory), GetType(DefaultSymbolNavigationServiceFactory), GetType(GeneratedCodeRecognitionServiceFactory)) Public ReadOnly ExportProvider As ExportProvider = MinimalTestExportProvider.CreateExportProvider(Catalog) Public Async Function TestAsync(workspaceDefinition As XElement, expectedResult As Boolean, executeOnDocument As Func(Of Document, Integer, IEnumerable(Of Lazy(Of INavigableItemsPresenter)), Boolean)) As System.Threading.Tasks.Task Using workspace = Await TestWorkspaceFactory.CreateWorkspaceAsync(workspaceDefinition, exportProvider:=ExportProvider) Dim solution = workspace.CurrentSolution Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue) Dim cursorPosition = cursorDocument.CursorPosition.Value Dim items As IList(Of INavigableItem) = Nothing ' Set up mocks. The IDocumentNavigationService should be called if there is one, ' location and the INavigableItemsPresenter should be called if there are ' multiple locations. ' prepare a notification listener Dim textView = cursorDocument.GetTextView() Dim textBuffer = textView.TextBuffer textView.Caret.MoveTo(New SnapshotPoint(textBuffer.CurrentSnapshot, cursorPosition)) Dim cursorBuffer = cursorDocument.TextBuffer Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id) Dim mockDocumentNavigationService = DirectCast(workspace.Services.GetService(Of IDocumentNavigationService)(), MockDocumentNavigationService) Dim presenter = New MockNavigableItemsPresenter(Sub(i) items = i) Dim presenters = {New Lazy(Of INavigableItemsPresenter)(Function() presenter)} Dim actualResult = executeOnDocument(document, cursorPosition, presenters) Assert.Equal(expectedResult, actualResult) If expectedResult Then If mockDocumentNavigationService._triedNavigationToSpan Then Dim definitionDocument = workspace.GetTestDocument(mockDocumentNavigationService._documentId) Assert.Single(definitionDocument.SelectedSpans) Assert.Equal(definitionDocument.SelectedSpans.Single(), mockDocumentNavigationService._span) ' The INavigableItemsPresenter should not have been called Assert.Null(items) Else Assert.False(mockDocumentNavigationService._triedNavigationToPosition) Assert.False(mockDocumentNavigationService._triedNavigationToLineAndOffset) Assert.NotEmpty(items) For Each location In items Dim definitionDocument = workspace.GetTestDocument(location.Document.Id) Assert.True(definitionDocument.SelectedSpans.Contains(location.SourceSpan)) Next ' The IDocumentNavigationService should not have been called Assert.Null(mockDocumentNavigationService._documentId) End If Else Assert.Null(mockDocumentNavigationService._documentId) Assert.True(items Is Nothing OrElse items.Count = 0) End If End Using End Function End Module End Namespace
managed-commons/roslyn
src/EditorFeatures/Test2/Utilities/GoToHelpers/GoToTestHelpers.vb
Visual Basic
apache-2.0
4,417
' 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.Reflection Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Shared.Options Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.UnitTests.Diagnostics Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests Public Class DiagnosticServiceTests Private _assemblyLoader As IAnalyzerAssemblyLoader = New InMemoryAssemblyLoader() Public Function CreateAnalyzerFileReference(ByVal fullPath As String) As AnalyzerFileReference Return New AnalyzerFileReference(fullPath, _assemblyLoader) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestProjectAnalyzers() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim solution = workspace.CurrentSolution Dim project = solution.Projects(0) Dim workspaceDiagnosticAnalyzer = New WorkspaceDiagnosticAnalyzer() Dim projectDiagnosticAnalyzer1 = New ProjectDiagnosticAnalyzer(1) Dim projectDiagnosticAnalyzer2 = New ProjectDiagnosticAnalyzer2(2) Dim diagnosticService = New TestDiagnosticAnalyzerService(LanguageNames.CSharp, workspaceDiagnosticAnalyzer) ' Verify available diagnostic descriptors/analyzers Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim descriptors = descriptorsMap.First().Value Assert.Equal(1, descriptors.Count()) Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, descriptors(0).Id) Dim document = project.Documents.Single() Dim analyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan).WaitAndGetResult(CancellationToken.None) Assert.Equal(1, diagnostics.Count()) ' Add a project analyzer reference Dim projectAnalyzers1 = ImmutableArray.Create(Of DiagnosticAnalyzer)(projectDiagnosticAnalyzer1) Dim projectAnalyzerReference1 = New AnalyzerImageReference(projectAnalyzers1, display:=NameOf(projectAnalyzers1)) Dim projectAnalyzerReferences1 = ImmutableArray.Create(Of AnalyzerReference)(projectAnalyzerReference1) project = project.WithAnalyzerReferences(projectAnalyzerReferences1) ' Verify available diagnostic descriptors/analyzers descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(2, descriptorsMap.Count) descriptors = descriptorsMap.Values.SelectMany(Function(d) d).OrderBy(Function(d) d.Id).ToImmutableArray() Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, descriptors(0).Id) Assert.Equal(projectDiagnosticAnalyzer1.DiagDescriptor.Id, descriptors(1).Id) Dim project1 = project.WithAssemblyName("Mumble") Assert.NotSame(project, project1) ' Add another project analyzer Dim projectAnalyzers2 = ImmutableArray.Create(Of DiagnosticAnalyzer)(projectDiagnosticAnalyzer2) Dim projectAnalyzerReference2 = New AnalyzerImageReference(projectAnalyzers2, display:=NameOf(projectAnalyzers2)) project = project.AddAnalyzerReference(projectAnalyzerReference2) ' Verify available diagnostic descriptors/analyzers descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(3, descriptorsMap.Count) descriptors = descriptorsMap.Values.SelectMany(Function(d) d).OrderBy(Function(d) d.Id).ToImmutableArray() Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, descriptors(0).Id) Assert.Equal(projectDiagnosticAnalyzer1.DiagDescriptor.Id, descriptors(1).Id) Assert.Equal(projectDiagnosticAnalyzer2.DiagDescriptor.Id, descriptors(2).Id) document = project.Documents.Single() diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan ).WaitAndGetResult(CancellationToken.None) Assert.Equal(3, diagnostics.Count()) ' Remove a project analyzer project = project.RemoveAnalyzerReference(projectAnalyzerReference1) ' Verify available diagnostic descriptors/analyzers descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(2, descriptorsMap.Count) descriptors = descriptorsMap.Values.SelectMany(Function(d) d).OrderBy(Function(d) d.Id).ToImmutableArray() Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, descriptors(0).Id) Assert.Equal(projectDiagnosticAnalyzer2.DiagDescriptor.Id, descriptors(1).Id) document = project.Documents.Single() diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan ).WaitAndGetResult(CancellationToken.None) Assert.Equal(2, diagnostics.Count()) ' Verify available diagnostic descriptors/analyzers if not project specific descriptorsMap = diagnosticService.GetDiagnosticDescriptors(projectOpt:=Nothing) Assert.Equal(1, descriptorsMap.Count) descriptors = descriptorsMap.First().Value Assert.Equal(1, descriptors.Count) Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, descriptors(0).Id) ' Add an existing workspace analyzer to the project, ensure no duplicate diagnostics. Dim duplicateProjectAnalyzersReference = diagnosticService.HostAnalyzerReferences.FirstOrDefault() project = project.WithAnalyzerReferences({duplicateProjectAnalyzersReference}) ' Verify duplicate descriptors or diagnostics. descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) descriptors = descriptorsMap.Values.SelectMany(Function(d) d).OrderBy(Function(d) d.Id).ToImmutableArray() Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, descriptors(0).Id) document = project.Documents.Single() diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan ).WaitAndGetResult(CancellationToken.None) Assert.Equal(1, diagnostics.Count()) End Using End Sub <Fact> Public Sub TestEmptyProjectAnalyzers() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects(0) Dim workspaceDiagnosticAnalyzer = New WorkspaceDiagnosticAnalyzer() Dim diagnosticService = New TestDiagnosticAnalyzerService(LanguageNames.CSharp, workspaceDiagnosticAnalyzer) ' Add project analyzer reference with no analyzers. Dim projectAnalyzersEmpty = ImmutableArray(Of DiagnosticAnalyzer).Empty Dim projectAnalyzerReference1 = New AnalyzerImageReference(projectAnalyzersEmpty) Dim projectAnalyzerReferences1 = ImmutableArray.Create(Of AnalyzerReference)(projectAnalyzerReference1) project = project.WithAnalyzerReferences(projectAnalyzerReferences1) ' Query descriptors twice: second query was hitting an assert in DiagnosticAnalyzersAndStates. Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim descriptors = descriptorsMap.First().Value Assert.Equal(1, descriptors.Count()) Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, descriptors(0).Id) End Using End Sub <Fact> Public Sub TestNameCollisionOnDisplayNames() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects(0) Dim referenceName = "Test" Dim hostAnalyzerReference = New AnalyzerImageReference( ImmutableArray.Create(Of DiagnosticAnalyzer)(New ProjectDiagnosticAnalyzer(0)), display:=referenceName) Dim projectAnalyzerReference = New AnalyzerImageReference( ImmutableArray.Create(Of DiagnosticAnalyzer)(New ProjectDiagnosticAnalyzer(1)), display:=referenceName) Dim diagnosticService = New TestDiagnosticAnalyzerService( ImmutableArray.Create(Of AnalyzerReference)(hostAnalyzerReference)) project = project.WithAnalyzerReferences(ImmutableArray.Create(Of AnalyzerReference)(projectAnalyzerReference)) Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) ' two references in the map Assert.Equal(1, descriptorsMap.Count) Dim names = New HashSet(Of String) names.UnionWith(descriptorsMap.Keys) Assert.Equal(1, names.Where(Function(n) n = referenceName).Count()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestRulesetBasedDiagnosticFiltering() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects(0) Dim workspaceDiagnosticAnalyzer = New WorkspaceDiagnosticAnalyzer() Dim diagnosticService = New TestDiagnosticAnalyzerService(LanguageNames.CSharp, workspaceDiagnosticAnalyzer) ' Verify available diagnostic descriptors/analyzers Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim descriptors = descriptorsMap.First().Value Assert.Equal(1, descriptors.Count()) Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, descriptors(0).Id) Dim document = project.Documents.Single() Dim span = document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan Dim analyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, span).WaitAndGetResult(CancellationToken.None).ToImmutableArray() Assert.Equal(1, diagnostics.Length) Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, diagnostics(0).Id) Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.DefaultSeverity, diagnostics(0).Severity) Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.DefaultSeverity, diagnostics(0).DefaultSeverity) Dim suppressDiagOptions = New Dictionary(Of String, ReportDiagnostic) suppressDiagOptions.Add(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, ReportDiagnostic.Suppress) Dim newCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(suppressDiagOptions) project = project.WithCompilationOptions(newCompilationOptions) document = project.Documents.Single() diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, span).WaitAndGetResult(CancellationToken.None).ToImmutableArray() Assert.Equal(0, diagnostics.Length) Dim changeSeverityDiagOptions = New Dictionary(Of String, ReportDiagnostic) changeSeverityDiagOptions.Add(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, ReportDiagnostic.Error) newCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(changeSeverityDiagOptions) project = project.WithCompilationOptions(newCompilationOptions) document = project.Documents.Single() diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, span).WaitAndGetResult(CancellationToken.None).ToImmutableArray() Assert.Equal(1, diagnostics.Length) Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, diagnostics(0).Id) Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.DefaultSeverity, diagnostics(0).DefaultSeverity) Assert.Equal(DiagnosticSeverity.Error, diagnostics(0).Severity) End Using End Sub <Fact> Public Sub TestProjectAnalyzerMessages() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Alpha.cs"> class Alpha { } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Bravo.vb"> Class Bravo : End Class </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim projectDiagnosticAnalyzer1 = New ProjectDiagnosticAnalyzer(1) Dim projectDiagnosticAnalyzer2 = New ProjectDiagnosticAnalyzer2(2) Dim solution = workspace.CurrentSolution Dim alpha = solution.Projects.Single(Function(p) p.Language = LanguageNames.CSharp) alpha = alpha.WithAnalyzerReferences(SpecializedCollections.SingletonCollection(New AnalyzerImageReference(ImmutableArray(Of DiagnosticAnalyzer).Empty.Add(projectDiagnosticAnalyzer1)))) solution = alpha.Solution Dim bravo = solution.Projects.Single(Function(p) p.Language = LanguageNames.VisualBasic) bravo = bravo.WithAnalyzerReferences(SpecializedCollections.SingletonCollection(New AnalyzerImageReference(ImmutableArray(Of DiagnosticAnalyzer).Empty.Add(projectDiagnosticAnalyzer2)))) solution = bravo.Solution Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim analyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim workspaceDescriptors = diagnosticService.GetDiagnosticDescriptors(projectOpt:=Nothing) Assert.Equal(0, workspaceDescriptors.Count) Dim alphaDescriptors = diagnosticService.GetDiagnosticDescriptors(alpha) Assert.Equal("XX0001", alphaDescriptors.Single().Value.Single().Id) Dim alphaDiagnostics = diagnosticService.GetDiagnosticsForSpanAsync(alpha.Documents.Single(), New TextSpan(0, alpha.Documents.Single().GetTextAsync().Result.Length)).Result Assert.Equal("XX0001", alphaDiagnostics.Single().Id) Dim bravoDescriptors = diagnosticService.GetDiagnosticDescriptors(bravo) Assert.Equal("XX0002", bravoDescriptors.Single().Value.Single().Id) Dim bravoDiagnostics = diagnosticService.GetDiagnosticsForSpanAsync(bravo.Documents.Single(), New TextSpan(0, bravo.Documents.Single().GetTextAsync().Result.Length)).Result Assert.Equal("XX0002", bravoDiagnostics.Single().Id) End Using End Sub <Fact> Public Sub TestGlobalAnalyzerGroup() Dim test = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Bravo.vb"> Class Bravo : End Class </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim analyzer1 = New ProjectDiagnosticAnalyzer(1) Dim analyzer2 = New ProjectDiagnosticAnalyzer2(2) Dim analyzersMap = New Dictionary(Of String, ImmutableArray(Of DiagnosticAnalyzer)) analyzersMap.Add(LanguageNames.CSharp, ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer1)) analyzersMap.Add(LanguageNames.VisualBasic, ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer2)) Dim diagnosticService2 = New TestDiagnosticAnalyzerService(analyzersMap.ToImmutableDictionary()) Dim descriptors = diagnosticService2.GetDiagnosticDescriptors(projectOpt:=Nothing) Assert.Equal(1, descriptors.Count) Assert.Equal(2, descriptors.Single().Value.Count) End Using End Sub <Fact, WorkItem(923324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923324"), Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestDuplicateFileAnalyzers() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() Dim analyzerReference1 = CreateAnalyzerFileReference("x:\temp.dll") Dim analyzerReference2 = CreateAnalyzerFileReference("x:\temp.dll") project = project.AddAnalyzerReference(analyzerReference1) #If DEBUG Then Debug.Assert(project.AnalyzerReferences.Contains(analyzerReference2)) #End If End Using End Sub <WpfFact, WorkItem(1091877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091877"), Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestDuplicateFileAnalyzers2() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) ' Add duplicate analyzer references: one as VSIX analyzer reference and other one as project analyzer reference. Dim project = workspace.CurrentSolution.Projects.Single() Dim analyzerReference1 = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location) project = project.AddAnalyzerReference(analyzerReference1) Dim analyzerReference2 = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location) Dim diagnosticService = New TestDiagnosticAnalyzerService(ImmutableArray.Create(Of AnalyzerReference)(analyzerReference2)) Dim analyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) ' Verify no duplicate diagnostics. Dim document = project.Documents.Single() Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync( document, document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan) _ .WaitAndGetResult(CancellationToken.None) _ .Select(Function(d) d.Id = WorkspaceDiagnosticAnalyzer.Descriptor.Id) Assert.Equal(1, diagnostics.Count) End Using End Sub <Fact, WorkItem(923324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923324"), Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestDuplicateImageAnalyzers() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() Dim analyzer = New ProjectDiagnosticAnalyzer(0) Dim analyzerReference1 = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) Dim analyzerReference2 = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference1) project = project.AddAnalyzerReference(analyzerReference2) #If DEBUG Then Debug.Assert(project.AnalyzerReferences.Contains(analyzerReference1)) #End If End Using End Sub <WpfFact, WorkItem(937956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/937956"), Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestDiagnosticAnalyzerExceptionHandledGracefully() Dim test = <Workspace> <Project Language="C#" CommonReferences="true" Features="IOperation"> <Document FilePath="Test.cs"> class Foo { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() Dim analyzer = New ThrowsExceptionAnalyzer Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim descriptors = descriptorsMap.First().Value Assert.Equal(0, descriptors.Count()) Dim document = project.Documents.Single() Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan ).WaitAndGetResult(CancellationToken.None) Assert.Equal(0, diagnostics.Count()) End Using End Sub <WpfFact, WorkItem(937915, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/937915"), Trait(Traits.Feature, Traits.Features.Diagnostics)> <WorkItem(759, "https://github.com/dotnet/roslyn/issues/759")> Public Sub TestDiagnosticAnalyzerExceptionHandledGracefully2() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { void M() {} } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() Dim analyzer = New CodeBlockStartedAnalyzer(Of Microsoft.CodeAnalysis.CSharp.SyntaxKind) Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim exceptionDiagnosticsSource = New TestHostDiagnosticUpdateSource(workspace) Dim diagnosticService = New TestDiagnosticAnalyzerService(hostDiagnosticUpdateSource:=exceptionDiagnosticsSource) Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim document = project.Documents.Single() Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan ).WaitAndGetResult(CancellationToken.None) Assert.Equal(0, diagnostics.Count()) diagnostics = exceptionDiagnosticsSource.TestOnly_GetReportedDiagnostics(analyzer) Assert.Equal(1, diagnostics.Count()) Dim diagnostic = diagnostics.First() Assert.True(diagnostic.Id = "AD0001") Assert.Contains("CodeBlockStartedAnalyzer", diagnostic.Message, StringComparison.Ordinal) End Using End Sub <Fact, WorkItem(1167439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1167439"), Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestDiagnosticAnalyzerExceptionHandledNoCrash() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"/> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() Dim analyzer = New CodeBlockStartedAnalyzer(Of Microsoft.CodeAnalysis.CSharp.SyntaxKind) Dim expected = Diagnostic.Create("test", "test", "test", DiagnosticSeverity.Error, DiagnosticSeverity.Error, True, 0) Dim exceptionDiagnosticsSource = New TestHostDiagnosticUpdateSource(workspace) ' check reporting diagnostic to a project that doesn't exist exceptionDiagnosticsSource.ReportAnalyzerDiagnostic(analyzer, expected, workspace, New ProjectId(Guid.NewGuid(), "dummy")) Dim diagnostics = exceptionDiagnosticsSource.TestOnly_GetReportedDiagnostics(analyzer) Assert.Equal(0, diagnostics.Count()) ' check workspace diagnostic reporting exceptionDiagnosticsSource.ReportAnalyzerDiagnostic(analyzer, expected, workspace, Nothing) diagnostics = exceptionDiagnosticsSource.TestOnly_GetReportedDiagnostics(analyzer) Assert.Equal(1, diagnostics.Count()) Assert.Equal(expected.Id, diagnostics.First().Id) End Using End Sub <WpfFact, WorkItem(937939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/937939"), Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestOperationAnalyzers() Dim test = <Workspace> <Project Language="C#" CommonReferences="true" Features="IOperation"> <Document FilePath="Test.cs"> class Foo { void M() { int x = 0; } } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) For Each actionKind As OperationAnalyzer.ActionKind In [Enum].GetValues(GetType(OperationAnalyzer.ActionKind)) Dim project = workspace.CurrentSolution.Projects.Single Dim analyzer = New OperationAnalyzer(actionKind) Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim document = project.Documents.Single() Dim diagnostics = diagnosticService.GetDiagnosticsAsync(project.Solution, project.Id).WaitAndGetResult(CancellationToken.None) Assert.Equal(1, diagnostics.Count()) Dim diagnostic = diagnostics.First() Assert.Equal(OperationAnalyzer.Descriptor.Id, diagnostic.Id) Dim expectedMessage = String.Format(OperationAnalyzer.Descriptor.MessageFormat.ToString(), actionKind) Assert.Equal(diagnostic.Message, expectedMessage) Next actionKind End Using End Sub <WpfFact, WorkItem(937939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/937939"), Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestStatelessCodeBlockEndedAnalyzer() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { void M() {} } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() Dim analyzer = New CodeBlockEndedAnalyzer() Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim document = project.Documents.Single() Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan ).WaitAndGetResult(CancellationToken.None) Assert.Equal(1, diagnostics.Count()) Dim diagnostic = diagnostics.First() Assert.Equal(CodeBlockEndedAnalyzer.Descriptor.Id, diagnostic.Id) End Using End Sub <WpfFact, WorkItem(937939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/937939"), Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestSameCodeBlockStartedAndEndedAnalyzer() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { void M() {} } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() Dim analyzer = New CodeBlockStartedAndEndedAnalyzer(Of Microsoft.CodeAnalysis.CSharp.SyntaxKind) Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() ' Ensure no duplicate diagnostics. Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim document = project.Documents.Single() Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan ).WaitAndGetResult(CancellationToken.None) Assert.Equal(1, diagnostics.Count()) Dim diagnostic = diagnostics.First() Assert.Equal(CodeBlockEndedAnalyzer.Descriptor.Id, diagnostic.Id) End Using End Sub <WpfFact, WorkItem(1005568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1005568"), Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestCodeBlockAnalyzerForLambda() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System; class AnonymousFunctions { public void SimpleLambdaFunctionWithoutBraces() { bool x = false; Action<string> lambda = s => x = true; lambda(""); Console.WriteLine(x); } public void SimpleLambdaFunctionWithBraces() { bool x = false; Action<string> lambda = s => { x = true; }; lambda(""); Console.WriteLine(x); } public void ParenthesizedLambdaFunctionWithoutBraces() { bool x = false; Action<string> lambda = (s) => x = true; lambda(""); Console.WriteLine(x); } public void ParenthesizedLambdaFunctionWithBraces() { bool x = false; Action<string> lambda = (s) => { x = true; }; lambda(""); Console.WriteLine(x); } }]]> </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() Dim analyzer = New CodeBlockStartedAndEndedAnalyzer(Of Microsoft.CodeAnalysis.CSharp.SyntaxKind) Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() ' Ensure no duplicate diagnostics. Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim document = project.Documents.Single() Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan ).WaitAndGetResult(CancellationToken.None) Assert.Equal(4, diagnostics.Count()) Dim diagnostic = diagnostics.First() Assert.Equal(CodeBlockEndedAnalyzer.Descriptor.Id, diagnostic.Id) End Using End Sub <WpfFact, WorkItem(937952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/937952"), WorkItem(944832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/944832"), WorkItem(1112907, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112907"), Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestCompilationEndedAnalyzer() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { void M() {} } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() ' turn off heuristic Dim options = workspace.Services.GetService(Of IOptionService)() options.SetOptions(options.GetOptions.WithChangedOption(InternalDiagnosticsOptions.UseCompilationEndCodeFixHeuristic, False)) Dim analyzer = New CompilationEndedAnalyzer Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) ' Ask for document diagnostics multiple times, and verify compilation diagnostics are reported. Dim document = project.Documents.Single() Dim fullSpan = document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, fullSpan).WaitAndGetResult(CancellationToken.None) Assert.Equal(1, diagnostics.Count()) Assert.Equal(document.Id, diagnostics.First().DocumentId) diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, fullSpan).WaitAndGetResult(CancellationToken.None) Assert.Equal(1, diagnostics.Count()) Assert.Equal(document.Id, diagnostics.First().DocumentId) diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, fullSpan).WaitAndGetResult(CancellationToken.None) Assert.Equal(1, diagnostics.Count()) Assert.Equal(document.Id, diagnostics.First().DocumentId) ' REVIEW: GetProjectDiagnosticsForIdsAsync is for project diagnostics with no location. not sure why in v1, this API returns ' diagnostic with location? ' Verify compilation diagnostics are reported with correct location info when asked for project diagnostics. Dim projectDiagnostics = diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id).WaitAndGetResult(CancellationToken.None) Assert.Equal(2, projectDiagnostics.Count()) Dim noLocationDiagnostic = projectDiagnostics.First(Function(d) Not d.HasTextSpan) Assert.Equal(CompilationEndedAnalyzer.Descriptor.Id, noLocationDiagnostic.Id) Assert.Equal(False, noLocationDiagnostic.HasTextSpan) Dim withDocumentLocationDiagnostic = projectDiagnostics.First(Function(d) d.HasTextSpan) Assert.Equal(CompilationEndedAnalyzer.Descriptor.Id, withDocumentLocationDiagnostic.Id) Assert.Equal(True, withDocumentLocationDiagnostic.HasTextSpan) Assert.NotNull(withDocumentLocationDiagnostic.DocumentId) Dim diagnosticDocument = project.GetDocument(withDocumentLocationDiagnostic.DocumentId) Dim tree = diagnosticDocument.GetSyntaxTreeAsync().Result Dim actualLocation = withDocumentLocationDiagnostic.ToDiagnosticAsync(project, CancellationToken.None).Result.Location Dim expectedLocation = document.GetSyntaxRootAsync().Result.GetLocation Assert.Equal(expectedLocation, actualLocation) End Using End Sub <Fact, WorkItem(1083854, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1083854"), Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Async Function TestStatefulCompilationAnalyzer() As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { void M() {} } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() Dim analyzer = New StatefulCompilationAnalyzer Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim projectDiagnostics = Await DiagnosticProviderTestUtilities.GetProjectDiagnosticsAsync(workspaceAnalyzerOpt:=Nothing, project:=project) Assert.Equal(1, projectDiagnostics.Count()) Dim diagnostic = projectDiagnostics.Single() Assert.Equal(StatefulCompilationAnalyzer.Descriptor.Id, diagnostic.Id) Dim expectedMessage = String.Format(StatefulCompilationAnalyzer.Descriptor.MessageFormat.ToString(), 1) Assert.Equal(expectedMessage, diagnostic.GetMessage) End Using End Function <WpfFact, WorkItem(248, "https://github.com/dotnet/roslyn/issues/248"), Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Async Function TestStatefulCompilationAnalyzer_2() As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { void M() {} } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() Dim analyzer = New StatefulCompilationAnalyzer Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) ' Make couple of dummy invocations to GetDocumentDiagnostics. Dim document = project.Documents.Single() Dim fullSpan = document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan Dim documentDiagnostics = Await DiagnosticProviderTestUtilities.GetDocumentDiagnosticsAsync(workspaceAnalyzerOpt:=Nothing, document:=document, span:=fullSpan) documentDiagnostics = Await DiagnosticProviderTestUtilities.GetDocumentDiagnosticsAsync(workspaceAnalyzerOpt:=Nothing, document:=document, span:=fullSpan) ' Verify that the eventual compilation end diagnostics (and hence the analyzer state) is not affected by prior document analysis. Dim projectDiagnostics = Await DiagnosticProviderTestUtilities.GetProjectDiagnosticsAsync(workspaceAnalyzerOpt:=Nothing, project:=project) Assert.Equal(1, projectDiagnostics.Count()) Dim diagnostic = projectDiagnostics.Single() Assert.Equal(StatefulCompilationAnalyzer.Descriptor.Id, diagnostic.Id) Dim expectedMessage = String.Format(StatefulCompilationAnalyzer.Descriptor.MessageFormat.ToString(), 1) Assert.Equal(expectedMessage, diagnostic.GetMessage) End Using End Function <WpfFact, WorkItem(9462, "https://github.com/dotnet/roslyn/issues/9462"), Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestMultiplePartialDefinitionsInAFile() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> partial class Foo { } partial class Foo { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() Dim analyzer = New NamedTypeAnalyzer Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) ' Verify no duplicate analysis/diagnostics. Dim document = project.Documents.Single() Dim diagnostics = diagnosticService.GetDiagnosticsAsync(project.Solution, project.Id) _ .WaitAndGetResult(CancellationToken.None) _ .Select(Function(d) d.Id = NamedTypeAnalyzer.DiagDescriptor.Id) Assert.Equal(1, diagnostics.Count) End Using End Sub <WpfFact, WorkItem(1042914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1042914"), Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestPartialTypeInGeneratedCode() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Foo.generated.cs"> public partial class Foo { } </Document> <Document FilePath="Test1.cs"> public partial class Foo { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() ' Test partial type diagnostic reported on user file. Dim analyzer = New PartialTypeDiagnosticAnalyzer(indexOfDeclToReportDiagnostic:=1) Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim document = project.Documents.Single(Function(d) d.Name = "Test1.cs") Dim fullSpan = document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, fullSpan).WaitAndGetResult(CancellationToken.None) Assert.Equal(1, diagnostics.Count()) Assert.Equal(PartialTypeDiagnosticAnalyzer.DiagDescriptor.Id, diagnostics.Single().Id) End Using End Sub <WpfFact, WorkItem(1042914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1042914"), Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestDiagnosticsReportedOnAllPartialDefinitions() ' Test partial type diagnostic reported on all source files. Dim analyzer = New PartialTypeDiagnosticAnalyzer(indexOfDeclToReportDiagnostic:=Nothing) TestDiagnosticsReportedOnAllPartialDefinitionsCore(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) End Sub <WpfFact, WorkItem(3748, "https://github.com/dotnet/roslyn/issues/3748"), Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestDiagnosticsReportedOnAllPartialDefinitions2() ' Test partial type diagnostic reported on all source files with multiple analyzers. ' NOTE: This test is written to guard a race condition, which originally reproed only when the driver processes 'dummyAnalyzer' before 'analyzer'. ' As this is non-deterministic, we execute it within a loop to increase the chance of failure if this regresses again. For i = 0 To 10 Dim dummyAnalyzer = New DummySymbolAnalyzer() Dim analyzer = New PartialTypeDiagnosticAnalyzer(indexOfDeclToReportDiagnostic:=Nothing) TestDiagnosticsReportedOnAllPartialDefinitionsCore(ImmutableArray.Create(Of DiagnosticAnalyzer)(dummyAnalyzer, analyzer)) Next i End Sub Private Shared Sub TestDiagnosticsReportedOnAllPartialDefinitionsCore(analyzers As ImmutableArray(Of DiagnosticAnalyzer)) Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test1.cs"> public partial class Foo { } </Document> <Document FilePath="Test2.cs"> public partial class Foo { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() ' Test partial type diagnostic reported on all source files. Dim analyzerReference = New AnalyzerImageReference(analyzers) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) ' Verify project diagnostics contains diagnostics reported on both partial definitions. Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsAsync(project.Solution, project.Id).WaitAndGetResult(CancellationToken.None) Assert.Equal(2, diagnostics.Count()) Dim file1HasDiag = False, file2HasDiag = False For Each diagnostic In diagnostics Assert.Equal(PartialTypeDiagnosticAnalyzer.DiagDescriptor.Id, diagnostic.Id) Dim document = project.GetDocument(diagnostic.DocumentId) If document.Name = "Test1.cs" Then file1HasDiag = True ElseIf document.Name = "Test2.cs" Then file2HasDiag = True End If Next Assert.True(file1HasDiag) Assert.True(file2HasDiag) End Using End Sub <WpfFact, WorkItem(1067286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067286")> Private Sub TestCodeBlockAnalyzersForExpressionBody() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class B { public int Property => 0; public int Method() => 0; public int this[int i] => 0; } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() ' Test code block analyzer Dim analyzer As DiagnosticAnalyzer = New CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer:=True) Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim document = project.Documents.Single() Dim fullSpan = document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, fullSpan).WaitAndGetResult(CancellationToken.None) Assert.Equal(6, diagnostics.Count()) Assert.Equal(3, diagnostics.Where(Function(d) d.Id = CodeBlockOrSyntaxNodeAnalyzer.Descriptor1.Id).Count) Assert.Equal(1, diagnostics.Where(Function(d) d.Id = CodeBlockOrSyntaxNodeAnalyzer.Descriptor4.Id).Count) Assert.Equal(1, diagnostics.Where(Function(d) d.Id = CodeBlockOrSyntaxNodeAnalyzer.Descriptor5.Id).Count) Assert.Equal(1, diagnostics.Where(Function(d) d.Id = CodeBlockOrSyntaxNodeAnalyzer.Descriptor6.Id).Count) End Using End Sub <WpfFact, WorkItem(592, "https://github.com/dotnet/roslyn/issues/592")> Private Sub TestSyntaxNodeAnalyzersForExpressionBody() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class B { public int Property => 0; public int Method() => 0; public int this[int i] => 0; } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() ' Test syntax node analyzer Dim analyzer As DiagnosticAnalyzer = New CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer:=False) Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim document = project.Documents.Single() Dim fullSpan = document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, fullSpan).WaitAndGetResult(CancellationToken.None) Assert.Equal(3, diagnostics.Count()) Assert.Equal(1, diagnostics.Where(Function(d) d.Id = CodeBlockOrSyntaxNodeAnalyzer.Descriptor4.Id).Count) Assert.Equal(1, diagnostics.Where(Function(d) d.Id = CodeBlockOrSyntaxNodeAnalyzer.Descriptor5.Id).Count) Assert.Equal(1, diagnostics.Where(Function(d) d.Id = CodeBlockOrSyntaxNodeAnalyzer.Descriptor6.Id).Count) End Using End Sub <WpfFact, WorkItem(592, "https://github.com/dotnet/roslyn/issues/592")> Private Sub TestMethodSymbolAnalyzersForExpressionBody() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class B { public int Property => 0; public int Method() => 0; public int this[int i] => 0; } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() ' Test method symbol analyzer Dim analyzer As DiagnosticAnalyzer = New MethodSymbolAnalyzer Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim document = project.Documents.Single() Dim fullSpan = document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, fullSpan). WaitAndGetResult(CancellationToken.None). OrderBy(Function(d) d.TextSpan.Start).ToArray Assert.Equal(3, diagnostics.Count) Assert.True(diagnostics.All(Function(d) d.Id = MethodSymbolAnalyzer.Descriptor.Id)) Assert.Equal("B.Property.get", diagnostics(0).Message) Assert.Equal("B.Method()", diagnostics(1).Message) Assert.Equal("B.this[int].get", diagnostics(2).Message) End Using End Sub <WpfFact, WorkItem(1109105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109105")> Public Sub TestMethodSymbolAnalyzer_MustOverrideMethod() Dim test = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public MustInherit Class Class1 Public MustOverride Function Foo(x As Integer, y As Integer) As Integer End Class Public Class Class2 Public Function Foo(x As Integer, y As Integer) As Integer Return x + y End Function End Class </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() Dim analyzer = New MustOverrideMethodAnalyzer() Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim document = project.Documents.Single() Dim fullSpan = document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, fullSpan).WaitAndGetResult(CancellationToken.None) Assert.Equal(1, diagnostics.Count()) Assert.Equal(1, diagnostics.Where(Function(d) d.Id = MustOverrideMethodAnalyzer.Descriptor1.Id).Count) End Using End Sub Public Class MustOverrideMethodAnalyzer Inherits DiagnosticAnalyzer Public Shared Descriptor1 As New DiagnosticDescriptor("MustOverrideMethodDiagnostic", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Descriptor1) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSymbolAction(AddressOf AnalyzeSymbol, SymbolKind.Method) End Sub Public Sub AnalyzeSymbol(context As SymbolAnalysisContext) Dim method = DirectCast(context.Symbol, IMethodSymbol) If method.IsAbstract Then Dim sourceLoc = context.Symbol.Locations.First(Function(l) l.IsInSource) context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor1, sourceLoc)) End If End Sub End Class <WpfFact, WorkItem(565, "https://github.com/dotnet/roslyn/issues/565")> Public Sub TestFieldDeclarationAnalyzer() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class B { public string field0; public string field1, field2; public int field3 = 0, field4 = 1; public int field5, field6 = 1; } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() Dim analyzer = New FieldDeclarationAnalyzer() Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim document = project.Documents.Single() Dim fullSpan = document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, fullSpan). WaitAndGetResult(CancellationToken.None). OrderBy(Function(d) d.TextSpan.Start). ToArray() Assert.Equal(4, diagnostics.Length) Assert.Equal(4, diagnostics.Where(Function(d) d.Id = FieldDeclarationAnalyzer.Descriptor1.Id).Count) Assert.Equal("public string field0;", diagnostics(0).Message) Assert.Equal("public string field1, field2;", diagnostics(1).Message) Assert.Equal("public int field3 = 0, field4 = 1;", diagnostics(2).Message) Assert.Equal("public int field5, field6 = 1;", diagnostics(3).Message) End Using End Sub Public Class FieldDeclarationAnalyzer Inherits DiagnosticAnalyzer Public Shared Descriptor1 As New DiagnosticDescriptor("FieldDeclarationDiagnostic", "DummyDescription", "{0}", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Descriptor1) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, CodeAnalysis.CSharp.SyntaxKind.FieldDeclaration) End Sub Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Dim fieldDecl = DirectCast(context.Node, CodeAnalysis.CSharp.Syntax.FieldDeclarationSyntax) context.ReportDiagnostic(Diagnostic.Create(Descriptor1, fieldDecl.GetLocation, fieldDecl.ToString())) End Sub End Class <WpfFact, WorkItem(530, "https://github.com/dotnet/roslyn/issues/530")> Public Sub TestCompilationAnalyzerWithAnalyzerOptions() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class B { } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() ' Add analyzer Dim analyzer = New CompilationAnalyzerWithAnalyzerOptions() Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) ' Add additional document Dim additionalDocText = "First" Dim additionalDoc = project.AddAdditionalDocument("AdditionalDoc", additionalDocText) project = additionalDoc.Project Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) TestCompilationAnalyzerWithAnalyzerOptionsCore(project, additionalDocText, diagnosticService) ' Update additional document text Dim newAdditionalDocText = "Second" additionalDoc = additionalDoc.WithText(SourceText.From(newAdditionalDocText)) project = additionalDoc.Project ' Verify updated additional document text TestCompilationAnalyzerWithAnalyzerOptionsCore(project, newAdditionalDocText, diagnosticService) End Using End Sub Private Shared Sub TestCompilationAnalyzerWithAnalyzerOptionsCore(project As Project, expectedDiagnosticMessage As String, diagnosticService As DiagnosticAnalyzerService) Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim document = project.Documents.Single() Dim fullSpan = document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, fullSpan). WaitAndGetResult(CancellationToken.None) Assert.Equal(1, diagnostics.Count()) Assert.Equal(CompilationAnalyzerWithAnalyzerOptions.Descriptor.Id, diagnostics(0).Id) Assert.Equal(expectedDiagnosticMessage, diagnostics(0).Message) End Sub <DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)> Private Class CompilationAnalyzerWithAnalyzerOptions Inherits DiagnosticAnalyzer Public Shared Descriptor As DiagnosticDescriptor = New DiagnosticDescriptor("CompilationAnalyzerWithAnalyzerOptionsDiagnostic", "CompilationAnalyzerWithAnalyzerOptionsDiagnostic", "{0}", "CompilationAnalyzerWithAnalyzerOptionsDiagnostic", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterCompilationStartAction(Sub(compilationContext As CompilationStartAnalysisContext) ' Cache additional file text Dim additionalFileText = compilationContext.Options.AdditionalFiles.Single().GetText().ToString() compilationContext.RegisterSymbolAction(Sub(symbolContext As SymbolAnalysisContext) Dim diag = Diagnostic.Create(Descriptor, symbolContext.Symbol.Locations(0), additionalFileText) symbolContext.ReportDiagnostic(diag) End Sub, SymbolKind.NamedType) End Sub) End Sub End Class <DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)> Private Class WorkspaceDiagnosticAnalyzer Inherits AbstractDiagnosticAnalyzer Public Shared ReadOnly Descriptor As DiagnosticDescriptor = New DiagnosticDescriptor("XX0000", "WorkspaceDiagnosticDescription", "WorkspaceDiagnosticMessage", "WorkspaceDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Public Overrides ReadOnly Property DiagDescriptor As DiagnosticDescriptor Get Return Descriptor End Get End Property End Class Private Class ProjectDiagnosticAnalyzer2 Inherits ProjectDiagnosticAnalyzer Public Sub New(index As Integer) MyBase.New(index) End Sub End Class Private Class ProjectDiagnosticAnalyzer Inherits AbstractDiagnosticAnalyzer Private ReadOnly _index As Integer Public ReadOnly Descriptor As DiagnosticDescriptor Public Sub New(index As Integer) Me._index = index Me.Descriptor = New DiagnosticDescriptor("XX000" + index.ToString, "ProjectDiagnosticDescription", "ProjectDiagnosticMessage", "ProjectDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault:=True) End Sub Public Overrides ReadOnly Property DiagDescriptor As DiagnosticDescriptor Get Return Descriptor End Get End Property End Class Private MustInherit Class AbstractDiagnosticAnalyzer Inherits DiagnosticAnalyzer Public MustOverride ReadOnly Property DiagDescriptor As DiagnosticDescriptor Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(DiagDescriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSymbolAction(AddressOf AnalyzeSymbol, SymbolKind.NamedType) End Sub Private Sub AnalyzeSymbol(context As SymbolAnalysisContext) context.ReportDiagnostic(Diagnostic.Create(DiagDescriptor, context.Symbol.Locations.First(), context.Symbol.Locations.Skip(1))) End Sub End Class Private Class PartialTypeDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private ReadOnly _indexOfDeclToReportDiagnostic As Integer? Public Sub New(indexOfDeclToReportDiagnostic As Integer?) Me._indexOfDeclToReportDiagnostic = indexOfDeclToReportDiagnostic End Sub Public Shared ReadOnly DiagDescriptor As DiagnosticDescriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic") Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(DiagDescriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSymbolAction(AddressOf AnalyzeSymbol, SymbolKind.NamedType) End Sub Private Sub AnalyzeSymbol(context As SymbolAnalysisContext) Dim index = 0 For Each location In context.Symbol.Locations If Not Me._indexOfDeclToReportDiagnostic.HasValue OrElse Me._indexOfDeclToReportDiagnostic.Value = index Then context.ReportDiagnostic(Diagnostic.Create(DiagDescriptor, location)) End If index += 1 Next End Sub End Class Private Class NamedTypeAnalyzer Inherits DiagnosticAnalyzer Public Shared ReadOnly DiagDescriptor As DiagnosticDescriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic") Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(DiagDescriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterCompilationStartAction(Sub(compStartContext As CompilationStartAnalysisContext) Dim symbols = New HashSet(Of ISymbol) compStartContext.RegisterSymbolAction(Sub(sc As SymbolAnalysisContext) If (symbols.Contains(sc.Symbol)) Then Throw New Exception("Duplicate symbol callback") End If sc.ReportDiagnostic(Diagnostic.Create(DiagDescriptor, sc.Symbol.Locations.First())) End Sub, SymbolKind.NamedType) End Sub) End Sub End Class Private Class DummySymbolAnalyzer Inherits DiagnosticAnalyzer Public Shared ReadOnly DiagDescriptor As DiagnosticDescriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic") Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(DiagDescriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSymbolAction(AddressOf AnalyzeSymbol, SymbolKind.NamedType) End Sub Private Sub AnalyzeSymbol(context As SymbolAnalysisContext) End Sub End Class Private Class ThrowsExceptionAnalyzer Inherits DiagnosticAnalyzer Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Throw New NotImplementedException() End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSymbolAction(AddressOf AnalyzeSymbol, SymbolKindsOfInterest) End Sub Public Sub AnalyzeSymbol(context As SymbolAnalysisContext) Throw New NotImplementedException() End Sub Private ReadOnly Property SymbolKindsOfInterest As SymbolKind() Get Throw New NotImplementedException() End Get End Property End Class Private Class CodeBlockStartedAnalyzer(Of TLanguageKindEnum As Structure) Inherits DiagnosticAnalyzer Public Shared Descriptor As DiagnosticDescriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic") Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Descriptor) End Get End Property Public Sub CreateAnalyzerWithinCodeBlock(context As CodeBlockStartAnalysisContext(Of TLanguageKindEnum)) context.RegisterCodeBlockEndAction(AddressOf (New CodeBlockEndedAnalyzer).AnalyzeCodeBlock) End Sub Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterCodeBlockStartAction(Of TLanguageKindEnum)(AddressOf CreateAnalyzerWithinCodeBlock) ' Register a semantic model action that doesn't do anything to make sure that doesn't confuse anything. context.RegisterSemanticModelAction(Sub(sm) Return) End Sub Private Class CodeBlockEndedAnalyzer Public Sub AnalyzeCodeBlock(context As CodeBlockAnalysisContext) Throw New NotImplementedException() End Sub End Class End Class Private Class CodeBlockEndedAnalyzer Inherits DiagnosticAnalyzer Public Shared Descriptor As DiagnosticDescriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic") Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterCodeBlockAction(AddressOf AnalyzeCodeBlock) ' Register a compilation start action that doesn't do anything to make sure that doesn't confuse anything. context.RegisterCompilationStartAction(Sub(c) Return) ' Register a compilation action that doesn't do anything to make sure that doesn't confuse anything. context.RegisterCompilationAction(Sub(c) Return) End Sub Public Sub AnalyzeCodeBlock(context As CodeBlockAnalysisContext) Assert.NotNull(context.CodeBlock) Assert.NotNull(context.OwningSymbol) context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.CodeBlock.GetLocation)) End Sub End Class Private Class CodeBlockStartedAndEndedAnalyzer(Of TLanguageKindEnum As Structure) Inherits DiagnosticAnalyzer Public Shared Descriptor As DiagnosticDescriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic") Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterCodeBlockStartAction(Of TLanguageKindEnum)(AddressOf CreateAnalyzerWithinCodeBlock) ' Register a compilation action that doesn't do anything to make sure that doesn't confuse anything. context.RegisterCompilationAction(Sub(c) Return) End Sub Public Sub AnalyzeCodeBlock(context As CodeBlockAnalysisContext) context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.CodeBlock.GetLocation)) End Sub Public Sub CreateAnalyzerWithinCodeBlock(context As CodeBlockStartAnalysisContext(Of TLanguageKindEnum)) context.RegisterCodeBlockEndAction(AddressOf AnalyzeCodeBlock) End Sub End Class Private Class CompilationEndedAnalyzer Inherits DiagnosticAnalyzer Public Shared Descriptor As DiagnosticDescriptor = DescriptorFactory.CreateSimpleDescriptor("CompilationEndedAnalyzerDiagnostic") Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) ' Register a symbol analyzer that doesn't do anything to verify that that doesn't confuse anything. context.RegisterSymbolAction(Sub(s) Return, SymbolKind.NamedType) context.RegisterCompilationAction(AddressOf AnalyzeCompilation) End Sub Private Shared Sub AnalyzeCompilation(context As CompilationAnalysisContext) context.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None)) context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Compilation.SyntaxTrees(0).GetRoot().GetLocation)) End Sub End Class Private Class StatefulCompilationAnalyzer Inherits DiagnosticAnalyzer Public Shared Descriptor As DiagnosticDescriptor = New DiagnosticDescriptor("StatefulCompilationAnalyzerDiagnostic", "", "Compilation NamedType Count: {0}", "", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterCompilationStartAction(AddressOf OnCompilationStarted) End Sub Private Shared Sub OnCompilationStarted(context As CompilationStartAnalysisContext) Dim compilationAnalyzer = New CompilationAnalyzer context.RegisterSymbolAction(AddressOf compilationAnalyzer.AnalyzeSymbol, SymbolKind.NamedType) context.RegisterCompilationEndAction(AddressOf compilationAnalyzer.AnalyzeCompilation) End Sub Private Class CompilationAnalyzer Private ReadOnly _symbolNames As New List(Of String) Public Sub AnalyzeSymbol(context As SymbolAnalysisContext) _symbolNames.Add(context.Symbol.Name) End Sub Public Sub AnalyzeCompilation(context As CompilationAnalysisContext) context.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None, _symbolNames.Count)) End Sub End Class End Class Private Class CodeBlockOrSyntaxNodeAnalyzer Inherits DiagnosticAnalyzer Private ReadOnly _isCodeBlockAnalyzer As Boolean Public Shared Descriptor1 As DiagnosticDescriptor = DescriptorFactory.CreateSimpleDescriptor("CodeBlockDiagnostic") Public Shared Descriptor2 As DiagnosticDescriptor = DescriptorFactory.CreateSimpleDescriptor("EqualsValueDiagnostic") Public Shared Descriptor3 As DiagnosticDescriptor = DescriptorFactory.CreateSimpleDescriptor("ConstructorInitializerDiagnostic") Public Shared Descriptor4 As DiagnosticDescriptor = DescriptorFactory.CreateSimpleDescriptor("PropertyExpressionBodyDiagnostic") Public Shared Descriptor5 As DiagnosticDescriptor = DescriptorFactory.CreateSimpleDescriptor("IndexerExpressionBodyDiagnostic") Public Shared Descriptor6 As DiagnosticDescriptor = DescriptorFactory.CreateSimpleDescriptor("MethodExpressionBodyDiagnostic") Public Sub New(isCodeBlockAnalyzer As Boolean) _isCodeBlockAnalyzer = isCodeBlockAnalyzer End Sub Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Descriptor1, Descriptor2, Descriptor3, Descriptor4, Descriptor5, Descriptor6) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) If _isCodeBlockAnalyzer Then context.RegisterCodeBlockStartAction(Of CodeAnalysis.CSharp.SyntaxKind)(AddressOf OnCodeBlockStarted) context.RegisterCodeBlockAction(AddressOf OnCodeBlockEnded) Else Dim analyzer = New NodeAnalyzer analyzer.Initialize(Sub(action, Kinds) context.RegisterSyntaxNodeAction(action, Kinds)) End If End Sub Public Shared Sub OnCodeBlockEnded(context As CodeBlockAnalysisContext) context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor1, context.CodeBlock.GetLocation())) End Sub Public Shared Sub OnCodeBlockStarted(context As CodeBlockStartAnalysisContext(Of CodeAnalysis.CSharp.SyntaxKind)) Dim analyzer = New NodeAnalyzer analyzer.Initialize(Sub(action, Kinds) context.RegisterSyntaxNodeAction(action, Kinds)) End Sub Protected Class NodeAnalyzer Public Sub Initialize(registerSyntaxNodeAction As Action(Of Action(Of SyntaxNodeAnalysisContext), ImmutableArray(Of CodeAnalysis.CSharp.SyntaxKind))) registerSyntaxNodeAction(Sub(context) context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor2, context.Node.GetLocation())) End Sub, ImmutableArray.Create(CodeAnalysis.CSharp.SyntaxKind.EqualsValueClause)) registerSyntaxNodeAction(Sub(context) context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor3, context.Node.GetLocation())) End Sub, ImmutableArray.Create(CodeAnalysis.CSharp.SyntaxKind.BaseConstructorInitializer)) registerSyntaxNodeAction(Sub(context) Dim descriptor As DiagnosticDescriptor Select Case CodeAnalysis.CSharp.CSharpExtensions.Kind(context.Node.Parent) Case CodeAnalysis.CSharp.SyntaxKind.PropertyDeclaration descriptor = Descriptor4 Exit Select Case CodeAnalysis.CSharp.SyntaxKind.IndexerDeclaration descriptor = Descriptor5 Exit Select Case Else descriptor = Descriptor6 Exit Select End Select context.ReportDiagnostic(Diagnostic.Create(descriptor, context.Node.GetLocation)) End Sub, ImmutableArray.Create(CodeAnalysis.CSharp.SyntaxKind.ArrowExpressionClause)) End Sub End Class End Class Private Class MethodSymbolAnalyzer Inherits DiagnosticAnalyzer Public Shared Descriptor As DiagnosticDescriptor = New DiagnosticDescriptor("MethodSymbolDiagnostic", "MethodSymbolDiagnostic", "{0}", "MethodSymbolDiagnostic", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSymbolAction(Sub(ctxt) Dim method = (DirectCast(ctxt.Symbol, IMethodSymbol)) ctxt.ReportDiagnostic(Diagnostic.Create(Descriptor, method.Locations(0), method.ToDisplayString)) End Sub, SymbolKind.Method) End Sub End Class <WpfFact, WorkItem(1709, "https://github.com/dotnet/roslyn/issues/1709")> Public Sub TestCodeBlockAction() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public void M() {} } </Document> </Project> </Workspace> TestCodeBlockActionCore(test) test = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Sub M() End Sub End Class </Document> </Project> </Workspace> TestCodeBlockActionCore(test) End Sub <WpfFact, WorkItem(1709, "https://github.com/dotnet/roslyn/issues/1709")> Public Sub TestCodeBlockAction_OnlyStatelessAction() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public void M() {} } </Document> </Project> </Workspace> TestCodeBlockActionCore(test, onlyStatelessAction:=True) test = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Sub M() End Sub End Class </Document> </Project> </Workspace> TestCodeBlockActionCore(test, onlyStatelessAction:=True) End Sub Private Sub TestCodeBlockActionCore(test As XElement, Optional onlyStatelessAction As Boolean = False) Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() ' Add analyzer Dim analyzer = New CodeBlockActionAnalyzer(onlyStatelessAction) Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim document = project.Documents.Single() Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan ).WaitAndGetResult(CancellationToken.None) Dim expectedCount = If(onlyStatelessAction, 1, 2) Assert.Equal(expectedCount, diagnostics.Count()) Dim diagnostic = diagnostics.Single(Function(d) d.Id = CodeBlockActionAnalyzer.CodeBlockTopLevelRule.Id) Assert.Equal("CodeBlock : M", diagnostic.Message) Dim stateFullDiagnostics = diagnostics.Where(Function(d) d.Id = CodeBlockActionAnalyzer.CodeBlockPerCompilationRule.Id) Assert.Equal(expectedCount - 1, stateFullDiagnostics.Count) If Not onlyStatelessAction Then Assert.Equal("CodeBlock : M", stateFullDiagnostics.Single().Message) End If End Using End Sub <WpfFact, WorkItem(2614, "https://github.com/dotnet/roslyn/issues/2614")> Public Sub TestGenericName() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; using System.Text; namespace ConsoleApplication1 { class MyClass { private Nullable<int> myVar = 5; void Method() { } } }]]> </Document> </Project> </Workspace> TestGenericNameCore(test, CSharpGenericNameAnalyzer.Message, CSharpGenericNameAnalyzer.DiagnosticId, New CSharpGenericNameAnalyzer) End Sub Private Sub TestGenericNameCore(test As XElement, expectedMessage As String, expectedId As String, ParamArray analyzers As DiagnosticAnalyzer()) Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() ' Add analyzer Dim analyzerReference = New AnalyzerImageReference(analyzers.ToImmutableArray()) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim document = project.Documents.Single() Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan ).WaitAndGetResult(CancellationToken.None) Assert.Equal(1, diagnostics.Count()) Dim diagnostic = diagnostics.Single(Function(d) d.Id = expectedId) Assert.Equal(expectedMessage, diagnostic.Message) End Using End Sub <WpfFact, WorkItem(2980, "https://github.com/dotnet/roslyn/issues/2980")> Public Sub TestAnalyzerWithNoActions() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; using System.Text; namespace ConsoleApplication1 { class MyClass { private Nullable<int> myVar = 5; void Method() { } } }]]> </Document> </Project> </Workspace> ' Ensure that adding a dummy analyzer with no actions doesn't bring down entire analysis. ' See https//github.com/dotnet/roslyn/issues/2980 for details. TestGenericNameCore(test, CSharpGenericNameAnalyzer.Message, CSharpGenericNameAnalyzer.DiagnosticId, New AnalyzerWithNoActions, New CSharpGenericNameAnalyzer) End Sub <WpfFact, WorkItem(4055, "https://github.com/dotnet/roslyn/issues/4055")> Public Sub TestAnalyzerWithNoSupportedDiagnostics() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class MyClass { }]]> </Document> </Project> </Workspace> ' Ensure that adding a dummy analyzer with no supported diagnostics doesn't bring down entire analysis. Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single() ' Add analyzer Dim analyzer = New AnalyzerWithNoSupportedDiagnostics() Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) ' Verify available diagnostic descriptors/analyzers Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Assert.Equal(0, descriptorsMap.First().Value.Length) Dim document = project.Documents.Single() Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan ).WaitAndGetResult(CancellationToken.None) Assert.Equal(0, diagnostics.Count()) End Using End Sub <WpfFact, WorkItem(4068, "https://github.com/dotnet/roslyn/issues/4068")> Public Sub TestAnalyzerWithCompilationActionReportingHiddenDiagnostics() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class MyClass { }]]> </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) workspace.Options = workspace.Options.WithChangedOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, LanguageNames.CSharp, True) Dim project = workspace.CurrentSolution.Projects.Single() ' Add analyzer Dim analyzer = New HiddenDiagnosticsCompilationAnalyzer() Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) ' Verify available diagnostic descriptors Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim descriptors = descriptorsMap.First().Value Assert.Equal(1, descriptors.Length) Assert.Equal(HiddenDiagnosticsCompilationAnalyzer.Descriptor.Id, descriptors.Single().Id) ' Force project analysis incrementalAnalyzer.AnalyzeProjectAsync(project, semanticsChanged:=True, cancellationToken:=CancellationToken.None).Wait() ' Get cached project diagnostics. Dim diagnostics = diagnosticService.GetCachedDiagnosticsAsync(workspace, project.Id).WaitAndGetResult(CancellationToken.None) ' different behavior between v1 and v2. in v2. in v2, solution crawler never creates non-local hidden diagnostics. ' v2 still creates those for LB and explicit queries such as FixAll. Dim expectedCount = If(workspace.Options.GetOption(InternalDiagnosticsOptions.UseDiagnosticEngineV2), 0, 1) Assert.Equal(expectedCount, diagnostics.Count()) ' Get diagnostics explicitly Dim hiddenDiagnostics = diagnosticService.GetDiagnosticsAsync(project.Solution, project.Id).WaitAndGetResult(CancellationToken.None) Assert.Equal(1, hiddenDiagnostics.Count()) Assert.Equal(HiddenDiagnosticsCompilationAnalyzer.Descriptor.Id, hiddenDiagnostics.Single().Id) End Using End Sub <WpfFact> Public Sub TestEnsureNoMergedNamespaceSymbolAnalyzer() Dim test = <Workspace> <Project Language="C#" AssemblyName="BaseAssembly" CommonReferences="true"> <Document> namespace N1.N2 { class C1 { } } </Document> </Project> <Project Language="C#" AssemblyName="MainAssembly" CommonReferences="true"> <ProjectReference>BaseAssembly</ProjectReference> <Document> namespace N1.N2 { class C2 { } } </Document> </Project> </Workspace> Using workspace = TestWorkspace.CreateWorkspace(test) Dim project = workspace.CurrentSolution.Projects.Single(Function(p As Project) p.Name = "MainAssembly") ' Analyzer reports a diagnostic if it receives a merged namespace symbol across assemblies in compilation. Dim analyzer = New EnsureNoMergedNamespaceSymbolAnalyzer() Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) project = project.AddAnalyzerReference(analyzerReference) Dim diagnosticService = New TestDiagnosticAnalyzerService() Dim descriptorsMap = diagnosticService.GetDiagnosticDescriptors(project) Assert.Equal(1, descriptorsMap.Count) Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace) Dim diagnostics = diagnosticService.GetDiagnosticsAsync(project.Solution, project.Id).WaitAndGetResult(CancellationToken.None) Assert.Equal(0, diagnostics.Count()) End Using End Sub End Class End Namespace
sharadagrawal/Roslyn
src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb
Visual Basic
apache-2.0
108,148
#If _MyType <> "Empty" Then Namespace My ''' <summary> ''' WPF のマイ名前空間で使用できるプロパティを定義するためのモジュール ''' </summary> ''' <remarks></remarks> <Global.Microsoft.VisualBasic.HideModuleName()> _ Module MyWpfExtension Private s_Computer As New ThreadSafeObjectProvider(Of Global.Microsoft.VisualBasic.Devices.Computer) Private s_User As New ThreadSafeObjectProvider(Of Global.Microsoft.VisualBasic.ApplicationServices.User) Private s_Windows As New ThreadSafeObjectProvider(Of MyWindows) Private s_Log As New ThreadSafeObjectProvider(Of Global.Microsoft.VisualBasic.Logging.Log) ''' <summary> ''' 実行中のアプリケーション用のアプリケーション オブジェクトを返します ''' </summary> <Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _ Friend ReadOnly Property Application() As Application Get Return CType(Global.System.Windows.Application.Current, Application) End Get End Property ''' <summary> ''' ホスト コンピューターに関する情報を返します。 ''' </summary> <Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _ Friend ReadOnly Property Computer() As Global.Microsoft.VisualBasic.Devices.Computer Get Return s_Computer.GetInstance() End Get End Property ''' <summary> ''' 現在のユーザーに関する情報を返します。現在の ''' Windows ユーザー資格情報でアプリケーションを実行する場合は、My.User.InitializeWithWindowsUser() を呼び出してください。 ''' </summary> <Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _ Friend ReadOnly Property User() As Global.Microsoft.VisualBasic.ApplicationServices.User Get Return s_User.GetInstance() End Get End Property ''' <summary> ''' アプリケーション ログを返します。リスナーは、アプリケーションの構成ファイルを使用して構成できます。 ''' </summary> <Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _ Friend ReadOnly Property Log() As Global.Microsoft.VisualBasic.Logging.Log Get Return s_Log.GetInstance() End Get End Property ''' <summary> ''' プロジェクトで定義されている Windows の集合を返します。 ''' </summary> <Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _ Friend ReadOnly Property Windows() As MyWindows <Global.System.Diagnostics.DebuggerHidden()> _ Get Return s_Windows.GetInstance() End Get End Property <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _ <Global.Microsoft.VisualBasic.MyGroupCollection("System.Windows.Window", "Create__Instance__", "Dispose__Instance__", "My.MyWpfExtenstionModule.Windows")> _ Friend NotInheritable Class MyWindows <Global.System.Diagnostics.DebuggerHidden()> _ Private Shared Function Create__Instance__(Of T As {New, Global.System.Windows.Window})(ByVal Instance As T) As T If Instance Is Nothing Then If s_WindowBeingCreated IsNot Nothing Then If s_WindowBeingCreated.ContainsKey(GetType(T)) = True Then Throw New Global.System.InvalidOperationException("The window cannot be accessed via My.Windows from the Window constructor.") End If Else s_WindowBeingCreated = New Global.System.Collections.Hashtable() End If s_WindowBeingCreated.Add(GetType(T), Nothing) Return New T() s_WindowBeingCreated.Remove(GetType(T)) Else Return Instance End If End Function <Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1822:MarkMembersAsStatic")> _ <Global.System.Diagnostics.DebuggerHidden()> _ Private Sub Dispose__Instance__(Of T As Global.System.Windows.Window)(ByRef instance As T) instance = Nothing End Sub <Global.System.Diagnostics.DebuggerHidden()> _ <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _ Public Sub New() MyBase.New() End Sub <Global.System.ThreadStatic()> Private Shared s_WindowBeingCreated As Global.System.Collections.Hashtable <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Public Overrides Function Equals(ByVal o As Object) As Boolean Return MyBase.Equals(o) End Function <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Public Overrides Function GetHashCode() As Integer Return MyBase.GetHashCode End Function <Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1822:MarkMembersAsStatic")> _ <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> _ Friend Overloads Function [GetType]() As Global.System.Type Return GetType(MyWindows) End Function <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Public Overrides Function ToString() As String Return MyBase.ToString End Function End Class End Module End Namespace Partial Class Application Inherits Global.System.Windows.Application <Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _ <Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1822:MarkMembersAsStatic")> _ Friend ReadOnly Property Info() As Global.Microsoft.VisualBasic.ApplicationServices.AssemblyInfo <Global.System.Diagnostics.DebuggerHidden()> _ Get Return New Global.Microsoft.VisualBasic.ApplicationServices.AssemblyInfo(Global.System.Reflection.Assembly.GetExecutingAssembly()) End Get End Property End Class #End If
surviveplus/EditorPlus
prototype/BulkUI/BulkUI/My Project/MyExtensions/MyWpfExtension.vb
Visual Basic
mit
7,170
' 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.CSharp.CodeFixes.AddImport Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.AddImport Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.AddImport Public Class AddImportCrossLanguageTests Inherits AbstractCrossLanguageUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace, language As String) As Tuple(Of DiagnosticAnalyzer, CodeFixProvider) Dim fixer As CodeFixProvider If language = LanguageNames.CSharp Then fixer = New CSharpAddImportCodeFixProvider() Else fixer = New VisualBasicAddImportCodeFixProvider() End If Return Tuple.Create(Of DiagnosticAnalyzer, CodeFixProvider)(Nothing, fixer) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)> Public Sub Test_CSharpToVisualBasic1() Dim input = <Workspace> <Project Language='C#' AssemblyName='CSharpAssembly1' CommonReferences='true'> <ProjectReference>VBAssembly1</ProjectReference> <Document FilePath="Test1.vb"> public class Class1 { public void Foo() { var x = new Cl$$ass2(); } } </Document> </Project> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <Document FilePath='Test2.vb'> namespace NS2 public class Class2 end class end namespace </Document> </Project> </Workspace> Dim expected = <text> using NS2; public class Class1 { public void Foo() { var x = new Class2(); } } </text>.Value.Trim() Test(input, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)> Public Sub Test_VisualBasicToCSharp1() Dim input = <Workspace> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <ProjectReference>CSAssembly1</ProjectReference> <Document FilePath="Test1.vb"> public class Class1 public sub Foo() dim x as new Cl$$ass2() end sub end class </Document> </Project> <Project Language='C#' AssemblyName='CSAssembly1' CommonReferences='true'> <Document FilePath='Test2.cs'> namespace NS2 { public class Class2 { } } </Document> </Project> </Workspace> Dim expected = <text> Imports NS2 Public Class Class1 Public Sub Foo() Dim x As New Class2() End Sub End Class </text>.Value.Trim() Test(input, expected) End Sub <WorkItem(1083419)> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)> Public Sub TestExtensionMethods1() Dim input = <Workspace> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <Document FilePath="Test1.vb"> Imports System.Collections.Generic Imports System.Runtime.CompilerServices Namespace VBAssembly1 Public Module Module1 &lt;Extension&gt; Public Function [Select](x As List(Of Integer)) As IEnumerable(Of Integer) Return Nothing End Function End Module End Namespace </Document> </Project> <Project Language='C#' AssemblyName='CSAssembly1' CommonReferences='true'> <ProjectReference>VBAssembly1</ProjectReference> <Document FilePath='Test1.cs'> using System.Collections.Generic; namespace CSAssembly1 { class Program { static void Main() { var l = new List&lt;int&gt;(); l.Se$$lect(); } } } </Document> </Project> </Workspace> Dim expected = <text> using System.Collections.Generic; using VBAssembly1; namespace CSAssembly1 { class Program { static void Main() { var l = new List&lt;int&gt;(); l.Select(); } } } </text>.Value.Trim() Test(input, expected, codeActionIndex:=1) End Sub <WorkItem(1083419)> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)> Public Sub TestExtensionMethods2() Dim input = <Workspace> <Project Language='C#' AssemblyName='CSAssembly1' CommonReferences='true'> <Document FilePath='Test1.cs'> using System.Collections.Generic; namespace CSAssembly1 { public static class Program { public static IEnumerable&lt;int&gt; Select(this List&lt;int&gt; x) { return null; } } } </Document> </Project> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <ProjectReference>CSAssembly1</ProjectReference> <CompilationOptions></CompilationOptions> <Document FilePath="Test1.vb"> Imports System.Collections.Generic Namespace VBAssembly1 Module Module1 Sub Main() Dim l = New List(Of Integer)() l.Se$$lect() End Sub End Module End Namespace </Document> </Project> </Workspace> Dim expected = <text> Imports System.Collections.Generic Imports CSAssembly1 Namespace VBAssembly1 Module Module1 Sub Main() Dim l = New List(Of Integer)() l.Select() End Sub End Module End Namespace </text>.Value.Trim() Test(input, expected, codeActionIndex:=0) End Sub End Class End Namespace
jbhensley/roslyn
src/EditorFeatures/Test2/Diagnostics/AddImport/AddImportCrossLanguageTests.vb
Visual Basic
apache-2.0
7,627
' 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.Expressions Public Class AwaitKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InSynchronousMethodTest() VerifyRecommendationsContain(<File> Class C Sub Goo() Dim z = | End Sub End Class </File>, "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InMethodStatementTest() VerifyRecommendationsContain(<File> Class C Async Sub Goo() | End Sub End Class </File>, "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InMethodExpressionTest() VerifyRecommendationsContain(<File> Class C Async Sub Goo() Dim z = | End Sub End Class </File>, "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInCatchTest() VerifyRecommendationsMissing(<File> Class C Async Sub Goo() Try Catch Dim z = | End Try End Sub End Class </File>, "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInCatchExceptionFilterTest() VerifyRecommendationsMissing(<File> Class C Async Sub Goo() Try Catch When Err = | End Try End Sub End Class </File>, "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InCatchNestedDelegateTest() VerifyRecommendationsContain(<File> Class C Async Sub Goo() Try Catch Dim z = Function() | End Try End Sub End Class </File>, "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInFinallyTest() VerifyRecommendationsMissing(<File> Class C Async Sub Goo() Try Finally Dim z = | End Try End Sub End Class </File>, "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInSyncLockTest() VerifyRecommendationsMissing(<File> Class C Async Sub Goo() SyncLock True Dim z = | End SyncLock End Sub End Class </File>, "Await") End Sub End Class End Namespace
physhi/roslyn
src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/AwaitKeywordRecommenderTests.vb
Visual Basic
apache-2.0
3,073
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements ''' <summary> ''' Recommends the "Select" keyword at the start of a statement ''' </summary> Friend Class SelectKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.IsMultiLineStatementContext Then Return ImmutableArray.Create(New RecommendedKeyword("Select", VBFeaturesResources.Runs_one_of_several_groups_of_statements_depending_on_the_value_of_an_expression)) End If Dim targetToken = context.TargetToken If targetToken.IsKind(SyntaxKind.ExitKeyword) AndAlso context.IsInStatementBlockOfKind(SyntaxKind.SelectBlock) AndAlso Not context.IsInStatementBlockOfKind(SyntaxKind.FinallyBlock) Then Return ImmutableArray.Create(New RecommendedKeyword("Select", VBFeaturesResources.Exits_a_Select_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Select_statement)) End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
AmadeusW/roslyn
src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/SelectKeywordRecommender.vb
Visual Basic
apache-2.0
1,715
' 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 Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class HoistedMeTests Inherits ExpressionCompilerTestBase <WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")> <Fact> Public Sub InstanceIterator_NoCapturing() Const source = " Class C Iterator Function F() As System.Collections.IEnumerable Yield 1 End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub <WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")> <Fact> Public Sub InstanceAsync_NoCapturing() Const source = " Imports System Imports System.Threading.Tasks Class C Async Function F() As Task Await Console.Out.WriteLineAsync(""a"") End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.VB$StateMachine_1_F V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub <WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")> <Fact> Public Sub InstanceLambda_NoCapturing() Const source = " Class C Sub M() Dim a As System.Action = Sub() Equals(1, 2) a() End Sub End Class " ' This test documents the fact that, as in dev12, "Me" ' is unavailable while stepping through the lambda. It ' would be preferable if it were. VerifyNoMe(source, "C._Closure$__._Lambda$__1-0") End Sub <Fact()> Public Sub InstanceLambda_NoCapturingExceptThis() Const source = " Class C Sub M() Dim a As System.Action = Sub() Equals(Me.GetHashCode(), 2) a() End Sub End Class " Const expectedIL = " { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } " VerifyHasMe(source, "C._Lambda$__1-0", "C", expectedIL) End Sub <Fact> Public Sub InstanceIterator_CapturedMe() Const source = " Class C Iterator Function F() As System.Collections.IEnumerable Yield Me End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub <Fact> Public Sub InstanceAsync_CapturedMe() Const source = " Imports System Imports System.Threading.Tasks Class C Async Function F() As Task Await Console.Out.WriteLineAsync(Me.ToString()) End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.VB$StateMachine_1_F V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub <Fact()> Public Sub InstanceLambda_CapturedMe_DisplayClass() Const source = " Class C Private x As Integer Sub M(y As Integer) Dim a As System.Action = Sub() Equals(x, y) a() End Sub End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C._Closure$__2-0.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C._Closure$__2-0._Lambda$__0", "C", expectedIL) End Sub <Fact()> Public Sub InstanceLambda_CapturedMe_NoDisplayClass() Const source = " Class C Private x As Integer Sub M() Dim a As System.Action = Sub() Equals(x, 1) a() End Sub End Class " Const expectedIL = " { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } " VerifyHasMe(source, "C._Lambda$__2-0", "C", expectedIL) End Sub <Fact> Public Sub InstanceIterator_Generic() Const source = " Class C(Of T) Iterator Function F(Of U)() As System.Collections.IEnumerable Yield Me End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C(Of T).VB$StateMachine_1_F(Of U).$VB$Me As C(Of T)"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C(Of T)", expectedIL) End Sub <Fact> Public Sub InstanceAsync_Generic() Const source = " Imports System Imports System.Threading.Tasks Class C(Of T) Async Function F(Of U)() As Task Await Console.Out.WriteLineAsync(Me.ToString()) End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C(Of T).VB$StateMachine_1_F(Of U) V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C(Of T).VB$StateMachine_1_F(Of U).$VB$Me As C(Of T)"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C(Of T)", expectedIL) End Sub <Fact()> Public Sub InstanceLambda_Generic() Const source = " Class C(Of T) Private x As Integer Sub M(Of U)(y As Integer) Dim a As System.Action = Sub() Equals(x, y) a() End Sub End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C(Of T)._Closure$__2-0(Of $CLS0).$VB$Me As C(Of T)"" IL_0006: ret } " VerifyHasMe(source, "C._Closure$__2-0._Lambda$__0", "C(Of T)", expectedIL) End Sub ' Note: Not actually an issue in VB, since the name isn't mangled. <Fact> Public Sub InstanceIterator_ExplicitInterfaceImplementation() Const source = " Interface I Function F() As System.Collections.IEnumerable End Interface Class C : Implements I Iterator Function F() As System.Collections.IEnumerable Implements I.F Yield Me End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub ' Note: Not actually an issue in VB, since the name isn't mangled. <Fact> Public Sub InstanceAsync_ExplicitInterfaceImplementation() Const source = " Imports System Imports System.Threading.Tasks Interface I Function F() As Task End Interface Class C : Implements I Async Function F() As Task Implements I.F Await Console.Out.WriteLineAsync(Me.ToString()) End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.VB$StateMachine_1_F V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub <Fact()> Public Sub InstanceLambda_ExplicitInterfaceImplementation() Const source = " Interface I Sub M(y As Integer) End Interface Class C : Implements I Private x As Integer Sub M(y As Integer) Implements I.M Dim a As System.Action = Sub() Equals(x, y) a() End Sub End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C._Closure$__2-0.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C._Closure$__2-0._Lambda$__0", "C", expectedIL) End Sub <Fact> Public Sub SharedIterator() Const source = " Module M Iterator Function F() As System.Collections.IEnumerable Yield 1 End Function End Module " VerifyNoMe(source, "M.VB$StateMachine_0_F.MoveNext") End Sub <Fact> Public Sub SharedAsync() Const source = " Imports System Imports System.Threading.Tasks Module M Async Function F() As Task Await Console.Out.WriteLineAsync(""A"") End Function End Module " VerifyNoMe(source, "M.VB$StateMachine_0_F.MoveNext") End Sub <Fact()> Public Sub SharedLambda() Const source = " Module M Sub M(y As Integer) Dim a As System.Action = Sub() Equals(1, y) a() End Sub End Module " VerifyNoMe(source, "M._Closure$__0-0._Lambda$__0") End Sub <Fact> Public Sub ExtensionIterator() Const source = " Module M <System.Runtime.CompilerServices.Extension> Iterator Function F(x As Integer) As System.Collections.IEnumerable Yield x End Function End Module " VerifyNoMe(source, "M.VB$StateMachine_0_F.MoveNext") End Sub <Fact> Public Sub ExtensionAsync() Const source = " Imports System Imports System.Threading.Tasks Module M <System.Runtime.CompilerServices.Extension> Async Function F(x As Integer) As Task Await Console.Out.WriteLineAsync(""A"") End Function End Module " VerifyNoMe(source, "M.VB$StateMachine_0_F.MoveNext") End Sub <Fact()> Public Sub ExtensionLambda() Const source = " Module M <System.Runtime.CompilerServices.Extension> Sub M(y As Integer) Dim a As System.Action = Sub() Equals(1, y) a() End Sub End Module " VerifyNoMe(source, "M._Closure$__0-0._Lambda$__0") End Sub <WorkItem(1072296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072296")> <Fact> Public Sub OldStyleNonCapturingLambda() Const ilSource = " .class public auto ansi C extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method public instance void M() cil managed { ldnull throw } .method private specialname static int32 _Lambda$__1() cil managed { ldnull throw } } // end of class C " Dim ilModule = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource) Dim runtime = CreateRuntimeInstance(ilModule, {MscorlibRef}) Dim context = CreateMethodContext(runtime, "C._Lambda$__1") VerifyNoMe(context) End Sub <WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")> <WorkItem(1069554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069554")> <Fact> Public Sub LambdaLocations_HasThis() Const source = " Imports System Class C Private _toBeCaptured As Integer Private _f As Integer = (Function(x) (Function() _toBeCaptured + x + 1)() + 1)(1) Public Sub New() Dim l As Integer = (Function(x) (Function() _toBeCaptured + x + 2)() + 1)(1) End Sub Protected Overrides Sub Finalize() Dim l As Integer = (Function(x) (Function() _toBeCaptured + x + 3)() + 1)(1) End Sub Public Property P As Integer Get Return (Function(x) (Function() _toBeCaptured + x + 4)() + 1)(1) End Get Set(value As Integer) value = (Function(x) (Function() _toBeCaptured + x + 5)() + 1)(1) End Set End Property Public Custom Event E As Action AddHandler(value As Action) Dim l As Integer = (Function(x) (Function() _toBeCaptured + x + 6)() + 1)(1) End AddHandler RemoveHandler(value As Action) Dim l As Integer = (Function(x) (Function() _toBeCaptured + x + 7)() + 1)(1) End RemoveHandler RaiseEvent() Dim l As Integer = (Function(x) (Function() _toBeCaptured + x + 8)() + 1)(1) End RaiseEvent End Event End Class " Const expectedILTemplate = " {{ // Code size 7 (0x7) .maxstack 1 .locals init (Object V_0) IL_0000: ldarg.0 IL_0001: ldfld ""C.{0}.$VB$Me As C"" IL_0006: ret }} " Dim comp = CreateEmptyCompilationWithReferences({VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef, MsvbRef}, TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim compOptions = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All) Dim dummyComp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences((<Compilation/>), {comp.EmitToImageReference()}, compOptions) Dim typeC = dummyComp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim displayClassTypes = typeC.GetMembers().OfType(Of NamedTypeSymbol)() Assert.True(displayClassTypes.Any()) For Each displayClassType In displayClassTypes Dim displayClassName = displayClassType.Name Assert.True(displayClassName.StartsWith(StringConstants.DisplayClassPrefix, StringComparison.Ordinal)) For Each displayClassMethod In displayClassType.GetMembers().OfType(Of MethodSymbol)().Where(AddressOf IsLambda) Dim lambdaMethodName = String.Format("C.{0}.{1}", displayClassName, displayClassMethod.Name) Dim context = CreateMethodContext(runtime, lambdaMethodName) Dim expectedIL = String.Format(expectedILTemplate, displayClassName) VerifyHasMe(context, "C", expectedIL) Next Next End Sub) End Sub <WorkItem(1069554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069554")> <Fact> Public Sub LambdaLocations_NoThis() Const source = " Imports System Module M Private _f As Integer = (Function(x) (Function() x + 1)() + 1)(1) Sub New() Dim l As Integer = (Function(x) (Function() x + 2)() + 1)(1) End Sub Public Property P As Integer Get Return (Function(x) (Function() x + 3)() + 1)(1) End Get Set(value As Integer) value = (Function(x) (Function() x + 4)() + 1)(1) End Set End Property Public Custom Event E As Action AddHandler(value As Action) Dim l As Integer = (Function(x) (Function() x + 5)() + 1)(1) End AddHandler RemoveHandler(value As Action) Dim l As Integer = (Function(x) (Function() x + 6)() + 1)(1) End RemoveHandler RaiseEvent() Dim l As Integer = (Function(x) (Function() x + 7)() + 1)(1) End RaiseEvent End Event End Module " Dim comp = CreateEmptyCompilationWithReferences({VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef, MsvbRef}, TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim dummyComp As VisualBasicCompilation = MakeDummyCompilation(comp) Dim typeC = dummyComp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("M") Dim displayClassTypes = typeC.GetMembers().OfType(Of NamedTypeSymbol)() Assert.True(displayClassTypes.Any()) For Each displayClassType In displayClassTypes Dim displayClassName = displayClassType.Name Assert.True(displayClassName.StartsWith(StringConstants.DisplayClassPrefix, StringComparison.Ordinal)) For Each displayClassMethod In displayClassType.GetMembers().OfType(Of MethodSymbol)().Where(AddressOf IsLambda) Dim lambdaMethodName = String.Format("M.{0}.{1}", displayClassName, displayClassMethod.Name) Dim context = CreateMethodContext(runtime, lambdaMethodName) VerifyNoMe(context) Next Next End Sub) End Sub Private Sub VerifyHasMe(source As String, moveNextMethodName As String, expectedType As String, expectedIL As String) Dim sourceCompilation = CreateEmptyCompilationWithReferences( {VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929}, TestOptions.DebugDll) WithRuntimeInstance(sourceCompilation, Sub(runtime) VerifyHasMe(CreateMethodContext(runtime, moveNextMethodName), expectedType, expectedIL) End Sub) ' Now recompile and test CompileExpression with optimized code. WithRuntimeInstance(sourceCompilation.WithOptions(sourceCompilation.Options.WithOptimizationLevel(OptimizationLevel.Release)), Sub(runtime) ' In VB, "Me" is never optimized away. VerifyHasMe(CreateMethodContext(runtime, moveNextMethodName), expectedType, expectedIL:=Nothing) End Sub) End Sub Private Sub VerifyHasMe(context As EvaluationContext, expectedType As String, expectedIL As String) Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance() Dim typeName As String = Nothing Dim testData As New CompilationTestData() Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData) Assert.NotNull(assembly) Assert.NotEqual(0, assembly.Count) Dim localAndMethod = locals.Single(Function(l) l.LocalName = "Me") Dim methods = testData.GetMethodsByName() If expectedIL IsNot Nothing Then VerifyMethodData(methods.Single(Function(m) m.Key.Contains(localAndMethod.MethodName)).Value, expectedType, expectedIL) End If locals.Free() Dim errorMessage As String = Nothing testData = New CompilationTestData() context.CompileExpression("Me", errorMessage, testData) Assert.Null(errorMessage) If expectedIL IsNot Nothing Then VerifyMethodData(methods.Single(Function(m) m.Key.Contains("<>m0")).Value, expectedType, expectedIL) End If End Sub Private Shared Sub VerifyMethodData(methodData As CompilationTestData.MethodData, expectedType As String, expectedIL As String) methodData.VerifyIL(expectedIL) Dim method As MethodSymbol = DirectCast(methodData.Method, MethodSymbol) VerifyTypeParameters(method) Assert.Equal(expectedType, method.ReturnType.ToTestDisplayString()) End Sub Private Sub VerifyNoMe(source As String, moveNextMethodName As String) Dim comp = CreateEmptyCompilationWithReferences( {VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929}, TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) VerifyNoMe(CreateMethodContext(runtime, moveNextMethodName)) End Sub) End Sub Private Shared Sub VerifyNoMe(context As EvaluationContext) Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance() Dim typeName As String = Nothing Dim testData As New CompilationTestData() Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData) Assert.NotNull(assembly) AssertEx.None(locals, Function(l) l.LocalName.Contains("Me")) locals.Free() Dim errorMessage As String = Nothing testData = New CompilationTestData() context.CompileExpression("Me", errorMessage, testData) Assert.Contains(errorMessage, { "error BC32001: 'Me' is not valid within a Module.", "error BC30043: 'Me' is valid only within an instance method." }) testData = New CompilationTestData() context.CompileExpression("MyBase.ToString()", errorMessage, testData) Assert.Contains(errorMessage, { "error BC32001: 'MyBase' is not valid within a Module.", "error BC30043: 'MyBase' is valid only within an instance method." }) testData = New CompilationTestData() context.CompileExpression("MyClass.ToString()", errorMessage, testData) Assert.Contains(errorMessage, { "error BC30470: 'MyClass' cannot be used outside of a class.", "error BC32001: 'MyClass' is not valid within a Module.", "error BC30043: 'MyClass' is valid only within an instance method." }) End Sub <WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")> <Fact> Public Sub InstanceMembersInIterator() Const source = " Class C Private x As Object Iterator Function F() As System.Collections.IEnumerable Yield Me.x End Function End Class " Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.VB$StateMachine_2_F.MoveNext") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("Me.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 12 (0xc) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_2_F.$VB$Me As C"" IL_0006: ldfld ""C.x As Object"" IL_000b: ret } ") End Sub) End Sub <WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")> <Fact> Public Sub InstanceMembersInLambda() Const source = " Class C Private x As Object Sub F() Dim a As System.Action = Sub() Me.x.ToString() a() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C._Lambda$__2-0") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("Me.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C.x As Object"" IL_0006: ret } ") End Sub) End Sub <WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")> <Fact> Public Sub InstanceMembersInAsync() Const source = " Imports System Imports System.Threading.Tasks Class C Private x As Object Async Function F() As Task Await Console.Out.WriteLineAsync(Me.ToString()) End Function End Class " Dim comp = CreateEmptyCompilationWithReferences( {VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929}, TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.VB$StateMachine_2_F.MoveNext") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("Me.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 12 (0xc) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.VB$StateMachine_2_F V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_2_F.$VB$Me As C"" IL_0006: ldfld ""C.x As Object"" IL_000b: ret } ") End Sub) End Sub <Fact> Public Sub BaseMembersInIterator() Const source = " Class Base Protected x As Integer End Class Class Derived : Inherits Base Shadows Protected x As Object Iterator Function F() As System.Collections.IEnumerable Yield MyBase.x End Function End Class " Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "Derived.VB$StateMachine_2_F.MoveNext") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("MyBase.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 12 (0xc) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""Derived.VB$StateMachine_2_F.$VB$Me As Derived"" IL_0006: ldfld ""Base.x As Integer"" IL_000b: ret } ") End Sub) End Sub <Fact> Public Sub BaseMembersInAsync() Const source = " Imports System Imports System.Threading.Tasks Class Base Protected x As Integer End Class Class Derived : Inherits Base Shadows Protected x As Object Async Function F() As Task Await Console.Out.WriteLineAsync(Me.ToString()) End Function End Class " Dim comp = CreateEmptyCompilationWithReferences( {VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929}, TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "Derived.VB$StateMachine_2_F.MoveNext") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("MyBase.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 12 (0xc) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, Derived.VB$StateMachine_2_F V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""Derived.VB$StateMachine_2_F.$VB$Me As Derived"" IL_0006: ldfld ""Base.x As Integer"" IL_000b: ret } ") End Sub) End Sub <Fact> Public Sub BaseMembersInLambda() Const source = " Class Base Protected x As Integer End Class Class Derived : Inherits Base Shadows Protected x As Object Sub F() Dim a As System.Action = Sub() Me.x.ToString() a() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "Derived._Lambda$__2-0") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("MyBase.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""Base.x As Integer"" IL_0006: ret } ") End Sub) End Sub <Fact> Public Sub IteratorOverloading_Parameters1() Const source = " Imports System.Collections Public Class C Public Iterator Function M() As IEnumerable Yield Me End Function Public Function M(x As Integer) As IEnumerable Return Nothing End Function End Class " CheckIteratorOverloading(source, Function(m) m.ParameterCount = 0) End Sub <Fact> Public Sub IteratorOverloading_Parameters2() ' Same as above, but declarations reversed. Const source = " Imports System.Collections Public Class C Public Function M(x As Integer) As IEnumerable Return Nothing End Function Public Iterator Function M() As IEnumerable Yield Me End Function End Class " ' NB: We pick the wrong overload, but it doesn't matter because ' the methods have the same characteristics. ' Also, we don't require this behavior, we're just documenting it. CheckIteratorOverloading(source, Function(m) m.ParameterCount = 1) End Sub <Fact> Public Sub IteratorOverloading_Sharedness() Const source = " Imports System.Collections Public Class C Public Shared Function M(x As Integer) As IEnumerable Return Nothing End Function ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M() As IEnumerable Yield Me End Function End Class " CheckIteratorOverloading(source, Function(m) Not m.IsShared) End Sub <Fact> Public Sub IteratorOverloading_MustOverrideness() Const source = " Imports System.Collections Public MustInherit Class C Public MustOverride Function M(x As Integer) As IEnumerable ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M() As IEnumerable Yield Me End Function End Class " CheckIteratorOverloading(source, Function(m) Not m.IsMustOverride) End Sub <Fact> Public Sub IteratorOverloading_Arity1() Const source = " Imports System.Collections Public Class C Public Function M(Of T)(x As Integer) As IEnumerable Return Nothing End Function ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M() As IEnumerable Yield Me End Function End Class " CheckIteratorOverloading(source, Function(m) m.Arity = 0) End Sub <Fact> Public Sub IteratorOverloading_Arity2() Const source = " Imports System.Collections Public Class C Public Function M(x As Integer) As IEnumerable Return Nothing End Function ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M(Of T)() As IEnumerable Yield Me End Function End Class " CheckIteratorOverloading(source, Function(m) m.Arity = 1) End Sub <Fact> Public Sub IteratorOverloading_Constraints1() Const source = " Imports System.Collections Public Class C Public Function M(Of T As Structure)(x As Integer) As IEnumerable Return Nothing End Function ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M(Of T As Class)() As IEnumerable Yield Me End Function End Class " CheckIteratorOverloading(source, Function(m) m.TypeParameters.Single().HasReferenceTypeConstraint) End Sub <Fact> Public Sub IteratorOverloading_Constraints2() Const source = " Imports System.Collections Imports System.Collections.Generic Public Class C ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M(Of T As IEnumerable(Of U), U As Class)() As IEnumerable Yield Me End Function End Class " ' NOTE: this isn't the feature we're switching on, but it is a convenient differentiator. CheckIteratorOverloading(source, Function(m) m.ParameterCount = 0) End Sub <Fact> Public Sub LambdaOverloading_NonGeneric() Const source = " Public Class C Public Sub M(x As Integer) Dim a As System.Action = Sub() x.ToString() End Sub End Class " ' Note: We're picking the first method with the correct generic arity, etc. CheckLambdaOverloading(source, Function(m) m.MethodKind = MethodKind.Constructor) End Sub <Fact> Public Sub LambdaOverloading_Generic() Const source = " Public Class C Public Sub M(Of T)(x As Integer) Dim a As System.Action = Sub() x.ToString() End Sub End Class " CheckLambdaOverloading(source, Function(m) m.Arity = 1) End Sub Private Shared Sub CheckIteratorOverloading(source As String, isDesiredOverload As Func(Of MethodSymbol, Boolean)) CheckOverloading( source, Function(m) m.Name = "M" AndAlso isDesiredOverload(m), Function(originalType) Dim stateMachineType = originalType.GetMembers().OfType(Of NamedTypeSymbol).Single(Function(t) t.Name.StartsWith(StringConstants.StateMachineTypeNamePrefix, StringComparison.Ordinal)) Return stateMachineType.GetMember(Of MethodSymbol)("MoveNext") End Function) End Sub Private Shared Sub CheckLambdaOverloading(source As String, isDesiredOverload As Func(Of MethodSymbol, Boolean)) CheckOverloading( source, isDesiredOverload, Function(originalType) Dim displayClass As NamedTypeSymbol = originalType.GetMembers().OfType(Of NamedTypeSymbol).Single(Function(t) t.Name.StartsWith(StringConstants.DisplayClassPrefix, StringComparison.Ordinal)) Return displayClass.GetMembers().OfType(Of MethodSymbol).Single(AddressOf IsLambda) End Function) End Sub Private Shared Function IsLambda(method As MethodSymbol) As Boolean Return method.Name.StartsWith(StringConstants.LambdaMethodNamePrefix, StringComparison.Ordinal) End Function Private Shared Sub CheckOverloading(source As String, isDesiredOverload As Func(Of MethodSymbol, Boolean), getSynthesizedMethod As Func(Of NamedTypeSymbol, MethodSymbol)) Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim dummyComp = MakeDummyCompilation(comp) Dim originalType = dummyComp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim desiredMethod = originalType.GetMembers().OfType(Of MethodSymbol).Single(isDesiredOverload) Dim synthesizedMethod As MethodSymbol = getSynthesizedMethod(originalType) Dim guessedMethod = CompilationContext.GetSubstitutedSourceMethod(synthesizedMethod, sourceMethodMustBeInstance:=True) Assert.Equal(desiredMethod, guessedMethod.OriginalDefinition) End Sub Private Shared Function MakeDummyCompilation(comp As VisualBasicCompilation) As VisualBasicCompilation Dim compOptions = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All) Return CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(<Compilation/>, {comp.EmitToImageReference()}, compOptions) End Function End Class End Namespace
OmarTawfik/roslyn
src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/HoistedMeTests.vb
Visual Basic
apache-2.0
39,059
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. '----------------------------------------------------------------------------- ' Contains the definition of the Scanner, which produces tokens from text '----------------------------------------------------------------------------- Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Partial Friend Class Scanner ''' <summary> ''' page represents a cached array of chars. ''' </summary> Private Class Page ''' <summary> ''' where page maps in the stream. Used to validate pages ''' </summary> Friend _pageStart As Integer ''' <summary> ''' page's buffer ''' </summary> Friend ReadOnly _arr As Char() Private ReadOnly _pool As ObjectPool(Of Page) Private Sub New(pool As ObjectPool(Of Page)) Me._pageStart = -1 Me._arr = New Char(s_PAGE_SIZE - 1) {} Me._pool = pool End Sub Friend Sub Free() Me._pageStart = -1 _pool.Free(Me) End Sub Private Shared ReadOnly s_poolInstance As ObjectPool(Of Page) = CreatePool() Private Shared Function CreatePool() As ObjectPool(Of Page) Dim pool As ObjectPool(Of Page) = Nothing pool = New ObjectPool(Of Page)(Function() New Page(pool), 128) Return pool End Function Friend Shared Function GetInstance() As Page Dim instance = s_poolInstance.Allocate() Return instance End Function End Class ''' <summary> ''' current page we are reading. ''' </summary> Private _curPage As Page Private ReadOnly _pages(s_PAGE_NUM - 1) As Page Private Const s_PAGE_NUM_SHIFT = 2 Private Const s_PAGE_NUM = CInt(2 ^ s_PAGE_NUM_SHIFT) Private Const s_PAGE_NUM_MASK = s_PAGE_NUM - 1 Private Const s_PAGE_SHIFT = 11 Private Const s_PAGE_SIZE = CInt(2 ^ s_PAGE_SHIFT) Private Const s_PAGE_MASK = s_PAGE_SIZE - 1 Private Const s_NOT_PAGE_MASK = Not s_PAGE_MASK Private ReadOnly _buffer As SourceText Private ReadOnly _bufferLen As Integer ' created on demand. we may not need it Private _builder As StringBuilder ''' <summary> ''' gets a page for the position. ''' will initialize it if we have cache miss ''' </summary> Private Function GetPage(position As Integer) As Page Dim pageNum = (position >> s_PAGE_SHIFT) And s_PAGE_NUM_MASK Dim p = _pages(pageNum) Dim pageStart = position And s_NOT_PAGE_MASK If p Is Nothing Then p = Page.GetInstance _pages(pageNum) = p End If If p._pageStart <> pageStart Then _buffer.CopyTo(pageStart, p._arr, 0, Math.Min(_bufferLen - pageStart, s_PAGE_SIZE)) p._pageStart = pageStart End If _curPage = p Return p End Function ' PERF CRITICAL Private Function Peek(skip As Integer) As Char Debug.Assert(CanGet(skip)) Debug.Assert(skip >= -MaxCharsLookBehind) Dim position = _lineBufferOffset Dim page = _curPage position += skip Dim ch = page._arr(position And s_PAGE_MASK) Dim start = page._pageStart Dim expectedStart = position And s_NOT_PAGE_MASK If start <> expectedStart Then page = GetPage(position) ch = page._arr(position And s_PAGE_MASK) End If Return ch End Function ' PERF CRITICAL Friend Function Peek() As Char Dim page = _curPage Dim position = _lineBufferOffset Dim ch = page._arr(position And s_PAGE_MASK) Dim start = page._pageStart Dim expectedStart = position And s_NOT_PAGE_MASK If start <> expectedStart Then page = GetPage(position) ch = page._arr(position And s_PAGE_MASK) End If Return ch End Function Friend Function GetChar() As String Return Intern(Peek()) End Function Friend Function GetText(start As Integer, length As Integer) As String Dim page = _curPage Dim offsetInPage = start And s_PAGE_MASK If page._pageStart = (start And s_NOT_PAGE_MASK) AndAlso offsetInPage + length < s_PAGE_SIZE Then Return Intern(page._arr, offsetInPage, length) End If Return GetTextSlow(start, length) End Function Friend Function GetTextNotInterned(start As Integer, length As Integer) As String Dim page = _curPage Dim offsetInPage = start And s_PAGE_MASK If page._pageStart = (start And s_NOT_PAGE_MASK) AndAlso offsetInPage + length < s_PAGE_SIZE Then Dim arr() As Char = page._arr ' Always intern CR+LF since it occurs so frequently If length = 2 AndAlso arr(offsetInPage) = ChrW(13) AndAlso arr(offsetInPage + 1) = ChrW(10) Then Return vbCrLf End If Return New String(arr, offsetInPage, length) End If Return GetTextSlow(start, length, suppressInterning:=True) End Function Private Function GetTextSlow(start As Integer, length As Integer, Optional suppressInterning As Boolean = False) As String Dim textOffset = start And s_PAGE_MASK Dim page = GetPage(start) If textOffset + length < s_PAGE_SIZE Then If suppressInterning Then Return New String(page._arr, textOffset, length) Else Return Intern(page._arr, textOffset, length) End If End If ' make a string builder that is big enough, but not too big If _builder Is Nothing Then _builder = New StringBuilder(Math.Min(length, 1024)) End If Dim cnt = Math.Min(length, s_PAGE_SIZE - textOffset) _builder.Append(page._arr, textOffset, cnt) Dim dst = cnt length -= cnt start += cnt Do page = GetPage(start) cnt = Math.Min(length, s_PAGE_SIZE) _builder.Append(page._arr, 0, cnt) dst += cnt length -= cnt start += cnt Loop While length > 0 Dim result As String If suppressInterning Then result = _builder.ToString Else result = _stringTable.Add(_builder) End If If result.Length < 1024 Then _builder.Clear() Else _builder = Nothing End If Return result End Function End Class End Namespace
v-codeel/roslyn
src/Compilers/VisualBasic/Portable/Scanner/ScannerBuffer.vb
Visual Basic
apache-2.0
7,560
' 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.ExtractMethod Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod Partial Friend Class VisualBasicMethodExtractor Partial Private Class VisualBasicCodeGenerator Private Class SingleStatementCodeGenerator Inherits VisualBasicCodeGenerator Public Sub New(insertionPoint As InsertionPoint, selectionResult As SelectionResult, analyzerResult As AnalyzerResult) MyBase.New(insertionPoint, selectionResult, analyzerResult) End Sub Public Shared Function IsExtractMethodOnSingleStatement(code As SelectionResult) As Boolean Dim result = DirectCast(code, VisualBasicSelectionResult) Dim firstStatement = result.GetFirstStatement() Dim lastStatement = result.GetLastStatement() Return firstStatement Is lastStatement OrElse firstStatement.Span.Contains(lastStatement.Span) End Function Protected Overrides Function CreateMethodName() As SyntaxToken ' change this to more smarter one. Dim semanticModel = CType(SemanticDocument.SemanticModel, SemanticModel) Dim nameGenerator = New UniqueNameGenerator(semanticModel) Dim containingScope = VBSelectionResult.GetContainingScope() Return SyntaxFactory.Identifier( nameGenerator.CreateUniqueMethodName(containingScope, "NewMethod")) End Function Protected Overrides Function GetInitialStatementsForMethodDefinitions() As IEnumerable(Of StatementSyntax) Contract.ThrowIfFalse(IsExtractMethodOnSingleStatement(VBSelectionResult)) Return SpecializedCollections.SingletonEnumerable(Of StatementSyntax)(VBSelectionResult.GetFirstStatement()) End Function Protected Overrides Function GetOutermostCallSiteContainerToProcess(cancellationToken As CancellationToken) As SyntaxNode Dim callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken) If callSiteContainer IsNot Nothing Then Return callSiteContainer Else Dim first = VBSelectionResult.GetFirstStatement() Return first.Parent End If End Function Protected Overrides Function GetFirstStatementOrInitializerSelectedAtCallSite() As StatementSyntax Return VBSelectionResult.GetFirstStatement() End Function Protected Overrides Function GetLastStatementOrInitializerSelectedAtCallSite() As StatementSyntax ' it is a single statement case. either first statement is same as last statement or ' last statement belongs (embedded statement) to the first statement. Return VBSelectionResult.GetFirstStatement() End Function Protected Overrides Function GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(callSiteAnnotation As SyntaxAnnotation, cancellationToken As CancellationToken) As Task(Of StatementSyntax) Return Task.FromResult(GetStatementContainingInvocationToExtractedMethodWorker().WithAdditionalAnnotations(callSiteAnnotation)) End Function End Class End Class End Class End Namespace
v-codeel/roslyn
src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.VisualBasicCodeGenerator.SingleStatementCodeGenerator.vb
Visual Basic
apache-2.0
3,869