code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Expressions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions Public Class CastOperatorsKeywordRecommenderTests Private ReadOnly Property AllTypeConversionOperatorKeywords As String() Get Dim keywords As New List(Of String) From {"CType", "DirectCast", "TryCast"} For Each k In CastOperatorsKeywordRecommender.PredefinedKeywordList keywords.Add(SyntaxFacts.GetText(k)) Next Return keywords.ToArray() End Get End Property <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub DirectCastHelpText() VerifyRecommendationDescriptionTextIs(<MethodBody>Return |</MethodBody>, "DirectCast", $"{VBFeaturesResources.DirectcastFunction} {IntroducesTypeConversion} DirectCast({Expression1}, {VBWorkspaceResources.Typename}) As {Result}") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub TryCastHelpText() VerifyRecommendationDescriptionTextIs(<MethodBody>Return |</MethodBody>, "TryCast", $"{VBFeaturesResources.TrycastFunction} {IntroducesSafeTypeConversion} TryCast({Expression1}, {VBWorkspaceResources.Typename}) As {Result}") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CTypeHelpText() VerifyRecommendationDescriptionTextIs(<MethodBody>Return |</MethodBody>, "CType", $"{VBFeaturesResources.CtypeFunction} {ReturnsConvertResult} CType({Expression1}, {VBWorkspaceResources.Typename}) As {Result}") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CBoolHelpText() VerifyRecommendationDescriptionTextIs(<MethodBody>Return |</MethodBody>, "CBool", $"{String.Format(VBFeaturesResources.Function1, "CBool")} {String.Format(ConvertsToDataType, "Boolean")} CBool({Expression1}) As Boolean") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInClassDeclaration() VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllInStatement() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterReturn() VerifyRecommendationsContain(<MethodBody>Return |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterArgument1() VerifyRecommendationsContain(<MethodBody>Foo(|</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterArgument2() VerifyRecommendationsContain(<MethodBody>Foo(bar, |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterBinaryExpression() VerifyRecommendationsContain(<MethodBody>Foo(bar + |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterNot() VerifyRecommendationsContain(<MethodBody>Foo(Not |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterTypeOf() VerifyRecommendationsContain(<MethodBody>If TypeOf |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterDoWhile() VerifyRecommendationsContain(<MethodBody>Do While |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterDoUntil() VerifyRecommendationsContain(<MethodBody>Do Until |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterLoopWhile() VerifyRecommendationsContain(<MethodBody> Do Loop While |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterLoopUntil() VerifyRecommendationsContain(<MethodBody> Do Loop Until |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterIf() VerifyRecommendationsContain(<MethodBody>If |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterElseIf() VerifyRecommendationsContain(<MethodBody>ElseIf |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterElseSpaceIf() VerifyRecommendationsContain(<MethodBody>Else If |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterError() VerifyRecommendationsContain(<MethodBody>Error |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterThrow() VerifyRecommendationsContain(<MethodBody>Throw |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterInitializer() VerifyRecommendationsContain(<MethodBody>Dim x = |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterArrayInitializerSquiggle() VerifyRecommendationsContain(<MethodBody>Dim x = {|</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterArrayInitializerComma() VerifyRecommendationsContain(<MethodBody>Dim x = {0, |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <WorkItem(543270)> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInDelegateCreation() Dim code = <File> Module Program Sub Main(args As String()) Dim f1 As New Foo2( | End Sub Delegate Sub Foo2() Function Bar2() As Object Return Nothing End Function End Module </File> VerifyRecommendationsMissing(code, AllTypeConversionOperatorKeywords) End Sub End Class End Namespace
hanu412/roslyn
src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/CastOperatorsKeywordRecommenderTests.vb
Visual Basic
apache-2.0
7,659
Imports System.ComponentModel Imports System.Drawing Imports System.Windows.Forms Imports Telerik.Reporting Imports Telerik.Reporting.Drawing Partial Public Class RepBalanceComprobacionAcumuladoNivelMayor Inherits Telerik.Reporting.Report Public Sub New() InitializeComponent() End Sub End Class
crackper/SistFoncreagro
SistFoncreagro.Report/RepBalanceComprobacionAcumuladoNivelMayor.vb
Visual Basic
mit
316
Imports System Imports System.Reflection Imports System.Runtime.InteropServices Imports System.Globalization Imports System.Resources Imports System.Windows ' 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("EditorPlus.UI")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("EditorPlus.UI")> <Assembly: AssemblyCopyright("Copyright @ 2016~2020")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(false)> 'In order to begin building localizable applications, set '<UICulture>CultureYouAreCodingWith</UICulture> in your .vbproj file 'inside a <PropertyGroup>. For example, if you are using US english 'in your source files, set the <UICulture> to "en-US". Then uncomment the 'NeutralResourceLanguage attribute below. Update the "en-US" in the line 'below to match the UICulture setting in the project file. '<Assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)> 'The ThemeInfo attribute describes where any theme specific and generic resource dictionaries can be found. '1st parameter: where theme specific resource dictionaries are located '(used if a resource is not found in the page, ' or application resource dictionaries) '2nd parameter: where the generic resource dictionary is located '(used if a resource is not found in the page, 'app, and any theme specific resource dictionaries) <Assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("d9cbd2cd-a2b0-4b59-8193-71b08ec43ecf")> ' 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.9.6")> '<Assembly: AssemblyFileVersion("1.0.0.0")>
surviveplus/EditorPlus
office2013/EditorPlus.UI/EditorPlus.UI/My Project/AssemblyInfo.vb
Visual Basic
mit
2,256
Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim Numero As String = "" For i As Integer = 5 To 100 Numero += i.ToString() & ", " MessageBox.Show(i) i = i + 4 Next TextBox1.Text = Numero.ToString End Sub End Class
rafael25/poe-unitec
Practica3/Practica3/Form1.vb
Visual Basic
mit
365
 Partial Class Master_Default Inherits System.Web.UI.Page Dim acs As New HelperClass Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load End Sub End Class
prashantkakde31/Catalyst
admin/SRC/Catalyst/CatalystClientUI/Master/Default.aspx.vb
Visual Basic
mit
205
#Region "License" ' The MIT License (MIT) ' ' Copyright (c) 2017 Richard L King (TradeWright Software Systems) ' ' Permission is hereby granted, free of charge, to any person obtaining a copy ' of this software and associated documentation files (the "Software"), to deal ' in the Software without restriction, including without limitation the rights ' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ' copies of the Software, and to permit persons to whom the Software is ' furnished to do so, subject to the following conditions: ' ' The above copyright notice and this permission notice shall be included in all ' copies or substantial portions of the Software. ' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ' SOFTWARE. #End Region <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> Partial Class ContractSelector Inherits System.Windows.Forms.UserControl 'UserControl overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(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 DataGridViewCellStyle1 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle Dim DataGridViewCellStyle2 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle Dim DataGridViewCellStyle3 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle Dim DataGridViewCellStyle4 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle Dim DataGridViewCellStyle5 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle Me.ContractsGrid = New System.Windows.Forms.DataGridView Me.Column1 = New System.Windows.Forms.DataGridViewTextBoxColumn Me.Column2 = New System.Windows.Forms.DataGridViewTextBoxColumn Me.Column3 = New System.Windows.Forms.DataGridViewTextBoxColumn Me.Column4 = New System.Windows.Forms.DataGridViewTextBoxColumn Me.Column5 = New System.Windows.Forms.DataGridViewTextBoxColumn CType(Me.ContractsGrid, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'ContractsGrid ' Me.ContractsGrid.AllowUserToAddRows = False Me.ContractsGrid.AllowUserToDeleteRows = False DataGridViewCellStyle1.BackColor = System.Drawing.Color.White Me.ContractsGrid.AlternatingRowsDefaultCellStyle = DataGridViewCellStyle1 Me.ContractsGrid.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells Me.ContractsGrid.BackgroundColor = System.Drawing.Color.White Me.ContractsGrid.BorderStyle = System.Windows.Forms.BorderStyle.None Me.ContractsGrid.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None DataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Control DataGridViewCellStyle2.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText DataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText DataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.[True] Me.ContractsGrid.ColumnHeadersDefaultCellStyle = DataGridViewCellStyle2 Me.ContractsGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize Me.ContractsGrid.ColumnHeadersVisible = False Me.ContractsGrid.Columns.AddRange(New System.Windows.Forms.DataGridViewColumn() {Me.Column1, Me.Column2, Me.Column3, Me.Column4, Me.Column5}) DataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Window DataGridViewCellStyle3.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.ControlText DataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText DataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.[False] Me.ContractsGrid.DefaultCellStyle = DataGridViewCellStyle3 Me.ContractsGrid.Dock = System.Windows.Forms.DockStyle.Fill Me.ContractsGrid.Location = New System.Drawing.Point(0, 0) Me.ContractsGrid.Name = "ContractsGrid" Me.ContractsGrid.ReadOnly = True Me.ContractsGrid.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None DataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle4.BackColor = System.Drawing.SystemColors.Control DataGridViewCellStyle4.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle4.ForeColor = System.Drawing.SystemColors.WindowText DataGridViewCellStyle4.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle4.SelectionForeColor = System.Drawing.SystemColors.HighlightText DataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.[True] Me.ContractsGrid.RowHeadersDefaultCellStyle = DataGridViewCellStyle4 Me.ContractsGrid.RowHeadersVisible = False DataGridViewCellStyle5.BackColor = System.Drawing.Color.WhiteSmoke Me.ContractsGrid.RowsDefaultCellStyle = DataGridViewCellStyle5 Me.ContractsGrid.RowTemplate.ReadOnly = True Me.ContractsGrid.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect Me.ContractsGrid.Size = New System.Drawing.Size(374, 206) Me.ContractsGrid.TabIndex = 0 ' 'Column1 ' Me.Column1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells Me.Column1.HeaderText = "Column1" Me.Column1.Name = "Column1" Me.Column1.ReadOnly = True Me.Column1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable Me.Column1.Width = 5 ' 'Column2 ' Me.Column2.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells Me.Column2.HeaderText = "Column2" Me.Column2.Name = "Column2" Me.Column2.ReadOnly = True Me.Column2.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable Me.Column2.Width = 5 ' 'Column3 ' Me.Column3.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells Me.Column3.HeaderText = "Column3" Me.Column3.Name = "Column3" Me.Column3.ReadOnly = True Me.Column3.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable Me.Column3.Width = 5 ' 'Column4 ' Me.Column4.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells Me.Column4.HeaderText = "Column4" Me.Column4.Name = "Column4" Me.Column4.ReadOnly = True Me.Column4.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable Me.Column4.Width = 5 ' 'Column5 ' Me.Column5.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill Me.Column5.HeaderText = "Column5" Me.Column5.Name = "Column5" Me.Column5.ReadOnly = True Me.Column5.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable ' 'ContractSelector ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.Controls.Add(Me.ContractsGrid) Me.Name = "ContractSelector" Me.Size = New System.Drawing.Size(374, 206) CType(Me.ContractsGrid, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) End Sub Friend WithEvents ContractsGrid As System.Windows.Forms.DataGridView Friend WithEvents Column1 As System.Windows.Forms.DataGridViewTextBoxColumn Friend WithEvents Column2 As System.Windows.Forms.DataGridViewTextBoxColumn Friend WithEvents Column3 As System.Windows.Forms.DataGridViewTextBoxColumn Friend WithEvents Column4 As System.Windows.Forms.DataGridViewTextBoxColumn Friend WithEvents Column5 As System.Windows.Forms.DataGridViewTextBoxColumn End Class
tradewright/tradebuild-platform.net
src/ContractsUI/ContractSelector.Designer.vb
Visual Basic
mit
10,143
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.34209 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My '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.FileRenamer.frmRenamer End Sub End Class End Namespace
PaulAnderson/FileRenamer
My Project/Application.Designer.vb
Visual Basic
mit
1,520
Imports Microsoft.VisualBasic Imports System.IO Imports Aspose.Words Imports Aspose.Words.Fields Public Class InsertNestedFields Public Shared Sub Run() ' The path to the documents directory. Dim dataDir As String = RunExamples.GetDataDir_WorkingWithFields() Dim doc As New Document() Dim builder As New DocumentBuilder(doc) ' Insert a few page breaks (just for testing) For i As Integer = 0 To 4 builder.InsertBreak(BreakType.PageBreak) Next i ' Move the DocumentBuilder cursor into the primary footer. builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary) ' We want to insert a field like this: ' { IF {PAGE} <> {NUMPAGES} "See Next Page" "Last Page" } Dim field As Field = builder.InsertField("IF ") builder.MoveTo(field.Separator) builder.InsertField("PAGE") builder.Write(" <> ") builder.InsertField("NUMPAGES") builder.Write(" ""See Next Page"" ""Last Page"" ") ' Finally update the outer field to recalcaluate the final value. Doing this will automatically update ' the inner fields at the same time. field.Update() dataDir = dataDir & "InsertNestedFields_out_.docx" doc.Save(dataDir) Console.WriteLine(vbNewLine & "Inserted nested fields in the document successfully." & vbNewLine & "File saved at " + dataDir) End Sub End Class
assadvirgo/Aspose_Words_NET
Examples/VisualBasic/Programming-Documents/Fields/InsertNestedFields.vb
Visual Basic
mit
1,457
Namespace Commands ''' <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:45:54</generator-date> ''' <generator-functions>1</generator-functions> ''' <generator-source>Leviathan\_Commands\Generated\CommandInterrogated.tt</generator-source> ''' <generator-template>Text-Templates\Classes\VB_Object.tt</generator-template> ''' <generator-version>1</generator-version> <System.CodeDom.Compiler.GeneratedCode("Leviathan\_Commands\Generated\CommandInterrogated.tt", "1")> _ Partial Public Class CommandInterrogated Inherits System.Object #Region " Public Constructors " ''' <summary>Default Constructor</summary> Public Sub New() MyBase.New() End Sub ''' <summary>Parametered Constructor (1 Parameters)</summary> Public Sub New( _ ByVal _Command As CommandInterrogatedClass _ ) MyBase.New() Command = _Command End Sub ''' <summary>Parametered Constructor (2 Parameters)</summary> Public Sub New( _ ByVal _Command As CommandInterrogatedClass, _ ByVal _CommandObject As System.Object _ ) MyBase.New() Command = _Command CommandObject = _CommandObject End Sub ''' <summary>Parametered Constructor (3 Parameters)</summary> Public Sub New( _ ByVal _Command As CommandInterrogatedClass, _ ByVal _CommandObject As System.Object, _ ByVal _MethodIndexes As System.Int32() _ ) MyBase.New() Command = _Command CommandObject = _CommandObject MethodIndexes = _MethodIndexes End Sub #End Region #Region " Public Constants " ''' <summary>Public Shared Reference to the Name of the Property: Command</summary> ''' <remarks></remarks> Public Const PROPERTY_COMMAND As String = "Command" ''' <summary>Public Shared Reference to the Name of the Property: CommandObject</summary> ''' <remarks></remarks> Public Const PROPERTY_COMMANDOBJECT As String = "CommandObject" ''' <summary>Public Shared Reference to the Name of the Property: MethodIndexes</summary> ''' <remarks></remarks> Public Const PROPERTY_METHODINDEXES As String = "MethodIndexes" #End Region #Region " Private Variables " ''' <summary>Private Data Storage Variable for Property: Command</summary> ''' <remarks></remarks> Private m_Command As CommandInterrogatedClass ''' <summary>Private Data Storage Variable for Property: CommandObject</summary> ''' <remarks></remarks> Private m_CommandObject As System.Object ''' <summary>Private Data Storage Variable for Property: MethodIndexes</summary> ''' <remarks></remarks> Private m_MethodIndexes As System.Int32() #End Region #Region " Public Properties " ''' <summary>Provides Access to the Property: Command</summary> ''' <remarks></remarks> Public Property Command() As CommandInterrogatedClass Get Return m_Command End Get Set(value As CommandInterrogatedClass) m_Command = value End Set End Property ''' <summary>Provides Access to the Property: CommandObject</summary> ''' <remarks></remarks> Public Property CommandObject() As System.Object Get Return m_CommandObject End Get Set(value As System.Object) m_CommandObject = value End Set End Property ''' <summary>Provides Access to the Property: MethodIndexes</summary> ''' <remarks></remarks> Public Property MethodIndexes() As System.Int32() Get Return m_MethodIndexes End Get Set(value As System.Int32()) m_MethodIndexes = value End Set End Property #End Region End Class End Namespace
thiscouldbejd/Leviathan
_Commands/Generated/CommandInterrogated.vb
Visual Basic
mit
3,710
Imports System.IO Imports System.IO.Ports Imports System.Collections.Queue Imports System.Net.Sockets Imports System.Net Imports System.Text Imports GrblPanel.My.Resources ' ' Useful serialport tips, #3 is important!!!! ' http://blogs.msdn.com/b/bclteam/archive/2006/10/10/top-5-serialport-tips-_5b00_kim-hamilton_5d00_.aspx ' Public Class GrblIF Public Enum ConnectionType IP Serial None End Enum ' A class to handle serial port list/open/close/read/write Private _commports As String() ' the comm ports available Private WithEvents _port As SerialPort ' Private _commport As String = "COM1" ' desired comm port Private _baudrate As Integer = 115200 ' active baudrate Private _connected As Boolean = False Private _client As New TcpClient() Private _remoteHost As IPAddress ' desired remote host Private _portNum As Integer = 0 ' remote port number Private _type As ConnectionType Private Delegate Sub _dataReceived() ' The inbound queue supports delegates to call when a line of data arrives Public Delegate Sub grblDataReceived(ByVal data As String) Private _recvDelegates As List(Of grblDataReceived) ' who should get called when a line arrives Public Sub New() _port = New SerialPort() _port.ReceivedBytesThreshold = 2 ' wait for this # of bytes to raise event _recvDelegates = New List(Of grblDataReceived) AddHandler serialDataEvent, AddressOf raiseAppSerialDataEvent End Sub ''' <summary> ''' Starts the connection to grbl, via IP or Serial (COM). Expects to have the needed properties set beforehand. ''' </summary> ''' <param name="typeIn">Specifies if we're connecting via IP or Serial. None as safety/exception case</param> ''' <returns>Returns True if the connection succeeded, false otherwise.</returns> Public Function Connect(typeIn As ConnectionType) As Boolean _type = typeIn Select Case _type Case ConnectionType.IP If _client.Connected Then Return False End If Try _client = New TcpClient() _client.Connect(_remoteHost, _portNum) Dim d As _dataReceived = AddressOf _client_DataReceived d.BeginInvoke(Nothing, Nothing) Catch ex As Exception Return False End Try _connected = True Return True Case ConnectionType.Serial If _port.IsOpen Then Return False End If _port.PortName = _commport _port.BaudRate = _baudrate _port.ReadTimeout = 5000 Try _port.Open() Catch ex As System.IO.IOException Return False Catch ex As System.UnauthorizedAccessException Return False End Try ' Reset the board _port.DtrEnable = True _port.DtrEnable = False _connected = True _client_ComReadData() ' Start reading Return True Case Else Return False ' This should never happen, just in case. End Select End Function ''' <summary> ''' Closes the connection. ''' </summary> Public Sub Disconnect() Select Case _type Case ConnectionType.IP _client.Close() Case ConnectionType.Serial ' disconnect from Grbl Try If _port.IsOpen Then _port.BaseStream.Close() ' _port.Close() ' There is a known problem that hangs the program if you are using Invoke in the ReceiveData event (I now use BeforeInvoke) ' See http://social.msdn.microsoft.com/Forums/en-US/ce8ce1a3-64ed-4f26-b9ad-e2ff1d3be0a5/serial-port-hangs-whilst-closing?forum=Vsexpressvcs End If Catch ' This happens for sure if user disconnects the USB cable MessageBox.Show(Resources.GrblIF_Disconnect_ErrorOnCloseOfGrblPort) End Try End Select _connected = False _type = ConnectionType.None End Sub Public Function rescan() As String() ' scan for com ports again Return IO.Ports.SerialPort.GetPortNames End Function #Region "Properties" ''' <summary> ''' Lists the available COM ports on the system. ''' </summary> ''' <returns>String Array of COM ports</returns> ReadOnly Property comports() As String() Get ' get list of available com ports _commports = IO.Ports.SerialPort.GetPortNames() Return _commports End Get End Property ''' <summary> ''' COM port to use if connected via COM ''' </summary> ''' <value>The COM port to use</value> ''' <returns>The selected COM port</returns> Property comport() As String Get Return _commport End Get Set(value As String) _commport = value End Set End Property ''' <summary> ''' Baudrate to use if connected via COM ''' </summary> ''' <value>The baudrate, as an integer. 9600 (0.8c) and 115200 (0.9g) are common values.</value> ''' <returns>The configured baudrate</returns> Property baudrate() As Integer Get Return _baudrate End Get Set(value As Integer) _baudrate = value End Set End Property ''' <summary> ''' IP Address to use if connected via IP ''' </summary> ''' <value>The IP Address to connect to</value> ''' <returns>The IP Address currently configured</returns> Property ipaddress() As IPAddress Get Return _remoteHost End Get Set(value As IPAddress) _remoteHost = value End Set End Property ''' <summary> ''' Port Number to use if connected via IP ''' </summary> ''' <value>Port number to use, as an integer between 1 and 65,535. WiFly defaults to 2000</value> ''' <returns></returns> ''' <remarks></remarks> Property portnum() As Integer Get Return _portNum End Get Set(value As Integer) If value > 65535 Or value < 0 Then 'port number passed in is outside of valid bounds, default to 2000. _portNum = 2000 Else _portNum = value End If End Set End Property ''' <summary> ''' Are we connected to grbl? ''' </summary> ReadOnly Property Connected As Boolean ' Are we connected to Grbl? Get Return _connected End Get End Property #End Region ' **** Receive Queue Management ' calls delegates (callbacks) to consumers of the data ' collects received data line and pushes to queue ' pops from queue after last delegate returns Public Function addRcvDelegate(param As grblDataReceived) As Boolean ' Add a delegate (callback) to the received Data list _recvDelegates.Add(param) Return True End Function Public Function deleteRcvDelegate(param As grblDataReceived) As Boolean ' Add a delegate (callback) to the received Data list _recvDelegates.Remove(param) Return True End Function Private Sub _client_DataReceived() 'sender As Object, e As IO.Ports.SerialDataReceivedEventArgs) Handles _stream.DataReceived ' THIS RUNS IN ITS OWN THREAD!!!!! with no direct access to UI elements ' By using ReadLine here, we should block this thread until the rest of a line is available, set ReceivedBytesThreshold low (2) ' All registered delegates are called, any new receive events get queued up 'in the system' Dim data As String Dim _stream As NetworkStream = _client.GetStream() Dim _reader As New StreamReader(_stream) While _connected Try data = _reader.ReadLine() If data.Length <> 0 Then 'Dim lines As String() = data.Split({10, 13}, StringSplitOptions.RemoveEmptyEntries) 'If lines.Length > 0 Then 'For Each line In lines For Each callback In _recvDelegates callback.Invoke(data) Next 'Next 'End If End If Catch ex As Exception ' various exceptions occur when closing app ' all due to race conditions because we process receive events on ' different thread from gui. ' This Catch handles data=Nothing from passing to rest of code at exit 'Disconnect() 'Return End Try End While End Sub Dim readBuffer(256) As Byte Private Async Sub _client_ComReadData() Try Dim _actualLength As Integer = Await _port.BaseStream.ReadAsync(readBuffer, 0, 200) Dim _received(_actualLength) As Byte Buffer.BlockCopy(readBuffer, 0, _received, 0, _actualLength) 'Console.WriteLine("_client_ComReadData: Finished async read, bytes {0}", _actualLength) 'raiseAppSerialDataEvent(System.Text.ASCIIEncoding.ASCII.GetString(_received)) RaiseEvent serialDataEvent(System.Text.ASCIIEncoding.ASCII.GetString(_received)) _client_ComReadData() ' reprime the read Catch e As System.InvalidOperationException Catch e As System.UnauthorizedAccessException Catch e As System.IO.IOException Debug.WriteLine("_client_ComReadData: error on reading from port " + e.Message) Catch e As TimeoutException Debug.WriteLine("_client_ComReadData: Timeout exception {0}", e.Message) End Try End Sub Public Event serialDataEvent(data As String) ''' <summary> ''' Handles the application serial data event. ''' </summary> ''' <remarks> ''' Processes the received data into lines ''' For each line, calls the registered delegates ''' </remarks> ''' <param name="data">The (possibly partial) data.</param> Private Sub raiseAppSerialDataEvent(data As String) Static line As New StringBuilder() For Each ch As Char In data If ch <> vbNullChar Then ' ignore the Null at end of received data If ch = vbLf Then line.Append(ch) 'Send for processing ' Console.WriteLine("raiseAppSerialDataEvent: {0} ", line) For Each callback In _recvDelegates 'Console.WriteLine("recvDelegates: calling " + callback.Method.Name) callback.Invoke(line.ToString) Next ' Get ready for next portion line.Clear() Else line.Append(ch) End If End If Next End Sub ''' <summary> ''' Sends a byte of data to grbl ''' </summary> ''' <param name="data">The data to send to grbl</param> ''' <returns>True if send was successful, false otherwise</returns> Public Function sendData(ByVal data As String) As Boolean Select Case _type Case ConnectionType.IP ' We depend on the caller to not over send the 127 byte limit TODO HOW DO I PREVENT THIS??? If _connected And _client.Connected Then ' Write data to Grbl ' Simple is send data, wait for ok before sending next block ' Aggressive is determing how full the Grbl buffer is and sending as much as possible. ' This requires tracking ok's, see Grbl Wiki ' For now we just write If data.Length = 1 Then ' no CRLF at end, it should be an immediate command such as ! or ~ or ? '_port.Write(data) Dim c As Byte() = System.Text.Encoding.GetEncoding(1252).GetBytes(data) Try _client.GetStream().Write(c, 0, c.Length) Catch _connected = False ' _port.Close() MessageBox.Show(Resources.GrblIF_sendData_FatalErrorOnWriteToGrbl) End Try 'Console.WriteLine("GrblIF::sendData Sent: " + data + " to Grbl") Else ' Note that this encoding allows only 7 bit Ascii characters! Dim c As Byte() = ASCIIEncoding.ASCII.GetBytes(data + vbLf) Try _client.GetStream().Write(c, 0, c.Length) Catch _connected = False '_port.Close() MessageBox.Show(GrblIF_sendData_FatalErrorOnWriteToGrbl) End Try 'Console.WriteLine("GrblIF::sendData Sent: " + data + " to Grbl") End If Return True Else Return False End If Case ConnectionType.Serial ' We depend on the caller to not over send the 127 byte limit TODO HOW DO I PREVENT THIS??? If _connected And _port.IsOpen Then ' Write data to Grbl ' Simple is send data, wait for ok before sending next block ' Aggressive is determing how full the Grbl buffer is and sending as much as possible. ' This requires tracking ok's, see Grbl Wiki ' For now we just write If data.Length = 1 Then ' no CRLF at end, it should be an immediate command such as ! or ~ or ? Dim c As Byte() = System.Text.Encoding.GetEncoding(1252).GetBytes(data) Try _port.BaseStream.Write(c, 0, c.Length) Catch e As Exception _connected = False ' _port.Close() MessageBox.Show(GrblIF_sendData_FatalErrorOnWriteToGrbl + ", " + e.Message) End Try ' Console.WriteLine("GrblIF:char:sendData Sent: " + data + " to Grbl") Else ' Note that this encoding allows only 7 bit Ascii characters! Dim c As Byte() = ASCIIEncoding.ASCII.GetBytes(data + vbLf) Try _port.BaseStream.Write(c, 0, c.Length) Catch e As Exception _connected = False '_port.Close() MessageBox.Show(GrblIF_sendData_FatalErrorOnWriteToGrbl + ", " + e.Message) End Try ' Console.WriteLine(String.Format("Sent as byte: {0:X} {1:X}", c(0), c(1))) ' Console.WriteLine("GrblIF:line:sendData Sent: " + data + " to Grbl") End If Return True Else Return False End If Case Else Return False 'This should not happen if connected, just in case. End Select End Function End Class
gerritv/Grbl-Panel
Grbl-Panel/GrblIF.vb
Visual Basic
mit
15,998
' 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 Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A class representing Visual Basic compilation Options. ''' </summary> Public NotInheritable Class VisualBasicCompilationOptions Inherits CompilationOptions Implements IEquatable(Of VisualBasicCompilationOptions) Private Const s_globalImportsString = "GlobalImports" Private Const s_rootNamespaceString = "RootNamespace" Private Const s_optionStrictString = "OptionStrict" Private Const s_optionInferString = "OptionInfer" Private Const s_optionExplicitString = "OptionExplicit" Private Const s_optionCompareTextString = "OptionCompareText" Private Const s_embedVbCoreRuntimeString = "EmbedVbCoreRuntime" Private Const s_parseOptionsString = "ParseOptions" Private _globalImports As ImmutableArray(Of GlobalImport) Private _rootNamespace As String Private _optionStrict As OptionStrict Private _optionInfer As Boolean Private _optionExplicit As Boolean Private _optionCompareText As Boolean Private _embedVbCoreRuntime As Boolean Private _parseOptions As VisualBasicParseOptions ' The assemblies emitted by the expression compiler should never contain embedded declarations - ' those should come from the user's code. Private _suppressEmbeddedDeclarations As Boolean ''' <summary> ''' Initializes a new instance of the VisualBasicCompilationOptions type with various options. ''' </summary> ''' <param name="outputKind">The compilation output kind. <see cref="CodeAnalysis.OutputKind"/></param> ''' <param name="moduleName">An optional parameter to specify the name of the assembly that this module will be a part of.</param> ''' <param name="mainTypeName">An optional parameter to specify the class or module that contains the Sub Main procedure.</param> ''' <param name="scriptClassName">An optional parameter to specify an alteranate DefaultScriptClassName object to be used.</param> ''' <param name="globalImports">An optional collection of GlobalImports <see cref="GlobalImports"/> .</param> ''' <param name="rootNamespace">An optional parameter to specify the name of the default root namespace.</param> ''' <param name="optionStrict">An optional parameter to specify the default Option Strict behavior. <see cref="VisualBasic.OptionStrict"/></param> ''' <param name="optionInfer">An optional parameter to specify default Option Infer behavior.</param> ''' <param name="optionExplicit">An optional parameter to specify the default Option Explicit behavior.</param> ''' <param name="optionCompareText">An optional parameter to specify the default Option Compare Text behavior.</param> ''' <param name="embedVbCoreRuntime">An optional parameter to specify the embedded Visual Basic Core Runtime behavior.</param> ''' <param name="checkOverflow">An optional parameter to specify enabling/disabling overflow checking.</param> ''' <param name="concurrentBuild">An optional parameter to specify enabling/disabling concurrent build.</param> ''' <param name="cryptoKeyContainer">An optional parameter to specify a key container name for a key pair to give an assembly a strong name.</param> ''' <param name="cryptoKeyFile">An optional parameter to specify a file containing a key or key pair to give an assembly a strong name.</param> ''' <param name="cryptoPublicKey">An optional parameter to specify a public key used to give an assembly a strong name.</param> ''' <param name="delaySign">An optional parameter to specify whether the assembly will be fully or partially signed.</param> ''' <param name="platform">An optional parameter to specify which platform version of common language runtime (CLR) can run compilation. <see cref="CodeAnalysis.Platform"/></param> ''' <param name="generalDiagnosticOption">An optional parameter to specify the general warning level.</param> ''' <param name="specificDiagnosticOptions">An optional collection representing specific warnings that differ from general warning behavior.</param> ''' <param name="optimizationLevel">An optional parameter to enabled/disable optimizations. </param> ''' <param name="parseOptions">An optional parameter to specify the parse options. <see cref="VisualBasicParseOptions"/></param> ''' <param name="xmlReferenceResolver">An optional parameter to specify the XML file resolver.</param> ''' <param name="sourceReferenceResolver">An optional parameter to specify the source file resolver.</param> ''' <param name="metadataReferenceResolver">An optional parameter to specify <see cref="CodeAnalysis.MetadataReferenceResolver"/>.</param> ''' <param name="assemblyIdentityComparer">An optional parameter to specify <see cref="CodeAnalysis.AssemblyIdentityComparer"/>.</param> ''' <param name="strongNameProvider">An optional parameter to specify <see cref="CodeAnalysis.StrongNameProvider"/>.</param> Public Sub New( outputKind As OutputKind, Optional moduleName As String = Nothing, Optional mainTypeName As String = Nothing, Optional scriptClassName As String = WellKnownMemberNames.DefaultScriptClassName, Optional globalImports As IEnumerable(Of GlobalImport) = Nothing, Optional rootNamespace As String = Nothing, Optional optionStrict As OptionStrict = OptionStrict.Off, Optional optionInfer As Boolean = True, Optional optionExplicit As Boolean = True, Optional optionCompareText As Boolean = False, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional embedVbCoreRuntime As Boolean = False, Optional optimizationLevel As OptimizationLevel = OptimizationLevel.Debug, Optional checkOverflow As Boolean = True, Optional cryptoKeyContainer As String = Nothing, Optional cryptoKeyFile As String = Nothing, Optional cryptoPublicKey As ImmutableArray(Of Byte) = Nothing, Optional delaySign As Boolean? = Nothing, Optional platform As Platform = Platform.AnyCpu, Optional generalDiagnosticOption As ReportDiagnostic = ReportDiagnostic.Default, Optional specificDiagnosticOptions As IEnumerable(Of KeyValuePair(Of String, ReportDiagnostic)) = Nothing, Optional concurrentBuild As Boolean = True, Optional xmlReferenceResolver As XmlReferenceResolver = Nothing, Optional sourceReferenceResolver As SourceReferenceResolver = Nothing, Optional metadataReferenceResolver As MetadataReferenceResolver = Nothing, Optional assemblyIdentityComparer As AssemblyIdentityComparer = Nothing, Optional strongNameProvider As StrongNameProvider = Nothing) MyClass.New( outputKind, moduleName, mainTypeName, scriptClassName, globalImports, rootNamespace, optionStrict, optionInfer, optionExplicit, optionCompareText, parseOptions, embedVbCoreRuntime, optimizationLevel, checkOverflow, cryptoKeyContainer, cryptoKeyFile, cryptoPublicKey, delaySign, platform, generalDiagnosticOption, specificDiagnosticOptions, concurrentBuild, suppressEmbeddedDeclarations:=False, extendedCustomDebugInformation:=True, xmlReferenceResolver:=xmlReferenceResolver, sourceReferenceResolver:=sourceReferenceResolver, metadataReferenceResolver:=metadataReferenceResolver, assemblyIdentityComparer:=assemblyIdentityComparer, strongNameProvider:=strongNameProvider, metadataImportOptions:=MetadataImportOptions.Public) End Sub Friend Sub New( outputKind As OutputKind, moduleName As String, mainTypeName As String, scriptClassName As String, globalImports As IEnumerable(Of GlobalImport), rootNamespace As String, optionStrict As OptionStrict, optionInfer As Boolean, optionExplicit As Boolean, optionCompareText As Boolean, parseOptions As VisualBasicParseOptions, embedVbCoreRuntime As Boolean, optimizationLevel As OptimizationLevel, checkOverflow As Boolean, cryptoKeyContainer As String, cryptoKeyFile As String, cryptoPublicKey As ImmutableArray(Of Byte), delaySign As Boolean?, platform As Platform, generalDiagnosticOption As ReportDiagnostic, specificDiagnosticOptions As IEnumerable(Of KeyValuePair(Of String, ReportDiagnostic)), concurrentBuild As Boolean, suppressEmbeddedDeclarations As Boolean, extendedCustomDebugInformation As Boolean, xmlReferenceResolver As XmlReferenceResolver, sourceReferenceResolver As SourceReferenceResolver, metadataReferenceResolver As MetadataReferenceResolver, assemblyIdentityComparer As AssemblyIdentityComparer, strongNameProvider As StrongNameProvider, metadataImportOptions As MetadataImportOptions) MyBase.New( outputKind:=outputKind, moduleName:=moduleName, mainTypeName:=mainTypeName, scriptClassName:=scriptClassName, cryptoKeyContainer:=cryptoKeyContainer, cryptoKeyFile:=cryptoKeyFile, cryptoPublicKey:=cryptoPublicKey, delaySign:=delaySign, optimizationLevel:=optimizationLevel, checkOverflow:=checkOverflow, platform:=platform, generalDiagnosticOption:=generalDiagnosticOption, warningLevel:=1, specificDiagnosticOptions:=specificDiagnosticOptions.ToImmutableDictionaryOrEmpty(CaseInsensitiveComparison.Comparer), ' Diagnostic ids must be processed in case-insensitive fashion. concurrentBuild:=concurrentBuild, extendedCustomDebugInformation:=extendedCustomDebugInformation, xmlReferenceResolver:=xmlReferenceResolver, sourceReferenceResolver:=sourceReferenceResolver, metadataReferenceResolver:=metadataReferenceResolver, assemblyIdentityComparer:=assemblyIdentityComparer, strongNameProvider:=strongNameProvider, metadataImportOptions:=metadataImportOptions) _globalImports = globalImports.AsImmutableOrEmpty() _rootNamespace = If(rootNamespace, String.Empty) _optionStrict = optionStrict _optionInfer = optionInfer _optionExplicit = optionExplicit _optionCompareText = optionCompareText _embedVbCoreRuntime = embedVbCoreRuntime _suppressEmbeddedDeclarations = suppressEmbeddedDeclarations _parseOptions = parseOptions Debug.Assert(Not (_embedVbCoreRuntime AndAlso _suppressEmbeddedDeclarations), "_embedVbCoreRuntime and _suppressEmbeddedDeclarations are mutually exclusive") End Sub Private Sub New(other As VisualBasicCompilationOptions) MyClass.New( outputKind:=other.OutputKind, moduleName:=other.ModuleName, mainTypeName:=other.MainTypeName, scriptClassName:=other.ScriptClassName, globalImports:=other.GlobalImports, rootNamespace:=other.RootNamespace, optionStrict:=other.OptionStrict, optionInfer:=other.OptionInfer, optionExplicit:=other.OptionExplicit, optionCompareText:=other.OptionCompareText, parseOptions:=other.ParseOptions, embedVbCoreRuntime:=other.EmbedVbCoreRuntime, suppressEmbeddedDeclarations:=other.SuppressEmbeddedDeclarations, optimizationLevel:=other.OptimizationLevel, checkOverflow:=other.CheckOverflow, cryptoKeyContainer:=other.CryptoKeyContainer, cryptoKeyFile:=other.CryptoKeyFile, cryptoPublicKey:=other.CryptoPublicKey, delaySign:=other.DelaySign, platform:=other.Platform, generalDiagnosticOption:=other.GeneralDiagnosticOption, specificDiagnosticOptions:=other.SpecificDiagnosticOptions, concurrentBuild:=other.ConcurrentBuild, extendedCustomDebugInformation:=other.ExtendedCustomDebugInformation, xmlReferenceResolver:=other.XmlReferenceResolver, sourceReferenceResolver:=other.SourceReferenceResolver, metadataReferenceResolver:=other.MetadataReferenceResolver, assemblyIdentityComparer:=other.AssemblyIdentityComparer, strongNameProvider:=other.StrongNameProvider, metadataImportOptions:=other.MetadataImportOptions) End Sub ''' <summary> ''' Gets the global imports collection. ''' </summary> ''' <returns>The global imports.</returns> Public ReadOnly Property GlobalImports As ImmutableArray(Of GlobalImport) Get Return _globalImports End Get End Property ''' <summary> ''' Gets the default namespace for all source code in the project. Corresponds to the ''' "RootNamespace" project option or the "/rootnamespace" command line option. ''' </summary> ''' <returns>The default namespace.</returns> Public ReadOnly Property RootNamespace As String Get Return _rootNamespace End Get End Property Friend Function GetRootNamespaceParts() As ImmutableArray(Of String) If String.IsNullOrEmpty(_rootNamespace) OrElse Not OptionsValidator.IsValidNamespaceName(_rootNamespace) Then Return ImmutableArray(Of String).Empty End If Return MetadataHelpers.SplitQualifiedName(_rootNamespace) End Function ''' <summary> ''' Gets the Option Strict Setting. ''' </summary> ''' <returns>The Option Strict setting.</returns> Public ReadOnly Property OptionStrict As OptionStrict Get Return _optionStrict End Get End Property ''' <summary> ''' Gets the Option Infer setting. ''' </summary> ''' <returns>The Option Infer setting. True if Option Infer On is in effect by default. False if Option Infer Off is on effect by default. </returns> Public ReadOnly Property OptionInfer As Boolean Get Return _optionInfer End Get End Property ''' <summary> ''' Gets the Option Explicit setting. ''' </summary> ''' <returns>The Option Explicit setting. True if Option Explicit On is in effect by default. False if Option Explicit Off is on by default.</returns> Public ReadOnly Property OptionExplicit As Boolean Get Return _optionExplicit End Get End Property ''' <summary> ''' Gets the Option Compare Text setting. ''' </summary> ''' <returns> ''' The Option Compare Text Setting, True if Option Compare Text is in effect by default. False if Option Compare Binary is ''' in effect by default. ''' </returns> Public ReadOnly Property OptionCompareText As Boolean Get Return _optionCompareText End Get End Property ''' <summary> ''' Gets the Embed Visual Basic Core Runtime setting. ''' </summary> ''' <returns> ''' The EmbedVbCoreRuntime setting, True if VB core runtime should be embedded in the compilation. Equal to '/vbruntime*' ''' </returns> Public ReadOnly Property EmbedVbCoreRuntime As Boolean Get Return _embedVbCoreRuntime End Get End Property ''' <summary> ''' Gets the embedded declaration suppression setting. ''' </summary> ''' <returns> ''' The embedded declaration suppression setting. ''' </returns> Friend ReadOnly Property SuppressEmbeddedDeclarations As Boolean Get Return _suppressEmbeddedDeclarations End Get End Property ''' <summary> ''' Gets the Parse Options setting. ''' Compilation level parse options. Used when compiling synthetic embedded code such as My template ''' </summary> ''' <returns>The Parse Options Setting.</returns> Friend ReadOnly Property ParseOptions As VisualBasicParseOptions Get Return _parseOptions End Get End Property ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different OutputKind specified. ''' </summary> ''' <param name="kind">The Output Kind.</param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the output kind is different; otherwise current instance.</returns> Public Shadows Function WithOutputKind(kind As OutputKind) As VisualBasicCompilationOptions If kind = Me.OutputKind Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.OutputKind = kind} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance With a different ModuleName specified. ''' </summary> ''' <param name="moduleName">The moduleName.</param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the module name is different; otherwise current instance.</returns> Public Function WithModuleName(moduleName As String) As VisualBasicCompilationOptions If String.Equals(moduleName, Me.ModuleName, StringComparison.Ordinal) Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.ModuleName = moduleName} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a Script Class Name specified. ''' </summary> ''' <param name="name">The name for the ScriptClassName.</param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the script class name is different; otherwise current instance.</returns> Public Shadows Function WithScriptClassName(name As String) As VisualBasicCompilationOptions If String.Equals(name, Me.ScriptClassName, StringComparison.Ordinal) Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.ScriptClassName = name} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different Main Type name specified. ''' </summary> ''' <param name="name">The name for the MainType .</param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the main type name is different; otherwise current instance.</returns> Public Shadows Function WithMainTypeName(name As String) As VisualBasicCompilationOptions If String.Equals(name, Me.MainTypeName, StringComparison.Ordinal) Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.MainTypeName = name} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different global imports specified. ''' </summary> ''' <param name="globalImports">A collection of Global Imports <see cref="GlobalImport"/>.</param> ''' <returns>A new instance of VisualBasicCompilationOptions.</returns> Public Function WithGlobalImports(globalImports As ImmutableArray(Of GlobalImport)) As VisualBasicCompilationOptions If Me.GlobalImports.Equals(globalImports) Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {._globalImports = globalImports} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different global imports specified. ''' </summary> ''' <param name="globalImports">A collection of Global Imports <see cref="GlobalImport"/>.</param> ''' <returns>A new instance of VisualBasicCompilationOptions.</returns> Public Function WithGlobalImports(globalImports As IEnumerable(Of GlobalImport)) As VisualBasicCompilationOptions Return New VisualBasicCompilationOptions(Me) With {._globalImports = globalImports.AsImmutableOrEmpty()} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different global imports specified. ''' </summary> ''' <param name="globalImports">A collection of Global Imports <see cref="GlobalImport"/>.</param> ''' <returns>A new instance of VisualBasicCompilationOptions.</returns> Public Function WithGlobalImports(ParamArray globalImports As GlobalImport()) As VisualBasicCompilationOptions Return WithGlobalImports(DirectCast(globalImports, IEnumerable(Of GlobalImport))) End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different root namespace specified. ''' </summary> ''' <param name="rootNamespace">The root namespace.</param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the root namespace is different; otherwise current instance.</returns> Public Function WithRootNamespace(rootNamespace As String) As VisualBasicCompilationOptions If String.Equals(rootNamespace, Me.RootNamespace, StringComparison.Ordinal) Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {._rootNamespace = rootNamespace} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different option strict specified. ''' </summary> ''' <param name="value">The Option Strict setting. <see cref="Microsoft.CodeAnalysis.VisualBasic.OptionStrict"/></param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the option strict is different; otherwise current instance.</returns> Public Shadows Function WithOptionStrict(value As OptionStrict) As VisualBasicCompilationOptions If value = Me.OptionStrict Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {._optionStrict = value} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different option infer specified. ''' </summary> ''' <param name="value">The Option infer setting. </param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the option infer is different; otherwise current instance.</returns> Public Shadows Function WithOptionInfer(value As Boolean) As VisualBasicCompilationOptions If value = Me.OptionInfer Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {._optionInfer = value} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different option explicit specified. ''' </summary> ''' <param name="value">The Option Explicit setting. </param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the option explicit is different; otherwise current instance.</returns> Public Shadows Function WithOptionExplicit(value As Boolean) As VisualBasicCompilationOptions If value = Me.OptionExplicit Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {._optionExplicit = value} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different Option Compare Text specified. ''' </summary> ''' <param name="value">The Option Compare Text setting. </param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the option compare text is different; otherwise current instance.</returns> Public Shadows Function WithOptionCompareText(value As Boolean) As VisualBasicCompilationOptions If value = Me.OptionCompareText Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {._optionCompareText = value} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different Embed VB Core Runtime specified. ''' </summary> ''' <param name="value">The Embed VB Core Runtime setting. </param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the embed vb core runtime is different; otherwise current instance.</returns> Public Shadows Function WithEmbedVbCoreRuntime(value As Boolean) As VisualBasicCompilationOptions If value = Me.EmbedVbCoreRuntime Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {._embedVbCoreRuntime = value} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different Overflow checks specified. ''' </summary> ''' <param name="enabled">The overflow check setting. </param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the overflow check is different; otherwise current instance.</returns> Public Shadows Function WithOverflowChecks(enabled As Boolean) As VisualBasicCompilationOptions If enabled = Me.CheckOverflow Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.CheckOverflow = enabled} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different concurrent build specified. ''' </summary> ''' <param name="concurrentBuild">The concurrent build setting. </param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the concurrent build is different; otherwise current instance.</returns> Public Shadows Function WithConcurrentBuild(concurrentBuild As Boolean) As VisualBasicCompilationOptions If concurrentBuild = Me.ConcurrentBuild Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.ConcurrentBuild = concurrentBuild} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different extended custom debug information specified. ''' </summary> ''' <param name="extendedCustomDebugInformation">The extended custom debug information setting. </param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the extended custom debug information is different; otherwise current instance.</returns> Friend Function WithExtendedCustomDebugInformation(extendedCustomDebugInformation As Boolean) As VisualBasicCompilationOptions If extendedCustomDebugInformation = Me.ExtendedCustomDebugInformation Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.ExtendedCustomDebugInformation_internal_protected_set = extendedCustomDebugInformation} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with different embedded declaration suppression setting specified. ''' </summary> ''' <param name="suppressEmbeddedDeclarations">The embedded declaration suppression setting. </param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the embedded declaration suppression setting is different; otherwise current instance.</returns> ''' <remarks>Only expected to be called from the expression compiler.</remarks> Friend Function WithSuppressEmbeddedDeclarations(suppressEmbeddedDeclarations As Boolean) As VisualBasicCompilationOptions If suppressEmbeddedDeclarations = _suppressEmbeddedDeclarations Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {._suppressEmbeddedDeclarations = suppressEmbeddedDeclarations} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different cryptography key container specified ''' </summary> ''' <param name="name">The name of the cryptography key container. </param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the cryptography key container name is different; otherwise current instance.</returns> Public Shadows Function WithCryptoKeyContainer(name As String) As VisualBasicCompilationOptions If String.Equals(name, Me.CryptoKeyContainer, StringComparison.Ordinal) Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.CryptoKeyContainer = name} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different cryptography key file path specified. ''' </summary> ''' <param name="path">The cryptography key file path. </param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the cryptography key path is different; otherwise current instance.</returns> Public Shadows Function WithCryptoKeyFile(path As String) As VisualBasicCompilationOptions If String.Equals(path, Me.CryptoKeyFile, StringComparison.Ordinal) Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.CryptoKeyFile = path} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different public key. ''' </summary> ''' <param name="value">The cryptography key file path. </param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the public key is different; otherwise current instance.</returns> Public Shadows Function WithCryptoPublicKey(value As ImmutableArray(Of Byte)) As VisualBasicCompilationOptions If value.IsDefault Then value = ImmutableArray(Of Byte).Empty End If If value = Me.CryptoPublicKey Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.CryptoPublicKey = value} End Function ''' <summary> ''' Creates a new VisualBasicCompilationOptions instance with a different delay signing specified. ''' </summary> ''' <param name="value">The delay signing setting. </param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the delay sign is different; otherwise current instance.</returns> Public Shadows Function WithDelaySign(value As Boolean?) As VisualBasicCompilationOptions If value = Me.DelaySign Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.DelaySign = value} End Function ''' <summary> ''' Creates a new <see cref="VisualBasicCompilationOptions"/> instance with a different platform specified. ''' </summary> ''' <param name="value">The platform setting. <see cref="Microsoft.CodeAnalysis.Platform"/></param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the platform is different; otherwise current instance.</returns> Public Shadows Function WithPlatform(value As Platform) As VisualBasicCompilationOptions If value = Me.Platform Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.Platform = value} End Function Protected Overrides Function CommonWithGeneralDiagnosticOption(value As ReportDiagnostic) As CompilationOptions Return Me.WithGeneralDiagnosticOption(value) End Function Protected Overrides Function CommonWithSpecificDiagnosticOptions(specificDiagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic)) As CompilationOptions Return Me.WithSpecificDiagnosticOptions(specificDiagnosticOptions) End Function Protected Overrides Function CommonWithSpecificDiagnosticOptions(specificDiagnosticOptions As IEnumerable(Of KeyValuePair(Of String, ReportDiagnostic))) As CompilationOptions Return Me.WithSpecificDiagnosticOptions(specificDiagnosticOptions) End Function <Obsolete> Protected Overrides Function CommonWithFeatures(features As ImmutableArray(Of String)) As CompilationOptions Throw New NotImplementedException() End Function ''' <summary> ''' Creates a new <see cref="VisualBasicCompilationOptions"/> instance with a different report warning specified. ''' </summary> ''' <param name="value">The Report Warning setting. <see cref="Microsoft.CodeAnalysis.ReportDiagnostic"/></param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the report warning is different; otherwise current instance.</returns> Public Shadows Function WithGeneralDiagnosticOption(value As ReportDiagnostic) As VisualBasicCompilationOptions If value = Me.GeneralDiagnosticOption Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.GeneralDiagnosticOption = value} End Function ''' <summary> ''' Creates a new <see cref="VisualBasicCompilationOptions"/> instance with different specific warnings specified. ''' </summary> ''' <param name="value">Specific report warnings. <see cref="Microsoft.CodeAnalysis.ReportDiagnostic"/></param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the dictionary of report warning is different; otherwise current instance.</returns> Public Shadows Function WithSpecificDiagnosticOptions(value As ImmutableDictionary(Of String, ReportDiagnostic)) As VisualBasicCompilationOptions If value Is Nothing Then value = ImmutableDictionary(Of String, ReportDiagnostic).Empty End If If value Is Me.SpecificDiagnosticOptions Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.SpecificDiagnosticOptions = value} End Function ''' <summary> ''' Creates a new <see cref="VisualBasicCompilationOptions"/> instance with different specific warnings specified. ''' </summary> ''' <param name="value">Specific report warnings. <see cref="Microsoft.CodeAnalysis.ReportDiagnostic"/></param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the dictionary of report warning is different; otherwise current instance.</returns> Public Shadows Function WithSpecificDiagnosticOptions(value As IEnumerable(Of KeyValuePair(Of String, ReportDiagnostic))) As VisualBasicCompilationOptions Return New VisualBasicCompilationOptions(Me) With {.SpecificDiagnosticOptions = value.ToImmutableDictionaryOrEmpty()} End Function ''' <summary> ''' Creates a new <see cref="VisualBasicCompilationOptions"/> instance with a specified <see cref="VisualBasicCompilationOptions.OptimizationLevel"/>. ''' </summary> ''' <returns>A new instance of <see cref="VisualBasicCompilationOptions"/>, if the value is different; otherwise the current instance.</returns> Public Shadows Function WithOptimizationLevel(value As OptimizationLevel) As VisualBasicCompilationOptions If value = Me.OptimizationLevel Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.OptimizationLevel = value} End Function Friend Function WithMetadataImportOptions(value As MetadataImportOptions) As VisualBasicCompilationOptions If value = Me.MetadataImportOptions Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.MetadataImportOptions_internal_protected_set = value} End Function ''' <summary> ''' Creates a new <see cref="VisualBasicCompilationOptions"/> instance with a different parse option specified. ''' </summary> ''' <param name="options">The parse option setting. <see cref="Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions"/></param> ''' <returns>A new instance of VisualBasicCompilationOptions, if the parse options is different; otherwise current instance.</returns> Public Function WithParseOptions(options As VisualBasicParseOptions) As VisualBasicCompilationOptions If options Is Me.ParseOptions Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {._parseOptions = options} End Function Public Shadows Function WithXmlReferenceResolver(resolver As XmlReferenceResolver) As VisualBasicCompilationOptions If resolver Is Me.XmlReferenceResolver Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.XmlReferenceResolver = resolver} End Function Public Shadows Function WithSourceReferenceResolver(resolver As SourceReferenceResolver) As VisualBasicCompilationOptions If resolver Is Me.SourceReferenceResolver Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.SourceReferenceResolver = resolver} End Function Public Shadows Function WithMetadataReferenceResolver(resolver As MetadataReferenceResolver) As VisualBasicCompilationOptions If resolver Is Me.MetadataReferenceResolver Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.MetadataReferenceResolver = resolver} End Function Public Shadows Function WithAssemblyIdentityComparer(comparer As AssemblyIdentityComparer) As VisualBasicCompilationOptions comparer = If(comparer, AssemblyIdentityComparer.Default) If comparer Is Me.AssemblyIdentityComparer Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.AssemblyIdentityComparer = comparer} End Function Public Shadows Function WithStrongNameProvider(provider As StrongNameProvider) As VisualBasicCompilationOptions If provider Is Me.StrongNameProvider Then Return Me End If Return New VisualBasicCompilationOptions(Me) With {.StrongNameProvider = provider} End Function Protected Overrides Function CommonWithOutputKind(kind As OutputKind) As CompilationOptions Return WithOutputKind(kind) End Function Protected Overrides Function CommonWithPlatform(platform As Platform) As CompilationOptions Return WithPlatform(platform) End Function Protected Overrides Function CommonWithOptimizationLevel(value As OptimizationLevel) As CompilationOptions Return WithOptimizationLevel(value) End Function Protected Overrides Function CommonWithAssemblyIdentityComparer(comparer As AssemblyIdentityComparer) As CompilationOptions Return WithAssemblyIdentityComparer(comparer) End Function Protected Overrides Function CommonWithXmlReferenceResolver(resolver As XmlReferenceResolver) As CompilationOptions Return WithXmlReferenceResolver(resolver) End Function Protected Overrides Function CommonWithSourceReferenceResolver(resolver As SourceReferenceResolver) As CompilationOptions Return WithSourceReferenceResolver(resolver) End Function Protected Overrides Function CommonWithMetadataReferenceResolver(resolver As MetadataReferenceResolver) As CompilationOptions Return WithMetadataReferenceResolver(resolver) End Function Protected Overrides Function CommonWithStrongNameProvider(provider As StrongNameProvider) As CompilationOptions Return WithStrongNameProvider(provider) End Function Friend Overrides Sub ValidateOptions(builder As ArrayBuilder(Of Diagnostic)) If Me.EmbedVbCoreRuntime AndAlso Me.OutputKind.IsNetModule() Then builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_VBCoreNetModuleConflict)) End If If Not Platform.IsValid() Then builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_InvalidSwitchValue, NameOf(Platform), Platform.ToString())) End If If ModuleName IsNot Nothing Then Dim e As Exception = MetadataHelpers.CheckAssemblyOrModuleName(ModuleName, NameOf(ModuleName)) If e IsNot Nothing Then builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_BadCompilationOption, e.Message)) End If End If If Not OutputKind.IsValid() Then builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_InvalidSwitchValue, NameOf(OutputKind), OutputKind.ToString())) End If If Not OptimizationLevel.IsValid() Then builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_InvalidSwitchValue, NameOf(OptimizationLevel), OptimizationLevel.ToString())) End If If ScriptClassName Is Nothing OrElse Not ScriptClassName.IsValidClrTypeName() Then builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_InvalidSwitchValue, NameOf(ScriptClassName), If(ScriptClassName, "Nothing"))) End If If MainTypeName IsNot Nothing AndAlso Not MainTypeName.IsValidClrTypeName() Then builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_InvalidSwitchValue, NameOf(MainTypeName), MainTypeName)) End If If Not String.IsNullOrEmpty(RootNamespace) AndAlso Not OptionsValidator.IsValidNamespaceName(RootNamespace) Then builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_InvalidSwitchValue, NameOf(RootNamespace), RootNamespace)) End If If Not OptionStrict.IsValid Then builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_InvalidSwitchValue, NameOf(OptionStrict), OptionStrict.ToString())) End If If Platform = Platform.AnyCpu32BitPreferred AndAlso OutputKind.IsValid() AndAlso Not (OutputKind = OutputKind.ConsoleApplication OrElse OutputKind = OutputKind.WindowsApplication OrElse OutputKind = OutputKind.WindowsRuntimeApplication) Then builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_LibAnycpu32bitPreferredConflict, NameOf(Platform), Platform.ToString())) End If ' TODO: add check for ' (kind == 'arm' || kind == 'appcontainer' || kind == 'winmdobj') && ' (version >= "6.2") If Not CryptoPublicKey.IsEmpty Then If CryptoKeyFile IsNot Nothing Then builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_MutuallyExclusiveOptions, NameOf(CryptoPublicKey), NameOf(CryptoKeyFile))) End If If CryptoKeyContainer IsNot Nothing Then builder.Add(Diagnostic.Create(MessageProvider.Instance, ERRID.ERR_MutuallyExclusiveOptions, NameOf(CryptoPublicKey), NameOf(CryptoKeyContainer))) End If End If End Sub ''' <summary> ''' Determines whether the current object is equal to another object of the same type. ''' </summary> ''' <param name="other">A VisualBasicCompilationOptions to compare with this object</param> ''' <returns>A boolean value. True if the current object is equal to the other parameter; otherwise, False.</returns> Public Overloads Function Equals(other As VisualBasicCompilationOptions) As Boolean Implements IEquatable(Of VisualBasicCompilationOptions).Equals If Me Is other Then Return True End If If Not MyBase.EqualsHelper(other) Then Return False End If Return If(Me.GlobalImports.IsDefault, other.GlobalImports.IsDefault, Me.GlobalImports.SequenceEqual(other.GlobalImports)) AndAlso String.Equals(Me.RootNamespace, other.RootNamespace, StringComparison.Ordinal) AndAlso Me.OptionStrict = other.OptionStrict AndAlso Me.OptionInfer = other.OptionInfer AndAlso Me.OptionExplicit = other.OptionExplicit AndAlso Me.OptionCompareText = other.OptionCompareText AndAlso Me.EmbedVbCoreRuntime = other.EmbedVbCoreRuntime AndAlso Me.SuppressEmbeddedDeclarations = other.SuppressEmbeddedDeclarations AndAlso If(Me.ParseOptions Is Nothing, other.ParseOptions Is Nothing, Me.ParseOptions.Equals(other.ParseOptions)) End Function ''' <summary> ''' Indicates whether the current object is equal to another object. ''' </summary> ''' <param name="obj">A object to compare with this object</param> ''' <returns>A boolean value. True if the current object is equal to the other parameter; otherwise, False.</returns> Public Overrides Function Equals(obj As Object) As Boolean Return Me.Equals(TryCast(obj, VisualBasicCompilationOptions)) End Function ''' <summary> ''' Creates a hashcode for this instance. ''' </summary> ''' <returns>A hashcode representing this instance.</returns> Public Overrides Function GetHashCode() As Integer Return Hash.Combine(MyBase.GetHashCodeHelper(), Hash.Combine(Hash.CombineValues(Me.GlobalImports), Hash.Combine(If(Me.RootNamespace IsNot Nothing, StringComparer.Ordinal.GetHashCode(Me.RootNamespace), 0), Hash.Combine(Me.OptionStrict, Hash.Combine(Me.OptionInfer, Hash.Combine(Me.OptionExplicit, Hash.Combine(Me.OptionCompareText, Hash.Combine(Me.EmbedVbCoreRuntime, Hash.Combine(Me.SuppressEmbeddedDeclarations, Hash.Combine(Me.ParseOptions, 0)))))))))) End Function End Class End Namespace
DinoV/roslyn
src/Compilers/VisualBasic/Portable/VisualBasicCompilationOptions.vb
Visual Basic
apache-2.0
49,003
' Copyright 2018 Google LLC ' ' Licensed under the Apache License, Version 2.0 (the "License"); ' you may not use this file except in compliance with the License. ' You may obtain a copy of the License at ' ' http://www.apache.org/licenses/LICENSE-2.0 ' ' Unless required by applicable law or agreed to in writing, software ' distributed under the License is distributed on an "AS IS" BASIS, ' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ' See the License for the specific language governing permissions and ' limitations under the License. Imports Google.Api.Ads.AdWords.Lib Imports Google.Api.Ads.AdWords.v201809 Namespace Google.Api.Ads.AdWords.Examples.VB.v201809 ''' <summary> ''' This code example illustrates how to retrieve all the ad groups for a ''' campaign. To create an ad group, run AddAdGroup.vb. ''' </summary> Public Class GetAdGroups 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 GetAdGroups Console.WriteLine(codeExample.Description) Try Dim campaignId As Long = Long.Parse("INSERT_CAMPAIGN_ID_HERE") codeExample.Run(New AdWordsUser, campaignId) Catch e As Exception Console.WriteLine("An exception occurred while running this code example. {0}", ExampleUtilities.FormatException(e)) End Try End Sub ''' <summary> ''' Returns a description about the code example. ''' </summary> Public Overrides ReadOnly Property Description() As String Get Return "This code example illustrates how to retrieve all the ad groups for a " & "campaign. To create an ad group, run AddAdGroup.vb." End Get End Property ''' <summary> ''' Runs the code example. ''' </summary> ''' <param name="user">The AdWords user.</param> ''' <param name="campaignId">Id of the campaign for which ad groups are ''' retrieved.</param> Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long) Using adGroupService As AdGroupService = CType( user.GetService( AdWordsService.v201809.AdGroupService), AdGroupService) ' Create the selector. Dim selector As New Selector selector.fields = New String() { _ AdGroup.Fields.Id, AdGroup.Fields.Name } selector.predicates = New Predicate() { _ Predicate.Equals( AdGroup.Fields.CampaignId, campaignId) } selector.ordering = New OrderBy() {OrderBy.Asc(AdGroup.Fields.Name)} selector.paging = Paging.Default Dim page As New AdGroupPage Try Do ' Get the ad groups. page = adGroupService.get(selector) ' Display the results. If ((Not page Is Nothing) AndAlso (Not page.entries Is Nothing)) Then Dim i As Integer = selector.paging.startIndex For Each adGroup As AdGroup In page.entries Console.WriteLine( "{0}) Ad group name is ""{1}"" and id is ""{2}"".", i + 1, adGroup.name, adGroup.id) i += 1 Next End If selector.paging.IncreaseOffset() Loop While (selector.paging.startIndex < page.totalNumEntries) Console.WriteLine("Number of ad groups found: {0}", page.totalNumEntries) Catch e As Exception Throw New System.ApplicationException("Failed to retrieve ad group(s).", e) End Try End Using End Sub End Class End Namespace
googleads/googleads-dotnet-lib
examples/AdWords/Vb/v201809/BasicOperations/GetAdGroups.vb
Visual Basic
apache-2.0
4,639
Imports System.ComponentModel Imports System.Linq Imports bv.winclient.BasePanel Namespace BaseForms Public Class BaseReportForm Inherits BaseForm #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() DbService = New bv.common.db.BaseDbService 'Add any initialization after the InitializeComponent() call Me.FormType = BaseFormType.ReportForm End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) eventManager.ClearAllReferences() If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub Friend WithEvents btnClose As DevExpress.XtraEditors.SimpleButton '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(BaseReportForm)) Me.btnClose = New DevExpress.XtraEditors.SimpleButton Me.SuspendLayout() ' 'btnClose ' resources.ApplyResources(Me.btnClose, "btnClose") Me.btnClose.Image = Global.bv.common.win.My.Resources.Resources.Close Me.btnClose.ImageLocation = DevExpress.XtraEditors.ImageLocation.MiddleRight Me.btnClose.Name = "btnClose" ' 'BaseReportForm ' Me.Controls.Add(Me.btnClose) resources.ApplyResources(Me, "$this") Me.Name = "BaseReportForm" Me.ResumeLayout(False) End Sub #End Region #Region "Data Methods" Public Overrides Function GetBindingManager(Optional ByVal aTableName As String = Nothing) As BindingManagerBase If baseDataSet Is Nothing Then Return Nothing If baseDataSet.Tables.Count = 0 Then Return Nothing If aTableName Is Nothing OrElse aTableName = "" Then aTableName = ObjectName End If If aTableName Is Nothing OrElse aTableName = "" Then Return Nothing If baseDataSet.Tables.Contains(aTableName) Then Return BindingContext(baseDataSet.Tables(aTableName)) Else Return Nothing End If End Function Public Overrides Function FillDataset(Optional ByVal id As Object = Nothing) As Boolean If DbService Is Nothing Then Return True baseDataSet.EnforceConstraints = False baseDataSet.Clear() Dim ds As DataSet = DbService.LoadDetailData(id) If Not ds Is Nothing Then Merge(ds) DbDisposeHelper.DisposeDataset(ds) Return True Else Dim errorMessage As ErrorMessage errorMessage = DbService.LastError ErrorForm.ShowError(errorMessage) Return False End If End Function Public Overrides Function HasChanges() As Boolean If m_WasSaved Then Return True Return m_ChildForms.Any(Function(child) child.HasChanges()) End Function Protected m_PromptResult As DialogResult = DialogResult.Yes Protected m_DisableFormDuringPost As Boolean = True Public Overrides Function Post(Optional ByVal postType As PostType = PostType.FinalPosting) As Boolean If UseFormStatus = True AndAlso Status = FormStatus.Demo OrElse [ReadOnly] Then Return True End If If DbService Is Nothing Then Return True DataEventManager.Flush() Dim aHasChanges As Boolean = HasChanges() 'We assume that if DbService.ID is not initialized, detail form is called for list data editing 'and we should not save new object if data was not changed. If Not aHasChanges Then Return True End If 'if new detail object is saved we should validate daat suggest saviing even if 'object was not changed If Not DbService.IsNewObject _ AndAlso Not ((m_State And BusinessObjectState.IntermediateObject) <> 0) _ AndAlso Not HasChanges() Then Return True End If If (postType And postType.IntermediatePosting) = 0 Then Dim defaultResult As DialogResult = DialogResult.Yes If m_ClosingMode <> BaseDetailForm.ClosingMode.Ok Then defaultResult = DialogResult.No End If Dim form As Form = FindForm() If Not (form Is Nothing) Then form.BringToFront() End If m_PromptResult = SavePromptDialog(defaultResult) If m_PromptResult = DialogResult.Cancel Then Return False End If If m_PromptResult = DialogResult.No Then Return True End If RaiseBeforeValidatingEvent() If ValidateData() = False Then m_PromptResult = DialogResult.Cancel Return False Else m_PromptResult = DialogResult.Yes End If End If If DbService Is Nothing Then Throw New Exception("Detail form DB service is not defined") End If RaiseBeforePostEvent(Me) If (m_DisableFormDuringPost = True) Then ' Special hint for the form designer Enabled = False End If DbService.ClearEvents() Try Dim childForPost As BaseDetailPanel = GetChildForPost() If (Not childForPost Is Nothing) Then If (Not childForPost.Post(postType)) Then ErrorForm.ShowError(DbService.LastError) Enabled = True Return False End If End If Enabled = True VisitCheckLlists(Me) If (postType And postType.IntermediatePosting) <> 0 Then m_State = BusinessObjectState.EditObject Or (m_State And BusinessObjectState.IntermediateObject) m_WasSaved = True End If If (postType And postType.FinalPosting) <> 0 Then m_State = BusinessObjectState.EditObject SaveInitialChanges() For Each child As IRelatedObject In m_ChildForms If TypeOf (child) Is BaseForm Then CType(child, BaseForm).SaveInitialChanges() End If Next m_WasSaved = False m_WasPosted = True End If RaiseAfterPostEvent(Me) Return True Catch ex As Exception Throw End Try End Function Protected Overridable Function GetChildForPost() As BaseRamDetailPanel Throw New NotImplementedException("method should be overriden") End Function #End Region #Region "Close Methods" Protected m_DoDeleteAfterNo As Boolean = True 'Protected m_ClosingMode As BaseDetailForm.ClosingMode Protected Overridable Function cmdClose_Click() As Boolean m_ClosingMode = BaseDetailForm.ClosingMode.Cancel Dim okToClose As Boolean = True If (BaseDetailForm.cancelMode = BaseDetailForm.CancelCloseMode.Normal) Then Return True If m_ClosingProcessed = True Then Return True If (State And BusinessObjectState.IntermediateObject) <> 0 _ AndAlso (m_State And BusinessObjectState.NewObject) = 0 _ AndAlso Not DbService Is Nothing Then Try Post() If (m_PromptResult = DialogResult.No) AndAlso m_DoDeleteAfterNo Then If Delete(GetKey) = False Then ErrorForm.ShowError(DbService.LastError) Return False End If ElseIf m_PromptResult = DialogResult.Cancel Then okToClose = False End If Catch ex As Exception Trace.WriteLine(ex) End Try ElseIf BaseSettings.SaveOnCancel = True Then If Post() = False Then CancelFormClosing() Return False End If End If If okToClose Then DoClose() m_ClosingProcessed = True Else CancelFormClosing() End If Return okToClose End Function Private Sub FormClosing(ByVal sender As Object, ByVal e As CancelEventArgs) If Loading Then e.Cancel = True Else ' Note: Commented by Ivan bacause of double Posting ' BaseDetailForm.cancelMode = BaseDetailForm.CancelCloseMode.CallPost ' e.Cancel = Not cmdClose_Click() End If End Sub Private Sub CancelFormClosing() If Not ParentForm Is Nothing Then If BaseFormManager.ModalFormCount > 0 Then ParentForm.DialogResult = DialogResult.None End If End If SelectLastFocusedControl() End Sub #End Region #Region "Private Local Methods" Private Sub btnClose_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnClose.Click cmdClose_Click() End Sub Private Sub BaseReportForm_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load If Not Visible Then Return Dim mainObjectRow As DataRow = GetCurrentRow() If Not PermissionObject Is Nothing Then If _ Not Me.ReadOnly AndAlso (Permissions.CanUpdate = False OrElse Permissions.CanUpdateRow(mainObjectRow) = False) Then Me.ReadOnly = True End If End If ResizeForm() If Not ParentForm Is Nothing AndAlso FullScreenMode = False Then AddHandler ParentForm.Closing, AddressOf FormClosing End If End Sub Private Sub BaseReportForm_Resize(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Resize ResizeForm() End Sub #End Region #Region "Properties" Dim m_CloseButton As Boolean = True <DefaultValue(True), Localizable(False)> Public Property ShowCloseButton() As Boolean Get Return m_CloseButton End Get Set(ByVal value As Boolean) m_CloseButton = value If Not btnClose Is Nothing Then btnClose.Visible = value End If End Set End Property <Browsable(True), DefaultValue(False)> Public Overrides Property [ReadOnly]() As Boolean Get Return MyBase.ReadOnly End Get Set(ByVal value As Boolean) MyBase.ReadOnly = value btnClose.Visible = True ArrangeButtons(btnClose.Top, "BottomButtons") End Set End Property Protected Overrides Sub ResizeForm() ArrangeButtons(btnClose.Top, "BottomButtons", btnClose.Height, Height - btnClose.Height - 8) End Sub Public Overrides Sub BaseForm_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) If e.KeyCode = Keys.Escape Then btnClose_Click(btnClose, EventArgs.Empty) Else MyBase.BaseForm_KeyDown(sender, e) End If End Sub #End Region Protected Overrides Sub RemoveParentFormEvents(ByVal form As Form) MyBase.RemoveParentFormEvents(form) Try RemoveHandler form.Closing, AddressOf FormClosing Catch ex As Exception End Try End Sub End Class End Namespace
EIDSS/EIDSS-Legacy
EIDSS v5/vb/Shared/bvwin_common/BaseForms/BaseReportForm.vb
Visual Basic
bsd-2-clause
13,482
' 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.CodeGeneration Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor Imports Microsoft.CodeAnalysis.GenerateType Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Shared.Options Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateType <ExportLanguageService(GetType(IGenerateTypeService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicGenerateTypeService Inherits AbstractGenerateTypeService(Of VisualBasicGenerateTypeService, SimpleNameSyntax, ObjectCreationExpressionSyntax, ExpressionSyntax, TypeBlockSyntax, ArgumentSyntax) Private Shared ReadOnly s_annotation As SyntaxAnnotation = New SyntaxAnnotation <ImportingConstructor> Public Sub New() End Sub Protected Overrides ReadOnly Property DefaultFileExtension As String Get Return ".vb" End Get End Property Protected Overrides Function GenerateParameterNames(semanticModel As SemanticModel, arguments As IList(Of ArgumentSyntax), cancellationToken As CancellationToken) As IList(Of ParameterName) Return semanticModel.GenerateParameterNames(arguments, reservedNames:=Nothing, cancellationToken:=cancellationToken) End Function Protected Overrides Function GetLeftSideOfDot(simpleName As SimpleNameSyntax) As ExpressionSyntax Return simpleName.GetLeftSideOfDot() End Function Protected Overrides Function IsArrayElementType(expression As ExpressionSyntax) As Boolean Return expression.IsParentKind(SyntaxKind.ArrayCreationExpression) End Function Protected Overrides Function IsInCatchDeclaration(expression As ExpressionSyntax) As Boolean Return False End Function Protected Overrides Function IsInInterfaceList(expression As ExpressionSyntax) As Boolean If TypeOf expression Is TypeSyntax AndAlso expression.IsParentKind(SyntaxKind.ImplementsStatement) Then Return True End If If TypeOf expression Is TypeSyntax AndAlso expression.IsParentKind(SyntaxKind.TypeConstraint) AndAlso expression.Parent.IsParentKind(SyntaxKind.TypeParameterMultipleConstraintClause) Then ' TODO: Code Coverage Dim typeConstraint = DirectCast(expression.Parent, TypeConstraintSyntax) Dim constraintClause = DirectCast(typeConstraint.Parent, TypeParameterMultipleConstraintClauseSyntax) Dim index = constraintClause.Constraints.IndexOf(typeConstraint) Return index > 0 End If Return False End Function Protected Overrides Function IsInValueTypeConstraintContext(semanticModel As SemanticModel, expression As Microsoft.CodeAnalysis.VisualBasic.Syntax.ExpressionSyntax, cancellationToken As System.Threading.CancellationToken) As Boolean ' TODO(cyrusn) implement this Return False End Function Protected Overrides Function TryGetArgumentList( objectCreationExpression As ObjectCreationExpressionSyntax, ByRef argumentList As IList(Of ArgumentSyntax)) As Boolean If objectCreationExpression IsNot Nothing AndAlso objectCreationExpression.ArgumentList IsNot Nothing Then argumentList = objectCreationExpression.ArgumentList.Arguments.ToList() Return True End If Return False End Function Protected Overrides Function TryGetNameParts(expression As ExpressionSyntax, ByRef nameParts As IList(Of String)) As Boolean Return expression.TryGetNameParts(nameParts) End Function Protected Overrides Function TryInitializeState( document As SemanticDocument, simpleName As SimpleNameSyntax, cancellationToken As CancellationToken, ByRef generateTypeServiceStateOptions As GenerateTypeServiceStateOptions) As Boolean generateTypeServiceStateOptions = New GenerateTypeServiceStateOptions() If simpleName.IsParentKind(SyntaxKind.DictionaryAccessExpression) Then Return False End If Dim nameOrMemberAccessExpression As ExpressionSyntax = Nothing If simpleName.IsRightSideOfDot() Then nameOrMemberAccessExpression = DirectCast(simpleName.Parent, ExpressionSyntax) If Not (TypeOf simpleName.GetLeftSideOfDot() Is NameSyntax) Then Return False End If Else nameOrMemberAccessExpression = simpleName End If generateTypeServiceStateOptions.NameOrMemberAccessExpression = nameOrMemberAccessExpression If TypeOf nameOrMemberAccessExpression.Parent Is BinaryExpressionSyntax Then Return False End If Dim syntaxTree = document.SyntaxTree Dim semanticModel = document.SemanticModel If Not SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression) Then generateTypeServiceStateOptions.IsDelegateAllowed = False Dim position = nameOrMemberAccessExpression.SpanStart Dim isExpressionContext = syntaxTree.IsExpressionContext(position, cancellationToken) Dim isStatementContext = syntaxTree.IsSingleLineStatementContext(position, cancellationToken) Dim isExpressionOrStatementContext = isExpressionContext OrElse isStatementContext If isExpressionOrStatementContext Then If Not simpleName.IsLeftSideOfDot() Then If nameOrMemberAccessExpression Is Nothing OrElse Not nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Return False End If Dim leftSymbol = semanticModel.GetSymbolInfo(DirectCast(nameOrMemberAccessExpression, MemberAccessExpressionSyntax).Expression).Symbol Dim token = simpleName.GetLastToken().GetNextToken() If leftSymbol Is Nothing OrElse Not leftSymbol.IsKind(SymbolKind.Namespace) OrElse Not token.IsKind(SyntaxKind.DotToken) Then Return False Else generateTypeServiceStateOptions.IsMembersWithModule = True generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = True End If End If If Not generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess AndAlso Not SyntaxFacts.IsInNamespaceOrTypeContext(simpleName) Then Dim token = simpleName.GetLastToken().GetNextToken() If token.IsKind(SyntaxKind.DotToken) AndAlso simpleName.Parent Is token.Parent Then generateTypeServiceStateOptions.IsMembersWithModule = True generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = True End If End If End If End If If nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.InvocationExpression) Then Return False End If ' Check if module could be an option Dim nextToken = simpleName.GetLastToken().GetNextToken() If simpleName.IsLeftSideOfDot() OrElse nextToken.IsKind(SyntaxKind.DotToken) Then If simpleName.IsRightSideOfDot() Then Dim parent = TryCast(simpleName.Parent, QualifiedNameSyntax) If parent IsNot Nothing Then Dim leftSymbol = semanticModel.GetSymbolInfo(parent.Left).Symbol If leftSymbol IsNot Nothing And leftSymbol.IsKind(SymbolKind.Namespace) Then generateTypeServiceStateOptions.IsMembersWithModule = True End If End If End If End If If SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression) Then ' In Namespace or Type Context we cannot have Interface, Enum, Delegate as part of the Left Expression of a QualifiedName If nextToken.IsKind(SyntaxKind.DotToken) Then generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = True generateTypeServiceStateOptions.IsDelegateAllowed = False generateTypeServiceStateOptions.IsMembersWithModule = True End If ' Case : Class Goo(of T as MyType) If nameOrMemberAccessExpression.GetAncestors(Of TypeConstraintSyntax).Any() Then generateTypeServiceStateOptions.IsClassInterfaceTypes = True Return True End If ' Case : Custom Event E As Goo ' Case : Public Event F As Goo If nameOrMemberAccessExpression.GetAncestors(Of EventStatementSyntax)().Any() Then ' Case : Goo ' Only Delegate If simpleName.Parent IsNot Nothing AndAlso TypeOf simpleName.Parent IsNot QualifiedNameSyntax Then generateTypeServiceStateOptions.IsDelegateOnly = True Return True End If ' Case : Something.Goo ... If TypeOf nameOrMemberAccessExpression Is QualifiedNameSyntax Then ' Case : NSOrSomething.GenType.Goo If nextToken.IsKind(SyntaxKind.DotToken) Then If nameOrMemberAccessExpression.Parent IsNot Nothing AndAlso TypeOf nameOrMemberAccessExpression.Parent Is QualifiedNameSyntax Then Return True Else Contract.Fail("Cannot reach this point") End If Else ' Case : NSOrSomething.GenType generateTypeServiceStateOptions.IsDelegateOnly = True Return True End If End If End If ' Case : Public WithEvents G As Delegate1 Dim fieldDecl = nameOrMemberAccessExpression.GetAncestor(Of FieldDeclarationSyntax)() If fieldDecl IsNot Nothing AndAlso fieldDecl.GetModifiers().Any(Function(n) n.Kind() = SyntaxKind.WithEventsKeyword) Then generateTypeServiceStateOptions.IsClassInterfaceTypes = True Return True End If ' No Enum Type Generation in AddHandler or RemoverHandler Statement If nameOrMemberAccessExpression.GetAncestors(Of AccessorStatementSyntax)().Any() Then If Not nextToken.IsKind(SyntaxKind.DotToken) AndAlso nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleAsClause) AndAlso nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.Parameter) AndAlso nameOrMemberAccessExpression.Parent.Parent.IsParentKind(SyntaxKind.ParameterList) AndAlso (nameOrMemberAccessExpression.Parent.Parent.Parent.IsParentKind(SyntaxKind.AddHandlerAccessorStatement) OrElse nameOrMemberAccessExpression.Parent.Parent.Parent.IsParentKind(SyntaxKind.RemoveHandlerAccessorStatement)) Then generateTypeServiceStateOptions.IsDelegateOnly = True Return True End If generateTypeServiceStateOptions.IsEnumNotAllowed = True End If Else ' MemberAccessExpression If nameOrMemberAccessExpression.GetAncestors(Of UnaryExpressionSyntax)().Any(Function(n) n.IsKind(SyntaxKind.AddressOfExpression)) Then generateTypeServiceStateOptions.IsEnumNotAllowed = True End If ' Check to see if the expression is part of Invocation Expression If (nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) OrElse (nameOrMemberAccessExpression.Parent IsNot Nothing AndAlso nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))) _ AndAlso nameOrMemberAccessExpression.IsLeftSideOfDot() Then Dim outerMostMemberAccessExpression As ExpressionSyntax = Nothing If nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then outerMostMemberAccessExpression = nameOrMemberAccessExpression Else Debug.Assert(nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)) outerMostMemberAccessExpression = DirectCast(nameOrMemberAccessExpression.Parent, ExpressionSyntax) End If outerMostMemberAccessExpression = outerMostMemberAccessExpression.GetAncestorsOrThis(Of ExpressionSyntax)().SkipWhile(Function(n) n IsNot Nothing AndAlso n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).FirstOrDefault() If outerMostMemberAccessExpression IsNot Nothing AndAlso TypeOf outerMostMemberAccessExpression Is InvocationExpressionSyntax Then generateTypeServiceStateOptions.IsEnumNotAllowed = True End If End If End If ' New MyDelegate(AddressOf goo) ' New NS.MyDelegate(Function(n) n) If TypeOf nameOrMemberAccessExpression.Parent Is ObjectCreationExpressionSyntax Then Dim objectCreationExpressionOpt = DirectCast(nameOrMemberAccessExpression.Parent, ObjectCreationExpressionSyntax) generateTypeServiceStateOptions.ObjectCreationExpressionOpt = objectCreationExpressionOpt ' Interface and Enum not allowed generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = True If objectCreationExpressionOpt.ArgumentList IsNot Nothing Then If objectCreationExpressionOpt.ArgumentList.CloseParenToken.IsMissing Then Return False End If ' Get the Method Symbol for Delegate to be created ' Currently simple argument is the only argument that can be fed to the Object Creation for Delegate Creation If generateTypeServiceStateOptions.IsDelegateAllowed AndAlso objectCreationExpressionOpt.ArgumentList.Arguments.Count = 1 AndAlso TypeOf objectCreationExpressionOpt.ArgumentList.Arguments(0) Is SimpleArgumentSyntax Then Dim simpleArgumentExpression = DirectCast(objectCreationExpressionOpt.ArgumentList.Arguments(0), SimpleArgumentSyntax).Expression If simpleArgumentExpression.IsKind(SyntaxKind.AddressOfExpression) Then generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMemberGroupIfPresent(semanticModel, DirectCast(simpleArgumentExpression, UnaryExpressionSyntax).Operand, cancellationToken) ElseIf (simpleArgumentExpression.IsKind(SyntaxKind.MultiLineFunctionLambdaExpression) OrElse simpleArgumentExpression.IsKind(SyntaxKind.SingleLineFunctionLambdaExpression) OrElse simpleArgumentExpression.IsKind(SyntaxKind.MultiLineSubLambdaExpression) OrElse simpleArgumentExpression.IsKind(SyntaxKind.SingleLineSubLambdaExpression)) Then generateTypeServiceStateOptions.DelegateCreationMethodSymbol = TryCast(semanticModel.GetSymbolInfo(simpleArgumentExpression, cancellationToken).Symbol, IMethodSymbol) End If ElseIf objectCreationExpressionOpt.ArgumentList.Arguments.Count <> 1 Then generateTypeServiceStateOptions.IsDelegateAllowed = False End If End If Dim initializers = TryCast(objectCreationExpressionOpt.Initializer, ObjectMemberInitializerSyntax) If initializers IsNot Nothing Then For Each initializer In initializers.Initializers.ToList() Dim namedFieldInitializer = TryCast(initializer, NamedFieldInitializerSyntax) If namedFieldInitializer IsNot Nothing Then generateTypeServiceStateOptions.PropertiesToGenerate.Add(namedFieldInitializer.Name) End If Next End If End If Dim variableDeclarator As VariableDeclaratorSyntax = Nothing If generateTypeServiceStateOptions.IsDelegateAllowed Then ' Dim f As MyDel = ... ' Dim f as NS.MyDel = ... If nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleAsClause) AndAlso nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.VariableDeclarator) Then variableDeclarator = DirectCast(nameOrMemberAccessExpression.Parent.Parent, VariableDeclaratorSyntax) If variableDeclarator.Initializer IsNot Nothing AndAlso variableDeclarator.Initializer.Value IsNot Nothing Then Dim expression = variableDeclarator.Initializer.Value If expression.IsKind(SyntaxKind.AddressOfExpression) Then ' ... = AddressOf Goo generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMemberGroupIfPresent(semanticModel, DirectCast(expression, UnaryExpressionSyntax).Operand, cancellationToken) Else If TypeOf expression Is LambdaExpressionSyntax Then '... = Lambda Dim type = semanticModel.GetTypeInfo(expression, cancellationToken).Type If type IsNot Nothing AndAlso type.IsDelegateType() Then generateTypeServiceStateOptions.DelegateCreationMethodSymbol = DirectCast(type, INamedTypeSymbol).DelegateInvokeMethod End If Dim symbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol If symbol IsNot Nothing AndAlso symbol.IsKind(SymbolKind.Method) Then generateTypeServiceStateOptions.DelegateCreationMethodSymbol = DirectCast(symbol, IMethodSymbol) End If End If End If End If ElseIf TypeOf nameOrMemberAccessExpression.Parent Is CastExpressionSyntax Then ' Case: Dim s1 = DirectCast(AddressOf goo, Myy) ' Dim s2 = TryCast(AddressOf goo, Myy) ' Dim s3 = CType(AddressOf goo, Myy) Dim expressionToBeCasted = DirectCast(nameOrMemberAccessExpression.Parent, CastExpressionSyntax).Expression If expressionToBeCasted.IsKind(SyntaxKind.AddressOfExpression) Then ' ... = AddressOf Goo generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMemberGroupIfPresent(semanticModel, DirectCast(expressionToBeCasted, UnaryExpressionSyntax).Operand, cancellationToken) End If End If End If Return True End Function Private Function GetMemberGroupIfPresent(semanticModel As SemanticModel, expression As ExpressionSyntax, cancellationToken As CancellationToken) As IMethodSymbol If expression Is Nothing Then Return Nothing End If Dim memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken) If memberGroup.Count <> 0 Then Return If(memberGroup.ElementAt(0).IsKind(SymbolKind.Method), DirectCast(memberGroup.ElementAt(0), IMethodSymbol), Nothing) End If Return Nothing End Function Public Overrides Function GetRootNamespace(options As CompilationOptions) As String Return DirectCast(options, VisualBasicCompilationOptions).RootNamespace End Function Protected Overloads Overrides Function GetTypeParameters(state As State, semanticModel As SemanticModel, cancellationToken As CancellationToken) As ImmutableArray(Of ITypeParameterSymbol) If TypeOf state.SimpleName Is GenericNameSyntax Then Dim genericName = DirectCast(state.SimpleName, GenericNameSyntax) Dim typeArguments = If(state.SimpleName.Arity = genericName.TypeArgumentList.Arguments.Count, genericName.TypeArgumentList.Arguments.OfType(Of SyntaxNode)().ToList(), Enumerable.Repeat(Of SyntaxNode)(Nothing, state.SimpleName.Arity)) Return Me.GetTypeParameters(state, semanticModel, typeArguments, cancellationToken) End If Return ImmutableArray(Of ITypeParameterSymbol).Empty End Function Protected Overrides Function IsInVariableTypeContext(expression As Microsoft.CodeAnalysis.VisualBasic.Syntax.ExpressionSyntax) As Boolean Return expression.IsParentKind(SyntaxKind.SimpleAsClause) End Function Protected Overrides Function DetermineTypeToGenerateIn(semanticModel As SemanticModel, simpleName As SimpleNameSyntax, cancellationToken As CancellationToken) As INamedTypeSymbol Dim typeBlock = simpleName.GetAncestorsOrThis(Of TypeBlockSyntax). Where(Function(t) t.Members.Count > 0). FirstOrDefault(Function(t) simpleName.SpanStart >= t.Members.First().SpanStart AndAlso simpleName.Span.End <= t.Members.Last().Span.End) Return If(typeBlock Is Nothing, Nothing, TryCast(semanticModel.GetDeclaredSymbol(typeBlock.BlockStatement, cancellationToken), INamedTypeSymbol)) End Function Protected Overrides Function GetAccessibility(state As State, semanticModel As SemanticModel, intoNamespace As Boolean, cancellationToken As CancellationToken) As Accessibility Dim accessibility = DetermineDefaultAccessibility(state, semanticModel, intoNamespace, cancellationToken) If Not state.IsTypeGeneratedIntoNamespaceFromMemberAccess Then Dim accessibilityConstraint = semanticModel.DetermineAccessibilityConstraint( TryCast(state.NameOrMemberAccessExpression, TypeSyntax), cancellationToken) If accessibilityConstraint = Accessibility.Public OrElse accessibilityConstraint = Accessibility.Internal Then accessibility = accessibilityConstraint End If End If Return accessibility End Function Protected Overrides Function DetermineArgumentType(semanticModel As SemanticModel, argument As ArgumentSyntax, cancellationToken As CancellationToken) As ITypeSymbol Return argument.DetermineType(semanticModel, cancellationToken) End Function Protected Overrides Function IsConversionImplicit(compilation As Compilation, sourceType As ITypeSymbol, targetType As ITypeSymbol) As Boolean Return compilation.ClassifyConversion(sourceType, targetType).IsWidening End Function Public Overrides Async Function GetOrGenerateEnclosingNamespaceSymbolAsync(namedTypeSymbol As INamedTypeSymbol, containers() As String, selectedDocument As Document, selectedDocumentRoot As SyntaxNode, cancellationToken As CancellationToken) As Task(Of Tuple(Of INamespaceSymbol, INamespaceOrTypeSymbol, Location)) Dim compilationUnit = DirectCast(selectedDocumentRoot, CompilationUnitSyntax) Dim semanticModel = Await selectedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False) If containers.Length <> 0 Then ' Search the NS declaration in the root Dim containerList = New List(Of String)(containers) Dim enclosingNamespace = GetDeclaringNamespace(containerList, 0, compilationUnit) If enclosingNamespace IsNot Nothing Then Dim enclosingNamespaceSymbol = semanticModel.GetSymbolInfo(enclosingNamespace.Name) If enclosingNamespaceSymbol.Symbol IsNot Nothing Then Return Tuple.Create(DirectCast(enclosingNamespaceSymbol.Symbol, INamespaceSymbol), DirectCast(namedTypeSymbol, INamespaceOrTypeSymbol), DirectCast(enclosingNamespace.Parent, NamespaceBlockSyntax).EndNamespaceStatement.GetLocation()) Return Nothing End If End If End If Dim globalNamespace = semanticModel.GetEnclosingNamespace(0, cancellationToken) Dim rootNamespaceOrType = namedTypeSymbol.GenerateRootNamespaceOrType(containers) Dim lastMember = compilationUnit.Members.LastOrDefault() Dim afterThisLocation As Location = Nothing ' Add at the end If lastMember Is Nothing Then afterThisLocation = semanticModel.SyntaxTree.GetLocation(New TextSpan()) Else afterThisLocation = semanticModel.SyntaxTree.GetLocation(New TextSpan(lastMember.Span.End, 0)) End If Return Tuple.Create(globalNamespace, rootNamespaceOrType, afterThisLocation) End Function Private Function GetDeclaringNamespace(containers As List(Of String), indexDone As Integer, compilationUnit As CompilationUnitSyntax) As NamespaceStatementSyntax For Each member In compilationUnit.Members Dim namespaceDeclaration = GetDeclaringNamespace(containers, 0, member) If namespaceDeclaration IsNot Nothing Then Return namespaceDeclaration End If Next Return Nothing End Function Private Function GetDeclaringNamespace(containers As List(Of String), indexDone As Integer, localRoot As SyntaxNode) As NamespaceStatementSyntax Dim namespaceBlock = TryCast(localRoot, NamespaceBlockSyntax) If namespaceBlock IsNot Nothing Then Dim matchingNamesCount = MatchingNamesFromNamespaceName(containers, indexDone, namespaceBlock.NamespaceStatement) If matchingNamesCount = -1 Then Return Nothing End If If containers.Count = indexDone + matchingNamesCount Then Return namespaceBlock.NamespaceStatement Else indexDone += matchingNamesCount End If For Each member In namespaceBlock.Members Dim resultantNamespace = GetDeclaringNamespace(containers, indexDone, member) If resultantNamespace IsNot Nothing Then Return resultantNamespace End If Next Return Nothing End If Return Nothing End Function Private Function MatchingNamesFromNamespaceName(containers As List(Of String), indexDone As Integer, namespaceStatementSyntax As NamespaceStatementSyntax) As Integer If namespaceStatementSyntax Is Nothing Then Return -1 End If Dim namespaceContainers = New List(Of String)() GetNamespaceContainers(namespaceStatementSyntax.Name, namespaceContainers) If namespaceContainers.Count + indexDone > containers.Count OrElse Not IdentifierMatches(indexDone, namespaceContainers, containers) Then Return -1 End If Return namespaceContainers.Count End Function Private Function IdentifierMatches(indexDone As Integer, namespaceContainers As List(Of String), containers As List(Of String)) As Boolean For index = 0 To namespaceContainers.Count - 1 If Not namespaceContainers(index).Equals(containers(indexDone + index), StringComparison.OrdinalIgnoreCase) Then Return False End If Next Return True End Function Private Sub GetNamespaceContainers(name As NameSyntax, namespaceContainers As List(Of String)) If TypeOf name Is QualifiedNameSyntax Then GetNamespaceContainers(DirectCast(name, QualifiedNameSyntax).Left, namespaceContainers) namespaceContainers.Add(DirectCast(name, QualifiedNameSyntax).Right.Identifier.ValueText) ElseIf TypeOf name Is SimpleNameSyntax Then namespaceContainers.Add(DirectCast(name, SimpleNameSyntax).Identifier.ValueText) Else Debug.Assert(TypeOf name Is GlobalNameSyntax) namespaceContainers.Add(DirectCast(name, GlobalNameSyntax).GlobalKeyword.ValueText) End If End Sub Friend Overrides Function TryGetBaseList(expression As ExpressionSyntax, ByRef typeKindValue As TypeKindOptions) As Boolean typeKindValue = TypeKindOptions.AllOptions If expression Is Nothing Then Return False End If Dim node As SyntaxNode = expression While node IsNot Nothing If TypeOf node Is InheritsStatementSyntax Then If node.Parent IsNot Nothing AndAlso TypeOf node.Parent Is InterfaceBlockSyntax Then typeKindValue = TypeKindOptions.Interface Return True End If typeKindValue = TypeKindOptions.Class Return True ElseIf TypeOf node Is ImplementsStatementSyntax Then typeKindValue = TypeKindOptions.Interface Return True End If node = node.Parent End While Return False End Function Friend Overrides Function IsPublicOnlyAccessibility(expression As ExpressionSyntax, project As Project) As Boolean If expression Is Nothing Then Return False End If If GeneratedTypesMustBePublic(project) Then Return True End If Dim node As SyntaxNode = expression While node IsNot Nothing ' Types in BaseList, Type Constraint or Member Types cannot be of more restricted accessibility than the declaring type If TypeOf node Is InheritsOrImplementsStatementSyntax AndAlso node.Parent IsNot Nothing AndAlso TypeOf node.Parent Is TypeBlockSyntax Then Return IsAllContainingTypeBlocksPublic(node.Parent) End If If TypeOf node Is TypeParameterListSyntax AndAlso node.Parent IsNot Nothing AndAlso TypeOf node.Parent Is TypeStatementSyntax AndAlso node.Parent.Parent IsNot Nothing AndAlso TypeOf node.Parent.Parent Is TypeBlockSyntax Then Return IsAllContainingTypeBlocksPublic(node.Parent.Parent) End If If TypeOf node Is EventStatementSyntax AndAlso node.Parent IsNot Nothing AndAlso TypeOf node.Parent Is TypeBlockSyntax Then Return IsAllContainingTypeBlocksPublic(node) End If If TypeOf node Is FieldDeclarationSyntax AndAlso node.Parent IsNot Nothing AndAlso TypeOf node.Parent Is TypeBlockSyntax Then Return IsAllContainingTypeBlocksPublic(node) End If node = node.Parent End While Return False End Function Private Function IsAllContainingTypeBlocksPublic(node As SyntaxNode) As Boolean ' Make sure all the Ancestoral Type Blocks are Declared with Public Access Modifiers Dim containingTypeBlocks = node.GetAncestorsOrThis(Of TypeBlockSyntax)() If containingTypeBlocks.Count() = 0 Then Return True Else Return containingTypeBlocks.All(Function(typeBlock) typeBlock.GetModifiers().Any(Function(n) n.Kind() = SyntaxKind.PublicKeyword)) End If End Function Friend Overrides Function IsGenericName(expression As SimpleNameSyntax) As Boolean If expression Is Nothing Then Return False End If Dim node = TryCast(expression, GenericNameSyntax) Return node IsNot Nothing End Function Friend Overrides Function IsSimpleName(expression As ExpressionSyntax) As Boolean Return TypeOf expression Is SimpleNameSyntax End Function Friend Overrides Async Function TryAddUsingsOrImportToDocumentAsync(updatedSolution As Solution, modifiedRoot As SyntaxNode, document As Document, simpleName As SimpleNameSyntax, includeUsingsOrImports As String, cancellationToken As CancellationToken) As Task(Of Solution) ' Nothing to include If String.IsNullOrWhiteSpace(includeUsingsOrImports) Then Return updatedSolution End If Dim documentOptions = Await document.GetOptionsAsync(cancellationToken).ConfigureAwait(False) Dim placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst) Dim root As SyntaxNode = Nothing If (modifiedRoot Is Nothing) Then root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Else root = modifiedRoot End If If TypeOf root Is CompilationUnitSyntax Then Dim compilationRoot = DirectCast(root, CompilationUnitSyntax) Dim memberImportsClause = SyntaxFactory.SimpleImportsClause( name:=SyntaxFactory.ParseName(includeUsingsOrImports)) Dim lastToken = memberImportsClause.GetLastToken() Dim lastTokenWithEndOfLineTrivia = lastToken.WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed) ' Replace the token the line carriage memberImportsClause = memberImportsClause.ReplaceToken(lastToken, lastTokenWithEndOfLineTrivia) Dim newImport = SyntaxFactory.ImportsStatement( importsClauses:=SyntaxFactory.SingletonSeparatedList(Of ImportsClauseSyntax)(memberImportsClause)) ' Check if the imports is already present Dim importsClauses = compilationRoot.Imports.Select(Function(n) n.ImportsClauses) For Each importClause In importsClauses For Each import In importClause If TypeOf import Is SimpleImportsClauseSyntax Then Dim membersImport = DirectCast(import, SimpleImportsClauseSyntax) If membersImport.Name IsNot Nothing AndAlso membersImport.Name.ToString().Equals(memberImportsClause.Name.ToString()) Then Return updatedSolution End If End If Next Next ' Check if the GFU is triggered from the namespace same as the imports namespace If Await IsWithinTheImportingNamespaceAsync(document, simpleName.SpanStart, includeUsingsOrImports, cancellationToken).ConfigureAwait(False) Then Return updatedSolution End If Dim addedCompilationRoot = compilationRoot.AddImportsStatement(newImport, placeSystemNamespaceFirst, Formatter.Annotation, Simplifier.Annotation) updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity) End If Return updatedSolution End Function Private Function GetPropertyType(propIdentifierName As SimpleNameSyntax, semanticModel As SemanticModel, typeInference As ITypeInferenceService, cancellationToken As CancellationToken) As ITypeSymbol Dim fieldInitializer = TryCast(propIdentifierName.Parent, NamedFieldInitializerSyntax) If fieldInitializer IsNot Nothing Then Return typeInference.InferType(semanticModel, fieldInitializer.Name, True, cancellationToken) End If Return Nothing End Function Private Function GenerateProperty(propertyName As SimpleNameSyntax, typeSymbol As ITypeSymbol) As IPropertySymbol Return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes:=ImmutableArray(Of AttributeData).Empty, accessibility:=Accessibility.Public, modifiers:=New DeclarationModifiers(), explicitInterfaceImplementations:=Nothing, name:=propertyName.ToString, type:=typeSymbol, refKind:=RefKind.None, parameters:=Nothing, getMethod:=Nothing, setMethod:=Nothing, isIndexer:=False) End Function Friend Overrides Function TryGenerateProperty(propertyName As SimpleNameSyntax, semanticModel As SemanticModel, typeInferenceService As ITypeInferenceService, cancellationToken As CancellationToken, ByRef propertySymbol As IPropertySymbol) As Boolean propertySymbol = Nothing Dim typeSymbol = GetPropertyType(propertyName, semanticModel, typeInferenceService, cancellationToken) If typeSymbol Is Nothing OrElse TypeOf typeSymbol Is IErrorTypeSymbol Then propertySymbol = GenerateProperty(propertyName, semanticModel.Compilation.ObjectType) Return propertySymbol IsNot Nothing End If propertySymbol = GenerateProperty(propertyName, typeSymbol) Return propertySymbol IsNot Nothing End Function Friend Overrides Function GetDelegatingConstructor(document As SemanticDocument, objectCreation As ObjectCreationExpressionSyntax, namedType As INamedTypeSymbol, candidates As ISet(Of IMethodSymbol), cancellationToken As CancellationToken) As IMethodSymbol Dim model = document.SemanticModel Dim oldNode = objectCreation _ .AncestorsAndSelf(ascendOutOfTrivia:=False) _ .Where(Function(node) SpeculationAnalyzer.CanSpeculateOnNode(node)) _ .LastOrDefault() Dim typeNameToReplace = objectCreation.Type Dim newTypeName = namedType.GenerateTypeSyntax() Dim newObjectCreation = objectCreation.WithType(newTypeName).WithAdditionalAnnotations(s_annotation) Dim newNode = oldNode.ReplaceNode(objectCreation, newObjectCreation) Dim speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(oldNode, newNode, model) If speculativeModel IsNot Nothing Then newObjectCreation = DirectCast(newNode.GetAnnotatedNodes(s_annotation).Single(), ObjectCreationExpressionSyntax) Dim symbolInfo = speculativeModel.GetSymbolInfo(newObjectCreation, cancellationToken) Dim parameterTypes As IList(Of ITypeSymbol) = GetSpeculativeArgumentTypes(speculativeModel, newObjectCreation) Return GenerateConstructorHelpers.GetDelegatingConstructor( document, symbolInfo, candidates, namedType, parameterTypes) End If Return Nothing End Function Private Shared Function GetSpeculativeArgumentTypes(model As SemanticModel, newObjectCreation As ObjectCreationExpressionSyntax) As IList(Of ITypeSymbol) Return If(newObjectCreation.ArgumentList Is Nothing, SpecializedCollections.EmptyList(Of ITypeSymbol), newObjectCreation.ArgumentList.Arguments.Select( Function(a) Return If(a.GetExpression() Is Nothing, Nothing, model.GetTypeInfo(a.GetExpression()).ConvertedType) End Function).ToList()) End Function End Class End Namespace
nguerrera/roslyn
src/Features/VisualBasic/Portable/GenerateType/VisualBasicGenerateTypeService.vb
Visual Basic
apache-2.0
43,230
' 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.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 VisitConversion(node As BoundConversion) As BoundNode If Not _inExpressionLambda AndAlso Conversions.IsIdentityConversion(node.ConversionKind) Then Return Visit(node.Operand) End If If node.Operand.Kind = BoundKind.UserDefinedConversion Then If _inExpressionLambda Then Return node.Update(DirectCast(Visit(node.Operand), BoundExpression), node.ConversionKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ConstructorOpt, node.RelaxationLambdaOpt, node.RelaxationReceiverPlaceholderOpt, node.Type) End If If (node.ConversionKind And ConversionKind.Nullable) <> 0 Then Return RewriteNullableUserDefinedConversion(DirectCast(node.Operand, BoundUserDefinedConversion)) End If Return Visit(DirectCast(node.Operand, BoundUserDefinedConversion).UnderlyingExpression) End If ' not all nullable conversions have Nullable flag ' For example Nothing --> Boolean? has conversionkind = WideningNothingLiteral If (node.Type IsNot Nothing AndAlso node.Type.IsNullableType OrElse node.Operand.Type IsNot Nothing AndAlso node.Operand.Type.IsNullableType) AndAlso Not _inExpressionLambda Then Return RewriteNullableConversion(node) End If ' Rewrite Anonymous Delegate conversion into a delegate creation If (node.ConversionKind And ConversionKind.AnonymousDelegate) <> 0 Then Return RewriteAnonymousDelegateConversion(node) End If ' Handle other conversions. Debug.Assert(node.RelaxationReceiverPlaceholderOpt Is Nothing) ' Optimization for object comparisons that are operands of a conversion to boolean. ' Must be done before the object comparison is visited. If Not node.HasErrors AndAlso node.Type.IsBooleanType() AndAlso node.Operand.Type.IsObjectType() Then Dim operand As BoundNode = node.Operand ' Skip parens. While operand.Kind = BoundKind.Parenthesized operand = DirectCast(operand, BoundParenthesized).Expression End While If operand.Kind = BoundKind.BinaryOperator Then Dim binary = DirectCast(operand, BoundBinaryOperator) Select Case binary.OperatorKind And BinaryOperatorKind.OpMask Case BinaryOperatorKind.Equals, BinaryOperatorKind.NotEquals, BinaryOperatorKind.LessThan, BinaryOperatorKind.LessThanOrEqual, BinaryOperatorKind.GreaterThan, BinaryOperatorKind.GreaterThanOrEqual ' Attempt to optimize the coercion. ' The result of the comparison is known to be boolean, so force it to be. ' Rewrite of the operator will do the right thing. Debug.Assert(binary.Type.IsObjectType()) Return Visit(binary.Update(binary.OperatorKind, binary.Left, binary.Right, binary.Checked, binary.ConstantValueOpt, node.Type)) End Select End If End If ' Set "inExpressionLambda" if we're converting lambda to expression tree. Dim returnValue As BoundNode Dim wasInExpressionlambda As Boolean = _inExpressionLambda If (node.ConversionKind And (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree)) = (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree) Then _inExpressionLambda = True End If If node.RelaxationLambdaOpt IsNot Nothing Then returnValue = node.Update(VisitExpressionNode(node.RelaxationLambdaOpt), node.ConversionKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ConstructorOpt, relaxationLambdaOpt:=Nothing, relaxationReceiverPlaceholderOpt:=Nothing, type:=node.Type) ElseIf node.ConversionKind = ConversionKind.InterpolatedString Then returnValue = RewriteInterpolatedStringConversion(node) Else returnValue = MyBase.VisitConversion(node) If returnValue.Kind = BoundKind.Conversion Then returnValue = TransformRewrittenConversion(DirectCast(returnValue, BoundConversion)) End If End If _inExpressionLambda = wasInExpressionlambda Return returnValue End Function ' Rewrite Anonymous Delegate conversion into a delegate creation Private Function RewriteAnonymousDelegateConversion(node As BoundConversion) As BoundNode Debug.Assert(Not Conversions.IsIdentityConversion(node.ConversionKind)) Debug.Assert(node.Operand.Type.IsDelegateType() AndAlso DirectCast(node.Operand.Type, NamedTypeSymbol).IsAnonymousType AndAlso node.Type.IsDelegateType() AndAlso node.Type.SpecialType <> SpecialType.System_MulticastDelegate) Dim F As New SyntheticBoundNodeFactory(Me._topMethod, Me._currentMethodOrLambda, node.Syntax, Me._compilationState, Me._diagnostics) If (node.Operand.IsDefaultValueConstant) Then Return F.Null(node.Type) ElseIf (Not Me._inExpressionLambda AndAlso CouldPossiblyBeNothing(F, node.Operand)) Then Dim savedOriginalValue = F.SynthesizedLocal(node.Operand.Type) Dim checkIfNothing = F.ReferenceIsNothing(F.Local(savedOriginalValue, False)) Dim conversionIfNothing = F.Null(node.Type) Dim convertedValue = New BoundDelegateCreationExpression(node.Syntax, F.Local(savedOriginalValue, False), DirectCast(node.Operand.Type, NamedTypeSymbol).DelegateInvokeMethod, node.RelaxationLambdaOpt, node.RelaxationReceiverPlaceholderOpt, methodGroupOpt:=Nothing, type:=node.Type) Dim conditionalResult As BoundExpression = F.TernaryConditionalExpression(condition:=checkIfNothing, ifTrue:=conversionIfNothing, ifFalse:=convertedValue) Return F.Sequence(savedOriginalValue, F.AssignmentExpression(F.Local(savedOriginalValue, True), VisitExpression(node.Operand)), VisitExpression(conditionalResult)) Else Dim convertedValue = New BoundDelegateCreationExpression(node.Syntax, node.Operand, DirectCast(node.Operand.Type, NamedTypeSymbol).DelegateInvokeMethod, node.RelaxationLambdaOpt, node.RelaxationReceiverPlaceholderOpt, methodGroupOpt:=Nothing, type:=node.Type) Return VisitExpression(convertedValue) End If End Function Private Function CouldPossiblyBeNothing(F As SyntheticBoundNodeFactory, node As BoundExpression) As Boolean Select Case node.Kind Case BoundKind.TernaryConditionalExpression Dim t = DirectCast(node, BoundTernaryConditionalExpression) Return CouldPossiblyBeNothing(F, t.WhenTrue) OrElse CouldPossiblyBeNothing(F, t.WhenFalse) Case BoundKind.Conversion Dim t = DirectCast(node, BoundConversion) Return CouldPossiblyBeNothing(F, t.Operand) Case BoundKind.Lambda Return False Case BoundKind.Call Dim t = DirectCast(node, BoundCall) Return Not (t.Method = F.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Delegate__CreateDelegate, True) OrElse t.Method = F.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Delegate__CreateDelegate4, True) OrElse t.Method = F.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Reflection_MethodInfo__CreateDelegate, True)) Case Else Return True End Select End Function Private Function RewriteNullableConversion(node As BoundConversion) As BoundExpression Debug.Assert(Not _inExpressionLambda) Dim rewrittenOperand = DirectCast(Me.Visit(node.Operand), BoundExpression) If Conversions.IsIdentityConversion(node.ConversionKind) Then Debug.Assert(rewrittenOperand.Type.IsSameTypeIgnoringCustomModifiers(node.Type)) Return rewrittenOperand End If Return RewriteNullableConversion(node, rewrittenOperand) End Function Private Function RewriteNullableConversion(node As BoundConversion, rewrittenOperand As BoundExpression) As BoundExpression Dim resultType = node.Type Dim operandType = rewrittenOperand.Type Debug.Assert(resultType.IsNullableType OrElse (operandType IsNot Nothing AndAlso operandType.IsNullableType), "operand or operator must be nullable") ' Nothing --> T? ==> new T? If rewrittenOperand.ConstantValueOpt Is ConstantValue.Nothing Then Return NullableNull(rewrittenOperand.Syntax, resultType) End If ' Conversions between reference types and nullables do not need further rewriting. ' Lifting will be done as part of box/unbox operation. If operandType.IsReferenceType OrElse resultType.IsReferenceType Then If resultType.IsStringType Then ' conversion to string is an intrinsic conversion and can be lifted. ' T? --> string ==> T.Value -- string ' note that nullable null does not convert to string, i.e. this conversion ' is not null-propagating rewrittenOperand = NullableValue(rewrittenOperand) ElseIf operandType.IsStringType Then ' CType(string, T?) ---> new T?(CType(string, T)) Dim innerTargetType = resultType.GetNullableUnderlyingType Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Dim convKind = Conversions.ClassifyConversion(rewrittenOperand.Type, innerTargetType, useSiteDiagnostics).Key Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteDiagnostics) Return WrapInNullable( TransformRewrittenConversion( node.Update(rewrittenOperand, convKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ConstructorOpt, node.RelaxationLambdaOpt, node.RelaxationReceiverPlaceholderOpt, resultType.GetNullableUnderlyingType)), resultType) ElseIf operandType.IsNullableType Then If HasNoValue(rewrittenOperand) Then ' DirectCast(Nothing, operatorType) Return New BoundDirectCast(node.Syntax, MakeNullLiteral(rewrittenOperand.Syntax, resultType), ConversionKind.WideningNothingLiteral, resultType) End If If HasValue(rewrittenOperand) Then ' DirectCast(operand.GetValueOrDefault, operatorType) Dim unwrappedOperand = NullableValueOrDefault(rewrittenOperand) Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Dim convKind = Conversions.ClassifyDirectCastConversion(unwrappedOperand.Type, resultType, useSiteDiagnostics) Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteDiagnostics) Return New BoundDirectCast(node.Syntax, unwrappedOperand, convKind, resultType) End If End If Return TransformRewrittenConversion( node.Update(rewrittenOperand, node.ConversionKind And (Not ConversionKind.Nullable), node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ConstructorOpt, node.RelaxationLambdaOpt, node.RelaxationReceiverPlaceholderOpt, resultType)) End If Debug.Assert(Not resultType.IsSameTypeIgnoringCustomModifiers(operandType), "converting to same type") Dim result As BoundExpression = rewrittenOperand ' unwrap operand if needed and propagate HasValue if needed. ' If need to propagate HasValue, may also need to hoist the operand value into a temp Dim operandHasValue As BoundExpression = Nothing Dim temps As ArrayBuilder(Of LocalSymbol) = Nothing Dim inits As ArrayBuilder(Of BoundExpression) = Nothing If operandType.IsNullableType Then If resultType.IsNullableType Then If HasValue(rewrittenOperand) Then ' just get the value result = NullableValueOrDefault(rewrittenOperand) ElseIf HasNoValue(rewrittenOperand) Then ' converting null Return NullableNull(result.Syntax, resultType) Else Dim whenNotNull As BoundExpression = Nothing Dim whenNull As BoundExpression = Nothing If IsConditionalAccess(rewrittenOperand, whenNotNull, whenNull) Then If HasValue(whenNotNull) AndAlso HasNoValue(whenNull) Then Return UpdateConditionalAccess(rewrittenOperand, FinishRewriteNullableConversion(node, resultType, NullableValueOrDefault(whenNotNull), Nothing, Nothing, Nothing), NullableNull(result.Syntax, resultType)) End If End If ' uncaptured locals are safe here because we are dealing with a single operand result = ProcessNullableOperand(rewrittenOperand, operandHasValue, temps, inits, doNotCaptureLocals:=True) End If Else ' no propagation. result = NullableValue(rewrittenOperand) End If End If Return FinishRewriteNullableConversion(node, resultType, result, operandHasValue, temps, inits) End Function Private Function FinishRewriteNullableConversion( node As BoundConversion, resultType As TypeSymbol, operand As BoundExpression, operandHasValue As BoundExpression, temps As ArrayBuilder(Of LocalSymbol), inits As ArrayBuilder(Of BoundExpression) ) As BoundExpression Debug.Assert(resultType Is node.Type) Dim unwrappedResultType = resultType.GetNullableUnderlyingTypeOrSelf ' apply unlifted conversion If Not operand.Type.IsSameTypeIgnoringCustomModifiers(unwrappedResultType) Then Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Dim convKind = Conversions.ClassifyConversion(operand.Type, unwrappedResultType, useSiteDiagnostics).Key Debug.Assert(Conversions.ConversionExists(convKind)) ' Check for potential constant folding Dim integerOverflow As Boolean = False Dim constantResult = Conversions.TryFoldConstantConversion(operand, unwrappedResultType, integerOverflow) Debug.Assert(constantResult Is Nothing OrElse Not constantResult.IsBad) If constantResult IsNot Nothing AndAlso Not constantResult.IsBad Then ' Overflow should have been detected at classification time during binding. Debug.Assert(Not integerOverflow OrElse Not node.Checked) operand = RewriteConstant(New BoundLiteral(node.Syntax, constantResult, unwrappedResultType), constantResult) Else _diagnostics.Add(node, useSiteDiagnostics) operand = TransformRewrittenConversion( New BoundConversion(node.Syntax, operand, convKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ConstructorOpt, node.RelaxationLambdaOpt, node.RelaxationReceiverPlaceholderOpt, unwrappedResultType)) End If End If ' wrap if needed If resultType.IsNullableType Then operand = WrapInNullable(operand, resultType) ' propagate null from the operand If operandHasValue IsNot Nothing Then operand = MakeTernaryConditionalExpression(node.Syntax, operandHasValue, operand, NullableNull(operand.Syntax, resultType)) ' if used temps, arrange a sequence for temps and inits. If temps IsNot Nothing Then operand = New BoundSequence(operand.Syntax, temps.ToImmutableAndFree, inits.ToImmutableAndFree, operand, operand.Type) End If End If End If Return operand End Function Private Function RewriteNullableReferenceConversion(node As BoundConversion, rewrittenOperand As BoundExpression) As BoundExpression Dim resultType = node.Type Dim operandType = rewrittenOperand.Type If operandType.IsStringType Then ' CType(string, T?) ---> new T?(CType(string, T)) Dim innerTargetType = resultType.GetNullableUnderlyingType Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Dim convKind = Conversions.ClassifyConversion(operandType, innerTargetType, useSiteDiagnostics).Key Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteDiagnostics) Return WrapInNullable( TransformRewrittenConversion( node.Update(rewrittenOperand, convKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ConstructorOpt, node.RelaxationLambdaOpt, node.RelaxationReceiverPlaceholderOpt, resultType.GetNullableUnderlyingType)), resultType) End If If resultType.IsStringType Then ' conversion to string is an intrinsic conversion and can be lifted. ' T? --> string ==> T.Value -- string ' note that nullable null does not convert to string null, i.e. this conversion ' is not null-propagating rewrittenOperand = NullableValue(rewrittenOperand) Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Dim convKind = Conversions.ClassifyDirectCastConversion(rewrittenOperand.Type, resultType, useSiteDiagnostics) Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteDiagnostics) Return TransformRewrittenConversion( node.Update(rewrittenOperand, node.ConversionKind And (Not ConversionKind.Nullable), node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ConstructorOpt, node.RelaxationLambdaOpt, node.RelaxationReceiverPlaceholderOpt, resultType)) End If If operandType.IsNullableType Then ' T? --> RefType, this is a boxing conversion (DirectCast) If HasNoValue(rewrittenOperand) Then ' DirectCast(Nothing, operatorType) Return New BoundDirectCast(node.Syntax, MakeNullLiteral(rewrittenOperand.Syntax, resultType), ConversionKind.WideningNothingLiteral, resultType) End If If HasValue(rewrittenOperand) Then ' DirectCast(operand.GetValueOrDefault, operatorType) Dim unwrappedOperand = NullableValueOrDefault(rewrittenOperand) Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Dim convKind = Conversions.ClassifyDirectCastConversion(unwrappedOperand.Type, resultType, useSiteDiagnostics) Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteDiagnostics) Return New BoundDirectCast(node.Syntax, unwrappedOperand, convKind, resultType) End If End If If resultType.IsNullableType Then ' RefType --> T? , this is just an unboxing conversion. Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Dim convKind = Conversions.ClassifyDirectCastConversion(rewrittenOperand.Type, resultType, useSiteDiagnostics) Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteDiagnostics) Return New BoundDirectCast(node.Syntax, rewrittenOperand, convKind, resultType) End If Throw ExceptionUtilities.Unreachable End Function Private Function RewriteNullableUserDefinedConversion(node As BoundUserDefinedConversion) As BoundNode ' User defined conversions rewrite as: ' Sequence(operandCapture, If(operandCapture.HasValue, Conversion(operandCapture), Null) ' ' The structure of the nullable BoundUserDefinedConversion looks like this: ' [OPERAND] -> [IN-CONVERSION] -> [CALL] -> [OUT-CONVERSION] ' ' In-conversion also does unwrapping. ' Out-conversion also does wrapping. ' ' operand ' the thing that we will be converting. Must be nullable. We will be checking HasValue on it and will return null if it does not. Dim operand = node.Operand Debug.Assert(operand.Type.IsNullableType) ' inner conversion Dim inConversion = node.InConversionOpt Debug.Assert(inConversion IsNot Nothing, "There is always an inner conversion.") ' operator Dim operatorCall As BoundCall = node.Call ' outer conversion Dim outConversion As BoundConversion = node.OutConversionOpt Debug.Assert(outConversion IsNot Nothing, "There is always an outer conversion.") ' result type ' type that we need to return from the conversion. It must be a nullable type. Dim resultType As TypeSymbol = outConversion.Type Debug.Assert(resultType.IsNullableType, "lifted operator must have nullable type") ' === START REWRITE Dim rewrittenOperand = Me.VisitExpressionNode(operand) ' this is what we return when operand has no value Dim whenHasNoValue As BoundExpression = NullableNull(node.Syntax, resultType) '== TRIVIAL CASE If HasNoValue(rewrittenOperand) Then Return whenHasNoValue End If ' Do we know statically that operand has value? Dim operandHasValue As Boolean = HasValue(rewrittenOperand) ' This is what we will pass to the operator method if operand has value Dim inputToOperatorMethod As BoundExpression Dim condition As BoundExpression = Nothing Dim temp As SynthesizedLocal = Nothing If operandHasValue Then ' just pass the operand, no need to capture inputToOperatorMethod = rewrittenOperand Else ' operator input would be captured operand Dim tempInit As BoundExpression = Nothing ' no need to capture locals since we will not ' evaluate anything between HasValue and ValueOrDefault Dim capturedleft As BoundExpression = CaptureNullableIfNeeded(rewrittenOperand, temp, tempInit, doNotCaptureLocals:=True) condition = NullableHasValue(If(tempInit, capturedleft)) ' Note that we will be doing the conversion only when ' we know that we have a value, so we will pass to the conversion wrapped NullableValueOrDefault. ' so that it could use NullableValueOrDefault instead of Value. inputToOperatorMethod = WrapInNullable(NullableValueOrDefault(capturedleft), capturedleft.Type) End If ' inConversion is always a nullable conversion. We need to rewrite it. inputToOperatorMethod = RewriteNullableConversion(inConversion, inputToOperatorMethod) ' result of the conversion when operand has value. (replace the arg) Dim whenHasValue As BoundExpression = operatorCall.Update(operatorCall.Method, Nothing, operatorCall.ReceiverOpt, ImmutableArray.Create(inputToOperatorMethod), operatorCall.ConstantValueOpt, operatorCall.SuppressObjectClone, operatorCall.Type) ' outConversion is a nullable conversion. need to rewrite it. whenHasValue = RewriteNullableConversion(outConversion, whenHasValue) ' Now we have whenHasValue, whenHasNoValue and condition. The rest is easy. If operandHasValue Then Return whenHasValue Else ' == rewrite operand as ternary expression Dim result As BoundExpression = MakeTernaryConditionalExpression(node.Syntax, condition, whenHasValue, whenHasNoValue) ' if we used a temp, arrange a sequence for it If temp IsNot Nothing Then result = New BoundSequence(node.Syntax, ImmutableArray.Create(Of LocalSymbol)(temp), ImmutableArray(Of BoundExpression).Empty, result, result.Type) End If Return result End If End Function #Region "Post-rewrite conversion" Private Function TransformRewrittenConversion(rewrittenConversion As BoundConversion) As BoundExpression If rewrittenConversion.HasErrors OrElse _inExpressionLambda Then Return rewrittenConversion End If Dim result As BoundExpression = rewrittenConversion Dim underlyingTypeTo = rewrittenConversion.Type.GetEnumUnderlyingTypeOrSelf() Dim operand = rewrittenConversion.Operand If operand.IsNothingLiteral() Then Debug.Assert(rewrittenConversion.ConversionKind = ConversionKind.WideningNothingLiteral OrElse (Conversions.IsIdentityConversion(rewrittenConversion.ConversionKind) AndAlso Not underlyingTypeTo.IsTypeParameter() AndAlso underlyingTypeTo.IsReferenceType) OrElse (rewrittenConversion.ConversionKind And (ConversionKind.Reference Or ConversionKind.Array)) <> 0) If underlyingTypeTo.IsTypeParameter() OrElse underlyingTypeTo.IsReferenceType Then result = RewriteAsDirectCast(rewrittenConversion) Else Debug.Assert(underlyingTypeTo.IsValueType) ' Find the parameterless constructor to be used in conversion of Nothing to a value type result = InitWithParameterlessValueTypeConstructor(rewrittenConversion, DirectCast(underlyingTypeTo, NamedTypeSymbol)) End If ElseIf operand.Kind = BoundKind.Lambda Then Return rewrittenConversion Else Dim underlyingTypeFrom = operand.Type.GetEnumUnderlyingTypeOrSelf() If underlyingTypeFrom.IsFloatingType() AndAlso underlyingTypeTo.IsIntegralType() Then result = RewriteFloatingToIntegralConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeFrom.IsDecimalType() AndAlso (underlyingTypeTo.IsBooleanType() OrElse underlyingTypeTo.IsIntegralType() OrElse underlyingTypeTo.IsFloatingType) Then result = RewriteDecimalToNumericOrBooleanConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeTo.IsDecimalType() AndAlso (underlyingTypeFrom.IsBooleanType() OrElse underlyingTypeFrom.IsIntegralType() OrElse underlyingTypeFrom.IsFloatingType) Then result = RewriteNumericOrBooleanToDecimalConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeFrom.IsNullableType OrElse underlyingTypeTo.IsNullableType Then ' conversions between nullable and reference types are not directcasts, they are boxing/unboxing conversions. ' CodeGen will handle this. ElseIf underlyingTypeFrom.IsObjectType() AndAlso (underlyingTypeTo.IsTypeParameter() OrElse underlyingTypeTo.IsIntrinsicType()) Then result = RewriteFromObjectConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeFrom.IsTypeParameter() Then result = RewriteAsDirectCast(rewrittenConversion) ElseIf underlyingTypeTo.IsTypeParameter() Then result = RewriteAsDirectCast(rewrittenConversion) ElseIf underlyingTypeFrom.IsStringType() AndAlso (underlyingTypeTo.IsCharSZArray() OrElse underlyingTypeTo.IsIntrinsicValueType()) Then result = RewriteFromStringConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeTo.IsStringType() AndAlso (underlyingTypeFrom.IsCharSZArray() OrElse underlyingTypeFrom.IsIntrinsicValueType()) Then result = RewriteToStringConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeFrom.IsReferenceType AndAlso underlyingTypeTo.IsCharSZArray() Then result = RewriteReferenceTypeToCharArrayRankOneConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeTo.IsReferenceType Then result = RewriteAsDirectCast(rewrittenConversion) ElseIf underlyingTypeFrom.IsReferenceType AndAlso underlyingTypeTo.IsIntrinsicValueType() Then result = RewriteFromObjectConversion(rewrittenConversion, Compilation.GetSpecialType(SpecialType.System_Object), underlyingTypeTo) Else Debug.Assert(underlyingTypeTo.IsValueType) ' Find the parameterless constructor to be used in emit phase, see 'CodeGenerator.EmitConversionExpression' result = InitWithParameterlessValueTypeConstructor(rewrittenConversion, DirectCast(underlyingTypeTo, NamedTypeSymbol)) End If End If Return result End Function ''' <summary> Given bound conversion node and the type the conversion is being done to initializes ''' bound conversion node with the reference to parameterless value type constructor and returns ''' modified bound node. ''' In case the constructor is not accessible from current context, or there is no parameterless ''' constructor found in the type (which should never happen, because in such cases a synthesized ''' constructor is supposed to be generated) ''' </summary> Private Function InitWithParameterlessValueTypeConstructor(node As BoundConversion, typeTo As NamedTypeSymbol) As BoundExpression Debug.Assert(typeTo.IsValueType AndAlso Not typeTo.IsTypeParameter) Debug.Assert(node.RelaxationLambdaOpt Is Nothing AndAlso node.RelaxationReceiverPlaceholderOpt Is Nothing) ' find valuetype parameterless constructor and check the accessibility For Each constr In typeTo.InstanceConstructors ' NOTE: we intentionally skip constructors with all ' optional parameters; this matches Dev10 behavior If constr.ParameterCount = 0 Then ' check 'constr' If AccessCheck.IsSymbolAccessible(constr, Me._topMethod.ContainingType, typeTo, useSiteDiagnostics:=Nothing) Then ' before we use constructor symbol we need to report use site error if any Dim useSiteError = constr.GetUseSiteErrorInfo() If useSiteError IsNot Nothing Then ReportDiagnostic(node, useSiteError, Me._diagnostics) End If ' update bound node Return node.Update(node.Operand, node.ConversionKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, constr, node.RelaxationLambdaOpt, node.RelaxationReceiverPlaceholderOpt, node.Type) End If ' exit for each in any case Return node End If Next ' This point should not be reachable, because if there is no constructor in the ' loaded value type, we should have generated a synthesized constructor. Throw ExceptionUtilities.Unreachable End Function Private Function RewriteReferenceTypeToCharArrayRankOneConversion(node As BoundConversion, typeFrom As TypeSymbol, typeTo As TypeSymbol) As BoundExpression Debug.Assert(typeFrom.IsReferenceType AndAlso typeTo.IsCharSZArray()) Dim result As BoundExpression = node Const member As WellKnownMember = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneObject Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then Dim operand = node.Operand Debug.Assert(memberSymbol.Parameters(0).Type.IsObjectType()) If Not operand.Type.IsObjectType() Then Dim objectType As TypeSymbol = memberSymbol.Parameters(0).Type Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing operand = New BoundDirectCast(operand.Syntax, operand, Conversions.ClassifyDirectCastConversion(operand.Type, objectType, useSiteDiagnostics), objectType) _diagnostics.Add(node, useSiteDiagnostics) End If result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) Debug.Assert(memberSymbol.ReturnType.IsSameTypeIgnoringCustomModifiers(node.Type)) End If Return result End Function Private Function RewriteAsDirectCast(node As BoundConversion) As BoundExpression #If DEBUG Then Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Debug.Assert(node.Operand.IsNothingLiteral() OrElse (node.ConversionKind And (Not ConversionKind.DelegateRelaxationLevelMask)) = Conversions.ClassifyDirectCastConversion(node.Operand.Type, node.Type, useSiteDiagnostics)) #End If ' TODO: A chain of widening reference conversions that starts from NOTHING literal can be collapsed to a single node. ' Semantics::Convert does this in Dev10. ' It looks like we already achieve the same result due to folding of NOTHING conversions. Return New BoundDirectCast(node.Syntax, node.Operand, node.ConversionKind, node.Type, Nothing) End Function Private Function RewriteFromObjectConversion(node As BoundConversion, typeFrom As TypeSymbol, underlyingTypeTo As TypeSymbol) As BoundExpression Debug.Assert(typeFrom.IsObjectType()) Dim result As BoundExpression = node Dim member As WellKnownMember = WellKnownMember.Count Select Case underlyingTypeTo.SpecialType Case SpecialType.System_Boolean : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanObject Case SpecialType.System_SByte : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteObject Case SpecialType.System_Byte : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToByteObject Case SpecialType.System_Int16 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToShortObject Case SpecialType.System_UInt16 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortObject Case SpecialType.System_Int32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerObject Case SpecialType.System_UInt32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerObject Case SpecialType.System_Int64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToLongObject Case SpecialType.System_UInt64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToULongObject Case SpecialType.System_Single : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleObject Case SpecialType.System_Double : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleObject Case SpecialType.System_Decimal : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalObject Case SpecialType.System_DateTime : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDateObject Case SpecialType.System_Char : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToCharObject Case SpecialType.System_String : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringObject Case Else If underlyingTypeTo.IsTypeParameter() Then member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object End If End Select If member <> WellKnownMember.Count Then Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then If member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object Then memberSymbol = memberSymbol.Construct(underlyingTypeTo) End If Dim operand = node.Operand If Not operand.Type.IsObjectType() Then Debug.Assert(typeFrom.IsObjectType()) Debug.Assert(operand.Type.IsReferenceType) Debug.Assert(underlyingTypeTo.IsIntrinsicValueType()) Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing operand = New BoundDirectCast(operand.Syntax, operand, Conversions.ClassifyDirectCastConversion(operand.Type, typeFrom, useSiteDiagnostics), typeFrom) _diagnostics.Add(node, useSiteDiagnostics) End If Debug.Assert(memberSymbol.ReturnType.IsSameTypeIgnoringCustomModifiers(underlyingTypeTo)) Debug.Assert(memberSymbol.Parameters(0).Type Is typeFrom) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) Dim targetResultType = node.Type If Not targetResultType.IsSameTypeIgnoringCustomModifiers(memberSymbol.ReturnType) Then ' Must be conversion to an enum Debug.Assert(targetResultType.IsEnumType()) Dim conv = ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions #If DEBUG Then Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Debug.Assert(conv = Conversions.ClassifyConversion(memberSymbol.ReturnType, targetResultType, useSiteDiagnostics).Key) #End If result = New BoundConversion(node.Syntax, DirectCast(result, BoundExpression), conv, node.Checked, node.ExplicitCastInCode, targetResultType, Nothing) End If End If End If Return result End Function Private Function RewriteToStringConversion(node As BoundConversion, underlyingTypeFrom As TypeSymbol, typeTo As TypeSymbol) As BoundExpression Debug.Assert(typeTo.IsStringType()) Dim result As BoundExpression = node Dim memberSymbol As MethodSymbol = Nothing If underlyingTypeFrom.IsCharSZArray() Then Const memberId As SpecialMember = SpecialMember.System_String__CtorSZArrayChar memberSymbol = DirectCast(ContainingAssembly.GetSpecialTypeMember(memberId), MethodSymbol) If ReportMissingOrBadRuntimeHelper(node, memberId, memberSymbol) Then memberSymbol = Nothing End If Else Dim member As WellKnownMember = WellKnownMember.Count ' Note, conversion from Object is handled by RewriteFromObjectConversion. Select Case underlyingTypeFrom.SpecialType Case SpecialType.System_Boolean : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringBoolean Case SpecialType.System_SByte, SpecialType.System_Int16, SpecialType.System_Int32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt32 Case SpecialType.System_Byte : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringByte Case SpecialType.System_UInt16, SpecialType.System_UInt32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt32 Case SpecialType.System_Int64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt64 Case SpecialType.System_UInt64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt64 Case SpecialType.System_Single : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringSingle Case SpecialType.System_Double : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDouble Case SpecialType.System_Decimal : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDecimal Case SpecialType.System_DateTime : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDateTime Case SpecialType.System_Char : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringChar End Select If member <> WellKnownMember.Count Then memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then memberSymbol = Nothing End If End If End If If memberSymbol IsNot Nothing Then Dim operand = node.Operand Dim operandType = operand.Type If Not operandType.IsSameTypeIgnoringCustomModifiers(memberSymbol.Parameters(0).Type) Then Dim conv As ConversionKind If operandType.IsEnumType() Then conv = ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions Else conv = ConversionKind.WideningNumeric End If #If DEBUG Then Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Debug.Assert(conv = Conversions.ClassifyConversion(operandType, memberSymbol.Parameters(0).Type, useSiteDiagnostics).Key) #End If operand = New BoundConversion(node.Syntax, operand, conv, node.Checked, node.ExplicitCastInCode, memberSymbol.Parameters(0).Type, Nothing) End If If memberSymbol.MethodKind = MethodKind.Constructor Then Debug.Assert(memberSymbol.ContainingType Is typeTo) result = New BoundObjectCreationExpression( node.Syntax, memberSymbol, ImmutableArray.Create(operand), Nothing, typeTo) Else Debug.Assert(memberSymbol.ReturnType Is typeTo) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) End If End If Return result End Function Private Function RewriteFromStringConversion(node As BoundConversion, typeFrom As TypeSymbol, underlyingTypeTo As TypeSymbol) As BoundExpression Debug.Assert(typeFrom.IsStringType()) Dim result As BoundExpression = node Dim member As WellKnownMember = WellKnownMember.Count Select Case underlyingTypeTo.SpecialType Case SpecialType.System_Boolean : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanString Case SpecialType.System_SByte : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteString Case SpecialType.System_Byte : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToByteString Case SpecialType.System_Int16 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToShortString Case SpecialType.System_UInt16 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortString Case SpecialType.System_Int32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerString Case SpecialType.System_UInt32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerString Case SpecialType.System_Int64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToLongString Case SpecialType.System_UInt64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToULongString Case SpecialType.System_Single : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleString Case SpecialType.System_Double : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleString Case SpecialType.System_Decimal : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalString Case SpecialType.System_DateTime : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDateString Case SpecialType.System_Char : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToCharString Case Else If underlyingTypeTo.IsCharSZArray() Then member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneString End If End Select If member <> WellKnownMember.Count Then Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then Dim operand = node.Operand Debug.Assert(memberSymbol.ReturnType.IsSameTypeIgnoringCustomModifiers(underlyingTypeTo)) Debug.Assert(memberSymbol.Parameters(0).Type Is typeFrom) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) Dim targetResultType = node.Type If Not targetResultType.IsSameTypeIgnoringCustomModifiers(memberSymbol.ReturnType) Then ' Must be conversion to an enum Debug.Assert(targetResultType.IsEnumType()) Dim conv = ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions #If DEBUG Then Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Debug.Assert(conv = Conversions.ClassifyConversion(memberSymbol.ReturnType, targetResultType, useSiteDiagnostics).Key) #End If result = New BoundConversion(node.Syntax, DirectCast(result, BoundExpression), conv, node.Checked, node.ExplicitCastInCode, targetResultType, Nothing) End If End If End If Return result End Function Private Function RewriteNumericOrBooleanToDecimalConversion(node As BoundConversion, underlyingTypeFrom As TypeSymbol, typeTo As TypeSymbol) As BoundExpression Debug.Assert(typeTo.IsDecimalType() AndAlso (underlyingTypeFrom.IsBooleanType() OrElse underlyingTypeFrom.IsIntegralType() OrElse underlyingTypeFrom.IsFloatingType)) Dim result As BoundExpression = node Dim memberSymbol As MethodSymbol If underlyingTypeFrom.IsBooleanType() Then Const memberId As WellKnownMember = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalBoolean memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(memberId), MethodSymbol) If ReportMissingOrBadRuntimeHelper(node, memberId, memberSymbol) Then memberSymbol = Nothing End If Else Dim member As SpecialMember Select Case underlyingTypeFrom.SpecialType Case SpecialType.System_SByte, SpecialType.System_Byte, SpecialType.System_Int16, SpecialType.System_UInt16, SpecialType.System_Int32 : member = SpecialMember.System_Decimal__CtorInt32 Case SpecialType.System_UInt32 : member = SpecialMember.System_Decimal__CtorUInt32 Case SpecialType.System_Int64 : member = SpecialMember.System_Decimal__CtorInt64 Case SpecialType.System_UInt64 : member = SpecialMember.System_Decimal__CtorUInt64 Case SpecialType.System_Single : member = SpecialMember.System_Decimal__CtorSingle Case SpecialType.System_Double : member = SpecialMember.System_Decimal__CtorDouble Case Else 'cannot get here Return result End Select memberSymbol = DirectCast(ContainingAssembly.GetSpecialTypeMember(member), MethodSymbol) If ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then memberSymbol = Nothing End If End If ' Call the method. If memberSymbol IsNot Nothing Then Dim operand = node.Operand Dim operandType = operand.Type If operandType IsNot memberSymbol.Parameters(0).Type Then Dim conv As ConversionKind If operandType.IsEnumType() Then conv = ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions Else conv = ConversionKind.WideningNumeric End If #If DEBUG Then Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Debug.Assert(conv = Conversions.ClassifyConversion(operandType, memberSymbol.Parameters(0).Type, useSiteDiagnostics).Key) #End If operand = New BoundConversion(node.Syntax, operand, conv, node.Checked, node.ExplicitCastInCode, memberSymbol.Parameters(0).Type, Nothing) End If If memberSymbol.MethodKind = MethodKind.Constructor Then Debug.Assert(memberSymbol.ContainingType Is typeTo) result = New BoundObjectCreationExpression( node.Syntax, memberSymbol, ImmutableArray.Create(operand), Nothing, typeTo) Else Debug.Assert(memberSymbol.ReturnType Is typeTo) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) End If End If Return result End Function Private Function RewriteDecimalToNumericOrBooleanConversion(node As BoundConversion, typeFrom As TypeSymbol, underlyingTypeTo As TypeSymbol) As BoundExpression Debug.Assert(typeFrom.IsDecimalType() AndAlso (underlyingTypeTo.IsBooleanType() OrElse underlyingTypeTo.IsIntegralType() OrElse underlyingTypeTo.IsFloatingType)) Dim result As BoundExpression = node Dim member As WellKnownMember Select Case underlyingTypeTo.SpecialType Case SpecialType.System_Boolean : member = WellKnownMember.System_Convert__ToBooleanDecimal Case SpecialType.System_SByte : member = WellKnownMember.System_Convert__ToSByteDecimal Case SpecialType.System_Byte : member = WellKnownMember.System_Convert__ToByteDecimal Case SpecialType.System_Int16 : member = WellKnownMember.System_Convert__ToInt16Decimal Case SpecialType.System_UInt16 : member = WellKnownMember.System_Convert__ToUInt16Decimal Case SpecialType.System_Int32 : member = WellKnownMember.System_Convert__ToInt32Decimal Case SpecialType.System_UInt32 : member = WellKnownMember.System_Convert__ToUInt32Decimal Case SpecialType.System_Int64 : member = WellKnownMember.System_Convert__ToInt64Decimal Case SpecialType.System_UInt64 : member = WellKnownMember.System_Convert__ToUInt64Decimal Case SpecialType.System_Single : member = WellKnownMember.System_Convert__ToSingleDecimal Case SpecialType.System_Double : member = WellKnownMember.System_Convert__ToDoubleDecimal Case Else 'cannot get here Return result End Select Dim memberSymbol As MethodSymbol ' Call the method. memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then Dim operand = node.Operand Debug.Assert(memberSymbol.ReturnType Is underlyingTypeTo) Debug.Assert(memberSymbol.Parameters(0).Type Is typeFrom) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) Dim targetResultType = node.Type If targetResultType IsNot memberSymbol.ReturnType Then ' Must be conversion to an enum Debug.Assert(targetResultType.IsEnumType()) Dim conv = ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions #If DEBUG Then Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Debug.Assert(conv = Conversions.ClassifyConversion(memberSymbol.ReturnType, targetResultType, useSiteDiagnostics).Key) #End If result = New BoundConversion(node.Syntax, DirectCast(result, BoundExpression), conv, node.Checked, node.ExplicitCastInCode, targetResultType, Nothing) End If End If Return result End Function Private Function RewriteFloatingToIntegralConversion(node As BoundConversion, typeFrom As TypeSymbol, underlyingTypeTo As TypeSymbol) As BoundExpression Debug.Assert(typeFrom.IsFloatingType() AndAlso underlyingTypeTo.IsIntegralType()) Dim result As BoundExpression = node Dim mathRound As MethodSymbol ' Call Math.Round method to enforce VB style rounding. Const memberId As WellKnownMember = WellKnownMember.System_Math__RoundDouble mathRound = DirectCast(Compilation.GetWellKnownTypeMember(memberId), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, memberId, mathRound) Then ' If we got here and passed badness check, it should be safe to assume that we have ' a "good" symbol for Double type Dim operand = node.Operand #If DEBUG Then Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing #End If If typeFrom IsNot mathRound.Parameters(0).Type Then ' Converting from Single #If DEBUG Then Debug.Assert(ConversionKind.WideningNumeric = Conversions.ClassifyConversion(typeFrom, mathRound.Parameters(0).Type, useSiteDiagnostics).Key) #End If operand = New BoundConversion(node.Syntax, operand, ConversionKind.WideningNumeric, node.Checked, node.ExplicitCastInCode, mathRound.Parameters(0).Type, Nothing) End If Dim callMathRound = New BoundCall(node.Syntax, mathRound, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, mathRound.ReturnType) #If DEBUG Then Debug.Assert(node.ConversionKind = Conversions.ClassifyConversion(mathRound.ReturnType, node.Type, useSiteDiagnostics).Key) #End If result = New BoundConversion(node.Syntax, callMathRound, node.ConversionKind, node.Checked, node.ExplicitCastInCode, node.Type, Nothing) End If Return result End Function #End Region #Region "DirectCast" Public Overrides Function VisitDirectCast(node As BoundDirectCast) As BoundNode If Not _inExpressionLambda AndAlso Conversions.IsIdentityConversion(node.ConversionKind) Then Return VisitExpressionNode(node.Operand) End If ' Set "inExpressionLambda" if we're converting lambda to expression tree. Dim returnValue As BoundNode Dim wasInExpressionlambda As Boolean = _inExpressionLambda If (node.ConversionKind And (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree)) = (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree) Then _inExpressionLambda = True End If If node.RelaxationLambdaOpt Is Nothing Then returnValue = MyBase.VisitDirectCast(node) Else returnValue = node.Update(VisitExpressionNode(node.RelaxationLambdaOpt), node.ConversionKind, node.SuppressVirtualCalls, node.ConstantValueOpt, relaxationLambdaOpt:=Nothing, type:=node.Type) End If _inExpressionLambda = wasInExpressionlambda Return returnValue End Function #End Region #Region "TryCast" Public Overrides Function VisitTryCast(node As BoundTryCast) As BoundNode If Not _inExpressionLambda AndAlso Conversions.IsIdentityConversion(node.ConversionKind) Then Return Visit(node.Operand) End If ' Set "inExpressionLambda" if we're converting lambda to expression tree. Dim returnValue As BoundNode Dim wasInExpressionlambda As Boolean = _inExpressionLambda If (node.ConversionKind And (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree)) = (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree) Then _inExpressionLambda = True End If If node.RelaxationLambdaOpt Is Nothing Then returnValue = Nothing If Conversions.IsWideningConversion(node.ConversionKind) AndAlso Not Conversions.IsIdentityConversion(node.ConversionKind) Then Dim operand As BoundExpression = node.Operand If operand.Kind <> BoundKind.Lambda Then Dim typeFrom As TypeSymbol = operand.Type Dim typeTo As TypeSymbol = node.Type If (Not typeTo.IsTypeParameter()) AndAlso typeTo.IsReferenceType AndAlso (Not typeFrom.IsTypeParameter()) AndAlso typeFrom.IsReferenceType Then #If DEBUG Then Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing Debug.Assert(node.ConversionKind = Conversions.ClassifyDirectCastConversion(operand.Type, node.Type, useSiteDiagnostics)) #End If returnValue = New BoundDirectCast(node.Syntax, DirectCast(Visit(operand), BoundExpression), node.ConversionKind, typeTo, Nothing) End If End If End If If returnValue Is Nothing Then returnValue = MyBase.VisitTryCast(node) End If Else returnValue = node.Update(VisitExpressionNode(node.RelaxationLambdaOpt), node.ConversionKind, node.ConstantValueOpt, relaxationLambdaOpt:=Nothing, type:=node.Type) End If _inExpressionLambda = wasInExpressionlambda Return returnValue End Function #End Region End Class End Namespace
ericfe-ms/roslyn
src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_Conversion.vb
Visual Basic
apache-2.0
71,101
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.18052 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace My.Resources 'This class was auto-generated by the StronglyTypedResourceBuilder 'class via a tool like ResGen or Visual Studio. 'To add or remove a member, edit your .ResX file then rerun ResGen 'with the /str option, or rebuild your VS project. '''<summary> ''' A strongly-typed resource class, for looking up localized strings, etc. '''</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '''<summary> ''' Returns the cached ResourceManager instance used by this class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("db_update.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' Overrides the current thread's CurrentUICulture property for all ''' resource lookups using this strongly typed resource class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property End Module End Namespace
jirikadlec2/hydrodata
hydrodatainfo/lahti_update/My Project/Resources.Designer.vb
Visual Basic
bsd-3-clause
2,715
Imports System.Windows.Forms Imports System.Data.SqlClient Public Class frmAddQuestion Public myGuid As String Public Mode As String Public WithEvents cms As New ContextMenuStrip Private drHistory As DataTable Public sHandle As String = "" Private sHistoryGuid As String Private Sub frmAddQuestion_Activated(sender As Object, e As System.EventArgs) Handles Me.Activated If mGRCData.IsAuthenticated(GetSessionGuid) = False Then Me.Hide() Me.Visible = False If mfrmLogin Is Nothing Then mfrmLogin = New frmLogin End If mfrmLogin.Show() Exit Sub End If End Sub Private Sub frmAddQuestion_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load mGRCData = New GRCSec.GridcoinData End Sub Private Sub btnSubmit_Click(sender As System.Object, e As System.EventArgs) Handles btnSubmit.Click If Len(rtbNotes.Text) = 0 Then MsgBox("Question must be provided.", MsgBoxStyle.Critical) Exit Sub End If If mGRCData.IsAuthenticated(GetSessionGuid) = False Then If mfrmLogin Is Nothing Then mfrmLogin = New frmLogin End If mfrmLogin.Show() Exit Sub End If If Len(rtbNotes.Text) > 1000 Then MsgBox("Sorry your question must not exceed 1000 characters.", MsgBoxStyle.Exclamation) Exit Sub End If mGRCData.mInsertQuestion(rtbNotes.Text, GetSessionGuid()) btnSubmit.Enabled = True MsgBox("Success: Your Question has been added. ", MsgBoxStyle.Information) Me.Hide() mfrmFAQ.RefreshFAQ() End Sub End Class
Lederstrumpf/Gridcoin-Research
contrib/Installer/boinc/boinc/frmAddFaqQuestion.vb
Visual Basic
mit
1,794
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic Partial Class LocalRewriter Private Structure XmlLiteralFixupData Public Structure LocalWithInitialization Public ReadOnly Local As LocalSymbol Public ReadOnly Initialization As BoundExpression Public Sub New(local As LocalSymbol, initialization As BoundExpression) Me.Local = local Me.Initialization = initialization End Sub End Structure Private _locals As ArrayBuilder(Of LocalWithInitialization) Public Sub AddLocal(local As LocalSymbol, initialization As BoundExpression) If Me._locals Is Nothing Then Me._locals = ArrayBuilder(Of LocalWithInitialization).GetInstance End If Me._locals.Add(New LocalWithInitialization(local, initialization)) End Sub Public ReadOnly Property IsEmpty As Boolean Get Return Me._locals Is Nothing End Get End Property Public Function MaterializeAndFree() As ImmutableArray(Of LocalWithInitialization) Debug.Assert(Not Me.IsEmpty) Dim materialized = Me._locals.ToImmutableAndFree Me._locals = Nothing Return materialized End Function End Structure End Class End Namespace
mono/roslyn
src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_XmlLiteralFixupData.vb
Visual Basic
apache-2.0
1,907
' 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 Microsoft.CodeAnalysis.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE ''' <summary> ''' Tuples can be represented using tuple syntax and be given ''' names. However, the underlying representation for tuples unifies ''' to a single underlying tuple type, System.ValueTuple. Since the ''' names aren't part of the underlying tuple type they have to be ''' recorded somewhere else. ''' ''' Roslyn records tuple names in an attribute: the ''' TupleElementNamesAttribute. The attribute contains a single string ''' array which records the names of the tuple elements in a pre-order ''' depth-first traversal. If the type contains nested parameters, ''' they are also recorded in a pre-order depth-first traversal. ''' <see cref="DecodeTupleTypesIfApplicable(TypeSymbol, EntityHandle, PEModuleSymbol)"/> ''' can be used to extract tuple names and types from metadata and create ''' a <see cref="TupleTypeSymbol"/> with attached names. ''' ''' <example> ''' For instance, a method returning a tuple ''' ''' <code> ''' Function M() As (x As Integer, y As Integer) ''' </code> ''' ''' will be encoded using an attribute on the return type as follows ''' ''' <code> ''' &lt; return: TupleElementNamesAttribute({ "x", "y" }) > ''' Function M() As System.ValueTuple(Of Integer, Integer) ''' </code> ''' </example> ''' ''' <example> ''' For nested type parameters, we expand the tuple names in a pre-order ''' traversal: ''' ''' <code> ''' Class C ''' Inherits BaseType(Of (e3 As (e1 As Integer, e2 As Integer), e4 As Integer)) ''' </code> ''' ''' becomes ''' ''' <code> ''' &lt; TupleElementNamesAttribute({ "e3", "e4", "e1", "e2" }) > ''' Class C ''' Inherits BaseType(of System.ValueTuple(of System.ValueTuple(Of Integer, Integer), Integer) ''' </code> ''' </example> ''' </summary> Friend Structure TupleTypeDecoder Private ReadOnly _elementNames As ImmutableArray(Of String) ' Keep track of how many names we've "used" during decoding. Starts at ' the back of the array and moves forward. Private _namesIndex As Integer Private Sub New(elementNames As ImmutableArray(Of String)) _elementNames = elementNames _namesIndex = If(elementNames.IsDefault, 0, elementNames.Length) End Sub Public Shared Function DecodeTupleTypesIfApplicable( metadataType As TypeSymbol, targetSymbolToken As EntityHandle, containingModule As PEModuleSymbol) As TypeSymbol Dim elementNames As ImmutableArray(Of String) = Nothing Dim hasTupleElementNamesAttribute = containingModule.Module.HasTupleElementNamesAttribute(targetSymbolToken, elementNames) ' If we have the TupleElementNamesAttribute, but no names, that's ' bad metadata If hasTupleElementNamesAttribute AndAlso elementNames.IsDefaultOrEmpty Then Return New UnsupportedMetadataTypeSymbol() End If Return DecodeTupleTypesInternal(metadataType, elementNames, hasTupleElementNamesAttribute) End Function Public Shared Function DecodeTupleTypesIfApplicable( metadataType As TypeSymbol, elementNames As ImmutableArray(Of String)) As TypeSymbol Return DecodeTupleTypesInternal(metadataType, elementNames, hasTupleElementNamesAttribute:=Not elementNames.IsDefaultOrEmpty) End Function Private Shared Function DecodeTupleTypesInternal(metadataType As TypeSymbol, elementNames As ImmutableArray(Of String), hasTupleElementNamesAttribute As Boolean) As TypeSymbol Debug.Assert(metadataType IsNot Nothing) Dim decoder = New TupleTypeDecoder(elementNames) Try Dim decoded = decoder.DecodeType(metadataType) ' If not all of the names have been used, the metadata is bad If Not hasTupleElementNamesAttribute OrElse decoder._namesIndex = 0 Then Return decoded End If Catch ex As InvalidOperationException ' Indicates that the tuple info in the attribute didn't match ' the type. Bad metadata. End Try If metadataType.GetUseSiteErrorInfo() IsNot Nothing Then Return metadataType End If ' Bad metadata Return New UnsupportedMetadataTypeSymbol() End Function Private Function DecodeType(type As TypeSymbol) As TypeSymbol Select Case type.Kind Case SymbolKind.ErrorType, SymbolKind.DynamicType, SymbolKind.TypeParameter, SymbolKind.PointerType Return type Case SymbolKind.NamedType ' We may have a tuple type from a substituted type symbol, ' but it will be missing names from metadata, so we'll ' need to re-create the type. ' ' Consider the declaration ' ' class C : Inherits BaseType(of (x As Integer, y As Integer)) ' ' The process for decoding tuples in looks at the BaseType, calls ' DecodeOrThrow, then passes the decoded type to the TupleTypeDecoder. ' However, DecodeOrThrow uses the AbstractTypeMap to construct a ' SubstitutedTypeSymbol, which eagerly converts tuple-compatible ' types to TupleTypeSymbols. Thus, by the time we get to the Decoder ' all metadata instances of System.ValueTuple will have been ' replaced with TupleTypeSymbols without names. ' ' Rather than fixing up after-the-fact it's possible that we could ' flow up a SubstituteWith/Without tuple unification to the top level ' of the type map and change DecodeOrThrow to call into the substitution ' without unification instead. Return If(type.IsTupleType, DecodeNamedType(type.TupleUnderlyingType), DecodeNamedType(DirectCast(type, NamedTypeSymbol))) Case SymbolKind.ArrayType Return DecodeArrayType(DirectCast(type, ArrayTypeSymbol)) Case Else Throw ExceptionUtilities.UnexpectedValue(type.TypeKind) End Select End Function Private Function DecodeNamedType(type As NamedTypeSymbol) As NamedTypeSymbol ' First decode the type arguments Dim typeArgs = type.TypeArgumentsNoUseSiteDiagnostics Dim decodedArgs = DecodeTypeArguments(typeArgs) Dim decodedType = type ' Now check the container Dim containingType = type.ContainingType Dim decodedContainingType As NamedTypeSymbol = Nothing If containingType IsNot Nothing AndAlso containingType.IsGenericType Then decodedContainingType = DecodeNamedType(containingType) Debug.Assert(decodedContainingType.IsGenericType) Else decodedContainingType = containingType End If ' Replace the type if necessary Dim containerChanged = decodedContainingType IsNot containingType Dim typeArgsChanged = typeArgs <> decodedArgs If typeArgsChanged OrElse containerChanged Then Dim newTypeArgs = If(type.HasTypeArgumentsCustomModifiers, decodedArgs.SelectAsArray(Function(t, i, m) New TypeWithModifiers(t, m.GetTypeArgumentCustomModifiers(i)), type), decodedArgs.SelectAsArray(Function(t) New TypeWithModifiers(t, Nothing))) If containerChanged Then decodedType = decodedType.OriginalDefinition.AsMember(decodedContainingType) ' If the type is nested, e.g. Outer(of T).Inner(of V), then Inner is definitely ' not a tuple, since we know all tuple-compatible types (System.ValueTuple) ' are not nested types. Thus, it is safe to return without checking if ' Inner is a tuple. Return If(decodedType.TypeParameters.IsEmpty, decodedType, Construct(decodedType, newTypeArgs)) End If decodedType = Construct(type, newTypeArgs) End If ' Now decode into a tuple, if it is one Dim tupleCardinality As Integer If decodedType.IsTupleCompatible(tupleCardinality) Then Dim elementNames = EatElementNamesIfAvailable(tupleCardinality) Debug.Assert(elementNames.IsDefault OrElse elementNames.Length = tupleCardinality) decodedType = TupleTypeSymbol.Create(decodedType, elementNames) End If Return decodedType End Function Private Shared Function Construct(type As NamedTypeSymbol, newTypeArgs As ImmutableArray(Of TypeWithModifiers)) As NamedTypeSymbol Dim definition = type.OriginalDefinition Dim parentSubst = type.ConstructedFrom.ContainingType?.TypeSubstitution Dim subst As TypeSubstitution If parentSubst IsNot Nothing Then subst = TypeSubstitution.Create(parentSubst, definition, newTypeArgs, False) Else subst = TypeSubstitution.Create(definition, definition.TypeParameters, newTypeArgs, False) End If Return definition.Construct(subst) End Function Private Function DecodeTypeArguments(typeArgs As ImmutableArray(Of TypeSymbol)) As ImmutableArray(Of TypeSymbol) If typeArgs.IsEmpty Then Return typeArgs End If Dim decodedArgs = ArrayBuilder(Of TypeSymbol).GetInstance(typeArgs.Length) Dim anyDecoded = False ' Visit the type arguments in reverse For i As Integer = typeArgs.Length - 1 To 0 Step -1 Dim typeArg = typeArgs(i) Dim decoded = DecodeType(typeArg) anyDecoded = anyDecoded Or decoded IsNot typeArg decodedArgs.Add(decoded) Next If Not anyDecoded Then decodedArgs.Free() Return typeArgs End If decodedArgs.ReverseContents() Return decodedArgs.ToImmutableAndFree() End Function Private Function DecodeArrayType(type As ArrayTypeSymbol) As ArrayTypeSymbol Dim decodedElementType = DecodeType(type.ElementType) Return If(decodedElementType Is type.ElementType, type, type.WithElementType(decodedElementType)) End Function Private Function EatElementNamesIfAvailable(numberOfElements As Integer) As ImmutableArray(Of String) Debug.Assert(numberOfElements > 0) ' If we don't have any element names there's nothing to eat If _elementNames.IsDefault Then Return _elementNames End If ' We've gone past the end of the names -- bad metadata If numberOfElements > _namesIndex Then Throw New InvalidOperationException() End If ' Check to see if all the elements are null Dim start = _namesIndex - numberOfElements Dim allNull = True _namesIndex = start For i As Integer = 0 To numberOfElements - 1 If _elementNames(start + i) IsNot Nothing Then allNull = False Exit For End If Next If allNull Then Return Nothing End If Dim builder = ArrayBuilder(Of String).GetInstance(numberOfElements) For i As Integer = 0 To numberOfElements - 1 builder.Add(_elementNames(start + i)) Next Return builder.ToImmutableAndFree() End Function End Structure End Namespace
OmarTawfik/roslyn
src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/TupleTypeDecoder.vb
Visual Basic
apache-2.0
12,982
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod Friend Module Extensions <Extension()> Public Function GetUnparenthesizedExpression(node As SyntaxNode) As ExpressionSyntax Dim parenthesizedExpression = TryCast(node, ParenthesizedExpressionSyntax) If parenthesizedExpression Is Nothing Then Return DirectCast(node, ExpressionSyntax) End If Return GetUnparenthesizedExpression(parenthesizedExpression.Expression) End Function <Extension()> Public Function GetStatementContainer(node As SyntaxNode) As SyntaxNode Contract.ThrowIfNull(node) Dim statement = node.GetStatementUnderContainer() If statement Is Nothing Then Return Nothing End If Return statement.Parent End Function <Extension()> Public Function GetStatementUnderContainer(node As SyntaxNode) As ExecutableStatementSyntax Contract.ThrowIfNull(node) Do While node IsNot Nothing If node.Parent.IsStatementContainerNode() AndAlso TypeOf node Is ExecutableStatementSyntax AndAlso node.Parent.ContainStatement(DirectCast(node, ExecutableStatementSyntax)) Then Return TryCast(node, ExecutableStatementSyntax) End If node = node.Parent Loop Return Nothing End Function <Extension()> Public Function ContainStatement(node As SyntaxNode, statement As StatementSyntax) As Boolean Contract.ThrowIfNull(node) Contract.ThrowIfNull(statement) If Not node.IsStatementContainerNode() Then Return False End If Return node.GetStatements().IndexOf(statement) >= 0 End Function <Extension()> Public Function GetOutermostNodeWithSameSpan(initialNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As SyntaxNode If initialNode Is Nothing Then Return Nothing End If ' now try to find outmost node that has same span Dim firstContainingSpan = initialNode.Span Dim node = initialNode Dim lastNode = Nothing Do If predicate(node) Then lastNode = node End If node = node.Parent Loop While node IsNot Nothing AndAlso node.Span.Equals(firstContainingSpan) Return CType(If(lastNode, initialNode), SyntaxNode) End Function <Extension()> Public Function PartOfConstantInitializerExpression(node As SyntaxNode) As Boolean Return node.PartOfConstantInitializerExpression(Of FieldDeclarationSyntax)(Function(n) n.Modifiers) OrElse node.PartOfConstantInitializerExpression(Of LocalDeclarationStatementSyntax)(Function(n) n.Modifiers) End Function <Extension()> Private Function PartOfConstantInitializerExpression(Of T As SyntaxNode)(node As SyntaxNode, modifiersGetter As Func(Of T, SyntaxTokenList)) As Boolean Dim decl = node.GetAncestor(Of T)() If decl Is Nothing Then Return False End If If Not modifiersGetter(decl).Any(Function(m) m.Kind = SyntaxKind.ConstKeyword) Then Return False End If ' we are under decl with const modifier, check we are part of initializer expression Dim equal = node.GetAncestor(Of EqualsValueSyntax)() If equal Is Nothing Then Return False End If Return equal.Value IsNot Nothing AndAlso equal.Value.Span.Contains(node.Span) End Function <Extension()> Public Function IsArgumentForByRefParameter(node As SyntaxNode, model As SemanticModel, cancellationToken As CancellationToken) As Boolean Dim argument = node.FirstAncestorOrSelf(Of ArgumentSyntax)() ' make sure we are the argument If argument Is Nothing OrElse node.Span <> argument.Span Then Return False End If ' now find invocation node Dim invocation = argument.FirstAncestorOrSelf(Of InvocationExpressionSyntax)() ' argument for something we are not interested in If invocation Is Nothing Then Return False End If ' find argument index Dim argumentIndex = invocation.ArgumentList.Arguments.IndexOf(argument) If argumentIndex < 0 Then Return False End If ' get all method symbols Dim methodSymbols = model.GetSymbolInfo(invocation, cancellationToken).GetAllSymbols().Where(Function(s) s.Kind = SymbolKind.Method).Cast(Of IMethodSymbol)() For Each method In methodSymbols ' not a right method If method.Parameters.Length <= argumentIndex Then Continue For End If ' make sure there is no ref type Dim parameter = method.Parameters(argumentIndex) If parameter.RefKind <> RefKind.None Then Return True End If Next Return False End Function <Extension()> Public Function ContainArgumentlessThrowWithoutEnclosingCatch(ByVal tokens As IEnumerable(Of SyntaxToken), ByVal textSpan As TextSpan) As Boolean For Each token In tokens If token.Kind <> SyntaxKind.ThrowKeyword Then Continue For End If Dim throwStatement = TryCast(token.Parent, ThrowStatementSyntax) If throwStatement Is Nothing OrElse throwStatement.Expression IsNot Nothing Then Continue For End If Dim catchBlock = token.GetAncestor(Of CatchBlockSyntax)() If catchBlock Is Nothing OrElse Not textSpan.Contains(catchBlock.Span) Then Return True End If Next token Return False End Function <Extension()> Public Function ContainPreprocessorCrossOver(ByVal tokens As IEnumerable(Of SyntaxToken), ByVal textSpan As TextSpan) As Boolean Dim activeRegions As Integer = 0 Dim activeIfs As Integer = 0 For Each trivia In tokens.GetAllTrivia() If Not trivia.IsDirective Then Continue For End If Dim directive = DirectCast(trivia.GetStructure(), DirectiveTriviaSyntax) If Not textSpan.Contains(directive.Span) Then Continue For End If Select Case directive.Kind Case SyntaxKind.RegionDirectiveTrivia activeRegions += 1 Case SyntaxKind.EndRegionDirectiveTrivia If activeRegions <= 0 Then Return True activeRegions -= 1 Case SyntaxKind.IfDirectiveTrivia activeIfs += 1 Case SyntaxKind.EndIfDirectiveTrivia If activeIfs <= 0 Then Return True activeIfs -= 1 Case SyntaxKind.ElseDirectiveTrivia, SyntaxKind.ElseIfDirectiveTrivia If activeIfs <= 0 Then Return True End Select Next trivia Return activeIfs <> 0 OrElse activeRegions <> 0 End Function <Extension()> Public Function GetAllTrivia(ByVal tokens As IEnumerable(Of SyntaxToken)) As IEnumerable(Of SyntaxTrivia) Dim list = New List(Of SyntaxTrivia)() For Each token In tokens list.AddRange(token.LeadingTrivia) list.AddRange(token.TrailingTrivia) Next token Return list End Function <Extension()> Public Function ContainsFieldInitializer(node As SyntaxNode) As Boolean node = node.GetOutermostNodeWithSameSpan(Function(n) True) Return node.DescendantNodesAndSelf().Any(Function(n) TypeOf n Is FieldInitializerSyntax) End Function <Extension()> Public Function ContainsDotMemberAccess(node As SyntaxNode) As Boolean Dim predicate = Function(n As SyntaxNode) Dim member = TryCast(n, MemberAccessExpressionSyntax) If member Is Nothing Then Return False End If Return member.Expression Is Nothing AndAlso member.OperatorToken.Kind = SyntaxKind.DotToken End Function Return node.DescendantNodesAndSelf().Any(predicate) End Function <Extension()> Public Function UnderWithBlockContext(token As SyntaxToken) As Boolean Dim withBlock = token.GetAncestor(Of WithBlockSyntax)() If withBlock Is Nothing Then Return False End If Dim withBlockSpan = TextSpan.FromBounds(withBlock.WithStatement.Span.End, withBlock.EndWithStatement.SpanStart) Return withBlockSpan.Contains(token.Span) End Function <Extension()> Public Function UnderObjectMemberInitializerContext(token As SyntaxToken) As Boolean Dim initializer = token.GetAncestor(Of ObjectMemberInitializerSyntax)() If initializer Is Nothing Then Return False End If Dim initializerSpan = TextSpan.FromBounds(initializer.WithKeyword.Span.End, initializer.Span.End) Return initializerSpan.Contains(token.Span) End Function <Extension()> Public Function UnderValidContext(token As SyntaxToken) As Boolean Dim predicate As Func(Of SyntaxNode, Boolean) = Function(n) Dim range = TryCast(n, RangeArgumentSyntax) If range IsNot Nothing Then If range.UpperBound.Span.Contains(token.Span) AndAlso range.GetAncestor(Of FieldDeclarationSyntax)() IsNot Nothing Then Return True End If End If Dim [property] = TryCast(n, PropertyStatementSyntax) If [property] IsNot Nothing Then Dim asNewClause = TryCast([property].AsClause, AsNewClauseSyntax) If asNewClause IsNot Nothing AndAlso asNewClause.NewExpression IsNot Nothing Then Dim span = TextSpan.FromBounds(asNewClause.NewExpression.NewKeyword.Span.End, asNewClause.NewExpression.Span.End) Return span.Contains(token.Span) End If End If If n.CheckTopLevel(token.Span) Then Return True End If Return False End Function Return token.GetAncestors(Of SyntaxNode)().Any(predicate) End Function <Extension()> Public Function ContainsInMethodBlockBody(block As MethodBlockBaseSyntax, textSpan As TextSpan) As Boolean If block Is Nothing Then Return False End If Dim blockSpan = TextSpan.FromBounds(block.BlockStatement.Span.End, block.EndBlockStatement.SpanStart) Return blockSpan.Contains(textSpan) End Function <Extension()> _ Public Function UnderValidContext(ByVal node As SyntaxNode) As Boolean Contract.ThrowIfNull(node) Dim predicate As Func(Of SyntaxNode, Boolean) = Function(n) If TypeOf n Is MethodBlockBaseSyntax OrElse TypeOf n Is MultiLineLambdaExpressionSyntax OrElse TypeOf n Is SingleLineLambdaExpressionSyntax Then Return True End If Return False End Function If Not node.GetAncestorsOrThis(Of SyntaxNode)().Any(predicate) Then Return False End If If node.FromScript() OrElse node.GetAncestor(Of TypeBlockSyntax)() IsNot Nothing Then Return True End If Return False End Function <Extension()> Public Function IsReturnableConstruct(node As SyntaxNode) As Boolean Return TypeOf node Is MethodBlockBaseSyntax OrElse TypeOf node Is SingleLineLambdaExpressionSyntax OrElse TypeOf node Is MultiLineLambdaExpressionSyntax End Function <Extension()> Public Function HasSyntaxAnnotation([set] As HashSet(Of SyntaxAnnotation), node As SyntaxNode) As Boolean Return [set].Any(Function(a) node.GetAnnotatedNodesAndTokens(a).Any()) End Function <Extension()> Public Function IsFunctionValue(symbol As ISymbol) As Boolean Dim local = TryCast(symbol, ILocalSymbol) Return local IsNot Nothing AndAlso local.IsFunctionValue End Function <Extension()> Public Function ToSeparatedList(Of T As SyntaxNode)(nodes As IEnumerable(Of Tuple(Of T, SyntaxToken))) As SeparatedSyntaxList(Of T) Dim list = New List(Of SyntaxNodeOrToken) For Each tuple In nodes Contract.ThrowIfNull(tuple.Item1) list.Add(tuple.Item1) If tuple.Item2.Kind = SyntaxKind.None Then Exit For End If list.Add(tuple.Item2) Next Return SyntaxFactory.SeparatedList(Of T)(list) End Function <Extension()> Public Function CreateAssignmentExpressionStatementWithValue(identifier As SyntaxToken, rvalue As ExpressionSyntax) As StatementSyntax Return SyntaxFactory.SimpleAssignmentStatement(SyntaxFactory.IdentifierName(identifier), SyntaxFactory.Token(SyntaxKind.EqualsToken), rvalue).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker) End Function <Extension()> Public Function ProcessLocalDeclarationStatement(variableToRemoveMap As HashSet(Of SyntaxAnnotation), declarationStatement As LocalDeclarationStatementSyntax, expressionStatements As List(Of StatementSyntax), variableDeclarators As List(Of VariableDeclaratorSyntax), triviaList As List(Of SyntaxTrivia)) As Boolean ' go through each var decls in decl statement, and create new assignment if ' variable is initialized at decl. Dim hasChange As Boolean = False Dim leadingTriviaApplied As Boolean = False For Each variableDeclarator In declarationStatement.Declarators Dim identifierList = New List(Of ModifiedIdentifierSyntax)() Dim nameCount = variableDeclarator.Names.Count For i = 0 To nameCount - 1 Step 1 Dim variable = variableDeclarator.Names(i) If variableToRemoveMap.HasSyntaxAnnotation(variable) Then If variableDeclarator.Initializer IsNot Nothing AndAlso i = nameCount - 1 Then ' move comments with the variable here Dim identifier As SyntaxToken = variable.Identifier ' The leading trivia from the declaration is applied to the first variable ' There is not much value in appending the trailing trivia of the modifier If i = 0 AndAlso Not leadingTriviaApplied AndAlso declarationStatement.HasLeadingTrivia Then identifier = identifier.WithLeadingTrivia(declarationStatement.GetLeadingTrivia.AddRange(identifier.LeadingTrivia)) leadingTriviaApplied = True End If expressionStatements.Add(identifier.CreateAssignmentExpressionStatementWithValue(variableDeclarator.Initializer.Value)) Continue For End If ' we don't remove trivia around tokens we remove triviaList.AddRange(variable.GetLeadingTrivia()) triviaList.AddRange(variable.GetTrailingTrivia()) Continue For End If If triviaList.Count > 0 Then identifierList.Add(variable.WithPrependedLeadingTrivia(triviaList)) triviaList.Clear() Continue For End If identifierList.Add(variable) Next If identifierList.Count = 0 Then ' attach left over trivia to last expression statement If triviaList.Count > 0 AndAlso expressionStatements.Count > 0 Then Dim lastStatement = expressionStatements(expressionStatements.Count - 1) lastStatement = lastStatement.WithPrependedLeadingTrivia(triviaList) expressionStatements(expressionStatements.Count - 1) = lastStatement triviaList.Clear() End If Continue For ElseIf identifierList.Count = variableDeclarator.Names.Count Then variableDeclarators.Add(variableDeclarator) ElseIf identifierList.Count > 0 Then variableDeclarators.Add( variableDeclarator.WithNames(SyntaxFactory.SeparatedList(identifierList)). WithPrependedLeadingTrivia(triviaList)) hasChange = True End If Next variableDeclarator Return hasChange OrElse declarationStatement.Declarators.Count <> variableDeclarators.Count End Function <Extension()> Public Function IsExpressionInCast(node As SyntaxNode) As Boolean Return TypeOf node Is ExpressionSyntax AndAlso TypeOf node.Parent Is CastExpressionSyntax End Function <Extension()> Public Function IsErrorType(type As ITypeSymbol) As Boolean Return type Is Nothing OrElse type.Kind = SymbolKind.ErrorType End Function <Extension()> Public Function IsObjectType(type As ITypeSymbol) As Boolean Return type Is Nothing OrElse type.SpecialType = SpecialType.System_Object End Function End Module End Namespace
AmadeusW/roslyn
src/Features/VisualBasic/Portable/ExtractMethod/Extensions.vb
Visual Basic
apache-2.0
19,783
'-------------------------------------------------------------------------------------------' ' Inicio del codigo '-------------------------------------------------------------------------------------------' ' Importando librerias '-------------------------------------------------------------------------------------------' Imports System.Data '-------------------------------------------------------------------------------------------' ' Inicio de clase "fDatos_Medidores_Manuales" '-------------------------------------------------------------------------------------------' Partial Class fDatos_Medidores_Manuales Inherits vis2Formularios.frmReporte Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try Dim loComandoSeleccionar As New StringBuilder() loComandoSeleccionar.AppendLine(" SELECT ") loComandoSeleccionar.AppendLine(" Medidores.Cod_Med,") loComandoSeleccionar.AppendLine(" Medidores.Nom_Med,") loComandoSeleccionar.AppendLine(" CASE") loComandoSeleccionar.AppendLine(" WHEN Medidores.Status = 'A' THEN 'Activo'") loComandoSeleccionar.AppendLine(" WHEN Medidores.Status = 'I' THEN 'Inactivo'") loComandoSeleccionar.AppendLine(" WHEN Medidores.Status = 'S' THEN 'Suspendido'") loComandoSeleccionar.AppendLine(" END AS Status,") loComandoSeleccionar.AppendLine(" Medidores.Responsable,") loComandoSeleccionar.AppendLine(" Medidores.Fec_Ini,") loComandoSeleccionar.AppendLine(" Medidores.Fec_Fin,") loComandoSeleccionar.AppendLine(" Medidores.Clase,") loComandoSeleccionar.AppendLine(" Medidores.Tipo,") loComandoSeleccionar.AppendLine(" Medidores.Grupo,") loComandoSeleccionar.AppendLine(" Medidores.Manual,") loComandoSeleccionar.AppendLine(" Medidores.Por_Sup,") loComandoSeleccionar.AppendLine(" Medidores.Por_Inf,") loComandoSeleccionar.AppendLine(" Medidores.Por_Pro,") loComandoSeleccionar.AppendLine(" Medidores.Mon_Sup,") loComandoSeleccionar.AppendLine(" Medidores.Mon_Inf,") loComandoSeleccionar.AppendLine(" Medidores.Mon_Pro,") loComandoSeleccionar.AppendLine(" Medidores.Can_Sup,") loComandoSeleccionar.AppendLine(" Medidores.Can_Inf,") loComandoSeleccionar.AppendLine(" Medidores.Can_Pro,") loComandoSeleccionar.AppendLine(" Medidores.Doc_Sup,") loComandoSeleccionar.AppendLine(" Medidores.Doc_Inf,") loComandoSeleccionar.AppendLine(" Medidores.Doc_Pro,") loComandoSeleccionar.AppendLine(" Medidores.Formulario,") loComandoSeleccionar.AppendLine(" Medidores.Reporte,") loComandoSeleccionar.AppendLine(" Medidores.Cod_Mon,") loComandoSeleccionar.AppendLine(" Monedas.Nom_Mon,") loComandoSeleccionar.AppendLine(" Medidores.Tasa,") loComandoSeleccionar.AppendLine(" Medidores.Prioridad,") loComandoSeleccionar.AppendLine(" Medidores.Importancia,") loComandoSeleccionar.AppendLine(" Medidores.Nivel,") loComandoSeleccionar.AppendLine(" Medidores.Comentario,") loComandoSeleccionar.AppendLine(" Medidores.Objetivo,") loComandoSeleccionar.AppendLine(" Renglones_Medidores.Renglon,") loComandoSeleccionar.AppendLine(" Renglones_Medidores.Mes,") loComandoSeleccionar.AppendLine(" Renglones_Medidores.Año,") loComandoSeleccionar.AppendLine(" Renglones_Medidores.Mon_Est,") loComandoSeleccionar.AppendLine(" Renglones_Medidores.Mon_Eje,") loComandoSeleccionar.AppendLine(" Renglones_Medidores.Mon_Des,") loComandoSeleccionar.AppendLine(" Renglones_Medidores.Can_Est,") loComandoSeleccionar.AppendLine(" Renglones_Medidores.Can_Eje,") loComandoSeleccionar.AppendLine(" Renglones_Medidores.Can_Des,") loComandoSeleccionar.AppendLine(" Renglones_Medidores.Doc_Est,") loComandoSeleccionar.AppendLine(" Renglones_Medidores.Doc_Eje,") loComandoSeleccionar.AppendLine(" Renglones_Medidores.Doc_Des,") loComandoSeleccionar.AppendLine(" Renglones_Medidores.Por_Est,") loComandoSeleccionar.AppendLine(" Renglones_Medidores.Por_Eje,") loComandoSeleccionar.AppendLine(" Renglones_Medidores.Por_Des,") loComandoSeleccionar.AppendLine(" Renglones_Medidores.Comentario AS Comentario_Renglon") loComandoSeleccionar.AppendLine(" FROM Medidores ") loComandoSeleccionar.AppendLine(" JOIN Renglones_Medidores ON (Renglones_Medidores.Cod_Med = Medidores.Cod_Med)") loComandoSeleccionar.AppendLine(" JOIN Monedas ON (Monedas.Cod_Mon = Medidores.Cod_Mon)") loComandoSeleccionar.AppendLine(" WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal) loComandoSeleccionar.AppendLine(" ORDER BY Cod_Med, Renglon ASC ") 'me.mEscribirConsulta(loComandoSeleccionar.ToString) Dim loServicios As New cusDatos.goDatos Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes") '--------------------------------------------------' ' Carga la imagen del logo en cusReportes ' '--------------------------------------------------' Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa") '------------------------------------------------------------------------------------------------------- ' Verificando si el select (tabla nº0) trae registros '------------------------------------------------------------------------------------------------------- If (laDatosReporte.Tables(0).Rows.Count <= 0) Then Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _ "No se Encontraron Registros para los Parámetros Especificados. ", _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _ "350px", _ "200px") End If loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("fDatos_Medidores_Manuales", laDatosReporte) Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvfDatos_Medidores_Manuales.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 Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _ "No se pudo Completar el Proceso: " & loExcepcion.Message, _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _ "auto", _ "auto") End Try End Sub End Class '-------------------------------------------------------------------------------------------' ' Fin del codigo ' '-------------------------------------------------------------------------------------------' ' MAT: 10/08/11 : Codigo inicial ' '-------------------------------------------------------------------------------------------'
kodeitsolutions/ef-reports
fDatos_Medidores_Manuales.aspx.vb
Visual Basic
mit
7,797
Imports MySql.Data.MySqlClient Namespace BurnSoft Public Class BSDatabase Public Conn As MySqlConnection Private Function MyConnectionString() As String Dim sAns As String = "Server=" & System.Configuration.ConfigurationManager.AppSettings("DB_HOST") sAns &= ";user id=" & System.Configuration.ConfigurationManager.AppSettings("DB_UID") sAns &= ";password=" & System.Configuration.ConfigurationManager.AppSettings("DB_PWD") sAns &= ";persist security info=true" sAns &= ";database=" & System.Configuration.ConfigurationManager.AppSettings("DB_NAME") Return sAns End Function Public Function ConnectDB() As Integer Dim iAns As Integer = 0 Err.Clear() Try Dim sConnect As String = MyConnectionString() Conn = New MySqlConnection(sConnect) Conn.Open() Catch ex As Exception iAns = Err.Number Dim strForm As String = "BSGlobalClass.BSDatabase" Dim strSubFunc As String = "ConnectDB" Dim sMsg As String = " - ERROR - " & Err.Number & " - " & ex.Message.ToString Call LogError(sMsg, strForm & "." & strSubFunc) End Try Return iAns End Function Public Sub ConnExe(ByVal SQL As String) Try If ConnectDB() = 0 Then Dim CMD As New MySqlCommand CMD.CommandText = SQL CMD.Connection = Conn CMD.ExecuteNonQuery() CMD.Connection.Close() CMD = Nothing Call CloseDB() End If Catch ex As Exception Dim strForm As String = "BSGlobalClass.BSDatabase" Dim strSubFunc As String = "ConnExe" Dim sMsg As String = " - ERROR - " & Err.Number & " - " & ex.Message.ToString Call LogError(sMsg, strForm & "." & strSubFunc) End Try End Sub Public Sub CloseDB() If Conn.State <> ConnectionState.Closed Then Conn.Close() End If Conn = Nothing End Sub End Class Public Class BSSqliteDatabase Public Conn As SQLite.SQLiteConnection Private Function MyConnectionString() As String Return "Data Source=bsap_client.db" End Function Public Function ConnectDB() As Integer Dim iAns As Integer = 0 Err.Clear() Try Dim sConnect As String = MyConnectionString() Conn = New SQLite.SQLiteConnection(sConnect) Conn.Open() Catch ex As Exception iAns = Err.Number Dim strForm As String = "BSGlobalClass.BSSqliteDatabase" Dim strSubFunc As String = "ConnectDB" Dim sMsg As String = " - ERROR - " & Err.Number & " - " & ex.Message.ToString Call LogError(sMsg, strForm & "." & strSubFunc) End Try Return iAns End Function Public Sub ConnExe(SQL As String) Try If ConnectDB() = 0 Then Dim CMD As New SQLite.SQLiteCommand With CMD .CommandText = SQL .Connection = Conn .ExecuteNonQuery() .Connection.Close() End With CMD = Nothing Call CloseDB() End If Catch ex As Exception Dim strForm As String = "BSGlobalClass.BSSQLiteDatabase" Dim strSubFunc As String = "ConnExe" Dim sMsg As String = " - ERROR - " & Err.Number & " - " & ex.Message.ToString Call LogError(sMsg, strForm & "." & strSubFunc) End Try End Sub Public Sub CloseDB() If Conn.State <> ConnectionState.Closed Then Conn.Close() End If Conn = Nothing End Sub End Class End Namespace
burnsoftnet/BSApplicationProfiler
BSApplicationProfiler/BSGlobalClass.vb
Visual Basic
mit
4,346
Imports System.IO Imports System.Drawing.Drawing2D Public Class DObject Public ObjectName As String Dim SpriteName As String Dim Frame As Int16 Dim FrameLimit As Int16 Public MyXDSLines As String Dim DEventMainClasses As New List(Of String) Dim DEventSubClasses As New List(Of String) Public Actions As New List(Of String) Public ActionImages As New List(Of String) Public ActionArguments As New List(Of String) Public ActionDisplays As New List(Of String) Public ActionAppliesTos As New List(Of String) Dim SelectedEvent As Int16 = 0 Dim CurrentIndents As New List(Of SByte) Dim DragFromBottom As Boolean Dim DragInternal As Boolean Dim DraggingInternal As Int16 Dim DraggingFromBottom As Panel Dim MouseInBox As Boolean = False Dim SaveOnNextChange As Boolean = False Dim ThinList As Boolean = True Sub ActionMouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) DragFromBottom = True DraggingFromBottom = sender Me.Cursor = Cursors.NoMove2D 'DirectCast(sender, Panel).DoDragDrop(DirectCast(sender, Panel).Tag, DragDropEffects.Move) End Sub Sub ActionMouseEnter(ByVal sender As System.Object, ByVal e As System.EventArgs) Dim ActionName As String = DirectCast(sender, Panel).Tag ActionNameLabel.Text = ActionName ArgumentsListLabel.Text = String.Empty Dim ArgumentCount As Byte = 0 For Each X As String In IO.File.ReadAllLines(AppPath + "Actions\" + ActionName + ".action") If X.StartsWith("ARG ") Then X = X.Substring(4) Dim ArgumentName As String = iGet(X, 0, ",") ArgumentsListLabel.Text += ArgumentName + vbCrLf ArgumentCount += 1 End If Next If ArgumentCount = 0 Then ArgumentsListLabel.Text = "<No Arguments>" Dim RequiresPro As Boolean = False For Each X As String In ProActions If X = ActionName Then RequiresPro = True Next RequiresProBanner.Visible = RequiresPro If RequiresPro Then ArgumentsHeaderLabel.Height = 94 ArgumentsListLabel.Height = 68 Else ArgumentsHeaderLabel.Height = 120 ArgumentsListLabel.Height = 94 End If End Sub Sub ActionMouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Me.Cursor = Cursors.Default Dim ActionName As String = DirectCast(DraggingFromBottom, Panel).Tag If SelectedEvent = 100 Then MsgWarn("You must add an Event, to which to add Actions.") Exit Sub End If If Not DragFromBottom Then Exit Sub 'MsgError(Location.X.ToString) 'MsgError(Location.Y.ToString) 'Dim MDIID As Byte = 10 'Dim DOn As Byte = 0 'MsgError(ObjectName) 'For Each X As Form In MainForm.MdiChildren ' If X.Text = ObjectName Then MDIID = DOn ' DOn += 1 'Next 'MsgError(MDIID.ToString) 'If Not ActionsList.PointToClient(Cursor.Position).X > 0 Then Exit Sub 'MsgError(Cursor.Position.X.ToString) 'MsgError(Me.PointToScreen(ActionsList.Location).X.ToString) Dim TheX As Int16 = ActionsList.PointToClient(Cursor.Position).X ' - Location.X Dim TheY As Int16 = ActionsList.PointToClient(Cursor.Position).Y ' - Location.Y If TheX < 0 Then Exit Sub If TheX > ActionsList.Width Then Exit Sub If TheY < 0 Then Exit Sub If TheY > ActionsList.Height Then Exit Sub Dim ArgCount As Byte = 0 Dim NoAppliesTo As Boolean = False For Each X As String In File.ReadAllLines(AppPath + "Actions\" + ActionName + ".action") If X.StartsWith("ARG ") Then ArgCount += 1 If X = "NOAPPLIES" Then NoAppliesTo = True Next Dim Code As Boolean = (ActionName = "Execute Code") Dim JustAdd As Boolean = Not (ActionsList.SelectedIndices.Count = 1) Dim Position As Int16 = ActionsList.SelectedIndex + 1 If NoAppliesTo And ArgCount = 0 Then If JustAdd Then Actions.Add(ActionName) ActionImages.Add(ActionGetIconPath(ActionName, False)) ActionArguments.Add(String.Empty) ActionDisplays.Add(ActionEquateDisplay(ActionName, String.Empty)) ActionAppliesTos.Add("this") GenerateIndentIndices() ActionsList.Items.Add(String.Empty) ActionsList.SelectedItems.Clear() ActionsList.SelectedIndex = ActionsList.Items.Count - 1 Else Actions.Insert(Position, ActionName) ActionImages.Insert(Position, ActionGetIconPath(ActionName, False)) ActionArguments.Insert(Position, String.Empty) ActionDisplays.Insert(Position, ActionEquateDisplay(ActionName, String.Empty)) ActionAppliesTos.Insert(Position, "this") GenerateIndentIndices() ActionsList.Items.Insert(Position, String.Empty) ActionsList.SelectedItems.Clear() ActionsList.SelectedIndex = Position End If DragFromBottom = False Exit Sub End If If Not Code Then Action.ActionName = ActionName Action.AppliesTo = "this" Action.ArgumentString = String.Empty End If If ArgCount > 1 Then Dim MyShizzle As String = String.Empty For X As Byte = 0 To ArgCount - 2 MyShizzle += ";" Next Action.ArgumentString = MyShizzle End If If Code Then EditCode.ReturnableCode = String.Empty EditCode.ImportExport = True If Not EditCode.ShowDialog = Windows.Forms.DialogResult.OK Then Exit Sub Else Action.AppliesToGroupBox.Enabled = True If NoAppliesTo Then Action.AppliesToGroupBox.Enabled = False End If Action.ShowDialog() If Not Action.UseData Then Me.Cursor = Cursors.Default : Exit Sub End If If JustAdd Then Actions.Add(ActionName) ActionImages.Add(ActionGetIconPath(ActionName, False)) Else Actions.Insert(Position, ActionName) ActionImages.Insert(Position, ActionGetIconPath(ActionName, False)) End If If Code Then If JustAdd Then ActionArguments.Add(EditCode.ReturnableCode) ActionDisplays.Add(ActionEquateDisplay(ActionName, EditCode.ReturnableCode)) ActionAppliesTos.Add("this") Else ActionArguments.Insert(Position, EditCode.ReturnableCode) ActionDisplays.Insert(Position, ActionEquateDisplay(ActionName, EditCode.ReturnableCode)) ActionAppliesTos.Insert(Position, "this") End If Else If JustAdd Then ActionArguments.Add(Action.ArgumentString) ActionDisplays.Add(ActionEquateDisplay(ActionName, Action.ArgumentString)) ActionAppliesTos.Add(Action.AppliesTo) Else ActionArguments.Insert(Position, Action.ArgumentString) ActionDisplays.Insert(Position, ActionEquateDisplay(ActionName, Action.ArgumentString)) ActionAppliesTos.Insert(Position, Action.AppliesTo) End If End If GenerateIndentIndices() ActionsList.SelectedItems.Clear() If JustAdd Then ActionsList.Items.Add(String.Empty) ActionsList.SelectedIndex = ActionsList.Items.Count - 1 Else ActionsList.Items.Insert(Position, String.Empty) ActionsList.SelectedIndex = Position End If 'MsgError((ActionsList.PointToClient(Cursor.Position).X).ToString + " v.s. " + ActionsList.Location.X.ToString + " and " + ActionsList.Width.ToString) 'MsgError(TheY) 'If ActionsList.PointToClient(Cursor.Position).X > ActionsList.Width Then Exit Sub 'If Not ActionsList.PointToClient(Cursor.Position).Y > 0 Then Exit Sub 'If ActionsList.PointToClient(Cursor.Position).Y > ActionsList.Height Then Exit Sub DragFromBottom = False End Sub Sub GenerateIndentIndices() CurrentIndents.Clear() If Actions.Count = 0 Then Exit Sub Dim RunningIndent As Byte = 0 For X As Int16 = 0 To Actions.Count - 1 Dim ActionName As String = Actions(X) Dim IndentChange As Byte = 0 For Each Y As String In IO.File.ReadAllLines(AppPath + "Actions\" + ActionName + ".action") If Y = "INDENT" Then IndentChange = 2 : Exit For If Y = "DEDENT" Then IndentChange = 1 : Exit For Next If IndentChange = 2 Then RunningIndent += 1 CurrentIndents.Add(RunningIndent) If RunningIndent > 0 Then If IndentChange = 1 Then RunningIndent -= 1 End If Next 'Dim IndentChange As Byte = 0 'Dim CurrentIndent As Byte = 1 'Dim Thingy As Byte = 0 'For X As Int16 = 0 To Actions.Count - 1 ' IndentChange = 0 ' Dim ActionName As String = Actions(X) ' For Each Y As String In IO.File.ReadAllLines(AppPath + "Actions\" + ActionName + ".action") ' If Y = "INDENT" Then IndentChange = 2 : Exit For ' If Y = "DEDENT" Then IndentChange = 1 : Exit For ' Next ' If IndentChange = 1 Then ' If CurrentIndent > 1 Then ' For i = 0 To CurrentIndent - 2 ' Thingy += 1 ' Next ' CurrentIndent -= 1 ' End If ' Else ' If CurrentIndent > 0 Then ' For i = 0 To CurrentIndent - 1 ' Thingy += 1 ' Next ' End If ' End If ' CurrentIndents.Add(Thingy) ' If IndentChange = 2 Then CurrentIndent += 1 'Next End Sub Sub RenderSprite() Dim Final As New Bitmap(64, 64) Dim FinalGFX As Graphics = Graphics.FromImage(Final) FinalGFX.Clear(Color.White) Dim ImagePath As String If SpriteDropper.Text = "None" Then ImagePath = AppPath + "Resources\NoSprite.png" Else ImagePath = SessionPath + "Sprites\" + Frame.ToString + "_" + SpriteDropper.Text + ".png" End If Dim Drawable As Image = PathToImage(ImagePath) Drawable = MakeBMPTransparent(Drawable, Color.Magenta) FinalGFX.DrawImage(Drawable, New Point(32 - (Drawable.Width / 2), 32 - (Drawable.Height / 2))) SpritePanel.BackgroundImage = Final End Sub Public Sub PopulateActionsTabControl(ByRef RAppliesTo As TabControl) Dim Hide As Boolean = (GetSetting("HIDE_OLD_ACTIONS") = "1") Dim BannedActions As New List(Of String) With BannedActions .Add("load collision map") .Add("if position free") .Add("if position occupied") .Add("palib") .Add("run c script") .Add("enable guitar controller") .Add("set color") End With Dim BackupIndex As Byte = 100 Try BackupIndex = RAppliesTo.SelectedIndex Catch : End Try For Each X As TabPage In RAppliesTo.TabPages Try If X.Controls.Count > 0 Then For Y = 0 To X.Controls.Count - 1 RemoveHandler X.Controls(Y).MouseDown, AddressOf ActionMouseDown RemoveHandler X.Controls(Y).MouseEnter, AddressOf ActionMouseEnter RemoveHandler X.Controls(Y).MouseUp, AddressOf ActionMouseUp X.Controls.RemoveAt(Y) Next End If Catch : End Try RAppliesTo.TabPages.Remove(X) Next RAppliesTo.TabPages.Clear() For X As Byte = 0 To 5 Dim Y As New TabPage Y.Text = ActionTypeToString(X) Y.Name = ActionTypeToString(X) + "TabPage" Y.AutoScroll = True Y.SetAutoScrollMargin(8, 8) Dim Actions As New List(Of String) For Each Z As String In Directory.GetFiles(AppPath + "Actions") Dim ActionName As String = Z.Substring(Z.LastIndexOf("\") + 1) ActionName = ActionName.Substring(0, ActionName.LastIndexOf(".")) If Hide Then If BannedActions.Contains(ActionName.ToLower) Then Continue For End If Dim ActionType As Byte = 100 For Each I As String In File.ReadAllLines(Z) If I.StartsWith("TYPE ") Then ActionType = Convert.ToByte(I.Substring(5)) Next If ActionType = 100 Then Continue For 'Bad action If Not ActionType = X Then Continue For Actions.Add(ActionName) Next Dim DOn As Int16 = 0 Dim XOn As Int16 = 0 Dim YOn As Int16 = 0 For Each Z As String In Actions Dim NewPanel As New Panel With NewPanel .Size = New Size(32, 32) .Tag = Z .Name = Z.Replace(" ", "_") + "ActionPanel" .Location = New Point(10 + (XOn * 32) + (XOn * 10), 10 + (YOn * 32) + (YOn * 10)) 'MsgError(Z + " at " + NewPanel.Location.ToString) .BackgroundImage = ActionGetIcon(Z) End With Y.Controls.Add(NewPanel) 'AddHandler NewPanel.Click, AddressOf ActionPanelClicked AddHandler NewPanel.MouseDown, AddressOf ActionMouseDown AddHandler NewPanel.MouseEnter, AddressOf ActionMouseEnter AddHandler NewPanel.MouseUp, AddressOf ActionMouseUp If XOn = 6 Then YOn += 1 : XOn = 0 Else XOn += 1 End If DOn += 1 Next RAppliesTo.TabPages.Add(Y) Next If Not BackupIndex = 100 Then RAppliesTo.SelectedIndex = BackupIndex End Sub Public Sub ChangeSprite(ByVal OldName As String, ByVal NewName As String) For DOn As Byte = 0 To SpriteDropper.Items.Count - 1 If SpriteDropper.Items(DOn) = OldName Then SpriteDropper.Items.Item(DOn) = NewName Next If SpriteDropper.Text = OldName Then SpriteDropper.Text = NewName End Sub Private Sub DObject_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load SelectedEvent = 100 ThinList = (GetSetting("SHRINK_ACTIONS_LIST") = "1") MainToolStrip.Renderer = New clsToolstripRenderer ActionRightClickMenu.Renderer = New clsMenuRenderer EventRightClickMenu.Renderer = New clsMenuRenderer Text = ObjectName PopulateActionsTabControl(ActionsToAddTabControl) NameTextBox.Text = ObjectName Dim XDSLine As String = GetXDSLine("OBJECT " + ObjectName + ",") MyXDSLines = String.Empty 'MyXDSLines += XDSLine EventsListBox.Items.Clear() For Each X As String In GetXDSFilter("EVENT " + ObjectName + ",") MyXDSLines += X + vbCrLf DEventMainClasses.Add(MainClassTypeToString(iGet(X, 1, ","))) DEventSubClasses.Add(iGet(X, 2, ",")) Next For Each X As String In GetXDSFilter("ACT " + ObjectName + ",") MyXDSLines += X + vbCrLf Next For Each X As String In DEventSubClasses EventsListBox.Items.Add(X) Next SpriteName = iGet(XDSLine, 1, ",") 'MsgError(iget(XDSLine, 1, ",")) Frame = Convert.ToInt16(iGet(XDSLine, 2, ",")) SpriteDropper.Items.Clear() SpriteDropper.Items.Add("None") For Each X As String In GetXDSFilter("SPRITE ") SpriteDropper.Items.Add(iGet(X.Substring(7), 0, ",")) Next SpriteDropper.Text = SpriteName If EventsListBox.Items.Count > 0 Then SaveOnNextChange = False SelectedEvent = 0 EventsListBox.SelectedIndex = 0 End If ArgumentsHeaderLabel.Height = 120 ArgumentsListLabel.Height = 94 End Sub Private Sub DAcceptButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DAcceptButton.Click If MyXDSLines.Length > 0 Then SaveCurrentData() Dim NewName As String = NameTextBox.Text If Not ObjectName = NewName Then If GUIResNameChecker(NameTextBox.Text) Then Exit Sub End If If NewName = "NoData" Then MsgWarn("'NoData' is not a valid name. You must choose another name.") : Exit Sub If NewName = "this" Then MsgWarn("'this' is not a valid name. You must choose another name.") : Exit Sub Dim OldLine As String = GetXDSLine("OBJECT " + ObjectName + ",") Dim NewLine As String = "OBJECT " + NewName + "," + SpriteDropper.Text + "," + Frame.ToString XDSChangeLine(OldLine, NewLine) XDSRemoveFilter("EVENT " + ObjectName + ",") XDSRemoveFilter("ACT " + ObjectName + ",") For Each X As String In GetXDSFilter("OBJECTPLOT " + ObjectName + ",") XDSChangeLine(X, "OBJECTPLOT " + NewName + X.Substring(X.IndexOf(","))) Next Dim FinalString As String = String.Empty If NewName = ObjectName Then FinalString = MyXDSLines Else If MyXDSLines.Length > 0 Then For Each X As String In StringToLines(MyXDSLines) If X.StartsWith("EVENT ") Then X = "EVENT " + NewName + X.Substring(X.IndexOf(",")) End If If X.StartsWith("ACT ") Then X = "ACT " + NewName + X.Substring(X.IndexOf(",")) End If FinalString += X + vbCrLf Next End If End If 'FinalString = UpdateActionsName(FinalString, "Object", ObjectName, NewName, True) CurrentXDS += vbCrLf + FinalString + vbCrLf For Each X As Form In MainForm.MdiChildren If X.Name = "Room" Then Dim DForm As Room = DirectCast(X, Room) DForm.RenameObjectDropper(ObjectName, NewName) For DOn As Byte = 0 To DForm.Objects.Length - 1 If DForm.Objects(DOn).InUse And DForm.Objects(DOn).ObjectName = ObjectName Then DForm.Objects(DOn).ObjectName = NewName Next End If Next For Each X As String In GetXDSFilter("ACT ") Dim SubPoint As Int16 = iGet(X, 0, ",").Length + 1 + iGet(X, 1, ",").Length Dim SubPoint2 As Int16 = SubPoint + 1 + iGet(X, 2, ",").Length + 1 If iGet(X, 1, ",") = "6" Then If iGet(X, 2, ",") = ObjectName Then XDSChangeLine(X, X.Substring(0, SubPoint) + "," + NewName + "," + X.Substring(SubPoint2)) End If End If Next For Each X As String In GetXDSFilter("EVENT ") If iGet(X, 1, ",") = "6" And iGet(X, 2, ",") = ObjectName Then XDSChangeLine(X, iGet(X, 0, ",") + ",6," + NewName) Next CurrentXDS = UpdateActionsName(CurrentXDS, "Object", ObjectName, NewName, True) For Each X As Form In MainForm.MdiChildren If Not IsObject(X.Text) Then Continue For Dim DForm As DObject = DirectCast(X, DObject) If DForm.MyXDSLines.Length = 0 Then Continue For Dim LF As String = String.Empty For Each Y As String In StringToLines(DForm.MyXDSLines) If Y.StartsWith("EVENT ") Then If iGet(Y, 1, ",") = "6" And iGet(Y, 2, ",") = ObjectName Then Y = iGet(Y, 0, ",") + ",6," + NewName End If If Y.StartsWith("ACT ") Then Dim SubPoint As Int16 = iGet(Y, 0, ",").Length + 1 + iGet(Y, 1, ",").Length Dim SubPoint2 As Int16 = SubPoint + 1 + iGet(Y, 2, ",").Length + 1 If iGet(Y, 1, ",") = "6" And iGet(Y, 2, ",") = ObjectName Then Y = Y.Substring(0, SubPoint) + "," + NewName + "," + Y.Substring(SubPoint2) End If End If LF += Y + vbCrLf Next DForm.MyXDSLines = LF Next For Each X As Form In MainForm.MdiChildren If Not X.Name = "DObject" Then Continue For Dim DForm As DObject = DirectCast(X, DObject) DForm.MyXDSLines = UpdateActionsName(DForm.MyXDSLines, "Object", ObjectName, NewName, True) Next UpdateArrayActionsName("Object", ObjectName, NewName, True) For Each X As Form In MainForm.MdiChildren If Not X.Name = "DObject" Then Continue For If DirectCast(X, DObject).DEventMainClasses.Count = 0 Then Continue For 'MsgError("processing form " + X.Text) For Y As Byte = 0 To DirectCast(X, DObject).DEventMainClasses.Count - 1 'MsgError("mainclass " + Y.ToString + " is " + DirectCast(X, DObject).DEventMainClasses(Y)) 'MsgError("subclass " + Y.ToString + " is " + DirectCast(X, DObject).DEventSubClasses(Y)) If DirectCast(X, DObject).DEventMainClasses(Y) = "Collision" And DirectCast(X, DObject).DEventSubClasses(Y) = ObjectName Then DirectCast(X, DObject).DEventSubClasses(Y) = NewName End If Next For Each Y As Control In X.Controls If Not Y.Name = "ObjectPropertiesPanel" Then Continue For For Each Z As Control In Y.Controls If Z.Name = "EventsListBox" Then DirectCast(Z, ListBox).Invalidate() Next Next Next For Each X As TreeNode In MainForm.ResourcesTreeView.Nodes(ResourceIDs.DObject).Nodes If X.Text = ObjectName Then X.Text = NewName Next Me.Close() End Sub Public Sub AddSprite(ByVal SpriteName As String) SpriteDropper.Items.Add(SpriteName) End Sub Public Function GetSpriteName() As String Return SpriteDropper.Text End Function Public Sub DeleteSprite() SpriteDropper.Text = "None" End Sub Private Sub SpriteDropper_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SpriteDropper.SelectedIndexChanged OpenSpriteButton.Enabled = True Dim ImageCount As Int16 = 0 If SpriteDropper.Text = "None" Then ImageCount = 1 OpenSpriteButton.Enabled = False Else For Each X As String In Directory.GetFiles(SessionPath + "Sprites") X = X.Substring(X.LastIndexOf("\") + 1) X = X.Substring(0, X.LastIndexOf(".")) X = X.Substring(X.IndexOf("_") + 1) If X = SpriteDropper.Text Then ImageCount += 1 Next End If FrameLimit = ImageCount If Not Frame <= FrameLimit - 1 Then Frame = 0 FrameLeftButton.Enabled = True FrameRightButton.Enabled = True If FrameLimit = 1 Then FrameRightButton.Enabled = False If Frame = 0 Then FrameLeftButton.Enabled = False If Frame = FrameLimit - 1 Then FrameRightButton.Enabled = False RenderSprite() End Sub Private Sub FrameLeftButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FrameLeftButton.Click Frame -= 1 FrameRightButton.Enabled = True RenderSprite() If Frame = 0 Then FrameLeftButton.Enabled = False End Sub Private Sub FrameRightButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FrameRightButton.Click Frame += 1 FrameLeftButton.Enabled = True RenderSprite() If Frame = FrameLimit - 1 Then FrameRightButton.Enabled = False End Sub Private Sub AddEventButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddEventButton.Click, AddEventRightClickButton.Click DEvent.Text = "Add Event" DEvent.ShowDialog() If Not DEvent.UseData Then Exit Sub Dim MainClass As String = DEvent.MainClass Dim SubClass As String = DEvent.SubClass If MainClass = "NoData" Then Exit Sub For X As Int16 = 0 To DEventMainClasses.Count - 1 If DEventMainClasses(X) = MainClass And DEventSubClasses(X) = SubClass Then SaveOnNextChange = True EventsListBox.SelectedIndex = X - 1 Exit Sub End If Next Dim NewLine As String = "EVENT " + NameTextBox.Text + "," + MainClassStringToType(MainClass).ToString + "," + SubClass MyXDSLines += NewLine + vbCrLf If DEventMainClasses.Count = 0 Then SaveOnNextChange = False Else SaveOnNextChange = True End If DEventMainClasses.Add(MainClass) DEventSubClasses.Add(SubClass) EventsListBox.Items.Add(SubClass) EventsListBox.SelectedIndex = EventsListBox.Items.Count - 1 End Sub Private Sub EventsListBox_MeasureItem(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MeasureItemEventArgs) Handles EventsListBox.MeasureItem e.ItemHeight = 24 End Sub Private Sub EventsListBox_DrawItem(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles EventsListBox.DrawItem If e.Index < 0 Then Exit Sub Dim IsSelected As Boolean = False If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then IsSelected = True Dim Drawable As New Bitmap(16, 16) Dim FinalText As String = String.Empty Select Case MainClassStringToType(DEventMainClasses(e.Index)) Case 0 Drawable = My.Resources.QuestionIcon FinalText = "<Unkown>" Case 1 Drawable = My.Resources.CreateEventIcon FinalText = "Create" Case 2, 3, 4 Drawable = My.Resources.KeyIcon FinalText = DEventSubClasses(e.Index) + " " + DEventMainClasses(e.Index) Case 5 Drawable = My.Resources.StylusIcon FinalText += "Touch (" + DEventSubClasses(e.Index) + ")" Case 6 Drawable = My.Resources.Collision Dim TheWith As String = DEventSubClasses(e.Index) If TheWith = "NoData" Then TheWith = "<Unknown>" FinalText += "Collision with " + TheWith Case 7 Drawable = My.Resources.ClockIcon FinalText = "Step" Case 8 Drawable = My.Resources.OtherIcon FinalText += DEventSubClasses(e.Index) End Select e.Graphics.FillRectangle(Brushes.White, e.Bounds) If IsSelected Then e.Graphics.DrawImage(My.Resources.BarBGSmall, e.Bounds) If IsSelected Then e.Graphics.DrawImageUnscaled(My.Resources.RoundedBlock, New Point(2, e.Bounds.Y + 2)) e.Graphics.DrawImage(Drawable, New Point(4, e.Bounds.Y + 4)) 'If IsSelected Then ' e.Graphics.DrawString(FinalText, New Font("Tahoma", 11, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.Black, 24, 5 + e.Bounds.Y) ' e.Graphics.DrawString(FinalText, New Font("Tahoma", 11, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, 24, 4 + e.Bounds.Y) 'Else ' e.Graphics.DrawString(FinalText, New Font("Tahoma", 11, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.Black, 24, 4 + e.Bounds.Y) 'End If If IsSelected Then e.Graphics.DrawString(FinalText, New Font("Tahoma", 11, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, 24, 5 + e.Bounds.Y) e.Graphics.DrawString(FinalText, New Font("Tahoma", 11, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.Black, 24, 4 + e.Bounds.Y) Else e.Graphics.DrawString(FinalText, New Font("Tahoma", 11, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.Black, 24, 4 + e.Bounds.Y) End If End Sub Sub DeleteEvent(ByVal TheIndex As Int16) SaveOnNextChange = False Dim FI As Int16 = 0 If EventsListBox.Items.Count > 1 Then If TheIndex = 0 Then FI = 1 Else FI = 0 EventsListBox.SelectedIndex = FI 'SelectedEvent = FI Else SelectedEvent = 100 End If Dim FinalString As String = String.Empty For Each X As String In StringToLines(MyXDSLines) If X.StartsWith("EVENT " + ObjectName + "," + MainClassStringToType(DEventMainClasses(TheIndex)).ToString + "," + DEventSubClasses(TheIndex)) Then Continue For End If If X.StartsWith("ACT " + ObjectName + "," + MainClassStringToType(DEventMainClasses(TheIndex)).ToString + "," + DEventSubClasses(TheIndex) + ",") Then Continue For End If FinalString += X + vbCrLf Next MyXDSLines = FinalString EventsListBox.Items.RemoveAt(TheIndex) If EventsListBox.Items.Count > 0 Then SelectedEvent = EventsListBox.SelectedIndex DEventMainClasses.RemoveAt(TheIndex) DEventSubClasses.RemoveAt(TheIndex) 'If EventsListBox.SelectedIndex = TheIndex Then ' ActionsList.Items.Clear() ' Actions.Clear() ' ActionDisplays.Clear() ' ActionAppliesTos.Clear() ' ActionArguments.Clear() ' ActionImages.Clear() 'End If 'EventsListBox.Items.RemoveAt(TheIndex) 'DEventMainClasses.RemoveAt(TheIndex) 'DEventSubClasses.RemoveAt(TheIndex) End Sub Private Sub DeleteEventButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteEventButton.Click, DeleteEventRightClickButton.Click 'MsgError(MyXDSLines) 'Exit Sub If EventsListBox.SelectedIndices.Count = 0 Then Exit Sub Dim Response As Byte = MessageBox.Show("Are you sure you want to remove the Event and all of its Actions?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) If Not Response = MsgBoxResult.Yes Then Exit Sub DeleteEvent(EventsListBox.SelectedIndices(0)) End Sub Private Sub ChangeEventButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChangeEventButton.Click, ChangeEventRightClickButton.Click If EventsListBox.SelectedIndices.Count = 0 Then Exit Sub DEvent.ShowDialog() If DEvent.UseData = False Then Exit Sub Dim I As Int16 = EventsListBox.SelectedIndex Dim OldMC As Byte = MainClassStringToType(DEventMainClasses(I)) Dim OldSC As String = DEventSubClasses(I) Dim MC As Byte = MainClassStringToType(DEvent.MainClass) Dim SC As String = DEvent.SubClass If MC = OldMC And SC = OldSC Then Exit Sub If DEventMainClasses.Contains(DEvent.MainClass) And DEventSubClasses.Contains(DEvent.SubClass) Then MsgWarn("That event is already in-use.") Exit Sub End If Dim FinalString As String = String.Empty For Each P As String In StringToLines(MyXDSLines) If P.Length = 0 Then Continue For If P.StartsWith("EVENT ") And P.EndsWith("," + OldMC.ToString + "," + OldSC) Then P = P.Substring(0, P.Length - ("," + OldMC.ToString + "," + OldSC).Length) P += "," + MC.ToString + "," + SC End If If P.StartsWith("ACT " + ObjectName + "," + OldMC.ToString + "," + OldSC + ",") Then P = P.Substring(("ACT " + ObjectName + "," + MC.ToString + "," + SC + ",").Length) P = "ACT " + ObjectName + "," + MC.ToString + "," + SC + "," + P End If FinalString += P + vbCrLf Next MyXDSLines = FinalString DEventMainClasses(I) = DEvent.MainClass DEventSubClasses(I) = SC EventsListBox.Refresh() 'MsgError(Actions.Count.ToString) 'MsgError(ActionArguments.Count.ToString) 'MsgError(ActionAppliesTos.Count.ToString) 'MsgError(ActionDisplays.Count.ToString) 'MsgError(ActionImages.Count.ToString) 'For i As Byte = 0 To Actions.Count - 1 ' MsgError(Actions(i)) ' MsgError(ActionArguments(i)) ' MsgError(ActionAppliesTos(i)) 'Next 'MsgError(MyXDSLines) 'For Each X As String In ActionAppliesTos ' MsgError(X) 'Next 'MsgError(FS) 'Actions(DraggingInternal) = Actions(DraggingInternal - 1) 'Exit Sub 'DEvent.Text = "Change Event" 'MsgError(MyXDSLines) End Sub Private Sub ActionsList_DrawItem(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles ActionsList.DrawItem If e.Index < 0 Then Exit Sub Dim IsSelected As Boolean = False Dim ThinNum As Byte = If(ThinList, 24, 36) If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then IsSelected = True Dim MyX As Int16 = CurrentIndents(e.Index) * If(ThinList, 16, 24) e.Graphics.FillRectangle(Brushes.White, New Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height)) If IsSelected Then e.Graphics.DrawImage(My.Resources.BarBG, New Rectangle(0, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height)) Dim ThingString As String = ActionAppliesTos(e.Index) Dim ArgString As String = String.Empty Dim NiceArgs As String = ArgumentsMakeAttractive(ActionArguments(e.Index), True) If ThinList Then e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic e.Graphics.DrawImage(ActionGetIcon(Actions(e.Index)), New Rectangle(MyX + 2, e.Bounds.Y + 2, 20, 20)) e.Graphics.DrawString(ActionDisplays(e.Index), New Font("Tahoma", 11, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, MyX + ThinNum, e.Bounds.Y + 5 + 1) e.Graphics.DrawString(ActionDisplays(e.Index), New Font("Tahoma", 11, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.Black, MyX + ThinNum, e.Bounds.Y + 5) Exit Sub Else e.Graphics.DrawImageUnscaled(ActionGetIcon(Actions(e.Index)), New Point(MyX + 2, e.Bounds.Y + 2)) If NiceArgs.Length > 0 Then If ThingString = "this" Then If Actions(e.Index) = "Execute Code" Then ArgString = NiceArgs Else ArgString = "Arguments of " + NiceArgs End If ElseIf IsObject(ThingString) Then If Actions(e.Index) = "Execute Code" Then ArgString = "Applies to instances of " + ThingString + ": " + NiceArgs Else ArgString = "Applies to instances of " + ThingString + " with Args. " + NiceArgs End If Else If Actions(e.Index) = "Execute Code" Then ArgString = "Applies to instance IDs " + ThingString + ": " + NiceArgs Else ArgString = "Applies to instance IDs " + ThingString + " with Args. " + NiceArgs End If End If 'Else ' If IsObject(ThingString) Then ' ArgString = "Applies to instances of " + ThingString ' Else ' ArgString = "Applies to instance IDs " + ThingString ' End If End If Dim TheY As Int16 = e.Bounds.Y + If(NiceArgs.Length > 0, 5, 10) If IsSelected Then e.Graphics.DrawString(ArgString, New Font("Tahoma", 11, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, MyX + ThinNum, e.Bounds.Y + (ThinNum / 2) + 1) e.Graphics.DrawString(ArgString, New Font("Tahoma", 11, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.Gray, MyX + ThinNum, e.Bounds.Y + 18) e.Graphics.DrawString(ActionDisplays(e.Index), New Font("Tahoma", 11, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, MyX + ThinNum, e.Bounds.Y + If(NiceArgs.Length > 0, 5, 10) + 1) e.Graphics.DrawString(ActionDisplays(e.Index), New Font("Tahoma", 11, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.Black, MyX + ThinNum, e.Bounds.Y + If(NiceArgs.Length > 0, 5, 10)) e.Graphics.DrawImageUnscaled(My.Resources.Corners, New Point(-7, e.Bounds.Y - 6)) e.Graphics.DrawImageUnscaled(My.Resources.Corners, New Point(-7, e.Bounds.Y + ThinNum - 6)) e.Graphics.DrawImageUnscaled(My.Resources.Corners, New Point(e.Bounds.Width - 7, e.Bounds.Y - 7)) e.Graphics.DrawImageUnscaled(My.Resources.Corners, New Point(e.Bounds.Width - 7, e.Bounds.Y + 29)) Else e.Graphics.DrawString(ArgString, New Font("Tahoma", 11, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.LightGray, MyX + ThinNum, e.Bounds.Y + (ThinNum / 2)) e.Graphics.DrawString(ActionDisplays(e.Index), New Font("Tahoma", 11, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.Black, MyX + ThinNum, e.Bounds.Y + If(NiceArgs.Length > 0, 5, 10)) End If End If End Sub Private Sub ActionsList_MeasureItem(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MeasureItemEventArgs) Handles ActionsList.MeasureItem e.ItemHeight = If(ThinList, 24, 36) End Sub Public Function ArgumentsMakeAttractive(ByVal InputArguments As String, ByVal HideSymbols As Boolean) As String Dim Returnable As String = InputArguments Returnable = Returnable.Replace(";", ", ").Replace("<com>", ",").Replace("<sem>", ";") If HideSymbols Then Returnable = Returnable.Replace("<br|>", " .. ") Return Returnable End Function Sub SaveCurrentData() 'MsgError(SelectedEvent.ToString) 'MsgError("Saved Current Data") If EventsListBox.SelectedIndices.Count = 0 Then Exit Sub 'If DEventMainClasses.Count = 0 Then Exit Sub 'MsgError("SaveCurrentData 2") Dim FinalString As String = String.Empty 'MsgError("filter is ACT " + ObjectName + "," + DEventMainClasses(TempIndex) + "," + DEventSubClasses(TempIndex) + ",") 'MsgError("filter is ACT " + ObjectName + "," + MainClassStringToType(DEventMainClasses(SelectedEvent)).ToString + "," + DEventSubClasses(SelectedEvent) + ",") 'MsgError(MainClassStringToType(DEventMainClasses(SelectedEvent)).ToString) For Each X As String In StringToLines(MyXDSLines) If X.Length = 0 Then Continue For 'MsgError(X + vbcrlf + vbcrlf + "against" + vbcrlf + vbcrlf + "ACT " + ObjectName + "," + MainClassStringToType(DEventMainClasses(SelectedEvent)).ToString + "," + DEventSubClasses(SelectedEvent) + ",") If Not X.StartsWith("ACT " + ObjectName + "," + MainClassStringToType(DEventMainClasses(SelectedEvent)).ToString + "," + DEventSubClasses(SelectedEvent) + ",") Then FinalString += X + vbCrLf End If Next 'MsgError(FinalString) 'MsgError("new index is " + EventsListBox.SelectedIndex.ToString) 'Dim TempIndex As Byte = EventsListBox.SelectedIndex For X As Int16 = 0 To Actions.Count - 1 Dim TheNewLine As String = "ACT " + ObjectName + "," + MainClassStringToType(DEventMainClasses(SelectedEvent)).ToString + "," + DEventSubClasses(SelectedEvent) + "," TheNewLine += Actions(X) + "," + ActionArguments(X) + "," + ActionAppliesTos(X) FinalString += TheNewLine + vbCrLf Next MyXDSLines = FinalString End Sub Private Sub EventsListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EventsListBox.SelectedIndexChanged 'MsgBox(If(SaveDataOnEventChange, "true", "false")) If EventsListBox.Items.Count = 0 Then Exit Sub If EventsListBox.SelectedIndex < 0 Then Exit Sub If EventsListBox.SelectedIndex > DEventMainClasses.Count - 1 Then Exit Sub 'If SelectedEvent = 100 Then Exit Sub If SaveOnNextChange Then SaveCurrentData() SaveOnNextChange = True Actions.Clear() ActionArguments.Clear() ActionDisplays.Clear() ActionAppliesTos.Clear() ActionImages.Clear() ActionsList.Items.Clear() 'GenerateIndentIndices() Dim MainClass As Byte = MainClassStringToType(DEventMainClasses(EventsListBox.SelectedIndex)) Dim SubClass As String = DEventSubClasses(EventsListBox.SelectedIndex) 'MsgError("Mainclass is " + MainClass.ToString) 'MsgError("Subclass is " + SubClass.ToString) 'MsgError("Gonna work on:" + vbcrlf + vbcrlf + MyXDSLines) Dim TempCount As Int16 = 0 If MyXDSLines.Length > 0 Then For Each X As String In StringToLines(MyXDSLines) If X.Length = 0 Then Continue For If Not X.StartsWith("ACT ") Then Continue For X = SillyFixMe(X) 'MsgError(X(X.Length - 1)) If Not (iGet(X, 1, ",") = MainClass.ToString) Or Not (iGet(X, 2, ",") = SubClass) Then Continue For 'MsgError("On X at " + X) Dim ActionName As String = iGet(X, 3, ",") 'MsgError("ActionName is " + ActionName) Dim ActionArgs As String = iGet(X, 4, ",") 'ActionArgs = ActionArgs.Replace("<com>", ",") 'MsgError("Action Arguments are " + ActionArgs.ToString) Actions.Add(ActionName) ActionArguments.Add(ActionArgs) Dim AppliesTo As String = iGet(X, 5, ",") 'MsgError(ActionEquateDisplay(ActionName, ActionArgs)) ActionDisplays.Add(ActionEquateDisplay(ActionName, ActionArgs)) ActionAppliesTos.Add(AppliesTo) ActionImages.Add(ActionGetIconPath(ActionName, False)) 'MsgError(ActionGetIconPath(ActionName, False)) TempCount += 1 Next End If GenerateIndentIndices() If TempCount > 0 Then For X = 0 To TempCount - 1 ActionsList.Items.Add(String.Empty) Next End If 'Hmm 'SaveDataOnEventChange = False SelectedEvent = EventsListBox.SelectedIndex 'MsgError(SelectedEvent) End Sub Private Sub OpenSpriteButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenSpriteButton.Click For Each TheForm As Form In Me.MdiChildren If TheForm.Text = SpriteDropper.Text Then TheForm.Focus() Exit Sub End If Next Dim SpriteForm As New Sprite SpriteForm.SpriteName = SpriteDropper.Text ShowInternalForm(SpriteForm) End Sub Sub EditAction() If ActionsList.SelectedIndices.Count = 0 Then Exit Sub If ActionsList.SelectedIndices.Count > 1 Then MsgWarn("You may only edit one Action at once.") Exit Sub End If Dim EditingIndex As Int16 = ActionsList.SelectedIndices(0) If Actions(EditingIndex) = "Execute Code" Then EditCode.ReturnableCode = ActionArguments(EditingIndex) EditCode.CodeMode = CodeMode.DBAS EditCode.ImportExport = True If EditCode.ShowDialog = Windows.Forms.DialogResult.OK Then ActionArguments(EditingIndex) = EditCode.ReturnableCode End If Else 'MsgError("Previous to Opening the dialogue") 'MsgError("AppliesTo: """ + ActionAppliesTos(EditingIndex) + """") With Action .ArgumentString = ActionArguments(EditingIndex) .ActionName = Actions(EditingIndex) .AppliesTo = ActionAppliesTos(EditingIndex) .ShowDialog() If Not .UseData Then Exit Sub ActionAppliesTos.Item(EditingIndex) = .AppliesTo ActionArguments.Item(EditingIndex) = .ArgumentString ActionDisplays.Item(EditingIndex) = ActionEquateDisplay(.ActionName, .ArgumentString) End With ActionsList.Invalidate() End If End Sub Function ShouldAllowDialog(ByVal ActionName As String) As Boolean Dim NoAppliesTo As Boolean = False Dim ArgCount As Byte = 0 For Each X As String In File.ReadAllLines(AppPath + "Actions\" + Actions(ActionsList.SelectedIndices(0)) + ".action") If X = "NOAPPLIES" Then NoAppliesTo = True If X.StartsWith("ARG ") Then ArgCount += 1 Next If ArgCount = 0 And NoAppliesTo Then Return False Return True End Function Private Sub ActionsList_MouseDoubleClick() Handles ActionsList.MouseDoubleClick, EditValuesRightClickButton.Click If ActionsList.SelectedIndices.Count = 0 Then Exit Sub If ShouldAllowDialog(Actions(ActionsList.SelectedIndices(0))) Then EditAction() End Sub Private Sub DeleteRightClickButton_Click() Handles DeleteActionRightClickButton.Click While ActionsList.SelectedIndices.Count > 0 Dim TheIndex As Int16 = ActionsList.SelectedIndices(0) Actions.RemoveAt(TheIndex) ActionDisplays.RemoveAt(TheIndex) ActionArguments.RemoveAt(TheIndex) ActionAppliesTos.RemoveAt(TheIndex) ActionImages.RemoveAt(TheIndex) ActionsList.Items.RemoveAt(TheIndex) End While 'ActionsList.Items.RemoveAt(ActionsList.SelectedIndex) GenerateIndentIndices() End Sub Private Sub ActionRightClickMenu_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ActionRightClickMenu.Opening Dim HasActions As Boolean = If(ActionsList.Items.Count > 0, True, False) DeleteActionRightClickButton.Enabled = HasActions CutActionRightClickButton.Enabled = HasActions CopyActionRightClickButton.Enabled = HasActions ClearActionsRightClickButton.Enabled = HasActions If ActionsList.Items.Count > 0 Then ActionsList.SelectedIndex = ActionsList.IndexFromPoint(ActionsList.PointToClient(Control.MousePosition)) End If Dim CanPaste As Boolean = Clipboard.ContainsText() If CanPaste Then 'Attempt to disprove paste ability Dim DOn As Int32 = 0 Dim TheItems As New List(Of String) For Each X As String In StringToLines(Clipboard.GetText) If X.Length > 0 Then If DOn = 0 And Not X = "DSGMACTS" Then CanPaste = False : Exit For If DOn > 0 Then TheItems.Add(X) End If DOn += 1 End If Next If TheItems.Count = 0 Then CanPaste = False End If EditValuesRightClickButton.Enabled = If(ActionsList.SelectedIndices.Count = 1, True, False) PasteActionBelowRightClickButton.Enabled = CanPaste If ActionsList.Items.Count > 0 Then If Not ShouldAllowDialog(Actions(ActionsList.SelectedIndex)) Then EditValuesRightClickButton.Enabled = False End If End If End Sub Private Sub ActionsList_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ActionsList.MouseDown If Not ActionsList.SelectionMode = SelectionMode.One Then Exit Sub DragInternal = True DraggingInternal = ActionsList.SelectedIndex Me.Cursor = Cursors.NoMove2D End Sub Private Sub ActionsList_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ActionsList.MouseUp If Not ActionsList.SelectionMode = SelectionMode.One Then Exit Sub DragInternal = False GenerateIndentIndices() ActionsList.Invalidate() Me.Cursor = Cursors.Default End Sub Private Sub ActionsList_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ActionsList.MouseMove If Not ActionsList.SelectionMode = SelectionMode.One Then Exit Sub If Not DragInternal Then Exit Sub If DraggingInternal = ActionsList.SelectedIndex Then Exit Sub If DraggingInternal > ActionsList.SelectedIndex Then Dim TextForCurrent As String = Actions(DraggingInternal - 1) Dim TextForAbove As String = Actions(DraggingInternal) Actions(DraggingInternal) = TextForCurrent Actions(DraggingInternal - 1) = TextForAbove Dim ImageForCurrent As String = ActionImages(DraggingInternal - 1) Dim ImageForAbove As String = ActionImages(DraggingInternal) ActionImages(DraggingInternal) = ImageForCurrent ActionImages(DraggingInternal - 1) = ImageForAbove Dim ArgumentForCurrent As String = ActionArguments(DraggingInternal - 1) Dim ArgumentForAbove As String = ActionArguments(DraggingInternal) ActionArguments(DraggingInternal) = ArgumentForCurrent ActionArguments(DraggingInternal - 1) = ArgumentForAbove Dim DisplayForCurrent As String = ActionDisplays(DraggingInternal - 1) Dim DisplayForAbove As String = ActionDisplays(DraggingInternal) ActionDisplays(DraggingInternal) = DisplayForCurrent ActionDisplays(DraggingInternal - 1) = DisplayForAbove Dim ApplyForCurrent As String = ActionAppliesTos(DraggingInternal - 1) Dim ApplyForAbove As String = ActionAppliesTos(DraggingInternal) ActionAppliesTos(DraggingInternal) = ApplyForCurrent ActionAppliesTos(DraggingInternal - 1) = ApplyForAbove DraggingInternal -= 1 Else Dim TextForCurrent As String = Actions(DraggingInternal + 1) Dim TextForAbove As String = Actions(DraggingInternal) Actions(DraggingInternal) = TextForCurrent Actions(DraggingInternal + 1) = TextForAbove Dim ImageForCurrent As String = ActionImages(DraggingInternal + 1) Dim ImageForAbove As String = ActionImages(DraggingInternal) ActionImages(DraggingInternal) = ImageForCurrent ActionImages(DraggingInternal + 1) = ImageForAbove Dim ArgumentForCurrent As String = ActionArguments(DraggingInternal + 1) Dim ArgumentForAbove As String = ActionArguments(DraggingInternal) ActionArguments(DraggingInternal) = ArgumentForCurrent ActionArguments(DraggingInternal + 1) = ArgumentForAbove Dim DisplayForCurrent As String = ActionDisplays(DraggingInternal + 1) Dim DisplayForAbove As String = ActionDisplays(DraggingInternal) ActionDisplays(DraggingInternal) = DisplayForCurrent ActionDisplays(DraggingInternal + 1) = DisplayForAbove Dim ApplyForCurrent As String = ActionAppliesTos(DraggingInternal + 1) Dim ApplyForAbove As String = ActionAppliesTos(DraggingInternal) ActionAppliesTos(DraggingInternal) = ApplyForCurrent ActionAppliesTos(DraggingInternal + 1) = ApplyForAbove DraggingInternal += 1 End If ActionsList.Invalidate() End Sub 'Function GenerateForumLine(ByVal RowID As Int16) As String ' Dim Returnable As String = Actions(RowID) + " " + ArgumentsMakeAttractive(ActionArguments(RowID)) ' Dim ApplyTo As String = ActionAppliesTos(RowID) ' If Not ApplyTo = "this" Then ' If IsObject(ApplyTo) Then ' ApplyTo = "instances of " + ApplyTo ' Else ' ApplyTo = "instances IDs " + ApplyTo ' End If ' Returnable += " (applying to " + ApplyTo + ")" ' End If ' Return Returnable 'End Function Sub RepopulateLibrary() PopulateActionsTabControl(ActionsToAddTabControl) End Sub 'Private Sub CopyAllForForumButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) ' Dim FinalString As String = "Actions for " + DEventMainClasses(SelectedEvent) + " Event on " + ObjectName + vbcrlf + vbcrlf ' For X As Int16 = 0 To ActionsList.Items.Count - 1 ' FinalString += GenerateForumLine(X) + vbcrlf ' Next ' Clipboard.SetText(FinalString) 'End Sub 'Private Sub ActionsDropper_DropDownOpening(ByVal sender As System.Object, ByVal e As System.EventArgs) ' For X As Byte = 0 To ActionsDropper.DropDownItems.Count - 1 ' ActionsDropper.DropDownItems(X).Enabled = True ' Next ' If ActionsList.Items.Count = 0 Then ' CopyAllForForumButton.Enabled = False ' 'FUTURE ADDITION?? ' End If 'End Sub Private Sub ClearRightClickButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ClearActionsRightClickButton.Click Dim Response As Byte = MessageBox.Show("Are you sure you want to clear the list of Actions?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) If Not Response = MsgBoxResult.Yes Then Exit Sub Actions.Clear() ActionImages.Clear() ActionDisplays.Clear() ActionAppliesTos.Clear() ActionArguments.Clear() ActionsList.Items.Clear() GenerateIndentIndices() End Sub Private Sub CutRightClickButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CutActionRightClickButton.Click CopyActionRightClickButton_Click() DeleteRightClickButton_Click() End Sub Private Sub EventRightClickMenu_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles EventRightClickMenu.Opening If Not EventsListBox.Items.Count = 0 Then EventsListBox.SelectedIndex = EventsListBox.IndexFromPoint(EventsListBox.PointToClient(Control.MousePosition)) For X As Byte = 0 To EventRightClickMenu.Items.Count - 1 EventRightClickMenu.Items(X).Enabled = True Next If EventsListBox.Items.Count = 0 Then ChangeEventRightClickButton.Enabled = False DeleteEventRightClickButton.Enabled = False ClearEventsButton.Enabled = False Exit Sub End If End Sub Private Sub ClearEventsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ClearEventsButton.Click Dim Response As Byte = MessageBox.Show("Are you sure you want to clear the list of Events?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) If Not Response = MsgBoxResult.Yes Then Exit Sub EventsListBox.Items.Clear() DEventMainClasses.Clear() DEventSubClasses.Clear() Actions.Clear() ActionImages.Clear() ActionDisplays.Clear() ActionAppliesTos.Clear() ActionArguments.Clear() ActionsList.Items.Clear() GenerateIndentIndices() MyXDSLines = String.Empty End Sub Private Sub SelectAllButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SelectAllButton.Click For i As Int16 = 0 To ActionsList.Items.Count - 1 ActionsList.SelectedIndices.Add(i) Next 'Dim FinalString As String = "DSGMALL" + vbcrlf 'For i As Int16 = 0 To Actions.Count - 1 ' FinalString += Actions(i) + "," ' FinalString += ActionArguments(i) + "," ' FinalString += ActionAppliesTos(i) + vbcrlf 'Next 'Clipboard.SetText(FinalString) End Sub Private Sub CopyActionRightClickButton_Click() Handles CopyActionRightClickButton.Click Dim FinalString As String = "DSGMACTS" + vbCrLf For Each X As Int16 In ActionsList.SelectedIndices FinalString += Actions(X) + "," + ActionArguments(X) + "," + ActionAppliesTos(X) + vbCrLf Next FinalString = FinalString.Substring(0, FinalString.Length - 1) Clipboard.SetText(FinalString) End Sub 'Private Sub PasteAtBottomButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) ' If Not Clipboard.ContainsText Then Exit Sub ' If Not Clipboard.GetText.StartsWith("DSGMALL") Then Exit Sub ' For Each X As String In StringToLines(Clipboard.GetText) ' If X.StartsWith("DSGMALL") Then Continue For ' If X.Length = 0 Then Continue For ' Dim ActionName As String = iget(X, 0, ",") ' Dim ActionArgs As String = iget(X, 1, ",") ' Dim ActionApply As String = iget(X, 2, ",") ' Actions.Add(ActionName) ' ActionArguments.Add(ActionArgs) ' ActionAppliesTos.Add(ActionApply) ' ActionDisplays.Add(ActionEquateDisplay(ActionName, ActionArgs)) ' ActionImages.Add(ActionGetIconPath(ActionName, False)) ' ActionsList.Items.Add(String.Empty) ' Next ' GenerateIndentIndices() 'End Sub Private Sub SelectOneButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SelectOneButton.Click, SelectOneRightClickButton.Click ActionsList.SelectionMode = SelectionMode.One End Sub Private Sub SelectManyButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SelectManyButton.Click, SelectManyRightClickButton.Click ActionsList.SelectionMode = SelectionMode.MultiExtended End Sub End Class
jadaradix/dsgamemaker
DObject.vb
Visual Basic
mit
59,804
Public Class DetalleConciliacion Public Property IdDetalle As Int32 Public Property IdConciliacion As Int32 Public Property Fecha As Date Public Property Glosa As String Public Property IdProveedorCliente As Int32 Public Property Monto As Decimal Public Property IdTipoMovimiento As Int32 Public Property Coa As ProveedorCliente Public Property TipoMovimiento As TipoMovimiento Public ReadOnly Property ProveedorCliente As String Get Return Coa.Ruc + " " + Coa.RazonSocial End Get End Property Public ReadOnly Property TipoMovimientoDesc As String Get Return TipoMovimiento.Descripcion End Get End Property End Class
crackper/SistFoncreagro
SistFoncreagro.BussinessEntities/DetalleConciliacion.vb
Visual Basic
mit
728
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.17626 ' ' 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.ImgBrick5.mForm End Sub End Class End Namespace
DadeLamkins/ImgBrick3
My Project/Application.Designer.vb
Visual Basic
mit
1,475
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Simulasjon Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.SuspendLayout() ' 'Simulasjon ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(789, 261) Me.Name = "Simulasjon" Me.Text = "Simulasjon" Me.ResumeLayout(False) End Sub End Class
Audiopolis/Gruppe21-prosjekt
TestingGrounds/TestingGrounds/Simulasjon.Designer.vb
Visual Basic
mit
1,274
Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Namespace Examples Friend Class Program <STAThread> Shared Sub Main(ByVal args() As String) Dim application As SolidEdgeFramework.Application = Nothing Dim documents As SolidEdgeFramework.Documents = Nothing Dim partDocument As SolidEdgePart.PartDocument = Nothing Dim refPlanes As SolidEdgePart.RefPlanes = Nothing Dim profileSets As SolidEdgePart.ProfileSets = Nothing Dim profileSet As SolidEdgePart.ProfileSet = Nothing Dim profiles As SolidEdgePart.Profiles = Nothing Dim profile As SolidEdgePart.Profile = Nothing Dim bSplineCurves2d As SolidEdgeFrameworkSupport.BSplineCurves2d = Nothing Dim bSplineCurve2d As SolidEdgeFrameworkSupport.BSplineCurve2d = Nothing Dim lines2d As SolidEdgeFrameworkSupport.Lines2d = Nothing Dim line2d As SolidEdgeFrameworkSupport.Line2d = Nothing Try ' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic. OleMessageFilter.Register() ' Attempt to connect to a running instance of Solid Edge. application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application) documents = application.Documents partDocument = CType(documents.Add("SolidEdge.PartDocument"), SolidEdgePart.PartDocument) refPlanes = partDocument.RefPlanes profileSets = partDocument.ProfileSets profileSet = profileSets.Add() profiles = profileSet.Profiles profile = profiles.Add(refPlanes.Item(1)) bSplineCurves2d = profile.BSplineCurves2d ' Contains x and y pairs that specify the points that define the curve. Dim Points = CType(New Double(), System.Array) { 0, 0, 0.03, 0.02, 0.04, 0.01, 0.05, 0.08, 0.07, 0.04 } bSplineCurve2d = bSplineCurves2d.AddByPoints(4, Points.Length \ 2, Points) lines2d = profile.Lines2d line2d = lines2d.AddBy2Points(0.06, 0.035, 0.08, 0.035) bSplineCurve2d.Extend(0.09, 0.1, line2d) Catch ex As System.Exception Console.WriteLine(ex) Finally OleMessageFilter.Unregister() End Try End Sub End Class End Namespace
SolidEdgeCommunity/docs
docfx_project/snippets/SolidEdgeFrameworkSupport.BSplineCurve2d.Extend.vb
Visual Basic
mit
2,558
''' <summary> ''' Public variable which will be set as the active inventor application ''' when the Add In is loaded <see cref="Inventor_To_M2K.StandardAddInServer"/> ''' </summary> Module globals Public m_inventorApplication As Inventor.Application End Module
LindyMan93/Inventor_2_M2K
Inventor_To_M2K/Inventor_To_M2K/globals.vb
Visual Basic
mit
268
' The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 Imports WinRTXamlToolkit.Controls.DataVisualization.Charting ''' <summary> ''' An empty page that can be used on its own or navigated to within a Frame. ''' </summary> Public NotInheritable Class MainPage Inherits Page Public Sub New() ' This call is required by the designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. AddHandler Me.Loaded, AddressOf MainPage_Loaded End Sub Private Sub MainPage_Loaded(sender As Object, e As RoutedEventArgs) LoadChartContents() End Sub Private Sub LoadChartContents() Dim rand As New Random() Dim financialStuffList As New List(Of FinancialStuff)() financialStuffList.Add(New FinancialStuff() With { .Name = "MSFT", .Amount = rand.[Next](0, 200) }) financialStuffList.Add(New FinancialStuff() With { .Name = "AAPL", .Amount = rand.[Next](0, 200) }) financialStuffList.Add(New FinancialStuff() With { .Name = "GOOG", .Amount = rand.[Next](0, 200) }) financialStuffList.Add(New FinancialStuff() With { .Name = "BBRY", .Amount = rand.[Next](0, 200) }) TryCast(PieChart.Series(0), PieSeries).ItemsSource = financialStuffList TryCast(ColumnChart.Series(0), ColumnSeries).ItemsSource = financialStuffList TryCast(LineChart.Series(0), LineSeries).ItemsSource = financialStuffList TryCast(BarChart.Series(0), BarSeries).ItemsSource = financialStuffList TryCast(BubbleChart.Series(0), BubbleSeries).ItemsSource = financialStuffList End Sub Private Sub ButtonRefresh_Click(sender As Object, e As RoutedEventArgs) LoadChartContents() End Sub End Class
Myfreedom614/UWP-Samples
WinRTXamlToolkitChartingVBApp1/WinRTXamlToolkitChartingVBApp1/MainPage.xaml.vb
Visual Basic
mit
2,178
' 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.Concurrent Imports System.Collections.Immutable Imports System.IO Imports System.Reflection.Metadata Imports System.Runtime.InteropServices Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.Cci Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.InternalUtilities Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' The Compilation object is an immutable representation of a single invocation of the ''' compiler. Although immutable, a Compilation is also on-demand, in that a compilation can be ''' created quickly, but will that compiler parts or all of the code in order to respond to ''' method or properties. Also, a compilation can produce a new compilation with a small change ''' from the current compilation. This is, in many cases, more efficient than creating a new ''' compilation from scratch, as the new compilation can share information from the old ''' compilation. ''' </summary> Public NotInheritable Class VisualBasicCompilation Inherits Compilation ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ' ' Changes to the public interface of this class should remain synchronized with the C# ' version. Do not make any changes to the public interface without making the corresponding ' change to the C# version. ' ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ''' <summary> ''' most of time all compilation would use same MyTemplate. no reason to create (reparse) one for each compilation ''' as long as its parse option is same ''' </summary> Private Shared ReadOnly s_myTemplateCache As ConcurrentLruCache(Of VisualBasicParseOptions, SyntaxTree) = New ConcurrentLruCache(Of VisualBasicParseOptions, SyntaxTree)(capacity:=5) ''' <summary> ''' The SourceAssemblySymbol for this compilation. Do not access directly, use Assembly ''' property instead. This field is lazily initialized by ReferenceManager, ''' ReferenceManager.CacheLockObject must be locked while ReferenceManager "calculates" the ''' value and assigns it, several threads must not perform duplicate "calculation" ''' simultaneously. ''' </summary> Private _lazyAssemblySymbol As SourceAssemblySymbol ''' <summary> ''' Holds onto data related to reference binding. ''' The manager is shared among multiple compilations that we expect to have the same result of reference binding. ''' In most cases this can be determined without performing the binding. If the compilation however contains a circular ''' metadata reference (a metadata reference that refers back to the compilation) we need to avoid sharing of the binding results. ''' We do so by creating a new reference manager for such compilation. ''' </summary> Private _referenceManager As ReferenceManager ''' <summary> ''' The options passed to the constructor of the Compilation ''' </summary> Private ReadOnly _options As VisualBasicCompilationOptions ''' <summary> ''' The global namespace symbol. Lazily populated on first access. ''' </summary> Private _lazyGlobalNamespace As NamespaceSymbol ''' <summary> ''' The syntax trees explicitly given to the compilation at creation, in ordinal order. ''' </summary> Private ReadOnly _syntaxTrees As ImmutableArray(Of SyntaxTree) Private ReadOnly _syntaxTreeOrdinalMap As ImmutableDictionary(Of SyntaxTree, Integer) ''' <summary> ''' The syntax trees of this compilation plus all 'hidden' trees ''' added to the compilation by compiler, e.g. Vb Core Runtime. ''' </summary> Private _lazyAllSyntaxTrees As ImmutableArray(Of SyntaxTree) ''' <summary> ''' A map between syntax trees and the root declarations in the declaration table. ''' Incrementally updated between compilation versions when source changes are made. ''' </summary> Private ReadOnly _rootNamespaces As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry) ''' <summary> ''' Imports appearing in <see cref="SyntaxTree"/>s in this compilation. ''' </summary> ''' <remarks> ''' Unlike in C#, we don't need to use a set because the <see cref="SourceFile"/> objects ''' that record the imports are persisted. ''' </remarks> Private _lazyImportInfos As ConcurrentQueue(Of ImportInfo) Private _lazyImportClauseDependencies As ConcurrentDictionary(Of (SyntaxTree As SyntaxTree, ImportsClausePosition As Integer), ImmutableArray(Of AssemblySymbol)) ''' <summary> ''' Cache the CLS diagnostics for the whole compilation so they aren't computed repeatedly. ''' </summary> ''' <remarks> ''' NOTE: Presently, we do not cache the per-tree diagnostics. ''' </remarks> Private _lazyClsComplianceDiagnostics As ImmutableArray(Of Diagnostic) Private _lazyClsComplianceDependencies As ImmutableArray(Of AssemblySymbol) ''' <summary> ''' A SyntaxTree and the associated RootSingleNamespaceDeclaration for an embedded ''' syntax tree in the Compilation. Unlike the entries in m_rootNamespaces, the ''' SyntaxTree here is lazy since the tree cannot be evaluated until the references ''' have been resolved (as part of binding the source module), and at that point, the ''' SyntaxTree may be Nothing if the embedded tree is not needed for the Compilation. ''' </summary> Private Structure EmbeddedTreeAndDeclaration Public ReadOnly Tree As Lazy(Of SyntaxTree) Public ReadOnly DeclarationEntry As DeclarationTableEntry Public Sub New(treeOpt As Func(Of SyntaxTree), rootNamespaceOpt As Func(Of RootSingleNamespaceDeclaration)) Me.Tree = New Lazy(Of SyntaxTree)(treeOpt) Me.DeclarationEntry = New DeclarationTableEntry(New Lazy(Of RootSingleNamespaceDeclaration)(rootNamespaceOpt), isEmbedded:=True) End Sub End Structure Private ReadOnly _embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration) ''' <summary> ''' The declaration table that holds onto declarations from source. Incrementally updated ''' between compilation versions when source changes are made. ''' </summary> ''' <remarks></remarks> Private ReadOnly _declarationTable As DeclarationTable ''' <summary> ''' Manages anonymous types declared in this compilation. Unifies types that are structurally equivalent. ''' </summary> Private ReadOnly _anonymousTypeManager As AnonymousTypeManager ''' <summary> ''' Manages automatically embedded content. ''' </summary> Private _lazyEmbeddedSymbolManager As EmbeddedSymbolManager ''' <summary> ''' MyTemplate automatically embedded from resource in the compiler. ''' It doesn't feel like it should be managed by EmbeddedSymbolManager ''' because MyTemplate is treated as user code, i.e. can be extended via ''' partial declarations, doesn't require "on-demand" metadata generation, etc. ''' ''' SyntaxTree.Dummy means uninitialized. ''' </summary> Private _lazyMyTemplate As SyntaxTree = VisualBasicSyntaxTree.Dummy Private ReadOnly _scriptClass As Lazy(Of ImplicitNamedTypeSymbol) ''' <summary> ''' Contains the main method of this assembly, if there is one. ''' </summary> Private _lazyEntryPoint As EntryPoint ''' <summary> ''' The set of trees for which a <see cref="CompilationUnitCompletedEvent"/> has been added to the queue. ''' </summary> Private _lazyCompilationUnitCompletedTrees As HashSet(Of SyntaxTree) ''' <summary> ''' The common language version among the trees of the compilation. ''' </summary> Private ReadOnly _languageVersion As LanguageVersion Public Overrides ReadOnly Property Language As String Get Return LanguageNames.VisualBasic End Get End Property Public Overrides ReadOnly Property IsCaseSensitive As Boolean Get Return False End Get End Property Friend ReadOnly Property Declarations As DeclarationTable Get Return _declarationTable End Get End Property Friend ReadOnly Property MergedRootDeclaration As MergedNamespaceDeclaration Get Return Declarations.GetMergedRoot(Me) End Get End Property Public Shadows ReadOnly Property Options As VisualBasicCompilationOptions Get Return _options End Get End Property ''' <summary> ''' The language version that was used to parse the syntax trees of this compilation. ''' </summary> Public ReadOnly Property LanguageVersion As LanguageVersion Get Return _languageVersion End Get End Property Friend ReadOnly Property AnonymousTypeManager As AnonymousTypeManager Get Return Me._anonymousTypeManager End Get End Property Friend Overrides ReadOnly Property CommonAnonymousTypeManager As CommonAnonymousTypeManager Get Return Me._anonymousTypeManager End Get End Property ''' <summary> ''' SyntaxTree of MyTemplate for the compilation. Settable for testing purposes only. ''' </summary> Friend Property MyTemplate As SyntaxTree Get If _lazyMyTemplate Is VisualBasicSyntaxTree.Dummy Then Dim compilationOptions = Me.Options If compilationOptions.EmbedVbCoreRuntime OrElse compilationOptions.SuppressEmbeddedDeclarations Then _lazyMyTemplate = Nothing Else ' first see whether we can use one from global cache Dim parseOptions = If(compilationOptions.ParseOptions, VisualBasicParseOptions.Default) Dim tree As SyntaxTree = Nothing If s_myTemplateCache.TryGetValue(parseOptions, tree) Then Debug.Assert(tree IsNot Nothing) Debug.Assert(tree IsNot VisualBasicSyntaxTree.Dummy) Debug.Assert(tree.IsMyTemplate) Interlocked.CompareExchange(_lazyMyTemplate, tree, VisualBasicSyntaxTree.Dummy) Else ' we need to make one. Dim text As String = EmbeddedResources.VbMyTemplateText ' The My template regularly makes use of more recent language features. Care is ' taken to ensure these are compatible with 2.0 runtimes so there is no danger ' with allowing the newer syntax here. Dim options = parseOptions.WithLanguageVersion(LanguageVersion.Default) tree = VisualBasicSyntaxTree.ParseText(text, options:=options, isMyTemplate:=True) If tree.GetDiagnostics().Any() Then Throw ExceptionUtilities.Unreachable End If If Interlocked.CompareExchange(_lazyMyTemplate, tree, VisualBasicSyntaxTree.Dummy) Is VisualBasicSyntaxTree.Dummy Then ' set global cache s_myTemplateCache(parseOptions) = tree End If End If End If Debug.Assert(_lazyMyTemplate Is Nothing OrElse _lazyMyTemplate.IsMyTemplate) End If Return _lazyMyTemplate End Get Set(value As SyntaxTree) Debug.Assert(_lazyMyTemplate Is VisualBasicSyntaxTree.Dummy) Debug.Assert(value IsNot VisualBasicSyntaxTree.Dummy) Debug.Assert(value Is Nothing OrElse value.IsMyTemplate) If value?.GetDiagnostics().Any() Then Throw ExceptionUtilities.Unreachable End If _lazyMyTemplate = value End Set End Property Friend ReadOnly Property EmbeddedSymbolManager As EmbeddedSymbolManager Get If _lazyEmbeddedSymbolManager Is Nothing Then Dim embedded = If(Options.EmbedVbCoreRuntime, EmbeddedSymbolKind.VbCore, EmbeddedSymbolKind.None) Or If(IncludeInternalXmlHelper(), EmbeddedSymbolKind.XmlHelper, EmbeddedSymbolKind.None) If embedded <> EmbeddedSymbolKind.None Then embedded = embedded Or EmbeddedSymbolKind.EmbeddedAttribute End If Interlocked.CompareExchange(_lazyEmbeddedSymbolManager, New EmbeddedSymbolManager(embedded), Nothing) End If Return _lazyEmbeddedSymbolManager End Get End Property #Region "Constructors and Factories" ''' <summary> ''' Create a new compilation from scratch. ''' </summary> ''' <param name="assemblyName">Simple assembly name.</param> ''' <param name="syntaxTrees">The syntax trees with the source code for the new compilation.</param> ''' <param name="references">The references for the new compilation.</param> ''' <param name="options">The compiler options to use.</param> ''' <returns>A new compilation.</returns> Public Shared Function Create( assemblyName As String, Optional syntaxTrees As IEnumerable(Of SyntaxTree) = Nothing, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing ) As VisualBasicCompilation Return Create(assemblyName, options, If(syntaxTrees IsNot Nothing, syntaxTrees.Cast(Of SyntaxTree), Nothing), references, previousSubmission:=Nothing, returnType:=Nothing, hostObjectType:=Nothing, isSubmission:=False) End Function ''' <summary> ''' Creates a new compilation that can be used in scripting. ''' </summary> Friend Shared Function CreateScriptCompilation( assemblyName As String, Optional syntaxTree As SyntaxTree = Nothing, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional previousScriptCompilation As VisualBasicCompilation = Nothing, Optional returnType As Type = Nothing, Optional globalsType As Type = Nothing) As VisualBasicCompilation CheckSubmissionOptions(options) ValidateScriptCompilationParameters(previousScriptCompilation, returnType, globalsType) Return Create( assemblyName, If(options, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)).WithReferencesSupersedeLowerVersions(True), If((syntaxTree IsNot Nothing), {syntaxTree}, SpecializedCollections.EmptyEnumerable(Of SyntaxTree)()), references, previousScriptCompilation, returnType, globalsType, isSubmission:=True) End Function Private Shared Function Create( assemblyName As String, options As VisualBasicCompilationOptions, syntaxTrees As IEnumerable(Of SyntaxTree), references As IEnumerable(Of MetadataReference), previousSubmission As VisualBasicCompilation, returnType As Type, hostObjectType As Type, isSubmission As Boolean ) As VisualBasicCompilation Debug.Assert(Not isSubmission OrElse options.ReferencesSupersedeLowerVersions) If options Is Nothing Then options = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication) End If Dim validatedReferences = ValidateReferences(Of VisualBasicCompilationReference)(references) Dim c As VisualBasicCompilation = Nothing Dim embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c)) Dim declMap = ImmutableDictionary.Create(Of SyntaxTree, DeclarationTableEntry)() Dim declTable = AddEmbeddedTrees(DeclarationTable.Empty, embeddedTrees) c = New VisualBasicCompilation( assemblyName, options, validatedReferences, ImmutableArray(Of SyntaxTree).Empty, ImmutableDictionary.Create(Of SyntaxTree, Integer)(), declMap, embeddedTrees, declTable, previousSubmission, returnType, hostObjectType, isSubmission, referenceManager:=Nothing, reuseReferenceManager:=False, eventQueue:=Nothing, semanticModelProvider:=Nothing) If syntaxTrees IsNot Nothing Then c = c.AddSyntaxTrees(syntaxTrees) End If Debug.Assert(c._lazyAssemblySymbol Is Nothing) Return c End Function Private Sub New( assemblyName As String, options As VisualBasicCompilationOptions, references As ImmutableArray(Of MetadataReference), syntaxTrees As ImmutableArray(Of SyntaxTree), syntaxTreeOrdinalMap As ImmutableDictionary(Of SyntaxTree, Integer), rootNamespaces As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry), embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration), declarationTable As DeclarationTable, previousSubmission As VisualBasicCompilation, submissionReturnType As Type, hostObjectType As Type, isSubmission As Boolean, referenceManager As ReferenceManager, reuseReferenceManager As Boolean, semanticModelProvider As SemanticModelProvider, Optional eventQueue As AsyncQueue(Of CompilationEvent) = Nothing ) MyBase.New(assemblyName, references, SyntaxTreeCommonFeatures(syntaxTrees), isSubmission, semanticModelProvider, eventQueue) Debug.Assert(rootNamespaces IsNot Nothing) Debug.Assert(declarationTable IsNot Nothing) Debug.Assert(syntaxTrees.All(Function(tree) syntaxTrees(syntaxTreeOrdinalMap(tree)) Is tree)) Debug.Assert(syntaxTrees.SetEquals(rootNamespaces.Keys.AsImmutable(), EqualityComparer(Of SyntaxTree).Default)) Debug.Assert(embeddedTrees.All(Function(treeAndDeclaration) declarationTable.Contains(treeAndDeclaration.DeclarationEntry))) _options = options _syntaxTrees = syntaxTrees _syntaxTreeOrdinalMap = syntaxTreeOrdinalMap _rootNamespaces = rootNamespaces _embeddedTrees = embeddedTrees _declarationTable = declarationTable _anonymousTypeManager = New AnonymousTypeManager(Me) _languageVersion = CommonLanguageVersion(syntaxTrees) _scriptClass = New Lazy(Of ImplicitNamedTypeSymbol)(AddressOf BindScriptClass) If isSubmission Then Debug.Assert(previousSubmission Is Nothing OrElse previousSubmission.HostObjectType Is hostObjectType) Me.ScriptCompilationInfo = New VisualBasicScriptCompilationInfo(previousSubmission, submissionReturnType, hostObjectType) Else Debug.Assert(previousSubmission Is Nothing AndAlso submissionReturnType Is Nothing AndAlso hostObjectType Is Nothing) End If If reuseReferenceManager Then referenceManager.AssertCanReuseForCompilation(Me) _referenceManager = referenceManager Else _referenceManager = New ReferenceManager(MakeSourceAssemblySimpleName(), options.AssemblyIdentityComparer, If(referenceManager IsNot Nothing, referenceManager.ObservedMetadata, Nothing)) End If Debug.Assert(_lazyAssemblySymbol Is Nothing) If Me.EventQueue IsNot Nothing Then Me.EventQueue.TryEnqueue(New CompilationStartedEvent(Me)) End If End Sub Friend Overrides Sub ValidateDebugEntryPoint(debugEntryPoint As IMethodSymbol, diagnostics As DiagnosticBag) Debug.Assert(debugEntryPoint IsNot Nothing) ' Debug entry point has to be a method definition from this compilation. Dim methodSymbol = TryCast(debugEntryPoint, MethodSymbol) If methodSymbol?.DeclaringCompilation IsNot Me OrElse Not methodSymbol.IsDefinition Then diagnostics.Add(ERRID.ERR_DebugEntryPointNotSourceMethodDefinition, Location.None) End If End Sub Private Function CommonLanguageVersion(syntaxTrees As ImmutableArray(Of SyntaxTree)) As LanguageVersion ' We don't check m_Options.ParseOptions.LanguageVersion for consistency, because ' it isn't consistent in practice. In fact sometimes m_Options.ParseOptions is Nothing. Dim result As LanguageVersion? = Nothing For Each tree In syntaxTrees Dim version = CType(tree.Options, VisualBasicParseOptions).LanguageVersion If result Is Nothing Then result = version ElseIf result <> version Then Throw New ArgumentException(CodeAnalysisResources.InconsistentLanguageVersions, NameOf(syntaxTrees)) End If Next Return If(result, LanguageVersion.Default.MapSpecifiedToEffectiveVersion) End Function ''' <summary> ''' Create a duplicate of this compilation with different symbol instances ''' </summary> Public Shadows Function Clone() As VisualBasicCompilation Return New VisualBasicCompilation( Me.AssemblyName, _options, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, _embeddedTrees, _declarationTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=True, Me.SemanticModelProvider, eventQueue:=Nothing) ' no event queue when cloning End Function Private Function UpdateSyntaxTrees( syntaxTrees As ImmutableArray(Of SyntaxTree), syntaxTreeOrdinalMap As ImmutableDictionary(Of SyntaxTree, Integer), rootNamespaces As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry), declarationTable As DeclarationTable, referenceDirectivesChanged As Boolean) As VisualBasicCompilation Return New VisualBasicCompilation( Me.AssemblyName, _options, Me.ExternalReferences, syntaxTrees, syntaxTreeOrdinalMap, rootNamespaces, _embeddedTrees, declarationTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=Not referenceDirectivesChanged, Me.SemanticModelProvider) End Function ''' <summary> ''' Creates a new compilation with the specified name. ''' </summary> Public Shadows Function WithAssemblyName(assemblyName As String) As VisualBasicCompilation ' Can't reuse references since the source assembly name changed and the referenced symbols might ' have internals-visible-to relationship with this compilation or they might had a circular reference ' to this compilation. Return New VisualBasicCompilation( assemblyName, Me.Options, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, _embeddedTrees, _declarationTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=String.Equals(assemblyName, Me.AssemblyName, StringComparison.Ordinal), Me.SemanticModelProvider) End Function Public Shadows Function WithReferences(ParamArray newReferences As MetadataReference()) As VisualBasicCompilation Return WithReferences(DirectCast(newReferences, IEnumerable(Of MetadataReference))) End Function ''' <summary> ''' Creates a new compilation with the specified references. ''' </summary> ''' <remarks> ''' The new <see cref="VisualBasicCompilation"/> will query the given <see cref="MetadataReference"/> for the underlying ''' metadata as soon as the are needed. ''' ''' The New compilation uses whatever metadata is currently being provided by the <see cref="MetadataReference"/>. ''' E.g. if the current compilation references a metadata file that has changed since the creation of the compilation ''' the New compilation is going to use the updated version, while the current compilation will be using the previous (it doesn't change). ''' </remarks> Public Shadows Function WithReferences(newReferences As IEnumerable(Of MetadataReference)) As VisualBasicCompilation Dim declTable = RemoveEmbeddedTrees(_declarationTable, _embeddedTrees) Dim c As VisualBasicCompilation = Nothing Dim embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c)) declTable = AddEmbeddedTrees(declTable, embeddedTrees) ' References might have changed, don't reuse reference manager. ' Don't even reuse observed metadata - let the manager query for the metadata again. c = New VisualBasicCompilation( Me.AssemblyName, Me.Options, ValidateReferences(Of VisualBasicCompilationReference)(newReferences), _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, embeddedTrees, declTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, referenceManager:=Nothing, reuseReferenceManager:=False, Me.SemanticModelProvider) Return c End Function Public Shadows Function WithOptions(newOptions As VisualBasicCompilationOptions) As VisualBasicCompilation If newOptions Is Nothing Then Throw New ArgumentNullException(NameOf(newOptions)) End If Dim c As VisualBasicCompilation = Nothing Dim embeddedTrees = _embeddedTrees Dim declTable = _declarationTable Dim declMap = Me._rootNamespaces If Not String.Equals(Me.Options.RootNamespace, newOptions.RootNamespace, StringComparison.Ordinal) Then ' If the root namespace was updated we have to update declaration table ' entries for all the syntax trees of the compilation ' ' NOTE: we use case-sensitive comparison so that the new compilation ' gets a root namespace with correct casing declMap = ImmutableDictionary.Create(Of SyntaxTree, DeclarationTableEntry)() declTable = DeclarationTable.Empty embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c)) declTable = AddEmbeddedTrees(declTable, embeddedTrees) Dim discardedReferenceDirectivesChanged As Boolean = False For Each tree In _syntaxTrees AddSyntaxTreeToDeclarationMapAndTable(tree, newOptions, Me.IsSubmission, declMap, declTable, discardedReferenceDirectivesChanged) ' declMap and declTable passed ByRef Next ElseIf Me.Options.EmbedVbCoreRuntime <> newOptions.EmbedVbCoreRuntime OrElse Me.Options.ParseOptions <> newOptions.ParseOptions Then declTable = RemoveEmbeddedTrees(declTable, _embeddedTrees) embeddedTrees = CreateEmbeddedTrees(New Lazy(Of VisualBasicCompilation)(Function() c)) declTable = AddEmbeddedTrees(declTable, embeddedTrees) End If c = New VisualBasicCompilation( Me.AssemblyName, newOptions, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, declMap, embeddedTrees, declTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=_options.CanReuseCompilationReferenceManager(newOptions), Me.SemanticModelProvider) Return c End Function ''' <summary> ''' Returns a new compilation with the given compilation set as the previous submission. ''' </summary> Friend Shadows Function WithScriptCompilationInfo(info As VisualBasicScriptCompilationInfo) As VisualBasicCompilation If info Is ScriptCompilationInfo Then Return Me End If ' Metadata references are inherited from the previous submission, ' so we can only reuse the manager if we can guarantee that these references are the same. ' Check if the previous script compilation doesn't change. ' TODO Consider comparing the metadata references if they have been bound already. ' https://github.com/dotnet/roslyn/issues/43397 Dim reuseReferenceManager = ScriptCompilationInfo?.PreviousScriptCompilation Is info?.PreviousScriptCompilation Return New VisualBasicCompilation( Me.AssemblyName, Me.Options, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, _embeddedTrees, _declarationTable, info?.PreviousScriptCompilation, info?.ReturnTypeOpt, info?.GlobalsType, info IsNot Nothing, _referenceManager, reuseReferenceManager, Me.SemanticModelProvider) End Function ''' <summary> ''' Returns a new compilation with the given semantic model provider. ''' </summary> Friend Overrides Function WithSemanticModelProvider(semanticModelProvider As SemanticModelProvider) As Compilation If Me.SemanticModelProvider Is semanticModelProvider Then Return Me End If Return New VisualBasicCompilation( Me.AssemblyName, Me.Options, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, _embeddedTrees, _declarationTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=True, semanticModelProvider) End Function ''' <summary> ''' Returns a new compilation with a given event queue. ''' </summary> Friend Overrides Function WithEventQueue(eventQueue As AsyncQueue(Of CompilationEvent)) As Compilation Return New VisualBasicCompilation( Me.AssemblyName, Me.Options, Me.ExternalReferences, _syntaxTrees, _syntaxTreeOrdinalMap, _rootNamespaces, _embeddedTrees, _declarationTable, Me.PreviousSubmission, Me.SubmissionReturnType, Me.HostObjectType, Me.IsSubmission, _referenceManager, reuseReferenceManager:=True, Me.SemanticModelProvider, eventQueue:=eventQueue) End Function Friend Overrides Sub SerializePdbEmbeddedCompilationOptions(builder As BlobBuilder) ' LanguageVersion should already be mapped to an effective version at this point Debug.Assert(LanguageVersion.MapSpecifiedToEffectiveVersion() = LanguageVersion) WriteValue(builder, CompilationOptionNames.LanguageVersion, LanguageVersion.ToDisplayString()) WriteValue(builder, CompilationOptionNames.Checked, Options.CheckOverflow.ToString()) WriteValue(builder, CompilationOptionNames.OptionStrict, Options.OptionStrict.ToString()) WriteValue(builder, CompilationOptionNames.OptionInfer, Options.OptionInfer.ToString()) WriteValue(builder, CompilationOptionNames.OptionCompareText, Options.OptionCompareText.ToString()) WriteValue(builder, CompilationOptionNames.OptionExplicit, Options.OptionExplicit.ToString()) WriteValue(builder, CompilationOptionNames.EmbedRuntime, Options.EmbedVbCoreRuntime.ToString()) If Options.GlobalImports.Length > 0 Then WriteValue(builder, CompilationOptionNames.GlobalNamespaces, String.Join(";", Options.GlobalImports.Select(Function(x) x.Name))) End If If Not String.IsNullOrEmpty(Options.RootNamespace) Then WriteValue(builder, CompilationOptionNames.RootNamespace, Options.RootNamespace) End If If Options.ParseOptions IsNot Nothing Then Dim preprocessorStrings = Options.ParseOptions.PreprocessorSymbols.Select( Function(p) As String If TypeOf p.Value Is String Then Return p.Key + "=""" + p.Value.ToString() + """" ElseIf p.Value Is Nothing Then Return p.Key Else Return p.Key + "=" + p.Value.ToString() End If End Function) WriteValue(builder, CompilationOptionNames.Define, String.Join(",", preprocessorStrings)) End If End Sub Private Sub WriteValue(builder As BlobBuilder, key As String, value As String) builder.WriteUTF8(key) builder.WriteByte(0) builder.WriteUTF8(value) builder.WriteByte(0) End Sub #End Region #Region "Submission" Friend Shadows ReadOnly Property ScriptCompilationInfo As VisualBasicScriptCompilationInfo Friend Overrides ReadOnly Property CommonScriptCompilationInfo As ScriptCompilationInfo Get Return ScriptCompilationInfo End Get End Property Friend Shadows ReadOnly Property PreviousSubmission As VisualBasicCompilation Get Return ScriptCompilationInfo?.PreviousScriptCompilation End Get End Property Friend Overrides Function HasSubmissionResult() As Boolean Debug.Assert(IsSubmission) ' submission can be empty or comprise of a script file Dim tree = SyntaxTrees.SingleOrDefault() If tree Is Nothing Then Return False End If Dim root = tree.GetCompilationUnitRoot() If root.HasErrors Then Return False End If ' TODO: look for return statements ' https://github.com/dotnet/roslyn/issues/5773 Dim lastStatement = root.Members.LastOrDefault() If lastStatement Is Nothing Then Return False End If Dim model = GetSemanticModel(tree) Select Case lastStatement.Kind Case SyntaxKind.PrintStatement Dim expression = DirectCast(lastStatement, PrintStatementSyntax).Expression Dim info = model.GetTypeInfo(expression) ' always true, even for info.Type = Void Return True Case SyntaxKind.ExpressionStatement Dim expression = DirectCast(lastStatement, ExpressionStatementSyntax).Expression Dim info = model.GetTypeInfo(expression) Return info.Type.SpecialType <> SpecialType.System_Void Case SyntaxKind.CallStatement Dim expression = DirectCast(lastStatement, CallStatementSyntax).Invocation Dim info = model.GetTypeInfo(expression) Return info.Type.SpecialType <> SpecialType.System_Void Case Else Return False End Select End Function Friend Function GetSubmissionInitializer() As SynthesizedInteractiveInitializerMethod Return If(IsSubmission AndAlso ScriptClass IsNot Nothing, ScriptClass.GetScriptInitializer(), Nothing) End Function Protected Overrides ReadOnly Property CommonScriptGlobalsType As ITypeSymbol Get Return Nothing End Get End Property #End Region #Region "Syntax Trees" ''' <summary> ''' Get a read-only list of the syntax trees that this compilation was created with. ''' </summary> Public Shadows ReadOnly Property SyntaxTrees As ImmutableArray(Of SyntaxTree) Get Return _syntaxTrees End Get End Property ''' <summary> ''' Get a read-only list of the syntax trees that this compilation was created with PLUS ''' the trees that were automatically added to it, i.e. Vb Core Runtime tree. ''' </summary> Friend Shadows ReadOnly Property AllSyntaxTrees As ImmutableArray(Of SyntaxTree) Get If _lazyAllSyntaxTrees.IsDefault Then Dim builder = ArrayBuilder(Of SyntaxTree).GetInstance() builder.AddRange(_syntaxTrees) For Each embeddedTree In _embeddedTrees Dim tree = embeddedTree.Tree.Value If tree IsNot Nothing Then builder.Add(tree) End If Next ImmutableInterlocked.InterlockedInitialize(_lazyAllSyntaxTrees, builder.ToImmutableAndFree()) End If Return _lazyAllSyntaxTrees End Get End Property ''' <summary> ''' Is the passed in syntax tree in this compilation? ''' </summary> Public Shadows Function ContainsSyntaxTree(syntaxTree As SyntaxTree) As Boolean Return syntaxTree IsNot Nothing AndAlso _rootNamespaces.ContainsKey(syntaxTree) End Function Public Shadows Function AddSyntaxTrees(ParamArray trees As SyntaxTree()) As VisualBasicCompilation Return AddSyntaxTrees(DirectCast(trees, IEnumerable(Of SyntaxTree))) End Function Public Shadows Function AddSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As VisualBasicCompilation If trees Is Nothing Then Throw New ArgumentNullException(NameOf(trees)) End If If Not trees.Any() Then Return Me End If ' We're using a try-finally for this builder because there's a test that ' specifically checks for one or more of the argument exceptions below ' and we don't want to see console spew (even though we don't generally ' care about pool "leaks" in exceptional cases). Alternatively, we ' could create a new ArrayBuilder. Dim builder = ArrayBuilder(Of SyntaxTree).GetInstance() Try builder.AddRange(_syntaxTrees) Dim referenceDirectivesChanged = False Dim oldTreeCount = _syntaxTrees.Length Dim ordinalMap = _syntaxTreeOrdinalMap Dim declMap = _rootNamespaces Dim declTable = _declarationTable Dim i = 0 For Each tree As SyntaxTree In trees If tree Is Nothing Then Throw New ArgumentNullException(String.Format(VBResources.Trees0, i)) End If If Not tree.HasCompilationUnitRoot Then Throw New ArgumentException(String.Format(VBResources.TreesMustHaveRootNode, i)) End If If tree.IsEmbeddedOrMyTemplateTree() Then Throw New ArgumentException(VBResources.CannotAddCompilerSpecialTree) End If If declMap.ContainsKey(tree) Then Throw New ArgumentException(VBResources.SyntaxTreeAlreadyPresent, String.Format(VBResources.Trees0, i)) End If AddSyntaxTreeToDeclarationMapAndTable(tree, _options, Me.IsSubmission, declMap, declTable, referenceDirectivesChanged) ' declMap and declTable passed ByRef builder.Add(tree) ordinalMap = ordinalMap.Add(tree, oldTreeCount + i) i += 1 Next If IsSubmission AndAlso declMap.Count > 1 Then Throw New ArgumentException(VBResources.SubmissionCanHaveAtMostOneSyntaxTree, NameOf(trees)) End If Return UpdateSyntaxTrees(builder.ToImmutable(), ordinalMap, declMap, declTable, referenceDirectivesChanged) Finally builder.Free() End Try End Function Private Shared Sub AddSyntaxTreeToDeclarationMapAndTable( tree As SyntaxTree, compilationOptions As VisualBasicCompilationOptions, isSubmission As Boolean, ByRef declMap As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry), ByRef declTable As DeclarationTable, ByRef referenceDirectivesChanged As Boolean ) Dim entry = New DeclarationTableEntry(New Lazy(Of RootSingleNamespaceDeclaration)(Function() ForTree(tree, compilationOptions, isSubmission)), isEmbedded:=False) declMap = declMap.Add(tree, entry) ' Callers are responsible for checking for existing entries. declTable = declTable.AddRootDeclaration(entry) referenceDirectivesChanged = referenceDirectivesChanged OrElse tree.HasReferenceDirectives End Sub Private Shared Function ForTree(tree As SyntaxTree, options As VisualBasicCompilationOptions, isSubmission As Boolean) As RootSingleNamespaceDeclaration Return DeclarationTreeBuilder.ForTree(tree, options.GetRootNamespaceParts(), If(options.ScriptClassName, ""), isSubmission) End Function Public Shadows Function RemoveSyntaxTrees(ParamArray trees As SyntaxTree()) As VisualBasicCompilation Return RemoveSyntaxTrees(DirectCast(trees, IEnumerable(Of SyntaxTree))) End Function Public Shadows Function RemoveSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As VisualBasicCompilation If trees Is Nothing Then Throw New ArgumentNullException(NameOf(trees)) End If If Not trees.Any() Then Return Me End If Dim referenceDirectivesChanged = False Dim removeSet As New HashSet(Of SyntaxTree)() Dim declMap = _rootNamespaces Dim declTable = _declarationTable For Each tree As SyntaxTree In trees If tree.IsEmbeddedOrMyTemplateTree() Then Throw New ArgumentException(VBResources.CannotRemoveCompilerSpecialTree) End If RemoveSyntaxTreeFromDeclarationMapAndTable(tree, declMap, declTable, referenceDirectivesChanged) removeSet.Add(tree) Next Debug.Assert(removeSet.Count > 0) ' We're going to have to revise the ordinals of all ' trees after the first one removed, so just build ' a new map. ' CONSIDER: an alternative approach would be to set the map to empty and ' re-calculate it the next time we need it. This might save us time in the ' case where remove calls are made sequentially (rare?). Dim ordinalMap = ImmutableDictionary.Create(Of SyntaxTree, Integer)() Dim builder = ArrayBuilder(Of SyntaxTree).GetInstance() Dim i = 0 For Each tree In _syntaxTrees If Not removeSet.Contains(tree) Then builder.Add(tree) ordinalMap = ordinalMap.Add(tree, i) i += 1 End If Next Return UpdateSyntaxTrees(builder.ToImmutableAndFree(), ordinalMap, declMap, declTable, referenceDirectivesChanged) End Function Private Shared Sub RemoveSyntaxTreeFromDeclarationMapAndTable( tree As SyntaxTree, ByRef declMap As ImmutableDictionary(Of SyntaxTree, DeclarationTableEntry), ByRef declTable As DeclarationTable, ByRef referenceDirectivesChanged As Boolean ) Dim root As DeclarationTableEntry = Nothing If Not declMap.TryGetValue(tree, root) Then Throw New ArgumentException(String.Format(VBResources.SyntaxTreeNotFoundToRemove, tree)) End If declTable = declTable.RemoveRootDeclaration(root) declMap = declMap.Remove(tree) referenceDirectivesChanged = referenceDirectivesChanged OrElse tree.HasReferenceDirectives End Sub Public Shadows Function RemoveAllSyntaxTrees() As VisualBasicCompilation Return UpdateSyntaxTrees(ImmutableArray(Of SyntaxTree).Empty, ImmutableDictionary.Create(Of SyntaxTree, Integer)(), ImmutableDictionary.Create(Of SyntaxTree, DeclarationTableEntry)(), AddEmbeddedTrees(DeclarationTable.Empty, _embeddedTrees), referenceDirectivesChanged:=_declarationTable.ReferenceDirectives.Any()) End Function Public Shadows Function ReplaceSyntaxTree(oldTree As SyntaxTree, newTree As SyntaxTree) As VisualBasicCompilation If oldTree Is Nothing Then Throw New ArgumentNullException(NameOf(oldTree)) End If If newTree Is Nothing Then Return Me.RemoveSyntaxTrees(oldTree) ElseIf newTree Is oldTree Then Return Me End If If Not newTree.HasCompilationUnitRoot Then Throw New ArgumentException(VBResources.TreeMustHaveARootNodeWithCompilationUnit, NameOf(newTree)) End If Dim vbOldTree = oldTree Dim vbNewTree = newTree If vbOldTree.IsEmbeddedOrMyTemplateTree() Then Throw New ArgumentException(VBResources.CannotRemoveCompilerSpecialTree) End If If vbNewTree.IsEmbeddedOrMyTemplateTree() Then Throw New ArgumentException(VBResources.CannotAddCompilerSpecialTree) End If Dim declMap = _rootNamespaces If declMap.ContainsKey(vbNewTree) Then Throw New ArgumentException(VBResources.SyntaxTreeAlreadyPresent, NameOf(newTree)) End If Dim declTable = _declarationTable Dim referenceDirectivesChanged = False ' TODO(tomat): Consider comparing #r's of the old and the new tree. If they are exactly the same we could still reuse. ' This could be a perf win when editing a script file in the IDE. The services create a new compilation every keystroke ' that replaces the tree with a new one. RemoveSyntaxTreeFromDeclarationMapAndTable(vbOldTree, declMap, declTable, referenceDirectivesChanged) AddSyntaxTreeToDeclarationMapAndTable(vbNewTree, _options, Me.IsSubmission, declMap, declTable, referenceDirectivesChanged) Dim ordinalMap = _syntaxTreeOrdinalMap Debug.Assert(ordinalMap.ContainsKey(oldTree)) ' Checked by RemoveSyntaxTreeFromDeclarationMapAndTable Dim oldOrdinal = ordinalMap(oldTree) Dim newArray = _syntaxTrees.ToArray() newArray(oldOrdinal) = vbNewTree ' CONSIDER: should this be an operation on ImmutableDictionary? ordinalMap = ordinalMap.Remove(oldTree) ordinalMap = ordinalMap.Add(newTree, oldOrdinal) Return UpdateSyntaxTrees(newArray.AsImmutableOrNull(), ordinalMap, declMap, declTable, referenceDirectivesChanged) End Function Private Shared Function CreateEmbeddedTrees(compReference As Lazy(Of VisualBasicCompilation)) As ImmutableArray(Of EmbeddedTreeAndDeclaration) Return ImmutableArray.Create( New EmbeddedTreeAndDeclaration( Function() Dim compilation = compReference.Value Return If(compilation.Options.EmbedVbCoreRuntime Or compilation.IncludeInternalXmlHelper, EmbeddedSymbolManager.EmbeddedSyntax, Nothing) End Function, Function() Dim compilation = compReference.Value Return If(compilation.Options.EmbedVbCoreRuntime Or compilation.IncludeInternalXmlHelper, ForTree(EmbeddedSymbolManager.EmbeddedSyntax, compilation.Options, isSubmission:=False), Nothing) End Function), New EmbeddedTreeAndDeclaration( Function() Dim compilation = compReference.Value Return If(compilation.Options.EmbedVbCoreRuntime, EmbeddedSymbolManager.VbCoreSyntaxTree, Nothing) End Function, Function() Dim compilation = compReference.Value Return If(compilation.Options.EmbedVbCoreRuntime, ForTree(EmbeddedSymbolManager.VbCoreSyntaxTree, compilation.Options, isSubmission:=False), Nothing) End Function), New EmbeddedTreeAndDeclaration( Function() Dim compilation = compReference.Value Return If(compilation.IncludeInternalXmlHelper(), EmbeddedSymbolManager.InternalXmlHelperSyntax, Nothing) End Function, Function() Dim compilation = compReference.Value Return If(compilation.IncludeInternalXmlHelper(), ForTree(EmbeddedSymbolManager.InternalXmlHelperSyntax, compilation.Options, isSubmission:=False), Nothing) End Function), New EmbeddedTreeAndDeclaration( Function() Dim compilation = compReference.Value Return compilation.MyTemplate End Function, Function() Dim compilation = compReference.Value Return If(compilation.MyTemplate IsNot Nothing, ForTree(compilation.MyTemplate, compilation.Options, isSubmission:=False), Nothing) End Function)) End Function Private Shared Function AddEmbeddedTrees( declTable As DeclarationTable, embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration) ) As DeclarationTable For Each embeddedTree In embeddedTrees declTable = declTable.AddRootDeclaration(embeddedTree.DeclarationEntry) Next Return declTable End Function Private Shared Function RemoveEmbeddedTrees( declTable As DeclarationTable, embeddedTrees As ImmutableArray(Of EmbeddedTreeAndDeclaration) ) As DeclarationTable For Each embeddedTree In embeddedTrees declTable = declTable.RemoveRootDeclaration(embeddedTree.DeclarationEntry) Next Return declTable End Function ''' <summary> ''' Returns True if the set of references contains those assemblies needed for XML ''' literals. ''' If those assemblies are included, we should include the InternalXmlHelper ''' SyntaxTree in the Compilation so the helper methods are available for binding XML. ''' </summary> Private Function IncludeInternalXmlHelper() As Boolean ' In new flavors of the framework, types, that XML helpers depend upon, are ' defined in assemblies with different names. Let's not hardcode these names, ' let's check for presence of types instead. Return Not Me.Options.SuppressEmbeddedDeclarations AndAlso InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Linq_Enumerable) AndAlso InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Xml_Linq_XElement) AndAlso InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Xml_Linq_XName) AndAlso InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Xml_Linq_XAttribute) AndAlso InternalXmlHelperDependencyIsSatisfied(WellKnownType.System_Xml_Linq_XNamespace) End Function Private Function InternalXmlHelperDependencyIsSatisfied(type As WellKnownType) As Boolean Dim metadataName = MetadataTypeName.FromFullName(WellKnownTypes.GetMetadataName(type), useCLSCompliantNameArityEncoding:=True) Dim sourceAssembly = Me.SourceAssembly ' Lookup only in references. An attempt to lookup in assembly being built will get us in a cycle. ' We are explicitly ignoring scenario where the type might be defined in an added module. For Each reference As AssemblySymbol In sourceAssembly.SourceModule.GetReferencedAssemblySymbols() Debug.Assert(Not reference.IsMissing) Dim candidate As NamedTypeSymbol = reference.LookupTopLevelMetadataType(metadataName, digThroughForwardedTypes:=False) If sourceAssembly.IsValidWellKnownType(candidate) AndAlso AssemblySymbol.IsAcceptableMatchForGetTypeByNameAndArity(candidate) Then Return True End If Next Return False End Function ' TODO: This comparison probably will change to compiler command line order, or at least needs ' TODO: to be resolved. See bug 8520. ''' <summary> ''' Compare two source locations, using their containing trees, and then by Span.First within a tree. ''' Can be used to get a total ordering on declarations, for example. ''' </summary> Friend Overrides Function CompareSourceLocations(first As Location, second As Location) As Integer Return LexicalSortKey.Compare(first, second, Me) End Function ''' <summary> ''' Compare two source locations, using their containing trees, and then by Span.First within a tree. ''' Can be used to get a total ordering on declarations, for example. ''' </summary> Friend Overrides Function CompareSourceLocations(first As SyntaxReference, second As SyntaxReference) As Integer Return LexicalSortKey.Compare(first, second, Me) End Function ''' <summary> ''' Compare two source locations, using their containing trees, and then by Span.First within a tree. ''' Can be used to get a total ordering on declarations, for example. ''' </summary> Friend Overrides Function CompareSourceLocations(first As SyntaxNode, second As SyntaxNode) As Integer Return LexicalSortKey.Compare(first, second, Me) End Function Friend Overrides Function GetSyntaxTreeOrdinal(tree As SyntaxTree) As Integer Debug.Assert(Me.ContainsSyntaxTree(tree)) Return _syntaxTreeOrdinalMap(tree) End Function #End Region #Region "References" Friend Overrides Function CommonGetBoundReferenceManager() As CommonReferenceManager Return GetBoundReferenceManager() End Function Friend Shadows Function GetBoundReferenceManager() As ReferenceManager If _lazyAssemblySymbol Is Nothing Then _referenceManager.CreateSourceAssemblyForCompilation(Me) Debug.Assert(_lazyAssemblySymbol IsNot Nothing) End If ' referenceManager can only be accessed after we initialized the lazyAssemblySymbol. ' In fact, initialization of the assembly symbol might change the reference manager. Return _referenceManager End Function ' for testing only: Friend Function ReferenceManagerEquals(other As VisualBasicCompilation) As Boolean Return _referenceManager Is other._referenceManager End Function Public Overrides ReadOnly Property DirectiveReferences As ImmutableArray(Of MetadataReference) Get Return GetBoundReferenceManager().DirectiveReferences End Get End Property Friend Overrides ReadOnly Property ReferenceDirectiveMap As IDictionary(Of (path As String, content As String), MetadataReference) Get Return GetBoundReferenceManager().ReferenceDirectiveMap End Get End Property ''' <summary> ''' Gets the <see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> for a metadata reference used to create this compilation. ''' </summary> ''' <returns><see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> corresponding to the given reference or Nothing if there is none.</returns> ''' <remarks> ''' Uses object identity when comparing two references. ''' </remarks> Friend Shadows Function GetAssemblyOrModuleSymbol(reference As MetadataReference) As Symbol If (reference Is Nothing) Then Throw New ArgumentNullException(NameOf(reference)) End If If reference.Properties.Kind = MetadataImageKind.Assembly Then Return GetBoundReferenceManager().GetReferencedAssemblySymbol(reference) Else Debug.Assert(reference.Properties.Kind = MetadataImageKind.Module) Dim index As Integer = GetBoundReferenceManager().GetReferencedModuleIndex(reference) Return If(index < 0, Nothing, Me.Assembly.Modules(index)) End If End Function ''' <summary> ''' Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol. ''' </summary> Friend Shadows Function GetMetadataReference(assemblySymbol As AssemblySymbol) As MetadataReference Return Me.GetBoundReferenceManager().GetMetadataReference(assemblySymbol) End Function Private Protected Overrides Function CommonGetMetadataReference(assemblySymbol As IAssemblySymbol) As MetadataReference Dim symbol = TryCast(assemblySymbol, AssemblySymbol) If symbol IsNot Nothing Then Return GetMetadataReference(symbol) End If Return Nothing End Function Public Overrides ReadOnly Property ReferencedAssemblyNames As IEnumerable(Of AssemblyIdentity) Get Return [Assembly].Modules.SelectMany(Function(m) m.GetReferencedAssemblies()) End Get End Property Friend Overrides ReadOnly Property ReferenceDirectives As IEnumerable(Of ReferenceDirective) Get Return _declarationTable.ReferenceDirectives End Get End Property Public Overrides Function ToMetadataReference(Optional aliases As ImmutableArray(Of String) = Nothing, Optional embedInteropTypes As Boolean = False) As CompilationReference Return New VisualBasicCompilationReference(Me, aliases, embedInteropTypes) End Function Public Shadows Function AddReferences(ParamArray references As MetadataReference()) As VisualBasicCompilation Return DirectCast(MyBase.AddReferences(references), VisualBasicCompilation) End Function Public Shadows Function AddReferences(references As IEnumerable(Of MetadataReference)) As VisualBasicCompilation Return DirectCast(MyBase.AddReferences(references), VisualBasicCompilation) End Function Public Shadows Function RemoveReferences(ParamArray references As MetadataReference()) As VisualBasicCompilation Return DirectCast(MyBase.RemoveReferences(references), VisualBasicCompilation) End Function Public Shadows Function RemoveReferences(references As IEnumerable(Of MetadataReference)) As VisualBasicCompilation Return DirectCast(MyBase.RemoveReferences(references), VisualBasicCompilation) End Function Public Shadows Function RemoveAllReferences() As VisualBasicCompilation Return DirectCast(MyBase.RemoveAllReferences(), VisualBasicCompilation) End Function Public Shadows Function ReplaceReference(oldReference As MetadataReference, newReference As MetadataReference) As VisualBasicCompilation Return DirectCast(MyBase.ReplaceReference(oldReference, newReference), VisualBasicCompilation) End Function ''' <summary> ''' Determine if enum arrays can be initialized using block initialization. ''' </summary> ''' <returns>True if it's safe to use block initialization for enum arrays.</returns> ''' <remarks> ''' In NetFx 4.0, block array initializers do not work on all combinations of {32/64 X Debug/Retail} when array elements are enums. ''' This is fixed in 4.5 thus enabling block array initialization for a very common case. ''' We look for the presence of <see cref="System.Runtime.GCLatencyMode.SustainedLowLatency"/> which was introduced in .NET Framework 4.5 ''' </remarks> Friend ReadOnly Property EnableEnumArrayBlockInitialization As Boolean Get Dim sustainedLowLatency = GetWellKnownTypeMember(WellKnownMember.System_Runtime_GCLatencyMode__SustainedLowLatency) Return sustainedLowLatency IsNot Nothing AndAlso sustainedLowLatency.ContainingAssembly = Assembly.CorLibrary End Get End Property #End Region #Region "Symbols" Friend ReadOnly Property SourceAssembly As SourceAssemblySymbol Get GetBoundReferenceManager() Return _lazyAssemblySymbol End Get End Property ''' <summary> ''' Gets the AssemblySymbol that represents the assembly being created. ''' </summary> Friend Shadows ReadOnly Property Assembly As AssemblySymbol Get Return Me.SourceAssembly End Get End Property ''' <summary> ''' Get a ModuleSymbol that refers to the module being created by compiling all of the code. By ''' getting the GlobalNamespace property of that module, all of the namespace and types defined in source code ''' can be obtained. ''' </summary> Friend Shadows ReadOnly Property SourceModule As ModuleSymbol Get Return Me.Assembly.Modules(0) End Get End Property ''' <summary> ''' Gets the merged root namespace that contains all namespaces and types defined in source code or in ''' referenced metadata, merged into a single namespace hierarchy. This namespace hierarchy is how the compiler ''' binds types that are referenced in code. ''' </summary> Friend Shadows ReadOnly Property GlobalNamespace As NamespaceSymbol Get If _lazyGlobalNamespace Is Nothing Then Interlocked.CompareExchange(_lazyGlobalNamespace, MergedNamespaceSymbol.CreateGlobalNamespace(Me), Nothing) End If Return _lazyGlobalNamespace End Get End Property ''' <summary> ''' Get the "root" or default namespace that all source types are declared inside. This may be the ''' global namespace or may be another namespace. ''' </summary> Friend ReadOnly Property RootNamespace As NamespaceSymbol Get Return DirectCast(Me.SourceModule, SourceModuleSymbol).RootNamespace End Get End Property ''' <summary> ''' Given a namespace symbol, returns the corresponding namespace symbol with Compilation extent ''' that refers to that namespace in this compilation. Returns Nothing if there is no corresponding ''' namespace. This should not occur if the namespace symbol came from an assembly referenced by this ''' compilation. ''' </summary> Friend Shadows Function GetCompilationNamespace(namespaceSymbol As INamespaceSymbol) As NamespaceSymbol If namespaceSymbol Is Nothing Then Throw New ArgumentNullException(NameOf(namespaceSymbol)) End If Dim vbNs = TryCast(namespaceSymbol, NamespaceSymbol) If vbNs IsNot Nothing AndAlso vbNs.Extent.Kind = NamespaceKind.Compilation AndAlso vbNs.Extent.Compilation Is Me Then ' If we already have a namespace with the right extent, use that. Return vbNs ElseIf namespaceSymbol.ContainingNamespace Is Nothing Then ' If is the root namespace, return the merged root namespace Debug.Assert(namespaceSymbol.Name = "", "Namespace with Nothing container should be root namespace with empty name") Return GlobalNamespace Else Dim containingNs = GetCompilationNamespace(namespaceSymbol.ContainingNamespace) If containingNs Is Nothing Then Return Nothing End If ' Get the child namespace of the given name, if any. Return containingNs.GetMembers(namespaceSymbol.Name).OfType(Of NamespaceSymbol)().FirstOrDefault() End If End Function Friend Shadows Function GetEntryPoint(cancellationToken As CancellationToken) As MethodSymbol Dim entryPoint As EntryPoint = GetEntryPointAndDiagnostics(cancellationToken) Return If(entryPoint Is Nothing, Nothing, entryPoint.MethodSymbol) End Function Friend Function GetEntryPointAndDiagnostics(cancellationToken As CancellationToken) As EntryPoint If Not Me.Options.OutputKind.IsApplication() AndAlso ScriptClass Is Nothing Then Return Nothing End If If Me.Options.MainTypeName IsNot Nothing AndAlso Not Me.Options.MainTypeName.IsValidClrTypeName() Then Debug.Assert(Not Me.Options.Errors.IsDefaultOrEmpty) Return New EntryPoint(Nothing, ImmutableArray(Of Diagnostic).Empty) End If If _lazyEntryPoint Is Nothing Then Dim diagnostics As ImmutableArray(Of Diagnostic) = Nothing Dim entryPoint = FindEntryPoint(cancellationToken, diagnostics) Interlocked.CompareExchange(_lazyEntryPoint, New EntryPoint(entryPoint, diagnostics), Nothing) End If Return _lazyEntryPoint End Function Private Function FindEntryPoint(cancellationToken As CancellationToken, ByRef sealedDiagnostics As ImmutableArray(Of Diagnostic)) As MethodSymbol Dim diagnostics = DiagnosticBag.GetInstance() Dim entryPointCandidates = ArrayBuilder(Of MethodSymbol).GetInstance() Try Dim mainType As SourceMemberContainerTypeSymbol Dim mainTypeName As String = Me.Options.MainTypeName Dim globalNamespace As NamespaceSymbol = Me.SourceModule.GlobalNamespace Dim errorTarget As Object If mainTypeName IsNot Nothing Then ' Global code is the entry point, ignore all other Mains. If ScriptClass IsNot Nothing Then ' CONSIDER: we could use the symbol instead of just the name. diagnostics.Add(ERRID.WRN_MainIgnored, NoLocation.Singleton, mainTypeName) Return ScriptClass.GetScriptEntryPoint() End If Dim mainTypeOrNamespace = globalNamespace.GetNamespaceOrTypeByQualifiedName(mainTypeName.Split("."c)).OfType(Of NamedTypeSymbol)().OfMinimalArity() If mainTypeOrNamespace Is Nothing Then diagnostics.Add(ERRID.ERR_StartupCodeNotFound1, NoLocation.Singleton, mainTypeName) Return Nothing End If mainType = TryCast(mainTypeOrNamespace, SourceMemberContainerTypeSymbol) If mainType Is Nothing OrElse (mainType.TypeKind <> TYPEKIND.Class AndAlso mainType.TypeKind <> TYPEKIND.Structure AndAlso mainType.TypeKind <> TYPEKIND.Module) Then diagnostics.Add(ERRID.ERR_StartupCodeNotFound1, NoLocation.Singleton, mainType) Return Nothing End If ' Dev10 reports ERR_StartupCodeNotFound1 but that doesn't make much sense If mainType.IsGenericType Then diagnostics.Add(ERRID.ERR_GenericSubMainsFound1, NoLocation.Singleton, mainType) Return Nothing End If errorTarget = mainType ' NOTE: unlike in C#, we're not going search the member list of mainType directly. ' Instead, we're going to mimic dev10's behavior by doing a lookup for "Main", ' starting in mainType. Among other things, this implies that the entrypoint ' could be in a base class and that it could be hidden by a non-method member ' named "Main". Dim binder As Binder = BinderBuilder.CreateBinderForType(mainType.ContainingSourceModule, mainType.SyntaxReferences(0).SyntaxTree, mainType) Dim lookupResult As LookupResult = lookupResult.GetInstance() Dim entryPointLookupOptions As LookupOptions = LookupOptions.AllMethodsOfAnyArity Or LookupOptions.IgnoreExtensionMethods binder.LookupMember(lookupResult, mainType, WellKnownMemberNames.EntryPointMethodName, arity:=0, options:=entryPointLookupOptions, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If (Not lookupResult.IsGoodOrAmbiguous) OrElse lookupResult.Symbols(0).Kind <> SymbolKind.Method Then diagnostics.Add(ERRID.ERR_StartupCodeNotFound1, NoLocation.Singleton, mainType) lookupResult.Free() Return Nothing End If For Each candidate In lookupResult.Symbols ' The entrypoint cannot be in another assembly. ' NOTE: filter these out here, rather than below, so that we ' report "not found", rather than "invalid", as in dev10. If candidate.ContainingAssembly = Me.Assembly Then entryPointCandidates.Add(DirectCast(candidate, MethodSymbol)) End If Next lookupResult.Free() Else mainType = Nothing errorTarget = Me.AssemblyName For Each candidate In Me.GetSymbolsWithName(WellKnownMemberNames.EntryPointMethodName, SymbolFilter.Member, cancellationToken) Dim method = TryCast(candidate, MethodSymbol) If method?.IsEntryPointCandidate = True Then entryPointCandidates.Add(method) End If Next ' Global code is the entry point, ignore all other Mains. If ScriptClass IsNot Nothing Then For Each main In entryPointCandidates diagnostics.Add(ERRID.WRN_MainIgnored, main.Locations.First(), main) Next Return ScriptClass.GetScriptEntryPoint() End If End If If entryPointCandidates.Count = 0 Then diagnostics.Add(ERRID.ERR_StartupCodeNotFound1, NoLocation.Singleton, errorTarget) Return Nothing End If Dim hasViableGenericEntryPoints As Boolean = False Dim viableEntryPoints = ArrayBuilder(Of MethodSymbol).GetInstance() For Each candidate In entryPointCandidates If Not candidate.IsViableMainMethod Then Continue For End If If candidate.IsGenericMethod OrElse candidate.ContainingType.IsGenericType Then hasViableGenericEntryPoints = True Else viableEntryPoints.Add(candidate) End If Next Dim entryPoint As MethodSymbol = Nothing If viableEntryPoints.Count = 0 Then If hasViableGenericEntryPoints Then diagnostics.Add(ERRID.ERR_GenericSubMainsFound1, NoLocation.Singleton, errorTarget) Else diagnostics.Add(ERRID.ERR_InValidSubMainsFound1, NoLocation.Singleton, errorTarget) End If ElseIf viableEntryPoints.Count > 1 Then viableEntryPoints.Sort(LexicalOrderSymbolComparer.Instance) diagnostics.Add(ERRID.ERR_MoreThanOneValidMainWasFound2, NoLocation.Singleton, Me.AssemblyName, New FormattedSymbolList(viableEntryPoints.ToArray(), CustomSymbolDisplayFormatter.ErrorMessageFormatNoModifiersNoReturnType)) Else entryPoint = viableEntryPoints(0) If entryPoint.IsAsync Then ' The rule we follow: ' First determine the Sub Main using pre-async rules, and give the pre-async errors if there were 0 or >1 results ' If there was exactly one result, but it was async, then give an error. Otherwise proceed. ' This doesn't follow the same pattern as "error due to being generic". That's because ' maybe one day we'll want to allow Async Sub Main but without breaking back-compat. Dim sourceMethod = TryCast(entryPoint, SourceMemberMethodSymbol) Debug.Assert(sourceMethod IsNot Nothing) If sourceMethod IsNot Nothing Then Dim location As Location = sourceMethod.NonMergedLocation Debug.Assert(location IsNot Nothing) If location IsNot Nothing Then Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_AsyncSubMain) End If End If End If End If viableEntryPoints.Free() Return entryPoint Finally entryPointCandidates.Free() sealedDiagnostics = diagnostics.ToReadOnlyAndFree() End Try End Function Friend Class EntryPoint Public ReadOnly MethodSymbol As MethodSymbol Public ReadOnly Diagnostics As ImmutableArray(Of Diagnostic) Public Sub New(methodSymbol As MethodSymbol, diagnostics As ImmutableArray(Of Diagnostic)) Me.MethodSymbol = methodSymbol Me.Diagnostics = diagnostics End Sub End Class ''' <summary> ''' Returns the list of member imports that apply to all syntax trees in this compilation. ''' </summary> Friend ReadOnly Property MemberImports As ImmutableArray(Of NamespaceOrTypeSymbol) Get Return DirectCast(Me.SourceModule, SourceModuleSymbol).MemberImports.SelectAsArray(Function(m) m.NamespaceOrType) End Get End Property ''' <summary> ''' Returns the list of alias imports that apply to all syntax trees in this compilation. ''' </summary> Friend ReadOnly Property AliasImports As ImmutableArray(Of AliasSymbol) Get Return DirectCast(Me.SourceModule, SourceModuleSymbol).AliasImports.SelectAsArray(Function(a) a.Alias) End Get End Property Friend Overrides Sub ReportUnusedImports(diagnostics As DiagnosticBag, cancellationToken As CancellationToken) ReportUnusedImports(filterTree:=Nothing, New BindingDiagnosticBag(diagnostics), cancellationToken) End Sub Private Overloads Sub ReportUnusedImports(filterTree As SyntaxTree, diagnostics As BindingDiagnosticBag, cancellationToken As CancellationToken) If _lazyImportInfos IsNot Nothing AndAlso (filterTree Is Nothing OrElse ReportUnusedImportsInTree(filterTree)) Then Dim unusedBuilder As ArrayBuilder(Of TextSpan) = Nothing For Each info As ImportInfo In _lazyImportInfos cancellationToken.ThrowIfCancellationRequested() Dim infoTree As SyntaxTree = info.Tree If (filterTree Is Nothing OrElse filterTree Is infoTree) AndAlso ReportUnusedImportsInTree(infoTree) Then Dim clauseSpans = info.ClauseSpans Dim numClauseSpans = clauseSpans.Length If numClauseSpans = 1 Then ' Do less work in common case (one clause per statement). If Not Me.IsImportDirectiveUsed(infoTree, clauseSpans(0).Start) Then diagnostics.Add(ERRID.HDN_UnusedImportStatement, infoTree.GetLocation(info.StatementSpan)) Else AddImportsDependencies(diagnostics, infoTree, clauseSpans(0)) End If Else If unusedBuilder IsNot Nothing Then unusedBuilder.Clear() End If For Each clauseSpan In info.ClauseSpans If Not Me.IsImportDirectiveUsed(infoTree, clauseSpan.Start) Then If unusedBuilder Is Nothing Then unusedBuilder = ArrayBuilder(Of TextSpan).GetInstance() End If unusedBuilder.Add(clauseSpan) Else AddImportsDependencies(diagnostics, infoTree, clauseSpan) End If Next If unusedBuilder IsNot Nothing AndAlso unusedBuilder.Count > 0 Then If unusedBuilder.Count = numClauseSpans Then diagnostics.Add(ERRID.HDN_UnusedImportStatement, infoTree.GetLocation(info.StatementSpan)) Else For Each clauseSpan In unusedBuilder diagnostics.Add(ERRID.HDN_UnusedImportClause, infoTree.GetLocation(clauseSpan)) Next End If End If End If End If Next If unusedBuilder IsNot Nothing Then unusedBuilder.Free() End If End If CompleteTrees(filterTree) End Sub Private Sub AddImportsDependencies(diagnostics As BindingDiagnosticBag, infoTree As SyntaxTree, clauseSpan As TextSpan) Dim dependencies As ImmutableArray(Of AssemblySymbol) = Nothing If diagnostics.AccumulatesDependencies AndAlso _lazyImportClauseDependencies IsNot Nothing AndAlso _lazyImportClauseDependencies.TryGetValue((infoTree, clauseSpan.Start), dependencies) Then diagnostics.AddDependencies(dependencies) End If End Sub Friend Overrides Sub CompleteTrees(filterTree As SyntaxTree) ' By definition, a tree Is complete when all of its compiler diagnostics have been reported. ' Since unused imports are the last thing we compute And report, a tree Is complete when ' the unused imports have been reported. If EventQueue IsNot Nothing Then If filterTree IsNot Nothing Then CompleteTree(filterTree) Else For Each tree As SyntaxTree In SyntaxTrees CompleteTree(tree) Next End If End If End Sub Private Sub CompleteTree(tree As SyntaxTree) If tree.IsEmbeddedOrMyTemplateTree Then ' The syntax trees added to AllSyntaxTrees by the compiler ' do not count toward completion. Return End If Debug.Assert(AllSyntaxTrees.Contains(tree)) If _lazyCompilationUnitCompletedTrees Is Nothing Then Interlocked.CompareExchange(_lazyCompilationUnitCompletedTrees, New HashSet(Of SyntaxTree)(), Nothing) End If SyncLock _lazyCompilationUnitCompletedTrees If _lazyCompilationUnitCompletedTrees.Add(tree) Then ' signal the end of the compilation unit EventQueue.TryEnqueue(New CompilationUnitCompletedEvent(Me, tree)) If _lazyCompilationUnitCompletedTrees.Count = SyntaxTrees.Length Then ' if that was the last tree, signal the end of compilation CompleteCompilationEventQueue_NoLock() End If End If End SyncLock End Sub Friend Function ShouldAddEvent(symbol As Symbol) As Boolean Return EventQueue IsNot Nothing AndAlso symbol.IsInSource() End Function Friend Sub SymbolDeclaredEvent(symbol As Symbol) If ShouldAddEvent(symbol) Then EventQueue.TryEnqueue(New SymbolDeclaredCompilationEvent(Me, symbol)) End If End Sub Friend Sub RecordImportsClauseDependencies(syntaxTree As SyntaxTree, importsClausePosition As Integer, dependencies As ImmutableArray(Of AssemblySymbol)) If Not dependencies.IsDefaultOrEmpty Then LazyInitializer.EnsureInitialized(_lazyImportClauseDependencies).TryAdd((syntaxTree, importsClausePosition), dependencies) End If End Sub Friend Sub RecordImports(syntax As ImportsStatementSyntax) LazyInitializer.EnsureInitialized(_lazyImportInfos).Enqueue(New ImportInfo(syntax)) End Sub Private Structure ImportInfo Public ReadOnly Tree As SyntaxTree Public ReadOnly StatementSpan As TextSpan Public ReadOnly ClauseSpans As ImmutableArray(Of TextSpan) ' CONSIDER: ClauseSpans will usually be a singleton. If we're ' creating too much garbage, it might be worthwhile to store ' a single clause span in a separate field. Public Sub New(syntax As ImportsStatementSyntax) Me.Tree = syntax.SyntaxTree Me.StatementSpan = syntax.Span Dim builder = ArrayBuilder(Of TextSpan).GetInstance() For Each clause In syntax.ImportsClauses builder.Add(clause.Span) Next Me.ClauseSpans = builder.ToImmutableAndFree() End Sub End Structure Friend ReadOnly Property DeclaresTheObjectClass As Boolean Get Return SourceAssembly.DeclaresTheObjectClass End Get End Property Friend Function MightContainNoPiaLocalTypes() As Boolean Return SourceAssembly.MightContainNoPiaLocalTypes() End Function ' NOTE(cyrusn): There is a bit of a discoverability problem with this method and the same ' named method in SyntaxTreeSemanticModel. Technically, i believe these are the appropriate ' locations for these methods. This method has no dependencies on anything but the ' compilation, while the other method needs a bindings object to determine what bound node ' an expression syntax binds to. Perhaps when we document these methods we should explain ' where a user can find the other. ''' <summary> ''' Determine what kind of conversion, if any, there is between the types ''' "source" and "destination". ''' </summary> Public Shadows Function ClassifyConversion(source As ITypeSymbol, destination As ITypeSymbol) As Conversion If source Is Nothing Then Throw New ArgumentNullException(NameOf(source)) End If If destination Is Nothing Then Throw New ArgumentNullException(NameOf(destination)) End If Dim vbsource = source.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(source)) Dim vbdest = destination.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(destination)) If vbsource.IsErrorType() OrElse vbdest.IsErrorType() Then Return New Conversion(Nothing) ' No conversion End If Return New Conversion(Conversions.ClassifyConversion(vbsource, vbdest, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) End Function Public Overrides Function ClassifyCommonConversion(source As ITypeSymbol, destination As ITypeSymbol) As CommonConversion Return ClassifyConversion(source, destination).ToCommonConversion() End Function Friend Overrides Function ClassifyConvertibleConversion(source As IOperation, destination As ITypeSymbol, ByRef constantValue As ConstantValue) As IConvertibleConversion constantValue = Nothing If destination Is Nothing Then Return New Conversion(Nothing) ' No conversion End If Dim sourceType As ITypeSymbol = source.Type Dim sourceConstantValue As ConstantValue = source.GetConstantValue() If sourceType Is Nothing Then If sourceConstantValue IsNot Nothing AndAlso sourceConstantValue.IsNothing AndAlso destination.IsReferenceType Then constantValue = sourceConstantValue Return New Conversion(New KeyValuePair(Of ConversionKind, MethodSymbol)(ConversionKind.WideningNothingLiteral, Nothing)) End If Return New Conversion(Nothing) ' No conversion End If Dim result As Conversion = ClassifyConversion(sourceType, destination) If result.IsReference AndAlso sourceConstantValue IsNot Nothing AndAlso sourceConstantValue.IsNothing Then constantValue = sourceConstantValue End If Return result End Function ''' <summary> ''' A symbol representing the implicit Script class. This is null if the class is not ''' defined in the compilation. ''' </summary> Friend Shadows ReadOnly Property ScriptClass As NamedTypeSymbol Get Return SourceScriptClass End Get End Property Friend ReadOnly Property SourceScriptClass As ImplicitNamedTypeSymbol Get Return _scriptClass.Value End Get End Property ''' <summary> ''' Resolves a symbol that represents script container (Script class). ''' Uses the full name of the container class stored in <see cref="CompilationOptions.ScriptClassName"/> to find the symbol. ''' </summary> ''' <returns> ''' The Script class symbol or null if it is not defined. ''' </returns> Private Function BindScriptClass() As ImplicitNamedTypeSymbol Return DirectCast(CommonBindScriptClass(), ImplicitNamedTypeSymbol) End Function ''' <summary> ''' Get symbol for predefined type from Cor Library referenced by this compilation. ''' </summary> Friend Shadows Function GetSpecialType(typeId As SpecialType) As NamedTypeSymbol Dim result = Assembly.GetSpecialType(typeId) Debug.Assert(result.SpecialType = typeId) Return result End Function ''' <summary> ''' Get symbol for predefined type member from Cor Library referenced by this compilation. ''' </summary> Friend Shadows Function GetSpecialTypeMember(memberId As SpecialMember) As Symbol Return Assembly.GetSpecialTypeMember(memberId) End Function Friend Overrides Function CommonGetSpecialTypeMember(specialMember As SpecialMember) As ISymbolInternal Return GetSpecialTypeMember(specialMember) End Function Friend Function GetTypeByReflectionType(type As Type) As TypeSymbol ' TODO: See CSharpCompilation.GetTypeByReflectionType Return GetSpecialType(SpecialType.System_Object) End Function ''' <summary> ''' Lookup a type within the compilation's assembly and all referenced assemblies ''' using its canonical CLR metadata name (names are compared case-sensitively). ''' </summary> ''' <param name="fullyQualifiedMetadataName"> ''' </param> ''' <returns> ''' Symbol for the type or null if type cannot be found or is ambiguous. ''' </returns> Friend Shadows Function GetTypeByMetadataName(fullyQualifiedMetadataName As String) As NamedTypeSymbol Return Me.Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName, includeReferences:=True, isWellKnownType:=False, conflicts:=Nothing) End Function Friend Shadows ReadOnly Property ObjectType As NamedTypeSymbol Get Return Assembly.ObjectType End Get End Property Friend Shadows Function CreateArrayTypeSymbol(elementType As TypeSymbol, Optional rank As Integer = 1) As ArrayTypeSymbol If elementType Is Nothing Then Throw New ArgumentNullException(NameOf(elementType)) End If If rank < 1 Then Throw New ArgumentException(NameOf(rank)) End If Return ArrayTypeSymbol.CreateVBArray(elementType, Nothing, rank, Me) End Function Friend ReadOnly Property HasTupleNamesAttributes As Boolean Get Dim constructorSymbol = TryCast(GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames), MethodSymbol) Return constructorSymbol IsNot Nothing AndAlso Binder.GetUseSiteInfoForWellKnownTypeMember(constructorSymbol, WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames, embedVBRuntimeUsed:=False).DiagnosticInfo Is Nothing End Get End Property Private Protected Overrides Function IsSymbolAccessibleWithinCore(symbol As ISymbol, within As ISymbol, throughType As ITypeSymbol) As Boolean Dim symbol0 = symbol.EnsureVbSymbolOrNothing(Of Symbol)(NameOf(symbol)) Dim within0 = within.EnsureVbSymbolOrNothing(Of Symbol)(NameOf(within)) Dim throughType0 = throughType.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(throughType)) Return If(within0.Kind = SymbolKind.Assembly, AccessCheck.IsSymbolAccessible(symbol0, DirectCast(within0, AssemblySymbol), useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded), AccessCheck.IsSymbolAccessible(symbol0, DirectCast(within0, NamedTypeSymbol), throughType0, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) End Function <Obsolete("Compilation.IsSymbolAccessibleWithin is not designed for use within the compilers", True)> Friend Shadows Function IsSymbolAccessibleWithin(symbol As ISymbol, within As ISymbol, Optional throughType As ITypeSymbol = Nothing) As Boolean Throw New NotImplementedException End Function #End Region #Region "Binding" '''<summary> ''' Get a fresh SemanticModel. Note that each invocation gets a fresh SemanticModel, each of ''' which has a cache. Therefore, one effectively clears the cache by discarding the ''' SemanticModel. '''</summary> Public Shadows Function GetSemanticModel(syntaxTree As SyntaxTree, Optional ignoreAccessibility As Boolean = False) As SemanticModel Dim model As SemanticModel = Nothing If SemanticModelProvider IsNot Nothing Then model = SemanticModelProvider.GetSemanticModel(syntaxTree, Me, ignoreAccessibility) Debug.Assert(model IsNot Nothing) End If Return If(model, CreateSemanticModel(syntaxTree, ignoreAccessibility)) End Function Friend Overrides Function CreateSemanticModel(syntaxTree As SyntaxTree, ignoreAccessibility As Boolean) As SemanticModel Return New SyntaxTreeSemanticModel(Me, DirectCast(Me.SourceModule, SourceModuleSymbol), syntaxTree, ignoreAccessibility) End Function Friend ReadOnly Property FeatureStrictEnabled As Boolean Get Return Me.Feature("strict") IsNot Nothing End Get End Property #End Region #Region "Diagnostics" Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider Get Return VisualBasic.MessageProvider.Instance End Get End Property ''' <summary> ''' Get all diagnostics for the entire compilation. This includes diagnostics from parsing, declarations, and ''' the bodies of methods. Getting all the diagnostics is potentially a length operations, as it requires parsing and ''' compiling all the code. The set of diagnostics is not caches, so each call to this method will recompile all ''' methods. ''' </summary> ''' <param name="cancellationToken">Cancellation token to allow cancelling the operation.</param> Public Overrides Function GetDiagnostics(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Return GetDiagnostics(DefaultDiagnosticsStage, True, cancellationToken) End Function ''' <summary> ''' Get parse diagnostics for the entire compilation. This includes diagnostics from parsing BUT NOT from declarations and ''' the bodies of methods or initializers. The set of parse diagnostics is cached, so calling this method a second time ''' should be fast. ''' </summary> Public Overrides Function GetParseDiagnostics(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Return GetDiagnostics(CompilationStage.Parse, False, cancellationToken) End Function ''' <summary> ''' Get declarations diagnostics for the entire compilation. This includes diagnostics from declarations, BUT NOT ''' the bodies of methods or initializers. The set of declaration diagnostics is cached, so calling this method a second time ''' should be fast. ''' </summary> ''' <param name="cancellationToken">Cancellation token to allow cancelling the operation.</param> Public Overrides Function GetDeclarationDiagnostics(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Return GetDiagnostics(CompilationStage.Declare, False, cancellationToken) End Function ''' <summary> ''' Get method body diagnostics for the entire compilation. This includes diagnostics only from ''' the bodies of methods and initializers. These diagnostics are NOT cached, so calling this method a second time ''' repeats significant work. ''' </summary> ''' <param name="cancellationToken">Cancellation token to allow cancelling the operation.</param> Public Overrides Function GetMethodBodyDiagnostics(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Return GetDiagnostics(CompilationStage.Compile, False, cancellationToken) End Function ''' <summary> ''' Get all errors in the compilation, up through the given compilation stage. Note that this may ''' require significant work by the compiler, as all source code must be compiled to the given ''' level in order to get the errors. Errors on Options should be inspected by the user prior to constructing the compilation. ''' </summary> ''' <returns> ''' Returns all errors. The errors are not sorted in any particular order, and the client ''' should sort the errors as desired. ''' </returns> Friend Overloads Function GetDiagnostics(stage As CompilationStage, Optional includeEarlierStages As Boolean = True, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Dim diagnostics = DiagnosticBag.GetInstance() GetDiagnostics(stage, includeEarlierStages, diagnostics, cancellationToken) Return diagnostics.ToReadOnlyAndFree() End Function Friend Overrides Sub GetDiagnostics(stage As CompilationStage, includeEarlierStages As Boolean, diagnostics As DiagnosticBag, Optional cancellationToken As CancellationToken = Nothing) Dim builder = DiagnosticBag.GetInstance() GetDiagnosticsWithoutFiltering(stage, includeEarlierStages, New BindingDiagnosticBag(builder), cancellationToken) ' Before returning diagnostics, we filter some of them ' to honor the compiler options (e.g., /nowarn and /warnaserror) FilterAndAppendAndFreeDiagnostics(diagnostics, builder, cancellationToken) End Sub Private Sub GetDiagnosticsWithoutFiltering(stage As CompilationStage, includeEarlierStages As Boolean, builder As BindingDiagnosticBag, Optional cancellationToken As CancellationToken = Nothing) Debug.Assert(builder.AccumulatesDiagnostics) ' Add all parsing errors. If (stage = CompilationStage.Parse OrElse stage > CompilationStage.Parse AndAlso includeEarlierStages) Then ' Embedded trees shouldn't have any errors, let's avoid making decision if they should be added too early. ' Otherwise IDE performance might be affect. If Options.ConcurrentBuild Then RoslynParallel.For( 0, SyntaxTrees.Length, UICultureUtilities.WithCurrentUICulture( Sub(i As Integer) builder.AddRange(SyntaxTrees(i).GetDiagnostics(cancellationToken)) End Sub), cancellationToken) Else For Each tree In SyntaxTrees cancellationToken.ThrowIfCancellationRequested() builder.AddRange(tree.GetDiagnostics(cancellationToken)) Next End If Dim parseOptionsReported = New HashSet(Of ParseOptions) If Options.ParseOptions IsNot Nothing Then parseOptionsReported.Add(Options.ParseOptions) ' This is reported in Options.Errors at CompilationStage.Declare End If For Each tree In SyntaxTrees cancellationToken.ThrowIfCancellationRequested() If Not tree.Options.Errors.IsDefaultOrEmpty AndAlso parseOptionsReported.Add(tree.Options) Then Dim location = tree.GetLocation(TextSpan.FromBounds(0, 0)) For Each err In tree.Options.Errors builder.Add(err.WithLocation(location)) Next End If Next End If ' Add declaration errors If (stage = CompilationStage.Declare OrElse stage > CompilationStage.Declare AndAlso includeEarlierStages) Then CheckAssemblyName(builder.DiagnosticBag) builder.AddRange(Options.Errors) builder.AddRange(GetBoundReferenceManager().Diagnostics) SourceAssembly.GetAllDeclarationErrors(builder, cancellationToken) AddClsComplianceDiagnostics(builder, cancellationToken) If EventQueue IsNot Nothing AndAlso SyntaxTrees.Length = 0 Then EnsureCompilationEventQueueCompleted() End If End If ' Add method body compilation errors. If (stage = CompilationStage.Compile OrElse stage > CompilationStage.Compile AndAlso includeEarlierStages) Then ' Note: this phase does not need to be parallelized because ' it is already implemented in method compiler Dim methodBodyDiagnostics = New BindingDiagnosticBag(DiagnosticBag.GetInstance(), If(builder.AccumulatesDependencies, New ConcurrentSet(Of AssemblySymbol), Nothing)) GetDiagnosticsForAllMethodBodies(builder.HasAnyErrors(), methodBodyDiagnostics, doLowering:=False, cancellationToken) builder.AddRange(methodBodyDiagnostics) methodBodyDiagnostics.DiagnosticBag.Free() End If End Sub Private Sub AddClsComplianceDiagnostics(diagnostics As BindingDiagnosticBag, cancellationToken As CancellationToken, Optional filterTree As SyntaxTree = Nothing, Optional filterSpanWithinTree As TextSpan? = Nothing) If filterTree IsNot Nothing Then ClsComplianceChecker.CheckCompliance(Me, diagnostics, cancellationToken, filterTree, filterSpanWithinTree) Return End If Debug.Assert(filterSpanWithinTree Is Nothing) If _lazyClsComplianceDiagnostics.IsDefault OrElse _lazyClsComplianceDependencies.IsDefault Then Dim builder = BindingDiagnosticBag.GetInstance() ClsComplianceChecker.CheckCompliance(Me, builder, cancellationToken) Dim result As ImmutableBindingDiagnostic(Of AssemblySymbol) = builder.ToReadOnlyAndFree() ImmutableInterlocked.InterlockedInitialize(_lazyClsComplianceDependencies, result.Dependencies) ImmutableInterlocked.InterlockedInitialize(_lazyClsComplianceDiagnostics, result.Diagnostics) End If Debug.Assert(Not _lazyClsComplianceDependencies.IsDefault) Debug.Assert(Not _lazyClsComplianceDiagnostics.IsDefault) diagnostics.AddRange(New ImmutableBindingDiagnostic(Of AssemblySymbol)(_lazyClsComplianceDiagnostics, _lazyClsComplianceDependencies), allowMismatchInDependencyAccumulation:=True) End Sub Private Shared Iterator Function FilterDiagnosticsByLocation(diagnostics As IEnumerable(Of Diagnostic), tree As SyntaxTree, filterSpanWithinTree As TextSpan?) As IEnumerable(Of Diagnostic) For Each diagnostic In diagnostics If diagnostic.HasIntersectingLocation(tree, filterSpanWithinTree) Then Yield diagnostic End If Next End Function Friend Function GetDiagnosticsForSyntaxTree(stage As CompilationStage, tree As SyntaxTree, filterSpanWithinTree As TextSpan?, includeEarlierStages As Boolean, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) If Not SyntaxTrees.Contains(tree) Then Throw New ArgumentException("Cannot GetDiagnosticsForSyntax for a tree that is not part of the compilation", NameOf(tree)) End If Dim builder = New BindingDiagnosticBag(DiagnosticBag.GetInstance()) If (stage = CompilationStage.Parse OrElse stage > CompilationStage.Parse AndAlso includeEarlierStages) Then ' Add all parsing errors. cancellationToken.ThrowIfCancellationRequested() Dim syntaxDiagnostics = tree.GetDiagnostics(cancellationToken) syntaxDiagnostics = FilterDiagnosticsByLocation(syntaxDiagnostics, tree, filterSpanWithinTree) builder.AddRange(syntaxDiagnostics) End If ' Add declaring errors If (stage = CompilationStage.Declare OrElse stage > CompilationStage.Declare AndAlso includeEarlierStages) Then Dim declarationDiags = DirectCast(SourceModule, SourceModuleSymbol).GetDeclarationErrorsInTree(tree, filterSpanWithinTree, AddressOf FilterDiagnosticsByLocation, cancellationToken) Dim filteredDiags = FilterDiagnosticsByLocation(declarationDiags, tree, filterSpanWithinTree) builder.AddRange(filteredDiags) AddClsComplianceDiagnostics(builder, cancellationToken, tree, filterSpanWithinTree) End If ' Add method body declaring errors. If (stage = CompilationStage.Compile OrElse stage > CompilationStage.Compile AndAlso includeEarlierStages) Then Dim methodBodyDiagnostics = New BindingDiagnosticBag(DiagnosticBag.GetInstance()) GetDiagnosticsForMethodBodiesInTree(tree, filterSpanWithinTree, builder.HasAnyErrors(), methodBodyDiagnostics, cancellationToken) ' This diagnostics can include diagnostics for initializers that do not belong to the tree. ' Let's filter them out. If Not methodBodyDiagnostics.DiagnosticBag.IsEmptyWithoutResolution Then Dim allDiags = methodBodyDiagnostics.DiagnosticBag.AsEnumerableWithoutResolution() Dim filteredDiags = FilterDiagnosticsByLocation(allDiags, tree, filterSpanWithinTree) For Each diag In filteredDiags builder.Add(diag) Next End If End If Dim result = DiagnosticBag.GetInstance() FilterAndAppendAndFreeDiagnostics(result, builder.DiagnosticBag, cancellationToken) Return result.ToReadOnlyAndFree(Of Diagnostic)() End Function ' Get diagnostics by compiling all method bodies. Private Sub GetDiagnosticsForAllMethodBodies(hasDeclarationErrors As Boolean, diagnostics As BindingDiagnosticBag, doLowering As Boolean, cancellationToken As CancellationToken) MethodCompiler.GetCompileDiagnostics(Me, SourceModule.GlobalNamespace, Nothing, Nothing, hasDeclarationErrors, diagnostics, doLowering, cancellationToken) DocumentationCommentCompiler.WriteDocumentationCommentXml(Me, Nothing, Nothing, diagnostics, cancellationToken) Me.ReportUnusedImports(Nothing, diagnostics, cancellationToken) End Sub ' Get diagnostics by compiling all method bodies in the given tree. Private Sub GetDiagnosticsForMethodBodiesInTree(tree As SyntaxTree, filterSpanWithinTree As TextSpan?, hasDeclarationErrors As Boolean, diagnostics As BindingDiagnosticBag, cancellationToken As CancellationToken) Dim sourceMod = DirectCast(SourceModule, SourceModuleSymbol) MethodCompiler.GetCompileDiagnostics(Me, SourceModule.GlobalNamespace, tree, filterSpanWithinTree, hasDeclarationErrors, diagnostics, doLoweringPhase:=False, cancellationToken) DocumentationCommentCompiler.WriteDocumentationCommentXml(Me, Nothing, Nothing, diagnostics, cancellationToken, tree, filterSpanWithinTree) ' Report unused import diagnostics only if computing diagnostics for the entire tree. ' Otherwise we cannot determine if a particular directive is used outside of the given sub-span within the tree. If Not filterSpanWithinTree.HasValue OrElse filterSpanWithinTree.Value = tree.GetRoot(cancellationToken).FullSpan Then Me.ReportUnusedImports(tree, diagnostics, cancellationToken) End If End Sub Friend Overrides Function CreateAnalyzerDriver(analyzers As ImmutableArray(Of DiagnosticAnalyzer), analyzerManager As AnalyzerManager, severityFilter As SeverityFilter) As AnalyzerDriver Dim getKind As Func(Of SyntaxNode, SyntaxKind) = Function(node As SyntaxNode) node.Kind Dim isComment As Func(Of SyntaxTrivia, Boolean) = Function(trivia As SyntaxTrivia) trivia.Kind() = SyntaxKind.CommentTrivia Return New AnalyzerDriver(Of SyntaxKind)(analyzers, getKind, analyzerManager, severityFilter, isComment) End Function #End Region #Region "Resources" Protected Overrides Sub AppendDefaultVersionResource(resourceStream As Stream) Dim fileVersion As String = If(SourceAssembly.FileVersion, SourceAssembly.Identity.Version.ToString()) 'for some parameters, alink used to supply whitespace instead of null. Win32ResourceConversions.AppendVersionToResourceStream(resourceStream, Not Me.Options.OutputKind.IsApplication(), fileVersion:=fileVersion, originalFileName:=Me.SourceModule.Name, internalName:=Me.SourceModule.Name, productVersion:=If(SourceAssembly.InformationalVersion, fileVersion), assemblyVersion:=SourceAssembly.Identity.Version, fileDescription:=If(SourceAssembly.Title, " "), legalCopyright:=If(SourceAssembly.Copyright, " "), legalTrademarks:=SourceAssembly.Trademark, productName:=SourceAssembly.Product, comments:=SourceAssembly.Description, companyName:=SourceAssembly.Company) End Sub #End Region #Region "Emit" Friend Overrides ReadOnly Property LinkerMajorVersion As Byte Get Return &H50 End Get End Property Friend Overrides ReadOnly Property IsDelaySigned As Boolean Get Return SourceAssembly.IsDelaySigned End Get End Property Friend Overrides ReadOnly Property StrongNameKeys As StrongNameKeys Get Return SourceAssembly.StrongNameKeys End Get End Property Friend Overrides Function CreateModuleBuilder( emitOptions As EmitOptions, debugEntryPoint As IMethodSymbol, sourceLinkStream As Stream, embeddedTexts As IEnumerable(Of EmbeddedText), manifestResources As IEnumerable(Of ResourceDescription), testData As CompilationTestData, diagnostics As DiagnosticBag, cancellationToken As CancellationToken) As CommonPEModuleBuilder Return CreateModuleBuilder( emitOptions, debugEntryPoint, sourceLinkStream, embeddedTexts, manifestResources, testData, diagnostics, ImmutableArray(Of NamedTypeSymbol).Empty, cancellationToken) End Function Friend Overloads Function CreateModuleBuilder( emitOptions As EmitOptions, debugEntryPoint As IMethodSymbol, sourceLinkStream As Stream, embeddedTexts As IEnumerable(Of EmbeddedText), manifestResources As IEnumerable(Of ResourceDescription), testData As CompilationTestData, diagnostics As DiagnosticBag, additionalTypes As ImmutableArray(Of NamedTypeSymbol), cancellationToken As CancellationToken) As CommonPEModuleBuilder Debug.Assert(Not IsSubmission OrElse HasCodeToEmit() OrElse (emitOptions = EmitOptions.Default AndAlso debugEntryPoint Is Nothing AndAlso sourceLinkStream Is Nothing AndAlso embeddedTexts Is Nothing AndAlso manifestResources Is Nothing AndAlso testData Is Nothing)) ' Get the runtime metadata version from the cor library. If this fails we have no reasonable value to give. Dim runtimeMetadataVersion = GetRuntimeMetadataVersion() Dim moduleSerializationProperties = ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion) If manifestResources Is Nothing Then manifestResources = SpecializedCollections.EmptyEnumerable(Of ResourceDescription)() End If ' if there is no stream to write to, then there is no need for a module Dim moduleBeingBuilt As PEModuleBuilder If Options.OutputKind.IsNetModule() Then Debug.Assert(additionalTypes.IsEmpty) moduleBeingBuilt = New PENetModuleBuilder( DirectCast(Me.SourceModule, SourceModuleSymbol), emitOptions, moduleSerializationProperties, manifestResources) Else Dim kind = If(Options.OutputKind.IsValid(), Options.OutputKind, OutputKind.DynamicallyLinkedLibrary) moduleBeingBuilt = New PEAssemblyBuilder( SourceAssembly, emitOptions, kind, moduleSerializationProperties, manifestResources, additionalTypes) End If If debugEntryPoint IsNot Nothing Then moduleBeingBuilt.SetDebugEntryPoint(DirectCast(debugEntryPoint, MethodSymbol), diagnostics) End If moduleBeingBuilt.SourceLinkStreamOpt = sourceLinkStream If embeddedTexts IsNot Nothing Then moduleBeingBuilt.EmbeddedTexts = embeddedTexts End If If testData IsNot Nothing Then moduleBeingBuilt.SetMethodTestData(testData.Methods) testData.Module = moduleBeingBuilt End If Return moduleBeingBuilt End Function Friend Overrides Function CompileMethods( moduleBuilder As CommonPEModuleBuilder, emittingPdb As Boolean, emitMetadataOnly As Boolean, emitTestCoverageData As Boolean, diagnostics As DiagnosticBag, filterOpt As Predicate(Of ISymbolInternal), cancellationToken As CancellationToken) As Boolean ' The diagnostics should include syntax and declaration errors. We insert these before calling Emitter.Emit, so that we don't emit ' metadata if there are declaration errors or method body errors (but we do insert all errors from method body binding...) Dim hasDeclarationErrors = Not FilterAndAppendDiagnostics(diagnostics, GetDiagnostics(CompilationStage.Declare, True, cancellationToken), exclude:=Nothing, cancellationToken) Dim moduleBeingBuilt = DirectCast(moduleBuilder, PEModuleBuilder) Me.EmbeddedSymbolManager.MarkAllDeferredSymbolsAsReferenced(Me) ' The translation of global imports assumes absence of error symbols. ' We don't need to translate them if there are any declaration errors since ' we are not going to emit the metadata. If Not hasDeclarationErrors Then moduleBeingBuilt.TranslateImports(diagnostics) End If If emitMetadataOnly Then If hasDeclarationErrors Then Return False End If If moduleBeingBuilt.SourceModule.HasBadAttributes Then ' If there were errors but no declaration diagnostics, explicitly add a "Failed to emit module" error. diagnostics.Add(ERRID.ERR_ModuleEmitFailure, NoLocation.Singleton, moduleBeingBuilt.SourceModule.Name, New LocalizableResourceString(NameOf(CodeAnalysisResources.ModuleHasInvalidAttributes), CodeAnalysisResources.ResourceManager, GetType(CodeAnalysisResources))) Return False End If SynthesizedMetadataCompiler.ProcessSynthesizedMembers(Me, moduleBeingBuilt, cancellationToken) Else ' start generating PDB checksums if we need to emit PDBs If (emittingPdb OrElse emitTestCoverageData) AndAlso Not CreateDebugDocuments(moduleBeingBuilt.DebugDocumentsBuilder, moduleBeingBuilt.EmbeddedTexts, diagnostics) Then Return False End If ' Perform initial bind of method bodies in spite of earlier errors. This is the same ' behavior as when calling GetDiagnostics() ' Use a temporary bag so we don't have to refilter pre-existing diagnostics. Dim methodBodyDiagnosticBag = DiagnosticBag.GetInstance() MethodCompiler.CompileMethodBodies( Me, moduleBeingBuilt, emittingPdb, emitTestCoverageData, hasDeclarationErrors, filterOpt, New BindingDiagnosticBag(methodBodyDiagnosticBag), cancellationToken) Dim hasMethodBodyErrors As Boolean = Not FilterAndAppendAndFreeDiagnostics(diagnostics, methodBodyDiagnosticBag, cancellationToken) If hasDeclarationErrors OrElse hasMethodBodyErrors Then Return False End If End If cancellationToken.ThrowIfCancellationRequested() ' TODO (tomat): XML doc comments diagnostics Return True End Function Friend Overrides Function GenerateResourcesAndDocumentationComments( moduleBuilder As CommonPEModuleBuilder, xmlDocStream As Stream, win32Resources As Stream, useRawWin32Resources As Boolean, outputNameOverride As String, diagnostics As DiagnosticBag, cancellationToken As CancellationToken) As Boolean ' Use a temporary bag so we don't have to refilter pre-existing diagnostics. Dim resourceDiagnostics = DiagnosticBag.GetInstance() SetupWin32Resources(moduleBuilder, win32Resources, useRawWin32Resources, resourceDiagnostics) ' give the name of any added modules, but not the name of the primary module. ReportManifestResourceDuplicates( moduleBuilder.ManifestResources, SourceAssembly.Modules.Skip(1).Select(Function(x) x.Name), AddedModulesResourceNames(resourceDiagnostics), resourceDiagnostics) If Not FilterAndAppendAndFreeDiagnostics(diagnostics, resourceDiagnostics, cancellationToken) Then Return False End If cancellationToken.ThrowIfCancellationRequested() ' Use a temporary bag so we don't have to refilter pre-existing diagnostics. Dim xmlDiagnostics = DiagnosticBag.GetInstance() Dim assemblyName = FileNameUtilities.ChangeExtension(outputNameOverride, extension:=Nothing) DocumentationCommentCompiler.WriteDocumentationCommentXml(Me, assemblyName, xmlDocStream, New BindingDiagnosticBag(xmlDiagnostics), cancellationToken) Return FilterAndAppendAndFreeDiagnostics(diagnostics, xmlDiagnostics, cancellationToken) End Function Private Iterator Function AddedModulesResourceNames(diagnostics As DiagnosticBag) As IEnumerable(Of String) Dim modules As ImmutableArray(Of ModuleSymbol) = SourceAssembly.Modules For i As Integer = 1 To modules.Length - 1 Dim m = DirectCast(modules(i), Symbols.Metadata.PE.PEModuleSymbol) Try For Each resource In m.Module.GetEmbeddedResourcesOrThrow() Yield resource.Name Next Catch mrEx As BadImageFormatException diagnostics.Add(ERRID.ERR_UnsupportedModule1, NoLocation.Singleton, m) End Try Next End Function Friend Overrides Function EmitDifference( baseline As EmitBaseline, edits As IEnumerable(Of SemanticEdit), isAddedSymbol As Func(Of ISymbol, Boolean), metadataStream As Stream, ilStream As Stream, pdbStream As Stream, testData As CompilationTestData, cancellationToken As CancellationToken) As EmitDifferenceResult Return EmitHelpers.EmitDifference( Me, baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, testData, cancellationToken) End Function Friend Function GetRuntimeMetadataVersion() As String Dim corLibrary = TryCast(Assembly.CorLibrary, Symbols.Metadata.PE.PEAssemblySymbol) Return If(corLibrary Is Nothing, String.Empty, corLibrary.Assembly.ManifestModule.MetadataVersion) End Function Friend Overrides Sub AddDebugSourceDocumentsForChecksumDirectives( documentsBuilder As DebugDocumentsBuilder, tree As SyntaxTree, diagnosticBag As DiagnosticBag) Dim checksumDirectives = tree.GetRoot().GetDirectives(Function(d) d.Kind = SyntaxKind.ExternalChecksumDirectiveTrivia AndAlso Not d.ContainsDiagnostics) For Each directive In checksumDirectives Dim checksumDirective As ExternalChecksumDirectiveTriviaSyntax = DirectCast(directive, ExternalChecksumDirectiveTriviaSyntax) Dim path = checksumDirective.ExternalSource.ValueText Dim checkSumText = checksumDirective.Checksum.ValueText Dim normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(path, basePath:=tree.FilePath) Dim existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath) If existingDoc IsNot Nothing Then ' directive matches a file path on an actual tree. ' Dev12 compiler just ignores the directive in this case which means that ' checksum of the actual tree always wins and no warning is given. ' We will continue doing the same. If existingDoc.IsComputedChecksum Then Continue For End If Dim sourceInfo = existingDoc.GetSourceInfo() If CheckSumMatches(checkSumText, sourceInfo.Checksum) Then Dim guid As Guid = guid.Parse(checksumDirective.Guid.ValueText) If guid = sourceInfo.ChecksumAlgorithmId Then ' all parts match, nothing to do Continue For End If End If ' did not match to an existing document ' produce a warning and ignore the directive diagnosticBag.Add(ERRID.WRN_MultipleDeclFileExtChecksum, New SourceLocation(checksumDirective), path) Else Dim newDocument = New DebugSourceDocument( normalizedPath, DebugSourceDocument.CorSymLanguageTypeBasic, MakeCheckSumBytes(checksumDirective.Checksum.ValueText), Guid.Parse(checksumDirective.Guid.ValueText)) documentsBuilder.AddDebugDocument(newDocument) End If Next End Sub Private Shared Function CheckSumMatches(bytesText As String, bytes As ImmutableArray(Of Byte)) As Boolean If bytesText.Length <> bytes.Length * 2 Then Return False End If For i As Integer = 0 To bytesText.Length \ 2 - 1 ' 1A in text becomes 0x1A Dim b As Integer = SyntaxFacts.IntegralLiteralCharacterValue(bytesText(i * 2)) * 16 + SyntaxFacts.IntegralLiteralCharacterValue(bytesText(i * 2 + 1)) If b <> bytes(i) Then Return False End If Next Return True End Function Private Shared Function MakeCheckSumBytes(bytesText As String) As ImmutableArray(Of Byte) Dim builder As ArrayBuilder(Of Byte) = ArrayBuilder(Of Byte).GetInstance() For i As Integer = 0 To bytesText.Length \ 2 - 1 ' 1A in text becomes 0x1A Dim b As Byte = CByte(SyntaxFacts.IntegralLiteralCharacterValue(bytesText(i * 2)) * 16 + SyntaxFacts.IntegralLiteralCharacterValue(bytesText(i * 2 + 1))) builder.Add(b) Next Return builder.ToImmutableAndFree() End Function Friend Overrides ReadOnly Property DebugSourceDocumentLanguageId As Guid Get Return DebugSourceDocument.CorSymLanguageTypeBasic End Get End Property Friend Overrides Function HasCodeToEmit() As Boolean For Each syntaxTree In SyntaxTrees Dim unit = syntaxTree.GetCompilationUnitRoot() If unit.Members.Count > 0 Then Return True End If Next Return False End Function #End Region #Region "Common Members" Protected Overrides Function CommonWithReferences(newReferences As IEnumerable(Of MetadataReference)) As Compilation Return WithReferences(newReferences) End Function Protected Overrides Function CommonWithAssemblyName(assemblyName As String) As Compilation Return WithAssemblyName(assemblyName) End Function Protected Overrides Function CommonWithScriptCompilationInfo(info As ScriptCompilationInfo) As Compilation Return WithScriptCompilationInfo(DirectCast(info, VisualBasicScriptCompilationInfo)) End Function Protected Overrides ReadOnly Property CommonAssembly As IAssemblySymbol Get Return Me.Assembly End Get End Property Protected Overrides ReadOnly Property CommonGlobalNamespace As INamespaceSymbol Get Return Me.GlobalNamespace End Get End Property Protected Overrides ReadOnly Property CommonOptions As CompilationOptions Get Return Options End Get End Property Protected Overrides Function CommonGetSemanticModel(syntaxTree As SyntaxTree, ignoreAccessibility As Boolean) As SemanticModel Return Me.GetSemanticModel(syntaxTree, ignoreAccessibility) End Function Protected Overrides ReadOnly Property CommonSyntaxTrees As ImmutableArray(Of SyntaxTree) Get Return Me.SyntaxTrees End Get End Property Protected Overrides Function CommonAddSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As Compilation Dim array = TryCast(trees, SyntaxTree()) If array IsNot Nothing Then Return Me.AddSyntaxTrees(array) End If If trees Is Nothing Then Throw New ArgumentNullException(NameOf(trees)) End If Return Me.AddSyntaxTrees(trees.Cast(Of SyntaxTree)()) End Function Protected Overrides Function CommonRemoveSyntaxTrees(trees As IEnumerable(Of SyntaxTree)) As Compilation Dim array = TryCast(trees, SyntaxTree()) If array IsNot Nothing Then Return Me.RemoveSyntaxTrees(array) End If If trees Is Nothing Then Throw New ArgumentNullException(NameOf(trees)) End If Return Me.RemoveSyntaxTrees(trees.Cast(Of SyntaxTree)()) End Function Protected Overrides Function CommonRemoveAllSyntaxTrees() As Compilation Return Me.RemoveAllSyntaxTrees() End Function Protected Overrides Function CommonReplaceSyntaxTree(oldTree As SyntaxTree, newTree As SyntaxTree) As Compilation Return Me.ReplaceSyntaxTree(oldTree, newTree) End Function Protected Overrides Function CommonWithOptions(options As CompilationOptions) As Compilation Return Me.WithOptions(DirectCast(options, VisualBasicCompilationOptions)) End Function Protected Overrides Function CommonContainsSyntaxTree(syntaxTree As SyntaxTree) As Boolean Return Me.ContainsSyntaxTree(syntaxTree) End Function Protected Overrides Function CommonGetAssemblyOrModuleSymbol(reference As MetadataReference) As ISymbol Return Me.GetAssemblyOrModuleSymbol(reference) End Function Protected Overrides Function CommonClone() As Compilation Return Me.Clone() End Function Protected Overrides ReadOnly Property CommonSourceModule As IModuleSymbol Get Return Me.SourceModule End Get End Property Private Protected Overrides Function CommonGetSpecialType(specialType As SpecialType) As INamedTypeSymbolInternal Return Me.GetSpecialType(specialType) End Function Protected Overrides Function CommonGetCompilationNamespace(namespaceSymbol As INamespaceSymbol) As INamespaceSymbol Return Me.GetCompilationNamespace(namespaceSymbol) End Function Protected Overrides Function CommonGetTypeByMetadataName(metadataName As String) As INamedTypeSymbol Return Me.GetTypeByMetadataName(metadataName) End Function Protected Overrides ReadOnly Property CommonScriptClass As INamedTypeSymbol Get Return Me.ScriptClass End Get End Property Protected Overrides Function CommonCreateErrorTypeSymbol(container As INamespaceOrTypeSymbol, name As String, arity As Integer) As INamedTypeSymbol Return New ExtendedErrorTypeSymbol( container.EnsureVbSymbolOrNothing(Of NamespaceOrTypeSymbol)(NameOf(container)), name, arity) End Function Protected Overrides Function CommonCreateErrorNamespaceSymbol(container As INamespaceSymbol, name As String) As INamespaceSymbol Return New MissingNamespaceSymbol( container.EnsureVbSymbolOrNothing(Of NamespaceSymbol)(NameOf(container)), name) End Function Protected Overrides Function CommonCreateArrayTypeSymbol(elementType As ITypeSymbol, rank As Integer, elementNullableAnnotation As NullableAnnotation) As IArrayTypeSymbol Return CreateArrayTypeSymbol(elementType.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(elementType)), rank) End Function Protected Overrides Function CommonCreateTupleTypeSymbol(elementTypes As ImmutableArray(Of ITypeSymbol), elementNames As ImmutableArray(Of String), elementLocations As ImmutableArray(Of Location), elementNullableAnnotations As ImmutableArray(Of NullableAnnotation)) As INamedTypeSymbol Dim typesBuilder = ArrayBuilder(Of TypeSymbol).GetInstance(elementTypes.Length) For i As Integer = 0 To elementTypes.Length - 1 typesBuilder.Add(elementTypes(i).EnsureVbSymbolOrNothing(Of TypeSymbol)($"{NameOf(elementTypes)}[{i}]")) Next 'no location for the type declaration Return TupleTypeSymbol.Create(locationOpt:=Nothing, elementTypes:=typesBuilder.ToImmutableAndFree(), elementLocations:=elementLocations, elementNames:=elementNames, compilation:=Me, shouldCheckConstraints:=False, errorPositions:=Nothing) End Function Protected Overrides Function CommonCreateTupleTypeSymbol( underlyingType As INamedTypeSymbol, elementNames As ImmutableArray(Of String), elementLocations As ImmutableArray(Of Location), elementNullableAnnotations As ImmutableArray(Of NullableAnnotation)) As INamedTypeSymbol Dim csharpUnderlyingTuple = underlyingType.EnsureVbSymbolOrNothing(Of NamedTypeSymbol)(NameOf(underlyingType)) Dim cardinality As Integer If Not csharpUnderlyingTuple.IsTupleCompatible(cardinality) Then Throw New ArgumentException(CodeAnalysisResources.TupleUnderlyingTypeMustBeTupleCompatible, NameOf(underlyingType)) End If elementNames = CheckTupleElementNames(cardinality, elementNames) CheckTupleElementLocations(cardinality, elementLocations) CheckTupleElementNullableAnnotations(cardinality, elementNullableAnnotations) Return TupleTypeSymbol.Create( locationOpt:=Nothing, tupleCompatibleType:=underlyingType.EnsureVbSymbolOrNothing(Of NamedTypeSymbol)(NameOf(underlyingType)), elementLocations:=elementLocations, elementNames:=elementNames, errorPositions:=Nothing) End Function Protected Overrides Function CommonCreatePointerTypeSymbol(elementType As ITypeSymbol) As IPointerTypeSymbol Throw New NotSupportedException(VBResources.ThereAreNoPointerTypesInVB) End Function Protected Overrides Function CommonCreateFunctionPointerTypeSymbol( returnType As ITypeSymbol, refKind As RefKind, parameterTypes As ImmutableArray(Of ITypeSymbol), parameterRefKinds As ImmutableArray(Of RefKind), callingConvention As System.Reflection.Metadata.SignatureCallingConvention, callingConventionTypes As ImmutableArray(Of INamedTypeSymbol)) As IFunctionPointerTypeSymbol Throw New NotSupportedException(VBResources.ThereAreNoFunctionPointerTypesInVB) End Function Protected Overrides Function CommonCreateNativeIntegerTypeSymbol(signed As Boolean) As INamedTypeSymbol Throw New NotSupportedException(VBResources.ThereAreNoNativeIntegerTypesInVB) End Function Protected Overrides Function CommonCreateAnonymousTypeSymbol( memberTypes As ImmutableArray(Of ITypeSymbol), memberNames As ImmutableArray(Of String), memberLocations As ImmutableArray(Of Location), memberIsReadOnly As ImmutableArray(Of Boolean), memberNullableAnnotations As ImmutableArray(Of CodeAnalysis.NullableAnnotation)) As INamedTypeSymbol Dim i = 0 For Each t In memberTypes t.EnsureVbSymbolOrNothing(Of TypeSymbol)($"{NameOf(memberTypes)}({i})") i = i + 1 Next Dim fields = ArrayBuilder(Of AnonymousTypeField).GetInstance() For i = 0 To memberTypes.Length - 1 Dim type = memberTypes(i) Dim name = memberNames(i) Dim loc = If(memberLocations.IsDefault, Location.None, memberLocations(i)) Dim isReadOnly = memberIsReadOnly.IsDefault OrElse memberIsReadOnly(i) fields.Add(New AnonymousTypeField(name, DirectCast(type, TypeSymbol), loc, isReadOnly)) Next Dim descriptor = New AnonymousTypeDescriptor( fields.ToImmutableAndFree(), Location.None, isImplicitlyDeclared:=False) Return Me.AnonymousTypeManager.ConstructAnonymousTypeSymbol(descriptor) End Function Protected Overrides ReadOnly Property CommonDynamicType As ITypeSymbol Get Throw New NotSupportedException(VBResources.ThereIsNoDynamicTypeInVB) End Get End Property Protected Overrides ReadOnly Property CommonObjectType As INamedTypeSymbol Get Return Me.ObjectType End Get End Property Protected Overrides Function CommonGetEntryPoint(cancellationToken As CancellationToken) As IMethodSymbol Return Me.GetEntryPoint(cancellationToken) End Function ''' <summary> ''' Return true if there is a source declaration symbol name that meets given predicate. ''' </summary> Public Overrides Function ContainsSymbolsWithName(predicate As Func(Of String, Boolean), Optional filter As SymbolFilter = SymbolFilter.TypeAndMember, Optional cancellationToken As CancellationToken = Nothing) As Boolean If predicate Is Nothing Then Throw New ArgumentNullException(NameOf(predicate)) End If If filter = SymbolFilter.None Then Throw New ArgumentException(VBResources.NoNoneSearchCriteria, NameOf(filter)) End If Return DeclarationTable.ContainsName(MergedRootDeclaration, predicate, filter, cancellationToken) End Function ''' <summary> ''' Return source declaration symbols whose name meets given predicate. ''' </summary> Public Overrides Function GetSymbolsWithName(predicate As Func(Of String, Boolean), Optional filter As SymbolFilter = SymbolFilter.TypeAndMember, Optional cancellationToken As CancellationToken = Nothing) As IEnumerable(Of ISymbol) If predicate Is Nothing Then Throw New ArgumentNullException(NameOf(predicate)) End If If filter = SymbolFilter.None Then Throw New ArgumentException(VBResources.NoNoneSearchCriteria, NameOf(filter)) End If Return New PredicateSymbolSearcher(Me, filter, predicate, cancellationToken).GetSymbolsWithName() End Function #Disable Warning RS0026 ' Do not add multiple public overloads with optional parameters ''' <summary> ''' Return true if there is a source declaration symbol name that matches the provided name. ''' This may be faster than <see cref="ContainsSymbolsWithName(Func(Of String, Boolean), ''' SymbolFilter, CancellationToken)"/> when predicate is just a simple string check. ''' <paramref name="name"/> is case insensitive. ''' </summary> Public Overrides Function ContainsSymbolsWithName(name As String, Optional filter As SymbolFilter = SymbolFilter.TypeAndMember, Optional cancellationToken As CancellationToken = Nothing) As Boolean If name Is Nothing Then Throw New ArgumentNullException(NameOf(name)) End If If filter = SymbolFilter.None Then Throw New ArgumentException(VBResources.NoNoneSearchCriteria, NameOf(filter)) End If Return DeclarationTable.ContainsName(MergedRootDeclaration, name, filter, cancellationToken) End Function Public Overrides Function GetSymbolsWithName(name As String, Optional filter As SymbolFilter = SymbolFilter.TypeAndMember, Optional cancellationToken As CancellationToken = Nothing) As IEnumerable(Of ISymbol) If name Is Nothing Then Throw New ArgumentNullException(NameOf(name)) End If If filter = SymbolFilter.None Then Throw New ArgumentException(VBResources.NoNoneSearchCriteria, NameOf(filter)) End If Return New NameSymbolSearcher(Me, filter, name, cancellationToken).GetSymbolsWithName() End Function #Enable Warning RS0026 ' Do not add multiple public overloads with optional parameters Friend Overrides Function IsUnreferencedAssemblyIdentityDiagnosticCode(code As Integer) As Boolean Select Case code Case ERRID.ERR_UnreferencedAssemblyEvent3, ERRID.ERR_UnreferencedAssembly3 Return True Case Else Return False End Select End Function #End Region Private MustInherit Class AbstractSymbolSearcher Private ReadOnly _cache As PooledDictionary(Of Declaration, NamespaceOrTypeSymbol) Private ReadOnly _compilation As VisualBasicCompilation Private ReadOnly _includeNamespace As Boolean Private ReadOnly _includeType As Boolean Private ReadOnly _includeMember As Boolean Private ReadOnly _cancellationToken As CancellationToken Public Sub New(compilation As VisualBasicCompilation, filter As SymbolFilter, cancellationToken As CancellationToken) _cache = PooledDictionary(Of Declaration, NamespaceOrTypeSymbol).GetInstance() _compilation = compilation _includeNamespace = (filter And SymbolFilter.Namespace) = SymbolFilter.Namespace _includeType = (filter And SymbolFilter.Type) = SymbolFilter.Type _includeMember = (filter And SymbolFilter.Member) = SymbolFilter.Member _cancellationToken = cancellationToken End Sub Protected MustOverride Function Matches(name As String) As Boolean Protected MustOverride Function ShouldCheckTypeForMembers(typeDeclaration As MergedTypeDeclaration) As Boolean Public Function GetSymbolsWithName() As IEnumerable(Of ISymbol) Dim result = New HashSet(Of ISymbol)() Dim spine = ArrayBuilder(Of MergedNamespaceOrTypeDeclaration).GetInstance() AppendSymbolsWithName(spine, _compilation.MergedRootDeclaration, result) spine.Free() _cache.Free() Return result End Function Private Sub AppendSymbolsWithName( spine As ArrayBuilder(Of MergedNamespaceOrTypeDeclaration), current As MergedNamespaceOrTypeDeclaration, [set] As HashSet(Of ISymbol)) If current.Kind = DeclarationKind.Namespace Then If _includeNamespace AndAlso Matches(current.Name) Then Dim container = GetSpineSymbol(spine) Dim symbol = GetSymbol(container, current) If symbol IsNot Nothing Then [set].Add(symbol) End If End If Else If _includeType AndAlso Matches(current.Name) Then Dim container = GetSpineSymbol(spine) Dim symbol = GetSymbol(container, current) If symbol IsNot Nothing Then [set].Add(symbol) End If End If If _includeMember Then Dim typeDeclaration = DirectCast(current, MergedTypeDeclaration) If ShouldCheckTypeForMembers(typeDeclaration) Then AppendMemberSymbolsWithName(spine, typeDeclaration, [set]) End If End If End If spine.Add(current) For Each child In current.Children Dim mergedNamespaceOrType = TryCast(child, MergedNamespaceOrTypeDeclaration) If mergedNamespaceOrType IsNot Nothing Then If _includeMember OrElse _includeType OrElse child.Kind = DeclarationKind.Namespace Then AppendSymbolsWithName(spine, mergedNamespaceOrType, [set]) End If End If Next spine.RemoveAt(spine.Count - 1) End Sub Private Sub AppendMemberSymbolsWithName( spine As ArrayBuilder(Of MergedNamespaceOrTypeDeclaration), mergedType As MergedTypeDeclaration, [set] As HashSet(Of ISymbol)) _cancellationToken.ThrowIfCancellationRequested() spine.Add(mergedType) Dim container As NamespaceOrTypeSymbol = Nothing For Each name In mergedType.MemberNames If Matches(name) Then container = If(container, GetSpineSymbol(spine)) If container IsNot Nothing Then [set].UnionWith(container.GetMembers(name)) End If End If Next spine.RemoveAt(spine.Count - 1) End Sub Private Function GetSpineSymbol(spine As ArrayBuilder(Of MergedNamespaceOrTypeDeclaration)) As NamespaceOrTypeSymbol If spine.Count = 0 Then Return Nothing End If Dim symbol = GetCachedSymbol(spine(spine.Count - 1)) If symbol IsNot Nothing Then Return symbol End If Dim current = TryCast(Me._compilation.GlobalNamespace, NamespaceOrTypeSymbol) For i = 1 To spine.Count - 1 current = GetSymbol(current, spine(i)) Next Return current End Function Private Function GetCachedSymbol(declaration As MergedNamespaceOrTypeDeclaration) As NamespaceOrTypeSymbol Dim symbol As NamespaceOrTypeSymbol = Nothing If Me._cache.TryGetValue(declaration, symbol) Then Return symbol End If Return Nothing End Function Private Function GetSymbol(container As NamespaceOrTypeSymbol, declaration As MergedNamespaceOrTypeDeclaration) As NamespaceOrTypeSymbol If container Is Nothing Then Return Me._compilation.GlobalNamespace End If Dim symbol = GetCachedSymbol(declaration) If symbol IsNot Nothing Then Return symbol End If If declaration.Kind = DeclarationKind.Namespace Then AddCache(container.GetMembers(declaration.Name).OfType(Of NamespaceOrTypeSymbol)()) Else AddCache(container.GetTypeMembers(declaration.Name)) End If Return GetCachedSymbol(declaration) End Function Private Sub AddCache(symbols As IEnumerable(Of NamespaceOrTypeSymbol)) For Each symbol In symbols Dim mergedNamespace = TryCast(symbol, MergedNamespaceSymbol) If mergedNamespace IsNot Nothing Then Me._cache(mergedNamespace.ConstituentNamespaces.OfType(Of SourceNamespaceSymbol).First().MergedDeclaration) = symbol Continue For End If Dim sourceNamespace = TryCast(symbol, SourceNamespaceSymbol) If sourceNamespace IsNot Nothing Then Me._cache(sourceNamespace.MergedDeclaration) = sourceNamespace Continue For End If Dim sourceType = TryCast(symbol, SourceMemberContainerTypeSymbol) If sourceType IsNot Nothing Then Me._cache(sourceType.TypeDeclaration) = sourceType End If Next End Sub End Class Private Class PredicateSymbolSearcher Inherits AbstractSymbolSearcher Private ReadOnly _predicate As Func(Of String, Boolean) Public Sub New( compilation As VisualBasicCompilation, filter As SymbolFilter, predicate As Func(Of String, Boolean), cancellationToken As CancellationToken) MyBase.New(compilation, filter, cancellationToken) _predicate = predicate End Sub Protected Overrides Function ShouldCheckTypeForMembers(current As MergedTypeDeclaration) As Boolean Return True End Function Protected Overrides Function Matches(name As String) As Boolean Return _predicate(name) End Function End Class Private Class NameSymbolSearcher Inherits AbstractSymbolSearcher Private ReadOnly _name As String Public Sub New( compilation As VisualBasicCompilation, filter As SymbolFilter, name As String, cancellationToken As CancellationToken) MyBase.New(compilation, filter, cancellationToken) _name = name End Sub Protected Overrides Function ShouldCheckTypeForMembers(current As MergedTypeDeclaration) As Boolean For Each typeDecl In current.Declarations If typeDecl.MemberNames.Contains(_name) Then Return True End If Next Return False End Function Protected Overrides Function Matches(name As String) As Boolean Return IdentifierComparison.Equals(_name, name) End Function End Class End Class End Namespace
sharwell/roslyn
src/Compilers/VisualBasic/Portable/Compilation/VisualBasicCompilation.vb
Visual Basic
mit
156,166
Imports Microsoft.Win32 Class MainWindow ''' <summary> ''' 打开包文件的打开框 ''' </summary> Public open_packups_file As New Microsoft.Win32.OpenFileDialog ''' <summary> ''' 打开源文件的打开框 ''' </summary> Public open_exe_file As New Microsoft.Win32.OpenFileDialog ''' <summary> ''' 打开ballance主文件文件的打开框 ''' </summary> Public open_ballance_dir As New Microsoft.Win32.OpenFileDialog ''' <summary> ''' 保存包文件的保存框 ''' </summary> Public save_packups_file As New Microsoft.Win32.SaveFileDialog ''' <summary> ''' cache要验证的md5,允许安装的文件的md5 ''' </summary> Public cache_md5 As String = "" ''' <summary> ''' 材质要验证的md5,允许安装的文件的md5 ''' </summary> Public material_md5 As String = "" ''' <summary> ''' 背景要验证的md5,允许安装的文件的md5 ''' </summary> Public background_md5 As String = "" ''' <summary> ''' 音效要验证的md5,允许安装的文件的md5 ''' </summary> Public wave_md5 As String = "" ''' <summary> ''' bgm要验证的md5,允许安装的文件的md5 ''' </summary> Public bgm_md5 As String = "" ''' <summary> ''' bml要验证的md5,允许安装的文件的md5 ''' </summary> Public bml_md5 As String = "" ''' <summary> ''' 关卡要验证的md5,允许安装的文件的md5 ''' </summary> Public level_md5 As String = "" ''' <summary> ''' Ballance路径,带\ ''' </summary> Public ballance_path As String = "" ''' <summary> ''' 选择文件 ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> Private Sub select_packups(sender As Object, e As RoutedEventArgs) For a = 1 To 7 Dim tabitem_linshi As TabItem = CType(tab_contorl.Items.Item(a), TabItem) If tabitem_linshi.IsSelected = True Then '区分分析,输入 If a = 7 Then open_exe_file.ShowDialog() If System.IO.File.Exists(open_exe_file.FileName) = True Then ui_bml_text.Text = open_exe_file.FileName End If Else open_packups_file.ShowDialog() If System.IO.File.Exists(open_packups_file.FileName) = True Then Select Case a Case 1 ui_cache_text.Text = open_packups_file.FileName Case 2 ui_material_text.Text = open_packups_file.FileName Case 3 ui_background_text.Text = open_packups_file.FileName Case 4 ui_wave_text.Text = open_packups_file.FileName Case 5 ui_bgm_text.Text = open_packups_file.FileName Case 6 ui_level_text.Text = open_packups_file.FileName End Select End If End If End If Next End Sub ''' <summary> ''' 部署 ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> Private Sub file_free(sender As Object, e As RoutedEventArgs) '等待窗口 Dim linshi = New Window_wait linshi.Owner = Me linshi.Show() For a = 1 To 7 Dim tabitem_linshi As TabItem = CType(tab_contorl.Items.Item(a), TabItem) If tabitem_linshi.IsSelected = True Then Select Case a Case 1 If System.IO.File.Exists(ui_cache_text.Text) = True Then Dim word_arr() As String = cache_md5.Split(",") Dim file_md5 As String = get_file_md5(ui_cache_text.Text) Dim yes As Boolean = False For b = 0 To word_arr.Count - 1 If word_arr(b) = file_md5 Then yes = True Exit For End If Next If yes = True Then Try '解压缩 Dim bbb As New ICSharpCode.SharpZipLib.Zip.FastZip bbb.ExtractZip(ui_cache_text.Text, Environment.CurrentDirectory & "\cache\", Nothing) MsgBox("部署成功", 64, "Ballance工具箱部署器") Catch ex As Exception MsgBox("该文件部署时发生错误,部署失败!" & vbCrLf & "原因:" & ex.Message & vbCrLf & "详细消息:" & vbCrLf & ex.StackTrace, 16, "Ballance工具箱部署器") End Try Else MsgBox("该文件不是有效的,所以无法部署!请确认其来源是否正确!", 16, "Ballance工具箱部署器") End If Else MsgBox("要部署的包文件不存在!", 16, "Ballance工具箱部署器") End If Case 2 If System.IO.File.Exists(ui_material_text.Text) = True Then Dim word_arr() As String = material_md5.Split(",") Dim file_md5 As String = get_file_md5(ui_material_text.Text) Dim yes As Boolean = False For b = 0 To word_arr.Count - 1 If word_arr(b) = file_md5 Then yes = True Exit For End If Next If yes = True Then System.IO.File.Delete(Environment.CurrentDirectory & "\system_nmo\normal_material.zip") System.IO.File.Copy(ui_material_text.Text, Environment.CurrentDirectory & "\system_nmo\normal_material.zip") MsgBox("部署成功", 64, "Ballance工具箱部署器") Else MsgBox("该文件不是有效的,所以无法部署!请确认其来源是否正确!", 16, "Ballance工具箱部署器") End If Else MsgBox("要部署的包文件不存在!", 16, "Ballance工具箱部署器") End If Case 3 If System.IO.File.Exists(ui_background_text.Text) = True Then Dim word_arr() As String = background_md5.Split(",") Dim file_md5 As String = get_file_md5(ui_background_text.Text) Dim yes As Boolean = False For b = 0 To word_arr.Count - 1 If word_arr(b) = file_md5 Then yes = True Exit For End If Next If yes = True Then System.IO.File.Delete(Environment.CurrentDirectory & "\system_nmo\normal_background.zip") System.IO.File.Copy(ui_background_text.Text, Environment.CurrentDirectory & "\system_nmo\normal_background.zip") MsgBox("部署成功", 64, "Ballance工具箱部署器") Else MsgBox("该文件不是有效的,所以无法部署!请确认其来源是否正确!", 16, "Ballance工具箱部署器") End If Else MsgBox("要部署的包文件不存在!", 16, "Ballance工具箱部署器") End If Case 4 If System.IO.File.Exists(ui_wave_text.Text) = True Then Dim word_arr() As String = wave_md5.Split(",") Dim file_md5 As String = get_file_md5(ui_wave_text.Text) Dim yes As Boolean = False For b = 0 To word_arr.Count - 1 If word_arr(b) = file_md5 Then yes = True Exit For End If Next If yes = True Then System.IO.File.Delete(Environment.CurrentDirectory & "\system_nmo\normal_wave.zip") System.IO.File.Copy(ui_wave_text.Text, Environment.CurrentDirectory & "\system_nmo\normal_wave.zip") MsgBox("部署成功", 64, "Ballance工具箱部署器") Else MsgBox("该文件不是有效的,所以无法部署!请确认其来源是否正确!", 16, "Ballance工具箱部署器") End If Else MsgBox("要部署的包文件不存在!", 16, "Ballance工具箱部署器") End If Case 5 If System.IO.File.Exists(ui_bgm_text.Text) = True Then Dim word_arr() As String = bgm_md5.Split(",") Dim file_md5 As String = get_file_md5(ui_bgm_text.Text) Dim yes As Boolean = False For b = 0 To word_arr.Count - 1 If word_arr(b) = file_md5 Then yes = True Exit For End If Next If yes = True Then System.IO.File.Delete(Environment.CurrentDirectory & "\system_nmo\normal_bgm.zip") System.IO.File.Copy(ui_bgm_text.Text, Environment.CurrentDirectory & "\system_nmo\normal_bgm.zip") MsgBox("部署成功", 64, "Ballance工具箱部署器") Else MsgBox("该文件不是有效的,所以无法部署!请确认其来源是否正确!", 16, "Ballance工具箱部署器") End If Else MsgBox("要部署的包文件不存在!", 16, "Ballance工具箱部署器") End If Case 6 If System.IO.File.Exists(ui_level_text.Text) = True Then Dim word_arr() As String = level_md5.Split(",") Dim file_md5 As String = get_file_md5(ui_level_text.Text) Dim yes As Boolean = False For b = 0 To word_arr.Count - 1 If word_arr(b) = file_md5 Then yes = True Exit For End If Next If yes = True Then Try '解压缩 Dim bbb As New ICSharpCode.SharpZipLib.Zip.FastZip '确认文件夹 If System.IO.Directory.Exists(Environment.CurrentDirectory & "\system_nmo\level") = False Then System.IO.Directory.CreateDirectory(Environment.CurrentDirectory & "\system_nmo\level") End If bbb.ExtractZip(ui_level_text.Text, Environment.CurrentDirectory & "\system_nmo\level\", Nothing) MsgBox("部署成功", 64, "Ballance工具箱部署器") Catch ex As Exception MsgBox("该文件部署时发生错误,部署失败!" & vbCrLf & "原因:" & ex.Message & vbCrLf & "详细消息:" & vbCrLf & ex.StackTrace, 16, "Ballance工具箱部署器") End Try Else MsgBox("该文件不是有效的,所以无法部署!请确认其来源是否正确!", 16, "Ballance工具箱部署器") End If Else MsgBox("要部署的包文件不存在!", 16, "Ballance工具箱部署器") End If Case 7 If System.IO.File.Exists(ui_bml_text.Text) = True Then Dim word_arr() As String = bml_md5.Split(",") Dim file_md5 As String = get_file_md5(ui_bml_text.Text) Dim yes As Boolean = False For b = 0 To word_arr.Count - 1 If word_arr(b) = file_md5 Then yes = True Exit For End If Next If yes = True Then System.IO.File.Delete(Environment.CurrentDirectory & "\system_nmo\bml_install.exe") System.IO.File.Copy(ui_bml_text.Text, Environment.CurrentDirectory & "\system_nmo\bml_install.exe") MsgBox("部署成功", 64, "Ballance工具箱部署器") Else MsgBox("该文件不是有效的,所以无法部署!请确认其来源是否正确!", 16, "Ballance工具箱部署器") End If Else MsgBox("要部署的包文件不存在!", 16, "Ballance工具箱部署器") End If End Select End If Next linshi.Close() End Sub ''' <summary> ''' 获取文件的md5 ''' </summary> ''' <param name="filename">文件路径</param> ''' <returns></returns> Public Function get_file_md5(ByVal filename As String) Try Dim file As System.IO.FileStream = New System.IO.FileStream(filename, IO.FileMode.Open, IO.FileAccess.Read) Dim md5 As System.Security.Cryptography.MD5 = New System.Security.Cryptography.MD5CryptoServiceProvider Dim retval As Byte() = md5.ComputeHash(file) file.Close() Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder For i = 0 To retval.Length - 1 sb.Append(retval(i).ToString("x2")) Next Return sb.ToString Catch ex As Exception Return "" End Try End Function ''' <summary> ''' 应用启动 ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> Private Sub app_start(sender As Object, e As RoutedEventArgs) If System.IO.File.Exists(Environment.CurrentDirectory & "\ballance_tools.exe") = False Then MsgBox("该程序在错误的目录执行,请确保本程序在ballance_tools的根目录运行!", 16, "Ballance工具箱部署器") Environment.Exit(1) End If If System.IO.Directory.Exists(Environment.CurrentDirectory & "\system_nmo") = False Then MsgBox("该程序在错误的目录执行,请确保本程序在ballance_tools的根目录运行!", 16, "Ballance工具箱部署器") Environment.Exit(1) End If app_init_reg() open_packups_file.Filter = "ZIP包文件|*.zip" open_exe_file.Filter = "源文件/可执行程序|*.exe" save_packups_file.Filter = "ZIP包文件|*.zip" End Sub ''' <summary> ''' 设置保存的zip文件地址 ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> Private Sub set_save_zip_path(sender As Object, e As RoutedEventArgs) For a = 1 To 6 Dim tabitem_linshi As TabItem = CType(tab_contorl_pack.Items.Item(a), TabItem) If tabitem_linshi.IsSelected = True Then Select Case a Case 1 save_packups_file.Filter = "材质包文件(*.bab)|*.bab" Case 2 save_packups_file.Filter = "背景包文件(*.bbb)|*.bbb" Case 3 save_packups_file.Filter = "BGM包文件(*.bgb)|*.bgb" Case 4 save_packups_file.Filter = "音效包文件(*.bwb)|*.bwb" Case 5 save_packups_file.Filter = "Mod包文件(*.bob)|*.bob" Case 6 save_packups_file.Filter = "模型包文件(*.bpb)|*.bpb" End Select save_packups_file.ShowDialog() Select Case a Case 1 ui_pack_material_text.Text = save_packups_file.FileName Case 2 ui_pack_background_text.Text = save_packups_file.FileName Case 3 ui_pack_bgm_text.Text = save_packups_file.FileName Case 4 ui_pack_wave_text.Text = save_packups_file.FileName Case 5 ui_pack_mod_text.Text = save_packups_file.FileName Case 6 ui_pack_ph_text.Text = save_packups_file.FileName End Select End If Next End Sub ''' <summary> ''' 打包文件 ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> Private Sub save_zip_pack(sender As Object, e As RoutedEventArgs) '等待窗口 Dim linshi = New Window_wait linshi.Owner = Me linshi.Show() For a = 1 To 6 Dim tabitem_linshi As TabItem = CType(tab_contorl_pack.Items.Item(a), TabItem) If tabitem_linshi.IsSelected = True Then Select Case a Case 1 If ui_pack_material_text.Text = "" Then MsgBox("未填写输出包地址,无法打包!", 16, "Ballance工具箱部署器") linshi.Close() Exit Sub End If Try Dim aaa As New ICSharpCode.SharpZipLib.Zip.FastZip aaa.CreateZip(ui_pack_material_text.Text, ballance_path & "Textures", False, "") MsgBox("打包成功", 64, "Ballance工具箱部署器") Catch ex As Exception MsgBox("该文件打包时发生错误,打包失败!" & vbCrLf & "原因:" & ex.Message & vbCrLf & "详细消息:" & vbCrLf & ex.StackTrace, 16, "Ballance工具箱部署器") linshi.Close() Exit Sub End Try Case 2 If ui_pack_background_text.Text = "" Then MsgBox("未填写输出包地址,无法打包!", 16, "Ballance工具箱部署器") linshi.Close() Exit Sub End If System.IO.File.Move(ballance_path & "Textures\Sky\Sky_" & Mid(ui_pack_background_group.Text, 6, 1) & "_Back.BMP", ballance_path & "Textures\Sky\Sky_Back.new") System.IO.File.Move(ballance_path & "Textures\Sky\Sky_" & Mid(ui_pack_background_group.Text, 6, 1) & "_Down.BMP", ballance_path & "Textures\Sky\Sky_Down.new") System.IO.File.Move(ballance_path & "Textures\Sky\Sky_" & Mid(ui_pack_background_group.Text, 6, 1) & "_Front.BMP", ballance_path & "Textures\Sky\Sky_Front.new") System.IO.File.Move(ballance_path & "Textures\Sky\Sky_" & Mid(ui_pack_background_group.Text, 6, 1) & "_Left.BMP", ballance_path & "Textures\Sky\Sky_Left.new") System.IO.File.Move(ballance_path & "Textures\Sky\Sky_" & Mid(ui_pack_background_group.Text, 6, 1) & "_Right.BMP", ballance_path & "Textures\Sky\Sky_Right.new") Try Dim aaa As New ICSharpCode.SharpZipLib.Zip.FastZip aaa.CreateZip(ui_pack_material_text.Text, ballance_path & "Textures\Sky", False, "new") MsgBox("打包成功", 64, "Ballance工具箱部署器") Catch ex As Exception MsgBox("该文件打包时发生错误,打包失败!" & vbCrLf & "原因:" & ex.Message & vbCrLf & "详细消息:" & vbCrLf & ex.StackTrace, 16, "Ballance工具箱部署器") System.IO.File.Move(ballance_path & "Textures\Sky\Sky_Back.new", ballance_path & "Textures\Sky\Sky_" & Mid(ui_pack_background_group.Text, 6, 1) & "_Back.BMP") System.IO.File.Move(ballance_path & "Textures\Sky\Sky_Down.new", ballance_path & "Textures\Sky\Sky_" & Mid(ui_pack_background_group.Text, 6, 1) & "_Down.BMP") System.IO.File.Move(ballance_path & "Textures\Sky\Sky_Front.new", ballance_path & "Textures\Sky\Sky_" & Mid(ui_pack_background_group.Text, 6, 1) & "_Front.BMP") System.IO.File.Move(ballance_path & "Textures\Sky\Sky_Left.new", ballance_path & "Textures\Sky\Sky_" & Mid(ui_pack_background_group.Text, 6, 1) & "_Left.BMP") System.IO.File.Move(ballance_path & "Textures\Sky\Sky_Right.new", ballance_path & "Textures\Sky\Sky_" & Mid(ui_pack_background_group.Text, 6, 1) & "_Right.BMP") linshi.Close() Exit Sub End Try System.IO.File.Move(ballance_path & "Textures\Sky\Sky_Back.new", ballance_path & "Textures\Sky\Sky_" & Mid(ui_pack_background_group.Text, 6, 1) & "_Back.BMP") System.IO.File.Move(ballance_path & "Textures\Sky\Sky_Down.new", ballance_path & "Textures\Sky\Sky_" & Mid(ui_pack_background_group.Text, 6, 1) & "_Down.BMP") System.IO.File.Move(ballance_path & "Textures\Sky\Sky_Front.new", ballance_path & "Textures\Sky\Sky_" & Mid(ui_pack_background_group.Text, 6, 1) & "_Front.BMP") System.IO.File.Move(ballance_path & "Textures\Sky\Sky_Left.new", ballance_path & "Textures\Sky\Sky_" & Mid(ui_pack_background_group.Text, 6, 1) & "_Left.BMP") System.IO.File.Move(ballance_path & "Textures\Sky\Sky_Right.new", ballance_path & "Textures\Sky\Sky_" & Mid(ui_pack_background_group.Text, 6, 1) & "_Right.BMP") Case 3 If ui_pack_bgm_text.Text = "" Then MsgBox("未填写输出包地址,无法打包!", 16, "Ballance工具箱部署器") linshi.Close() Exit Sub End If For d = 1 To 3 For f = 1 To 3 System.IO.File.Move(ballance_path & "Sounds\Music_Theme_" & d.ToString & "_" & f.ToString & ".wav", ballance_path & "Sounds\Music_Theme_" & d.ToString & "_" & f.ToString & ".new") Next Next Try Dim aaa As New ICSharpCode.SharpZipLib.Zip.FastZip aaa.CreateZip(ui_pack_material_text.Text, ballance_path & "Sounds", False, "new") MsgBox("打包成功", 64, "Ballance工具箱部署器") Catch ex As Exception MsgBox("该文件打包时发生错误,打包失败!" & vbCrLf & "原因:" & ex.Message & vbCrLf & "详细消息:" & vbCrLf & ex.StackTrace, 16, "Ballance工具箱部署器") For d = 1 To 3 For f = 1 To 3 System.IO.File.Move(ballance_path & "Sounds\Music_Theme_" & d.ToString & "_" & f.ToString & ".new", ballance_path & "Sounds\Music_Theme_" & d.ToString & "_" & f.ToString & ".wav") Next Next linshi.Close() Exit Sub End Try For d = 1 To 3 For f = 1 To 3 System.IO.File.Move(ballance_path & "Sounds\Music_Theme_" & d.ToString & "_" & f.ToString & ".new", ballance_path & "Sounds\Music_Theme_" & d.ToString & "_" & f.ToString & ".wav") Next Next Case 4 If ui_pack_wave_text.Text = "" Then MsgBox("未填写输出包地址,无法打包!", 16, "Ballance工具箱部署器") linshi.Close() Exit Sub End If For d = 1 To 3 For f = 1 To 3 System.IO.File.Move(ballance_path & "Sounds\Music_Theme_" & d.ToString & "_" & f.ToString & ".wav", ballance_path & "Sounds\Music_Theme_" & d.ToString & "_" & f.ToString & ".new") Next Next Try Dim aaa As New ICSharpCode.SharpZipLib.Zip.FastZip aaa.CreateZip(ui_pack_material_text.Text, ballance_path & "Sounds", False, "wav") MsgBox("打包成功", 64, "Ballance工具箱部署器") Catch ex As Exception MsgBox("该文件打包时发生错误,打包失败!" & vbCrLf & "原因:" & ex.Message & vbCrLf & "详细消息:" & vbCrLf & ex.StackTrace, 16, "Ballance工具箱部署器") For d = 1 To 3 For f = 1 To 3 System.IO.File.Move(ballance_path & "Sounds\Music_Theme_" & d.ToString & "_" & f.ToString & ".new", ballance_path & "Sounds\Music_Theme_" & d.ToString & "_" & f.ToString & ".wav") Next Next linshi.Close() Exit Sub End Try For d = 1 To 3 For f = 1 To 3 System.IO.File.Move(ballance_path & "Sounds\Music_Theme_" & d.ToString & "_" & f.ToString & ".new", ballance_path & "Sounds\Music_Theme_" & d.ToString & "_" & f.ToString & ".wav") Next Next Case 5 If ui_pack_mod_text.Text = "" Then MsgBox("未填写输出包地址,无法打包!", 16, "Ballance工具箱部署器") linshi.Close() Exit Sub End If If System.IO.File.Exists(ballance_path & "ModLoader\ModLoader.nmo") = True Then Try Dim aaa As New ICSharpCode.SharpZipLib.Zip.FastZip aaa.CreateZip(ui_pack_material_text.Text, ballance_path & "ModLoader\Mods", False, "nmo") MsgBox("打包成功", 64, "Ballance工具箱部署器") Catch ex As Exception MsgBox("该文件打包时发生错误,打包失败!" & vbCrLf & "原因:" & ex.Message & vbCrLf & "详细消息:" & vbCrLf & ex.StackTrace, 16, "Ballance工具箱部署器") linshi.Close() Exit Sub End Try Else MsgBox("无法打包,因为你当前未安装BML,所以没有任何Mod可以打包", 16, "Ballance工具箱部署器") linshi.Close() Exit Sub End If Case 6 If ui_pack_ph_text.Text = "" Then MsgBox("未填写输出包地址,无法打包!", 16, "Ballance工具箱部署器") linshi.Close() Exit Sub End If Try Dim aaa As New ICSharpCode.SharpZipLib.Zip.FastZip aaa.CreateZip(ui_pack_material_text.Text, ballance_path & "3D Entities\PH", False, "nmo") MsgBox("打包成功", 64, "Ballance工具箱部署器") Catch ex As Exception MsgBox("该文件打包时发生错误,打包失败!" & vbCrLf & "原因:" & ex.Message & vbCrLf & "详细消息:" & vbCrLf & ex.StackTrace, 16, "Ballance工具箱部署器") linshi.Close() Exit Sub End Try End Select '是否需要验证md5 If MsgBox("确认需要输出包文件的MD5?这在你以后提交该文件验证时会有用", 32 + 1, "Ballance工具箱部署器") = 1 Then Dim md5_word As String = "" Select Case a Case 1 md5_word = get_file_md5(ui_pack_material_text.Text) Case 2 md5_word = get_file_md5(ui_pack_background_text.Text) Case 3 md5_word = get_file_md5(ui_pack_bgm_text.Text) Case 4 md5_word = get_file_md5(ui_pack_wave_text.Text) Case 5 md5_word = get_file_md5(ui_pack_mod_text.Text) Case 6 md5_word = get_file_md5(ui_pack_ph_text.Text) End Select MsgBox("文件的MD5为" & vbCrLf & md5_word, 64, "Ballance工具箱部署器") End If End If Next linshi.Close() End Sub Public Sub app_init_reg() '读取注册表 Dim Key As RegistryKey = Registry.LocalMachine Dim b_full_screen As RegistryKey Dim info As String = "" Try If Environment.Is64BitOperatingSystem = True Then '64位系统 b_full_screen = Key.OpenSubKey("SOFTWARE\Wow6432Node\ballance\Settings", True) Else '32位 b_full_screen = Key.OpenSubKey("SOFTWARE\ballance\Settings", True) End If '地址 If ballance_path = "" Then info = b_full_screen.GetValue("TargetDir").ToString '解决多行字符串读不出来的问题 If info = "System.String[]" Then '是multi_sz字符串读不出来 Dim ccc As String() = CType(b_full_screen.GetValue("TargetDir"), String()) info = ccc.GetValue(0).ToString() End If If Mid(info, info.Length, 1) <> "\" Then info = info & "\" End If ballance_path = info End If Catch ex As Exception '错误意味着没有注册表项,默认一切,只写部分写注册表 Dim b_full_screen_2 As RegistryKey Dim b_full_screen_3 As RegistryKey If Environment.Is64BitOperatingSystem = True Then '64位系统 b_full_screen_2 = Key.CreateSubKey("SOFTWARE\Wow6432Node\ballance") b_full_screen_2 = Key.CreateSubKey("SOFTWARE\Wow6432Node\ballance\Settings") b_full_screen_3 = Key.OpenSubKey("SOFTWARE\Wow6432Node\ballance\Settings", True) b_full_screen_3.SetValue("Fullscreen", "1", RegistryValueKind.DWord) Else '32位 b_full_screen_2 = Key.CreateSubKey("SOFTWARE\ballance") b_full_screen_2 = Key.CreateSubKey("SOFTWARE\ballance\Settings") b_full_screen_3 = Key.OpenSubKey("SOFTWARE\ballance\Settings", True) b_full_screen_3.SetValue("Fullscreen", "1", RegistryValueKind.DWord) End If End Try open_ballance_dir.Filter = "Ballance主启动程序|Startup.exe" open_ballance_dir.Title = "选择你安装的Ballance的主启动程序Startup.exe" If ballance_path = "" Then '没有读到地址 MsgBox("没有找到Ballance的安装位置,请选择你安装的Ballance的主启动程序Startup.exe(位于 Ballance安装目录 下)", MsgBoxStyle.Exclamation, "Ballance工具箱部署器") open_ballance_dir.ShowDialog() If open_ballance_dir.FileName <> "" Then Dim info_2 As String = "" info_2 = open_ballance_dir.FileName info_2 = Mid(info_2, 1, info_2.Length - 11) If Mid(info_2, info_2.Length, 1) <> "\" Then info_2 = info_2 & "\" End If ballance_path = info_2 Else MsgBox("您必须选择Ballance主启动程序Startup.exe,否则这将无法开启工具箱部署器,现在程序即将退出!", 16, "Ballance工具箱部署器") Environment.Exit(1) End If If Environment.Is64BitOperatingSystem = True Then '64位系统 b_full_screen = Key.OpenSubKey("SOFTWARE\Wow6432Node\ballance\Settings", True) Else '32位 b_full_screen = Key.OpenSubKey("SOFTWARE\ballance\Settings", True) End If b_full_screen.SetValue("TargetDir", Mid(ballance_path, 1, ballance_path.Length - 1), RegistryValueKind.String) End If Key.Dispose() End Sub ''' <summary> ''' 选择背景编号 ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> Private Sub ui_pack_background_select(sender As Object, e As RoutedEventArgs) Dim aaa As New ui_depend_window_select_item_list ui_connect_window_select_item_list.Clear() ui_connect_window_select_item_list_select_index = 0 aaa.pro_title = "序号A" aaa.pro_text = "第 3 关背景" ui_connect_window_select_item_list.Add(aaa) aaa = New ui_depend_window_select_item_list aaa.pro_title = "序号B" aaa.pro_text = "第 10 关背景" ui_connect_window_select_item_list.Add(aaa) aaa = New ui_depend_window_select_item_list aaa.pro_title = "序号C" aaa.pro_text = "第 5 关背景" ui_connect_window_select_item_list.Add(aaa) aaa = New ui_depend_window_select_item_list aaa.pro_title = "序号D" aaa.pro_text = "第 7 关背景" ui_connect_window_select_item_list.Add(aaa) aaa = New ui_depend_window_select_item_list aaa.pro_title = "序号E" aaa.pro_text = "第 2 关背景" ui_connect_window_select_item_list.Add(aaa) aaa = New ui_depend_window_select_item_list aaa.pro_title = "序号F" aaa.pro_text = "第 13 关背景" ui_connect_window_select_item_list.Add(aaa) aaa = New ui_depend_window_select_item_list aaa.pro_title = "序号G" aaa.pro_text = "第 8 关背景" ui_connect_window_select_item_list.Add(aaa) aaa = New ui_depend_window_select_item_list aaa.pro_title = "序号H" aaa.pro_text = "第 6 关背景" ui_connect_window_select_item_list.Add(aaa) aaa = New ui_depend_window_select_item_list aaa.pro_title = "序号I" aaa.pro_text = "第 12 关背景" ui_connect_window_select_item_list.Add(aaa) aaa = New ui_depend_window_select_item_list aaa.pro_title = "序号J" aaa.pro_text = "第 11 关背景" ui_connect_window_select_item_list.Add(aaa) aaa = New ui_depend_window_select_item_list aaa.pro_title = "序号K" aaa.pro_text = "第 9 关背景" ui_connect_window_select_item_list.Add(aaa) aaa = New ui_depend_window_select_item_list aaa.pro_title = "序号L" aaa.pro_text = "第 1 关背景" ui_connect_window_select_item_list.Add(aaa) '显示对话框 Dim linshi = New Window_select_item ui_connect_window_select_item_list_select_index = -1 linshi.Owner = Me linshi.ShowDialog() '安装 If ui_connect_window_select_item_list_select_index <> -1 Then '处理文件 Dim bk_list As String = "" Select Case ui_connect_window_select_item_list_select_index Case 0 bk_list = "A" Case 1 bk_list = "B" Case 2 bk_list = "C" Case 3 bk_list = "D" Case 4 bk_list = "E" Case 5 bk_list = "F" Case 6 bk_list = "G" Case 7 bk_list = "H" Case 8 bk_list = "I" Case 9 bk_list = "J" Case 10 bk_list = "K" Case 11 bk_list = "L" Case Else MsgBox("发生错误", 16, "Ballance工具箱部署器") Exit Sub End Select ui_pack_background_group.Text = "保存编号:" & bk_list End If End Sub End Class
yyc12345/ballance_tools
ballance_tools_deploy/MainWindow.xaml.vb
Visual Basic
mit
39,949
Public Class FormMain Public Shared ReadOnly DocumentationBase As String = "https://netoffice.io/documentation/" Public Sub New() InitializeComponent() Me.Text = "NetOffice Tutorials in VB" LoadTutorials() End Sub Private Sub LoadTutorials() LoadTutorial(New Tutorial01()) LoadTutorial(New Tutorial02()) LoadTutorial(New Tutorial03()) LoadTutorial(New Tutorial04()) LoadTutorial(New Tutorial05()) LoadTutorial(New Tutorial06()) LoadTutorial(New Tutorial07()) LoadTutorial(New Tutorial08()) LoadTutorial(New Tutorial09()) LoadTutorial(New Tutorial10()) LoadTutorial(New Tutorial11()) LoadTutorial(New Tutorial12()) LoadTutorial(New Tutorial13()) LoadTutorial(New Tutorial14()) LoadTutorial(New Tutorial15()) LoadTutorial(New Tutorial16()) LoadTutorial(New Tutorial17()) End Sub End Class
NetOfficeFw/NetOffice
Tutorials/VB/Tutorials/FormMain.vb
Visual Basic
mit
978
'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 System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("")> <Assembly: AssemblyCopyright("")> <Assembly: AssemblyTrademark("")> <Assembly: CLSCompliant(True)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("E76C5B64-185C-47F3-961E-8580EFE55A5C")> ' 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.*")>
Esri/arcobjects-sdk-community-samples
Net/Controls/ControlsCommandsFeatureEditing/VBNet/AssemblyInfo.vb
Visual Basic
apache-2.0
1,568
Imports System.Text Imports System.Xml Imports System.Xml.Serialization Imports System.Xml.XPath Imports System.Text.RegularExpressions <Assembly: CLSCompliant(True)> <CLSCompliant(True)> _ Public Class Xml #Region "Declarations" Public Shared Event OnError(ByVal sender As Object, ByVal e As Protean.Tools.Errors.ErrorEventArgs) Private Const mcModuleName As String = "Protean.Tools.Xml" Public Enum XmlDataType TypeString = 1 TypeNumber = 2 TypeDate = 3 End Enum Public Enum XmlNodeState NotInstantiated = 0 IsEmpty = 1 HasContents = 2 IsEmptyOrHasContents = 3 End Enum #End Region #Region "Private Procedures" Private Shared Sub CombineInstance_Sub1(ByRef oMasterElmt As XmlElement, ByVal oExistingInstance As XmlElement, ByVal cXPath As String) 'Looks for stuff with the same xpath Try If Not cXPath = "" Then cXPath = cXPath & "/" cXPath &= oMasterElmt.Name Dim oInstanceElmt As XmlElement = oExistingInstance.SelectSingleNode(cXPath) If Not oInstanceElmt Is Nothing Then 'Master Attributes first For i As Integer = 0 To oMasterElmt.Attributes.Count - 1 Dim oMasterAtt As XmlAttribute = oMasterElmt.Attributes(i) Dim oInstanceAtt As XmlAttribute = oInstanceElmt.Attributes.ItemOf(oMasterAtt.Name) If Not oInstanceAtt Is Nothing Then oMasterAtt.Value = oInstanceAtt.Value Next 'Now Existing For i As Integer = 0 To oInstanceElmt.Attributes.Count - 1 Dim oInstanceAtt As XmlAttribute = oInstanceElmt.Attributes(i) Dim oMasterAtt As XmlAttribute = oMasterElmt.Attributes.ItemOf(oInstanceAtt.Name) If oMasterAtt Is Nothing Then oMasterElmt.SetAttribute(oInstanceAtt.Name, oInstanceAtt.Value) Next 'Now we need to check child nodes If oMasterElmt.SelectNodes("*").Count > 0 Then For Each oChild As XmlElement In oMasterElmt.SelectNodes("*") CombineInstance_Sub1(oChild, oExistingInstance, cXPath) Next ElseIf oInstanceElmt.SelectNodes("*").Count > 0 Then For Each oChild As XmlElement In oInstanceElmt.SelectNodes("*") oMasterElmt.AppendChild(oMasterElmt.OwnerDocument.ImportNode(oChild, True)) Next CombineInstance_MarkSubElmts(oInstanceElmt) ElseIf Not oInstanceElmt.InnerText = "" Then oMasterElmt.InnerText = oInstanceElmt.InnerText End If 'now mark both elements as found oMasterElmt.SetAttribute("ewCombineInstanceFound", "TRUE") oInstanceElmt.SetAttribute("ewCombineInstanceFound", "TRUE") 'We wont go for others just yet as we want to complete this before finding 'other less obvious stuff End If Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "CombineInstance_Sub1", ex, "")) End Try End Sub Private Shared Sub CombineInstance_Sub2(ByRef oExisting As XmlElement, ByVal oMasterInstance As XmlElement, ByVal cRootName As String) 'Gets any unmarked in Existing data and copies over to new Try Dim cXPath As String = "" CombineInstance_GetXPath(oExisting, cXPath, cRootName) Dim oParts() As String = Split(cXPath, "/") Dim oRefPart As XmlElement = oMasterInstance For i As Integer = 0 To oParts.Length - 2 If Not oRefPart.SelectSingleNode(oParts(i)) Is Nothing Then oRefPart = oRefPart.SelectSingleNode(oParts(i)) Else Dim oElmt As XmlElement = oMasterInstance.OwnerDocument.CreateElement(oParts(i)) oRefPart.AppendChild(oElmt) oRefPart = oElmt End If Next 'still need to create last part oRefPart.AppendChild(oMasterInstance.OwnerDocument.ImportNode(oExisting, True)) CombineInstance_MarkSubElmts(oExisting) Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "CombineInstance_Sub2", ex, "")) End Try End Sub Private Shared Sub CombineInstance_GetXPath(ByVal oElmt As XmlElement, ByRef xPath As String, ByVal cRootName As String) Try If xPath = "" Then xPath = oElmt.Name If Not oElmt.ParentNode Is Nothing Then If Not oElmt.ParentNode.Name = cRootName Then xPath = oElmt.ParentNode.Name & "/" & xPath CombineInstance_GetXPath(oElmt.ParentNode, xPath, cRootName) End If End If Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "CombineInstance_GetXPath", ex, "")) End Try End Sub Private Shared Sub CombineInstance_MarkSubElmts(ByRef oElmt As XmlElement, Optional ByVal bRemove As Boolean = False) Try If bRemove Then oElmt.RemoveAttribute("ewCombineInstanceFound") Else oElmt.SetAttribute("ewCombineInstanceFound", "TRUE") End If For Each oChild As XmlElement In oElmt.SelectNodes("*") CombineInstance_MarkSubElmts(oChild, bRemove) Next Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "CombineInstance_MarkSubElmts", ex, "")) End Try End Sub #End Region #Region "Public Functions" Public Shared Function SortedNodeList_UNCONNECTED(ByVal oRootObject As XmlElement, ByVal cXPath As String, ByVal cSortItem As String, ByVal cSortOrder As XmlSortOrder, ByVal cSortDataType As XmlDataType, ByVal cCaseOrder As XmlCaseOrder) As XmlNodeList Dim oElmt As XmlElement = oRootObject.OwnerDocument.CreateElement("List") Try Dim oNavigator As XPathNavigator = oRootObject.CreateNavigator() Dim oExpression As XPathExpression = oNavigator.Compile(cXPath) oExpression.AddSort(cSortItem, cSortOrder, cCaseOrder, "", cSortDataType) Dim oIterator As XPathNodeIterator = oNavigator.Select(oExpression) Do Until Not oIterator.MoveNext oElmt.InnerXml &= oIterator.Current.OuterXml Loop Return oElmt.ChildNodes Catch ex As Exception Return oElmt.ChildNodes End Try End Function Public Shared Function XmlToForm(ByVal sString As String) As String Dim sProcessInfo As String = "" Try sString = Replace(sString, "<", "&lt;") sString = Replace(sString, ">", "&gt;") Return sString & "" Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "XmlToForm", ex, "")) Return "" End Try End Function Public Shared Function htmlToXmlDoc(ByVal shtml As String) As XmlDocument Dim oXmlDoc As New XmlDocument Dim sProcessInfo As String = "" Try shtml = Replace(shtml, "<!DOCTYPE html public shared ""-//W3C//DTD XHTML 1.1//EN"" ""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"">", "") shtml = Replace(shtml, " Xmlns = ""http://www.w3.org/1999/xhtml""", "") shtml = Replace(shtml, " Xmlns=""http://www.w3.org/1999/xhtml""", "") shtml = Replace(shtml, " Xml:lang=""""", "") oXmlDoc.LoadXml(shtml) Return oXmlDoc Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "htmlToXmlDoc", ex, "")) Return Nothing End Try End Function Public Shared Function getNsMgr(ByRef oNode As XmlNode, ByRef oXml As XmlDocument) As XmlNamespaceManager Try Dim oElmt As XmlElement Dim cNsUri As String = "" Dim nsMgr As XmlNamespaceManager = New XmlNamespaceManager(oXml.NameTable) 'does the instance have a namespace, if so give it a standard prefix of EWS oElmt = oNode If Not oElmt Is Nothing Then cNsUri = oElmt.GetAttribute("Xmlns") If cNsUri = "" Then cNsUri = oElmt.GetAttribute("xmlns") End If End If If cNsUri <> "" Then nsMgr.AddNamespace("ews", cNsUri) End If Return nsMgr Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "getNsMgr", ex, "")) Return Nothing End Try End Function Public Shared Function getNsMgrWithURI(ByRef oNode As XmlNode, ByRef oXml As XmlDocument) As XmlNamespaceManager Dim oElmt As XmlElement Dim cNsUri As String Try Dim nsMgr As XmlNamespaceManager = New XmlNamespaceManager(oXml.NameTable) 'does the instance have a namespace, if so give it a standard prefix of EWS oElmt = oNode cNsUri = oElmt.GetAttribute("xmlns") If cNsUri <> "" Then nsMgr.AddNamespace("ews", cNsUri) ElseIf oElmt.NamespaceURI <> "" Then nsMgr.AddNamespace("ews", oElmt.NamespaceURI) End If Return nsMgr Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "getNsMgrWithURI", ex, "")) Return Nothing End Try End Function Public Shared Function getNsMgrRecursive(ByRef oNode As XmlNode, ByRef oXml As XmlDocument) As XmlNamespaceManager Try Dim oElmt As XmlElement Dim cNsUri As String = "" Dim nsMgr As XmlNamespaceManager = New XmlNamespaceManager(oXml.NameTable) Dim cPrefix As String = "ews" 'does the instance have a namespace? if so give it a standard prefix of EWS 'If a subnode of the instance has a namespace we give it a prefix of ews2 'allows us to specifiy ews2 in bind paths. For Each oElmt In oNode.SelectNodes("descendant-or-self::*") If Not oElmt Is Nothing Then cNsUri = oElmt.GetAttribute("Xmlns") If cNsUri = "" Then cNsUri = oElmt.GetAttribute("xmlns") End If End If If cNsUri <> "" Then nsMgr.AddNamespace(cPrefix, cNsUri) End If If cPrefix = "ews" Then cPrefix = "ews2" Next Return nsMgr Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "getNsMgr", ex, "")) Return Nothing End Try End Function Public Shared Function addNsToXpath(ByVal cXpath As String, ByRef nsMgr As XmlNamespaceManager) As String Try 'check namespace not allready specified If InStr(cXpath, "ews:") = 0 Then If nsMgr.HasNamespace("ews") Then cXpath = "ews:" & Replace(cXpath, "/", "/ews:") 'find any [ not followed by number Dim substrings() As String = Regex.Split(cXpath, "(\[(?!\d))") If substrings.Length > 1 Then Dim cNewXpath As String = "" For Each match As String In substrings If match.StartsWith("[") Then cNewXpath = cNewXpath & "[ews:" & match.Substring(1) Else cNewXpath = cNewXpath & match End If Next cXpath = cNewXpath End If 'undo any attributes cXpath = Replace(cXpath, "/ews:@", "/@") cXpath = Replace(cXpath, "[ews:@", "[@") cXpath = Replace(cXpath, "[ews:position()", "[position()") End If End If Return cXpath Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "addNsToXpath", ex, "")) Return "" End Try End Function Public Shared Function addElement(ByRef oParent As XmlElement, ByVal cNewNodeName As String, Optional ByVal cNewNodeValue As String = "", Optional ByVal bAddAsXml As Boolean = False, Optional ByVal bPrepend As Boolean = False, Optional ByRef oNodeFromXPath As XmlNode = Nothing, Optional ByVal sPrefix As String = Nothing, Optional ByVal NamespaceURI As String = "") As XmlElement Try Dim oNewNode As XmlElement If sPrefix Is Nothing Then oNewNode = oParent.OwnerDocument.CreateElement(cNewNodeName) Else oNewNode = oParent.OwnerDocument.CreateElement(sPrefix, cNewNodeName, NamespaceURI) End If If cNewNodeValue = "" And Not (oNodeFromXPath Is Nothing) Then If bAddAsXml Then cNewNodeValue = oNodeFromXPath.InnerXml Else cNewNodeValue = oNodeFromXPath.InnerText End If If cNewNodeValue <> "" Then If bAddAsXml Then oNewNode.InnerXml = cNewNodeValue Else oNewNode.InnerText = cNewNodeValue End If If bPrepend Then oParent.PrependChild(oNewNode) Else oParent.AppendChild(oNewNode) Return oNewNode Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "addElement", ex, "")) Return Nothing End Try End Function Public Shared Function firstElement(ByRef oElement As XmlElement) As XmlElement Dim oNode As XmlNode Dim oReturnNode As XmlElement = Nothing Try For Each oNode In oElement.ChildNodes If oNode.NodeType = XmlNodeType.Element Then oReturnNode = oNode Exit For End If Next Return oReturnNode Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "firstElement", ex, "")) Return Nothing End Try End Function Public Shared Sub renameNode(ByRef oNode As XmlElement, ByVal cNewNodeName As String) Try Dim oNewNode As XmlElement Dim oChildElmt As XmlElement oNewNode = oNode.OwnerDocument.CreateElement(cNewNodeName) For Each oChildElmt In oNode.SelectNodes("*") oNewNode.AppendChild(oChildElmt) Next oNode.ParentNode.ReplaceChild(oNewNode, oNode) Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "renameNode", ex, "")) End Try End Sub Public Shared Sub removeChildByName(ByRef oNode As XmlElement, ByVal cRemoveNodeName As String) Try Dim removeElmt As XmlElement = oNode.SelectSingleNode(cRemoveNodeName) If removeElmt IsNot Nothing Then oNode.RemoveChild(removeElmt) End If Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "removeChildByName", ex, "")) End Try End Sub Public Shared Function addNewTextNode(ByVal cNodeName As String, ByRef oNode As XmlNode, Optional ByVal cNodeValue As String = "", Optional ByVal bAppendNotPrepend As Boolean = True, Optional ByVal bOverwriteExistingNode As Boolean = False) As XmlElement Try Dim oElem As XmlElement If bOverwriteExistingNode Then ' Search for an existing node - delete it if it exists oElem = oNode.SelectSingleNode(cNodeName) If Not (oElem Is Nothing) Then oNode.RemoveChild(oElem) End If oElem = oNode.OwnerDocument.CreateElement(cNodeName) If cNodeValue <> "" Then oElem.InnerText = cNodeValue If bAppendNotPrepend Then oNode.AppendChild(oElem) Else oNode.PrependChild(oElem) End If Return oElem Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "addNewTextNode", ex, "")) Return Nothing End Try End Function 'Public Shared Function getNodeValueByType(ByVal oParent As XmlNode, ByVal cXPath As String, Optional ByVal nNodeType As XmlDataType = XmlDataType.TypeString, Optional ByVal vDefaultValue As Object = "") As Object ' Try ' Dim oNode As XmlNode ' Dim cValue As Object ' oNode = oParent.SelectSingleNode(cXPath) ' If oNode Is Nothing Then ' ' No xPath match, let's return a default value ' ' If there are no default values, then let's return a nominal default value ' Select Case nNodeType ' Case XmlDataType.TypeNumber ' cValue = IIf(IsNumeric(vDefaultValue), vDefaultValue, 0) ' Case XmlDataType.TypeDate ' cValue = IIf(IsDate(vDefaultValue), vDefaultValue, Now()) ' Case Else ' Assume default type is string ' cValue = IIf(vDefaultValue <> "", vDefaultValue.ToString, "") ' End Select ' Else ' ' XPath match, let's check it against type ' cValue = oNode.InnerText ' Select Case nNodeType ' Case XmlDataType.TypeNumber ' cValue = IIf(IsNumeric(cValue), cValue, IIf(IsNumeric(vDefaultValue), vDefaultValue, 0)) ' Case XmlDataType.TypeDate ' cValue = IIf(IsDate(cValue), cValue, IIf(IsDate(vDefaultValue), vDefaultValue, Now())) ' Case Else ' Assume default type is string ' cValue = IIf(cValue <> "", cValue.ToString, IIf(vDefaultValue <> "", vDefaultValue.ToString, "")) ' End Select ' End If ' Return cValue ' Catch ex As Exception ' RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "getNodeValueByType", ex, "")) ' Return Nothing ' End Try 'End Function Public Shared Function getNodeValueByType(ByRef oParent As XmlNode, ByVal cXPath As String, Optional ByVal nNodeType As XmlDataType = XmlDataType.TypeString, Optional ByVal vDefaultValue As Object = "", Optional ByRef nsMgr As XmlNamespaceManager = Nothing) As Object Dim oNode As XmlNode Dim cValue As Object If nsMgr Is Nothing Then oNode = oParent.SelectSingleNode(cXPath) Else oNode = oParent.SelectSingleNode(addNsToXpath(cXPath, nsMgr), nsMgr) End If If oNode Is Nothing Then ' No xPath match, let's return a default value ' If there are no default values, then let's return a nominal default value Select Case nNodeType Case XmlDataType.TypeNumber cValue = IIf(IsNumeric(vDefaultValue), vDefaultValue, 0) Case XmlDataType.TypeDate cValue = IIf(IsDate(vDefaultValue), vDefaultValue, Now()) Case Else ' Assume default type is string cValue = IIf(vDefaultValue <> "", vDefaultValue.ToString, "") End Select Else ' XPath match, let's check it against type cValue = oNode.InnerText Select Case nNodeType Case XmlDataType.TypeNumber cValue = IIf(IsNumeric(cValue), cValue, IIf(IsNumeric(vDefaultValue), vDefaultValue, 0)) Case XmlDataType.TypeDate cValue = IIf(IsDate(cValue), cValue, IIf(IsDate(vDefaultValue), vDefaultValue, Now())) Case Else ' Assume default type is string cValue = IIf(cValue <> "", cValue.ToString, IIf(vDefaultValue <> "", vDefaultValue.ToString, "")) End Select End If Return cValue End Function ''' <summary> ''' <para>This allows XML to be loaded in to an element from a given file</para> ''' <para>The following checks are made:</para> ''' <list> ''' <item><term>File Exists?</term><description>Does the file provided by cFilePath actually exist</description></item> ''' <item><term>Valid XML</term><description>Is the loaded XMl actually valid?</description></item> ''' </list> ''' <para>If either check fails, then either Nothing or an empty element with a node name determined by <c>cErrorNodeName</c>.</para> ''' </summary> ''' <param name="cFilePath">The file path of the file that is being loaded</param> ''' <param name="oXmlDocument">Optional - the xml document to generate the return element from</param> ''' <param name="cErrorNodeName">Optional - if the checks fail, then this param determines the name of an empty returned element.</param> ''' <returns>The loaded XML's DocumentElement, or Nothing/empty element</returns> ''' <remarks></remarks> Public Shared Function loadElement(ByVal cFilePath As String, Optional ByRef oXmlDocument As XmlDocument = Nothing, Optional ByVal cErrorNodeName As String = "") As XmlElement Try Dim oXmlLoadDocument As XmlDocument = New XmlDocument() Dim oReturnElement As XmlElement = Nothing Dim bSuccess As Boolean = False If oXmlDocument Is Nothing Then oXmlDocument = New XmlDocument() ' Try to find and load the element If IO.File.Exists(cFilePath) Then Try oXmlLoadDocument.Load(cFilePath) oReturnElement = oXmlLoadDocument.DocumentElement bSuccess = True Catch ex As Exception bSuccess = False End Try End If ' Did the checks fail? If Not (bSuccess) Then ' return Nothing or empty element If Not (String.IsNullOrEmpty(cErrorNodeName)) Then oReturnElement = oXmlDocument.CreateElement(cErrorNodeName) End If Else oReturnElement = oXmlDocument.ImportNode(oReturnElement, True) End If Return oReturnElement Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "loadElement", ex, "")) Return Nothing End Try End Function ''' <summary> ''' NodeState - Given a node, looks to see if it has been instantiated and has contents ''' </summary> ''' <param name="oNode">The root node for testing</param> ''' <param name="xPath">The xpath to apply to the root node. If this is not supplied, the root node is tested.</param> ''' <param name="populateAsText">Text that can be added to the test node.</param> ''' <param name="populateAsXml">Xml that can be added to the test node</param> ''' <param name="populateState">The state that the test node must be in before it can be populated</param> ''' <param name="returnElement">The test node</param> ''' <param name="returnAsXml">The test node's inner xml</param> ''' <param name="returnAsText">The test node's inner text</param> ''' <param name="bCheckTrimmedInnerText">The matched node will have its innertext trimmed and examined</param> ''' <returns>XmlNodeState - the state of the test node.</returns> ''' <remarks></remarks> Public Shared Function NodeState( _ ByRef oNode As XmlElement, _ Optional ByVal xPath As String = "", _ Optional ByVal populateAsText As String = "", _ Optional ByVal populateAsXml As String = "", _ Optional ByVal populateState As Xml.XmlNodeState = XmlNodeState.IsEmpty, _ Optional ByRef returnElement As XmlElement = Nothing, _ Optional ByRef returnAsXml As String = "", _ Optional ByRef returnAsText As String = "", _ Optional ByVal bCheckTrimmedInnerText As Boolean = False _ ) As Xml.XmlNodeState Try Dim oReturnState As Xml.XmlNodeState = XmlNodeState.NotInstantiated ' Find the xPath if appropriate If Not (String.IsNullOrEmpty(xPath)) And Not (oNode Is Nothing) Then returnElement = oNode.SelectSingleNode(xPath) Else returnElement = oNode End If If Not (returnElement Is Nothing) Then ' Determine the node status If returnElement.IsEmpty Or (bCheckTrimmedInnerText And returnElement.InnerText.Trim() = "") Then oReturnState = XmlNodeState.IsEmpty Else oReturnState = XmlNodeState.HasContents End If ' Populate if necessary If (populateAsText <> "" Or populateAsXml <> "") And ((populateState = oReturnState) Or (populateState = XmlNodeState.IsEmptyOrHasContents)) Then If populateAsText <> "" Then returnElement.InnerText = populateAsText Else Try returnElement.InnerXml = populateAsXml Catch ex As Exception ' Could not populate the Xml - what to do? End Try End If End If ' Return the optional params returnAsXml = returnElement.InnerXml returnAsText = returnElement.InnerText End If Return oReturnState Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "NodeState", ex, "")) Return Nothing End Try End Function 'RJP 7 Nove 2012. Added email address checker. Public Shared Function EmailAddressCheck(ByVal emailAddress As String) As Boolean Dim pattern As String = "^[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$" Dim emailAddressMatch As Match = Regex.Match(emailAddress, pattern) If emailAddressMatch.Success Then EmailAddressCheck = True Else EmailAddressCheck = False End If End Function 'RJP 7 Nov 2012. Moved from Setup.vb Public Shared Function EncodeForXml(ByVal data As String) As String Static badAmpersand As New Regex("&(?![a-zA-Z]{2,6};|#[0-9]{2,4};)") data = badAmpersand.Replace(data, "&amp;") Return data.Replace("<", "&lt;").Replace("""", "&quot;").Replace(">", "gt;") End Function Public Shared Function convertEntitiesToCodes(ByVal sString As String) As String Try Dim startString As String = sString If sString Is Nothing Then Return "" Else sString = Replace(sString, "Xmlns=""""", "") ' sString = Replace(sString, "& ", "&amp; ") 'strip out any empty tags left by tinyMCE as the complier converts the to <h1/> sString = Replace(sString, "<h1></h1>", "") sString = Replace(sString, "<h2></h2>", "") sString = Replace(sString, "<h3></h3>", "") sString = Replace(sString, "<h4></h4>", "") sString = Replace(sString, "<h5></h5>", "") sString = Replace(sString, "<h6></h6>", "") sString = Replace(sString, "<span></span>", "") 're.Replace(sString, "&^(;)" "&amp;") 'xhtml Tidy sString = Replace(sString, "<o:p>", "<p>") sString = Replace(sString, "</o:p>", "</p>") sString = Replace(sString, "<o:p/>", "<p/>") 'sString = Replace(sString, "&lt;", "&#60;") 'sString = Replace(sString, "&gt;", "&#92;") sString = Replace(sString, "&quot;", "&#34;") sString = Replace(sString, "&apos;", "&#39;") sString = Replace(sString, "&nbsp;", "&#160;") sString = Replace(sString, "&iexcl;", "&#161;") sString = Replace(sString, "&cent;", "&#162;") sString = Replace(sString, "&pound;", "&#163;") sString = Replace(sString, "&curren;", "&#164;") sString = Replace(sString, "&yen;", "&#165;") sString = Replace(sString, "&brvbar;", "&#166;") sString = Replace(sString, "&sect;", "&#167;") sString = Replace(sString, "&uml;", "&#168;") sString = Replace(sString, "&copy;", "&#169;") sString = Replace(sString, "&ordf;", "&#170;") sString = Replace(sString, "&laquo;", "&#171;") sString = Replace(sString, "&not;", "&#172;") sString = Replace(sString, "&shy;", "&#173;") sString = Replace(sString, "&reg;", "&#174;") sString = Replace(sString, "&macr;", "&#175;") sString = Replace(sString, "&deg;", "&#176;") sString = Replace(sString, "&plusmn;", "&#177;") sString = Replace(sString, "&sup2;", "&#178;") sString = Replace(sString, "&sup3;", "&#179;") sString = Replace(sString, "&acute;", "&#180;") sString = Replace(sString, "&micro;", "&#181;") sString = Replace(sString, "&para;", "&#182;") sString = Replace(sString, "&middot;", "&#183;") sString = Replace(sString, "&cedil;", "&#184;") sString = Replace(sString, "&sup1;", "&#185;") sString = Replace(sString, "&ordm;", "&#186;") sString = Replace(sString, "&raquo;", "&#187;") sString = Replace(sString, "&frac14;", "&#188;") sString = Replace(sString, "&frac12;", "&#189;") sString = Replace(sString, "&frac34;", "&#190;") sString = Replace(sString, "&iquest;", "&#191;") sString = Replace(sString, "&Agrave;", "&#192;") sString = Replace(sString, "&Aacute;", "&#193;") sString = Replace(sString, "&Acirc;", "&#194;") sString = Replace(sString, "&Atilde;", "&#195;") sString = Replace(sString, "&Auml;", "&#196;") sString = Replace(sString, "&Aring;", "&#197;") sString = Replace(sString, "&AElig;", "&#198;") sString = Replace(sString, "&Ccedil;", "&#199;") sString = Replace(sString, "&Egrave;", "&#200;") sString = Replace(sString, "&Eacute;", "&#201;") sString = Replace(sString, "&Ecirc;", "&#202;") sString = Replace(sString, "&Euml;", "&#203;") sString = Replace(sString, "&Igrave;", "&#204;") sString = Replace(sString, "&Iacute;", "&#205;") sString = Replace(sString, "&Icirc;", "&#206;") sString = Replace(sString, "&Iuml;", "&#207;") sString = Replace(sString, "&ETH;", "&#208;") sString = Replace(sString, "&Ntilde;", "&#209;") sString = Replace(sString, "&Ograve;", "&#210;") sString = Replace(sString, "&Oacute;", "&#211;") sString = Replace(sString, "&Ocirc;", "&#212;") sString = Replace(sString, "&Otilde;", "&#213;") sString = Replace(sString, "&Ouml;", "&#214;") sString = Replace(sString, "&times;", "&#215;") sString = Replace(sString, "&Oslash;", "&#216;") sString = Replace(sString, "&Ugrave;", "&#217;") sString = Replace(sString, "&Uacute;", "&#218;") sString = Replace(sString, "&Ucirc;", "&#219;") sString = Replace(sString, "&Uuml;", "&#220;") sString = Replace(sString, "&Yacute;", "&#221;") sString = Replace(sString, "&THORN;", "&#222;") sString = Replace(sString, "&szlig;", "&#223;") sString = Replace(sString, "&agrave;", "&#224;") sString = Replace(sString, "&aacute;", "&#225;") sString = Replace(sString, "&acirc;", "&#226;") sString = Replace(sString, "&atilde;", "&#227;") sString = Replace(sString, "&auml;", "&#228;") sString = Replace(sString, "&aring;", "&#229;") sString = Replace(sString, "&aelig;", "&#230;") sString = Replace(sString, "&ccedil;", "&#231;") sString = Replace(sString, "&egrave;", "&#232;") sString = Replace(sString, "&eacute;", "&#233;") sString = Replace(sString, "&ecirc;", "&#234;") sString = Replace(sString, "&euml;", "&#235;") sString = Replace(sString, "&igrave;", "&#236;") sString = Replace(sString, "&iacute;", "&#237;") sString = Replace(sString, "&icirc;", "&#238;") sString = Replace(sString, "&iuml;", "&#239;") sString = Replace(sString, "&eth;", "&#240;") sString = Replace(sString, "&ntilde;", "&#241;") sString = Replace(sString, "&ograve;", "&#242;") sString = Replace(sString, "&oacute;", "&#243;") sString = Replace(sString, "&ocirc;", "&#244;") sString = Replace(sString, "&otilde;", "&#245;") sString = Replace(sString, "&ouml;", "&#246;") sString = Replace(sString, "&divide;", "&#247;") sString = Replace(sString, "&oslash;", "&#248;") sString = Replace(sString, "&ugrave;", "&#249;") sString = Replace(sString, "&uacute;", "&#250;") sString = Replace(sString, "&ucirc;", "&#251;") sString = Replace(sString, "&uuml;", "&#252;") sString = Replace(sString, "&yacute;", "&#253;") sString = Replace(sString, "&thorn;", "&#254;") sString = Replace(sString, "&yuml;", "&#255;") sString = Replace(sString, "&OElig;", "&#338;") sString = Replace(sString, "&oelig;", "&#339;") sString = Replace(sString, "&Scaron;", "&#352;") sString = Replace(sString, "&scaron;", "&#353;") sString = Replace(sString, "&Yuml;", "&#376;") sString = Replace(sString, "&fnof;", "&#402;") sString = Replace(sString, "&circ;", "&#710;") sString = Replace(sString, "&tilde;", "&#732;") sString = Replace(sString, "&Alpha;", "&#913;") sString = Replace(sString, "&Beta;", "&#914;") sString = Replace(sString, "&Gamma;", "&#915;") sString = Replace(sString, "&Delta;", "&#916;") sString = Replace(sString, "&Epsilon;", "&#917;") sString = Replace(sString, "&Zeta;", "&#918;") sString = Replace(sString, "&Eta;", "&#919;") sString = Replace(sString, "&Theta;", "&#920;") sString = Replace(sString, "&Iota;", "&#921;") sString = Replace(sString, "&Kappa;", "&#922;") sString = Replace(sString, "&Lambda;", "&#923;") sString = Replace(sString, "&Mu;", "&#924;") sString = Replace(sString, "&Nu;", "&#925;") sString = Replace(sString, "&Xi;", "&#926;") sString = Replace(sString, "&Omicron;", "&#927;") sString = Replace(sString, "&Pi;", "&#928;") sString = Replace(sString, "&Rho;", "&#929;") sString = Replace(sString, "&Sigma;", "&#931;") sString = Replace(sString, "&Tau;", "&#932;") sString = Replace(sString, "&Upsilon;", "&#933;") sString = Replace(sString, "&Phi;", "&#934;") sString = Replace(sString, "&Chi;", "&#935;") sString = Replace(sString, "&Psi;", "&#936;") sString = Replace(sString, "&Omega;", "&#937;") sString = Replace(sString, "&alpha;", "&#945;") sString = Replace(sString, "&beta;", "&#946;") sString = Replace(sString, "&gamma;", "&#947;") sString = Replace(sString, "&delta;", "&#948;") sString = Replace(sString, "&epsilon;", "&#949;") sString = Replace(sString, "&zeta;", "&#950;") sString = Replace(sString, "&eta;", "&#951;") sString = Replace(sString, "&theta;", "&#952;") sString = Replace(sString, "&iota;", "&#953;") sString = Replace(sString, "&kappa;", "&#954;") sString = Replace(sString, "&lambda;", "&#955;") sString = Replace(sString, "&mu;", "&#956;") sString = Replace(sString, "&nu;", "&#957;") sString = Replace(sString, "&xi;", "&#958;") sString = Replace(sString, "&omicron;", "&#959;") sString = Replace(sString, "&pi;", "&#960;") sString = Replace(sString, "&rho;", "&#961;") sString = Replace(sString, "&sigmaf;", "&#962;") sString = Replace(sString, "&sigma;", "&#963;") sString = Replace(sString, "&tau;", "&#964;") sString = Replace(sString, "&upsilon;", "&#965;") sString = Replace(sString, "&phi;", "&#966;") sString = Replace(sString, "&chi;", "&#967;") sString = Replace(sString, "&psi;", "&#968;") sString = Replace(sString, "&omega;", "&#969;") sString = Replace(sString, "&thetasym;", "&#977;") sString = Replace(sString, "&upsih;", "&#978;") sString = Replace(sString, "&piv;", "&#982;") sString = Replace(sString, "&ensp;", "&#8194;") sString = Replace(sString, "&emsp;", "&#8195;") sString = Replace(sString, "&thinsp;", "&#8201;") sString = Replace(sString, "&zwnj;", "&#8204;") sString = Replace(sString, "&zwj;", "&#8205;") sString = Replace(sString, "&lrm;", "&#8206;") sString = Replace(sString, "&rlm;", "&#8207;") sString = Replace(sString, "&ndash;", "&#8211;") sString = Replace(sString, "&mdash;", "&#8212;") sString = Replace(sString, "&lsquo;", "&#8216;") sString = Replace(sString, "&rsquo;", "&#8217;") sString = Replace(sString, "&sbquo;", "&#8218;") sString = Replace(sString, "&ldquo;", "&#8220;") sString = Replace(sString, "&rdquo;", "&#8221;") sString = Replace(sString, "&bdquo;", "&#8222;") sString = Replace(sString, "&dagger;", "&#8224;") sString = Replace(sString, "&Dagger;", "&#8225;") sString = Replace(sString, "&bull;", "&#8226;") sString = Replace(sString, "&hellip;", "&#8230;") sString = Replace(sString, "&permil;", "&#8240;") sString = Replace(sString, "&prime;", "&#8242;") sString = Replace(sString, "&Prime;", "&#8243;") sString = Replace(sString, "&lsaquo;", "&#8249;") sString = Replace(sString, "&rsaquo;", "&#8250;") sString = Replace(sString, "&oline;", "&#8254;") sString = Replace(sString, "&frasl;", "&#8260;") sString = Replace(sString, "&euro;", "&#8364;") sString = Replace(sString, "&image;", "&#8465;") sString = Replace(sString, "&weierp;", "&#8472;") sString = Replace(sString, "&real;", "&#8476;") sString = Replace(sString, "&trade;", "&#8482;") sString = Replace(sString, "&alefsym;", "&#8501;") sString = Replace(sString, "&larr;", "&#8592;") sString = Replace(sString, "&uarr;", "&#8593;") sString = Replace(sString, "&rarr;", "&#8594;") sString = Replace(sString, "&darr;", "&#8595;") sString = Replace(sString, "&harr;", "&#8596;") sString = Replace(sString, "&crarr;", "&#8629;") sString = Replace(sString, "&lArr;", "&#8656;") sString = Replace(sString, "&uArr;", "&#8657;") sString = Replace(sString, "&rArr;", "&#8658;") sString = Replace(sString, "&dArr;", "&#8659;") sString = Replace(sString, "&hArr;", "&#8660;") sString = Replace(sString, "&forall;", "&#8704;") sString = Replace(sString, "&part;", "&#8706;") sString = Replace(sString, "&exist;", "&#8707;") sString = Replace(sString, "&empty;", "&#8709;") sString = Replace(sString, "&nabla;", "&#8711;") sString = Replace(sString, "&isin;", "&#8712;") sString = Replace(sString, "&notin;", "&#8713;") sString = Replace(sString, "&ni;", "&#8715;") sString = Replace(sString, "&prod;", "&#8719;") sString = Replace(sString, "&sum;", "&#8721;") sString = Replace(sString, "&minus;", "&#8722;") sString = Replace(sString, "&lowast;", "&#8727;") sString = Replace(sString, "&radic;", "&#8730;") sString = Replace(sString, "&prop;", "&#8733;") sString = Replace(sString, "&infin;", "&#8734;") sString = Replace(sString, "&ang;", "&#8736;") sString = Replace(sString, "&and;", "&#8743;") sString = Replace(sString, "&or;", "&#8744;") sString = Replace(sString, "&cap;", "&#8745;") sString = Replace(sString, "&cup;", "&#8746;") sString = Replace(sString, "&int;", "&#8747;") sString = Replace(sString, "&there4;", "&#8756;") sString = Replace(sString, "&sim;", "&#8764;") sString = Replace(sString, "&cong;", "&#8773;") sString = Replace(sString, "&asymp;", "&#8776;") sString = Replace(sString, "&ne;", "&#8800;") sString = Replace(sString, "&equiv;", "&#8801;") sString = Replace(sString, "&le;", "&#8804;") sString = Replace(sString, "&ge;", "&#8805;") sString = Replace(sString, "&sub;", "&#8834;") sString = Replace(sString, "&sup;", "&#8835;") sString = Replace(sString, "&nsub;", "&#8836;") sString = Replace(sString, "&sube;", "&#8838;") sString = Replace(sString, "&supe;", "&#8839;") sString = Replace(sString, "&oplus;", "&#8853;") sString = Replace(sString, "&otimes;", "&#8855;") sString = Replace(sString, "&perp;", "&#8869;") sString = Replace(sString, "&sdot;", "&#8901;") sString = Replace(sString, "&lceil;", "&#8968;") sString = Replace(sString, "&rceil;", "&#8969;") sString = Replace(sString, "&lfloor;", "&#8970;") sString = Replace(sString, "&rfloor;", "&#8971;") sString = Replace(sString, "&lang;", "&#9001;") sString = Replace(sString, "&rang;", "&#9002;") sString = Replace(sString, "&loz;", "&#9674;") sString = Replace(sString, "&spades;", "&#9824;") sString = Replace(sString, "&clubs;", "&#9827;") sString = Replace(sString, "&hearts;", "&#9829;") sString = Replace(sString, "&diams;", "&#9830;") If sString Is Nothing Then Return "" Else sString = Regex.Replace(sString, "&(?!#?\w+;)", "&amp;") Return sString End If End If Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "convertEntitiesToCodes", ex, "")) Return "" End Try End Function Public Shared Function convertEntitiesToCodesFast(ByVal sString As String) As String Try Dim startString As String = sString If sString Is Nothing Then Return "" Else sString = Replace(sString, "Xmlns=""""", "") Dim chars As Char() = sString.ToCharArray() Dim result As StringBuilder = New StringBuilder(sString.Length + CInt((sString.Length * 0.1))) For Each c As Char In chars Dim value As Integer = Convert.ToInt32(c) If value > 127 Then result.AppendFormat("&#{0};", value) Else result.Append(c) Next sString = result.ToString() If sString Is Nothing Then Return "" Else sString = Regex.Replace(sString, "&(?!#?\w+;)", "&amp;") Return sString End If End If Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "convertEntitiesToCodes", ex, "")) Return "" End Try End Function Public Shared Function convertEntitiesToString(ByVal sString As String) As String Try sString = sString.Replace("&amp;", "&") sString = sString.Replace("&lt;", "<") sString = sString.Replace("&gt;", ">") Return IIf(sString Is Nothing, "", sString) Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "convertEntitiesToString", ex, "")) Return "" End Try End Function Public Shared Function XmlDate(ByVal dDate As Object, Optional ByVal bIncludeTime As Boolean = False) As String Try Dim cReturn As String If IsDBNull(dDate) Or Not (IsDate(dDate)) Then cReturn = "" Else Dim cFormat As String = "yyyy-MM-dd" If bIncludeTime Then cFormat += "THH:mm:ss" cReturn = CDate(dDate).ToString(cFormat) End If Return cReturn Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "XmlDate", ex, "")) Return "" End Try End Function Public Shared Function GenerateConcatForXPath(ByVal a_xPathQueryString As String) As String Dim returnString As String = String.Empty Dim searchString As String = a_xPathQueryString Dim quoteChars As Char() = New Char() {"'"c, """"c} Dim quotePos As Integer = searchString.IndexOfAny(quoteChars) If quotePos = -1 Then returnString = "'" + searchString + "'" Else returnString = "concat(" While quotePos <> -1 Dim subString As String = searchString.Substring(0, quotePos) returnString += "'" + subString + "', " If searchString.Substring(quotePos, 1) = "'" Then returnString += """'"", " Else 'must be a double quote returnString += "'""', " End If searchString = searchString.Substring(quotePos + 1, searchString.Length - quotePos - 1) quotePos = searchString.IndexOfAny(quoteChars) End While returnString += "'" + searchString + "')" End If Return returnString End Function Public Shared Function encodeAllHTML(ByVal shtml As String) shtml = Replace(shtml, "&", "&amp;") shtml = Replace(shtml, """", "&quot;") shtml = Replace(shtml, "<", "&lt;") shtml = Replace(shtml, ">", "&gt;") Return shtml End Function Public Shared Function CombineNodes(ByVal oMasterStructureNode As XmlElement, ByVal oExistingDataNode As XmlElement) As XmlElement 'combines an existing instance with a new Try 'firstly we will go through and find like for like 'we will skip the immediate node below instance as this is usually fairly static 'except for attributes 'Attributes of Root Dim oMasterFirstElement As XmlElement = firstElement(oMasterStructureNode) Dim oExistingFirstElement As XmlElement = firstElement(oExistingDataNode) If oMasterFirstElement IsNot Nothing Then If oMasterFirstElement.HasAttributes Then For i As Integer = 0 To oMasterFirstElement.Attributes.Count - 1 Dim oMainAtt As XmlAttribute = oMasterFirstElement.Attributes(i) If Not oExistingDataNode.Attributes.ItemOf(oMainAtt.Name).Value = "" Then oMainAtt.Value = oExistingDataNode.Attributes.ItemOf(oMainAtt.Name).Value End If Next End If 'Navigate Down Elmts and find with same xpath For Each oMainElmt As XmlElement In oMasterFirstElement.SelectNodes("*") CombineInstance_Sub1(oMainElmt, oExistingDataNode, oMasterFirstElement.Name) Next 'Now for any existing stuff that has not been brought across If oExistingFirstElement IsNot Nothing Then For Each oExistElmt As XmlElement In oExistingFirstElement.SelectNodes("descendant-or-self::*[not(@ewCombineInstanceFound)]") If Not oExistElmt.OuterXml = oExistingFirstElement.OuterXml Then CombineInstance_Sub2(oExistElmt, oMasterStructureNode, oMasterFirstElement.Name) End If Next End If CombineInstance_MarkSubElmts(oMasterStructureNode, True) End If Return oMasterStructureNode Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "CombineNodes", ex, "")) Return oMasterStructureNode End Try End Function Shared Function GetOrCreateSingleChildElement(ByRef parentNode As XmlNode, ByVal nodeName As String) As XmlElement Try Dim returnNode As XmlElement = parentNode.SelectSingleNode(nodeName) If returnNode Is Nothing Then returnNode = parentNode.OwnerDocument.CreateElement(nodeName) parentNode.AppendChild(returnNode) End If Return returnNode Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "GetOrCreateSingleChildElement", ex, "")) Return Nothing End Try End Function ''' <summary> ''' Attempts to set an element's inner xml from a string - if it fails it will set the inner text instead ''' </summary> ''' <param name="element">the element to set</param> ''' <param name="value">the string to try and set the element for</param> ''' <remarks></remarks> Public Shared Sub SetInnerXmlThenInnerText(ByRef element As XmlElement, ByVal value As String) If element IsNot Nothing Then Try element.InnerXml = value Catch ex As XmlException element.InnerText = value Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "SetInnerXmlThenInnerText", ex, "")) End Try End If End Sub Public Shared Function XmltoDictionary(oXml As XmlElement) As System.Collections.Generic.Dictionary(Of String, String) Try Dim myDict = New System.Collections.Generic.Dictionary(Of String, String) XmltoDictionaryNode(oXml, myDict, oXml.Name()) Return myDict Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "XmltoDictionary", ex, "")) End Try End Function Private Shared Sub XmltoDictionaryNode(oThisElmt As XmlElement, ByRef myDict As Dictionary(Of String, String), ByVal Prefix As String) Dim oElmt As XmlElement Try For Each Attribute As XmlAttribute In oThisElmt.Attributes myDict.Add(Prefix & ".-" & Attribute.Name, Attribute.Value) Next If oThisElmt.SelectNodes("*").Count = 0 Then If oThisElmt.InnerText <> "" And Not (myDict.ContainsKey(Prefix & "." & oThisElmt.Name)) Then myDict.Add(Prefix, oThisElmt.InnerText) End If Else For Each oElmt In oThisElmt.SelectNodes("*") XmltoDictionaryNode(oElmt, myDict, Prefix & "." & oElmt.Name()) Next End If Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "XmltoDictionaryNode", ex, "")) End Try End Sub #End Region ''' <summary> ''' Serializes an object and returns the serialization as a string representation of UTF-8 encoded XML ''' </summary> ''' <typeparam name="T">The type of object to serialize</typeparam> ''' <param name="value">The object to serialize</param> ''' <returns></returns> ''' <remarks></remarks> Public Shared Function Serialize(Of T)(ByVal value As T) As String Dim serializer As New XmlSerializer(GetType(T)) Dim mStream As New IO.MemoryStream() Dim settings As New XmlWriterSettings() settings.Encoding = New UTF8Encoding(False) settings.Indent = False settings.OmitXmlDeclaration = False Dim xWriter As XmlWriter = XmlWriter.Create(mStream, settings) serializer.Serialize(xWriter, value) Dim serializedString As String = Tools.Text.UTF8ByteArrayToString(mStream.ToArray()) mStream.Close() Return serializedString End Function Public Shared Function SerializeToXml(Of T)(ByVal value As T) As XmlNode Dim cProcessInfo As String = "" Try ' Get the serialized object Dim serializedObject As String = Serialize(Of T)(value) cProcessInfo = serializedObject If Not serializedObject = Nothing Then ' Remove the namespaces serializedObject = System.Text.RegularExpressions.Regex.Replace(serializedObject, "xmlns(:\w+?)?="".*?""", "") serializedObject = System.Text.RegularExpressions.Regex.Replace(serializedObject, "<\?xml.+\?>", "") End If ' Remove the declaration ' Load into XML Dim serializedObjectDocument As New XmlDocument serializedObjectDocument.LoadXml(serializedObject) Return serializedObjectDocument.DocumentElement Catch ex As Exception RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "Read", ex, cProcessInfo)) Return Nothing End Try End Function Public Shared Sub AddExistingNode(ByRef nodeToAddTo As XmlElement, ByVal nodeToBeAdded As XmlNode) nodeToAddTo.AppendChild(nodeToAddTo.OwnerDocument.ImportNode(nodeToBeAdded, True)) End Sub Public Shared Sub AddExistingNode(ByRef nodeToAddTo As XmlNode, ByVal nodeToBeAdded As XmlNode) nodeToAddTo.AppendChild(nodeToAddTo.OwnerDocument.ImportNode(nodeToBeAdded, True)) End Sub Public Class XmlNoNamespaceWriter Inherits System.Xml.XmlTextWriter Dim skipAttribute As Boolean = False Public Sub New(ByVal writer As System.IO.TextWriter) MyBase.New(writer) End Sub Public Sub New(ByVal stream As System.IO.Stream, ByVal encoding As System.Text.Encoding) MyBase.New(stream, encoding) End Sub Public Overloads Overrides Sub WriteStartElement(ByVal prefix As String, ByVal localName As String, ByVal ns As String) MyBase.WriteStartElement(Nothing, localName, Nothing) End Sub Public Overloads Overrides Sub WriteStartAttribute(ByVal prefix As String, ByVal localName As String, ByVal ns As String) If prefix.CompareTo("Xmlns") = 0 Or localName.CompareTo("xmlns") = 0 Then skipAttribute = True Else MyBase.WriteStartAttribute(Nothing, localName, Nothing) End If End Sub Public Overloads Overrides Sub WriteString(ByVal text As String) If Not skipAttribute Then MyBase.WriteString(text) End If End Sub Public Overloads Overrides Sub WriteEndAttribute() If Not skipAttribute Then MyBase.WriteEndAttribute() End If skipAttribute = False End Sub Public Overloads Overrides Sub WriteQualifiedName(ByVal localName As String, ByVal ns As String) MyBase.WriteQualifiedName(localName, Nothing) End Sub End Class Public Class XmlSanitizingStream Inherits System.IO.StreamReader Public Shared Event OnError(ByVal sender As Object, ByVal e As Protean.Tools.Errors.ErrorEventArgs) Private Const mcModuleName As String = "Protean.Tools.Xml.XmlSanitizingStream" ' Pass 'true' to automatically detect encoding using BOMs. ' BOMs: http://en.wikipedia.org/wiki/Byte-order_mark Public Sub New(streamToSanitize As System.IO.Stream) MyBase.New(streamToSanitize, True) End Sub ''' <summary> ''' Whether a given character is allowed by XML 1.0. ''' </summary> Public Shared Function IsLegalXmlChar(character As Integer) As Boolean ' == '\t' == 9 ' == '\n' == 10 ' == '\r' == 13 Return (character = &H9 OrElse character = &HA OrElse character = &HD OrElse (character >= &H20 AndAlso character <= &HD7FF) OrElse (character >= &HE000 AndAlso character <= &HFFFD) OrElse (character >= &H10000 AndAlso character <= &H10FFFF)) End Function Private Const EOF As Integer = -1 Public Overrides Function Read() As Integer ' Read each char, skipping ones XML has prohibited Dim nextCharacter As Integer Do ' Read a character If (InlineAssignHelper(nextCharacter, MyBase.Read())) = EOF Then ' If the char denotes end of file, stop Exit Do End If ' Skip char if it's illegal, and try the next Loop While Not XmlSanitizingStream.IsLegalXmlChar(nextCharacter) Return nextCharacter End Function Public Overrides Function Peek() As Integer ' Return next legal XML char w/o reading it Dim nextCharacter As Integer Do ' See what the next character is nextCharacter = MyBase.Peek() ' If it's illegal, skip over ' and try the next. Loop While Not XmlSanitizingStream.IsLegalXmlChar(nextCharacter) AndAlso (InlineAssignHelper(nextCharacter, MyBase.Read())) <> EOF Return nextCharacter End Function 'Public Overrides Function Read(buffer As Char(), index As Integer, count As Integer) As Integer ' Dim cProcessInfo As String = Nothing ' Try ' If buffer Is Nothing Then ' Throw New ArgumentNullException("buffer") ' End If ' If index < 0 Then ' Throw New ArgumentOutOfRangeException("index") ' End If ' If count < 0 Then ' Throw New ArgumentOutOfRangeException("count") ' End If ' If (buffer.Length - index) < count Then ' Throw New ArgumentException() ' End If ' Dim num As Integer = 0 ' Do ' Dim num2 As Integer = Me.Read() ' If num2 = -1 Then ' Return num ' End If ' cProcessInfo = buffer.Length ' buffer(index + System.Math.Max(System.Threading.Interlocked.Increment(num), num - 1)) = ChrW(num2) ' Loop While num < count ' Return num ' Catch ex As Exception ' RaiseEvent OnError(Nothing, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "Read", ex, cProcessInfo)) ' Return Nothing ' End Try 'End Function Public Overrides Function ReadBlock(buffer As Char(), index As Integer, count As Integer) As Integer Dim num As Integer Dim num2 As Integer = 0 Do num2 += InlineAssignHelper(num, Me.Read(buffer, index + num2, count - num2)) Loop While (num > 0) AndAlso (num2 < count) Return num2 End Function Public Overrides Function ReadLine() As String Dim builder As New StringBuilder() While True Dim num As Integer = Me.Read() Select Case num Case -1 If builder.Length > 0 Then Return builder.ToString() End If Return Nothing Case 13, 10 If (num = 13) AndAlso (Me.Peek() = 10) Then Me.Read() End If Return builder.ToString() Case Else Return Nothing End Select builder.Append(ChrW(num)) End While End Function Public Overrides Function ReadToEnd() As String Dim num As Integer Dim buffer As Char() = New Char(4095) {} Dim builder As New StringBuilder(&H1000) While (InlineAssignHelper(num, Me.Read(buffer, 0, buffer.Length))) <> 0 builder.Append(buffer, 0, num) End While Return builder.ToString() End Function Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T target = value Return value End Function End Class End Class Namespace Xslt Public Class XsltFunctions Public Function stringcompare(ByVal stringX As String, ByVal stringY As String) As Integer stringX = UCase(stringX) stringY = UCase(stringY) If stringX = stringY Then Return 0 ElseIf stringX < stringY Then Return -1 ElseIf stringX > stringY Then Return 1 End If End Function Public Function replacestring(ByVal text As String, ByVal replace As String, ByVal replaceWith As String) As String Try Return text.Replace(replace, replaceWith) Catch ex As Exception Return text End Try End Function Public Function getdate(ByVal dateString As String) As String Try Select Case dateString Case "now()", "Now()", "now", "Now" dateString = CStr(Protean.Tools.Xml.XmlDate(Now(), True)) End Select Return dateString Catch ex As Exception Return dateString End Try End Function Public Function formatdate(ByVal dateString As String, ByVal dateFormat As String) As String Try If IsDate(dateString) Then dateString = New Date(dateString).ToString(dateFormat) End If Return dateString Catch ex As Exception Return dateString End Try End Function Public Function textafterlast(ByVal text As String, ByVal search As String) As String Try If text.LastIndexOf(search) > 0 Then text = text.Substring(text.LastIndexOf(search) + search.Length()) End If Return text Catch ex As Exception Return text End Try End Function Public Function textbeforelast(ByVal text As String, ByVal search As String) As String Try If text.LastIndexOf(search) > 0 Then text = text.Substring(0, text.LastIndexOf(search)) End If Return text Catch ex As Exception Return text End Try End Function Public Function randomnumber(ByVal min As Integer, ByVal max As Integer) As Integer Try Dim oRand As New Random Return oRand.Next(min, max) Catch ex As Exception Return min End Try End Function Public Function datediff(ByVal date1String As String, ByVal date2String As String, ByVal datePart As String) As String Dim nDiff As String = "" Try Dim ValidDatePart As String() = {"d", "y", "h", "n", "m", "q", "s", "w", "ww", "yyyy"} If IsDate(date1String) _ AndAlso IsDate(date2String) _ AndAlso Array.IndexOf(ValidDatePart, datePart) > (ValidDatePart.GetLowerBound(0) - 1) Then nDiff = Microsoft.VisualBasic.DateDiff(datePart, CDate(date1String), CDate(date2String)).ToString() End If Return nDiff Catch ex As Exception Return nDiff End Try End Function End Class Public Class Transform #Region " Declarations" Private cFileLocation As String = "" 'Xsl File path Private cXslText As String = "" 'Xsl Blob Private oXml As System.Xml.XPath.IXPathNavigable 'Xml Document Private bCompiled As Boolean 'If we want it to be compiled Private nTimeoutMillisec As Integer = 0 'Timeout in milliseconds (0 means not timed) Private bDebuggable As Boolean = False 'If we want to be able to step through the code Private bClearXml As Boolean = True 'Do we want to clear the Xml object after a transform (to reduce object size for caching) Private bClearXmlDec As Boolean = True 'Remove Xml Declaration Private oXslTExtensionsObject As Object 'Any Class we want to use for additional functionality Private cXslTExtensionsURN As String 'The Urn for the class Private oClassicTransform As Xsl.XslTransform ' Classic Transform Object Private oCompiledTransform As Xsl.XslCompiledTransform 'Compiled Transform Object Private XsltArgs As Xsl.XsltArgumentList 'Argurment List 'Error Handling 'General Error Public Event OnError(ByVal sender As Object, ByVal e As Protean.Tools.Errors.ErrorEventArgs) 'Private TimeOutError Private Event OnTimeoutError_Private(ByVal sender As Object, ByVal e As Protean.Tools.Errors.ErrorEventArgs) 'Public TimeOutError Public Event OnTimeoutError(ByVal sender As Object, ByVal e As Protean.Tools.Errors.ErrorEventArgs) Private oXslReader As XmlReader 'to read the Xsl Private oXslReaderSettings As XmlReaderSettings Private Const mcModuleName As String = "Protean.Tools.Xml.XslTransform" Private Sub EonicPrivateError_Handle(ByVal sender As Object, ByVal e As Protean.Tools.Errors.ErrorEventArgs) Handles Me.OnTimeoutError_Private Try 'make sure we close the reader properly oXslReader.Close() Catch ex As Exception 'dont do anyrhing End Try 'raise the public timeout event RaiseEvent OnTimeoutError(sender, e) End Sub #End Region #Region " Properties" Public Property XslTFile() As String Get Return cFileLocation End Get Set(ByVal value As String) cFileLocation = value End Set End Property Public Property XslText() As String Get Return cXslText End Get Set(ByVal value As String) cXslText = value End Set End Property Public Property Compiled() As Boolean Get Return bCompiled End Get Set(ByVal value As Boolean) bCompiled = value End Set End Property Public Property TimeoutSeconds() As Integer Get Dim oTimeSpan As New TimeSpan(0, 0, 0, 0, nTimeoutMillisec) Return oTimeSpan.TotalSeconds End Get Set(ByVal value As Integer) Dim oTimeSpan As New TimeSpan(0, 0, 0, value) nTimeoutMillisec = oTimeSpan.TotalMilliseconds End Set End Property Public Property Debuggable() As Boolean Get Return bDebuggable End Get Set(ByVal value As Boolean) bDebuggable = value End Set End Property Public Property Xml() As System.Xml.XPath.IXPathNavigable Get Return oXml End Get Set(ByVal value As System.Xml.XPath.IXPathNavigable) oXml = value End Set End Property Public Property XslTExtensionObject() As Object Get Return oXslTExtensionsObject End Get Set(ByVal value As Object) oXslTExtensionsObject = value End Set End Property Public Property XslTExtensionURN() As String Get Return cXslTExtensionsURN End Get Set(ByVal value As String) cXslTExtensionsURN = value If Not cXslTExtensionsURN.Contains("urn:") Then cXslTExtensionsURN = "urn:" & value End Set End Property Public Property ClearXmlAfterTransform() As Boolean Get Return bClearXml End Get Set(ByVal value As Boolean) bClearXml = value End Set End Property Public Property RemoveXmlDeclaration() As Boolean Get Return bClearXmlDec End Get Set(ByVal value As Boolean) bClearXmlDec = value End Set End Property #End Region #Region " Compiled" Private Delegate Sub TransformCompiledDelegate(ByRef cResult As String) Private Sub ProcessCompiledTimed(ByRef cResult As String) Try Dim d As New TransformCompiledDelegate(AddressOf ProcessCompiled) Dim res As IAsyncResult = d.BeginInvoke(cResult, Nothing, Nothing) If res.IsCompleted = False Then res.AsyncWaitHandle.WaitOne(nTimeoutMillisec, False) If res.IsCompleted = False Then d.EndInvoke(cResult, DirectCast(res, Runtime.Remoting.Messaging.AsyncResult)) d = Nothing Dim oSettings As New Hashtable oSettings.Add("TimeoutSeconds", Me.TimeoutSeconds) oSettings.Add("Compiled", Me.Compiled) RaiseEvent OnTimeoutError_Private(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "ProcessCompiledTimed", New Exception("XsltTransformTimeout"), "", , oSettings)) End If End If If Not d Is Nothing Then d.EndInvoke(cResult, DirectCast(res, Runtime.Remoting.Messaging.AsyncResult)) Catch ex As Exception RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "ProcessCompiledTimed", ex, "")) End Try End Sub Private Sub ProcessCompiled(ByRef cResult As String) Try 'make a resolver/setting Dim resolver As New XmlUrlResolver() resolver.Credentials = System.Net.CredentialCache.DefaultCredentials 'create the transform object If oCompiledTransform Is Nothing Then 'if it is not nothing we will have already used it "cache" oCompiledTransform = New Xsl.XslCompiledTransform(bDebuggable) 'get the Xsl If Not cFileLocation = "" Then oXslReader = XmlReader.Create(cFileLocation, oXslReaderSettings) oCompiledTransform.Load(oXslReader, Xsl.XsltSettings.TrustedXslt, resolver) oXslReader.Close() Else Dim oXsl As New XmlDocument oXsl.InnerXml = cXslText oCompiledTransform.Load(oXsl, Xsl.XsltSettings.TrustedXslt, resolver) End If 'any vb functions we want to use make an extension object XsltArgs = New Xsl.XsltArgumentList If Not oXslTExtensionsObject Is Nothing And Not cXslTExtensionsURN = "" Then XsltArgs.AddExtensionObject(cXslTExtensionsURN, oXslTExtensionsObject) End If End If 'make a writer Dim osWriter As IO.TextWriter = New IO.StringWriter 'transform 'Change the XmlDocument to xPathDocument to improve performance Dim xpathDoc As XPath.XPathDocument = New XPath.XPathDocument(New XmlNodeReader(oXml)) oCompiledTransform.Transform(xpathDoc, XsltArgs, osWriter) 'Return results cResult = osWriter.ToString Catch ex As Exception RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "TransformCompiled", ex, "")) cResult = "" End Try End Sub #End Region #Region " Classic" Private Delegate Sub TransformClassicDelegate(ByRef cResult As String) Private Sub ProcessClassicTimed(ByRef cResult As String) Dim sProcessInfo As String = "" Try Dim d As New TransformClassicDelegate(AddressOf ProcessClassic) Dim res As IAsyncResult = d.BeginInvoke(cResult, Nothing, Nothing) If res.IsCompleted = False Then res.AsyncWaitHandle.WaitOne(nTimeoutMillisec, False) If res.IsCompleted = False Then d.EndInvoke(cResult, DirectCast(res, Runtime.Remoting.Messaging.AsyncResult)) d = Nothing Dim oSettings As New Hashtable oSettings.Add("TimeoutSeconds", Me.TimeoutSeconds) oSettings.Add("Compiled", Me.Compiled) RaiseEvent OnTimeoutError_Private(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "ProcessClassicTimed", New Exception("XsltTransformTimeout"), "", , oSettings)) End If End If If Not d Is Nothing Then d.EndInvoke(cResult, DirectCast(res, Runtime.Remoting.Messaging.AsyncResult)) Catch ex As Exception RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "ProcessClassicTimed", ex, "")) End Try End Sub Private Sub ProcessClassic(ByRef cResult As String) Try 'make a resolver/setting Dim resolver As New XmlUrlResolver() resolver.Credentials = System.Net.CredentialCache.DefaultCredentials 'create the transform object oClassicTransform = New Xsl.XslTransform() 'get the Xsl If Not cFileLocation = "" Then oXslReader = XmlReader.Create(cFileLocation, oXslReaderSettings) oClassicTransform.Load(oXslReader, resolver) oXslReader.Close() Else Dim oXsl As New XmlDocument oXsl.InnerXml = cXslText oClassicTransform.Load(oXsl, resolver) End If 'any vb functions we want to use make an extension object XsltArgs = New Xsl.XsltArgumentList If Not oXslTExtensionsObject Is Nothing And Not cXslTExtensionsURN = "" Then XsltArgs.AddExtensionObject(cXslTExtensionsURN, oXslTExtensionsObject) End If 'make a writer Dim osWriter As IO.TextWriter = New IO.StringWriter 'transform 'Change the XmlDocument to xPathDocument to improve performance Dim xpathDoc As XPath.XPathDocument = New XPath.XPathDocument(New XmlNodeReader(oXml)) oClassicTransform.Transform(xpathDoc, XsltArgs, osWriter, Nothing) 'Return results cResult = osWriter.ToString Catch ex As Exception RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "TransformClassic", ex, "")) cResult = "" End Try End Sub #End Region Public Function Process() As String Try Dim cResult As String = "" If bCompiled And nTimeoutMillisec > 0 Then ProcessCompiledTimed(cResult) ElseIf Not bCompiled And nTimeoutMillisec > 0 Then ProcessClassicTimed(cResult) ElseIf bCompiled And nTimeoutMillisec = 0 Then ProcessCompiled(cResult) ElseIf Not bCompiled And nTimeoutMillisec = 0 Then ProcessClassic(cResult) End If If RemoveXmlDeclaration Then Me.RemoveDeclaration(cResult) End If Return cResult Catch ex As Exception RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "Transform", ex, "")) Return "" Finally If bClearXml Then oXml = Nothing End Try End Function Private Sub RemoveDeclaration(ByRef cResult As String) cResult = Replace(cResult, "<?Xml version=""1.0"" encoding=""utf-8""?>", "") cResult = Replace(cResult, "<?Xml version=""1.0"" encoding=""utf-16""?>", "") cResult = Trim(cResult) End Sub Public Sub New() Try oXslReaderSettings = New XmlReaderSettings oXslReaderSettings.ProhibitDtd = False Catch ex As Exception RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "New", ex, "")) End Try End Sub End Class End Namespace
Eonic/EonicWeb5
Assemblies/Protean.Tools/XML.vb
Visual Basic
apache-2.0
81,194
Imports System.IO Friend Class NetworkBlock Private Shared nb As New NetworkBlock() Public Shared Function getInstance() As NetworkBlock Return nb End Function Protected blocks As New List(Of NB_interface)() Public Sub New() Dim reader As New StreamReader(New FileInfo("пока еше не сделанно, но вскоре будет").FullName) Do While Not reader.EndOfStream Dim line As String = reader.ReadLine() If line.Length = 0 Then Continue Do End If If line.StartsWith("//") Then Continue Do End If If line.StartsWith("d") Then Dim i As New NB_interface() i.directIp = line.Split(" "c)(1) i.forever = line.Split(" "c)(2).Equals("0") blocks.Add(i) ElseIf line.StartsWith("m") Then Dim i As New NB_interface() i.mask = line.Split(" "c)(1) i.forever = line.Split(" "c)(2).Equals("0") blocks.Add(i) End If Loop ' Logger.info("NetworkBlock: " & blocks.Count & " blocks.") End Sub Public Function allowed(ByVal ip As String) As Boolean If blocks.Count = 0 Then Return True End If For Each nbi As NB_interface In blocks If nbi.directIp IsNot Nothing Then If nbi.directIp.Equals(ip) Then If nbi.forever Then Return False Else If nbi.timeEnd.CompareTo(Date.Now) = 1 Then Return False End If End If End If End If If nbi.mask IsNot Nothing Then Dim a() As String = ip.Split("."c), b() As String = nbi.mask.Split("."c) Dim d(3) As Boolean For c As Integer = 0 To 3 d(c) = False If b(c) = "*" Then d(c) = True ElseIf b(c) = a(c) Then d(c) = True ElseIf b(c).Contains("/") Then Dim n As Short = Short.Parse(b(c).Split("/"c)(0)), x As Short = Short.Parse(b(c).Split("/"c)(1)) Dim t As Short = Short.Parse(a(c)) d(c) = t >= n AndAlso t <= x End If Next c For Each u As Boolean In d If u Then Return False End If Next u End If Next nbi Return True End Function End Class Public Class NB_interface Public directIp As String = Nothing Public mask As String = Nothing Public forever As Boolean = False Public timeEnd As Date End Class
LargoWinch/LegacyEmu
GameServer/Game_Server/GameServer/network/NetworkBlock.vb
Visual Basic
apache-2.0
2,960
Imports Com.Aspose.Storage.Api Imports Com.Aspose.Barcode.Api Imports Com.Aspose.Barcode.Model Namespace ManagingRecognition.WithoutCloudStorage Class ReadBarcodesbyApplyingImageProcessingAlgorithm Public Shared Sub Run() 'ExStart:1 ' Instantiate Aspose Storage Cloud API SDK Dim storageApi As New StorageApi(Common.APP_KEY, Common.APP_SID, Common.BASEPATH) ' Instantiate Aspose BarCode Cloud API SDK Dim barcodeApi As New BarcodeApi(Common.APP_KEY, Common.APP_SID, Common.BASEPATH) ' Set input file name Dim name As [String] = "sample-barcode.jpeg" ' The barcode type. If this parameter is empty, autodetection of all supported types is used. Dim type As [String] = "" ' Set folder location at cloud storage Dim folder As [String] = "" Dim body As New BarcodeReader() ' Set if FNC symbol stripping should be performed. body.StripFNC = True ' Set mode for checksum validation during recognition body.ChecksumValidation = "OFF" ' Set special mode of barcode binarization body.BinarizationHints = BinarizationHints.ComplexBackground Try ' Upload files to aspose cloud storage storageApi.PutCreate(name, "", "", System.IO.File.ReadAllBytes(Common.GetDataDir + name)) ' Invoke Aspose.BarCode Cloud SDK API to recognition of a barcode by apply various available image processing algorithms Dim apiResponse As BarcodeResponseList = barcodeApi.PutBarcodeRecognizeFromBody(name, type, folder, body) If apiResponse IsNot Nothing Then For Each barcode As Barcode In apiResponse.Barcodes Console.WriteLine("Codetext: " + barcode.BarcodeValue + vbLf & "Type: " + barcode.BarcodeType) Next Console.WriteLine("Read Barcodes by Applying Image Processing Algorithm, 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
aspose-barcode/Aspose.BarCode-for-Cloud
Examples/DotNET/VisualBasic/ManagingRecognition/WithoutCloudStorage/ReadBarcodesbyApplyingImageProcessingAlgorithm.vb
Visual Basic
mit
2,305
Public Enum ObjectType As Long None = 0 Diagnosis = 10060001 District = 10060002 Root = 10060003 Freezer = 10060004 FreezerContainer = 10060005 HumanCase = 10060006 InterfaceAction = 10060007 InterfaceObject = 10060008 Sample = 10060009 SentByOfficeAddress = 10060010 Site = 10060011 Test = 10060012 VetCase = 10060013 End Enum
EIDSS/EIDSS-Legacy
EIDSS v6/vb/EIDSS/EIDSS_Common/Enums/ObjectType.vb
Visual Basic
bsd-2-clause
400
Imports InfoSoftGlobal Partial Class BasicChartCSY Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Literal1.Text = FusionCharts.RenderChart("../FusionCharts/MSCombi2D.swf", "Data/CSYData.xml", "", "myFirst", "600", "300", False, True) End Sub End Class
TechFor/agile
public/js/FusionCharts/Code/VB_NET/BasicExample/BasicChart-CSY.aspx.vb
Visual Basic
bsd-3-clause
363
' 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 System.Xml.Linq Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Public Class SuggestionModeCompletionProviderTests Inherits AbstractVisualBasicCompletionProviderTests <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub FieldDeclaration1() Dim markup = <a>Class C $$ End Class</a> VerifyNotBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub FieldDeclaration2() Dim markup = <a>Class C Public $$ End Class</a> VerifyBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub FieldDeclaration3() Dim markup = <a>Module M Public $$ End Module</a> VerifyBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub FieldDeclaration4() Dim markup = <a>Structure S Public $$ End Structure</a> VerifyBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub FieldDeclaration5() Dim markup = <a>Class C WithEvents $$ End Class</a> VerifyBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub FieldDeclaration6() Dim markup = <a>Class C Protected Friend $$ End Class</a> VerifyBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub ParameterDeclaration1() Dim markup = <a>Class C Public Sub Bar($$ End Sub End Class</a> VerifyBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub ParameterDeclaration2() Dim markup = <a>Class C Public Sub Bar(Optional foo as Integer, $$ End Sub End Class</a> VerifyNotBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub ParameterDeclaration3() Dim markup = <a>Class C Public Sub Bar(Optional $$ End Sub End Class</a> VerifyBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub ParameterDeclaration4() Dim markup = <a>Class C Public Sub Bar(Optional x $$ End Sub End Class</a> VerifyNotBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub ParameterDeclaration5() Dim markup = <a>Class C Public Sub Bar(Optional x As $$ End Sub End Class</a> VerifyNotBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub ParameterDeclaration6() Dim markup = <a>Class C Public Sub Bar(Optional x As Integer $$ End Sub End Class</a> VerifyNotBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub ParameterDeclaration7() Dim markup = <a>Class C Public Sub Bar(ByVal $$ End Sub End Class</a> VerifyBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub ParameterDeclaration8() Dim markup = <a>Class C Public Sub Bar(ByVal x $$ End Sub End Class</a> VerifyNotBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub ParameterDeclaration9() Dim markup = <a>Class C Sub Foo $$ End Class</a> VerifyNotBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub ParameterDeclaration10() Dim markup = <a>Class C Public Property SomeProp $$ End Class</a> VerifyNotBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub SelectClause1() Dim markup = <a>Class z Sub bar() Dim a = New Integer(1, 2, 3) {} Dim foo = From z In a Select $$ End Sub End Class</a> VerifyBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub SelectClause2() Dim markup = <a>Class z Sub bar() Dim a = New Integer(1, 2, 3) {} Dim foo = From z In a Select 1, $$ End Sub End Class</a> VerifyBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub ForStatement1() Dim markup = <a>Class z Sub bar() For $$ End Sub End Class</a> VerifyBuilder(markup) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub ForStatement2() Dim markup = <a>Class z Sub bar() For $$ = 1 To 10 Next End Sub End Class</a> VerifyBuilder(markup) End Sub <WorkItem(545351)> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub BuilderWhenOptionExplicitOff() Dim markup = <a>Option Explicit Off Class C1 Sub M() Console.WriteLine($$ End Sub End Class </a> VerifyBuilder(markup) End Sub <WorkItem(546659)> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub UsingStatement() Dim markup = <a> Class C1 Sub M() Using $$ End Sub End Class </a> VerifyBuilder(markup) End Sub <WorkItem(734596)> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub OptionExplicitOffStatementLevel1() Dim markup = <a> Option Explicit Off Class C1 Sub M() $$ End Sub End Class </a> VerifyBuilder(markup) End Sub <WorkItem(734596)> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub OptionExplicitOffStatementLevel2() Dim markup = <a> Option Explicit Off Class C1 Sub M() a = $$ End Sub End Class </a> VerifyBuilder(markup) End Sub <WorkItem(960416)> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub ReadonlyField() Dim markup = <a> Class C1 Readonly $$ Sub M() End Sub End Class </a> VerifyBuilder(markup) End Sub <WorkItem(1044441)> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub BuilderInDebugger Dim markup = <a> Class C1 Sub Foo() Dim __o = $$ End Sub End Class </a> VerifyBuilder(markup, CompletionTriggerInfo.CreateInvokeCompletionTriggerInfo().WithIsDebugger(True)) End Sub Private Sub VerifyNotBuilder(markup As XElement, Optional triggerInfo As CompletionTriggerInfo? = Nothing) VerifySuggestionModeWorker(markup, isBuilder:=False, triggerInfo:=triggerInfo) End Sub Private Sub VerifyBuilder(markup As XElement, Optional triggerInfo As CompletionTriggerInfo? = Nothing) VerifySuggestionModeWorker(markup, isBuilder:=True, triggerInfo:=triggerInfo) End Sub Private Sub VerifySuggestionModeWorker(markup As XElement, isBuilder As Boolean, triggerInfo As CompletionTriggerInfo?) Dim code As String = Nothing Dim position As Integer = 0 MarkupTestFile.GetPosition(markup.NormalizedValue, code, position) Using workspaceFixture = New VisualBasicTestWorkspaceFixture() Dim document1 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular) CheckResults(document1, position, isBuilder, triggerInfo) If CanUseSpeculativeSemanticModel(document1, position) Then Dim document2 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular, cleanBeforeUpdate:=False) CheckResults(document2, position, isBuilder, triggerInfo) End If End Using End Sub Private Sub CheckResults(document As Document, position As Integer, isBuilder As Boolean, triggerInfo As CompletionTriggerInfo?) triggerInfo = If(triggerInfo, CompletionTriggerInfo.CreateTypeCharTriggerInfo("a"c)) Dim provider = CreateCompletionProvider() If isBuilder Then Dim group = provider.GetGroupAsync(document, position, triggerInfo.Value, CancellationToken.None).Result Assert.NotNull(group) Assert.NotNull(group.Builder) Else Dim group = provider.GetGroupAsync(document, position, triggerInfo.Value, CancellationToken.None).Result If group IsNot Nothing Then Assert.True(group.Builder Is Nothing, "group.Builder = " & group.Builder.DisplayText) End If End If End Sub Friend Overrides Function CreateCompletionProvider() As ICompletionProvider Return New VisualBasicSuggestionModeCompletionProvider() End Function End Class End Namespace
cybernet14/roslyn
src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/SuggestionModeCompletionProviderTests.vb
Visual Basic
apache-2.0
10,114
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Globalization Imports 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 Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class OverridesTests Inherits BasicTestBase ' Test that basic overriding of properties and methods works. ' Test OverriddenMethod/OverriddenProperty API. <Fact> Public Sub SimpleOverrides() Dim code = <compilation name="SimpleOverrides"> <file name="a.vb"> Imports System Class Base Public Overridable Sub O1(a As String) Console.WriteLine("Base.O1") End Sub Public Sub N1(a As String) Console.WriteLine("Base.N1") End Sub Public Overridable Property O2 As String Get Console.WriteLine("Base.O2.Get") Return "Base.O2" End Get Set(value As String) Console.WriteLine("Base.O2.Set") End Set End Property Public Overridable Property N2 As String Get Console.WriteLine("Base.N2.Get") Return "Base.N2" End Get Set(value As String) Console.WriteLine("Base.N2.Set") End Set End Property End Class Class Derived Inherits Base Public Overrides Sub O1(a As String) Console.WriteLine("Derived.O1") End Sub Public Shadows Sub N1(a As String) Console.WriteLine("Derived.N1") End Sub Public Overrides Property O2 As String Get Console.WriteLine("Derived.O2.Get") Return "Derived.O2" End Get Set(value As String) Console.WriteLine("Derived.O2.Set") End Set End Property Public Shadows Property N2 As String Get Console.WriteLine("Derived.N2.Get") Return "Derived.N2" End Get Set(value As String) Console.WriteLine("Derived.N2.Set") End Set End Property End Class Module Module1 Sub Main() Dim s As String Dim b As Base = New Derived() b.O1("hi") b.O2 = "x" s = b.O2 b.N1("hi") b.N2 = "x" s = b.N2 Console.WriteLine("---") b = New Base() b.O1("hi") b.O2 = "x" s = b.O2 b.N1("hi") b.N2 = "x" s = b.N2 Console.WriteLine("---") Dim d As Derived = New Derived() d.O1("hi") d.O2 = "x" s = d.O2 d.N1("hi") d.N2 = "x" s = d.N2 End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib(code) Dim globalNS = comp.GlobalNamespace Dim clsBase = DirectCast(globalNS.GetMembers("Base").Single(), NamedTypeSymbol) Dim clsDerived = DirectCast(globalNS.GetMembers("Derived").Single(), NamedTypeSymbol) Dim o1Base = DirectCast(clsBase.GetMembers("O1").Single(), MethodSymbol) Dim o1Derived = DirectCast(clsDerived.GetMembers("O1").Single(), MethodSymbol) Assert.Null(o1Base.OverriddenMethod) Assert.Same(o1Base, o1Derived.OverriddenMethod) Dim o2Base = DirectCast(clsBase.GetMembers("O2").Single(), PropertySymbol) Dim o2Derived = DirectCast(clsDerived.GetMembers("O2").Single(), PropertySymbol) Assert.Null(o2Base.OverriddenProperty) Assert.Same(o2Base, o2Derived.OverriddenProperty) Dim get_o2Base = DirectCast(clsBase.GetMembers("get_O2").Single(), MethodSymbol) Dim get_o2Derived = DirectCast(clsDerived.GetMembers("get_O2").Single(), MethodSymbol) Assert.Null(get_o2Base.OverriddenMethod) Assert.Same(get_o2Base, get_o2Derived.OverriddenMethod) Dim set_o2Base = DirectCast(clsBase.GetMembers("set_O2").Single(), MethodSymbol) Dim set_o2Derived = DirectCast(clsDerived.GetMembers("set_O2").Single(), MethodSymbol) Assert.Null(set_o2Base.OverriddenMethod) Assert.Same(set_o2Base, set_o2Derived.OverriddenMethod) Dim n1Base = DirectCast(clsBase.GetMembers("N1").Single(), MethodSymbol) Dim n1Derived = DirectCast(clsDerived.GetMembers("N1").Single(), MethodSymbol) Assert.Null(n1Base.OverriddenMethod) Assert.Null(n1Derived.OverriddenMethod) Dim n2Base = DirectCast(clsBase.GetMembers("N2").Single(), PropertySymbol) Dim n2Derived = DirectCast(clsDerived.GetMembers("N2").Single(), PropertySymbol) Assert.Null(n2Base.OverriddenProperty) Assert.Null(n2Derived.OverriddenProperty) Dim get_n2Base = DirectCast(clsBase.GetMembers("get_N2").Single(), MethodSymbol) Dim get_n2Derived = DirectCast(clsDerived.GetMembers("get_N2").Single(), MethodSymbol) Assert.Null(get_n2Base.OverriddenMethod) Assert.Null(get_n2Derived.OverriddenMethod) Dim set_n2Base = DirectCast(clsBase.GetMembers("set_N2").Single(), MethodSymbol) Dim set_n2Derived = DirectCast(clsDerived.GetMembers("set_N2").Single(), MethodSymbol) Assert.Null(set_n2Base.OverriddenMethod) Assert.Null(set_n2Derived.OverriddenMethod) CompileAndVerify(code, expectedOutput:=<![CDATA[ Derived.O1 Derived.O2.Set Derived.O2.Get Base.N1 Base.N2.Set Base.N2.Get --- Base.O1 Base.O2.Set Base.O2.Get Base.N1 Base.N2.Set Base.N2.Get --- Derived.O1 Derived.O2.Set Derived.O2.Get Derived.N1 Derived.N2.Set Derived.N2.Get]]>) End Sub <Fact> Public Sub UnimplementedMustOverride() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="UnimplementedMustOverride"> <file name="a.vb"> Option Strict On Namespace X Public MustInherit Class A Public MustOverride Sub foo(x As Integer) Public MustOverride Sub bar() Public MustOverride Sub quux() Protected MustOverride Function zing() As String Public MustOverride Property bing As Integer Public MustOverride ReadOnly Property bang As Integer End Class Public MustInherit Class B Inherits A Public Overrides Sub bar() End Sub Protected MustOverride Function baz() As String Protected Overrides Function zing() As String Return "" End Function End Class Partial MustInherit Class C Inherits B Public Overrides Property bing As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Protected MustOverride Overrides Function zing() As String End Class Class D Inherits C Public Overrides Sub quux() End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30610: Class 'D' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): C: Protected MustOverride Overrides Function zing() As String B: Protected MustOverride Function baz() As String A: Public MustOverride Sub foo(x As Integer) A: Public MustOverride ReadOnly Property bang As Integer. Class D ~ </expected>) End Sub <Fact> Public Sub HidingMembersInClass() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="HidingMembersInClass"> <file name="a.vb"> Option Strict On Namespace N Class A Public Sub foo() End Sub Public Sub foo(x As Integer) End Sub Public Sub bar() End Sub Public Sub bar(x As Integer) End Sub Private Sub bing() End Sub Public Const baz As Integer = 5 Public Const baz2 As Integer = 5 End Class Class B Inherits A Public Shadows Sub foo(x As String) End Sub End Class Class C Inherits B Public foo As String Public bing As Integer Public Shadows baz As Integer Public baz2 As Integer Public Enum bar Red End Enum End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40004: variable 'foo' conflicts with sub 'foo' in the base class 'B' and should be declared 'Shadows'. Public foo As String ~~~ BC40004: variable 'baz2' conflicts with variable 'baz2' in the base class 'A' and should be declared 'Shadows'. Public baz2 As Integer ~~~~ BC40004: enum 'bar' conflicts with sub 'bar' in the base class 'A' and should be declared 'Shadows'. Public Enum bar ~~~ </expected>) End Sub <WorkItem(540791, "DevDiv")> <Fact> Public Sub HidingMembersInClass_01() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="HidingMembersInClass"> <file name="a.vb"> Class C1 Inherits C2 ' no warnings here Class C(Of T) End Class ' warning Sub foo(Of T)() End Sub End Class Class C2 Class C End Class Sub Foo() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40003: sub 'foo' shadows an overloadable member declared in the base class 'C2'. If you want to overload the base method, this method must be declared 'Overloads'. Sub foo(Of T)() ~~~ </expected>) End Sub <Fact> Public Sub HidingMembersInInterface() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="HidingMembersInInterface"> <file name="a.vb"> Option Strict On Namespace N Interface A Sub foo() Sub foo(x As Integer) Enum e Red End Enum End Interface Interface B Sub bar() Sub bar(x As Integer) End Interface Interface C Inherits A, B ReadOnly Property quux As Integer End Interface Interface D Inherits C Enum bar Red End Enum Enum foo Red End Enum Shadows Enum quux red End Enum End Interface End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40004: enum 'bar' conflicts with sub 'bar' in the base interface 'B' and should be declared 'Shadows'. Enum bar ~~~ BC40004: enum 'foo' conflicts with sub 'foo' in the base interface 'A' and should be declared 'Shadows'. Enum foo ~~~ </expected>) End Sub <Fact> Public Sub AccessorHidingNonAccessor() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="AccessorHidingNonAccessor"> <file name="a.vb"> Namespace N Public Class A Public Property Z As Integer Public Property ZZ As Integer End Class Public Class B Inherits A Public Sub get_Z() End Sub Public Shadows Sub get_ZZ() End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40014: sub 'get_Z' conflicts with a member implicitly declared for property 'Z' in the base class 'A' and should be declared 'Shadows'. Public Sub get_Z() ~~~~~ </expected>) End Sub <Fact> Public Sub NonAccessorHidingAccessor() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="NonAccessorHidingAccessor"> <file name="a.vb"> Namespace N Public Class B Public Sub get_X() End Sub Public Sub get_XX() End Sub Public Sub set_Z() End Sub Public Sub set_ZZ() End Sub End Class Public Class A Inherits B Public Property X As Integer Public Property Z As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Shadows Property XX As Integer Public Shadows Property ZZ As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40012: property 'X' implicitly declares 'get_X', which conflicts with a member in the base class 'B', and so the property should be declared 'Shadows'. Public Property X As Integer ~ BC40012: property 'Z' implicitly declares 'set_Z', which conflicts with a member in the base class 'B', and so the property should be declared 'Shadows'. Public Property Z As Integer ~ </expected>) End Sub <Fact> Public Sub HidingShouldHaveOverloadsOrOverrides() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="AccessorHidingNonAccessor"> <file name="a.vb"> Namespace N Public Class A Public Sub foo() End Sub Public Overridable Property bar As Integer End Class Public Class B Inherits A Public Sub foo(a As Integer) End Sub Public Property bar As String End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40003: sub 'foo' shadows an overloadable member declared in the base class 'A'. If you want to overload the base method, this method must be declared 'Overloads'. Public Sub foo(a As Integer) ~~~ BC40005: property 'bar' shadows an overridable method in the base class 'A'. To override the base method, this method must be declared 'Overrides'. Public Property bar As String ~~~ </expected>) End Sub <Fact> Public Sub HiddenMustOverride() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="HiddenMustOverride"> <file name="a.vb"> Option Strict On Namespace N Public MustInherit Class A Public MustOverride Sub f() Public MustOverride Sub f(a As Integer) Public MustOverride Sub g() Public MustOverride Sub h() Public MustOverride Sub i() Public MustOverride Function j(a As String) as Integer End Class Public MustInherit Class B Inherits A Public Overrides Sub g() End Sub End Class Public MustInherit Class C Inherits B Public Overloads Sub h(x As Integer) End Sub End Class Public MustInherit Class D Inherits C Public Shadows f As Integer Public Shadows g As Integer Public Shadows Enum h Red End Enum Public Overloads Sub i(x As String, y As String) End Sub Public Overloads Function j(a as String) As String return "" End Function End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC31404: 'Public f As Integer' cannot shadow a method declared 'MustOverride'. Public Shadows f As Integer ~ BC31404: 'D.h' cannot shadow a method declared 'MustOverride'. Public Shadows Enum h ~ BC31404: 'Public Overloads Function j(a As String) As String' cannot shadow a method declared 'MustOverride'. Public Overloads Function j(a as String) As String ~ </expected>) End Sub <Fact> Public Sub AccessorHideMustOverride() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="AccessorHideMustOverride"> <file name="a.vb"> Namespace N Public MustInherit Class B Public MustOverride Property X As Integer Public MustOverride Function set_Y(a As Integer) End Class Public MustInherit Class A Inherits B Public Shadows Function get_X() As Integer Return 0 End Function Public Shadows Property Y As Integer End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC31413: 'Public Property Set Y(AutoPropertyValue As Integer)', implicitly declared for property 'Y', cannot shadow a 'MustOverride' method in the base class 'B'. Public Shadows Property Y As Integer ~ </expected>) End Sub <Fact> Public Sub NoOverride() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="NoOverride"> <file name="a.vb"> Option Strict On Namespace N Class A Public Overridable Property x As Integer Public Overridable Sub y() End Sub Public z As Integer End Class Class B Inherits A Public Overrides Sub x(a As String, b As Integer) End Sub Public Overrides Sub y(x As Integer) End Sub Public Overrides Property z As Integer End Class Structure K Public Overrides Function f() As Integer Return 0 End Function End Structure End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30284: sub 'x' cannot be declared 'Overrides' because it does not override a sub in a base class. Public Overrides Sub x(a As String, b As Integer) ~ BC40004: sub 'x' conflicts with property 'x' in the base class 'A' and should be declared 'Shadows'. Public Overrides Sub x(a As String, b As Integer) ~ BC30284: sub 'y' cannot be declared 'Overrides' because it does not override a sub in a base class. Public Overrides Sub y(x As Integer) ~ BC30284: property 'z' cannot be declared 'Overrides' because it does not override a property in a base class. Public Overrides Property z As Integer ~ BC40004: property 'z' conflicts with variable 'z' in the base class 'A' and should be declared 'Shadows'. Public Overrides Property z As Integer ~ BC30284: function 'f' cannot be declared 'Overrides' because it does not override a function in a base class. Public Overrides Function f() As Integer ~ </expected>) End Sub <Fact> Public Sub AmbiguousOverride() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="AmbiguousOverride"> <file name="a.vb"> Namespace N Class A(Of T, U) Public Overridable Sub foo(a As T) End Sub Public Overridable Sub foo(a As U) End Sub Public Overridable Sub foo(a As String) End Sub Public Overridable Property bar As Integer Public Overridable ReadOnly Property bar(a As T) As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property bar(a As U) As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property bar(a As String) As Integer Get Return 0 End Get End Property End Class Class B Inherits A(Of String, String) Public Overrides Sub foo(a As String) End Sub Public Overrides ReadOnly Property bar(a As String) As Integer Get Return 0 End Get End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30935: Member 'Public Overridable Sub foo(a As String)' that matches this signature cannot be overridden because the class 'A' contains multiple members with this same name and signature: 'Public Overridable Sub foo(a As T)' 'Public Overridable Sub foo(a As U)' 'Public Overridable Sub foo(a As String)' Public Overrides Sub foo(a As String) ~~~ BC30935: Member 'Public Overridable ReadOnly Property bar(a As String) As Integer' that matches this signature cannot be overridden because the class 'A' contains multiple members with this same name and signature: 'Public Overridable ReadOnly Property bar(a As T) As Integer' 'Public Overridable ReadOnly Property bar(a As U) As Integer' 'Public Overridable ReadOnly Property bar(a As String) As Integer' Public Overrides ReadOnly Property bar(a As String) As Integer ~~~ </expected>) End Sub <Fact> Public Sub OverrideNotOverridable() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="OverrideNotOverridable"> <file name="a.vb"> Option Strict On Namespace N Public Class A Public Overridable Sub f() End Sub Public Overridable Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Public Class B Inherits A Public NotOverridable Overrides Sub f() End Sub Public NotOverridable Overrides Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Public Class C Inherits B Public Overrides Sub f() End Sub Public NotOverridable Overrides Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30267: 'Public Overrides Sub f()' cannot override 'Public NotOverridable Overrides Sub f()' because it is declared 'NotOverridable'. Public Overrides Sub f() ~ BC30267: 'Public NotOverridable Overrides Property p As Integer' cannot override 'Public NotOverridable Overrides Property p As Integer' because it is declared 'NotOverridable'. Public NotOverridable Overrides Property p As Integer ~ </expected>) End Sub <Fact> Public Sub MustBeOverridable() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="MustBeOverridable"> <file name="a.vb"> Option Strict On Namespace N Public Class A Public Sub f() End Sub Public Property p As Integer End Class Public Class B Inherits A Public Overrides Sub f() End Sub Public Overrides Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC31086: 'Public Overrides Sub f()' cannot override 'Public Sub f()' because it is not declared 'Overridable'. Public Overrides Sub f() ~ BC31086: 'Public Overrides Property p As Integer' cannot override 'Public Property p As Integer' because it is not declared 'Overridable'. Public Overrides Property p As Integer ~ </expected>) End Sub <Fact> Public Sub ByRefMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="ByRefMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Sub f(q As String, ByRef a As Integer) End Sub End Class Class B Inherits A Public Overrides Sub f(q As String, a As Integer) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30398: 'Public Overrides Sub f(q As String, a As Integer)' cannot override 'Public Overridable Sub f(q As String, ByRef a As Integer)' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'. Public Overrides Sub f(q As String, a As Integer) ~ </expected>) End Sub <Fact> Public Sub OptionalMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="OptionalMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Sub f(q As String, Optional a As Integer = 5) End Sub Public Overridable Sub g(q As String) End Sub Public Overridable Property p1(q As String, Optional a As Integer = 5) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable Property p2(q As String) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Class B Inherits A Public Overrides Sub f(q As String) End Sub Public Overrides Sub g(q As String, Optional a As Integer = 4) End Sub Public Overrides Property p1(q As String) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overrides Property p2(q As String, Optional a As Integer = 5) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30308: 'Public Overrides Sub f(q As String)' cannot override 'Public Overridable Sub f(q As String, [a As Integer = 5])' because they differ by optional parameters. Public Overrides Sub f(q As String) ~ BC30308: 'Public Overrides Sub g(q As String, [a As Integer = 4])' cannot override 'Public Overridable Sub g(q As String)' because they differ by optional parameters. Public Overrides Sub g(q As String, Optional a As Integer = 4) ~ BC30308: 'Public Overrides Property p1(q As String) As Integer' cannot override 'Public Overridable Property p1(q As String, [a As Integer = 5]) As Integer' because they differ by optional parameters. Public Overrides Property p1(q As String) As Integer ~~ BC30308: 'Public Overrides Property p2(q As String, [a As Integer = 5]) As Integer' cannot override 'Public Overridable Property p2(q As String) As Integer' because they differ by optional parameters. Public Overrides Property p2(q As String, Optional a As Integer = 5) As Integer ~~ </expected>) End Sub <Fact> Public Sub ReturnTypeMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="ReturnTypeMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Function x(a As Integer) As String Return "" End Function Public Overridable Function y(Of T)() As T Return Nothing End Function Public Overridable Sub z() End Sub Public Overridable Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Class B Inherits A Public Overrides Function y(Of U)() As U Return Nothing End Function Public Overrides Function x(a As Integer) As Integer Return 0 End Function Public Overrides Function z() As Integer Return 0 End Function Public Overrides Property p As String Get Return "" End Get Set(value As String) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30437: 'Public Overrides Function x(a As Integer) As Integer' cannot override 'Public Overridable Function x(a As Integer) As String' because they differ by their return types. Public Overrides Function x(a As Integer) As Integer ~ BC30437: 'Public Overrides Function z() As Integer' cannot override 'Public Overridable Sub z()' because they differ by their return types. Public Overrides Function z() As Integer ~ BC30437: 'Public Overrides Property p As String' cannot override 'Public Overridable Property p As Integer' because they differ by their return types. Public Overrides Property p As String ~ </expected>) End Sub <Fact> Public Sub PropertyTypeMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="PropertyTypeMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable ReadOnly Property q As Integer Get Return 0 End Get End Property Public Overridable WriteOnly Property r As Integer Set(value As Integer) End Set End Property End Class Class B Inherits A Public Overrides ReadOnly Property p As Integer Get Return 0 End Get End Property Public Overrides WriteOnly Property q As Integer Set(value As Integer) End Set End Property Public Overrides Property r As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30362: 'Public Overrides ReadOnly Property p As Integer' cannot override 'Public Overridable Property p As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property p As Integer ~ BC30362: 'Public Overrides WriteOnly Property q As Integer' cannot override 'Public Overridable ReadOnly Property q As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides WriteOnly Property q As Integer ~ BC30362: 'Public Overrides Property r As Integer' cannot override 'Public Overridable WriteOnly Property r As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property r As Integer ~ </expected>) End Sub <WorkItem(540791, "DevDiv")> <Fact> Public Sub PropertyAccessibilityMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="PropertyAccessibilityMismatch"> <file name="a.vb"> Public Class Base Public Overridable Property Property1() As Long Get Return m_Property1 End Get Protected Set(value As Long) m_Property1 = Value End Set End Property Private m_Property1 As Long End Class Public Class Derived1 Inherits Base Public Overrides Property Property1() As Long Get Return m_Property1 End Get Private Set(value As Long) m_Property1 = Value End Set End Property Private m_Property1 As Long End Class </file> </compilation>) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_BadOverrideAccess2, "Set").WithArguments("Private Overrides Property Set Property1(value As Long)", "Protected Overridable Property Set Property1(value As Long)")) End Sub <Fact> Public Sub PropertyAccessibilityMismatch2() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="PropertyAccessibilityMismatch"> <file name="a.vb"> Public Class Base Public Overridable Property Property1() As Long Get Return m_Property1 End Get Set(value As Long) m_Property1 = Value End Set End Property Private m_Property1 As Long End Class Public Class Derived1 Inherits Base Public Overrides Property Property1() As Long Protected Get Return m_Property1 End Get Set(value As Long) m_Property1 = Value End Set End Property Private m_Property1 As Long End Class </file> </compilation>) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_BadOverrideAccess2, "Get").WithArguments("Protected Overrides Property Get Property1() As Long", "Public Overridable Property Get Property1() As Long")) End Sub <Fact> <WorkItem(546836, "DevDiv")> Public Sub PropertyOverrideAccessibility() Dim csharpComp = CreateCSharpCompilation("Lib", <![CDATA[ public class A { public virtual int P { get { System.Console.WriteLine("A.P.get"); return 0; } protected internal set { System.Console.WriteLine("A.P.set"); } } } public class B : A { public override int P { protected internal set { System.Console.WriteLine("B.P.set"); } } } public class C : A { public override int P { get { System.Console.WriteLine("C.P.get"); return 0; } } } ]]>) csharpComp.VerifyDiagnostics() Dim csharpRef = csharpComp.EmitToImageReference() Dim vbComp = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="PropertyOverrideAccessibility"> <file name="a.vb"> Public Class D1 Inherits A Public Overrides Property P() As Integer Get System.Console.WriteLine("D1.P.get") Return 0 End Get Protected Set(value As Integer) System.Console.WriteLine("D1.P.set") End Set End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Public Class D2 Inherits B Protected Overrides WriteOnly Property P() As Integer Set(value As Integer) System.Console.WriteLine("D2.P.set") End Set End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Public Class D3 Inherits C Public Overrides ReadOnly Property P() As Integer Get System.Console.WriteLine("D3.P.get") Return 0 End Get End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Module Test Sub Main() Dim d1 As New D1() Dim d2 As New D2() Dim d3 As New D3() d1.Test() d2.Test() d3.Test() End Sub End Module </file> </compilation>, {csharpRef}, TestOptions.ReleaseExe) CompileAndVerify(vbComp, emitOptions:=TestEmitters.CCI, expectedOutput:=<![CDATA[ D1.P.set D1.P.get D2.P.set A.P.get A.P.set D3.P.get ]]>) Dim errorComp = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="PropertyOverrideAccessibility"> <file name="a.vb"> ' Set is protected friend, but should be protected Public Class D1 Inherits A Public Overrides Property P() As Integer Get Return 0 End Get Protected Friend Set(value As Integer) End Set End Property End Class ' protected friend, should be protected Public Class D2 Inherits B Protected Friend Overrides WriteOnly Property P() As Integer Set(value As Integer) End Set End Property End Class ' Can't override getter (Dev11 also gives error about accessibility change) Public Class D3 Inherits B Public Overrides ReadOnly Property P() As Integer Get Return 0 End Get End Property End Class ' Getter has to be public Public Class D4 Inherits C Protected Overrides ReadOnly Property P() As Integer Get Return 0 End Get End Property End Class ' Can't override setter (Dev11 also gives error about accessibility change) Public Class D5 Inherits C Protected Overrides WriteOnly Property P() As Integer Set(value As Integer) End Set End Property End Class </file> </compilation>, {csharpRef}) errorComp.VerifyDiagnostics( Diagnostic(ERRID.ERR_FriendAssemblyBadAccessOverride2, "P").WithArguments("Protected Friend Overrides WriteOnly Property P As Integer", "Protected Friend Overrides WriteOnly Property P As Integer"), Diagnostic(ERRID.ERR_FriendAssemblyBadAccessOverride2, "Set").WithArguments("Protected Friend Overrides Property Set P(value As Integer)", "Protected Friend Overridable Overloads Property Set P(value As Integer)"), Diagnostic(ERRID.ERR_OverridingPropertyKind2, "P").WithArguments("Protected Overrides WriteOnly Property P As Integer", "Public Overrides ReadOnly Property P As Integer"), Diagnostic(ERRID.ERR_OverridingPropertyKind2, "P").WithArguments("Public Overrides ReadOnly Property P As Integer", "Protected Friend Overrides WriteOnly Property P As Integer"), Diagnostic(ERRID.ERR_BadOverrideAccess2, "P").WithArguments("Protected Overrides ReadOnly Property P As Integer", "Public Overrides ReadOnly Property P As Integer")) End Sub <Fact> <WorkItem(546836, "DevDiv")> Public Sub PropertyOverrideAccessibilityInternalsVisibleTo() Dim csharpComp = CreateCSharpCompilation("Lib", <![CDATA[ [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("PropertyOverrideAccessibilityInternalsVisibleTo")] public class A { public virtual int P { get { System.Console.WriteLine("A.P.get"); return 0; } protected internal set { System.Console.WriteLine("A.P.set"); } } internal static void ConfirmIVT() { } } public class B : A { public override int P { protected internal set { System.Console.WriteLine("B.P.set"); } } } public class C : A { public override int P { get { System.Console.WriteLine("C.P.get"); return 0; } } } ]]>) csharpComp.VerifyDiagnostics() Dim csharpRef = csharpComp.EmitToImageReference() ' Unlike in C#, internals-visible-to does not affect the way protected friend ' members are overridden (i.e. still must be protected). Dim vbComp = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="PropertyOverrideAccessibilityInternalsVisibleTo"> <file name="a.vb"> Public Class D1 Inherits A Public Overrides Property P() As Integer Get System.Console.WriteLine("D1.P.get") Return 0 End Get Protected Set(value As Integer) System.Console.WriteLine("D1.P.set") End Set End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Public Class D2 Inherits B Protected Overrides WriteOnly Property P() As Integer Set(value As Integer) System.Console.WriteLine("D2.P.set") End Set End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Public Class D3 Inherits C Public Overrides ReadOnly Property P() As Integer Get System.Console.WriteLine("D3.P.get") Return 0 End Get End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Module Test Sub Main() A.ConfirmIVT() Dim d1 As New D1() Dim d2 As New D2() Dim d3 As New D3() d1.Test() d2.Test() d3.Test() End Sub End Module </file> </compilation>, {csharpRef}, TestOptions.ReleaseExe) CompileAndVerify(vbComp, emitOptions:=TestEmitters.CCI, expectedOutput:=<![CDATA[ D1.P.set D1.P.get D2.P.set A.P.get A.P.set D3.P.get ]]>) Dim errorComp = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="PropertyOverrideAccessibility"> <file name="a.vb"> ' Set is protected friend, but should be protected Public Class D1 Inherits A Public Overrides Property P() As Integer Get Return 0 End Get Protected Friend Set(value As Integer) End Set End Property End Class ' protected friend, should be protected Public Class D2 Inherits B Protected Friend Overrides WriteOnly Property P() As Integer Set(value As Integer) End Set End Property End Class ' Can't override getter (Dev11 also gives error about accessibility change) Public Class D3 Inherits B Public Overrides ReadOnly Property P() As Integer Get Return 0 End Get End Property End Class ' Getter has to be public Public Class D4 Inherits C Protected Overrides ReadOnly Property P() As Integer Get Return 0 End Get End Property End Class ' Can't override setter (Dev11 also gives error about accessibility change) Public Class D5 Inherits C Protected Overrides WriteOnly Property P() As Integer Set(value As Integer) End Set End Property End Class </file> </compilation>, {csharpRef}) errorComp.VerifyDiagnostics( Diagnostic(ERRID.ERR_FriendAssemblyBadAccessOverride2, "P").WithArguments("Protected Friend Overrides WriteOnly Property P As Integer", "Protected Friend Overrides WriteOnly Property P As Integer"), Diagnostic(ERRID.ERR_FriendAssemblyBadAccessOverride2, "Set").WithArguments("Protected Friend Overrides Property Set P(value As Integer)", "Protected Friend Overridable Overloads Property Set P(value As Integer)"), Diagnostic(ERRID.ERR_OverridingPropertyKind2, "P").WithArguments("Protected Overrides WriteOnly Property P As Integer", "Public Overrides ReadOnly Property P As Integer"), Diagnostic(ERRID.ERR_OverridingPropertyKind2, "P").WithArguments("Public Overrides ReadOnly Property P As Integer", "Protected Friend Overrides WriteOnly Property P As Integer"), Diagnostic(ERRID.ERR_BadOverrideAccess2, "P").WithArguments("Protected Overrides ReadOnly Property P As Integer", "Public Overrides ReadOnly Property P As Integer")) End Sub <Fact()> Public Sub OptionalValueMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="OptionalValueMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Property p(Optional k As Integer = 4) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable Sub f(Optional k As String = "foo") End Sub End Class Class B Inherits A Public Overrides Property p(Optional k As Integer = 7) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overrides Sub f(Optional k As String = "hi") End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30307: 'Public Overrides Property p([k As Integer = 7]) As Integer' cannot override 'Public Overridable Property p([k As Integer = 4]) As Integer' because they differ by the default values of optional parameters. Public Overrides Property p(Optional k As Integer = 7) As Integer ~ BC30307: 'Public Overrides Sub f([k As String = "hi"])' cannot override 'Public Overridable Sub f([k As String = "foo"])' because they differ by the default values of optional parameters. Public Overrides Sub f(Optional k As String = "hi") ~ </expected>) End Sub <Fact> Public Sub ParamArrayMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="ParamArrayMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Property p(x() As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable Sub f(ParamArray x() As String) End Sub End Class Class B Inherits A Public Overrides Property p(ParamArray x() As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overrides Sub f(x() As String) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30906: 'Public Overrides Property p(ParamArray x As Integer()) As Integer' cannot override 'Public Overridable Property p(x As Integer()) As Integer' because they differ by parameters declared 'ParamArray'. Public Overrides Property p(ParamArray x() As Integer) As Integer ~ BC30906: 'Public Overrides Sub f(x As String())' cannot override 'Public Overridable Sub f(ParamArray x As String())' because they differ by parameters declared 'ParamArray'. Public Overrides Sub f(x() As String) ~ </expected>) End Sub <WorkItem(529018, "DevDiv")> <Fact()> Public Sub OptionalTypeMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="OptionalTypeMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Property p(Optional x As String = "") As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable Sub f(Optional x As String = "") End Sub End Class Class B Inherits A Public Overrides Property p(Optional x As Integer = 0) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overrides Sub f(Optional x As Integer = 0) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30697: 'Public Overrides Property p([x As Integer = 0]) As Integer' cannot override 'Public Overridable Property p([x As String = ""]) As Integer' because they differ by the types of optional parameters. Public Overrides Property p(Optional x As Integer = 0) As Integer ~ BC30697: 'Public Overrides Sub f([x As Integer = 0])' cannot override 'Public Overridable Sub f([x As String = ""])' because they differ by the types of optional parameters. Public Overrides Sub f(Optional x As Integer = 0) ~ </expected>) End Sub <Fact()> Public Sub ConstraintMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="ConstraintMismatch"> <file name="a.vb"> Imports System Namespace N Class A Public Overridable Sub f(Of T As ICloneable)(x As T) End Sub End Class Class B Inherits A Public Overrides Sub f(Of U)(x As U) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC32077: 'Public Overrides Sub f(Of U)(x As U)' cannot override 'Public Overridable Sub f(Of T As ICloneable)(x As T)' because they differ by type parameter constraints. Public Overrides Sub f(Of U)(x As U) ~ </expected>) End Sub <Fact> Public Sub AccessMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="AccessMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Sub f() End Sub Protected Overridable Sub g() End Sub Friend Overridable Sub h() End Sub End Class Class B Inherits A Protected Overrides Sub f() End Sub Public Overrides Sub g() End Sub Protected Friend Overrides Sub h() End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30266: 'Protected Overrides Sub f()' cannot override 'Public Overridable Sub f()' because they have different access levels. Protected Overrides Sub f() ~ BC30266: 'Public Overrides Sub g()' cannot override 'Protected Overridable Sub g()' because they have different access levels. Public Overrides Sub g() ~ BC30266: 'Protected Friend Overrides Sub h()' cannot override 'Friend Overridable Sub h()' because they have different access levels. Protected Friend Overrides Sub h() ~ </expected>) End Sub <Fact> Public Sub PropertyShadows() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> Interface IA Default Overloads ReadOnly Property P(o As Object) Property Q(o As Object) End Interface Interface IB Inherits IA Default Overloads ReadOnly Property P(x As Integer, y As Integer) Overloads Property Q(x As Integer, y As Integer) End Interface Interface IC Inherits IA Default Shadows ReadOnly Property P(x As Integer, y As Integer) Shadows Property Q(x As Integer, y As Integer) End Interface Module M Sub M(b As IB, c As IC) Dim value As Object value = b.P(1, 2) value = b.P(3) value = b(1, 2) value = b(3) b.Q(1, 2) = value b.Q(3) = value value = c.P(1, 2) value = c.P(3) value = c(1, 2) value = c(3) c.Q(1, 2) = value c.Q(3) = value End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'y' of 'ReadOnly Default Property P(x As Integer, y As Integer) As Object'. value = c.P(3) ~ BC30455: Argument not specified for parameter 'y' of 'ReadOnly Default Property P(x As Integer, y As Integer) As Object'. value = c(3) ~ BC30455: Argument not specified for parameter 'y' of 'Property Q(x As Integer, y As Integer) As Object'. c.Q(3) = value ~ </expected>) End Sub <Fact> Public Sub ShadowsNotOverloads() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> Class A Public Sub M1(o As Object) End Sub Public Overloads Sub M2(o As Object) End Sub Public ReadOnly Property P1(o As Object) Get Return Nothing End Get End Property Public Overloads ReadOnly Property P2(o As Object) Get Return Nothing End Get End Property End Class Class B Inherits A Public Shadows Sub M1(x As Integer, y As Integer) End Sub Public Overloads Sub M2(x As Integer, y As Integer) End Sub Public Shadows ReadOnly Property P1(x As Integer, y As Integer) Get Return Nothing End Get End Property Public Overloads ReadOnly Property P2(x As Integer, y As Integer) Get Return Nothing End Get End Property End Class Module M Sub M(o As B) Dim value o.M1(1) o.M2(1) value = o.P1(1) value = o.P2(1) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'y' of 'Public Sub M1(x As Integer, y As Integer)'. o.M1(1) ~~ BC30455: Argument not specified for parameter 'y' of 'Public ReadOnly Property P1(x As Integer, y As Integer) As Object'. value = o.P1(1) ~~ </expected>) End Sub <Fact> Public Sub OverridingBlockedByShadowing() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> Class A Overridable Sub Foo() End Sub Overridable Sub Bar() End Sub Overridable Sub Quux() End Sub End Class Class B Inherits A Shadows Sub Foo(x As Integer) End Sub Overloads Property Bar(x As Integer) Get Return Nothing End Get Set(value) End Set End Property Public Shadows Quux As Integer End Class Class C Inherits B Overrides Sub Foo() End Sub Overrides Sub Bar() End Sub Overrides Sub Quux() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC40004: property 'Bar' conflicts with sub 'Bar' in the base class 'A' and should be declared 'Shadows'. Overloads Property Bar(x As Integer) ~~~ BC30284: sub 'Foo' cannot be declared 'Overrides' because it does not override a sub in a base class. Overrides Sub Foo() ~~~ BC30284: sub 'Bar' cannot be declared 'Overrides' because it does not override a sub in a base class. Overrides Sub Bar() ~~~ BC40004: sub 'Bar' conflicts with property 'Bar' in the base class 'B' and should be declared 'Shadows'. Overrides Sub Bar() ~~~ BC30284: sub 'Quux' cannot be declared 'Overrides' because it does not override a sub in a base class. Overrides Sub Quux() ~~~~ BC40004: sub 'Quux' conflicts with variable 'Quux' in the base class 'B' and should be declared 'Shadows'. Overrides Sub Quux() ~~~~ </expected>) End Sub <WorkItem(541752, "DevDiv")> <Fact> Public Sub Bug8634() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> Class A Overridable Sub Foo() End Sub End Class Class B Inherits A Shadows Property Foo() As Integer End Class Class C Inherits B Overrides Sub Foo() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30284: sub 'Foo' cannot be declared 'Overrides' because it does not override a sub in a base class. Overrides Sub Foo() ~~~ BC40004: sub 'Foo' conflicts with property 'Foo' in the base class 'B' and should be declared 'Shadows'. Overrides Sub Foo() ~~~ </expected>) End Sub <Fact> Public Sub HideBySig() Dim customIL = <![CDATA[ .class public A { .method public hidebysig instance object F(object o) { ldnull ret } .method public instance object G(object o) { ldnull ret } .method public hidebysig instance object get_P(object o) { ldnull ret } .method public instance object get_Q(object o) { ldnull ret } .property object P(object o) { .get instance object A::get_P(object o) } .property object Q(object o) { .get instance object A::get_Q(object o) } } .class public B extends A { .method public hidebysig instance object F(object x, object y) { ldnull ret } .method public instance object G(object x, object y) { ldnull ret } .method public hidebysig instance object get_P(object x, object y) { ldnull ret } .method public instance object get_Q(object x, object y) { ldnull ret } .property object P(object x, object y) { .get instance object B::get_P(object x, object y) } .property object Q(object x, object y) { .get instance object B::get_Q(object x, object y) } } .class public C { .method public hidebysig instance object F(object o) { ldnull ret } .method public hidebysig instance object F(object x, object y) { ldnull ret } .method public instance object G(object o) { ldnull ret } .method public instance object G(object x, object y) { ldnull ret } .method public hidebysig instance object get_P(object o) { ldnull ret } .method public hidebysig instance object get_P(object x, object y) { ldnull ret } .method public instance object get_Q(object o) { ldnull ret } .method public instance object get_Q(object x, object y) { ldnull ret } .property object P(object o) { .get instance object C::get_P(object o) } .property object P(object x, object y) { .get instance object C::get_P(object x, object y) } .property object Q(object o) { .get instance object C::get_Q(object o) } .property object Q(object x, object y) { .get instance object C::get_Q(object x, object y) } } ]]> Dim source = <compilation> <file name="a.vb"> Module M Sub M(b As B, c As C) Dim value As Object value = b.F(b, c) value = b.F(Nothing) value = b.G(b, c) value = b.G(Nothing) value = b.P(b, c) value = b.P(Nothing) value = b.Q(b, c) value = b.Q(Nothing) value = c.F(b, c) value = c.F(Nothing) value = c.G(b, c) value = c.G(Nothing) value = c.P(b, c) value = c.P(Nothing) value = c.Q(b, c) value = c.Q(Nothing) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'y' of 'Public Function G(x As Object, y As Object) As Object'. value = b.G(Nothing) ~ BC30455: Argument not specified for parameter 'y' of 'Public ReadOnly Property Q(x As Object, y As Object) As Object'. value = b.Q(Nothing) ~ </expected>) End Sub <Fact()> Public Sub Bug10702() Dim code = <compilation name="SimpleOverrides"> <file name="a.vb"> Imports System.Collections.Generic Class SyntaxNode : End Class Structure SyntaxToken : End Structure Class CancellationToken : End Class Class Diagnostic : End Class MustInherit Class BaseSyntaxTree Protected MustOverride Overloads Function GetDiagnosticsCore(Optional cancellationToken As CancellationToken = Nothing) As IEnumerable(Of Diagnostic) Protected MustOverride Overloads Function GetDiagnosticsCore(node As SyntaxNode) As IEnumerable(Of Diagnostic) Protected MustOverride Overloads Function GetDiagnosticsCore(token As SyntaxToken) As IEnumerable(Of Diagnostic) End Class Class SyntaxTree : Inherits BaseSyntaxTree Protected Overrides Function GetDiagnosticsCore(Optional cancellationToken As CancellationToken = Nothing) As IEnumerable(Of Diagnostic) Return Nothing End Function Protected Overrides Function GetDiagnosticsCore(node As SyntaxNode) As IEnumerable(Of Diagnostic) Return Nothing End Function Protected Overrides Function GetDiagnosticsCore(token As SyntaxToken) As IEnumerable(Of Diagnostic) Return Nothing End Function End Class Public Module Module1 Sub Main() End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib(code) CompileAndVerify(code).VerifyDiagnostics() End Sub <Fact, WorkItem(543948, "DevDiv")> Public Sub OverrideMemberOfConstructedProtectedInnerClass() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> Public Class Outer1(Of T) Protected MustInherit Class Inner1 Public MustOverride Sub Method() End Class Protected MustInherit Class Inner2 Inherits Inner1 Public Overrides Sub Method() End Sub End Class End Class </file> </compilation>) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlibAndReferences( <compilation> <file name="a.vb"> Friend Class Outer2 Inherits Outer1(Of Outer2) Private Class Inner3 Inherits Inner2 End Class End Class </file> </compilation>, {New VisualBasicCompilationReference(compilation1)}) CompilationUtils.AssertNoErrors(compilation2) End Sub <Fact, WorkItem(545484, "DevDiv")> Public Sub MetadataOverridesOfAccessors() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class X1 Public Overridable Property Foo As Integer Get Return 1 End Get Set(value As Integer) End Set End Property End Class </file> </compilation>) Dim compilation2 = CreateCSharpCompilation("assem2", <![CDATA[ using System; public class X2: X1 { public override int Foo { get { return base.Foo; } set { base.Foo = value; } } public virtual event Action Bar { add{} remove{}} } public class X3: X2 { public override event Action Bar { add {} remove {} } } ]]>.Value, referencedCompilations:={compilation1}) Dim compilation2Bytes = compilation2.EmitToArray() Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Option Strict On Class Dummy End Class </file> </compilation>, additionalRefs:={New VisualBasicCompilationReference(compilation1), MetadataReference.CreateFromImage(compilation2Bytes)}) Dim globalNS = compilation3.GlobalNamespace Dim classX1 = DirectCast(globalNS.GetMembers("X1").First(), NamedTypeSymbol) Dim propX1Foo = DirectCast(classX1.GetMembers("Foo").First(), PropertySymbol) Dim accessorX1GetFoo = DirectCast(classX1.GetMembers("get_Foo").First(), MethodSymbol) Dim accessorX1SetFoo = DirectCast(classX1.GetMembers("set_Foo").First(), MethodSymbol) Dim classX2 = DirectCast(globalNS.GetMembers("X2").First(), NamedTypeSymbol) Dim propX2Foo = DirectCast(classX2.GetMembers("Foo").First(), PropertySymbol) Dim accessorX2GetFoo = DirectCast(classX2.GetMembers("get_Foo").First(), MethodSymbol) Dim accessorX2SetFoo = DirectCast(classX2.GetMembers("set_Foo").First(), MethodSymbol) Dim classX3 = DirectCast(globalNS.GetMembers("X3").First(), NamedTypeSymbol) Dim overriddenPropX1Foo = propX1Foo.OverriddenProperty Assert.Null(overriddenPropX1Foo) Dim overriddenPropX2Foo = propX2Foo.OverriddenProperty Assert.NotNull(overriddenPropX2Foo) Assert.Equal(propX1Foo, overriddenPropX2Foo) Dim overriddenAccessorX1GetFoo = accessorX1GetFoo.OverriddenMethod Assert.Null(overriddenAccessorX1GetFoo) Dim overriddenAccessorX2GetFoo = accessorX2GetFoo.OverriddenMethod Assert.NotNull(overriddenAccessorX2GetFoo) Assert.Equal(accessorX1GetFoo, overriddenAccessorX2GetFoo) Dim overriddenAccessorX1SetFoo = accessorX1SetFoo.OverriddenMethod Assert.Null(overriddenAccessorX1SetFoo) Dim overriddenAccessorX2SetFoo = accessorX2SetFoo.OverriddenMethod Assert.NotNull(overriddenAccessorX2SetFoo) Assert.Equal(accessorX1SetFoo, overriddenAccessorX2SetFoo) Dim eventX2Bar = DirectCast(classX2.GetMembers("Bar").First(), EventSymbol) Dim accessorX2AddBar = DirectCast(classX2.GetMembers("add_Bar").First(), MethodSymbol) Dim accessorX2RemoveBar = DirectCast(classX2.GetMembers("remove_Bar").First(), MethodSymbol) Dim eventX3Bar = DirectCast(classX3.GetMembers("Bar").First(), EventSymbol) Dim accessorX3AddBar = DirectCast(classX3.GetMembers("add_Bar").First(), MethodSymbol) Dim accessorX3RemoveBar = DirectCast(classX3.GetMembers("remove_Bar").First(), MethodSymbol) Dim overriddenEventX2Bar = eventX2Bar.OverriddenEvent Assert.Null(overriddenEventX2Bar) Dim overriddenEventX3Bar = eventX3Bar.OverriddenEvent Assert.NotNull(overriddenEventX3Bar) Assert.Equal(eventX2Bar, overriddenEventX3Bar) Dim overriddenAccessorsX2AddBar = accessorX2AddBar.OverriddenMethod Assert.Null(overriddenAccessorsX2AddBar) Dim overriddenAccessorsX3AddBar = accessorX3AddBar.OverriddenMethod Assert.NotNull(overriddenAccessorsX3AddBar) Assert.Equal(accessorX2AddBar, overriddenAccessorsX3AddBar) Dim overriddenAccessorsX2RemoveBar = accessorX2RemoveBar.OverriddenMethod Assert.Null(overriddenAccessorsX2RemoveBar) Dim overriddenAccessorsX3RemoveBar = accessorX3RemoveBar.OverriddenMethod Assert.NotNull(overriddenAccessorsX3RemoveBar) Assert.Equal(accessorX2RemoveBar, overriddenAccessorsX3RemoveBar) End Sub <Fact, WorkItem(545484, "DevDiv")> Public Sub OverridesOfConstructedMethods() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class X1 Public Overridable Function Foo(Of T)(x as T) As Integer Return 1 End Function End Class </file> </compilation>) Dim compilation2 = CreateCSharpCompilation("assem2", <![CDATA[ using System; public class X2: X1 { public override int Foo<T>(T x) { return base.Foo(x); } } ]]>.Value, referencedCompilations:={compilation1}) Dim compilation2Bytes = compilation2.EmitToArray() Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Option Strict On Class Dummy End Class </file> </compilation>, additionalRefs:={New VisualBasicCompilationReference(compilation1), MetadataReference.CreateFromImage(compilation2Bytes)}) Dim globalNS = compilation3.GlobalNamespace Dim classX1 = DirectCast(globalNS.GetMembers("X1").First(), NamedTypeSymbol) Dim methodX1Foo = DirectCast(classX1.GetMembers("Foo").First(), MethodSymbol) Dim classX2 = DirectCast(globalNS.GetMembers("X2").First(), NamedTypeSymbol) Dim methodX2Foo = DirectCast(classX2.GetMembers("Foo").First(), MethodSymbol) Dim overriddenMethX1Foo = methodX1Foo.OverriddenMethod Assert.Null(overriddenMethX1Foo) Dim overriddenMethX2Foo = methodX2Foo.OverriddenMethod Assert.NotNull(overriddenMethX2Foo) Assert.Equal(methodX1Foo, overriddenMethX2Foo) ' Constructed methods should never override. Dim constructedMethodX1Foo = methodX1Foo.Construct(compilation3.GetWellKnownType(WellKnownType.System_Exception)) Dim constructedMethodX2Foo = methodX2Foo.Construct(compilation3.GetWellKnownType(WellKnownType.System_Exception)) Dim overriddenConstructedMethX1Foo = constructedMethodX1Foo.OverriddenMethod Assert.Null(overriddenConstructedMethX1Foo) Dim overriddenConstructedMethX2Foo = constructedMethodX2Foo.OverriddenMethod Assert.Null(overriddenConstructedMethX2Foo) End Sub <Fact, WorkItem(539893, "DevDiv")> Public Sub AccessorMetadataCasing() Dim compilation1 = CreateCSharpCompilation("assem2", <![CDATA[ using System; using System.Collections.Generic; public class CSharpBase { public virtual int Prop1 { get { return 0; } set { } } } ]]>.Value) Dim compilation1Bytes = compilation1.EmitToArray() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Option Strict On Imports System Class X1 Inherits CSharpBase Public Overloads Property pRop1(x As String) As String Get Return "" End Get Set(value As String) End Set End Property Public Overrides Property prop1 As Integer Get Return MyBase.Prop1 End Get Set(value As Integer) MyBase.Prop1 = value End Set End Property Public Overridable Overloads Property pROP1(x As Long) As String Get Return "" End Get Set(value As String) End Set End Property End Class Class X2 Inherits X1 Public Overloads Property PROP1(x As Double) As String Get Return "" End Get Set(value As String) End Set End Property Public Overloads Overrides Property proP1(x As Long) As String Get Return "" End Get Set(value As String) End Set End Property Public Overrides Property PrOp1 As Integer End Class </file> </compilation>, additionalRefs:={MetadataReference.CreateFromImage(compilation1Bytes)}) Dim globalNS = compilation2.GlobalNamespace Dim classX1 = DirectCast(globalNS.GetMembers("X1").First(), NamedTypeSymbol) Dim classX2 = DirectCast(globalNS.GetMembers("X2").First(), NamedTypeSymbol) Dim x1Getters = (From memb In classX1.GetMembers("get_Prop1") Where memb.Kind = SymbolKind.Method Select DirectCast(memb, MethodSymbol)) Dim x1Setters = (From memb In classX1.GetMembers("set_Prop1") Where memb.Kind = SymbolKind.Method Select DirectCast(memb, MethodSymbol)) Dim x2Getters = (From memb In classX2.GetMembers("get_Prop1") Where memb.Kind = SymbolKind.Method Select DirectCast(memb, MethodSymbol)) Dim x2Setters = (From memb In classX2.GetMembers("set_Prop1") Where memb.Kind = SymbolKind.Method Select DirectCast(memb, MethodSymbol)) Dim x1noArgGetter = (From meth In x1Getters Let params = meth.Parameters Where params.Length = 0 Select meth).First() Assert.Equal("get_prop1", x1noArgGetter.Name) Assert.Equal("get_Prop1", x1noArgGetter.MetadataName) Dim x1StringArgGetter = (From meth In x1Getters Let params = meth.Parameters Where params.Length = 1 AndAlso params(0).Type.SpecialType = SpecialType.System_String Select meth).First() Assert.Equal("get_pRop1", x1StringArgGetter.Name) Assert.Equal("get_pRop1", x1StringArgGetter.MetadataName) Dim x1LongArgGetter = (From meth In x1Getters Let params = meth.Parameters Where params.Length = 1 AndAlso params(0).Type.SpecialType = SpecialType.System_Int64 Select meth).First() Assert.Equal("get_pROP1", x1LongArgGetter.Name) Assert.Equal("get_pROP1", x1LongArgGetter.MetadataName) Dim x2noArgGetter = (From meth In x2Getters Let params = meth.Parameters Where params.Length = 0 Select meth).First() Assert.Equal("get_PrOp1", x2noArgGetter.Name) Assert.Equal("get_Prop1", x2noArgGetter.MetadataName) Dim x2LongArgGetter = (From meth In x2Getters Let params = meth.Parameters Where params.Length = 1 AndAlso params(0).Type.SpecialType = SpecialType.System_Int64 Select meth).First() Assert.Equal("get_proP1", x2LongArgGetter.Name) Assert.Equal("get_pROP1", x2LongArgGetter.MetadataName) Dim x2DoubleArgGetter = (From meth In x2Getters Let params = meth.Parameters Where params.Length = 1 AndAlso params(0).Type.SpecialType = SpecialType.System_Double Select meth).First() Assert.Equal("get_PROP1", x2DoubleArgGetter.Name) Assert.Equal("get_PROP1", x2DoubleArgGetter.MetadataName) Dim x1noArgSetter = (From meth In x1Setters Let params = meth.Parameters Where params.Length = 1 Select meth).First() Assert.Equal("set_prop1", x1noArgSetter.Name) Assert.Equal("set_Prop1", x1noArgSetter.MetadataName) Dim x1StringArgSetter = (From meth In x1Setters Let params = meth.Parameters Where params.Length = 2 AndAlso params(0).Type.SpecialType = SpecialType.System_String Select meth).First() Assert.Equal("set_pRop1", x1StringArgSetter.Name) Assert.Equal("set_pRop1", x1StringArgSetter.MetadataName) Dim x1LongArgSetter = (From meth In x1Setters Let params = meth.Parameters Where params.Length = 2 AndAlso params(0).Type.SpecialType = SpecialType.System_Int64 Select meth).First() Assert.Equal("set_pROP1", x1LongArgSetter.Name) Assert.Equal("set_pROP1", x1LongArgSetter.MetadataName) Dim x2noArgSetter = (From meth In x2Setters Let params = meth.Parameters Where params.Length = 1 Select meth).First() Assert.Equal("set_PrOp1", x2noArgSetter.Name) Assert.Equal("set_Prop1", x2noArgSetter.MetadataName) Dim x2LongArgSetter = (From meth In x2Setters Let params = meth.Parameters Where params.Length = 2 AndAlso params(0).Type.SpecialType = SpecialType.System_Int64 Select meth).First() Assert.Equal("set_proP1", x2LongArgSetter.Name) Assert.Equal("set_pROP1", x2LongArgSetter.MetadataName) Dim x2DoubleArgSetter = (From meth In x2Setters Let params = meth.Parameters Where params.Length = 2 AndAlso params(0).Type.SpecialType = SpecialType.System_Double Select meth).First() Assert.Equal("set_PROP1", x2DoubleArgSetter.Name) Assert.Equal("set_PROP1", x2DoubleArgSetter.MetadataName) End Sub <Fact(), WorkItem(546816, "DevDiv")> Public Sub Bug16887() Dim compilation = CompilationUtils.CreateCompilationWithReferences( <compilation name="E"> <file name="a.vb"><![CDATA[ Class SelfDestruct Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class ]]></file> </compilation>, {MscorlibRef_v20}) Dim obj = compilation.GetSpecialType(SpecialType.System_Object) Dim finalize = DirectCast(obj.GetMembers("Finalize").Single(), MethodSymbol) Assert.True(finalize.IsOverridable) Assert.False(finalize.IsOverrides) AssertTheseDiagnostics(compilation, <expected></expected>) CompileAndVerify(compilation) End Sub <WorkItem(608228, "DevDiv")> <Fact> Public Sub OverridePropertyWithByRefParameter() Dim il = <![CDATA[ .class public auto ansi Base 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 newslot specialname strict virtual instance string get_P(int32& x) cil managed { ldnull ret } .method public newslot specialname strict virtual instance void set_P(int32& x, string 'value') cil managed { ret } .property instance string P(int32&) { .set instance void Base::set_P(int32&, string) .get instance string Base::get_P(int32&) } } // end of class Base ]]> Dim source = <compilation> <file name="a.vb"> Public Class Derived Inherits Base Public Overrides Property P(x As Integer) As String Get Return Nothing End Get Set(value As String) End Set End Property End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il) ' Note: matches dev11, but not interface implementation (which treats the PEProperty as bogus). compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_OverrideWithByref2, "P").WithArguments("Public Overrides Property P(x As Integer) As String", "Public Overridable Property P(ByRef x As Integer) As String")) Dim globalNamespace = compilation.GlobalNamespace Dim baseType = globalNamespace.GetMember(Of NamedTypeSymbol)("Base") Dim baseProperty = baseType.GetMember(Of PropertySymbol)("P") Assert.True(baseProperty.Parameters.Single().IsByRef) Dim derivedType = globalNamespace.GetMember(Of NamedTypeSymbol)("Derived") Dim derivedProperty = derivedType.GetMember(Of PropertySymbol)("P") Assert.False(derivedProperty.Parameters.Single().IsByRef) ' Note: matches dev11, but not interface implementation (which treats the PEProperty as bogus). Assert.Equal(baseProperty, derivedProperty.OverriddenProperty) End Sub <Fact(), WorkItem(528549, "DevDiv")> Public Sub Bug528549() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module CORError033mod NotOverridable Sub abcDef() End Sub Overrides Sub abcDef2() End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(compilation, <expected> BC30433: Methods in a Module cannot be declared 'NotOverridable'. NotOverridable Sub abcDef() ~~~~~~~~~~~~~~ BC30433: Methods in a Module cannot be declared 'Overrides'. Overrides Sub abcDef2() ~~~~~~~~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_01() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overriden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30935: Member 'Public Overridable Function M1(x As Integer) As Integer' that matches this signature cannot be overridden because the class 'Base' contains multiple members with this same name and signature: 'Public Overridable Function M1(x As Integer) As Integer' 'Public Overridable Function M1(x As Integer) As Integer' Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_02() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Output from native compiler: 'Base::M1_1 'Derived.M1 'Base::M1_3 Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="Base::M1_1" & vbCrLf & "Derived.M1" & vbCrLf & "Base::M1_3") compilation.VerifyDiagnostics() End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_03() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Output from native compiler: 'Base::M1_1 'Derived.M1 'Base::M1_3 Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="Base::M1_1" & vbCrLf & "Derived.M1" & vbCrLf & "Base::M1_3") compilation.VerifyDiagnostics() End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_04() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overriden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30935: Member 'Public Overridable Function M1(x As Integer) As Integer' that matches this signature cannot be overridden because the class 'Base' contains multiple members with this same name and signature: 'Public Overridable Function M1(x As Integer) As Integer' 'Public Overridable Function M1(x As Integer) As Integer' Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_05() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overriden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30935: Member 'Public Overridable Function M1(x As Integer) As Integer' that matches this signature cannot be overridden because the class 'Base' contains multiple members with this same name and signature: 'Public Overridable Function M1(x As Integer) As Integer' 'Public Overridable Function M1(x As Integer) As Integer' Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_06() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int32 BaseBase::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Output from native compiler: 'Base::M1_1 'Derived.M1 'Base::M1_3 Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="Base::M1_1" & vbCrLf & "Derived.M1" & vbCrLf & "Base::M1_3") compilation.VerifyDiagnostics() End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_07() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int64 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int64 BaseBase::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overriden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Long' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_08() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int64 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int64 BaseBase::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overriden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Long' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_09() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int64 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int64 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 BaseBase::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Long' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_10() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int64 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int64 Base::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler: no errors, nothing is overriden Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Long' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_11() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int64 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int64 Base::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler: no errors ' Derived.M1 ' Base::M1_2 ' Roslyn's behavior looks reasonable and it has nothing to do with custom modifiers. Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30935: Member 'Public Overridable Function M1(x As Integer) As Integer' that matches this signature cannot be overridden because the class 'Base' contains multiple members with this same name and signature: 'Public Overridable Function M1(x As Integer) As Integer' 'Public Overridable Function M1(x As Integer) As Long' Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_12() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldnull IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 BaseBase::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Integer()' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_13() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldnull IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 BaseBase::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Integer()' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_14() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { } // end of method Base::M1 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] M2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { } // end of method Base::M2 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M3(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { } // end of method Base::M3 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M11(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { } // end of method Base::M1 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] M12(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { } // end of method Base::M2 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M13(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { } // end of method Base::M3 .method public newslot abstract strict virtual instance !!T modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M4<T>(!!T y, !!T modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, !!T [] z) cil managed { } // end of method Base::M4 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Imports System.Runtime.InteropServices Module Module1 Sub Main() Dim x as Base = New Derived() x.M1(Nothing) x.M2(Nothing) x.M3(Nothing) x.M11(Nothing) x.M12(Nothing) x.M13(Nothing) x.M4(Of Integer)(Nothing, Nothing, Nothing) End Sub End Module Class Derived Inherits Base Public Overrides Function M2(x() As Integer) As Integer() System.Console.WriteLine("Derived.M2") return Nothing End Function Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function Public Overrides Function M3(x() As Integer) As Integer() System.Console.WriteLine("Derived.M3") return Nothing End Function Public Overrides Function M12(<[In]> x() As Integer) As Integer() System.Console.WriteLine("Derived.M12") return Nothing End Function Public Overrides Function M11(<[In]> x As Integer) As Integer System.Console.WriteLine("Derived.M11") return Nothing End Function Public Overrides Function M13(<[In]> x() As Integer) As Integer() System.Console.WriteLine("Derived.M13") return Nothing End Function Public Overrides Function M4(Of S)(y as S, x() As S, z() as S) As S System.Console.WriteLine("Derived.M4") return Nothing End Function End Class ]]> </file> </compilation> Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:="Derived.M1" & vbCrLf & "Derived.M2" & vbCrLf & "Derived.M3" & vbCrLf & "Derived.M11" & vbCrLf & "Derived.M12" & vbCrLf & "Derived.M13" & vbCrLf & "Derived.M4") compilation.VerifyDiagnostics() Dim derived = DirectCast(compilation.Compilation, VisualBasicCompilation).GetTypeByMetadataName("Derived") Assert.IsAssignableFrom(Of SourceSimpleParameterSymbol)(derived.GetMember(Of MethodSymbol)("M1").Parameters(0)) Assert.IsAssignableFrom(Of SourceSimpleParameterSymbol)(derived.GetMember(Of MethodSymbol)("M2").Parameters(0)) Assert.IsAssignableFrom(Of SourceSimpleParameterSymbol)(derived.GetMember(Of MethodSymbol)("M3").Parameters(0)) Assert.IsAssignableFrom(Of SourceComplexParameterSymbol)(derived.GetMember(Of MethodSymbol)("M11").Parameters(0)) Assert.IsAssignableFrom(Of SourceComplexParameterSymbol)(derived.GetMember(Of MethodSymbol)("M12").Parameters(0)) Assert.IsAssignableFrom(Of SourceComplexParameterSymbol)(derived.GetMember(Of MethodSymbol)("M13").Parameters(0)) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_15() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived1.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived1.P2_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived2.P2_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & vbCrLf & "Derived1.P1_set" & vbCrLf & "Derived1.P2_get" & vbCrLf & "Derived1.P2_set" & vbCrLf & "Derived2.P1_get" & vbCrLf & "Derived2.P1_set" & vbCrLf & "Derived2.P2_get" & vbCrLf & "Derived2.P2_set") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_16() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived1.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived1.P2_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived2.P2_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & vbCrLf & "Derived1.P1_set" & vbCrLf & "Derived1.P2_get" & vbCrLf & "Derived1.P2_set" & vbCrLf & "Derived2.P1_get" & vbCrLf & "Derived2.P1_set" & vbCrLf & "Derived2.P2_get" & vbCrLf & "Derived2.P2_set") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_17() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 ) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base Public Shared Sub Main() Dim x As Base = New Derived() x.Test() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim verifier = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & vbCrLf & "Derived1.P1_set" & vbCrLf & "Base.P2_get" & vbCrLf & "Base.P2_set" & vbCrLf & "Derived2.P1_get" & vbCrLf & "Derived2.P1_set" & vbCrLf & "Base.P2_get" & vbCrLf & "Base.P2_set") verifier.VerifyDiagnostics() AssertOverridingProperty(verifier.Compilation) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_18() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 [] P1(int32 ) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 P2(int32 []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base Public Shared Sub Main() Dim x As Base = New Derived() x.Test() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_19() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base::get_P1(int32) IL_0009: callvirt instance void Base::set_P1(int32, int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base::get_P2(int32 []) IL_0017: callvirt instance void Base::set_P2(int32 [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base::get_P1(int32 ) .set instance void Base::set_P1(int32 , int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base::get_P2(int32 []) .set instance void Base::set_P2(int32 [], int32 ) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base Public Shared Sub Main() Dim x As Base = New Derived() x.Test() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Derived.P1_get 'Derived.P1_set 'Derived.P2_get 'Derived.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_20() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base1 extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base1.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base1.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test1() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base .class public abstract auto ansi Base2 extends Base1 { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void Base1::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base2.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base2.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test2() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base2::get_P1(int32) IL_0009: callvirt instance void Base2::set_P1(int32, int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base2::get_P2(int32 []) IL_0017: callvirt instance void Base2::set_P2(int32 [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base2::get_P1(int32 ) .set instance void Base2::set_P1(int32 , int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base2::get_P2(int32 []) .set instance void Base2::set_P2(int32 [], int32 ) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base2 Public Shared Sub Main() Dim x As Base2 = New Derived() x.Test1() x.Test2() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base1.P1_get 'Base1.P1_set 'Base1.P2_get 'Base1.P2_set 'Derived.P1_get 'Derived.P1_set 'Derived.P2_get 'Derived.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base2.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_21() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base1 extends Base2 { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void Base2::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base1.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base1.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test1() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base .class public abstract auto ansi Base2 extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base2.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base2.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test2() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base2::get_P1(int32) IL_0009: callvirt instance void Base2::set_P1(int32, int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base2::get_P2(int32 []) IL_0017: callvirt instance void Base2::set_P2(int32 [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base2::get_P1(int32 ) .set instance void Base2::set_P1(int32 , int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base2::get_P2(int32 []) .set instance void Base2::set_P2(int32 [], int32 ) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base1 Public Shared Sub Main() Dim x As Base1 = New Derived() x.Test2() x.Test1() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Derived.P1_get 'Derived.P1_set 'Derived.P2_get 'Derived.P2_set 'Base1.P1_get 'Base1.P1_set 'Base1.P2_get 'Base1.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:= "Base2.P1_get" & vbCrLf & "Base2.P1_set" & vbCrLf & "Base2.P2_get" & vbCrLf & "Base2.P2_set" & vbCrLf & "Derived.P1_get" & vbCrLf & "Derived.P1_set" & vbCrLf & "Derived.P2_get" & vbCrLf & "Derived.P2_set" ) compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_22() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base1 extends Base2 { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void Base2::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base1.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base1.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test1() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base1::get_P1(int32 ) IL_0009: callvirt instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base1::set_P2(int32 [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base1::get_P1(int32 ) .set instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base1::set_P2(int32 [], int32 ) } // end of property Base::P2 } // end of class Base .class public abstract auto ansi Base2 extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base2.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base2.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test2() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base2::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base2::set_P1(int32, int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base2::get_P2(int32 []) IL_0017: callvirt instance void Base2::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base2::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base2::set_P1(int32 , int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base2::get_P2(int32 []) .set instance void Base2::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base1 Public Shared Sub Main() Dim x As Base1 = New Derived() x.Test2() x.Test1() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base2.P1_get 'Derived.P1_set 'Derived.P2_get 'Base2.P2_set 'Derived.P1_get 'Base1.P1_set 'Base1.P2_get 'Derived.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base1.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_23() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0002: ldarg.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1() IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_0010: ldarg.0 IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2() IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1() { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1() .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2() { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2() .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1() As Integer() Public Overrides Property P2() As Integer End Class ]]> </file> </compilation> Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:="") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_24() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0002: ldarg.0 IL_0004: callvirt instance int32 [] Base::get_P1() IL_0009: callvirt instance void Base::set_P1(int32 []) IL_000e: ldarg.0 IL_0010: ldarg.0 IL_0012: callvirt instance int32 Base::get_P2() IL_0017: callvirt instance void Base::set_P2(int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1() { .get instance int32 [] Base::get_P1() .set instance void Base::set_P1(int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2() { .get instance int32 Base::get_P2() .set instance void Base::set_P2(int32) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1() As Integer() Public Overrides Property P2() As Integer End Class ]]> </file> </compilation> Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:="") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_25() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0002: ldarg.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1() IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_0010: ldarg.0 IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2() IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 [] P1() { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1() .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 P2() { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2() .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1() As Integer() Public Overrides Property P2() As Integer End Class ]]> </file> </compilation> Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:="") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_26() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32[] P1(int32) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived1.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived1.P2_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived2.P2_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & vbCrLf & "Derived1.P1_set" & vbCrLf & "Derived1.P2_get" & vbCrLf & "Derived1.P2_set" & vbCrLf & "Derived2.P1_get" & vbCrLf & "Derived2.P1_set" & vbCrLf & "Derived2.P2_get" & vbCrLf & "Derived2.P2_set") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_27() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base::get_P1(int32 ) IL_0009: callvirt instance void Base::set_P1(int32 , int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base::get_P1(int32 ) .set instance void Base::set_P1(int32, int32[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived1.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived1.P2_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived2.P2_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & vbCrLf & "Derived1.P1_set" & vbCrLf & "Derived1.P2_get" & vbCrLf & "Derived1.P2_set" & vbCrLf & "Derived2.P1_get" & vbCrLf & "Derived2.P1_set" & vbCrLf & "Derived2.P2_get" & vbCrLf & "Derived2.P2_set") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub Private Sub AssertOverridingProperty(compilation As Compilation) For Each namedType In compilation.SourceModule.GlobalNamespace.GetTypeMembers() If namedType.Name.StartsWith("Derived", StringComparison.OrdinalIgnoreCase) Then For Each member In namedType.GetMembers() If member.Kind = SymbolKind.Property Then Dim thisProperty = DirectCast(member, PropertySymbol) Dim overriddenProperty = thisProperty.OverriddenProperty Assert.True(overriddenProperty.TypeCustomModifiers.SequenceEqual(thisProperty.TypeCustomModifiers)) Assert.Equal(overriddenProperty.Type, thisProperty.Type) For i As Integer = 0 To thisProperty.ParameterCount - 1 Assert.True(overriddenProperty.Parameters(i).CustomModifiers.SequenceEqual(thisProperty.Parameters(i).CustomModifiers)) Assert.Equal(overriddenProperty.Parameters(i).Type, thisProperty.Parameters(i).Type) Assert.Equal(overriddenProperty.Parameters(i).HasByRefBeforeCustomModifiers, thisProperty.Parameters(i).HasByRefBeforeCustomModifiers) Next End If Next End If Next End Sub <Fact(), WorkItem(830352, "DevDiv")> Public Sub Bug830352() Dim code = <compilation> <file name="a.vb"> Public Class Base Overridable Sub Test(Of T As Structure)(x As T?) End Sub End Class Class Derived Inherits Base Public Overrides Sub Test(Of T As Structure)(x As T?) MyBase.Test(x) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib(code, TestOptions.ReleaseDll) CompileAndVerify(comp).VerifyDiagnostics() End Sub <Fact(), WorkItem(837884, "DevDiv")> Public Sub Bug837884() Dim code1 = <compilation> <file name="a.vb"> Public Class Cls Public Overridable Property r() Get Return 1 End Get Friend Set(ByVal Value) End Set End Property End Class </file> </compilation> Dim comp1 = CreateCompilationWithMscorlib(code1, TestOptions.ReleaseDll) CompileAndVerify(comp1).VerifyDiagnostics() Dim code2 = <compilation> <file name="a.vb"> Class cls2 Inherits Cls Public Overrides Property r() As Object Get Return 1 End Get Friend Set(ByVal Value As Object) End Set End Property End Class </file> </compilation> Dim comp2 = CreateCompilationWithMscorlibAndReferences(code2, {New VisualBasicCompilationReference(comp1)}, TestOptions.ReleaseDll) Dim expected = <expected> BC31417: 'Friend Overrides Property Set r(Value As Object)' cannot override 'Friend Overridable Property Set r(Value As Object)' because it is not accessible in this context. Friend Set(ByVal Value As Object) ~~~ </expected> AssertTheseDeclarationDiagnostics(comp2, expected) Dim comp3 = CreateCompilationWithMscorlibAndReferences(code2, {comp1.EmitToImageReference()}, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(comp3, expected) End Sub <WorkItem(1067044, "DevDiv")> <Fact> Public Sub Bug1067044() Dim il = <![CDATA[ .class public abstract auto ansi beforefieldinit C1 extends [mscorlib]System.Object { .method public hidebysig newslot abstract virtual instance int32* M1() cil managed { } // end of method C1::M1 .method family hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor } // end of class C1 .class public abstract auto ansi beforefieldinit C2 extends C1 { .method public hidebysig virtual instance int32* M1() cil managed { // Code size 8 (0x8) .maxstack 1 .locals init (int32* V_0) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: conv.u IL_0003: stloc.0 IL_0004: br.s IL_0006 IL_0006: ldloc.0 IL_0007: ret } // end of method C2::M1 .method public hidebysig newslot abstract virtual instance void M2() cil managed { } // end of method C2::M2 .method family hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: nop IL_0007: ret } // end of method C2::.ctor } // end of class C2 ]]> Dim source = <compilation> <file name="a.vb"> Public Class C3 Inherits C2 Public Overrides Sub M2() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il.Value, options:=TestOptions.DebugDll) CompileAndVerify(compilation) End Sub End Class End Namespace
wschae/roslyn
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/OverridesTests.vb
Visual Basic
apache-2.0
226,472
'-------------------------------------------------------------------------------------------' ' Inicio del codigo '-------------------------------------------------------------------------------------------' ' Importando librerias '-------------------------------------------------------------------------------------------' Imports System.Data '-------------------------------------------------------------------------------------------' ' Inicio de clase "rOPagos_tConceptosMen" '-------------------------------------------------------------------------------------------' Partial Class rOPagos_tConceptosMen Inherits vis2formularios.frmReporte Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try Dim loComandoSeleccionar As New StringBuilder() Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0)) Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0)) Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia) Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia) Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2)) Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2)) Dim lcParametro3Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3)) Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4)) Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4)) Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5)) Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5)) Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden loComandoSeleccionar.AppendLine("SELECT Conceptos.Cod_Con, ") loComandoSeleccionar.AppendLine(" Conceptos.Nom_Con, ") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Ordenes_Pagos.Fec_ini) = 1 THEN ((Renglones_oPagos.Mon_Deb - Renglones_oPagos.Mon_hab)) ") loComandoSeleccionar.AppendLine(" else 0 ") loComandoSeleccionar.AppendLine(" END as Ene, ") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Ordenes_Pagos.Fec_ini) = 2 THEN ((Renglones_oPagos.Mon_Deb - Renglones_oPagos.Mon_hab)) ") loComandoSeleccionar.AppendLine(" else 0 ") loComandoSeleccionar.AppendLine(" END as Feb, ") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Ordenes_Pagos.Fec_ini) = 3 THEN ((Renglones_oPagos.Mon_Deb - Renglones_oPagos.Mon_hab)) ") loComandoSeleccionar.AppendLine(" else 0 ") loComandoSeleccionar.AppendLine(" END as Mar, ") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Ordenes_Pagos.Fec_ini) = 4 THEN ((Renglones_oPagos.Mon_Deb - Renglones_oPagos.Mon_hab)) ") loComandoSeleccionar.AppendLine(" else 0 ") loComandoSeleccionar.AppendLine(" END as Abr, ") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Ordenes_Pagos.Fec_ini) = 5 THEN ((Renglones_oPagos.Mon_Deb - Renglones_oPagos.Mon_hab)) ") loComandoSeleccionar.AppendLine(" else 0 ") loComandoSeleccionar.AppendLine(" END as May, ") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Ordenes_Pagos.Fec_ini) = 6 THEN ((Renglones_oPagos.Mon_Deb - Renglones_oPagos.Mon_hab)) ") loComandoSeleccionar.AppendLine(" else 0 ") loComandoSeleccionar.AppendLine(" END as Jun, ") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Ordenes_Pagos.Fec_ini) = 7 THEN ((Renglones_oPagos.Mon_Deb - Renglones_oPagos.Mon_hab)) ") loComandoSeleccionar.AppendLine(" else 0 ") loComandoSeleccionar.AppendLine(" END as Jul, ") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Ordenes_Pagos.Fec_ini) = 8 THEN ((Renglones_oPagos.Mon_Deb - Renglones_oPagos.Mon_hab)) ") loComandoSeleccionar.AppendLine(" else 0 ") loComandoSeleccionar.AppendLine(" END as Ago, ") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Ordenes_Pagos.Fec_ini) = 9 THEN ((Renglones_oPagos.Mon_Deb - Renglones_oPagos.Mon_hab)) ") loComandoSeleccionar.AppendLine(" else 0 ") loComandoSeleccionar.AppendLine(" END as Sep, ") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Ordenes_Pagos.Fec_ini) = 10 THEN ((Renglones_oPagos.Mon_Deb - Renglones_oPagos.Mon_hab)) ") loComandoSeleccionar.AppendLine(" else 0 ") loComandoSeleccionar.AppendLine(" END as Oct, ") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Ordenes_Pagos.Fec_ini) = 11 THEN ((Renglones_oPagos.Mon_Deb - Renglones_oPagos.Mon_hab)) ") loComandoSeleccionar.AppendLine(" else 0 ") loComandoSeleccionar.AppendLine(" END as Nov, ") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Ordenes_Pagos.Fec_ini) = 12 THEN ((Renglones_oPagos.Mon_Deb - Renglones_oPagos.Mon_hab)) ") loComandoSeleccionar.AppendLine(" else 0 ") loComandoSeleccionar.AppendLine(" END as Dic, ") loComandoSeleccionar.AppendLine(" (Renglones_oPagos.Mon_Deb - Renglones_oPagos.Mon_hab) AS Total ") loComandoSeleccionar.AppendLine(" INTO #tmpTemporal ") loComandoSeleccionar.AppendLine("FROM Ordenes_Pagos, ") loComandoSeleccionar.AppendLine(" Renglones_oPagos, ") loComandoSeleccionar.AppendLine(" Conceptos, ") loComandoSeleccionar.AppendLine(" Proveedores ") loComandoSeleccionar.AppendLine(" WHERE(Ordenes_Pagos.Documento = Renglones_oPagos.Documento) ") loComandoSeleccionar.AppendLine(" And Renglones_oPagos.Cod_Con = Conceptos.Cod_Con ") loComandoSeleccionar.AppendLine(" And Ordenes_Pagos.Cod_Pro = Proveedores.Cod_Pro ") loComandoSeleccionar.AppendLine(" And Ordenes_Pagos.Documento Between " & lcParametro0Desde) loComandoSeleccionar.AppendLine(" And " & lcParametro0Hasta) loComandoSeleccionar.AppendLine(" And Ordenes_Pagos.Fec_Ini Between " & lcParametro1Desde) loComandoSeleccionar.AppendLine(" And " & lcParametro1Hasta) loComandoSeleccionar.AppendLine(" And Ordenes_Pagos.Cod_Pro Between " & lcParametro2Desde) loComandoSeleccionar.AppendLine(" And " & lcParametro2Hasta) loComandoSeleccionar.AppendLine(" And Ordenes_Pagos.Status IN (" & lcParametro3Desde & ")") loComandoSeleccionar.AppendLine(" And Conceptos.Cod_Con Between " & lcParametro4Desde) loComandoSeleccionar.AppendLine(" And " & lcParametro4Hasta) loComandoSeleccionar.AppendLine(" And Ordenes_Pagos.Cod_rev Between " & lcParametro5Desde) loComandoSeleccionar.AppendLine(" And " & lcParametro5Hasta) loComandoSeleccionar.AppendLine("SELECT ") loComandoSeleccionar.AppendLine(" #tmpTemporal.Cod_Con, ") loComandoSeleccionar.AppendLine(" #tmpTemporal.Nom_Con, ") loComandoSeleccionar.AppendLine(" sum(ene) as Ene, ") loComandoSeleccionar.AppendLine(" sum(feb) as Feb, ") loComandoSeleccionar.AppendLine(" sum(mar) as Mar, ") loComandoSeleccionar.AppendLine(" sum(abr) as Abr, ") loComandoSeleccionar.AppendLine(" sum(may) as May, ") loComandoSeleccionar.AppendLine(" sum(jun) as Jun, ") loComandoSeleccionar.AppendLine(" sum(jul) as Jul, ") loComandoSeleccionar.AppendLine(" sum(ago) as Ago, ") loComandoSeleccionar.AppendLine(" sum(sep) as Sep, ") loComandoSeleccionar.AppendLine(" sum(oct) as Oct, ") loComandoSeleccionar.AppendLine(" sum(nov) as Nov, ") loComandoSeleccionar.AppendLine(" sum(dic) as Dic, ") loComandoSeleccionar.AppendLine(" sum(total) as Total") loComandoSeleccionar.AppendLine("FROM #tmpTemporal ") loComandoSeleccionar.AppendLine("Group By ") loComandoSeleccionar.AppendLine(" Cod_Con, ") loComandoSeleccionar.AppendLine(" Nom_Con ") loComandoSeleccionar.AppendLine("ORDER BY " & lcOrdenamiento) Dim loServicios As New cusDatos.goDatos Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes") loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rOPagos_tConceptosMen", laDatosReporte) Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvrOPagos_tConceptosMen.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 '-------------------------------------------------------------------------------------------' ' CMS: 07/05/09: Codigo inicial '-------------------------------------------------------------------------------------------' ' YJP: 14/05/09: Agregar filtro Revisión '-------------------------------------------------------------------------------------------' ' CMS: 26/03/10: Se cambio la funcion DATEPART por DATEPART '-------------------------------------------------------------------------------------------' ' MAT: 19/05/11: Ajuste de la vista de diseño '-------------------------------------------------------------------------------------------'
kodeitsolutions/ef-reports
rOPagos_tConceptosMen.aspx.vb
Visual Basic
mit
12,810
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("SolidEdge.UnitsOfMeasure")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyConfiguration("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("SolidEdge.UnitsOfMeasure")> <Assembly: AssemblyCopyright("Copyright © 2013")> <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("d41bcbb2-c944-47f9-9381-99e5c57d3bbf")> ' 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
General/UnitsOfMeasure/vb/UnitsOfMeasure/My Project/AssemblyInfo.vb
Visual Basic
mit
1,410
Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Namespace Examples Friend Class Program <STAThread> Shared Sub Main(ByVal args() As String) Dim application As SolidEdgeFramework.Application = Nothing Dim documents As SolidEdgeFramework.Documents = Nothing Dim draftDocument As SolidEdgeDraft.DraftDocument = Nothing Dim sheet As SolidEdgeDraft.Sheet = Nothing Dim arcs2d As SolidEdgeFrameworkSupport.Arcs2d = Nothing Dim arc2d As SolidEdgeFrameworkSupport.Arc2d = Nothing Dim dimensions As SolidEdgeFrameworkSupport.Dimensions = Nothing Dim dimension As SolidEdgeFrameworkSupport.Dimension = Nothing Try ' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic. OleMessageFilter.Register() ' Attempt to connect to a running instance of Solid Edge. application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application) documents = application.Documents draftDocument = CType(documents.Add("SolidEdge.DraftDocument"), SolidEdgeDraft.DraftDocument) sheet = draftDocument.ActiveSheet arcs2d = sheet.Arcs2d dimensions = CType(sheet.Dimensions, SolidEdgeFrameworkSupport.Dimensions) arc2d = arcs2d.AddByCenterStartEnd(0.2, 0.2, 0.1, 0.1, 0.3, 0.3) dimension = dimensions.AddRadius(arc2d) Dim x As Double = Nothing Dim y As Double = Nothing dimension.GetTextOffsets(x, y) Catch ex As System.Exception Console.WriteLine(ex) Finally OleMessageFilter.Unregister() End Try End Sub End Class End Namespace
SolidEdgeCommunity/docs
docfx_project/snippets/SolidEdgeFrameworkSupport.Dimension.GetTextOffsets.vb
Visual Basic
mit
1,942
Imports DotNetNuke.Entities.Portals Imports DotNetNuke.Entities.Users Namespace DotNetNuke.Modules.Feedback Public Class Utilities Public Shared Function ConvertServerTimeToUserTime(ByVal value As DateTime) As DateTime Dim result As DateTime Try 'Get the portalTimeZone as a fallback Dim portalTimeZone As TimeZoneInfo = PortalController.Instance.GetCurrentPortalSettings().TimeZone 'Get the userTime based on user profile preference if user is authenticated If System.Web.HttpContext.Current.Request.IsAuthenticated Then Dim objUser As UserInfo = UserController.Instance.GetCurrentUserInfo() Dim userTimeZone As TimeZoneInfo = objUser.Profile.PreferredTimeZone result = TimeZoneInfo.ConvertTimeFromUtc(value, userTimeZone) Else result = TimeZoneInfo.ConvertTimeFromUtc(value, portalTimeZone) End If Catch result = value End Try Return result End Function End Class End Namespace
DNNCommunity/DNN.Feedback
Components/Utilities.vb
Visual Basic
mit
1,167
Public Class PositionerForm Public MissionObjectController As MissionObjectController Private _newSwitchDriverForm As NewSwitchDriverForm Private _positionerForm As PositionerForm Private _positonerIdx As Integer Private _maxPositoners As Integer Private _surveyName As String Private _numSwitchDrivers As Integer Public Sub New(ByRef aMissionObjectController As MissionObjectController, ByVal aIdx As Integer, ByVal maxNum As Integer, ByVal numSwitchDrivers As Integer) Me.MissionObjectController = aMissionObjectController Me._positonerIdx = aIdx Me._maxPositoners = maxNum Me._numSwitchDrivers = numSwitchDrivers If aIdx >= maxNum Then Me._newSwitchDriverForm = New NewSwitchDriverForm(Me.MissionObjectController, 0, numSwitchDrivers) Return End If InitializeComponent() 'populate the combo box with the types defined Me.cmbBxPositionerType.DataSource = System.Enum.GetValues(GetType(Enumerations.PositionerModel)) Me.Text = "Positioner " & aIdx + 1 Me.StartPosition = FormStartPosition.Manual Me.Left = 300 Me.Top = 300 Me.Visible = True End Sub Private Sub btnFinished_Click_1(sender As System.Object, e As System.EventArgs) Handles btnFinished.Click With Me.MissionObjectController.aMain.SurveyController.surveyObj .getPositioner(Me._positonerIdx) = New PositionerObject With .getPositioner(Me._positonerIdx) .getPositionerType = Me.cmbBxPositionerType.SelectedItem .getComPortNumber = Me.numUpDwnSerCOMportNum.Value .getConnectionString = "ASRL" & .getComPortNumber & "::INSTR" .getInterleaveStep = Me.numUpDwnInterleaveStep.Value .getAzimuthStep = Me.numUpDwnAzimuthStep.Value .getAzimuthStart = Me.numUpDwnAzimStart.Value .getAzimuthStop = Me.numUpDwnAzimStop.Value .getElevationStart = Me.numUpDwnElStart.Value .getElevationStop = Me.numUpDownElStop.Value .getElevationStep = Me.numUpDwnElStep.Value .getElevationInterleaveStep = Me.numUpDownElInterleaveStep.Value If Me.cmbBxIgnoreElevation.Text = "TRUE" Then .getIgnoreElevationParameters = True Else .getIgnoreElevationParameters = False End If If Me.cmbBxPrevCableWrap.Text = "TRUE" Then .getPreventCableWrap = True Else .getPreventCableWrap = False End If End With End With Me._positonerIdx += 1 Me.Visible = False Me._positionerForm = New PositionerForm(Me.MissionObjectController, Me._positonerIdx, Me._maxPositoners, Me._numSwitchDrivers) End Sub Private Sub cmbBxIgnoreElevation_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbBxIgnoreElevation.SelectedIndexChanged Try If Me.cmbBxIgnoreElevation.Text.ToUpper = "TRUE" Then Me.grpBxElev.Visible = False ElseIf Me.cmbBxIgnoreElevation.Text.ToUpper = "FALSE" Then Me.grpBxElev.Visible = True End If Catch ex As Exception End Try End Sub End Class
wboxx1/85-EIS-PUMA
puma/src/Supporting Forms/zzz - Legacy Forms/PositionerForm.vb
Visual Basic
mit
3,425
Namespace Ribbons.Companies.Show Public Class LinkedDocuments Inherits RibbonButtonBase Public Sub New() _Image = "" _Order = 1 _Text = "Linked Documents" _ToolTip = "" End Sub Protected Friend Overrides Sub OnClick() End Sub Protected Friend Overrides Sub OnIsEnabled() End Sub End Class End Namespace
nublet/DMS
DMS.Forms/Ribbons/Items/Companies/Show/LinkedDocuments.vb
Visual Basic
mit
424
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:2.0.50727.1433 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings),MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property <Global.System.Configuration.ApplicationScopedSettingAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Configuration.SpecialSettingAttribute(Global.System.Configuration.SpecialSetting.ConnectionString), _ Global.System.Configuration.DefaultSettingValueAttribute("Data Source=|DataDirectory|\Database\Exercise.sdf")> _ Public ReadOnly Property ExerciseConnectionString() As String Get Return CType(Me("ExerciseConnectionString"),String) 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.Exercise.My.MySettings Get Return Global.Exercise.My.MySettings.Default End Get End Property End Module End Namespace
Mimalef/limons
src/Exercise/My Project/Settings.Designer.vb
Visual Basic
mit
3,585
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("BarcodeGenerator")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyConfiguration("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("BarcodeGenerator")> <Assembly: AssemblyCopyright("Copyright © 2017")> <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("2738cd4c-2f0a-4653-a375-a21eaa89059f")> ' 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")>
Dynamsoft/Dynamic-.NET-TWAIN-SDK
samples/VB .NET Samples/BarcodeGenerator/BarcodeGenerator/Properties/AssemblyInfo.vb
Visual Basic
apache-2.0
1,391
Public Class Help Private Sub PictureBox3_Click(sender As Object, e As EventArgs) End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click HangMan_By_Vahe.Menu.Show() Me.Close() End Sub End Class
VaheDanielyan/Hangman
Source/Help.vb
Visual Basic
apache-2.0
276
'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.Editor Imports ESRI.ArcGIS.Geodatabase Namespace AddInEditorExtension ''' <summary> ''' ValidateFeaturesExtension class implementing custom ESRI Editor Extension functionalities. ''' </summary> Public Class ValidateFeaturesExtension Inherits ESRI.ArcGIS.Desktop.AddIns.Extension Public Sub New() End Sub 'Invoked when the Editor Extension is loaded Protected Overrides Sub OnStartup() AddHandler Events.OnStartEditing, AddressOf Events_OnStartEditing AddHandler Events.OnStopEditing, AddressOf Events_OnStopEditing End Sub 'Invoked at the start of the Editor Session Private Sub Events_OnStartEditing() 'Since features of shapefiles, coverages etc cannot be validated, ignore wiring events for them If ArcMap.Editor.EditWorkspace.Type <> esriWorkspaceType.esriFileSystemWorkspace Then 'wire OnCreateFeature Edit event AddHandler Events.OnCreateFeature, AddressOf Events_OnCreateChangeFeature 'wire onChangeFeature Edit Event AddHandler Events.OnChangeFeature, AddressOf Events_OnCreateChangeFeature End If End Sub 'Invoked at the end of the Edit session Private Sub Events_OnStopEditing(ByVal Save As Boolean) 'Since features of shapefiles, coverages etc cannot be validated, ignore wiring events for them If ArcMap.Editor.EditWorkspace.Type <> esriWorkspaceType.esriFileSystemWorkspace Then 'unwire OnCreateFeature Edit event RemoveHandler Events.OnCreateFeature, AddressOf Events_OnCreateChangeFeature 'unwire onChangeFeature Edit Event RemoveHandler Events.OnChangeFeature, AddressOf Events_OnCreateChangeFeature End If End Sub 'Invoked when a feature is created or modified Private Sub Events_OnCreateChangeFeature(ByVal obj As ESRI.ArcGIS.Geodatabase.IObject) Dim inFeature As IFeature = CType(obj, IFeature) If TypeOf inFeature.Class Is IValidation Then Dim validate As IValidate = CType(inFeature, IValidate) Dim errorMessage As String errorMessage = String.Empty Dim bIsvalid As Boolean = validate.Validate(errorMessage) If (Not bIsvalid) Then System.Windows.Forms.MessageBox.Show("Invalid Feature" & Constants.vbLf + Constants.vbLf & errorMessage) Else System.Windows.Forms.MessageBox.Show("Valid Feature") End If End If End Sub Protected Overrides Sub OnShutdown() End Sub #Region "Editor Events" #Region "Shortcut properties to the various editor event interfaces" Private ReadOnly Property Events() As IEditEvents_Event Get Return TryCast(ArcMap.Editor, IEditEvents_Event) End Get End Property Private ReadOnly Property Events2() As IEditEvents2_Event Get Return TryCast(ArcMap.Editor, IEditEvents2_Event) End Get End Property Private ReadOnly Property Events3() As IEditEvents3_Event Get Return TryCast(ArcMap.Editor, IEditEvents3_Event) End Get End Property Private ReadOnly Property Events4() As IEditEvents4_Event Get Return TryCast(ArcMap.Editor, IEditEvents4_Event) End Get End Property #End Region Private Sub WireEditorEvents() ' ' TODO: Sample code demonstrating editor event wiring ' AddHandler Events.OnCurrentTaskChanged, AddressOf AnonymousMethod1 AddHandler Events2.BeforeStopEditing, AddressOf AnonymousMethod2 End Sub Private Sub AnonymousMethod1() If ArcMap.Editor.CurrentTask IsNot Nothing Then System.Windows.Forms.MessageBox.Show(ArcMap.Editor.CurrentTask.Name) End If End Sub Private Sub AnonymousMethod2(ByVal save As Boolean) OnBeforeStopEditing(save) End Sub Private Sub OnBeforeStopEditing(ByVal save As Boolean) End Sub #End Region End Class End Namespace
Esri/arcobjects-sdk-community-samples
Net/Framework/AddInEditorExtension/VBNet/ValidateFeaturesExtension.vb
Visual Basic
apache-2.0
4,536
Public Class CopyDirectoryProgressChangedEventArgs Private _ProgressPercentage As Single Public Overloads ReadOnly Property ProgressPercentage As Single Get Return _ProgressPercentage End Get End Property Private _BytesCopied As Long Public ReadOnly Property BytesCopied As Long Get Return _BytesCopied End Get End Property Private _TotalBytes As Long Public ReadOnly Property TotalBytes As Long Get Return _TotalBytes End Get End Property Sub New(progressPercentage As Single, bytesCopied As Long, totalBytes As Long) Me._ProgressPercentage = progressPercentage Me._BytesCopied = bytesCopied Me._TotalBytes = totalBytes End Sub End Class
nicoco007/MCBackup-3
MCBackup 3/EventArgs/CopyDirectoryProgressChangedEventArgs.vb
Visual Basic
apache-2.0
799
' 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.IO Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods Public Class AnonymousTypesEmittedSymbolsTests : Inherits BasicTestBase <Fact> Public Sub EmitAnonymousTypeTemplate_NoNeededSymbols() Dim compilationDef = <compilation name="EmitAnonymousTypeTemplate_NoNeededSymbols"> <file name="a.vb"> Class ModuleB Private v1 = New With { .aa = 1 } End Class </file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source:=compilationDef, references:={}) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30002: Type 'System.Void' is not defined. Class ModuleB ~~~~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'EmitAnonymousTypeTemplate_NoNeededSymbols.dll' failed. Class ModuleB ~~~~~~~ BC30002: Type 'System.Object' is not defined. Private v1 = New With { .aa = 1 } ~~ BC30002: Type 'System.Object' is not defined. Private v1 = New With { .aa = 1 } ~~~~~~~~~~~~~~~~ BC30002: Type 'System.Int32' is not defined. Private v1 = New With { .aa = 1 } ~ </errors>) End Sub <Fact> Public Sub EmitAnonymousTypeTemplateGenericTest() Dim compilationDef = <compilation name="EmitGenericAnonymousTypeTemplate"> <file name="a.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Assert.Equal(GetNamedTypeSymbol(m, "System.Object"), type.BaseType) Assert.True(type.IsGenericType) Assert.Equal(3, type.TypeParameters.Length) End Sub) End Sub <Fact> Public Sub EmitAnonymousTypeUnification01() Dim compilationDef = <compilation name="EmitAnonymousTypeUnification01"> <file name="a.vb"> Module ModuleB Sub Test1(x As Integer) Dim at1 As Object = New With { .aa = 1, .b1 = "", .Int = x + x, .Object=Nothing } Dim at2 As Object = New With { .aA = "X"c, .B1 = 0.123# * x, .int = new Object(), .objecT = Nothing } at1 = at2 End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim types = m.ContainingAssembly.GlobalNamespace.GetTypeMembers() Dim list = types.Where(Function(t) t.Name.StartsWith("VB$AnonymousType_", StringComparison.Ordinal)).ToList() Assert.Equal(1, list.Count()) Dim type = list.First() Assert.Equal("VB$AnonymousType_0", type.Name) Assert.Equal(4, type.Arity) Dim mems = type.GetMembers() ' 4 fields, 4 get, 4 set, 1 ctor, 1 ToString Assert.Equal(14, mems.Length) Dim mlist = mems.Where(Function(mt) mt.Name = "GetHashCode" OrElse mt.Name = "Equals").Select(Function(mt) mt) Assert.Equal(0, mlist.Count) End Sub) End Sub <Fact> Public Sub EmitAnonymousTypeUnification02() Dim compilationDef = <compilation name="EmitAnonymousTypeUnification02"> <file name="b.vb"> Imports System Imports System.Collections.Generic Class A Sub Test(p As List(Of String)) Dim local = New Char() {"a"c, "b"c} Dim at1 As Object = New With {.test = p, Key .key = local, Key .k2 = "QC" + p(0)} End Sub End Class </file> <file name="a.vb"> Structure S Function Test(p As Char()) As Object Dim at2 As Object = New With {.TEST = New System.Collections.Generic.List(Of String)(), Key .Key = p, Key .K2 = ""} Return at2 End Function End Structure </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim types = m.ContainingAssembly.GlobalNamespace.GetTypeMembers() Dim list = types.Where(Function(t) t.Name.StartsWith("VB$AnonymousType", StringComparison.Ordinal)).ToList() Assert.Equal(1, list.Count()) Dim type = list.First() Assert.Equal("VB$AnonymousType_0", type.Name) Assert.Equal(3, type.Arity) Dim mems = type.GetMembers() ' 3 fields, 3 get, 1 set, 1 ctor, 1 ToString, 1 GetHashCode, 2 Equals Assert.Equal(12, mems.Length) Dim mlist = mems.Where(Function(mt) mt.Name = "GetHashCode" OrElse mt.Name = "Equals").Select(Function(mt) mt) Assert.Equal(3, mlist.Count) End Sub) End Sub <Fact> Public Sub EmitAnonymousTypeUnification03() Dim compilationDef = <compilation name="EmitAnonymousTypeUnification03"> <file name="b.vb"> Imports System Imports System.Collections.Generic Class A Sub Test(p As List(Of String)) Dim local = New Char() {"a"c, "b"c} Dim at1 As Object = New With {.test = p, Key .key = local, Key .k2 = "QC" + p(0)} End Sub End Class </file> <file name="a.vb"> Imports System Imports System.Collections.Generic Class B Sub Test(p As List(Of String)) Dim local = New Char() {"a"c, "b"c} Dim at1 As Object = New With {.test = p, Key .key = local, .k2 = "QC" + p(0)} End Sub End Class </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim types = m.ContainingAssembly.GlobalNamespace.GetTypeMembers() Dim list = types.Where(Function(t) t.Name.StartsWith("VB$AnonymousType", StringComparison.Ordinal)).ToList() ' no unification - diff in key Assert.Equal(2, list.Count()) Dim type = m.ContainingAssembly.GlobalNamespace.GetTypeMembers("VB$AnonymousType_1").Single() Assert.Equal("VB$AnonymousType_1", type.Name) Assert.Equal(3, type.Arity) Dim mems = type.GetMembers() ' Second: 3 fields, 3 get, 2 set, 1 ctor, 1 ToString, 1 GetHashCode, 2 Equals Assert.Equal(13, mems.Length) Dim mlist = mems.Where(Function(mt) mt.Name = "GetHashCode" OrElse mt.Name = "Equals").Select(Function(mt) mt) Assert.Equal(3, mlist.Count) ' type = m.ContainingAssembly.GlobalNamespace.GetTypeMembers("VB$AnonymousType_0").Single() Assert.Equal("VB$AnonymousType_0", type.Name) Assert.Equal(3, type.Arity) mems = type.GetMembers() ' First: 3 fields, 3 get, 1 set, 1 ctor, 1 ToString, 1 GetHashCode, 2 Equals Assert.Equal(12, mems.Length) mlist = mems.Where(Function(mt) mt.Name = "GetHashCode" OrElse mt.Name = "Equals").Select(Function(mt) mt) Assert.Equal(3, mlist.Count) End Sub) End Sub <Fact> Public Sub EmitAnonymousTypeCustomModifiers() Dim compilationDef = <compilation name="EmitAnonymousTypeCustomModifiers"> <file name="b.vb"> Imports System Imports System.Collections.Generic Class A Sub Test(p As List(Of String)) Dim intArrMod = Modifiers.F9() Dim at1 = New With { Key .f = intArrMod} Dim at2 = New With { Key .f = New Integer() {}} at1 = at2 at2 = at1 End Sub End Class </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef, TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll}) End Sub <Fact> Public Sub AnonymousTypes_MultiplyEmitOfTheSameAssembly() Dim compilationDef = <compilation name="AnonymousTypes_MultiplyEmitOfTheSameAssembly"> <file name="b.vb"> Module ModuleB Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1 } Dim v2 As Object = New With { Key .AA = "a" } End Sub End Module </file> <file name="a.vb"> Module ModuleA Sub Test1(x As Integer) Dim v1 As Object = New With { .Aa = 1 } Dim v2 As Object = New With { Key .aA = "A" } End Sub End Module </file> <file name="c.vb"> Module ModuleC Sub Test1(x As Integer) Dim v1 As Object = New With { .AA = 1 } Dim v2 As Object = New With { Key .aa = "A" } End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim position = compilationDef.<file>.Value.IndexOf("Dim v2", StringComparison.Ordinal) - 1 ' The sole purpose of this is to check if there will be any asserts ' or exceptions related to adjusted names/locations of anonymous types ' symbols when Emit is called several times for the same compilation For i = 0 To 10 Using stream As New MemoryStream() compilation.Emit(stream) End Using ' do some speculative semantic query Dim expr1 = SyntaxFactory.ParseExpression(<text>New With { .aa = 1, .BB<%= i %> = "" }</text>.Value) Dim info1 = model.GetSpeculativeTypeInfo(position, expr1, SpeculativeBindingOption.BindAsExpression) Assert.NotNull(info1.Type) Next End Sub <Fact> Public Sub EmitCompilerGeneratedAttributeTest() Dim compilationDef = <compilation name="EmitCompilerGeneratedAttributeTest"> <file name="a.vb"> Module Module1 Sub Test1(x As Integer) Dim v As Object = New With { .a = 1 } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`1") Assert.NotNull(type) Dim attr = type.GetAttribute( GetNamedTypeSymbol(m, "System.Runtime.CompilerServices.CompilerGeneratedAttribute")) Assert.NotNull(attr) End Sub) End Sub <Fact> Public Sub CheckPropertyFieldAndAccessorsNamesTest() Dim compilationDef = <compilation name="CheckPropertyFieldAndAccessorsNamesTest"> <file name="b.vb"> Module ModuleB Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1 }.aa Dim v2 As Object = New With { Key .AA = "a" }.aa End Sub End Module </file> <file name="a.vb"> Module ModuleA Sub Test1(x As Integer) Dim v1 As Object = New With { .Aa = 1 }.aa Dim v2 As Object = New With { Key .aA = "A" }.aa End Sub End Module </file> <file name="c.vb"> Module ModuleC Sub Test1(x As Integer) Dim v1 As Object = New With { .AA = 1 }.aa Dim v2 As Object = New With { Key .aa = "A" }.aa End Sub End Module </file> </compilation> ' Cycle to hopefully get different order of files For i = 0 To 50 CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`1") Assert.NotNull(type) CheckPropertyAccessorsAndField(m, type, "aa", type.TypeParameters(0), False) type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_1`1") Assert.NotNull(type) CheckPropertyAccessorsAndField(m, type, "AA", type.TypeParameters(0), True) End Sub) Next End Sub <Fact> Public Sub CheckEmittedSymbol_ctor() Dim compilationDef = <compilation name="CheckEmittedSymbol_ctor"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Assert.Equal(1, type.InstanceConstructors.Length) Dim constr = type.InstanceConstructors(0) CheckMethod(m, constr, ".ctor", Accessibility.Public, isSub:=True, paramCount:=3) Assert.Equal(type.TypeParameters(0), constr.Parameters(0).Type) Assert.Equal("aa", constr.Parameters(0).Name) Assert.Equal(type.TypeParameters(1), constr.Parameters(1).Type) Assert.Equal("BB", constr.Parameters(1).Name) Assert.Equal(type.TypeParameters(2), constr.Parameters(2).Type) Assert.Equal("CCC", constr.Parameters(2).Name) End Sub) End Sub <Fact> Public Sub CheckEmittedSymbol_ToString() Dim compilationDef = <compilation name="CheckEmittedSymbol_ToString"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Dim toStr = type.GetMember(Of MethodSymbol)("ToString") CheckMethod(m, toStr, "ToString", Accessibility.Public, retType:=GetNamedTypeSymbol(m, "System.String"), isOverrides:=True, isOverloads:=True) Assert.Equal(GetNamedTypeSymbol(m, "System.Object").GetMember("ToString"), toStr.OverriddenMethod) End Sub) End Sub <Fact> Public Sub CheckNoExtraMethodsAreEmittedIfThereIsNoKeyFields() Dim compilationDef = <compilation name="CheckNoExtraMethodsAreEmittedIfThereIsNoKeyFields"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Assert.Equal(0, type.Interfaces.Length) Assert.Equal(0, type.GetMembers("GetHashCode").Length) Assert.Equal(0, type.GetMembers("Equals").Length) End Sub) End Sub <Fact> Public Sub CheckEmittedSymbol_SystemObject_Equals() Dim compilationDef = <compilation name="CheckEmittedSymbol_SystemObject_Equals"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { Key .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Dim method = DirectCast(type.GetMembers("Equals"). Where(Function(s) Return DirectCast(s, MethodSymbol).ExplicitInterfaceImplementations.Length = 0 End Function).Single(), MethodSymbol) CheckMethod(m, method, "Equals", Accessibility.Public, retType:=GetNamedTypeSymbol(m, "System.Boolean"), isOverrides:=True, isOverloads:=True, paramCount:=1) Assert.Equal(GetNamedTypeSymbol(m, "System.Object"), method.Parameters(0).Type) Assert.Equal(GetNamedTypeSymbol(m, "System.Object"). GetMembers("Equals").Where(Function(s) Not s.IsShared).Single(), method.OverriddenMethod) End Sub) End Sub <Fact> Public Sub CheckEmittedSymbol_GetHashCode() Dim compilationDef = <compilation name="CheckEmittedSymbol_GetHashCode"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { Key .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Dim method = type.GetMember(Of MethodSymbol)("GetHashCode") CheckMethod(m, method, "GetHashCode", Accessibility.Public, retType:=GetNamedTypeSymbol(m, "System.Int32"), isOverrides:=True, isOverloads:=True) Assert.Equal(GetNamedTypeSymbol(m, "System.Object").GetMember("GetHashCode"), method.OverriddenMethod) End Sub) End Sub <Fact> Public Sub CheckEmittedSymbol_IEquatableImplementation() Dim compilationDef = <compilation name="CheckEmittedSymbol_GetHashCode"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { Key .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Assert.Equal(1, type.Interfaces.Length) Dim [interface] = type.Interfaces(0) Assert.Equal(GetNamedTypeSymbol(m, "System.IEquatable").Construct(type), [interface]) Dim method = DirectCast(type.GetMembers("Equals"). Where(Function(s) Return DirectCast(s, MethodSymbol).ExplicitInterfaceImplementations.Length = 1 End Function).Single(), MethodSymbol) CheckMethod(m, method, "Equals", Accessibility.Public, retType:=GetNamedTypeSymbol(m, "System.Boolean"), paramCount:=1, isOverloads:=True) Assert.Equal(type, method.Parameters(0).Type) Assert.Equal([interface].GetMember("Equals"), method.ExplicitInterfaceImplementations(0)) End Sub) End Sub <Fact> Public Sub NotEmittingAnonymousTypeCreatedSolelyViaSemanticAPI() Dim compilationDef = <compilation name="NotEmittingAnonymousTypeCreatedSolelyViaSemanticAPI"> <file name="a.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() } 'POSITION End Sub End Module </file> </compilation> Dim position = compilationDef.<file>.Value.IndexOf("'POSITION", StringComparison.Ordinal) CompileAndVerify(compilationDef, references:={SystemCoreRef}, sourceSymbolValidator:=Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node0 = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.AnonymousObjectCreationExpression).AsNode(), ExpressionSyntax) Dim info0 = model.GetSemanticInfoSummary(node0) Assert.NotNull(info0.Type) Dim expr1 = SyntaxFactory.ParseExpression(<text>New With { .aa = 1, .BB = "", .CCC = new SSS() }</text>.Value) Dim info1 = model.GetSpeculativeTypeInfo(position, expr1, SpeculativeBindingOption.BindAsExpression) Assert.NotNull(info1.Type) Assert.Equal(info0.Type.OriginalDefinition, info1.Type.OriginalDefinition) Dim expr2 = SyntaxFactory.ParseExpression(<text>New With { .aa = 1, Key .BB = "", .CCC = new SSS() }</text>.Value) Dim info2 = model.GetSpeculativeTypeInfo(position, expr2, SpeculativeBindingOption.BindAsExpression) Assert.NotNull(info2.Type) Assert.NotEqual(info0.Type.OriginalDefinition, info2.Type.OriginalDefinition) End Sub, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Assert.Equal(GetNamedTypeSymbol(m, "System.Object"), type.BaseType) Assert.True(type.IsGenericType) Assert.Equal(3, type.TypeParameters.Length) ' Only one type should be emitted!! Dim type2 = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_1`3") Assert.Null(type2) End Sub) End Sub <Fact> <WorkItem(641639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/641639")> Public Sub Bug641639() Dim moduleDef = <compilation name="TestModule"> <file name="a.vb"> Module ModuleB Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1 } Dim v2 As Object = Function(y as Integer) y + 1 End Sub End Module </file> </compilation> Dim testModule = CreateCompilationWithMscorlib40AndVBRuntime(moduleDef, TestOptions.ReleaseModule) Dim compilationDef = <compilation> <file name="a.vb"> Module ModuleA End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(moduleDef, {testModule.EmitToImageReference()}, TestOptions.ReleaseDll) Assert.Equal(1, compilation.Assembly.Modules(1).GlobalNamespace.GetTypeMembers("VB$AnonymousDelegate_0<TestModule>", 2).Length) Assert.Equal(1, compilation.Assembly.Modules(1).GlobalNamespace.GetTypeMembers("VB$AnonymousType_0<TestModule>", 1).Length) End Sub #Region "Utils" Private Shared Sub CheckPropertyAccessorsAndField(m As ModuleSymbol, type As NamedTypeSymbol, propName As String, propType As TypeSymbol, isKey As Boolean) Dim prop = DirectCast(type.GetMember(propName), PropertySymbol) Assert.NotNull(prop) Assert.Equal(propType, prop.Type) Assert.Equal(propName, prop.Name) Assert.Equal(propName, prop.MetadataName) Assert.Equal(Accessibility.Public, prop.DeclaredAccessibility) Assert.False(prop.IsDefault) Assert.False(prop.IsMustOverride) Assert.False(prop.IsNotOverridable) Assert.False(prop.IsOverridable) Assert.False(prop.IsOverrides) Assert.False(prop.IsOverloads) Assert.Equal(isKey, prop.IsReadOnly) Assert.False(prop.IsShared) Assert.False(prop.IsWriteOnly) Assert.Equal(0, prop.Parameters.Length) Assert.False(prop.ShadowsExplicitly) Dim getter = prop.GetMethod CheckMethod(m, getter, "get_" & prop.Name, Accessibility.Public, retType:=getter.ReturnType) If Not isKey Then Dim setter = prop.SetMethod CheckMethod(m, setter, "set_" & prop.Name, Accessibility.Public, paramCount:=1, isSub:=True) Assert.Equal(propType, setter.Parameters(0).Type) Else Assert.Null(prop.SetMethod) End If Assert.Equal(0, type.GetMembers("$" & propName).Length) End Sub Private Shared Sub CheckMethod(m As ModuleSymbol, method As MethodSymbol, name As String, accessibility As Accessibility, Optional paramCount As Integer = 0, Optional retType As TypeSymbol = Nothing, Optional isSub As Boolean = False, Optional isOverloads As Boolean = False, Optional isOverrides As Boolean = False, Optional isOverridable As Boolean = False, Optional isNotOverridable As Boolean = False) Assert.NotNull(method) Assert.Equal(name, method.Name) Assert.Equal(paramCount, method.ParameterCount) If isSub Then Assert.Null(retType) Assert.Equal(GetNamedTypeSymbol(m, "System.Void"), method.ReturnType) Assert.True(method.IsSub) End If If retType IsNot Nothing Then Assert.False(isSub) Assert.Equal(retType, method.ReturnType) Assert.False(method.IsSub) End If Assert.Equal(accessibility, method.DeclaredAccessibility) Assert.Equal(isOverloads, method.IsOverloads) Assert.Equal(isOverrides, method.IsOverrides) Assert.Equal(isOverridable, method.IsOverridable) Assert.Equal(isNotOverridable, method.IsNotOverridable) Assert.False(method.IsShared) Assert.False(method.IsMustOverride) Assert.False(method.IsGenericMethod) Assert.False(method.ShadowsExplicitly) End Sub Private Shared Function GetNamedTypeSymbol(m As ModuleSymbol, namedTypeName As String) As NamedTypeSymbol Dim nameParts = namedTypeName.Split("."c) Dim peAssembly = DirectCast(m.ContainingAssembly, PEAssemblySymbol) Dim nsSymbol As NamespaceSymbol = Nothing For Each ns In nameParts.Take(nameParts.Length - 1) nsSymbol = DirectCast(If(nsSymbol Is Nothing, m.ContainingAssembly.CorLibrary.GlobalNamespace.GetMember(ns), nsSymbol.GetMember(ns)), NamespaceSymbol) Next Return DirectCast(nsSymbol.GetTypeMember(nameParts(nameParts.Length - 1)), NamedTypeSymbol) End Function #End Region <Fact, WorkItem(1319, "https://github.com/dotnet/roslyn/issues/1319")> Public Sub MultipleNetmodulesWithAnonymousTypes() Dim compilationDef1 = <compilation> <file name="a.vb"> Class A Friend o1 As Object = new with { .hello = 1, .world = 2 } Friend d1 As Object = Function() 1 public shared Function M1() As String return "Hello, " End Function End Class </file> </compilation> Dim compilationDef2 = <compilation> <file name="a.vb"> Class B Inherits A Friend o2 As Object = new with { .hello = 1, .world = 2 } Friend d2 As Object = Function() 1 public shared Function M2() As String return "world!" End Function End Class </file> </compilation> Dim compilationDef3 = <compilation> <file name="a.vb"> Class Module1 Friend o3 As Object = new with { .hello = 1, .world = 2 } Friend d3 As Object = Function() 1 public shared Sub Main() System.Console.Write(A.M1()) System.Console.WriteLine(B.M2()) End Sub End Class </file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(compilationDef1, options:=TestOptions.ReleaseModule.WithModuleName("A")) comp1.VerifyDiagnostics() Dim ref1 = comp1.EmitToImageReference() Dim comp2 = CreateCompilationWithMscorlib40AndReferences(compilationDef2, {ref1}, options:=TestOptions.ReleaseModule.WithModuleName("B")) comp2.VerifyDiagnostics() Dim ref2 = comp2.EmitToImageReference() Dim comp3 = CreateCompilationWithMscorlib40AndReferences(compilationDef3, {ref1, ref2}, options:=TestOptions.ReleaseExe.WithModuleName("C")) comp3.VerifyDiagnostics() Dim mA = comp3.Assembly.Modules(1) Assert.Equal("VB$AnonymousType_0<A>`2", mA.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousType")).Single().MetadataName) Assert.Equal("VB$AnonymousDelegate_0<A>`1", mA.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousDelegate")).Single().MetadataName) Dim mB = comp3.Assembly.Modules(2) Assert.Equal("VB$AnonymousType_0<B>`2", mB.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousType")).Single().MetadataName) Assert.Equal("VB$AnonymousDelegate_0<B>`1", mB.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousDelegate")).Single().MetadataName) CompileAndVerify(comp3, expectedOutput:="Hello, world!", symbolValidator:= Sub(m) Dim mC = DirectCast(m, PEModuleSymbol) Assert.Equal("VB$AnonymousType_0`2", mC.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousType")).Single().MetadataName) Assert.Equal("VB$AnonymousDelegate_0`1", mC.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousDelegate")).Single().MetadataName) End Sub) End Sub End Class End Namespace
lorcanmooney/roslyn
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousTypes/AnonymousTypesEmittedSymbolsTests.vb
Visual Basic
apache-2.0
38,138
'*******************************************************************************************' ' ' ' 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.Spreadsheet Imports Bytescout.Spreadsheet.Charts Module Module1 Sub Main() ' Create new Spreadsheet object Dim spreadsheet As New Spreadsheet() spreadsheet.RegistrationName = "demo" spreadsheet.RegistrationKey = "demo" ' Add new worksheet Dim sheet As Worksheet = spreadsheet.Workbook.Worksheets.Add("Sample") ' Add few random numbers Dim length As Integer = 10 Dim rnd As New Random() For i As Integer = 0 To length - 1 sheet.Cell(i, 0).Value = rnd.[Next](10) sheet.Cell(i, 1).Value = rnd.[Next](10) Next ' Add charts to worksheet Dim doughnutChart As Chart = sheet.Charts.AddChartAndFitInto(12, 1, 35, 9, ChartType.Doughnut) doughnutChart.SeriesCollection.Add(New Series(sheet.Range(0, 0, length - 1, 0))) doughnutChart.SeriesCollection.Add(New Series(sheet.Range(0, 1, length - 1, 1))) doughnutChart = sheet.Charts.AddChartAndFitInto(12, 10, 35, 18, ChartType.DoughnutExploded) doughnutChart.SeriesCollection.Add(New Series(sheet.Range(0, 0, length - 1, 0))) doughnutChart.SeriesCollection.Add(New Series(sheet.Range(0, 1, length - 1, 1))) ' Save it as XLS spreadsheet.SaveAs("Output.xls") ' Close the document spreadsheet.Close() ' Cleanup spreadsheet.Dispose() ' Open generated XLS file in default associated application Process.Start("Output.xls") End Sub End Module
bytescout/ByteScout-SDK-SourceCode
Spreadsheet SDK/VB.NET/Add Doughnut Chart/Module1.vb
Visual Basic
apache-2.0
2,535
' 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 Imports System.Collections.Generic Imports System.Linq Imports System.Text 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 SyntaxNormalizerTests <WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> <ConditionalFact(GetType(WindowsOnly))> Public Sub TestAllInVB() Dim allInVB As String = TestResource.AllInOneVisualBasicCode Dim expected As String = TestResource.AllInOneVisualBasicBaseline Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(allInVB) Dim actual = node.NormalizeWhitespace(" ").ToFullString() Assert.Equal(expected, actual) End Sub <Fact()> Public Sub TestNormalizeExpressions() TestNormalizeExpression("+1", "+1") TestNormalizeExpression("+a", "+a") TestNormalizeExpression("-a", "-a") TestNormalizeExpression("a", "a") TestNormalizeExpression("a+b", "a + b") TestNormalizeExpression("a-b", "a - b") TestNormalizeExpression("a*b", "a * b") TestNormalizeExpression("a/b", "a / b") TestNormalizeExpression("a mod b", "a mod b") TestNormalizeExpression("a xor b", "a xor b") TestNormalizeExpression("a or b", "a or b") TestNormalizeExpression("a and b", "a and b") TestNormalizeExpression("a orelse b", "a orelse b") TestNormalizeExpression("a andalso b", "a andalso b") TestNormalizeExpression("a<b", "a < b") TestNormalizeExpression("a<=b", "a <= b") TestNormalizeExpression("a>b", "a > b") TestNormalizeExpression("a>=b", "a >= b") TestNormalizeExpression("a=b", "a = b") TestNormalizeExpression("a<>b", "a <> b") TestNormalizeExpression("a<<b", "a << b") TestNormalizeExpression("a>>b", "a >> b") TestNormalizeExpression("(a+b)", "(a + b)") TestNormalizeExpression("((a)+(b))", "((a) + (b))") TestNormalizeExpression("(a)", "(a)") TestNormalizeExpression("(a)(b)", "(a)(b)") TestNormalizeExpression("m()", "m()") TestNormalizeExpression("m(a)", "m(a)") TestNormalizeExpression("m(a,b)", "m(a, b)") TestNormalizeExpression("m(a,b,c)", "m(a, b, c)") TestNormalizeExpression("m(a,b(c,d))", "m(a, b(c, d))") TestNormalizeExpression("m( , ,, )", "m(,,,)") TestNormalizeExpression("a(b(c(0)))", "a(b(c(0)))") TestNormalizeExpression("if(a,b,c)", "if(a, b, c)") TestNormalizeExpression("a().b().c()", "a().b().c()") TestNormalizeExpression("""aM5b"" Like ""a[L-P]#[!c-e]a?""", """aM5b"" Like ""a[L-P]#[!c-e]a?""") End Sub Private Sub TestNormalizeExpression(text As String, expected As String) Dim node = SyntaxFactory.ParseExpression(text) Dim actual = node.NormalizeWhitespace(" ").ToFullString() Assert.Equal(expected, actual) End Sub <Fact()> Public Sub TestTrailingComment() TestNormalizeBlock("Dim goo as Bar ' it is a Bar", "Dim goo as Bar ' it is a Bar" + vbCrLf) End Sub <Fact()> Public Sub TestOptionStatements() TestNormalizeBlock("Option Explicit Off", "Option Explicit Off" + vbCrLf) End Sub <Fact()> Public Sub TestImportsStatements() TestNormalizeBlock("Imports System", "Imports System" + vbCrLf) TestNormalizeBlock("Imports System.Goo.Bar", "Imports System.Goo.Bar" + vbCrLf) TestNormalizeBlock("Imports T2=System.String", "Imports T2 = System.String" + vbCrLf) TestNormalizeBlock("Imports <xmlns:db=""http://example.org/database"">", "Imports <xmlns:db=""http://example.org/database"">" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestLabelStatements() TestNormalizeStatement("while a<b" + vbCrLf + "goo:" + vbCrLf + "c" + vbCrLf + "end while", "while a < b" + vbCrLf + "goo:" + vbCrLf + " c" + vbCrLf + "end while") End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestMethodStatements() TestNormalizeBlock("Sub goo()" + vbCrLf + "a()" + vbCrLf + "end Sub", "Sub goo()" + vbCrLf + " a()" + vbCrLf + "end Sub" + vbCrLf) TestNormalizeBlock("Function goo() as Integer" + vbCrLf + "return 23" + vbCrLf + "end function", "Function goo() as Integer" + vbCrLf + " return 23" + vbCrLf + "end function" + vbCrLf) TestNormalizeBlock("Function goo( x as System.Int32,[Char] as Integer) as Integer" + vbCrLf + "return 23" + vbCrLf + "end function", "Function goo(x as System.Int32, [Char] as Integer) as Integer" + vbCrLf + " return 23" + vbCrLf + "end function" + vbCrLf) TestNormalizeBlock("Sub goo()" + vbCrLf + "Dim a ( ) ( )=New Integer ( ) ( ) ( ){ }" + vbCrLf + "end Sub", "Sub goo()" + vbCrLf + " Dim a()() = New Integer()()() {}" + vbCrLf + "end Sub" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestWithStatements() TestNormalizeBlock( <code> Sub goo() with goo .bar() end with end Sub</code>.Value, _ _ <code>Sub goo() with goo .bar() end with end Sub </code>.Value) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestSyncLockStatements() TestNormalizeBlock("Sub goo()" + vbCrLf + "SyncLock me" + vbCrLf + "bar()" + vbCrLf + "end synclock" + vbCrLf + "end Sub", "Sub goo()" + vbCrLf + " SyncLock me" + vbCrLf + " bar()" + vbCrLf + " end synclock" + vbCrLf + "end Sub" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestEventStatements() TestNormalizeBlock( <code> module m1 private withevents x as y private sub myhandler() Handles y.e1 end sub end module </code>.Value, _ <code>module m1 private withevents x as y private sub myhandler() Handles y.e1 end sub end module </code>.Value) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestAssignmentStatements() TestNormalizeBlock("module m1" + vbCrLf + "sub s1()" + vbCrLf + "Dim x as Integer()" + vbCrLf + "x(2)=23" + vbCrLf + "Dim s as string=""boo""&""ya""" + vbCrLf + "end sub" + vbCrLf + "end module", _ _ "module m1" + vbCrLf + vbCrLf + " sub s1()" + vbCrLf + " Dim x as Integer()" + vbCrLf + " x(2) = 23" + vbCrLf + " Dim s as string = ""boo"" & ""ya""" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) TestNormalizeBlock("module m1" + vbCrLf + vbCrLf + "sub s1()" + vbCrLf + "Dim x as Integer" + vbCrLf + "x^=23" + vbCrLf + "x*=23" + vbCrLf + "x/=23" + vbCrLf + "x\=23" + vbCrLf + "x+=23" + vbCrLf + "x-=23" + vbCrLf + "x<<=23" + vbCrLf + "x>>=23" + vbCrLf + "Dim y as string" + vbCrLf + "y &=""a""" + vbCrLf + "end sub" + vbCrLf + "end module", _ _ "module m1" + vbCrLf + vbCrLf + " sub s1()" + vbCrLf + " Dim x as Integer" + vbCrLf + " x ^= 23" + vbCrLf + " x *= 23" + vbCrLf + " x /= 23" + vbCrLf + " x \= 23" + vbCrLf + " x += 23" + vbCrLf + " x -= 23" + vbCrLf + " x <<= 23" + vbCrLf + " x >>= 23" + vbCrLf + " Dim y as string" + vbCrLf + " y &= ""a""" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) TestNormalizeBlock("module m1" + vbCrLf + "sub s1()" + vbCrLf + "Dim s1 As String=""a""" + vbCrLf + "Dim s2 As String=""b""" + vbCrLf + "Mid$(s1,3,3)=s2" + vbCrLf + "end sub" + vbCrLf + "end module", _ _ "module m1" + vbCrLf + vbCrLf + " sub s1()" + vbCrLf + " Dim s1 As String = ""a""" + vbCrLf + " Dim s2 As String = ""b""" + vbCrLf + " Mid$(s1, 3, 3) = s2" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestCallStatements() TestNormalizeBlock("module m1" + vbCrLf + "sub s2()" + vbCrLf + "s1 ( 23 )" + vbCrLf + "s1 ( p1:=23 , p2:=23)" + vbCrLf + "end sub" + vbCrLf + "end module", _ _ "module m1" + vbCrLf + vbCrLf + " sub s2()" + vbCrLf + " s1(23)" + vbCrLf + " s1(p1:=23, p2:=23)" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) TestNormalizeBlock("module m1" + vbCrLf + vbCrLf + "sub s2 ( Of T ) ( optional x As T=nothing )" + vbCrLf + "N1.M2.S2 ( ) " + vbCrLf + "end sub" + vbCrLf + "end module", _ _ "module m1" + vbCrLf + vbCrLf + " sub s2(Of T)(optional x As T = nothing)" + vbCrLf + " N1.M2.S2()" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) End Sub <Fact()> Public Sub TestNewStatements() TestNormalizeBlock("Dim zipState=New With { Key .ZipCode=98112, .State=""WA"" }", "Dim zipState = New With {Key .ZipCode = 98112, .State = ""WA""}" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397"), WorkItem(546514, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546514")> Public Sub TestXmlAccessStatements() TestNormalizeBlock("Imports <xmlns:db=""http://example.org/database"">" + vbCrLf + "Module Test" + vbCrLf + "Sub Main ( )" + vbCrLf + "Dim x=<db:customer><db:Name>Bob</db:Name></db:customer>" + vbCrLf + "Console . WriteLine ( x .< db:Name > )" + vbCrLf + "End Sub" + vbCrLf + "End Module", _ "Imports <xmlns:db=""http://example.org/database"">" + vbCrLf + "" + vbCrLf + "Module Test" + vbCrLf + vbCrLf + " Sub Main()" + vbCrLf + " Dim x = <db:customer><db:Name>Bob</db:Name></db:customer>" + vbCrLf + " Console.WriteLine(x.<db:Name>)" + vbCrLf + " End Sub" + vbCrLf + "End Module" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestNamespaceStatements() TestNormalizeBlock("Imports I1.I2" + vbCrLf + "Namespace N1" + vbCrLf + "Namespace N2.N3" + vbCrLf + "end Namespace" + vbCrLf + "end Namespace", _ _ "Imports I1.I2" + vbCrLf + "" + vbCrLf + "Namespace N1" + vbCrLf + " Namespace N2.N3" + vbCrLf + " end Namespace" + vbCrLf + "end Namespace" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestNullableStatements() TestNormalizeBlock( <code> module m1 Dim x as Integer?=nothing end module</code>.Value, _ _ <code>module m1 Dim x as Integer? = nothing end module </code>.Value) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestInterfaceStatements() TestNormalizeBlock("namespace N1" + vbCrLf + "Interface I1" + vbCrLf + "public Function F1() As Object" + vbCrLf + "End Interface" + vbCrLf + "Interface I2" + vbCrLf + "Function F2() As Integer" + vbCrLf + "End Interface" + vbCrLf + "Structure S1" + vbCrLf + "Implements I1,I2" + vbCrLf + "public Function F1() As Object" + vbCrLf + "Dim x as Integer=23" + vbCrLf + "return x" + vbCrLf + "end function" + vbCrLf + "End Structure" + vbCrLf + "End Namespace", _ _ "namespace N1" + vbCrLf + vbCrLf + " Interface I1" + vbCrLf + vbCrLf + " public Function F1() As Object" + vbCrLf + vbCrLf + " End Interface" + vbCrLf + vbCrLf + " Interface I2" + vbCrLf + vbCrLf + " Function F2() As Integer" + vbCrLf + vbCrLf + " End Interface" + vbCrLf + vbCrLf + " Structure S1" + vbCrLf + " Implements I1, I2" + vbCrLf + vbCrLf + " public Function F1() As Object" + vbCrLf + " Dim x as Integer = 23" + vbCrLf + " return x" + vbCrLf + " end function" + vbCrLf + " End Structure" + vbCrLf + "End Namespace" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestEnumStatements() TestNormalizeBlock("Module M1" + vbCrLf + vbCrLf + "ENUM E1 as long" + vbCrLf + " goo=23" + vbCrLf + "bar " + vbCrLf + "boo=goo" + vbCrLf + "booya=1.4" + vbCrLf + "end enum" + vbCrLf + "end MODule", _ _ "Module M1" + vbCrLf + vbCrLf + " ENUM E1 as long" + vbCrLf + " goo = 23" + vbCrLf + " bar" + vbCrLf + " boo = goo" + vbCrLf + " booya = 1.4" + vbCrLf + " end enum" + vbCrLf + "end MODule" + vbCrLf) TestNormalizeBlock("class c1" + vbCrLf + "ENUM E1 as long" + vbCrLf + " goo=23" + vbCrLf + "bar " + vbCrLf + "boo=goo" + vbCrLf + "booya=1.4" + vbCrLf + "end enum" + vbCrLf + "end class", _ _ "class c1" + vbCrLf + vbCrLf + " ENUM E1 as long" + vbCrLf + " goo = 23" + vbCrLf + " bar" + vbCrLf + " boo = goo" + vbCrLf + " booya = 1.4" + vbCrLf + " end enum" + vbCrLf + "end class" + vbCrLf) TestNormalizeBlock("public class c1" + vbCrLf + vbCrLf + "ENUM E1 as long" + vbCrLf + " goo=23" + vbCrLf + "bar " + vbCrLf + "boo=goo" + vbCrLf + "booya=1.4" + vbCrLf + "end enum" + vbCrLf + "end class", _ _ "public class c1" + vbCrLf + vbCrLf + " ENUM E1 as long" + vbCrLf + " goo = 23" + vbCrLf + " bar" + vbCrLf + " boo = goo" + vbCrLf + " booya = 1.4" + vbCrLf + " end enum" + vbCrLf + "end class" + vbCrLf) TestNormalizeBlock("class c1" + vbCrLf + "public ENUM E1 as long" + vbCrLf + " goo=23" + vbCrLf + "bar " + vbCrLf + "boo=goo" + vbCrLf + "booya=1.4" + vbCrLf + "end enum" + vbCrLf + "end class", _ _ "class c1" + vbCrLf + vbCrLf + " public ENUM E1 as long" + vbCrLf + " goo = 23" + vbCrLf + " bar" + vbCrLf + " boo = goo" + vbCrLf + " booya = 1.4" + vbCrLf + " end enum" + vbCrLf + "end class" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestDelegateStatements() TestNormalizeBlock("Module M1" + vbCrLf + "Dim x=Function( x ,y )x+y" + vbCrLf + "Dim y As Func ( Of Integer ,Integer ,Integer )=x" + vbCrLf + "end MODule", _ _ "Module M1" + vbCrLf + vbCrLf + " Dim x = Function(x, y) x + y" + vbCrLf + vbCrLf + " Dim y As Func(Of Integer, Integer, Integer) = x" + vbCrLf + "end MODule" + vbCrLf) TestNormalizeBlock("Module M1" + vbCrLf + "Dim x=Function( x ,y )" + vbCrLf + "return x+y" + vbCrLf + "end function" + vbCrLf + "Dim y As Func ( Of Integer ,Integer ,Integer )=x" + vbCrLf + "end MODule", _ _ "Module M1" + vbCrLf + vbCrLf + " Dim x = Function(x, y)" + vbCrLf + " return x + y" + vbCrLf + " end function" + vbCrLf + vbCrLf + " Dim y As Func(Of Integer, Integer, Integer) = x" + vbCrLf + "end MODule" + vbCrLf) TestNormalizeBlock("Module M1" + vbCrLf + "Dim x=Sub( x ,y )" + vbCrLf + "dim x as integer" + vbCrLf + "end sub" + vbCrLf + "Dim y As Action ( Of Integer ,Integer)=x" + vbCrLf + "end MODule", _ _ "Module M1" + vbCrLf + vbCrLf + " Dim x = Sub(x, y)" + vbCrLf + " dim x as integer" + vbCrLf + " end sub" + vbCrLf + vbCrLf + " Dim y As Action(Of Integer, Integer) = x" + vbCrLf + "end MODule" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestSelectStatements() TestNormalizeBlock(" Module M1" + vbCrLf + "sub s1()" + vbCrLf + "select case goo" + vbCrLf + "case 23 " + vbCrLf + "return goo " + vbCrLf + "case 42,11 " + vbCrLf + "return goo " + vbCrLf + "case > 100 " + vbCrLf + "return goo " + vbCrLf + "case 200 to 300 " + vbCrLf + "return goo " + vbCrLf + "case 12," + vbCrLf + "13" + vbCrLf + "return goo " + vbCrLf + "case else" + vbCrLf + "return goo " + vbCrLf + "end select " + vbCrLf + "end sub " + vbCrLf + "end module ", _ _ "Module M1" + vbCrLf + vbCrLf + " sub s1()" + vbCrLf + " select case goo" + vbCrLf + " case 23" + vbCrLf + " return goo" + vbCrLf + " case 42, 11" + vbCrLf + " return goo" + vbCrLf + " case > 100" + vbCrLf + " return goo" + vbCrLf + " case 200 to 300" + vbCrLf + " return goo" + vbCrLf + " case 12, 13" + vbCrLf + " return goo" + vbCrLf + " case else" + vbCrLf + " return goo" + vbCrLf + " end select" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestIfStatement() ' expressions TestNormalizeStatement("a", "a") ' if TestNormalizeStatement("if a then b", "if a then b") TestNormalizeStatement("if a then b else c", "if a then b else c") TestNormalizeStatement("if a then b else if c then d else e", "if a then b else if c then d else e") TestNormalizeStatement("if a then b else if c then d else e", "if a then b else if c then d else e") TestNormalizeStatement("if " + vbTab + " a then b else if c then d else e", "if a then b else if c then d else e") TestNormalizeStatement("if a then" + vbCrLf + "b" + vbCrLf + "end if", "if a then" + vbCrLf + " b" + vbCrLf + "end if") TestNormalizeStatement("if a then" + vbCrLf + vbCrLf + vbCrLf + "b" + vbCrLf + "end if", "if a then" + vbCrLf + " b" + vbCrLf + "end if") TestNormalizeStatement("if a then" + vbCrLf + "if a then" + vbCrLf + "b" + vbCrLf + "end if" + vbCrLf + "else" + vbCrLf + "b" + vbCrLf + "end if", "if a then" + vbCrLf + " if a then" + vbCrLf + " b" + vbCrLf + " end if" + vbCrLf + "else" + vbCrLf + " b" + vbCrLf + "end if") ' line continuation trivia will be removed TestNormalizeStatement("if a then _" + vbCrLf + "b _" + vbCrLf + "else c", "if a then b else c") TestNormalizeStatement("if a then:b:end if", "if a then : b : end if") Dim generatedLeftLiteralToken = SyntaxFactory.IntegerLiteralToken("42", LiteralBase.Decimal, TypeCharacter.None, 42) Dim generatedRightLiteralToken = SyntaxFactory.IntegerLiteralToken("23", LiteralBase.Decimal, TypeCharacter.None, 23) Dim generatedLeftLiteralExpression = SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, generatedLeftLiteralToken) Dim generatedRightLiteralExpression = SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, generatedRightLiteralToken) Dim generatedRedLiteralExpression = SyntaxFactory.GreaterThanExpression(generatedLeftLiteralExpression, SyntaxFactory.Token(SyntaxKind.GreaterThanToken), generatedRightLiteralExpression) Dim generatedRedIfStatement = SyntaxFactory.IfStatement(SyntaxFactory.Token(SyntaxKind.IfKeyword), generatedRedLiteralExpression, SyntaxFactory.Token(SyntaxKind.ThenKeyword, "THeN")) Dim expression As ExpressionSyntax = SyntaxFactory.StringLiteralExpression(SyntaxFactory.StringLiteralToken("goo", "goo")) Dim callexpression = SyntaxFactory.InvocationExpression(expression:=expression) Dim callstatement = SyntaxFactory.CallStatement(SyntaxFactory.Token(SyntaxKind.CallKeyword), callexpression) Dim stmtlist = SyntaxFactory.List(Of StatementSyntax)({CType(callstatement, StatementSyntax), CType(callstatement, StatementSyntax)}) Dim generatedEndIfStatement = SyntaxFactory.EndIfStatement(SyntaxFactory.Token(SyntaxKind.EndKeyword), SyntaxFactory.Token(SyntaxKind.IfKeyword)) Dim mlib = SyntaxFactory.MultiLineIfBlock(generatedRedIfStatement, stmtlist, Nothing, Nothing, generatedEndIfStatement) Dim str = mlib.NormalizeWhitespace(" ").ToFullString() Assert.Equal("If 42 > 23 THeN" + vbCrLf + " Call goo" + vbCrLf + " Call goo" + vbCrLf + "End If", str) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestLoopStatements() TestNormalizeStatement("while a<b" + vbCrLf + "c " + vbCrLf + "end while", "while a < b" + vbCrLf + " c" + vbCrLf + "end while") TestNormalizeStatement("DO until a(2)<>12" + vbCrLf + "Dim x = 12" + vbCrLf + " loop", _ _ "DO until a(2) <> 12" + vbCrLf + " Dim x = 12" + vbCrLf + "loop") TestNormalizeStatement("DO while a(2)<>12" + vbCrLf + "Dim x = 12" + vbCrLf + " loop", _ _ "DO while a(2) <> 12" + vbCrLf + " Dim x = 12" + vbCrLf + "loop") TestNormalizeStatement("DO " + vbCrLf + "Dim x = 12" + vbCrLf + " loop", _ _ "DO" + vbCrLf + " Dim x = 12" + vbCrLf + "loop") TestNormalizeStatement("DO " + vbCrLf + "Dim x = 12" + vbCrLf + " loop until a ( 2 ) <> 12 ", _ _ "DO" + vbCrLf + " Dim x = 12" + vbCrLf + "loop until a(2) <> 12") TestNormalizeStatement("For Each i In x" + vbCrLf + "Dim x = 12" + vbCrLf + " next", _ _ "For Each i In x" + vbCrLf + " Dim x = 12" + vbCrLf + "next") TestNormalizeStatement("For Each i In x" + vbCrLf + "For Each j In x" + vbCrLf + "Dim x = 12" + vbCrLf + " next j,i", _ _ "For Each i In x" + vbCrLf + " For Each j In x" + vbCrLf + " Dim x = 12" + vbCrLf + "next j, i") End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestExceptionsStatements() TestNormalizeStatement(" try" + vbCrLf + "dim x =23" + vbCrLf + "Catch e1 As Exception When 1>2" + vbCrLf + "dim x =23" + vbCrLf + "Catch" + vbCrLf + "dim x =23" + vbCrLf + "finally" + vbCrLf + "dim x =23" + vbCrLf + " end try", _ _ "try" + vbCrLf + " dim x = 23" + vbCrLf + "Catch e1 As Exception When 1 > 2" + vbCrLf + " dim x = 23" + vbCrLf + "Catch" + vbCrLf + " dim x = 23" + vbCrLf + "finally" + vbCrLf + " dim x = 23" + vbCrLf + "end try") End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestUsingStatements() TestNormalizeStatement(" Using r1 As R = New R ( ) , r2 As R = New R( )" + vbCrLf + "dim x =23" + vbCrLf + "end using", _ _ "Using r1 As R = New R(), r2 As R = New R()" + vbCrLf + " dim x = 23" + vbCrLf + "end using") End Sub <Fact()> Public Sub TestQueryExpressions() TestNormalizeStatement(" Dim waCusts = _" + vbCrLf + "From cust As Customer In Customers _" + vbCrLf + "Where cust.State = ""WA""", _ _ "Dim waCusts = From cust As Customer In Customers Where cust.State = ""WA""") End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestDefaultCasingForKeywords() Dim expected = "Module m1" + vbCrLf + vbCrLf + " Dim x = Function(x, y) x + y" + vbCrLf + vbCrLf + " Dim y As func(Of Integer, Integer, Integer) = x" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(expected.ToLowerInvariant) Dim actual = node.NormalizeWhitespace(indentation:=" ", useDefaultCasing:=True).ToFullString() Assert.Equal(expected, actual) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestComment() ' trailing whitespace will be aligned to the indent level (see second comment) ' when determining if there should be a separator between tokens, the current algorithm does not check if a token comes out ' of structured trivia. Because of that there is now a space at the end of structured trivia before the next token ' whitespace before comments get reduced to one (see comment after code), whitespace in trivia is maintained (see same comment) ' xml doc comments somehow contain \n in the XmlTextLiterals ... will not spend time to work around Dim input = "Module m1" + vbCrLf + " ' a nice comment" + vbCrLf + " ''' even more comments" + vbCrLf + "' and more comments " + vbCrLf + "#if false " + vbCrLf + " whatever? " + vbCrLf + "#end if" + vbCrLf + "' and more comments" + vbCrLf + " ''' structured trivia before code" + vbCrLf + "Dim x = Function(x, y) x + y ' trivia after code" + vbCrLf + "End Module" Dim expected = "Module m1" + vbCrLf + vbCrLf + " ' a nice comment" + vbCrLf + " ''' even more comments" + vbCrLf + vbCrLf + " ' and more comments " + vbCrLf + "#if false" + vbCrLf + " whatever? " + vbCrLf + "#end if" + vbCrLf + " ' and more comments" + vbCrLf + " ''' structured trivia before code" + vbCrLf + " Dim x = Function(x, y) x + y ' trivia after code" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(input) Dim actual = node.NormalizeWhitespace(" ").ToFullString() Assert.Equal(expected, actual) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestMultilineLambdaFunctionsAsParameter() ' trailing whitespace will be aligned to the indent level (see second comment) ' when determining if there should be a separator between tokens, the current algorithm does not check if a token comes out ' of structured trivia. Because of that there is now a space at the end of structured trivia before the next token ' whitespace before comments get reduced to one (see comment after code), whitespace in trivia is maintained (see same comment) ' xml doc comments somehow contain \n in the XmlTextLiterals ... will not spend time to work around Dim input = "Module m1" + vbCrLf + "Sub Main(args As String())" + vbCrLf + "Sub1(Function(p As Integer)" + vbCrLf + "Sub2()" + vbCrLf + "End Function)" + vbCrLf + "End Sub" + vbCrLf + "End Module" Dim expected = "Module m1" + vbCrLf + vbCrLf + " Sub Main(args As String())" + vbCrLf + " Sub1(Function(p As Integer)" + vbCrLf + " Sub2()" + vbCrLf + " End Function)" + vbCrLf + " End Sub" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(input) Dim actual = node.NormalizeWhitespace(" ").ToFullString() Assert.Equal(expected, actual) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestProperty() Dim input = <text>Property p As Integer Get End Get Set ( value As Integer ) End Set End Property</text>.Value.Replace(vbLf, vbCrLf) Dim expected = <text>Property p As Integer Get End Get Set(value As Integer) End Set End Property </text>.Value.Replace(vbLf, vbCrLf) TestNormalizeBlock(input, expected) End Sub Private Sub TestNormalizeStatement(text As String, expected As String) Dim node As StatementSyntax = SyntaxFactory.ParseExecutableStatement(text) Dim actual = node.NormalizeWhitespace(" ").ToFullString() Assert.Equal(expected, actual) End Sub Private Sub TestNormalizeBlock(text As String, expected As String) Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(text) Dim actual = node.NormalizeWhitespace(" ").ToFullString() expected = expected.Replace(vbCrLf, vbLf).Replace(vbLf, vbCrLf) ' in case tests use XML literals Assert.Equal(expected, actual) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestStructuredTriviaAndAttributes() Dim source = "Module m1" + vbCrLf + " '''<x>...</x>" + vbCrLf + " <goo()>" + vbCrLf + " sub a()" + vbCrLf + " end sub" + vbCrLf + "End Module" + vbCrLf + vbCrLf Dim expected = "Module m1" + vbCrLf + vbCrLf + " '''<x>...</x>" + vbCrLf + " <goo()>" + vbCrLf + " sub a()" + vbCrLf + " end sub" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(source) Dim actual = node.NormalizeWhitespace(indentation:=" ", useDefaultCasing:=False).ToFullString() Assert.Equal(expected, actual) End Sub <Fact(), WorkItem(531607, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531607")> Public Sub TestNestedStructuredTrivia() Dim trivia = SyntaxFactory.TriviaList( SyntaxFactory.Trivia( SyntaxFactory.ConstDirectiveTrivia( "constant", SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(1).WithTrailingTrivia(SyntaxFactory.Trivia(SyntaxFactory.SkippedTokensTrivia(SyntaxFactory.TokenList(SyntaxFactory.Literal("A"c))))))))) Dim expected = "#Const constant = 1 ""A""c" Dim actual = trivia.NormalizeWhitespace(indentation:=" ", elasticTrivia:=False, useDefaultCasing:=False).ToFullString() Assert.Equal(expected, actual) End Sub <Fact()> Public Sub TestCrefAttribute() Dim source = "''' <summary>" + vbCrLf + "''' <see cref = """"/>" + vbCrLf + "''' <see cref =""""/>" + vbCrLf + "''' <see cref= """"/>" + vbCrLf + "''' <see cref=""""/>" + vbCrLf + "''' <see cref = ""1""/>" + vbCrLf + "''' <see cref =""a""/>" + vbCrLf + "''' <see cref= ""Integer()""/>" + vbCrLf + "''' <see cref = ""a()""/>" + vbCrLf + "''' </summary>" + vbCrLf + "Module Program" + vbCrLf + "End Module" + vbCrLf Dim expected = "''' <summary>" + vbCrLf + "''' <see cref=""""/> " + vbCrLf + "''' <see cref=""""/> " + vbCrLf + "''' <see cref=""""/> " + vbCrLf + "''' <see cref=""""/> " + vbCrLf + "''' <see cref=""1""/> " + vbCrLf + "''' <see cref=""a""/> " + vbCrLf + "''' <see cref=""Integer()""/> " + vbCrLf + "''' <see cref=""a()""/> " + vbCrLf + "''' </summary>" + vbCrLf + "Module Program" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(source) Dim actual = node.NormalizeWhitespace(indentation:=" ", useDefaultCasing:=False).ToFullString() Assert.Equal(expected, actual) End Sub <Fact()> Public Sub TestNameAttribute() Dim source = "''' <summary>" + vbCrLf + "''' <paramref name = """"/>" + vbCrLf + "''' <paramref name =""""/>" + vbCrLf + "''' <paramref name= """"/>" + vbCrLf + "''' <paramref name=""""/>" + vbCrLf + "''' <paramref name = ""1""/>" + vbCrLf + "''' <paramref name =""a""/>" + vbCrLf + "''' <paramref name= ""Integer()""/>" + vbCrLf + "''' <paramref name = ""a()""/>" + vbCrLf + "''' </summary>" + vbCrLf + "Module Program" + vbCrLf + "End Module" + vbCrLf Dim expected = "''' <summary>" + vbCrLf + "''' <paramref name=""""/> " + vbCrLf + "''' <paramref name=""""/> " + vbCrLf + "''' <paramref name=""""/> " + vbCrLf + "''' <paramref name=""""/> " + vbCrLf + "''' <paramref name=""1""/> " + vbCrLf + "''' <paramref name=""a""/> " + vbCrLf + "''' <paramref name=""Integer()""/> " + vbCrLf + "''' <paramref name=""a()""/> " + vbCrLf + "''' </summary>" + vbCrLf + "Module Program" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(source) Dim actual = node.NormalizeWhitespace(indentation:=" ", useDefaultCasing:=False).ToFullString() Assert.Equal(expected, actual) End Sub <Fact> Public Sub TestEnableWarningDirective() Dim text = <![CDATA[ # enable warning[BC000],Bc123, BC456,_789' comment # enable warning # enable warning ,]]>.Value.Replace(vbLf, vbCrLf) Dim root = Parse(text).GetRoot() Dim normalizedRoot = root.NormalizeWhitespace(indentation:=" ", elasticTrivia:=True, useDefaultCasing:=True) Dim expected = <![CDATA[#Enable Warning [BC000], Bc123, BC456, _789 ' comment #Enable Warning #Enable Warning , ]]>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expected, normalizedRoot.ToFullString()) End Sub <Fact> Public Sub TestDisableWarningDirective() Dim text = <![CDATA[Module Program # disable warning Sub Main() #disable warning bc123, Bc456,BC789 End Sub # disable warning[BC123], ' Comment End Module]]>.Value.Replace(vbLf, vbCrLf) Dim root = Parse(text).GetRoot() Dim normalizedRoot = root.NormalizeWhitespace(indentation:=" ", elasticTrivia:=True, useDefaultCasing:=True) Dim expected = <![CDATA[Module Program #Disable Warning Sub Main() #Disable Warning bc123, Bc456, BC789 End Sub #Disable Warning [BC123], ' Comment End Module ]]>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expected, normalizedRoot.ToFullString()) End Sub <Fact> Public Sub TestNormalizeEOL() Dim code = "Class C" & vbCrLf & "End Class" Dim expected = "Class C" & vbLf & "End Class" & vbLf Dim actual = SyntaxFactory.ParseCompilationUnit(code).NormalizeWhitespace(" ", eol:=vbLf).ToFullString() Assert.Equal(expected, actual) End Sub <Fact> Public Sub TestNormalizeTabs() Dim code = "Class C" & vbCrLf & "Sub M()" & vbCrLf & "End Sub" & vbCrLf & "End Class" Dim expected = "Class C" & vbCrLf & vbCrLf & vbTab & "Sub M()" & vbCrLf & vbTab & "End Sub" & vbCrLf & "End Class" & vbCrLf Dim actual = SyntaxFactory.ParseCompilationUnit(code).NormalizeWhitespace(vbTab).ToFullString() Assert.Equal(expected, actual) End Sub End Class End Namespace
AlekseyTs/roslyn
src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxNormalizerTests.vb
Visual Basic
mit
46,399
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend Class VisualBasicDeclarationComputer Inherits DeclarationComputer Public Shared Sub ComputeDeclarationsInSpan(model As SemanticModel, span As TextSpan, getSymbol As Boolean, builder As List(Of DeclarationInfo), cancellationToken As CancellationToken) ComputeDeclarationsCore(model, model.SyntaxTree.GetRoot(), Function(node, level) Not node.Span.OverlapsWith(span) OrElse InvalidLevel(level), getSymbol, builder, Nothing, cancellationToken) End Sub Public Shared Sub ComputeDeclarationsInNode(model As SemanticModel, node As SyntaxNode, getSymbol As Boolean, builder As List(Of DeclarationInfo), cancellationToken As CancellationToken, Optional levelsToCompute As Integer? = Nothing) ComputeDeclarationsCore(model, node, Function(n, level) InvalidLevel(level), getSymbol, builder, levelsToCompute, cancellationToken) End Sub Private Shared Function InvalidLevel(level As Integer?) As Boolean Return level.HasValue AndAlso level.Value <= 0 End Function Private Shared Function DecrementLevel(level As Integer?) As Integer? Return If(level.HasValue, level.Value - 1, level) End Function Private Shared Sub ComputeDeclarationsCore(model As SemanticModel, node As SyntaxNode, shouldSkip As Func(Of SyntaxNode, Integer?, Boolean), getSymbol As Boolean, builder As List(Of DeclarationInfo), levelsToCompute As Integer?, cancellationToken As CancellationToken) cancellationToken.ThrowIfCancellationRequested() If shouldSkip(node, levelsToCompute) Then Return End If Dim newLevel = DecrementLevel(levelsToCompute) Select Case node.Kind() Case SyntaxKind.NamespaceBlock Dim ns = CType(node, NamespaceBlockSyntax) For Each decl In ns.Members ComputeDeclarationsCore(model, decl, shouldSkip, getSymbol, builder, newLevel, cancellationToken) Next builder.Add(GetDeclarationInfo(model, node, getSymbol, cancellationToken)) Dim name = ns.NamespaceStatement.Name While (name.Kind() = SyntaxKind.QualifiedName) name = (CType(name, QualifiedNameSyntax)).Left Dim declaredSymbol = If(getSymbol, model.GetSymbolInfo(name, cancellationToken).Symbol, Nothing) builder.Add(New DeclarationInfo(name, ImmutableArray(Of SyntaxNode).Empty, declaredSymbol)) End While Return Case SyntaxKind.EnumBlock Dim t = CType(node, EnumBlockSyntax) For Each decl In t.Members ComputeDeclarationsCore(model, decl, shouldSkip, getSymbol, builder, newLevel, cancellationToken) Next builder.Add(GetDeclarationInfo(model, node, getSymbol, cancellationToken)) Return Case SyntaxKind.EnumMemberDeclaration Dim t = CType(node, EnumMemberDeclarationSyntax) builder.Add(GetDeclarationInfo(model, node, getSymbol, t.Initializer, cancellationToken)) Return Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Dim t = CType(node, DelegateStatementSyntax) Dim paramInitializers As IEnumerable(Of SyntaxNode) = GetParameterInitializers(t.ParameterList) builder.Add(GetDeclarationInfo(model, node, getSymbol, paramInitializers, cancellationToken)) Return Case SyntaxKind.EventBlock Dim t = CType(node, EventBlockSyntax) For Each decl In t.Accessors ComputeDeclarationsCore(model, decl, shouldSkip, getSymbol, builder, newLevel, cancellationToken) Next Dim eventInitializers = GetParameterInitializers(t.EventStatement.ParameterList) builder.Add(GetDeclarationInfo(model, node, getSymbol, eventInitializers, cancellationToken)) Return Case SyntaxKind.EventStatement Dim t = CType(node, EventStatementSyntax) Dim paramInitializers = GetParameterInitializers(t.ParameterList) builder.Add(GetDeclarationInfo(model, node, getSymbol, paramInitializers, cancellationToken)) Return Case SyntaxKind.FieldDeclaration Dim t = CType(node, FieldDeclarationSyntax) For Each decl In t.Declarators For Each identifier In decl.Names builder.Add(GetDeclarationInfo(model, identifier, getSymbol, decl.Initializer, cancellationToken)) Next Next Return Case SyntaxKind.PropertyBlock Dim t = CType(node, PropertyBlockSyntax) For Each decl In t.Accessors ComputeDeclarationsCore(model, decl, shouldSkip, getSymbol, builder, newLevel, cancellationToken) Next Dim propertyInitializers = GetParameterInitializers(t.PropertyStatement.ParameterList) Dim codeBlocks = propertyInitializers.Concat(t.PropertyStatement.Initializer) builder.Add(GetDeclarationInfo(model, node, getSymbol, codeBlocks, cancellationToken)) Return Case SyntaxKind.PropertyStatement Dim t = CType(node, PropertyStatementSyntax) Dim propertyInitializers = GetParameterInitializers(t.ParameterList) Dim codeBlocks = propertyInitializers.Concat(t.Initializer) builder.Add(GetDeclarationInfo(model, node, getSymbol, codeBlocks, cancellationToken)) Return Case SyntaxKind.CompilationUnit Dim t = CType(node, CompilationUnitSyntax) For Each decl In t.Members ComputeDeclarationsCore(model, decl, shouldSkip, getSymbol, builder, newLevel, cancellationToken) Next Return Case Else Dim typeBlock = TryCast(node, TypeBlockSyntax) If typeBlock IsNot Nothing Then For Each decl In typeBlock.Members ComputeDeclarationsCore(model, decl, shouldSkip, getSymbol, builder, newLevel, cancellationToken) Next builder.Add(GetDeclarationInfo(model, node, getSymbol, cancellationToken)) Return End If Dim typeStatement = TryCast(node, TypeStatementSyntax) If typeStatement IsNot Nothing Then builder.Add(GetDeclarationInfo(model, node, getSymbol, cancellationToken)) Return End If Dim methodBlock = TryCast(node, MethodBlockBaseSyntax) If methodBlock IsNot Nothing Then Dim paramInitializers = GetParameterInitializers(methodBlock.BlockStatement.ParameterList) Dim codeBlocks = paramInitializers.Concat(methodBlock.Statements).Concat(methodBlock.EndBlockStatement) builder.Add(GetDeclarationInfo(model, node, getSymbol, codeBlocks, cancellationToken)) Return End If Dim methodStatement = TryCast(node, MethodBaseSyntax) If methodStatement IsNot Nothing Then Dim paramInitializers = GetParameterInitializers(methodStatement.ParameterList) builder.Add(GetDeclarationInfo(model, node, getSymbol, paramInitializers, cancellationToken)) Return End If Return End Select End Sub Private Shared Function GetParameterInitializers(parameterList As ParameterListSyntax) As IEnumerable(Of SyntaxNode) Return If(parameterList IsNot Nothing, parameterList.Parameters.Select(Function(p) p.Default), SpecializedCollections.EmptyEnumerable(Of SyntaxNode)) End Function End Class End Namespace
MihaMarkic/roslyn-prank
src/Compilers/VisualBasic/BasicAnalyzerDriver/VisualBasicDeclarationComputer.vb
Visual Basic
apache-2.0
9,057
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.34014 ' ' 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("Project2.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
Neo-Desktop/Coleman-Code
COM350/Project2/Project2/My Project/Resources.Designer.vb
Visual Basic
mit
2,717
Imports NetOffice Imports System.Runtime.InteropServices Imports NetOffice.Tools Imports Office = NetOffice.OfficeApi Imports NetOffice.OfficeApi.Tools.Contribution Imports Excel = NetOffice.ExcelApi Imports NetOffice.ExcelApi.Tools 'Register Addin Example ' <COMAddin("Excel04 Sample Addin VB4", "Register Addin Example", LoadBehavior.LoadAtStartup)> <ProgId("Excel04AddinVB4.Connect"), Guid("CCFA5EB8-D53E-476A-9318-35CF655AD417"), Codebase, Timestamp> <RegistryLocation(RegistrySaveLocation.InstallScopeCurrentUser)> Public Class Addin Inherits COMAddin <UnRegisterFunction(RegisterMode.CallAfter)> ' We want that NetOffice call this method after register Private Shared Sub Register(type As Type, registerCall As RegisterCall, scope As InstallScope, keyState As OfficeRegisterKeyState) End Sub <RegisterFunction(RegisterMode.CallBeforeAndAfter)> ' We want that NetOffice call this method before and after unregister Private Shared Sub Unregister(type As Type, registerCall As RegisterCall, scope As InstallScope, keyState As OfficeRegisterKeyState) End Sub ' An unexpected error occured in register or unregister action <RegisterErrorHandler> Private Shared Sub RegisterError(methodKind As RegisterErrorMethodKind, exception As Exception) DialogUtils.ShowRegisterError("Excel04AddinVB4", methodKind, exception) End Sub End Class
NetOfficeFw/NetOffice
Examples/Excel/VB/NetOffice COMAddin Examples/04 Register and Unregister/Addin.vb
Visual Basic
mit
1,396
Imports System.Collections Imports System.Collections.Specialized Public Class Entity Private mName As String Private mSetName As String Private mDescription As String Private mModel As Model Private mDescriptor As String Private mSetDescriptor As String Private mGenre As String Private mSqlTable As String Private mProperties As IList = New ArrayList() Private mRelations As IList = New ArrayList() Public Property Name() As String Get Return mName End Get Set(ByVal Value As String) mName = Value End Set End Property Public Property Description() As String Get Return mDescription End Get Set(ByVal Value As String) mDescription = Value End Set End Property Public Property Model() As Model Get Return mModel End Get Set(ByVal Value As Model) mModel = Value End Set End Property Public Property SetName() As String Get If mSetName Is Nothing Then Return Name & "s" End If Return mSetName End Get Set(ByVal Value As String) mSetName = Value End Set End Property Public Property Descriptor() As String Get If mDescriptor Is Nothing Then Return Name End If Return mDescriptor End Get Set(ByVal Value As String) mDescriptor = Value End Set End Property Public Property SetDescriptor() As String Get If mSetDescriptor Is Nothing Then Return SetName End If Return mSetDescriptor End Get Set(ByVal Value As String) mSetDescriptor = Value End Set End Property Public Property Genre() As String Get If mGenre Is Nothing Then Return "M" End If Return mGenre End Get Set(ByVal Value As String) mGenre = Value End Set End Property Public Property SqlTable() As String Get If mSqlTable Is Nothing Then Return SetName End If Return mSqlTable End Get Set(ByVal Value As String) mSqlTable = Value End Set End Property Public ReadOnly Property Properties() As IList Get Return mProperties End Get End Property Public ReadOnly Property Relations() As IList Get Return mRelations End Get End Property Public Function GetProperty(ByVal name As String) As EntityProperty Dim prop As EntityProperty For Each prop In Properties If prop.Name = name Then Return prop End If Next Return Nothing End Function Public Function GetRelation(ByVal name As String) As EntityRelation Dim rel As EntityRelation For Each rel In Relations If rel.Name = name Then Return rel End If Next Return Nothing End Function End Class
ajlopez/AjGenesis
src/AjGenesis/Model/Entity.vb
Visual Basic
mit
3,432
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Form11 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.btn_link11 = New System.Windows.Forms.Button() Me.SuspendLayout() ' 'btn_link11 ' Me.btn_link11.BackColor = System.Drawing.Color.Transparent Me.btn_link11.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None Me.btn_link11.Cursor = System.Windows.Forms.Cursors.Hand Me.btn_link11.ForeColor = System.Drawing.Color.Transparent Me.btn_link11.Location = New System.Drawing.Point(12, 219) Me.btn_link11.Name = "btn_link11" Me.btn_link11.Size = New System.Drawing.Size(111, 36) Me.btn_link11.TabIndex = 2 Me.btn_link11.UseVisualStyleBackColor = False ' 'Form11 ' Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None Me.BackgroundImage = Global.Nvidia_Graphics_Driver_Installer.My.Resources.Resources.Screenshot_1031 Me.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch Me.ClientSize = New System.Drawing.Size(441, 264) Me.Controls.Add(Me.btn_link11) Me.DoubleBuffered = True Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None Me.MaximizeBox = False Me.MinimizeBox = False Me.Name = "Form11" Me.ShowIcon = False Me.ShowInTaskbar = False Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent Me.ResumeLayout(False) End Sub Friend WithEvents btn_link11 As Button End Class
conorpark/phishingPrank
Fake-GPU-driver-installer/Form11.Designer.vb
Visual Basic
mit
2,434
Namespace Security.View_Layout Public Class Restore Inherits SecurityItemBase Public Sub New() _ConceptItemName = "Restore" _ConceptName = "View_Layout" _Description = "Enable Layout 'Restore' button" _IsEnterprise = True _IsSmallBusiness = True _IsViewer = True _IsWeb = True _IsWebPlus = True End Sub End Class End Namespace
nublet/DMS
DMS.Forms.Shared/Security/Items/View/Layout/Restore.vb
Visual Basic
mit
464
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Form1 Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.Label1 = New System.Windows.Forms.Label Me.Label2 = New System.Windows.Forms.Label Me.Label3 = New System.Windows.Forms.Label Me.Label4 = New System.Windows.Forms.Label Me.Label5 = New System.Windows.Forms.Label Me.Label6 = New System.Windows.Forms.Label Me.Label7 = New System.Windows.Forms.Label Me.Label8 = New System.Windows.Forms.Label Me.Label9 = New System.Windows.Forms.Label Me.Label10 = New System.Windows.Forms.Label Me.Label11 = New System.Windows.Forms.Label Me.btnCalculate = New System.Windows.Forms.Button Me.btnExit = New System.Windows.Forms.Button Me.TextBox1 = New System.Windows.Forms.TextBox Me.txtEP1 = New System.Windows.Forms.TextBox Me.txtEP2 = New System.Windows.Forms.TextBox Me.txtEP3 = New System.Windows.Forms.TextBox Me.txtSupplies = New System.Windows.Forms.TextBox Me.txtRent = New System.Windows.Forms.TextBox Me.txtPayroll = New System.Windows.Forms.TextBox Me.txtRevenue = New System.Windows.Forms.TextBox Me.txtUtilities = New System.Windows.Forms.TextBox Me.txtProfit = New System.Windows.Forms.TextBox Me.txtLoss = New System.Windows.Forms.TextBox Me.txtEP4 = New System.Windows.Forms.TextBox Me.txtOther = New System.Windows.Forms.TextBox Me.txtTotalExpense = New System.Windows.Forms.TextBox Me.txtEP5 = New System.Windows.Forms.TextBox Me.btnClear = New System.Windows.Forms.Button Me.SuspendLayout() ' 'Label1 ' Me.Label1.AutoSize = True Me.Label1.Location = New System.Drawing.Point(52, 36) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(51, 13) Me.Label1.TabIndex = 0 Me.Label1.Text = "Revenue" ' 'Label2 ' Me.Label2.AutoSize = True Me.Label2.Location = New System.Drawing.Point(52, 91) Me.Label2.Name = "Label2" Me.Label2.Size = New System.Drawing.Size(53, 13) Me.Label2.TabIndex = 1 Me.Label2.Text = "Expenses" ' 'Label3 ' Me.Label3.AutoSize = True Me.Label3.Location = New System.Drawing.Point(52, 138) Me.Label3.Name = "Label3" Me.Label3.Size = New System.Drawing.Size(30, 13) Me.Label3.TabIndex = 2 Me.Label3.Text = "Rent" ' 'Label4 ' Me.Label4.AutoSize = True Me.Label4.Location = New System.Drawing.Point(52, 161) Me.Label4.Name = "Label4" Me.Label4.Size = New System.Drawing.Size(38, 13) Me.Label4.TabIndex = 3 Me.Label4.Text = "Payroll" ' 'Label5 ' Me.Label5.AutoSize = True Me.Label5.Location = New System.Drawing.Point(52, 185) Me.Label5.Name = "Label5" Me.Label5.Size = New System.Drawing.Size(40, 13) Me.Label5.TabIndex = 4 Me.Label5.Text = "Utilities" ' 'Label6 ' Me.Label6.AutoSize = True Me.Label6.Location = New System.Drawing.Point(52, 211) Me.Label6.Name = "Label6" Me.Label6.Size = New System.Drawing.Size(47, 13) Me.Label6.TabIndex = 5 Me.Label6.Text = "Supplies" ' 'Label7 ' Me.Label7.AutoSize = True Me.Label7.Location = New System.Drawing.Point(52, 233) Me.Label7.Name = "Label7" Me.Label7.Size = New System.Drawing.Size(33, 13) Me.Label7.TabIndex = 6 Me.Label7.Text = "Other" ' 'Label8 ' Me.Label8.AutoSize = True Me.Label8.Location = New System.Drawing.Point(52, 254) Me.Label8.Name = "Label8" Me.Label8.Size = New System.Drawing.Size(80, 13) Me.Label8.TabIndex = 7 Me.Label8.Text = "Total Expenses" ' 'Label9 ' Me.Label9.AutoSize = True Me.Label9.Location = New System.Drawing.Point(52, 298) Me.Label9.Name = "Label9" Me.Label9.Size = New System.Drawing.Size(31, 13) Me.Label9.TabIndex = 8 Me.Label9.Text = "Profit" ' 'Label10 ' Me.Label10.AutoSize = True Me.Label10.Location = New System.Drawing.Point(52, 321) Me.Label10.Name = "Label10" Me.Label10.Size = New System.Drawing.Size(29, 13) Me.Label10.TabIndex = 9 Me.Label10.Text = "Loss" ' 'Label11 ' Me.Label11.AutoSize = True Me.Label11.Location = New System.Drawing.Point(283, 91) Me.Label11.Name = "Label11" Me.Label11.Size = New System.Drawing.Size(111, 13) Me.Label11.TabIndex = 10 Me.Label11.Text = "Expense Percentages" ' 'btnCalculate ' Me.btnCalculate.Location = New System.Drawing.Point(286, 270) Me.btnCalculate.Name = "btnCalculate" Me.btnCalculate.Size = New System.Drawing.Size(96, 23) Me.btnCalculate.TabIndex = 11 Me.btnCalculate.Text = "&Calculate" Me.btnCalculate.UseVisualStyleBackColor = True ' 'btnExit ' Me.btnExit.Location = New System.Drawing.Point(286, 311) Me.btnExit.Name = "btnExit" Me.btnExit.Size = New System.Drawing.Size(96, 23) Me.btnExit.TabIndex = 12 Me.btnExit.Text = "E&xit" Me.btnExit.UseVisualStyleBackColor = True ' 'TextBox1 ' Me.TextBox1.Location = New System.Drawing.Point(122, 225) Me.TextBox1.Name = "TextBox1" Me.TextBox1.Size = New System.Drawing.Size(96, 20) Me.TextBox1.TabIndex = 13 ' 'txtEP1 ' Me.txtEP1.Location = New System.Drawing.Point(286, 131) Me.txtEP1.Name = "txtEP1" Me.txtEP1.ReadOnly = True Me.txtEP1.Size = New System.Drawing.Size(96, 20) Me.txtEP1.TabIndex = 14 ' 'txtEP2 ' Me.txtEP2.Location = New System.Drawing.Point(286, 161) Me.txtEP2.Name = "txtEP2" Me.txtEP2.ReadOnly = True Me.txtEP2.Size = New System.Drawing.Size(96, 20) Me.txtEP2.TabIndex = 15 ' 'txtEP3 ' Me.txtEP3.Location = New System.Drawing.Point(286, 187) Me.txtEP3.Name = "txtEP3" Me.txtEP3.ReadOnly = True Me.txtEP3.Size = New System.Drawing.Size(96, 20) Me.txtEP3.TabIndex = 16 ' 'txtSupplies ' Me.txtSupplies.Location = New System.Drawing.Point(122, 208) Me.txtSupplies.Name = "txtSupplies" Me.txtSupplies.Size = New System.Drawing.Size(96, 20) Me.txtSupplies.TabIndex = 5 ' 'txtRent ' Me.txtRent.Location = New System.Drawing.Point(122, 135) Me.txtRent.Name = "txtRent" Me.txtRent.Size = New System.Drawing.Size(96, 20) Me.txtRent.TabIndex = 2 ' 'txtPayroll ' Me.txtPayroll.Location = New System.Drawing.Point(122, 158) Me.txtPayroll.Name = "txtPayroll" Me.txtPayroll.Size = New System.Drawing.Size(96, 20) Me.txtPayroll.TabIndex = 3 ' 'txtRevenue ' Me.txtRevenue.Location = New System.Drawing.Point(122, 33) Me.txtRevenue.Name = "txtRevenue" Me.txtRevenue.Size = New System.Drawing.Size(96, 20) Me.txtRevenue.TabIndex = 1 ' 'txtUtilities ' Me.txtUtilities.Location = New System.Drawing.Point(122, 182) Me.txtUtilities.Name = "txtUtilities" Me.txtUtilities.Size = New System.Drawing.Size(96, 20) Me.txtUtilities.TabIndex = 4 ' 'txtProfit ' Me.txtProfit.Location = New System.Drawing.Point(122, 295) Me.txtProfit.Name = "txtProfit" Me.txtProfit.ReadOnly = True Me.txtProfit.Size = New System.Drawing.Size(96, 20) Me.txtProfit.TabIndex = 7 ' 'txtLoss ' Me.txtLoss.Location = New System.Drawing.Point(122, 321) Me.txtLoss.Name = "txtLoss" Me.txtLoss.ReadOnly = True Me.txtLoss.Size = New System.Drawing.Size(96, 20) Me.txtLoss.TabIndex = 23 ' 'txtEP4 ' Me.txtEP4.Location = New System.Drawing.Point(286, 207) Me.txtEP4.Name = "txtEP4" Me.txtEP4.ReadOnly = True Me.txtEP4.Size = New System.Drawing.Size(96, 20) Me.txtEP4.TabIndex = 24 ' 'txtOther ' Me.txtOther.Location = New System.Drawing.Point(122, 230) Me.txtOther.Name = "txtOther" Me.txtOther.Size = New System.Drawing.Size(96, 20) Me.txtOther.TabIndex = 6 ' 'txtTotalExpense ' Me.txtTotalExpense.Location = New System.Drawing.Point(122, 251) Me.txtTotalExpense.Name = "txtTotalExpense" Me.txtTotalExpense.ReadOnly = True Me.txtTotalExpense.Size = New System.Drawing.Size(96, 20) Me.txtTotalExpense.TabIndex = 11 ' 'txtEP5 ' Me.txtEP5.Location = New System.Drawing.Point(286, 233) Me.txtEP5.Name = "txtEP5" Me.txtEP5.ReadOnly = True Me.txtEP5.Size = New System.Drawing.Size(96, 20) Me.txtEP5.TabIndex = 27 ' 'btnClear ' Me.btnClear.Location = New System.Drawing.Point(286, 26) Me.btnClear.Name = "btnClear" Me.btnClear.Size = New System.Drawing.Size(96, 23) Me.btnClear.TabIndex = 28 Me.btnClear.Text = "C&lear" Me.btnClear.UseVisualStyleBackColor = True ' 'Form1 ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(428, 393) Me.Controls.Add(Me.btnClear) Me.Controls.Add(Me.txtEP5) Me.Controls.Add(Me.txtTotalExpense) Me.Controls.Add(Me.txtOther) Me.Controls.Add(Me.txtEP4) Me.Controls.Add(Me.txtLoss) Me.Controls.Add(Me.txtProfit) Me.Controls.Add(Me.txtUtilities) Me.Controls.Add(Me.txtRevenue) Me.Controls.Add(Me.txtPayroll) Me.Controls.Add(Me.txtRent) Me.Controls.Add(Me.txtSupplies) Me.Controls.Add(Me.txtEP3) Me.Controls.Add(Me.txtEP2) Me.Controls.Add(Me.txtEP1) Me.Controls.Add(Me.TextBox1) Me.Controls.Add(Me.btnExit) Me.Controls.Add(Me.btnCalculate) Me.Controls.Add(Me.Label11) Me.Controls.Add(Me.Label10) Me.Controls.Add(Me.Label9) Me.Controls.Add(Me.Label8) Me.Controls.Add(Me.Label7) Me.Controls.Add(Me.Label6) Me.Controls.Add(Me.Label5) Me.Controls.Add(Me.Label4) Me.Controls.Add(Me.Label3) Me.Controls.Add(Me.Label2) Me.Controls.Add(Me.Label1) Me.Name = "Form1" Me.Text = "Profit Loss Calculater" Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents Label2 As System.Windows.Forms.Label Friend WithEvents Label3 As System.Windows.Forms.Label Friend WithEvents Label4 As System.Windows.Forms.Label Friend WithEvents Label5 As System.Windows.Forms.Label Friend WithEvents Label6 As System.Windows.Forms.Label Friend WithEvents Label7 As System.Windows.Forms.Label Friend WithEvents Label8 As System.Windows.Forms.Label Friend WithEvents Label9 As System.Windows.Forms.Label Friend WithEvents Label10 As System.Windows.Forms.Label Friend WithEvents Label11 As System.Windows.Forms.Label Friend WithEvents btnCalculate As System.Windows.Forms.Button Friend WithEvents btnExit As System.Windows.Forms.Button Friend WithEvents TextBox1 As System.Windows.Forms.TextBox Friend WithEvents txtEP1 As System.Windows.Forms.TextBox Friend WithEvents txtEP2 As System.Windows.Forms.TextBox Friend WithEvents txtEP3 As System.Windows.Forms.TextBox Friend WithEvents txtSupplies As System.Windows.Forms.TextBox Friend WithEvents txtRent As System.Windows.Forms.TextBox Friend WithEvents txtPayroll As System.Windows.Forms.TextBox Friend WithEvents txtRevenue As System.Windows.Forms.TextBox Friend WithEvents txtUtilities As System.Windows.Forms.TextBox Friend WithEvents txtProfit As System.Windows.Forms.TextBox Friend WithEvents txtLoss As System.Windows.Forms.TextBox Friend WithEvents txtEP4 As System.Windows.Forms.TextBox Friend WithEvents txtOther As System.Windows.Forms.TextBox Friend WithEvents txtTotalExpense As System.Windows.Forms.TextBox Friend WithEvents txtEP5 As System.Windows.Forms.TextBox Friend WithEvents btnClear As System.Windows.Forms.Button End Class
hhaslam11/Visual-Basic-Projects
Profit and Loss/Profit and Loss/Form1.Designer.vb
Visual Basic
mit
13,770
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 estudyType As SolidEdgePart.FEAStudyTypeEnum_Auto Dim eMeshType As SolidEdgePart.FEAMeshTypeEnum_Auto Dim dThickness As Double = 0 Dim dwInputOptions As UInteger = 0 Dim ulNumModes As ULong = 7 Dim dFreqlow As Double = 0 Dim dFreqHigh As Double = 1.0 Dim cmdLineOpts As String = "" Dim nastranKeywordOpts As String = "" Dim dwResultoptions As UInteger = 0 'Thermal Options Dim dConvectionExp As Double = 0 Dim dEnclosureAmbientEle As Double = 0 Dim dwThrmlOptions As UInteger = 0 Try OleMessageFilter.Register() objApplication = Marshal.GetActiveObject("SolidEdge.Application") objPartDocument = objApplication.ActiveDocument objStudyOwner = objPartDocument.StudyOwner 'Add Thermal Study estudyType = SolidEdgePart.FEAStudyTypeEnum_Auto.eStudyTypeSSHT_Auto eMeshType = SolidEdgePart.FEAMeshTypeEnum_Auto.eMeshTypeTetrahedral_Auto objStudyOwner.AddThermalStudy(estudyType, eMeshType, dThickness, dwInputOptions, ulNumModes, dFreqlow, dFreqHigh, cmdLineOpts, nastranKeywordOpts, dwResultoptions, dwThrmlOptions, dEnclosureAmbientEle, dConvectionExp, objStudy) Catch ex As Exception Console.WriteLine(ex.Message) Finally OleMessageFilter.Revoke() End Try End Sub End Module
SolidEdgeCommunity/docs
docfx_project/snippets/SolidEdgePart.StudyOwner.AddThermalStudy.vb
Visual Basic
mit
2,330
Sub MSD_3() Dim track As Double Dim row As Double Dim frame As Double 'frames = # of frames per track frames = Worksheets("Zwischenwerte").Cells(5, 8).Value 'tracks = # of tracks tracks = Worksheets("Zwischenwerte").Cells(3, 8).Value Worksheets("Zwischenwerte_3").Cells.Delete For track = 1 To tracks For frame = 1 To frames 'calculate rownumbers for x and y @ timepoint/frame t0 (termed rownumt0) rownumt0 = frames * (track - 1) + 1 + 1 'calculate rownumber for x and y @ a given timepoint/frame t (termed rownumt) rownumt = frames * (track - 1) + frame + 1 'get values of x and y @ t0 and t x0 = Worksheets("MSD_3").Cells(rownumt0, 2).Value xt = Worksheets("MSD_3").Cells(rownumt, 2).Value y0 = Worksheets("MSD_3").Cells(rownumt0, 3).Value yt = Worksheets("MSD_3").Cells(rownumt, 3).Value 'calculate (xt-x0)^2 and (yt-y0)^2 Worksheets("Zwischenwerte_3").Cells(rownumt, 2) = (xt - x0) ^ 2 Worksheets("Zwischenwerte_3").Cells(rownumt, 3) = (yt - y0) ^ 2 'add column labels and time Worksheets("Zwischenwerte_3").Cells(1, 1) = "t" Worksheets("Zwischenwerte_3").Cells(1, 2) = "x^2 [µm^2]" Worksheets("Zwischenwerte_3").Cells(1, 3) = "y^2 [µm^2]" Worksheets("Zwischenwerte_3").Cells(1, 4) = "x^2 + y^2" Worksheets("Zwischenwerte_3").Cells(1, 5) = "MSD [µm^2]" Worksheets("Zwischenwerte_3").Cells(rownumt, 1) = Worksheets("MSD_3").Cells(rownumt, 1).Value 'calculate sum of (xt-x0)^2 and (yt-y0)^2 @ timepoint t Worksheets("Zwischenwerte_3").Cells(rownumt, 4) = (xt - x0) ^ 2 + (yt - y0) ^ 2 'calculate MSD for given cell @ given timepoint Sum = WorksheetFunction.Sum(Range(Worksheets("Zwischenwerte_3").Cells(frames * (track - 1) + 1 + 1, 4), Worksheets("Zwischenwerte_3").Cells(rownumt, 4))) MSD = Sum / frame Worksheets("Zwischenwerte_3").Cells(rownumt, 5) = MSD Next frame Next track 'sort calculated MSD by time For frame = 1 To frames Worksheets("Zwischenwerte_3").Cells(1, frame + 6) = frame For track = 1 To tracks Worksheets("Zwischenwerte_3").Cells(track + 1, frame + 6) = Worksheets("Zwischenwerte_3").Cells(frames * (track - 1) + frame - 1 + 2, 5) Next track Next frame For frame = 1 To frames 'calculate average and sd of MSD at each timepoint mean = WorksheetFunction.Average(Range(Worksheets("Zwischenwerte_3").Cells(2, frame + 6), Worksheets("Zwischenwerte_3").Cells(tracks + 1, frame + 6))) sd = WorksheetFunction.StDev(Range(Worksheets("Zwischenwerte_3").Cells(2, frame + 6), Worksheets("Zwischenwerte_3").Cells(tracks + 1, frame + 6))) 'round mean mean_r = Round(mean, 3) 'calculate and round S.E.M. sem = sd / (tracks ^ (1 / 2)) sem_r = Round(sem, 3) 'add time and data to MSD worksheet timeint = Worksheets("Zwischenwerte").Cells(4, 8) Worksheets("MSD_3").Cells(frame + 1, 7) = timeint * (frame - 1) Worksheets("MSD_3").Cells(frame + 1, 8) = mean_r Worksheets("MSD_3").Cells(frame + 1, 9) = sem_r 'add column labels to MSD worksheet Worksheets("MSD_3").Cells(1, 7) = "t [ ]" Worksheets("MSD_3").Cells(1, 8) = "MSD" Worksheets("MSD_3").Cells(1, 9) = "S.E.M." Next frame End Sub
ChristofLitschko/Dicty-Tracking
source-code/MSD-Calculation/MSD_3.vb
Visual Basic
mit
3,295
Option Strict Off Option Explicit On Imports VB = Microsoft.VisualBasic Friend Class frmZaznamy Inherits System.Windows.Forms.Form Dim rec As New ADODB.Recordset Dim PomCol As New Collection 'Pomocná kolekce jednotlivých zkoušení Private IsInitializing As Boolean Public Sub New() MyBase.New() IsInitializing = True InitializeComponent() IsInitializing = False End Sub Private Sub frmZaznamy_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load Dim I As Short 'Naplnìní comboboxù z databáze rec.Open("SELECT DISTINCT * FROM ZKOUSENI_HLAVICKY ORDER BY HLAVICKA_ID DESC", SConn, ADODB.CursorTypeEnum.adOpenStatic, , ADODB.CommandTypeEnum.adCmdText) If rec.RecordCount > 0 Then rec.MoveFirst() For I = 1 To rec.RecordCount If (Not IsDBNull(rec.Fields("HLAVICKA_ID").Value) And Not IsDBNull(rec.Fields("DATUM").Value) And Not IsDBNull(rec.Fields("CAS_OD").Value) And Not IsDBNull(rec.Fields("CAS_DO").Value) And Not IsDBNull(rec.Fields("LEKCE_OD").Value) And Not IsDBNull(rec.Fields("LEKCE_DO").Value)) Then Hlavicka.Items.Add(rec.Fields("HLAVICKA_ID").Value & ". " & rec.Fields("DATUM").Value & ", " & VB.Left(rec.Fields("CAS_OD").Value, 5) & " - " & VB.Left(rec.Fields("CAS_DO").Value, 5) & ", " & rec.Fields("LEKCE_OD").Value & ".-" & rec.Fields("LEKCE_DO").Value & ".lekce ") PomCol.Add(rec.Fields("HLAVICKA_ID").Value) End If rec.MoveNext() Next I Hlavicka.SelectedIndex = 0 rec.Close() Else rec.Close() End If End Sub 'UPGRADE_WARNING: Event Hlavicka.SelectedIndexChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"' Private Sub Hlavicka_SelectedIndexChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Hlavicka.SelectedIndexChanged If Me.IsInitializing = True Then Exit Sub Else NaplnRadky() End If End Sub 'UPGRADE_WARNING: Event Chybne.CheckedChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"' Private Sub Chybne_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Chybne.CheckedChanged If Me.IsInitializing = True Then Exit Sub Else If eventSender.Checked Then NaplnRadky() End If End If End Sub 'UPGRADE_WARNING: Event Vse.CheckedChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"' Private Sub Vse_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Vse.CheckedChanged If Me.IsInitializing = True Then Exit Sub Else If eventSender.Checked Then NaplnRadky() End If End If End Sub Private Sub Vymazat_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Vymazat.Click Dim Odpoved As String Dim I As Short For I = 1 To PomCol.Count() PomCol.Remove(1) Next Odpoved = CStr(MsgBox("Opravdu chcete vymazat všechny záznamy o zkoušení?!", MsgBoxStyle.Critical + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Pozor!")) If Odpoved = CStr(MsgBoxResult.Yes) Then SConn.Execute("DROP TABLE ZKOUSENI_HLAVICKY") SConn.Execute("DROP TABLE ZKOUSENI_RADKY") SConn.Execute("CREATE TABLE ZKOUSENI_HLAVICKY (HLAVICKA_ID counter, DATUM varchar(10) NULL, CAS_OD varchar(8) NULL, CAS_DO varchar (8) NULL, LEKCE_OD integer NULL, LEKCE_DO integer NULL, SMER varchar(255), CO varchar(255) NULL, JAK varchar(255) NULL, UZIVATEL varchar(255) NULL, POZNAMKA memo NULL)") SConn.Execute("CREATE TABLE ZKOUSENI_RADKY (RADEK_ID counter, HLAVICKA_ID single, VAZBA_ID single, ODPOVED varchar(255) NULL, VYSLEDEK integer NULL, POZNAMKA memo NULL)") Me.Close() End If End Sub Private Sub Zrusit_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Zrusit.Click Dim I As Short For I = 1 To PomCol.Count() PomCol.Remove(1) Next Me.Close() End Sub Public Sub NaplnRadky() Dim I As Short Dim r As New ADODB.Recordset Radky.Items.Clear() 'UPGRADE_WARNING: Couldn't resolve default property of object PomCol.Item(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' r.Open("SELECT DISTINCT * FROM ZKOUSENI_HLAVICKY WHERE ZKOUSENI_HLAVICKY.HLAVICKA_ID = " & PomCol.Item((Hlavicka.SelectedIndex) + 1), SConn, ADODB.CursorTypeEnum.adOpenStatic, , ADODB.CommandTypeEnum.adCmdText) 'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"' If Not IsDbNull(r.Fields("SMER").Value) Then Smer.Text = r.Fields("SMER").Value 'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"' If Not IsDbNull(r.Fields("CO").Value) Then Co.Text = r.Fields("CO").Value 'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"' If Not IsDbNull(r.Fields("JAK").Value) Then Jak.Text = r.Fields("JAK").Value 'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"' If Not IsDbNull(r.Fields("POZNAMKA").Value) Then Hodnoceni.Text = CStr(r.Fields("POZNAMKA").Value) & " úspìšnost" r.Close() 'UPGRADE_WARNING: Couldn't resolve default property of object PomCol.Item(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' r.Open("SELECT * FROM VAZBY, ZKOUSENI_RADKY, ZKOUSENI_HLAVICKY WHERE ZKOUSENI_RADKY.HLAVICKA_ID = " & PomCol.Item((Hlavicka.SelectedIndex) + 1) & " AND ZKOUSENI_RADKY.VAZBA_ID = VAZBY.VAZBA_ID AND ZKOUSENI_HLAVICKY.HLAVICKA_ID = ZKOUSENI_RADKY.HLAVICKA_ID ORDER BY ZKOUSENI_RADKY.RADEK_ID", SConn, ADODB.CursorTypeEnum.adOpenStatic, , ADODB.CommandTypeEnum.adCmdText) For I = 0 To r.RecordCount - 1 If r.Fields("SMER").Value = "z èeštiny" Then If r.Fields("VYSLEDEK").Value = Utils.SPRAVNE And Vse.Checked Then Radky.Items.Add(CStr(I + 1) & ". " & r.Fields("EKVIVALENT").Value & " = " & r.Fields("CESKY").Value) ElseIf r.Fields("VYSLEDEK").Value <> Utils.SPRAVNE Then Radky.Items.Add(CStr(I + 1) & ". " & r.Fields("EKVIVALENT").Value & " = " & r.Fields("ODPOVED").Value & " (" & r.Fields("CESKY").Value & ")") End If Else If r.Fields("VYSLEDEK").Value = Utils.SPRAVNE And Vse.Checked Then Radky.Items.Add(CStr(I + 1) & ". " & r.Fields("CESKY").Value & " = " & r.Fields("EKVIVALENT").Value) ElseIf r.Fields("VYSLEDEK").Value <> Utils.SPRAVNE Then Radky.Items.Add(CStr(I + 1) & ". " & r.Fields("CESKY").Value & " = " & r.Fields("ODPOVED").Value & " (" & r.Fields("EKVIVALENT").Value & ")") End If End If r.MoveNext() Next I Zkouseni.Text = r.RecordCount & " vazeb" r.Close() End Sub End Class
KamilSvoboda/Slovnicek
Zaznamy.vb
Visual Basic
apache-2.0
7,846
' 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.NetCore.Analyzers.Runtime Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime ''' <summary> ''' CA1820: Test for empty strings using string length ''' </summary> <ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]> Public NotInheritable Class BasicTestForEmptyStringsUsingStringLengthFixer Inherits TestForEmptyStringsUsingStringLengthFixer Protected Overrides Function GetBinaryExpression(node As SyntaxNode) As SyntaxNode Dim argumentSyntax = TryCast(node, ArgumentSyntax) Return If(argumentSyntax IsNot Nothing, argumentSyntax.GetExpression(), node) End Function Protected Overrides Function IsEqualsOperator(node As SyntaxNode) As Boolean Return node.IsKind(SyntaxKind.EqualsExpression) End Function Protected Overrides Function IsNotEqualsOperator(node As SyntaxNode) As Boolean Return node.IsKind(SyntaxKind.NotEqualsExpression) End Function Protected Overrides Function GetLeftOperand(binaryExpressionSyntax As SyntaxNode) As SyntaxNode Return DirectCast(binaryExpressionSyntax, BinaryExpressionSyntax).Left End Function Protected Overrides Function GetRightOperand(binaryExpressionSyntax As SyntaxNode) As SyntaxNode Return DirectCast(binaryExpressionSyntax, BinaryExpressionSyntax).Right End Function End Class End Namespace
pakdev/roslyn-analyzers
src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicTestForEmptyStringsUsingStringLength.Fixer.vb
Visual Basic
apache-2.0
1,808
' 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.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.DebuggerIntelliSense Public Class VisualBasicDebuggerIntellisenseTests <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function QueryVariables() As Task Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>$$</Document> <Document>Module Program Sub Main(args As String()) Dim bar = From x In "asdf" Where [|x = "d"|] Select x Dim z = 4 End Sub End Module</Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, False) Await VerifyCompletionAndDotAfter("x", state) End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function EnteringMethod() As Task Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>$$</Document> <Document>Module Program [|Sub Main(args As String())|] Dim z = 4 End Sub End Module</Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, False) Await VerifyCompletionAndDotAfter("args", state) Await VerifyCompletionAndDotAfter("z", state) End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function ExitingMethod() As Task Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>$$</Document> <Document>Module Program Sub Main(args As String()) Dim z = 4 [|End Sub|] End Module</Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, False) Await VerifyCompletionAndDotAfter("args", state) Await VerifyCompletionAndDotAfter("z", state) End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function SingleLineLambda() As Task Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>$$</Document> <Document>Module Program Sub Main(args As String()) Dim z = [|Function(x) x + 5|] z(3) End Sub End Module</Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, False) Await VerifyCompletionAndDotAfter("x", state) End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function MultiLineLambda() As Task Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>$$</Document> <Document>Module Program Sub Main(args As String()) Dim z = [|Function(x)|] Return x + 5 End Function z(3) End Sub End Module</Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, False) Await VerifyCompletionAndDotAfter("x", state) End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function LocalVariables() As Task Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>$$</Document> <Document>Module Program Sub Main(args As String()) Dim bar as String = "boo" [|Dim y = 3|] Dim z = 4 End Sub End Module</Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, False) Await VerifyCompletionAndDotAfter("bar", state) Await VerifyCompletionAndDotAfter("y", state) Await VerifyCompletionAndDotAfter("z", state) End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function CompletionAfterReturn() As Task Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>$$</Document> <Document>Module Program Sub Main(args As String()) Dim bar as String = "boo" [|Dim y = 3|] Dim z = 4 End Sub End Module</Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, True) Await VerifyCompletionAndDotAfter("bar", state) Await VerifyCompletionAndDotAfter("y", state) Await VerifyCompletionAndDotAfter("z", state) state.SendReturn() Await VerifyCompletionAndDotAfter("y", state) End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Sub TypeALineTenTimes() Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>$$</Document> <Document>Module Program Sub Main(args As String()) Dim xx as String = "boo" [|Dim y = 3|] Dim z = 4 End Sub End Module</Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, True) For xx = 0 To 10 state.SendTypeChars("z") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("z") state.SendTab() state.SendTypeChars(".") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() state.SendReturn() Next End Using End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Sub SignatureHelpInParameterizedConstructor() Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>$$</Document> <Document>Module Program Sub Main(args As String()) Dim xx as String = "boo" [|Dim y = 3|] Dim z = 4 End Sub End Module</Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, False) state.SendTypeChars("new String(") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSignatureHelpSession() End Using End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Sub SignatureHelpInMethodCall() Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>$$</Document> <Document>Module Program Sub Main(args As String()) Dim xx as String = "boo" [|Dim y = 3|] Dim z = 4 End Sub End Module</Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, False) state.SendTypeChars("Main(") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSignatureHelpSession() End Using End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Sub SignatureHelpInGenericMethod() Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>$$</Document> <Document>Module Program Sub Self(Of T)(goo as T) Return goo End Sub Sub Main(args As String()) Dim xx as String = "boo" [|Dim y = 3|] Dim z = 4 End Sub End Module</Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, False) state.SendTypeChars("Self(Of Integer)(") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSignatureHelpSession() End Using End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Sub CompletionInExpression() Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>$$</Document> <Document>Module Program Sub Self(Of T)(goo as T) Return goo End Sub Sub Main(args As String()) Dim xx as String = "boo" [|Dim y = 3|] Dim z = 4 End Sub End Module</Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, False) state.SendTypeChars("new List(Of String) From { a") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() End Using End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Sub CompletionShowTypesFromProjectReference() Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>ReferencedProject</ProjectReference> <Document>$$</Document> <Document>Module Program Sub Main(args As String()) Dim xx as String = "boo" [|Dim y = 3|] Dim z = 4 End Sub End Module</Document> </Project> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ReferencedProject"> <Document> Public Class AClass Sub New() End Sub End Class </Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, False) state.SendTypeChars("new AClass") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("AClass") End Using End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Sub CompletionForGenericType() Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>$$</Document> <Document>Module Program Sub Self(Of T)(goo as T) Return goo End Sub Sub Main(args As String()) Dim xx as String = "boo" [|Dim y = 3|] Dim z = 4 End Sub End Module</Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, False) state.SendTypeChars("Self(Of ") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() End Using End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Sub LocalsInForBlock() Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>$$</Document> <Document>Module Program Sub Main(args As String()) Dim xx as String = "boo" Dim y = 3 Dim z = 4 For xx As Integer = 1 To 10 [|Dim q = xx + 2|] Next End Sub End Module</Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, False) Await VerifyCompletionAndDotAfter("q", state) Await VerifyCompletionAndDotAfter("xx", state) Await VerifyCompletionAndDotAfter("z", state) End Using End Sub Private Async Function VerifyCompletionAndDotAfter(item As String, state As TestState) As Task If state.IsImmediateWindow Then state.SendTypeChars("?") End If state.SendTypeChars(item) Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(item) state.SendTab() state.SendTypeChars(".") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() For i As Integer = 0 To item.Length state.SendBackspace() Next End Function <WorkItem(1044441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1044441")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Sub StoppedOnEndSub() Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>$$</Document> <Document>Module Program Sub Main(o as Integer) [|End Sub|] End Module</Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, False) Await VerifyCompletionAndDotAfter("o", state) End Using End Sub <WorkItem(1044441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1044441")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Sub StoppedOnEndProperty() Dim text = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document>$$</Document> <Document>Class C Public Property x As Integer Get Return 0 End Get Set(value As Integer) [|End Set|] End Property End Class</Document> </Project> </Workspace> Using state = TestState.CreateVisualBasicTestState(text, False) Await VerifyCompletionAndDotAfter("value", state) End Using End Sub End Class End Namespace
Hosch250/roslyn
src/VisualStudio/Core/Test/DebuggerIntelliSense/VisualBasicDebuggerIntellisenseTests.vb
Visual Basic
apache-2.0
16,839
Imports bv.winclient.BasePanel Imports bv.common.db Imports EIDSS.model.Resources Imports bv.common.Resources Public Class HumanCaseDeduplicationDetail Inherits BaseDetailForm Dim HumanCaseDeduplicationDbService As HumanCaseDeduplication_DB #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call HumanCaseDeduplicationDbService = New HumanCaseDeduplication_DB DbService = HumanCaseDeduplicationDbService AuditObject = New Core.EIDSSAuditObject(EIDSSAuditObject.daoHumanCaseDeduplication, AuditTable.tlbCase) 'Me.PermissionObject = eidss.model.Enums.EIDSSPermissionObject.HumanCaseDeduplication Me.m_RelatedLists = New String() {"HumanCaseDeduplicationListItem", "HumanCaseListItem"} End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub Friend WithEvents pnHCDeduplication As DevExpress.XtraEditors.PanelControl Friend WithEvents tcSuperseded As DevExpress.XtraTab.XtraTabControl Friend WithEvents tpNotificationSuperseded As DevExpress.XtraTab.XtraTabPage Friend WithEvents tcSurvivor As DevExpress.XtraTab.XtraTabControl Friend WithEvents tpNotificationSurvivor As DevExpress.XtraTab.XtraTabPage Friend WithEvents gbSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents gbSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents cbSuperseded As DevExpress.XtraEditors.ComboBoxEdit Friend WithEvents cbSurvivor As DevExpress.XtraEditors.ComboBoxEdit Friend WithEvents tbCaseIDSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents tbCaseIDSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents rbCaseIDSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents pnDemographicSurvivor As DevExpress.XtraEditors.GroupControl Friend WithEvents pnDemographicSuperseded As DevExpress.XtraEditors.GroupControl Friend WithEvents lblPatientNameSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents rbLastNameSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents tbLastNameSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents tbFirstNameSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents rbFirstNameSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents tbSecondNameSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents rbSecondNameSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblPatientNameSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents tbSecondNameSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents rbLastNameSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents rbSecondNameSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents tbLastNameSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents tbFirstNameSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents rbFirstNameSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents tbSexSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents rbDOBSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents rbSexSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents rbAgeSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents tbDOBSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents tbAgeSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents tbAgeUnitsSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents tbAgeUnitsSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents tbSexSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents rbDOBSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents rbSexSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents rbAgeSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents tbDOBSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents tbAgeSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents gbPatientInfoSurvivor As DevExpress.XtraEditors.GroupControl Friend WithEvents rbGeoLocationHomeIDSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents tbRegionHomeSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents lblRegionHomeSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents lblRayonHomeSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents tbRayonHomeSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents lblStreetHomeSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents tbStreetHomeSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents lblSettlementHomeSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents tbSettlementHomeSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents lblPostalCodeHomeSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents tbPostalCodeHomeSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents lblHBAHomeSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents tbHouseHomeSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents tbAptmHomeSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents tbBuildingHomeSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents gbPatientInfoSuperseded As DevExpress.XtraEditors.GroupControl Friend WithEvents tbAptmHomeSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents tbBuildingHomeSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents lblHBAHomeSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents tbHouseHomeSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents lblPostalCodeHomeSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents tbPostalCodeHomeSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents lblStreetHomeSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents tbStreetHomeSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents lblSettlementHomeSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents tbSettlementHomeSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents lblRayonHomeSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents tbRayonHomeSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents lblRegionHomeSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents tbRegionHomeSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents rbGeoLocationHomeIDSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents tbEmployerNameSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents rbPhoneNumberSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents rbEmployerNameSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents rbNationalitySurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents tbPhoneNumberSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents tbNationalitySurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents tbGeoLocationEmployerSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents rbGeoLocationEmployerSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents tbGeoLocationEmployerSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents rbGeoLocationEmployerSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents tbEmployerNameSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents rbPhoneNumberSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents rbEmployerNameSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents rbNationalitySuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents tbPhoneNumberSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents tbNationalitySuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents pnClinicalSurvivor As DevExpress.XtraEditors.GroupControl Friend WithEvents pnCaseIDSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents rbCaseIDSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents pnCaseIDSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents pnSecondNameSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents pnDOBSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents pnLastNameSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents pnFirstNameSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents pnLastNameSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents pnAgeSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents pnSexSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents pnFirstNameSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents pnSecondNameSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents pnDOBSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents pnAgeSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents pnSexSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents pnEmployerNameSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents pnGeoLocationEmployerSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents pnGeoLocationHomeIDSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents pnPhoneNumberSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents pnNationalitySuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents pnGeoLocationHomeIDSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents pnPhoneNumberSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents pnNationalitySurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents pnEmployerNameSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents pnGeoLocationEmployerSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents lblLastNameSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents lblFirstNameSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents lblSecondNameSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents lblDOBSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents lblAgeSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents lblSexSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents lblPhoneNumberSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents lblNationalitySurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents lblEmployerNameSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents lblGeoLocationEmployerSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents lblLastNameSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents lblFirstNameSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents lblCaseIDSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents lblCaseIDSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents lblSecondNameSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents lblDOBSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents lblAgeSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents lblSexSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents lblPhoneNumberSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents lblNationalitySuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents lblEmployerNameSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents lblGeoLocationEmployerSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents lblGeoLocationHomeIDSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents lblGeoLocationHomeIDSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents pnDiagnosisSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents rbDiagnosisSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblDiagnosisSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents tbDiagnosisSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents tbDiagnosisDateSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents pnDiagnosisDateSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents rbDiagnosisDateSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblDiagnosisDateSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents tbDiagnosisSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents pnDiagnosisSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents rbDiagnosisSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblDiagnosisSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents tbDiagnosisDateSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents pnDiagnosisDateSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents rbDiagnosisDateSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblDiagnosisDateSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents pnOnsetDateSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents rbOnsetDateSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblOnsetDateSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents tbOnsetDateSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents tbFinalStateSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents pnFinalStateSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents rbFinalStateSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblFinalStateSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents tbChangedDiagnosisSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents pnChangedDiagnosisSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents rbChangedDiagnosisSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblChangedDiagnosisSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents tbChangedDiagnosisDateSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents pnChangedDiagnosisDateSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents rbChangedDiagnosisDateSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblChangedDiagnosisDateSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents lblPatientLocationSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents tbPatientLocationStatusSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents pnPatientLocationStatusSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents rbPatientLocationStatusSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblPatientLocationStatusSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents tbPatientLocationNameSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents pnPatientLocationNameSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents rbPatientLocationNameSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblPatientLocationNameSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents tbAddCaseInfoSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents pnAddCaseInfoSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents rbAddCaseInfoSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblAddCaseInfoSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents pnClinicalSuperseded As DevExpress.XtraEditors.GroupControl Friend WithEvents tbAddCaseInfoSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents pnAddCaseInfoSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents rbAddCaseInfoSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblAddCaseInfoSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents tbPatientLocationNameSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents pnPatientLocationNameSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents rbPatientLocationNameSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblPatientLocationNameSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents tbPatientLocationStatusSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents pnPatientLocationStatusSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents rbPatientLocationStatusSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblPatientLocationStatusSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents lblPatientLocationSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents tbChangedDiagnosisDateSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents pnChangedDiagnosisDateSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents rbChangedDiagnosisDateSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblChangedDiagnosisDateSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents tbChangedDiagnosisSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents pnChangedDiagnosisSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents rbChangedDiagnosisSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblChangedDiagnosisSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents tbFinalStateSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents pnFinalStateSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents rbFinalStateSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblFinalStateSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents tbOnsetDateSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents pnOnsetDateSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents rbOnsetDateSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblOnsetDateSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents btnAllSurvivor As DevExpress.XtraEditors.SimpleButton Friend WithEvents btnAllSuperseded As DevExpress.XtraEditors.SimpleButton Friend WithEvents tbLocalIDSurvivor As DevExpress.XtraEditors.TextEdit Friend WithEvents pnLocalIDSurvivor As DevExpress.XtraEditors.PanelControl Friend WithEvents rbLocalIDSurvivor As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblLocalIDSurvivor As DevExpress.XtraEditors.LabelControl Friend WithEvents tbLocalIDSuperseded As DevExpress.XtraEditors.TextEdit Friend WithEvents pnLocalIDSuperseded As DevExpress.XtraEditors.PanelControl Friend WithEvents rbLocalIDSuperseded As DevExpress.XtraEditors.CheckEdit Friend WithEvents lblLocalIDSuperseded As DevExpress.XtraEditors.LabelControl Friend WithEvents tpSamplesSuperseded As DevExpress.XtraTab.XtraTabPage Friend WithEvents tpSamplesSurvivor As DevExpress.XtraTab.XtraTabPage Friend WithEvents gcSamplesSurvivor As DevExpress.XtraGrid.GridControl Friend WithEvents gvSamplesSurvivor As DevExpress.XtraGrid.Views.Grid.GridView Friend WithEvents gcolMaterialIDSurvivor As DevExpress.XtraGrid.Columns.GridColumn Friend WithEvents gcolRowTypeSurvivor As DevExpress.XtraGrid.Columns.GridColumn Friend WithEvents gcolSampleIDSurvivor As DevExpress.XtraGrid.Columns.GridColumn Friend WithEvents gcolCheckedSurvivor As DevExpress.XtraGrid.Columns.GridColumn Friend WithEvents chAddToCaseSurvivor As DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit Friend WithEvents gcolSampleTypeSurvivor As DevExpress.XtraGrid.Columns.GridColumn Friend WithEvents gcolCollectionDateSurvivor As DevExpress.XtraGrid.Columns.GridColumn Friend WithEvents gcSamplesSuperseded As DevExpress.XtraGrid.GridControl Friend WithEvents gvSamplesSuperseded As DevExpress.XtraGrid.Views.Grid.GridView Friend WithEvents gcolMaterialIDSuperseded As DevExpress.XtraGrid.Columns.GridColumn Friend WithEvents gcolRowTypeSuperseded As DevExpress.XtraGrid.Columns.GridColumn Friend WithEvents gcolCheckedSuperseded As DevExpress.XtraGrid.Columns.GridColumn Friend WithEvents chAddToCaseSuperseded As DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit Friend WithEvents gcolSampleIDSuperseded As DevExpress.XtraGrid.Columns.GridColumn Friend WithEvents gcolSampleTypeSuperseded As DevExpress.XtraGrid.Columns.GridColumn Friend WithEvents gcolCollectionDateSuperseded As DevExpress.XtraGrid.Columns.GridColumn Friend WithEvents gcolTestQuantitySuperseded As DevExpress.XtraGrid.Columns.GridColumn Friend WithEvents gcolTestQuantitySurvivor As DevExpress.XtraGrid.Columns.GridColumn Friend WithEvents gcolCanUncheckSurvivor As DevExpress.XtraGrid.Columns.GridColumn Friend WithEvents gcolCanUncheckSuperseded As DevExpress.XtraGrid.Columns.GridColumn Friend WithEvents LabelControl1 As DevExpress.XtraEditors.GroupControl Friend WithEvents LabelControl4 As DevExpress.XtraEditors.GroupControl Friend WithEvents LabelControl3 As DevExpress.XtraEditors.GroupControl Friend WithEvents LabelControl2 As DevExpress.XtraEditors.GroupControl Friend WithEvents LabelControl6 As DevExpress.XtraEditors.GroupControl Friend WithEvents LabelControl5 As DevExpress.XtraEditors.GroupControl Friend WithEvents LabelControl8 As DevExpress.XtraEditors.GroupControl Friend WithEvents LabelControl7 As DevExpress.XtraEditors.GroupControl '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(HumanCaseDeduplicationDetail)) Me.pnHCDeduplication = New DevExpress.XtraEditors.PanelControl Me.gbSurvivor = New DevExpress.XtraEditors.PanelControl Me.btnAllSurvivor = New DevExpress.XtraEditors.SimpleButton Me.cbSurvivor = New DevExpress.XtraEditors.ComboBoxEdit Me.gbSuperseded = New DevExpress.XtraEditors.PanelControl Me.btnAllSuperseded = New DevExpress.XtraEditors.SimpleButton Me.cbSuperseded = New DevExpress.XtraEditors.ComboBoxEdit Me.tcSuperseded = New DevExpress.XtraTab.XtraTabControl Me.tpNotificationSuperseded = New DevExpress.XtraTab.XtraTabPage Me.tbLocalIDSuperseded = New DevExpress.XtraEditors.TextEdit Me.pnLocalIDSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbLocalIDSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblLocalIDSuperseded = New DevExpress.XtraEditors.LabelControl Me.pnClinicalSuperseded = New DevExpress.XtraEditors.GroupControl Me.LabelControl6 = New DevExpress.XtraEditors.GroupControl Me.LabelControl5 = New DevExpress.XtraEditors.GroupControl Me.tbAddCaseInfoSuperseded = New DevExpress.XtraEditors.TextEdit Me.pnAddCaseInfoSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbAddCaseInfoSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblAddCaseInfoSuperseded = New DevExpress.XtraEditors.LabelControl Me.tbPatientLocationNameSuperseded = New DevExpress.XtraEditors.TextEdit Me.pnPatientLocationNameSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbPatientLocationNameSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblPatientLocationNameSuperseded = New DevExpress.XtraEditors.LabelControl Me.tbPatientLocationStatusSuperseded = New DevExpress.XtraEditors.TextEdit Me.pnPatientLocationStatusSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbPatientLocationStatusSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblPatientLocationStatusSuperseded = New DevExpress.XtraEditors.LabelControl Me.lblPatientLocationSuperseded = New DevExpress.XtraEditors.LabelControl Me.tbChangedDiagnosisDateSuperseded = New DevExpress.XtraEditors.TextEdit Me.pnChangedDiagnosisDateSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbChangedDiagnosisDateSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblChangedDiagnosisDateSuperseded = New DevExpress.XtraEditors.LabelControl Me.tbChangedDiagnosisSuperseded = New DevExpress.XtraEditors.TextEdit Me.pnChangedDiagnosisSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbChangedDiagnosisSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblChangedDiagnosisSuperseded = New DevExpress.XtraEditors.LabelControl Me.tbFinalStateSuperseded = New DevExpress.XtraEditors.TextEdit Me.pnFinalStateSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbFinalStateSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblFinalStateSuperseded = New DevExpress.XtraEditors.LabelControl Me.tbOnsetDateSuperseded = New DevExpress.XtraEditors.TextEdit Me.pnOnsetDateSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbOnsetDateSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblOnsetDateSuperseded = New DevExpress.XtraEditors.LabelControl Me.tbDiagnosisDateSuperseded = New DevExpress.XtraEditors.TextEdit Me.pnDiagnosisDateSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbDiagnosisDateSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblDiagnosisDateSuperseded = New DevExpress.XtraEditors.LabelControl Me.tbDiagnosisSuperseded = New DevExpress.XtraEditors.TextEdit Me.pnDiagnosisSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbDiagnosisSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblDiagnosisSuperseded = New DevExpress.XtraEditors.LabelControl Me.pnDemographicSuperseded = New DevExpress.XtraEditors.GroupControl Me.LabelControl4 = New DevExpress.XtraEditors.GroupControl Me.LabelControl1 = New DevExpress.XtraEditors.GroupControl Me.tbGeoLocationEmployerSuperseded = New DevExpress.XtraEditors.TextEdit Me.tbEmployerNameSuperseded = New DevExpress.XtraEditors.TextEdit Me.tbPhoneNumberSuperseded = New DevExpress.XtraEditors.TextEdit Me.tbNationalitySuperseded = New DevExpress.XtraEditors.TextEdit Me.gbPatientInfoSuperseded = New DevExpress.XtraEditors.GroupControl Me.tbAptmHomeSuperseded = New DevExpress.XtraEditors.TextEdit Me.tbBuildingHomeSuperseded = New DevExpress.XtraEditors.TextEdit Me.lblHBAHomeSuperseded = New DevExpress.XtraEditors.LabelControl Me.tbHouseHomeSuperseded = New DevExpress.XtraEditors.TextEdit Me.lblPostalCodeHomeSuperseded = New DevExpress.XtraEditors.LabelControl Me.tbPostalCodeHomeSuperseded = New DevExpress.XtraEditors.TextEdit Me.lblStreetHomeSuperseded = New DevExpress.XtraEditors.LabelControl Me.tbStreetHomeSuperseded = New DevExpress.XtraEditors.TextEdit Me.lblSettlementHomeSuperseded = New DevExpress.XtraEditors.LabelControl Me.tbSettlementHomeSuperseded = New DevExpress.XtraEditors.TextEdit Me.lblRayonHomeSuperseded = New DevExpress.XtraEditors.LabelControl Me.tbRayonHomeSuperseded = New DevExpress.XtraEditors.TextEdit Me.lblRegionHomeSuperseded = New DevExpress.XtraEditors.LabelControl Me.tbRegionHomeSuperseded = New DevExpress.XtraEditors.TextEdit Me.tbAgeUnitsSuperseded = New DevExpress.XtraEditors.TextEdit Me.tbSexSuperseded = New DevExpress.XtraEditors.TextEdit Me.tbDOBSuperseded = New DevExpress.XtraEditors.TextEdit Me.tbAgeSuperseded = New DevExpress.XtraEditors.TextEdit Me.lblPatientNameSuperseded = New DevExpress.XtraEditors.LabelControl Me.tbSecondNameSuperseded = New DevExpress.XtraEditors.TextEdit Me.tbLastNameSuperseded = New DevExpress.XtraEditors.TextEdit Me.tbFirstNameSuperseded = New DevExpress.XtraEditors.TextEdit Me.pnLastNameSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbLastNameSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblLastNameSuperseded = New DevExpress.XtraEditors.LabelControl Me.pnFirstNameSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbFirstNameSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblFirstNameSuperseded = New DevExpress.XtraEditors.LabelControl Me.pnSecondNameSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbSecondNameSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblSecondNameSuperseded = New DevExpress.XtraEditors.LabelControl Me.pnDOBSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbDOBSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblDOBSuperseded = New DevExpress.XtraEditors.LabelControl Me.pnAgeSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbAgeSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblAgeSuperseded = New DevExpress.XtraEditors.LabelControl Me.pnSexSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbSexSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblSexSuperseded = New DevExpress.XtraEditors.LabelControl Me.pnGeoLocationHomeIDSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbGeoLocationHomeIDSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblGeoLocationHomeIDSuperseded = New DevExpress.XtraEditors.LabelControl Me.pnPhoneNumberSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbPhoneNumberSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblPhoneNumberSuperseded = New DevExpress.XtraEditors.LabelControl Me.pnNationalitySuperseded = New DevExpress.XtraEditors.PanelControl Me.rbNationalitySuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblNationalitySuperseded = New DevExpress.XtraEditors.LabelControl Me.pnEmployerNameSuperseded = New DevExpress.XtraEditors.PanelControl Me.lblEmployerNameSuperseded = New DevExpress.XtraEditors.LabelControl Me.rbEmployerNameSuperseded = New DevExpress.XtraEditors.CheckEdit Me.pnGeoLocationEmployerSuperseded = New DevExpress.XtraEditors.PanelControl Me.lblGeoLocationEmployerSuperseded = New DevExpress.XtraEditors.LabelControl Me.rbGeoLocationEmployerSuperseded = New DevExpress.XtraEditors.CheckEdit Me.tbCaseIDSuperseded = New DevExpress.XtraEditors.TextEdit Me.pnCaseIDSuperseded = New DevExpress.XtraEditors.PanelControl Me.rbCaseIDSuperseded = New DevExpress.XtraEditors.CheckEdit Me.lblCaseIDSuperseded = New DevExpress.XtraEditors.LabelControl Me.tpSamplesSuperseded = New DevExpress.XtraTab.XtraTabPage Me.gcSamplesSuperseded = New DevExpress.XtraGrid.GridControl Me.gvSamplesSuperseded = New DevExpress.XtraGrid.Views.Grid.GridView Me.gcolMaterialIDSuperseded = New DevExpress.XtraGrid.Columns.GridColumn Me.gcolRowTypeSuperseded = New DevExpress.XtraGrid.Columns.GridColumn Me.gcolCheckedSuperseded = New DevExpress.XtraGrid.Columns.GridColumn Me.chAddToCaseSuperseded = New DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit Me.gcolSampleIDSuperseded = New DevExpress.XtraGrid.Columns.GridColumn Me.gcolSampleTypeSuperseded = New DevExpress.XtraGrid.Columns.GridColumn Me.gcolCollectionDateSuperseded = New DevExpress.XtraGrid.Columns.GridColumn Me.gcolTestQuantitySuperseded = New DevExpress.XtraGrid.Columns.GridColumn Me.gcolCanUncheckSuperseded = New DevExpress.XtraGrid.Columns.GridColumn Me.tcSurvivor = New DevExpress.XtraTab.XtraTabControl Me.tpNotificationSurvivor = New DevExpress.XtraTab.XtraTabPage Me.tbLocalIDSurvivor = New DevExpress.XtraEditors.TextEdit Me.pnLocalIDSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbLocalIDSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblLocalIDSurvivor = New DevExpress.XtraEditors.LabelControl Me.pnClinicalSurvivor = New DevExpress.XtraEditors.GroupControl Me.LabelControl8 = New DevExpress.XtraEditors.GroupControl Me.LabelControl7 = New DevExpress.XtraEditors.GroupControl Me.tbAddCaseInfoSurvivor = New DevExpress.XtraEditors.TextEdit Me.pnAddCaseInfoSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbAddCaseInfoSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblAddCaseInfoSurvivor = New DevExpress.XtraEditors.LabelControl Me.tbPatientLocationNameSurvivor = New DevExpress.XtraEditors.TextEdit Me.pnPatientLocationNameSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbPatientLocationNameSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblPatientLocationNameSurvivor = New DevExpress.XtraEditors.LabelControl Me.tbPatientLocationStatusSurvivor = New DevExpress.XtraEditors.TextEdit Me.pnPatientLocationStatusSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbPatientLocationStatusSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblPatientLocationStatusSurvivor = New DevExpress.XtraEditors.LabelControl Me.lblPatientLocationSurvivor = New DevExpress.XtraEditors.LabelControl Me.tbChangedDiagnosisDateSurvivor = New DevExpress.XtraEditors.TextEdit Me.pnChangedDiagnosisDateSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbChangedDiagnosisDateSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblChangedDiagnosisDateSurvivor = New DevExpress.XtraEditors.LabelControl Me.tbChangedDiagnosisSurvivor = New DevExpress.XtraEditors.TextEdit Me.pnChangedDiagnosisSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbChangedDiagnosisSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblChangedDiagnosisSurvivor = New DevExpress.XtraEditors.LabelControl Me.tbFinalStateSurvivor = New DevExpress.XtraEditors.TextEdit Me.pnFinalStateSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbFinalStateSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblFinalStateSurvivor = New DevExpress.XtraEditors.LabelControl Me.tbOnsetDateSurvivor = New DevExpress.XtraEditors.TextEdit Me.pnOnsetDateSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbOnsetDateSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblOnsetDateSurvivor = New DevExpress.XtraEditors.LabelControl Me.tbDiagnosisDateSurvivor = New DevExpress.XtraEditors.TextEdit Me.pnDiagnosisDateSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbDiagnosisDateSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblDiagnosisDateSurvivor = New DevExpress.XtraEditors.LabelControl Me.tbDiagnosisSurvivor = New DevExpress.XtraEditors.TextEdit Me.pnDiagnosisSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbDiagnosisSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblDiagnosisSurvivor = New DevExpress.XtraEditors.LabelControl Me.pnDemographicSurvivor = New DevExpress.XtraEditors.GroupControl Me.LabelControl3 = New DevExpress.XtraEditors.GroupControl Me.LabelControl2 = New DevExpress.XtraEditors.GroupControl Me.tbGeoLocationEmployerSurvivor = New DevExpress.XtraEditors.TextEdit Me.tbEmployerNameSurvivor = New DevExpress.XtraEditors.TextEdit Me.tbPhoneNumberSurvivor = New DevExpress.XtraEditors.TextEdit Me.tbNationalitySurvivor = New DevExpress.XtraEditors.TextEdit Me.tbAptmHomeSurvivor = New DevExpress.XtraEditors.TextEdit Me.tbBuildingHomeSurvivor = New DevExpress.XtraEditors.TextEdit Me.lblHBAHomeSurvivor = New DevExpress.XtraEditors.LabelControl Me.tbHouseHomeSurvivor = New DevExpress.XtraEditors.TextEdit Me.lblPostalCodeHomeSurvivor = New DevExpress.XtraEditors.LabelControl Me.tbPostalCodeHomeSurvivor = New DevExpress.XtraEditors.TextEdit Me.lblStreetHomeSurvivor = New DevExpress.XtraEditors.LabelControl Me.tbStreetHomeSurvivor = New DevExpress.XtraEditors.TextEdit Me.lblSettlementHomeSurvivor = New DevExpress.XtraEditors.LabelControl Me.tbSettlementHomeSurvivor = New DevExpress.XtraEditors.TextEdit Me.lblRayonHomeSurvivor = New DevExpress.XtraEditors.LabelControl Me.tbRayonHomeSurvivor = New DevExpress.XtraEditors.TextEdit Me.lblRegionHomeSurvivor = New DevExpress.XtraEditors.LabelControl Me.tbRegionHomeSurvivor = New DevExpress.XtraEditors.TextEdit Me.gbPatientInfoSurvivor = New DevExpress.XtraEditors.GroupControl Me.tbAgeUnitsSurvivor = New DevExpress.XtraEditors.TextEdit Me.tbSexSurvivor = New DevExpress.XtraEditors.TextEdit Me.tbDOBSurvivor = New DevExpress.XtraEditors.TextEdit Me.tbAgeSurvivor = New DevExpress.XtraEditors.TextEdit Me.lblPatientNameSurvivor = New DevExpress.XtraEditors.LabelControl Me.tbSecondNameSurvivor = New DevExpress.XtraEditors.TextEdit Me.tbLastNameSurvivor = New DevExpress.XtraEditors.TextEdit Me.tbFirstNameSurvivor = New DevExpress.XtraEditors.TextEdit Me.pnLastNameSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbLastNameSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblLastNameSurvivor = New DevExpress.XtraEditors.LabelControl Me.pnFirstNameSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbFirstNameSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblFirstNameSurvivor = New DevExpress.XtraEditors.LabelControl Me.pnSecondNameSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbSecondNameSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblSecondNameSurvivor = New DevExpress.XtraEditors.LabelControl Me.pnDOBSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbDOBSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblDOBSurvivor = New DevExpress.XtraEditors.LabelControl Me.pnAgeSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbAgeSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblAgeSurvivor = New DevExpress.XtraEditors.LabelControl Me.pnSexSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbSexSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblSexSurvivor = New DevExpress.XtraEditors.LabelControl Me.pnPhoneNumberSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbPhoneNumberSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblPhoneNumberSurvivor = New DevExpress.XtraEditors.LabelControl Me.pnNationalitySurvivor = New DevExpress.XtraEditors.PanelControl Me.rbNationalitySurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblNationalitySurvivor = New DevExpress.XtraEditors.LabelControl Me.pnEmployerNameSurvivor = New DevExpress.XtraEditors.PanelControl Me.lblEmployerNameSurvivor = New DevExpress.XtraEditors.LabelControl Me.rbEmployerNameSurvivor = New DevExpress.XtraEditors.CheckEdit Me.pnGeoLocationEmployerSurvivor = New DevExpress.XtraEditors.PanelControl Me.lblGeoLocationEmployerSurvivor = New DevExpress.XtraEditors.LabelControl Me.rbGeoLocationEmployerSurvivor = New DevExpress.XtraEditors.CheckEdit Me.pnGeoLocationHomeIDSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbGeoLocationHomeIDSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblGeoLocationHomeIDSurvivor = New DevExpress.XtraEditors.LabelControl Me.tbCaseIDSurvivor = New DevExpress.XtraEditors.TextEdit Me.pnCaseIDSurvivor = New DevExpress.XtraEditors.PanelControl Me.rbCaseIDSurvivor = New DevExpress.XtraEditors.CheckEdit Me.lblCaseIDSurvivor = New DevExpress.XtraEditors.LabelControl Me.tpSamplesSurvivor = New DevExpress.XtraTab.XtraTabPage Me.gcSamplesSurvivor = New DevExpress.XtraGrid.GridControl Me.gvSamplesSurvivor = New DevExpress.XtraGrid.Views.Grid.GridView Me.gcolMaterialIDSurvivor = New DevExpress.XtraGrid.Columns.GridColumn Me.gcolRowTypeSurvivor = New DevExpress.XtraGrid.Columns.GridColumn Me.gcolCheckedSurvivor = New DevExpress.XtraGrid.Columns.GridColumn Me.chAddToCaseSurvivor = New DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit Me.gcolSampleIDSurvivor = New DevExpress.XtraGrid.Columns.GridColumn Me.gcolSampleTypeSurvivor = New DevExpress.XtraGrid.Columns.GridColumn Me.gcolCollectionDateSurvivor = New DevExpress.XtraGrid.Columns.GridColumn Me.gcolTestQuantitySurvivor = New DevExpress.XtraGrid.Columns.GridColumn Me.gcolCanUncheckSurvivor = New DevExpress.XtraGrid.Columns.GridColumn CType(Me.pnHCDeduplication, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnHCDeduplication.SuspendLayout() CType(Me.gbSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.gbSurvivor.SuspendLayout() CType(Me.cbSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.gbSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.gbSuperseded.SuspendLayout() CType(Me.cbSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tcSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.tcSuperseded.SuspendLayout() Me.tpNotificationSuperseded.SuspendLayout() CType(Me.tbLocalIDSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnLocalIDSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnLocalIDSuperseded.SuspendLayout() CType(Me.rbLocalIDSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnClinicalSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnClinicalSuperseded.SuspendLayout() CType(Me.LabelControl6, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.LabelControl5, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbAddCaseInfoSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnAddCaseInfoSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnAddCaseInfoSuperseded.SuspendLayout() CType(Me.rbAddCaseInfoSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbPatientLocationNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnPatientLocationNameSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnPatientLocationNameSuperseded.SuspendLayout() CType(Me.rbPatientLocationNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbPatientLocationStatusSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnPatientLocationStatusSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnPatientLocationStatusSuperseded.SuspendLayout() CType(Me.rbPatientLocationStatusSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbChangedDiagnosisDateSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnChangedDiagnosisDateSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnChangedDiagnosisDateSuperseded.SuspendLayout() CType(Me.rbChangedDiagnosisDateSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbChangedDiagnosisSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnChangedDiagnosisSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnChangedDiagnosisSuperseded.SuspendLayout() CType(Me.rbChangedDiagnosisSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbFinalStateSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnFinalStateSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnFinalStateSuperseded.SuspendLayout() CType(Me.rbFinalStateSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbOnsetDateSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnOnsetDateSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnOnsetDateSuperseded.SuspendLayout() CType(Me.rbOnsetDateSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbDiagnosisDateSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnDiagnosisDateSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnDiagnosisDateSuperseded.SuspendLayout() CType(Me.rbDiagnosisDateSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbDiagnosisSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnDiagnosisSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnDiagnosisSuperseded.SuspendLayout() CType(Me.rbDiagnosisSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnDemographicSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnDemographicSuperseded.SuspendLayout() CType(Me.LabelControl4, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.LabelControl1, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbGeoLocationEmployerSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbEmployerNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbPhoneNumberSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbNationalitySuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.gbPatientInfoSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbAptmHomeSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbBuildingHomeSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbHouseHomeSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbPostalCodeHomeSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbStreetHomeSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbSettlementHomeSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbRayonHomeSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbRegionHomeSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbAgeUnitsSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbSexSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbDOBSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbAgeSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbSecondNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbLastNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbFirstNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnLastNameSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnLastNameSuperseded.SuspendLayout() CType(Me.rbLastNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnFirstNameSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnFirstNameSuperseded.SuspendLayout() CType(Me.rbFirstNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnSecondNameSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnSecondNameSuperseded.SuspendLayout() CType(Me.rbSecondNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnDOBSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnDOBSuperseded.SuspendLayout() CType(Me.rbDOBSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnAgeSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnAgeSuperseded.SuspendLayout() CType(Me.rbAgeSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnSexSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnSexSuperseded.SuspendLayout() CType(Me.rbSexSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnGeoLocationHomeIDSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnGeoLocationHomeIDSuperseded.SuspendLayout() CType(Me.rbGeoLocationHomeIDSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnPhoneNumberSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnPhoneNumberSuperseded.SuspendLayout() CType(Me.rbPhoneNumberSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnNationalitySuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnNationalitySuperseded.SuspendLayout() CType(Me.rbNationalitySuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnEmployerNameSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnEmployerNameSuperseded.SuspendLayout() CType(Me.rbEmployerNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnGeoLocationEmployerSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnGeoLocationEmployerSuperseded.SuspendLayout() CType(Me.rbGeoLocationEmployerSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbCaseIDSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnCaseIDSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnCaseIDSuperseded.SuspendLayout() CType(Me.rbCaseIDSuperseded.Properties, System.ComponentModel.ISupportInitialize).BeginInit() Me.tpSamplesSuperseded.SuspendLayout() CType(Me.gcSamplesSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.gvSamplesSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.chAddToCaseSuperseded, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tcSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.tcSurvivor.SuspendLayout() Me.tpNotificationSurvivor.SuspendLayout() CType(Me.tbLocalIDSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnLocalIDSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnLocalIDSurvivor.SuspendLayout() CType(Me.rbLocalIDSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnClinicalSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnClinicalSurvivor.SuspendLayout() CType(Me.LabelControl8, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.LabelControl7, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbAddCaseInfoSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnAddCaseInfoSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnAddCaseInfoSurvivor.SuspendLayout() CType(Me.rbAddCaseInfoSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbPatientLocationNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnPatientLocationNameSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnPatientLocationNameSurvivor.SuspendLayout() CType(Me.rbPatientLocationNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbPatientLocationStatusSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnPatientLocationStatusSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnPatientLocationStatusSurvivor.SuspendLayout() CType(Me.rbPatientLocationStatusSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbChangedDiagnosisDateSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnChangedDiagnosisDateSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnChangedDiagnosisDateSurvivor.SuspendLayout() CType(Me.rbChangedDiagnosisDateSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbChangedDiagnosisSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnChangedDiagnosisSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnChangedDiagnosisSurvivor.SuspendLayout() CType(Me.rbChangedDiagnosisSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbFinalStateSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnFinalStateSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnFinalStateSurvivor.SuspendLayout() CType(Me.rbFinalStateSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbOnsetDateSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnOnsetDateSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnOnsetDateSurvivor.SuspendLayout() CType(Me.rbOnsetDateSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbDiagnosisDateSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnDiagnosisDateSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnDiagnosisDateSurvivor.SuspendLayout() CType(Me.rbDiagnosisDateSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbDiagnosisSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnDiagnosisSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnDiagnosisSurvivor.SuspendLayout() CType(Me.rbDiagnosisSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnDemographicSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnDemographicSurvivor.SuspendLayout() CType(Me.LabelControl3, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.LabelControl2, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbGeoLocationEmployerSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbEmployerNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbPhoneNumberSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbNationalitySurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbAptmHomeSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbBuildingHomeSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbHouseHomeSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbPostalCodeHomeSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbStreetHomeSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbSettlementHomeSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbRayonHomeSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbRegionHomeSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.gbPatientInfoSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbAgeUnitsSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbSexSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbDOBSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbAgeSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbSecondNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbLastNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbFirstNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnLastNameSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnLastNameSurvivor.SuspendLayout() CType(Me.rbLastNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnFirstNameSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnFirstNameSurvivor.SuspendLayout() CType(Me.rbFirstNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnSecondNameSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnSecondNameSurvivor.SuspendLayout() CType(Me.rbSecondNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnDOBSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnDOBSurvivor.SuspendLayout() CType(Me.rbDOBSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnAgeSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnAgeSurvivor.SuspendLayout() CType(Me.rbAgeSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnSexSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnSexSurvivor.SuspendLayout() CType(Me.rbSexSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnPhoneNumberSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnPhoneNumberSurvivor.SuspendLayout() CType(Me.rbPhoneNumberSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnNationalitySurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnNationalitySurvivor.SuspendLayout() CType(Me.rbNationalitySurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnEmployerNameSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnEmployerNameSurvivor.SuspendLayout() CType(Me.rbEmployerNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnGeoLocationEmployerSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnGeoLocationEmployerSurvivor.SuspendLayout() CType(Me.rbGeoLocationEmployerSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnGeoLocationHomeIDSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnGeoLocationHomeIDSurvivor.SuspendLayout() CType(Me.rbGeoLocationHomeIDSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.tbCaseIDSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pnCaseIDSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnCaseIDSurvivor.SuspendLayout() CType(Me.rbCaseIDSurvivor.Properties, System.ComponentModel.ISupportInitialize).BeginInit() Me.tpSamplesSurvivor.SuspendLayout() CType(Me.gcSamplesSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.gvSamplesSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.chAddToCaseSurvivor, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'pnHCDeduplication ' resources.ApplyResources(Me.pnHCDeduplication, "pnHCDeduplication") Me.pnHCDeduplication.Controls.Add(Me.gbSurvivor) Me.pnHCDeduplication.Controls.Add(Me.gbSuperseded) Me.pnHCDeduplication.Controls.Add(Me.tcSuperseded) Me.pnHCDeduplication.Controls.Add(Me.tcSurvivor) Me.pnHCDeduplication.Name = "pnHCDeduplication" Me.pnHCDeduplication.TabStop = True ' 'gbSurvivor ' Me.gbSurvivor.Controls.Add(Me.btnAllSurvivor) Me.gbSurvivor.Controls.Add(Me.cbSurvivor) resources.ApplyResources(Me.gbSurvivor, "gbSurvivor") Me.gbSurvivor.Name = "gbSurvivor" ' 'btnAllSurvivor ' resources.ApplyResources(Me.btnAllSurvivor, "btnAllSurvivor") Me.btnAllSurvivor.Name = "btnAllSurvivor" ' 'cbSurvivor ' resources.ApplyResources(Me.cbSurvivor, "cbSurvivor") Me.cbSurvivor.Name = "cbSurvivor" Me.cbSurvivor.Properties.Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(CType(resources.GetObject("cbSurvivor.Properties.Buttons"), DevExpress.XtraEditors.Controls.ButtonPredefines))}) ' 'gbSuperseded ' Me.gbSuperseded.Controls.Add(Me.btnAllSuperseded) Me.gbSuperseded.Controls.Add(Me.cbSuperseded) resources.ApplyResources(Me.gbSuperseded, "gbSuperseded") Me.gbSuperseded.Name = "gbSuperseded" ' 'btnAllSuperseded ' resources.ApplyResources(Me.btnAllSuperseded, "btnAllSuperseded") Me.btnAllSuperseded.Name = "btnAllSuperseded" ' 'cbSuperseded ' resources.ApplyResources(Me.cbSuperseded, "cbSuperseded") Me.cbSuperseded.Name = "cbSuperseded" Me.cbSuperseded.Properties.Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(CType(resources.GetObject("cbSuperseded.Properties.Buttons"), DevExpress.XtraEditors.Controls.ButtonPredefines))}) ' 'tcSuperseded ' resources.ApplyResources(Me.tcSuperseded, "tcSuperseded") Me.tcSuperseded.Name = "tcSuperseded" Me.tcSuperseded.SelectedTabPage = Me.tpNotificationSuperseded Me.tcSuperseded.TabPages.AddRange(New DevExpress.XtraTab.XtraTabPage() {Me.tpNotificationSuperseded, Me.tpSamplesSuperseded}) ' 'tpNotificationSuperseded ' Me.tpNotificationSuperseded.Appearance.PageClient.BackColor = System.Drawing.SystemColors.ControlLightLight Me.tpNotificationSuperseded.Appearance.PageClient.Options.UseBackColor = True resources.ApplyResources(Me.tpNotificationSuperseded, "tpNotificationSuperseded") Me.tpNotificationSuperseded.Controls.Add(Me.tbLocalIDSuperseded) Me.tpNotificationSuperseded.Controls.Add(Me.pnLocalIDSuperseded) Me.tpNotificationSuperseded.Controls.Add(Me.pnClinicalSuperseded) Me.tpNotificationSuperseded.Controls.Add(Me.tbDiagnosisDateSuperseded) Me.tpNotificationSuperseded.Controls.Add(Me.pnDiagnosisDateSuperseded) Me.tpNotificationSuperseded.Controls.Add(Me.tbDiagnosisSuperseded) Me.tpNotificationSuperseded.Controls.Add(Me.pnDiagnosisSuperseded) Me.tpNotificationSuperseded.Controls.Add(Me.pnDemographicSuperseded) Me.tpNotificationSuperseded.Controls.Add(Me.tbCaseIDSuperseded) Me.tpNotificationSuperseded.Controls.Add(Me.pnCaseIDSuperseded) Me.tpNotificationSuperseded.Name = "tpNotificationSuperseded" ' 'tbLocalIDSuperseded ' resources.ApplyResources(Me.tbLocalIDSuperseded, "tbLocalIDSuperseded") Me.tbLocalIDSuperseded.Name = "tbLocalIDSuperseded" ' 'pnLocalIDSuperseded ' Me.pnLocalIDSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnLocalIDSuperseded.Controls.Add(Me.rbLocalIDSuperseded) Me.pnLocalIDSuperseded.Controls.Add(Me.lblLocalIDSuperseded) resources.ApplyResources(Me.pnLocalIDSuperseded, "pnLocalIDSuperseded") Me.pnLocalIDSuperseded.Name = "pnLocalIDSuperseded" Me.pnLocalIDSuperseded.TabStop = True ' 'rbLocalIDSuperseded ' resources.ApplyResources(Me.rbLocalIDSuperseded, "rbLocalIDSuperseded") Me.rbLocalIDSuperseded.Name = "rbLocalIDSuperseded" Me.rbLocalIDSuperseded.Properties.Caption = resources.GetString("rbLocalIDSuperseded.Properties.Caption") Me.rbLocalIDSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblLocalIDSuperseded ' resources.ApplyResources(Me.lblLocalIDSuperseded, "lblLocalIDSuperseded") Me.lblLocalIDSuperseded.Name = "lblLocalIDSuperseded" ' 'pnClinicalSuperseded ' Me.pnClinicalSuperseded.Controls.Add(Me.LabelControl6) Me.pnClinicalSuperseded.Controls.Add(Me.LabelControl5) Me.pnClinicalSuperseded.Controls.Add(Me.tbAddCaseInfoSuperseded) Me.pnClinicalSuperseded.Controls.Add(Me.pnAddCaseInfoSuperseded) Me.pnClinicalSuperseded.Controls.Add(Me.tbPatientLocationNameSuperseded) Me.pnClinicalSuperseded.Controls.Add(Me.pnPatientLocationNameSuperseded) Me.pnClinicalSuperseded.Controls.Add(Me.tbPatientLocationStatusSuperseded) Me.pnClinicalSuperseded.Controls.Add(Me.pnPatientLocationStatusSuperseded) Me.pnClinicalSuperseded.Controls.Add(Me.lblPatientLocationSuperseded) Me.pnClinicalSuperseded.Controls.Add(Me.tbChangedDiagnosisDateSuperseded) Me.pnClinicalSuperseded.Controls.Add(Me.pnChangedDiagnosisDateSuperseded) Me.pnClinicalSuperseded.Controls.Add(Me.tbChangedDiagnosisSuperseded) Me.pnClinicalSuperseded.Controls.Add(Me.pnChangedDiagnosisSuperseded) Me.pnClinicalSuperseded.Controls.Add(Me.tbFinalStateSuperseded) Me.pnClinicalSuperseded.Controls.Add(Me.pnFinalStateSuperseded) Me.pnClinicalSuperseded.Controls.Add(Me.tbOnsetDateSuperseded) Me.pnClinicalSuperseded.Controls.Add(Me.pnOnsetDateSuperseded) resources.ApplyResources(Me.pnClinicalSuperseded, "pnClinicalSuperseded") Me.pnClinicalSuperseded.Name = "pnClinicalSuperseded" Me.pnClinicalSuperseded.TabStop = True ' 'LabelControl6 ' resources.ApplyResources(Me.LabelControl6, "LabelControl6") Me.LabelControl6.Name = "LabelControl6" ' 'LabelControl5 ' resources.ApplyResources(Me.LabelControl5, "LabelControl5") Me.LabelControl5.Name = "LabelControl5" ' 'tbAddCaseInfoSuperseded ' resources.ApplyResources(Me.tbAddCaseInfoSuperseded, "tbAddCaseInfoSuperseded") Me.tbAddCaseInfoSuperseded.Name = "tbAddCaseInfoSuperseded" Me.tbAddCaseInfoSuperseded.Properties.AutoHeight = CType(resources.GetObject("tbAddCaseInfoSuperseded.Properties.AutoHeight"), Boolean) ' 'pnAddCaseInfoSuperseded ' Me.pnAddCaseInfoSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnAddCaseInfoSuperseded.Controls.Add(Me.rbAddCaseInfoSuperseded) Me.pnAddCaseInfoSuperseded.Controls.Add(Me.lblAddCaseInfoSuperseded) resources.ApplyResources(Me.pnAddCaseInfoSuperseded, "pnAddCaseInfoSuperseded") Me.pnAddCaseInfoSuperseded.Name = "pnAddCaseInfoSuperseded" Me.pnAddCaseInfoSuperseded.TabStop = True ' 'rbAddCaseInfoSuperseded ' resources.ApplyResources(Me.rbAddCaseInfoSuperseded, "rbAddCaseInfoSuperseded") Me.rbAddCaseInfoSuperseded.Name = "rbAddCaseInfoSuperseded" Me.rbAddCaseInfoSuperseded.Properties.Caption = resources.GetString("rbAddCaseInfoSuperseded.Properties.Caption") Me.rbAddCaseInfoSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblAddCaseInfoSuperseded ' resources.ApplyResources(Me.lblAddCaseInfoSuperseded, "lblAddCaseInfoSuperseded") Me.lblAddCaseInfoSuperseded.Name = "lblAddCaseInfoSuperseded" ' 'tbPatientLocationNameSuperseded ' resources.ApplyResources(Me.tbPatientLocationNameSuperseded, "tbPatientLocationNameSuperseded") Me.tbPatientLocationNameSuperseded.Name = "tbPatientLocationNameSuperseded" ' 'pnPatientLocationNameSuperseded ' Me.pnPatientLocationNameSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnPatientLocationNameSuperseded.Controls.Add(Me.lblPatientLocationNameSuperseded) Me.pnPatientLocationNameSuperseded.Controls.Add(Me.rbPatientLocationNameSuperseded) resources.ApplyResources(Me.pnPatientLocationNameSuperseded, "pnPatientLocationNameSuperseded") Me.pnPatientLocationNameSuperseded.Name = "pnPatientLocationNameSuperseded" Me.pnPatientLocationNameSuperseded.TabStop = True ' 'rbPatientLocationNameSuperseded ' resources.ApplyResources(Me.rbPatientLocationNameSuperseded, "rbPatientLocationNameSuperseded") Me.rbPatientLocationNameSuperseded.Name = "rbPatientLocationNameSuperseded" Me.rbPatientLocationNameSuperseded.Properties.Caption = resources.GetString("rbPatientLocationNameSuperseded.Properties.Caption") Me.rbPatientLocationNameSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblPatientLocationNameSuperseded ' Me.lblPatientLocationNameSuperseded.Appearance.Options.UseTextOptions = True Me.lblPatientLocationNameSuperseded.Appearance.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap resources.ApplyResources(Me.lblPatientLocationNameSuperseded, "lblPatientLocationNameSuperseded") Me.lblPatientLocationNameSuperseded.Name = "lblPatientLocationNameSuperseded" ' 'tbPatientLocationStatusSuperseded ' resources.ApplyResources(Me.tbPatientLocationStatusSuperseded, "tbPatientLocationStatusSuperseded") Me.tbPatientLocationStatusSuperseded.Name = "tbPatientLocationStatusSuperseded" ' 'pnPatientLocationStatusSuperseded ' Me.pnPatientLocationStatusSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnPatientLocationStatusSuperseded.Controls.Add(Me.rbPatientLocationStatusSuperseded) Me.pnPatientLocationStatusSuperseded.Controls.Add(Me.lblPatientLocationStatusSuperseded) resources.ApplyResources(Me.pnPatientLocationStatusSuperseded, "pnPatientLocationStatusSuperseded") Me.pnPatientLocationStatusSuperseded.Name = "pnPatientLocationStatusSuperseded" Me.pnPatientLocationStatusSuperseded.TabStop = True ' 'rbPatientLocationStatusSuperseded ' resources.ApplyResources(Me.rbPatientLocationStatusSuperseded, "rbPatientLocationStatusSuperseded") Me.rbPatientLocationStatusSuperseded.Name = "rbPatientLocationStatusSuperseded" Me.rbPatientLocationStatusSuperseded.Properties.Caption = resources.GetString("rbPatientLocationStatusSuperseded.Properties.Caption") Me.rbPatientLocationStatusSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblPatientLocationStatusSuperseded ' resources.ApplyResources(Me.lblPatientLocationStatusSuperseded, "lblPatientLocationStatusSuperseded") Me.lblPatientLocationStatusSuperseded.Name = "lblPatientLocationStatusSuperseded" ' 'lblPatientLocationSuperseded ' Me.lblPatientLocationSuperseded.Appearance.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold) Me.lblPatientLocationSuperseded.Appearance.Options.UseFont = True Me.lblPatientLocationSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder resources.ApplyResources(Me.lblPatientLocationSuperseded, "lblPatientLocationSuperseded") Me.lblPatientLocationSuperseded.Name = "lblPatientLocationSuperseded" ' 'tbChangedDiagnosisDateSuperseded ' resources.ApplyResources(Me.tbChangedDiagnosisDateSuperseded, "tbChangedDiagnosisDateSuperseded") Me.tbChangedDiagnosisDateSuperseded.Name = "tbChangedDiagnosisDateSuperseded" ' 'pnChangedDiagnosisDateSuperseded ' Me.pnChangedDiagnosisDateSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnChangedDiagnosisDateSuperseded.Controls.Add(Me.rbChangedDiagnosisDateSuperseded) Me.pnChangedDiagnosisDateSuperseded.Controls.Add(Me.lblChangedDiagnosisDateSuperseded) resources.ApplyResources(Me.pnChangedDiagnosisDateSuperseded, "pnChangedDiagnosisDateSuperseded") Me.pnChangedDiagnosisDateSuperseded.Name = "pnChangedDiagnosisDateSuperseded" Me.pnChangedDiagnosisDateSuperseded.TabStop = True ' 'rbChangedDiagnosisDateSuperseded ' resources.ApplyResources(Me.rbChangedDiagnosisDateSuperseded, "rbChangedDiagnosisDateSuperseded") Me.rbChangedDiagnosisDateSuperseded.Name = "rbChangedDiagnosisDateSuperseded" Me.rbChangedDiagnosisDateSuperseded.Properties.Caption = resources.GetString("rbChangedDiagnosisDateSuperseded.Properties.Caption") Me.rbChangedDiagnosisDateSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblChangedDiagnosisDateSuperseded ' resources.ApplyResources(Me.lblChangedDiagnosisDateSuperseded, "lblChangedDiagnosisDateSuperseded") Me.lblChangedDiagnosisDateSuperseded.Name = "lblChangedDiagnosisDateSuperseded" ' 'tbChangedDiagnosisSuperseded ' resources.ApplyResources(Me.tbChangedDiagnosisSuperseded, "tbChangedDiagnosisSuperseded") Me.tbChangedDiagnosisSuperseded.Name = "tbChangedDiagnosisSuperseded" ' 'pnChangedDiagnosisSuperseded ' Me.pnChangedDiagnosisSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnChangedDiagnosisSuperseded.Controls.Add(Me.rbChangedDiagnosisSuperseded) Me.pnChangedDiagnosisSuperseded.Controls.Add(Me.lblChangedDiagnosisSuperseded) resources.ApplyResources(Me.pnChangedDiagnosisSuperseded, "pnChangedDiagnosisSuperseded") Me.pnChangedDiagnosisSuperseded.Name = "pnChangedDiagnosisSuperseded" Me.pnChangedDiagnosisSuperseded.TabStop = True ' 'rbChangedDiagnosisSuperseded ' resources.ApplyResources(Me.rbChangedDiagnosisSuperseded, "rbChangedDiagnosisSuperseded") Me.rbChangedDiagnosisSuperseded.Name = "rbChangedDiagnosisSuperseded" Me.rbChangedDiagnosisSuperseded.Properties.Caption = resources.GetString("rbChangedDiagnosisSuperseded.Properties.Caption") Me.rbChangedDiagnosisSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblChangedDiagnosisSuperseded ' resources.ApplyResources(Me.lblChangedDiagnosisSuperseded, "lblChangedDiagnosisSuperseded") Me.lblChangedDiagnosisSuperseded.Name = "lblChangedDiagnosisSuperseded" ' 'tbFinalStateSuperseded ' resources.ApplyResources(Me.tbFinalStateSuperseded, "tbFinalStateSuperseded") Me.tbFinalStateSuperseded.Name = "tbFinalStateSuperseded" ' 'pnFinalStateSuperseded ' Me.pnFinalStateSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnFinalStateSuperseded.Controls.Add(Me.rbFinalStateSuperseded) Me.pnFinalStateSuperseded.Controls.Add(Me.lblFinalStateSuperseded) resources.ApplyResources(Me.pnFinalStateSuperseded, "pnFinalStateSuperseded") Me.pnFinalStateSuperseded.Name = "pnFinalStateSuperseded" Me.pnFinalStateSuperseded.TabStop = True ' 'rbFinalStateSuperseded ' resources.ApplyResources(Me.rbFinalStateSuperseded, "rbFinalStateSuperseded") Me.rbFinalStateSuperseded.Name = "rbFinalStateSuperseded" Me.rbFinalStateSuperseded.Properties.Caption = resources.GetString("rbFinalStateSuperseded.Properties.Caption") Me.rbFinalStateSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblFinalStateSuperseded ' resources.ApplyResources(Me.lblFinalStateSuperseded, "lblFinalStateSuperseded") Me.lblFinalStateSuperseded.Name = "lblFinalStateSuperseded" ' 'tbOnsetDateSuperseded ' resources.ApplyResources(Me.tbOnsetDateSuperseded, "tbOnsetDateSuperseded") Me.tbOnsetDateSuperseded.Name = "tbOnsetDateSuperseded" ' 'pnOnsetDateSuperseded ' Me.pnOnsetDateSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnOnsetDateSuperseded.Controls.Add(Me.rbOnsetDateSuperseded) Me.pnOnsetDateSuperseded.Controls.Add(Me.lblOnsetDateSuperseded) resources.ApplyResources(Me.pnOnsetDateSuperseded, "pnOnsetDateSuperseded") Me.pnOnsetDateSuperseded.Name = "pnOnsetDateSuperseded" Me.pnOnsetDateSuperseded.TabStop = True ' 'rbOnsetDateSuperseded ' resources.ApplyResources(Me.rbOnsetDateSuperseded, "rbOnsetDateSuperseded") Me.rbOnsetDateSuperseded.Name = "rbOnsetDateSuperseded" Me.rbOnsetDateSuperseded.Properties.Caption = resources.GetString("rbOnsetDateSuperseded.Properties.Caption") Me.rbOnsetDateSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblOnsetDateSuperseded ' resources.ApplyResources(Me.lblOnsetDateSuperseded, "lblOnsetDateSuperseded") Me.lblOnsetDateSuperseded.Name = "lblOnsetDateSuperseded" ' 'tbDiagnosisDateSuperseded ' resources.ApplyResources(Me.tbDiagnosisDateSuperseded, "tbDiagnosisDateSuperseded") Me.tbDiagnosisDateSuperseded.Name = "tbDiagnosisDateSuperseded" ' 'pnDiagnosisDateSuperseded ' Me.pnDiagnosisDateSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnDiagnosisDateSuperseded.Controls.Add(Me.rbDiagnosisDateSuperseded) Me.pnDiagnosisDateSuperseded.Controls.Add(Me.lblDiagnosisDateSuperseded) resources.ApplyResources(Me.pnDiagnosisDateSuperseded, "pnDiagnosisDateSuperseded") Me.pnDiagnosisDateSuperseded.Name = "pnDiagnosisDateSuperseded" Me.pnDiagnosisDateSuperseded.TabStop = True ' 'rbDiagnosisDateSuperseded ' resources.ApplyResources(Me.rbDiagnosisDateSuperseded, "rbDiagnosisDateSuperseded") Me.rbDiagnosisDateSuperseded.Name = "rbDiagnosisDateSuperseded" Me.rbDiagnosisDateSuperseded.Properties.Caption = resources.GetString("rbDiagnosisDateSuperseded.Properties.Caption") Me.rbDiagnosisDateSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblDiagnosisDateSuperseded ' resources.ApplyResources(Me.lblDiagnosisDateSuperseded, "lblDiagnosisDateSuperseded") Me.lblDiagnosisDateSuperseded.Name = "lblDiagnosisDateSuperseded" ' 'tbDiagnosisSuperseded ' resources.ApplyResources(Me.tbDiagnosisSuperseded, "tbDiagnosisSuperseded") Me.tbDiagnosisSuperseded.Name = "tbDiagnosisSuperseded" ' 'pnDiagnosisSuperseded ' Me.pnDiagnosisSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnDiagnosisSuperseded.Controls.Add(Me.rbDiagnosisSuperseded) Me.pnDiagnosisSuperseded.Controls.Add(Me.lblDiagnosisSuperseded) resources.ApplyResources(Me.pnDiagnosisSuperseded, "pnDiagnosisSuperseded") Me.pnDiagnosisSuperseded.Name = "pnDiagnosisSuperseded" Me.pnDiagnosisSuperseded.TabStop = True ' 'rbDiagnosisSuperseded ' resources.ApplyResources(Me.rbDiagnosisSuperseded, "rbDiagnosisSuperseded") Me.rbDiagnosisSuperseded.Name = "rbDiagnosisSuperseded" Me.rbDiagnosisSuperseded.Properties.Caption = resources.GetString("rbDiagnosisSuperseded.Properties.Caption") Me.rbDiagnosisSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblDiagnosisSuperseded ' resources.ApplyResources(Me.lblDiagnosisSuperseded, "lblDiagnosisSuperseded") Me.lblDiagnosisSuperseded.Name = "lblDiagnosisSuperseded" ' 'pnDemographicSuperseded ' Me.pnDemographicSuperseded.Controls.Add(Me.LabelControl4) Me.pnDemographicSuperseded.Controls.Add(Me.LabelControl1) Me.pnDemographicSuperseded.Controls.Add(Me.tbGeoLocationEmployerSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbEmployerNameSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbPhoneNumberSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbNationalitySuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.gbPatientInfoSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbAptmHomeSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbBuildingHomeSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.lblHBAHomeSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbHouseHomeSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.lblPostalCodeHomeSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbPostalCodeHomeSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.lblStreetHomeSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbStreetHomeSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.lblSettlementHomeSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbSettlementHomeSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.lblRayonHomeSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbRayonHomeSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.lblRegionHomeSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbRegionHomeSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbAgeUnitsSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbSexSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbDOBSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbAgeSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.lblPatientNameSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbSecondNameSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbLastNameSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.tbFirstNameSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.pnLastNameSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.pnFirstNameSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.pnSecondNameSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.pnDOBSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.pnAgeSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.pnSexSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.pnGeoLocationHomeIDSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.pnPhoneNumberSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.pnNationalitySuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.pnEmployerNameSuperseded) Me.pnDemographicSuperseded.Controls.Add(Me.pnGeoLocationEmployerSuperseded) resources.ApplyResources(Me.pnDemographicSuperseded, "pnDemographicSuperseded") Me.pnDemographicSuperseded.Name = "pnDemographicSuperseded" Me.pnDemographicSuperseded.TabStop = True ' 'LabelControl4 ' resources.ApplyResources(Me.LabelControl4, "LabelControl4") Me.LabelControl4.Name = "LabelControl4" ' 'LabelControl1 ' resources.ApplyResources(Me.LabelControl1, "LabelControl1") Me.LabelControl1.Name = "LabelControl1" ' 'tbGeoLocationEmployerSuperseded ' resources.ApplyResources(Me.tbGeoLocationEmployerSuperseded, "tbGeoLocationEmployerSuperseded") Me.tbGeoLocationEmployerSuperseded.Name = "tbGeoLocationEmployerSuperseded" ' 'tbEmployerNameSuperseded ' resources.ApplyResources(Me.tbEmployerNameSuperseded, "tbEmployerNameSuperseded") Me.tbEmployerNameSuperseded.Name = "tbEmployerNameSuperseded" ' 'tbPhoneNumberSuperseded ' resources.ApplyResources(Me.tbPhoneNumberSuperseded, "tbPhoneNumberSuperseded") Me.tbPhoneNumberSuperseded.Name = "tbPhoneNumberSuperseded" ' 'tbNationalitySuperseded ' resources.ApplyResources(Me.tbNationalitySuperseded, "tbNationalitySuperseded") Me.tbNationalitySuperseded.Name = "tbNationalitySuperseded" ' 'gbPatientInfoSuperseded ' resources.ApplyResources(Me.gbPatientInfoSuperseded, "gbPatientInfoSuperseded") Me.gbPatientInfoSuperseded.Name = "gbPatientInfoSuperseded" ' 'tbAptmHomeSuperseded ' resources.ApplyResources(Me.tbAptmHomeSuperseded, "tbAptmHomeSuperseded") Me.tbAptmHomeSuperseded.Name = "tbAptmHomeSuperseded" ' 'tbBuildingHomeSuperseded ' resources.ApplyResources(Me.tbBuildingHomeSuperseded, "tbBuildingHomeSuperseded") Me.tbBuildingHomeSuperseded.Name = "tbBuildingHomeSuperseded" ' 'lblHBAHomeSuperseded ' resources.ApplyResources(Me.lblHBAHomeSuperseded, "lblHBAHomeSuperseded") Me.lblHBAHomeSuperseded.Name = "lblHBAHomeSuperseded" ' 'tbHouseHomeSuperseded ' resources.ApplyResources(Me.tbHouseHomeSuperseded, "tbHouseHomeSuperseded") Me.tbHouseHomeSuperseded.Name = "tbHouseHomeSuperseded" ' 'lblPostalCodeHomeSuperseded ' resources.ApplyResources(Me.lblPostalCodeHomeSuperseded, "lblPostalCodeHomeSuperseded") Me.lblPostalCodeHomeSuperseded.Name = "lblPostalCodeHomeSuperseded" ' 'tbPostalCodeHomeSuperseded ' resources.ApplyResources(Me.tbPostalCodeHomeSuperseded, "tbPostalCodeHomeSuperseded") Me.tbPostalCodeHomeSuperseded.Name = "tbPostalCodeHomeSuperseded" ' 'lblStreetHomeSuperseded ' resources.ApplyResources(Me.lblStreetHomeSuperseded, "lblStreetHomeSuperseded") Me.lblStreetHomeSuperseded.Name = "lblStreetHomeSuperseded" ' 'tbStreetHomeSuperseded ' resources.ApplyResources(Me.tbStreetHomeSuperseded, "tbStreetHomeSuperseded") Me.tbStreetHomeSuperseded.Name = "tbStreetHomeSuperseded" ' 'lblSettlementHomeSuperseded ' resources.ApplyResources(Me.lblSettlementHomeSuperseded, "lblSettlementHomeSuperseded") Me.lblSettlementHomeSuperseded.Name = "lblSettlementHomeSuperseded" ' 'tbSettlementHomeSuperseded ' resources.ApplyResources(Me.tbSettlementHomeSuperseded, "tbSettlementHomeSuperseded") Me.tbSettlementHomeSuperseded.Name = "tbSettlementHomeSuperseded" ' 'lblRayonHomeSuperseded ' resources.ApplyResources(Me.lblRayonHomeSuperseded, "lblRayonHomeSuperseded") Me.lblRayonHomeSuperseded.Name = "lblRayonHomeSuperseded" ' 'tbRayonHomeSuperseded ' resources.ApplyResources(Me.tbRayonHomeSuperseded, "tbRayonHomeSuperseded") Me.tbRayonHomeSuperseded.Name = "tbRayonHomeSuperseded" ' 'lblRegionHomeSuperseded ' resources.ApplyResources(Me.lblRegionHomeSuperseded, "lblRegionHomeSuperseded") Me.lblRegionHomeSuperseded.Name = "lblRegionHomeSuperseded" ' 'tbRegionHomeSuperseded ' resources.ApplyResources(Me.tbRegionHomeSuperseded, "tbRegionHomeSuperseded") Me.tbRegionHomeSuperseded.Name = "tbRegionHomeSuperseded" ' 'tbAgeUnitsSuperseded ' resources.ApplyResources(Me.tbAgeUnitsSuperseded, "tbAgeUnitsSuperseded") Me.tbAgeUnitsSuperseded.Name = "tbAgeUnitsSuperseded" Me.tbAgeUnitsSuperseded.Properties.AutoHeight = CType(resources.GetObject("tbAgeUnitsSuperseded.Properties.AutoHeight"), Boolean) ' 'tbSexSuperseded ' resources.ApplyResources(Me.tbSexSuperseded, "tbSexSuperseded") Me.tbSexSuperseded.Name = "tbSexSuperseded" ' 'tbDOBSuperseded ' resources.ApplyResources(Me.tbDOBSuperseded, "tbDOBSuperseded") Me.tbDOBSuperseded.Name = "tbDOBSuperseded" ' 'tbAgeSuperseded ' resources.ApplyResources(Me.tbAgeSuperseded, "tbAgeSuperseded") Me.tbAgeSuperseded.Name = "tbAgeSuperseded" Me.tbAgeSuperseded.Properties.AutoHeight = CType(resources.GetObject("tbAgeSuperseded.Properties.AutoHeight"), Boolean) ' 'lblPatientNameSuperseded ' Me.lblPatientNameSuperseded.Appearance.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold) Me.lblPatientNameSuperseded.Appearance.Options.UseFont = True resources.ApplyResources(Me.lblPatientNameSuperseded, "lblPatientNameSuperseded") Me.lblPatientNameSuperseded.Name = "lblPatientNameSuperseded" ' 'tbSecondNameSuperseded ' resources.ApplyResources(Me.tbSecondNameSuperseded, "tbSecondNameSuperseded") Me.tbSecondNameSuperseded.Name = "tbSecondNameSuperseded" ' 'tbLastNameSuperseded ' resources.ApplyResources(Me.tbLastNameSuperseded, "tbLastNameSuperseded") Me.tbLastNameSuperseded.Name = "tbLastNameSuperseded" ' 'tbFirstNameSuperseded ' resources.ApplyResources(Me.tbFirstNameSuperseded, "tbFirstNameSuperseded") Me.tbFirstNameSuperseded.Name = "tbFirstNameSuperseded" ' 'pnLastNameSuperseded ' Me.pnLastNameSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnLastNameSuperseded.Controls.Add(Me.rbLastNameSuperseded) Me.pnLastNameSuperseded.Controls.Add(Me.lblLastNameSuperseded) resources.ApplyResources(Me.pnLastNameSuperseded, "pnLastNameSuperseded") Me.pnLastNameSuperseded.Name = "pnLastNameSuperseded" Me.pnLastNameSuperseded.TabStop = True ' 'rbLastNameSuperseded ' resources.ApplyResources(Me.rbLastNameSuperseded, "rbLastNameSuperseded") Me.rbLastNameSuperseded.Name = "rbLastNameSuperseded" Me.rbLastNameSuperseded.Properties.Caption = resources.GetString("rbLastNameSuperseded.Properties.Caption") Me.rbLastNameSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblLastNameSuperseded ' resources.ApplyResources(Me.lblLastNameSuperseded, "lblLastNameSuperseded") Me.lblLastNameSuperseded.Name = "lblLastNameSuperseded" ' 'pnFirstNameSuperseded ' Me.pnFirstNameSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnFirstNameSuperseded.Controls.Add(Me.rbFirstNameSuperseded) Me.pnFirstNameSuperseded.Controls.Add(Me.lblFirstNameSuperseded) resources.ApplyResources(Me.pnFirstNameSuperseded, "pnFirstNameSuperseded") Me.pnFirstNameSuperseded.Name = "pnFirstNameSuperseded" Me.pnFirstNameSuperseded.TabStop = True ' 'rbFirstNameSuperseded ' resources.ApplyResources(Me.rbFirstNameSuperseded, "rbFirstNameSuperseded") Me.rbFirstNameSuperseded.Name = "rbFirstNameSuperseded" Me.rbFirstNameSuperseded.Properties.Caption = resources.GetString("rbFirstNameSuperseded.Properties.Caption") Me.rbFirstNameSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblFirstNameSuperseded ' resources.ApplyResources(Me.lblFirstNameSuperseded, "lblFirstNameSuperseded") Me.lblFirstNameSuperseded.Name = "lblFirstNameSuperseded" ' 'pnSecondNameSuperseded ' Me.pnSecondNameSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnSecondNameSuperseded.Controls.Add(Me.rbSecondNameSuperseded) Me.pnSecondNameSuperseded.Controls.Add(Me.lblSecondNameSuperseded) resources.ApplyResources(Me.pnSecondNameSuperseded, "pnSecondNameSuperseded") Me.pnSecondNameSuperseded.Name = "pnSecondNameSuperseded" Me.pnSecondNameSuperseded.TabStop = True ' 'rbSecondNameSuperseded ' resources.ApplyResources(Me.rbSecondNameSuperseded, "rbSecondNameSuperseded") Me.rbSecondNameSuperseded.Name = "rbSecondNameSuperseded" Me.rbSecondNameSuperseded.Properties.Caption = resources.GetString("rbSecondNameSuperseded.Properties.Caption") Me.rbSecondNameSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblSecondNameSuperseded ' resources.ApplyResources(Me.lblSecondNameSuperseded, "lblSecondNameSuperseded") Me.lblSecondNameSuperseded.Name = "lblSecondNameSuperseded" ' 'pnDOBSuperseded ' Me.pnDOBSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnDOBSuperseded.Controls.Add(Me.rbDOBSuperseded) Me.pnDOBSuperseded.Controls.Add(Me.lblDOBSuperseded) resources.ApplyResources(Me.pnDOBSuperseded, "pnDOBSuperseded") Me.pnDOBSuperseded.Name = "pnDOBSuperseded" Me.pnDOBSuperseded.TabStop = True ' 'rbDOBSuperseded ' resources.ApplyResources(Me.rbDOBSuperseded, "rbDOBSuperseded") Me.rbDOBSuperseded.Name = "rbDOBSuperseded" Me.rbDOBSuperseded.Properties.Caption = resources.GetString("rbDOBSuperseded.Properties.Caption") Me.rbDOBSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblDOBSuperseded ' resources.ApplyResources(Me.lblDOBSuperseded, "lblDOBSuperseded") Me.lblDOBSuperseded.Name = "lblDOBSuperseded" ' 'pnAgeSuperseded ' Me.pnAgeSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnAgeSuperseded.Controls.Add(Me.rbAgeSuperseded) Me.pnAgeSuperseded.Controls.Add(Me.lblAgeSuperseded) resources.ApplyResources(Me.pnAgeSuperseded, "pnAgeSuperseded") Me.pnAgeSuperseded.Name = "pnAgeSuperseded" Me.pnAgeSuperseded.TabStop = True ' 'rbAgeSuperseded ' resources.ApplyResources(Me.rbAgeSuperseded, "rbAgeSuperseded") Me.rbAgeSuperseded.Name = "rbAgeSuperseded" Me.rbAgeSuperseded.Properties.Caption = resources.GetString("rbAgeSuperseded.Properties.Caption") Me.rbAgeSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblAgeSuperseded ' resources.ApplyResources(Me.lblAgeSuperseded, "lblAgeSuperseded") Me.lblAgeSuperseded.Name = "lblAgeSuperseded" ' 'pnSexSuperseded ' Me.pnSexSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnSexSuperseded.Controls.Add(Me.rbSexSuperseded) Me.pnSexSuperseded.Controls.Add(Me.lblSexSuperseded) resources.ApplyResources(Me.pnSexSuperseded, "pnSexSuperseded") Me.pnSexSuperseded.Name = "pnSexSuperseded" Me.pnSexSuperseded.TabStop = True ' 'rbSexSuperseded ' resources.ApplyResources(Me.rbSexSuperseded, "rbSexSuperseded") Me.rbSexSuperseded.Name = "rbSexSuperseded" Me.rbSexSuperseded.Properties.Caption = resources.GetString("rbSexSuperseded.Properties.Caption") Me.rbSexSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblSexSuperseded ' resources.ApplyResources(Me.lblSexSuperseded, "lblSexSuperseded") Me.lblSexSuperseded.Name = "lblSexSuperseded" ' 'pnGeoLocationHomeIDSuperseded ' resources.ApplyResources(Me.pnGeoLocationHomeIDSuperseded, "pnGeoLocationHomeIDSuperseded") Me.pnGeoLocationHomeIDSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnGeoLocationHomeIDSuperseded.Controls.Add(Me.rbGeoLocationHomeIDSuperseded) Me.pnGeoLocationHomeIDSuperseded.Controls.Add(Me.lblGeoLocationHomeIDSuperseded) Me.pnGeoLocationHomeIDSuperseded.Name = "pnGeoLocationHomeIDSuperseded" Me.pnGeoLocationHomeIDSuperseded.TabStop = True ' 'rbGeoLocationHomeIDSuperseded ' resources.ApplyResources(Me.rbGeoLocationHomeIDSuperseded, "rbGeoLocationHomeIDSuperseded") Me.rbGeoLocationHomeIDSuperseded.Name = "rbGeoLocationHomeIDSuperseded" Me.rbGeoLocationHomeIDSuperseded.Properties.Appearance.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold) Me.rbGeoLocationHomeIDSuperseded.Properties.Appearance.Options.UseFont = True Me.rbGeoLocationHomeIDSuperseded.Properties.Caption = resources.GetString("rbGeoLocationHomeIDSuperseded.Properties.Caption") Me.rbGeoLocationHomeIDSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblGeoLocationHomeIDSuperseded ' resources.ApplyResources(Me.lblGeoLocationHomeIDSuperseded, "lblGeoLocationHomeIDSuperseded") Me.lblGeoLocationHomeIDSuperseded.Appearance.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold) Me.lblGeoLocationHomeIDSuperseded.Appearance.Options.UseFont = True Me.lblGeoLocationHomeIDSuperseded.Name = "lblGeoLocationHomeIDSuperseded" ' 'pnPhoneNumberSuperseded ' Me.pnPhoneNumberSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnPhoneNumberSuperseded.Controls.Add(Me.rbPhoneNumberSuperseded) Me.pnPhoneNumberSuperseded.Controls.Add(Me.lblPhoneNumberSuperseded) resources.ApplyResources(Me.pnPhoneNumberSuperseded, "pnPhoneNumberSuperseded") Me.pnPhoneNumberSuperseded.Name = "pnPhoneNumberSuperseded" Me.pnPhoneNumberSuperseded.TabStop = True ' 'rbPhoneNumberSuperseded ' resources.ApplyResources(Me.rbPhoneNumberSuperseded, "rbPhoneNumberSuperseded") Me.rbPhoneNumberSuperseded.Name = "rbPhoneNumberSuperseded" Me.rbPhoneNumberSuperseded.Properties.Caption = resources.GetString("rbPhoneNumberSuperseded.Properties.Caption") Me.rbPhoneNumberSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblPhoneNumberSuperseded ' resources.ApplyResources(Me.lblPhoneNumberSuperseded, "lblPhoneNumberSuperseded") Me.lblPhoneNumberSuperseded.Name = "lblPhoneNumberSuperseded" ' 'pnNationalitySuperseded ' Me.pnNationalitySuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnNationalitySuperseded.Controls.Add(Me.rbNationalitySuperseded) Me.pnNationalitySuperseded.Controls.Add(Me.lblNationalitySuperseded) resources.ApplyResources(Me.pnNationalitySuperseded, "pnNationalitySuperseded") Me.pnNationalitySuperseded.Name = "pnNationalitySuperseded" Me.pnNationalitySuperseded.TabStop = True ' 'rbNationalitySuperseded ' resources.ApplyResources(Me.rbNationalitySuperseded, "rbNationalitySuperseded") Me.rbNationalitySuperseded.Name = "rbNationalitySuperseded" Me.rbNationalitySuperseded.Properties.Caption = resources.GetString("rbNationalitySuperseded.Properties.Caption") Me.rbNationalitySuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblNationalitySuperseded ' resources.ApplyResources(Me.lblNationalitySuperseded, "lblNationalitySuperseded") Me.lblNationalitySuperseded.Name = "lblNationalitySuperseded" ' 'pnEmployerNameSuperseded ' Me.pnEmployerNameSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnEmployerNameSuperseded.Controls.Add(Me.lblEmployerNameSuperseded) Me.pnEmployerNameSuperseded.Controls.Add(Me.rbEmployerNameSuperseded) resources.ApplyResources(Me.pnEmployerNameSuperseded, "pnEmployerNameSuperseded") Me.pnEmployerNameSuperseded.Name = "pnEmployerNameSuperseded" Me.pnEmployerNameSuperseded.TabStop = True ' 'lblEmployerNameSuperseded ' Me.lblEmployerNameSuperseded.Appearance.Options.UseTextOptions = True Me.lblEmployerNameSuperseded.Appearance.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap resources.ApplyResources(Me.lblEmployerNameSuperseded, "lblEmployerNameSuperseded") Me.lblEmployerNameSuperseded.Name = "lblEmployerNameSuperseded" ' 'rbEmployerNameSuperseded ' resources.ApplyResources(Me.rbEmployerNameSuperseded, "rbEmployerNameSuperseded") Me.rbEmployerNameSuperseded.Name = "rbEmployerNameSuperseded" Me.rbEmployerNameSuperseded.Properties.Caption = resources.GetString("rbEmployerNameSuperseded.Properties.Caption") Me.rbEmployerNameSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'pnGeoLocationEmployerSuperseded ' Me.pnGeoLocationEmployerSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnGeoLocationEmployerSuperseded.Controls.Add(Me.lblGeoLocationEmployerSuperseded) Me.pnGeoLocationEmployerSuperseded.Controls.Add(Me.rbGeoLocationEmployerSuperseded) resources.ApplyResources(Me.pnGeoLocationEmployerSuperseded, "pnGeoLocationEmployerSuperseded") Me.pnGeoLocationEmployerSuperseded.Name = "pnGeoLocationEmployerSuperseded" Me.pnGeoLocationEmployerSuperseded.TabStop = True ' 'lblGeoLocationEmployerSuperseded ' Me.lblGeoLocationEmployerSuperseded.Appearance.Options.UseTextOptions = True Me.lblGeoLocationEmployerSuperseded.Appearance.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap resources.ApplyResources(Me.lblGeoLocationEmployerSuperseded, "lblGeoLocationEmployerSuperseded") Me.lblGeoLocationEmployerSuperseded.Name = "lblGeoLocationEmployerSuperseded" ' 'rbGeoLocationEmployerSuperseded ' resources.ApplyResources(Me.rbGeoLocationEmployerSuperseded, "rbGeoLocationEmployerSuperseded") Me.rbGeoLocationEmployerSuperseded.Name = "rbGeoLocationEmployerSuperseded" Me.rbGeoLocationEmployerSuperseded.Properties.Caption = resources.GetString("rbGeoLocationEmployerSuperseded.Properties.Caption") Me.rbGeoLocationEmployerSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'tbCaseIDSuperseded ' resources.ApplyResources(Me.tbCaseIDSuperseded, "tbCaseIDSuperseded") Me.tbCaseIDSuperseded.Name = "tbCaseIDSuperseded" ' 'pnCaseIDSuperseded ' Me.pnCaseIDSuperseded.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnCaseIDSuperseded.Controls.Add(Me.rbCaseIDSuperseded) Me.pnCaseIDSuperseded.Controls.Add(Me.lblCaseIDSuperseded) resources.ApplyResources(Me.pnCaseIDSuperseded, "pnCaseIDSuperseded") Me.pnCaseIDSuperseded.Name = "pnCaseIDSuperseded" Me.pnCaseIDSuperseded.TabStop = True ' 'rbCaseIDSuperseded ' resources.ApplyResources(Me.rbCaseIDSuperseded, "rbCaseIDSuperseded") Me.rbCaseIDSuperseded.Name = "rbCaseIDSuperseded" Me.rbCaseIDSuperseded.Properties.Caption = resources.GetString("rbCaseIDSuperseded.Properties.Caption") Me.rbCaseIDSuperseded.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblCaseIDSuperseded ' resources.ApplyResources(Me.lblCaseIDSuperseded, "lblCaseIDSuperseded") Me.lblCaseIDSuperseded.Name = "lblCaseIDSuperseded" ' 'tpSamplesSuperseded ' Me.tpSamplesSuperseded.Controls.Add(Me.gcSamplesSuperseded) Me.tpSamplesSuperseded.Name = "tpSamplesSuperseded" resources.ApplyResources(Me.tpSamplesSuperseded, "tpSamplesSuperseded") ' 'gcSamplesSuperseded ' resources.ApplyResources(Me.gcSamplesSuperseded, "gcSamplesSuperseded") Me.gcSamplesSuperseded.MainView = Me.gvSamplesSuperseded Me.gcSamplesSuperseded.Name = "gcSamplesSuperseded" Me.gcSamplesSuperseded.RepositoryItems.AddRange(New DevExpress.XtraEditors.Repository.RepositoryItem() {Me.chAddToCaseSuperseded}) Me.gcSamplesSuperseded.Tag = "{alwayseditable}" Me.gcSamplesSuperseded.ViewCollection.AddRange(New DevExpress.XtraGrid.Views.Base.BaseView() {Me.gvSamplesSuperseded}) ' 'gvSamplesSuperseded ' Me.gvSamplesSuperseded.Columns.AddRange(New DevExpress.XtraGrid.Columns.GridColumn() {Me.gcolMaterialIDSuperseded, Me.gcolRowTypeSuperseded, Me.gcolCheckedSuperseded, Me.gcolSampleIDSuperseded, Me.gcolSampleTypeSuperseded, Me.gcolCollectionDateSuperseded, Me.gcolTestQuantitySuperseded, Me.gcolCanUncheckSuperseded}) Me.gvSamplesSuperseded.GridControl = Me.gcSamplesSuperseded Me.gvSamplesSuperseded.Name = "gvSamplesSuperseded" Me.gvSamplesSuperseded.OptionsCustomization.AllowFilter = False Me.gvSamplesSuperseded.OptionsLayout.Columns.AddNewColumns = False Me.gvSamplesSuperseded.OptionsLayout.Columns.RemoveOldColumns = False Me.gvSamplesSuperseded.OptionsView.ShowGroupPanel = False Me.gvSamplesSuperseded.OptionsView.ShowIndicator = False ' 'gcolMaterialIDSuperseded ' resources.ApplyResources(Me.gcolMaterialIDSuperseded, "gcolMaterialIDSuperseded") Me.gcolMaterialIDSuperseded.FieldName = "idfMaterial" Me.gcolMaterialIDSuperseded.Name = "gcolMaterialIDSuperseded" ' 'gcolRowTypeSuperseded ' resources.ApplyResources(Me.gcolRowTypeSuperseded, "gcolRowTypeSuperseded") Me.gcolRowTypeSuperseded.FieldName = "rowType" Me.gcolRowTypeSuperseded.Name = "gcolRowTypeSuperseded" ' 'gcolCheckedSuperseded ' resources.ApplyResources(Me.gcolCheckedSuperseded, "gcolCheckedSuperseded") Me.gcolCheckedSuperseded.ColumnEdit = Me.chAddToCaseSuperseded Me.gcolCheckedSuperseded.FieldName = "AddToSurvivorCase" Me.gcolCheckedSuperseded.Name = "gcolCheckedSuperseded" Me.gcolCheckedSuperseded.OptionsColumn.ShowCaption = False ' 'chAddToCaseSuperseded ' resources.ApplyResources(Me.chAddToCaseSuperseded, "chAddToCaseSuperseded") Me.chAddToCaseSuperseded.Name = "chAddToCaseSuperseded" ' 'gcolSampleIDSuperseded ' resources.ApplyResources(Me.gcolSampleIDSuperseded, "gcolSampleIDSuperseded") Me.gcolSampleIDSuperseded.FieldName = "strFieldBarcode" Me.gcolSampleIDSuperseded.Name = "gcolSampleIDSuperseded" Me.gcolSampleIDSuperseded.OptionsColumn.AllowEdit = False ' 'gcolSampleTypeSuperseded ' resources.ApplyResources(Me.gcolSampleTypeSuperseded, "gcolSampleTypeSuperseded") Me.gcolSampleTypeSuperseded.FieldName = "SampleType_Name" Me.gcolSampleTypeSuperseded.Name = "gcolSampleTypeSuperseded" Me.gcolSampleTypeSuperseded.OptionsColumn.AllowEdit = False ' 'gcolCollectionDateSuperseded ' resources.ApplyResources(Me.gcolCollectionDateSuperseded, "gcolCollectionDateSuperseded") Me.gcolCollectionDateSuperseded.FieldName = "datFieldCollectionDate" Me.gcolCollectionDateSuperseded.Name = "gcolCollectionDateSuperseded" Me.gcolCollectionDateSuperseded.OptionsColumn.AllowEdit = False ' 'gcolTestQuantitySuperseded ' resources.ApplyResources(Me.gcolTestQuantitySuperseded, "gcolTestQuantitySuperseded") Me.gcolTestQuantitySuperseded.FieldName = "TestQuantity" Me.gcolTestQuantitySuperseded.Name = "gcolTestQuantitySuperseded" Me.gcolTestQuantitySuperseded.OptionsColumn.AllowEdit = False ' 'gcolCanUncheckSuperseded ' Me.gcolCanUncheckSuperseded.FieldName = "CanRemoveFromSurvivorCase" Me.gcolCanUncheckSuperseded.Name = "gcolCanUncheckSuperseded" ' 'tcSurvivor ' resources.ApplyResources(Me.tcSurvivor, "tcSurvivor") Me.tcSurvivor.Name = "tcSurvivor" Me.tcSurvivor.SelectedTabPage = Me.tpNotificationSurvivor Me.tcSurvivor.TabPages.AddRange(New DevExpress.XtraTab.XtraTabPage() {Me.tpNotificationSurvivor, Me.tpSamplesSurvivor}) ' 'tpNotificationSurvivor ' Me.tpNotificationSurvivor.Appearance.PageClient.BackColor = System.Drawing.SystemColors.ControlLightLight Me.tpNotificationSurvivor.Appearance.PageClient.Options.UseBackColor = True resources.ApplyResources(Me.tpNotificationSurvivor, "tpNotificationSurvivor") Me.tpNotificationSurvivor.Controls.Add(Me.tbLocalIDSurvivor) Me.tpNotificationSurvivor.Controls.Add(Me.pnLocalIDSurvivor) Me.tpNotificationSurvivor.Controls.Add(Me.pnClinicalSurvivor) Me.tpNotificationSurvivor.Controls.Add(Me.tbDiagnosisDateSurvivor) Me.tpNotificationSurvivor.Controls.Add(Me.pnDiagnosisDateSurvivor) Me.tpNotificationSurvivor.Controls.Add(Me.tbDiagnosisSurvivor) Me.tpNotificationSurvivor.Controls.Add(Me.pnDiagnosisSurvivor) Me.tpNotificationSurvivor.Controls.Add(Me.pnDemographicSurvivor) Me.tpNotificationSurvivor.Controls.Add(Me.tbCaseIDSurvivor) Me.tpNotificationSurvivor.Controls.Add(Me.pnCaseIDSurvivor) Me.tpNotificationSurvivor.Name = "tpNotificationSurvivor" ' 'tbLocalIDSurvivor ' resources.ApplyResources(Me.tbLocalIDSurvivor, "tbLocalIDSurvivor") Me.tbLocalIDSurvivor.Name = "tbLocalIDSurvivor" ' 'pnLocalIDSurvivor ' Me.pnLocalIDSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnLocalIDSurvivor.Controls.Add(Me.rbLocalIDSurvivor) Me.pnLocalIDSurvivor.Controls.Add(Me.lblLocalIDSurvivor) resources.ApplyResources(Me.pnLocalIDSurvivor, "pnLocalIDSurvivor") Me.pnLocalIDSurvivor.Name = "pnLocalIDSurvivor" Me.pnLocalIDSurvivor.TabStop = True ' 'rbLocalIDSurvivor ' resources.ApplyResources(Me.rbLocalIDSurvivor, "rbLocalIDSurvivor") Me.rbLocalIDSurvivor.Name = "rbLocalIDSurvivor" Me.rbLocalIDSurvivor.Properties.Caption = resources.GetString("rbLocalIDSurvivor.Properties.Caption") Me.rbLocalIDSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblLocalIDSurvivor ' resources.ApplyResources(Me.lblLocalIDSurvivor, "lblLocalIDSurvivor") Me.lblLocalIDSurvivor.Name = "lblLocalIDSurvivor" ' 'pnClinicalSurvivor ' Me.pnClinicalSurvivor.Controls.Add(Me.LabelControl8) Me.pnClinicalSurvivor.Controls.Add(Me.LabelControl7) Me.pnClinicalSurvivor.Controls.Add(Me.tbAddCaseInfoSurvivor) Me.pnClinicalSurvivor.Controls.Add(Me.pnAddCaseInfoSurvivor) Me.pnClinicalSurvivor.Controls.Add(Me.tbPatientLocationNameSurvivor) Me.pnClinicalSurvivor.Controls.Add(Me.pnPatientLocationNameSurvivor) Me.pnClinicalSurvivor.Controls.Add(Me.tbPatientLocationStatusSurvivor) Me.pnClinicalSurvivor.Controls.Add(Me.pnPatientLocationStatusSurvivor) Me.pnClinicalSurvivor.Controls.Add(Me.lblPatientLocationSurvivor) Me.pnClinicalSurvivor.Controls.Add(Me.tbChangedDiagnosisDateSurvivor) Me.pnClinicalSurvivor.Controls.Add(Me.pnChangedDiagnosisDateSurvivor) Me.pnClinicalSurvivor.Controls.Add(Me.tbChangedDiagnosisSurvivor) Me.pnClinicalSurvivor.Controls.Add(Me.pnChangedDiagnosisSurvivor) Me.pnClinicalSurvivor.Controls.Add(Me.tbFinalStateSurvivor) Me.pnClinicalSurvivor.Controls.Add(Me.pnFinalStateSurvivor) Me.pnClinicalSurvivor.Controls.Add(Me.tbOnsetDateSurvivor) Me.pnClinicalSurvivor.Controls.Add(Me.pnOnsetDateSurvivor) resources.ApplyResources(Me.pnClinicalSurvivor, "pnClinicalSurvivor") Me.pnClinicalSurvivor.Name = "pnClinicalSurvivor" Me.pnClinicalSurvivor.TabStop = True ' 'LabelControl8 ' Me.LabelControl8.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.Simple resources.ApplyResources(Me.LabelControl8, "LabelControl8") Me.LabelControl8.Name = "LabelControl8" ' 'LabelControl7 ' resources.ApplyResources(Me.LabelControl7, "LabelControl7") Me.LabelControl7.Name = "LabelControl7" ' 'tbAddCaseInfoSurvivor ' resources.ApplyResources(Me.tbAddCaseInfoSurvivor, "tbAddCaseInfoSurvivor") Me.tbAddCaseInfoSurvivor.Name = "tbAddCaseInfoSurvivor" Me.tbAddCaseInfoSurvivor.Properties.AutoHeight = CType(resources.GetObject("tbAddCaseInfoSurvivor.Properties.AutoHeight"), Boolean) ' 'pnAddCaseInfoSurvivor ' Me.pnAddCaseInfoSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnAddCaseInfoSurvivor.Controls.Add(Me.rbAddCaseInfoSurvivor) Me.pnAddCaseInfoSurvivor.Controls.Add(Me.lblAddCaseInfoSurvivor) resources.ApplyResources(Me.pnAddCaseInfoSurvivor, "pnAddCaseInfoSurvivor") Me.pnAddCaseInfoSurvivor.Name = "pnAddCaseInfoSurvivor" Me.pnAddCaseInfoSurvivor.TabStop = True ' 'rbAddCaseInfoSurvivor ' resources.ApplyResources(Me.rbAddCaseInfoSurvivor, "rbAddCaseInfoSurvivor") Me.rbAddCaseInfoSurvivor.Name = "rbAddCaseInfoSurvivor" Me.rbAddCaseInfoSurvivor.Properties.Caption = resources.GetString("rbAddCaseInfoSurvivor.Properties.Caption") Me.rbAddCaseInfoSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblAddCaseInfoSurvivor ' resources.ApplyResources(Me.lblAddCaseInfoSurvivor, "lblAddCaseInfoSurvivor") Me.lblAddCaseInfoSurvivor.Name = "lblAddCaseInfoSurvivor" ' 'tbPatientLocationNameSurvivor ' resources.ApplyResources(Me.tbPatientLocationNameSurvivor, "tbPatientLocationNameSurvivor") Me.tbPatientLocationNameSurvivor.Name = "tbPatientLocationNameSurvivor" ' 'pnPatientLocationNameSurvivor ' Me.pnPatientLocationNameSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnPatientLocationNameSurvivor.Controls.Add(Me.lblPatientLocationNameSurvivor) Me.pnPatientLocationNameSurvivor.Controls.Add(Me.rbPatientLocationNameSurvivor) resources.ApplyResources(Me.pnPatientLocationNameSurvivor, "pnPatientLocationNameSurvivor") Me.pnPatientLocationNameSurvivor.Name = "pnPatientLocationNameSurvivor" Me.pnPatientLocationNameSurvivor.TabStop = True ' 'rbPatientLocationNameSurvivor ' resources.ApplyResources(Me.rbPatientLocationNameSurvivor, "rbPatientLocationNameSurvivor") Me.rbPatientLocationNameSurvivor.Name = "rbPatientLocationNameSurvivor" Me.rbPatientLocationNameSurvivor.Properties.Caption = resources.GetString("rbPatientLocationNameSurvivor.Properties.Caption") Me.rbPatientLocationNameSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblPatientLocationNameSurvivor ' Me.lblPatientLocationNameSurvivor.Appearance.Options.UseTextOptions = True Me.lblPatientLocationNameSurvivor.Appearance.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap resources.ApplyResources(Me.lblPatientLocationNameSurvivor, "lblPatientLocationNameSurvivor") Me.lblPatientLocationNameSurvivor.Name = "lblPatientLocationNameSurvivor" ' 'tbPatientLocationStatusSurvivor ' resources.ApplyResources(Me.tbPatientLocationStatusSurvivor, "tbPatientLocationStatusSurvivor") Me.tbPatientLocationStatusSurvivor.Name = "tbPatientLocationStatusSurvivor" ' 'pnPatientLocationStatusSurvivor ' Me.pnPatientLocationStatusSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnPatientLocationStatusSurvivor.Controls.Add(Me.rbPatientLocationStatusSurvivor) Me.pnPatientLocationStatusSurvivor.Controls.Add(Me.lblPatientLocationStatusSurvivor) resources.ApplyResources(Me.pnPatientLocationStatusSurvivor, "pnPatientLocationStatusSurvivor") Me.pnPatientLocationStatusSurvivor.Name = "pnPatientLocationStatusSurvivor" Me.pnPatientLocationStatusSurvivor.TabStop = True ' 'rbPatientLocationStatusSurvivor ' resources.ApplyResources(Me.rbPatientLocationStatusSurvivor, "rbPatientLocationStatusSurvivor") Me.rbPatientLocationStatusSurvivor.Name = "rbPatientLocationStatusSurvivor" Me.rbPatientLocationStatusSurvivor.Properties.Caption = resources.GetString("rbPatientLocationStatusSurvivor.Properties.Caption") Me.rbPatientLocationStatusSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblPatientLocationStatusSurvivor ' resources.ApplyResources(Me.lblPatientLocationStatusSurvivor, "lblPatientLocationStatusSurvivor") Me.lblPatientLocationStatusSurvivor.Name = "lblPatientLocationStatusSurvivor" ' 'lblPatientLocationSurvivor ' Me.lblPatientLocationSurvivor.Appearance.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold) Me.lblPatientLocationSurvivor.Appearance.Options.UseFont = True Me.lblPatientLocationSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder resources.ApplyResources(Me.lblPatientLocationSurvivor, "lblPatientLocationSurvivor") Me.lblPatientLocationSurvivor.Name = "lblPatientLocationSurvivor" ' 'tbChangedDiagnosisDateSurvivor ' resources.ApplyResources(Me.tbChangedDiagnosisDateSurvivor, "tbChangedDiagnosisDateSurvivor") Me.tbChangedDiagnosisDateSurvivor.Name = "tbChangedDiagnosisDateSurvivor" ' 'pnChangedDiagnosisDateSurvivor ' Me.pnChangedDiagnosisDateSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnChangedDiagnosisDateSurvivor.Controls.Add(Me.rbChangedDiagnosisDateSurvivor) Me.pnChangedDiagnosisDateSurvivor.Controls.Add(Me.lblChangedDiagnosisDateSurvivor) resources.ApplyResources(Me.pnChangedDiagnosisDateSurvivor, "pnChangedDiagnosisDateSurvivor") Me.pnChangedDiagnosisDateSurvivor.Name = "pnChangedDiagnosisDateSurvivor" Me.pnChangedDiagnosisDateSurvivor.TabStop = True ' 'rbChangedDiagnosisDateSurvivor ' resources.ApplyResources(Me.rbChangedDiagnosisDateSurvivor, "rbChangedDiagnosisDateSurvivor") Me.rbChangedDiagnosisDateSurvivor.Name = "rbChangedDiagnosisDateSurvivor" Me.rbChangedDiagnosisDateSurvivor.Properties.Caption = resources.GetString("rbChangedDiagnosisDateSurvivor.Properties.Caption") Me.rbChangedDiagnosisDateSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblChangedDiagnosisDateSurvivor ' resources.ApplyResources(Me.lblChangedDiagnosisDateSurvivor, "lblChangedDiagnosisDateSurvivor") Me.lblChangedDiagnosisDateSurvivor.Name = "lblChangedDiagnosisDateSurvivor" ' 'tbChangedDiagnosisSurvivor ' resources.ApplyResources(Me.tbChangedDiagnosisSurvivor, "tbChangedDiagnosisSurvivor") Me.tbChangedDiagnosisSurvivor.Name = "tbChangedDiagnosisSurvivor" ' 'pnChangedDiagnosisSurvivor ' Me.pnChangedDiagnosisSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnChangedDiagnosisSurvivor.Controls.Add(Me.rbChangedDiagnosisSurvivor) Me.pnChangedDiagnosisSurvivor.Controls.Add(Me.lblChangedDiagnosisSurvivor) resources.ApplyResources(Me.pnChangedDiagnosisSurvivor, "pnChangedDiagnosisSurvivor") Me.pnChangedDiagnosisSurvivor.Name = "pnChangedDiagnosisSurvivor" Me.pnChangedDiagnosisSurvivor.TabStop = True ' 'rbChangedDiagnosisSurvivor ' resources.ApplyResources(Me.rbChangedDiagnosisSurvivor, "rbChangedDiagnosisSurvivor") Me.rbChangedDiagnosisSurvivor.Name = "rbChangedDiagnosisSurvivor" Me.rbChangedDiagnosisSurvivor.Properties.Caption = resources.GetString("rbChangedDiagnosisSurvivor.Properties.Caption") Me.rbChangedDiagnosisSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblChangedDiagnosisSurvivor ' resources.ApplyResources(Me.lblChangedDiagnosisSurvivor, "lblChangedDiagnosisSurvivor") Me.lblChangedDiagnosisSurvivor.Name = "lblChangedDiagnosisSurvivor" ' 'tbFinalStateSurvivor ' resources.ApplyResources(Me.tbFinalStateSurvivor, "tbFinalStateSurvivor") Me.tbFinalStateSurvivor.Name = "tbFinalStateSurvivor" ' 'pnFinalStateSurvivor ' Me.pnFinalStateSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnFinalStateSurvivor.Controls.Add(Me.rbFinalStateSurvivor) Me.pnFinalStateSurvivor.Controls.Add(Me.lblFinalStateSurvivor) resources.ApplyResources(Me.pnFinalStateSurvivor, "pnFinalStateSurvivor") Me.pnFinalStateSurvivor.Name = "pnFinalStateSurvivor" Me.pnFinalStateSurvivor.TabStop = True ' 'rbFinalStateSurvivor ' resources.ApplyResources(Me.rbFinalStateSurvivor, "rbFinalStateSurvivor") Me.rbFinalStateSurvivor.Name = "rbFinalStateSurvivor" Me.rbFinalStateSurvivor.Properties.Caption = resources.GetString("rbFinalStateSurvivor.Properties.Caption") Me.rbFinalStateSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblFinalStateSurvivor ' resources.ApplyResources(Me.lblFinalStateSurvivor, "lblFinalStateSurvivor") Me.lblFinalStateSurvivor.Name = "lblFinalStateSurvivor" ' 'tbOnsetDateSurvivor ' resources.ApplyResources(Me.tbOnsetDateSurvivor, "tbOnsetDateSurvivor") Me.tbOnsetDateSurvivor.Name = "tbOnsetDateSurvivor" ' 'pnOnsetDateSurvivor ' Me.pnOnsetDateSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnOnsetDateSurvivor.Controls.Add(Me.rbOnsetDateSurvivor) Me.pnOnsetDateSurvivor.Controls.Add(Me.lblOnsetDateSurvivor) resources.ApplyResources(Me.pnOnsetDateSurvivor, "pnOnsetDateSurvivor") Me.pnOnsetDateSurvivor.Name = "pnOnsetDateSurvivor" Me.pnOnsetDateSurvivor.TabStop = True ' 'rbOnsetDateSurvivor ' resources.ApplyResources(Me.rbOnsetDateSurvivor, "rbOnsetDateSurvivor") Me.rbOnsetDateSurvivor.Name = "rbOnsetDateSurvivor" Me.rbOnsetDateSurvivor.Properties.Caption = resources.GetString("rbOnsetDateSurvivor.Properties.Caption") Me.rbOnsetDateSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblOnsetDateSurvivor ' resources.ApplyResources(Me.lblOnsetDateSurvivor, "lblOnsetDateSurvivor") Me.lblOnsetDateSurvivor.Name = "lblOnsetDateSurvivor" ' 'tbDiagnosisDateSurvivor ' resources.ApplyResources(Me.tbDiagnosisDateSurvivor, "tbDiagnosisDateSurvivor") Me.tbDiagnosisDateSurvivor.Name = "tbDiagnosisDateSurvivor" ' 'pnDiagnosisDateSurvivor ' Me.pnDiagnosisDateSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnDiagnosisDateSurvivor.Controls.Add(Me.rbDiagnosisDateSurvivor) Me.pnDiagnosisDateSurvivor.Controls.Add(Me.lblDiagnosisDateSurvivor) resources.ApplyResources(Me.pnDiagnosisDateSurvivor, "pnDiagnosisDateSurvivor") Me.pnDiagnosisDateSurvivor.Name = "pnDiagnosisDateSurvivor" Me.pnDiagnosisDateSurvivor.TabStop = True ' 'rbDiagnosisDateSurvivor ' resources.ApplyResources(Me.rbDiagnosisDateSurvivor, "rbDiagnosisDateSurvivor") Me.rbDiagnosisDateSurvivor.Name = "rbDiagnosisDateSurvivor" Me.rbDiagnosisDateSurvivor.Properties.Caption = resources.GetString("rbDiagnosisDateSurvivor.Properties.Caption") Me.rbDiagnosisDateSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblDiagnosisDateSurvivor ' resources.ApplyResources(Me.lblDiagnosisDateSurvivor, "lblDiagnosisDateSurvivor") Me.lblDiagnosisDateSurvivor.Name = "lblDiagnosisDateSurvivor" ' 'tbDiagnosisSurvivor ' resources.ApplyResources(Me.tbDiagnosisSurvivor, "tbDiagnosisSurvivor") Me.tbDiagnosisSurvivor.Name = "tbDiagnosisSurvivor" ' 'pnDiagnosisSurvivor ' Me.pnDiagnosisSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnDiagnosisSurvivor.Controls.Add(Me.rbDiagnosisSurvivor) Me.pnDiagnosisSurvivor.Controls.Add(Me.lblDiagnosisSurvivor) resources.ApplyResources(Me.pnDiagnosisSurvivor, "pnDiagnosisSurvivor") Me.pnDiagnosisSurvivor.Name = "pnDiagnosisSurvivor" Me.pnDiagnosisSurvivor.TabStop = True ' 'rbDiagnosisSurvivor ' resources.ApplyResources(Me.rbDiagnosisSurvivor, "rbDiagnosisSurvivor") Me.rbDiagnosisSurvivor.Name = "rbDiagnosisSurvivor" Me.rbDiagnosisSurvivor.Properties.Caption = resources.GetString("rbDiagnosisSurvivor.Properties.Caption") Me.rbDiagnosisSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblDiagnosisSurvivor ' resources.ApplyResources(Me.lblDiagnosisSurvivor, "lblDiagnosisSurvivor") Me.lblDiagnosisSurvivor.Name = "lblDiagnosisSurvivor" ' 'pnDemographicSurvivor ' Me.pnDemographicSurvivor.Controls.Add(Me.LabelControl3) Me.pnDemographicSurvivor.Controls.Add(Me.LabelControl2) Me.pnDemographicSurvivor.Controls.Add(Me.tbGeoLocationEmployerSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbEmployerNameSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbPhoneNumberSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbNationalitySurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbAptmHomeSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbBuildingHomeSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.lblHBAHomeSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbHouseHomeSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.lblPostalCodeHomeSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbPostalCodeHomeSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.lblStreetHomeSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbStreetHomeSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.lblSettlementHomeSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbSettlementHomeSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.lblRayonHomeSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbRayonHomeSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.lblRegionHomeSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbRegionHomeSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.gbPatientInfoSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbAgeUnitsSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbSexSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbDOBSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbAgeSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.lblPatientNameSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbSecondNameSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbLastNameSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.tbFirstNameSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.pnLastNameSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.pnFirstNameSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.pnSecondNameSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.pnDOBSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.pnAgeSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.pnSexSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.pnPhoneNumberSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.pnNationalitySurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.pnEmployerNameSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.pnGeoLocationEmployerSurvivor) Me.pnDemographicSurvivor.Controls.Add(Me.pnGeoLocationHomeIDSurvivor) resources.ApplyResources(Me.pnDemographicSurvivor, "pnDemographicSurvivor") Me.pnDemographicSurvivor.Name = "pnDemographicSurvivor" Me.pnDemographicSurvivor.TabStop = True ' 'LabelControl3 ' resources.ApplyResources(Me.LabelControl3, "LabelControl3") Me.LabelControl3.Name = "LabelControl3" ' 'LabelControl2 ' resources.ApplyResources(Me.LabelControl2, "LabelControl2") Me.LabelControl2.Name = "LabelControl2" ' 'tbGeoLocationEmployerSurvivor ' resources.ApplyResources(Me.tbGeoLocationEmployerSurvivor, "tbGeoLocationEmployerSurvivor") Me.tbGeoLocationEmployerSurvivor.Name = "tbGeoLocationEmployerSurvivor" ' 'tbEmployerNameSurvivor ' resources.ApplyResources(Me.tbEmployerNameSurvivor, "tbEmployerNameSurvivor") Me.tbEmployerNameSurvivor.Name = "tbEmployerNameSurvivor" ' 'tbPhoneNumberSurvivor ' resources.ApplyResources(Me.tbPhoneNumberSurvivor, "tbPhoneNumberSurvivor") Me.tbPhoneNumberSurvivor.Name = "tbPhoneNumberSurvivor" ' 'tbNationalitySurvivor ' resources.ApplyResources(Me.tbNationalitySurvivor, "tbNationalitySurvivor") Me.tbNationalitySurvivor.Name = "tbNationalitySurvivor" ' 'tbAptmHomeSurvivor ' resources.ApplyResources(Me.tbAptmHomeSurvivor, "tbAptmHomeSurvivor") Me.tbAptmHomeSurvivor.Name = "tbAptmHomeSurvivor" ' 'tbBuildingHomeSurvivor ' resources.ApplyResources(Me.tbBuildingHomeSurvivor, "tbBuildingHomeSurvivor") Me.tbBuildingHomeSurvivor.Name = "tbBuildingHomeSurvivor" ' 'lblHBAHomeSurvivor ' resources.ApplyResources(Me.lblHBAHomeSurvivor, "lblHBAHomeSurvivor") Me.lblHBAHomeSurvivor.Name = "lblHBAHomeSurvivor" ' 'tbHouseHomeSurvivor ' resources.ApplyResources(Me.tbHouseHomeSurvivor, "tbHouseHomeSurvivor") Me.tbHouseHomeSurvivor.Name = "tbHouseHomeSurvivor" ' 'lblPostalCodeHomeSurvivor ' resources.ApplyResources(Me.lblPostalCodeHomeSurvivor, "lblPostalCodeHomeSurvivor") Me.lblPostalCodeHomeSurvivor.Name = "lblPostalCodeHomeSurvivor" ' 'tbPostalCodeHomeSurvivor ' resources.ApplyResources(Me.tbPostalCodeHomeSurvivor, "tbPostalCodeHomeSurvivor") Me.tbPostalCodeHomeSurvivor.Name = "tbPostalCodeHomeSurvivor" ' 'lblStreetHomeSurvivor ' resources.ApplyResources(Me.lblStreetHomeSurvivor, "lblStreetHomeSurvivor") Me.lblStreetHomeSurvivor.Name = "lblStreetHomeSurvivor" ' 'tbStreetHomeSurvivor ' resources.ApplyResources(Me.tbStreetHomeSurvivor, "tbStreetHomeSurvivor") Me.tbStreetHomeSurvivor.Name = "tbStreetHomeSurvivor" ' 'lblSettlementHomeSurvivor ' resources.ApplyResources(Me.lblSettlementHomeSurvivor, "lblSettlementHomeSurvivor") Me.lblSettlementHomeSurvivor.Name = "lblSettlementHomeSurvivor" ' 'tbSettlementHomeSurvivor ' resources.ApplyResources(Me.tbSettlementHomeSurvivor, "tbSettlementHomeSurvivor") Me.tbSettlementHomeSurvivor.Name = "tbSettlementHomeSurvivor" ' 'lblRayonHomeSurvivor ' resources.ApplyResources(Me.lblRayonHomeSurvivor, "lblRayonHomeSurvivor") Me.lblRayonHomeSurvivor.Name = "lblRayonHomeSurvivor" ' 'tbRayonHomeSurvivor ' resources.ApplyResources(Me.tbRayonHomeSurvivor, "tbRayonHomeSurvivor") Me.tbRayonHomeSurvivor.Name = "tbRayonHomeSurvivor" ' 'lblRegionHomeSurvivor ' resources.ApplyResources(Me.lblRegionHomeSurvivor, "lblRegionHomeSurvivor") Me.lblRegionHomeSurvivor.Name = "lblRegionHomeSurvivor" ' 'tbRegionHomeSurvivor ' resources.ApplyResources(Me.tbRegionHomeSurvivor, "tbRegionHomeSurvivor") Me.tbRegionHomeSurvivor.Name = "tbRegionHomeSurvivor" ' 'gbPatientInfoSurvivor ' resources.ApplyResources(Me.gbPatientInfoSurvivor, "gbPatientInfoSurvivor") Me.gbPatientInfoSurvivor.Name = "gbPatientInfoSurvivor" ' 'tbAgeUnitsSurvivor ' resources.ApplyResources(Me.tbAgeUnitsSurvivor, "tbAgeUnitsSurvivor") Me.tbAgeUnitsSurvivor.Name = "tbAgeUnitsSurvivor" Me.tbAgeUnitsSurvivor.Properties.AutoHeight = CType(resources.GetObject("tbAgeUnitsSurvivor.Properties.AutoHeight"), Boolean) ' 'tbSexSurvivor ' resources.ApplyResources(Me.tbSexSurvivor, "tbSexSurvivor") Me.tbSexSurvivor.Name = "tbSexSurvivor" ' 'tbDOBSurvivor ' resources.ApplyResources(Me.tbDOBSurvivor, "tbDOBSurvivor") Me.tbDOBSurvivor.Name = "tbDOBSurvivor" ' 'tbAgeSurvivor ' resources.ApplyResources(Me.tbAgeSurvivor, "tbAgeSurvivor") Me.tbAgeSurvivor.Name = "tbAgeSurvivor" Me.tbAgeSurvivor.Properties.AutoHeight = CType(resources.GetObject("tbAgeSurvivor.Properties.AutoHeight"), Boolean) ' 'lblPatientNameSurvivor ' Me.lblPatientNameSurvivor.Appearance.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold) Me.lblPatientNameSurvivor.Appearance.Options.UseFont = True resources.ApplyResources(Me.lblPatientNameSurvivor, "lblPatientNameSurvivor") Me.lblPatientNameSurvivor.Name = "lblPatientNameSurvivor" ' 'tbSecondNameSurvivor ' resources.ApplyResources(Me.tbSecondNameSurvivor, "tbSecondNameSurvivor") Me.tbSecondNameSurvivor.Name = "tbSecondNameSurvivor" ' 'tbLastNameSurvivor ' resources.ApplyResources(Me.tbLastNameSurvivor, "tbLastNameSurvivor") Me.tbLastNameSurvivor.Name = "tbLastNameSurvivor" ' 'tbFirstNameSurvivor ' resources.ApplyResources(Me.tbFirstNameSurvivor, "tbFirstNameSurvivor") Me.tbFirstNameSurvivor.Name = "tbFirstNameSurvivor" ' 'pnLastNameSurvivor ' Me.pnLastNameSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnLastNameSurvivor.Controls.Add(Me.rbLastNameSurvivor) Me.pnLastNameSurvivor.Controls.Add(Me.lblLastNameSurvivor) resources.ApplyResources(Me.pnLastNameSurvivor, "pnLastNameSurvivor") Me.pnLastNameSurvivor.Name = "pnLastNameSurvivor" Me.pnLastNameSurvivor.TabStop = True ' 'rbLastNameSurvivor ' resources.ApplyResources(Me.rbLastNameSurvivor, "rbLastNameSurvivor") Me.rbLastNameSurvivor.Name = "rbLastNameSurvivor" Me.rbLastNameSurvivor.Properties.Caption = resources.GetString("rbLastNameSurvivor.Properties.Caption") Me.rbLastNameSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblLastNameSurvivor ' resources.ApplyResources(Me.lblLastNameSurvivor, "lblLastNameSurvivor") Me.lblLastNameSurvivor.Name = "lblLastNameSurvivor" ' 'pnFirstNameSurvivor ' Me.pnFirstNameSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnFirstNameSurvivor.Controls.Add(Me.rbFirstNameSurvivor) Me.pnFirstNameSurvivor.Controls.Add(Me.lblFirstNameSurvivor) resources.ApplyResources(Me.pnFirstNameSurvivor, "pnFirstNameSurvivor") Me.pnFirstNameSurvivor.Name = "pnFirstNameSurvivor" Me.pnFirstNameSurvivor.TabStop = True ' 'rbFirstNameSurvivor ' resources.ApplyResources(Me.rbFirstNameSurvivor, "rbFirstNameSurvivor") Me.rbFirstNameSurvivor.Name = "rbFirstNameSurvivor" Me.rbFirstNameSurvivor.Properties.Caption = resources.GetString("rbFirstNameSurvivor.Properties.Caption") Me.rbFirstNameSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblFirstNameSurvivor ' resources.ApplyResources(Me.lblFirstNameSurvivor, "lblFirstNameSurvivor") Me.lblFirstNameSurvivor.Name = "lblFirstNameSurvivor" ' 'pnSecondNameSurvivor ' Me.pnSecondNameSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnSecondNameSurvivor.Controls.Add(Me.rbSecondNameSurvivor) Me.pnSecondNameSurvivor.Controls.Add(Me.lblSecondNameSurvivor) resources.ApplyResources(Me.pnSecondNameSurvivor, "pnSecondNameSurvivor") Me.pnSecondNameSurvivor.Name = "pnSecondNameSurvivor" Me.pnSecondNameSurvivor.TabStop = True ' 'rbSecondNameSurvivor ' resources.ApplyResources(Me.rbSecondNameSurvivor, "rbSecondNameSurvivor") Me.rbSecondNameSurvivor.Name = "rbSecondNameSurvivor" Me.rbSecondNameSurvivor.Properties.Caption = resources.GetString("rbSecondNameSurvivor.Properties.Caption") Me.rbSecondNameSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblSecondNameSurvivor ' resources.ApplyResources(Me.lblSecondNameSurvivor, "lblSecondNameSurvivor") Me.lblSecondNameSurvivor.Name = "lblSecondNameSurvivor" ' 'pnDOBSurvivor ' Me.pnDOBSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnDOBSurvivor.Controls.Add(Me.rbDOBSurvivor) Me.pnDOBSurvivor.Controls.Add(Me.lblDOBSurvivor) resources.ApplyResources(Me.pnDOBSurvivor, "pnDOBSurvivor") Me.pnDOBSurvivor.Name = "pnDOBSurvivor" Me.pnDOBSurvivor.TabStop = True ' 'rbDOBSurvivor ' resources.ApplyResources(Me.rbDOBSurvivor, "rbDOBSurvivor") Me.rbDOBSurvivor.Name = "rbDOBSurvivor" Me.rbDOBSurvivor.Properties.Caption = resources.GetString("rbDOBSurvivor.Properties.Caption") Me.rbDOBSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblDOBSurvivor ' resources.ApplyResources(Me.lblDOBSurvivor, "lblDOBSurvivor") Me.lblDOBSurvivor.Name = "lblDOBSurvivor" ' 'pnAgeSurvivor ' Me.pnAgeSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnAgeSurvivor.Controls.Add(Me.rbAgeSurvivor) Me.pnAgeSurvivor.Controls.Add(Me.lblAgeSurvivor) resources.ApplyResources(Me.pnAgeSurvivor, "pnAgeSurvivor") Me.pnAgeSurvivor.Name = "pnAgeSurvivor" Me.pnAgeSurvivor.TabStop = True ' 'rbAgeSurvivor ' resources.ApplyResources(Me.rbAgeSurvivor, "rbAgeSurvivor") Me.rbAgeSurvivor.Name = "rbAgeSurvivor" Me.rbAgeSurvivor.Properties.Caption = resources.GetString("rbAgeSurvivor.Properties.Caption") Me.rbAgeSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblAgeSurvivor ' resources.ApplyResources(Me.lblAgeSurvivor, "lblAgeSurvivor") Me.lblAgeSurvivor.Name = "lblAgeSurvivor" ' 'pnSexSurvivor ' Me.pnSexSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnSexSurvivor.Controls.Add(Me.rbSexSurvivor) Me.pnSexSurvivor.Controls.Add(Me.lblSexSurvivor) resources.ApplyResources(Me.pnSexSurvivor, "pnSexSurvivor") Me.pnSexSurvivor.Name = "pnSexSurvivor" Me.pnSexSurvivor.TabStop = True ' 'rbSexSurvivor ' resources.ApplyResources(Me.rbSexSurvivor, "rbSexSurvivor") Me.rbSexSurvivor.Name = "rbSexSurvivor" Me.rbSexSurvivor.Properties.Caption = resources.GetString("rbSexSurvivor.Properties.Caption") Me.rbSexSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblSexSurvivor ' resources.ApplyResources(Me.lblSexSurvivor, "lblSexSurvivor") Me.lblSexSurvivor.Name = "lblSexSurvivor" ' 'pnPhoneNumberSurvivor ' Me.pnPhoneNumberSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnPhoneNumberSurvivor.Controls.Add(Me.rbPhoneNumberSurvivor) Me.pnPhoneNumberSurvivor.Controls.Add(Me.lblPhoneNumberSurvivor) resources.ApplyResources(Me.pnPhoneNumberSurvivor, "pnPhoneNumberSurvivor") Me.pnPhoneNumberSurvivor.Name = "pnPhoneNumberSurvivor" Me.pnPhoneNumberSurvivor.TabStop = True ' 'rbPhoneNumberSurvivor ' resources.ApplyResources(Me.rbPhoneNumberSurvivor, "rbPhoneNumberSurvivor") Me.rbPhoneNumberSurvivor.Name = "rbPhoneNumberSurvivor" Me.rbPhoneNumberSurvivor.Properties.Caption = resources.GetString("rbPhoneNumberSurvivor.Properties.Caption") Me.rbPhoneNumberSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblPhoneNumberSurvivor ' resources.ApplyResources(Me.lblPhoneNumberSurvivor, "lblPhoneNumberSurvivor") Me.lblPhoneNumberSurvivor.Name = "lblPhoneNumberSurvivor" ' 'pnNationalitySurvivor ' Me.pnNationalitySurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnNationalitySurvivor.Controls.Add(Me.rbNationalitySurvivor) Me.pnNationalitySurvivor.Controls.Add(Me.lblNationalitySurvivor) resources.ApplyResources(Me.pnNationalitySurvivor, "pnNationalitySurvivor") Me.pnNationalitySurvivor.Name = "pnNationalitySurvivor" Me.pnNationalitySurvivor.TabStop = True ' 'rbNationalitySurvivor ' resources.ApplyResources(Me.rbNationalitySurvivor, "rbNationalitySurvivor") Me.rbNationalitySurvivor.Name = "rbNationalitySurvivor" Me.rbNationalitySurvivor.Properties.Caption = resources.GetString("rbNationalitySurvivor.Properties.Caption") Me.rbNationalitySurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblNationalitySurvivor ' resources.ApplyResources(Me.lblNationalitySurvivor, "lblNationalitySurvivor") Me.lblNationalitySurvivor.Name = "lblNationalitySurvivor" ' 'pnEmployerNameSurvivor ' Me.pnEmployerNameSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnEmployerNameSurvivor.Controls.Add(Me.lblEmployerNameSurvivor) Me.pnEmployerNameSurvivor.Controls.Add(Me.rbEmployerNameSurvivor) resources.ApplyResources(Me.pnEmployerNameSurvivor, "pnEmployerNameSurvivor") Me.pnEmployerNameSurvivor.Name = "pnEmployerNameSurvivor" Me.pnEmployerNameSurvivor.TabStop = True ' 'lblEmployerNameSurvivor ' Me.lblEmployerNameSurvivor.Appearance.Options.UseTextOptions = True Me.lblEmployerNameSurvivor.Appearance.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap resources.ApplyResources(Me.lblEmployerNameSurvivor, "lblEmployerNameSurvivor") Me.lblEmployerNameSurvivor.Name = "lblEmployerNameSurvivor" ' 'rbEmployerNameSurvivor ' resources.ApplyResources(Me.rbEmployerNameSurvivor, "rbEmployerNameSurvivor") Me.rbEmployerNameSurvivor.Name = "rbEmployerNameSurvivor" Me.rbEmployerNameSurvivor.Properties.Caption = resources.GetString("rbEmployerNameSurvivor.Properties.Caption") Me.rbEmployerNameSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'pnGeoLocationEmployerSurvivor ' Me.pnGeoLocationEmployerSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnGeoLocationEmployerSurvivor.Controls.Add(Me.lblGeoLocationEmployerSurvivor) Me.pnGeoLocationEmployerSurvivor.Controls.Add(Me.rbGeoLocationEmployerSurvivor) resources.ApplyResources(Me.pnGeoLocationEmployerSurvivor, "pnGeoLocationEmployerSurvivor") Me.pnGeoLocationEmployerSurvivor.Name = "pnGeoLocationEmployerSurvivor" Me.pnGeoLocationEmployerSurvivor.TabStop = True ' 'lblGeoLocationEmployerSurvivor ' Me.lblGeoLocationEmployerSurvivor.Appearance.Options.UseTextOptions = True Me.lblGeoLocationEmployerSurvivor.Appearance.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap resources.ApplyResources(Me.lblGeoLocationEmployerSurvivor, "lblGeoLocationEmployerSurvivor") Me.lblGeoLocationEmployerSurvivor.Name = "lblGeoLocationEmployerSurvivor" ' 'rbGeoLocationEmployerSurvivor ' resources.ApplyResources(Me.rbGeoLocationEmployerSurvivor, "rbGeoLocationEmployerSurvivor") Me.rbGeoLocationEmployerSurvivor.Name = "rbGeoLocationEmployerSurvivor" Me.rbGeoLocationEmployerSurvivor.Properties.Caption = resources.GetString("rbGeoLocationEmployerSurvivor.Properties.Caption") Me.rbGeoLocationEmployerSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'pnGeoLocationHomeIDSurvivor ' resources.ApplyResources(Me.pnGeoLocationHomeIDSurvivor, "pnGeoLocationHomeIDSurvivor") Me.pnGeoLocationHomeIDSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnGeoLocationHomeIDSurvivor.Controls.Add(Me.rbGeoLocationHomeIDSurvivor) Me.pnGeoLocationHomeIDSurvivor.Controls.Add(Me.lblGeoLocationHomeIDSurvivor) Me.pnGeoLocationHomeIDSurvivor.Name = "pnGeoLocationHomeIDSurvivor" Me.pnGeoLocationHomeIDSurvivor.TabStop = True ' 'rbGeoLocationHomeIDSurvivor ' resources.ApplyResources(Me.rbGeoLocationHomeIDSurvivor, "rbGeoLocationHomeIDSurvivor") Me.rbGeoLocationHomeIDSurvivor.Name = "rbGeoLocationHomeIDSurvivor" Me.rbGeoLocationHomeIDSurvivor.Properties.Appearance.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold) Me.rbGeoLocationHomeIDSurvivor.Properties.Appearance.Options.UseFont = True Me.rbGeoLocationHomeIDSurvivor.Properties.Caption = resources.GetString("rbGeoLocationHomeIDSurvivor.Properties.Caption") Me.rbGeoLocationHomeIDSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblGeoLocationHomeIDSurvivor ' resources.ApplyResources(Me.lblGeoLocationHomeIDSurvivor, "lblGeoLocationHomeIDSurvivor") Me.lblGeoLocationHomeIDSurvivor.Appearance.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold) Me.lblGeoLocationHomeIDSurvivor.Appearance.Options.UseFont = True Me.lblGeoLocationHomeIDSurvivor.Name = "lblGeoLocationHomeIDSurvivor" ' 'tbCaseIDSurvivor ' resources.ApplyResources(Me.tbCaseIDSurvivor, "tbCaseIDSurvivor") Me.tbCaseIDSurvivor.Name = "tbCaseIDSurvivor" ' 'pnCaseIDSurvivor ' Me.pnCaseIDSurvivor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder Me.pnCaseIDSurvivor.Controls.Add(Me.rbCaseIDSurvivor) Me.pnCaseIDSurvivor.Controls.Add(Me.lblCaseIDSurvivor) resources.ApplyResources(Me.pnCaseIDSurvivor, "pnCaseIDSurvivor") Me.pnCaseIDSurvivor.Name = "pnCaseIDSurvivor" Me.pnCaseIDSurvivor.TabStop = True ' 'rbCaseIDSurvivor ' resources.ApplyResources(Me.rbCaseIDSurvivor, "rbCaseIDSurvivor") Me.rbCaseIDSurvivor.Name = "rbCaseIDSurvivor" Me.rbCaseIDSurvivor.Properties.Caption = resources.GetString("rbCaseIDSurvivor.Properties.Caption") Me.rbCaseIDSurvivor.Properties.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Radio ' 'lblCaseIDSurvivor ' resources.ApplyResources(Me.lblCaseIDSurvivor, "lblCaseIDSurvivor") Me.lblCaseIDSurvivor.Name = "lblCaseIDSurvivor" ' 'tpSamplesSurvivor ' Me.tpSamplesSurvivor.Controls.Add(Me.gcSamplesSurvivor) Me.tpSamplesSurvivor.Name = "tpSamplesSurvivor" resources.ApplyResources(Me.tpSamplesSurvivor, "tpSamplesSurvivor") ' 'gcSamplesSurvivor ' resources.ApplyResources(Me.gcSamplesSurvivor, "gcSamplesSurvivor") Me.gcSamplesSurvivor.MainView = Me.gvSamplesSurvivor Me.gcSamplesSurvivor.Name = "gcSamplesSurvivor" Me.gcSamplesSurvivor.RepositoryItems.AddRange(New DevExpress.XtraEditors.Repository.RepositoryItem() {Me.chAddToCaseSurvivor}) Me.gcSamplesSurvivor.Tag = "{alwayseditable}" Me.gcSamplesSurvivor.ViewCollection.AddRange(New DevExpress.XtraGrid.Views.Base.BaseView() {Me.gvSamplesSurvivor}) ' 'gvSamplesSurvivor ' Me.gvSamplesSurvivor.Columns.AddRange(New DevExpress.XtraGrid.Columns.GridColumn() {Me.gcolMaterialIDSurvivor, Me.gcolRowTypeSurvivor, Me.gcolCheckedSurvivor, Me.gcolSampleIDSurvivor, Me.gcolSampleTypeSurvivor, Me.gcolCollectionDateSurvivor, Me.gcolTestQuantitySurvivor, Me.gcolCanUncheckSurvivor}) Me.gvSamplesSurvivor.GridControl = Me.gcSamplesSurvivor Me.gvSamplesSurvivor.Name = "gvSamplesSurvivor" Me.gvSamplesSurvivor.OptionsCustomization.AllowFilter = False Me.gvSamplesSurvivor.OptionsLayout.Columns.AddNewColumns = False Me.gvSamplesSurvivor.OptionsLayout.Columns.RemoveOldColumns = False Me.gvSamplesSurvivor.OptionsView.ShowGroupPanel = False Me.gvSamplesSurvivor.OptionsView.ShowIndicator = False ' 'gcolMaterialIDSurvivor ' resources.ApplyResources(Me.gcolMaterialIDSurvivor, "gcolMaterialIDSurvivor") Me.gcolMaterialIDSurvivor.FieldName = "idfMaterial" Me.gcolMaterialIDSurvivor.Name = "gcolMaterialIDSurvivor" ' 'gcolRowTypeSurvivor ' resources.ApplyResources(Me.gcolRowTypeSurvivor, "gcolRowTypeSurvivor") Me.gcolRowTypeSurvivor.FieldName = "rowType" Me.gcolRowTypeSurvivor.Name = "gcolRowTypeSurvivor" ' 'gcolCheckedSurvivor ' resources.ApplyResources(Me.gcolCheckedSurvivor, "gcolCheckedSurvivor") Me.gcolCheckedSurvivor.ColumnEdit = Me.chAddToCaseSurvivor Me.gcolCheckedSurvivor.FieldName = "AddToSurvivorCase" Me.gcolCheckedSurvivor.Name = "gcolCheckedSurvivor" Me.gcolCheckedSurvivor.OptionsColumn.ShowCaption = False ' 'chAddToCaseSurvivor ' resources.ApplyResources(Me.chAddToCaseSurvivor, "chAddToCaseSurvivor") Me.chAddToCaseSurvivor.Name = "chAddToCaseSurvivor" ' 'gcolSampleIDSurvivor ' resources.ApplyResources(Me.gcolSampleIDSurvivor, "gcolSampleIDSurvivor") Me.gcolSampleIDSurvivor.FieldName = "strFieldBarcode" Me.gcolSampleIDSurvivor.Name = "gcolSampleIDSurvivor" Me.gcolSampleIDSurvivor.OptionsColumn.AllowEdit = False ' 'gcolSampleTypeSurvivor ' resources.ApplyResources(Me.gcolSampleTypeSurvivor, "gcolSampleTypeSurvivor") Me.gcolSampleTypeSurvivor.FieldName = "SampleType_Name" Me.gcolSampleTypeSurvivor.Name = "gcolSampleTypeSurvivor" Me.gcolSampleTypeSurvivor.OptionsColumn.AllowEdit = False ' 'gcolCollectionDateSurvivor ' resources.ApplyResources(Me.gcolCollectionDateSurvivor, "gcolCollectionDateSurvivor") Me.gcolCollectionDateSurvivor.FieldName = "datFieldCollectionDate" Me.gcolCollectionDateSurvivor.Name = "gcolCollectionDateSurvivor" Me.gcolCollectionDateSurvivor.OptionsColumn.AllowEdit = False ' 'gcolTestQuantitySurvivor ' resources.ApplyResources(Me.gcolTestQuantitySurvivor, "gcolTestQuantitySurvivor") Me.gcolTestQuantitySurvivor.FieldName = "TestQuantity" Me.gcolTestQuantitySurvivor.Name = "gcolTestQuantitySurvivor" Me.gcolTestQuantitySurvivor.OptionsColumn.AllowEdit = False ' 'gcolCanUncheckSurvivor ' Me.gcolCanUncheckSurvivor.FieldName = "CanRemoveFromSurvivorCase" Me.gcolCanUncheckSurvivor.Name = "gcolCanUncheckSurvivor" ' 'HumanCaseDeduplicationDetail ' resources.ApplyResources(Me, "$this") Me.Controls.Add(Me.pnHCDeduplication) Me.FormID = "H11" Me.HelpTopicID = "HumanDeduplicationForm" Me.LeftIcon = Global.EIDSS.My.Resources.Resources.Human_Case_De_duplication__large_ Me.Name = "HumanCaseDeduplicationDetail" Me.ShowDeleteButton = False Me.ShowSaveButton = False Me.Controls.SetChildIndex(Me.pnHCDeduplication, 0) CType(Me.pnHCDeduplication, System.ComponentModel.ISupportInitialize).EndInit() Me.pnHCDeduplication.ResumeLayout(False) CType(Me.gbSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.gbSurvivor.ResumeLayout(False) CType(Me.cbSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.gbSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.gbSuperseded.ResumeLayout(False) CType(Me.cbSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tcSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.tcSuperseded.ResumeLayout(False) Me.tpNotificationSuperseded.ResumeLayout(False) CType(Me.tbLocalIDSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnLocalIDSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnLocalIDSuperseded.ResumeLayout(False) Me.pnLocalIDSuperseded.PerformLayout() CType(Me.rbLocalIDSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnClinicalSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnClinicalSuperseded.ResumeLayout(False) Me.pnClinicalSuperseded.PerformLayout() CType(Me.LabelControl6, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.LabelControl5, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbAddCaseInfoSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnAddCaseInfoSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnAddCaseInfoSuperseded.ResumeLayout(False) Me.pnAddCaseInfoSuperseded.PerformLayout() CType(Me.rbAddCaseInfoSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbPatientLocationNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnPatientLocationNameSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnPatientLocationNameSuperseded.ResumeLayout(False) CType(Me.rbPatientLocationNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbPatientLocationStatusSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnPatientLocationStatusSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnPatientLocationStatusSuperseded.ResumeLayout(False) Me.pnPatientLocationStatusSuperseded.PerformLayout() CType(Me.rbPatientLocationStatusSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbChangedDiagnosisDateSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnChangedDiagnosisDateSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnChangedDiagnosisDateSuperseded.ResumeLayout(False) Me.pnChangedDiagnosisDateSuperseded.PerformLayout() CType(Me.rbChangedDiagnosisDateSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbChangedDiagnosisSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnChangedDiagnosisSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnChangedDiagnosisSuperseded.ResumeLayout(False) Me.pnChangedDiagnosisSuperseded.PerformLayout() CType(Me.rbChangedDiagnosisSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbFinalStateSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnFinalStateSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnFinalStateSuperseded.ResumeLayout(False) Me.pnFinalStateSuperseded.PerformLayout() CType(Me.rbFinalStateSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbOnsetDateSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnOnsetDateSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnOnsetDateSuperseded.ResumeLayout(False) Me.pnOnsetDateSuperseded.PerformLayout() CType(Me.rbOnsetDateSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbDiagnosisDateSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnDiagnosisDateSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnDiagnosisDateSuperseded.ResumeLayout(False) Me.pnDiagnosisDateSuperseded.PerformLayout() CType(Me.rbDiagnosisDateSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbDiagnosisSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnDiagnosisSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnDiagnosisSuperseded.ResumeLayout(False) Me.pnDiagnosisSuperseded.PerformLayout() CType(Me.rbDiagnosisSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnDemographicSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnDemographicSuperseded.ResumeLayout(False) Me.pnDemographicSuperseded.PerformLayout() CType(Me.LabelControl4, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.LabelControl1, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbGeoLocationEmployerSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbEmployerNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbPhoneNumberSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbNationalitySuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.gbPatientInfoSuperseded, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbAptmHomeSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbBuildingHomeSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbHouseHomeSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbPostalCodeHomeSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbStreetHomeSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbSettlementHomeSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbRayonHomeSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbRegionHomeSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbAgeUnitsSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbSexSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbDOBSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbAgeSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbSecondNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbLastNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbFirstNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnLastNameSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnLastNameSuperseded.ResumeLayout(False) Me.pnLastNameSuperseded.PerformLayout() CType(Me.rbLastNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnFirstNameSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnFirstNameSuperseded.ResumeLayout(False) Me.pnFirstNameSuperseded.PerformLayout() CType(Me.rbFirstNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnSecondNameSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnSecondNameSuperseded.ResumeLayout(False) Me.pnSecondNameSuperseded.PerformLayout() CType(Me.rbSecondNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnDOBSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnDOBSuperseded.ResumeLayout(False) Me.pnDOBSuperseded.PerformLayout() CType(Me.rbDOBSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnAgeSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnAgeSuperseded.ResumeLayout(False) Me.pnAgeSuperseded.PerformLayout() CType(Me.rbAgeSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnSexSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnSexSuperseded.ResumeLayout(False) Me.pnSexSuperseded.PerformLayout() CType(Me.rbSexSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnGeoLocationHomeIDSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnGeoLocationHomeIDSuperseded.ResumeLayout(False) Me.pnGeoLocationHomeIDSuperseded.PerformLayout() CType(Me.rbGeoLocationHomeIDSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnPhoneNumberSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnPhoneNumberSuperseded.ResumeLayout(False) Me.pnPhoneNumberSuperseded.PerformLayout() CType(Me.rbPhoneNumberSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnNationalitySuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnNationalitySuperseded.ResumeLayout(False) Me.pnNationalitySuperseded.PerformLayout() CType(Me.rbNationalitySuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnEmployerNameSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnEmployerNameSuperseded.ResumeLayout(False) CType(Me.rbEmployerNameSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnGeoLocationEmployerSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnGeoLocationEmployerSuperseded.ResumeLayout(False) CType(Me.rbGeoLocationEmployerSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbCaseIDSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnCaseIDSuperseded, System.ComponentModel.ISupportInitialize).EndInit() Me.pnCaseIDSuperseded.ResumeLayout(False) Me.pnCaseIDSuperseded.PerformLayout() CType(Me.rbCaseIDSuperseded.Properties, System.ComponentModel.ISupportInitialize).EndInit() Me.tpSamplesSuperseded.ResumeLayout(False) CType(Me.gcSamplesSuperseded, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.gvSamplesSuperseded, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.chAddToCaseSuperseded, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tcSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.tcSurvivor.ResumeLayout(False) Me.tpNotificationSurvivor.ResumeLayout(False) CType(Me.tbLocalIDSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnLocalIDSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnLocalIDSurvivor.ResumeLayout(False) Me.pnLocalIDSurvivor.PerformLayout() CType(Me.rbLocalIDSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnClinicalSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnClinicalSurvivor.ResumeLayout(False) Me.pnClinicalSurvivor.PerformLayout() CType(Me.LabelControl8, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.LabelControl7, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbAddCaseInfoSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnAddCaseInfoSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnAddCaseInfoSurvivor.ResumeLayout(False) Me.pnAddCaseInfoSurvivor.PerformLayout() CType(Me.rbAddCaseInfoSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbPatientLocationNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnPatientLocationNameSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnPatientLocationNameSurvivor.ResumeLayout(False) CType(Me.rbPatientLocationNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbPatientLocationStatusSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnPatientLocationStatusSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnPatientLocationStatusSurvivor.ResumeLayout(False) Me.pnPatientLocationStatusSurvivor.PerformLayout() CType(Me.rbPatientLocationStatusSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbChangedDiagnosisDateSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnChangedDiagnosisDateSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnChangedDiagnosisDateSurvivor.ResumeLayout(False) Me.pnChangedDiagnosisDateSurvivor.PerformLayout() CType(Me.rbChangedDiagnosisDateSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbChangedDiagnosisSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnChangedDiagnosisSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnChangedDiagnosisSurvivor.ResumeLayout(False) Me.pnChangedDiagnosisSurvivor.PerformLayout() CType(Me.rbChangedDiagnosisSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbFinalStateSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnFinalStateSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnFinalStateSurvivor.ResumeLayout(False) Me.pnFinalStateSurvivor.PerformLayout() CType(Me.rbFinalStateSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbOnsetDateSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnOnsetDateSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnOnsetDateSurvivor.ResumeLayout(False) Me.pnOnsetDateSurvivor.PerformLayout() CType(Me.rbOnsetDateSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbDiagnosisDateSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnDiagnosisDateSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnDiagnosisDateSurvivor.ResumeLayout(False) Me.pnDiagnosisDateSurvivor.PerformLayout() CType(Me.rbDiagnosisDateSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbDiagnosisSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnDiagnosisSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnDiagnosisSurvivor.ResumeLayout(False) Me.pnDiagnosisSurvivor.PerformLayout() CType(Me.rbDiagnosisSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnDemographicSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnDemographicSurvivor.ResumeLayout(False) Me.pnDemographicSurvivor.PerformLayout() CType(Me.LabelControl3, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.LabelControl2, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbGeoLocationEmployerSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbEmployerNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbPhoneNumberSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbNationalitySurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbAptmHomeSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbBuildingHomeSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbHouseHomeSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbPostalCodeHomeSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbStreetHomeSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbSettlementHomeSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbRayonHomeSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbRegionHomeSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.gbPatientInfoSurvivor, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbAgeUnitsSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbSexSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbDOBSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbAgeSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbSecondNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbLastNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbFirstNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnLastNameSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnLastNameSurvivor.ResumeLayout(False) Me.pnLastNameSurvivor.PerformLayout() CType(Me.rbLastNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnFirstNameSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnFirstNameSurvivor.ResumeLayout(False) Me.pnFirstNameSurvivor.PerformLayout() CType(Me.rbFirstNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnSecondNameSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnSecondNameSurvivor.ResumeLayout(False) Me.pnSecondNameSurvivor.PerformLayout() CType(Me.rbSecondNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnDOBSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnDOBSurvivor.ResumeLayout(False) Me.pnDOBSurvivor.PerformLayout() CType(Me.rbDOBSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnAgeSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnAgeSurvivor.ResumeLayout(False) Me.pnAgeSurvivor.PerformLayout() CType(Me.rbAgeSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnSexSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnSexSurvivor.ResumeLayout(False) Me.pnSexSurvivor.PerformLayout() CType(Me.rbSexSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnPhoneNumberSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnPhoneNumberSurvivor.ResumeLayout(False) Me.pnPhoneNumberSurvivor.PerformLayout() CType(Me.rbPhoneNumberSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnNationalitySurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnNationalitySurvivor.ResumeLayout(False) Me.pnNationalitySurvivor.PerformLayout() CType(Me.rbNationalitySurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnEmployerNameSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnEmployerNameSurvivor.ResumeLayout(False) CType(Me.rbEmployerNameSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnGeoLocationEmployerSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnGeoLocationEmployerSurvivor.ResumeLayout(False) CType(Me.rbGeoLocationEmployerSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnGeoLocationHomeIDSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnGeoLocationHomeIDSurvivor.ResumeLayout(False) Me.pnGeoLocationHomeIDSurvivor.PerformLayout() CType(Me.rbGeoLocationHomeIDSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.tbCaseIDSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pnCaseIDSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.pnCaseIDSurvivor.ResumeLayout(False) Me.pnCaseIDSurvivor.PerformLayout() CType(Me.rbCaseIDSurvivor.Properties, System.ComponentModel.ISupportInitialize).EndInit() Me.tpSamplesSurvivor.ResumeLayout(False) CType(Me.gcSamplesSurvivor, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.gvSamplesSurvivor, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.chAddToCaseSurvivor, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) End Sub #End Region #Region "Main form interface" Public Shared Sub ShowMe() BaseFormManager.ShowNormal(New HumanCaseDeduplicationDetail, Nothing) 'BaseForm.ShowModal(New HumanCaseDeduplicationDetail) End Sub #End Region #Region "Control Movement" Dim OkToChangeTabPage As Boolean = True Private Sub tcSurvivor_SelectedIndexChanged(ByVal sender As Object, ByVal e As DevExpress.XtraTab.TabPageChangedEventArgs) Handles tcSurvivor.SelectedPageChanged If (OkToChangeTabPage = True) Then OkToChangeTabPage = False tcSuperseded.SelectedTabPageIndex = tcSurvivor.SelectedTabPageIndex tcSurvivor.Select() OkToChangeTabPage = True End If End Sub Private Sub tcSuperseded_SelectedIndexChanged(ByVal sender As Object, ByVal e As DevExpress.XtraTab.TabPageChangedEventArgs) Handles tcSuperseded.SelectedPageChanged If (OkToChangeTabPage = True) Then OkToChangeTabPage = False tcSurvivor.SelectedTabPageIndex = tcSuperseded.SelectedTabPageIndex tcSuperseded.Select() OkToChangeTabPage = True End If End Sub Dim OkToScrollTabPage As Boolean = True Private m_NotificationScrollValue As Integer = 0 Private Sub tpNotificationSurvivor_MouseWheel(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles tpNotificationSurvivor.MouseWheel If (OkToScrollTabPage = True) Then OkToScrollTabPage = False m_NotificationScrollValue = tpNotificationSurvivor.VerticalScroll.Value tpNotificationSuperseded_MouseWheel(tpNotificationSuperseded, e) OkToScrollTabPage = True Else tpNotificationSurvivor.VerticalScroll.Value = m_NotificationScrollValue tpNotificationSurvivor.VerticalScroll.Value = m_NotificationScrollValue tpNotificationSurvivor.Update() End If End Sub Private Sub tpNotificationSurvivor_Scroll(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.XtraScrollEventArgs) Handles tpNotificationSurvivor.Scroll If (OkToScrollTabPage = True) Then OkToScrollTabPage = False m_NotificationScrollValue = e.NewValue tpNotificationSurvivor.VerticalScroll.Value = m_NotificationScrollValue tpNotificationSuperseded_Scroll(tpNotificationSuperseded, e) OkToScrollTabPage = True Else tpNotificationSurvivor.VerticalScroll.Value = m_NotificationScrollValue tpNotificationSurvivor.VerticalScroll.Value = m_NotificationScrollValue tpNotificationSurvivor.Update() End If End Sub Private Sub tpNotificationSuperseded_MouseWheel(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles tpNotificationSuperseded.MouseWheel If (OkToScrollTabPage = True) Then OkToScrollTabPage = False m_NotificationScrollValue = tpNotificationSuperseded.VerticalScroll.Value tpNotificationSurvivor_MouseWheel(tpNotificationSurvivor, e) OkToScrollTabPage = True Else tpNotificationSuperseded.VerticalScroll.Value = m_NotificationScrollValue tpNotificationSuperseded.VerticalScroll.Value = m_NotificationScrollValue tpNotificationSuperseded.Update() End If End Sub Private Sub tpNotificationSuperseded_Scroll(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.XtraScrollEventArgs) Handles tpNotificationSuperseded.Scroll If (OkToScrollTabPage = True) Then OkToScrollTabPage = False m_NotificationScrollValue = e.NewValue tpNotificationSuperseded.VerticalScroll.Value = m_NotificationScrollValue tpNotificationSurvivor_Scroll(tpNotificationSurvivor, e) OkToScrollTabPage = True Else tpNotificationSuperseded.VerticalScroll.Value = m_NotificationScrollValue tpNotificationSuperseded.VerticalScroll.Value = m_NotificationScrollValue tpNotificationSuperseded.Update() End If End Sub Private m_SampleScrollValue As Integer = 0 Private Sub tpSamplesSurvivor_MouseWheel(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles tpSamplesSurvivor.MouseWheel If (OkToScrollTabPage = True) Then OkToScrollTabPage = False m_SampleScrollValue = tpSamplesSurvivor.VerticalScroll.Value tpSamplesSuperseded_MouseWheel(tpSamplesSuperseded, e) OkToScrollTabPage = True Else tpSamplesSurvivor.VerticalScroll.Value = m_SampleScrollValue tpSamplesSurvivor.VerticalScroll.Value = m_SampleScrollValue tpSamplesSurvivor.Update() End If End Sub Private Sub tpSamplesSurvivor_Scroll(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.XtraScrollEventArgs) Handles tpSamplesSurvivor.Scroll If (OkToScrollTabPage = True) Then OkToScrollTabPage = False m_SampleScrollValue = e.NewValue tpSamplesSurvivor.VerticalScroll.Value = m_SampleScrollValue tpSamplesSuperseded_Scroll(tpSamplesSuperseded, e) OkToScrollTabPage = True Else tpSamplesSurvivor.VerticalScroll.Value = m_SampleScrollValue tpSamplesSurvivor.VerticalScroll.Value = m_SampleScrollValue tpSamplesSurvivor.Update() End If End Sub Private Sub tpSamplesSuperseded_MouseWheel(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles tpSamplesSuperseded.MouseWheel If (OkToScrollTabPage = True) Then OkToScrollTabPage = False m_SampleScrollValue = tpSamplesSuperseded.VerticalScroll.Value tpSamplesSurvivor_MouseWheel(tpSamplesSurvivor, e) OkToScrollTabPage = True Else tpSamplesSuperseded.VerticalScroll.Value = m_SampleScrollValue tpSamplesSuperseded.VerticalScroll.Value = m_SampleScrollValue tpSamplesSuperseded.Update() End If End Sub Private Sub tpSamplesSuperseded_Scroll(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.XtraScrollEventArgs) Handles tpSamplesSuperseded.Scroll If (OkToScrollTabPage = True) Then OkToScrollTabPage = False m_SampleScrollValue = e.NewValue tpSamplesSuperseded.VerticalScroll.Value = m_SampleScrollValue tpSamplesSurvivor_Scroll(tpSamplesSurvivor, e) OkToScrollTabPage = True Else tpSamplesSuperseded.VerticalScroll.Value = m_SampleScrollValue tpSamplesSuperseded.VerticalScroll.Value = m_SampleScrollValue tpSamplesSuperseded.Update() End If End Sub #End Region #Region "ReadOnly View" Public Overrides Property [ReadOnly]() As Boolean Get Return MyBase.ReadOnly End Get Set(ByVal Value As Boolean) MyBase.ReadOnly = Value If Value Then Me.ShowCancelButton = True ArrangeButtons(CancelButton.Top, "BottomButtons") End If End Set End Property #End Region #Region "Bindings" Private Sub InitData(ByVal parent As Control) For Each ctrl As Control In parent.Controls If (TypeOf (ctrl) Is DevExpress.XtraEditors.TextEdit) Then CType(ctrl, DevExpress.XtraEditors.TextEdit).TabStop = True Dim cpName As String = "" If (ctrl.Name.StartsWith("tb") = True) AndAlso _ ((ctrl.Name.EndsWith("Survivor") = True) OrElse (ctrl.Name.EndsWith("Superseded") = True)) AndAlso _ (ctrl.Name.Replace("Survivor", "").Replace("Superseded", "").Length > 2) Then cpName = ctrl.Name.Substring(2, ctrl.Name.Length - 2).Replace("Survivor", "").Replace("Superseded", "") End If Dim cp As CaseProperty = Nothing cp = HumanCaseDeduplicationDbService.FindProperty(cpName) If (Not cp Is Nothing) Then If (Utils.Str(cp.SurvivorValueText, "") <> Utils.Str(cp.SupersededValueText, "")) Then Dim f As System.Drawing.Font = New System.Drawing.Font(CType(ctrl, DevExpress.XtraEditors.TextEdit).Font, Drawing.FontStyle.Bold) CType(ctrl, DevExpress.XtraEditors.TextEdit).Font = f CType(ctrl, DevExpress.XtraEditors.TextEdit).ForeColor = Drawing.Color.Red Else Dim f As System.Drawing.Font = New System.Drawing.Font(CType(ctrl, DevExpress.XtraEditors.TextEdit).Font, Drawing.FontStyle.Regular) CType(ctrl, DevExpress.XtraEditors.TextEdit).Font = f CType(ctrl, DevExpress.XtraEditors.TextEdit).ForeColor = Drawing.Color.Black End If If ((m_SelectedIndex = 0) AndAlso ctrl.Name.EndsWith("Survivor")) OrElse _ ((m_SelectedIndex = 1) AndAlso ctrl.Name.EndsWith("Superseded")) Then CType(ctrl, DevExpress.XtraEditors.TextEdit).Properties.ReadOnly = False If (TypeOf (cp.SurvivorValueText) Is DateTime) Then CType(ctrl, DevExpress.XtraEditors.TextEdit).Text = CDate(cp.SurvivorValueText).ToString("d") Else CType(ctrl, DevExpress.XtraEditors.TextEdit).Text = Utils.Str(cp.SurvivorValueText, "") End If CType(ctrl, DevExpress.XtraEditors.TextEdit).Properties.ReadOnly = True CType(ctrl, DevExpress.XtraEditors.TextEdit).BackColor = Drawing.Color.White End If If ((m_SelectedIndex = 1) AndAlso ctrl.Name.EndsWith("Survivor")) OrElse _ ((m_SelectedIndex = 0) AndAlso ctrl.Name.EndsWith("Superseded")) Then CType(ctrl, DevExpress.XtraEditors.TextEdit).Properties.ReadOnly = False If (TypeOf (cp.SupersededValueText) Is DateTime) Then CType(ctrl, DevExpress.XtraEditors.TextEdit).Text = CDate(cp.SupersededValueText).ToString("d") Else CType(ctrl, DevExpress.XtraEditors.TextEdit).Text = Utils.Str(cp.SupersededValueText, "") End If CType(ctrl, DevExpress.XtraEditors.TextEdit).Properties.ReadOnly = True CType(ctrl, DevExpress.XtraEditors.TextEdit).BackColor = Drawing.Color.White End If End If End If '(only for non-simple version of de-duplication) 'If (TypeOf (ctrl) Is DevExpress.XtraEditors.CheckEdit) Then ' CType(ctrl, DevExpress.XtraEditors.CheckEdit).TabStop = True ' Dim cpName As String = "" ' If (ctrl.Name.StartsWith("rb") = True) AndAlso _ ' ((ctrl.Name.EndsWith("Survivor") = True) OrElse (ctrl.Name.EndsWith("Superseded") = True)) AndAlso _ ' (ctrl.Name.Replace("Survivor", "").Replace("Superseded", "").Length > 2) Then ' cpName = ctrl.Name.Substring(2, ctrl.Name.Length - 2).Replace("Survivor", "").Replace("Superseded", "") ' End If ' Dim cp As CaseProperty = Nothing ' cp = HumanCaseDeduplicationDbService.FindProperty(cpName) ' If (Not cp Is Nothing) Then ' If (Utils.Str(cp.SurvivorValueText, "") <> Utils.Str(cp.SupersededValueText, "")) Then ' CType(ctrl, DevExpress.XtraEditors.CheckEdit).ForeColor = Drawing.Color.Red ' CType(ctrl, DevExpress.XtraEditors.CheckEdit).Visible = True ' If (ctrl.Name.EndsWith("Survivor") = True) Then ' OkToChangeObjectRole = False ' CType(ctrl, DevExpress.XtraEditors.CheckEdit).Checked = _ ' ((m_SelectedIndex = 0) AndAlso cp.IsSurvivorValuePrimary) OrElse _ ' ((m_SelectedIndex = 1) AndAlso Not cp.IsSurvivorValuePrimary) ' OkToChangeObjectRole = True ' End If ' If (ctrl.Name.EndsWith("Superseded") = True) Then ' OkToChangeObjectRole = False ' CType(ctrl, DevExpress.XtraEditors.CheckEdit).Checked = _ ' ((m_SelectedIndex = 0) AndAlso Not cp.IsSurvivorValuePrimary) OrElse _ ' ((m_SelectedIndex = 1) AndAlso cp.IsSurvivorValuePrimary) ' OkToChangeObjectRole = True ' End If ' Else ' CType(ctrl, DevExpress.XtraEditors.CheckEdit).ForeColor = Drawing.Color.Black ' CType(ctrl, DevExpress.XtraEditors.CheckEdit).Visible = False ' End If ' End If 'End If If (TypeOf (ctrl) Is DevExpress.XtraEditors.LabelControl) Then Dim cpName As String = "" If (ctrl.Name.StartsWith("lbl") = True) AndAlso _ ((ctrl.Name.EndsWith("Survivor") = True) OrElse (ctrl.Name.EndsWith("Superseded") = True)) AndAlso _ (ctrl.Name.Replace("Survivor", "").Replace("Superseded", "").Length > 3) Then cpName = ctrl.Name.Substring(3, ctrl.Name.Length - 3).Replace("Survivor", "").Replace("Superseded", "") End If Dim cp As CaseProperty = Nothing cp = HumanCaseDeduplicationDbService.FindProperty(cpName) If (Not cp Is Nothing) Then If (Utils.Str(cp.SurvivorValueText, "") <> Utils.Str(cp.SupersededValueText, "")) Then CType(ctrl, DevExpress.XtraEditors.LabelControl).ForeColor = Drawing.Color.Red Else CType(ctrl, DevExpress.XtraEditors.LabelControl).ForeColor = Drawing.Color.Black End If End If End If If (ctrl.Controls.Count > 0) Then InitData(ctrl) End If Next End Sub Private Sub AddHandlers(ByVal parent As Control) If (TypeOf (parent) Is Panel) OrElse (TypeOf (parent) Is DevExpress.XtraEditors.PanelControl) OrElse _ (TypeOf (parent) Is GroupBox) OrElse (TypeOf (parent) Is DevExpress.XtraEditors.GroupControl) OrElse _ (TypeOf (parent) Is Label) OrElse (TypeOf (parent) Is DevExpress.XtraEditors.LabelControl) OrElse _ (TypeOf (parent) Is RadioButton) OrElse (TypeOf (parent) Is DevExpress.XtraEditors.CheckEdit) OrElse _ (TypeOf (parent) Is TextBox) OrElse (TypeOf (parent) Is DevExpress.XtraEditors.TextEdit) Then AddHandler parent.GotFocus, AddressOf Me.Control_GotFocus End If If (TypeOf (parent) Is DevExpress.XtraEditors.CheckEdit) Then Dim rb As DevExpress.XtraEditors.CheckEdit = CType(parent, DevExpress.XtraEditors.CheckEdit) AddHandler rb.CheckedChanged, AddressOf Me.rb_CheckedChanged End If For Each ctrl As Control In parent.Controls AddHandlers(ctrl) Next End Sub Private Sub RemoveHandlers(ByVal parent As Control) If (TypeOf (parent) Is Panel) OrElse (TypeOf (parent) Is DevExpress.XtraEditors.PanelControl) OrElse _ (TypeOf (parent) Is GroupBox) OrElse (TypeOf (parent) Is DevExpress.XtraEditors.GroupControl) OrElse _ (TypeOf (parent) Is Label) OrElse (TypeOf (parent) Is DevExpress.XtraEditors.LabelControl) OrElse _ (TypeOf (parent) Is RadioButton) OrElse (TypeOf (parent) Is DevExpress.XtraEditors.CheckEdit) OrElse _ (TypeOf (parent) Is TextBox) OrElse (TypeOf (parent) Is DevExpress.XtraEditors.TextEdit) Then RemoveHandler parent.GotFocus, AddressOf Me.Control_GotFocus End If If (TypeOf (parent) Is DevExpress.XtraEditors.CheckEdit) Then Dim rb As DevExpress.XtraEditors.CheckEdit = CType(parent, DevExpress.XtraEditors.CheckEdit) RemoveHandler rb.CheckedChanged, AddressOf Me.rb_CheckedChanged End If For Each ctrl As Control In parent.Controls RemoveHandlers(ctrl) Next End Sub Protected Overrides Sub DefineBinding() RemoveHandlers(Me) Dim dvSamplesSurvivor As DataView = New DataView( _ baseDataSet.Tables(HumanCaseDeduplication_DB.tlbMaterial), _ "rowType = 'Survivor'", _ "strFieldBarcode", _ DataViewRowState.CurrentRows) gcSamplesSurvivor.DataSource = dvSamplesSurvivor Dim dvSamplesSuperseded As DataView = New DataView( _ baseDataSet.Tables(HumanCaseDeduplication_DB.tlbMaterial), _ "rowType = 'Superseded'", _ "strFieldBarcode", _ DataViewRowState.CurrentRows) gcSamplesSuperseded.DataSource = dvSamplesSuperseded InitData(Me) AddHandlers(Me) End Sub #End Region #Region "Post Methods" Public Overrides Function ValidateData() As Boolean Return True End Function Private Function PromptDialog(ByVal Question As String, Optional ByVal DefaultResult As DialogResult = DialogResult.Yes) As DialogResult If bv.common.Configuration.BaseSettings.ShowSaveDataPrompt Then Return bv.winclient.Core.MessageForm.Show(Question, BvMessages.Get("Confirmation"), MessageBoxButtons.YesNoCancel) End If Return DefaultResult End Function Public Overrides Function Post(Optional ByVal postType As PostType = PostType.FinalPosting) As Boolean If UseFormStatus = True AndAlso Status = FormStatus.Demo Then Return True End If If HumanCaseDeduplicationDbService Is Nothing Then Return True If (PostType And PostType.IntermediatePosting) = 0 Then Dim DefaultResult As DialogResult = DialogResult.Yes If m_ClosingMode <> ClosingMode.Ok Then DefaultResult = DialogResult.No End If m_PromptResult = PromptDialog(EidssMessages.Get("msgDeduplicateQuestion", "De-duplicate cases?"), DefaultResult) If m_PromptResult = DialogResult.Cancel Then Return False End If If m_PromptResult = DialogResult.No Then Return True RaiseBeforeValidatingEvent() If ValidateData() = False Then m_PromptResult = DialogResult.Cancel Return False Else m_PromptResult = DialogResult.Yes End If End If If HumanCaseDeduplicationDbService Is Nothing Then Throw New Exception("Detail form DB service is not defined") Return False End If RaiseBeforePostEvent(Me) #If DEBUG Then Dbg.Assert(IgnoreAudit = True OrElse Not AuditObject Is Nothing, "Audit object for baseform {0} is not defined", Me.GetType().Name) #End If HumanCaseDeduplicationDbService.ClearEvents() If Not AuditObject Is Nothing Then Dim cp As CaseProperty = Nothing cp = HumanCaseDeduplicationDbService.FindProperty("idfCase") If (Not cp Is Nothing) Then AuditObject.Key = cp.SurvivorValueID Else AuditObject.Key = Nothing End If Dbg.DbgAssert(Not Utils.IsEmpty(AuditObject.Key), "object key is not defined for object {0}", AuditObject.Name) AuditObject.EventType = AuditEventType.daeEdit AddHandler HumanCaseDeduplicationDbService.OnTransactionStarted, AddressOf CreateAuditEvent AddHandler HumanCaseDeduplicationDbService.OnTransactionFinished, AddressOf SaveEventLog AddHandler HumanCaseDeduplicationDbService.OnTransactionFinished, AddressOf ProcessFiltration End If If (m_DisableFormDuringPost = True) Then ' Special hint for the form designer Enabled = False End If Try If HumanCaseDeduplicationDbService.Post(baseDataSet, PostType) = False Then ErrorForm.ShowError(DbService.LastError) Me.Enabled = True Return False End If Me.Enabled = True If (PostType And PostType.IntermediatePosting) <> 0 Then m_State = BusinessObjectState.EditObject Or (m_State And BusinessObjectState.IntermediateObject) m_WasSaved = True End If If (PostType And PostType.FinalPosting) <> 0 Then m_State = BusinessObjectState.EditObject SaveInitialChanges() m_WasSaved = False m_WasPosted = True End If RaiseAfterPostEvent(Me) m_RefereshParentForm = True RefreshRelatedForms() Return True Catch ex As Exception Throw Finally If Not AuditObject Is Nothing Then RemoveHandler HumanCaseDeduplicationDbService.OnTransactionStarted, AddressOf CreateAuditEvent RemoveHandler HumanCaseDeduplicationDbService.OnTransactionFinished, AddressOf SaveEventLog RemoveHandler HumanCaseDeduplicationDbService.OnTransactionFinished, AddressOf ProcessFiltration End If If Not m_ParentBaseForm Is Nothing AndAlso Not m_ParentBaseForm.IsDisposed AndAlso TypeOf Me.m_ParentBaseForm Is BaseListForm Then m_ParentBaseForm.LoadData(Nothing) CType(m_ParentBaseForm, BaseListForm).LocateRow(GetKey) m_RefereshParentForm = False End If Enabled = True End Try End Function #End Region #Region "Control Events" Dim OkToChangeRoles As Boolean = True Private Sub HumanCaseDetail_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load OkToChangeRoles = False cbSurvivor.Properties.Items.Clear() cbSurvivor.Properties.Items.Add(EidssMessages.Get("Survivor", "Survivor")) cbSurvivor.Properties.Items.Add(EidssMessages.Get("Superseded", "Superseded")) cbSurvivor.SelectedIndex = 0 cbSuperseded.Properties.Items.Clear() cbSuperseded.Properties.Items.Add(EidssMessages.Get("Survivor", "Survivor")) cbSuperseded.Properties.Items.Add(EidssMessages.Get("Superseded", "Superseded")) cbSuperseded.SelectedIndex = 1 OkToChangeRoles = True tpNotificationSurvivor.VerticalScroll.SmallChange = 1 tpNotificationSurvivor.VerticalScroll.LargeChange = 10 tpNotificationSuperseded.VerticalScroll.SmallChange = 1 tpNotificationSuperseded.VerticalScroll.LargeChange = 10 tpSamplesSurvivor.VerticalScroll.SmallChange = 1 tpSamplesSurvivor.VerticalScroll.LargeChange = 10 tpSamplesSuperseded.VerticalScroll.SmallChange = 1 tpSamplesSuperseded.VerticalScroll.LargeChange = 10 End Sub Dim m_SelectedIndex As Integer = 0 Private Sub cbSurvivor_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbSurvivor.SelectedValueChanged If (OkToChangeRoles = True) Then OkToChangeRoles = False cbSuperseded.SelectedIndex = 1 - cbSurvivor.SelectedIndex If (cbSurvivor.SelectedIndex <> m_SelectedIndex) Then m_SelectedIndex = cbSurvivor.SelectedIndex HumanCaseDeduplicationDbService.ChangeRoles() End If InitData(Me) OkToChangeRoles = True End If End Sub Private Sub cbSuperseded_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbSuperseded.SelectedValueChanged If (OkToChangeRoles = True) Then OkToChangeRoles = False cbSurvivor.SelectedIndex = 1 - cbSuperseded.SelectedIndex If (cbSuperseded.SelectedIndex <> 1 - m_SelectedIndex) Then m_SelectedIndex = 1 - cbSuperseded.SelectedIndex HumanCaseDeduplicationDbService.ChangeRoles() End If InitData(Me) OkToChangeRoles = True End If End Sub Private Function GetParentTabPageName(ByVal ctrl As Control) As String If (Not ctrl Is Nothing) AndAlso (Not TypeOf (ctrl) Is DevExpress.XtraTab.XtraTabPage) AndAlso (Not ctrl.Parent Is Nothing) Then Dim p As Control = ctrl.Parent While (Not p Is Nothing) AndAlso (Not TypeOf (p) Is DevExpress.XtraTab.XtraTabPage) p = p.Parent End While If (Not p Is Nothing) Then Return CType(p, DevExpress.XtraTab.XtraTabPage).Name End If End If Return Nothing End Function Private Sub Control_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) If (TypeOf (sender) Is Control) Then Dim ctrl As Control = CType(sender, Control) Dim tpName As String = GetParentTabPageName(ctrl) If ((ctrl.Name.EndsWith("Survivor") = True) OrElse (ctrl.Name.EndsWith("Superseded") = True)) AndAlso _ (ctrl.Name.Replace("Survivor", "").Replace("Superseded", "").Length > 2) AndAlso _ (Not Utils.IsEmpty(tpName)) AndAlso _ ((tpName.EndsWith("Survivor") = True) OrElse (tpName.EndsWith("Superseded") = True)) AndAlso _ (tpName.Replace("Survivor", "").Replace("Superseded", "").Length > 2) Then Dim ctrlMainName As String = ctrl.Name.Replace("Survivor", "").Replace("Superseded", "") Dim tpMainName As String = tpName.Replace("Survivor", "").Replace("Superseded", "") Dim DiffSuffix As String = tpName.Replace(tpMainName, "") If (DiffSuffix = "Survivor") Then DiffSuffix = "Superseded" ElseIf (DiffSuffix = "Superseded") Then DiffSuffix = "Survivor" End If Dim DiffTP() As Control = Me.Controls.Find(tpMainName + DiffSuffix, True) Dim DiffCtrl() As Control = Me.Controls.Find(ctrlMainName + DiffSuffix, True) If (DiffTP.Length > 0) AndAlso (TypeOf (DiffTP(0)) Is DevExpress.XtraTab.XtraTabPage) AndAlso (DiffCtrl.Length > 0) Then CType(DiffTP(0), DevExpress.XtraTab.XtraTabPage).ScrollControlIntoView(DiffCtrl(0)) End If End If End If End Sub Dim OkToChangeObjectRole As Boolean = True Private Sub rb_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) If (OkToChangeObjectRole = True) Then OkToChangeObjectRole = False If (TypeOf (sender) Is DevExpress.XtraEditors.CheckEdit) Then Dim rb As DevExpress.XtraEditors.CheckEdit = CType(sender, DevExpress.XtraEditors.CheckEdit) Dim cpName As String = "" Dim cpSuffix As String = "" If (rb.Name.StartsWith("rb") = True) AndAlso _ ((rb.Name.EndsWith("Survivor") = True) OrElse (rb.Name.EndsWith("Superseded") = True)) AndAlso _ (rb.Name.Replace("Survivor", "").Replace("Superseded", "").Length > 2) Then cpName = rb.Name.Substring(2, rb.Name.Length - 2).Replace("Survivor", "").Replace("Superseded", "") cpSuffix = rb.Name.Substring(2, rb.Name.Length - 2).Replace(cpName, "") If (cpSuffix = "Survivor") Then cpSuffix = "Superseded" ElseIf (cpSuffix = "Superseded") Then cpSuffix = "Survivor" End If End If Dim cp As CaseProperty = Nothing cp = HumanCaseDeduplicationDbService.FindProperty(cpName) If (Not cp Is Nothing) Then cp.IsSurvivorValuePrimary() = Not cp.IsSurvivorValuePrimary() If (cpName = CaseProperty.CasePropertyKind.Age.ToString()) Then cp = HumanCaseDeduplicationDbService.FindProperty(CaseProperty.CasePropertyKind.AgeUnits.ToString()) If (Not cp Is Nothing) Then cp.IsSurvivorValuePrimary() = Not cp.IsSurvivorValuePrimary() End If End If If (cpName = CaseProperty.CasePropertyKind.LastName.ToString()) Then cp = HumanCaseDeduplicationDbService.FindProperty(CaseProperty.CasePropertyKind.idfHuman.ToString()) If (Not cp Is Nothing) Then cp.IsSurvivorValuePrimary() = Not cp.IsSurvivorValuePrimary() End If End If End If Dim ctrl() As Control = Me.Controls.Find("rb" + cpName + cpSuffix, True) If (ctrl.Length > 0) AndAlso (TypeOf (ctrl(0)) Is DevExpress.XtraEditors.CheckEdit) Then CType(ctrl(0), DevExpress.XtraEditors.CheckEdit).Checked = Not rb.Checked End If End If Else OkToChangeObjectRole = True End If End Sub Private Sub CheckAll(ByVal parent As Control, ByVal Suffix As String) Dim altSuffix As String = "" If Suffix = "Survivor" Then altSuffix = "Superseded" End If If Suffix = "Superseded" Then altSuffix = "Survivor" End If For Each ctrl As Control In parent.Controls If (TypeOf (ctrl) Is DevExpress.XtraEditors.CheckEdit) AndAlso (ctrl.Name.StartsWith("rb") = True) Then If (ctrl.Name.EndsWith(Suffix) = True) AndAlso (ctrl.Name.Length > 2 + Suffix.Length) Then CType(ctrl, DevExpress.XtraEditors.CheckEdit).Checked = True End If If (Not Utils.IsEmpty(altSuffix)) AndAlso (ctrl.Name.EndsWith(altSuffix) = True) AndAlso _ (ctrl.Name.Length > 2 + altSuffix.Length) Then CType(ctrl, DevExpress.XtraEditors.CheckEdit).Checked = False End If End If If (ctrl.Controls.Count > 0) Then CheckAll(ctrl, Suffix) End If Next OkToChangeObjectRole = True End Sub Private Sub btnAllSurvivor_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAllSurvivor.Click CheckAll(Me, "Survivor") End Sub Private Sub btnAllSuperseded_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAllSuperseded.Click CheckAll(Me, "Superseded") End Sub Private Sub gvSamplesSurvivor_ShowingEditor(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles gvSamplesSurvivor.ShowingEditor If Closing Then Return If (Not gvSamplesSurvivor Is Nothing) AndAlso (gvSamplesSurvivor.FocusedRowHandle >= 0) AndAlso _ (gvSamplesSurvivor.FocusedColumn Is gcolCheckedSurvivor) Then Dim r As DataRow = gvSamplesSurvivor.GetDataRow(gvSamplesSurvivor.FocusedRowHandle) Dim CanEdit As Boolean = _ (r Is Nothing) OrElse _ Utils.IsEmpty(r("CanRemoveFromSurvivorCase")) OrElse (CBool(r("CanRemoveFromSurvivorCase")) = True) OrElse _ Utils.IsEmpty(r("AddToSurvivorCase")) OrElse (CBool(r("AddToSurvivorCase")) = False) e.Cancel = Not CanEdit End If End Sub Private Sub gvSamplesSuperseded_ShowingEditor(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles gvSamplesSuperseded.ShowingEditor If (Not gvSamplesSuperseded Is Nothing) AndAlso (gvSamplesSuperseded.FocusedRowHandle >= 0) AndAlso _ (gvSamplesSuperseded.FocusedColumn Is gcolCheckedSuperseded) Then Dim r As DataRow = gvSamplesSuperseded.GetDataRow(gvSamplesSuperseded.FocusedRowHandle) Dim CanEdit As Boolean = _ (r Is Nothing) OrElse _ Utils.IsEmpty(r("CanRemoveFromSurvivorCase")) OrElse (CBool(r("CanRemoveFromSurvivorCase")) = True) OrElse _ Utils.IsEmpty(r("AddToSurvivorCase")) OrElse (CBool(r("AddToSurvivorCase")) = False) e.Cancel = Not CanEdit End If End Sub #End Region End Class
EIDSS/EIDSS-Legacy
EIDSS v5/vb/EIDSS/EIDSS_Human/Human Case/HumanCaseDeduplicationDetail.vb
Visual Basic
bsd-2-clause
216,845
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Imports Microsoft.VisualStudio.Text Imports Xunit.Abstractions Imports Xunit.Sdk Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename ''' <summary> ''' A class that holds the result of a rename engine call, and asserts ''' various things about it. This is used in the tests for the rename engine ''' to make asserting that certain spans were converted to what they should be. ''' </summary> Friend Class RenameEngineResult Implements IDisposable Private ReadOnly _workspace As TestWorkspace Private ReadOnly _resolution As ConflictResolution ''' <summary> ''' The list of related locations that haven't been asserted about yet. Items are ''' removed from here when they are asserted on, so the set should be empty once we're ''' done. ''' </summary> Private ReadOnly _unassertedRelatedLocations As HashSet(Of RelatedLocation) Private ReadOnly _renameTo As String Private _failedAssert As Boolean Private Sub New(workspace As TestWorkspace, resolution As ConflictResolution, renameTo As String) _workspace = workspace _resolution = resolution _unassertedRelatedLocations = New HashSet(Of RelatedLocation)(resolution.RelatedLocations) _renameTo = renameTo End Sub Public Shared Function Create( helper As ITestOutputHelper, workspaceXml As XElement, renameTo As String, host As RenameTestHost, Optional renameOptions As SymbolRenameOptions = Nothing, Optional expectFailure As Boolean = False, Optional sourceGenerator As ISourceGenerator = Nothing) As RenameEngineResult Dim composition = EditorTestCompositions.EditorFeatures.AddParts(GetType(NoCompilationContentTypeLanguageService), GetType(NoCompilationContentTypeDefinitions)) If host = RenameTestHost.OutOfProcess_SingleCall OrElse host = RenameTestHost.OutOfProcess_SplitCall Then composition = composition.WithTestHostParts(Remote.Testing.TestHost.OutOfProcess) End If Dim workspace = TestWorkspace.CreateWorkspace(workspaceXml, composition:=composition) workspace.SetTestLogger(AddressOf helper.WriteLine) If sourceGenerator IsNot Nothing Then workspace.OnAnalyzerReferenceAdded(workspace.CurrentSolution.ProjectIds.Single(), New TestGeneratorReference(sourceGenerator)) End If Dim engineResult As RenameEngineResult = Nothing Try If workspace.Documents.Where(Function(d) d.CursorPosition.HasValue).Count <> 1 Then AssertEx.Fail("The test must have a single $$ marking the symbol being renamed.") End If Dim cursorDocument = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue) Dim cursorPosition = cursorDocument.CursorPosition.Value Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id) Dim symbol = RenameLocations.ReferenceProcessing.TryGetRenamableSymbolAsync(document, cursorPosition, CancellationToken.None).Result If symbol Is Nothing Then AssertEx.Fail("The symbol touching the $$ could not be found.") End If Dim result = GetConflictResolution(renameTo, workspace.CurrentSolution, symbol, renameOptions, host) If expectFailure Then Assert.NotNull(result.ErrorMessage) Return engineResult Else Assert.Null(result.ErrorMessage) End If engineResult = New RenameEngineResult(workspace, result, renameTo) engineResult.AssertUnlabeledSpansRenamedAndHaveNoConflicts() Catch ' Something blew up, so we still own the test workspace If engineResult IsNot Nothing Then engineResult.Dispose() Else workspace.Dispose() End If Throw End Try Return engineResult End Function Private Shared Function GetConflictResolution( renameTo As String, solution As Solution, symbol As ISymbol, renameOptions As SymbolRenameOptions, host As RenameTestHost) As ConflictResolution If host = RenameTestHost.OutOfProcess_SplitCall Then ' This tests that each portion of rename can properly marshal to/from the OOP process. It validates ' features that need to call each part independently and operate on the intermediary values. Dim locations = Renamer.FindRenameLocationsAsync( solution, symbol, renameOptions, CancellationToken.None).GetAwaiter().GetResult() Return locations.ResolveConflictsAsync(renameTo, nonConflictSymbols:=Nothing, cancellationToken:=CancellationToken.None).GetAwaiter().GetResult() Else ' This tests that rename properly works when the entire call is remoted to OOP and the final result is ' marshaled back. Return Renamer.RenameSymbolAsync( solution, symbol, renameTo, renameOptions, nonConflictSymbols:=Nothing, CancellationToken.None).GetAwaiter().GetResult() End If End Function Friend ReadOnly Property ConflictResolution As ConflictResolution Get Return _resolution End Get End Property Private Sub AssertUnlabeledSpansRenamedAndHaveNoConflicts() For Each documentWithSpans In _workspace.Documents.Where(Function(d) Not d.IsSourceGenerated) Dim oldSyntaxTree = _workspace.CurrentSolution.GetDocument(documentWithSpans.Id).GetSyntaxTreeAsync().Result For Each span In documentWithSpans.SelectedSpans Dim location = oldSyntaxTree.GetLocation(span) AssertLocationReferencedAs(location, RelatedLocationType.NoConflict) AssertLocationReplacedWith(location, _renameTo) Next Next End Sub Public Sub AssertLabeledSpansInStringsAndCommentsAre(label As String, replacement As String) AssertLabeledSpansAre(label, replacement, RelatedLocationType.NoConflict, isRenameWithinStringOrComment:=True) End Sub Public Sub AssertLabeledSpansAre(label As String, Optional replacement As String = Nothing, Optional type As RelatedLocationType? = Nothing, Optional isRenameWithinStringOrComment As Boolean = False) For Each location In GetLabeledLocations(label) If replacement IsNot Nothing Then If type.HasValue Then AssertLocationReplacedWith(location, replacement, isRenameWithinStringOrComment) End If End If If type.HasValue AndAlso Not isRenameWithinStringOrComment Then AssertLocationReferencedAs(location, type.Value) End If Next End Sub Public Sub AssertLabeledSpecialSpansAre(label As String, replacement As String, type As RelatedLocationType?) For Each location In GetLabeledLocations(label) If replacement IsNot Nothing Then If type.HasValue Then AssertLocationReplacedWith(location, replacement) AssertLocationReferencedAs(location, type.Value) End If End If Next End Sub Private Function GetLabeledLocations(label As String) As IEnumerable(Of Location) Dim locations As New List(Of Location) For Each document In _workspace.Documents Dim annotatedSpans = document.AnnotatedSpans If annotatedSpans.ContainsKey(label) Then Dim syntaxTree = _workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxTreeAsync().Result For Each span In annotatedSpans(label) locations.Add(syntaxTree.GetLocation(span)) Next End If Next If locations.Count = 0 Then _failedAssert = True AssertEx.Fail(String.Format("The label '{0}' was not mentioned in the test.", label)) End If Return locations End Function Private Sub AssertLocationReplacedWith(location As Location, replacementText As String, Optional isRenameWithinStringOrComment As Boolean = False) Try Dim documentId = ConflictResolution.OldSolution.GetDocumentId(location.SourceTree) Dim newLocation = ConflictResolution.GetResolutionTextSpan(location.SourceSpan, documentId) Dim newTree = ConflictResolution.NewSolution.GetDocument(documentId).GetSyntaxTreeAsync().Result Dim newToken = newTree.GetRoot.FindToken(newLocation.Start, findInsideTrivia:=True) Dim newText As String If newToken.Span = newLocation Then newText = newToken.ToString() ElseIf isRenameWithinStringOrComment AndAlso newToken.FullSpan.Contains(newLocation) Then newText = newToken.ToFullString().Substring(newLocation.Start - newToken.FullSpan.Start, newLocation.Length) Else newText = newTree.GetText().ToString(newLocation) End If Assert.Equal(replacementText, newText) Catch ex As XunitException _failedAssert = True Throw End Try End Sub Private Sub AssertLocationReferencedAs(location As Location, type As RelatedLocationType) Try Dim documentId = ConflictResolution.OldSolution.GetDocumentId(location.SourceTree) Dim reference = _unassertedRelatedLocations.SingleOrDefault( Function(r) r.ConflictCheckSpan = location.SourceSpan AndAlso r.DocumentId = documentId) Assert.NotNull(reference) Assert.True(type.HasFlag(reference.Type)) _unassertedRelatedLocations.Remove(reference) Catch ex As XunitException _failedAssert = True Throw End Try End Sub Private Sub Dispose() Implements IDisposable.Dispose ' Make sure we're cleaned up. Don't want the test harness crashing... GC.SuppressFinalize(Me) ' If we failed some other assert, we know we're going to have things left ' over. So let's just suppress these so we don't lose the root cause If Not _failedAssert Then If _unassertedRelatedLocations.Count > 0 Then AssertEx.Fail( "There were additional related locations that were unasserted:" + Environment.NewLine _ + String.Join(Environment.NewLine, From location In _unassertedRelatedLocations Let document = _workspace.CurrentSolution.GetDocument(location.DocumentId) Let spanText = document.GetTextSynchronously(CancellationToken.None).ToString(location.ConflictCheckSpan) Select $"{spanText} @{document.Name}[{location.ConflictCheckSpan.Start}..{location.ConflictCheckSpan.End})")) End If End If _workspace.Dispose() End Sub Protected Overrides Sub Finalize() If Not Environment.HasShutdownStarted Then Throw New Exception("Dispose was not called in a Rename test.") End If End Sub Public Sub AssertReplacementTextInvalid() Try Assert.False(_resolution.ReplacementTextValid) Catch ex As XunitException _failedAssert = True Throw End Try End Sub Public Sub AssertIsInvalidResolution() Assert.Null(_resolution) End Sub End Class End Namespace
CyrusNajmabadi/roslyn
src/EditorFeatures/Test2/Rename/RenameEngineResult.vb
Visual Basic
mit
13,056
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Expressions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions Public Class CastOperatorsKeywordRecommenderTests Private ReadOnly Property AllTypeConversionOperatorKeywords As String() Get Dim keywords As New List(Of String) From {"CType", "DirectCast", "TryCast"} For Each k In CastOperatorsKeywordRecommender.PredefinedKeywordList keywords.Add(SyntaxFacts.GetText(k)) Next Return keywords.ToArray() End Get End Property <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function DirectCastHelpTextTest() As Task Await VerifyRecommendationDescriptionTextIsAsync(<MethodBody>Return |</MethodBody>, "DirectCast", $"{VBFeaturesResources.DirectCast_function} {VBWorkspaceResources.Introduces_a_type_conversion_operation_similar_to_CType_The_difference_is_that_CType_succeeds_as_long_as_there_is_a_valid_conversion_whereas_DirectCast_requires_that_one_type_inherit_from_or_implement_the_other_type} DirectCast({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TryCastHelpTextTest() As Task Await VerifyRecommendationDescriptionTextIsAsync(<MethodBody>Return |</MethodBody>, "TryCast", $"{VBFeaturesResources.TryCast_function} {VBWorkspaceResources.Introduces_a_type_conversion_operation_that_does_not_throw_an_exception_If_an_attempted_conversion_fails_TryCast_returns_Nothing_which_your_program_can_test_for} TryCast({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function CTypeHelpTextTest() As Task Await VerifyRecommendationDescriptionTextIsAsync(<MethodBody>Return |</MethodBody>, "CType", $"{VBFeaturesResources.CType_function} {VBWorkspaceResources.Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type} CType({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function CBoolHelpTextTest() As Task Await VerifyRecommendationDescriptionTextIsAsync(<MethodBody>Return |</MethodBody>, "CBool", $"{String.Format(VBFeaturesResources._0_function, "CBool")} {String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "Boolean")} CBool({VBWorkspaceResources.expression}) As Boolean") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function NoneInClassDeclarationTest() As Task Await VerifyRecommendationsMissingAsync(<ClassDeclaration>|</ClassDeclaration>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllInStatementTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>|</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterReturnTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Return |</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterArgument1Test() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Goo(|</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterArgument2Test() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Goo(bar, |</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterBinaryExpressionTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Goo(bar + |</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterNotTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Goo(Not |</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterTypeOfTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>If TypeOf |</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterDoWhileTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Do While |</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterDoUntilTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Do Until |</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterLoopWhileTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody> Do Loop While |</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterLoopUntilTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody> Do Loop Until |</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterIfTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>If |</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterElseIfTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>ElseIf |</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterElseSpaceIfTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Else If |</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterErrorTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Error |</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterThrowTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Throw |</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterInitializerTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = |</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterArrayInitializerSquiggleTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = {|</MethodBody>, AllTypeConversionOperatorKeywords) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function AllAfterArrayInitializerCommaTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = {0, |</MethodBody>, AllTypeConversionOperatorKeywords) End Function <WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function NoneInDelegateCreationTest() As Task Dim code = <File> Module Program Sub Main(args As String()) Dim f1 As New Goo2( | End Sub Delegate Sub Goo2() Function Bar2() As Object Return Nothing End Function End Module </File> Await VerifyRecommendationsMissingAsync(code, AllTypeConversionOperatorKeywords) End Function End Class End Namespace
aelij/roslyn
src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/CastOperatorsKeywordRecommenderTests.vb
Visual Basic
apache-2.0
9,340
Imports SistFoncreagro.BussinessEntities Imports System.Data.SqlClient Imports System.Data Public Class CaracteristicaRepository : Inherits MasterDataAccess : Implements ICaracteristicaRepository Private Function SelectObjectFactory(ByVal command As SqlCommand) As List(Of Caracteristica) Dim lista As New List(Of Caracteristica) Using reader As SqlDataReader = MyBase.ExecuteReader(command) While reader.Read Dim _Caracteristica As New Caracteristica() With { .IdCaracteristica = reader.GetValue(0), .Descripcion = reader.GetValue(1), .HabilitarComentario = reader.GetValue(2), .IdFactor = reader.GetValue(3) } lista.Add(_Caracteristica) End While End Using Return lista End Function Public Sub DeleteCARACTERISTICA(ByVal IdCaracteristica As Integer) Implements ICaracteristicaRepository.DeleteCARACTERISTICA Dim command As SqlCommand = MyBase.CreateSPCommand("DeleteCARACTERISTICA") command.Parameters.AddWithValue("IdCaracteristica", IdCaracteristica) MyBase.ExecuteNonQuery(command) End Sub Public Function GetCARACTERISTICAByIdCaracteristica(ByVal IdCaracteristica As Integer) As BussinessEntities.Caracteristica Implements ICaracteristicaRepository.GetCARACTERISTICAByIdCaracteristica Dim command As SqlCommand = MyBase.CreateSPCommand("GetCARACTERISTICAByIdCaracteristica") command.Parameters.AddWithValue("IdCaracteristica", IdCaracteristica) Return SelectObjectFactory(command).SingleOrDefault End Function Public Function GetCARACTERISTICAByIdFactor(ByVal IdFactor As Integer) As System.Collections.Generic.List(Of BussinessEntities.Caracteristica) Implements ICaracteristicaRepository.GetCARACTERISTICAByIdFactor Dim command As SqlCommand = MyBase.CreateSPCommand("GetAllFromBANCO") command.Parameters.AddWithValue("IdFactor", IdFactor) Return SelectObjectFactory(command) End Function Public Sub SaveCARACTERISTICA(ByVal _Caracteristica As BussinessEntities.Caracteristica) Implements ICaracteristicaRepository.SaveCARACTERISTICA Dim command As SqlCommand = MyBase.CreateSPCommand("SaveCARACTERISTICA") command.Parameters.AddWithValue("Descripcion", _Caracteristica.Descripcion) command.Parameters.AddWithValue("HabilitarComentario", _Caracteristica.HabilitarComentario) command.Parameters.AddWithValue("IdCaracteristica", _Caracteristica.IdCaracteristica) command.Parameters.AddWithValue("IdFactor", _Caracteristica.IdFactor) MyBase.ExecuteReader(command) End Sub End Class
crackper/SistFoncreagro
SistFoncreagro.DataAccess/CaracteristicaRepository.vb
Visual Basic
mit
2,759
Imports SistFoncreagro.BussinessEntities Imports System.Data.SqlClient Imports System.Data Public Class TipoCtaBancariaRepository : Inherits MasterDataAccess : Implements ITipoCtaBancariaRepository Private Function SelectObjectFactory(ByVal command As SqlCommand) As List(Of TipoCtaBancaria) Dim lista As New List(Of TipoCtaBancaria) Using reader As SqlDataReader = MyBase.ExecuteReader(command) While reader.Read Dim _TipoCtaBancaria As New TipoCtaBancaria() With { .Descripcion = reader.GetValue(0), .IdTipoCtaBancaria = reader.GetValue(1) } lista.Add(_TipoCtaBancaria) End While End Using Return lista End Function Public Function GetAllFromTIPOCTABANCARIA() As System.Collections.Generic.List(Of BussinessEntities.TipoCtaBancaria) Implements ITipoCtaBancariaRepository.GetAllFromTIPOCTABANCARIA Dim command As SqlCommand = MyBase.CreateSPCommand("GetAllFromTIPOCTABANCARIA") Return SelectObjectFactory(command) End Function Public Function GetTIPOCTABANCARIAByIdTipoCtaBancaria(ByVal IdTipoCtaBancaria As Integer) As BussinessEntities.TipoCtaBancaria Implements ITipoCtaBancariaRepository.GetTIPOCTABANCARIAByIdTipoCtaBancaria Dim command As SqlCommand = MyBase.CreateSPCommand("GetTIPOCTABANCARIAByIdTipoCtaBancaria") command.Parameters.AddWithValue("IdTipoCtaBancaria", IdTipoCtaBancaria) Return SelectObjectFactory(command).SingleOrDefault End Function End Class
crackper/SistFoncreagro
SistFoncreagro.DataAccess/TipoCtaBancariaRepository.vb
Visual Basic
mit
1,596
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class start Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(start)) Me.Label1 = New System.Windows.Forms.Label() Me.Timer1 = New System.Windows.Forms.Timer(Me.components) Me.ProgressBar1 = New System.Windows.Forms.ProgressBar() Me.SuspendLayout() ' 'Label1 ' Me.Label1.AutoSize = True Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label1.ForeColor = System.Drawing.SystemColors.ControlLightLight Me.Label1.Location = New System.Drawing.Point(7, 9) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(265, 16) Me.Label1.TabIndex = 0 Me.Label1.Text = "Please wait, the application being analyzed" ' 'Timer1 ' Me.Timer1.Interval = 250 ' 'ProgressBar1 ' Me.ProgressBar1.Location = New System.Drawing.Point(10, 25) Me.ProgressBar1.Name = "ProgressBar1" Me.ProgressBar1.Size = New System.Drawing.Size(256, 12) Me.ProgressBar1.TabIndex = 1 ' 'start ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.Color.FromArgb(CType(CType(90, Byte), Integer), CType(CType(90, Byte), Integer), CType(CType(90, Byte), Integer)) Me.ClientSize = New System.Drawing.Size(278, 49) Me.Controls.Add(Me.ProgressBar1) Me.Controls.Add(Me.Label1) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.MaximizeBox = False Me.MinimizeBox = False Me.Name = "start" Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "Starting vFolderLocker" Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents Timer1 As System.Windows.Forms.Timer Friend WithEvents ProgressBar1 As System.Windows.Forms.ProgressBar End Class
DeVoresyah/vFolderLocker-Open-Source
start.Designer.vb
Visual Basic
mit
3,291
Module Module1 Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,) Dim length = a.GetLength(0) - 1 Dim result(length - 1, length - 1) As Double For i = 1 To length For j = 1 To length If i < x AndAlso j < y Then result(i - 1, j - 1) = a(i - 1, j - 1) ElseIf i >= x AndAlso j < y Then result(i - 1, j - 1) = a(i, j - 1) ElseIf i < x AndAlso j >= y Then result(i - 1, j - 1) = a(i - 1, j) Else result(i - 1, j - 1) = a(i, j) End If Next Next Return result End Function Function Det(a As Double(,)) As Double If a.GetLength(0) = 1 Then Return a(0, 0) Else Dim sign = 1 Dim sum = 0.0 For i = 1 To a.GetLength(0) sum += sign * a(0, i - 1) * Det(Minor(a, 0, i)) sign *= -1 Next Return sum End If End Function Function Perm(a As Double(,)) As Double If a.GetLength(0) = 1 Then Return a(0, 0) Else Dim sum = 0.0 For i = 1 To a.GetLength(0) sum += a(0, i - 1) * Perm(Minor(a, 0, i)) Next Return sum End If End Function Sub WriteLine(a As Double(,)) For i = 1 To a.GetLength(0) Console.Write("[") For j = 1 To a.GetLength(1) If j > 1 Then Console.Write(", ") End If Console.Write(a(i - 1, j - 1)) Next Console.WriteLine("]") Next End Sub Sub Test(a As Double(,)) If a.GetLength(0) <> a.GetLength(1) Then Throw New ArgumentException("The dimensions must be equal") End If WriteLine(a) Console.WriteLine("Permanant : {0}", Perm(a)) Console.WriteLine("Determinant: {0}", Det(a)) Console.WriteLine() End Sub Sub Main() Test({{1, 2}, {3, 4}}) Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}}) Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}}) End Sub End Module
ncoe/rosetta
Determinant_and_permanent/Visual Basic .NET/DeterminantAndPermanent/Module1.vb
Visual Basic
mit
2,370
Imports HomeSeerAPI Imports System Imports System.IO Imports System.Text Imports System.Runtime.Serialization Imports System.Runtime.Serialization.Formatters Friend Module Procedures Friend WithEvents API As Media_API = Nothing Friend Class WaitTaskClass Friend PeriodMS As Double Friend Finished As Boolean Sub Sandwiches() Dim MRE As New Threading.ManualResetEvent(False) If PeriodMS > 0 Then MRE.WaitOne(PeriodMS) End If Finished = True ' Set a return value in the return argument. End Sub End Class Friend Sub DoWait(ByVal WaitPeriodMS As Double) If WaitPeriodMS < 1 Then Exit Sub If WaitPeriodMS < 100 Then Threading.Thread.Sleep(WaitPeriodMS) Exit Sub End If Dim Tasks As New WaitTaskClass() Dim Thread1 As New System.Threading.Thread( _ AddressOf Tasks.Sandwiches) Tasks.PeriodMS = WaitPeriodMS Thread1.Start() ' Start the new thread. Thread1.Join() ' Wait for thread 1 to finish. End Sub Friend Function FormatTimeSpan(ByVal TS As TimeSpan, _ ByVal IncludeSeconds As Boolean, _ ByVal Scales As Boolean, _ ByVal LongScales As Boolean) As String Dim Res As String = "" Dim GotFront As Boolean = False Dim Y As Integer Dim D As Integer 'MsgBox(TS.ToString("%d' days, '%h' hours, '%m' minutes, '%s' seconds'")) 'MsgBox(TS.ToString("%d' Days, 'h\:mm\:ss")) 'MsgBox(TS.ToString("%d'd '%h'h '%m'm '%s\s")) If TS.Days <> 0 Then Y = Convert.ToInt32(TS.Days / 365.25) If Y > 0 Then GotFront = True D = Convert.ToInt32(TS.Days Mod 365.25) Res = Y.ToString If Scales Then If LongScales Then If Y = 1 Then Res &= " Year" Else Res &= " Years" End If Else Res &= "y" End If Else Res &= "-" End If Else D = TS.Days End If If GotFront Or D <> 0 Then If Scales Then Res &= IIf(GotFront, ", ", "") & D.ToString & IIf(LongScales, IIf(D = 1, " Day", " Days"), "d") GotFront = True Else If GotFront Then Res &= D.ToString("00") & "." Else GotFront = True Res &= D.ToString & "." End If End If End If End If If GotFront Or TS.Hours <> 0 Then If Scales Then Res &= IIf(GotFront, ", ", "") & TS.Hours.ToString & IIf(LongScales, IIf(TS.Hours = 1, " Hour", " Hours"), "h") GotFront = True Else Res &= TS.Hours.ToString & ":" GotFront = True End If End If If GotFront Or TS.Minutes <> 0 Then If Scales Then Res &= IIf(GotFront, ", ", "") & TS.Minutes.ToString & IIf(LongScales, IIf(TS.Minutes = 1, " Minute", " Minutes"), "m") GotFront = True Else If GotFront Then Res &= TS.Minutes.ToString("00") & IIf(IncludeSeconds, ":", "") Else GotFront = True Res &= TS.Minutes.ToString & IIf(IncludeSeconds, ":", "") End If End If End If If IncludeSeconds Then If Scales Then Res &= IIf(GotFront, ", ", "") & TS.Seconds.ToString & IIf(LongScales, IIf(TS.Seconds = 1, " Second", " Seconds"), "s") GotFront = True Else If GotFront Then Res &= TS.Seconds.ToString("00") Else Res &= TS.Seconds.ToString End If End If End If Return Res End Function Friend Function PlayerActionName(ByVal PC As Player_Action) As String Select Case PC Case Player_Action.player_play Return "Play" Case Player_Action.player_stop Return "Stop" Case Player_Action.player_pause Return "Pause" Case Player_Action.player_unpause Return "Resume" Case Player_Action.player_resume_if_paused Return "Resume If Paused" Case Player_Action.player_next Return "Next Media" Case Player_Action.player_prev Return "Previous Media" Case Player_Action.player_FastForward Return "Fast Forward" Case Player_Action.player_FastReverse Return "Fast Reverse" Case Player_Action.player_Jump_Forward Return "Jump Forward" Case Player_Action.player_Jump_Back Return "Jump Back" Case Player_Action.player_mute Return "Mute" Case Player_Action.player_unmute Return "Unmute" Case Player_Action.player_volume_up Return "Raise Volume" Case Player_Action.player_volume_down Return "Lower Volume" Case Player_Action.player_volume_set Return "Set Volume" Case Player_Action.player_enable_visuals Return "Show Media Player UI" Case Player_Action.player_hide_video Return "Hide Media Player UI" Case Player_Action.player_enable_fullscreen_visuals Return "Show Media Player UI Full Screen" Case Player_Action.player_disable_fullscreen_visuals Return "Restore Media Player UI" Case Else Return PC.ToString End Select End Function Friend Function SerializeObject(ByRef ObjIn As Object, ByRef bteOut() As Byte) As Boolean If ObjIn Is Nothing Then Return False Dim str As New MemoryStream Dim sf As New Binary.BinaryFormatter Try sf.Serialize(str, ObjIn) ReDim bteOut(Convert.ToInt32(str.Length - 1)) bteOut = str.ToArray Return True Catch ex As Exception Log(IFACE_NAME & " Error: Serializing object " & ObjIn.ToString & " EX:" & ex.Message, LogType.LOG_TYPE_ERROR) Return False End Try End Function Friend Function SerializeObject(ByRef ObjIn As Object, ByRef HexOut As String) As Boolean If ObjIn Is Nothing Then Return False Dim str As New MemoryStream Dim sf As New Binary.BinaryFormatter Dim bteOut() As Byte Try sf.Serialize(str, ObjIn) ReDim bteOut(Convert.ToInt32(str.Length - 1)) bteOut = str.ToArray HexOut = "" For i As Integer = 0 To bteOut.Length - 1 HexOut &= bteOut(i).ToString("x2").ToUpper Next Return True Catch ex As Exception Log(IFACE_NAME & " Error: Serializing (Hex) object " & ObjIn.ToString & " :" & ex.Message, LogType.LOG_TYPE_ERROR) Return False End Try End Function Friend Function DeSerializeObject(ByRef bteIn() As Byte, ByRef ObjOut As Object) As Boolean ' Almost immediately there is a test to see if ObjOut is NOTHING. The reason for this ' when the ObjOut is suppose to be where the deserialized object is stored, is that ' I could find no way to test to see if the deserialized object and the variable to ' hold it was of the same type. If you try to get the type of a null object, you get ' only a null reference exception! If I do not test the object type beforehand and ' there is a difference, then the InvalidCastException is thrown back in the CALLING ' procedure, not here, because the cast is made when the ByRef object is cast when this ' procedure returns, not earlier. In order to prevent a cast exception in the calling ' procedure that may or may not be handled, I made it so that you have to at least ' provide an initialized ObjOut when you call this - ObjOut is set to nothing after it ' is typed. If bteIn Is Nothing Then Return False If bteIn.Length < 1 Then Return False If ObjOut Is Nothing Then Return False Dim str As MemoryStream Dim sf As New Binary.BinaryFormatter Dim ObjTest As Object Dim TType As System.Type = Nothing Dim OType As System.Type = Nothing Try OType = ObjOut.GetType ObjOut = Nothing str = New MemoryStream(bteIn) ObjTest = sf.Deserialize(str) If ObjTest Is Nothing Then Return False TType = ObjTest.GetType If Not TType.Equals(OType) Then Return False ObjOut = ObjTest If ObjOut Is Nothing Then Return False Return True Catch exIC As InvalidCastException Return False Catch ex As Exception #If DEBUG Then Log("DeSerializing object from Bytes to " & IIf(OType Is Nothing, "(Unknown)", OType.ToString) & ": " & ex.Message, LogType.LOG_TYPE_ERROR) #End If Return False End Try End Function Friend Function DeSerializeObject(ByRef HexIn As String, ByRef ObjOut As Object) As Boolean ' Almost immediately there is a test to see if ObjOut is NOTHING. The reason for this ' when the ObjOut is suppose to be where the deserialized object is stored, is that ' I could find no way to test to see if the deserialized object and the variable to ' hold it was of the same type. If you try to get the type of a null object, you get ' only a null reference exception! If I do not test the object type beforehand and ' there is a difference, then the InvalidCastException is thrown back in the CALLING ' procedure, not here, because the cast is made when the ByRef object is cast when this ' procedure returns, not earlier. In order to prevent a cast exception in the calling ' procedure that may or may not be handled, I made it so that you have to at least ' provide an initialized ObjOut when you call this - ObjOut is set to nothing after it ' is typed. If HexIn Is Nothing Then Return False If String.IsNullOrEmpty(HexIn.Trim) Then Return False If ObjOut Is Nothing Then Return False Dim str As MemoryStream Dim sf As New Binary.BinaryFormatter Dim ObjTest As Object Dim TType As System.Type Dim OType As System.Type Dim bteIn() As Byte Dim HowMany As Integer Try HowMany = Convert.ToInt32((HexIn.Length / 2) - 1) ReDim bteIn(HowMany) For i As Integer = 0 To HowMany bteIn(i) = Convert.ToByte(HexIn.Substring(i * 2, 2)) Next OType = ObjOut.GetType ObjOut = Nothing str = New MemoryStream(bteIn) ObjTest = sf.Deserialize(str) If ObjTest Is Nothing Then Return False TType = ObjTest.GetType If Not TType.Equals(OType) Then Return False ObjOut = ObjTest If ObjOut Is Nothing Then Return False Return True Catch exIC As InvalidCastException Return False Catch ex As Exception #If DEBUG Then Log("DeSerializing object from Hex: " & ex.Message, LogType.LOG_TYPE_ERROR) #End If Return False End Try End Function Friend Function FixPath(ByVal fpath As String) As String #If Linux Then Return fpath.Replace("\", "/") #Else Return fpath.Replace("/", "\") #End If End Function Friend Sub GetSettings() Try ArtistVRCommand = hs.GetINISetting("Settings", "artistvr", "Play Artist", "MediaPlayer.ini") AlbumVRCommand = hs.GetINISetting("Settings", "albumvr", "Play Album", "MediaPlayer.ini") GenreVRCommand = hs.GetINISetting("Settings", "genrevr", "Play Genre", "MediaPlayer.ini") PlaylistVRCommand = hs.GetINISetting("Settings", "playlistvr", "Play Playlist", "MediaPlayer.ini") PlayerControlVRCommand = hs.GetINISetting("Settings", "playercontrolsvr", "Player", "MediaPlayer.ini") 'screenwidth = hs.GetINISetting("Display", "screenwidth", "1024", "settings.ini") Catch ex As Exception End Try Try bNoPLDupes = Convert.ToBoolean(hs.GetINISetting("Settings", "NoPLDupes", "True", "MediaPlayer.ini")) 'load_message_interval = Convert.ToInt32(hs.GetINISetting("Settings", "load_message_interval", "500", "MediaPlayer.ini")) 'load_message = Convert.ToBoolean(hs.GetINISetting("Settings", "load_message", "True", "MediaPlayer.ini")) Catch ex As Exception End Try 'Try ' If Not gHSPI.MusicAPI Is Nothing Then ' bNoPLDupes = bNoPLDupes ' End If 'Catch ex As Exception 'End Try Try bExtendedStatus = Convert.ToBoolean(hs.GetINISetting("Settings", "ExtendedStatus", "False", "MediaPlayer.ini")) Catch ex As Exception End Try Try gPauseAudio = Convert.ToBoolean(hs.GetINISetting("Settings", "gPauseAudio", "True", "MediaPlayer.ini")) Catch ex As Exception End Try Try gEnableVRCommands = Convert.ToBoolean(hs.GetINISetting("Settings", "gEnableVRCommands", "True", "MediaPlayer.ini")) Catch ex As Exception End Try Try gDetectDatabaseChanges = Convert.ToBoolean(hs.GetINISetting("Settings", "gDetectDatabaseChanges", "True", "MediaPlayer.ini")) Catch ex As Exception End Try End Sub Friend Function sn(ByVal sIN As String) As Boolean If sIN Is Nothing Then Return True Return String.IsNullOrEmpty(sIN.Trim) End Function Friend Function sna(ByVal sIN As String) As Boolean If sIN Is Nothing Then Return True If String.IsNullOrEmpty(sIN.Trim) Then Return True If sIN.Trim = "*" Then Return True Return False End Function Friend Function fixs(ByVal sIN As String) As String If sIN Is Nothing Then Return "" Return sIN.Trim End Function Friend Function fixs(ByRef AO As ActionObject) As ActionObject If AO Is Nothing Then AO = New ActionObject Return AO End If AO.Album = fixs(AO.Album) AO.Artist = fixs(AO.Artist) AO.Genre = fixs(AO.Genre) AO.MediaLib = fixs(AO.MediaLib) AO.Playlist = fixs(AO.Playlist) AO.Title = fixs(AO.Title) Return AO End Function Friend Function WB(ByVal sIn As String) As String If sIn Is Nothing Then Return "" Return "<b>" & sIn & "</b>" End Function Friend Function GetHSMediaNameFromEnum(ByVal MT As eLib_Media_Type) As String Select Case MT Case eLib_Media_Type.Unknown_Error Return "Unknown" Case eLib_Media_Type.Music Return "Music/Audio" Case eLib_Media_Type.Video Return "Video" Case eLib_Media_Type.Music_Stream Return "Music Stream" Case eLib_Media_Type.Video_Stream Return "Video Stream" Case eLib_Media_Type.Photo Return "Photo" Case eLib_Media_Type.Radio Return "Radio" Case eLib_Media_Type.Radio_Stream Return "Radio Stream" Case eLib_Media_Type.Playlist Return "Playlist" Case eLib_Media_Type.Other_09 Return "Other 9" Case eLib_Media_Type.Other_10 Return "Other 10" Case eLib_Media_Type.Other_11 Return "Other 11" Case eLib_Media_Type.Other_12 Return "Other 12" Case eLib_Media_Type.Other_13 Return "Other 13" Case eLib_Media_Type.Other_14 Return "Other 14" Case eLib_Media_Type.Other_15 Return "Other 15" Case eLib_Media_Type.Any_All Return "Any/All Media Types" Case Else Return "Error" End Select End Function Friend Function GetHSMediaEnumFromWMPName(ByVal sMedia As String) As eLib_Media_Type If sn(sMedia) Then Return eLib_Media_Type.Unknown_Error Dim mt As eWMPMediaTypes = eWMPMediaTypes.Unknown Try mt = GetWMPMediaEnumFromName(sMedia) Select Case mt Case eWMPMediaTypes.Unknown Return eLib_Media_Type.Unknown_Error Case eWMPMediaTypes.Audio Return eLib_Media_Type.Music Case eWMPMediaTypes.Other Return eLib_Media_Type.Other_09 Case eWMPMediaTypes.Photo Return eLib_Media_Type.Photo Case eWMPMediaTypes.Playlist Return eLib_Media_Type.Playlist Case eWMPMediaTypes.Radio Return eLib_Media_Type.Radio Case eWMPMediaTypes.Video Return eLib_Media_Type.Video Case eWMPMediaTypes.NoWMP_CDPlaylist Return eLib_Media_Type.Other_10 Case eWMPMediaTypes.NoWMP_CDTrack Return eLib_Media_Type.Other_11 Case eWMPMediaTypes.NoWMP_CommonFile Return eLib_Media_Type.Other_12 Case eWMPMediaTypes.NoWMP_DVD Return eLib_Media_Type.Other_13 Case eWMPMediaTypes.NoWMP_MusicFile Return eLib_Media_Type.Music Case Else Return eLib_Media_Type.Unknown_Error End Select Catch ex As Exception Return eLib_Media_Type.Unknown_Error End Try End Function Friend Function GetWMPMediaEnumFromName(ByVal sMedia As String) As eWMPMediaTypes 'Audio Other Photo Playlists Radio Video CD Playlist CD Track Common File DVD Music File If sMedia Is Nothing Then Return eWMPMediaTypes.Unknown If String.IsNullOrEmpty(sMedia.Trim) Then Return eWMPMediaTypes.Unknown Select Case sMedia.Trim.ToLower Case "audio" Return eWMPMediaTypes.Audio Case "other" Return eWMPMediaTypes.Other Case "photo" Return eWMPMediaTypes.Photo Case "playlist", "playlists", "wpl" Return eWMPMediaTypes.Playlist Case "radio" Return eWMPMediaTypes.Radio Case "video" Return eWMPMediaTypes.Video Case "cd playlist" Return eWMPMediaTypes.NoWMP_CDPlaylist Case "cd track" Return eWMPMediaTypes.NoWMP_CDTrack Case "common file" Return eWMPMediaTypes.NoWMP_CommonFile Case "dvd" Return eWMPMediaTypes.NoWMP_DVD Case "music file" Return eWMPMediaTypes.NoWMP_MusicFile Case Else Return eWMPMediaTypes.Unknown End Select End Function Friend Sub ShutDownPlayerStatus() Dim dv As Object 'DeviceClass Dim dvalbum As Object 'DeviceClass Dim st As String Dim blankimage As String = "" ' "<img border=""0"" src=""/MediaPlayer/images/blank.gif"">" Try st = blankimage & "Playing " & WB("System Shutdown") & "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;By " & WB("HomeSeer Technologies, LLC") dv = GetOurDevice(DR(DeviceTypeInfo.eDeviceType_Media.Player_Status)) If Not dv Is Nothing Then hs.SetDeviceString(dv.hc & dv.dc, st, True) End If st = blankimage & "" dvalbum = GetOurDevice(DR(DeviceTypeInfo.eDeviceType_Media.Media_Album)) hs.SetDeviceString(dvalbum.hc & dvalbum.dc, st, True) st = blankimage & "Temporarily Muted" dv = GetOurDevice(DR(DeviceTypeInfo.eDeviceType_Media.Player_Volume)) If Not dv Is Nothing Then hs.SetDeviceString(dv.hc & dv.dc, st, True) End If st = blankimage & "" dv = GetOurDevice(DR(DeviceTypeInfo.eDeviceType_Media.Player_Shuffle)) If Not dv Is Nothing Then hs.SetDeviceString(dv.hc & dv.dc, st, True) End If st = blankimage & "Disabled" dv = GetOurDevice(DR(DeviceTypeInfo.eDeviceType_Media.Player_Repeat)) If Not dv Is Nothing Then hs.SetDeviceString(dv.hc & dv.dc, st, True) End If st = blankimage & "Plug-In Shutdown-Restart" dv = GetOurDevice(DR(DeviceTypeInfo.eDeviceType_Media.Player_Status_Additional)) If Not dv Is Nothing Then hs.SetDeviceString(dv.hc & dv.dc, st, True) hs.SetDeviceLastChange(dv.hc & dv.dc, Now) End If Catch ex As Exception End Try End Sub Function RemoveNonAlpha(ByVal st As String) As String Dim i As Integer Dim st_out As New StringBuilder Dim ch As String For i = 1 To Len(st) ch = Mid(st, i, 1) If IsAlpha(ch) Then st_out.Append(ch) End If Next Return st_out.ToString End Function Public Function Valid(ByVal sIn As String) As Boolean If sIn Is Nothing Then Return False If ((sIn <> "") And (sIn <> "No Action")) Then Return True End If Return False End Function ' for VR commands, only allow: ' 0-9 ' a->z ' A->Z ' space Function IsAlpha(ByVal ch As String) As Boolean Dim chi As Integer = Asc(ch) If (chi >= 65 And chi <= 90) Or _ (chi >= 97 And chi <= 122) Or _ (chi >= &H30 And chi <= &H39) Or _ chi = &H20 Then Return True Else Return False End If End Function Public Sub Log(ByVal msg As String, ByVal logType As LogType) Try If msg Is Nothing Then msg = "" If Not [Enum].IsDefined(GetType(LogType), logType) Then logType = logType.LOG_TYPE_ERROR End If Dim sWhat As String = IFACE_NAME If Instance Is Nothing Then Instance = "" If Not String.IsNullOrEmpty(Instance.Trim) Then sWhat &= "-" & Instance.Trim End If Select Case logType Case logType.LOG_TYPE_ERROR hs.WriteLog(sWhat & " ERROR", msg) WriteDebug(msg) Case logType.LOG_TYPE_WARNING hs.WriteLog(sWhat & " Warning", msg) WriteDebug(msg) Case logType.LOG_TYPE_INFO hs.WriteLog(sWhat, msg) Case logType.LOG_TYPE_DEBUG WriteDebug(msg) End Select Catch ex As Exception Console.WriteLine("Exception in LOG of " & IFACE_NAME & ": " & ex.Message) End Try End Sub Friend Function WMPTriggerName(ByVal Trig As WMPTriggers) As String Select Case Trig Case WMPTriggers.Idle Return "Media Player becomes Idle" Case WMPTriggers.Playing Return "Media Player starts Playing" Case WMPTriggers.Stopped Return "Media Player Stops" Case WMPTriggers.Paused Return "Media Player becomes Paused" Case WMPTriggers.Forwarding Return "Media Player starts Fast Forwarding" Case WMPTriggers.Rewinding Return "Media Player starts Rewinding" Case WMPTriggers.MediaEnding Return "Media Player Media is Ending" Case WMPTriggers.MediaStarting Return "Media Player Media is Starting" Case WMPTriggers.Waiting Return "Media Player enters a Waiting State" Case WMPTriggers.Playlist_Changed Return "Media Player Playlist Changes" Case WMPTriggers.Library_Updating Return "Media Player Library starts Updating" Case Else Return "ERROR" End Select End Function Friend Function WMPConditionName(ByVal Cond As WMPConditions) As String Select Case Cond Case WMPConditions.Idle Return "Media Player Is Idle" Case WMPConditions.Playing Return "Media Player Is Playing" Case WMPConditions.Stopped Return "Media Player Is Stopped" Case WMPConditions.Paused Return "Media Player Is Paused" Case WMPConditions.Waiting Return "Media Player Is Waiting" Case Else Return "ERROR" End Select End Function Public Sub WriteDebug(ByVal msg As String) If Not gDebug Then Exit Sub If Instance Is Nothing Then Instance = "" Console.WriteLine(Format(Now, TIME_STAMP) & ":" & msg) If Not IO.Directory.Exists(FixPath(gEXEPath & "\Debug Logs")) Then IO.Directory.CreateDirectory(FixPath(gEXEPath & "\Debug Logs")) End If Try My.Computer.FileSystem.WriteAllText(FixPath(gEXEPath & "\Debug Logs\" & IFACE_NAME & IIf(String.IsNullOrEmpty(Instance.Trim), "", "-" & Instance.Trim) & ".log"), Format(Now, TIME_STAMP) & vbTab & msg & vbCrLf, True) Catch ex As Exception End Try End Sub Friend Function GetTriggerObject(ByRef TrigInfo As HomeSeerAPI.IPlugInAPI.strTrigActInfo) As TriggerObject If Triggers Is Nothing Then Triggers = New Collections.Concurrent.ConcurrentDictionary(Of String, TriggerObject) If TrigInfo.Instance Is Nothing Then TrigInfo.Instance = "" Dim sKey As String = "K" & TrigInfo.evRef.ToString & "_" & TrigInfo.TANumber.ToString & "_" & TrigInfo.SubTANumber.ToString & "_" & TrigInfo.Instance Dim TObj As TriggerObject = Nothing Try TObj = Triggers.Item(sKey) Catch ex As Exception TObj = Nothing End Try If TObj Is Nothing Then If TrigInfo.DataIn IsNot Nothing AndAlso TrigInfo.DataIn.Length > 5 Then TObj = New TriggerObject Try If Not DeSerializeObject(TrigInfo.DataIn, TObj) Then TObj = New TriggerObject TObj.Condition = False TObj.evRef = TrigInfo.evRef TObj.Instance = TrigInfo.Instance TObj.SubTANumber = TrigInfo.SubTANumber TObj.TANumber = TrigInfo.TANumber Try Triggers.TryAdd(sKey, TObj) Catch ex As Exception End Try End If Catch ex As Exception TObj = New TriggerObject TObj.Condition = False TObj.evRef = TrigInfo.evRef TObj.Instance = TrigInfo.Instance TObj.SubTANumber = TrigInfo.SubTANumber TObj.TANumber = TrigInfo.TANumber Try Triggers.TryAdd(sKey, TObj) Catch ex2 As Exception End Try End Try Else TObj = New TriggerObject TObj.Condition = False TObj.evRef = TrigInfo.evRef TObj.Instance = TrigInfo.Instance TObj.SubTANumber = TrigInfo.SubTANumber TObj.TANumber = TrigInfo.TANumber Try Triggers.TryAdd(sKey, TObj) Catch ex As Exception End Try End If End If Return TObj End Function Friend Function GetTriggerObject(ByVal sKey As String) As TriggerObject If Triggers Is Nothing Then Triggers = New Collections.Concurrent.ConcurrentDictionary(Of String, TriggerObject) Try Return Triggers.Item(sKey) Catch ex As Exception Return Nothing End Try End Function Friend Sub SaveTriggerObject(ByRef TrigInfo As HomeSeerAPI.IPlugInAPI.strTrigActInfo, ByRef TObj As TriggerObject) If TObj Is Nothing Then Exit Sub If Triggers Is Nothing Then Triggers = New Collections.Concurrent.ConcurrentDictionary(Of String, TriggerObject) If TrigInfo.Instance Is Nothing Then TrigInfo.Instance = "" Dim sKey As String = "K" & TrigInfo.evRef.ToString & "_" & TrigInfo.TANumber.ToString & "_" & TrigInfo.SubTANumber.ToString & "_" & TrigInfo.Instance If Triggers.ContainsKey(sKey) Then Triggers.Item(sKey) = TObj Else Try Triggers.TryAdd(sKey, TObj) Catch ex As Exception End Try End If Dim bte() As Byte = Nothing Try If SerializeObject(TObj, bte) Then TrigInfo.DataIn = bte End If Catch ex As Exception End Try End Sub Friend Function SaveTriggerObject(ByVal sKey As String, ByRef TObj As TriggerObject) As Byte() If TObj Is Nothing Then Return Nothing If Triggers Is Nothing Then Triggers = New Collections.Concurrent.ConcurrentDictionary(Of String, TriggerObject) If Triggers.ContainsKey(sKey) Then Triggers.Item(sKey) = TObj Else Try Triggers.TryAdd(sKey, TObj) Catch ex As Exception End Try End If Dim bte() As Byte = Nothing Try If SerializeObject(TObj, bte) Then Return bte End If Catch ex As Exception End Try Return Nothing End Function End Module
HomeSeer/HSPI_MEDIAPLAYER
Globals/Procedures.vb
Visual Basic
mit
31,001
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> Partial Class frmStockMultiCost #Region "Windows Form Designer generated code " <System.Diagnostics.DebuggerNonUserCode()> Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() End Sub 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> Protected Overloads Overrides Sub Dispose(ByVal Disposing As Boolean) If Disposing Then If Not components Is Nothing Then components.Dispose() End If End If MyBase.Dispose(Disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer Public ToolTip1 As System.Windows.Forms.ToolTip Public WithEvents cmdClose As System.Windows.Forms.Button Public WithEvents cmdFilter As System.Windows.Forms.Button Public WithEvents cmdPrint As System.Windows.Forms.Button Public WithEvents lblHeading As System.Windows.Forms.Label Public WithEvents picButtons As System.Windows.Forms.Panel Public WithEvents grdDataGrid As myDataGridView '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.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(frmStockMultiCost)) Me.components = New System.ComponentModel.Container() Me.ToolTip1 = New System.Windows.Forms.ToolTip(components) Me.picButtons = New System.Windows.Forms.Panel Me.cmdClose = New System.Windows.Forms.Button Me.cmdFilter = New System.Windows.Forms.Button Me.cmdPrint = New System.Windows.Forms.Button Me.lblHeading = New System.Windows.Forms.Label Me.grdDataGrid = New myDataGridView Me.picButtons.SuspendLayout() Me.SuspendLayout() Me.ToolTip1.Active = True CType(Me.grdDataGrid, System.ComponentModel.ISupportInitialize).BeginInit() Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle Me.Text = "Edit Stock Item Costs" Me.ClientSize = New System.Drawing.Size(565, 493) Me.Location = New System.Drawing.Point(73, 22) Me.ControlBox = False Me.KeyPreview = True Me.MaximizeBox = False Me.MinimizeBox = False Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.SystemColors.Control Me.Enabled = True Me.Cursor = System.Windows.Forms.Cursors.Default Me.RightToLeft = System.Windows.Forms.RightToLeft.No Me.ShowInTaskbar = True Me.HelpButton = False Me.WindowState = System.Windows.Forms.FormWindowState.Normal Me.Name = "frmStockMultiCost" Me.picButtons.Dock = System.Windows.Forms.DockStyle.Top Me.picButtons.BackColor = System.Drawing.Color.Blue Me.picButtons.ForeColor = System.Drawing.SystemColors.WindowText Me.picButtons.Size = New System.Drawing.Size(565, 68) Me.picButtons.Location = New System.Drawing.Point(0, 0) Me.picButtons.TabIndex = 1 Me.picButtons.TabStop = False Me.picButtons.CausesValidation = True Me.picButtons.Enabled = True Me.picButtons.Cursor = System.Windows.Forms.Cursors.Default Me.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No Me.picButtons.Visible = True Me.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.None Me.picButtons.Name = "picButtons" Me.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter Me.cmdClose.Text = "E&xit" Me.cmdClose.Size = New System.Drawing.Size(73, 62) Me.cmdClose.Location = New System.Drawing.Point(489, 3) Me.cmdClose.TabIndex = 4 Me.cmdClose.BackColor = System.Drawing.SystemColors.Control Me.cmdClose.CausesValidation = True Me.cmdClose.Enabled = True Me.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdClose.Cursor = System.Windows.Forms.Cursors.Default Me.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdClose.TabStop = True Me.cmdClose.Name = "cmdClose" Me.cmdFilter.TextAlign = System.Drawing.ContentAlignment.MiddleCenter Me.cmdFilter.Text = "&Filter" Me.cmdFilter.Size = New System.Drawing.Size(73, 29) Me.cmdFilter.Location = New System.Drawing.Point(411, 3) Me.cmdFilter.TabIndex = 3 Me.cmdFilter.TabStop = False Me.cmdFilter.BackColor = System.Drawing.SystemColors.Control Me.cmdFilter.CausesValidation = True Me.cmdFilter.Enabled = True Me.cmdFilter.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdFilter.Cursor = System.Windows.Forms.Cursors.Default Me.cmdFilter.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdFilter.Name = "cmdFilter" Me.cmdPrint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter Me.cmdPrint.Text = "&Print" Me.cmdPrint.Size = New System.Drawing.Size(73, 29) Me.cmdPrint.Location = New System.Drawing.Point(411, 36) Me.cmdPrint.TabIndex = 2 Me.cmdPrint.TabStop = False Me.cmdPrint.BackColor = System.Drawing.SystemColors.Control Me.cmdPrint.CausesValidation = True Me.cmdPrint.Enabled = True Me.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default Me.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdPrint.Name = "cmdPrint" Me.lblHeading.BackColor = System.Drawing.Color.FromARGB(192, 192, 255) Me.lblHeading.Text = "Using the ""Stock Item Selector"" ....." Me.lblHeading.Size = New System.Drawing.Size(403, 61) Me.lblHeading.Location = New System.Drawing.Point(3, 3) Me.lblHeading.TabIndex = 5 Me.lblHeading.TextAlign = System.Drawing.ContentAlignment.TopLeft Me.lblHeading.Enabled = True Me.lblHeading.ForeColor = System.Drawing.SystemColors.ControlText Me.lblHeading.Cursor = System.Windows.Forms.Cursors.Default Me.lblHeading.RightToLeft = System.Windows.Forms.RightToLeft.No Me.lblHeading.UseMnemonic = True Me.lblHeading.Visible = True Me.lblHeading.AutoSize = False Me.lblHeading.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D Me.lblHeading.Name = "lblHeading" 'grdDataGrid.OcxState = CType(resources.GetObject("grdDataGrid.OcxState"), System.Windows.Forms.AxHost.State) Me.grdDataGrid.Dock = System.Windows.Forms.DockStyle.Top Me.grdDataGrid.Size = New System.Drawing.Size(565, 233) Me.grdDataGrid.Location = New System.Drawing.Point(0, 68) Me.grdDataGrid.TabIndex = 0 Me.grdDataGrid.Name = "grdDataGrid" Me.Controls.Add(picButtons) Me.Controls.Add(grdDataGrid) Me.picButtons.Controls.Add(cmdClose) Me.picButtons.Controls.Add(cmdFilter) Me.picButtons.Controls.Add(cmdPrint) Me.picButtons.Controls.Add(lblHeading) CType(Me.grdDataGrid, System.ComponentModel.ISupportInitialize).EndInit() Me.picButtons.ResumeLayout(False) Me.ResumeLayout(False) Me.PerformLayout() End Sub #End Region End Class
nodoid/PointOfSale
VB/4PosBackOffice.NET/frmStockMultiCost.Designer.vb
Visual Basic
mit
7,071
Imports Keysight.Visa Imports Ivi.Visa Imports NLog Imports NLog.Logger Imports Transporter_AEHF.Objects.Enumerations Imports NationalInstruments Public Class MySignalFinder ' Public PositionerControl As PositionerForm2 ' Public Main As Main ' Public Amplitude As String, PositionerAzimuth As Double ' Public DirectionFinderThread As New Threading.Thread(AddressOf DirectionFinder) 'for running survey and allowing control to work ' Public ClosingDirectionFinderThread As Boolean = False ' Public SigLocker As New Object ' Public MySigFinderForm As MySignalFinderForm ' Public InvalidAzimuth As Double = 999999.999999 ' Public FirstTime As Boolean = True ' Public StateRun As Boolean = False ' Dim _mode As ScanMode ' Dim _conectionString As String = "" '"TCPIP0::169.254.209.88::inst0::INSTR" ' Dim _findFrequency As String ' Public AzrSession As TcpipSession ' Public PositionerCorrectionForNorth As Double = 0 ' Public DataController As DataController ' Public MarkerArry() As String ' Public FreqIdx As Integer = 0 ' Public LevelIdx As Integer = 1 ' Public MarkerTrace As Integer = 1 ' Public SpinPositionerThread As New Threading.Thread(AddressOf SpinPositioner) ' Private Shared _log As Logger = LogManager.GetCurrentClassLogger() ' Public ClosingSpinPositionerthread As Boolean = False ' Public Sub New(ByRef aMain As Main, ByVal newConnectionString As String, Optional ByVal centerFrequency As String = Nothing) 'passing the connection string avoids cross threading problems ' _log.Debug(aMain.LoggerComboBox.Text & " -Starting sub 'New()'.") ' Me.Main = aMain ' 'Me.PositionerControl = New PositionerForm2("ASRL" & Trim(Me.Main.ToolStripTextBoxPosSerPortNum.Text) & "::INSTR", Me.Main.signalStartedOnce, Me.Main.preventCableWrap) ' If Me.Main.signalStartedOnce = False Then ' Me.Main.signalStartedOnce = True ' Me.Main.cmbBxPositionerStartedOnce.Text = "True" ' End If ' Me.DataController = New DataController ' Me.mySigFinderForm = New MySignalFinderForm(Me) ' Me.updateRadialLabels() ' Me.mySigFinderForm.Visible = True ' _mode = ScanMode.Continuous ' _conectionString = NewConnectionString ' Try ' Dim mgr = New ResourceManager ' Me.AzrSession = CType(mgr.Open(_conectionString), MessageBasedSession) ' Catch ex As Exception ' MsgBox("Exception occured. Most likely cause is the software could not make connection with analyzer.", MsgBoxStyle.MsgBoxSetForeground) ' End Try ' _findFrequency = CenterFrequency ' Me.markerTrace = Me.Main.missionObj.getSearchAnalyzerClass.getMarkerTraceAssignment ' _log.Debug(aMain.LoggerComboBox.Text & " -Ending sub 'New()'.") ' End Sub ' Public Sub UpdateRadialLabels() ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Starting sub 'updateRadialLabels().") ' Try ' 'come up with the offset for the top label ' Dim tempLabel As Double = System.Math.Round(CDbl(Trim(Me.Main.Van_Heading.Text)), 0) ' Dim positionerOffset As Double = System.Math.Round(CDbl(Trim(Me.Main.PositionerOffset.Text)), 0) ' 'ensure the positioner offset is >0 for the math to stay correct ' While (positionerOffset < 0) ' positionerOffset += 360 ' End While ' positionerCorrectionForNorth = tempLabel + positionerOffset ' 'now put a tick mark on the plot where the front of the van is ' Dim vanFront As Double = System.Math.Round(CDbl(Trim(Me.Main.Van_Heading.Text)), 0) ' While vanFront >= 360 ' vanFront -= 360 ' End While ' Dim polarMuliplier As Double = Double.Parse(Me.mySigFinderForm.cmbMultiplier.Text) ' Dim blankingLineLength As Double = PolarMuliplier * 9 / 16 ' Dim tickLength As Double = PolarMuliplier * 12 / 16 ' Me.mySigFinderForm.TickLine.ClearData() ' Me.mySigFinderForm.TickLine.PlotXYAppend(0, 0) ' Me.mySigFinderForm.TickLine.PlotXYAppend(tickLength * System.Math.Sin(vanFront * System.Math.PI / 180), tickLength * System.Math.Cos(vanFront * System.Math.PI / 180)) ' 'Me.mySigFinderForm.BlankingLine.PlotXYAppend(0, 0) ' 'Me.mySigFinderForm.BlankingLine.PlotXYAppend(blankingLineLength * System.Math.Sin(vanFront * System.Math.PI / 180), blankingLineLength * System.Math.Cos(vanFront * System.Math.PI / 180)) ' Catch ex As Exception ' _log.Error(Me.Main.LoggerComboBox.Text & " -Error in sub 'updateRadialLabels()' updating azimuth labels on radial plot. " & ex.Message) ' MsgBox("Error updating azimuth labels on radial plot. " & ex.Message, MsgBoxStyle.MsgBoxSetForeground) ' End Try ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Ending sub 'updateRadialLabels()'.") ' End Sub ' Function ShowAzrTrace() As Boolean ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Starting function 'ShowAZRTrace()'.") ' Try ' Dim mTrace As Trace = GetXSeriesTraceBinary4(4, ' Transporter_AEHF.Main.MXAPXATrace.TRACE1, ' Me.Main.MissionObj.GetSearchAnalyzerClass.GetMarkerTraceAssignment, ' Me.Main.MissionObj.GetAnalyzer(Me.Main.cmbBxSearchAzr.SelectedIndex).GetAnalyzerModel) ' Dim currentTraceData As Double(,) = DataArrayConverterDoubles(mTrace) ' ' Dim ScaledData As Double(,) = Main.ScaleData(CurrentTraceData, Main.CALData4, Main.AntennaData4) ' Dim scaledData As Double(,) = CurrentTraceData ' If mTrace.StartFrequency = mTrace.StopFrequency Then ' '0 span change axis ' Dim numPoints As Integer = mTrace.DataSingles.Length ' Dim sweepTime As Double = mTrace.SweepTime ' For ii As Integer = 0 To numPoints - 1 ' ScaledData(0, ii) = ii * sweepTime / numPoints ' Next ' Me.mySigFinderForm.ScatterPlot1.XAxis.Range = New NationalInstruments.UI.Range(0, sweepTime) ' End If ' Me.mySigFinderForm.ScatterPlot1.PlotXY(Analysis.Math.ArrayOperation.CopyRow(ScaledData, 0), Analysis.Math.ArrayOperation.CopyRow(ScaledData, 1)) ' Me.mySigFinderForm.DataScatterGraph.Refresh() ' Return True ' Catch ex As Exception ' _log.Error(Me.Main.LoggerComboBox.Text & " -Error in function 'ShowAZRTrace()': " & ex.Message) ' MsgBox("Error grabbing trace in signal finder. " & ex.Message) ' End Try ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Ending function 'ShowAZRTrace()'.") ' End Function ' Sub DirectionFinder() ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Starting sub 'DirectionFinder()'.") ' Try ' Control.CheckForIllegalCrossThreadCalls = False ' Dim elevation As Double = 0 ' Dim speed As Double = CDbl(Me.mySigFinderForm.cmbPanSpeed.Text) ' Dim amplitude As String ' 'Dim PositionerAzimuth As Double ' Me.mySigFinderForm.Frequency.Text = Main.searchFreq ' Select Case _mode ' Case ScanMode.Continuous ' If Not _findFrequency = Nothing Then ' AzrSession.FormattedIO.WriteLine("FREQuency:CENTer " + _findFrequency + " MHz") ' End If ' AzrSession.FormattedIO.WriteLine("FREQuency:CENTer?") ' _findFrequency = AzrSession.FormattedIO.ReadString ' Me.mySigFinderForm.Frequency.Text = System.Math.Round((CDbl(_findFrequency) / 10 ^ 6), 2).ToString ' 'AzrSession.Write("CALCulate:MARKer:X " + FindFrequency) ' Try ' With Me.mySigFinderForm ' .numUpDwnCenterFreq.Value = _findFrequency / 10 ^ 6 ' AzrSession.FormattedIO.WriteLine("FREQuency:SPAN?") ' .numUpDwnSpan.Value = AzrSession.FormattedIO.ReadString() / 10 ^ 6 ' AzrSession.FormattedIO.WriteLine("Bandwidth:Resolution?") ' .numUpDwnRBW.Value = AzrSession.FormattedIO.ReadString() / 10 ^ 6 ' AzrSession.FormattedIO.WriteLine("sweep:points?") ' .numUpDwnNumPoints.Value = AzrSession.FormattedIO.ReadString() ' Dim tmp As String = "" ' Dim tmp1 As String = "" ' If Me.Main.missionObj.getAnalyzer(Me.Main.cmbBxSearchAzr.SelectedIndex).getAnalyzerModel = Enumerations.AnalyzerModels.AgilentFieldFox Then ' AzrSession.FormattedIO.WriteLine(":SENSe:SWEep:ACQuisition:AUTO?") ' tmp = AzrSession.FormattedIO.ReadString() ' AzrSession.FormattedIO.WriteLine(":SENSe:SWEep:ACQ?") ' tmp1 = AzrSession.FormattedIO.ReadString() ' .numUpDwnSeepTime.Value = tmp1 ' Else ' AzrSession.FormattedIO.WriteLine(":SWEep:TIME:AUTO?") ' tmp = AzrSession.FormattedIO.ReadString() ' AzrSession.FormattedIO.WriteLine(":SENSe:SWEep:TIME?") ' tmp1 = AzrSession.FormattedIO.ReadString() ' .numUpDwnSeepTime.Value = tmp1 * 10 ^ 3 ' End If ' If tmp.Contains("1") Then ' .chkBxAutoSwpTime.Checked = True ' Else ' .chkBxAutoSwpTime.Checked = False ' End If ' .numUpDwnSpeedRPM.Value = 500 * Me.PositionerControl.DegreesPerPanPosition * 60 / 360 ' Me.markerArry = Me.DataController.getMarkerValue(Me.markerTrace, Me.AzrSession, Me.Main.missionObj.getAnalyzer(Me.Main.cmbBxSearchAzr.SelectedIndex).getAnalyzerModel, False) ' .numUpDwnMarkerFreq.Value = Me.markerArry(Me.freqIdx) / 10 ^ 6 ' 'RPM = Pan Speed (PS) * DegreesPerPanPosition* 60secondsPerMinute /360degreesPerRevolution ' End With ' Catch ex As Exception ' _log.Error(Me.Main.LoggerComboBox.Text & " -Error in sub 'DirectionFinder()' configuring azr settings on signal finder form: " & ex.Message) ' End Try ' 'PositionerControl.SpeedMode = Speed / Me.PositionerControl.DegreesPerPanPosition ' mySigFinderForm.MaxHold1.Visible = True ' Dim currrentAz As Double = PositionerControl.PanPosition ' Dim fCommand As String = "" ' ' If Main.signalStartedOnce = False Then ' 'fCommand = PositionerControl.QueryPTU300("FT") ' Set unit to Terse Mode. ' 'fCommand = PositionerControl.QueryPTU300("ED") ' Set unit to Echo Off ' 'fCommand = PositionerControl.QueryPTU300("H") ' Stop Moving!!!!! ' 'fCommand = PositionerControl.QueryPTU300("LD") ' Disable Pan Limits ' 'fCommand = PositionerControl.QueryPTU300("I") ' Imediate ' 'fCommand = PositionerControl.QueryPTU300("PMR") ' Stationary Power Mode Low ' 'fCommand = PositionerControl.QueryPTU300("TMR") ' Stationary Power Mode Low ' 'fCommand = PositionerControl.QueryPTU300("S") ' slave mode alows the next command to complete before proceeding ' 'fCommand = PositionerControl.QueryPTU300("RP") ' reset PAN axis only 'umcommented 2/11/14 ' 'fCommand = PositionerControl.QueryPTU300("A") ' initiate reset ' 'fCommand = PositionerControl.QueryPTU300("I") ' reinstate imediate ' ''fCommand = PositionerControl.QueryPTU300("CV") ' Pure Velocity Mode ' ''fCommand = PositionerControl.QueryPTU300("%%1CPT") ' 'Main.signalStartedOnce = True ' ''check for cable wrap ' ' If Me.Main.preventCableWrap = True Then ' ' PositionerControl.prevenCableWrap = True ' ' PositionerControl.SpinWrapThread.Start() ' ' Else ' ' fCommand = PositionerControl.QueryPTU300("CV") ' Pure Velocity Mode ' ' fCommand = PositionerControl.QueryPTU300("%%1CPT") ' ' fCommand = PositionerControl.QueryPTU300("PS500") ' + CDbl(Me.mySigFinderForm.cmbPanSpeed.Text) / Me.PositionerControl.DegreesPerPanPosition) ' + Speed.ToString) ' spin at speed rate ' ' End If ' 'Else ' 'check for cable wrap ' 'If Me.Main.preventCableWrap = True Then ' ' PositionerControl.prevenCableWrap = True ' ' 'MsgBox("starting spinPreventWrap() ", MsgBoxStyle.MsgBoxSetForeground) ' ' PositionerControl.SpinWrapThread.Start() ' 'Else ' ' fCommand = PositionerControl.QueryPTU300("CV") ' Pure Velocity Mode ' ' fCommand = PositionerControl.QueryPTU300("%%1CPT") ' ' fCommand = PositionerControl.QueryPTU300("PS500") ' + CDbl(Me.mySigFinderForm.cmbPanSpeed.Text) / Me.PositionerControl.DegreesPerPanPosition) ' + Speed.ToString) ' spin at speed rate ' 'End If ' 'End If ' 'Me.PositionerControl.mbSession.Flush(BufferTypes.InBuffer, True) ' Dim polarMuliplier As Double = Double.Parse(Me.mySigFinderForm.cmbMultiplier.Text) ' Me.DrawALargeCircle() ' Me.DrawASmallerCircle() ' Me.drawSomeCrossHairs() ' Me.updateRadialLabels() ' Me.mySigFinderForm.isInitialized = True ' Do Until closingDirectionFinderThread ' Try ' If stateRun <> False Then ' Control.CheckForIllegalCrossThreadCalls = False ' System.Threading.Monitor.Enter(sigLocker) ' Me.markerArry = Me.DataController.getMarkerValue(Me.markerTrace, Me.AzrSession, Me.Main.missionObj.getAnalyzer(Me.Main.cmbBxSearchAzr.SelectedIndex).getAnalyzerModel, False) ' _findFrequency = Me.markerArry(Me.freqIdx) ' ' FindFrequency = System.Math.Round(CDbl(AzrSession.Query("CALCulate:MARKer:X?")) / 10 ^ 6, 2).ToString ' If CDbl(_findFrequency) < 1 Then ' AzrSession.FormattedIO.WriteLine("FREQuency:CENTer?") ' _findFrequency = System.Math.Round(CDbl(AzrSession.FormattedIO.ReadString()) / 10 ^ 6, 2).ToString ' End If ' Amplitude = Me.markerArry(levelIdx) ' 'Amplitude = System.Math.Round(CDbl(AzrSession.Query("CALCulate:MARKer:Y?")), 2).ToString ' System.Threading.Monitor.Exit(sigLocker) ' Me.mySigFinderForm.powerLabel.Text = System.Math.Round(CDbl(Amplitude), 2).ToString ' Me.mySigFinderForm.Frequency.Text = System.Math.Round(CDbl(_findFrequency), 2).ToString ' PolarMuliplier = Double.Parse(Me.mySigFinderForm.cmbMultiplier.Text) ' Try ' 'PositionerAzimuth = PositionerControl.PanPosition ' 'tmpAzPos = PositionerControl.QueryPTU300("PP") ' 'Me.mySigFinderForm.lblAzPosUnits.Text = tmpAzPos ' 'Me.mySigFinderForm.lblAzimuth.Text = PositionerAzimuth ' 'Me.Main.azimuthValue = PositionerAzimuth ' Finally ' End Try ' If PositionerAzimuth <> Me.invalidAzimuth Or CDbl(Amplitude) > 900 Then ' PositionerAzimuth += Me.positionerCorrectionForNorth ' Me.mySigFinderForm.Radial.ClearData() ' Threading.Thread.Sleep(50) ' Me.mySigFinderForm.Radial.PlotXYAppend(0, 0) ' Threading.Thread.Sleep(50) ' Me.mySigFinderForm.Radial.PlotXYAppend(CDbl(Amplitude + PolarMuliplier) * System.Math.Sin(PositionerAzimuth * System.Math.PI / 180), _ ' CDbl(Amplitude + PolarMuliplier) * System.Math.Cos(PositionerAzimuth * System.Math.PI / 180)) ' Me.mySigFinderForm.ScatterPlotCurrent.PlotXYAppend(CDbl(Amplitude + PolarMuliplier) * System.Math.Sin(PositionerAzimuth * System.Math.PI / 180), _ ' CDbl(Amplitude + PolarMuliplier) * System.Math.Cos(PositionerAzimuth * System.Math.PI / 180)) ' Threading.Thread.Sleep(50) ' End If ' 'Do ' ' If PositionerAzimuth > 180 Then ' ' PositionerAzimuth -= 360 ' ' 'ElseIf PositionerAzimuth < -180 Then ' ' ' PositionerAzimuth += 360 ' ' Else ' ' Exit Do ' ' End If ' 'Loop ' ' txtAzimuth.Text = PositionerAzimuth.ToString("000.0") ' Me.mySigFinderForm.MaxHold1.PlotXYAppend(PositionerAzimuth, CDbl(Amplitude)) ' Me.mySigFinderForm.DataScatterGraph.Refresh() ' 'If Me.mySigFinderForm.chkContinue.Checked = False Then Exit Do ' Else ' PositionerControl.preventingCableWrap = False ' End If ' Catch ex As Exception ' _log.Error(Me.Main.LoggerComboBox.Text & " -Error in sub 'DirectionFinder()': " & ex.Message) ' MsgBox("Error in sub 'DirectionFinder'. Message: " & ex.Message, MsgBoxStyle.MsgBoxSetForeground) ' End Try ' Loop ' End Select ' Catch ex As Exception ' _log.Error(Me.Main.LoggerComboBox.Text & " -Error in sub 'DirectionFinder()': " & ex.Message) ' MsgBox("Error in sub 'DirectionFinder'. Message: " & ex.Message, MsgBoxStyle.MsgBoxSetForeground) ' End Try ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Ending sub 'DirectionFinder()'.") ' End Sub ' Function GetXSeriesTraceBinary4(ByVal azr As Integer, ByVal trace As MxapxaTrace, ByVal traceNum As Integer, ByVal azrType As Enumerations.AnalyzerModels) As Trace ' Try ' 'If SearchAzrSession Is Nothing Then ' Dim mgr = New ResourceManager ' Dim ipStr As String = Me.MissionObj.GetAnalyzer(cmbBxSearchAzr.SelectedIndex).GetIPaddress ' Me._searchAzrSession = CType(mgr.Open(ipStr), MessageBasedSession) ' 'End If ' Dim newTrace As New Trace ' ' step 1. Get the traces ' With newTrace ' _searchAzrSession.FormattedIO.WriteLine("POWer:ATTenuation?") ' .Attenuation = _searchAzrSession.FormattedIO.ReadString ' _searchAzrSession.FormattedIO.WriteLine("DISPlay:WINDow:TRACe:Y:RLEVel?") ' .ReferenceLevel = _searchAzrSession.FormattedIO.ReadString ' _searchAzrSession.FormattedIO.WriteLine("Bandwidth:Resolution?") ' .ResolutionBandwidth = _searchAzrSession.FormattedIO.ReadString ' _searchAzrSession.FormattedIO.WriteLine("Bandwidth:video?") ' .VideoBandwidth = _searchAzrSession.FormattedIO.ReadString ' _searchAzrSession.FormattedIO.WriteLine("Sweep:Time?") ' .SweepTime = _searchAzrSession.FormattedIO.ReadString ' _searchAzrSession.FormattedIO.WriteLine("FREQuency:STARt?") ' .StartFrequency = _searchAzrSession.FormattedIO.ReadString ' txtStartFreq.Text = .StartFrequency.ToString ' _searchAzrSession.FormattedIO.WriteLine("FREQuency:STOP?") ' .StopFrequency = _searchAzrSession.FormattedIO.ReadString ' txtStopFreq.Text = .StopFrequency.ToString ' .Errorcode = "" ' If chkXLGPS.Checked = True Then ' Try ' Me.LedXLGPS.BlinkMode = LedBlinkMode.BlinkWhenOn ' Select Case cmbBXGPSSource.SelectedIndex ' Case Enumerations.GpsSources.XlGps ' .MeasurementDateTime = AXlGpsController.TimeUtc ' .Latitude = AXlGpsController.Latitude ' .Longitude = AXlGpsController.Longitude ' Case Enumerations.GpsSources.GarminGpSmapSeries ' .MeasurementDateTime = GarminGpsController.TimeUtc ' .Latitude = GarminGpsController.Latitude ' .Longitude = GarminGpsController.Longitude ' End Select ' txtMeasurementTime.Text = .MeasurementDateTime.ToString("dd MMM yyyy HH:mm:ss.f") ' txtLatitude.Text = .Latitude.ToString ' txtLongitude.Text = .Longitude.ToString ' Catch ex As Exception ' .MeasurementDateTime = Date.UtcNow ' txtMeasurementTime.Text = .MeasurementDateTime.ToString("dd MMM yyyy HH:mm:ss.f") ' .Latitude = txtLatitude.Text ' .Longitude = txtLongitude.Text ' End Try ' Else ' .MeasurementDateTime = Date.UtcNow ' txtMeasurementTime.Text = .MeasurementDateTime.ToString("dd MMM yyyy HH:mm:ss.f") ' .Latitude = txtLatitude.Text ' .Longitude = txtLongitude.Text ' End If ' ' .Name = cmbScan.Text & AZR 'CurrentScan.Name ' .Name = azr 'CurrentScan.Name ' ' .Notes = txtNotes.Text ' ' .Location = cmbLocation.Text ' End With ' 'change some default values ' _searchAzrSession.SetBufferSize(IOBuffers.ReadWrite, 200000) ' value on bytes ' _searchAzrSession.TimeoutMilliseconds = 60000 ' time in milliseconds ' 'trace formatting stuff ' Dim format As String = "" 'AzrSession.Query(":Format:Trace:Data?") 'just for debugging to see what it is ' 'SearchAzrSession.Write(":Format:Border SWAPped") ' get the bytes LSB first ' 'SearchAzrSession.Write(":Format:Trace:Data REAL,32") 'get the trace data y axis values as 64 bit real numbers ' '' format = AzrSession.Query(":Format:Trace:Data?") 'just for debugging to ensure that it changed ' '' get trace ' 'SearchAzrSession.Write(":TRAC:DATA? TRACE" & traceNum) 'request trace values ' If azrType <> Enumerations.AnalyzerModels.AgilentFieldFox Then ' _searchAzrSession.FormattedIO.WriteLine(":Format:Border SWAPped") ' get the bytes LSB first ' End If ' _searchAzrSession.FormattedIO.WriteLine(":Format:Data REAL,32") 'get the trace data y axis values as 32 bit real numbers '2/3/14: got rid of the word TRACE to support FieldFox ' _searchAzrSession.FormattedIO.WriteLine(":Format:Data?") ' format = _searchAzrSession.FormattedIO.ReadString 'just for debugging to ensure that it changed '2/3/14: got rid of the word TRACE to support FieldFox ' ' get trace ' If azrType = Enumerations.AnalyzerModels.AgilentFieldFox Then ' _searchAzrSession.FormattedIO.WriteLine(":TRACE" & traceNum & ":DATA?") ' Else ' _searchAzrSession.FormattedIO.WriteLine(":TRAC:DATA? TRACE" & traceNum) 'request trace values ' End If ' Dim traceByte() As Byte = _searchAzrSession.FormattedIO.ReadBinaryBlockOfByte ' store the values into a byte array ' _searchAzrSession.Clear() ' ' step 2. Convert the trace data to display it ' 'get the start and stop frequencies and number of data points ' _searchAzrSession.FormattedIO.WriteLine(":Sense:Freq:Start?") ' Dim startFreq As String = _searchAzrSession.FormattedIO.ReadString() ' _searchAzrSession.FormattedIO.WriteLine(":Sense:Freq:Stop?") ' Dim stopFreq As String = _searchAzrSession.FormattedIO.ReadString() ' _searchAzrSession.FormattedIO.WriteLine(":Sense:Sweep:Points?") ' Dim numDataPoints As String = _searchAzrSession.FormattedIO.ReadString() ' 'close the session ' 'AzrSession.Dispose() ' 'set-up the output arrays ' Dim dataPoints As Double = CDbl(numDataPoints) ' Dim span As Double = CDbl(startFreq) - CDbl(stopFreq) ' Dim fPoint(dataPoints - 1) As Double ' Dim ampAarray(dataPoints - 1) As Single ' 'get some temporary loop variables ' Dim ii As Integer = 0 ' Dim jj As Integer = 0 ' Dim idx As Integer = 0 ' Dim fPt As Double = 0 ' 'determine how at which point we need to start at in the byte arrays to leap over some header ' 'bytes and get into the amplitude bytes ' If traceByte.Length < 1000000 Then ' jj = 8 ' End If ' If traceByte.Length < 100000 Then ' jj = 7 ' End If ' If traceByte.Length < 10000 Then ' if the byte array length is less than 10,000 bytes ' jj = 6 ' End If ' If traceByte.Length < 1000 Then ' jj = 5 ' End If ' If traceByte.Length < 100 Then ' jj = 4 ' End If ' If traceByte.Length < 10 Then ' jj = 3 ' End If ' 'loop through and build the arrays ' ReDim newTrace.DataSingles(dataPoints - 1) ' For ii = 0 To (dataPoints - 1) ' fPt = CDbl(startFreq) + (span * idx / (dataPoints)) 'calc freq of this point ' fPoint(idx) = fPt / (10 ^ 6) ' convert to MHz ' ampAarray(idx) = System.BitConverter.ToSingle(traceByte, jj) ' newTrace.DataSingles(idx) = System.Math.Round(ampAarray(idx), 3) ' idx += 1 ' increment the freq and amplitude arrays by 1 ' jj += 4 ' advance the byte arrays by 8 (8 bytes to one double) ' Next ' Return newTrace ' Catch ex As Exception ' Dim logMsg As String = " -Error in getting analyzer " & azr & " trace. " & ex.Message ' _log.Trace(Me.LoggerComboBox.Text & logMsg) ' Return Nothing ' Finally ' End Try ' End Function ' Private Sub SpinPositioner() ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Starting sub 'SpinPositioner()'.") ' Dim preventingCableWrap = Me.Main.preventingCableWrap ' Dim lastDirectionWasClockwise As Boolean = False ' Dim justHalted As Boolean = False ' Try ' If preventingCableWrap Then ' Using flirUnit As FlirPositionerControl.FlirUnit = New FlirPositionerControl.FlirUnit("COM" & Trim(Me.Main.ToolStripTextBoxPosSerPortNum.Text), False, True) ' 'flirUnit.SetCommandMode(FlirPositionerControl.CommandMode.Slaved) ' 'log.Trace(Me.Main.LoggerComboBox.Text & " -Set positioner to Slaved. Answer: ") ' flirUnit.MovePanToPosition(181) ' 'flirUnit.Await() ' Do Until closingSpinPositionerthread ' 'Dim degPerPos = 1 / flirUnit.DegreeToPosition(1) ' 'Dim posPerMin = Me.mySigFinderForm.numUpDwnSpeedRPM.Value * 360 / (degPerPos * 60) ' 'flirUnit.SetPanSpeed(posPerMin) ' If stateRun Then ' If justHalted Then ' If lastDirectionWasClockwise Then ' flirUnit.MovePanToPosition(180) ' ' flirUnit.Await() ' Else ' flirUnit.MovePanToPosition(181) ' 'flirUnit.Await() ' End If ' justHalted = False ' End If ' If (Convert.ToInt32(flirUnit.GetPanPosition()) < -178 And Convert.ToInt32(flirUnit.GetPanPosition()) > -181) Then ' flirUnit.MovePanToPosition(180) ' 'flirUnit.Await() ' lastDirectionWasClockwise = True ' End If ' If (Convert.ToInt32(flirUnit.GetPanPosition()) > 178 And Convert.ToInt32(flirUnit.GetPanPosition()) < 181) Then ' flirUnit.MovePanToPosition(181) ' 'flirUnit.Await() ' lastDirectionWasClockwise = False ' End If ' PositionerAzimuth = flirUnit.GetPanPosition() ' Me.mySigFinderForm.lblAzPosUnits.Text = PositionerAzimuth ' Me.mySigFinderForm.lblAzimuth.Text = PositionerAzimuth ' Me.Main.azimuthValue = PositionerAzimuth ' Else ' flirUnit.Halt() ' justHalted = True ' End If ' Loop ' flirUnit.Halt() ' End Using ' Else ' Using flirUnit As FlirPositionerControl.FlirUnit = New FlirPositionerControl.FlirUnit("COM" & Trim(Me.Main.ToolStripTextBoxPosSerPortNum.Text), True, False) ' flirUnit.EnableContinousRotationPanAxis() ' Do Until closingSpinPositionerthread ' If stateRun Then ' flirUnit.RotatePan(PanRotationDirection.Right) ' Else ' flirUnit.Halt() ' End If ' Loop ' flirUnit.Halt() ' End Using ' End If ' Catch ex As Exception ' _log.Error(Me.Main.LoggerComboBox.Text & " -Error in sub 'SpinPositioner()': " & ex.Message) ' MsgBox("Error in Spin Positioner thread: " & ex.Message) ' End Try ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Ending sub 'SpinPositioner()'.") ' End Sub ' 'this compares a value to a limit line value ' ''' <summary> ' ''' takes a Trace and generates the Frequency column for the TraceData. This is used to Plot the data in a graph ' ''' </summary> ' ''' <param name="tracedata"></param> ' ''' <returns>A 2 by datapoints array of Doubles</returns> ' ''' <remarks></remarks> ' Function DataArrayConverterDoubles(ByVal tracedata As Trace) As Double(,) ' _log.Debug(Me.LoggerComboBox.Text & " -Starting function 'DataArrayConverterDoubles()'.") ' Dim mDataArray As Double(,) ' Dim x As Integer = tracedata.DataSingles.Length - 1 ' ReDim mDataArray(1, x) ' resize array ' Dim I As Integer = 0 ' Dim fpoint As Double ' Dim span As Double = CDbl(tracedata.StopFrequency) - CDbl(tracedata.StartFrequency) ' Dim dataPoints As Integer = tracedata.DataSingles.Length ' For Each ss In tracedata.DataSingles() 'convert to mDataArray ' If dataPoints <> 1 Then ' fpoint = CDbl(tracedata.StartFrequency) + span * (I) / (dataPoints - 1) 'calc freq of point ' Else ' fpoint = CDbl(tracedata.StartFrequency) ' End If ' mDataArray(0, I) = CDbl(fpoint / 1000000) 'Freq in Mhz ' mDataArray(1, I) = ss ' If tracedata.DataSingles.Length <> dataPoints Then ' Dim tmpStr As String = (" -Datapoint mismatch in function 'DataArrayConverterDoubles()'. Tracedata.Name = " & tracedata.Name) ' _log.Error(Me.LoggerComboBox.Text & tmpStr) ' Exit For ' End If ' I += 1 ' Next ' Return mDataArray ' End Function ' Public Sub SetAzr() ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Starting sub 'setAzr()'.") ' Try ' With Me.mySigFinderForm ' Dim azrSession = Me.AzrSession ' azrSession.FormattedIO.WriteLine("Bandwidth:Resolution " & .numUpDwnRBW.Value & .cmbBxRBWfreqUnits.Text) ' azrSession.FormattedIO.WriteLine("sweep:points " & .numUpDwnNumPoints.Value) ' azrSession.FormattedIO.WriteLine("FREQuency:CENTer " & .numUpDwnCenterFreq.Value & .cmbBxCtrFreqUnits.Text) ' azrSession.FormattedIO.WriteLine("FREQuency:SPAN " & .numUpDwnSpan.Value & .cmbBxSpanUnits.Text) ' Me.DataController.setMarker(Me.Main.missionObj.getSearchAnalyzerClass.getMarkerTraceAssignment, azrSession, Me.Main.missionObj.getAnalyzer(Me.Main.cmbBxSearchAzr.SelectedIndex).getAnalyzerModel, False, _findFrequency) ' If Me.Main.missionObj.getAnalyzer(Me.Main.cmbBxSearchAzr.SelectedIndex).getAnalyzerModel = Enumerations.AnalyzerModels.AgilentFieldFox Then ' If Me.mySigFinderForm.chkBxAutoSwpTime.Checked = True Then ' azrSession.FormattedIO.WriteLine(":SENSe:SWEep:ACQuisition:AUTO ON") ' Else ' azrSession.FormattedIO.WriteLine(":SENSe:SWEep:ACQuisition:AUTO OFF") ' azrSession.FormattedIO.WriteLine(":SENSe:SWEep:ACQ " & .numUpDwnSeepTime.Value) ' End If ' Else ' If Me.mySigFinderForm.chkBxAutoSwpTime.Checked = True Then ' azrSession.FormattedIO.WriteLine(":SWEep:TIME:AUTO ON") ' Else ' azrSession.FormattedIO.WriteLine(":SWEep:TIME:AUTO OFF") ' azrSession.FormattedIO.WriteLine(":SENSe:SWEep:TIME " & .numUpDwnSeepTime.Value & "ms") ' End If ' End If ' 'get the value the marker is on ' Me.markerArry = Me.DataController.getMarkerValue(Me.markerTrace, Me.AzrSession, Me.Main.missionObj.getAnalyzer(Me.Main.cmbBxSearchAzr.SelectedIndex).getAnalyzerModel, False) ' Dim tmpValue As String = Me.markerArry(freqIdx) / 10 ^ 6 ' 'Dim tmpValue As String = azrSession.Query("CALCulate:MARKer:X?") / 10 ^ 6 ' If CDbl(tmpValue) > 1 Then ' .numUpDwnMarkerFreq.Value = tmpValue ' Else ' .numUpDwnMarkerFreq.Value = .numUpDwnCenterFreq.Value ' End If ' End With ' Catch ex As Exception ' _log.Error(Me.Main.LoggerComboBox.Text & " -Error in sub 'setAZR()': " & ex.Message) ' MsgBox("Unable to update search azr parameters", MsgBoxStyle.MsgBoxSetForeground) ' End Try ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Ending sub 'setAZR()'.") ' End Sub ' Public Sub DrawALargeCircle() ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Starting sub 'DrawALargerCircle()'.") ' Dim xData(360) As Double ' Dim yData(360) As Double ' Dim muliplier As Double = CDbl(Me.mySigFinderForm.cmbMultiplier.Text) * 5 / 8 ' For ii = 0 To 360 ' xData(ii) = muliplier * Math.Sin(ii * Math.PI / 180) ' yData(ii) = muliplier * Math.Cos(ii * Math.PI / 180) ' Next ' Me.mySigFinderForm.BigCircle.PlotXY(xData, yData) ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Ending sub 'DrawALargerCircle()'.") ' End Sub ' Public Sub DrawASmallerCircle() ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Starting sub 'DrawASmallerCircle()'.") ' Dim xData(360) As Double ' Dim yData(360) As Double ' Dim muliplier As Double = CDbl(Me.mySigFinderForm.cmbMultiplier.Text) / 4 ' For ii = 0 To 360 ' xData(ii) = muliplier * Math.Sin(ii * Math.PI / 180) ' yData(ii) = muliplier * Math.Cos(ii * Math.PI / 180) ' Next ' Me.mySigFinderForm.SmallCircle.PlotXY(xData, yData) ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Ending sub 'DrewASmallerCircle()'.") ' End Sub ' Public Sub DrawSomeCrossHairs() ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Starting sub 'drawSomeCrossHairs()'.") ' Dim xDataX(2) As Double ' Dim yDataX(2) As Double ' Dim xDataY(2) As Double ' Dim yDataY(2) As Double ' Dim muliplier As Double = CDbl(Me.mySigFinderForm.cmbMultiplier.Text) * 5 / 8 ' xDataX(0) = 0 ' yDataX(0) = muliplier ' xDataX(1) = 0 ' yDataX(1) = muliplier * -1 ' xDataY(0) = muliplier ' yDataY(0) = 0 ' xDataY(1) = muliplier * -1 ' yDataY(1) = 0 ' Me.mySigFinderForm.Xaxis.PlotXY(xDataX, yDataX) ' Me.mySigFinderForm.Yaxis.PlotXY(xDataY, yDataY) ' 'now put a tick mark on the plot where the front of the van is ' Dim vanFront As Double = System.Math.Round(CDbl(Trim(Me.Main.Van_Heading.Text)), 0) ' While vanFront >= 360 ' vanFront -= 360 ' End While ' Dim polarMuliplier As Double = Double.Parse(Me.mySigFinderForm.cmbMultiplier.Text) ' Dim blankingLineLength As Double = PolarMuliplier * 9 / 16 ' Dim tickLength As Double = PolarMuliplier * 12 / 16 ' Me.mySigFinderForm.TickLine.PlotXYAppend(0, 0) ' Me.mySigFinderForm.TickLine.PlotXYAppend(tickLength * System.Math.Sin(vanFront * System.Math.PI / 180), tickLength * System.Math.Cos(vanFront * System.Math.PI / 180)) ' 'Me.mySigFinderForm.BlankingLine.PlotXYAppend(0, 0) ' 'Me.mySigFinderForm.BlankingLine.PlotXYAppend(blankingLineLength * System.Math.Sin(vanFront * System.Math.PI / 180), blankingLineLength * System.Math.Cos(vanFront * System.Math.PI / 180)) ' Me.mySigFinderForm.ScatterGraphAzimuth.Update() ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Ending sub 'drawSomeCrossHairs()'.") ' End Sub ' Sub SaveRadialPng() ' PNG's go thru email WMFs get stripped out ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Starting sub 'SaveRadialPNG()'.") ' Dim dir As String = "C:\" & Me.Main.comboBoxMissionName.Text & "\" ' Me.mySigFinderForm.SaveFileDialog1.InitialDirectory = dir ' Me.mySigFinderForm.SaveFileDialog1.Filter = "Portable Network Graphics File |*.png" ' Me.mySigFinderForm.SaveFileDialog1.FileName = _findFrequency & " Radial Plot " & Date.UtcNow.ToString("ddMMMyyyy HHmmss") ' Me.mySigFinderForm.SaveFileDialog1.ShowDialog() ' Me.mySigFinderForm.ScatterGraphAzimuth.ToImage.Save(Me.mySigFinderForm.SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Png) ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Ending sub 'SaveRadialPNG()'.") ' End Sub ' Sub SaveDataPng() ' PNG's go thru email WMFs get stripped ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Starting sub 'SaveDataPNG()'.") ' Me.mySigFinderForm.SaveFileDialog1.Filter = "Portable Network Graphics File |*.png" ' Me.mySigFinderForm.SaveFileDialog1.FileName = _findFrequency & " Linear Azimuth Plot " & Date.UtcNow.ToString("ddMMMyyyy HHmmss") ' Me.mySigFinderForm.SaveFileDialog1.ShowDialog() ' Me.mySigFinderForm.DataScatterGraph.ToImage.Save(Me.mySigFinderForm.SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Png) ' _log.Debug(Me.Main.LoggerComboBox.Text & " -Ending sub 'SaveDataPNG()'.") ' End Sub ' Public Delegate Sub UpdateLevelTextBoxCallback(ByVal aLevel As String) ' Private Sub UpdateLevelTextBox(ByVal aLevel As String) ' 'If Me.mySigFinderForm.txtBxPowLevel.InvokeRequired Then ' ' Me.mySigFinderForm.txtBxPowLevel.Invoke(New updateLevelTextBoxCallback(AddressOf Me.updateLevelTextBox), New Object() {aLevel}) ' 'Else ' ' 'Me.txtBxPowLevel.Text = aLevel ' 'End If ' End Sub ' Public Enum ScanMode ' Range ' Continuous ' End Enum ' 'Private Sub SignalFinder_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' ' 'TODO: This line of code loads data into the 'EMDataSet.SignalFinderHotList' table. You can move, or remove it, as needed. ' ' Me.SignalFinderHotListTableAdapter.Fill(Me.EMDataSet.SignalFinderHotList) ' 'End Sub ' Enum MxapxaTrace ' Trace1 = 1 ' Trace2 = 2 ' Trace3 = 3 ' Trace4 = 4 ' Trace5 = 5 ' Trace6 = 6 ' End Enum End Class
wboxx1/85-EIS-PUMA
puma/src/Supporting Controllers/MySignalFinder.vb
Visual Basic
mit
45,120
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers <ExportCompletionProvider(NameOf(SymbolCompletionProvider), LanguageNames.VisualBasic)> <ExtensionOrder(After:=NameOf(KeywordCompletionProvider))> <[Shared]> Partial Friend Class SymbolCompletionProvider Inherits AbstractRecommendationServiceBasedCompletionProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function GetInsertionText(item As CompletionItem, ch As Char) As String Return CompletionUtilities.GetInsertionTextAtInsertionTime(item, ch) End Function Friend Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean Return CompletionUtilities.IsDefaultTriggerCharacterOrParen(text, characterPosition, options) End Function Friend Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = CompletionUtilities.CommonTriggerCharsAndParen Protected Overrides Async Function IsSemanticTriggerCharacterAsync(document As Document, characterPosition As Integer, cancellationToken As CancellationToken) As Task(Of Boolean) If document Is Nothing Then Return False End If Dim result = Await IsTriggerOnDotAsync(document, characterPosition, cancellationToken).ConfigureAwait(False) If result.HasValue Then Return result.Value End If Return True End Function Private Shared Async Function IsTriggerOnDotAsync(document As Document, characterPosition As Integer, cancellationToken As CancellationToken) As Task(Of Boolean?) Dim text = Await document.GetTextAsync(cancellationToken).ConfigureAwait(False) If text(characterPosition) <> "."c Then Return Nothing End If ' don't want to trigger after a number. All other cases after dot are ok. Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim token = root.FindToken(characterPosition) Return IsValidTriggerToken(token) End Function Private Shared Function IsValidTriggerToken(token As SyntaxToken) As Boolean If token.Kind <> SyntaxKind.DotToken Then Return False End If Dim previousToken = token.GetPreviousToken() If previousToken.Kind = SyntaxKind.IntegerLiteralToken Then Return token.Parent.Kind <> SyntaxKind.SimpleMemberAccessExpression OrElse Not DirectCast(token.Parent, MemberAccessExpressionSyntax).Expression.IsKind(SyntaxKind.NumericLiteralExpression) End If Return True End Function Protected Overrides Function GetDisplayAndSuffixAndInsertionText(symbol As ISymbol, context As SyntaxContext) As (displayText As String, suffix As String, insertionText As String) Return CompletionUtilities.GetDisplayAndSuffixAndInsertionText(symbol, context) End Function Protected Overrides Async Function CreateContextAsync(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of SyntaxContext) Dim semanticModel = Await document.GetSemanticModelForSpanAsync(New TextSpan(position, 0), cancellationToken).ConfigureAwait(False) Return Await VisualBasicSyntaxContext.CreateContextAsync(document.Project.Solution.Workspace, semanticModel, position, cancellationToken).ConfigureAwait(False) End Function Protected Overrides Function GetFilterText(symbol As ISymbol, displayText As String, context As SyntaxContext) As String ' Filter on New if we have a ctor If symbol.IsConstructor() Then Return "New" End If Return MyBase.GetFilterText(symbol, displayText, context) End Function Private Shared ReadOnly cachedRules As Dictionary(Of ValueTuple(Of Boolean, Boolean, Boolean), CompletionItemRules) = InitCachedRules() Private Shared Function InitCachedRules() As Dictionary(Of ValueTuple(Of Boolean, Boolean, Boolean), CompletionItemRules) Dim result = New Dictionary(Of ValueTuple(Of Boolean, Boolean, Boolean), CompletionItemRules)() For importDirective = 0 To 1 For preselect = 0 To 1 For tuple = 0 To 1 Dim context = ValueTuple.Create(importDirective = 1, preselect = 1, tuple = 1) result(context) = MakeRule(importDirective, preselect, tuple) Next Next Next Return result End Function Private Shared Function MakeRule(importDirective As Integer, preselect As Integer, tuple As Integer) As CompletionItemRules Return MakeRule(importDirective = 1, preselect = 1, tuple = 1) End Function Private Shared Function MakeRule(importDirective As Boolean, preselect As Boolean, tuple As Boolean) As CompletionItemRules ' '(' should not filter the completion list, even though it's in generic items like IList(Of...) Dim generalBaseline = CompletionItemRules.Default. WithFilterCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, "("c)). WithCommitCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Add, "("c)) Dim importDirectBasline As CompletionItemRules = CompletionItemRules.Create(commitCharacterRules:= ImmutableArray.Create( CharacterSetModificationRule.Create(CharacterSetModificationKind.Replace, "."c))) Dim rule = If(importDirective, importDirectBasline, generalBaseline) If preselect Then rule = rule.WithSelectionBehavior(CompletionItemSelectionBehavior.SoftSelection) End If If tuple Then rule = rule.WithCommitCharacterRule( CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, ":"c)) End If Return rule End Function Protected Overrides Function GetCompletionItemRules(symbols As List(Of ISymbol), context As SyntaxContext, preselect As Boolean) As CompletionItemRules Return If(cachedRules( ValueTuple.Create(context.IsInImportsDirective, preselect, context.IsPossibleTupleContext)), CompletionItemRules.Default) End Function Protected Overrides Function IsInstrinsic(s As ISymbol) As Boolean Return If(TryCast(s, ITypeSymbol)?.IsIntrinsicType(), False) End Function Protected Overrides ReadOnly Property PreselectedItemSelectionBehavior As CompletionItemSelectionBehavior Get Return CompletionItemSelectionBehavior.SoftSelection End Get End Property End Class End Namespace
davkean/roslyn
src/Features/VisualBasic/Portable/Completion/CompletionProviders/SymbolCompletionProvider.vb
Visual Basic
apache-2.0
7,982
'============================================================================== ' MyGeneration.dOOdads ' ' WhereParameter.vb ' Version 5.0 ' Updated - 09/15/2005 '------------------------------------------------------------------------------ ' Copyright 2004, 2005 by MyGeneration Software. ' All Rights Reserved. ' ' Permission to use, copy, modify, and distribute this software and its ' documentation for any purpose and without fee is hereby granted, ' provided that the above copyright notice appear in all copies and that ' both that copyright notice and this permission notice appear in ' supporting documentation. ' ' MYGENERATION SOFTWARE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS ' SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY ' AND FITNESS, IN NO EVENT SHALL MYGENERATION SOFTWARE BE LIABLE FOR ANY ' SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ' WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, ' WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER ' TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE ' OR PERFORMANCE OF THIS SOFTWARE. '============================================================================== Imports System.Collections Imports System.Data Namespace MyGeneration.dOOdads Public Class WhereParameter Public Enum Operand Equal = 1 NotEqual GreaterThan GreaterThanOrEqual LessThan LessThanOrEqual Like_ NotLike IsNull IsNotNull Between In_ NotIn End Enum Public Enum Dir ASC = 1 DESC End Enum Public Enum Conj AND_ = 1 OR_ UseDefault End Enum Public Sub New(ByVal column As String, ByVal param As IDataParameter, Optional ByVal [operator] As Operand = Operand.Equal) Me._column = column Me._param = param Me._operator = [operator] End Sub Public ReadOnly Property IsDirty() As Boolean Get Return _isDirty End Get End Property Public ReadOnly Property Column() As String Get Return _column End Get End Property Public ReadOnly Property Param() As IDataParameter Get Return _param End Get End Property Public Property Value() As Object Get Return _value End Get Set(ByVal TheValue As Object) _value = TheValue _isDirty = True End Set End Property Public Property [Operator]() As Operand Get Return _operator End Get Set(ByVal Value As Operand) _operator = Value _isDirty = True End Set End Property Public Property Conjuction() As Conj Get Return _conjuction End Get Set(ByVal Value As Conj) _conjuction = Value _isDirty = True End Set End Property Public Property BetweenBeginValue() As Object Get Return _betweenBegin End Get Set(ByVal TheValue As Object) _betweenBegin = TheValue _isDirty = True End Set End Property Public Property BetweenEndValue() As Object Get Return _betweenEnd End Get Set(ByVal TheValue As Object) _betweenEnd = TheValue _isDirty = True End Set End Property Private _operator As Operand Private _conjuction As Conj = Conj.UseDefault Private _value As Object = Nothing Private _column As String Private _param As IDataParameter Private _isDirty As Boolean = False Private _betweenBegin As Object Private _betweenEnd As Object End Class End Namespace
cafephin/mygeneration
src/doodads/VB.NET/MyGeneration.dOOdads/WhereParameter.vb
Visual Basic
bsd-3-clause
4,356
Namespace Controls.TabEx <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class TabButton Inherits System.Windows.Forms.UserControl 'UserControl overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() components = New System.ComponentModel.Container() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(TabButton)) lblCaption = New System.Windows.Forms.Label() CMMain = New System.Windows.Forms.ContextMenuStrip(Me.components) AddServerToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() ToolStripMenuItem1 = New System.Windows.Forms.ToolStripSeparator() CloseToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() TableMain = New System.Windows.Forms.TableLayoutPanel() btnClose = New ExButton() CMMain.SuspendLayout() TableMain.SuspendLayout() SuspendLayout() ' 'lblCaption ' lblCaption.ContextMenuStrip = CMMain lblCaption.Dock = System.Windows.Forms.DockStyle.Fill lblCaption.Location = New System.Drawing.Point(0, 6) lblCaption.Margin = New System.Windows.Forms.Padding(0, 6, 0, 0) lblCaption.Name = "lblCaption" lblCaption.Size = New System.Drawing.Size(131, 28) lblCaption.TabIndex = 1 ' 'CMMain ' CMMain.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.AddServerToolStripMenuItem, ToolStripMenuItem1, CloseToolStripMenuItem}) CMMain.Name = "CMMain" CMMain.Size = New System.Drawing.Size(138, 54) ' 'AddServerToolStripMenuItem ' AddServerToolStripMenuItem.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Bold) AddServerToolStripMenuItem.Name = "AddServerToolStripMenuItem" AddServerToolStripMenuItem.Size = New System.Drawing.Size(137, 22) AddServerToolStripMenuItem.Text = Global.ServicesPlus.My.Resources.TextAddServerCaption ' 'ToolStripMenuItem1 ' ToolStripMenuItem1.Name = "ToolStripMenuItem1" ToolStripMenuItem1.Size = New System.Drawing.Size(134, 6) ' 'CloseToolStripMenuItem ' CloseToolStripMenuItem.Name = "CloseToolStripMenuItem" CloseToolStripMenuItem.Size = New System.Drawing.Size(137, 22) CloseToolStripMenuItem.Text = Global.ServicesPlus.My.Resources.TextClose ' 'TableMain ' TableMain.ColumnCount = 2 TableMain.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100.0!)) TableMain.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20.0!)) TableMain.ContextMenuStrip = CMMain TableMain.Controls.Add(Me.lblCaption, 0, 0) TableMain.Controls.Add(Me.btnClose, 1, 0) TableMain.Dock = System.Windows.Forms.DockStyle.Fill TableMain.Location = New System.Drawing.Point(0, 0) TableMain.Margin = New System.Windows.Forms.Padding(0) TableMain.Name = "TableMain" TableMain.RowCount = 1 TableMain.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100.0!)) TableMain.Size = New System.Drawing.Size(151, 34) TableMain.TabIndex = 2 ' 'btnClose ' btnClose.BackgroundImage = CType(resources.GetObject("btnClose.BackgroundImage"), System.Drawing.Image) btnClose.ImageDown = CType(resources.GetObject("btnClose.ImageDown"), System.Drawing.Image) btnClose.ImageNormal = CType(resources.GetObject("btnClose.ImageNormal"), System.Drawing.Image) btnClose.ImageOver = CType(resources.GetObject("btnClose.ImageOver"), System.Drawing.Image) btnClose.Location = New System.Drawing.Point(131, 5) btnClose.Margin = New System.Windows.Forms.Padding(0, 5, 0, 0) btnClose.Name = "btnClose" btnClose.Size = New System.Drawing.Size(16, 16) btnClose.TabIndex = 2 ' 'TabButton ' AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!) AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font BackColor = Modules.ColorBackgroud Controls.Add(Me.TableMain) Font = New System.Drawing.Font("Segoe UI Semilight", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Margin = New System.Windows.Forms.Padding(0) Name = "TabButton" Padding = New System.Windows.Forms.Padding(0, 0, 0, 2) Size = New System.Drawing.Size(151, 36) CMMain.ResumeLayout(False) TableMain.ResumeLayout(False) ResumeLayout(False) End Sub Friend WithEvents lblCaption As System.Windows.Forms.Label Friend WithEvents TableMain As System.Windows.Forms.TableLayoutPanel Friend WithEvents btnClose As ExButton Friend WithEvents CMMain As System.Windows.Forms.ContextMenuStrip Friend WithEvents AddServerToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripMenuItem1 As System.Windows.Forms.ToolStripSeparator Friend WithEvents CloseToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem End Class End Namespace
fakoua/ServicesPlus
ServicesPlus/Controls/TabEx/TabButton.designer.vb
Visual Basic
bsd-3-clause
6,560
' 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 Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.UnitTests.Diagnostics <[UseExportProvider]> Public Class DiagnosticAnalyzerDriverTests <Fact> Public Async Function DiagnosticAnalyzerDriverAllInOne() As Task Dim source = TestResource.AllInOneVisualBasicCode Dim analyzer = New BasicTrackingDiagnosticAnalyzer() Using workspace = TestWorkspace.CreateVisualBasic(source) Dim document = workspace.CurrentSolution.Projects.Single().Documents.Single() AccessSupportedDiagnostics(analyzer) Await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, document, New TextSpan(0, document.GetTextAsync().Result.Length)) analyzer.VerifyAllAnalyzerMembersWereCalled() analyzer.VerifyAnalyzeSymbolCalledForAllSymbolKinds() analyzer.VerifyAnalyzeNodeCalledForAllSyntaxKinds(New HashSet(Of SyntaxKind)()) analyzer.VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(allowUnexpectedCalls:=True) End Using End Function <Fact, WorkItem(908658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908658")> Public Async Function DiagnosticAnalyzerDriverVsAnalyzerDriverOnCodeBlock() As Task Dim methodNames As String() = {"Initialize", "AnalyzeCodeBlock"} Dim source = <file><![CDATA[ <System.Obsolete> Class C Property P As Integer = 0 Event E() End Class ]]></file> Dim ideEngineAnalyzer = New BasicTrackingDiagnosticAnalyzer() Using ideEngineWorkspace = TestWorkspace.CreateVisualBasic(source.Value) Dim ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single() Await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(ideEngineAnalyzer, ideEngineDocument, New TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)) For Each method In methodNames Assert.False(ideEngineAnalyzer.CallLog.Any(Function(e) e.CallerName = method AndAlso If(e.SymbolKind = SymbolKind.Event, False))) Assert.True(ideEngineAnalyzer.CallLog.Any(Function(e) e.CallerName = method AndAlso If(e.SymbolKind = SymbolKind.NamedType, False))) Assert.True(ideEngineAnalyzer.CallLog.Any(Function(e) e.CallerName = method AndAlso If(e.SymbolKind = SymbolKind.Property, False))) Next method End Using Dim compilerEngineAnalyzer = New BasicTrackingDiagnosticAnalyzer() Using compilerEngineWorkspace = TestWorkspace.CreateVisualBasic(source.Value) Dim compilerEngineCompilation = CType(compilerEngineWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result, VisualBasicCompilation) compilerEngineCompilation.GetAnalyzerDiagnostics({compilerEngineAnalyzer}) For Each method In methodNames Assert.False(compilerEngineAnalyzer.CallLog.Any(Function(e) e.CallerName = method AndAlso If(e.SymbolKind = SymbolKind.Event, False))) Assert.True(compilerEngineAnalyzer.CallLog.Any(Function(e) e.CallerName = method AndAlso If(e.SymbolKind = SymbolKind.NamedType, False))) Assert.True(compilerEngineAnalyzer.CallLog.Any(Function(e) e.CallerName = method AndAlso If(e.SymbolKind = SymbolKind.Property, False))) Next method End Using End Function <Fact> <WorkItem(759, "https://github.com/dotnet/roslyn/issues/759")> Public Async Function DiagnosticAnalyzerDriverIsSafeAgainstAnalyzerExceptions() As Task Dim source = TestResource.AllInOneVisualBasicCode Using Workspace = TestWorkspace.CreateVisualBasic(source) Dim document = Workspace.CurrentSolution.Projects.Single().Documents.Single() Await ThrowingDiagnosticAnalyzer(Of SyntaxKind).VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync( Async Function(analyzer) Await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, document, New TextSpan(0, document.GetTextAsync().Result.Length))) End Using End Function <WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")> <Fact> Public Sub DiagnosticServiceIsSafeAgainstAnalyzerExceptions() Dim analyzer = New ThrowingDiagnosticAnalyzer(Of SyntaxKind)() analyzer.ThrowOn(GetType(DiagnosticAnalyzer).GetProperties().Single().Name) AccessSupportedDiagnostics(analyzer) End Sub Private Sub AccessSupportedDiagnostics(analyzer As DiagnosticAnalyzer) Dim diagnosticService = New TestDiagnosticAnalyzerService(LanguageNames.VisualBasic, analyzer) diagnosticService.AnalyzerInfoCache.GetDiagnosticDescriptorsPerReference() End Sub <Fact> Public Async Function AnalyzerOptionsArePassedToAllAnalyzers() As Task Using workspace = TestWorkspace.CreateVisualBasic(TestResource.AllInOneVisualBasicCode) Dim currentProject = workspace.CurrentSolution.Projects.Single() Dim additionalDocId = DocumentId.CreateNewId(currentProject.Id) Dim newSln = workspace.CurrentSolution.AddAdditionalDocument(additionalDocId, "add.config", SourceText.From("random text")) currentProject = newSln.Projects.Single() Dim additionalDocument = currentProject.GetAdditionalDocument(additionalDocId) Dim additionalStream As AdditionalText = New AdditionalTextWithState(additionalDocument.State) Dim options = New AnalyzerOptions(ImmutableArray.Create(additionalStream)) Dim analyzer = New OptionsDiagnosticAnalyzer(Of SyntaxKind)(expectedOptions:=options) Dim sourceDocument = currentProject.Documents.Single() Await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, sourceDocument, New Text.TextSpan(0, sourceDocument.GetTextAsync().Result.Length)) analyzer.VerifyAnalyzerOptions() End Using End Function End Class
abock/roslyn
src/EditorFeatures/VisualBasicTest/Diagnostics/DiagnosticAnalyzerDriver/DiagnosticAnalyzerDriverTests.vb
Visual Basic
mit
6,346
#Region "Microsoft.VisualBasic::44d5d50e895021028ea5aec4fe4a16eb, src\metadb\Massbank\Public\TMIC\HMDB\Tables\MetaDBTable.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 MetaInfo ' ' Properties: CAS, chebi, HMDB, KEGG ' ' Class BriefTable ' ' Properties: AdultConcentrationAbnormal, AdultConcentrationNormal, ChildrenConcentrationAbnormal, ChildrenConcentrationNormal, disease ' NewbornConcentrationAbnormal, NewbornConcentrationNormal, Sample, water_solubility ' ' Function: Clone ' ' Class MetaDb ' ' Properties: [class], accession, biospecimen, CAS, cellular_locations ' chebi_id, chemical_formula, description, direct_parent, exact_mass ' inchi, inchikey, iupac_name, kegg_id, kingdom ' molecular_framework, name, pubchem_cid, secondary_accessions, smiles ' state, sub_class, super_class, synonyms, tissue ' traditional_iupac, wikipedia_id ' ' Function: FromMetabolite, GetSynonym ' ' Sub: WriteTable ' ' ' /********************************************************************************/ #End Region Imports System.IO Imports BioNovoGene.BioDeep.Chemistry.MetaLib Imports BioNovoGene.BioDeep.Chemistry.MetaLib.Models Imports Microsoft.VisualBasic.Data.csv.IO.Linq Imports Microsoft.VisualBasic.Data.csv.StorageProvider.Reflection Imports Microsoft.VisualBasic.Linq Namespace TMIC.HMDB Public Class MetaInfo : Inherits MetaLib.Models.MetaInfo Public Property HMDB As String Public Property KEGG As String Public Property chebi As String Public Property CAS As String End Class Public Class BriefTable : Inherits MetaInfo Implements ICloneable Public Property Sample As String Public Property disease As String() Public Property water_solubility As String <Column("concentration (children-normal)")> Public Property ChildrenConcentrationNormal As String() <Column("concentration (children-abnormal)")> Public Property ChildrenConcentrationAbnormal As String() <Column("concentration (adult-normal)")> Public Property AdultConcentrationNormal As String() <Column("concentration (adult-abnormal)")> Public Property AdultConcentrationAbnormal As String() <Column("concentration (newborn-normal)")> Public Property NewbornConcentrationNormal As String() <Column("concentration (newborn-abnormal)")> Public Property NewbornConcentrationAbnormal As String() Public Function Clone() As Object Implements ICloneable.Clone Return MemberwiseClone() End Function End Class Public Class MetaDb : Implements ICompoundClass, ICompoundNames Public Property accession As String Public Property secondary_accessions As String() Public Property name As String Public Property chemical_formula As String Public Property exact_mass As Double Public Property iupac_name As String Public Property traditional_iupac As String Public Property synonyms As String() Public Property CAS As String Public Property smiles As String Public Property inchi As String Public Property inchikey As String Public Property kingdom As String Implements ICompoundClass.kingdom Public Property super_class As String Implements ICompoundClass.super_class Public Property [class] As String Implements ICompoundClass.class Public Property sub_class As String Implements ICompoundClass.sub_class Public Property molecular_framework As String Implements ICompoundClass.molecular_framework Public Property direct_parent As String Public Property state As String Public Property cellular_locations As String() Public Property biospecimen As String() Public Property tissue As String() Public Property chebi_id As Long Public Property pubchem_cid As Long Public Property kegg_id As String Public Property wikipedia_id As String Public Property description As String Public Iterator Function GetSynonym() As IEnumerable(Of String) Implements ICompoundNames.GetSynonym Yield name Yield iupac_name Yield traditional_iupac For Each name As String In synonyms.SafeQuery Yield name Next End Function Public Shared Function FromMetabolite(metabolite As metabolite) As MetaDb Dim metabolite_taxonomy = metabolite.taxonomy Dim biosample = metabolite.biological_properties Return New MetaDb With { .accession = metabolite.accession, .secondary_accessions = metabolite.secondary_accessions.accession, .chebi_id = Strings.Trim(metabolite.chebi_id).Split(":"c).Last.ParseInteger, .pubchem_cid = Strings.Trim(metabolite.pubchem_compound_id).ParseInteger, .chemical_formula = metabolite.chemical_formula, .kegg_id = metabolite.kegg_id, .wikipedia_id = metabolite.wikipedia_id, .inchi = metabolite.inchi, .inchikey = metabolite.inchikey, .name = metabolite.name, .state = metabolite.state, .traditional_iupac = metabolite.traditional_iupac, .smiles = metabolite.smiles, .iupac_name = metabolite.iupac_name, .CAS = metabolite.cas_registry_number, .exact_mass = Val(metabolite.monisotopic_molecular_weight), .direct_parent = metabolite_taxonomy?.direct_parent, .kingdom = metabolite_taxonomy?.kingdom, .super_class = metabolite_taxonomy?.super_class, .sub_class = metabolite_taxonomy?.sub_class, .molecular_framework = metabolite_taxonomy?.molecular_framework, .[class] = metabolite_taxonomy?.class, .biospecimen = biosample?.biospecimen_locations.biospecimen, .cellular_locations = biosample?.cellular_locations.cellular, .tissue = biosample?.tissue_locations.tissue, .synonyms = metabolite.synonyms.synonym, .description = metabolite.description } End Function Public Shared Sub WriteTable(metabolites As IEnumerable(Of metabolite), out As Stream) Using table As New WriteStream(Of MetaDb)(New StreamWriter(out)) For Each metabolite As metabolite In metabolites Call table.Flush(FromMetabolite(metabolite)) Next End Using End Sub End Class End Namespace
xieguigang/spectrum
src/metadb/Massbank/Public/TMIC/HMDB/Tables/MetaDBTable.vb
Visual Basic
mit
8,433
Option Strict On Option Explicit On Imports System.Globalization Imports DotSpatial.Data Imports NetTopologySuite.Geometries Namespace Manhattan ''' <summary> ''' <para>ManhattanShapes are polygons with only vertical or horizontal lines in their perimeters. ''' Lists of ManhattanShapes are the parts of a shape. ''' Each collection of parts is associated with a particular integer index, ''' representing a particular grid value.</para> ''' <para>The algorithm to make the polygons from a grid of cells, ''' each polygon indexed by the grid value it belongs to is: </para> ''' <para>1. Make the basic (horizontal) boxes for each index. ''' These boxes are unit height and integer width, and located by row and column number, ''' so that the next two steps only require integer arithmetic.</para> ''' <para>2. Merge the boxes for each index</para> ''' <para>3. Make the holes for each index</para> ''' <para>4. Convert the polygons into lists of points, the format for a shape in a shapefile</para> ''' </summary> Public Class ManhattanShapes Private ReadOnly gridFilePath As String Private ReadOnly ShapesTable As Dictionary(Of Integer, manhattanCustomData) ' ''' <summary> ' ''' Constructor, making an empty dictionary ' ''' </summary> Public Sub New(ByVal GridFileName As String) gridFilePath = GridFileName ShapesTable = New Dictionary(Of Integer, manhattanCustomData)() End Sub ''' <summary> ''' Adds a part p with index indx. ''' </summary> ''' <param name="indx"></param> ''' <param name="p"></param> ''' <param name="area"></param> Private Sub AddShape(ByVal indx As Integer, ByVal p As manhattanPolygon, ByVal area As Integer) If ShapesTable.ContainsKey(indx) Then ShapesTable(indx).polygons.Add(p) ShapesTable(indx).area += area Else Dim lp As New List(Of manhattanPolygon) From { p } ShapesTable.Add(indx, New manhattanCustomData(lp, area)) End If End Sub ''' <summary> ''' For each index in the dictionary, merges its parts if possible. ''' </summary> Private Sub MergeShapes() Dim keys As New List(Of Integer)() keys.AddRange(ShapesTable.Keys) For Each i As Integer In keys ShapesTable(i).polygons = MergeMyPolygons(ShapesTable(i).polygons) Next i End Sub ''' <summary> ''' Merges the polygons in a list todo of polygons. ''' Two polygons can be merged if they are not disjoint and contain complementary links. ''' </summary> ''' <param name="todo"></param> ''' <returns></returns> Private Shared Function MergeMyPolygons(ByVal todo As List(Of manhattanPolygon)) As List(Of manhattanPolygon) Dim done As New List(Of manhattanPolygon)() Do While todo.Count > 0 Dim p0 As manhattanPolygon = todo(0) todo.RemoveAt(0) Dim i0 As Integer Dim i1 As Integer Dim changed As Boolean = False Dim count As Integer = todo.Count For i As Integer = 0 To count - 1 If manhattanPolygon.canMerge(p0, i0, todo(i), i1) Then Dim p As manhattanPolygon = manhattanPolygon.merge(p0, i0, todo(i), i1) todo.RemoveAt(i) todo.Add(p) changed = True Exit For End If Next i If (Not changed) Then done.Add(p0) End If Loop Return done End Function ''' <summary> ''' For each index in the dictionary, separates out any holes. ''' </summary> Private Sub MakeHoles() Dim keys As New List(Of Integer)() keys.AddRange(ShapesTable.Keys) For Each i As Integer In keys ShapesTable(i).polygons = MakeHoles(New List(Of manhattanPolygon)(), ShapesTable(i).polygons) Next i End Sub ''' <summary> ''' Separates out the holes in a list of polygons. ''' There may be more than one hole in a polygon, and holes may be split into ''' several holes. A polygon contains a hole if it contains two non-adjacent ''' complementary links. ''' </summary> ''' <param name="done">polygons with no holes</param> ''' <param name="todo">polygons which may have holes</param> ''' <returns></returns> Private Shared Function MakeHoles(ByVal done As List(Of manhattanPolygon), ByVal todo As List(Of manhattanPolygon)) As List(Of manhattanPolygon) Do While todo.Count > 0 Dim first, last As Integer Dim [next] As manhattanPolygon = todo(0) If manhattanPolygon.hasHole([next].perimeter, first, last) Then 'Debug.WriteLine(Link.makeString(next)); 'Debug.WriteLine("has hole from " + first.ToString() + " to " + last.ToString()); Dim hole As List(Of manhattanCustomLink) = Nothing manhattanPolygon.makeHole([next].perimeter, first, last, hole) If hole IsNot Nothing Then ' Holes are never merged, so bounds are of no interest Dim bounds As New manhattanCustomBounds(0, 0, 0, 0) Dim p As New manhattanPolygon(hole, bounds) todo.Add(p) End If If [next].perimeter.Count = 0 Then ' degenerate case: all of next was a hole; the empty polygon can be removed todo.RemoveAt(0) End If Else done.Add([next]) todo.RemoveAt(0) End If Loop Return done End Function ''' <summary> ''' Finish by merging shapes and making holes ''' </summary> Public Sub FinishShapes() MergeShapes() MakeHoles() End Sub ''' <summary> ''' Generate a string for all the polygons. For each grid value: ''' 1. A line stating its value ''' 2. A set of lines, one for each polygon for that value. ''' </summary> ''' <returns></returns> Public Function MakeString() As String Dim res As String = "" For Each kvp As KeyValuePair(Of Integer, manhattanCustomData) In ShapesTable Dim indx As Integer = kvp.Key Dim lp As List(Of manhattanPolygon) = kvp.Value.polygons res &= "Index " & indx.ToString(CultureInfo.CurrentUICulture) + ControlChars.Lf For i As Integer = 0 To lp.Count - 1 res &= manhattanPolygon.makeString(lp(i).perimeter) res &= ControlChars.Lf Next i Next kvp Return res End Function 'Private Delegate Function Row(ByVal index As Integer) As Integer 'Private Class ArrayRow ' Private row_Renamed() As Integer ' Public Sub New(ByVal row() As Integer) ' Me.row_Renamed = row ' End Sub ' Public Function Row(ByVal index As Integer) As Integer ' Return row_Renamed(index) ' End Function 'End Class ' ''' <summary> ' ''' Adds boxes from array row number rowNum ' ''' </summary> ' ''' <param name="row"></param> ' ''' <param name="rowNum"></param> ' ''' <param name="noData"></param> 'Public Sub addArrayRow(ByVal row() As Integer, ByVal rowNum As Integer, ByVal noData As Double, ByVal valueToUse As Double) ' Dim ar As New ArrayRow(row) ' addRow(New Row(AddressOf ar.Row), rowNum, row.Length, noData, valueToUse) 'End Sub ' ''' <summary> ' ''' Adds boxes from grid row number rowNum of length length ' ''' </summary> ' ''' <param name="rowNum"></param> ' ''' <param name="length"></param> 'Public Sub addMyGridRow(ByVal rowNum As Integer, ByVal length As Integer, ByVal NoDataValue As Double, ByVal valueToUse As Double) ' Dim gr As New manhattanCustomGridRow(grid, rowNum) ' addRow(New Row(AddressOf gr.Row), rowNum, length, NoDataValue, valueToUse) 'End Sub ' ''' <summary> ' ''' row behaves like an array, indexed from 0 to length - 1 ' ''' This creates boxes, where boxes are made from adjacent cells ' ''' of the array with the same values, and adds them as parts. ' ''' Nodata values are ignored. ' ''' </summary> ' ''' <param name="row"></param> ' ''' <param name="rowNum"></param> ' ''' <param name="length"></param> ' ''' <param name="noData"></param> 'Private Sub addRow(ByVal row As Row, ByVal rowNum As Integer, ByVal length As Integer, ByVal noData As Double, ByVal valueToUse As Double) ' Dim col As Integer = 0 ' Dim width As Integer = 1 ' Dim last As Integer = row(0) ' Dim bound As Integer = length - 1 ' Do While col < bound ' Dim [next] As Integer = row(col + 1) ' If [next] = last Then ' width += 1 ' Else ' If last <> noData AndAlso last = valueToUse Then ' Me.addShape(last, manhattanPolygon.box(col + 1 - width, rowNum, width), width) ' End If ' last = [next] ' width = 1 ' End If ' col += 1 ' Loop ' If last <> noData AndAlso last = valueToUse Then ' Me.addShape(last, manhattanPolygon.box(col + 1 - width, rowNum, width), width) ' End If 'End Sub 'Private Sub addRow(ByVal row As Row, ByVal rowNum As Integer, ByVal length As Integer, ByVal noData As Double) ' Dim width As Integer = 1 ' Dim last As Integer = row(0) ' Dim bound As Integer = length - 1 ' Dim col As Integer ' For col = 0 To bound ' Dim NextValue As Integer = row(col + 1) ' If NextValue = last Then ' width += 1 ' Else ' If last <> noData Then ' Me.addShape(last, manhattanPolygon.box(col + 1 - width, rowNum, width), width) ' End If ' last = NextValue ' width = 1 ' End If ' col += 1 ' Next ' If last <> noData Then ' Me.addShape(last, manhattanPolygon.box(col + 1 - width, rowNum, width), width) ' End If 'End Sub ''' <summary> ''' Converts grid to a shapefile, replacing any existing shapefile. ''' Assumed to be an integer grid. ''' Attribute "BasinID" is populated with the grid values ''' Attribute "AREA" is populated with the area of each polygon. ''' </summary> ''' <returns>null if any errors, else FeatureSet</returns> Public Function GridToShapeManhattan() As FeatureSet Return GridToShapeManhattan("BasinID", "AREA") End Function ''' <summary> ''' Converts grid to a shapefile, replacing any existing shapefile. ''' Assumed to be an integer grid. ''' Attribute GridValueFieldName is populated with the grid values ''' Attribute "AREA" is populated with the area of each polygon. ''' </summary> ''' <returns>null if any errors, else FeatureSet</returns> Public Function GridToShapeManhattan(ByVal GridValueFieldName As String, ByVal AreaFieldName As String) As FeatureSet Dim grid As IRaster = Raster.OpenFile(gridFilePath) '// origin (taken as column zero and row zero) is at the top left of the grid Dim startC As Coordinate = grid.CellToProj(0, 0) startC.X -= (grid.CellWidth / 2) startC.Y += (grid.CellHeight / 2) Dim MainOffset As New ManhattanCustomOffSet(startC, grid.CellWidth, grid.CellHeight) Dim NoDataValue As Double = grid.NoDataValue Dim numRows As Integer = grid.EndRow Dim numCols As Integer = grid.EndColumn - 1 Dim width As Integer Dim GridValue As Integer Dim Col As Integer For Row As Integer = 0 To numRows - 1 GridValue = System.Convert.ToInt32(grid.Value(Row, 0), CultureInfo.InvariantCulture) width = 1 For Col = 1 To numCols Dim NextGridValue As Integer = System.Convert.ToInt32(grid.Value(Row, Col), CultureInfo.InvariantCulture) If NextGridValue = GridValue Then width += 1 Else If GridValue <> NoDataValue Then Me.AddShape(GridValue, manhattanPolygon.box(Col - width, Row, width), width) End If GridValue = NextGridValue width = 1 End If Next Col If GridValue <> NoDataValue Then Me.AddShape(GridValue, manhattanPolygon.box(Col - width, Row, width), width) End If Next Row Me.FinishShapes() Dim PolygonFeatureSet As New FeatureSet(FeatureType.Polygon) With { .Projection = grid.Projection } grid.Close() AddFieldToFS(PolygonFeatureSet, GridValueFieldName, GetType(Integer)) AddFieldToFS(PolygonFeatureSet, AreaFieldName, GetType(Double)) For Each GridValue In Me.ShapesTable.Keys Dim simplePolygon As Dictionary(Of Integer, ManhattanPolygonParts) = MainOffset.MakeShape(ShapesTable(GridValue).polygons) If simplePolygon Is Nothing Then Continue For Else For Each s As KeyValuePair(Of Integer, ManhattanPolygonParts) In simplePolygon Dim COORDS As New List(Of Coordinate) For Each S1 As KeyValuePair(Of Integer, Coordinate) In s.Value.Points COORDS.Add(S1.Value) Next If COORDS.Count > 0 Then Dim newPolygon As Geometry = New Polygon(New LinearRing(COORDS.ToArray())) Dim addedFEAT As IFeature = PolygonFeatureSet.AddFeature(newPolygon) addedFEAT.DataRow(0) = GridValue addedFEAT.DataRow(1) = addedFEAT.Geometry.Area addedFEAT.DataRow.AcceptChanges() End If Next End If Next GridValue Return PolygonFeatureSet End Function Public Shared Sub AddFieldToFS(ByVal polygonSF As FeatureSet, ByVal fieldName As String, ByVal dataType As Type) Dim exists As Boolean = False For Each c As DataColumn In polygonSF.DataTable.Columns If c.ColumnName.ToLower = fieldName.ToLower Then exists = True End If Next If Not exists Then Dim newCol As New DataColumn(fieldName, dataType) polygonSF.DataTable.Columns.Add(newCol) polygonSF.DataTable.AcceptChanges() End If End Sub End Class End Namespace
pergerch/DotSpatial
Source/DotSpatial.Plugins.Taudem.Port/Manhattan/ManhattanShapes.vb
Visual Basic
mit
16,528
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.ErrorReporting Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities.DocumentationCommentXmlNames Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Partial Friend Class XmlDocCommentCompletionProvider Inherits AbstractDocCommentCompletionProvider(Of DocumentationCommentTriviaSyntax) Public Sub New() MyBase.New(s_defaultRules) End Sub Friend Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean Dim isStartOfTag = text(characterPosition) = "<"c Dim isClosingTag = (text(characterPosition) = "/"c AndAlso characterPosition > 0 AndAlso text(characterPosition - 1) = "<"c) Dim isDoubleQuote = text(characterPosition) = """"c Return isStartOfTag OrElse isClosingTag OrElse isDoubleQuote OrElse IsTriggerAfterSpaceOrStartOfWordCharacter(text, characterPosition, options) End Function Public Function GetPreviousTokenIfTouchingText(token As SyntaxToken, position As Integer) As SyntaxToken Return If(token.IntersectsWith(position) AndAlso IsText(token), token.GetPreviousToken(includeSkipped:=True), token) End Function Private Function IsText(token As SyntaxToken) As Boolean Return token.IsKind(SyntaxKind.XmlNameToken, SyntaxKind.XmlTextLiteralToken, SyntaxKind.IdentifierToken) End Function Protected Overrides Async Function GetItemsWorkerAsync(document As Document, position As Integer, trigger As CompletionTrigger, cancellationToken As CancellationToken) As Task(Of IEnumerable(Of CompletionItem)) Try Dim tree = Await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(False) Dim token = tree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments:=True) Dim parent = token.GetAncestor(Of DocumentationCommentTriviaSyntax)() If parent Is Nothing Then Return Nothing End If ' If the user is typing in xml text, don't trigger on backspace. If token.IsKind(SyntaxKind.XmlTextLiteralToken) AndAlso trigger.Kind = CompletionTriggerKind.Deletion Then Return Nothing End If ' Never provide any items inside a cref If token.Parent.IsKind(SyntaxKind.XmlString) AndAlso token.Parent.Parent.IsKind(SyntaxKind.XmlAttribute) Then Dim attribute = DirectCast(token.Parent.Parent, XmlAttributeSyntax) Dim name = TryCast(attribute.Name, XmlNameSyntax) Dim value = TryCast(attribute.Value, XmlStringSyntax) If name?.LocalName.ValueText = CrefAttributeName AndAlso Not token = value?.EndQuoteToken Then Return Nothing End If End If If token.Parent.GetAncestor(Of XmlCrefAttributeSyntax)() IsNot Nothing Then Return Nothing End If Dim items = New List(Of CompletionItem)() Dim attachedToken = parent.ParentTrivia.Token If attachedToken.Kind = SyntaxKind.None Then Return items End If Dim declaration = attachedToken.GetAncestor(Of DeclarationStatementSyntax)() ' Maybe we're going to suggest the close tag If token.Kind = SyntaxKind.LessThanSlashToken Then Return GetCloseTagItem(token) ElseIf token.IsKind(SyntaxKind.XmlNameToken) AndAlso token.GetPreviousToken().IsKind(SyntaxKind.LessThanSlashToken) Then Return GetCloseTagItem(token.GetPreviousToken()) End If Dim semanticModel = Await document.GetSemanticModelForNodeAsync(attachedToken.Parent, cancellationToken).ConfigureAwait(False) Dim symbol As ISymbol = Nothing If declaration IsNot Nothing Then symbol = semanticModel.GetDeclaredSymbol(declaration, cancellationToken) End If If symbol IsNot Nothing Then ' Maybe we're going to do attribute completion TryGetAttributes(token, position, items, symbol) If items.Any() Then Return items End If End If If trigger.Kind = CompletionTriggerKind.Insertion AndAlso Not trigger.Character = """"c AndAlso Not trigger.Character = "<"c Then ' With the use of IsTriggerAfterSpaceOrStartOfWordCharacter, the code below is much ' too aggressive at suggesting tags, so exit early before degrading the experience Return items End If items.AddRange(GetAlwaysVisibleItems()) Dim parentElement = token.GetAncestor(Of XmlElementSyntax)() Dim grandParent = parentElement?.Parent If grandParent.IsKind(SyntaxKind.XmlElement) Then ' Avoid including language keywords when following < Or <text, since these cases should only be ' attempting to complete the XML name (which for language keywords Is 'see'). The VB parser treats ' spaces after a < character as trailing whitespace, even if an identifier follows it on the same line. ' Therefore, the consistent VB experience says we never show keywords for < followed by spaces. Dim xmlNameOnly = token.IsKind(SyntaxKind.LessThanToken) OrElse token.Parent.IsKind(SyntaxKind.XmlName) Dim includeKeywords = Not xmlNameOnly items.AddRange(GetNestedItems(symbol, includeKeywords)) AddXmlElementItems(items, grandParent) ElseIf token.Parent.IsKind(SyntaxKind.XmlText) AndAlso token.Parent.IsParentKind(SyntaxKind.DocumentationCommentTrivia) Then ' Top level, without tag: ' ''' $$ items.AddRange(GetTopLevelItems(symbol, parent)) ElseIf token.Parent.IsKind(SyntaxKind.XmlText) AndAlso token.Parent.Parent.IsKind(SyntaxKind.XmlElement) Then items.AddRange(GetNestedItems(symbol, includeKeywords:=True)) Dim xmlElement = token.Parent.Parent AddXmlElementItems(items, xmlElement) ElseIf grandParent.IsKind(SyntaxKind.DocumentationCommentTrivia) Then ' Top level, with tag: ' ''' <$$ ' ''' <tag$$ items.AddRange(GetTopLevelItems(symbol, parent)) End If If token.Parent.IsKind(SyntaxKind.XmlElementStartTag, SyntaxKind.XmlName) AndAlso parentElement.IsParentKind(SyntaxKind.XmlElement) Then AddXmlElementItems(items, parentElement.Parent) End If Return items Catch e As Exception When FatalError.ReportWithoutCrashUnlessCanceled(e) Return SpecializedCollections.EmptyEnumerable(Of CompletionItem) End Try End Function Private Sub AddXmlElementItems(items As List(Of CompletionItem), xmlElement As SyntaxNode) Dim startTagName = GetStartTagName(xmlElement) If startTagName = ListElementName Then items.AddRange(GetListItems()) ElseIf startTagName = ListHeaderElementName Then items.AddRange(GetListHeaderItems()) ElseIf startTagName = ItemElementName Then items.AddRange(GetItemTagItems()) End If End Sub Private Function GetCloseTagItem(token As SyntaxToken) As IEnumerable(Of CompletionItem) Dim endTag = TryCast(token.Parent, XmlElementEndTagSyntax) If endTag Is Nothing Then Return Nothing End If Dim element = TryCast(endTag.Parent, XmlElementSyntax) If element Is Nothing Then Return Nothing End If Dim startElement = element.StartTag Dim name = TryCast(startElement.Name, XmlNameSyntax) If name Is Nothing Then Return Nothing End If Dim nameToken = name.LocalName If Not nameToken.IsMissing AndAlso nameToken.ValueText.Length > 0 Then Return SpecializedCollections.SingletonEnumerable(CreateCompletionItem(nameToken.ValueText, nameToken.ValueText & ">", String.Empty)) End If Return Nothing End Function Private Shared Function GetStartTagName(element As SyntaxNode) As String Return DirectCast(DirectCast(element, XmlElementSyntax).StartTag.Name, XmlNameSyntax).LocalName.ValueText End Function Private Sub TryGetAttributes(token As SyntaxToken, position As Integer, items As List(Of CompletionItem), symbol As ISymbol) Dim tagNameSyntax As XmlNameSyntax = Nothing Dim tagAttributes As SyntaxList(Of XmlNodeSyntax) = Nothing Dim startTagSyntax = token.GetAncestor(Of XmlElementStartTagSyntax)() If startTagSyntax IsNot Nothing Then tagNameSyntax = TryCast(startTagSyntax.Name, XmlNameSyntax) tagAttributes = startTagSyntax.Attributes Else Dim emptyElementSyntax = token.GetAncestor(Of XmlEmptyElementSyntax)() If emptyElementSyntax IsNot Nothing Then tagNameSyntax = TryCast(emptyElementSyntax.Name, XmlNameSyntax) tagAttributes = emptyElementSyntax.Attributes End If End If If tagNameSyntax IsNot Nothing Then Dim targetToken = GetPreviousTokenIfTouchingText(token, position) Dim tagName = tagNameSyntax.LocalName.ValueText If targetToken.IsChildToken(Function(n As XmlNameSyntax) n.LocalName) AndAlso targetToken.Parent Is tagNameSyntax Then ' <exception | items.AddRange(GetAttributes(tagName, tagAttributes)) End If '<exception a| If targetToken.IsChildToken(Function(n As XmlNameSyntax) n.LocalName) AndAlso targetToken.Parent.IsParentKind(SyntaxKind.XmlAttribute) Then ' <exception | items.AddRange(GetAttributes(tagName, tagAttributes)) End If '<exception a=""| If (targetToken.IsChildToken(Function(s As XmlStringSyntax) s.EndQuoteToken) AndAlso targetToken.Parent.IsParentKind(SyntaxKind.XmlAttribute)) OrElse targetToken.IsChildToken(Function(a As XmlNameAttributeSyntax) a.EndQuoteToken) OrElse targetToken.IsChildToken(Function(a As XmlCrefAttributeSyntax) a.EndQuoteToken) Then items.AddRange(GetAttributes(tagName, tagAttributes)) End If ' <param name="|" If (targetToken.IsChildToken(Function(s As XmlStringSyntax) s.StartQuoteToken) AndAlso targetToken.Parent.IsParentKind(SyntaxKind.XmlAttribute)) OrElse targetToken.IsChildToken(Function(a As XmlNameAttributeSyntax) a.StartQuoteToken) Then Dim attributeName As String Dim xmlAttributeName = targetToken.GetAncestor(Of XmlNameAttributeSyntax)() If xmlAttributeName IsNot Nothing Then attributeName = xmlAttributeName.Name.LocalName.ValueText Else attributeName = DirectCast(targetToken.GetAncestor(Of XmlAttributeSyntax)().Name, XmlNameSyntax).LocalName.ValueText End If items.AddRange(GetAttributeValueItems(symbol, tagName, attributeName)) End If End If End Sub Protected Overrides Iterator Function GetKeywordNames() As IEnumerable(Of String) Yield SyntaxFacts.GetText(SyntaxKind.NothingKeyword) Yield SyntaxFacts.GetText(SyntaxKind.SharedKeyword) Yield SyntaxFacts.GetText(SyntaxKind.OverridableKeyword) Yield SyntaxFacts.GetText(SyntaxKind.TrueKeyword) Yield SyntaxFacts.GetText(SyntaxKind.FalseKeyword) Yield SyntaxFacts.GetText(SyntaxKind.MustInheritKeyword) Yield SyntaxFacts.GetText(SyntaxKind.NotOverridableKeyword) Yield SyntaxFacts.GetText(SyntaxKind.AsyncKeyword) Yield SyntaxFacts.GetText(SyntaxKind.AwaitKeyword) End Function Protected Overrides Function GetExistingTopLevelElementNames(parentTrivia As DocumentationCommentTriviaSyntax) As IEnumerable(Of String) Return parentTrivia.Content _ .Select(Function(node) GetElementNameAndAttributes(node).Name) _ .WhereNotNull() End Function Protected Overrides Function GetExistingTopLevelAttributeValues(syntax As DocumentationCommentTriviaSyntax, elementName As String, attributeName As String) As IEnumerable(Of String) Dim attributeValues = SpecializedCollections.EmptyEnumerable(Of String)() For Each node In syntax.Content Dim nameAndAttributes = GetElementNameAndAttributes(node) If nameAndAttributes.Name = elementName Then attributeValues = attributeValues.Concat( nameAndAttributes.Attributes _ .Where(Function(attribute) GetAttributeName(attribute) = attributeName) _ .Select(AddressOf GetAttributeValue)) End If Next Return attributeValues End Function Private Function GetElementNameAndAttributes(node As XmlNodeSyntax) As (Name As String, Attributes As SyntaxList(Of XmlNodeSyntax)) Dim nameSyntax As XmlNameSyntax = Nothing Dim attributes As SyntaxList(Of XmlNodeSyntax) = Nothing If node.IsKind(SyntaxKind.XmlEmptyElement) Then Dim emptyElementSyntax = DirectCast(node, XmlEmptyElementSyntax) nameSyntax = TryCast(emptyElementSyntax.Name, XmlNameSyntax) attributes = emptyElementSyntax.Attributes ElseIf node.IsKind(SyntaxKind.XmlElement) Then Dim elementSyntax = DirectCast(node, XmlElementSyntax) nameSyntax = TryCast(elementSyntax.StartTag.Name, XmlNameSyntax) attributes = elementSyntax.StartTag.Attributes End If Return (nameSyntax?.LocalName.ValueText, attributes) End Function Private Function GetAttributeValue(attribute As XmlNodeSyntax) As String If TypeOf attribute Is XmlAttributeSyntax Then ' Decode any XML enities and concatentate the results Return DirectCast(DirectCast(attribute, XmlAttributeSyntax).Value, XmlStringSyntax).TextTokens.GetValueText() End If Return TryCast(attribute, XmlNameAttributeSyntax)?.Reference?.Identifier.ValueText End Function Private Function GetAttributes(tagName As String, attributes As SyntaxList(Of XmlNodeSyntax)) As IEnumerable(Of CompletionItem) Dim existingAttributeNames = attributes.Select(AddressOf GetAttributeName).WhereNotNull().ToSet() Return GetAttributeItems(tagName, existingAttributeNames) End Function Private Shared Function GetAttributeName(node As XmlNodeSyntax) As String Dim nameSyntax As XmlNameSyntax = node.TypeSwitch( Function(attribute As XmlAttributeSyntax) TryCast(attribute.Name, XmlNameSyntax), Function(attribute As XmlNameAttributeSyntax) attribute.Name, Function(attribute As XmlCrefAttributeSyntax) attribute.Name) Return nameSyntax?.LocalName.ValueText End Function Private Shared s_defaultRules As CompletionItemRules = CompletionItemRules.Create( filterCharacterRules:=FilterRules, enterKeyRule:=EnterKeyRule.Never) End Class End Namespace
abock/roslyn
src/Features/VisualBasic/Portable/Completion/CompletionProviders/XmlDocCommentCompletionProvider.vb
Visual Basic
mit
17,297
' 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.CodeStyle Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests <UseExportProvider> Public Class CSharpEditorConfigGeneratorTests Inherits TestBase <ConditionalFact(GetType(IsEnglishLocal))> Public Sub TestEditorConfigGeneratorDefault() Using workspace = TestWorkspace.CreateCSharp("") Dim expectedText = "# Remove the line below if you want to inherit .editorconfig settings from higher directories root = true # C# files [*.cs] #### Core EditorConfig Options #### # Indentation and spacing indent_size = 4 indent_style = space tab_width = 4 # New line preferences end_of_line = crlf insert_final_newline = false #### .NET Coding Conventions #### # Organize usings dotnet_separate_import_directive_groups = false dotnet_sort_system_directives_first = true # this. and Me. preferences dotnet_style_qualification_for_event = false:silent dotnet_style_qualification_for_field = false:silent dotnet_style_qualification_for_method = false:silent dotnet_style_qualification_for_property = false:silent # Language keywords vs BCL types preferences dotnet_style_predefined_type_for_locals_parameters_members = true:silent dotnet_style_predefined_type_for_member_access = true:silent # Parentheses preferences dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent # Modifier preferences dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent # Expression-level preferences csharp_style_deconstructed_variable_declaration = true:suggestion csharp_style_inlined_variable_declaration = true:suggestion csharp_style_throw_expression = true:suggestion dotnet_style_coalesce_expression = true:suggestion dotnet_style_collection_initializer = true:suggestion dotnet_style_explicit_tuple_names = true:suggestion dotnet_style_null_propagation = true:suggestion dotnet_style_object_initializer = true:suggestion dotnet_style_prefer_auto_properties = true:silent dotnet_style_prefer_compound_assignment = true:suggestion dotnet_style_prefer_conditional_expression_over_assignment = true:silent dotnet_style_prefer_conditional_expression_over_return = true:silent dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion dotnet_style_prefer_inferred_tuple_names = true:suggestion dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion # Field preferences dotnet_style_readonly_field = true:suggestion # Parameter preferences dotnet_code_quality_unused_parameters = all:suggestion #### C# Coding Conventions #### # var preferences csharp_style_var_elsewhere = false:silent csharp_style_var_for_built_in_types = false:silent csharp_style_var_when_type_is_apparent = false:silent # Expression-bodied members csharp_style_expression_bodied_accessors = true:silent csharp_style_expression_bodied_constructors = false:silent csharp_style_expression_bodied_indexers = true:silent csharp_style_expression_bodied_lambdas = true:silent csharp_style_expression_bodied_local_functions = false:silent csharp_style_expression_bodied_methods = false:silent csharp_style_expression_bodied_operators = false:silent csharp_style_expression_bodied_properties = true:silent # Pattern matching preferences csharp_style_pattern_matching_over_as_with_null_check = true:suggestion csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion csharp_style_prefer_switch_expression = true:suggestion # Null-checking preferences csharp_style_conditional_delegate_call = true:suggestion # Modifier preferences csharp_prefer_static_local_function = true:suggestion csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async # Code-block preferences csharp_prefer_braces = true:silent csharp_prefer_simple_using_statement = true:suggestion # Expression-level preferences csharp_prefer_simple_default_expression = true:suggestion csharp_style_pattern_local_over_anonymous_function = true:suggestion csharp_style_prefer_index_operator = true:suggestion csharp_style_prefer_range_operator = true:suggestion csharp_style_unused_value_assignment_preference = discard_variable:suggestion csharp_style_unused_value_expression_statement_preference = discard_variable:silent # 'using' directive preferences csharp_using_directive_placement = outside_namespace:silent #### C# Formatting Rules #### # New line preferences csharp_new_line_before_catch = true csharp_new_line_before_else = true csharp_new_line_before_finally = true csharp_new_line_before_members_in_anonymous_types = true csharp_new_line_before_members_in_object_initializers = true csharp_new_line_before_open_brace = all csharp_new_line_between_query_expression_clauses = true # Indentation preferences csharp_indent_block_contents = true csharp_indent_braces = false csharp_indent_case_contents = true csharp_indent_case_contents_when_block = true csharp_indent_labels = one_less_than_current csharp_indent_switch_labels = true # Space preferences csharp_space_after_cast = false csharp_space_after_colon_in_inheritance_clause = true csharp_space_after_comma = true csharp_space_after_dot = false csharp_space_after_keywords_in_control_flow_statements = true csharp_space_after_semicolon_in_for_statement = true csharp_space_around_binary_operators = before_and_after csharp_space_around_declaration_statements = false csharp_space_before_colon_in_inheritance_clause = true csharp_space_before_comma = false csharp_space_before_dot = false csharp_space_before_open_square_brackets = false csharp_space_before_semicolon_in_for_statement = false csharp_space_between_empty_square_brackets = false csharp_space_between_method_call_empty_parameter_list_parentheses = false csharp_space_between_method_call_name_and_opening_parenthesis = false csharp_space_between_method_call_parameter_list_parentheses = false csharp_space_between_method_declaration_empty_parameter_list_parentheses = false csharp_space_between_method_declaration_name_and_open_parenthesis = false csharp_space_between_method_declaration_parameter_list_parentheses = false csharp_space_between_parentheses = false csharp_space_between_square_brackets = false # Wrapping preferences csharp_preserve_single_line_blocks = true csharp_preserve_single_line_statements = true #### Naming styles #### # Naming rules dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion dotnet_naming_rule.types_should_be_pascal_case.symbols = types dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case # Symbol specifications dotnet_naming_symbols.interface.applicable_kinds = interface dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected dotnet_naming_symbols.interface.required_modifiers = dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected dotnet_naming_symbols.types.required_modifiers = dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected dotnet_naming_symbols.non_field_members.required_modifiers = # Naming styles dotnet_naming_style.pascal_case.required_prefix = dotnet_naming_style.pascal_case.required_suffix = dotnet_naming_style.pascal_case.word_separator = dotnet_naming_style.pascal_case.capitalization = pascal_case dotnet_naming_style.begins_with_i.required_prefix = I dotnet_naming_style.begins_with_i.required_suffix = dotnet_naming_style.begins_with_i.word_separator = dotnet_naming_style.begins_with_i.capitalization = pascal_case " Dim editorConfigOptions = CSharp.Options.Formatting.CodeStylePage.TestAccessor.GetEditorConfigOptions() Dim actualText = EditorConfigFileGenerator.Generate(editorConfigOptions, workspace.Options, LanguageNames.CSharp) AssertEx.EqualOrDiff(expectedText, actualText) End Using End Sub <ConditionalFact(GetType(IsEnglishLocal))> Public Sub TestEditorConfigGeneratorToggleOptions() Using workspace = TestWorkspace.CreateCSharp("") Dim changedOptions = workspace.Options.WithChangedOption(New OptionKey(CodeStyleOptions.PreferExplicitTupleNames, LanguageNames.CSharp), New CodeStyleOption(Of Boolean)(False, NotificationOption.[Error])) Dim expectedText = "# Remove the line below if you want to inherit .editorconfig settings from higher directories root = true # C# files [*.cs] #### Core EditorConfig Options #### # Indentation and spacing indent_size = 4 indent_style = space tab_width = 4 # New line preferences end_of_line = crlf insert_final_newline = false #### .NET Coding Conventions #### # Organize usings dotnet_separate_import_directive_groups = false dotnet_sort_system_directives_first = true # this. and Me. preferences dotnet_style_qualification_for_event = false:silent dotnet_style_qualification_for_field = false:silent dotnet_style_qualification_for_method = false:silent dotnet_style_qualification_for_property = false:silent # Language keywords vs BCL types preferences dotnet_style_predefined_type_for_locals_parameters_members = true:silent dotnet_style_predefined_type_for_member_access = true:silent # Parentheses preferences dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent # Modifier preferences dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent # Expression-level preferences csharp_style_deconstructed_variable_declaration = true:suggestion csharp_style_inlined_variable_declaration = true:suggestion csharp_style_throw_expression = true:suggestion dotnet_style_coalesce_expression = true:suggestion dotnet_style_collection_initializer = true:suggestion dotnet_style_explicit_tuple_names = false:error dotnet_style_null_propagation = true:suggestion dotnet_style_object_initializer = true:suggestion dotnet_style_prefer_auto_properties = true:silent dotnet_style_prefer_compound_assignment = true:suggestion dotnet_style_prefer_conditional_expression_over_assignment = true:silent dotnet_style_prefer_conditional_expression_over_return = true:silent dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion dotnet_style_prefer_inferred_tuple_names = true:suggestion dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion # Field preferences dotnet_style_readonly_field = true:suggestion # Parameter preferences dotnet_code_quality_unused_parameters = all:suggestion #### C# Coding Conventions #### # var preferences csharp_style_var_elsewhere = false:silent csharp_style_var_for_built_in_types = false:silent csharp_style_var_when_type_is_apparent = false:silent # Expression-bodied members csharp_style_expression_bodied_accessors = true:silent csharp_style_expression_bodied_constructors = false:silent csharp_style_expression_bodied_indexers = true:silent csharp_style_expression_bodied_lambdas = true:silent csharp_style_expression_bodied_local_functions = false:silent csharp_style_expression_bodied_methods = false:silent csharp_style_expression_bodied_operators = false:silent csharp_style_expression_bodied_properties = true:silent # Pattern matching preferences csharp_style_pattern_matching_over_as_with_null_check = true:suggestion csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion csharp_style_prefer_switch_expression = true:suggestion # Null-checking preferences csharp_style_conditional_delegate_call = true:suggestion # Modifier preferences csharp_prefer_static_local_function = true:suggestion csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async # Code-block preferences csharp_prefer_braces = true:silent csharp_prefer_simple_using_statement = true:suggestion # Expression-level preferences csharp_prefer_simple_default_expression = true:suggestion csharp_style_pattern_local_over_anonymous_function = true:suggestion csharp_style_prefer_index_operator = true:suggestion csharp_style_prefer_range_operator = true:suggestion csharp_style_unused_value_assignment_preference = discard_variable:suggestion csharp_style_unused_value_expression_statement_preference = discard_variable:silent # 'using' directive preferences csharp_using_directive_placement = outside_namespace:silent #### C# Formatting Rules #### # New line preferences csharp_new_line_before_catch = true csharp_new_line_before_else = true csharp_new_line_before_finally = true csharp_new_line_before_members_in_anonymous_types = true csharp_new_line_before_members_in_object_initializers = true csharp_new_line_before_open_brace = all csharp_new_line_between_query_expression_clauses = true # Indentation preferences csharp_indent_block_contents = true csharp_indent_braces = false csharp_indent_case_contents = true csharp_indent_case_contents_when_block = true csharp_indent_labels = one_less_than_current csharp_indent_switch_labels = true # Space preferences csharp_space_after_cast = false csharp_space_after_colon_in_inheritance_clause = true csharp_space_after_comma = true csharp_space_after_dot = false csharp_space_after_keywords_in_control_flow_statements = true csharp_space_after_semicolon_in_for_statement = true csharp_space_around_binary_operators = before_and_after csharp_space_around_declaration_statements = false csharp_space_before_colon_in_inheritance_clause = true csharp_space_before_comma = false csharp_space_before_dot = false csharp_space_before_open_square_brackets = false csharp_space_before_semicolon_in_for_statement = false csharp_space_between_empty_square_brackets = false csharp_space_between_method_call_empty_parameter_list_parentheses = false csharp_space_between_method_call_name_and_opening_parenthesis = false csharp_space_between_method_call_parameter_list_parentheses = false csharp_space_between_method_declaration_empty_parameter_list_parentheses = false csharp_space_between_method_declaration_name_and_open_parenthesis = false csharp_space_between_method_declaration_parameter_list_parentheses = false csharp_space_between_parentheses = false csharp_space_between_square_brackets = false # Wrapping preferences csharp_preserve_single_line_blocks = true csharp_preserve_single_line_statements = true #### Naming styles #### # Naming rules dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion dotnet_naming_rule.types_should_be_pascal_case.symbols = types dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case # Symbol specifications dotnet_naming_symbols.interface.applicable_kinds = interface dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected dotnet_naming_symbols.interface.required_modifiers = dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected dotnet_naming_symbols.types.required_modifiers = dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected dotnet_naming_symbols.non_field_members.required_modifiers = # Naming styles dotnet_naming_style.pascal_case.required_prefix = dotnet_naming_style.pascal_case.required_suffix = dotnet_naming_style.pascal_case.word_separator = dotnet_naming_style.pascal_case.capitalization = pascal_case dotnet_naming_style.begins_with_i.required_prefix = I dotnet_naming_style.begins_with_i.required_suffix = dotnet_naming_style.begins_with_i.word_separator = dotnet_naming_style.begins_with_i.capitalization = pascal_case " Dim editorConfigOptions = CSharp.Options.Formatting.CodeStylePage.TestAccessor.GetEditorConfigOptions() Dim actualText = EditorConfigFileGenerator.Generate(editorConfigOptions, changedOptions, LanguageNames.CSharp) AssertEx.EqualOrDiff(expectedText, actualText) End Using End Sub End Class End Namespace
aelij/roslyn
src/VisualStudio/Core/Test/Options/CSharpEditorConfigGeneratorTests.vb
Visual Basic
apache-2.0
18,406
' 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.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Differencing Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.EditAndContinue.UnitTests Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EditAndContinue Imports Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.UnitTests Friend Module EditAndContinueValidation <Extension> Friend Sub VerifyRudeDiagnostics(editScript As EditScript(Of SyntaxNode), ParamArray expectedDiagnostics As RudeEditDiagnosticDescription()) VerifyRudeDiagnostics(editScript, ActiveStatementsDescription.Empty, expectedDiagnostics) End Sub <Extension> Friend Sub VerifyRudeDiagnostics(editScript As EditScript(Of SyntaxNode), description As ActiveStatementsDescription, ParamArray expectedDiagnostics As RudeEditDiagnosticDescription()) VerifySemantics(editScript, description, diagnostics:=expectedDiagnostics) End Sub <Extension> Friend Sub VerifyLineEdits(editScript As EditScript(Of SyntaxNode), lineEdits As SourceLineUpdate(), Optional semanticEdits As SemanticEditDescription() = Nothing, Optional diagnostics As RudeEditDiagnosticDescription() = Nothing) Assert.NotEmpty(lineEdits) VerifyLineEdits( editScript, {New SequencePointUpdates(editScript.Match.OldRoot.SyntaxTree.FilePath, lineEdits.ToImmutableArray())}, semanticEdits, diagnostics) End Sub <Extension> Friend Sub VerifyLineEdits(editScript As EditScript(Of SyntaxNode), lineEdits As SequencePointUpdates(), Optional semanticEdits As SemanticEditDescription() = Nothing, Optional diagnostics As RudeEditDiagnosticDescription() = Nothing) Dim validator = New VisualBasicEditAndContinueTestHelpers() validator.VerifyLineEdits(editScript, lineEdits, semanticEdits, diagnostics) End Sub <Extension> Friend Sub VerifySemanticDiagnostics(editScript As EditScript(Of SyntaxNode), ParamArray expectedDiagnostics As RudeEditDiagnosticDescription()) VerifySemantics( {editScript}, {New DocumentAnalysisResultsDescription(diagnostics:=expectedDiagnostics)}) End Sub <Extension> Friend Sub VerifySemanticDiagnostics(editScript As EditScript(Of SyntaxNode), targetFrameworks As TargetFramework(), ParamArray expectedDiagnostics As RudeEditDiagnosticDescription()) VerifySemantics( {editScript}, {New DocumentAnalysisResultsDescription(diagnostics:=expectedDiagnostics)}, targetFrameworks:=targetFrameworks) End Sub <Extension> Friend Sub VerifySemantics(editScript As EditScript(Of SyntaxNode), Optional activeStatements As ActiveStatementsDescription = Nothing, Optional semanticEdits As SemanticEditDescription() = Nothing, Optional diagnostics As RudeEditDiagnosticDescription() = Nothing, Optional targetFrameworks As TargetFramework() = Nothing, Optional capabilities As EditAndContinueCapabilities? = Nothing) VerifySemantics( {editScript}, {New DocumentAnalysisResultsDescription(activeStatements, semanticEdits, lineEdits:=Nothing, diagnostics)}, targetFrameworks, capabilities) End Sub <Extension> Friend Sub VerifySemantics(editScripts As EditScript(Of SyntaxNode)(), expected As DocumentAnalysisResultsDescription(), Optional targetFrameworks As TargetFramework() = Nothing, Optional capabilities As EditAndContinueCapabilities? = Nothing) For Each framework In If(targetFrameworks, {TargetFramework.NetStandard20, TargetFramework.NetCoreApp}) Dim validator = New VisualBasicEditAndContinueTestHelpers() validator.VerifySemantics(editScripts, framework, expected, capabilities) Next End Sub End Module End Namespace
wvdd007/roslyn
src/EditorFeatures/VisualBasicTest/EditAndContinue/Helpers/EditAndContinueValidation.vb
Visual Basic
apache-2.0
5,105
' 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.FindUsages Namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToImplementation <[UseExportProvider]> Public Class GoToImplementationTests Private Async Function TestAsync(workspaceDefinition As XElement, Optional shouldSucceed As Boolean = True) As Task Await GoToHelpers.TestAsync( workspaceDefinition, Async Function(document As Document, position As Integer, context As SimpleFindUsagesContext) As Task Dim findUsagesService = document.GetLanguageService(Of IFindUsagesService) Await findUsagesService.FindImplementationsAsync(document, position, context).ConfigureAwait(False) End Function, shouldSucceed) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestEmptyFile() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> $$ </Document> </Project> </Workspace> Await TestAsync(workspace, shouldSucceed:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithSingleClass() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$C|] { } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithAbstractClass() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> abstract class [|$$C|] { } class [|D|] : C { } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithAbstractClassFromInterface() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface $$I { } abstract class [|C|] : I { } class [|D|] : C { } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithSealedClass() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> sealed class [|$$C|] { } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithStruct() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> struct [|$$C|] { } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithEnum() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> enum [|$$C|] { } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithNonAbstractClass() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$C|] { } class [|D|] : C { } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithSingleClassImplementation() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|C|] : I { } interface $$I { } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithTwoClassImplementations() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|C|] : I { } class [|D|] : I { } interface $$I { } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithOneMethodImplementation_01() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C : I { public void [|M|]() { } } interface I { void $$M(); } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithOneMethodImplementation_02() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C : I { public void [|M|]() { } } interface I { void [|$$M|]() {} } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithOneMethodImplementation_03() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C : I { void I.[|M|]() { } } interface I { void [|$$M|]() {} } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithOneMethodImplementation_04() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface C : I { void I.[|M|]() { } void M(); } interface I { void $$M(); } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithOneMethodImplementation_05() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface C : I { void I.[|M|]() { } void M(); } interface I { void [|$$M|]() {} } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithOneEventImplementation() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class C : I { public event EventHandler [|E|]; } interface I { event EventHandler $$E; } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithTwoMethodImplementations() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C : I { public void [|M|]() { } } class D : I { public void [|M|]() { } } interface I { void $$M(); } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithNonInheritedImplementation() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public void [|M|]() { } } class D : C, I { } interface I { void $$M(); } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> <WorkItem(6752, "https://github.com/dotnet/roslyn/issues/6752")> Public Async Function TestWithVirtualMethodImplementationWithInterfaceOnBaseClass() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C : I { public virtual void [|M|]() { } } class D : C { public override void [|M|]() { } } interface I { void $$M(); } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> <WorkItem(6752, "https://github.com/dotnet/roslyn/issues/6752")> Public Async Function TestWithVirtualMethodImplementationWithInterfaceOnDerivedClass() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public virtual void M() { } } class D : C, I { public override void [|M|]() { } } interface I { void $$M(); } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> <WorkItem(6752, "https://github.com/dotnet/roslyn/issues/6752")> Public Async Function TestWithVirtualMethodImplementationAndInterfaceImplementedOnDerivedType() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C : I { public virtual void [|M|]() { } } class D : C, I { public override void [|M|]() { } } interface I { void $$M(); } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> <WorkItem(6752, "https://github.com/dotnet/roslyn/issues/6752")> Public Async Function TestWithAbstractMethodImplementation() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C : I { public abstract void [|M|]() { } } class D : C { public override void [|M|]() { } }} interface I { void $$M(); } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithInterfaceMemberFromMetdataAtUseSite() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class C : IDisposable { public void [|Dispose|]() { IDisposable d; d.$$Dispose(); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithSimpleMethod() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public void [|$$M|]() { } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithOverridableMethodOnBase() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public virtual void [|$$M|]() { } } class D : C { public override void [|M|]() { } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> Public Async Function TestWithOverridableMethodOnImplementation() As Task ' Our philosophy is to only show derived in this case, since we know the implementation of ' D could never call C.M here Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public virtual void M() { } } class D : C { public override void [|$$M|]() { } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)> <WorkItem(19700, "https://github.com/dotnet/roslyn/issues/19700")> Public Async Function TestWithIntermediateAbstractOverrides() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> abstract class A { public virtual void $$[|M|]() { } } abstract class B : A { public abstract override void [|M|](); } sealed class C1 : B { public override void [|M|]() { } } sealed class C2 : A { public override void [|M|]() => base.M(); } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function End Class End Namespace
nguerrera/roslyn
src/EditorFeatures/Test2/GoToImplementation/GoToImplementationTests.vb
Visual Basic
apache-2.0
13,664
' Copyright (c) 2015 ZZZ Projects. All rights reserved ' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods) ' Website: http://www.zzzprojects.com/ ' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927 ' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library Public Module Extensions_488 ''' <summary> ''' A string extension method that query if '@this' contains any values. ''' </summary> ''' <param name="this">The @this to act on.</param> ''' <param name="values">A variable-length parameters list containing values.</param> ''' <returns>true if it contains any values, otherwise false.</returns> <System.Runtime.CompilerServices.Extension> _ Public Function ContainsAny(this As String, ParamArray values As String()) As Boolean For Each value As String In values If this.IndexOf(value) <> -1 Then Return True End If Next Return False End Function ''' <summary> ''' A string extension method that query if '@this' contains any values. ''' </summary> ''' <param name="this">The @this to act on.</param> ''' <param name="comparisonType">Type of the comparison.</param> ''' <param name="values">A variable-length parameters list containing values.</param> ''' <returns>true if it contains any values, otherwise false.</returns> <System.Runtime.CompilerServices.Extension> _ Public Function ContainsAny(this As String, comparisonType As StringComparison, ParamArray values As String()) As Boolean For Each value As String In values If this.IndexOf(value, comparisonType) <> -1 Then Return True End If Next Return False End Function End Module
mario-loza/Z.ExtensionMethods
src (VB.NET)/Z.ExtensionMethods.VB/Z.Core/System.String/String.ContainsAny.vb
Visual Basic
mit
1,727
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading.Tasks Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestWinmdCSInterfaceProjection() As Task Dim input = <Workspace> <Project Language="C#" CommonReferencesWinRT="true" AssemblyName="SampleComponent"> <CompilationOptions OutputType="WindowsRuntimeMetadata"/> <Document> using System; using Windows.Foundation; namespace SampleComponent { public sealed class Test1 : IDisposable { public void Dispose() { } void IDisposable.{|Definition:Dispose|}() { } public void Close() { } } public sealed class Test2 : IDisposable { public void {|Definition:Dispose|}() { } } public sealed class M { void Some() { Test1 t1 = new Test1(); t1.Dispose(); (t1 as IDisposable).[|$$Dispose|](); } } } </Document> </Project> </Workspace> Await TestAsync(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestWinmdVBInterfaceProjection() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferencesWinRT="true"> <CompilationOptions OutputType="WindowsRuntimeMetadata"/> <Document> Imports System Imports Windows.Foundation Public NotInheritable Class Class1 Implements IDisposable Private Sub {|Definition:Dispose|}() Implements IDisposable.[|Dispose|] End Sub Public Sub Close() End Sub End Class Public NotInheritable Class Class2 Implements IDisposable Private Sub {|Definition:IDisposable_Dispose|}() Implements IDisposable.[|Dispose|] Throw New NotImplementedException() End Sub Public Sub Dispose() End Sub End Class Public NotInheritable Class M Sub Some() Dim c1 As New Class1 Dim c3 = DirectCast(New Class1(), IDisposable) c3.[|Dispose|]() c1.Close() Dim c2 As IDisposable = CType(c1, IDisposable) c2.[|$$Dispose|]() End Sub End Class </Document> </Project> </Workspace> Await TestAsync(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestWinmdCSCollectionProjection() As Task Dim input = <Workspace> <Project Language="C#" CommonReferencesWinRT="true" AssemblyName="SampleComponent"> <CompilationOptions OutputType="WindowsRuntimeMetadata"/> <Document><![CDATA[ using System.Collections.Generic; using System.Collections; using Windows.Foundation.Collections; namespace SampleComponent { public sealed class Test : IEnumerable<int> { int[] x = new int[] { 1, 2, 3 }; IIterator<int> y; public IEnumerator<int> GetEnumerator() { for (int i = 0; i < 3; i++) { yield return x[i]; } } IEnumerator IEnumerable.GetEnumerator() { for(int i=0; i< 3; i++) { yield return x[i]; } } public IIterator<int> {|Definition:$$First|}() { return y; } } }]]> </Document> </Project> </Workspace> Await TestAsync(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestWinmdVBCollectionProjection() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferencesWinRT="true"> <CompilationOptions OutputType="WindowsRuntimeMetadata"/> <Document> Imports System.Collections Imports System.Collections.Generic Imports Windows.Foundation.Collections Public NotInheritable Class Class1 Implements IEnumerable(Of Integer) Dim x As IEnumerator(Of Integer) Dim y As IIterator(Of Integer) Public Function GetEnumerator() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator Return x End Function Private Function AGetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return x End Function Public Function {|Definition:$$First|}() As IIterator(Of Integer) Return y End Function End Class </Document> </Project> </Workspace> Await TestAsync(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestWinmdCSEventProjection() As Task Dim input = <Workspace> <Project Language="C#" CommonReferencesWinRT="true" AssemblyName="SampleComponent"> <CompilationOptions OutputType="WindowsRuntimeMetadata"/> <Document><![CDATA[ using System; using System.Runtime.InteropServices.WindowsRuntime; namespace SampleComponent { public sealed class Class1 { private EventRegistrationTokenTable<EventHandler<int>> A = null; public event EventHandler<int> {|Definition:AChange|} { add { return EventRegistrationTokenTable<EventHandler<int>> .GetOrCreateEventRegistrationTokenTable(ref A) .AddEventHandler(value); } remove { EventRegistrationTokenTable<EventHandler<int>> .GetOrCreateEventRegistrationTokenTable(ref A) .RemoveEventHandler(value); } } public void Foo() { Class1 c1 = new Class1(); Class2 c2 = new Class2(); c1.[|AChange|] += null; c1.[|$$AChange|] -= null; c2.AChange += null; c2.AChange -= null; } } public sealed class Class2 { public event EventHandler<int> AChange { add { throw null; } remove { throw null; } } } }]]> </Document> </Project> </Workspace> Await TestAsync(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestWinmdVBEventProjection() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferencesWinRT="true"> <CompilationOptions OutputType="WindowsRuntimeMetadata"/> <Document> Imports System Imports System.Runtime.InteropServices.WindowsRuntime Public NotInheritable Class Class1 Private A As _ EventRegistrationTokenTable(Of EventHandler(Of Integer)) Public Custom Event {|Definition:AChange|} As EventHandler(Of Integer) AddHandler(ByVal handler As EventHandler(Of Integer)) Return EventRegistrationTokenTable(Of EventHandler(Of Integer)). GetOrCreateEventRegistrationTokenTable(A). AddEventHandler(handler) End AddHandler RemoveHandler(ByVal handler As EventRegistrationToken) EventRegistrationTokenTable(Of EventHandler(Of Integer)). GetOrCreateEventRegistrationTokenTable(A). RemoveEventHandler(handler) End RemoveHandler RaiseEvent(ByVal sender As Class1, ByVal args As Integer) Dim temp As EventHandler(Of Integer) = EventRegistrationTokenTable(Of EventHandler(Of Integer)). GetOrCreateEventRegistrationTokenTable(A). InvocationList If temp IsNot Nothing Then temp(sender, args) End If End RaiseEvent End Event End Class Module N Public Event AChange As EventHandler(Of Integer) Public Sub Test() Dim c1 As New Class1 AddHandler c1.[|$$AChange|], AddressOf HandleSub End Sub Private Sub HandleSub(sender As Object, e As Integer) End Sub End Module </Document> </Project> </Workspace> Await TestAsync(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestWinmdCSAllIsWellTest() As Task Dim input = <Workspace> <Project Language="C#" CommonReferencesWinRT="true" AssemblyName="SampleComponent"> <CompilationOptions OutputType="WindowsRuntimeMetadata"/> <Document><![CDATA[ using System; using System.Collections; using System.Collections.Generic; namespace SampleComponent { public interface I { void Add(int item); } public sealed class Class1 : I, IList<int> { int IList<int>.this[int index] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } int ICollection<int>.Count { get { throw new NotImplementedException(); } } bool ICollection<int>.IsReadOnly { get { throw new NotImplementedException(); } } void ICollection<int>.{|Definition:Add|}(int item) { throw new NotImplementedException(); } public void Add(int item) { throw new NotImplementedException(); } void ICollection<int>.Clear() { throw new NotImplementedException(); } bool ICollection<int>.Contains(int item) { throw new NotImplementedException(); } void ICollection<int>.CopyTo(int[] array, int arrayIndex) { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } IEnumerator<int> IEnumerable<int>.GetEnumerator() { throw new NotImplementedException(); } int IList<int>.IndexOf(int item) { throw new NotImplementedException(); } void IList<int>.Insert(int index, int item) { throw new NotImplementedException(); } bool ICollection<int>.Remove(int item) { throw new NotImplementedException(); } void IList<int>.RemoveAt(int index) { throw new NotImplementedException(); } } public sealed class Class2 : IList<int> { public int this[int index] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public int Count { get { throw new NotImplementedException(); } } public bool IsReadOnly { get { throw new NotImplementedException(); } } public void {|Definition:Add|}(int item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(int item) { throw new NotImplementedException(); } public void CopyTo(int[] array, int arrayIndex) { throw new NotImplementedException(); } public IEnumerator<int> GetEnumerator() { throw new NotImplementedException(); } public int IndexOf(int item) { throw new NotImplementedException(); } public void Insert(int index, int item) { throw new NotImplementedException(); } public bool Remove(int item) { throw new NotImplementedException(); } public void RemoveAt(int index) { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } public sealed class Test { public void Foo() { Class1 c1 = new Class1(); Class1 c2 = new Class1(); Class2 c3 = new Class2(); c2.Add(3); c1.Add(3); c3.[|Add|](3); (c1 as IList<int>).[|$$Add|](3); } } }]]> </Document> </Project> </Workspace> Await TestAsync(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestWinmdVBAllIsWellTest() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferencesWinRT="true"> <CompilationOptions OutputType="WindowsRuntimeMetadata"/> <Document> Imports System Imports System.Collections Imports System.Collections.Generic Public Interface I Sub Add(ByVal item As Integer) End Interface Public NotInheritable Class Class1 Implements I, IList(Of Integer) Public ReadOnly Property Count As Integer Implements ICollection(Of Integer).Count Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property IsReadOnly As Boolean Implements ICollection(Of Integer).IsReadOnly Get Throw New NotImplementedException() End Get End Property Default Public Property Item(index As Integer) As Integer Implements IList(Of Integer).Item Get Throw New NotImplementedException() End Get Set(value As Integer) Throw New NotImplementedException() End Set End Property Public Sub Add(item As Integer) Implements I.Add Throw New NotImplementedException() End Sub Public Sub Clear() Implements ICollection(Of Integer).Clear Throw New NotImplementedException() End Sub Public Sub CopyTo(array() As Integer, arrayIndex As Integer) Implements ICollection(Of Integer).CopyTo Throw New NotImplementedException() End Sub Public Sub Insert(index As Integer, item As Integer) Implements IList(Of Integer).Insert Throw New NotImplementedException() End Sub Public Sub RemoveAt(index As Integer) Implements IList(Of Integer).RemoveAt Throw New NotImplementedException() End Sub Private Sub {|Definition:ICollection_Add|}(item As Integer) Implements ICollection(Of Integer).[|Add|] Throw New NotImplementedException() End Sub Public Function Contains(item As Integer) As Boolean Implements ICollection(Of Integer).Contains Throw New NotImplementedException() End Function Public Function GetEnumerator() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator Throw New NotImplementedException() End Function Public Function IndexOf(item As Integer) As Integer Implements IList(Of Integer).IndexOf Throw New NotImplementedException() End Function Public Function Remove(item As Integer) As Boolean Implements ICollection(Of Integer).Remove Throw New NotImplementedException() End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function End Class Public NotInheritable Class Class2 Implements IList(Of Integer) Public ReadOnly Property Count As Integer Implements ICollection(Of Integer).Count Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property IsReadOnly As Boolean Implements ICollection(Of Integer).IsReadOnly Get Throw New NotImplementedException() End Get End Property Default Public Property Item(index As Integer) As Integer Implements IList(Of Integer).Item Get Throw New NotImplementedException() End Get Set(value As Integer) Throw New NotImplementedException() End Set End Property Public Sub {|Definition:Add|}(item As Integer) Implements ICollection(Of Integer).[|Add|] Throw New NotImplementedException() End Sub Public Sub Clear() Implements ICollection(Of Integer).Clear Throw New NotImplementedException() End Sub Public Sub CopyTo(array() As Integer, arrayIndex As Integer) Implements ICollection(Of Integer).CopyTo Throw New NotImplementedException() End Sub Public Sub Insert(index As Integer, item As Integer) Implements IList(Of Integer).Insert Throw New NotImplementedException() End Sub Public Sub RemoveAt(index As Integer) Implements IList(Of Integer).RemoveAt Throw New NotImplementedException() End Sub Public Function Contains(item As Integer) As Boolean Implements ICollection(Of Integer).Contains Throw New NotImplementedException() End Function Public Function GetEnumerator() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator Throw New NotImplementedException() End Function Public Function IndexOf(item As Integer) As Integer Implements IList(Of Integer).IndexOf Throw New NotImplementedException() End Function Public Function Remove(item As Integer) As Boolean Implements ICollection(Of Integer).Remove Throw New NotImplementedException() End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function End Class Public NotInheritable Class Test Public Sub Foo() Dim c1 = DirectCast(New Class1(), IList(Of Integer)) Dim c2 As New Class1 Dim c3 As New Class2 c2.Add(3) c1.[|Add|](3) c3.[|$$Add|](3) End Sub End Class </Document> </Project> </Workspace> Await TestAsync(input) End Function End Class End Namespace
managed-commons/roslyn
src/EditorFeatures/Test2/FindReferences/FindReferencesTests.WinmdSymbols.vb
Visual Basic
apache-2.0
18,485
'********************************************************* ' ' Copyright (c) Microsoft. All rights reserved. ' This code is licensed under the MIT License (MIT). ' THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ' ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY ' IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR ' PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ' '********************************************************* Imports System Imports SDKTemplate Imports Windows.ApplicationModel.Background Imports Windows.Storage Imports Windows.UI.Core Imports Windows.UI.Xaml Imports Windows.UI.Xaml.Controls Imports Windows.UI.Xaml.Navigation Namespace Global.SDKTemplate ''' <summary> ''' An empty page that can be used on its own or navigated to within a Frame. ''' </summary> Public NotInheritable Partial Class TimeTriggeredTask Inherits Page Dim rootPage As MainPage = MainPage.Current Public Sub New() Me.InitializeComponent() End Sub ''' <summary> ''' Invoked when this page is about to be displayed in a Frame. ''' </summary> ''' <param name="e">Event data that describes how this page was reached. The Parameter ''' property is typically used to configure the page.</param> Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs) For Each task In BackgroundTaskRegistration.AllTasks If task.Value.Name = BackgroundTaskSample.TimeTriggeredTaskName Then AttachProgressAndCompletedHandlers(task.Value) BackgroundTaskSample.UpdateBackgroundTaskRegistrationStatus(BackgroundTaskSample.TimeTriggeredTaskName, True) Exit For End If Next UpdateUI() End Sub ''' <summary> ''' Register a TimeTriggeredTask. ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> Private Sub RegisterBackgroundTask(sender As Object, e As RoutedEventArgs) Dim task = BackgroundTaskSample.RegisterBackgroundTask(BackgroundTaskSample.SampleBackgroundTaskEntryPoint, BackgroundTaskSample.TimeTriggeredTaskName, New TimeTrigger(15, False), Nothing) AttachProgressAndCompletedHandlers(task) UpdateUI() End Sub ''' <summary> ''' Unregister a TimeTriggeredTask. ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> Private Sub UnregisterBackgroundTask(sender As Object, e As RoutedEventArgs) BackgroundTaskSample.UnregisterBackgroundTasks(BackgroundTaskSample.TimeTriggeredTaskName) UpdateUI() End Sub ''' <summary> ''' Attach progress and completed handers to a background task. ''' </summary> ''' <param name="task">The task to attach progress and completed handlers to.</param> Private Sub AttachProgressAndCompletedHandlers(task As IBackgroundTaskRegistration) AddHandler task.Progress, New BackgroundTaskProgressEventHandler(AddressOf OnProgress) AddHandler task.Completed, New BackgroundTaskCompletedEventHandler(AddressOf OnCompleted) End Sub ''' <summary> ''' Handle background task progress. ''' </summary> ''' <param name="task">The task that is reporting progress.</param> ''' <param name="e">Arguments of the progress report.</param> Private Sub OnProgress(task As IBackgroundTaskRegistration, args As BackgroundTaskProgressEventArgs) Dim ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub() Dim progress = "Progress: " & args.Progress & "%" BackgroundTaskSample.TimeTriggeredTaskProgress = progress UpdateUI() End Sub) End Sub ''' <summary> ''' Handle background task completion. ''' </summary> ''' <param name="task">The task that is reporting completion.</param> ''' <param name="e">Arguments of the completion report.</param> Private Sub OnCompleted(task As IBackgroundTaskRegistration, args As BackgroundTaskCompletedEventArgs) UpdateUI() End Sub ''' <summary> ''' Update the scenario UI. ''' </summary> Private Async Sub UpdateUI() Await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub() RegisterButton.IsEnabled = Not BackgroundTaskSample.TimeTriggeredTaskRegistered UnregisterButton.IsEnabled = BackgroundTaskSample.TimeTriggeredTaskRegistered Progress.Text = BackgroundTaskSample.TimeTriggeredTaskProgress Status.Text = BackgroundTaskSample.GetBackgroundTaskStatus(BackgroundTaskSample.TimeTriggeredTaskName) End Sub) End Sub End Class End Namespace
oldnewthing/Windows-universal-samples
Samples/BackgroundTask/vb/BackgroundTask/Scenario4_TimeTriggeredTask.xaml.vb
Visual Basic
mit
4,952
' 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 Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic Imports Microsoft.CodeAnalysis.GenerateType Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateType Imports Microsoft.CodeAnalysis.VisualBasic.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateType Partial Public Class GenerateTypeTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest #Region "Same Project" #Region "SameProject SameFile" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDefaultValues() TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|$$Foo|] End Sub End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Class Program Sub Main() Dim f As Foo End Sub End Class Class Foo End Class </Text>.NormalizedValue, isNewFile:=False) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeInsideNamespace() TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.Foo$$|] End Sub End Class Namespace A End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Class Program Sub Main() Dim f As A.Foo End Sub End Class Namespace A Class Foo End Class End Namespace</Text>.NormalizedValue, isNewFile:=False) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeInsideQualifiedNamespace() TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A.B End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Class Program Sub Main() Dim f As A.B.Foo End Sub End Class Namespace A.B Class Foo End Class End Namespace</Text>.NormalizedValue, isNewFile:=False) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeWithinQualifiedNestedNamespace() TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.C.Foo$$|] End Sub End Class Namespace A.B Namespace C End Namespace End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Class Program Sub Main() Dim f As A.B.C.Foo End Sub End Class Namespace A.B Namespace C Class Foo End Class End Namespace End Namespace</Text>.NormalizedValue, isNewFile:=False) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeWithinNestedQualifiedNamespace() TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.C.Foo$$|] End Sub End Class Namespace A Namespace B.C End Namespace End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Class Program Sub Main() Dim f As A.B.C.Foo End Sub End Class Namespace A Namespace B.C Class Foo End Class End Namespace End Namespace</Text>.NormalizedValue, isNewFile:=False) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeWithConstructorMembers() TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f = New [|$$Foo|](bar:=1, baz:=2) End Sub End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Class Program Sub Main() Dim f = New Foo(bar:=1, baz:=2) End Sub End Class Class Foo Private bar As Integer Private baz As Integer Public Sub New(bar As Integer, baz As Integer) Me.bar = bar Me.baz = baz End Sub End Class </Text>.NormalizedValue, isNewFile:=False) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeWithBaseTypes() TestWithMockedGenerateTypeDialog( initial:=<Text>Imports System.Collections.Generic Class Program Sub Main() Dim f As List(Of Integer) = New [|$$Foo|]() End Sub End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Imports System.Collections.Generic Class Program Sub Main() Dim f As List(Of Integer) = New Foo() End Sub End Class Class Foo Inherits List(Of Integer) End Class </Text>.NormalizedValue, isNewFile:=False) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeWithPublicInterface() TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.C.Foo$$|] End Sub End Class Namespace A Namespace B.C End Namespace End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Class Program Sub Main() Dim f As A.B.C.Foo End Sub End Class Namespace A Namespace B.C Public Interface Foo End Interface End Namespace End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeWithInternalStruct() TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.C.Foo$$|] End Sub End Class Namespace A Namespace B.C End Namespace End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Class Program Sub Main() Dim f As A.B.C.Foo End Sub End Class Namespace A Namespace B.C Friend Structure Foo End Structure End Namespace End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.Friend, typeKind:=TypeKind.Structure, isNewFile:=False) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeWithDefaultEnum() TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A Namespace B End Namespace End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Class Program Sub Main() Dim f As A.B.Foo End Sub End Class Namespace A Namespace B Enum Foo End Enum End Namespace End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.NotApplicable, typeKind:=TypeKind.Enum, isNewFile:=False) End Sub #End Region #Region "SameProject ExistingFile" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeInExistingEmptyFile() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> <Document FilePath="Test2.vb"> </Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Namespace A.B Public Interface Foo End Interface End Namespace </Text>.NormalizedValue, isLine:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb") End Sub <WorkItem(850101)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeInExistingEmptyFile_Usings_Folders() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Foo$$|] End Sub End Class</Document> <Document Folders="outer\inner" FilePath="Test2.vb"> </Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Namespace outer.inner Public Interface Foo End Interface End Namespace </Text>.NormalizedValue, isLine:=False, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports outer.inner Class Program Sub Main() Dim f As Foo End Sub End Class</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb") End Sub <WorkItem(850101)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeInExistingEmptyFile_NoUsings_Folders_NotSimpleName() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> <Document FilePath="Test2.vb" Folders="outer\inner"> </Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Namespace A.B Public Interface Foo End Interface End Namespace </Text>.NormalizedValue, isLine:=False, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb") End Sub #End Region #Region "SameProject NewFile" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeInNewFile() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Namespace A.B Public Interface Foo End Interface End Namespace </Text>.NormalizedValue, isLine:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=New String(0) {}, newFileName:="Test2.vb") End Sub <WorkItem(850101)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_UsingsNotNeeded_InNewFile_InFolder() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Namespace outer Namespace inner Class Program Sub Main() Dim f As [|Foo$$|] End Sub End Class End Namespace End Namespace</Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Namespace outer.inner Public Interface Foo End Interface End Namespace </Text>.NormalizedValue, isLine:=False, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=New String() {"outer", "inner"}, newFileName:="Test2.vb") End Sub <WorkItem(898452)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_InValidFolderNameNotMadeNamespace() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Namespace outer Namespace inner Class Program Sub Main() Dim f As [|Foo$$|] End Sub End Class End Namespace End Namespace</Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Public Interface Foo End Interface </Text>.NormalizedValue, isLine:=False, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=New String() {"@@@@@", "#####"}, areFoldersValidIdentifiers:=False, newFileName:="Test2.vb") End Sub <WorkItem(850101)> <WorkItem(907454)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_UsingsNeeded_InNewFile_InFolder() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|$$Foo|] End Sub End Class</Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Namespace outer.inner Public Interface Foo End Interface End Namespace </Text>.NormalizedValue, isLine:=False, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports BarBaz.outer.inner Class Program Sub Main() Dim f As Foo End Sub End Class</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=New String() {"outer", "inner"}, newFileName:="Test2.vb") End Sub <WorkItem(907454)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_UsingsPresentAlready_InNewFile_InFolder() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb" Folders="outer"> Imports BarBaz.outer Class Program Sub Main() Dim f As [|$$Foo|] End Sub End Class</Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Namespace outer Public Interface Foo End Interface End Namespace </Text>.NormalizedValue, isLine:=False, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports BarBaz.outer Class Program Sub Main() Dim f As Foo End Sub End Class</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=New String() {"outer"}, newFileName:="Test2.vb") End Sub <WorkItem(850101)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_UsingsNotNeeded_InNewFile_InFolder_NotSimpleName() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Namespace A.B Public Interface Foo End Interface End Namespace </Text>.NormalizedValue, isLine:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=New String() {"outer", "inner"}, newFileName:="Test2.vb") End Sub #End Region #End Region #Region "SameLanguage DifferentProject" #Region "SameLanguage DifferentProject ExistingFile" <WorkItem(850101)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoSameLanguageDifferentProjectEmptyFile() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <Document FilePath="Test2.vb"> </Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Namespace Global.A.B Public Interface Foo End Interface End Namespace </Text>.NormalizedValue, isLine:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb", projectName:="Assembly2") End Sub <WorkItem(850101)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoSameLanguageDifferentProjectExistingFile() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> <Document FilePath="Test2.vb" Folders="outer\inner">Namespace Global.BarBaz.A Namespace B End Namespace End Namespace</Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Namespace Global.BarBaz.A Namespace B Public Interface Foo End Interface End Namespace End Namespace</Text>.NormalizedValue, isLine:=False, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb", projectName:="Assembly2") End Sub <WorkItem(850101)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoSameLanguageDifferentProjectExistingFile_Usings_Folders() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> <Document FilePath="Test2.vb" Folders="outer\inner">Namespace A Namespace B End Namespace End Namespace</Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Namespace A Namespace B End Namespace End Namespace Namespace outer.inner Public Interface Foo End Interface End Namespace </Text>.NormalizedValue, isLine:=False, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports Zoozoo.outer.inner Class Program Sub Main() Dim f As Foo End Sub End Class Namespace A.B End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb", projectName:="Assembly2") End Sub #End Region #Region "SameLanguage DifferentProject NewFile" <WorkItem(850101)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoSameLanguageDifferentProjectNewFile() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Namespace Global.A.B Public Interface Foo End Interface End Namespace </Text>.NormalizedValue, isLine:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileName:="Test2.vb", newFileFolderContainers:=New String(0) {}, projectName:="Assembly2") End Sub <WorkItem(850101)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_Usings() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Foo$$|] End Sub End Class</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Namespace outer.inner Public Interface Foo End Interface End Namespace </Text>.NormalizedValue, isLine:=False, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports Zoozoo.outer.inner Class Program Sub Main() Dim f As Foo End Sub End Class</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileName:="Test2.vb", newFileFolderContainers:=New String() {"outer", "inner"}, projectName:="Assembly2") End Sub <WorkItem(850101)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_NoUsings_NotSimpleName() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Namespace Global.BarBaz.A.B Public Interface Foo End Interface End Namespace </Text>.NormalizedValue, isLine:=False, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileName:="Test2.vb", newFileFolderContainers:=New String(0) {}, projectName:="Assembly2") End Sub <WorkItem(850101)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_NoUsings_NotSimpleName_ProjectReference() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> <Document FilePath="Test2.vb"> Namespace A.B Public Class Bar End Class End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <ProjectReference>Assembly2</ProjectReference> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Zoozoo.A.B.Foo$$|] End Sub End Class</Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Namespace A.B Public Interface Foo End Interface End Namespace </Text>.NormalizedValue, isLine:=False, checkIfUsingsNotIncluded:=False, expectedTextWithUsings:=<Text></Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileName:="Test3.vb", newFileFolderContainers:=New String(0) {}, projectName:="Assembly2") End Sub #End Region #End Region #Region "Different Language" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoDifferentLanguageNewFile() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>namespace A.B { public class Foo { } }</Text>.NormalizedValue, isLine:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=New String(0) {}, projectName:="Assembly2") End Sub <WorkItem(850101)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoDifferentLanguageNewFile_Folders_Imports() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>namespace outer.inner { public class Foo { } }</Text>.NormalizedValue, isLine:=False, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports outer.inner Class Program Sub Main() Dim f As Foo End Sub End Class Namespace A.B End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=New String() {"outer", "inner"}, projectName:="Assembly2") End Sub <WorkItem(850101)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoDifferentLanguageNewFile_Folders_NoImports_NotSimpleName() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>namespace A.B { public class Foo { } }</Text>.NormalizedValue, isLine:=False, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=New String() {"outer", "inner"}, projectName:="Assembly2") End Sub <WorkItem(850101)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoDifferentLanguageNewFile_Folders_Imports_DefaultNamespace() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>namespace ConsoleApplication.outer.inner { public class Foo { } }</Text>.NormalizedValue, isLine:=False, defaultNamespace:="ConsoleApplication", checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports ConsoleApplication.outer.inner Class Program Sub Main() Dim f As Foo End Sub End Class Namespace A.B End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=New String() {"outer", "inner"}, projectName:="Assembly2") End Sub <WorkItem(850101)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoDifferentLanguageNewFile_Folders_NoImports_NotSimpleName_DefaultNamespace() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>namespace BarBaz.A.B { public class Foo { } }</Text>.NormalizedValue, isLine:=False, defaultNamespace:="ConsoleApplication", checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=New String() {"outer", "inner"}, projectName:="Assembly2") End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoDifferentLanguageExistingEmptyFile() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> <Document Folders="outer\inner" FilePath="Test2.cs"> </Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>namespace A.B { public class Foo { } }</Text>.NormalizedValue, isLine:=False, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=False, existingFilename:="Test2.cs", projectName:="Assembly2") End Sub <WorkItem(850101)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoDifferentLanguageExistingEmptyFile_Imports_Folder() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Foo$$|] End Sub End Class</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> <Document Folders="outer\inner" FilePath="Test2.cs"> </Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>namespace outer.inner { public class Foo { } }</Text>.NormalizedValue, isLine:=False, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports outer.inner Class Program Sub Main() Dim f As Foo End Sub End Class</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=False, existingFilename:="Test2.cs", projectName:="Assembly2") End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoDifferentLanguageExistingNonEmptyFile() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> <Document FilePath="Test2.cs"> namespace A { }</Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text> namespace A { } namespace A.B { public class Foo { } }</Text>.NormalizedValue, isLine:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=False, existingFilename:="Test2.cs", projectName:="Assembly2") End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoDifferentLanguageExistingTargetFile() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> <Document FilePath="Test2.cs">namespace A { namespace B { } }</Document> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>namespace A { namespace B { public class Foo { } } }</Text>.NormalizedValue, isLine:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=False, existingFilename:="Test2.cs", projectName:="Assembly2") End Sub <WorkItem(858826)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeIntoDifferentLanguageNewFileAdjustTheFileExtension() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Foo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>namespace A.B { public class Foo { } }</Text>.NormalizedValue, isLine:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=New String(0) {}, projectName:="Assembly2") End Sub #End Region #Region "Bugfix" <WorkItem(861462)> <WorkItem(873066)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeWithProperAccessibilityAndTypeKind_1() TestWithMockedGenerateTypeDialog( initial:=<Text>Public Class C Implements [|$$D|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="D", expected:=<Text>Public Class C Implements D End Class Public Interface D End Interface </Text>.NormalizedValue, isNewFile:=False, typeKind:=TypeKind.Interface, accessibility:=Accessibility.Public, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Interface)) End Sub <WorkItem(861462)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeWithProperAccessibilityAndTypeKind_2() TestWithMockedGenerateTypeDialog( initial:=<Text>Public Class CC Inherits [|$$DD|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="DD", expected:=<Text>Public Class CC Inherits DD End Class Class DD End Class </Text>.NormalizedValue, isNewFile:=False, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Class)) End Sub <WorkItem(861462)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeWithProperAccessibilityAndTypeKind_3() TestWithMockedGenerateTypeDialog( initial:=<Text>Public Interface CCC Inherits [|$$DDD|] End Interface</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="DDD", expected:=<Text>Public Interface CCC Inherits DDD End Interface Interface DDD End Interface </Text>.NormalizedValue, isNewFile:=False, typeKind:=TypeKind.Interface, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Interface)) End Sub <WorkItem(861462)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeWithProperAccessibilityAndTypeKind_4() TestWithMockedGenerateTypeDialog( initial:=<Text>Public Structure CCC Implements [|$$DDD|] End Structure</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="DDD", expected:=<Text>Public Structure CCC Implements DDD End Structure Public Interface DDD End Interface </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Interface)) End Sub <WorkItem(861362)> <WorkItem(869593)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeWithModuleOption() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s as [|$$A.B.C|] End Sub End Module Namespace A End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="B", expected:=<Text>Module Program Sub Main(args As String()) Dim s as A.B.C End Sub End Module Namespace A Module B End Module End Namespace</Text>.NormalizedValue, isNewFile:=False, typeKind:=TypeKind.Module, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module)) End Sub <WorkItem(861362)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeInMemberAccessExpression() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = [|$$A.B|] End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="A", expected:=<Text>Module Program Sub Main(args As String()) Dim s = A.B End Sub End Module Public Module A End Module </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Module, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.MemberAccessWithNamespace)) End Sub <WorkItem(861362)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeInMemberAccessExpressionWithNamespace() TestWithMockedGenerateTypeDialog( initial:=<Text>Namespace A Module Program Sub Main(args As String()) Dim s = [|$$A.B.C|] End Sub End Module End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="B", expected:=<Text>Namespace A Module Program Sub Main(args As String()) Dim s = A.B.C End Sub End Module Public Module B End Module End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Module, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.MemberAccessWithNamespace)) End Sub <WorkItem(876202)> <WorkItem(883531)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_NoParameterLessConstructor() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = new [|$$Foo|]() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="B", expected:=<Text>Module Program Sub Main(args As String()) Dim s = new Foo() End Sub End Module Public Structure B End Structure </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Structure, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure)) End Sub <WorkItem(861600)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeWithoutEnumForGenericsInMemberAccessExpression() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = [|$$Foo(Of Bar).D|] End Sub End Module Class Bar End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Module Program Sub Main(args As String()) Dim s = Foo(Of Bar).D End Sub End Module Class Bar End Class Public Class Foo(Of T) End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure)) End Sub <WorkItem(861600)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeWithoutEnumForGenericsInNameContext() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s As [|$$Foo(Of Bar)|] End Sub End Module Class Bar End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Module Program Sub Main(args As String()) Dim s As Foo(Of Bar) End Sub End Module Class Bar End Class Public Class Foo(Of T) End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Interface Or TypeKindOptions.Delegate)) End Sub <WorkItem(861600)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeInMemberAccessWithNSForModule() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = [|$$Foo.Bar|].Baz End Sub End Module Namespace Foo End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text>Module Program Sub Main(args As String()) Dim s = Foo.Bar.Baz End Sub End Module Namespace Foo Public Class Bar End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.MemberAccessWithNamespace)) End Sub <WorkItem(861600)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeInMemberAccessWithGlobalNSForModule() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = [|$$Bar|].Baz End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text>Module Program Sub Main(args As String()) Dim s = Bar.Baz End Sub End Module Public Class Bar End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.MemberAccessWithNamespace)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeInMemberAccessWithoutNS() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = [|$$Bar|].Baz End Sub End Module Namespace Bar End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", isMissing:=True) End Sub #End Region #Region "Delegates" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegateFromObjectCreationExpression() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = New [|$$MyD|](AddressOf foo) End Sub Sub foo() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim s = New MyD(AddressOf foo) End Sub Sub foo() End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegateFromObjectCreationExpressionIntoNamespace() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim foo = New NS.[|$$MyD|](Sub() End Sub) End Sub End Module Namespace NS End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim foo = New NS.MyD(Sub() End Sub) End Sub End Module Namespace NS Public Delegate Sub MyD() End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegateFromObjectCreationExpression_1() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim foo = New [|$$NS.MyD|](Function(n) n) End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim foo = New NS.MyD(Function(n) n) End Sub End Module Namespace NS Public Delegate Function MyD(n As Object) As Object End Namespace </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegateFromObjectCreationExpression_2() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim foo = New [|$$MyD|](Sub() System.Console.WriteLine(1)) End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim foo = New MyD(Sub() System.Console.WriteLine(1)) End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegateFromObjectCreationExpression_3() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim foo = New [|$$MyD|](Function(n As Integer) Return n + n End Function) End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim foo = New MyD(Function(n As Integer) Return n + n End Function) End Sub End Module Public Delegate Function MyD(n As Integer) As Integer </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegateAddressOfExpression() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD(Of Integer)|] = AddressOf foo(Of Integer) End Sub Public Sub foo(Of T)() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD(Of Integer) = AddressOf foo(Of Integer) End Sub Public Sub foo(Of T)() End Sub End Module Public Delegate Sub MyD(Of T)() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Interface Or TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegateAddressOfExpressionWrongTypeArgument_1() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] = AddressOf foo(Of Integer) End Sub Public Sub foo(Of T)() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD = AddressOf foo(Of Integer) End Sub Public Sub foo(Of T)() End Sub End Module Public Delegate Sub MyD(Of T)() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegateAddressOfExpressionWrongTypeArgument_2() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] = AddressOf foo End Sub Public Sub foo(Of T)() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD = AddressOf foo End Sub Public Sub foo(Of T)() End Sub End Module Public Delegate Sub MyD(Of T)() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegateAddressOfExpressionWrongTypeArgument_3() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] = AddressOf foo End Sub Public Sub foo(Of T)() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD = AddressOf foo End Sub Public Sub foo(Of T)() End Sub End Module Public Delegate Sub MyD(Of T)() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegateWithNoInitializer() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegateWithLambda_MultiLineFunction() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] = Function() Return 0 End Function End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD = Function() Return 0 End Function End Sub End Module Public Delegate Function MyD() As Integer </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegateWithLambda_SingleLineFunction() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim a As [|$$MyD|] = Function(n As Integer) "" End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim a As MyD = Function(n As Integer) "" End Sub End Module Public Delegate Function MyD(n As Integer) As String </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegateWithLambda_MultiLineSub() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] = Sub() End Sub End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD = Sub() End Sub End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegateWithLambda_SingleLineSub() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim a As [|$$MyD|] = Sub(n As Double) Console.WriteLine(0) End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim a As MyD = Sub(n As Double) Console.WriteLine(0) End Sub End Module Public Delegate Sub MyD(n As Double) </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegateWithCast() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar = DirectCast(AddressOf foo, [|$$MyD|]) End Sub Public Sub foo() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar = DirectCast(AddressOf foo, MyD) End Sub Public Sub foo() End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegateWithCastAndError() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar = DirectCast(AddressOf foo, [|$$MyD|]) End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar = DirectCast(AddressOf foo, MyD) End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateDelegateTypeIntoDifferentLanguageNewFile() Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Module Program Sub Main(args As String()) Dim fooFoo = DirectCast(AddressOf Main, [|$$Bar|]) End Sub End Module</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text>public delegate void Bar(string[] args); </Text>.NormalizedValue, isLine:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=New String(0) {}, projectName:="Assembly2") End Sub <WorkItem(860210)> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateTypeDelegate_NoInfo() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s as [|$$MyD(Of Integer)|] End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim s as MyD(Of Integer) End Sub End Module Public Delegate Sub MyD(Of T)() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate) End Sub #End Region #Region "Dev12Filtering" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Invocation_NoEnum_0() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim a = [|$$Baz.Foo|].Bar() End Sub End Module Namespace Baz End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Module Program Sub Main(args As String()) Dim a = Baz.Foo.Bar() End Sub End Module Namespace Baz Public Class Foo End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum}) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Invocation_NoEnum_1() TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim a = [|$$Foo.Bar|]() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text>Module Program Sub Main(args As String()) Dim a = Foo.Bar() End Sub End Module Public Class Bar End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum}) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Invocation_NoEnum_2() TestWithMockedGenerateTypeDialog( initial:=<Text>Class C Custom Event E As Action AddHandler(value As [|$$Foo|]) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Class C Custom Event E As Action AddHandler(value As Foo) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Public Delegate Sub Foo() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertTypeKindPresent:=New TypeKindOptions() {TypeKindOptions.Delegate}, assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum}) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Invocation_NoEnum_3() TestWithMockedGenerateTypeDialog( initial:=<Text>Class C Custom Event E As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As [|$$Foo|]) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text>Class C Custom Event E As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Foo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Public Delegate Sub Foo() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertTypeKindPresent:=New TypeKindOptions() {TypeKindOptions.Delegate}, assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum}) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Invocation_NoEnum_4() TestWithMockedGenerateTypeDialog( initial:=<Text>Imports System Module Program Sub Main(args As String()) Dim s As Action = AddressOf [|NS.Bar$$|].Method End Sub End Module Namespace NS End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text>Imports System Module Program Sub Main(args As String()) Dim s As Action = AddressOf NS.Bar.Method End Sub End Module Namespace NS Public Class Bar End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum}) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_TypeConstraint_1() TestWithMockedGenerateTypeDialog( initial:=<Text> Public Class Foo(Of T As [|$$Bar|]) End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Public Class Foo(Of T As Bar) End Class Public Class Bar End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.BaseList)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_TypeConstraint_2() TestWithMockedGenerateTypeDialog( initial:=<Text> Class Outer Public Class Foo(Of T As [|$$Bar|]) End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Class Outer Public Class Foo(Of T As Bar) End Class End Class Public Class Bar End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_TypeConstraint_3() TestWithMockedGenerateTypeDialog( initial:=<Text> Public Class OuterOuter Public Class Outer Public Class Foo(Of T As [|$$Bar|]) End Class End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Public Class OuterOuter Public Class Outer Public Class Foo(Of T As Bar) End Class End Class End Class Public Class Bar End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.BaseList)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Event_1() TestWithMockedGenerateTypeDialog( initial:=<Text> Class C1 Custom Event E As [|$$Foo|] AddHandler(value As Foo) End AddHandler RemoveHandler(value As Foo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text> Class C1 Custom Event E As Foo AddHandler(value As Foo) End AddHandler RemoveHandler(value As Foo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Public Delegate Sub Foo() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Event_2() TestWithMockedGenerateTypeDialog( initial:=<Text> Class C1 Custom Event E As [|$$NS.Foo|] AddHandler(value As Foo) End AddHandler RemoveHandler(value As Foo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text> Class C1 Custom Event E As NS.Foo AddHandler(value As Foo) End AddHandler RemoveHandler(value As Foo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Namespace NS Public Delegate Sub Foo() End Namespace </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Event_3() TestWithMockedGenerateTypeDialog( initial:=<Text> Class C1 Custom Event E As [|$$NS.Foo.MyDel|] AddHandler(value As Foo) End AddHandler RemoveHandler(value As Foo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Namespace NS End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Foo", expected:=<Text> Class C1 Custom Event E As NS.Foo.MyDel AddHandler(value As Foo) End AddHandler RemoveHandler(value As Foo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Namespace NS Public Class Foo End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Event_4() TestWithMockedGenerateTypeDialog( initial:=<Text> Class Foo Public Event F As [|$$Bar|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Class Foo Public Event F As Bar End Class Public Delegate Sub Bar() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Event_5() TestWithMockedGenerateTypeDialog( initial:=<Text> Class Foo Public Event F As [|$$NS.Bar|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Class Foo Public Event F As NS.Bar End Class Namespace NS Public Delegate Sub Bar() End Namespace </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Event_6() TestWithMockedGenerateTypeDialog( initial:=<Text> Class Foo Public Event F As [|$$NS.Bar.MyDel|] End Class Namespace NS End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Class Foo Public Event F As NS.Bar.MyDel End Class Namespace NS Public Class Bar End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Event_7() TestWithMockedGenerateTypeDialog( initial:=<Text> Class Bar Public WithEvents G As [|$$Delegate1|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Delegate1", expected:=<Text> Class Bar Public WithEvents G As Delegate1 End Class Public Class Delegate1 End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Event_8() TestWithMockedGenerateTypeDialog( initial:=<Text> Class Bar Public WithEvents G As [|$$NS.Delegate1|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Delegate1", expected:=<Text> Class Bar Public WithEvents G As NS.Delegate1 End Class Namespace NS Public Class Delegate1 End Class End Namespace </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Event_9() TestWithMockedGenerateTypeDialog( initial:=<Text> Class Bar Public WithEvents G As [|$$NS.Delegate1.MyDel|] End Class Namespace NS End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Delegate1", expected:=<Text> Class Bar Public WithEvents G As NS.Delegate1.MyDel End Class Namespace NS Public Class Delegate1 End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Event_10() TestWithMockedGenerateTypeDialog( initial:=<Text> Class Baz Public Class Foo Public Event F As [|$$Bar|] End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Class Baz Public Class Foo Public Event F As Bar End Class End Class Public Delegate Sub Bar() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Event_11() TestWithMockedGenerateTypeDialog( initial:=<Text> Public Class Baz Public Class Foo Public Event F As [|$$Bar|] End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Public Class Baz Public Class Foo Public Event F As Bar End Class End Class Public Delegate Sub Bar() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Delegate)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Event_12() TestWithMockedGenerateTypeDialog( initial:=<Text> Class Baz Public Class Bar Public WithEvents G As [|$$Delegate1|] End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Delegate1", expected:=<Text> Class Baz Public Class Bar Public WithEvents G As Delegate1 End Class End Class Public Class Delegate1 End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList)) End Sub <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Sub GenerateType_Event_13() TestWithMockedGenerateTypeDialog( initial:=<Text> Public Class Baz Public Class Bar Public WithEvents G As [|$$Delegate1|] End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Delegate1", expected:=<Text> Public Class Baz Public Class Bar Public WithEvents G As Delegate1 End Class End Class Public Class Delegate1 End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.BaseList)) End Sub #End Region End Class End Namespace
v-codeel/roslyn
src/EditorFeatures/VisualBasicTest/Diagnostics/GenerateType/GenerateTypeTests_Dialog.vb
Visual Basic
apache-2.0
86,724
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Form4 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.Label1 = New System.Windows.Forms.Label Me.PictureBox1 = New System.Windows.Forms.PictureBox Me.Label2 = New System.Windows.Forms.Label Me.LinkLabel1 = New System.Windows.Forms.LinkLabel CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'Label1 ' Me.Label1.AutoSize = True Me.Label1.BackColor = System.Drawing.Color.Transparent Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 13.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label1.ForeColor = System.Drawing.Color.White Me.Label1.Location = New System.Drawing.Point(12, 0) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(100, 44) Me.Label1.TabIndex = 0 Me.Label1.Text = " Autorun" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "Processor" ' 'PictureBox1 ' Me.PictureBox1.BackColor = System.Drawing.Color.Transparent Me.PictureBox1.Image = Global.Autorun_Processor.My.Resources.Resources.green_close_normal Me.PictureBox1.Location = New System.Drawing.Point(310, 0) Me.PictureBox1.Name = "PictureBox1" Me.PictureBox1.Size = New System.Drawing.Size(36, 23) Me.PictureBox1.TabIndex = 1 Me.PictureBox1.TabStop = False ' 'Label2 ' Me.Label2.AutoSize = True Me.Label2.BackColor = System.Drawing.Color.Transparent Me.Label2.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label2.Location = New System.Drawing.Point(13, 74) Me.Label2.Name = "Label2" Me.Label2.Size = New System.Drawing.Size(274, 17) Me.Label2.TabIndex = 2 Me.Label2.Text = "Hidden Files Detected In Removable Drive" ' 'LinkLabel1 ' Me.LinkLabel1.AutoSize = True Me.LinkLabel1.BackColor = System.Drawing.Color.Transparent Me.LinkLabel1.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.LinkLabel1.Location = New System.Drawing.Point(251, 121) Me.LinkLabel1.Name = "LinkLabel1" Me.LinkLabel1.Size = New System.Drawing.Size(84, 13) Me.LinkLabel1.TabIndex = 3 Me.LinkLabel1.TabStop = True Me.LinkLabel1.Text = "View File Details" ' 'Form4 ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackgroundImage = Global.Autorun_Processor.My.Resources.Resources.form4_background Me.ClientSize = New System.Drawing.Size(347, 164) Me.Controls.Add(Me.LinkLabel1) Me.Controls.Add(Me.Label2) Me.Controls.Add(Me.PictureBox1) Me.Controls.Add(Me.Label1) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None Me.Name = "Form4" Me.Text = "Hidden Objects" CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents PictureBox1 As System.Windows.Forms.PictureBox Friend WithEvents Label2 As System.Windows.Forms.Label Friend WithEvents LinkLabel1 As System.Windows.Forms.LinkLabel End Class
pratheeshrussell/Autorun-Processor
Autorun Processor/Form4.Designer.vb
Visual Basic
mit
4,623
Namespace Networks Public MustInherit Class NetworkBase MustOverride Function Compute(Input As Tensor) As Tensor End Class End Namespace
mateuszzwierzycki/Owl
Owl.Learning/Networks/NetworkBase.vb
Visual Basic
mit
156
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class frmGame 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.TimerMain = New System.Windows.Forms.Timer(Me.components) Me.picInvader13 = New System.Windows.Forms.PictureBox() Me.picInvader7 = New System.Windows.Forms.PictureBox() Me.picInvader8 = New System.Windows.Forms.PictureBox() Me.picInvader9 = New System.Windows.Forms.PictureBox() Me.picInvader10 = New System.Windows.Forms.PictureBox() Me.picInvader11 = New System.Windows.Forms.PictureBox() Me.picInvader12 = New System.Windows.Forms.PictureBox() Me.picInvader4 = New System.Windows.Forms.PictureBox() Me.picInvader5 = New System.Windows.Forms.PictureBox() Me.picInvader6 = New System.Windows.Forms.PictureBox() Me.picInvader3 = New System.Windows.Forms.PictureBox() Me.picInvader2 = New System.Windows.Forms.PictureBox() Me.picInvader = New System.Windows.Forms.PictureBox() Me.picBullet = New System.Windows.Forms.PictureBox() Me.picShoot = New System.Windows.Forms.PictureBox() CType(Me.picInvader13, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picInvader7, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picInvader8, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picInvader9, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picInvader10, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picInvader11, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picInvader12, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picInvader4, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picInvader5, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picInvader6, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picInvader3, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picInvader2, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picInvader, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picBullet, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.picShoot, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'TimerMain ' Me.TimerMain.Enabled = True Me.TimerMain.Interval = 1 ' 'picInvader13 ' Me.picInvader13.BackColor = System.Drawing.Color.Transparent Me.picInvader13.Image = Global.Invaders.My.Resources.Resources.Invader11 Me.picInvader13.Location = New System.Drawing.Point(705, 12) Me.picInvader13.Name = "picInvader13" Me.picInvader13.Size = New System.Drawing.Size(50, 50) Me.picInvader13.TabIndex = 17 Me.picInvader13.TabStop = False ' 'picInvader7 ' Me.picInvader7.BackColor = System.Drawing.Color.Transparent Me.picInvader7.Image = Global.Invaders.My.Resources.Resources.Invader11 Me.picInvader7.Location = New System.Drawing.Point(361, 12) Me.picInvader7.Name = "picInvader7" Me.picInvader7.Size = New System.Drawing.Size(50, 50) Me.picInvader7.TabIndex = 16 Me.picInvader7.TabStop = False ' 'picInvader8 ' Me.picInvader8.BackColor = System.Drawing.Color.Transparent Me.picInvader8.Image = Global.Invaders.My.Resources.Resources.Invader11 Me.picInvader8.Location = New System.Drawing.Point(419, 12) Me.picInvader8.Name = "picInvader8" Me.picInvader8.Size = New System.Drawing.Size(50, 50) Me.picInvader8.TabIndex = 15 Me.picInvader8.TabStop = False ' 'picInvader9 ' Me.picInvader9.BackColor = System.Drawing.Color.Transparent Me.picInvader9.Image = Global.Invaders.My.Resources.Resources.InvaderRed Me.picInvader9.Location = New System.Drawing.Point(477, 12) Me.picInvader9.Name = "picInvader9" Me.picInvader9.Size = New System.Drawing.Size(50, 50) Me.picInvader9.TabIndex = 14 Me.picInvader9.TabStop = False ' 'picInvader10 ' Me.picInvader10.BackColor = System.Drawing.Color.Transparent Me.picInvader10.Image = Global.Invaders.My.Resources.Resources.Invader11 Me.picInvader10.Location = New System.Drawing.Point(535, 12) Me.picInvader10.Name = "picInvader10" Me.picInvader10.Size = New System.Drawing.Size(50, 50) Me.picInvader10.TabIndex = 13 Me.picInvader10.TabStop = False ' 'picInvader11 ' Me.picInvader11.BackColor = System.Drawing.Color.Transparent Me.picInvader11.Image = Global.Invaders.My.Resources.Resources.Invader11 Me.picInvader11.Location = New System.Drawing.Point(593, 12) Me.picInvader11.Name = "picInvader11" Me.picInvader11.Size = New System.Drawing.Size(50, 50) Me.picInvader11.TabIndex = 12 Me.picInvader11.TabStop = False ' 'picInvader12 ' Me.picInvader12.BackColor = System.Drawing.Color.Transparent Me.picInvader12.Image = Global.Invaders.My.Resources.Resources.InvaderRed Me.picInvader12.Location = New System.Drawing.Point(649, 12) Me.picInvader12.Name = "picInvader12" Me.picInvader12.Size = New System.Drawing.Size(50, 50) Me.picInvader12.TabIndex = 11 Me.picInvader12.TabStop = False ' 'picInvader4 ' Me.picInvader4.BackColor = System.Drawing.Color.Transparent Me.picInvader4.Image = Global.Invaders.My.Resources.Resources.InvaderGreen Me.picInvader4.Location = New System.Drawing.Point(187, 12) Me.picInvader4.Name = "picInvader4" Me.picInvader4.Size = New System.Drawing.Size(50, 50) Me.picInvader4.TabIndex = 10 Me.picInvader4.TabStop = False ' 'picInvader5 ' Me.picInvader5.BackColor = System.Drawing.Color.Transparent Me.picInvader5.Image = Global.Invaders.My.Resources.Resources.Invader11 Me.picInvader5.Location = New System.Drawing.Point(245, 12) Me.picInvader5.Name = "picInvader5" Me.picInvader5.Size = New System.Drawing.Size(50, 50) Me.picInvader5.TabIndex = 9 Me.picInvader5.TabStop = False ' 'picInvader6 ' Me.picInvader6.BackColor = System.Drawing.Color.Transparent Me.picInvader6.Image = Global.Invaders.My.Resources.Resources.Invader11 Me.picInvader6.Location = New System.Drawing.Point(303, 12) Me.picInvader6.Name = "picInvader6" Me.picInvader6.Size = New System.Drawing.Size(50, 50) Me.picInvader6.TabIndex = 8 Me.picInvader6.TabStop = False ' 'picInvader3 ' Me.picInvader3.BackColor = System.Drawing.Color.Transparent Me.picInvader3.Image = Global.Invaders.My.Resources.Resources.Invader11 Me.picInvader3.Location = New System.Drawing.Point(129, 12) Me.picInvader3.Name = "picInvader3" Me.picInvader3.Size = New System.Drawing.Size(50, 50) Me.picInvader3.TabIndex = 7 Me.picInvader3.TabStop = False ' 'picInvader2 ' Me.picInvader2.BackColor = System.Drawing.Color.Transparent Me.picInvader2.Image = Global.Invaders.My.Resources.Resources.InvaderRed Me.picInvader2.Location = New System.Drawing.Point(71, 12) Me.picInvader2.Name = "picInvader2" Me.picInvader2.Size = New System.Drawing.Size(50, 50) Me.picInvader2.TabIndex = 6 Me.picInvader2.TabStop = False ' 'picInvader ' Me.picInvader.BackColor = System.Drawing.Color.Black Me.picInvader.BackgroundImage = Global.Invaders.My.Resources.Resources.Space Me.picInvader.Image = Global.Invaders.My.Resources.Resources.Invader11 Me.picInvader.Location = New System.Drawing.Point(15, 12) Me.picInvader.Name = "picInvader" Me.picInvader.Size = New System.Drawing.Size(50, 50) Me.picInvader.TabIndex = 2 Me.picInvader.TabStop = False ' 'picBullet ' Me.picBullet.BackColor = System.Drawing.Color.White Me.picBullet.Location = New System.Drawing.Point(38, 290) Me.picBullet.Name = "picBullet" Me.picBullet.Size = New System.Drawing.Size(10, 17) Me.picBullet.TabIndex = 1 Me.picBullet.TabStop = False ' 'picShoot ' Me.picShoot.Image = Global.Invaders.My.Resources.Resources.space_invaders_my_ship Me.picShoot.Location = New System.Drawing.Point(337, 455) Me.picShoot.Name = "picShoot" Me.picShoot.Size = New System.Drawing.Size(85, 70) Me.picShoot.TabIndex = 0 Me.picShoot.TabStop = False ' 'frmGame ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.SystemColors.ControlText Me.ClientSize = New System.Drawing.Size(793, 526) Me.Controls.Add(Me.picInvader13) Me.Controls.Add(Me.picInvader7) Me.Controls.Add(Me.picInvader8) Me.Controls.Add(Me.picInvader9) Me.Controls.Add(Me.picInvader10) Me.Controls.Add(Me.picInvader11) Me.Controls.Add(Me.picInvader12) Me.Controls.Add(Me.picInvader4) Me.Controls.Add(Me.picInvader5) Me.Controls.Add(Me.picInvader6) Me.Controls.Add(Me.picInvader3) Me.Controls.Add(Me.picInvader2) Me.Controls.Add(Me.picInvader) Me.Controls.Add(Me.picBullet) Me.Controls.Add(Me.picShoot) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog Me.MaximizeBox = False Me.MinimizeBox = False Me.Name = "frmGame" Me.Text = "Invaders" CType(Me.picInvader13, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picInvader7, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picInvader8, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picInvader9, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picInvader10, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picInvader11, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picInvader12, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picInvader4, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picInvader5, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picInvader6, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picInvader3, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picInvader2, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picInvader, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picBullet, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.picShoot, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) End Sub Friend WithEvents picShoot As System.Windows.Forms.PictureBox Friend WithEvents TimerMain As System.Windows.Forms.Timer Friend WithEvents picBullet As System.Windows.Forms.PictureBox Friend WithEvents picInvader As System.Windows.Forms.PictureBox Friend WithEvents picInvader2 As System.Windows.Forms.PictureBox Friend WithEvents picInvader3 As System.Windows.Forms.PictureBox Friend WithEvents picInvader6 As System.Windows.Forms.PictureBox Friend WithEvents picInvader5 As System.Windows.Forms.PictureBox Friend WithEvents picInvader4 As System.Windows.Forms.PictureBox Friend WithEvents picInvader12 As System.Windows.Forms.PictureBox Friend WithEvents picInvader11 As System.Windows.Forms.PictureBox Friend WithEvents picInvader10 As System.Windows.Forms.PictureBox Friend WithEvents picInvader9 As System.Windows.Forms.PictureBox Friend WithEvents picInvader8 As System.Windows.Forms.PictureBox Friend WithEvents picInvader7 As System.Windows.Forms.PictureBox Friend WithEvents picInvader13 As System.Windows.Forms.PictureBox End Class
cessnao3/orientation-client
Invaders UNPUBLISHED/Invaders/GameMain.Designer.vb
Visual Basic
mit
13,337
Imports Tests.Core Public Class TestAssembly Implements ITestAssembly Private _listPackages As List(Of ITestPackage) Public ReadOnly Property Language As String Implements Tests.Core.ITestAssembly.Language Get Return "VB" End Get End Property Public Function LoadTestPackages() As Tests.Core.ITestPackage() Implements Tests.Core.ITestAssembly.LoadTestPackages If IsNothing(_listPackages) Then _listPackages = New List(Of ITestPackage) _listPackages.Add(New Test01()) _listPackages.Add(New Test02()) _listPackages.Add(New Test03()) _listPackages.Add(New Test04()) _listPackages.Add(New Test05()) _listPackages.Add(New Test06()) End If Return _listPackages.ToArray() End Function Public ReadOnly Property OfficeProduct As String Implements Tests.Core.ITestAssembly.OfficeProduct Get Return "PowerPoint" End Get End Property End Class
NetOfficeFw/NetOffice
Tests/Main Tests/PowerPointTestsVB/TestAssembly.vb
Visual Basic
mit
1,042
'------------------------------------------------------------------------------ ' <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 Partial Public Class CalcB '''<summary> '''lblLand control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents lblLand As Global.System.Web.UI.WebControls.Label '''<summary> '''Topinfobar1 control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents Topinfobar1 As Global.sklone.TopInfoBar '''<summary> '''Form1 control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents Form1 As Global.System.Web.UI.HtmlControls.HtmlForm '''<summary> '''lblerror control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents lblerror As Global.System.Web.UI.WebControls.Label '''<summary> '''txtASoldiers control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtASoldiers As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtDSoldiers control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtDSoldiers As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtADragoons control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtADragoons As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtDLDragoons control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtDLDragoons As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtATroopers control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtATroopers As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtDLTroopers control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtDLTroopers As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtATanks control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtATanks As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtDTanks control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtDTanks As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtATFs control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtATFs As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtDTFs control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtDTFs As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtASpecialOps control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtASpecialOps As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtDSpecialOps control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtDSpecialOps As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtAInterceptors control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtAInterceptors As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtDInterceptors control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtDInterceptors As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtALancers control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtALancers As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtDLancers control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtDLancers As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtASabres control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtASabres As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtDSabres control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtDSabres As Global.System.Web.UI.WebControls.TextBox '''<summary> '''cboAPlanet control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents cboAPlanet As Global.System.Web.UI.HtmlControls.HtmlSelect '''<summary> '''cboDPlanet control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents cboDPlanet As Global.System.Web.UI.HtmlControls.HtmlSelect '''<summary> '''cboARace control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents cboARace As Global.System.Web.UI.HtmlControls.HtmlSelect '''<summary> '''cboDRace control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents cboDRace As Global.System.Web.UI.HtmlControls.HtmlSelect '''<summary> '''txtAResearch control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtAResearch As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtDResearch control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtDResearch As Global.System.Web.UI.WebControls.TextBox '''<summary> '''txtWls control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents txtWls As Global.System.Web.UI.WebControls.TextBox '''<summary> '''cmdCalc control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents cmdCalc As Global.System.Web.UI.WebControls.Button '''<summary> '''BottomInfoBar1 control. '''</summary> '''<remarks> '''Auto-generated field. '''To modify move field declaration from designer file to code-behind file. '''</remarks> Protected WithEvents BottomInfoBar1 As Global.SKlone.BottomInfoBar End Class
jamend/SKlone
SKlone/scripts/CalcB.aspx.designer.vb
Visual Basic
mit
9,636
' 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.CSharp Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Shared.Options Imports Microsoft.CodeAnalysis.SolutionCrawler Imports Microsoft.CodeAnalysis.VisualBasic Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests ''' <summary> ''' Tests for Error List. Since it is language agnostic there are no C# or VB Specific tests ''' </summary> Public Class DiagnosticProviderTests Private Const ErrorElementName As String = "Error" Private Const ProjectAttributeName As String = "Project" Private Const CodeAttributeName As String = "Code" Private Const MappedLineAttributeName As String = "MappedLine" Private Const MappedColumnAttributeName As String = "MappedColumn" Private Const OriginalLineAttributeName As String = "OriginalLine" Private Const OriginalColumnAttributeName As String = "OriginalColumn" Private Const IdAttributeName As String = "Id" Private Const MessageAttributeName As String = "Message" Private Const OriginalFileAttributeName As String = "OriginalFile" Private Const MappedFileAttributeName As String = "MappedFile" <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestNoErrors() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { } </Document> </Project> </Workspace> VerifyAllAvailableDiagnostics(test, Nothing) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestSingleDeclarationError() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { dontcompile } </Document> </Project> </Workspace> Dim diagnostics = <Diagnostics> <Error Code="1519" Id="CS1519" MappedFile="Test.cs" MappedLine="1" MappedColumn="64" OriginalFile="Test.cs" OriginalLine="1" OriginalColumn="64" Message=<%= String.Format(CSharpResources.ERR_InvalidMemberDecl, "}") %>/> </Diagnostics> VerifyAllAvailableDiagnostics(test, diagnostics) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestLineDirective() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { dontcompile } #line 1000 class Foo2 { dontcompile } #line default class Foo4 { dontcompile } </Document> </Project> </Workspace> Dim diagnostics = <Diagnostics> <Error Code="1519" Id="CS1519" MappedFile="Test.cs" MappedLine="1" MappedColumn="64" OriginalFile="Test.cs" OriginalLine="1" OriginalColumn="64" Message=<%= String.Format(CSharpResources.ERR_InvalidMemberDecl, "}") %>/> <Error Code="1519" Id="CS1519" MappedFile="Test.cs" MappedLine="999" MappedColumn="65" OriginalFile="Test.cs" OriginalLine="3" OriginalColumn="65" Message=<%= String.Format(CSharpResources.ERR_InvalidMemberDecl, "}") %>/> <Error Code="1519" Id="CS1519" MappedFile="Test.cs" MappedLine="5" MappedColumn="65" OriginalFile="Test.cs" OriginalLine="5" OriginalColumn="65" Message=<%= String.Format(CSharpResources.ERR_InvalidMemberDecl, "}") %>/> </Diagnostics> VerifyAllAvailableDiagnostics(test, diagnostics) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestSingleBindingError() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { int a = "test"; } </Document> </Project> </Workspace> Dim diagnostics = <Diagnostics> <Error Code="29" Id="CS0029" MappedFile="Test.cs" MappedLine="1" MappedColumn="60" OriginalFile="Test.cs" OriginalLine="1" OriginalColumn="60" Message=<%= String.Format(CSharpResources.ERR_NoImplicitConv, "string", "int") %>/> </Diagnostics> VerifyAllAvailableDiagnostics(test, diagnostics) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestMultipleErrorsAndWarnings() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Foo { gibberish } class Foo2 { as; } class Foo3 { long q = 1l; } #pragma disable 9999999" </Document> </Project> </Workspace> Dim diagnostics = <Diagnostics> <Error Code="1519" Id="CS1519" MappedFile="Test.cs" MappedLine="1" MappedColumn="62" OriginalFile="Test.cs" OriginalLine="1" OriginalColumn="62" Message=<%= String.Format(CSharpResources.ERR_InvalidMemberDecl, "}") %>/> <Error Code="1519" Id="CS1519" MappedFile="Test.cs" MappedLine="2" MappedColumn="53" OriginalFile="Test.cs" OriginalLine="2" OriginalColumn="53" Message=<%= String.Format(CSharpResources.ERR_InvalidMemberDecl, "as") %>/> <Warning Code="78" Id="CS0078" MappedFile="Test.cs" MappedLine="3" MappedColumn="63" OriginalFile="Test.cs" OriginalLine="3" OriginalColumn="63" Message=<%= CSharpResources.WRN_LowercaseEllSuffix %>/> <Warning Code="1633" Id="CS1633" MappedFile="Test.cs" MappedLine="4" MappedColumn="48" OriginalFile="Test.cs" OriginalLine="4" OriginalColumn="48" Message=<%= CSharpResources.WRN_IllegalPragma %>/> </Diagnostics> ' Note: The below is removed because of bug # 550593. '<Warning Code = "414" Id="CS0414" MappedFile="Test.cs" MappedLine="3" MappedColumn="58" OriginalFile="Test.cs" OriginalLine="3" OriginalColumn="58" ' Message = "The field 'Foo3.q' is assigned but its value is never used" /> VerifyAllAvailableDiagnostics(test, diagnostics) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestBindingAndDeclarationErrors() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Program { void Main() { - } } </Document> </Project> </Workspace> Dim diagnostics = <Diagnostics> <Error Code="1525" Id="CS1525" MappedFile="Test.cs" MappedLine="1" MappedColumn="72" OriginalFile="Test.cs" OriginalLine="1" OriginalColumn="72" Message=<%= String.Format(CSharpResources.ERR_InvalidExprTerm, "}") %>/> <Error Code="1002" Id="CS1002" MappedFile="Test.cs" MappedLine="1" MappedColumn="72" OriginalFile="Test.cs" OriginalLine="1" OriginalColumn="72" Message=<%= CSharpResources.ERR_SemicolonExpected %>/> </Diagnostics> VerifyAllAvailableDiagnostics(test, diagnostics) End Sub ' Diagnostics are ordered by project-id <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestDiagnosticsFromMultipleProjects() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Program { - void Test() { int a = 5 - "2"; } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Test.vb"> Class FooClass Sub Blah() End Sub End Class </Document> </Project> </Workspace> Dim diagnostics = <Diagnostics> <Error Code="1519" Id="CS1519" MappedFile="Test.cs" MappedLine="3" MappedColumn="44" OriginalFile="Test.cs" OriginalLine="3" OriginalColumn="44" Message=<%= String.Format(CSharpResources.ERR_InvalidMemberDecl, "-") %>/> <Error Code="19" Id="CS0019" MappedFile="Test.cs" MappedLine="6" MappedColumn="56" OriginalFile="Test.cs" OriginalLine="6" OriginalColumn="56" Message=<%= String.Format(CSharpResources.ERR_BadBinaryOps, "-", "int", "string") %>/> <Error Code="30026" Id="BC30026" MappedFile="Test.vb" MappedLine="2" MappedColumn="44" OriginalFile="Test.vb" OriginalLine="2" OriginalColumn="44" Message=<%= ERR_EndSubExpected %>/> <Error Code="30205" Id="BC30205" MappedFile="Test.vb" MappedLine="2" MappedColumn="55" OriginalFile="Test.vb" OriginalLine="2" OriginalColumn="55" Message=<%= ERR_ExpectedEOS %>/> </Diagnostics> VerifyAllAvailableDiagnostics(test, diagnostics, ordered:=False) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub TestDiagnosticsFromTurnedOff() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Program { - void Test() { int a = 5 - "2"; } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Test.vb"> Class FooClass Sub Blah() End Sub End Class </Document> </Project> </Workspace> Dim diagnostics = <Diagnostics></Diagnostics> VerifyAllAvailableDiagnostics(test, diagnostics, ordered:=False, enabled:=False) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub WarningsAsErrors() Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <CompilationOptions ReportDiagnostic="Error"/> <Document FilePath="Test.cs"> class Program { void Test() { int a = 5; } } </Document> </Project> </Workspace> Dim diagnostics = <Diagnostics> <Error Code="219" Id="CS0219" MappedFile="Test.cs" MappedLine="5" MappedColumn="40" OriginalFile="Test.cs" OriginalLine="5" OriginalColumn="40" Message=<%= String.Format(CSharpResources.WRN_UnreferencedVarAssg, "a") %>/> </Diagnostics> VerifyAllAvailableDiagnostics(test, diagnostics) End Sub Private Sub VerifyAllAvailableDiagnostics(test As XElement, diagnostics As XElement, Optional ordered As Boolean = True, Optional enabled As Boolean = True) Using workspace = TestWorkspaceFactory.CreateWorkspace(test) ' turn off diagnostic If Not enabled Then Dim optionService = workspace.Services.GetService(Of IOptionService)() optionService.SetOptions( optionService.GetOptions().WithChangedOption(ServiceComponentOnOffOptions.DiagnosticProvider, False) _ .WithChangedOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, LanguageNames.CSharp, False) _ .WithChangedOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, LanguageNames.VisualBasic, False)) End If Dim registrationService = workspace.Services.GetService(Of ISolutionCrawlerRegistrationService)() registrationService.Register(workspace) Dim diagnosticProvider = GetDiagnosticProvider(workspace) Dim actualDiagnostics = diagnosticProvider.GetCachedDiagnosticsAsync(workspace).Result _ .Select(Function(d) New [Shared].Diagnostics.DiagnosticTaskItem(d)) registrationService.Unregister(workspace) If diagnostics Is Nothing Then Assert.Equal(0, actualDiagnostics.Count) Else Dim expectedDiagnostics = GetExpectedDiagnostics(workspace, diagnostics) If ordered Then AssertEx.Equal(expectedDiagnostics, actualDiagnostics, EqualityComparer(Of IErrorTaskItem).Default) Else AssertEx.SetEqual(expectedDiagnostics, actualDiagnostics, EqualityComparer(Of IErrorTaskItem).Default) End If End If End Using End Sub Private Function GetDiagnosticProvider(workspace As TestWorkspace) As DiagnosticAnalyzerService Dim snapshot = workspace.CurrentSolution Dim notificationServie = New TestForegroundNotificationService() Dim compilerAnalyzersMap = DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap() Dim analyzerService = New DiagnosticAnalyzerService(compilerAnalyzersMap) ' CollectErrors generates interleaved background and foreground tasks. Dim service = DirectCast(workspace.Services.GetService(Of ISolutionCrawlerRegistrationService)(), SolutionCrawlerRegistrationService) service.WaitUntilCompletion_ForTestingPurposesOnly(workspace, SpecializedCollections.SingletonEnumerable(analyzerService.CreateIncrementalAnalyzer(workspace)).WhereNotNull().ToImmutableArray()) Return analyzerService End Function Private Function GetExpectedDiagnostics(workspace As TestWorkspace, diagnostics As XElement) As List(Of IErrorTaskItem) Dim result As New List(Of IErrorTaskItem) Dim code As Integer, mappedLine As Integer, mappedColumn As Integer, originalLine As Integer, originalColumn As Integer Dim Id As String, message As String, originalFile As String, mappedFile As String Dim documentId As DocumentId For Each diagnostic As XElement In diagnostics.Elements() code = Integer.Parse(diagnostic.Attribute(CodeAttributeName).Value) mappedLine = Integer.Parse(diagnostic.Attribute(MappedLineAttributeName).Value) mappedColumn = Integer.Parse(diagnostic.Attribute(MappedColumnAttributeName).Value) originalLine = Integer.Parse(diagnostic.Attribute(OriginalLineAttributeName).Value) originalColumn = Integer.Parse(diagnostic.Attribute(OriginalColumnAttributeName).Value) Id = diagnostic.Attribute(IdAttributeName).Value message = diagnostic.Attribute(MessageAttributeName).Value originalFile = diagnostic.Attribute(OriginalFileAttributeName).Value mappedFile = diagnostic.Attribute(MappedFileAttributeName).Value documentId = GetDocumentId(workspace, originalFile) If diagnostic.Name.LocalName.Equals(ErrorElementName) Then result.Add(SourceError(Id, message, workspace, documentId, documentId.ProjectId, mappedLine, originalLine, mappedColumn, originalColumn, mappedFile, originalFile)) Else result.Add(SourceWarning(Id, message, workspace, documentId, documentId.ProjectId, mappedLine, originalLine, mappedColumn, originalColumn, mappedFile, originalFile)) End If Next Return result End Function Private Function GetProjectId(workspace As TestWorkspace, projectName As String) As ProjectId Return (From doc In workspace.Documents Where doc.Project.AssemblyName.Equals(projectName) Select doc.Project.Id).Single() End Function Private Function GetDocumentId(workspace As TestWorkspace, document As String) As DocumentId Return (From doc In workspace.Documents Where doc.FilePath.Equals(document) Select doc.Id).Single() End Function Private Function SourceError(id As String, message As String, workspace As Workspace, docId As DocumentId, projId As ProjectId, mappedLine As Integer, originalLine As Integer, mappedColumn As Integer, originalColumn As Integer, mappedFile As String, originalFile As String) As DiagnosticTaskItem Return New DiagnosticTaskItem(id, DiagnosticSeverity.Error, message, workspace, docId, mappedLine, originalLine, mappedColumn, originalColumn, mappedFile, originalFile) End Function Private Function SourceWarning(id As String, message As String, workspace As Workspace, docId As DocumentId, projId As ProjectId, mappedLine As Integer, originalLine As Integer, mappedColumn As Integer, originalColumn As Integer, mappedFile As String, originalFile As String) As DiagnosticTaskItem Return New DiagnosticTaskItem(id, DiagnosticSeverity.Warning, message, workspace, docId, mappedLine, originalLine, mappedColumn, originalColumn, mappedFile, originalFile) End Function Private Class DiagnosticTaskItem Inherits TaskItem Implements IErrorTaskItem Private ReadOnly _id As String Private ReadOnly _projectId As ProjectId Private ReadOnly _severity As DiagnosticSeverity Public Sub New(id As String, severity As DiagnosticSeverity, message As String, workspace As Workspace, docId As DocumentId, mappedLine As Integer, originalLine As Integer, mappedColumn As Integer, originalColumn As Integer, mappedFile As String, originalFile As String) MyBase.New(message, workspace, docId, mappedLine, originalLine, mappedColumn, originalColumn, mappedFile, originalFile) Me._id = id Me._projectId = docId.ProjectId Me._severity = severity End Sub Public ReadOnly Property Id As String Implements IErrorTaskItem.Id Get Return Me._id End Get End Property Public ReadOnly Property ProjectId As ProjectId Implements IErrorTaskItem.ProjectId Get Return Me._projectId End Get End Property Public ReadOnly Property Severity As DiagnosticSeverity Implements IErrorTaskItem.Severity Get Return Me._severity End Get End Property Public Overrides Function Equals(obj As Object) As Boolean Dim other As IErrorTaskItem = TryCast(obj, IErrorTaskItem) If other Is Nothing Then Return False End If If Not AbstractTaskItem.Equals(Me, other) Then Return False End If Return Id = other.Id AndAlso ProjectId = other.ProjectId AndAlso Severity = other.Severity End Function Public Overrides Function GetHashCode() As Integer Return Hash.Combine(AbstractTaskItem.GetHashCode(Me), Hash.Combine(Id.GetHashCode(), CType(Severity, Integer))) End Function End Class End Class End Namespace
ManishJayaswal/roslyn
src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb
Visual Basic
apache-2.0
23,148
' 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.Xml.Linq Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class PropertyTests Inherits BasicTestBase #Region "Basic Test cases" ' Allow assigning to property name in Get accessor. <Fact> Public Sub AssignToPropertyNameInGet() Dim source = <compilation> <file name="c.vb"> Class C ReadOnly Property P Get P = Nothing End Get End Property End Class </file> </compilation> CompileAndVerify(source) End Sub ' Properties with setter implemented by getter: not supported. <Fact> Public Sub GetUsedAsSet() Dim customIL = <![CDATA[ .class public A { .method public static bool get_s() { ldnull throw } .method public instance int32 get_i() { ldnull throw } .property bool P() { .get bool A::get_s() .set bool A::get_s() } .property int32 Q() { .get instance int32 A::get_i() .set instance int32 A::get_i() } } ]]> Dim source = <compilation> <file name="a.vb"> Class B Shared Sub M(x As A) N(A.P) N(x.Q) End Sub Shared Sub N(o) End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30643: Property 'A.P' is of an unsupported type. N(A.P) ~ BC30643: Property 'A.Q' is of an unsupported type. N(x.Q) ~ </expected>) End Sub ' Property and accessor signatures have mismatched parameter counts: not ' supported. (Note: Native compiler allows these properties but provides ' errors when trying to use cases where either the accessor or ' property signature has zero parameters and the other has non-zero.) <Fact> Public Sub PropertyParameterCountMismatch() Dim customIL = <![CDATA[ .class public A { .method public instance bool get_0() { ldnull throw } .method public instance void set_0(bool val) { ret } .method public instance bool get_1(int32 index) { ldnull throw } .method public instance void set_1(int32 index, bool val) { ret } .method public instance bool get_2(int32 x, int32 y) { ldnull throw } .method public instance void set_2(int32 x, int32 y, bool val) { ret } .property bool P() { .get instance bool A::get_1(int32 index) .set instance void A::set_1(int32 index, bool val) } .property bool Q(int32 index) { .get instance bool A::get_2(int32 x, int32 y) .set instance void A::set_2(int32 x, int32 y, bool val) } .property bool R(int32 x, int32 y) { .get instance bool A::get_0() .set instance void A::set_0(bool val) } } ]]> Dim source = <compilation> <file name="a.vb"> Class C Shared Sub M(x As A) Dim y As Boolean y = x.P y = x.Q(0) y = x.R(0, 1) x.P = y x.Q(0) = y x.R(0, 1) = y End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30643: Property 'A.P' is of an unsupported type. y = x.P ~ BC30643: Property 'A.Q(x As Integer)' is of an unsupported type. y = x.Q(0) ~ BC30643: Property 'A.R(val As Integer, Param As Integer)' is of an unsupported type. y = x.R(0, 1) ~ BC30643: Property 'A.P' is of an unsupported type. x.P = y ~ BC30643: Property 'A.Q(x As Integer)' is of an unsupported type. x.Q(0) = y ~ BC30643: Property 'A.R(val As Integer, Param As Integer)' is of an unsupported type. x.R(0, 1) = y ~ </expected>) End Sub ' Properties with one static and one instance accessor. ' Dev11 uses the accessor to determine whether access ' is through instance or type name. Roslyn does not ' support such properties. Breaking change. <WorkItem(528159, "DevDiv")> <Fact()> Public Sub MismatchedStaticInstanceAccessors() Dim customIL = <![CDATA[ .class public A { .method public static int32 get_s() { ldc.i4.0 ret } .method public static void set_s(int32 val) { ret } .method public instance int32 get_i() { ldc.i4.0 ret } .method public instance void set_i(int32 val) { ret } .property int32 P() { .get int32 A::get_s() .set instance void A::set_i(int32 val) } .property int32 Q() { .get instance int32 A::get_i() .set void A::set_s(int32 val) } } ]]> Dim source = <compilation> <file name="a.vb"> Class C Shared Sub M(x As A) x.P = x.Q A.Q = A.P End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL) compilation.AssertTheseDiagnostics( <expected> BC30643: Property 'A.P' is of an unsupported type. x.P = x.Q ~ BC30643: Property 'A.Q' is of an unsupported type. x.P = x.Q ~ BC30643: Property 'A.Q' is of an unsupported type. A.Q = A.P ~ BC30643: Property 'A.P' is of an unsupported type. A.Q = A.P ~ </expected>) End Sub ' Property with type that does not match accessors. ' Expression type should be determined from accessor. <WorkItem(528160, "DevDiv")> <Fact()> Public Sub WrongPropertyType() Dim customIL = <![CDATA[ .class public A { .method public instance int32 get() { ldc.i4.0 ret } .method public instance void set(int32 val) { ret } .property string P() { .get instance int32 A::get() .set instance void A::set(int32 val) } } ]]> Dim source = <compilation> <file name="a.vb"> Class C Shared Sub M(x As A) Dim y As Integer = x.P x.P = y End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL) CompilationUtils.AssertNoErrors(compilation) End Sub ' Property with void type. (IDE with native compiler crashes.) <Fact> Public Sub VoidPropertyType() Dim customIL = <![CDATA[ .class public A { .method public instance int32 get() { ldc.i4.0 ret } .method public instance void set(int32 val) { ret } .property void P() { .get instance int32 A::get() .set instance void A::set(int32 val) } } ]]> Dim source = <compilation> <file name="a.vb"> Class C Shared Sub M(x As A) Dim y As Integer = x.P x.P = y End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL) compilation.AssertNoErrors() End Sub ' Property and getter with void type. Dev10 treats this as a valid ' property. Would it be better to treat the property as invalid? <Fact> Public Sub VoidPropertyAndAccessorType() Dim customIL = <![CDATA[ .class public A { .method public static void get_P() { ret } .property void P() { .get void A::get_P() } .method public instance void get_Q() { ret } .property void Q() { .get instance void A::get_Q() } } ]]> Dim source = <compilation> <file name="a.vb"> Class B Shared Sub M(x As A) N(A.P) N(x.Q) End Sub Shared Sub N(o) End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30491: Expression does not produce a value. N(A.P) ~~~ BC30491: Expression does not produce a value. N(x.Q) ~~~ </expected>) End Sub ' Properties where the property and accessor signatures differ by ' modopt only should be supported (as in the native compiler). <Fact> Public Sub SignaturesDifferByModOptsOnly() Dim ilSource = <![CDATA[ .class public A { } .class public B { } .class public C { .method public instance int32 get_noopt() { ldc.i4.0 ret } .method public instance int32 modopt(A) get_returnopt() { ldc.i4.0 ret } .method public instance void set_noopt(int32 val) { ret } .method public instance void set_argopt(int32 modopt(A) val) { ret } .method public instance void modopt(A) set_returnopt(int32 val) { ret } // Modifier on property but not accessors. .property int32 modopt(A) P1() { .get instance int32 C::get_noopt() .set instance void C::set_noopt(int32) } // Modifier on accessors but not property. .property int32 P2() { .get instance int32 modopt(A) C::get_returnopt() .set instance void C::set_argopt(int32 modopt(A)) } // Modifier on getter only. .property int32 P3() { .get instance int32 modopt(A) C::get_returnopt() .set instance void C::set_noopt(int32) } // Modifier on setter only. .property int32 P4() { .get instance int32 C::get_noopt() .set instance void C::set_argopt(int32 modopt(A)) } // Modifier on setter return type. .property int32 P5() { .get instance int32 C::get_noopt() .set instance void modopt(A) C::set_returnopt(int32) } // Modifier on property and different modifier on accessors. .property int32 modopt(B) P6() { .get instance int32 modopt(A) C::get_returnopt() .set instance void C::set_argopt(int32 modopt(A)) } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class D Shared Sub M(c As C) c.P1 = c.P1 c.P2 = c.P2 c.P3 = c.P3 c.P4 = c.P4 c.P5 = c.P5 c.P6 = c.P6 End Sub End Class ]]> </file> </compilation> CompileWithCustomILSource(vbSource, ilSource) End Sub <Fact> Public Sub PropertyGetAndSet() Dim source = <compilation> <file name="c.vb"> Module M Sub Main() Dim x As C = New C() x.P = 2 C.Q = "q" System.Console.Write("{0}, {1}", x.P, C.Q) End Sub End Module Class C Private _p Property P Get Return _p End Get Set(value) _p = value End Set End Property Private Shared _q Shared Property Q Get Return _q End Get Set(value) _q = value End Set End Property End Class </file> </compilation> Dim compilationVerifier = CompileAndVerify(source, expectedOutput:="2, q") compilationVerifier.VerifyIL("M.Main", <![CDATA[ { // Code size 60 (0x3c) .maxstack 3 .locals init (C V_0) //x IL_0000: newobj "Sub C..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.2 IL_0008: box "Integer" IL_000d: callvirt "Sub C.set_P(Object)" IL_0012: ldstr "q" IL_0017: call "Sub C.set_Q(Object)" IL_001c: ldstr "{0}, {1}" IL_0021: ldloc.0 IL_0022: callvirt "Function C.get_P() As Object" IL_0027: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002c: call "Function C.get_Q() As Object" IL_0031: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0036: call "Sub System.Console.Write(String, Object, Object)" IL_003b: ret } ]]>) End Sub <Fact> Public Sub PropertyAutoGetAndSet() Dim source = <compilation> <file name="c.vb"> Module M Sub Main() Dim x As C = New C() x.P = 2 C.Q = "q" System.Console.Write("{0}, {1}", x.P, C.Q) End Sub End Module Class C Property P Shared Property Q End Class </file> </compilation> Dim compilationVerifier = CompileAndVerify(source, expectedOutput:="2, q") compilationVerifier.VerifyIL("M.Main", <![CDATA[ { // Code size 60 (0x3c) .maxstack 3 .locals init (C V_0) //x IL_0000: newobj "Sub C..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.2 IL_0008: box "Integer" IL_000d: callvirt "Sub C.set_P(Object)" IL_0012: ldstr "q" IL_0017: call "Sub C.set_Q(Object)" IL_001c: ldstr "{0}, {1}" IL_0021: ldloc.0 IL_0022: callvirt "Function C.get_P() As Object" IL_0027: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002c: call "Function C.get_Q() As Object" IL_0031: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0036: call "Sub System.Console.Write(String, Object, Object)" IL_003b: ret } ]]>) compilationVerifier.VerifyIL("C.get_P", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld "C._P As Object" IL_0006: ret } ]]>) compilationVerifier.VerifyIL("C.set_P", <![CDATA[ { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0007: stfld "C._P As Object" IL_000c: ret } ]]>) compilationVerifier.VerifyIL("C.get_Q", <![CDATA[ { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsfld "C._Q As Object" IL_0005: ret } ]]>) compilationVerifier.VerifyIL("C.set_Q", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0006: stsfld "C._Q As Object" IL_000b: ret } ]]>) End Sub #End Region #Region "Code Gen" ' All property overload metadata should have a name that matches the casing the of the first declared overload <WorkItem(539893, "DevDiv")> <Fact()> Public Sub PropertiesILCaseSenstivity() Dim source = <compilation> <file name="a.vb"> Public Class TestClass Property P As Integer Property p(i As Integer) As Integer Get Return Nothing End Get Set(value As Integer) End Set End Property Overridable Property P(i As String) As Integer Get Return Nothing End Get Set(value As Integer) End Set End Property End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source, OutputKind.DynamicallyLinkedLibrary) Dim referenceBytes = New IO.MemoryStream() compilation.Emit(referenceBytes) Dim symbols = MetadataTestHelpers.GetSymbolsForReferences({referenceBytes.GetBuffer()}).Single() Dim testClassSymbol = symbols.Modules.First().GlobalNamespace.GetMembers("TestClass").OfType(Of NamedTypeSymbol).Single() Dim propertySymbols = testClassSymbol.GetMembers("P").OfType(Of PropertySymbol)() Dim propertyGettersSymbols = testClassSymbol.GetMembers("get_P").OfType(Of MethodSymbol)() Assert.Equal(propertySymbols.Count(Function(psymb) psymb.Name.Equals("P")), 3) Assert.Equal(propertyGettersSymbols.Count(Function(msymb) msymb.Name.Equals("get_p")), 1) Assert.Equal(propertyGettersSymbols.Count(Function(msymb) msymb.Name.Equals("get_P")), 2) End Sub #End Region #Region "Properties Parameters" ' Set method with no explicit parameter. <Fact> Public Sub SetParameterImplicit() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="c.vb"> Class C Private _p As Object Property P Get Return _p End Get Set _p = value End Set End Property End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' Set method with parameter name different from default. <Fact> Public Sub SetParameterNonDefaultName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="c.vb"> Class C Private _p As Object Property P Get Return _p End Get Set(v) _p = v End Set End Property End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' Set method must specify type if property type is not Object. <Fact> Public Sub SetParameterExplicitTypeForNonObjectProperty() CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="c.vb"> Class C Private _p As Integer Property P As Integer Get Return _p End Get Set(value) _p = value End Set End Property End Class </file> </compilation>). VerifyDiagnostics( Diagnostic(ERRID.ERR_SetValueNotPropertyType, "value")) End Sub <Fact> Public Sub PropertyMembers() Dim sources = <compilation> <file name="c.vb"> Interface I Property P ReadOnly Property Q WriteOnly Property R End Interface MustInherit Class A MustOverride Property P MustOverride ReadOnly Property Q MustOverride WriteOnly Property R End Class Class B Property P ReadOnly Property Q Get Return Nothing End Get End Property WriteOnly Property R Set End Set End Property End Class </file> </compilation> Dim validator = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) Dim type = [module].GlobalNamespace.GetTypeMembers("I").Single() VerifyProperty(type, "P", Accessibility.Public, isFromSource, hasGet:=True, hasSet:=True, hasField:=False) VerifyProperty(type, "Q", Accessibility.Public, isFromSource, hasGet:=True, hasSet:=False, hasField:=False) VerifyProperty(type, "R", Accessibility.Public, isFromSource, hasGet:=False, hasSet:=True, hasField:=False) type = [module].GlobalNamespace.GetTypeMembers("A").Single() VerifyProperty(type, "P", Accessibility.Public, isFromSource, hasGet:=True, hasSet:=True, hasField:=False) VerifyProperty(type, "Q", Accessibility.Public, isFromSource, hasGet:=True, hasSet:=False, hasField:=False) VerifyProperty(type, "R", Accessibility.Public, isFromSource, hasGet:=False, hasSet:=True, hasField:=False) type = [module].GlobalNamespace.GetTypeMembers("B").Single() VerifyProperty(type, "P", Accessibility.Public, isFromSource, hasGet:=True, hasSet:=True, hasField:=True) VerifyProperty(type, "Q", Accessibility.Public, isFromSource, hasGet:=True, hasSet:=False, hasField:=False) VerifyProperty(type, "R", Accessibility.Public, isFromSource, hasGet:=False, hasSet:=True, hasField:=False) End Sub CompileAndVerify(sources, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False)) End Sub Private Sub VerifyProperty(type As NamedTypeSymbol, name As String, declaredAccessibility As Accessibility, isFromSource As Boolean, hasGet As Boolean, hasSet As Boolean, hasField As Boolean) Dim [property] = TryCast(type.GetMembers(name).SingleOrDefault(), PropertySymbol) Assert.NotNull([property]) Assert.Equal([property].DeclaredAccessibility, declaredAccessibility) Dim accessor = [property].GetMethod If hasGet Then Assert.NotNull(accessor) Assert.Equal(accessor.DeclaredAccessibility, declaredAccessibility) Else Assert.Null(accessor) End If accessor = [property].SetMethod If hasSet Then Assert.NotNull(accessor) Assert.Equal(accessor.DeclaredAccessibility, declaredAccessibility) Else Assert.Null(accessor) End If Dim field = DirectCast(type.GetMembers("_" + name).SingleOrDefault(), FieldSymbol) If isFromSource AndAlso hasField Then Assert.NotNull(field) Assert.Equal(field.DeclaredAccessibility, Accessibility.Private) Else Assert.Null(field) End If End Sub <Fact> Public Sub PropertyGetAndSetWithParameters() Dim sources = <compilation> <file name="c.vb"> Module Module1 Sub Main() Dim x As C = New C() x.P(1) = 2 System.Console.Write("{0}, {1}", x.P(1), x.P(x.P(1))) End Sub End Module Class C Private _p As Object Property P(ByVal i As Integer) As Object Get If (i = 1) Then Return _p End If Return 0 End Get Set(ByVal value As Object) If (i = 1) Then _p = value End If End Set End Property End Class </file> </compilation> Dim validator = Sub([module] As ModuleSymbol) Dim type = [module].GlobalNamespace.GetTypeMembers("C").Single() Dim [property] = type.GetMembers("P").OfType(Of PropertySymbol)().SingleOrDefault() Assert.NotNull([property]) VerifyPropertiesParametersCount([property], 1) Assert.Equal(SpecialType.System_Object, [property].Type.SpecialType) Assert.Equal(SpecialType.System_Int32, [property].Parameters(0).Type.SpecialType) Assert.Equal(SpecialType.System_Int32, [property].GetMethod.Parameters(0).Type.SpecialType) Assert.Equal(SpecialType.System_Int32, [property].SetMethod.Parameters(0).Type.SpecialType) Assert.Equal(SpecialType.System_Object, [property].SetMethod.Parameters(1).Type.SpecialType) Assert.Equal([property].SetMethod.Parameters(1).Name, "value") End Sub CompileAndVerify(sources, sourceSymbolValidator:=validator, symbolValidator:=validator, expectedOutput:="2, 0") End Sub <Fact()> Public Sub PropertyGetAndSetWithParametersOverridesAndGeneric() Dim sources = <compilation> <file name="c.vb"> Public MustInherit Class TestClass(Of T) End Class Public Class TestClass2 Inherits TestClass(Of String) Public Overloads Property P1(pr1 As String, Optional pr2 As String = "") As Integer Get Return Nothing End Get Set(value As Integer) End Set End Property Public Overloads Property P1(pr1 As Integer, pr2 As String, ParamArray parray() As Double) As Integer Get Return Nothing End Get Set(value As Integer) End Set End Property Public Overloads Property P2(pr1 As Integer, pr2 As String) As Integer Get Return Nothing End Get Set End Set End Property Public Overloads Property P2(pr1 As String, Optional pr2 As String = Nothing) As String Get Return Nothing End Get Set End Set End Property End Class </file> </compilation> Dim validator = Sub([module] As ModuleSymbol) Dim type = [module].GlobalNamespace.GetTypeMembers("TestClass2").Single() Dim P1s = type.GetMembers("P1").OfType(Of PropertySymbol)().OrderBy(Function(symb) symb.GetMethod.Parameters.Length) Dim P2s = type.GetMembers("P2").OfType(Of PropertySymbol)().OrderBy(Function(symb) symb.GetMethod.ReturnType.Name) Assert.NotNull(P1s) Assert.NotNull(P2s) Assert.NotEmpty(P1s) Assert.NotEmpty(P2s) VerifyPropertiesParametersCount(P1s.ElementAt(0), 2) VerifyPropertiesParametersCount(P1s.ElementAt(1), 3) Assert.True(P1s.ElementAt(0).Parameters(1).IsOptional) Assert.Equal(P1s.ElementAt(0).Parameters(1).ExplicitDefaultValue, String.Empty) Assert.True(P1s.ElementAt(1).Parameters(2).IsParamArray) VerifyPropertiesParametersCount(P2s.ElementAt(0), 2) VerifyPropertiesParametersCount(P2s.ElementAt(1), 2) Assert.Equal(SpecialType.System_String, P2s.ElementAt(1).Type.SpecialType) End Sub CompileAndVerify(sources, sourceSymbolValidator:=validator, symbolValidator:=validator) End Sub <Fact> Public Sub SetWithParametersGetObjectValue() Dim compilationVerifier = CompileAndVerify( <compilation> <file name="c.vb"> Class C Sub Invoke(arg, value) P(arg) = value End Sub Property P(arg As Object) As Object Get Return Nothing End Get Set(ByVal value As Object) End Set End Property End Class </file> </compilation>) compilationVerifier.VerifyIL("C.Invoke", <![CDATA[ { // Code size 19 (0x13) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0007: ldarg.2 IL_0008: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000d: call "Sub C.set_P(Object, Object)" IL_0012: ret } ]]>) End Sub <Fact> Public Sub DictionaryMemberAccess() Dim compilationVerifier = CompileAndVerify( <compilation> <file name="c.vb"> Imports System Imports System.Collections.Generic Class C Private _P As Dictionary(Of String, String) Default Property P(key As String) As String Get Return _P(key) End Get Set(value As String) _P(key) = value End Set End Property Sub New() _P = New Dictionary(Of String, String) End Sub Shared Sub Main() Dim x As C = New C() x("A") = "value" x!B = x!A.ToUpper() Console.WriteLine("A={0}, B={1}", x("A"), x("B")) End Sub End Class </file> </compilation>, expectedOutput:="A=value, B=VALUE") End Sub <Fact> Public Sub DictionaryMemberAccessPassByRef() Dim compilationVerifier = CompileAndVerify( <compilation> <file name="c.vb"> Imports System Imports System.Collections.Generic Class A Private _P As Dictionary(Of String, String) Default Property P(key As String) As String Get Return _P(key) End Get Set(value As String) _P(key) = value End Set End Property Sub New() _P = New Dictionary(Of String, String) End Sub End Class Class B Private _Q As Dictionary(Of String, A) Default ReadOnly Property Q(key As String) As A Get Return _Q(key) End Get End Property Sub New(key As String, value As A) _Q = New Dictionary(Of String, A) _Q(key) = value End Sub End Class Class C Shared Sub Main() Dim value As A = New A() value("B") = "value" Dim x As B = New B("A", value) Console.WriteLine("Before: {0}", x!A!B) M(x!A!B) Console.WriteLine("After: {0}", x!A!B) End Sub Shared Sub M(ByRef s As String) s = s.ToUpper() End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ Before: value After: VALUE ]]>) End Sub <Fact> Public Sub DictionaryMemberAccessWithTypeCharacter() Dim compilationVerifier = CompileAndVerify( <compilation> <file name="c.vb"> Option Infer Off Imports System.Collections.Generic Module M Sub Main() M() End Sub Sub M() Dim d As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)() d!x% = 1 d!y = 2 Dim x = d!x Dim y = d!y% System.Console.WriteLine("{0}, {1}", x, y) End Sub End Module </file> </compilation>, expectedOutput:="1, 2") compilationVerifier.VerifyIL("M.M", <![CDATA[ { // Code size 85 (0x55) .maxstack 4 .locals init (Object V_0, //x Object V_1) //y IL_0000: newobj "Sub System.Collections.Generic.Dictionary(Of String, Integer)..ctor()" IL_0005: dup IL_0006: ldstr "x" IL_000b: ldc.i4.1 IL_000c: callvirt "Sub System.Collections.Generic.Dictionary(Of String, Integer).set_Item(String, Integer)" IL_0011: dup IL_0012: ldstr "y" IL_0017: ldc.i4.2 IL_0018: callvirt "Sub System.Collections.Generic.Dictionary(Of String, Integer).set_Item(String, Integer)" IL_001d: dup IL_001e: ldstr "x" IL_0023: callvirt "Function System.Collections.Generic.Dictionary(Of String, Integer).get_Item(String) As Integer" IL_0028: box "Integer" IL_002d: stloc.0 IL_002e: ldstr "y" IL_0033: callvirt "Function System.Collections.Generic.Dictionary(Of String, Integer).get_Item(String) As Integer" IL_0038: box "Integer" IL_003d: stloc.1 IL_003e: ldstr "{0}, {1}" IL_0043: ldloc.0 IL_0044: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0049: ldloc.1 IL_004a: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_004f: call "Sub System.Console.WriteLine(String, Object, Object)" IL_0054: ret } ]]>) End Sub #End Region #Region "Auto Properties" <Fact> Public Sub AutoPropertyInitializer() Dim source = <compilation> <file name="c.vb"> Module M Sub Main() ' touch something shared from A or derived classes to force the shared constructors always to run. ' otherwise beforefieldinit causes different results while running under the debugger. Dim ignored = A.Dummy M(New ADerived()) M(New ADerived()) M(New BDerived()) M(New BDerived()) End Sub Sub M(ByVal o) End Sub End Module Class ABase Sub New() C.Message("ABase..ctor") End Sub End Class Class A Inherits ABase Shared Property P = New C("Shared Property A.P") Public Shared F = New C("Shared Field A.F") Public G = New C("Instance Field A.G") Overridable Property Q = New C("Instance Property A.Q") Public Shared Dummy As Integer = 23 End Class Class ADerived Inherits A Public Overrides Property Q As Object Get Return Nothing End Get Set(ByVal value As Object) C.Message("A.Q.set") End Set End Property End Class Class BBase Sub New() C.Message("BBase..ctor") End Sub End Class Class B Inherits BBase Public Shared F = New C("Shared Field B.F") Shared Property P = New C("Shared Property B.P") Overridable Property Q = New C("Instance Property B.Q") Public G = New C("Instance Field B.G") Shared Sub New() C.Message("B..cctor") End Sub Sub New() C.Message("B..ctor") End Sub End Class Class BDerived Inherits B Public Overrides Property Q As Object Get Return Nothing End Get Set(ByVal value As Object) C.Message("B.Q.set") End Set End Property End Class Class C Public Sub New(ByVal s As String) Message(s) End Sub Shared Sub Message(ByVal s As String) System.Console.WriteLine("{0}", s) End Sub End Class </file> </compilation> ' if a debugger is attached, the beforefieldinit attribute is ignored and the shared constructors ' are executed although no shared fields have been accessed. This causes the test to fail under a debugger. ' Therefore I've added an access to a shared field of class A, because accessing a field of type ADerived ' would not trigger the base type initializers. Dim compilationVerifier = CompileAndVerify(source, expectedOutput:=<![CDATA[ Shared Property A.P Shared Field A.F ABase..ctor Instance Field A.G Instance Property A.Q A.Q.set ABase..ctor Instance Field A.G Instance Property A.Q A.Q.set Shared Field B.F Shared Property B.P B..cctor BBase..ctor Instance Property B.Q B.Q.set Instance Field B.G B..ctor BBase..ctor Instance Property B.Q B.Q.set Instance Field B.G B..ctor ]]>) compilationVerifier.VerifyIL("A..ctor", <![CDATA[ { // Code size 39 (0x27) .maxstack 2 IL_0000: ldarg.0 IL_0001: call "Sub ABase..ctor()" IL_0006: ldarg.0 IL_0007: ldstr "Instance Field A.G" IL_000c: newobj "Sub C..ctor(String)" IL_0011: stfld "A.G As Object" IL_0016: ldarg.0 IL_0017: ldstr "Instance Property A.Q" IL_001c: newobj "Sub C..ctor(String)" IL_0021: callvirt "Sub A.set_Q(Object)" IL_0026: ret } ]]>) compilationVerifier.VerifyIL("B..ctor", <![CDATA[ { // Code size 49 (0x31) .maxstack 2 IL_0000: ldarg.0 IL_0001: call "Sub BBase..ctor()" IL_0006: ldarg.0 IL_0007: ldstr "Instance Property B.Q" IL_000c: newobj "Sub C..ctor(String)" IL_0011: callvirt "Sub B.set_Q(Object)" IL_0016: ldarg.0 IL_0017: ldstr "Instance Field B.G" IL_001c: newobj "Sub C..ctor(String)" IL_0021: stfld "B.G As Object" IL_0026: ldstr "B..ctor" IL_002b: call "Sub C.Message(String)" IL_0030: ret } ]]>) End Sub <Fact> Public Sub OverrideAutoPropertyInitializer() Dim compilationVerifier = CompileAndVerify( <compilation> <file name="c.vb"> Module M1 Sub Main() Dim c As C = New C() c.P = 3 End Sub End Module Class A Overridable Property P As Integer = 1 End Class Class B Inherits A Overrides Property P As Integer = 2 End Class Class C Inherits B Overrides Property P As Integer Get Return 0 End Get Set(value As Integer) System.Console.Write("{0}, ", value) End Set End Property End Class </file> </compilation>, expectedOutput:="1, 2, 3, ") compilationVerifier.VerifyIL("B..ctor", <![CDATA[ { // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: call "Sub A..ctor()" IL_0006: ldarg.0 IL_0007: ldc.i4.2 IL_0008: callvirt "Sub B.set_P(Integer)" IL_000d: ret } ]]>) End Sub <Fact> Public Sub AutoProperties() Dim validator = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) Dim type = [module].GlobalNamespace.GetTypeMembers("C").Single() VerifyAutoProperty(type, "P", Accessibility.Protected, isFromSource) VerifyAutoProperty(type, "Q", Accessibility.Friend, isFromSource) End Sub CompileAndVerify( <compilation> <file name="c.vb"> Class C Protected Property P Friend Shared Property Q End Class </file> </compilation>, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False), options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) End Sub <Fact> Public Sub AutoPropertiesComplexTypeInitializer() CompileAndVerify( <compilation> <file name="c.vb"> Module M1 Sub Main() Dim c As C = New C() c.P2.P1 = 2 System.Console.WriteLine(String.Join(",", c.P2.P1, String.Join(",", c.P3))) End Sub End Module Class A Property P1 As Integer = 1 Overridable Property P2 As A Property P3() As String() = New String() {"A", "B", "C"} End Class Class C Inherits A Overrides Property P2 As New A() End Class </file> </compilation>, expectedOutput:="2,A,B,C") End Sub <Fact> Public Sub AutoPropertiesAsNewInitializer() Dim source = <compilation> <file name="c.vb"> imports system Class C1 Public field As Integer Public Sub New(p As Integer) field = p End Sub End Class Class C2 Public Property P1 As New C1(23) Public Shared Sub Main() Dim c as new C2() console.writeline(c.P1.field) End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ 23 ]]>) End Sub <WorkItem(542749, "DevDiv")> <Fact> Public Sub ValueInAutoAndDefaultProperties() Dim source = <compilation> <file name="pp.vb"> Imports system Class C Public Property AP As String Structure S Default Public Property DefP(p As String) As String Get Return p End Get Set End Set End Property End Structure End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source) Dim type01 = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single() Dim type02 = type01.GetTypeMembers("S").Single() Dim autoProp = DirectCast(type01.GetMembers("AP").SingleOrDefault(), PropertySymbol) Dim deftProp = DirectCast(type02.GetMembers("DefP").SingleOrDefault(), PropertySymbol) ' All accessor's parameters should be Synthesized if it's NOT in source Assert.NotNull(autoProp.SetMethod) For Each p In autoProp.SetMethod.Parameters Assert.True(p.IsImplicitlyDeclared) Assert.True(p.IsFromCompilation(compilation)) Next Assert.NotNull(deftProp.SetMethod) For Each p In deftProp.SetMethod.Parameters Assert.True(p.IsImplicitlyDeclared) If p.Name.ToLower() <> "value" Then ' accessor's parameter should point to same location as the parameter's of parent property Assert.False(p.Locations.IsEmpty) End If Next End Sub <Fact> Public Sub ReadOnlyAutoProperties() Dim verifier = CompileAndVerify( <compilation> <file name="c.vb"> Imports System.Console Module Program Sub Main() Dim collection As New MyCollection() Write(collection.Capacity) Write(collection.Capacity = MyCollection.DefaultCapacity) collection = New MyCollection(15) Write(collection.Capacity) collection.DoubleCapacity() Write(collection.Capacity) End Sub End Module Class MyCollection Public Shared ReadOnly Property DefaultCapacity As Integer = 5 Public ReadOnly Property Capacity As Integer = DefaultCapacity Public Sub New() Write(_Capacity) End Sub Public Sub New(capacity As Integer) Write(_Capacity) _Capacity = capacity End Sub Public Sub DoubleCapacity() _Capacity *= 2 End Sub End Class </file> </compilation>, sourceSymbolValidator:=Sub(m As ModuleSymbol) Dim myCollectionType = m.GlobalNamespace.GetTypeMember("MyCollection") Dim defaultCapacityProperty = CType(myCollectionType.GetMember("DefaultCapacity"), PropertySymbol) Assert.True(defaultCapacityProperty.IsReadOnly) Assert.False(defaultCapacityProperty.IsWriteOnly) Assert.True(defaultCapacityProperty.IsShared) Assert.NotNull(defaultCapacityProperty.GetMethod) Assert.Null(defaultCapacityProperty.SetMethod) Dim backingField = CType(myCollectionType.GetMember("_DefaultCapacity"), FieldSymbol) Assert.NotNull(defaultCapacityProperty.AssociatedField) Assert.Same(defaultCapacityProperty.AssociatedField, backingField) End Sub, expectedOutput:="55True51530") verifier.VerifyIL("MyCollection..cctor()", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.5 IL_0001: stsfld "MyCollection._DefaultCapacity As Integer" IL_0006: ret } ]]>) verifier.VerifyIL("MyCollection..ctor()", <![CDATA[ { // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: call "Function MyCollection.get_DefaultCapacity() As Integer" IL_000c: stfld "MyCollection._Capacity As Integer" IL_0011: ldarg.0 IL_0012: ldfld "MyCollection._Capacity As Integer" IL_0017: call "Sub System.Console.Write(Integer)" IL_001c: ret } ]]>) End Sub <Fact> Public Sub WriteOnlyAutoProperties() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="c.vb"> Imports System.Console Module Program Sub Main() Dim collection As New MyCollection() collection.Capacity = 10 collection.WriteCapacity() MyCollection.DefaultCapacity = 15 MyCollection.WriteDefaultCapacity() End Sub End Module Class MyCollection Public Shared WriteOnly Property DefaultCapacity As Integer = 5 Public WriteOnly Property Capacity As Integer = _DefaultCapacity Shared Sub New() WriteDefaultCapacity() End Sub Public Sub New() WriteCapacity() End Sub Public Sub WriteCapacity() Write(_Capacity) Write("_") End Sub Public Shared Sub WriteDefaultCapacity() Write(_DefaultCapacity) Write("_") End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(Compilation, <expected> BC37243: Auto-implemented properties cannot be WriteOnly. Public Shared WriteOnly Property DefaultCapacity As Integer = 5 ~~~~~~~~~~~~~~~ BC37243: Auto-implemented properties cannot be WriteOnly. Public WriteOnly Property Capacity As Integer = _DefaultCapacity ~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReadOnlyAutoPropertiesAndImplements() Dim verifier = CompileAndVerify( <compilation> <file name="c.vb"> Imports System.Console Module Program Sub Main() Dim test As New Test() Dim i As I1 = test Write(i.P1) Write("_") End Sub End Module Interface I1 ReadOnly Property P1 As Integer End Interface Class Test Implements I1 Sub New() _P1 = 5 End Sub Public ReadOnly Property P1 As Integer Implements I1.P1 End Class </file> </compilation>, expectedOutput:="5_") End Sub <Fact> Public Sub ReadOnlyWriteOnlyAutoPropertiesAndImplementsMismatch() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="c.vb"> Module Program Sub Main() End Sub End Module Interface I1 ReadOnly Property P1 As Integer WriteOnly Property P2 As Integer Property P3 As Integer Property P4 As Integer End Interface Class Test Implements I1 Public WriteOnly Property P1 As Integer Implements I1.P1 Public ReadOnly Property P2 As Integer Implements I1.P2 Public WriteOnly Property P3 As Integer Implements I1.P3 Public ReadOnly Property P4 As Integer Implements I1.P4 End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC37243: Auto-implemented properties cannot be WriteOnly. Public WriteOnly Property P1 As Integer Implements I1.P1 ~~ BC31444: 'ReadOnly Property P1 As Integer' cannot be implemented by a WriteOnly property. Public WriteOnly Property P1 As Integer Implements I1.P1 ~~~~~ BC31444: 'WriteOnly Property P2 As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property P2 As Integer Implements I1.P2 ~~~~~ BC37243: Auto-implemented properties cannot be WriteOnly. Public WriteOnly Property P3 As Integer Implements I1.P3 ~~ BC31444: 'Property P3 As Integer' cannot be implemented by a WriteOnly property. Public WriteOnly Property P3 As Integer Implements I1.P3 ~~~~~ BC31444: 'Property P4 As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property P4 As Integer Implements I1.P4 ~~~~~ </expected>) End Sub <Fact> Public Sub ReadOnlyAutoPropertiesAndOverrides() Dim verifier = CompileAndVerify( <compilation> <file name="c.vb"> Imports System.Console Module Program Sub Main() Dim test As New Test() Dim i As I1 = test Write(i.P1) Write("_") End Sub End Module Class I1 Overridable ReadOnly Property P1 As Integer End Class Class Test Inherits I1 Sub New() _P1 = 5 End Sub Public Overrides ReadOnly Property P1 As Integer End Class </file> </compilation>, expectedOutput:="5_") End Sub <Fact> Public Sub ReadOnlyWriteOnlyAutoPropertiesAndOverridesMismatch() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="c.vb"> Module Program Sub Main() End Sub End Module Class I1 Overridable WriteOnly Property P2 As Integer Set end set end property Overridable Property P4 As Integer End Class Class Test Inherits I1 Public Overrides ReadOnly Property P2 As Integer Public Overrides ReadOnly Property P4 As Integer End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30362: 'Public Overrides ReadOnly Property P2 As Integer' cannot override 'Public Overridable WriteOnly Property P2 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property P2 As Integer ~~ BC30362: 'Public Overrides ReadOnly Property P4 As Integer' cannot override 'Public Overridable Property P4 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property P4 As Integer ~~ </expected>) End Sub <Fact> Public Sub ReadOnlyAutoPropertiesAndIterator() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="c.vb"> Module Program Sub Main() End Sub End Module Class Test Iterator ReadOnly Property P1 As System.Collections.Generic.IEnumerable(Of Integer) End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30025: Property missing 'End Property'. Iterator ReadOnly Property P1 As System.Collections.Generic.IEnumerable(Of Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30126: 'ReadOnly' property must provide a 'Get'. Iterator ReadOnly Property P1 As System.Collections.Generic.IEnumerable(Of Integer) ~~ </expected>) End Sub <Fact> Public Sub WriteOnlyAutoPropertiesAndIterator() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="c.vb"> Module Program Sub Main() End Sub End Module Class Test Iterator WriteOnly Property P2 As System.Collections.Generic.IEnumerable(Of Integer) End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30025: Property missing 'End Property'. Iterator WriteOnly Property P2 As System.Collections.Generic.IEnumerable(Of Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31408: 'Iterator' and 'WriteOnly' cannot be combined. Iterator WriteOnly Property P2 As System.Collections.Generic.IEnumerable(Of Integer) ~~~~~~~~~ BC30124: Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'. Iterator WriteOnly Property P2 As System.Collections.Generic.IEnumerable(Of Integer) ~~ </expected>) End Sub #End Region #Region "Default Properties" <Fact> Public Sub DefaultProperties() Dim source = <compilation> <file name="a.vb"> Module Program Sub Main() Dim d As New DefaultProps d(0) = 10 d("1") = 20 d.Items("2") = 30 d.items(3) = 40 System.Console.WriteLine(String.Join(",", d._items)) End Sub End Module Public Class DefaultProps Public _items As Integer() Public Sub New() _items = New Integer(3) {} End Sub Default Property Items(index As Integer) As Integer Get Return _items(index) End Get Set(value As Integer) _items(index) = value End Set End Property Default Property items(index As String) As Integer Get Return _items(index) End Get Set(value As Integer) _items(index) = value End Set End Property End Class </file> </compilation> Dim expectedMainILSource = <![CDATA[ { // Code size 72 (0x48) .maxstack 3 .locals init (DefaultProps V_0) //d IL_0000: newobj "Sub DefaultProps..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 10 IL_000a: callvirt "Sub DefaultProps.set_Items(Integer, Integer)" IL_000f: ldloc.0 IL_0010: ldstr "1" IL_0015: ldc.i4.s 20 IL_0017: callvirt "Sub DefaultProps.set_items(String, Integer)" IL_001c: ldloc.0 IL_001d: ldstr "2" IL_0022: ldc.i4.s 30 IL_0024: callvirt "Sub DefaultProps.set_items(String, Integer)" IL_0029: ldloc.0 IL_002a: ldc.i4.3 IL_002b: ldc.i4.s 40 IL_002d: callvirt "Sub DefaultProps.set_Items(Integer, Integer)" IL_0032: ldstr "," IL_0037: ldloc.0 IL_0038: ldfld "DefaultProps._items As Integer()" IL_003d: call "Function String.Join(Of Integer)(String, System.Collections.Generic.IEnumerable(Of Integer)) As String" IL_0042: call "Sub System.Console.WriteLine(String)" IL_0047: ret } ]]> Dim validator = Sub([module] As ModuleSymbol) Dim type = [module].GlobalNamespace.GetTypeMembers("DefaultProps").Single() Dim properties = type.GetMembers("Items").OfType(Of PropertySymbol)() Assert.True(properties.All(Function(prop) prop.IsDefault), "Not All default properties had PropertySymbol.IsDefault=true") End Sub Dim compilationVerifier = CompileAndVerify(source, sourceSymbolValidator:=validator, symbolValidator:=validator, expectedOutput:="10,20,30,40") compilationVerifier.VerifyIL("Program.Main", expectedMainILSource) End Sub <Fact> Public Sub DefaultPropertySameBaseAndDerived() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> ' Base and derived properties marked Default. Class A1 Default Public ReadOnly Property P(i As Integer) Get Return Nothing End Get End Property End Class Class B1 Inherits A1 Default Public Overloads WriteOnly Property P(x As Integer, y As Integer) Set(value) End Set End Property End Class Class C1 Inherits B1 End Class ' Derived property marked Default, base property not. Class A2 Public ReadOnly Property P(i As Integer) Get Return Nothing End Get End Property End Class Class B2 Inherits A2 Default Public Overloads WriteOnly Property P(x As Integer, y As Integer) Set(value) End Set End Property End Class Class C2 Inherits B2 End Class ' Base property marked Default, derived property not. Class A3 Default Public ReadOnly Property P(i As Integer) Get Return Nothing End Get End Property End Class Class B3 Inherits A3 Public Overloads WriteOnly Property P(x As Integer, y As Integer) Set(value) End Set End Property End Class Class C3 Inherits B3 End Class Module M Sub M(a As A1, b As B1, c As C1) b.P(1, 2) = a.P(3) b(1, 2) = a(3) c.P(1, 2) = c.P(3) c(1, 2) = c(3) End Sub Sub M(a As A2, b As B2, c As C2) b.P(4, 5) = a.P(6) b(4, 5) = a(6) c.P(4, 5) = c.P(6) c(4, 5) = c(6) End Sub Sub M(a As A3, b As B3, c As C3) b.P(7, 8) = a.P(9) b(7, 8) = a(9) c.P(7, 8) = c.P(9) c(7, 8) = c(9) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30367: Class 'A2' cannot be indexed because it has no default property. b(4, 5) = a(6) ~ BC30057: Too many arguments to 'Public ReadOnly Default Property P(i As Integer) As Object'. b(7, 8) = a(9) ~ BC30057: Too many arguments to 'Public ReadOnly Default Property P(i As Integer) As Object'. c(7, 8) = c(9) ~ </expected>) End Sub <Fact> Public Sub DefaultPropertyDifferentBaseAndDerived() Dim compilationVerifier = CompileAndVerify( <compilation> <file name="c.vb"> Imports System ' Default property "P" Class A Default Public ReadOnly Property P(i As Integer) Get Console.WriteLine("A.P: {0}", i) Return Nothing End Get End Property Public ReadOnly Property Q(i As Integer) Get Console.WriteLine("A.Q: {0}", i) Return Nothing End Get End Property Public ReadOnly Property R(x As Integer, y As Integer) Get Console.WriteLine("A.R: {0}, {1}", x, y) Return Nothing End Get End Property End Class ' Default property "Q" Class B Inherits A Public Overloads ReadOnly Property P(i As Integer) Get Console.WriteLine("B.P: {0}", i) Return Nothing End Get End Property Default Public Overloads ReadOnly Property Q(i As Integer) Get Console.WriteLine("B.Q: {0}", i) Return Nothing End Get End Property End Class ' Default property "R" Class C Inherits B Default Public Overloads ReadOnly Property R(i As Integer) Get Console.WriteLine("C.R: {0}", i) Return Nothing End Get End Property End Class ' No default property Class D Inherits B Public Overloads ReadOnly Property P(i As Integer) Get Console.WriteLine("C.P: {0}", i) Return Nothing End Get End Property Public Overloads ReadOnly Property Q(i As Integer) Get Console.WriteLine("C.Q: {0}", i) Return Nothing End Get End Property End Class Module M Sub M(x As C, y As D) Dim value = x(1) value = x(2, 3) value = y(4) value = DirectCast(y, B)(5) value = DirectCast(y, A)(6) End Sub Sub Main() M(New C(), New D()) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ C.R: 1 A.R: 2, 3 B.Q: 4 B.Q: 5 A.P: 6 ]]>) End Sub <Fact> Public Sub DefaultPropertyGroupError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> Class C Default Protected Property P(o As Object) Get Return Nothing End Get Set(value) End Set End Property End Class Module M Function F(o As C) Return o(Nothing) End Function End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30389: 'C.P(o As Object)' is not accessible in this context because it is 'Protected'. Return o(Nothing) ~ </expected>) End Sub <Fact> Public Sub DefaultMembersFromMetadata() Dim customIL = <![CDATA[ // DefaultMember names field .class public DefaultField { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} .field public object F } // DefaultMember names method .class public DefaultMethod { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} .method public hidebysig instance object F(object o) { ldnull ret } } // DefaultMember names property .class public DefaultProperty { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} .method public hidebysig instance object get_F(object o) { ldnull ret } .property object F(object o) { .get instance object DefaultProperty::get_F(object o) } } // DefaultMember names static property .class public DefaultStaticProperty { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} .method public static hidebysig object get_F(object o) { ldnull ret } .property object F(object o) { .get object DefaultStaticProperty::get_F(object o) } } // Property but no DefaultMember .class public PropertyNoDefault { .method public hidebysig instance object get_F(object o) { ldnull ret } .property object F(object o) { .get instance object PropertyNoDefault::get_F(object o) } } // DefaultMember names property with different case .class public DifferentCase { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('DefaultName')} .method public hidebysig instance object get(object o) { ldnull ret } .property object defaultNAME(object o) { .get instance object DifferentCase::get(object o) } } ]]> Dim source = <compilation> <file name="a.vb"> Module M Sub M( x1 As DefaultField, x2 As DefaultMethod, x3 As DefaultProperty, x4 As DefaultStaticProperty, x5 As PropertyNoDefault, x6 As DifferentCase) Dim value As Object value = x1.F value = x1() value = x2.F(value) value = x2(value) value = x3.F(value) value = x3(value) value = x4.F(value) value = x4(value) value = x5.F(value) value = x5(value) value = x6.DefaultName(value) value = x6(value) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30367: Class 'DefaultField' cannot be indexed because it has no default property. value = x1() ~~ BC30367: Class 'DefaultMethod' cannot be indexed because it has no default property. value = x2(value) ~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. value = x4.F(value) ~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. value = x4(value) ~~ BC30367: Class 'PropertyNoDefault' cannot be indexed because it has no default property. value = x5(value) ~~ </expected>) End Sub <Fact> Public Sub DefaultAmbiguousMembersFromMetadata() Dim customIL = <![CDATA[ // DefaultMember names field and property .class public DefaultFieldAndProperty { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} .method public hidebysig instance object get_F(object o) { ldnull ret } .property object F(object o) { .get instance object DefaultFieldAndProperty::get_F(object o) } .field public object F } // DefaultMember names method and property .class public DefaultMethodAndProperty { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} .method public hidebysig instance object F(object x, object y) { ldnull ret } .method public hidebysig instance object get_F(object o) { ldnull ret } .property object F(object o) { .get instance object DefaultMethodAndProperty::get_F(object o) } } ]]> Dim source = <compilation> <file name="a.vb"> Module M Sub M( a As DefaultFieldAndProperty, b As DefaultMethodAndProperty) Dim value As Object value = a.F value = a(value) value = b.F(value) value = b(value) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31429: 'F' is ambiguous because multiple kinds of members with this name exist in class 'DefaultFieldAndProperty'. value = a.F ~~~ BC31429: 'F' is ambiguous because multiple kinds of members with this name exist in class 'DefaultFieldAndProperty'. value = a(value) ~ BC31429: 'F' is ambiguous because multiple kinds of members with this name exist in class 'DefaultMethodAndProperty'. value = b.F(value) ~~~ BC31429: 'F' is ambiguous because multiple kinds of members with this name exist in class 'DefaultMethodAndProperty'. value = b(value) ~ </expected>) End Sub <Fact> Public Sub DefaultPropertiesFromMetadata() Dim customIL = <![CDATA[ // DefaultMember names property .class public DefaultProperty { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} .method public hidebysig instance object get_F(object o) { ldnull ret } .property object F(object o) { .get instance object DefaultProperty::get_F(object o) } } // Property but no DefaultMember .class public PropertyNoDefault { .method public hidebysig instance object get_F(object o) { ldnull ret } .property object F(object o) { .get instance object PropertyNoDefault::get_F(object o) } } // DefaultMember names property in base .class public DefaultBaseProperty extends PropertyNoDefault { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} } // DefaultMember names field in this class and property in base .class public DefaultFieldAndBaseProperty extends PropertyNoDefault { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} .field public object F } // DefaultMember names property (with no args) in this class and property (with args) in base .class public DefaultPropertyAndBaseProperty extends PropertyNoDefault { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} .method public hidebysig instance object get_F() { ldnull ret } .property object F() { .get instance object DefaultPropertyAndBaseProperty::get_F() } } // DefaultMember names assembly property in this class and public property in base .class public DefaultAssemblyPropertyAndBaseProperty extends PropertyNoDefault { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} .method assembly hidebysig instance object get_F() { ldnull ret } .property object F() { .get instance object DefaultAssemblyPropertyAndBaseProperty::get_F() } } // DefaultMember names no fields in this class while base has different DefaultMember .class public DifferentDefaultBaseProperty extends DefaultProperty { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('G')} } // DefaultMember names property in this class while base has different DefaultMember .class public DifferentDefaultPropertyAndBaseProperty extends DefaultProperty { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('G')} .method public hidebysig instance object get_G() { ldnull ret } .property object G() { .get instance object DifferentDefaultPropertyAndBaseProperty::get_G() } } ]]> Dim source = <compilation> <file name="a.vb"> Option Strict On Module M Sub M( x1 As DefaultBaseProperty, x2 As DefaultFieldAndBaseProperty, x3 As DefaultPropertyAndBaseProperty, x4 As DefaultAssemblyPropertyAndBaseProperty, x5 As DifferentDefaultBaseProperty, x6 As DifferentDefaultPropertyAndBaseProperty) Dim value As Object = Nothing value = x1.F(value) value = x1(value) value = x2() value = x3.F(value) value = x3(value) value = x3() value = x4.F(value) value = x4(value) value = x4() value = x5.F(value) value = x5(value) value = x6.F(value) value = x6(value) value = x6.G() value = x6() End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30367: Class 'DefaultBaseProperty' cannot be indexed because it has no default property. value = x1(value) ~~ BC30367: Class 'DefaultFieldAndBaseProperty' cannot be indexed because it has no default property. value = x2() ~~ BC30367: Class 'DefaultAssemblyPropertyAndBaseProperty' cannot be indexed because it has no default property. value = x4(value) ~~ BC30367: Class 'DefaultAssemblyPropertyAndBaseProperty' cannot be indexed because it has no default property. value = x4() ~~ BC30574: Option Strict On disallows late binding. value = x6(value) ~~ </expected>) End Sub <Fact()> Public Sub DefaultPropertiesFromMetadata2() Dim customIL = <![CDATA[ .class public auto ansi Class1 extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 54 65 73 74 00 00 ) // ...Test.. .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Class1::.ctor .method public specialname static int32 get_Test(int32 x) cil managed { // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Class1::get_Test .method public specialname static int32 get_Test(int32 x, int32 y) cil managed { // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.2 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Class1::get_Test .method public specialname instance int32 get_Test(int64 x, int32 y) cil managed { // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } // end of method Class1::get_Test .property int32 Test(int32) { .get int32 Class1::get_Test(int32) } // end of property Class1::Test .property int32 Test(int32, int32) { .get int32 Class1::get_Test(int32, int32) } // end of property Class1::Test .property instance int32 Test(int64, int32) { .get instance int32 Class1::get_Test(int64, int32) } // end of property Class1::Test } // end of class Class1 ]]> Dim source = <compilation> <file name="a.vb"> Module M Sub Main() Dim x As New Class1() System.Console.WriteLine(x(1, 2)) System.Console.WriteLine(x(2)) System.Console.WriteLine(x(3L, 2)) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(x(1, 2)) ~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(x(2)) ~ </expected>) CompileAndVerify(compilation, expectedOutput:= <![CDATA[ 2 1 3 ]]>) End Sub <Fact> Public Sub DefaultPropertiesDerivedTypes() Dim customIL = <![CDATA[ // Base class with default property .class public A { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} .method public hidebysig instance object get_F(object o) { ldnull ret } .property object F(object o) { .get instance object A::get_F(object o) } } // Derived class with property overload .class public B1 extends A { .method public hidebysig instance object get_F(object x, object y) { ldnull ret } .property object F(object x, object y) { .get instance object B1::get_F(object x, object y) } } // Derived class with different default property .class public B2 extends A { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('G')} .method public hidebysig instance object get_G(object x, object y) { ldnull ret } .property object G(object x, object y) { .get instance object B2::get_G(object x, object y) } } // Derived class with different internal default property .class public B3 extends A { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('G')} .method assembly hidebysig instance object get_G(object x, object y) { ldnull ret } .property object G(object x, object y) { .get instance object B3::get_G(object x, object y) } } ]]> Dim source = <compilation> <file name="a.vb"> Option Strict On Module M Sub M(b1 As B1, b2 As B2, b3 As B3) Dim value As Object value = b1(1) value = b1(2, 3) value = b2(1) value = b2(2, 3) value = b3(1) value = b3(2, 3) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30057: Too many arguments to 'Public Overloads ReadOnly Default Property F(o As Object) As Object'. value = b1(2, 3) ~ BC30455: Argument not specified for parameter 'y' of 'Public Overloads ReadOnly Default Property G(x As Object, y As Object) As Object'. value = b2(1) ~~ BC30057: Too many arguments to 'Public Overloads ReadOnly Default Property F(o As Object) As Object'. value = b3(2, 3) ~ </expected>) End Sub <WorkItem(529554, "DevDiv")> <Fact()> Public Sub DefaultPropertiesWithShadowingMethod() Dim customIL = <![CDATA[ // Base class with default property .class public A { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} .method public hidebysig instance object get_F(object o) { ldnull ret } .property object F(object o) { .get instance object A::get_F(object o) } } // Derived class with method with same name .class public B extends A { .method public hidebysig instance object F(int32 x, int32 y) { ldnull ret } } // Derived class with default property overload .class public C1 extends B { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} .method public hidebysig instance object get_F(object x, object y) { ldnull ret } .property object F(object x, object y) { .get instance object C1::get_F(object x, object y) } } // Derived class with internal default property overload .class public C2 extends B { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} .method assembly hidebysig instance object get_F(object x, object y) { ldnull ret } .property object F(object x, object y) { .get instance object C2::get_F(object x, object y) } } ]]> Dim source = <compilation> <file name="a.vb"> Option Strict On Module M Sub M(b As B, c1 As C1, c2 As C2) Dim value As Object value = b(1) value = b(2, 3) value = c1(1) value = c1(2, 3) value = c2(1) value = c2(2, 3) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30057: Too many arguments to 'Public Overloads ReadOnly Default Property F(o As Object) As Object'. value = b(2, 3) ~ BC30455: Argument not specified for parameter 'y' of 'Public Overloads ReadOnly Default Property F(x As Object, y As Object) As Object'. value = c1(1) ~~ BC30057: Too many arguments to 'Public Overloads ReadOnly Default Property F(o As Object) As Object'. value = c2(2, 3) ~ </expected>) End Sub <WorkItem(529553, "DevDiv")> <Fact()> Public Sub DefaultPropertiesInterfacesWithShadowingMethod() Dim customIL = <![CDATA[ // Base class with default property .class interface public IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} .method public hidebysig newslot abstract virtual instance object get_F(object o) { } .property object F(object o) { .get instance object IA::get_F(object o) } } // Derived class with method with same name .class interface public IB implements IA { .method public hidebysig newslot abstract virtual instance object F(int32 x, int32 y) { } } // Derived class with default property overload .class interface public IC implements IB { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')} .method public hidebysig newslot abstract virtual instance object get_F(object x, object y) { } .property object F(object x, object y) { .get instance object IC::get_F(object x, object y) } } ]]> Dim source = <compilation> <file name="a.vb"> Option Strict On Module M Sub M(b As IB, c As IC) Dim value As Object value = b(1) value = b(2, 3) value = c(1) value = c(2, 3) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30057: Too many arguments to 'ReadOnly Default Property F(o As Object) As Object'. value = b(2, 3) ~ </expected>) End Sub ''' <summary> ''' Should only generate DefaultMemberAttribute if not specified explicitly. ''' </summary> <Fact()> Public Sub DefaultMemberAttribute() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Imports System.Reflection ' No DefaultMemberAttribute. Interface IA Default ReadOnly Property P(o As Object) End Interface ' Expected DefaultMemberAttribute. <DefaultMember("P")> Interface IB Default ReadOnly Property P(o As Object) End Interface ' Different DefaultMemberAttribute. <DefaultMember("Q")> Interface IC Default ReadOnly Property P(o As Object) End Interface ' Nothing DefaultMemberAttribute value. <DefaultMember(Nothing)> Interface ID Default ReadOnly Property P(o As Object) End Interface ' Empty DefaultMemberAttribute value. <DefaultMember("")> Interface IE Default ReadOnly Property P(o As Object) End Interface ' Different case. <DefaultMember("p")> Interface [IF] Default ReadOnly Property P(o As Object) End Interface ' Different case. <DefaultMember("P")> Interface IG Default ReadOnly Property p(o As Object) End Interface ]]></file> </compilation>) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC32304: Conflict between the default property and the 'DefaultMemberAttribute' defined on 'IC'. Interface IC ~~ BC32304: Conflict between the default property and the 'DefaultMemberAttribute' defined on 'ID'. Interface ID ~~ BC32304: Conflict between the default property and the 'DefaultMemberAttribute' defined on 'IE'. Interface IE ~~ ]]></errors>) Dim globalNamespace = compilation.GlobalNamespace Dim type = globalNamespace.GetMember(Of NamedTypeSymbol)("IA") CheckDefaultMemberAttribute(compilation, type, "P", synthesized:=True) type = globalNamespace.GetMember(Of NamedTypeSymbol)("IB") CheckDefaultMemberAttribute(compilation, type, "P", synthesized:=False) type = globalNamespace.GetMember(Of NamedTypeSymbol)("IC") CheckDefaultMemberAttribute(compilation, type, "Q", synthesized:=False) type = globalNamespace.GetMember(Of NamedTypeSymbol)("ID") CheckDefaultMemberAttribute(compilation, type, Nothing, synthesized:=False) type = globalNamespace.GetMember(Of NamedTypeSymbol)("IE") CheckDefaultMemberAttribute(compilation, type, "", synthesized:=False) type = globalNamespace.GetMember(Of NamedTypeSymbol)("IF") CheckDefaultMemberAttribute(compilation, type, "p", synthesized:=False) type = globalNamespace.GetMember(Of NamedTypeSymbol)("IG") CheckDefaultMemberAttribute(compilation, type, "P", synthesized:=False) End Sub Private Sub CheckDefaultMemberAttribute(compilation As VisualBasicCompilation, type As NamedTypeSymbol, name As String, synthesized As Boolean) Dim attributes = type.GetAttributes() Dim synthesizedAttributes = type.GetSynthesizedAttributes() Dim attribute As VisualBasicAttributeData If synthesized Then Assert.Equal(attributes.Length, 0) Assert.Equal(synthesizedAttributes.Length, 1) attribute = synthesizedAttributes(0) Else Assert.Equal(attributes.Length, 1) Assert.Equal(synthesizedAttributes.Length, 0) attribute = attributes(0) End If Dim attributeType = attribute.AttributeConstructor.ContainingType Dim defaultMemberType = compilation.GetWellKnownType(WellKnownType.System_Reflection_DefaultMemberAttribute) Assert.Equal(attributeType, defaultMemberType) Assert.Equal(attribute.ConstructorArguments(0).Value, name) End Sub <Fact> Public Sub ParameterNames() Dim customIL = <![CDATA[ .class public C { // Property with getter and setter. .method public instance object get_P(object g1) { ldnull ret } .method public instance void set_P(object s1, object s2) { ret } .property object P(object p1) { .get instance object C::get_P(object p2) .set instance void C::set_P(object p3, object p4) } // Property with getter only. .method public instance object get_Q(object g1) { ldnull ret } .property object Q(object p1) { .get instance object C::get_Q(object p2) } // Property with setter only. .method public instance void set_R(object s1, object s2, object s3) { ret } .property object R(object p1, object p2) { .set instance void C::set_R(object p3, object p4, object p5) } // Bogus property: getter with too many parameters. .method public instance object get_S(object g1, object g2) { ldnull ret } .method public instance void set_S(object s1, object s2) { ret } .property object S(object p1) { .get instance object C::get_S(object p2, object p3) .set instance void C::set_S(object p4, object p5) } // Bogus property: setter with too many parameters. .method public instance void set_T(object s1, object s2, object s3) { ret } .property object T(object p1) { .set instance void C::set_T(object p2, object p3, object p4) } // Bogus property: getter and setter with too many parameters. .method public instance object get_U(object g1, object g2) { ldnull ret } .method public instance void set_U(object s1, object s2, object s3) { ret } .property object U(object p1) { .get instance object C::get_U(object p2, object P3) .set instance void C::set_U(object p4, object p5, object t6) } // Bogus property: getter with too few parameters. .method public instance object get_V() { ldnull ret } .method public instance void set_V(object s1, object s2) { ret } .property object V(object p1) { .get instance object C::get_V() .set instance void C::set_V(object p4, object p5) } // Bogus property: setter with too few parameters. .method public instance void set_W(object s1, object s2) { ret } .property object W(object p1, object p2) { .set instance void C::set_W(object p3, object p4) } // Bogus property: getter and setter with too few parameters. .method public instance object get_X(object g1) { ldnull ret } .method public instance void set_X(object s1, object s2) { ret } .property object X(object p1, object p2) { .get instance object C::get_X(object P3) .set instance void C::set_X(object p4, object p5) } } ]]> Dim source = <compilation> <file name="a.vb"> Module M Sub M(c As C) Dim value = c.P() c.P() = value value = c.Q() c.R() = value c.S() = value value = c.S(value) c.T() = value value = c.U() c.U() = value value = c.V() c.V() = value c.W() = value value = c.X() c.X() = value End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL) Dim type = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") CheckParameterNames(type.GetMember(Of PropertySymbol)("P"), "Param") CheckParameterNames(type.GetMember(Of PropertySymbol)("Q"), "g1") CheckParameterNames(type.GetMember(Of PropertySymbol)("R"), "s1", "s2") CheckParameterNames(type.GetMember(Of PropertySymbol)("S"), "Param") CheckParameterNames(type.GetMember(Of PropertySymbol)("T"), "s1") CheckParameterNames(type.GetMember(Of PropertySymbol)("U"), "Param") CheckParameterNames(type.GetMember(Of PropertySymbol)("V"), "s1") CheckParameterNames(type.GetMember(Of PropertySymbol)("W"), "s1", "s2") CheckParameterNames(type.GetMember(Of PropertySymbol)("X"), "Param", "s2") ' TODO: There are two issues (differences from Dev10) with the following: ' 1) We're currently using the property parameter name rather than the ' accessor parametername in "Argument not specified for parameter '...'". ' 2) Not all the bogus properties are supported. #If False Then CompilationUtils.AssertTheseErrors(compilation, <expected> BC30455: Argument not specified for parameter 'g1' of 'Public Property P(g1 As Object) As Object'. Dim value = c.P() ~~~~~ BC30455: Argument not specified for parameter 's1' of 'Public Property P(g1 As Object) As Object'. c.P() = value ~~~~~ BC30455: Argument not specified for parameter 'g1' of 'Public ReadOnly Property Q(g1 As Object) As Object'. value = c.Q() ~~~~~ BC30455: Argument not specified for parameter 's1' of 'Public WriteOnly Property R(s1 As Object) As Object'. c.R() = value ~~~~~ BC30455: Argument not specified for parameter 's1' of 'Public Property S(g1 As Object) As Object'. c.S() = value ~~~~~ BC30455: Argument not specified for parameter 'g2' of 'Public Property S(g1 As Object) As Object'. value = c.S(value) ~~~~~~~~~~ BC30455: Argument not specified for parameter 's1' of 'Public WriteOnly Property T(s1 As Object) As Object'. c.T() = value ~~~~~ BC30455: Argument not specified for parameter 's2' of 'Public WriteOnly Property T(s1 As Object) As Object'. c.T() = value ~~~~~ BC30455: Argument not specified for parameter 'g1' of 'Public Property U(g1 As Object) As Object'. value = c.U() ~~~~~ BC30455: Argument not specified for parameter 'g2' of 'Public Property U(g1 As Object) As Object'. value = c.U() ~~~~~ BC30455: Argument not specified for parameter 's1' of 'Public Property U(g1 As Object) As Object'. c.U() = value ~~~~~ BC30455: Argument not specified for parameter 's2' of 'Public Property U(g1 As Object) As Object'. c.U() = value ~~~~~ BC30455: Argument not specified for parameter 's1' of 'Public Property V(Param As Object) As Object'. c.V() = value ~~~~~ BC30455: Argument not specified for parameter 's1' of 'Public WriteOnly Property W(s1 As Object, s2 As Object) As Object'. c.W() = value ~~~~~ BC30455: Argument not specified for parameter 'g1' of 'Public Property X(g1 As Object, Param As Object) As Object'. value = c.X() ~~~~~ BC30455: Argument not specified for parameter 's1' of 'Public Property X(g1 As Object, Param As Object) As Object'. c.X() = value ~~~~~ </expected>) #End If End Sub Private Shared Sub CheckParameterNames([property] As PropertySymbol, ParamArray names() As String) Dim parameters = [property].Parameters Assert.Equal(parameters.Length, names.Length) For i = 0 To names.Length - 1 Assert.Equal(parameters(i).Name, names(i)) Next End Sub ' Should be possible to invoke a default property with no ' parameters, even though the property declaration is an error. <Fact> Public Sub DefaultParameterlessProperty() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> Class C Default ReadOnly Property P() Get Return Nothing End Get End Property Shared Sub M(ByVal x As C) N(x.P()) ' No error N(x()) ' No error End Sub Shared Sub N(ByVal o) End Sub End Class </file> </compilation>) Dim expectedErrors = <errors> BC31048: Properties with no required parameters cannot be declared 'Default'. Default ReadOnly Property P() ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub ''' <summary> ''' If the default property is parameterless (supported for ''' types from metadata), bind the argument list to the ''' default property of the return type instead. ''' </summary> <WorkItem(531372, "DevDiv")> <Fact()> Public Sub DefaultPropertyOfParameterlessDefaultPropertyReturnType01() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Imports System.Reflection Public Class A Default ReadOnly Property P(o As Object) As Object Get Return Nothing End Get End Property End Class <DefaultMember("Q")> Public Class B ReadOnly Property Q As A Get Return Nothing End Get End Property End Class ]]> </file> </compilation> Dim compilation1 = CreateCompilationWithMscorlib(source1) compilation1.AssertNoErrors() Dim source2 = <compilation> <file name="c.vb"><![CDATA[ Module M Sub M(o As B) Dim value As Object value = o()(Nothing) value = o(Nothing) End Sub End Module ]]> </file> </compilation> ' DefaultMember attribute from source should be ignored. Dim reference1a = New VisualBasicCompilationReference(compilation1) Dim compilation2a = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2, {reference1a}) compilation2a.AssertTheseDiagnostics( <expected> BC30367: Class 'B' cannot be indexed because it has no default property. value = o()(Nothing) ~ BC30367: Class 'B' cannot be indexed because it has no default property. value = o(Nothing) ~ </expected>) ' DefaultMember attribute from metadata should be used. Dim reference1b = MetadataReference.CreateFromImage(compilation1.EmitToArray()) Dim compilation2b = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2, {reference1b}) compilation2b.AssertNoErrors() End Sub ''' <summary> ''' WriteOnly default parameterless property. ''' </summary> <WorkItem(531372, "DevDiv")> <Fact()> Public Sub DefaultPropertyOfParameterlessDefaultPropertyReturnType02() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Imports System.Reflection Public Class A Default ReadOnly Property P(o As Object) As Object Get Return Nothing End Get End Property End Class <DefaultMember("Q")> Public Class B WriteOnly Property Q As A Set End Set End Property End Class ]]> </file> </compilation> Dim compilation1 = CreateCompilationWithMscorlib(source1) compilation1.AssertNoErrors() Dim source2 = <compilation> <file name="c.vb"><![CDATA[ Module M Sub M(o As B) Dim value As Object value = o()(Nothing) value = o(Nothing) End Sub End Module ]]> </file> </compilation> Dim reference1 = MetadataReference.CreateFromImage(compilation1.EmitToArray()) Dim compilation2 = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2, {reference1}) compilation2.AssertTheseDiagnostics( <expected> BC30524: Property 'Q' is 'WriteOnly'. value = o()(Nothing) ~~~ BC30524: Property 'Q' is 'WriteOnly'. value = o(Nothing) ~ </expected>) End Sub <WorkItem(531372, "DevDiv")> <Fact()> Public Sub DefaultPropertyOfParameterlessDefaultPropertyReturnType03() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Imports System.Reflection Public Class A End Class <DefaultMember("Q")> Public Class B ReadOnly Property Q As A Get Return Nothing End Get End Property End Class ]]> </file> </compilation> Dim compilation1 = CreateCompilationWithMscorlib(source1) compilation1.AssertNoErrors() Dim source2 = <compilation> <file name="c.vb"><![CDATA[ Module M Sub M(o As B) Dim value As Object value = o() value = o(Nothing) End Sub End Module ]]> </file> </compilation> Dim reference1 = MetadataReference.CreateFromImage(compilation1.EmitToArray()) Dim compilation2 = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2, {reference1}) compilation2.AssertTheseDiagnostics( <expected> BC32016: 'Public ReadOnly Default Property Q As A' has no parameters and its return type cannot be indexed. value = o(Nothing) ~ </expected>) End Sub <WorkItem(531372, "DevDiv")> <Fact()> Public Sub DefaultPropertyOfParameterlessDefaultPropertyReturnType04() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Imports System.Reflection Public Class A Default WriteOnly Property P(o As Object) As Object Set(value As Object) End Set End Property End Class ' Parameterless default member property. <DefaultMember("P1")> Public Class B1 ReadOnly Property P1 As A Get Return Nothing End Get End Property End Class ' Default member property with ParamArray. <DefaultMember("P2")> Public Class B2 ReadOnly Property P2(ParamArray args As Object()) As A Get Return Nothing End Get End Property End Class ' Default member property with Optional argument. <DefaultMember("P3")> Public Class B3 ReadOnly Property P3(Optional arg As Object = Nothing) As A Get Return Nothing End Get End Property End Class ' Parameterless default member property with overload. <DefaultMember("P4")> Public Class B4 Overloads ReadOnly Property P4 As A Get Return Nothing End Get End Property Overloads ReadOnly Property P4(arg As Object) As A Get Return Nothing End Get End Property End Class ' Parameterless default member function. <DefaultMember("F")> Public Class B5 Function F() As A Return Nothing End Function End Class ]]> </file> </compilation> Dim compilation1 = CreateCompilationWithMscorlib(source1) compilation1.AssertNoErrors() Dim reference1 = MetadataReference.CreateFromImage(compilation1.EmitToArray()) Dim source2 = <compilation> <file name="c.vb"><![CDATA[ Module M Sub M(_1 As B1, _2 As B2, _3 As B3, _4 As B4, _5 As B5) _1(Nothing) = Nothing _2(Nothing) = Nothing _3(Nothing) = Nothing _4(Nothing) = Nothing _5(Nothing) = Nothing End Sub End Module ]]> </file> </compilation> Dim compilation2 = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2, {reference1}) compilation2.AssertTheseDiagnostics( <expected> BC30526: Property 'P2' is 'ReadOnly'. _2(Nothing) = Nothing ~~~~~~~~~~~~~~~~~~~~~ BC30526: Property 'P3' is 'ReadOnly'. _3(Nothing) = Nothing ~~~~~~~~~~~~~~~~~~~~~ BC30526: Property 'P4' is 'ReadOnly'. _4(Nothing) = Nothing ~~~~~~~~~~~~~~~~~~~~~ BC30367: Class 'B5' cannot be indexed because it has no default property. _5(Nothing) = Nothing ~~ </expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Module M Sub M(_1 As B1, _2 As B2, _3 As B3, _4 As B4) Dim value As Object = Nothing _1(Nothing) = value value = _2(Nothing) value = _3(Nothing) value = _4(Nothing) End Sub End Module ]]> </file> </compilation> Dim compilation3 = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source3, {reference1}) compilation3.AssertNoErrors() Dim compilationVerifier = CompileAndVerify(compilation3) compilationVerifier.VerifyIL("M.M(B1, B2, B3, B4)", <![CDATA[ { // Code size 45 (0x2d) .maxstack 3 .locals init (Object V_0) //value IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: callvirt "Function B1.get_P1() As A" IL_0008: ldnull IL_0009: ldloc.0 IL_000a: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000f: callvirt "Sub A.set_P(Object, Object)" IL_0014: ldarg.1 IL_0015: ldnull IL_0016: callvirt "Function B2.get_P2(ParamArray Object()) As A" IL_001b: stloc.0 IL_001c: ldarg.2 IL_001d: ldnull IL_001e: callvirt "Function B3.get_P3(Object) As A" IL_0023: stloc.0 IL_0024: ldarg.3 IL_0025: ldnull IL_0026: callvirt "Function B4.get_P4(Object) As A" IL_002b: stloc.0 IL_002c: ret } ]]>) End Sub ''' <summary> ''' Default member from ElementAtOrDefault. ''' </summary> <WorkItem(531372, "DevDiv")> <Fact()> Public Sub DefaultPropertyOfParameterlessElementAtOrDefault01() Dim source = <compilation> <file name="c.vb"><![CDATA[ Delegate Function D(o As Object) As Object Class A Default ReadOnly Property P(o As Object) As Object Get Return Nothing End Get End Property End Class ' Default member returns type with default member. Class C1 Public Function [Select](f As System.Func(Of Object, Object)) As C1 Return Nothing End Function Public Function ElementAtOrDefault() As A Return Nothing End Function End Class ' Default member returns Array. Class C2 Public Function [Select](f As System.Func(Of Object, Object)) As C2 Return Nothing End Function Public Function ElementAtOrDefault() As Object() Return Nothing End Function End Class ' Default member returns Delegate. Class C3 Public Function [Select](f As System.Func(Of Object, Object)) As C3 Return Nothing End Function Public Function ElementAtOrDefault() As D Return Nothing End Function End Class Module M Sub M(_1 As C1, _2 As C2, _3 As C3) Dim value As Object value = _1()(Nothing) value = _1(Nothing) value = _1()() value = _2()(Nothing) value = _2(Nothing) value = _2()() value = _3()(Nothing) value = _3(Nothing) value = _3()() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) compilation.AssertTheseDiagnostics( <expected> BC30455: Argument not specified for parameter 'o' of 'Public ReadOnly Default Property P(o As Object) As Object'. value = _1()() ~~~~ BC30105: Number of indices is less than the number of dimensions of the indexed array. value = _2()() ~~ BC30455: Argument not specified for parameter 'o' of 'D'. value = _3()() ~~~~ </expected>) End Sub ''' <summary> ''' Default member from ElementAtOrDefault. ''' </summary> <WorkItem(531372, "DevDiv")> <Fact()> Public Sub DefaultPropertyOfParameterlessElementAtOrDefault02() Dim source = <compilation> <file name="c.vb"><![CDATA[ Class A Default ReadOnly Property P(o As Object) As Object Get Return Nothing End Get End Property End Class Class B Public Function [Select](f As System.Func(Of Object, Object)) As B Return Nothing End Function Public Function ElementAtOrDefault() As A Return Nothing End Function End Class Class C Public Function [Select](f As System.Func(Of Object, Object)) As C Return Nothing End Function Public Function ElementAtOrDefault() As B Return Nothing End Function End Class Class D Public Function [Select](f As System.Func(Of Object, Object)) As D Return Nothing End Function Public Function ElementAtOrDefault() As C Return Nothing End Function End Class Module M Sub M(o As D) Dim value As Object value = o()()()(Nothing) value = o()()(Nothing) value = o()(Nothing) value = o(Nothing) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) compilation.AssertTheseDiagnostics( <expected> BC30057: Too many arguments to 'Public Function ElementAtOrDefault() As A'. value = o()(Nothing) ~~~~~~~ BC30057: Too many arguments to 'Public Function ElementAtOrDefault() As B'. value = o(Nothing) ~~~~~~~ </expected>) End Sub ''' <summary> ''' ElementAtOrDefault returning System.Array. ''' </summary> <WorkItem(531372, "DevDiv")> <WorkItem(575547, "DevDiv")> <Fact()> Public Sub DefaultPropertyOfParameterlessElementAtOrDefault03() ' Option Strict On Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class C Public Function [Select](f As System.Func(Of Object, Object)) As C Return Nothing End Function Public Function ElementAtOrDefault() As System.Array Return Nothing End Function End Class Module M Sub M(o As C) Dim value As Object value = o()(1) value = o(2) o()(3) = value o(4) = value End Sub End Module ]]> </file> </compilation> Dim compilation1 = CreateCompilationWithMscorlibAndVBRuntime(source1) compilation1.AssertTheseDiagnostics( <expected> BC30574: Option Strict On disallows late binding. value = o()(1) ~~~ BC30574: Option Strict On disallows late binding. value = o(2) ~ BC30574: Option Strict On disallows late binding. o()(3) = value ~~~ BC30574: Option Strict On disallows late binding. o(4) = value ~ </expected>) ' Option Strict Off Dim source2 = <compilation> <file name="c.vb"><![CDATA[ Option Strict Off Class C Public Function [Select](f As System.Func(Of Object, Object)) As C Return Nothing End Function Public Function ElementAtOrDefault() As System.Array Return Nothing End Function End Class Module M Sub M(o As C) Dim value As Object value = o()(1) value = o(2) o()(3) = value o(4) = value End Sub End Module ]]> </file> </compilation> Dim compilation2 = CreateCompilationWithMscorlibAndVBRuntime(source2) compilation2.AssertNoErrors() End Sub ''' <summary> ''' ElementAtOrDefault property. (ElementAtOrDefault field ''' not supported - see #576814.) ''' </summary> <WorkItem(531372, "DevDiv")> <Fact()> Public Sub DefaultPropertyOfParameterlessElementAtOrDefault04() Dim source = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class A Public Function [Select](f As System.Func(Of Object, Object)) As A Return Nothing End Function Public ReadOnly Property ElementAtOrDefault As Integer() Get Return Nothing End Get End Property End Class Module M Sub M(_a As A) Dim value As Integer value = _a(1) _a(2) = value End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) compilation.AssertNoErrors() Dim compilationVerifier = CompileAndVerify(compilation) compilationVerifier.VerifyIL("M.M(A)", <![CDATA[ { // Code size 19 (0x13) .maxstack 3 .locals init (Integer V_0) //value IL_0000: ldarg.0 IL_0001: callvirt "Function A.get_ElementAtOrDefault() As Integer()" IL_0006: ldc.i4.1 IL_0007: ldelem.i4 IL_0008: stloc.0 IL_0009: ldarg.0 IL_000a: callvirt "Function A.get_ElementAtOrDefault() As Integer()" IL_000f: ldc.i4.2 IL_0010: ldloc.0 IL_0011: stelem.i4 IL_0012: ret } ]]>) End Sub ''' <summary> ''' Parentheses required for call to delegate. ''' </summary> <WorkItem(531372, "DevDiv")> <Fact()> Public Sub DefaultPropertyOfParameterlessDelegate() Dim source = <compilation> <file name="c.vb"><![CDATA[ Delegate Function D() As C Class C Default ReadOnly Property P(o As Object) As Object Get Return Nothing End Get End Property End Class Module M Sub M(o As D) Dim value As Object value = o()(Nothing) value = o(Nothing) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) compilation.AssertTheseDiagnostics( <expected> BC30057: Too many arguments to 'D'. value = o(Nothing) ~~~~~~~ </expected>) End Sub <WorkItem(578180, "DevDiv")> <Fact()> Public Sub DefaultPropertyOfInheritedConstrainedTypeParameter() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System.Reflection <DefaultMember("P")> Public Interface I ReadOnly Property P As Object End Interface <DefaultMember("P")> Public Class C Public ReadOnly Property P As Object Get Return Nothing End Get End Property End Class <DefaultMember("P")> Public Structure S Public ReadOnly Property P As Object Get Return Nothing End Get End Property End Structure <DefaultMember("M")> Public Enum E M End Enum Public Delegate Function D() As Object ]]> </file> </compilation> Dim compilation1 = CreateCompilationWithMscorlib(source1) compilation1.AssertNoErrors() Dim source2 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On MustInherit Class A(Of T) MustOverride Function F(Of U As T)(o As U) As Object End Class ' Interface with default parameterless property. Class B1 Inherits A(Of I) Public Overrides Function F(Of T As I)(o1 As T) As Object Return o1() End Function End Class ' Class with default parameterless property. Class B2 Inherits A(Of C) Public Overrides Function F(Of T As C)(o2 As T) As Object Return o2() End Function End Class ' Structure with default parameterless property. Class B3 Inherits A(Of S) Public Overrides Function F(Of T As S)(o3 As T) As Object Return o3() End Function End Class ' Enum with default member. Class B4 Inherits A(Of E) Public Overrides Function F(Of T As E)(o4 As T) As Object Return o4() End Function End Class ' Delegate. Class B5 Inherits A(Of D) Public Overrides Function F(Of T As D)(o5 As T) As Object Return o5() End Function End Class ' Array. Class B6 Inherits A(Of C()) Public Overrides Function F(Of T As C())(o6 As T) As Object Return o6() End Function End Class ' Type parameter. Class B7(Of T) Inherits A(Of T) Public Overrides Function F(Of U As T)(o7 As U) As Object Return o7() End Function End Class ]]> </file> </compilation> Dim reference1 = MetadataReference.CreateFromImage(compilation1.EmitToArray()) Dim compilation2 = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2, {reference1}) compilation2.AssertTheseDiagnostics( <expected> BC30547: 'T' cannot be indexed because it has no default property. Return o3() ~~ BC30547: 'T' cannot be indexed because it has no default property. Return o4() ~~ BC30547: 'T' cannot be indexed because it has no default property. Return o5() ~~ BC30547: 'T' cannot be indexed because it has no default property. Return o6() ~~ BC30547: 'U' cannot be indexed because it has no default property. Return o7() ~~ </expected>) End Sub <WorkItem(539951, "DevDiv")> <Fact> Public Sub ImportedParameterlessDefaultProperties() Dim customIL = <![CDATA[ .class public auto ansi beforefieldinit CSDefaultMembers extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 05 49 74 65 6D 73 00 00 ) // ...Items.. .field private int32 '<Items>k__BackingField' .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname instance int32 get_Items() cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 11 (0xb) .maxstack 1 .locals init (int32 V_0) IL_0000: ldarg.0 IL_0001: ldfld int32 CSDefaultMembers::'<Items>k__BackingField' IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } // end of method CSDefaultMembers::get_Items .method public hidebysig specialname instance void set_Items(int32 'value') cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld int32 CSDefaultMembers::'<Items>k__BackingField' IL_0007: ret } // end of method CSDefaultMembers::set_Items .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method CSDefaultMembers::.ctor .property instance int32 Items() { .get instance int32 CSDefaultMembers::get_Items() .set instance void CSDefaultMembers::set_Items(int32) } // end of property CSDefaultMembers::Items } // end of class CSDefaultMembers]]> Dim source = <compilation> <file name="a.vb"> Module Program Sub Main() Dim obj As CSDefaultMembers = New CSDefaultMembers() obj() = 9 Dim x = obj() System.Console.WriteLine(x) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, TestOptions.ReleaseExe, includeVbRuntime:=True) CompilationUtils.AssertNoErrors(compilation) CompileAndVerify(compilation, expectedOutput:="9") End Sub <WorkItem(539957, "DevDiv")> <Fact> Public Sub DefaultPropertyInFunctionReturn() Dim source = <compilation> <file name="a.vb"> Module Program Private Obj As VBDefaultMembers Sub Main() Obj = New VBDefaultMembers() Obj(1) = 4 System.Console.WriteLine(Foo(1)) Dim dd As DefaultDefaultMember = New DefaultDefaultMember dd.Item = Obj System.Console.WriteLine(dd.Item(1)) ' bind-position End Sub Function Foo() As VBDefaultMembers Return Obj End Function Function Bar() As Integer() Return Nothing End Function End Module Public Class DefaultDefaultMember Property Item As VBDefaultMembers End Class Public Class VBDefaultMembers 'Property Items As Integer Public _items As Integer() = New Integer(4) {} Default Public Property Items(index As Integer) As Integer Get Return _items(index) End Get Set(value As Integer) _items(index) = value End Set End Property End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) Dim position = (source...<file>.Single().Value.IndexOf("' bind-position", StringComparison.Ordinal)) Dim bindings = compilation.GetSemanticModel(CompilationUtils.GetTree(compilation, "a.vb")) Assert.Equal(SpecialType.System_Int32, bindings.GetSpeculativeSemanticInfoSummary(position, SyntaxFactory.ParseExpression("Foo().Items(1)"), SpeculativeBindingOption.BindAsExpression).Type.SpecialType) Assert.Equal(SpecialType.System_Int32, bindings.GetSpeculativeSemanticInfoSummary(position, SyntaxFactory.ParseExpression("Foo.Items(1)"), SpeculativeBindingOption.BindAsExpression).Type.SpecialType) Assert.Equal(SpecialType.System_Int32, bindings.GetSpeculativeSemanticInfoSummary(position, SyntaxFactory.ParseExpression("Foo()(1)"), SpeculativeBindingOption.BindAsExpression).Type.SpecialType) Assert.Equal(SpecialType.System_Int32, bindings.GetSpeculativeSemanticInfoSummary(position, SyntaxFactory.ParseExpression("Foo(1)"), SpeculativeBindingOption.BindAsExpression).Type.SpecialType) Assert.Equal(SpecialType.System_Int32, bindings.GetSpeculativeSemanticInfoSummary(position, SyntaxFactory.ParseExpression("dd.Item(1)"), SpeculativeBindingOption.BindAsExpression).Type.SpecialType) Assert.Equal(SpecialType.System_Int32, bindings.GetSpeculativeSemanticInfoSummary(position, SyntaxFactory.ParseExpression("Bar(1)"), SpeculativeBindingOption.BindAsExpression).Type.SpecialType) CompileAndVerify(compilation, expectedOutput:=<![CDATA[ 4 4 ]]>) End Sub <WorkItem(539957, "DevDiv")> <Fact> Public Sub EmptyArgumentListWithNoIndexerOrDefaultProperty() Dim source = <compilation> <file name="a.vb"> Class C2 Private Sub M() Dim x = A(6) Dim y = B(6) Dim z = C(6) Call A(6) Call B(6) Call C(6) End Sub Private Function A() As String Return "Hello" End Function Private Function B() As Integer() Return Nothing End Function Private Function C() As Integer Return Nothing End Function End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32016: 'Private Function C() As Integer' has no parameters and its return type cannot be indexed. Dim z = C(6) ~ BC30057: Too many arguments to 'Private Function A() As String'. Call A(6) ~ BC30057: Too many arguments to 'Private Function B() As Integer()'. Call B(6) ~ BC30057: Too many arguments to 'Private Function C() As Integer'. Call C(6) ~ </expected>) End Sub <WorkItem(539957, "DevDiv")> <Fact> Public Sub WrongArityWithFunctionsOfZeroParameters() Dim source = <compilation> <file name="a.vb"> Class C1 Public Function Foo() As Integer() Return Nothing End Function Public Sub TST() Dim a As Integer = Foo(Of Integer)(1) End Sub End Class Class C2 Public Function Foo(Of T)() As Integer() Return Nothing End Function Public Sub TST() Dim a As Integer = Foo(1) Call Foo(1) End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32045: 'Public Function Foo() As Integer()' has no type parameters and so cannot have type arguments. Dim a As Integer = Foo(Of Integer)(1) ~~~~~~~~~~~~ BC30057: Too many arguments to 'Public Function Foo(Of T)() As Integer()'. Dim a As Integer = Foo(1) ~ BC30057: Too many arguments to 'Public Function Foo(Of T)() As Integer()'. Call Foo(1) ~ </expected>) ' WARNING!!! Dev10 generates: ' ' BC32045: 'Public Function Foo() As Integer()' has no type parameters and so cannot have type arguments. ' BC32050: BC32050: Type parameter 'T' for 'Public Function Foo(Of T)() As Integer()' cannot be inferred. End Sub <WorkItem(539957, "DevDiv")> <Fact> Public Sub PropertyReturningDelegate() Dim source = <compilation> <file name="a.vb"> Imports System Class C Public ReadOnly Property Foo As Func(Of String, Integer) Get Return AddressOf Impl End Get End Property Private Function Impl(str As String) As Integer Return 0 End Function Public Sub TST() Dim a As Integer = Foo()("abc") Dim b As Integer = Foo("abc") Dim c = Foo() Dim d = Foo Call Foo()("abc") Call Foo("abc") Call Foo() Call Foo End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30057: Too many arguments to 'Public ReadOnly Property Foo As Func(Of String, Integer)'. Call Foo("abc") ~~~~~ BC30545: Property access must assign to the property or use its value. Call Foo() ~~~~~ BC30545: Property access must assign to the property or use its value. Call Foo ~~~ </expected>) End Sub <WorkItem(539957, "DevDiv")> <Fact> Public Sub FunctionWithZeroParametersReturingDelegate() Dim source = <compilation> <file name="a.vb"> Imports System Class C Public Function Foo() As Func(Of String, Integer) Return AddressOf Impl End Function Private Function Impl(str As String) As Integer Return 0 End Function Public Sub TST() Dim a As Integer = Foo()("abc") Dim b As Integer = Foo("abc") Dim c = Foo() Dim d = Foo() Foo()("abc") Foo("abc") Foo() Foo End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30057: Too many arguments to 'Public Function Foo() As Func(Of String, Integer)'. Foo("abc") ~~~~~ </expected>) End Sub <WorkItem(539957, "DevDiv")> <Fact> Public Sub EmptyArgumentListWithFunctionAndSub() Dim source = <compilation> <file name="a.vb"> Module Program Public Function Foo() As Integer() Dim arr As Integer() = New Integer(4) {} arr(2) = 234 Return arr End Function Public Sub Foo(i As Integer) System.Console.WriteLine(i) End Sub Public Sub Main() Dim a As Integer = Foo(2) Call Foo(a) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="234") End Sub <WorkItem(539957, "DevDiv")> <Fact> Public Sub FunctionsWithDifferentArity_0() Dim source = <compilation> <file name="a.vb"> Class CLS Public Overloads Function Foo(Of T)() As Integer() Return Nothing End Function Public Overloads Function Foo() As Integer() Return Nothing End Function Public Sub TST() Dim a As Integer = Foo(Of Integer)(1) Dim b As Integer = Foo(1) Call Foo(Of Integer)(1) Call Foo(1) End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30057: Too many arguments to 'Public Overloads Function Foo(Of Integer)() As Integer()'. Call Foo(Of Integer)(1) ~ BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. Call Foo(1) ~~~ </expected>) ' WARNING!!! Dev10 generates: ' ' BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. ' BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. ' BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. ' BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. End Sub <WorkItem(539957, "DevDiv")> <Fact> Public Sub FunctionsWithDifferentArity_1() Dim source = <compilation> <file name="a.vb"> Class CBase Public Function Foo(Of T)() As Integer() Return Nothing End Function End Class Class CDerived Inherits CBase Public Overloads Function Foo() As Integer() Return Nothing End Function Public Sub TST() Dim a As Integer = Foo(Of Integer)(1) Dim b As Integer = Foo(1) Call Foo(Of Integer)(1) Call Foo(1) End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30057: Too many arguments to 'Public Function Foo(Of Integer)() As Integer()'. Call Foo(Of Integer)(1) ~ BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. Call Foo(1) ~~~ </expected>) ' WARNING!!! Dev10 generates: ' ' BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. ' BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. ' BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. End Sub <WorkItem(539957, "DevDiv")> <Fact> Public Sub FunctionsWithDifferentArity_2() Dim source = <compilation> <file name="a.vb"> Class CBase Public Function Foo(Of T)() As Integer() Return Nothing End Function End Class Class CDerived Inherits CBase Public Overloads Function Foo(Of X, Y)() As Integer() Return Nothing End Function Public Sub TST() Dim a As Integer = Foo(Of Integer)(1) Dim b As Integer = Foo(1) Call Foo(Of Integer)(1) Call Foo(1) End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. Dim b As Integer = Foo(1) ~~~ BC30057: Too many arguments to 'Public Function Foo(Of Integer)() As Integer()'. Call Foo(Of Integer)(1) ~ BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. Call Foo(1) ~~~ </expected>) ' WARNING!!! Dev10 generates: ' ' BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. ' BC32050: Type parameter 'X' for 'Public Overloads Function Foo(Of X, Y)() As Integer()' cannot be inferred. ' BC32050: Type parameter 'Y' for 'Public Overloads Function Foo(Of X, Y)() As Integer()' cannot be inferred. ' BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. ' BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. End Sub <WorkItem(539957, "DevDiv")> <Fact> Public Sub PropertiesWithInheritanceAndParentheses() Dim source = <compilation> <file name="a.vb"> Interface IBase Property Foo As Integer() End Interface Class CBase Public Property Foo As Integer() End Class Class CDerived Inherits CBase Implements IBase Public Overloads Property Foo2 As Integer() Implements IBase.Foo Public Overloads Property Foo As Integer() Public Sub TST() Dim a As Integer = Foo()(1) Dim b As Integer = Foo(1) Dim c As Integer() = Foo() Dim d As Integer() = Foo Call Foo()(1) Call Foo(1) Call Foo() Call Foo End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30454: Expression is not a method. Call Foo()(1) ~~~~~ BC30516: Overload resolution failed because no accessible 'Foo' accepts this number of arguments. Call Foo(1) ~~~ BC30545: Property access must assign to the property or use its value. Call Foo() ~~~~~ BC30545: Property access must assign to the property or use its value. Call Foo ~~~ </expected>) ' WARNING!!! Dev10 generates: ' ' BC30454: Expression is not a method. ' BC30545: Property access must assign to the property or use its value. ' BC30545: Property access must assign to the property or use its value. ' BC30545: Property access must assign to the property or use its value. End Sub <WorkItem(539957, "DevDiv")> <Fact> Public Sub WriteOnlyPropertiesWithInheritanceAndParentheses() Dim source = <compilation> <file name="a.vb"> Interface IBase WriteOnly Property Foo As Integer() End Interface Class CBase Public WriteOnly Property Foo As Integer() Set(value As Integer()) End Set End Property End Class Class CDerived Inherits CBase Implements IBase Public WriteOnly Property Foo2 As Integer() Implements IBase.Foo Set(value As Integer()) End Set End Property Public Overloads WriteOnly Property Foo As Integer() Set(value As Integer()) End Set End Property Public Sub TST() Dim a As Integer = Foo()(1) Dim b As Integer = Foo(1) Dim c As Integer() = Foo() Dim d As Integer() = Foo End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30524: Property 'Foo' is 'WriteOnly'. Dim a As Integer = Foo()(1) ~~~~~ BC30524: Property 'Foo' is 'WriteOnly'. Dim b As Integer = Foo(1) ~~~ BC30524: Property 'Foo' is 'WriteOnly'. Dim c As Integer() = Foo() ~~~~~ BC30524: Property 'Foo' is 'WriteOnly'. Dim d As Integer() = Foo ~~~ </expected>) End Sub <WorkItem(539903, "DevDiv")> <Fact> Public Sub DefaultPropertyBangOperator() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Module Program Sub Main() Dim bang = New TestClassX() bang!Hello = "World" System.Console.WriteLine(bang!Hello) End Sub End Module Class TestClassX Public _items() As String = New String(100) {} Default Property Items(key As String) As String Get Return _items(key.Length) End Get Set(value As String) _items(key.Length) = value End Set End Property End Class ]]> </file> </compilation> CompileAndVerify(source, expectedOutput:="World") End Sub #End Region #Region "Typeless properties" <Fact> Public Sub TypelessAndImplicitlyTypeProperties() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class TestClass Property Typeless Property StringType$ Property IntegerType% Property LongType& Property DecimalType@ Property SingleType! Property DoubleType# End Class ]]> </file> </compilation> Dim validator = Sub([module] As ModuleSymbol) Dim testClassType = [module].GlobalNamespace.GetTypeMembers("TestClass").Single() Dim propertiesDictionary = testClassType.GetMembers().OfType(Of PropertySymbol).ToDictionary(Function(prop) prop.Name, Function(prop) prop) Assert.Equal(SpecialType.System_Object, propertiesDictionary!Typeless.Type.SpecialType) Assert.Equal(SpecialType.System_String, propertiesDictionary!StringType.Type.SpecialType) Assert.Equal(SpecialType.System_Int32, propertiesDictionary!IntegerType.Type.SpecialType) Assert.Equal(SpecialType.System_Int64, propertiesDictionary!LongType.Type.SpecialType) Assert.Equal(SpecialType.System_Decimal, propertiesDictionary!DecimalType.Type.SpecialType) Assert.Equal(SpecialType.System_Single, propertiesDictionary!SingleType.Type.SpecialType) Assert.Equal(SpecialType.System_Double, propertiesDictionary!DoubleType.Type.SpecialType) End Sub CompileAndVerify(source, sourceSymbolValidator:=validator, symbolValidator:=validator) End Sub #End Region #Region "Properties calls" Private ReadOnly _propertiesCallBaseSource As XElement = <compilation> <file name="a.vb"> Module Program Sub Main() Dim obj As TestClass1 = New TestClass1() obj.P1 = New TestClass2() obj.P2 = New TestClass2() obj.P1.id = 1 obj.P2.id = 2 <more_code/> End Sub Sub ByRefSwap(ByRef myObj1 As TestClass2, ByRef myObj2 As TestClass2) Dim tempObj As TestClass2 = myObj1 myObj1 = myObj2 myObj2 = tempObj End Sub Sub ByValSwap(myObj1 As TestClass2, myObj2 As TestClass2) Dim tempObj As TestClass2 = myObj1 myObj1 = myObj2 myObj2 = tempObj End Sub End Module Public Class TestClass2 Property id As Integer End Class Public Class TestClass1 Property P1 As TestClass2 Property P2 As TestClass2 End Class </file> </compilation> <Fact> Public Sub PassPropertyByValue() _propertiesCallBaseSource.Element("file").SetElementValue("more_code", <![CDATA[ ByValSwap(obj.P1, obj.P2) 'now o.P1.id = 1 and o.P2.id = 2 System.Console.WriteLine(String.Join(",", obj.P1.id, obj.P2.id))]]>.Value) CompileAndVerify(_propertiesCallBaseSource, expectedOutput:="1,2") End Sub <Fact> Public Sub PassPropertyByRef() _propertiesCallBaseSource.Element("file").SetElementValue("more_code", <![CDATA[ ByRefSwap(obj.P1, obj.P2) 'now o.P1.id = 2 and o.P2.id = 1 System.Console.WriteLine(String.Join(",", obj.P1.id, obj.P2.id))]]>.Value) CompileAndVerify(_propertiesCallBaseSource, expectedOutput:="2,1") End Sub <Fact> Public Sub PassPropertyByRefWithByValueOverride() _propertiesCallBaseSource.Element("file").SetElementValue("more_code", <![CDATA[ ByRefSwap((obj.P1), obj.P2) 'now o.P1.id = 1 and o.P2.id = 2 System.Console.WriteLine(String.Join(",", obj.P1.id, obj.P2.id))]]>.Value) CompileAndVerify(_propertiesCallBaseSource, expectedOutput:="1,1") End Sub #End Region #Region "Properties member access" <WorkItem(539962, "DevDiv")> <Fact> Public Sub PropertiesAccess() Dim source = <compilation> <file name="a.vb"> Public Class TestClass Public Property P1 As Integer Get Return 0 End Get Set End Set End Property Friend ReadOnly Property P2 As Integer Get Return 0 End Get End Property Protected Friend ReadOnly Property P3 As Integer Get Return 0 End Get End Property Protected ReadOnly Property P4 As Integer Get Return 0 End Get End Property Private WriteOnly Property P5 As Integer Set End Set End Property ReadOnly Property P6 As Integer Get Return 0 End Get End Property Public Property P7 As Integer Private Get Return 0 End Get Set End Set End Property Friend Property P8 As Integer Get Return 0 End Get Private Set End Set End Property Protected Property P9 As Integer Get Return 0 End Get Private Set End Set End Property Protected Friend Property P10 As Integer Protected Get Return 0 End Get Set End Set End Property Protected Friend Property P11 As Integer Friend Get Return 0 End Get Set End Set End Property End Class </file> </compilation> Dim validator = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) Dim type = [module].GlobalNamespace.GetTypeMembers("TestClass").Single() Dim members = type.GetMembers() ' Ensure member names are unique. Dim memberNames = members.[Select](Function(member) member.Name).Distinct().ToList() Assert.Equal(memberNames.Count, members.Length) 'Dim constructor = members.FirstOrDefault(Function(member) member.Name = ".ctor") 'Assert.NotNull(constructor) Dim p1 = type.GetMember(Of PropertySymbol)("P1") Dim p2 = type.GetMember(Of PropertySymbol)("P2") Dim p3 = type.GetMember(Of PropertySymbol)("P3") Dim p4 = type.GetMember(Of PropertySymbol)("P4") Dim p7 = type.GetMember(Of PropertySymbol)("P7") Dim p8 = type.GetMember(Of PropertySymbol)("P8") Dim p9 = type.GetMember(Of PropertySymbol)("P9") Dim p10 = type.GetMember(Of PropertySymbol)("P10") Dim p11 = type.GetMember(Of PropertySymbol)("P11") Dim privateOrNotApplicable = If(isFromSource, Accessibility.Private, Accessibility.NotApplicable) CheckPropertyAccessibility(p1, Accessibility.Public, Accessibility.Public, Accessibility.Public) CheckPropertyAccessibility(p2, Accessibility.Friend, Accessibility.Friend, Accessibility.NotApplicable) CheckPropertyAccessibility(p3, Accessibility.ProtectedOrFriend, Accessibility.ProtectedOrFriend, Accessibility.NotApplicable) CheckPropertyAccessibility(p4, Accessibility.Protected, Accessibility.Protected, Accessibility.NotApplicable) CheckPropertyAccessibility(p10, Accessibility.ProtectedOrFriend, Accessibility.Protected, Accessibility.ProtectedOrFriend) CheckPropertyAccessibility(p11, Accessibility.ProtectedOrFriend, Accessibility.Friend, Accessibility.ProtectedOrFriend) If isFromSource Then Dim p5 = type.GetMember(Of PropertySymbol)("P5") Dim p6 = type.GetMember(Of PropertySymbol)("P6") CheckPropertyAccessibility(p5, Accessibility.Private, Accessibility.NotApplicable, Accessibility.Private) CheckPropertyAccessibility(p6, Accessibility.Public, Accessibility.Public, Accessibility.NotApplicable) End If 'This checks a moved to last because they are affected by bug# CheckPropertyAccessibility(p7, Accessibility.Public, privateOrNotApplicable, Accessibility.Public) CheckPropertyAccessibility(p8, Accessibility.Friend, Accessibility.Friend, privateOrNotApplicable) CheckPropertyAccessibility(p9, Accessibility.Protected, Accessibility.Protected, privateOrNotApplicable) End Sub CompileAndVerify(source, symbolValidator:=validator(False), sourceSymbolValidator:=validator(True), options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) End Sub #End Region #Region "Ported C# test cases" #Region "Symbols" <Fact> Public Sub Simple1() Dim text = <compilation><file name="c.vb"><![CDATA[ Class A Private MustOverride Property P() As Integer End Class ]]></file></compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib(text) Dim [global] = comp.GlobalNamespace Dim a = [global].GetTypeMembers("A", 0).Single() Dim p = TryCast(a.GetMembers("P").AsEnumerable().SingleOrDefault(), PropertySymbol) End Sub <Fact> Public Sub EventEscapedIdentifier() Dim text = <compilation><file name="c.vb"><![CDATA[ Delegate Sub [out]() Class C1 Private Property [in] as out End Class ]]></file></compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib(text) Dim c1 As NamedTypeSymbol = DirectCast(comp.SourceModule.GlobalNamespace.GetMembers("C1").Single(), NamedTypeSymbol) Dim ein As PropertySymbol = DirectCast(c1.GetMembers("in").Single(), PropertySymbol) Assert.Equal("in", ein.Name) Assert.Equal("Private Property [in] As out", ein.ToString()) Dim dout As NamedTypeSymbol = DirectCast(ein.Type, NamedTypeSymbol) Assert.Equal("out", dout.Name) Assert.Equal("out", dout.ToString()) End Sub ''' <summary> ''' Properties should refer to methods ''' in the type members collection. ''' </summary> <Fact> Public Sub MethodsAndAccessorsSame() Dim sources = <compilation> <file name="c.vb"><![CDATA[ Class A Public Shared Property P Public Property Q Public Property R(arg) Get Return Nothing End Get Set(value) End Set End Property End Class Class B(Of T, U) Public Shared Property P Public Property Q Public Property R(arg As U) As T Get Return Nothing End Get Set(value As T) End Set End Property End Class Class C Inherits B(Of String, Integer) End Class ]]></file> </compilation> Dim validator = Sub([module] As ModuleSymbol) Dim type As NamedTypeSymbol Dim accessor As MethodSymbol Dim prop As PropertySymbol ' Non-generic type. type = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("A") Assert.Equal(type.TypeParameters.Length, 0) Assert.Same(type.ConstructedFrom, type) accessor = type.GetMember(Of MethodSymbol)("get_P") VerifyMethodAndAccessorSame(type, DirectCast(accessor.AssociatedSymbol, PropertySymbol), accessor) VerifyMethodsAndAccessorsSame(type, type.GetMember(Of PropertySymbol)("P")) VerifyMethodsAndAccessorsSame(type, type.GetMember(Of PropertySymbol)("Q")) prop = type.GetMember(Of PropertySymbol)("R") VerifyMethodsAndAccessorsSame(type, prop) ' Generic type. type = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("B") Assert.Equal(type.TypeParameters.Length, 2) Assert.Same(type.ConstructedFrom, type) accessor = type.GetMember(Of MethodSymbol)("get_P") VerifyMethodAndAccessorSame(type, DirectCast(accessor.AssociatedSymbol, PropertySymbol), accessor) VerifyMethodsAndAccessorsSame(type, type.GetMember(Of PropertySymbol)("P")) VerifyMethodsAndAccessorsSame(type, type.GetMember(Of PropertySymbol)("Q")) prop = type.GetMember(Of PropertySymbol)("R") VerifyMethodsAndAccessorsSame(type, prop) Assert.Equal(type.TypeArguments(0), prop.Type) Assert.Equal(type.TypeArguments(1), prop.Parameters(0).Type) ' Generic type with parameter substitution. type = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").BaseType Assert.Equal(type.TypeParameters.Length, 2) Assert.NotSame(type.ConstructedFrom, type) accessor = type.GetMember(Of MethodSymbol)("get_P") VerifyMethodAndAccessorSame(type, DirectCast(accessor.AssociatedSymbol, PropertySymbol), accessor) VerifyMethodsAndAccessorsSame(type, type.GetMember(Of PropertySymbol)("P")) VerifyMethodsAndAccessorsSame(type, type.GetMember(Of PropertySymbol)("Q")) prop = type.GetMember(Of PropertySymbol)("R") VerifyMethodsAndAccessorsSame(type, prop) Assert.Equal(type.TypeArguments(0), prop.Type) Assert.Equal(type.TypeArguments(1), prop.Parameters(0).Type) End Sub CompileAndVerify(sources, sourceSymbolValidator:=validator, symbolValidator:=validator) End Sub <Fact> Public Sub NoAccessors() Dim source = <compilation> <file name="a.vb"> Module Program Sub Main() End Sub Sub M(i As NoAccessors) i.Instance = NoAccessors.Static End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {TestReferences.SymbolsTests.Properties}, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30456: 'Instance' is not a member of 'NoAccessors'. i.Instance = NoAccessors.Static ~~~~~~~~~~ BC30456: 'Static' is not a member of 'NoAccessors'. i.Instance = NoAccessors.Static ~~~~~~~~~~~~~~~~~~ </expected>) Dim type = DirectCast(compilation.GlobalNamespace.GetMembers("NoAccessors").Single(), PENamedTypeSymbol) ' Methods are available. Assert.NotNull(type.GetMembers("StaticMethod").SingleOrDefault()) Assert.NotNull(type.GetMembers("InstanceMethod").SingleOrDefault()) Assert.Equal(2, type.GetMembers().OfType(Of MethodSymbol)().Count()) ' Properties are not available. Assert.Null(type.GetMembers("Static").SingleOrDefault()) Assert.Null(type.GetMembers("Instance").SingleOrDefault()) Assert.Equal(0, type.GetMembers().OfType(Of PropertySymbol)().Count()) End Sub <Fact> Public Sub FamilyAssembly() Dim source = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.Write(Signatures.StaticGet()) End Sub End Module </file> </compilation> Dim compilation = CompileWithCustomPropertiesAssembly(source, TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) Dim type = DirectCast(compilation.GlobalNamespace.GetMembers("FamilyAssembly").Single(), PENamedTypeSymbol) VerifyAccessibility( DirectCast(type.GetMembers("FamilyGetAssemblySetStatic").Single(), PEPropertySymbol), Accessibility.ProtectedOrFriend, Accessibility.[Protected], Accessibility.[Friend]) VerifyAccessibility( DirectCast(type.GetMembers("FamilyGetFamilyOrAssemblySetStatic").Single(), PEPropertySymbol), Accessibility.ProtectedOrFriend, Accessibility.[Protected], Accessibility.ProtectedOrFriend) VerifyAccessibility( DirectCast(type.GetMembers("FamilyGetFamilyAndAssemblySetStatic").Single(), PEPropertySymbol), Accessibility.[Protected], Accessibility.[Protected], Accessibility.ProtectedAndFriend) VerifyAccessibility( DirectCast(type.GetMembers("AssemblyGetFamilyOrAssemblySetStatic").Single(), PEPropertySymbol), Accessibility.ProtectedOrFriend, Accessibility.[Friend], Accessibility.ProtectedOrFriend) VerifyAccessibility( DirectCast(type.GetMembers("AssemblyGetFamilyAndAssemblySetStatic").Single(), PEPropertySymbol), Accessibility.[Friend], Accessibility.[Friend], Accessibility.ProtectedAndFriend) VerifyAccessibility( DirectCast(type.GetMembers("FamilyOrAssemblyGetFamilyOrAssemblySetStatic").Single(), PEPropertySymbol), Accessibility.ProtectedOrFriend, Accessibility.ProtectedOrFriend, Accessibility.ProtectedOrFriend) VerifyAccessibility( DirectCast(type.GetMembers("FamilyOrAssemblyGetFamilyAndAssemblySetStatic").Single(), PEPropertySymbol), Accessibility.ProtectedOrFriend, Accessibility.ProtectedOrFriend, Accessibility.ProtectedAndFriend) VerifyAccessibility( DirectCast(type.GetMembers("FamilyAndAssemblyGetFamilyAndAssemblySetStatic").Single(), PEPropertySymbol), Accessibility.ProtectedAndFriend, Accessibility.ProtectedAndFriend, Accessibility.ProtectedAndFriend) VerifyAccessibility( DirectCast(type.GetMembers("FamilyAndAssemblyGetOnlyInstance").Single(), PEPropertySymbol), Accessibility.ProtectedAndFriend, Accessibility.ProtectedAndFriend, Accessibility.NotApplicable) VerifyAccessibility( DirectCast(type.GetMembers("FamilyOrAssemblySetOnlyInstance").Single(), PEPropertySymbol), Accessibility.ProtectedOrFriend, Accessibility.NotApplicable, Accessibility.ProtectedOrFriend) VerifyAccessibility( DirectCast(type.GetMembers("FamilyAndAssemblyGetFamilyOrAssemblySetInstance").Single(), PEPropertySymbol), Accessibility.ProtectedOrFriend, Accessibility.ProtectedAndFriend, Accessibility.ProtectedOrFriend) End Sub <Fact> Public Sub PropertyAccessorDoesNotHideMethod() Dim vbSource = <compilation><file name="c.vb"> Interface IA Function get_Foo() As String End Interface Interface IB Inherits IA ReadOnly Property Foo() As Integer End Interface Class Program Private Shared Sub Main() Dim x As IB = Nothing Dim s As String = x.get_Foo().ToLower() End Sub End Class </file></compilation> CompileAndVerify(vbSource).VerifyDiagnostics( Diagnostic(ERRID.WRN_SynthMemberShadowsMember5, "Foo").WithArguments("property", "Foo", "get_Foo", "interface", "IA")) End Sub <Fact> Public Sub PropertyAccessorDoesNotConflictWithMethod() Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Interface IA Function get_Foo() As String End Interface Interface IB ReadOnly Property Foo() As Integer End Interface Interface IC Inherits IA Inherits IB End Interface Class Program Private Shared Sub Main() Dim x As IC = Nothing Dim s As String = x.get_Foo().ToLower() End Sub End Class ]]></file></compilation> CompileAndVerify(vbSource) End Sub <Fact> Public Sub PropertyAccessorCannotBeCalledAsMethod() Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Interface I ReadOnly Property Foo() As Integer End Interface Class Program Private Shared Sub Main() Dim x As I = Nothing Dim s As String = x.get_Foo() End Sub End Class ]]></file></compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(vbSource) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_NameNotMember2, "x.get_Foo").WithArguments("get_Foo", "I")) Assert.False(compilation.Emit(IO.Stream.Null).Success) End Sub <Fact> Public Sub CanReadInstancePropertyWithStaticGetterAsStatic() Dim ilSource = <![CDATA[ .class public A { .method public static int32 get_Foo() { ldnull throw } .property instance int32 Foo() { .get int32 A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Integer = A.Foo End Sub End Class ]]></file></compilation> CompileWithCustomILSource(vbSource, ilSource) End Sub <WorkItem(528038, "DevDiv")> <Fact()> Public Sub CanNotReadInstancePropertyWithStaticGetterAsInstance() Dim ilSource = <![CDATA[ .class public A { .method public static int32 get_Foo() { ldnull throw } .property instance int32 Foo() { .get int32 A::get_Foo() } } ]]> Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Integer = A.Foo End Sub End Class ]]></file></compilation> CompileWithCustomILSource(vbSource, ilSource) End Sub <WorkItem(527658, "DevDiv")> <Fact(Skip:="527658")> Public Sub PropertyWithPinnedModifierIsBogus() Dim ilSource = <![CDATA[ .class public A { .method public static int32 get_Foo() { ldnull throw } .property instance int32 pinned Foo() { .get int32 A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Object = A.Foo End Sub End Class ]]></file></compilation> CreateCompilationWithCustomILSource(vbSource, ilSource).VerifyDiagnostics() End Sub <WorkItem(538850, "DevDiv")> <Fact()> Public Sub PropertyWithMismatchedReturnTypeOfGetterIsBogus() Dim ilSource = <![CDATA[ .class public A { .method public static int32 get_Foo() { ldnull throw } .property string Foo() { .get int32 A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Object = A.Foo End Sub End Class ]]></file></compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource) compilation.AssertNoErrors() End Sub <WorkItem(527659, "DevDiv")> <Fact()> Public Sub PropertyWithCircularReturnTypeIsNotSupported() Dim ilSource = <![CDATA[ .class public E extends E { } .class public A { .method public static class E get_Foo() { ldnull throw } .property class E Foo() { .get class E A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Object = A.Foo End Sub End Class ]]></file></compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource).VerifyDiagnostics() ' Dev10 errors: ' error CS0268: Imported type 'E' is invalid. It contains a circular base class dependency. ' error CS0570: 'A.Foo' is not supported by the language End Sub <WorkItem(527664, "DevDiv")> <Fact(Skip:="527664")> Public Sub PropertyWithOpenGenericTypeAsTypeArgumentOfReturnTypeIsNotSupported() Dim ilSource = <![CDATA[ .class public E<T> { } .class public A { .method public static class E<class E> get_Foo() { ldnull throw } .property class E<class E> Foo() { .get class E<class E> A::get_Foo() } }]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Object = A.Foo End Sub End Class ]]></file></compilation> CreateCompilationWithCustomILSource(vbSource, ilSource).VerifyDiagnostics() End Sub <WorkItem(527657, "DevDiv")> <Fact(Skip:="527657")> Public Sub Dev10IgnoresSentinelInPropertySignature() Dim ilSource = <![CDATA[ .class public A { .method public static int32 get_Foo() { ldnull throw } .property int32 Foo(...) { .get int32 A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Integer = A.Foo End Sub End Class ]]></file></compilation> CompileWithCustomILSource(vbSource, ilSource) End Sub <Fact> Public Sub CanReadModOptProperty() Dim ilSource = <![CDATA[ .class public A { .method public static int32 modopt(int32) get_Foo() { ldnull throw } .property int32 modopt(int32) Foo() { .get int32 modopt(int32) A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Integer = A.Foo End Sub End Class ]]></file></compilation> CompileWithCustomILSource(vbSource, ilSource) End Sub <WorkItem(527660, "DevDiv")> <Fact(Skip:="527660")> Public Sub CanReadPropertyWithModOptInBaseClassOfReturnType() Dim ilSource = <![CDATA[ .class public E extends class [mscorlib]System.Collections.Generic.List`1<int32> modopt(int8) { } .class public A { .method public static class E get_Foo() { ldnull throw } .property class E Foo() { .get class E A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Object = A.Foo End Sub End Class ]]>.</file></compilation> CompileWithCustomILSource(vbSource, ilSource) End Sub <Fact> Public Sub CanReadPropertyOfArrayTypeWithModOptElement() Dim ilSource = <![CDATA[ .class public A { .method public static int32 modopt(int32)[] get_Foo() { ldnull throw } .property int32 modopt(int32)[] Foo() { .get int32 modopt(int32)[] A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Integer() = A.Foo End Sub End Class ]]></file></compilation> CompileWithCustomILSource(vbSource, ilSource) End Sub <Fact> Public Sub CanReadModOptPropertyWithNonModOptGetter() Dim ilSource = <![CDATA[ .class public A { .method public static int32 get_Foo() { ldnull throw } .property int32 modopt(int32) Foo() { .get int32 A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Integer = A.Foo End Sub End Class ]]></file></compilation> CompileWithCustomILSource(vbSource, ilSource) End Sub <WorkItem(527656, "DevDiv")> <Fact(Skip:="527656")> Public Sub CanReadNonModOptPropertyWithOpenGenericModOptGetter() Dim ilSource = <![CDATA[ .class public A { .method public static int32 modopt(class [mscorlib]System.IComparable`1) get_Foo() { ldnull throw } .property int32 Foo() { .get int32 modopt(class [mscorlib]System.IComparable`1) A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Integer = A.Foo End Sub End Class ]]></file></compilation> CompileWithCustomILSource(vbSource, ilSource) End Sub <Fact> Public Sub CanReadNonModOptPropertyWithModOptGetter() Dim ilSource = <![CDATA[ .class public A { .method public static int32 modopt(int32) get_Foo() { ldnull throw } .property int32 Foo() { .get int32 modopt(int32) A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Integer = A.Foo End Sub End Class ]]></file></compilation> CompileWithCustomILSource(vbSource, ilSource) End Sub <Fact> Public Sub CanReadModOptPropertyWithDifferentModOptGetter() Dim ilSource = <![CDATA[ .class public A { .method public static int32 modopt(int32) get_Foo() { ldnull throw } .property int32 modopt(string) Foo() { .get int32 modopt(int32) A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Integer = A.Foo End Sub End Class ]]></file></compilation> CompileWithCustomILSource(vbSource, ilSource) End Sub ''' <summary> ''' Nested modopt is invalid and results in a use-site error ''' in Roslyn. The native compiler ignores modopts completely. ''' </summary> <WorkItem(538845, "DevDiv")> <Fact> Public Sub CanReadPropertyWithMultipleAndNestedModOpts() Dim ilSource = <![CDATA[ .class public A { .method public static int32 modopt(int32) get_Foo() { ldnull throw } .property int32 modopt(int8) modopt(native int modopt(uint8)*[] modopt(void)) Foo() { .get int32 modopt(int32) A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Integer = A.Foo End Sub End Class ]]></file></compilation> CreateCompilationWithCustomILSource(vbSource, ilSource).AssertTheseDiagnostics( <expected> BC30643: Property 'Foo' is of an unsupported type. Dim x As Integer = A.Foo ~~~ </expected>) End Sub ''' <summary> ''' Nested modreq within modopt is invalid and results in a use-site error ''' in Roslyn. The native compiler ignores modopts completely. ''' </summary> <Fact()> Public Sub CanReadPropertyWithModReqsNestedWithinModOpts() Dim ilSource = <![CDATA[ .class public A { .method public static int32 modopt(int32) get_Foo() { ldnull throw } .property int32 modopt(class [mscorlib]System.IComparable`1<method void*()[]> modreq(bool)) Foo() { .get int32 modopt(int32) A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Integer = A.Foo End Sub End Class ]]></file></compilation> CreateCompilationWithCustomILSource(vbSource, ilSource).AssertTheseDiagnostics( <expected> BC30643: Property 'Foo' is of an unsupported type. Dim x As Integer = A.Foo ~~~ </expected>) End Sub <WorkItem(538846, "DevDiv")> <Fact> Public Sub CanNotReadPropertyWithModReq() Dim ilSource = <![CDATA[ .class public A { .method public static int32 get_Foo() { ldnull throw } .property int32 modreq(int8) Foo() { .get int32 A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Object = A.Foo x = A.get_Foo() End Sub End Class ]]></file></compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(vbSource, ilSource) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30643: Property 'Foo' is of an unsupported type. Dim x As Object = A.Foo ~~~ BC30456: 'get_Foo' is not a member of 'A'. x = A.get_Foo() ~~~~~~~~~ </expected>) End Sub <WorkItem(527662, "DevDiv")> <Fact(Skip:="527662")> Public Sub CanNotReadPropertyWithModReqInBaseClassOfReturnType() Dim ilSource = <![CDATA[ .class public E extends class [mscorlib]System.Collections.Generic.List`1<int32 modreq(int8)[]> { } .class public A { .method public static class E get_Foo() { ldnull throw } .property class E Foo() { .get class E A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Private Shared Sub Main() Dim x As Object = A.Foo End Sub End Class ]]></file></compilation> CompileWithCustomILSource(vbSource, ilSource) End Sub <Fact> Public Sub VoidReturningPropertyHidesMembersFromBase() Dim ilSource = <![CDATA[ .class public B { .method public static int32 get_Foo() { ldnull throw } .property int32 Foo() { .get int32 B::get_Foo() } } .class public A extends B { .method public static void get_Foo() { ldnull throw } .property void Foo() { .get void A::get_Foo() } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class B Shared Sub Main() Dim x As Object = A.Foo End Sub End Class ]]></file></compilation> CreateCompilationWithCustomILSource(vbSource, ilSource).VerifyDiagnostics( Diagnostic(ERRID.ERR_VoidValue, "A.Foo")) End Sub <WorkItem(527663, "DevDiv")> <Fact> Public Sub CanNotReadPropertyFromAmbiguousGenericClass() Dim ilSource = <![CDATA[ .class public A`1<T> { .method public static int32 get_Foo() { ldnull throw } .property int32 Foo() { .get int32 A`1::get_Foo() } } .class public A<T> { .method public static int32 get_Foo() { ldnull throw } .property int32 Foo() { .get int32 A::get_Foo() } } ]]> Dim source = <compilation><file name="c.vb"><![CDATA[ Class B Shared Sub Main() Dim x As Object = A(Of Integer).Foo End Sub End Class ]]></file></compilation> CreateCompilationWithCustomILSource(source, ilSource). VerifyDiagnostics(Diagnostic(ERRID.ERR_AmbiguousInUnnamedNamespace1, "A(Of Integer)").WithArguments("A")) End Sub <Fact> Public Sub PropertyWithoutAccessorsIsBogus() Dim ilSource = <![CDATA[ .class public B { .method public instance void .ctor() { ldarg.0 call instance void class System.Object::.ctor() ret } .property int32 Foo() { } } ]]>.Value Dim vbSource = <compilation><file name="c.vb"><![CDATA[ Class C Private Shared Sub Main() Dim foo As Object = B.Foo End Sub End Class ]]></file></compilation> CreateCompilationWithCustomILSource(vbSource, ilSource).VerifyDiagnostics( Diagnostic(ERRID.ERR_NameNotMember2, "B.Foo").WithArguments("Foo", "B")) End Sub <WorkItem(538946, "DevDiv")> <Fact> Public Sub FalseAmbiguity() Dim text = <compilation><file name="c.vb"><![CDATA[ Interface IA ReadOnly Property Foo() As Integer End Interface Interface IB(Of T) Inherits IA End Interface Interface IC Inherits IB(Of Integer) Inherits IB(Of String) End Interface Class C Private Shared Sub Main() Dim x As IC = Nothing Dim y As Integer = x.Foo End Sub End Class ]]></file></compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib(text) Dim diagnostics = comp.GetDiagnostics() Assert.Empty(diagnostics) End Sub <WorkItem(539320, "DevDiv")> <Fact> Public Sub FalseWarningCS0109ForNewModifier() Dim text = <compilation><file name="c.vb"><![CDATA[ Class [MyBase] Public ReadOnly Property MyProp() As Integer Get Return 1 End Get End Property End Class Class [MyClass] Inherits [MyBase] Private intI As Integer = 0 Private Shadows Property MyProp() As Integer Get Return intI End Get Set intI = value End Set End Property End Class ]]></file></compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib(text) Dim diagnostics = comp.GetDiagnostics() Assert.Empty(diagnostics) End Sub <Fact> Public Sub FalseErrorCS0103ForValueKeywordInExpImpl() Dim text = <compilation><file name="c.vb"><![CDATA[ Interface MyInter Property MyProp() As Integer End Interface Class TestClass Implements MyInter Shared intI As Integer = 0 Private Property MyInter_MyProp() As Integer Implements MyInter.MyProp Get Return intI End Get Set intI = value End Set End Property End Class ]]></file></compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib(text) Dim diagnostics = comp.GetDiagnostics() Assert.Empty(diagnostics) End Sub <Fact> Public Sub ExplicitInterfaceImplementationSimple() Dim text = <compilation><file name="c.vb"><![CDATA[ Interface I Property P() As Integer End Interface Class C Implements I Private Property I_P() As Integer Implements I.P Get Return m_I_P End Get Set m_I_P = Value End Set End Property Private m_I_P As Integer End Class ]]></file></compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib(text) CompilationUtils.AssertNoErrors(comp) Dim globalNamespace = comp.GlobalNamespace Dim [interface] = DirectCast(globalNamespace.GetTypeMembers("I").Single(), NamedTypeSymbol) Assert.Equal(TypeKind.[Interface], [interface].TypeKind) Dim interfaceProperty = DirectCast([interface].GetMembers("P").Single(), PropertySymbol) Dim [class] = DirectCast(globalNamespace.GetTypeMembers("C").Single(), NamedTypeSymbol) Assert.Equal(TypeKind.[Class], [class].TypeKind) Assert.True([class].Interfaces.Contains([interface])) Dim classProperty = DirectCast([class].GetMembers("I_P").Single(), PropertySymbol) CheckPropertyExplicitImplementation([class], classProperty, interfaceProperty) End Sub <Fact> Public Sub ExplicitInterfaceImplementationGeneric() Dim text = <compilation><file name="c.vb"><![CDATA[ Namespace N Interface I(Of T) Property P() As T End Interface End Namespace Class C Implements N.I(Of Integer) Private Property N_I_P() As Integer Implements N.I(Of Integer).P Get Return m_N_I_P End Get Set m_N_I_P = Value End Set End Property Private m_N_I_P As Integer End Class ]]></file></compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib(text) CompilationUtils.AssertNoErrors(comp) Dim globalNamespace = comp.GlobalNamespace Dim [namespace] = DirectCast(globalNamespace.GetMembers("N").Single(), NamespaceSymbol) Dim [interface] = DirectCast([namespace].GetTypeMembers("I").Single(), NamedTypeSymbol) Assert.Equal(TypeKind.[Interface], [interface].TypeKind) Dim interfaceProperty = DirectCast([interface].GetMembers("P").Single(), PropertySymbol) Dim [class] = DirectCast(globalNamespace.GetTypeMembers("C").Single(), NamedTypeSymbol) Assert.Equal(TypeKind.[Class], [class].TypeKind) Dim classProperty = DirectCast([class].GetMembers("N_I_P").Single(), PropertySymbol) Dim substitutedInterface = [class].Interfaces.Single() Assert.Equal([interface], substitutedInterface.ConstructedFrom) Dim substitutedInterfaceProperty = DirectCast(substitutedInterface.GetMembers("P").Single(), PropertySymbol) CheckPropertyExplicitImplementation([class], classProperty, substitutedInterfaceProperty) End Sub #End Region #Region "Emit""" <Fact> Public Sub PropertyNonDefaultAccessorNames() Dim source = <compilation><file name="c.vb"><![CDATA[ Class Program Private Shared Sub M(i As Valid) i.Instance = 0 System.Console.Write("{0}", i.Instance) End Sub Shared Sub Main() Valid.[Static] = 0 System.Console.Write("{0}", Valid.[Static]) End Sub End Class ]]></file></compilation> Dim compilation = CompileAndVerify(source, additionalRefs:={s_propertiesDll}, expectedOutput:="0") Dim ilSource = <![CDATA[{ // Code size 27 (0x1b) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: call "Sub Valid.StaticSet(Integer)" IL_0006: ldstr "{0}" IL_000b: call "Function Valid.StaticGet() As Integer" IL_0010: box "Integer" IL_0015: call "Sub System.Console.Write(String, Object)" IL_001a: ret } ]]> compilation.VerifyIL("Program.Main", ilSource) End Sub <WorkItem(528542, "DevDiv")> <Fact()> Public Sub MismatchedAccessorTypes() Dim source = <code><file name="c.vb"><![CDATA[ Class Program Private Shared Sub M(i As Mismatched) i.Instance = 0 System.Console.Write("{0}", i.Instance) End Sub Private Shared Sub N(i As Signatures) i.StaticAndInstance = 0 i.GetUsedAsSet = 0 End Sub Private Shared Sub Main() Mismatched.[Static] = 0 System.Console.Write("{0}", Mismatched.[Static]) End Sub End Class ]]></file></code> CompilationUtils.CreateCompilationWithMscorlibAndReferences(source, {s_propertiesDll}).VerifyDiagnostics( Diagnostic(ERRID.ERR_NameNotMember2, "i.Instance").WithArguments("Instance", "Mismatched"), Diagnostic(ERRID.ERR_NameNotMember2, "i.Instance").WithArguments("Instance", "Mismatched"), Diagnostic(ERRID.ERR_UnsupportedProperty1, "StaticAndInstance").WithArguments("Signatures.StaticAndInstance"), Diagnostic(ERRID.ERR_UnsupportedProperty1, "GetUsedAsSet").WithArguments("Signatures.GetUsedAsSet"), Diagnostic(ERRID.ERR_NameNotMember2, "Mismatched.[Static]").WithArguments("Static", "Mismatched"), Diagnostic(ERRID.ERR_NameNotMember2, "Mismatched.[Static]").WithArguments("Static", "Mismatched")) End Sub ''' <summary> ''' Calling bogus methods directly should not be allowed. ''' </summary> <Fact> Public Sub CallMethodsDirectly() Dim source = <compilation><file name="c.vb"><![CDATA[ Class Program Private Shared Sub M(i As Mismatched) i.InstanceBoolSet(False) System.Console.Write("{0}", i.InstanceInt32Get()) End Sub Private Shared Sub Main() Mismatched.StaticBoolSet(False) System.Console.Write("{0}", Mismatched.StaticInt32Get()) End Sub End Class ]]></file></compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndReferences(source, {s_propertiesDll}) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30456: 'InstanceBoolSet' is not a member of 'Mismatched'. i.InstanceBoolSet(False) ~~~~~~~~~~~~~~~~~ BC30456: 'InstanceInt32Get' is not a member of 'Mismatched'. System.Console.Write("{0}", i.InstanceInt32Get()) ~~~~~~~~~~~~~~~~~~ BC30456: 'StaticBoolSet' is not a member of 'Mismatched'. Mismatched.StaticBoolSet(False) ~~~~~~~~~~~~~~~~~~~~~~~~ BC30456: 'StaticInt32Get' is not a member of 'Mismatched'. System.Console.Write("{0}", Mismatched.StaticInt32Get()) ~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub MethodsReferencedInMultipleProperties() Dim source = <compilation><file name="c.vb"><![CDATA[ Class Program Private Shared Sub M(i As Signatures) i.GoodInstance = 0 System.Console.Write("{0}", i.GoodInstance) End Sub Public Shared Sub Main() Signatures.GoodStatic = 0 System.Console.Write("{0}", Signatures.GoodStatic) End Sub End Class ]]></file></compilation> Dim result = CompileAndVerify(source, additionalRefs:={s_propertiesDll}, expectedOutput:="0") Dim ilSource = <![CDATA[{ // Code size 27 (0x1b) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: call "Sub Signatures.StaticSet(Integer)" IL_0006: ldstr "{0}" IL_000b: call "Function Signatures.StaticGet() As Integer" IL_0010: box "Integer" IL_0015: call "Sub System.Console.Write(String, Object)" IL_001a: ret } ]]> result.VerifyIL("Program.Main", ilSource) Dim compilation = CompileWithCustomPropertiesAssembly(source) Dim type = DirectCast(compilation.GlobalNamespace.GetMembers("Signatures").Single(), PENamedTypeSymbol) ' Valid static property, property with signature that does not match accessors, ' and property with accessors that do not match each other. Dim goodStatic = DirectCast(type.GetMembers("GoodStatic").Single(), PEPropertySymbol) Dim badStatic = DirectCast(type.GetMembers("BadStatic").Single(), PEPropertySymbol) Dim mismatchedStatic = DirectCast(type.GetMembers("MismatchedStatic").Single(), PEPropertySymbol) Assert.Null(goodStatic.GetUseSiteErrorInfo()) Assert.Null(badStatic.GetUseSiteErrorInfo()) ' Mismatch based on property type is supported Assert.Null(mismatchedStatic.GetUseSiteErrorInfo()) ' Mismatch based on property type is supported VerifyAccessor(goodStatic.GetMethod, goodStatic, MethodKind.PropertyGet) VerifyAccessor(goodStatic.SetMethod, goodStatic, MethodKind.PropertySet) VerifyAccessor(badStatic.GetMethod, goodStatic, MethodKind.PropertyGet) VerifyAccessor(badStatic.SetMethod, goodStatic, MethodKind.PropertySet) VerifyAccessor(mismatchedStatic.GetMethod, goodStatic, MethodKind.PropertyGet) VerifyAccessor(mismatchedStatic.SetMethod, mismatchedStatic, MethodKind.PropertySet) ' Valid instance property, property with signature that does not match accessors, ' and property with accessors that do not match each other. Dim goodInstance = DirectCast(type.GetMembers("GoodInstance").Single(), PEPropertySymbol) Dim badInstance = DirectCast(type.GetMembers("BadInstance").Single(), PEPropertySymbol) Dim mismatchedInstance = DirectCast(type.GetMembers("MismatchedInstance").Single(), PEPropertySymbol) Assert.Null(goodInstance.GetUseSiteErrorInfo()) Assert.Null(badInstance.GetUseSiteErrorInfo()) ' Mismatch based on property type is supported Assert.Null(mismatchedInstance.GetUseSiteErrorInfo()) ' Mismatch based on property type is supported VerifyAccessor(goodInstance.GetMethod, goodInstance, MethodKind.PropertyGet) VerifyAccessor(goodInstance.SetMethod, goodInstance, MethodKind.PropertySet) VerifyAccessor(badInstance.GetMethod, goodInstance, MethodKind.PropertyGet) VerifyAccessor(badInstance.SetMethod, goodInstance, MethodKind.PropertySet) VerifyAccessor(mismatchedInstance.GetMethod, goodInstance, MethodKind.PropertyGet) VerifyAccessor(mismatchedInstance.SetMethod, mismatchedInstance, MethodKind.PropertySet) ' Mix of static and instance accessors. Dim staticAndInstance = DirectCast(type.GetMembers("StaticAndInstance").Single(), PEPropertySymbol) VerifyAccessor(staticAndInstance.GetMethod, goodStatic, MethodKind.PropertyGet) VerifyAccessor(staticAndInstance.SetMethod, goodInstance, MethodKind.PropertySet) Assert.Equal(ERRID.ERR_UnsupportedProperty1, staticAndInstance.GetUseSiteErrorInfo().Code) ' Property with get and set accessors both referring to the same get method. Dim getUsedAsSet = DirectCast(type.GetMembers("GetUsedAsSet").Single(), PEPropertySymbol) VerifyAccessor(getUsedAsSet.GetMethod, goodInstance, MethodKind.PropertyGet) VerifyAccessor(getUsedAsSet.SetMethod, goodInstance, MethodKind.PropertyGet) Assert.Equal(ERRID.ERR_UnsupportedProperty1, getUsedAsSet.GetUseSiteErrorInfo().Code) End Sub #End Region #End Region <WorkItem(540343, "DevDiv")> <Fact> Public Sub PropertiesWithCircularTypeReferences() CompileAndVerify( <compilation> <file name="Cobj010mod.vb"> Module Cobj010mod Class Class1 Public Property c2 As Class2 End Class Class Class2 Public Property c3 As Class3 End Class Class Class3 Public Property c4 As Class4 End Class Class Class4 Public Property c5 As Class5 End Class Class Class5 Public Property c6 As Class6 End Class Class Class6 Public Property c7 As Class7 End Class Class Class7 Public Property c8 As Class8 End Class Class Class8 Public Property c1 As Class1 End Class Sub Main() Dim c1 As New Class1() if c1 is nothing c1.c2.c3.c4.c5.c6.c7.c8.c1.c2.c3.c4.c5.c6.c7.c8.c1.c2.c3.c4.c5.c6.c7.c8.c1.c2.c3.c4.c5.c6.c7.c8 = New Class8() end if End Sub End Module </file> </compilation>, expectedOutput:="") End Sub <WorkItem(540342, "DevDiv")> <Fact> Public Sub NoSequencePointsForAutoPropertyAccessors() Dim source = <compilation> <file name="c.vb"> Class C Property P End Class </file> </compilation> CompileAndVerify(source, options:=TestOptions.ReleaseDll).VerifyDiagnostics() End Sub <Fact> Public Sub MultipleOverloadsMetadataName1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="b.vb"> Class Base Public ReadOnly Property BANANa(x as string, y as integer) as integer Get return 1 End Get End Property End Class Partial Class Class1 Inherits Base Public ReadOnly Property baNana() Get return 1 End Get End Property Public ReadOnly Property Banana(x as integer) Get return 1 End Get End Property End Class </file> <file name="a.vb"> Partial Class Class1 Public ReadOnly Property baNANa(xyz as String) Get return 1 End Get End Property Public ReadOnly Property BANANA(x as Long) Get return 1 End Get End Property End Class </file> </compilation>) ' No "Overloads", so all properties should match first overloads in first source file Dim class1 = compilation.GetTypeByMetadataName("Class1") Dim allProperties = class1.GetMembers("baNana").OfType(Of PropertySymbol)() ' All properties in Class1 should have metadata name "baNana" (first spelling, by source position). Dim count = 0 For Each m In allProperties count = count + 1 Assert.Equal("baNana", m.MetadataName) If m.Parameters.Any Then Assert.NotEqual("baNana", m.Name) End If Next Assert.Equal(4, count) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact> Public Sub MultipleOverloadsMetadataName2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="b.vb"> Class Base Public ReadOnly Property BANANa(x as string, y as integer) Get return 1 End Get End Property End Class Partial Class Class1 Inherits Base Overloads Public ReadOnly Property baNana() Get return 1 End Get End Property Overloads Public ReadOnly Property Banana(x as integer) Get return 1 End Get End Property End Class </file> <file name="a.vb"> Partial Class Class1 Overloads Public ReadOnly Property baNANa(xyz as String) Get return 1 End Get End Property Overloads Public ReadOnly Property BANANA(x as Long) Get return 1 End Get End Property End Class </file> </compilation>) ' "Overloads" specified, so all properties should match method in base Dim class1 = compilation.GetTypeByMetadataName("Class1") Dim allProperties = class1.GetMembers("baNANa").OfType(Of PropertySymbol)() ' All properties in Class1 should have metadata name "baNANa". Dim count = 0 For Each m In allProperties count = count + 1 Assert.Equal("BANANa", m.MetadataName) Next Assert.Equal(4, count) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact> Public Sub MultipleOverloadsMetadataName3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="b.vb"> Class Base Overridable Public ReadOnly Property BANANa(x as string, y as integer) Get return 1 End Get End Property End Class Partial Class Class1 Inherits Base Overloads Public ReadOnly Property baNana() Get return 1 End Get End Property Overrides Public ReadOnly Property baNANa(xyz as String, a as integer) Get return 1 End Get End Property Overloads Public ReadOnly Property Banana(x as integer) Get return 1 End Get End Property End Class </file> <file name="a.vb"> Partial Class Class1 Overloads Public ReadOnly Property BANANA(x as Long) Get return 1 End Get End Property End Class </file> </compilation>) ' "Overrides" specified, so all properties should match property in base Dim class1 = compilation.GetTypeByMetadataName("Class1") Dim allProperties = class1.GetMembers("baNANa").OfType(Of PropertySymbol)() ' All properties in Class1 should have metadata name "BANANa". Dim count = 0 For Each m In allProperties count = count + 1 Assert.Equal("BANANa", m.MetadataName) Next Assert.Equal(4, count) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact> Public Sub MultipleOverloadsMetadataName4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="b.vb"> Interface Base1 ReadOnly Property BANANa(x as string, y as integer) End Interface Interface Base2 ReadOnly Property BANANa(x as string, y as integer, z as Object) End Interface Interface Base3 Inherits Base2 End Interface Interface Interface1 Inherits Base1, Base3 Overloads ReadOnly Property baNana() Overloads ReadOnly Property baNANa(xyz as String, a as integer) Overloads ReadOnly Property Banana(x as integer) End Interface </file> </compilation>) ' "Overloads" specified, so all properties should match properties in base Dim interface1 = compilation.GetTypeByMetadataName("Interface1") Dim allProperties = interface1.GetMembers("baNANa").OfType(Of PropertySymbol)() CompilationUtils.AssertNoErrors(compilation) ' All methods in Interface1 should have metadata name "BANANa". Dim count = 0 For Each m In allProperties count = count + 1 Assert.Equal("BANANa", m.MetadataName) Next Assert.Equal(3, count) End Sub <Fact> Public Sub MultipleOverloadsMetadataName5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="b.vb"> Interface Base1 ReadOnly Property BAnANa(x as string, y as integer) End Interface Interface Base2 ReadOnly Property BANANa(x as string, y as integer, z as Object) End Interface Interface Base3 Inherits Base2 End Interface Interface Interface1 Inherits Base1, Base3 Overloads ReadOnly Property baNana() Overloads ReadOnly Property baNANa(xyz as String, a as integer) Overloads ReadOnly Property Banana(x as integer) End Interface </file> </compilation>) ' "Overloads" specified, but base properties have multiple casing, so don't use it. Dim interface1 = compilation.GetTypeByMetadataName("Interface1") Dim allProperties = interface1.GetMembers("baNANa").OfType(Of PropertySymbol)() CompilationUtils.AssertNoErrors(compilation) ' All methods in Interface1 should have metadata name "baNana". Dim count = 0 For Each m In allProperties count = count + 1 Assert.Equal("baNana", m.MetadataName) Next Assert.Equal(3, count) End Sub <Fact()> Public Sub AutoImplementedAccessorAreImplicitlyDeclared() Dim comp = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="b.vb"> MustInherit Class A Public MustOverride Property P As Integer Public Property P2 As Integer End Class Interface I Property Q As Integer End Interface </file> </compilation>) ' Per design meeting (see bug 11253), in VB, if there's no "Get" or "Set" written, ' then IsImplicitlyDeclared should be tru. Dim globalNS = comp.GlobalNamespace Dim a = globalNS.GetTypeMembers("A", 0).Single() Dim i = globalNS.GetTypeMembers("I", 0).Single() Dim p = TryCast(a.GetMembers("P").AsEnumerable().SingleOrDefault(), PropertySymbol) Assert.True(p.GetMethod.IsImplicitlyDeclared) Assert.True(p.SetMethod.IsImplicitlyDeclared) p = TryCast(a.GetMembers("P2").SingleOrDefault(), PropertySymbol) Assert.True(p.GetMethod.IsImplicitlyDeclared) Assert.True(p.SetMethod.IsImplicitlyDeclared) Dim q = TryCast(i.GetMembers("Q").AsEnumerable().SingleOrDefault(), PropertySymbol) Assert.True(q.GetMethod.IsImplicitlyDeclared) Assert.True(q.SetMethod.IsImplicitlyDeclared) End Sub <Fact(), WorkItem(544315, "DevDiv")> Public Sub PropertyAccessorParameterLocation() Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="b.vb"> Imports System Public Class A Public Default ReadOnly Property Prop(ByVal p1 As Integer) As String Get Return "passed" End Get End Property End Class </file> </compilation>) Dim globalNS = comp.SourceModule.GlobalNamespace Dim a = globalNS.GetTypeMembers("A").Single() Dim p = TryCast(a.GetMembers("Prop").Single(), PropertySymbol) Dim paras = p.Parameters Assert.Equal(1, paras.Length) Dim p1 = paras(0) Assert.Equal("p1", p1.Name) Assert.Equal(1, p1.Locations.Length) Assert.Equal(1, p.GetMethod.Parameters.Length) Dim p11 = p.GetMethod.Parameters(0) Assert.False(p11.Locations.IsEmpty, "Parameter Location NotEmpty") Assert.True(p11.Locations(0).IsInSource, "Parameter Location(0) IsInSource") Assert.Equal(p1.Locations(0), p11.Locations(0)) End Sub ''' <summary> ''' Consistent accessor signatures but different ''' from property signature. ''' </summary> <WorkItem(545814, "DevDiv")> <Fact()> Public Sub DifferentSignatures_AccessorsConsistent() Dim source1 = <![CDATA[ .class public A { .method public instance object get_P1(object& i) { ldnull ret } .method public instance void set_P1(object& i, object& v) { ret } .method public instance object get_P2(object& i) { ldnull ret } .method public instance void set_P3(object& i, object& v) { ret } .property instance object P1(object) { .get instance object A::get_P1(object& i) .set instance void A::set_P1(object& i, object& v) } .property instance object P2(object) { .get instance object A::get_P2(object& i) } .property instance object P3(object) { .set instance void A::set_P3(object& i, object& v) } } ]]>.Value Dim reference1 = CompileIL(source1) Dim source2 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M(o As A, i As Object) o.P1(i) = o.P1(i) o.P3(i) = o.P2(i) F(o.P1(i)) End Sub Sub F(ByRef o As Object) End Sub End Module ]]> </file> </compilation> Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2, {reference1}) compilation2.AssertNoErrors() Dim compilationVerifier = CompileAndVerify(compilation2) compilationVerifier.VerifyIL("M.M(A, Object)", <![CDATA[ { // Code size 131 (0x83) .maxstack 4 .locals init (Object V_0, Object V_1, Object V_2, Object V_3) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0007: stloc.0 IL_0008: ldloca.s V_0 IL_000a: ldarg.0 IL_000b: ldarg.1 IL_000c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0011: stloc.2 IL_0012: ldloca.s V_2 IL_0014: callvirt "Function A.get_P1(ByRef Object) As Object" IL_0019: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001e: stloc.1 IL_001f: ldloca.s V_1 IL_0021: callvirt "Sub A.set_P1(ByRef Object, ByRef Object)" IL_0026: ldarg.0 IL_0027: ldarg.1 IL_0028: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002d: stloc.1 IL_002e: ldloca.s V_1 IL_0030: ldarg.0 IL_0031: ldarg.1 IL_0032: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0037: stloc.2 IL_0038: ldloca.s V_2 IL_003a: callvirt "Function A.get_P2(ByRef Object) As Object" IL_003f: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0044: stloc.0 IL_0045: ldloca.s V_0 IL_0047: callvirt "Sub A.set_P3(ByRef Object, ByRef Object)" IL_004c: ldarg.0 IL_004d: dup IL_004e: ldarg.1 IL_004f: dup IL_0050: stloc.0 IL_0051: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0056: stloc.2 IL_0057: ldloca.s V_2 IL_0059: callvirt "Function A.get_P1(ByRef Object) As Object" IL_005e: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0063: stloc.1 IL_0064: ldloca.s V_1 IL_0066: call "Sub M.F(ByRef Object)" IL_006b: ldloc.0 IL_006c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0071: stloc.2 IL_0072: ldloca.s V_2 IL_0074: ldloc.1 IL_0075: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_007a: stloc.3 IL_007b: ldloca.s V_3 IL_007d: callvirt "Sub A.set_P1(ByRef Object, ByRef Object)" IL_0082: ret } ]]>) ' Accessor signature should be used for binding ' rather than property signature. Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M(o As A) Dim v As Integer = o.P1(1) v = o.P2(2) o.P3(3) = v F(o.P1(1)) End Sub Sub F(ByRef o As Integer) End Sub End Module ]]> </file> </compilation> Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source3, {reference1}) compilation3.AssertTheseDiagnostics(<errors><![CDATA[ BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'. Dim v As Integer = o.P1(1) ~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'. v = o.P2(2) ~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'. F(o.P1(1)) ~~~~~~~ ]]></errors>) End Sub ''' <summary> ''' Different accessor signatures and different accessor and ''' property signatures. (Both are supported by Dev11, but ''' Roslyn requires accessors to have consistent signatures.) ''' </summary> <WorkItem(545814, "DevDiv")> <Fact()> Public Sub DifferentSignatures_AccessorsDifferent() Dim source1 = <![CDATA[ .class public A { } .class public B { } .class public C { } .class public D { .method public instance class B get_P(class A i) { ldnull ret } .method public instance void set_P(class B i, class C v) { ret } .property instance class A P(class C) { .get instance class B D::get_P(class A) .set instance void D::set_P(class B, class C) } } ]]>.Value Dim reference1 = CompileIL(source1) ' Accessor method calls. Dim source2 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M(o As D, x As A, y As B, z As C) ' get_P signature. y = o.P(x) o.P(x) = y ' set_P signature. z = o.P(y) o.P(y) = z ' P signature. x = o.P(z) o.P(z) = x End Sub End Module ]]> </file> </compilation> Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2, {reference1}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC30643: Property 'D.P(i As C)' is of an unsupported type. y = o.P(x) ~ BC30643: Property 'D.P(i As C)' is of an unsupported type. o.P(x) = y ~ BC30643: Property 'D.P(i As C)' is of an unsupported type. z = o.P(y) ~ BC30643: Property 'D.P(i As C)' is of an unsupported type. o.P(y) = z ~ BC30643: Property 'D.P(i As C)' is of an unsupported type. x = o.P(z) ~ BC30643: Property 'D.P(i As C)' is of an unsupported type. o.P(z) = x ~ ]]></errors>) ' Property references. Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M(o As D, x As A) MBByVal(o.P(x)) MBByRef(o.P(x)) MCByVal(o.P(x)) MCByRef(o.P(x)) End Sub Sub MBByVal(y As B) End Sub Sub MBByRef(ByRef y As B) End Sub Sub MCByVal(z As C) End Sub Sub MCByRef(ByRef z As C) End Sub End Module ]]> </file> </compilation> Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source3, {reference1}) compilation3.AssertTheseDiagnostics(<errors><![CDATA[ BC30643: Property 'D.P(i As C)' is of an unsupported type. MBByVal(o.P(x)) ~ BC30643: Property 'D.P(i As C)' is of an unsupported type. MBByRef(o.P(x)) ~ BC30643: Property 'D.P(i As C)' is of an unsupported type. MCByVal(o.P(x)) ~ BC30643: Property 'D.P(i As C)' is of an unsupported type. MCByRef(o.P(x)) ~ ]]></errors>) End Sub ''' <summary> ''' Properties used in object initializers and attributes. ''' </summary> <WorkItem(545814, "DevDiv")> <Fact()> Public Sub DifferentSignatures_ObjectInitializersAndAttributes() Dim source1 = <![CDATA[ .class public A extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public instance int32 get_P() { ldc.i4.0 ret } .method public instance void set_P(int32 v) { ret } .property object P() { .get instance int32 A::get_P() .set instance void A::set_P(int32 v) } } ]]>.Value Dim reference1 = CompileIL(source1) ' Object initializer. Dim source2 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Private F As New A With {.P = ""} End Module ]]> </file> </compilation> Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2, {reference1}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'. Private F As New A With {.P = ""} ~~ ]]></errors>) ' Attribute. Dev11 no errors. Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On <A(P:="")> Class C End Class ]]> </file> </compilation> Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source3, {reference1}) compilation3.AssertTheseDiagnostics(<errors><![CDATA[ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'. <A(P:="")> ~~ BC30934: Conversion from 'String' to 'Integer' cannot occur in a constant expression used as an argument to an attribute. <A(P:="")> ~~ ]]></errors>) End Sub ''' <summary> ''' Overload resolution prefers supported properties over unsupported ''' properties. Since we're marking properties with inconsistent signatures ''' as unsupported, this can lead to different overload resolution than Dev11. ''' </summary> ''' <remarks></remarks> <WorkItem(545814, "DevDiv")> <Fact()> Public Sub DifferentSignatures_OverloadResolution() Dim source1 = <![CDATA[ .class public A { } .class public B extends A { } .class public C { .method public instance int32 get_P(class A o) { ldnull ret } .method public instance void set_P(class A o, int32 v) { ret } .method public instance int32 get_P(object o) { ldnull ret } .method public instance void set_P(object o, int32 v) { ret } // Property indexed by A, accessors indexed by A. .property instance int32 P(class A) { .get instance int32 C::get_P(class A o) .set instance void C::set_P(class A o, int32 v) } // Property indexed by B, accessors indexed by object. .property instance int32 P(class B) { .get instance int32 C::get_P(object o) .set instance void C::set_P(object o, int32 v) } } ]]>.Value Dim reference1 = CompileIL(source1) Dim source2 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M(_a As A, _b As B, o As C) o.P(_a) += 1 ' Dev11: P(A); Roslyn: P(A) o.P(_b) += 1 ' Dev11: P(B); Roslyn: P(A) End Sub End Module ]]> </file> </compilation> Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2, {reference1}) compilation2.AssertNoErrors() Dim compilationVerifier = CompileAndVerify(compilation2) compilationVerifier.VerifyIL("M.M(A, B, C)", <![CDATA[ { // Code size 41 (0x29) .maxstack 4 .locals init (C V_0, A V_1) IL_0000: ldarg.2 IL_0001: dup IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: dup IL_0005: stloc.1 IL_0006: ldloc.0 IL_0007: ldloc.1 IL_0008: callvirt "Function C.get_P(A) As Integer" IL_000d: ldc.i4.1 IL_000e: add.ovf IL_000f: callvirt "Sub C.set_P(A, Integer)" IL_0014: ldarg.2 IL_0015: dup IL_0016: stloc.0 IL_0017: ldarg.1 IL_0018: dup IL_0019: stloc.1 IL_001a: ldloc.0 IL_001b: ldloc.1 IL_001c: callvirt "Function C.get_P(A) As Integer" IL_0021: ldc.i4.1 IL_0022: add.ovf IL_0023: callvirt "Sub C.set_P(A, Integer)" IL_0028: ret } ]]>) End Sub ''' <summary> ''' Accessors with different parameter count than property. ''' </summary> <WorkItem(545814, "DevDiv")> <Fact()> Public Sub DifferentSignatures_ParameterCount() Dim source1 = <![CDATA[ .class public A { .method public instance int32 get_P(object x, object y) { ldnull ret } .method public instance void set_P(object x, object y, int32 v) { ret } .method public instance int32 get_Q(object o) { ldnull ret } .method public instance void set_Q(object o, int32 v) { ret } // Property with fewer arguments than accessors. .property instance int32 P(object) { .get instance int32 A::get_P(object x, object y) .set instance void A::set_P(object x, object y, int32 v) } // Property with more arguments than accessors. .property instance int32 Q(object, object) { .get instance int32 A::get_Q(object o) .set instance void A::set_Q(object o, int32 v) } } ]]>.Value Dim reference1 = CompileIL(source1) Dim source2 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M(o As A, x As Object, y As Object) o.P(x) = o.P(x) o.P(x, y) = o.P(x, y) o.Q(x) += 1 o.Q(x, y) += 1 End Sub End Module ]]> </file> </compilation> Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2, {reference1}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC30643: Property 'A.P(x As Object)' is of an unsupported type. o.P(x) = o.P(x) ~ BC30643: Property 'A.P(x As Object)' is of an unsupported type. o.P(x) = o.P(x) ~ BC30643: Property 'A.P(x As Object)' is of an unsupported type. o.P(x, y) = o.P(x, y) ~ BC30643: Property 'A.P(x As Object)' is of an unsupported type. o.P(x, y) = o.P(x, y) ~ BC30643: Property 'A.Q(o As Object, v As Object)' is of an unsupported type. o.Q(x) += 1 ~ BC30643: Property 'A.Q(o As Object, v As Object)' is of an unsupported type. o.Q(x, y) += 1 ~ ]]></errors>) End Sub <WorkItem(545959, "DevDiv")> <Fact()> Public Sub DifferentAccessorSignatures_NamedArguments_1() Dim ilSource = <![CDATA[ .class abstract public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method public abstract virtual instance void get(object x, object y) { } .method public abstract virtual instance void set(object x, object y) { } .method public instance int32 get_P(object x, object y) { ldarg.0 ldarg.1 ldarg.2 callvirt instance void A::get(object, object) ldnull ret } .method public instance void set_P(object y, object x, int32 v) { ldarg.0 ldarg.1 ldarg.2 callvirt instance void A::set(object, object) ret } .property instance int32 P(object, object) { .get instance int32 A::get_P(object, object) .set instance void A::set_P(object, object, int32) } } ]]>.Value Dim reference = CompileIL(ilSource) Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class B Inherits A Public Overrides Sub [get](x As Object, y As Object) System.Console.WriteLine("get {0}, {1}", x, y) End Sub Public Overrides Sub [set](x As Object, y As Object) System.Console.WriteLine("set {0}, {1}", x, y) End Sub End Class Module M Sub Main() Dim o = New B() o.P(1, 2) *= 1 o.P(x:=3, y:=4) *= 1 M(o.P(x:=5, y:=6)) End Sub Sub M(ByRef i As Integer) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(vbSource, additionalRefs:={reference}) compilation.AssertTheseDiagnostics( <expected> BC30455: Argument not specified for parameter 'Param' of 'Public Property P(Param As Object, Param As Object) As Integer'. o.P(x:=3, y:=4) *= 1 ~ BC30455: Argument not specified for parameter 'Param' of 'Public Property P(Param As Object, Param As Object) As Integer'. o.P(x:=3, y:=4) *= 1 ~ BC30272: 'x' is not a parameter of 'Public Property P(Param As Object, Param As Object) As Integer'. o.P(x:=3, y:=4) *= 1 ~ BC30272: 'y' is not a parameter of 'Public Property P(Param As Object, Param As Object) As Integer'. o.P(x:=3, y:=4) *= 1 ~ BC30455: Argument not specified for parameter 'Param' of 'Public Property P(Param As Object, Param As Object) As Integer'. M(o.P(x:=5, y:=6)) ~ BC30455: Argument not specified for parameter 'Param' of 'Public Property P(Param As Object, Param As Object) As Integer'. M(o.P(x:=5, y:=6)) ~ BC30272: 'x' is not a parameter of 'Public Property P(Param As Object, Param As Object) As Integer'. M(o.P(x:=5, y:=6)) ~ BC30272: 'y' is not a parameter of 'Public Property P(Param As Object, Param As Object) As Integer'. M(o.P(x:=5, y:=6)) ~ </expected>) End Sub ''' <summary> ''' Named arguments that differ by case. ''' </summary> <Fact()> Public Sub DifferentAccessorSignatures_NamedArguments_2() Dim ilSource = <![CDATA[ .class public A { .method public instance int32 get_P(object one, object two) { ldnull ret } .method public instance void set_P(object ONE, object _two, int32 v) { ret } .property instance int32 P(object, object) { .get instance int32 A::get_P(object one, object two) .set instance void A::set_P(object ONE, object _two, int32 v) } } ]]>.Value Dim reference = CompileIL(ilSource) Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M(o As A) o.P(1, 2) += 1 o.P(one:=1, two:=2) += 1 o.P(ONE:=1, _two:=2) += 1 End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(vbSource, additionalRefs:={reference}) compilation.AssertTheseDiagnostics( <expected> BC30455: Argument not specified for parameter 'Param' of 'Public Property P(one As Object, Param As Object) As Integer'. o.P(one:=1, two:=2) += 1 ~ BC30272: 'two' is not a parameter of 'Public Property P(one As Object, Param As Object) As Integer'. o.P(one:=1, two:=2) += 1 ~~~ BC30455: Argument not specified for parameter 'Param' of 'Public Property P(one As Object, Param As Object) As Integer'. o.P(ONE:=1, _two:=2) += 1 ~ BC30272: '_two' is not a parameter of 'Public Property P(one As Object, Param As Object) As Integer'. o.P(ONE:=1, _two:=2) += 1 ~~~~ </expected>) End Sub ''' <summary> ''' ByRef must be consistent between accessor parameters. ''' Note: Dev11 does not require this. ''' </summary> <Fact()> Public Sub DifferentAccessorSignatures_ByRef() Dim ilSource = <![CDATA[ .class public A1 { .method public instance object get_P(object i) { ldnull ret } .method public instance void set_P(object i, object v) { ret } .property instance object P(object) { .get instance object A1::get_P(object) .set instance void A1::set_P(object, object v) } } .class public A2 { .method public instance object get_P(object i) { ldnull ret } .method public instance void set_P(object& i, object v) { ret } .property instance object P(object) { .get instance object A2::get_P(object) .set instance void A2::set_P(object&, object v) } } .class public A3 { .method public instance object get_P(object i) { ldnull ret } .method public instance void set_P(object i, object& v) { ret } .property instance object P(object) { .get instance object A3::get_P(object) .set instance void A3::set_P(object, object& v) } } .class public A4 { .method public instance object& get_P(object i) { ldnull ret } .method public instance void set_P(object i, object v) { ret } .property instance object& P(object) { .get instance object& A4::get_P(object) .set instance void A4::set_P(object, object v) } } .class public A5 { .method public instance object& get_P(object i) { ldnull ret } .method public instance void set_P(object& i, object v) { ret } .property instance object& P(object) { .get instance object& A5::get_P(object) .set instance void A5::set_P(object&, object v) } } .class public A6 { .method public instance object& get_P(object i) { ldnull ret } .method public instance void set_P(object i, object& v) { ret } .property instance object& P(object) { .get instance object& A6::get_P(object) .set instance void A6::set_P(object, object& v) } } .class public A7 { .method public instance object get_P(object& i) { ldnull ret } .method public instance void set_P(object i, object v) { ret } .property instance object P(object&) { .get instance object A7::get_P(object&) .set instance void A7::set_P(object, object v) } } .class public A8 { .method public instance object get_P(object& i) { ldnull ret } .method public instance void set_P(object& i, object v) { ret } .property instance object P(object&) { .get instance object A8::get_P(object&) .set instance void A8::set_P(object&, object v) } } .class public A9 { .method public instance object get_P(object& i) { ldnull ret } .method public instance void set_P(object i, object& v) { ret } .property instance object P(object&) { .get instance object A9::get_P(object&) .set instance void A9::set_P(object, object& v) } } ]]>.Value Dim reference = CompileIL(ilSource) Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M(_1 As A1, _2 As A2, _3 As A3, _4 As A4, _5 As A5, _6 As A6, _7 As A7, _8 As A8, _9 As A9) Dim x As Object = Nothing Dim y As Object = Nothing _1.P(y) = _1.P(x) _2.P(y) = _2.P(x) _3.P(y) = _3.P(x) _4.P(y) = _4.P(x) _5.P(y) = _5.P(x) _6.P(y) = _6.P(x) _7.P(y) = _7.P(x) _8.P(y) = _8.P(x) _9.P(y) = _9.P(x) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(vbSource, additionalRefs:={reference}) compilation.AssertTheseDiagnostics( <expected> BC30643: Property 'A2.P(ByRef i As Object)' is of an unsupported type. _2.P(y) = _2.P(x) ~ BC30643: Property 'A2.P(ByRef i As Object)' is of an unsupported type. _2.P(y) = _2.P(x) ~ BC30643: Property 'P' is of an unsupported type. _4.P(y) = _4.P(x) ~ BC30643: Property 'P' is of an unsupported type. _4.P(y) = _4.P(x) ~ BC30643: Property 'A5.P(ByRef i As Object)' is of an unsupported type. _5.P(y) = _5.P(x) ~ BC30643: Property 'A5.P(ByRef i As Object)' is of an unsupported type. _5.P(y) = _5.P(x) ~ BC30643: Property 'P' is of an unsupported type. _6.P(y) = _6.P(x) ~ BC30643: Property 'P' is of an unsupported type. _6.P(y) = _6.P(x) ~ BC30643: Property 'A7.P(ByRef i As Object)' is of an unsupported type. _7.P(y) = _7.P(x) ~ BC30643: Property 'A7.P(ByRef i As Object)' is of an unsupported type. _7.P(y) = _7.P(x) ~ BC30643: Property 'A9.P(ByRef i As Object)' is of an unsupported type. _9.P(y) = _9.P(x) ~ BC30643: Property 'A9.P(ByRef i As Object)' is of an unsupported type. _9.P(y) = _9.P(x) ~ </expected>) End Sub ''' <summary> ''' ParamArray must be consistent between accessor parameters. ''' Note: Dev11 does not require this. ''' </summary> <Fact()> Public Sub DifferentAccessorSignatures_ParamArray() Dim ilSource = <![CDATA[ .class public A { .method public instance object get_NoParamArray(object[] i) { ldnull ret } .method public instance void set_NoParamArray(object[] i, object v) { ret } .method public instance object get_ParamArray(object[] i) { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) ldnull ret } .method public instance void set_ParamArray(object[] i, object v) { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) ret } // ParamArray on both accessors. .property instance object P1(object[]) { .get instance object A::get_ParamArray(object[]) .set instance void A::set_ParamArray(object[], object) } // ParamArray on getter only. .property instance object P2(object[]) { .get instance object A::get_ParamArray(object[]) .set instance void A::set_NoParamArray(object[], object) } // ParamArray on setter only. .property instance object P3(object[]) { .get instance object A::get_NoParamArray(object[]) .set instance void A::set_ParamArray(object[], object) } // ParamArray on readonly property. .property instance object P4(object[]) { .get instance object A::get_ParamArray(object[]) } // ParamArray on writeonly property. .property instance object P5(object[]) { .set instance void A::set_ParamArray(object[], object) } } ]]>.Value Dim reference = CompileIL(ilSource) Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Sub M(o As A) Dim v As Object Dim arg1 As Object = Nothing Dim arg2 As Object = Nothing Dim args = {arg1, arg2} v = o.P1(arg1, arg2) o.P1(arg1, arg2) = v v = o.P2(arg1, arg2) o.P2(arg1, arg2) = v v = o.P3(arg1, arg2) o.P3(arg1, arg2) = v v = o.P4(arg1, arg2) o.P5(arg1, arg2) = v v = o.P1(args) o.P1(args) = v v = o.P2(args) o.P2(args) = v v = o.P3(args) o.P3(args) = v v = o.P4(args) o.P5(args) = v End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(vbSource, additionalRefs:={reference}) compilation.AssertTheseDiagnostics( <expected> BC30057: Too many arguments to 'Public Property P2(i As Object()) As Object'. v = o.P2(arg1, arg2) ~~~~ BC30057: Too many arguments to 'Public Property P2(i As Object()) As Object'. o.P2(arg1, arg2) = v ~~~~ BC30057: Too many arguments to 'Public Property P3(i As Object()) As Object'. v = o.P3(arg1, arg2) ~~~~ BC30057: Too many arguments to 'Public Property P3(i As Object()) As Object'. o.P3(arg1, arg2) = v ~~~~ </expected>) Dim type = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A") Assert.True(type.GetMember(Of PropertySymbol)("P1").Parameters(0).IsParamArray) Assert.False(type.GetMember(Of PropertySymbol)("P2").Parameters(0).IsParamArray) Assert.False(type.GetMember(Of PropertySymbol)("P3").Parameters(0).IsParamArray) Assert.True(type.GetMember(Of PropertySymbol)("P4").Parameters(0).IsParamArray) Assert.True(type.GetMember(Of PropertySymbol)("P5").Parameters(0).IsParamArray) End Sub ''' <summary> ''' OptionCompare must be consistent between accessor parameters. ''' Note: Dev11 does not require this. ''' </summary> <Fact()> Public Sub DifferentAccessorSignatures_OptionCompare() Dim ilSource = <![CDATA[ .assembly extern Microsoft.VisualBasic { .ver 10:0:0:0 .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) } .class public A { .method public instance object get_NoOptionCompare(object i) { ldnull ret } .method public instance void set_NoOptionCompare(object i, object v) { ret } .method public instance object get_OptionCompare(object i) { .param [1] .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute::.ctor() = ( 01 00 00 00 ) ldnull ret } .method public instance void set_OptionCompare(object i, object v) { .param [1] .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute::.ctor() = ( 01 00 00 00 ) ret } // OptionCompare on both accessors. .property instance object P1(object) { .get instance object A::get_OptionCompare(object) .set instance void A::set_OptionCompare(object, object) } // OptionCompare on getter only. .property instance object P2(object) { .get instance object A::get_OptionCompare(object) .set instance void A::set_NoOptionCompare(object, object) } // OptionCompare on setter only. .property instance object P3(object) { .get instance object A::get_NoOptionCompare(object) .set instance void A::set_OptionCompare(object, object) } // OptionCompare on readonly property. .property instance object P4(object) { .get instance object A::get_OptionCompare(object) } // OptionCompare on writeonly property. .property instance object P5(object) { .set instance void A::set_OptionCompare(object, object) } } ]]>.Value Dim reference = CompileIL(ilSource) Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Sub M(o As A) Dim v As Object = Nothing v = o.P1(v) o.P1(v) = v v = o.P2(v) o.P2(v) = v v = o.P3(v) o.P3(v) = v v = o.P4(v) o.P5(v) = v End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(vbSource, additionalRefs:={reference}) compilation.AssertTheseDiagnostics( <expected> BC30643: Property 'A.P2(i As Object)' is of an unsupported type. v = o.P2(v) ~~ BC30643: Property 'A.P2(i As Object)' is of an unsupported type. o.P2(v) = v ~~ BC30643: Property 'A.P3(i As Object)' is of an unsupported type. v = o.P3(v) ~~ BC30643: Property 'A.P3(i As Object)' is of an unsupported type. o.P3(v) = v ~~ </expected>) Dim type = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A") Assert.True(type.GetMember(Of PropertySymbol)("P1").Parameters(0).HasOptionCompare) Assert.False(type.GetMember(Of PropertySymbol)("P2").Parameters(0).HasOptionCompare) Assert.False(type.GetMember(Of PropertySymbol)("P3").Parameters(0).HasOptionCompare) Assert.True(type.GetMember(Of PropertySymbol)("P4").Parameters(0).HasOptionCompare) Assert.True(type.GetMember(Of PropertySymbol)("P5").Parameters(0).HasOptionCompare) End Sub <Fact()> Public Sub OptionalParameterValues() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Imports System Public Class A Public ReadOnly Property P(x As Integer, Optional y As Integer = 1) As Integer Get Console.WriteLine("get_P: {0}", y) Return 0 End Get End Property Public WriteOnly Property Q(x As Integer, Optional y As Integer = 2) As Integer Set(value As Integer) Console.WriteLine("set_Q: {0}", y) End Set End Property End Class ]]> </file> </compilation> Dim compilation1 = CreateCompilationWithMscorlib(source1) Dim reference1 = MetadataReference.CreateFromImage(compilation1.EmitToArray()) Dim source2 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub Main() Dim o As A = New A() o.Q(2) = o.P(1) End Sub End Module ]]> </file> </compilation> Dim compilation2 = CompileAndVerify(source2, additionalRefs:={reference1}, expectedOutput:=<![CDATA[ get_P: 1 set_Q: 2 ]]>) End Sub <Fact()> Public Sub DifferentAccessorSignatures_Optional() Dim ilSource = <![CDATA[ .class public A { .method public instance object get_NoOpt(object x, object y) { .param[2] = int32(1) ldnull ret } .method public instance void set_NoOpt(object x, object y, object v) { ret } .method public instance object get_Opt(object x, [opt] object y) { .param[2] = int32(1) ldnull ret } .method public instance void set_Opt(object x, [opt] object y, object v) { .param[2] = int32(1) ret } // Opt on both accessors. .property instance object P1(object, object) { .get instance object A::get_Opt(object, object) .set instance void A::set_Opt(object, object, object) } // Opt on getter only. .property instance object P2(object, object) { .get instance object A::get_Opt(object, object) .set instance void A::set_NoOpt(object, object, object) } // Opt on setter only. .property instance object P3(object, object) { .get instance object A::get_NoOpt(object, object) .set instance void A::set_Opt(object, object, object) } // Opt on readonly property. .property instance object P4(object, object) { .get instance object A::get_Opt(object, object) } // Opt on writeonly property. .property instance object P5(object, object) { .set instance void A::set_Opt(object, object, object) } } ]]>.Value Dim reference = CompileIL(ilSource) Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Sub M(o As A) Dim v As Object = Nothing v = o.P1(v) o.P1(v) = v v = o.P2(v) o.P2(v) = v v = o.P3(v) o.P3(v) = v v = o.P4(v) o.P5(v) = v End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(vbSource, additionalRefs:={reference}) compilation.AssertTheseDiagnostics( <expected> BC30455: Argument not specified for parameter 'y' of 'Public Property P2(x As Object, y As Object) As Object'. v = o.P2(v) ~~ BC30455: Argument not specified for parameter 'y' of 'Public Property P2(x As Object, y As Object) As Object'. o.P2(v) = v ~~ BC30455: Argument not specified for parameter 'y' of 'Public Property P3(x As Object, y As Object) As Object'. v = o.P3(v) ~~ BC30455: Argument not specified for parameter 'y' of 'Public Property P3(x As Object, y As Object) As Object'. o.P3(v) = v ~~ </expected>) Dim defaultValue = ConstantValue.Create(1) Dim type = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A") Dim parameter As ParameterSymbol parameter = type.GetMember(Of PropertySymbol)("P1").Parameters(1) Assert.True(parameter.IsOptional) Assert.Equal(parameter.ExplicitDefaultConstantValue, defaultValue) parameter = type.GetMember(Of PropertySymbol)("P2").Parameters(1) Assert.False(parameter.IsOptional) Assert.Null(parameter.ExplicitDefaultConstantValue) parameter = type.GetMember(Of PropertySymbol)("P3").Parameters(1) Assert.False(parameter.IsOptional) Assert.Null(parameter.ExplicitDefaultConstantValue) parameter = type.GetMember(Of PropertySymbol)("P4").Parameters(1) Assert.True(parameter.IsOptional) Assert.Equal(parameter.ExplicitDefaultConstantValue, defaultValue) parameter = type.GetMember(Of PropertySymbol)("P5").Parameters(1) Assert.True(parameter.IsOptional) Assert.Equal(parameter.ExplicitDefaultConstantValue, defaultValue) End Sub <WorkItem(545959, "DevDiv")> <Fact()> Public Sub DistinctOptionalParameterValues() Dim ilSource = <![CDATA[ .class abstract public A { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance int32 get_P(int32 x, [opt] int32 y) { .param[2] = int32(1) } .method public abstract virtual instance void set_P(int32 x, [opt] int32 y, int32 v) { .param[2] = int32(2) } .property instance int32 P(int32, int32) { .get instance int32 A::get_P(int32, int32) .set instance void A::set_P(int32, int32, int32) } } ]]>.Value Dim reference = CompileIL(ilSource) Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Sub M(a As A) a(0) = a(0) a(1) += 1 [ByRef](a.P(2)) End Sub Sub [ByRef](ByRef o As Integer) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(vbSource, {reference}) compilation.AssertTheseDiagnostics( <expected> BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Default Property P(x As Integer, y As Integer) As Integer'. a(0) = a(0) ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Default Property P(x As Integer, y As Integer) As Integer'. a(0) = a(0) ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Default Property P(x As Integer, y As Integer) As Integer'. a(1) += 1 ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Default Property P(x As Integer, y As Integer) As Integer'. [ByRef](a.P(2)) ~ </expected>) End Sub <WorkItem(545959, "DevDiv")> <Fact()> Public Sub DistinctOptionalParameterValues_BadValue() Dim ilSource = <![CDATA[ .class abstract public A { .method public abstract virtual instance int32 get_P(int32 x, [opt] int32 y) { .param[2] = "" } .method public abstract virtual instance void set_P(int32 x, [opt] int32 y, int32 v) { .param[2] = int32(1) } .method public abstract virtual instance int32 get_Q(int32 x, [opt] int32 y) { .param[2] = int32(2) } .method public abstract virtual instance void set_Q(int32 x, [opt] int32 y, int32 v) { .param[2] = "" } // Bad getter default value. .property instance int32 P(int32, int32) { .get instance int32 A::get_P(int32, int32) .set instance void A::set_P(int32, int32, int32) } // Bad setter default value. .property instance int32 Q(int32, int32) { .get instance int32 A::get_Q(int32, int32) .set instance void A::set_Q(int32, int32, int32) } } ]]>.Value Dim reference = CompileIL(ilSource) Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M(o As A) o.P(1) = o.P(0) o.P(2) += 1 o.P(3, 0) += 1 o.Q(1) = o.Q(0) o.Q(2) += 1 o.Q(3, 0) += 1 End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(vbSource, {reference}) compilation.AssertTheseDiagnostics( <expected> BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property P(x As Integer, y As Integer) As Integer'. o.P(1) = o.P(0) ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property P(x As Integer, y As Integer) As Integer'. o.P(1) = o.P(0) ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property P(x As Integer, y As Integer) As Integer'. o.P(2) += 1 ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property Q(x As Integer, y As Integer) As Integer'. o.Q(1) = o.Q(0) ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property Q(x As Integer, y As Integer) As Integer'. o.Q(1) = o.Q(0) ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property Q(x As Integer, y As Integer) As Integer'. o.Q(2) += 1 ~ </expected>) End Sub <WorkItem(545959, "DevDiv")> <Fact()> Public Sub DistinctOptionalParameterValues_AdditionalOptional() Dim ilSource = <![CDATA[ .class abstract public A { .method public abstract virtual instance int32 get_P(int32 x, [opt] int32 y) { .param[2] = int32(1) } .method public abstract virtual instance void set_P(int32 x, int32 y, int32 v) { } .method public abstract virtual instance int32 get_Q(int32 x, int32 y) { } .method public abstract virtual instance void set_Q(int32 x, [opt] int32 y, int32 v) { .param[2] = int32(2) } // Optional parameter in getter. .property instance int32 P(int32, int32) { .get instance int32 A::get_P(int32, int32) .set instance void A::set_P(int32, int32, int32) } // Optional parameter in setter. .property instance int32 Q(int32, int32) { .get instance int32 A::get_Q(int32, int32) .set instance void A::set_Q(int32, int32, int32) } } ]]>.Value Dim reference = CompileIL(ilSource) Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M(o As A) o.P(1) = o.P(0) o.P(2) += 1 o.P(3, 0) += 1 [ByVal](o.P(4)) [ByRef](o.P(5)) o.Q(1) = o.Q(0) o.Q(2) += 1 o.Q(3, 0) += 1 [ByVal](o.Q(4)) [ByRef](o.Q(5)) End Sub Sub [ByVal](ByVal o As Integer) End Sub Sub [ByRef](ByRef o As Integer) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(vbSource, {reference}) compilation.AssertTheseDiagnostics( <expected> BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property P(x As Integer, y As Integer) As Integer'. o.P(1) = o.P(0) ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property P(x As Integer, y As Integer) As Integer'. o.P(1) = o.P(0) ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property P(x As Integer, y As Integer) As Integer'. o.P(2) += 1 ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property P(x As Integer, y As Integer) As Integer'. [ByVal](o.P(4)) ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property P(x As Integer, y As Integer) As Integer'. [ByRef](o.P(5)) ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property Q(x As Integer, y As Integer) As Integer'. o.Q(1) = o.Q(0) ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property Q(x As Integer, y As Integer) As Integer'. o.Q(1) = o.Q(0) ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property Q(x As Integer, y As Integer) As Integer'. o.Q(2) += 1 ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property Q(x As Integer, y As Integer) As Integer'. [ByVal](o.Q(4)) ~ BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property Q(x As Integer, y As Integer) As Integer'. [ByRef](o.Q(5)) ~ </expected>) End Sub ''' <summary> ''' Signatures where the property value type ''' does not match the getter return type. ''' </summary> <WorkItem(546476, "DevDiv")> <Fact()> Public Sub DifferentSignatures_PropertyType() Dim source1 = <![CDATA[ .class public A { } .class public B1 extends A { } .class public B2 extends A { } .class public C { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public instance class A get_A() { ldnull ret } .method public instance class B1 get_B1() { ldnull ret } .method public instance class B2 get_B2() { ldnull ret } .method public instance void set_A(class A v) { ret } .method public instance void set_B1(class B1 v) { ret } .property class A P1() { .get instance class B1 C::get_B1() .set instance void C::set_A(class A v) } .property class B1 P2() { .get instance class A C::get_A() .set instance void C::set_B1(class B1 v) } .property class B1 P3() { .get instance class B2 C::get_B2() .set instance void C::set_B1(class B1 v) } } ]]>.Value Dim reference1 = CompileIL(source1) Dim source2 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M1(o As C) Dim v As B1 v = o.P1 v = o.P2 v = o.P3 o.P1 = v o.P2 = v o.P3 = v M2(o.P1) M2(o.P2) M2(o.P3) M3(o.P1) M3(o.P2) M3(o.P3) End Sub Sub M2(o As B1) End Sub Sub M3(ByRef o As B1) End Sub End Module ]]> </file> </compilation> Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2, {reference1}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC30512: Option Strict On disallows implicit conversions from 'A' to 'B1'. v = o.P2 ~~~~ BC30311: Value of type 'B2' cannot be converted to 'B1'. v = o.P3 ~~~~ BC30512: Option Strict On disallows implicit conversions from 'A' to 'B1'. M2(o.P2) ~~~~ BC30311: Value of type 'B2' cannot be converted to 'B1'. M2(o.P3) ~~~~ BC30512: Option Strict On disallows implicit conversions from 'A' to 'B1'. M3(o.P2) ~~~~ BC30311: Value of type 'B2' cannot be converted to 'B1'. M3(o.P3) ~~~~ ]]></errors>) End Sub ''' <summary> ''' Signatures where the property value type ''' does not match the setter value type. ''' </summary> <WorkItem(546476, "DevDiv")> <Fact()> Public Sub DifferentSignatures_PropertyType_2() Dim source1 = <![CDATA[ .class public A { } .class public B1 extends A { } .class public B2 extends A { } .class public C { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public instance class A get_A() { ldnull ret } .method public instance class B1 get_B1() { ldnull ret } .method public instance void set_A(class A v) { ret } .method public instance void set_B1(class B1 v) { ret } .method public instance void set_B2(class B2 v) { ret } .property class A P1() { .get instance class A C::get_A() .set instance void C::set_B1(class B1 v) } .property class B1 P2() { .get instance class B1 C::get_B1() .set instance void C::set_A(class A v) } .property class B1 P3() { .get instance class B1 C::get_B1() .set instance void C::set_B2(class B2 v) } } ]]>.Value Dim reference1 = CompileIL(source1) Dim source2 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M1(o As C) Dim v As B1 v = o.P1 v = o.P2 v = o.P3 o.P1 = v o.P2 = v o.P3 = v M2(o.P1) M2(o.P2) M2(o.P3) M3(o.P1) M3(o.P2) M3(o.P3) End Sub Sub M2(o As B1) End Sub Sub M3(ByRef o As B1) End Sub End Module ]]> </file> </compilation> Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2, {reference1}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC30512: Option Strict On disallows implicit conversions from 'A' to 'B1'. v = o.P1 ~~~~ BC30311: Value of type 'B1' cannot be converted to 'B2'. o.P3 = v ~ BC30512: Option Strict On disallows implicit conversions from 'A' to 'B1'. M2(o.P1) ~~~~ BC30512: Option Strict On disallows implicit conversions from 'A' to 'B1'. M3(o.P1) ~~~~ BC33037: Cannot copy the value of 'ByRef' parameter 'o' back to the matching argument because type 'B1' cannot be converted to type 'B2'. M3(o.P3) ~~~~ ]]></errors>) End Sub ''' <summary> ''' Signatures where the property value type does not ''' match the accessors, used in compound assignment. ''' </summary> <WorkItem(546476, "DevDiv")> <Fact()> Public Sub DifferentSignatures_PropertyType_3() Dim source1 = <![CDATA[ .class public C { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public instance int32 get_P() { ldnull ret } .method public instance void set_P(int32 v) { ret } .method public instance object get_Q() { ldnull ret } .method public instance void set_Q(object v) { ret } .property object P() { .get instance int32 C::get_P() .set instance void C::set_P(int32 v) } .property int32 Q() { .get instance object C::get_Q() .set instance void C::set_Q(object v) } } ]]>.Value Dim reference1 = CompileIL(source1) Dim source2 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M(o As C) o.P += 1 o.Q += 1 End Sub End Module ]]> </file> </compilation> Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2, {reference1}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC30038: Option Strict On prohibits operands of type Object for operator '+'. o.Q += 1 ~~~ ]]></errors>) End Sub ''' <summary> ''' Getter return type is used for type inference. ''' Note: Dev11 uses the property type rather than getter. ''' </summary> <WorkItem(546476, "DevDiv")> <Fact()> Public Sub DifferentSignatures_PropertyType_4() Dim source1 = <![CDATA[ .class public A { } .class public B extends A { } .class public C { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public instance class A get_A() { ldnull ret } .method public instance class B get_B() { ldnull ret } .method public instance void set_A(class A v) { ret } .method public instance void set_B(class B v) { ret } .property class A P1() { .get instance class A C::get_A() .set instance void C::set_B(class B v) } .property class A P2() { .get instance class B C::get_B() .set instance void C::set_A(class A v) } .property class B P3() { .get instance class A C::get_A() .set instance void C::set_B(class B v) } .property class B P4() { .get instance class B C::get_B() .set instance void C::set_A(class A v) } } ]]>.Value Dim reference1 = CompileIL(source1) Dim source2 = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Module M Sub M(o As C) Dim v As B v = F1(o.P1) v = F1(o.P2) v = F1(o.P3) v = F1(o.P4) v = F2(o.P1) v = F2(o.P2) v = F2(o.P3) v = F2(o.P4) End Sub Function F1(Of T)(o As T) As T Return Nothing End Function Function F2(Of T)(ByRef o As T) As T Return Nothing End Function End Module ]]> </file> </compilation> Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2, {reference1}) compilation2.AssertTheseDiagnostics(<errors><![CDATA[ BC30512: Option Strict On disallows implicit conversions from 'A' to 'B'. v = F1(o.P1) ~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'A' to 'B'. v = F1(o.P3) ~~~~~~~~ BC32029: Option Strict On disallows narrowing from type 'A' to type 'B' in copying the value of 'ByRef' parameter 'o' back to the matching argument. v = F2(o.P1) ~~~~ BC32029: Option Strict On disallows narrowing from type 'A' to type 'B' in copying the value of 'ByRef' parameter 'o' back to the matching argument. v = F2(o.P3) ~~~~ ]]></errors>) End Sub <Fact()> Public Sub ByRefType() Dim ilSource = <![CDATA[ .class public A { .method public instance object& get_P() { ldnull ret } .method public instance void set_P(object& v) { ret } .property instance object& P() { .get instance object& A::get_P() .set instance void A::set_P(object&) } } ]]>.Value Dim reference = CompileIL(ilSource) Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Sub M(o As A) Dim v As Object v = o.P o.P = v End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(vbSource, additionalRefs:={reference}) compilation.AssertTheseDiagnostics( <expected> BC30643: Property 'P' is of an unsupported type. v = o.P ~ BC30643: Property 'P' is of an unsupported type. o.P = v ~ </expected>) End Sub <Fact()> Public Sub ByRefParameter() Dim ilSource = <![CDATA[ .class public A { .method public instance object get_P(object& i) { ldnull ret } .method public instance void set_P(object& i, object v) { ret } .property instance object P(object&) { .get instance object A::get_P(object&) .set instance void A::set_P(object&, object) } } ]]>.Value Dim reference = CompileIL(ilSource) Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Sub M(o As A) Dim v As Object v = o.P(Nothing) o.P(Nothing) = v o.P(v) = o.P(v) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(vbSource, additionalRefs:={reference}) compilation.AssertNoErrors() Dim compilationVerifier = CompileAndVerify(compilation) compilationVerifier.VerifyIL("M.M(A)", <![CDATA[ { // Code size 68 (0x44) .maxstack 4 .locals init (Object V_0, //v Object V_1, Object V_2) IL_0000: ldarg.0 IL_0001: ldnull IL_0002: stloc.1 IL_0003: ldloca.s V_1 IL_0005: callvirt "Function A.get_P(ByRef Object) As Object" IL_000a: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000f: stloc.0 IL_0010: ldarg.0 IL_0011: ldnull IL_0012: stloc.1 IL_0013: ldloca.s V_1 IL_0015: ldloc.0 IL_0016: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001b: callvirt "Sub A.set_P(ByRef Object, Object)" IL_0020: ldarg.0 IL_0021: ldloc.0 IL_0022: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0027: stloc.1 IL_0028: ldloca.s V_1 IL_002a: ldarg.0 IL_002b: ldloc.0 IL_002c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0031: stloc.2 IL_0032: ldloca.s V_2 IL_0034: callvirt "Function A.get_P(ByRef Object) As Object" IL_0039: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_003e: callvirt "Sub A.set_P(ByRef Object, Object)" IL_0043: ret } ]]>) End Sub <Fact()> Public Sub MissingSystemTypes_Property() Dim compilation = CompilationUtils.CreateCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ Interface I ReadOnly Property P As Object WriteOnly Property Q As Object End Interface ]]></file> </compilation>, references:=Nothing) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'System.Object' is not defined. ReadOnly Property P As Object ~~~~~~ BC30002: Type 'System.Void' is not defined. WriteOnly Property Q As Object ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30002: Type 'System.Object' is not defined. WriteOnly Property Q As Object ~~~~~~ ]]></errors>) End Sub <WorkItem(530418, "DevDiv")> <Fact(Skip:="530418")> Public Sub MissingSystemTypes_AutoProperty() Dim compilation = CompilationUtils.CreateCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ Class C Property P As Object End Class ]]></file> </compilation>, references:=Nothing) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue' is not defined. Property P As Object ~ BC30002: Type 'System.Void' is not defined. Class C ~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'C.dll' failed. Class C ~ BC30002: Type 'System.Void' is not defined. Property P As Object ~~~~~~~~~~~~~~~~~~~~ BC30002: Type 'System.Object' is not defined. Property P As Object ~~~~~~ ]]></errors>) End Sub <WorkItem(531292, "DevDiv")> <Fact()> Public Sub Bug17897() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Program Property Test0() Protected Get Return Nothing End Get Set(ByVal Value) End Set End Property Protected Sub Test1() End Sub Protected Property Test2 As Integer Property Test3() Get Return Nothing End Get Protected Set(ByVal Value) End Set End Property Protected Test4 As Integer Protected Class Test5 End Class Protected Event Test6 As Action Protected Delegate Sub Test7() Sub Main(args As String()) End Sub End Module ]]></file> </compilation>) compilation.AssertTheseDiagnostics( <errors><![CDATA[ BC30503: Properties in a Module cannot be declared 'Protected'. Protected Get ~~~~~~~~~ BC30433: Methods in a Module cannot be declared 'Protected'. Protected Sub Test1() ~~~~~~~~~ BC30503: Properties in a Module cannot be declared 'Protected'. Protected Property Test2 As Integer ~~~~~~~~~ BC30503: Properties in a Module cannot be declared 'Protected'. Protected Set(ByVal Value) ~~~~~~~~~ BC30593: Variables in Modules cannot be declared 'Protected'. Protected Test4 As Integer ~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected'. Protected Class Test5 ~~~~~~~~~ BC30434: Events in a Module cannot be declared 'Protected'. Protected Event Test6 As Action ~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected'. Protected Delegate Sub Test7() ~~~~~~~~~ ]]></errors>) End Sub ''' <summary> ''' When the output type is .winmdobj properties should emit put_Property methods instead ''' of set_Property methods. ''' </summary> <Fact()> Public Sub WinRtPropertySet() Dim libSrc = <compilation> <file name="c.vb"><![CDATA[ Public Class C Public Dim Abacking As Integer Public Property A As Integer Get Return Abacking End Get Set Abacking = value End Set End Property End Class ]]> </file> </compilation> Dim getValidator = Function(expectedMembers As String()) Return Sub(m As ModuleSymbol) Dim actualMembers = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMembers().ToArray() AssertEx.SetEqual((From s In actualMembers Select s.Name), expectedMembers) End Sub End Function Dim verify = Sub(winmd As Boolean, expected As String()) Dim validator = getValidator(expected) ' We should see the same members from both source and metadata Dim verifier = CompileAndVerify( libSrc, sourceSymbolValidator:=validator, symbolValidator:=validator, options:=If(winmd, TestOptions.ReleaseWinMD, TestOptions.ReleaseDll)) verifier.VerifyDiagnostics() End Sub ' Test winmd verify(True, New String() { "Abacking", "A", "get_A", "put_A", WellKnownMemberNames.InstanceConstructorName}) ' Test normal verify(False, New String() { "Abacking", "A", "get_A", "set_A", WellKnownMemberNames.InstanceConstructorName}) End Sub <Fact()> Public Sub WinRtAnonymousProperty() Dim src = <compilation> <file name="c.vb"> <![CDATA[ Imports System Class C Public Property P = New With {.Name = "prop"} End Class ]]> </file> </compilation> Dim srcValidator = Sub(m As ModuleSymbol) Dim members = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMembers() AssertEx.SetEqual((From member In members Select member.Name), {WellKnownMemberNames.InstanceConstructorName, "_P", "get_P", "put_P", "P"}) End Sub Dim mdValidator = Sub(m As ModuleSymbol) Dim members = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("VB$AnonymousType_0").GetMembers() AssertEx.SetEqual((From member In members Select member.Name), {"get_Name", "put_Name", WellKnownMemberNames.InstanceConstructorName, "ToString", "Name"}) End Sub Dim verifier = CompileAndVerify(src, allReferences:={MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseWinMD, sourceSymbolValidator:=srcValidator, symbolValidator:=mdValidator) End Sub ''' <summary> ''' Accessor type names that conflict should cause the appropriate diagnostic ''' (i.e., set_ for dll, put_ for winmdobj) ''' </summary> <Fact()> Public Sub WinRtPropertyAccessorNameConflict() Dim libSrc = <compilation> <file name="c.vb"> <![CDATA[ Public Class C Public Property A as Integer Public Sub put_A(value As Integer) End Sub Public Sub set_A(value as Integer) End Sub End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib(libSrc, OutputKind.DynamicallyLinkedLibrary) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_SynthMemberClashesWithMember5, "A").WithArguments("property", "A", "set_A", "class", "C")) comp = CreateCompilationWithMscorlib(libSrc, OutputKind.WindowsRuntimeMetadata) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_SynthMemberClashesWithMember5, "A").WithArguments("property", "A", "put_A", "class", "C")) End Sub #Region "Helpers" Private Sub VerifyMethodsAndAccessorsSame(type As NamedTypeSymbol, [property] As PropertySymbol) VerifyMethodAndAccessorSame(type, [property], [property].GetMethod) VerifyMethodAndAccessorSame(type, [property], [property].SetMethod) End Sub Private Sub VerifyMethodAndAccessorSame(type As NamedTypeSymbol, [property] As PropertySymbol, accessor As MethodSymbol) Assert.NotNull(accessor) Assert.Same(type, accessor.ContainingType) Assert.Same(type, accessor.ContainingSymbol) Dim method = type.GetMembers(accessor.Name).Single() Assert.NotNull(method) Assert.Equal(accessor, method) Dim isAccessor = accessor.MethodKind = MethodKind.PropertyGet OrElse accessor.MethodKind = MethodKind.PropertySet Assert.True(isAccessor) Assert.NotNull(accessor.AssociatedSymbol) Assert.Same(accessor.AssociatedSymbol, [property]) End Sub Private Shared Sub CheckPropertyAccessibility([property] As PropertySymbol, propertyAccessibility As Accessibility, getterAccessibility As Accessibility, setterAccessibility As Accessibility) Dim type = [property].Type Assert.NotEqual(type.PrimitiveTypeCode, Cci.PrimitiveTypeCode.Void) Assert.Equal(propertyAccessibility, [property].DeclaredAccessibility) CheckPropertyAccessorAccessibility([property], propertyAccessibility, [property].GetMethod, getterAccessibility) CheckPropertyAccessorAccessibility([property], propertyAccessibility, [property].SetMethod, setterAccessibility) End Sub Private Shared Sub CheckPropertyAccessorAccessibility([property] As PropertySymbol, propertyAccessibility As Accessibility, accessor As MethodSymbol, accessorAccessibility As Accessibility) If accessor Is Nothing Then Assert.Equal(accessorAccessibility, Accessibility.NotApplicable) Else Dim containingType = [property].ContainingType Assert.Same([property], accessor.AssociatedSymbol) Assert.Same(containingType, accessor.ContainingType) Assert.Same(containingType, accessor.ContainingSymbol) Dim method = containingType.GetMembers(accessor.Name).Single() Assert.Same(method, accessor) Assert.Equal(accessorAccessibility, accessor.DeclaredAccessibility) End If End Sub Private Shared Sub VerifyAutoProperty(type As NamedTypeSymbol, name As String, declaredAccessibility As Accessibility, isFromSource As Boolean) Dim [property] = type.GetMembers(name).OfType(Of PropertySymbol)().SingleOrDefault() Assert.NotNull([property]) Assert.Equal([property].DeclaredAccessibility, declaredAccessibility) Dim sourceProperty = TryCast([property], SourcePropertySymbol) If sourceProperty IsNot Nothing Then Assert.True(sourceProperty.IsAutoProperty) Dim c = sourceProperty.DeclaringCompilation Dim attributes = sourceProperty.AssociatedField.GetSynthesizedAttributes() Assert.Equal( c.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor), attributes.Single().AttributeConstructor) End If Dim field = type.GetMembers("_" + name).OfType(Of FieldSymbol)().SingleOrDefault() If isFromSource Then Assert.NotNull(field) Assert.Equal(field.DeclaredAccessibility, Accessibility.Private) Assert.Equal(field.Type, [property].Type) Else Assert.Null(field) End If End Sub Private Sub VerifyAccessor(accessor As MethodSymbol, associatedProperty As PEPropertySymbol, methodKind As MethodKind) Assert.NotNull(accessor) Assert.Same(accessor.AssociatedSymbol, associatedProperty) Assert.Equal(accessor.MethodKind, methodKind) If associatedProperty IsNot Nothing Then Dim method = If((methodKind = MethodKind.PropertyGet), associatedProperty.GetMethod, associatedProperty.SetMethod) Assert.Same(accessor, method) End If End Sub Private Sub VerifyPropertyParams(propertySymbol As PropertySymbol, expectedParams As String(,)) For index = 0 To expectedParams.Length Assert.Equal(propertySymbol.Parameters(index).Name, expectedParams(index, 0)) Assert.Equal(propertySymbol.Parameters(index).Type.Name, expectedParams(index, 1)) Next End Sub Private Shared Sub CheckPropertyExplicitImplementation([class] As NamedTypeSymbol, classProperty As PropertySymbol, interfaceProperty As PropertySymbol) Dim interfacePropertyGetter = interfaceProperty.GetMethod Assert.NotNull(interfacePropertyGetter) Dim interfacePropertySetter = interfaceProperty.SetMethod Assert.NotNull(interfacePropertySetter) Assert.Equal(interfaceProperty, classProperty.ExplicitInterfaceImplementations.Single()) Dim classPropertyGetter = classProperty.GetMethod Assert.NotNull(classPropertyGetter) Dim classPropertySetter = classProperty.SetMethod Assert.NotNull(classPropertySetter) Assert.Equal(interfacePropertyGetter, classPropertyGetter.ExplicitInterfaceImplementations.Single()) Assert.Equal(interfacePropertySetter, classPropertySetter.ExplicitInterfaceImplementations.Single()) Dim typeDef = DirectCast([class], Cci.ITypeDefinition) Dim [module] = New PEAssemblyBuilder(DirectCast([class].ContainingAssembly, SourceAssemblySymbol), EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable(Of ResourceDescription)()) Dim context = New EmitContext([module], Nothing, New DiagnosticBag()) Dim explicitOverrides = typeDef.GetExplicitImplementationOverrides(context) Assert.Equal(2, explicitOverrides.Count()) Assert.True(explicitOverrides.All(Function(override) [class] Is override.ContainingType)) ' We're not actually asserting that the overrides are in this order - set comparison just seems like overkill for two elements Dim getterOverride = explicitOverrides.First() Assert.Equal(classPropertyGetter, getterOverride.ImplementingMethod) Assert.Equal(interfacePropertyGetter.ContainingType, getterOverride.ImplementedMethod.GetContainingType(context)) Assert.Equal(interfacePropertyGetter.Name, getterOverride.ImplementedMethod.Name) Dim setterOverride = explicitOverrides.Last() Assert.Equal(classPropertySetter, setterOverride.ImplementingMethod) Assert.Equal(interfacePropertySetter.ContainingType, setterOverride.ImplementedMethod.GetContainingType(context)) Assert.Equal(interfacePropertySetter.Name, setterOverride.ImplementedMethod.Name) context.Diagnostics.Verify() End Sub Private Shared Sub VerifyAccessibility([property] As PEPropertySymbol, propertyAccessibility As Accessibility, getAccessibility As Accessibility, setAccessibility As Accessibility) Assert.Equal([property].DeclaredAccessibility, propertyAccessibility) VerifyAccessorAccessibility([property].GetMethod, getAccessibility) VerifyAccessorAccessibility([property].SetMethod, setAccessibility) End Sub Private Shared Sub VerifyAccessorAccessibility(accessor As MethodSymbol, accessorAccessibility As Accessibility) If accessorAccessibility = Accessibility.NotApplicable Then Assert.Null(accessor) Else Assert.NotNull(accessor) Assert.Equal(accessor.DeclaredAccessibility, accessorAccessibility) End If End Sub Private Function CompileWithCustomPropertiesAssembly(source As XElement, Optional options As VisualBasicCompilationOptions = Nothing) As VisualBasicCompilation Return CreateCompilationWithMscorlibAndReferences(source, {s_propertiesDll}, options) End Function Private Shared ReadOnly s_propertiesDll As MetadataReference = TestReferences.SymbolsTests.Properties Private Shared Sub VerifyPropertiesParametersCount([property] As PropertySymbol, expectedCount As Integer) Assert.Equal([property].Parameters.Length, expectedCount) If [property].GetMethod IsNot Nothing Then Assert.Equal([property].GetMethod.Parameters.Length, expectedCount) End If If [property].SetMethod IsNot Nothing Then Assert.Equal([property].SetMethod.Parameters.Length, expectedCount + 1) End If End Sub Private Shared Sub VeryifyPropertiesParametersTypes([property] As PropertySymbol, ParamArray expectedTypes() As TypeSymbol) Assert.Equal([property].SetMethod.Parameters.Last().Type, [property].Type) Assert.True((From param In [property].Parameters Select param.Type).SequenceEqual(expectedTypes)) If [property].GetMethod IsNot Nothing Then Assert.True((From param In [property].GetMethod.Parameters Select param.Type).SequenceEqual(expectedTypes)) End If If [property].SetMethod IsNot Nothing Then Assert.True((From param In [property].SetMethod.Parameters Select param.Type).Take([property].Parameters.Length - 1).SequenceEqual(expectedTypes)) End If End Sub Private Shared Sub VerifyNoDiagnostics(result As EmitResult) Assert.Equal(String.Empty, String.Join(Environment.NewLine, result.Diagnostics)) End Sub #End Region End Class End Namespace
stjeong/roslyn
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/PropertyTests.vb
Visual Basic
apache-2.0
272,599
' 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.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.ReplaceMethodWithProperty Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.ReplaceMethodWithProperty Public Class ReplaceMethodWithPropertyTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New ReplaceMethodWithPropertyCodeRefactoringProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestMethodWithGetName() As Task Await TestInRegularAndScriptAsync( "class C function [||]GetGoo() as integer End function End class", "class C ReadOnly Property Goo as integer Get End Get End Property End class") End Function <WorkItem(17368, "https://github.com/dotnet/roslyn/issues/17368")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestMissingParameterList() As Task Await TestInRegularAndScript1Async( "class C function [||]GetGoo as integer End function End class", "class C ReadOnly Property Goo as integer Get End Get End Property End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestMethodWithoutGetName() As Task Await TestInRegularAndScriptAsync( "class C function [||]Goo() as integer End function End class", "class C ReadOnly Property Goo as integer Get End Get End Property End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestMethodWithoutBody() As Task Await TestInRegularAndScriptAsync( "mustinherit class C MustOverride function [||]GetGoo() as integer End class", "mustinherit class C MustOverride ReadOnly Property Goo as integer End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestMethodWithModifiers() As Task Await TestInRegularAndScriptAsync( "class C public shared function [||]GetGoo() as integer End function End class", "class C public shared ReadOnly Property Goo as integer Get End Get End Property End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestMethodWithAttributes() As Task Await TestInRegularAndScriptAsync( "class C <A> function [||]GetGoo() as integer End function End class", "class C <A> ReadOnly Property Goo as integer Get End Get End Property End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestMethodWithTrivia_1() As Task Await TestInRegularAndScriptAsync( "class C ' Goo function [||]GetGoo() as integer End function End class", "class C ' Goo ReadOnly Property Goo as integer Get End Get End Property End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestIfDefMethod() As Task Await TestInRegularAndScriptAsync( "class C #if true function [||]GetGoo() as integer End function #End if End class", "class C #if true ReadOnly Property Goo as integer Get End Get End Property #End if End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestIfDefMethod2() As Task Await TestInRegularAndScriptAsync( "class C #if true function [||]GetGoo() as integer End function sub SetGoo(i as integer) end sub #End if End class", "class C #if true ReadOnly Property Goo as integer Get End Get End Property sub SetGoo(i as integer) end sub #End if End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestIfDefMethod3() As Task Await TestInRegularAndScriptAsync( "class C #if true function [||]GetGoo() as integer End function sub SetGoo(i as integer) end sub #End if End class", "class C #if true Property Goo as integer Get End Get Set(i as integer) End Set End Property #End if End class", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestIfDefMethod4() As Task Await TestInRegularAndScriptAsync( "class C #if true sub SetGoo(i as integer) end sub function [||]GetGoo() as integer End function #End if End class", "class C #if true sub SetGoo(i as integer) end sub ReadOnly Property Goo as integer Get End Get End Property #End if End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestIfDefMethod5() As Task Await TestInRegularAndScriptAsync( "class C #if true sub SetGoo(i as integer) end sub function [||]GetGoo() as integer End function #End if End class", "class C #if true Property Goo as integer Get End Get Set(i as integer) End Set End Property #End if End class", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestMethodWithTrivia_2() As Task Await TestInRegularAndScriptAsync( "class C ' Goo function [||]GetGoo() as integer End function ' SetGoo sub SetGoo(i as integer) End sub End class", "class C ' Goo ' SetGoo Property Goo as integer Get End Get Set(i as integer) End Set End Property End class", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestExplicitInterfaceMethod_2() As Task Await TestInRegularAndScriptAsync( "interface I function GetGoo() as integer End interface class C implements I function [||]GetGoo() as integer implements I.GetGoo End function End class", "interface I ReadOnly Property Goo as integer End interface class C implements I ReadOnly Property Goo as integer implements I.Goo Get End Get End Property End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestExplicitInterfaceMethod_3() As Task Await TestInRegularAndScriptAsync( "interface I function [||]GetGoo() as integer End interface class C implements I function GetGoo() as integer implements I.GetGoo End function End class", "interface I ReadOnly Property Goo as integer End interface class C implements I ReadOnly Property Goo as integer implements I.Goo Get End Get End Property End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestInAttribute() As Task Await TestMissingInRegularAndScriptAsync( "class C <At[||]tr> function GetGoo() as integer End function End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestInMethod() As Task Await TestMissingInRegularAndScriptAsync( "class C function GetGoo() as integer [||] End function End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestSubMethod() As Task Await TestMissingInRegularAndScriptAsync( "class C sub [||]GetGoo() End sub End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestAsyncMethod() As Task Await TestMissingInRegularAndScriptAsync( "class C async function [||]GetGoo() as Task End function End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestGenericMethod() As Task Await TestMissingInRegularAndScriptAsync( "class C function [||]GetGoo(of T)() as integer End function End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestExtensionMethod() As Task Await TestMissingInRegularAndScriptAsync( "module C <System.Runtime.CompilerServices.Extension> function [||]GetGoo(i as integer) as integer End function End module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestMethodWithParameters_1() As Task Await TestMissingInRegularAndScriptAsync( "class C function [||]GetGoo(i as integer) as integer End function End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestUpdateGetReferenceNotInMethod() As Task Await TestInRegularAndScriptAsync( "class C function [||]GetGoo() as integer End function sub Bar() dim x = GetGoo() End sub End class", "class C ReadOnly Property Goo as integer Get End Get End Property sub Bar() dim x = Goo End sub End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestUpdateGetReferenceMemberAccessInvocation() As Task Await TestInRegularAndScriptAsync( "class C function [||]GetGoo() as integer End function sub Bar() dim x = me.GetGoo() End sub End class", "class C ReadOnly Property Goo as integer Get End Get End Property sub Bar() dim x = me.Goo End sub End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestUpdateGetReferenceBindingMemberInvocation() As Task Await TestInRegularAndScriptAsync( "class C function [||]GetGoo() as integer End function sub Bar() dim x as C dim v = x?.GetGoo() End sub End class", "class C ReadOnly Property Goo as integer Get End Get End Property sub Bar() dim x as C dim v = x?.Goo End sub End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestUpdateGetReferenceInMethod() As Task Await TestInRegularAndScriptAsync( "class C function [||]GetGoo() as integer return GetGoo() End function End class", "class C ReadOnly Property Goo as integer Get return Goo End Get End Property End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestOverride() As Task Await TestInRegularAndScriptAsync( "class C public overridable function [||]GetGoo() as integer End function End class class D inherits C public overrides function GetGoo() as integer End function End class", "class C public overridable ReadOnly Property Goo as integer Get End Get End Property End class class D inherits C public overrides ReadOnly Property Goo as integer Get End Get End Property End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestUpdateGetReference_NonInvoked() As Task Await TestInRegularAndScriptAsync( "class C function [||]GetGoo() as integer End function sub Bar() dim i = GetGoo End sub End class", "class C ReadOnly Property Goo as integer Get End Get End Property sub Bar() dim i = Goo End sub End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestUpdateGetSet() As Task Await TestInRegularAndScriptAsync( "class C function [||]GetGoo() as integer End function sub SetGoo(i as integer) End sub End class", "class C Property Goo as integer Get End Get Set(i as integer) End Set End Property End class", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestUpdateGetSetReference_NonInvoked() As Task Await TestInRegularAndScriptAsync( "Imports System class C function [||]GetGoo() as integer End function sub SetGoo(i as integer) End sub sub Bar() dim i as Action(of integer) = addressof SetGoo End sub End class", "Imports System class C Property Goo as integer Get End Get Set(i as integer) End Set End Property sub Bar() dim i as Action(of integer) = addressof {|Conflict:Goo|} End sub End class", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestUpdateGetSet_SetterAccessibility() As Task Await TestInRegularAndScriptAsync( "class C public function [||]GetGoo() as integer End function private sub SetGoo(i as integer) End sub End class", "class C public Property Goo as integer Get End Get Private Set(i as integer) End Set End Property End class", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestUpdateGetSet_GetInSetReference() As Task Await TestInRegularAndScriptAsync( "class C function [||]GetGoo() as integer End function sub SetGoo(i as integer) End sub sub Bar() SetGoo(GetGoo() + 1) End sub End class", "class C Property Goo as integer Get End Get Set(i as integer) End Set End Property sub Bar() Goo = Goo + 1 End sub End class", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestUpdateGetSet_SetReferenceInSetter() As Task Await TestInRegularAndScriptAsync( "class C function [||]GetGoo() as integer End function sub SetGoo(i as integer) SetGoo(i - 1) End sub End class", "class C Property Goo as integer Get End Get Set(i as integer) Goo = i - 1 End Set End Property End class", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestVirtualGetWithOverride_1() As Task Await TestInRegularAndScriptAsync( "class C protected overridable function [||]GetGoo() as integer End function End class class D inherits C protected overrides function GetGoo() as integer End function End class", "class C protected overridable ReadOnly Property Goo as integer Get End Get End Property End class class D inherits C protected overrides ReadOnly Property Goo as integer Get End Get End Property End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestVirtualGetWithOverride_2() As Task Await TestInRegularAndScriptAsync( "class C protected overridable function [||]GetGoo() as integer End function End class class D inherits C protected overrides function GetGoo() as integer return mybase.GetGoo() End function End class", "class C protected overridable ReadOnly Property Goo as integer Get End Get End Property End class class D inherits C protected overrides ReadOnly Property Goo as integer Get return mybase.Goo End Get End Property End class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestWithPartialClasses() As Task Await TestInRegularAndScriptAsync( "partial class C function [||]GetGoo() as integer End function End class partial class C sub SetGoo(i as integer) End sub End class", "partial class C Property Goo as integer Get End Get Set(i as integer) End Set End Property End class partial class C End class", index:=1) End Function <WorkItem(14327, "https://github.com/dotnet/roslyn/issues/14327")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestUpdateChainedGet1() As Task Await TestInRegularAndScriptAsync( " public class Goo public sub Goo() dim v = GetValue().GetValue() end sub Public Function [||]GetValue() As Goo End Function end class", " public class Goo public sub Goo() dim v = Value.Value end sub Public ReadOnly Property Value As Goo Get End Get End Property end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)> Public Async Function TestIndentation() As Task Await TestInRegularAndScriptAsync( "class C Public Function [||]GetProp() As Integer dim count = 0 for each x in y count = count + z next return count End Function end class", "class C Public ReadOnly Property Prop As Integer Get dim count = 0 for each x in y count = count + z next return count End Get End Property end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestInterfaceImplementation() As Task Await TestInRegularAndScriptAsync( "Interface IGoo Function [||]GetGoo() As Integer End Interface Class C Implements IGoo Private _Goo As Integer Public Function GetGoo() As Integer Implements IGoo.GetGoo Return _Goo End Function End Class", "Interface IGoo ReadOnly Property Goo As Integer End Interface Class C Implements IGoo Private _Goo As Integer Public ReadOnly Property Goo As Integer Implements IGoo.Goo Get Return _Goo End Get End Property End Class") End Function <WorkItem(443523, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=443523")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestSystemObjectMetadataOverride() As Task Await TestMissingAsync( "class C public overrides function [||]ToString() as string End function End class") End Function <WorkItem(443523, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=443523")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)> Public Async Function TestMetadataOverride() As Task Await TestInRegularAndScriptAsync( "class C inherits system.type public overrides function [||]GetArrayRank() as integer End function End class", "class C inherits system.type public overrides ReadOnly Property {|Warning:ArrayRank|} as integer Get End Get End Property End class") End Function End Class End Namespace
abock/roslyn
src/EditorFeatures/VisualBasicTest/CodeActions/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.vb
Visual Basic
mit
21,320
 ''Code from http://web.archive.org/web/20080506103924/http://www.flawlesscode.com/post/2008/02/Enforcing-single-instance-with-argument-passing.aspx ''' <summary> ''' Holds a list of arguments given to an application at startup. ''' </summary> Public Class ArgumentsReceivedEventArgs Inherits EventArgs Public Property Args() As [String]() Get Return m_Args End Get Set m_Args = Value End Set End Property Private m_Args As [String]() End Class
n0ix/SFDL.NET
SFDL.NET 3/Classes/SingleInstance/ArgumentsReceivedEventArgs.vb
Visual Basic
mit
522
Imports Com.Aspose.Storage.Api Imports Com.Aspose.Barcode.Api Imports Com.Aspose.Barcode.Model Namespace GeneratingSaving.CloudStorage Class GenerateBarcodewithAppropriateCodeTextLocation Public Shared Sub Run() 'ExStart:1 'Instantiate Aspose Storage Cloud API SDK Dim storageApi As New StorageApi(Common.APP_KEY, Common.APP_SID, Common.BASEPATH) 'Instantiate Aspose BarCode Cloud API SDK Dim barcodeApi As New BarcodeApi(Common.APP_KEY, Common.APP_SID, Common.BASEPATH) 'Set the barcode file name created on server Dim name As [String] = "sample-barcode" 'Set Text to encode inside barcode Dim text As [String] = "AsposeBarCode" 'Set Barcode Symbology Dim type As [String] = "Code128" 'Set Generated Barcode Image Format Dim format As [String] = "png" 'Set Resolution along X and Y in dpi Dim resolutionX As System.Nullable(Of Single) = Nothing Dim resolutionY As System.Nullable(Of Single) = Nothing 'Set Width and Height of barcode unit Dim dimensionX As System.Nullable(Of Single) = Nothing Dim dimensionY As System.Nullable(Of Single) = Nothing 'Set Location, Measurement of the code Dim codeLocation As [String] = "Above" Dim grUnit As [String] = "mm" 'Set if barcode's size will be updated automatically Dim autoSize As [String] = "true" 'Height of the bar Dim barHeight As System.Nullable(Of Single) = Nothing 'Set height, Width and quality of the image Dim imageHeight As System.Nullable(Of Single) = Nothing Dim imageWidth As System.Nullable(Of Single) = Nothing Dim imageQuality As [String] = "default" 'Set Angle of barcode orientation Dim rotAngle As System.Nullable(Of Single) = Nothing 'Set Margin of image border Dim topMargin As System.Nullable(Of Single) = Nothing Dim bottomMargin As System.Nullable(Of Single) = Nothing Dim leftMargin As System.Nullable(Of Single) = Nothing Dim rightMargin As System.Nullable(Of Single) = Nothing 'Set if checksum will be added to barcode image Dim enableChecksum As [String] = "" 'Set 3rd party cloud storage server (if any) Dim storage As [String] = "" 'Set folder location at cloud storage Dim folder As [String] = "" 'Set local file (if any) Dim file As Byte() = Nothing Try 'invoke Aspose.BarCode Cloud SDK API to generate barcode with appropriate code text location and put in cloud storage Dim apiResponse As SaaSposeResponse = barcodeApi.PutBarcodeGenerateFile(name, text, type, format, resolutionX, resolutionY, _ dimensionX, dimensionY, codeLocation, grUnit, autoSize, barHeight, _ imageHeight, imageWidth, imageQuality, rotAngle, topMargin, bottomMargin, _ leftMargin, rightMargin, enableChecksum, storage, folder, file) If apiResponse IsNot Nothing Then 'download generated barcode from cloud storage Dim storageRes As Com.Aspose.Storage.Model.ResponseMessage = storageApi.GetDownload(name, Nothing, Nothing) System.IO.File.WriteAllBytes(Common.OUTFOLDER + name + "." + format, storageRes.ResponseStream) Console.WriteLine("Generate Barcode with Appropriate Code Text Location, Done!") End If Catch ex As Exception Console.WriteLine("error:" + ex.Message + vbLf + ex.StackTrace) End Try 'ExEnd:1 End Sub End Class End Namespace
farooqsheikhpk/Aspose.BarCode-for-Cloud
Examples/DotNET/VisualBasic/GeneratingSaving/CloudStorage/GenerateBarcodewithAppropriateCodeTextLocation.vb
Visual Basic
mit
3,946