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
|
|---|---|---|---|---|---|
Imports mzkit.DockSample
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class frmSearchList
Inherits ToolWindow
'Form 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()
Me.components = New System.ComponentModel.Container()
Me.Label2 = New System.Windows.Forms.Label()
Me.ListBox1 = New System.Windows.Forms.ListBox()
Me.ContextMenuStrip1 = New System.Windows.Forms.ContextMenuStrip(Me.components)
Me.ShowXICToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
Me.ShowSummaryMatrixToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
Me.ContextMenuStrip1.SuspendLayout()
Me.SuspendLayout()
'
'Label2
'
Me.Label2.Dock = System.Windows.Forms.DockStyle.Top
Me.Label2.Location = New System.Drawing.Point(0, 0)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(800, 18)
Me.Label2.TabIndex = 3
Me.Label2.Text = "No Feature At Here!"
Me.Label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'ListBox1
'
Me.ListBox1.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.ListBox1.ContextMenuStrip = Me.ContextMenuStrip1
Me.ListBox1.Dock = System.Windows.Forms.DockStyle.Fill
Me.ListBox1.Font = New System.Drawing.Font("微软雅黑", 10.5!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.ListBox1.FormattingEnabled = True
Me.ListBox1.ItemHeight = 20
Me.ListBox1.Items.AddRange(New Object() {"n/a"})
Me.ListBox1.Location = New System.Drawing.Point(0, 18)
Me.ListBox1.Name = "ListBox1"
Me.ListBox1.Size = New System.Drawing.Size(800, 397)
Me.ListBox1.TabIndex = 2
'
'ContextMenuStrip1
'
Me.ContextMenuStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ShowXICToolStripMenuItem, Me.ShowSummaryMatrixToolStripMenuItem})
Me.ContextMenuStrip1.Name = "ContextMenuStrip1"
Me.ContextMenuStrip1.Size = New System.Drawing.Size(207, 48)
'
'ShowXICToolStripMenuItem
'
Me.ShowXICToolStripMenuItem.Name = "ShowXICToolStripMenuItem"
Me.ShowXICToolStripMenuItem.Size = New System.Drawing.Size(206, 22)
Me.ShowXICToolStripMenuItem.Text = "Show XIC"
'
'ShowSummaryMatrixToolStripMenuItem
'
Me.ShowSummaryMatrixToolStripMenuItem.Name = "ShowSummaryMatrixToolStripMenuItem"
Me.ShowSummaryMatrixToolStripMenuItem.Size = New System.Drawing.Size(206, 22)
Me.ShowSummaryMatrixToolStripMenuItem.Text = "Show Summary Matrix"
'
'frmSearchList
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 12.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(800, 415)
Me.Controls.Add(Me.ListBox1)
Me.Controls.Add(Me.Label2)
Me.Name = "frmSearchList"
Me.Text = "Form1"
Me.ContextMenuStrip1.ResumeLayout(False)
Me.ResumeLayout(False)
End Sub
Friend WithEvents Label2 As Label
Friend WithEvents ListBox1 As ListBox
Friend WithEvents ContextMenuStrip1 As ContextMenuStrip
Friend WithEvents ShowXICToolStripMenuItem As ToolStripMenuItem
Friend WithEvents ShowSummaryMatrixToolStripMenuItem As ToolStripMenuItem
End Class
|
xieguigang/MassSpectrum-toolkits
|
src/mzkit/mzkit/pages/dockWindow/explorer/frmSearchList.Designer.vb
|
Visual Basic
|
mit
| 4,192
|
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("Task3")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Microsoft")>
<Assembly: AssemblyProduct("Task3")>
<Assembly: AssemblyCopyright("Copyright © Microsoft 2013")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("d26899d4-549b-427c-9234-84a2ccffd7ba")>
' 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")>
|
Ico093/TelerikAcademy
|
CSS/Exams/CSS-February-2013-Variant-1/Variant1/Task3/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,145
|
Imports RibbonLib
Imports RibbonLib.Controls
Imports RibbonLib.Controls.Events
Imports RibbonLib.Interop
Namespace _06_ComboBox
Public Enum RibbonMarkupCommands As UInteger
cmdButtonDropA = 1008
cmdButtonDropB = 1009
cmdButtonDropC = 1010
cmdButtonDropD = 1011
cmdButtonDropE = 1012
cmdButtonDropF = 1013
cmdTabDrop = 1014
cmdGroupDrop = 1015
cmdGroupMore = 1017
cmdComboBox1 = 1018
cmdComboBox2 = 1019
cmdTabSecond = 1020
cmdGroupSecond = 1021
cmdComboBox3 = 1022
End Enum
Partial Public Class Form1
Inherits Form
Private _buttonDropA As RibbonButton
Private _buttonDropB As RibbonButton
Private _buttonDropC As RibbonButton
Private _buttonDropD As RibbonButton
Private _buttonDropE As RibbonButton
Private _buttonDropF As RibbonButton
Private _comboBox1 As RibbonComboBox
Private _comboBox2 As RibbonComboBox
Private _comboBox3 As RibbonComboBox
Private _uiCollectionChangedEvent As UICollectionChangedEvent
Public Sub New()
InitializeComponent()
_buttonDropA = New RibbonButton(_ribbon, CUInt(RibbonMarkupCommands.cmdButtonDropA))
_buttonDropB = New RibbonButton(_ribbon, CUInt(RibbonMarkupCommands.cmdButtonDropB))
_buttonDropC = New RibbonButton(_ribbon, CUInt(RibbonMarkupCommands.cmdButtonDropC))
_buttonDropD = New RibbonButton(_ribbon, CUInt(RibbonMarkupCommands.cmdButtonDropD))
_buttonDropE = New RibbonButton(_ribbon, CUInt(RibbonMarkupCommands.cmdButtonDropE))
_buttonDropF = New RibbonButton(_ribbon, CUInt(RibbonMarkupCommands.cmdButtonDropF))
_comboBox1 = New RibbonComboBox(_ribbon, CUInt(RibbonMarkupCommands.cmdComboBox1))
_comboBox2 = New RibbonComboBox(_ribbon, CUInt(RibbonMarkupCommands.cmdComboBox2))
_comboBox3 = New RibbonComboBox(_ribbon, CUInt(RibbonMarkupCommands.cmdComboBox3))
_uiCollectionChangedEvent = New UICollectionChangedEvent()
AddHandler _buttonDropA.ExecuteEvent, AddressOf _buttonDropA_ExecuteEvent
AddHandler _buttonDropB.ExecuteEvent, AddressOf _buttonDropB_ExecuteEvent
AddHandler _buttonDropC.ExecuteEvent, AddressOf _buttonDropC_ExecuteEvent
AddHandler _buttonDropD.ExecuteEvent, AddressOf _buttonDropD_ExecuteEvent
AddHandler _buttonDropE.ExecuteEvent, AddressOf _buttonDropE_ExecuteEvent
AddHandler _buttonDropF.ExecuteEvent, AddressOf _buttonDropF_ExecuteEvent
InitComboBoxes()
End Sub
Private Sub _buttonDropA_ExecuteEvent(ByVal sender As Object, ByVal e As ExecuteEventArgs)
' get selected item index from combo box 1
Dim selectedItemIndex As UInteger = _comboBox1.SelectedItem
If selectedItemIndex = Constants.UI_Collection_InvalidIndex Then
MessageBox.Show("No item is selected in simple combo")
Else
Dim selectedItem As Object
_comboBox1.ItemsSource.GetItem(selectedItemIndex, selectedItem)
Dim uiItem As IUISimplePropertySet = CType(selectedItem, IUISimplePropertySet)
Dim itemLabel As PropVariant
uiItem.GetValue(RibbonProperties.Label, itemLabel)
MessageBox.Show("Selected item in simple combo is: " & CStr(itemLabel.Value))
End If
End Sub
Private Sub _buttonDropB_ExecuteEvent(ByVal sender As Object, ByVal e As ExecuteEventArgs)
' get string value from combo box 2
Dim stringValue As String = _comboBox2.StringValue
MessageBox.Show("String value in advanced combo is: " & stringValue)
End Sub
Private Sub _buttonDropC_ExecuteEvent(ByVal sender As Object, ByVal e As ExecuteEventArgs)
' enumerate over items
Dim itemsSource As IEnumUnknown = CType(_comboBox1.ItemsSource, IEnumUnknown)
itemsSource.Reset()
Dim items(0) As Object
Dim fetchedItem As UInteger
Do While itemsSource.Next(1, items, fetchedItem) = HRESULT.S_OK
Dim uiItem As IUISimplePropertySet = CType(items(0), IUISimplePropertySet)
Dim itemLabel As PropVariant
uiItem.GetValue(RibbonProperties.Label, itemLabel)
MessageBox.Show("Label = " & CStr(itemLabel.Value))
Loop
End Sub
Private Sub _buttonDropD_ExecuteEvent(ByVal sender As Object, ByVal e As ExecuteEventArgs)
_uiCollectionChangedEvent.Attach(_comboBox1.ItemsSource)
AddHandler _uiCollectionChangedEvent.ChangedEvent, AddressOf _uiCollectionChangedEvent_ChangedEvent
End Sub
Private Sub _buttonDropE_ExecuteEvent(ByVal sender As Object, ByVal e As ExecuteEventArgs)
Dim itemsSource1 As IUICollection = _comboBox1.ItemsSource
Dim count As UInteger
itemsSource1.GetCount(count)
count += 1
itemsSource1.Add(New GalleryItemPropertySet() With {.Label = "Label " & count.ToString(), .CategoryID = Constants.UI_Collection_InvalidIndex})
End Sub
Private Sub _buttonDropF_ExecuteEvent(ByVal sender As Object, ByVal e As ExecuteEventArgs)
RemoveHandler _uiCollectionChangedEvent.ChangedEvent, AddressOf _uiCollectionChangedEvent_ChangedEvent
_uiCollectionChangedEvent.Detach()
End Sub
Private Sub _uiCollectionChangedEvent_ChangedEvent(ByVal sender As Object, ByVal e As UICollectionChangedEventArgs)
MessageBox.Show("Got ChangedEvent. Action = " & e.Action.ToString())
End Sub
Private Sub InitComboBoxes()
_comboBox1.RepresentativeString = "Label 1"
_comboBox2.RepresentativeString = "XXXXXXXXXXX"
_comboBox3.RepresentativeString = "XXXXXXXXXXX"
_comboBox1.Label = "Simple Combo"
_comboBox2.Label = "Advanced Combo"
_comboBox3.Label = "Another Combo"
AddHandler _comboBox1.ItemsSourceReady, AddressOf _comboBox1_ItemsSourceReady
AddHandler _comboBox2.ItemsSourceReady, AddressOf _comboBox2_CategoriesReady
AddHandler _comboBox2.ItemsSourceReady, AddressOf _comboBox2_ItemsSourceReady
AddHandler _comboBox3.ItemsSourceReady, AddressOf _comboBox3_ItemsSourceReady
End Sub
Private Sub _comboBox1_ItemsSourceReady()
' set combobox1 items
Dim itemsSource1 As IUICollection = _comboBox1.ItemsSource
itemsSource1.Clear()
itemsSource1.Add(New GalleryItemPropertySet() With {.Label = "Label 1", .CategoryID = Constants.UI_Collection_InvalidIndex})
itemsSource1.Add(New GalleryItemPropertySet() With {.Label = "Label 2", .CategoryID = Constants.UI_Collection_InvalidIndex})
itemsSource1.Add(New GalleryItemPropertySet() With {.Label = "Label 3", .CategoryID = Constants.UI_Collection_InvalidIndex})
End Sub
Private Sub _comboBox2_CategoriesReady()
' set _comboBox2 categories
Dim categories2 As IUICollection = _comboBox2.Categories
categories2.Clear()
categories2.Add(New GalleryItemPropertySet() With {.Label = "Category 1", .CategoryID = 1})
categories2.Add(New GalleryItemPropertySet() With {.Label = "Category 2", .CategoryID = 2})
End Sub
Private Sub _comboBox2_ItemsSourceReady()
' set _comboBox2 items
Dim itemsSource2 As IUICollection = _comboBox2.ItemsSource
itemsSource2.Clear()
itemsSource2.Add(New GalleryItemPropertySet() With {.Label = "Label 1", .CategoryID = 1})
itemsSource2.Add(New GalleryItemPropertySet() With {.Label = "Label 2", .CategoryID = 1})
itemsSource2.Add(New GalleryItemPropertySet() With {.Label = "Label 3", .CategoryID = 2})
End Sub
Private Sub _comboBox3_ItemsSourceReady()
' set combobox3 items
Dim itemsSource3 As IUICollection = _comboBox3.ItemsSource
itemsSource3.Clear()
itemsSource3.Add(New GalleryItemPropertySet() With {.Label = "Label 1", .CategoryID = Constants.UI_Collection_InvalidIndex})
itemsSource3.Add(New GalleryItemPropertySet() With {.Label = "Label 2", .CategoryID = Constants.UI_Collection_InvalidIndex})
itemsSource3.Add(New GalleryItemPropertySet() With {.Label = "Label 3", .CategoryID = Constants.UI_Collection_InvalidIndex})
End Sub
End Class
End Namespace
|
joergkrause/netrix
|
NetrixDemo/RibbonLib/Samples/VB/06-ComboBox/Form1.vb
|
Visual Basic
|
mit
| 8,076
|
Imports System.Xml
Namespace Utility
' NAME : Xml
' DATE CREATED : 03/11/11
' MOD HISTORY :
''' <summary>
''' Xml Utility class.
''' </summary>
'''
Public Class Xml
#Region "Public Static Methods"
' NAME : XmlDocToString
' DATE CREATED : 03/11/11
' MOD HISTORY :
''' <summary>
''' Convert XmlDocument to raw XML string.
''' </summary>
'''
Public Shared Function XmlDocToString(ByVal currentXmlDocument As XmlDocument) As String
Dim myStringWriter As New System.IO.StringWriter
Dim myXmlWriter As New System.Xml.XmlTextWriter(myStringWriter)
currentXmlDocument.WriteTo(myXmlWriter)
Return myStringWriter.ToString()
End Function
#End Region
End Class
End Namespace
|
IDMI-NET/EmmaDotNet-Remote
|
Components/IDMI.Core/Utility/Xml.vb
|
Visual Basic
|
mit
| 866
|
Namespace Ribbons.View.Toolbars
Public Class TransmittalSearchResults
Inherits RibbonButtonBase
Public Sub New()
_Image = ""
_Order = 1
_Text = "Transmittal Search Results"
_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/View/Toolbars/TransmittalSearchResults.vb
|
Visual Basic
|
mit
| 442
|
Module Module1
Private _arrCategoria As New List(Of categoria)
Public Property arrCategorias() As List(Of categoria)
Get
Return _arrCategoria
End Get
Set(ByVal value As List(Of categoria))
_arrCategoria = value
End Set
End Property
Sub Main()
Dim tipoRol As Byte = 1
While True
If (login(tipoRol)) Then
If (tipoRol = 1) Then
mostrarMenuAdministrador()
Else
mostrarMenuVendedor()
End If
End If
End While
End Sub
Public Sub agregarCategoria()
Dim continuar As String = "s"
Do While continuar = "s"
Console.Clear()
Console.WriteLine("" & vbNewLine)
Console.WriteLine(vbTab & vbTab & vbTab & "==========================================")
Console.WriteLine(vbTab & vbTab & vbTab & "| MANTENIMIENTO DE CATEGORIA |")
Console.WriteLine(vbTab & vbTab & vbTab & "==========================================" & vbNewLine)
Dim objCategoria As New categoria()
Do
If (objCategoria.existeId()) Then
Console.WriteLine(vbTab & vbTab & vbTab & "Una categoría con dicho Id ya ha sido ingresada")
End If
Console.Write(vbTab & vbTab & vbTab & "Id: ")
objCategoria.Id = Console.ReadLine()
Loop While (objCategoria.existeId())
Console.Write(vbTab & vbTab & vbTab & "Nombre : ")
objCategoria.Nombre = Console.ReadLine()
objCategoria.GuardarCategoria()
Console.Write(vbTab & vbTab & vbTab & "Categoría guardada exitosamente" & vbNewLine & vbNewLine)
arrCategorias.Add(objCategoria)
Console.Write(vbTab & vbTab & vbTab & "¿Guardar otra categoría? [s/n]: ")
continuar = Console.ReadLine()
Loop
End Sub
Public Sub EditarCategoria()
Dim categoriaTmp As New categoria()
categoriaTmp.MostrarCategoria()
Console.Write(vbTab & vbTab & vbTab & "Ingrese El Id de Categoria: ")
categoriaTmp.Id = Console.ReadLine()
If categoriaTmp.existeId() Then
Console.Write(vbTab & vbTab & vbTab & "Ingrese el nuevo nombre de la Categoria: ")
categoriaTmp.Nombre = Console.ReadLine()
categoriaTmp.modificarCategoria()
Console.ReadLine()
End If
End Sub
Public Sub agregarProducto()
Dim continuar As String = "s"
Do While continuar = "s"
Console.Clear()
Console.WriteLine("" & vbNewLine)
Console.WriteLine(vbTab & vbTab & vbTab & "==========================================")
Console.WriteLine(vbTab & vbTab & vbTab & "| MANTENIMIENTO DE CATEGORIA |")
Console.WriteLine(vbTab & vbTab & vbTab & "==========================================" & vbNewLine)
Dim objArticulo As New articulo()
Console.Write(vbTab & vbTab & vbTab & "Id: ")
objArticulo.Id = Console.ReadLine()
Console.Write(vbTab & vbTab & vbTab & "Nombre : ")
objArticulo.Nombre = Console.ReadLine()
Console.Write(vbTab & vbTab & vbTab & "Marca : ")
objArticulo.Marca = Console.ReadLine()
Console.Write(vbTab & vbTab & vbTab & "Modelo : ")
objArticulo.Modelo = Console.ReadLine()
Console.Write(vbTab & vbTab & vbTab & "Precio : ")
objArticulo.Precio = Console.ReadLine()
Console.Write(vbTab & vbTab & vbTab & "Stock : ")
objArticulo.Stock = Console.ReadLine()
Console.Write(vbTab & vbTab & vbTab & "Aplica IVA [s/n] : ")
Dim input As String = Console.ReadLine()
objArticulo.AplicaIva = IIf(input = "s", True, False)
Console.Write(vbTab & vbTab & vbTab & "Descripción : ")
objArticulo.Descripcion = Console.ReadLine()
Console.Write(vbTab & vbTab & vbTab & "Categoría : ")
objArticulo.Categoria.Id = Console.ReadLine()
objArticulo.GuardarArticulo()
Console.Write(vbTab & vbTab & vbTab & "Artículo guardado exitosamente" & vbNewLine & vbNewLine)
Console.Write(vbTab & vbTab & vbTab & "¿Guardar otro artículo? [s/n]: ")
continuar = Console.ReadLine()
Loop
End Sub
Public Sub agregarAdministrador()
Dim continuar As String = "s"
Do While continuar = "s"
Console.Clear()
Console.WriteLine("" & vbNewLine)
Console.WriteLine(vbTab & vbTab & vbTab & "==========================================")
Console.WriteLine(vbTab & vbTab & vbTab & "| MANTENIMIENTO DE ADMINISTRADORES |")
Console.WriteLine(vbTab & vbTab & vbTab & "==========================================" & vbNewLine)
Dim administradorNuevo As administrador = New administrador
Console.Write(vbTab & vbTab & vbTab & "Ingrese Id: ")
administradorNuevo.Id = Console.ReadLine
Console.Write(vbTab & vbTab & vbTab & "Ingrese Nombre: ")
administradorNuevo.Nombre = Console.ReadLine
Console.Write(vbTab & vbTab & vbTab & "Ingrese Apellido: ")
administradorNuevo.Apellido = Console.ReadLine
Console.Write(vbTab & vbTab & vbTab & "Ingrese Cédula: ")
administradorNuevo.Cedula = Console.ReadLine
Console.Write(vbTab & vbTab & vbTab & "Ingrese Email: ")
administradorNuevo.Email = Console.ReadLine
Console.Write(vbTab & vbTab & vbTab & "Ingrese nombre User: ")
administradorNuevo.Usuario = Console.ReadLine
Console.Write(vbTab & vbTab & vbTab & "Ingrese Password: ")
administradorNuevo.Clave = Console.ReadLine
administradorNuevo.GuardarEmpleado()
Console.Write("" & vbNewLine)
Console.Write(vbTab & vbTab & vbTab & "Administrador registrado exitosamente" & vbNewLine & vbNewLine)
Console.Write(vbTab & vbTab & vbTab & "¿Registrar otro Administrador? [s/n]: ")
continuar = Console.ReadLine()
Loop
End Sub
Public Sub agregarVendedor()
Dim continuar As String = "s"
Do While continuar = "s"
Console.Clear()
Console.WriteLine("" & vbNewLine)
Console.WriteLine(vbTab & vbTab & vbTab & "==========================================")
Console.WriteLine(vbTab & vbTab & vbTab & "| MANTENIMIENTO DE VENDEDORES |")
Console.WriteLine(vbTab & vbTab & vbTab & "==========================================" & vbNewLine)
Dim empleadoNuevo As empleado = New empleado
Console.Write(vbTab & vbTab & vbTab & "Ingrese Id: ")
empleadoNuevo.Id = Console.ReadLine
Console.Write(vbTab & vbTab & vbTab & "Ingrese Nombre: ")
empleadoNuevo.Nombre = Console.ReadLine
Console.Write(vbTab & vbTab & vbTab & "Ingrese Apellido: ")
empleadoNuevo.Apellido = Console.ReadLine
Console.Write(vbTab & vbTab & vbTab & "Ingrese Cédula: ")
empleadoNuevo.Cedula = Console.ReadLine
Console.Write(vbTab & vbTab & vbTab & "Ingrese Email: ")
empleadoNuevo.Email = Console.ReadLine
Console.Write(vbTab & vbTab & vbTab & "Ingrese nombre User: ")
empleadoNuevo.Usuario = Console.ReadLine
Console.Write(vbTab & vbTab & vbTab & "Ingrese Password: ")
empleadoNuevo.Clave = Console.ReadLine
empleadoNuevo.GuardarEmpleado()
Console.Write("" & vbNewLine)
Console.Write(vbTab & vbTab & vbTab & "Vendedor registrado exitosamente" & vbNewLine & vbNewLine)
Console.Write(vbTab & vbTab & vbTab & "¿Registrar otro vendedor? [s/n]: ")
continuar = Console.ReadLine()
Loop
End Sub
Public Sub salir()
Console.WriteLine("FUNCION POR DEFINIR")
End Sub
Public Sub mostrarMenuAdministrador()
Dim opcion As String = String.Empty
While True
Console.Clear()
Console.WriteLine("" & vbNewLine)
Console.WriteLine(vbTab & vbTab & vbTab & "==============================")
Console.WriteLine(vbTab & vbTab & vbTab & "| MENÚ ADMIN |")
Console.WriteLine(vbTab & vbTab & vbTab & "==============================" & vbNewLine)
Console.WriteLine(vbTab & vbTab & vbTab & "1.- Agregar Administrador" & vbNewLine)
Console.WriteLine(vbTab & vbTab & vbTab & "2.- Agregar Vendedor" & vbNewLine)
Console.WriteLine(vbTab & vbTab & vbTab & "3.- Agregar categoría" & vbNewLine)
Console.WriteLine(vbTab & vbTab & vbTab & "4.- Editar Categoría" & vbNewLine)
Console.WriteLine(vbTab & vbTab & vbTab & "5.- Agregar Producto" & vbNewLine)
Console.WriteLine(vbTab & vbTab & vbTab & "6.- Salir" & vbNewLine)
Console.Write(vbTab & vbTab & vbTab & "Escriba su opción: ")
opcion = Console.ReadLine()
Console.WriteLine(vbTab & "--------------------------------------------------------------" & vbNewLine)
Select Case opcion
Case 1
agregarAdministrador()
Case 2
agregarVendedor()
Case 3
agregarCategoria()
Case 4
EditarCategoria()
Case 5
agregarProducto()
Case 6
Exit While
Case Else
Console.WriteLine("Opción no existe. Escriba bien por favor.")
End Select
End While
End Sub
Public Sub buscarFactura()
Dim facturaABuscar As New factura()
Console.Clear()
Console.Write(vbTab & vbTab & vbTab & "Ingrese Id. la factura: ")
facturaABuscar.Id = Console.ReadLine()
facturaABuscar.BuscarFactura()
facturaABuscar.imprimirFactura()
End Sub
Public Sub Facturar()
'INGRESO DE LA CABECERA
'Dim provincia As New provincia()
Dim factura As New factura()
Console.Clear()
Console.WriteLine(vbTab & vbTab & vbTab & "==========================================")
Console.WriteLine(vbTab & vbTab & vbTab & "| Facturar |")
Console.WriteLine(vbTab & vbTab & vbTab & "==========================================" & vbNewLine)
Console.Write(vbTab & vbTab & vbTab & "Ingrese Id de la factura")
factura.Id = Console.ReadLine()
Console.Write(vbTab & vbTab & vbTab & "Ingrese número de factura: ")
factura.NumeroFactura = Console.ReadLine()
Console.Write(vbTab & vbTab & vbTab & "Ingrese Nombre del cliente: ")
factura.NombreCliente = Console.ReadLine()
Console.Write(vbTab & vbTab & vbTab & "Ingrese RUC del cliente: ")
factura.Ruc = Console.ReadLine()
Console.Write(vbTab & vbTab & vbTab & "Ingrese teléfono del cliente: ")
factura.Telefono = Console.ReadLine()
Console.Write(vbTab & vbTab & vbTab & "Ingrese provincia:")
factura.provincia = Console.ReadLine()
Console.Write(vbTab & vbTab & vbTab & "Ingrese dirección del cliente: ")
factura.Direccion = Console.ReadLine()
Console.Write(vbTab & vbTab & vbTab & "Ingrese fecha de emisión: ")
factura.FechaEmision = Console.ReadLine()
'INGRESO DE LOS DETALLES
Dim continuar As String = "s"
Do While continuar = "s"
factura.ElegirArticuloAFacturar()
'==========================================
Dim nuevoDetalle As New detalleFactura()
Console.Write(vbTab & vbTab & vbTab & "Ingrese Id del artículo: ")
Dim nuevoArticulo As New articulo
nuevoArticulo.Id = Console.ReadLine()
nuevoArticulo.Buscar()
nuevoDetalle.Descripcion = nuevoArticulo.Nombre
nuevoDetalle.PrecioUnit = nuevoArticulo.Precio
Console.Write(vbTab & vbTab & vbTab & "Ingrese cantidad: ")
nuevoDetalle.Cantidad = Console.ReadLine()
nuevoDetalle.Costo = nuevoArticulo.Precio * nuevoDetalle.Cantidad
If (factura.provincia.ToLower = "manabi" Or factura.provincia.ToLower = "esmeralda") Then
nuevoDetalle.Iva = nuevoDetalle.Costo * 0.12
Else
nuevoDetalle.Iva = nuevoDetalle.Costo * 0.14
End If
nuevoDetalle.articulo = nuevoArticulo
factura.Detalle.Add(nuevoDetalle)
'==================================
Console.WriteLine(vbTab & vbTab & vbTab & "Desea agregar más productor S o facturar N")
continuar = Console.ReadLine()
Loop
factura.TotalPagar = factura.CalcularTotal()
factura.GuardarFactura()
End Sub
Public Sub mostrarMenuVendedor()
Dim opcion As String = String.Empty
While True
Console.Clear()
Console.WriteLine("" & vbNewLine)
Console.WriteLine(vbTab & vbTab & vbTab & "==============================")
Console.WriteLine(vbTab & vbTab & vbTab & "| MENÚ VENDEDOR |")
Console.WriteLine(vbTab & vbTab & vbTab & "==============================" & vbNewLine)
Console.WriteLine(vbTab & vbTab & vbTab & "1.- Facturar" & vbNewLine)
Console.WriteLine(vbTab & vbTab & vbTab & "2.- Buscar Factura" & vbNewLine)
Console.WriteLine(vbTab & vbTab & vbTab & "3.- Salir" & vbNewLine)
Console.Write(vbTab & vbTab & vbTab & "Escriba su opción: ")
opcion = Console.ReadLine()
Console.WriteLine(vbTab & "--------------------------------------------------------------" & vbNewLine)
Select Case opcion
Case 1
Facturar()
Case 2
buscarFactura()
Case 3
Exit While
Case Else
Console.WriteLine("Opción no existe. Escriba bien.")
End Select
End While
End Sub
Public Function login(ByRef rol As Byte) As Boolean
Dim usuarioInput As String = String.Empty
Dim claveInput As String = String.Empty
Dim continua As String = "s"
While True
Console.Clear()
Console.WriteLine("" & vbNewLine)
Console.WriteLine(vbTab & vbTab & vbTab & "==============================")
Console.WriteLine(vbTab & vbTab & vbTab & "| LOGIN |")
Console.WriteLine(vbTab & vbTab & vbTab & "==============================" & vbNewLine)
Console.Write(vbTab & vbTab & vbTab & "Usuario: ")
usuarioInput = Console.ReadLine()
Console.Write(vbTab & vbTab & vbTab & "Clave: ")
claveInput = Console.ReadLine()
Console.WriteLine(vbTab & "--------------------------------------------------------------" & vbNewLine)
Dim objUsuario As New empleado()
objUsuario.Usuario = usuarioInput
objUsuario.Clave = claveInput
If (objUsuario.Login) Then
rol = objUsuario.TipoEmpleado
Return True
Else
Console.WriteLine(vbTab & "Usuario no existe, intente nuevamente." & vbNewLine)
End If
End While
Return False
End Function
End Module
|
Grupo4Proyecto/Proyecto-Visual-Primer-Parcial
|
ProyectoVB_parcial1/ProyectoFactura/Module1.vb
|
Visual Basic
|
mit
| 15,873
|
#Region "Microsoft.VisualBasic::ca1e2d8d2e0bc8aaf1fe0a2f3bf22421, src\mzmath\ms2_math-core\Spectra\Alignment\JaccardAlignment.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 JaccardAlignment
'
' Constructor: (+1 Overloads) Sub New
' Function: (+2 Overloads) GetScore
'
'
' /********************************************************************************/
#End Region
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Ms1
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Spectra.Xml
Imports Microsoft.VisualBasic.ComponentModel.Collection
Namespace Spectra
Public Class JaccardAlignment : Inherits AlignmentProvider
ReadOnly topSet As Integer
Public Sub New(mzwidth As Tolerance, intocutoff As LowAbundanceTrimming, Optional topSet As Integer = 5)
MyBase.New(mzwidth, intocutoff)
Me.topSet = topSet
End Sub
Public Overrides Function GetScore(a As ms2(), b As ms2()) As Double
Return GlobalAlignment.JaccardIndex(a, b, mzwidth, topSet)
End Function
Public Overrides Function GetScore(alignment() As SSM2MatrixFragment) As (forward As Double, reverse As Double)
Static NA As Index(Of String) = {"NA", "n/a", "NaN"}
Dim intersect As Integer = Aggregate a As SSM2MatrixFragment
In alignment
Where Not a.da Like NA
Into Sum(1)
Dim union As Integer = alignment.Length
Dim J As Double = intersect / union
Return (J, J)
End Function
End Class
End Namespace
|
xieguigang/MassSpectrum-toolkits
|
src/mzmath/ms2_math-core/Spectra/Alignment/JaccardAlignment.vb
|
Visual Basic
|
mit
| 3,115
|
Public Class WaitF
End Class
|
krispo/chart-grid-control
|
ChartGridControl/WaitF.vb
|
Visual Basic
|
mit
| 32
|
Namespace Core
''' <summary></summary>
''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated>
''' <generator-date>03/02/2014 13:08:43</generator-date>
''' <generator-functions>1</generator-functions>
''' <generator-source>Athena\Athena\_Core\Generated\Instance.tt</generator-source>
''' <generator-template>Text-Templates\Classes\VB_Object.tt</generator-template>
''' <generator-version>1</generator-version>
<System.CodeDom.Compiler.GeneratedCode("Athena\Athena\_Core\Generated\Instance.tt", "1")> _
<System.Serializable()> _
Partial Public Class Instance
Inherits System.Object
Implements System.IComparable
Implements System.IFormattable
Implements System.ComponentModel.INotifyPropertyChanged
#Region " Public Constructors "
''' <summary>Default Constructor</summary>
Public Sub New()
MyBase.New()
m_Created = DateTime.Now()
End Sub
''' <summary>Parametered Constructor (1 Parameters)</summary>
Public Sub New( _
ByVal _Id As System.Int64 _
)
MyBase.New()
m_Id = _Id
m_Created = DateTime.Now()
End Sub
''' <summary>Parametered Constructor (2 Parameters)</summary>
Public Sub New( _
ByVal _Id As System.Int64, _
ByVal _Option As System.Int32 _
)
MyBase.New()
m_Id = _Id
[Option] = _Option
m_Created = DateTime.Now()
End Sub
''' <summary>Parametered Constructor (3 Parameters)</summary>
Public Sub New( _
ByVal _Id As System.Int64, _
ByVal _Option As System.Int32, _
ByVal _Code As System.String _
)
MyBase.New()
m_Id = _Id
[Option] = _Option
Code = _Code
m_Created = DateTime.Now()
End Sub
''' <summary>Parametered Constructor (4 Parameters)</summary>
Public Sub New( _
ByVal _Id As System.Int64, _
ByVal _Option As System.Int32, _
ByVal _Code As System.String, _
ByVal _Created As System.DateTime _
)
MyBase.New()
m_Id = _Id
[Option] = _Option
Code = _Code
Created = _Created
End Sub
#End Region
#Region " Class Plumbing/Interface Code "
#Region " IComparable Implementation "
#Region " Public Methods "
''' <summary>Comparison Method</summary>
Public Overridable Function IComparable_CompareTo( _
ByVal value As System.Object _
) As System.Int32 Implements System.IComparable.CompareTo
Dim typed_Value As Instance = TryCast(value, Instance)
If typed_Value Is Nothing Then
Throw New ArgumentException(String.Format("Value is not of comparable type: {0}", value.GetType.Name), "Value")
Else
Dim return_Value As Integer = 0
return_Value = Created.CompareTo(typed_Value.Created)
If return_Value <> 0 Then Return return_Value
Return return_Value
End If
End Function
#End Region
#End Region
#Region " DbRetrievable Implementation "
#Region " Protected Methods "
''' <summary>This method should be overridden to provide custom validation logic.</summary>
Protected Overridable Function DbRetrievable_ValidateForSet() As Boolean
Return True
End Function
#End Region
Public Class All
Implements System.Collections.Generic.IEnumerable(Of Instance)
Implements System.Collections.Generic.IEnumerator(Of Instance)
Implements System.ComponentModel.ITypedList
#Region " Public Enums "
<Flags()> _
Public Enum Filters As System.Int64
ID = 1
[OPTION] = 2
CODE = 4
CREATED = 8
End Enum
#End Region
#Region " Private Variables "
''' <summary></summary>
''' <remarks></remarks>
Private IDX_INSTANCE_ID As System.Int32 = -1
''' <summary></summary>
''' <remarks></remarks>
Private IDX_INSTANCE_OPTION As System.Int32 = -1
''' <summary></summary>
''' <remarks></remarks>
Private IDX_INSTANCE_CODE As System.Int32 = -1
''' <summary></summary>
''' <remarks></remarks>
Private IDX_INSTANCE_CREATED As System.Int32 = -1
#End Region
#Region " Protected Variables "
''' <summary></summary>
''' <remarks></remarks>
Protected Cmd As System.Data.IDbCommand
''' <summary></summary>
''' <remarks></remarks>
Protected Rdr As System.Data.IDataReader
''' <summary></summary>
''' <remarks></remarks>
Protected Cur As Instance
''' <summary></summary>
''' <remarks></remarks>
Protected Ini As System.Boolean
''' <summary></summary>
''' <remarks></remarks>
Protected Idx As System.Int32
''' <summary></summary>
''' <remarks></remarks>
Protected Own As System.Int32 = System.Threading.Thread.CurrentThread.ManagedThreadId
#End Region
#Region " Protected Methods "
Protected Function Hydrate( _
ByVal reader As System.Data.IDataReader _
) As Instance
Return Hydrate(New Instance(), reader)
End Function
Protected Function Hydrate( _
ByRef value As Instance, _
ByVal reader As System.Data.IDataReader _
) As Instance
If Not reader.IsDBNull(IDX_INSTANCE_ID) Then _
value.m_Id = reader.GetInt64(IDX_INSTANCE_ID)
If Not reader.IsDBNull(IDX_INSTANCE_OPTION) Then _
value.Option = reader.GetInt32(IDX_INSTANCE_OPTION)
If Not reader.IsDBNull(IDX_INSTANCE_CODE) Then _
value.Code = reader.GetString(IDX_INSTANCE_CODE)
If Not reader.IsDBNull(IDX_INSTANCE_CREATED) Then _
value.Created = reader.GetDateTime(IDX_INSTANCE_CREATED)
Return value
End Function
#End Region
#Region " Public Constructors "
Public Sub New( _
ByVal _cmd As System.Data.IDbCommand _
)
MyBase.New()
Cmd = _cmd
End Sub
#End Region
#Region " IEnumerator Implementation "
Private ReadOnly Property GetCurrent_UnTyped() As Object Implements IEnumerator.Current
Get
Return Cur
End Get
End Property
Private ReadOnly Property GetCurrent_Typed() As Instance Implements IEnumerator(Of Instance).Current
Get
Return Cur
End Get
End Property
Private Function MoveNext() As Boolean Implements IEnumerator(Of Instance).MoveNext
If Not Ini Then Reset()
If Rdr.Read() Then
Cur = Hydrate(Rdr)
Idx += 1
Return True
Else
Cur = Nothing
Return False
End If
End Function
Private Sub Reset() Implements IEnumerator(Of Instance).Reset
If Not Rdr Is Nothing Then Rdr.Close()
If Cmd.Connection.State = System.Data.ConnectionState.Closed Then Cmd.Connection.Open()
Rdr = Cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
Idx = -1
IDX_INSTANCE_ID = rdr.GetOrdinal("Instance_Id")
If IDX_INSTANCE_ID < 0 Then Throw New Exception("Mapping For Field Not Correct: Instance_Id")
IDX_INSTANCE_OPTION = rdr.GetOrdinal("Instance_Option")
If IDX_INSTANCE_OPTION < 0 Then Throw New Exception("Mapping For Field Not Correct: Instance_Option")
IDX_INSTANCE_CODE = rdr.GetOrdinal("Instance_Code")
If IDX_INSTANCE_CODE < 0 Then Throw New Exception("Mapping For Field Not Correct: Instance_Code")
IDX_INSTANCE_CREATED = rdr.GetOrdinal("Instance_Created")
If IDX_INSTANCE_CREATED < 0 Then Throw New Exception("Mapping For Field Not Correct: Instance_Created")
Ini = True
End Sub
#End Region
#Region " IEnumerable Implementation "
Private Function GetEnumerator_UnTyped As IEnumerator Implements IEnumerable.GetEnumerator
Return GetEnumerator()
End Function
Private Function GetEnumerator As IEnumerator(Of Instance) Implements IEnumerable(Of Instance).GetEnumerator
If System.Threading.Thread.CurrentThread.ManagedThreadId = Own AndAlso Idx = -1 Then
Return Me
Else
Return New All(Cmd)
End If
End Function
#End Region
#Region " IDisposable Implementation "
Private Sub Dispose() Implements IEnumerator(Of Instance).Dispose
If Not Rdr Is Nothing Then Rdr.Close()
End Sub
#End Region
#Region " ITypedList Implementation "
Public Function GetItemProperties( _
ByVal listAccessors() As System.ComponentModel.PropertyDescriptor _
) As System.ComponentModel.PropertyDescriptorCollection _
Implements System.ComponentModel.ITypedList.GetItemProperties
Return System.ComponentModel.TypeDescriptor.GetProperties(GetType(Instance))
End Function
Public Function GetListName( _
ByVal listAccessors() As System.ComponentModel.PropertyDescriptor _
) As String _
Implements System.ComponentModel.ITypedList.GetListName
Return "Enumerable Collection of Instance"
End Function
#End Region
#Region " Public Shared Select Methods "
Protected Friend Shared Function [Select]( _
ByVal connection As System.Data.IDbConnection, _
ByVal query As String _
) As IEnumerable(Of Instance)
Return [Select](connection, query, _
CType(Nothing, System.Collections.Generic.KeyValuePair(Of System.String, System.Object)()))
End Function
Protected Friend Shared Function [Select]( _
ByVal connection As System.Data.IDbConnection, _
ByVal query As String, _
ByVal ParamArray parameters As System.Collections.Generic.KeyValuePair(Of System.String, System.Object)() _
) As IEnumerable(Of Instance)
Dim command As System.Data.IDbCommand = connection.CreateCommand()
If query.IndexOf(" ") > 0 Then command.CommandType = System.Data.CommandType.Text Else command.CommandType = System.Data.CommandType.StoredProcedure
command.CommandText = query
If Not parameters Is Nothing Then
For i As Integer = 0 To parameters.Length - 1
Dim param As System.Data.IDbDataParameter = command.CreateParameter()
param.ParameterName = parameters(i).Key
param.Value = parameters(i).Value
command.Parameters.Add(param)
Next
End If
Return New All(command)
End Function
Protected Friend Shared Function [Select]( _
ByVal command As System.Data.IDbCommand, _
ByVal ParamArray parameters As System.Data.IDbDataParameter() _
) As IEnumerable(Of Instance)
If Not parameters Is Nothing Then
For i As Integer = 0 To parameters.Length - 1
If parameters(i).Value Is Nothing AndAlso (parameters(i).Direction = System.Data.ParameterDirection.InputOutput _
OrElse parameters(i).Direction = System.Data.ParameterDirection.Input) Then parameters(i).Value = DBNull.Value
command.Parameters.Add(parameters(i))
Next
End If
Return New All(command)
End Function
#End Region
#Region " Public Shared Enumeration Methods "
Public Shared Function [Get]( _
ByVal connection As System.Data.IDbConnection _
) As IEnumerable(Of Instance)
Return [Get](connection, "tbl_Core_Instances")
End Function
Public Shared Function [Get]( _
ByVal connection As System.Data.IDbConnection, _
ByVal viewName As String _
) As IEnumerable(Of Instance)
Return [Select](connection, String.Format("SELECT * FROM {0}", viewName))
End Function
Public Shared Function Filter( _
ByVal connection As System.Data.IDbConnection, _
ByVal field As Filters, _
ByVal value As Object _
) As IEnumerable(Of Instance)
Return Filter(connection, field, New Object() {value})
End Function
Public Shared Function Filter( _
ByVal connection As System.Data.IDbConnection, _
ByVal fields As Filters, _
ByVal values As Object(), _
Optional ByVal condition_AND As Boolean = True _
) As IEnumerable(Of Instance)
Dim value_Index As Integer = 0
Dim parameter_Names As New System.Text.StringBuilder()
Dim parameter_Values As New System.Collections.Generic.List(Of System.Collections.Generic.KeyValuePair(Of System.String, System.Object))
Dim condition_Operator As String = " AND "
If Not condition_AND Then condition_Operator = " OR "
If (fields And 1) = 1 Then
If parameter_Names.Length > 0 Then parameter_Names.Append(condition_Operator)
parameter_Names.Append("(Instance_Id = ")
If connection.GetType Is GetType(System.Data.OleDb.OleDbConnection) Then
parameter_Names.Append("?)")
Else
parameter_Names.Append("@Id)")
End If
parameter_Values.Add(New System.Collections.Generic.KeyValuePair(Of System.String, System.Object)("Id", values(value_Index)))
value_Index += 1
End If
If (fields And 2) = 2 Then
If parameter_Names.Length > 0 Then parameter_Names.Append(condition_Operator)
parameter_Names.Append("(Instance_Option = ")
If connection.GetType Is GetType(System.Data.OleDb.OleDbConnection) Then
parameter_Names.Append("?)")
Else
parameter_Names.Append("@Option)")
End If
parameter_Values.Add(New System.Collections.Generic.KeyValuePair(Of System.String, System.Object)("Option", values(value_Index)))
value_Index += 1
End If
If (fields And 4) = 4 Then
If parameter_Names.Length > 0 Then parameter_Names.Append(condition_Operator)
If Not String.IsNullOrEmpty(CType(values(value_Index), System.String)) AndAlso CType(values(value_Index), System.String).Contains("*") Then
parameter_Names.Append("(Instance_Code LIKE ")
If connection.GetType Is GetType(System.Data.SqlClient.SqlConnection) Then values(value_Index) = CStr(values(value_Index)).Replace("*", "%") Else _
values(value_Index) = CStr(values(value_Index)).Replace("*", "")
Else
parameter_Names.Append("(Instance_Code = ")
End If
If connection.GetType Is GetType(System.Data.OleDb.OleDbConnection) Then
parameter_Names.Append("?)")
Else
parameter_Names.Append("@Code)")
End If
parameter_Values.Add(New System.Collections.Generic.KeyValuePair(Of System.String, System.Object)("Code", values(value_Index)))
value_Index += 1
End If
If (fields And 8) = 8 Then
If parameter_Names.Length > 0 Then parameter_Names.Append(condition_Operator)
parameter_Names.Append("(Instance_Created = ")
If connection.GetType Is GetType(System.Data.OleDb.OleDbConnection) Then
parameter_Names.Append("?)")
Else
parameter_Names.Append("@Created)")
End If
parameter_Values.Add(New System.Collections.Generic.KeyValuePair(Of System.String, System.Object)("Created", values(value_Index)))
value_Index += 1
End If
Return [Select](connection, String.Format("SELECT * FROM {0} WHERE (" & parameter_Names.ToString() & ")", "tbl_Core_Instances"), _
parameter_Values.ToArray())
End Function
#End Region
#Region " Public Shared Manipulation Methods "
Public Shared Function [Set]( _
ByVal connection As System.Data.IDbConnection, _
ByRef value As Instance _
) As Boolean
Return [Set](connection, value, "tbl_Core_Instances")
End Function
Public Shared Function [Set]( _
ByVal connection As System.Data.IDbConnection, _
ByRef value As Instance, _
ByVal tableName As String _
) As Boolean
If value Is Nothing Then Throw New ArgumentNullException("value")
If connection Is Nothing Then Throw New ArgumentNullException("connection")
If String.IsNullOrEmpty(tableName) Then Throw New ArgumentNullException("tableName")
If connection.State = System.Data.ConnectionState.Closed Then connection.Open()
Dim return_Value As Boolean = False
If value.DbRetrievable_ValidateForSet Then
Dim insert_New As Boolean = (value.Id <= 0)
If connection.GetType Is GetType(System.Data.OleDb.OleDbConnection) Then
Dim OLEDB_Proc As String
If insert_New Then
OLEDB_Proc = String.Format("INSERT INTO {0} (Instance_Option, Instance_Code, Instance_Created) VALUES (?, ?, ?)", tableName)
Else
OLEDB_Proc = String.Format("UPDATE {0} SET Instance_Option = ?, Instance_Code = ?, Instance_Created = ? WHERE (Instance_Id = ?)", tableName)
End If
Dim OLEDB_Comm As New System.Data.OleDb.OleDbCommand(OLEDB_Proc, CType(connection, System.Data.OleDb.OleDbConnection))
OLEDB_Comm.CommandType = System.Data.CommandType.Text
OLEDB_Comm.Parameters.Add(New System.Data.OleDb.OleDbParameter("Option", value.Option))
If String.IsNullOrEmpty(value.Code) Then
OLEDB_Comm.Parameters.Add(New System.Data.OleDb.OleDbParameter("Code", String.Empty))
Else
OLEDB_Comm.Parameters.Add(New System.Data.OleDb.OleDbParameter("Code", value.Code))
End If
OLEDB_Comm.Parameters.Add(New System.Data.OleDb.OleDbParameter("Created", value.Created.Date))
If Not insert_New Then OLEDB_Comm.Parameters.Add(New System.Data.OleDb.OleDbParameter("Id", value.Id))
return_Value = (OLEDB_Comm.ExecuteNonQuery() = 1)
If insert_New Then
Dim OLEDB_Identity As New System.Data.OleDb.OleDbCommand("SELECT @@IDENTITY", CType(connection, System.Data.OleDb.OleDbConnection))
OLEDB_Identity.CommandType = System.Data.CommandType.Text
value.m_Id = CType(OLEDB_Identity.ExecuteScalar(), System.Int64)
End If
ElseIf connection.GetType Is GetType(System.Data.SqlClient.SqlConnection) Then
Dim SQL_Proc As String
If insert_New Then
SQL_Proc = String.Format("INSERT INTO {0} (Instance_Option, Instance_Code, Instance_Created) VALUES (@Option, @Code, @Created); SELECT @Id = SCOPE_IDENTITY();", tableName)
Else
SQL_Proc = String.Format("UPDATE {0} SET Instance_Option = @Option, Instance_Code = @Code, Instance_Created = @Created WHERE (Instance_Id = @Id)", tableName)
End If
Dim SQL_Comm As New System.Data.SqlClient.SqlCommand(SQL_Proc, CType(connection, System.Data.SqlClient.SqlConnection))
SQL_Comm.CommandType = System.Data.CommandType.Text
Dim param_1 As New System.Data.SqlClient.SqlParameter("@Id", value.Id)
If insert_New Then param_1.Direction = System.Data.ParameterDirection.Output
SQL_Comm.Parameters.Add(param_1)
Dim param_2 As System.Data.SqlClient.SqlParameter
param_2 = New System.Data.SqlClient.SqlParameter("@Option", value.Option)
SQL_Comm.Parameters.Add(param_2)
Dim param_3 As System.Data.SqlClient.SqlParameter
param_3 = New System.Data.SqlClient.SqlParameter("@Code", value.Code)
SQL_Comm.Parameters.Add(param_3)
Dim param_4 As System.Data.SqlClient.SqlParameter
param_4 = New System.Data.SqlClient.SqlParameter("@Created", value.Created)
SQL_Comm.Parameters.Add(param_4)
return_Value = (SQL_Comm.ExecuteNonQuery() = 1)
If insert_New Then value.m_Id = CType(param_1.Value, System.Int64)
Else
Throw New NotImplementedException(String.Format("DB Connection of Type: {0} Not Yet Supported", connection.GetType.Name))
End If
End If
If connection.State = System.Data.ConnectionState.Open Then connection.Close()
Return return_Value
End Function
Public Shared Function [Create]( _
ByVal connection As System.Data.IDbConnection, _
ByVal _option as System.Int32, _
ByVal _code as System.String, _
ByVal _created as System.DateTime _
) As Boolean
Return [Create](connection, _option, _code, _created, "tbl_Core_Instances")
End Function
Public Shared Function [Create]( _
ByVal connection As System.Data.IDbConnection, _
ByVal _option as System.Int32, _
ByVal _code as System.String, _
ByVal _created as System.DateTime, _
ByVal tableName As String _
) As Boolean
If connection Is Nothing Then Throw New ArgumentNullException("connection")
If String.IsNullOrEmpty(tableName) Then Throw New ArgumentNullException("tableName")
If connection.State = System.Data.ConnectionState.Closed Then connection.Open()
Dim return_Value As Boolean = False
Dim value As New Instance()
value.Option = _option
value.Code = _code
value.Created = _created
If value.DbRetrievable_ValidateForSet Then
If connection.GetType Is GetType(System.Data.OleDb.OleDbConnection) Then
Dim OLEDB_Comm As New System.Data.OleDb.OleDbCommand(String.Format("INSERT INTO {0} (Instance_Option, Instance_Code, Instance_Created) VALUES (?, ?, ?)", tableName), CType(connection, System.Data.OleDb.OleDbConnection))
OLEDB_Comm.CommandType = System.Data.CommandType.Text
OLEDB_Comm.Parameters.Add(New System.Data.OleDb.OleDbParameter("Option", value.Option))
If String.IsNullOrEmpty(value.Code) Then
OLEDB_Comm.Parameters.Add(New System.Data.OleDb.OleDbParameter("Code", String.Empty))
Else
OLEDB_Comm.Parameters.Add(New System.Data.OleDb.OleDbParameter("Code", value.Code))
End If
OLEDB_Comm.Parameters.Add(New System.Data.OleDb.OleDbParameter("Created", value.Created.Date))
return_Value = (OLEDB_Comm.ExecuteNonQuery() = 1)
ElseIf connection.GetType Is GetType(System.Data.SqlClient.SqlConnection) Then
Dim SQL_Comm As New System.Data.SqlClient.SqlCommand(String.Format("INSERT INTO {0} (Instance_Option, Instance_Code, Instance_Created) VALUES (@Option, @Code, @Created); SELECT @Id = SCOPE_IDENTITY();", tableName), CType(connection, System.Data.SqlClient.SqlConnection))
SQL_Comm.CommandType = System.Data.CommandType.Text
Dim param_1 As System.Data.SqlClient.SqlParameter
param_1 = New System.Data.SqlClient.SqlParameter("@Option", value.Option)
SQL_Comm.Parameters.Add(param_1)
Dim param_2 As System.Data.SqlClient.SqlParameter
param_2 = New System.Data.SqlClient.SqlParameter("@Code", value.Code)
SQL_Comm.Parameters.Add(param_2)
Dim param_3 As System.Data.SqlClient.SqlParameter
param_3 = New System.Data.SqlClient.SqlParameter("@Created", value.Created)
SQL_Comm.Parameters.Add(param_3)
return_Value = (SQL_Comm.ExecuteNonQuery() = 1)
Else
Throw New NotImplementedException(String.Format("DB Connection of Type: {0} Not Yet Supported", connection.GetType.Name))
End If
End If
If connection.State = System.Data.ConnectionState.Open Then connection.Close()
Return return_Value
End Function
#End Region
#Region " Public Shared Identity Methods "
Public Shared Function [One]( _
ByVal connection As System.Data.IDbConnection, _
ByRef value As Instance _
) As Instance
Return [One](connection, value, "tbl_Core_Instances")
End Function
Public Shared Function [One]( _
ByVal connection As System.Data.IDbConnection, _
ByVal id As System.Int64 _
) As Instance
Return [One](connection, id, "tbl_Core_Instances")
End Function
Public Shared Function [One]( _
ByVal connection As System.Data.IDbConnection, _
ByRef value As Instance, _
ByVal viewName As String _
) As Instance
Return [One](connection, value.Id, viewName)
End Function
Public Shared Function [One]( _
ByVal connection As System.Data.IDbConnection, _
ByVal id As System.Int64, _
ByVal viewName As String _
) As Instance
If connection.GetType Is GetType(System.Data.OleDb.OleDbConnection) Then
Return System.Linq.Enumerable.FirstOrDefault([Select](connection, _
String.Format("SELECT * FROM {0} WHERE (Instance_Id = ?)", viewName), _
New System.Collections.Generic.KeyValuePair(Of System.String, System.Object)("Id", id)))
Else
Return System.Linq.Enumerable.FirstOrDefault([Select](connection, _
String.Format("SELECT * FROM {0} WHERE (Instance_Id = @Id)", viewName), _
New System.Collections.Generic.KeyValuePair(Of System.String, System.Object)("Id", id)))
End If
End Function
Public Shared Function [Delete]( _
ByVal connection As System.Data.IDbConnection, _
ByRef value As Instance _
) As Boolean
Return [Delete](connection, value, "tbl_Core_Instances")
End Function
Public Shared Function [Delete]( _
ByVal connection As System.Data.IDbConnection, _
ByVal id As System.Int64 _
) As Boolean
Return [Delete](connection, id, "tbl_Core_Instances")
End Function
Public Shared Function [Delete]( _
ByVal connection As System.Data.IDbConnection, _
ByRef value As Instance, _
ByVal tableName As String _
) As Boolean
Return [Delete](connection, value.Id, tableName)
End Function
Public Shared Function [Delete]( _
ByVal connection As System.Data.IDbConnection, _
ByVal id As System.Int64, _
ByVal tableName As String _
) As Boolean
If (id <= 0) Then Throw New ArgumentNullException("value")
If connection Is Nothing Then Throw New ArgumentNullException("connection")
If String.IsNullOrEmpty(tableName) Then Throw New ArgumentNullException("tableName")
If connection.State = System.Data.ConnectionState.Closed Then connection.Open()
Dim return_Value As Boolean = False
If connection.GetType Is GetType(System.Data.OleDb.OleDbConnection) Then
Dim OLEDB_Proc As String = String.Format("DELETE FROM {0} WHERE (Instance_Id = ?)", tableName)
Dim OLEDB_Comm As New System.Data.OleDb.OleDbCommand(OLEDB_Proc, CType(connection, System.Data.OleDb.OleDbConnection))
OLEDB_Comm.CommandType = System.Data.CommandType.Text
OLEDB_Comm.Parameters.Add(New System.Data.OleDb.OleDbParameter("Id", id))
return_Value = (OLEDB_Comm.ExecuteNonQuery() = 1)
ElseIf connection.GetType Is GetType(System.Data.SqlClient.SqlConnection) Then
Dim SQL_Proc As String = String.Format("DELETE FROM {0} WHERE (Instance_Id = @Id)", tableName)
Dim SQL_Comm As New System.Data.SqlClient.SqlCommand(SQL_Proc, CType(connection, System.Data.SqlClient.SqlConnection))
SQL_Comm.CommandType = System.Data.CommandType.Text
SQL_Comm.Parameters.Add(New System.Data.SqlClient.SqlParameter("@Id", id))
return_Value = (SQL_Comm.ExecuteNonQuery() = 1)
Else
Throw New NotImplementedException(String.Format("DB Connection of Type: {0} Not Yet Supported", connection.GetType.Name))
End If
If connection.State = System.Data.ConnectionState.Open Then connection.Close()
Return return_Value
End Function
#End Region
End Class
#End Region
#Region " IFormattable Implementation "
#Region " Public Constants "
''' <summary>Public Shared Reference to the Name of the Property: AsString</summary>
''' <remarks></remarks>
Public Const PROPERTY_ASSTRING As String = "AsString"
#End Region
#Region " Public Properties "
''' <summary></summary>
''' <remarks></remarks>
Public ReadOnly Property AsString() As System.String
Get
Return Me.ToString()
End Get
End Property
#End Region
#Region " Public Shared Methods "
Public Shared Function ToString_default( _
ByVal Code As System.String _
) As String
Return String.Format( _
"{0}", _
Code)
End Function
#End Region
#Region " Public Methods "
Public Overloads Overrides Function ToString() As String
Return Me.ToString(String.Empty, Nothing)
End Function
Public Overloads Function ToString( _
ByVal format As String _
) As String
If String.IsNullOrEmpty(format) OrElse String.Compare(format, "default", True) = 0 Then
Return ToString_default( _
Code _
)
End If
Return String.Empty
End Function
Public Overloads Function ToString( _
ByVal format As String, _
ByVal formatProvider As System.IFormatProvider _
) As String Implements System.IFormattable.ToString
If String.IsNullOrEmpty(format) OrElse String.Compare(format, "default", True) = 0 Then
Return ToString_default( _
Code _
)
End If
Return String.Empty
End Function
#End Region
#End Region
#Region " INotifyPropertyChanged Implementation "
#Region " Public Events "
''' <summary></summary>
''' <remarks></remarks>
Public Event INotifyPropertyChanged_PropertyChanged( _
ByVal sender As System.Object, _
ByVal e As System.ComponentModel.PropertyChangedEventArgs _
) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
#End Region
#Region " Protected Methods "
''' <summary></summary>
''' <remarks></remarks>
Protected Sub INotifyPropertyChanged_RaiseChanged( _
ByVal propertyName As System.String _
)
RaiseEvent INotifyPropertyChanged_PropertyChanged(Me, New System.ComponentModel.PropertyChangedEventArgs(propertyName))
End Sub
#End Region
#End Region
#End Region
#Region " Public Constants "
''' <summary>Public Shared Reference to the Name of the Property: Id</summary>
''' <remarks></remarks>
Public Const PROPERTY_ID As String = "Id"
''' <summary>Public Shared Reference to the Name of the Property: Option</summary>
''' <remarks></remarks>
Public Const PROPERTY_OPTION As String = "Option"
''' <summary>Public Shared Reference to the Name of the Property: Code</summary>
''' <remarks></remarks>
Public Const PROPERTY_CODE As String = "Code"
''' <summary>Public Shared Reference to the Name of the Property: Created</summary>
''' <remarks></remarks>
Public Const PROPERTY_CREATED As String = "Created"
#End Region
#Region " Private Variables "
''' <summary>Private Data Storage Variable for Property: Id</summary>
''' <remarks></remarks>
Private m_Id As System.Int64
''' <summary>Private Data Storage Variable for Property: Option</summary>
''' <remarks></remarks>
Private m_Option As System.Int32
''' <summary>Private Data Storage Variable for Property: Code</summary>
''' <remarks></remarks>
Private m_Code As System.String
''' <summary>Private Data Storage Variable for Property: Created</summary>
''' <remarks></remarks>
Private m_Created As System.DateTime
#End Region
#Region " Public Properties "
''' <summary>Provides Access to the Property: Id</summary>
''' <remarks></remarks>
<System.Xml.Serialization.XmlElement(ElementName:="Id")> _
Public ReadOnly Property Id() As System.Int64
Get
Return m_Id
End Get
End Property
''' <summary>Provides Access to the Property: Option</summary>
''' <remarks></remarks>
<System.Xml.Serialization.XmlElement(ElementName:="Option")> _
Public Property [Option]() As System.Int32
Get
Return m_Option
End Get
Set(value As System.Int32)
m_Option = value
End Set
End Property
''' <summary>Provides Access to the Property: Code</summary>
''' <remarks></remarks>
<System.Xml.Serialization.XmlElement(ElementName:="Code")> _
Public Property Code() As System.String
Get
Return m_Code
End Get
Set(value As System.String)
m_Code = value
End Set
End Property
''' <summary>Provides Access to the Property: Created</summary>
''' <remarks></remarks>
<System.Xml.Serialization.XmlElement(ElementName:="Created")> _
Public Property Created() As System.DateTime
Get
Return m_Created
End Get
Set(value As System.DateTime)
m_Created = value
End Set
End Property
#End Region
End Class
End Namespace
|
thiscouldbejd/Athena
|
Athena/_Core/Generated/Instance.vb
|
Visual Basic
|
mit
| 33,128
|
Option Strict Off
Option Explicit On
Imports Microsoft.VisualBasic.PowerPacks
Friend Class frmGRVprint
Inherits System.Windows.Forms.Form
Private Sub loadLanguage()
rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1781 'Invoice Print|Checked
If rsLang.RecordCount Then Me.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : Me.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value
rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1433 'Select a Supplier|Checked
If rsLang.RecordCount Then _lbl_0.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : _lbl_0.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value
rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1783 'Select an Invoice|Checked
If rsLang.RecordCount Then _lbl_1.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : _lbl_1.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value
rsHelp.filter = "Help_Section=0 AND Help_Form='" & Me.Name & "'"
'UPGRADE_ISSUE: Form property frmGRVprint.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
If rsHelp.RecordCount Then Me.ToolTip1 = rsHelp.Fields("Help_ContextID").Value
End Sub
Private Sub setHeading()
Dim lvHeading As System.Windows.Forms.ColumnHeader
lvItems.Columns.Clear()
lvHeading = lvItems.Columns.Add("Supplier")
lvHeading.Width = twipsToPixels(2100, True)
lvHeading = lvItems.Columns.Add("Invoice Number")
lvHeading.Width = twipsToPixels(1500, True)
lvHeading = lvItems.Columns.Add("Date")
lvHeading.Width = twipsToPixels(1100, True)
lvHeading = lvItems.Columns.Add("Amount")
lvHeading.Width = twipsToPixels(1300, True)
lvHeading.TextAlign = System.Windows.Forms.HorizontalAlignment.Right
End Sub
Private Sub cmdBack_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdBack.Click
Me.Close()
End Sub
Private Sub frmGRVprint_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
If KeyAscii = 27 Then
KeyAscii = 0
Me.Close()
End If
eventArgs.KeyChar = Chr(KeyAscii)
If KeyAscii = 0 Then
eventArgs.Handled = True
End If
End Sub
Private Sub frmGRVprint_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
Dim loading As Boolean
loading = True
Dim rs As ADODB.Recordset
Dim ltype As String
Dim tmpString As String
loadLanguage()
setHeading()
rs = getRS("SELECT TOP 100 PERCENT Supplier.* FROM Supplier WHERE Supplier_Disabled = 0 ORDER BY Supplier.Supplier_Name")
Me.lstSupplier.Items.Clear()
Do Until rs.EOF
If IsDbNull(rs.Fields("Supplier_GRVtype").Value) Then
ltype = "normal"
Else
ltype = rs.Fields("Supplier_GRVtype").Value
If ltype = "" Then ltype = "normal"
End If
tmpString = rs.Fields("Supplier_Name").Value & " " & rs.Fields("SupplierID").Value
lstSupplier.Items.Add(tmpString)
rs.moveNext()
Loop
lstSupplier.SelectedIndex = 0
loading = False
End Sub
Private Sub lstSupplier_SelectedIndexChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles lstSupplier.SelectedIndexChanged
Dim ltype As String
Dim rs As ADODB.Recordset
Dim lvItem As System.Windows.Forms.ListViewItem
If lstSupplier.SelectedIndex = -1 Then Exit Sub
rs = getRS("SELECT TOP 100 GRV.GRVID, Supplier.SupplierID, Supplier.Supplier_Name, GRV.GRV_GRVStatusID, GRV.GRV_InvoiceNumber, GRV.GRV_InvoiceDate, GRV.GRV_InvoiceInclusive, Supplier.Supplier_GRVtype FROM (PurchaseOrder INNER JOIN GRV ON PurchaseOrder.PurchaseOrderID = GRV.GRV_PurchaseOrderID) INNER JOIN Supplier ON PurchaseOrder.PurchaseOrder_SupplierID = Supplier.SupplierID Where (((Supplier.SupplierID) = " & CLng(lstSupplier.SelectedIndex) & ")) ORDER BY GRV.GRV_InvoiceDate DESC;")
Me.lvItems.Items.Clear()
Do Until rs.EOF
If IsDbNull(rs.Fields("Supplier_GRVtype").Value) Then
ltype = "normal"
Else
ltype = rs.Fields("Supplier_GRVtype").Value
If ltype = "" Then ltype = "normal"
End If
lvItem = lvItems.Items.Add("K" & rs.Fields("GRVID").Value, rs.Fields("Supplier_Name").Value, "")
lvItem.Font = New Font(lvItem.Font, rs.Fields("GRV_GRVStatusID").Value <> 1)
If lvItem.SubItems.Count > 0 Then
lvItem.SubItems(0).Text = rs.Fields("GRV_InvoiceNumber").Value
Else
lvItem.SubItems.Insert(0, New System.Windows.Forms.ListViewItem.ListViewSubItem(Nothing, rs.Fields("GRV_InvoiceNumber").Value))
End If
If lvItem.SubItems.Count > 0 Then
lvItem.SubItems(0).Text = Format(rs.Fields("GRV_InvoiceDate").Value, "dd,mmm yyyy")
Else
lvItem.SubItems.Insert(0, New System.Windows.Forms.ListViewItem.ListViewSubItem(Nothing, Format(rs.Fields("GRV_InvoiceDate").Value, "dd,mmm yyyy")))
End If
If lvItem.SubItems.Count > 1 Then
lvItem.SubItems(1).Text = FormatNumber(rs.Fields("GRV_InvoiceInclusive").Value, 1)
Else
lvItem.SubItems.Insert(1, New System.Windows.Forms.ListViewItem.ListViewSubItem(Nothing, FormatNumber(rs.Fields("GRV_InvoiceInclusive").Value, 2)))
End If
rs.moveNext()
Loop
End Sub
Private Sub lstSupplier_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles lstSupplier.KeyPress
Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
If KeyAscii = 27 Then
Me.Close()
End If
eventArgs.KeyChar = Chr(KeyAscii)
If KeyAscii = 0 Then
eventArgs.Handled = True
End If
End Sub
Private Sub lvItems_DoubleClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles lvItems.DoubleClick
If lvItems.FocusedItem Is Nothing Then
Else
report_GRV(CInt(Mid(lvItems.FocusedItem.Name, 2)))
End If
End Sub
Private Sub lvItems_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles lvItems.KeyPress
Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
If KeyAscii = 27 Then
Me.Close()
ElseIf KeyAscii = 13 Then
lvItems_DoubleClick(lvItems, New System.EventArgs())
End If
eventArgs.KeyChar = Chr(KeyAscii)
If KeyAscii = 0 Then
eventArgs.Handled = True
End If
End Sub
End Class
|
nodoid/PointOfSale
|
VB/4PosBackOffice.NET/frmGRVprint.vb
|
Visual Basic
|
mit
| 6,717
|
Partial Class masterpages_standard_blank
Inherits System.Web.UI.MasterPage
End Class
|
select-interactive/SI-CRE
|
masterpages/standard-blank.master.vb
|
Visual Basic
|
mit
| 94
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.ComponentModel.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.Editor.Implementation.Intellisense.Completion.CompletionProviders
Imports Microsoft.CodeAnalysis.Options
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.Completion.CompletionProviders
<ExportCompletionProvider("OverrideCompletionProvider", LanguageNames.VisualBasic)>
Friend Class OverrideCompletionProvider
Inherits AbstractOverrideCompletionProvider
Private isFunction As Boolean
Private isSub As Boolean
Private isProperty As Boolean
<ImportingConstructor()>
Sub New(waitIndicator As IWaitIndicator)
MyBase.New(waitIndicator)
End Sub
Protected Overrides Function GetSyntax(commonSyntaxToken As SyntaxToken) As SyntaxNode
Dim token = CType(commonSyntaxToken, SyntaxToken)
Dim propertyBlock = token.GetAncestor(Of PropertyBlockSyntax)()
If propertyBlock IsNot Nothing Then
Return propertyBlock
End If
Dim methodBlock = token.GetAncestor(Of MethodBlockBaseSyntax)()
If methodBlock IsNot Nothing Then
Return methodBlock
End If
Return token.GetAncestor(Of MethodStatementSyntax)()
End Function
Protected Overrides Function GetToken(completionItem As MemberInsertionCompletionItem, commonTree As SyntaxTree, cancellationToken As CancellationToken) As SyntaxToken
Dim token = completionItem.Token
Dim tree = DirectCast(commonTree, SyntaxTree)
Return tree.FindTokenOnLeftOfPosition(token.Span.End, cancellationToken)
End Function
Public Overrides Function FindStartingToken(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As SyntaxToken
Dim tree = DirectCast(syntaxTree, SyntaxTree)
Dim token = tree.FindTokenOnLeftOfPosition(position, cancellationToken)
Return token.GetPreviousTokenIfTouchingWord(position)
End Function
Protected Overrides Function GetTextChangeSpan(text As SourceText, position As Integer) As TextSpan
Return CompletionUtilities.GetTextChangeSpan(text, position)
End Function
Public Overrides Function IsTriggerCharacter(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean
Return CompletionUtilities.IsTriggerAfterSpaceOrStartOfWordCharacter(text, characterPosition, options)
End Function
Public Overrides Function TryDetermineModifiers(startToken As SyntaxToken,
text As SourceText, startLine As Integer,
ByRef seenAccessibility As Accessibility,
ByRef modifiers As DeclarationModifiers) As Boolean
Dim token = CType(startToken, SyntaxToken)
modifiers = New DeclarationModifiers()
seenAccessibility = Accessibility.NotApplicable
Dim overridesToken = New SyntaxToken()
Dim isMustOverride = False
Dim isNotOverridable = False
Me.isSub = False
Me.isFunction = False
Me.isProperty = False
Do While IsOnStartLine(token.SpanStart, text, startLine)
Select Case token.Kind
Case SyntaxKind.OverridesKeyword
overridesToken = token
Case SyntaxKind.MustOverrideKeyword
isMustOverride = True
Case SyntaxKind.NotOverridableKeyword
isNotOverridable = True
Case SyntaxKind.FunctionKeyword
isFunction = True
Case SyntaxKind.PropertyKeyword
isProperty = True
Case SyntaxKind.SubKeyword
isSub = True
' Filter on accessibility by keeping the first one that we see
Case SyntaxKind.PublicKeyword
If seenAccessibility = Accessibility.NotApplicable Then
seenAccessibility = Accessibility.Public
End If
Case SyntaxKind.FriendKeyword
If seenAccessibility = Accessibility.NotApplicable Then
seenAccessibility = Accessibility.Internal
End If
' If we see Friend AND Protected, assume Friend Protected
If seenAccessibility = Accessibility.Protected Then
seenAccessibility = Accessibility.ProtectedOrInternal
End If
Case SyntaxKind.ProtectedKeyword
If seenAccessibility = Accessibility.NotApplicable Then
seenAccessibility = Accessibility.Protected
End If
' If we see Protected and Friend, assume Protected Friend
If seenAccessibility = Accessibility.Internal Then
seenAccessibility = Accessibility.ProtectedOrInternal
End If
Case Else
' If we see anything else, give up
Return False
End Select
Dim previousToken = token.GetPreviousToken()
' Consume only modifiers on the same line
If previousToken.Kind = SyntaxKind.None OrElse Not IsOnStartLine(previousToken.SpanStart, text, startLine) Then
Exit Do
End If
token = previousToken
Loop
modifiers = New DeclarationModifiers(isAbstract:=isMustOverride, isOverride:=True, isSealed:=isNotOverridable)
Return overridesToken.Kind = SyntaxKind.OverridesKeyword AndAlso IsOnStartLine(overridesToken.Parent.SpanStart, text, startLine)
End Function
Public Overrides Function TryDetermineReturnType(startToken As SyntaxToken,
semanticModel As SemanticModel,
cancellationToken As CancellationToken,
ByRef returnType As ITypeSymbol, ByRef nextToken As SyntaxToken) As Boolean
nextToken = startToken
returnType = Nothing
Return True
End Function
Public Overrides Function FilterOverrides(members As ISet(Of ISymbol), returnType As ITypeSymbol) As ISet(Of ISymbol)
' Start by removing Finalize(), which we never want to show.
Dim finalizeMethod = members.OfType(Of IMethodSymbol)().Where(Function(x) x.Name = "Finalize" AndAlso OverridesObjectMethod(x)).SingleOrDefault()
If finalizeMethod IsNot Nothing Then
members.Remove(finalizeMethod)
End If
If Me.isFunction Then
' Function: look for non-void return types
Dim filteredMembers = members.OfType(Of IMethodSymbol)().Where(Function(m) Not m.ReturnsVoid)
If filteredMembers.Any Then
Return New HashSet(Of ISymbol)(filteredMembers)
End If
ElseIf Me.isProperty Then
' Property: return properties
Dim filteredMembers = members.Where(Function(m) m.Kind = SymbolKind.Property)
If filteredMembers.Any Then
Return New HashSet(Of ISymbol)(filteredMembers)
End If
ElseIf Me.isSub Then
' Sub: look for void return types
Dim filteredMembers = members.OfType(Of IMethodSymbol)().Where(Function(m) m.ReturnsVoid)
If filteredMembers.Any Then
Return New HashSet(Of ISymbol)(filteredMembers)
End If
End If
Return members.Where(Function(m) Not m.IsKind(SymbolKind.Event)).ToSet()
End Function
Private Function OverridesObjectMethod(method As IMethodSymbol) As Boolean
Dim overriddenMember = method
Do While overriddenMember.OverriddenMethod IsNot Nothing
overriddenMember = overriddenMember.OverriddenMethod
Loop
If overriddenMember.ContainingType.SpecialType = SpecialType.System_Object Then
Return True
End If
Return False
End Function
Protected Overrides Function GetTargetCaretPosition(caretTarget As SyntaxNode) As Integer
Dim node = DirectCast(caretTarget, SyntaxNode)
' MustOverride Sub | MustOverride Function: move to end of line
Dim methodStatement = TryCast(node, MethodStatementSyntax)
If methodStatement IsNot Nothing Then
Return methodStatement.GetLocation().SourceSpan.End
End If
Dim methodBlock = TryCast(node, MethodBlockBaseSyntax)
If methodBlock IsNot Nothing Then
Dim lastStatement = methodBlock.Statements.LastOrDefault()
If lastStatement IsNot Nothing Then
Return lastStatement.GetLocation().SourceSpan.End
End If
End If
Dim propertyBlock = TryCast(node, PropertyBlockSyntax)
If propertyBlock IsNot Nothing Then
Dim firstAccessor = propertyBlock.Accessors.FirstOrDefault()
If firstAccessor IsNot Nothing Then
Dim lastAccessorStatement = firstAccessor.Statements.LastOrDefault()
If lastAccessorStatement IsNot Nothing Then
Return lastAccessorStatement.GetLocation().SourceSpan.End
End If
End If
End If
Return -1
End Function
End Class
End Namespace
|
ManishJayaswal/roslyn
|
src/EditorFeatures/VisualBasic/Completion/CompletionProviders/OverrideCompletionProvider.vb
|
Visual Basic
|
apache-2.0
| 10,743
|
Namespace BasicWM
Public Class Desktop
Public openterminals As Integer = 0
Private Sub btnnewterminal_Click(sender As Object, e As EventArgs) Handles btnnewterminal.Click
If openterminals = 3 Then
AddLine("The maximum ammount of Terminal windows are open.")
AddLine(username + "@" + osname + " " & Terminal.currentdir.ToLower.Replace("c:\shiftos", "~") & "$> ")
Else
Dim term As New Terminal
term.StartPosition = FormStartPosition.CenterParent
term.TopMost = True
term.Show()
openterminals += 1
End If
End Sub
Private Sub Desktop_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Terminal.Close()
Me.WindowState = FormWindowState.Maximized
Dim term As New Terminal
term.StartPosition = FormStartPosition.CenterParent
term.TopMost = True
term.Show()
openterminals += 1
End Sub
End Class
End Namespace
|
pfgithub/shiftos-next
|
shiftos_next/BWMDesktop.vb
|
Visual Basic
|
apache-2.0
| 1,094
|
' 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.CodeGen
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGen
Partial Friend Class CodeGenerator
Private _recursionDepth As Integer
Private Class EmitCancelledException
Inherits Exception
End Class
Private Enum UseKind
Unused
UsedAsValue
UsedAsAddress
End Enum
Private Sub EmitExpression(expression As BoundExpression, used As Boolean)
If expression Is Nothing Then
Return
End If
Dim constantValue = expression.ConstantValueOpt
If constantValue IsNot Nothing Then
If Not used Then
' unused constants have no side-effects.
Return
End If
If constantValue.IsDecimal OrElse constantValue.IsDateTime Then
' Decimal/DateTime literal fields like Decimal.One should be emitted as fields.
Debug.Assert(expression.Kind = BoundKind.FieldAccess)
Else
EmitConstantExpression(expression.Type, constantValue, used, expression.Syntax)
Return
End If
End If
_recursionDepth += 1
If _recursionDepth > 1 Then
StackGuard.EnsureSufficientExecutionStack(_recursionDepth)
EmitExpressionCore(expression, used)
Else
EmitExpressionCoreWithStackGuard(expression, used)
End If
_recursionDepth -= 1
End Sub
Private Sub EmitExpressionCoreWithStackGuard(expression As BoundExpression, used As Boolean)
Debug.Assert(_recursionDepth = 1)
Try
EmitExpressionCore(expression, used)
Debug.Assert(_recursionDepth = 1)
Catch ex As InsufficientExecutionStackException
_diagnostics.Add(ERRID.ERR_TooLongOrComplexExpression,
BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(expression))
Throw New EmitCancelledException()
End Try
End Sub
Private Sub EmitExpressionCore(expression As BoundExpression, used As Boolean)
Select Case expression.Kind
Case BoundKind.AssignmentOperator
EmitAssignmentExpression(DirectCast(expression, BoundAssignmentOperator), used)
Case BoundKind.Call
EmitCallExpression(DirectCast(expression, BoundCall), If(used, UseKind.UsedAsValue, UseKind.Unused))
Case BoundKind.TernaryConditionalExpression
EmitTernaryConditionalExpression(DirectCast(expression, BoundTernaryConditionalExpression), used)
Case BoundKind.BinaryConditionalExpression
EmitBinaryConditionalExpression(DirectCast(expression, BoundBinaryConditionalExpression), used)
Case BoundKind.ObjectCreationExpression
EmitObjectCreationExpression(DirectCast(expression, BoundObjectCreationExpression), used)
Case BoundKind.ArrayCreation
EmitArrayCreationExpression(DirectCast(expression, BoundArrayCreation), used)
Case BoundKind.ArrayLength
EmitArrayLengthExpression(DirectCast(expression, BoundArrayLength), used)
Case BoundKind.Conversion
EmitConversionExpression(DirectCast(expression, BoundConversion), used)
Case BoundKind.DirectCast
EmitDirectCastExpression(DirectCast(expression, BoundDirectCast), used)
Case BoundKind.TryCast
EmitTryCastExpression(DirectCast(expression, BoundTryCast), used)
Case BoundKind.TypeOf
EmitTypeOfExpression(DirectCast(expression, BoundTypeOf), used)
Case BoundKind.Local
EmitLocalLoad(DirectCast(expression, BoundLocal), used)
Case BoundKind.Parameter
If used Then ' unused parameter has no side-effects
EmitParameterLoad(DirectCast(expression, BoundParameter))
End If
Case BoundKind.Dup
EmitDupExpression(DirectCast(expression, BoundDup), used)
Case BoundKind.FieldAccess
EmitFieldLoad(DirectCast(expression, BoundFieldAccess), used)
Case BoundKind.ArrayAccess
EmitArrayElementLoad(DirectCast(expression, BoundArrayAccess), used)
Case BoundKind.MeReference, BoundKind.MyClassReference
If used Then ' unused Me/MyClass has no side-effects
EmitMeOrMyClassReferenceExpression(expression)
End If
Case BoundKind.MyBaseReference
If used Then ' unused base has no side-effects
_builder.EmitOpCode(ILOpCode.Ldarg_0)
End If
Case BoundKind.Sequence
EmitSequenceExpression(DirectCast(expression, BoundSequence), used)
Case BoundKind.SequencePointExpression
EmitSequencePointExpression(DirectCast(expression, BoundSequencePointExpression), used)
Case BoundKind.UnaryOperator
EmitUnaryOperatorExpression(DirectCast(expression, BoundUnaryOperator), used)
Case BoundKind.BinaryOperator
EmitBinaryOperatorExpression(DirectCast(expression, BoundBinaryOperator), used)
Case BoundKind.DelegateCreationExpression
EmitDelegateCreationExpression(DirectCast(expression, BoundDelegateCreationExpression), used)
Case BoundKind.GetType
EmitGetType(DirectCast(expression, BoundGetType), used)
Case BoundKind.FieldInfo
EmitFieldInfoExpression(DirectCast(expression, BoundFieldInfo), used)
Case BoundKind.MethodInfo
EmitMethodInfoExpression(DirectCast(expression, BoundMethodInfo), used)
Case BoundKind.ReferenceAssignment
EmitReferenceAssignment(DirectCast(expression, BoundReferenceAssignment), used)
Case BoundKind.ValueTypeMeReference
' We want to restrict the usage of BoundValueTypeMeReference to the very minimum possible,
' which is to be able to pass Me reference of value type as ByRef argument in compiler
' generated code, this is why we specifically prohibit emitting this as value
Throw ExceptionUtilities.UnexpectedValue(expression.Kind)
Case BoundKind.LoweredConditionalAccess
EmitConditionalAccess(DirectCast(expression, BoundLoweredConditionalAccess), used)
Case BoundKind.ConditionalAccessReceiverPlaceholder
EmitConditionalAccessReceiverPlaceholder(DirectCast(expression, BoundConditionalAccessReceiverPlaceholder), used)
Case BoundKind.ComplexConditionalAccessReceiver
EmitComplexConditionalAccessReceiver(DirectCast(expression, BoundComplexConditionalAccessReceiver), used)
Case BoundKind.PseudoVariable
EmitPseudoVariableValue(DirectCast(expression, BoundPseudoVariable), used)
Case BoundKind.ModuleVersionId
Debug.Assert(used)
EmitModuleVersionIdLoad(DirectCast(expression, BoundModuleVersionId))
Case BoundKind.ModuleVersionIdString
Debug.Assert(used)
EmitModuleVersionIdStringLoad(DirectCast(expression, BoundModuleVersionIdString))
Case BoundKind.InstrumentationPayloadRoot
Debug.Assert(used)
EmitInstrumentationPayloadRootLoad(DirectCast(expression, BoundInstrumentationPayloadRoot))
Case BoundKind.MethodDefIndex
Debug.Assert(used)
EmitMethodDefIndexExpression(DirectCast(expression, BoundMethodDefIndex))
Case BoundKind.MaximumMethodDefIndex
Debug.Assert(used)
EmitMaximumMethodDefIndexExpression(DirectCast(expression, BoundMaximumMethodDefIndex))
Case BoundKind.SourceDocumentIndex
Debug.Assert(used)
EmitSourceDocumentIndex(DirectCast(expression, BoundSourceDocumentIndex))
Case Else
' Code gen should not be invoked if there are errors.
' Debug.Assert(expression.Kind <> BoundKind.BadExpression AndAlso expression.Kind <> BoundKind.Parenthesized)
Throw ExceptionUtilities.UnexpectedValue(expression.Kind)
Return
End Select
End Sub
Private Sub EmitConditionalAccessReceiverPlaceholder(expression As BoundConditionalAccessReceiverPlaceholder, used As Boolean)
Debug.Assert(Not expression.Type.IsValueType)
If used AndAlso Not expression.Type.IsReferenceType Then
EmitLoadIndirect(expression.Type, expression.Syntax)
End If
EmitPopIfUnused(used)
End Sub
Private Sub EmitComplexConditionalAccessReceiver(expression As BoundComplexConditionalAccessReceiver, used As Boolean)
Debug.Assert(Not expression.Type.IsReferenceType)
Debug.Assert(Not expression.Type.IsValueType)
Dim receiverType = expression.Type
Dim whenValueTypeLabel As New Object()
Dim doneLabel As New Object()
EmitInitObj(receiverType, True, expression.Syntax)
EmitBox(receiverType, expression.Syntax)
_builder.EmitBranch(ILOpCode.Brtrue, whenValueTypeLabel)
EmitExpression(expression.ReferenceTypeReceiver, used)
_builder.EmitBranch(ILOpCode.Br, doneLabel)
_builder.AdjustStack(-1)
_builder.MarkLabel(whenValueTypeLabel)
EmitExpression(expression.ValueTypeReceiver, used)
_builder.MarkLabel(doneLabel)
End Sub
Private Sub EmitConditionalAccess(conditional As BoundLoweredConditionalAccess, used As Boolean)
Debug.Assert(conditional.WhenNullOpt IsNot Nothing OrElse Not used)
If conditional.ReceiverOrCondition.Type.IsBooleanType() Then
' This is a trivial case
Debug.Assert(Not conditional.CaptureReceiver)
Debug.Assert(conditional.PlaceholderId = 0)
Dim doneLabel = New Object()
Dim consequenceLabel = New Object()
EmitCondBranch(conditional.ReceiverOrCondition, consequenceLabel, sense:=True)
If conditional.WhenNullOpt IsNot Nothing Then
EmitExpression(conditional.WhenNullOpt, used)
Else
Debug.Assert(Not used)
End If
_builder.EmitBranch(ILOpCode.Br, doneLabel)
If used Then
' If we get to consequenceLabel, we should not have WhenFalse on stack, adjust for that.
_builder.AdjustStack(-1)
End If
_builder.MarkLabel(consequenceLabel)
EmitExpression(conditional.WhenNotNull, used)
_builder.MarkLabel(doneLabel)
Else
Debug.Assert(Not conditional.ReceiverOrCondition.Type.IsValueType)
Dim receiverTemp As LocalDefinition = Nothing
Dim temp As LocalDefinition = Nothing
' labels
Dim whenNotNullLabel As New Object()
Dim doneLabel As New Object()
' we need a copy if we deal with nonlocal value (to capture the value)
' Or if we have a ref-constrained T (to do box just once)
Dim receiver As BoundExpression = conditional.ReceiverOrCondition
Dim receiverType As TypeSymbol = receiver.Type
Dim nullCheckOnCopy = conditional.CaptureReceiver OrElse (receiverType.IsReferenceType AndAlso receiverType.TypeKind = TypeKind.TypeParameter)
If nullCheckOnCopy Then
EmitReceiverRef(receiver, isAccessConstrained:=Not receiverType.IsReferenceType, addressKind:=AddressKind.ReadOnly)
If Not receiverType.IsReferenceType Then
' unconstrained case needs to handle case where T Is actually a struct.
' such values are never nulls
' we will emit a check for such case, but the check Is really a JIT-time
' constant since JIT will know if T Is a struct Or Not.
'
' if ((object)default(T) != null)
' {
' goto whenNotNull
' }
' else
' {
' temp = receiverRef
' receiverRef = ref temp
' }
EmitInitObj(receiverType, True, receiver.Syntax)
EmitBox(receiverType, receiver.Syntax)
_builder.EmitBranch(ILOpCode.Brtrue, whenNotNullLabel)
EmitLoadIndirect(receiverType, receiver.Syntax)
temp = AllocateTemp(receiverType, receiver.Syntax)
_builder.EmitLocalStore(temp)
_builder.EmitLocalAddress(temp)
_builder.EmitLocalLoad(temp)
EmitBox(receiver.Type, receiver.Syntax)
' here we have loaded a ref to a temp And its boxed value { &T, O }
Else
_builder.EmitOpCode(ILOpCode.Dup)
' here we have loaded two copies of a reference { O, O }
End If
Else
EmitExpression(receiver, True)
If Not receiverType.IsReferenceType Then
EmitBox(receiverType, receiver.Syntax)
End If
' here we have loaded just { O }
' we have the most trivial case where we can just reload O when needed
End If
_builder.EmitBranch(ILOpCode.Brtrue, whenNotNullLabel)
If nullCheckOnCopy Then
_builder.EmitOpCode(ILOpCode.Pop)
End If
If conditional.WhenNullOpt IsNot Nothing Then
EmitExpression(conditional.WhenNullOpt, used)
Else
Debug.Assert(Not used)
End If
_builder.EmitBranch(ILOpCode.Br, doneLabel)
If used Then
' If we get to whenNotNullLabel, we should not have WhenNullOpt on stack, adjust for that.
_builder.AdjustStack(-1)
End If
If nullCheckOnCopy Then
' whenNull branch pops copy of the receiver off the stack when nullCheckOnCopy
' however on this branch we still have the stack as it was and need
' to adjust stack depth accordingly.
_builder.AdjustStack(+1)
End If
_builder.MarkLabel(whenNotNullLabel)
If Not nullCheckOnCopy Then
receiverTemp = EmitReceiverRef(receiver, isAccessConstrained:=Not receiverType.IsReferenceType, addressKind:=AddressKind.ReadOnly)
Debug.Assert(receiverTemp Is Nothing OrElse receiver.IsDefaultValue())
End If
EmitExpression(conditional.WhenNotNull, used)
_builder.MarkLabel(doneLabel)
If temp IsNot Nothing Then
FreeTemp(temp)
End If
If receiverTemp IsNot Nothing Then
FreeTemp(receiverTemp)
End If
End If
End Sub
Private Sub EmitComplexConditionalAccessReceiverAddress(expression As BoundComplexConditionalAccessReceiver)
Debug.Assert(Not expression.Type.IsReferenceType)
Debug.Assert(Not expression.Type.IsValueType)
Dim receiverType = expression.Type
Dim whenValueTypeLabel As New Object()
Dim doneLabel As New Object()
EmitInitObj(receiverType, True, expression.Syntax)
EmitBox(receiverType, expression.Syntax)
_builder.EmitBranch(ILOpCode.Brtrue, whenValueTypeLabel)
Dim receiverTemp = EmitAddress(expression.ReferenceTypeReceiver, addressKind:=AddressKind.ReadOnly)
Debug.Assert(receiverTemp Is Nothing)
_builder.EmitBranch(ILOpCode.Br, doneLabel)
_builder.AdjustStack(-1)
_builder.MarkLabel(whenValueTypeLabel)
EmitReceiverRef(expression.ValueTypeReceiver, isAccessConstrained:=True, addressKind:=AddressKind.ReadOnly)
_builder.MarkLabel(doneLabel)
End Sub
Private Sub EmitDelegateCreationExpression(expression As BoundDelegateCreationExpression, used As Boolean)
Dim invoke = DirectCast(expression.Method, MethodSymbol)
EmitDelegateCreation(expression.ReceiverOpt, invoke, expression.Type, used, expression.Syntax)
End Sub
Private Sub EmitLocalLoad(local As BoundLocal, used As Boolean)
If IsStackLocal(local.LocalSymbol) Then
' local should be already on the stack
EmitPopIfUnused(used)
Else
If used Then ' unused local has no side-effects
_builder.EmitLocalLoad(GetLocal(local))
Else
' do nothing. Unused local load has no side-effects.
Return
End If
End If
If used AndAlso local.LocalSymbol.IsByRef Then
EmitLoadIndirect(local.Type, local.Syntax)
End If
End Sub
Private Sub EmitDelegateCreation(receiver As BoundExpression, method As MethodSymbol, delegateType As TypeSymbol, used As Boolean, syntaxNode As SyntaxNode)
Dim isStatic = receiver Is Nothing OrElse method.IsShared
If Not used Then
If Not isStatic Then
EmitExpression(receiver, False)
End If
Return
End If
If isStatic Then
_builder.EmitNullConstant()
Else
EmitExpression(receiver, True)
If Not IsVerifierReference(receiver.Type) Then
EmitBox(receiver.Type, receiver.Syntax)
End If
End If
' Metadata Spec (II.14.6):
' Delegates shall be declared sealed.
' The Invoke method shall be virtual.
' Dev11 VB uses ldvirtftn for delegate methods, we emit ldftn to be consistent with C#.
If method.IsMetadataVirtual AndAlso Not method.ContainingType.IsDelegateType() AndAlso Not receiver.SuppressVirtualCalls Then
_builder.EmitOpCode(ILOpCode.Dup)
_builder.EmitOpCode(ILOpCode.Ldvirtftn)
Else
_builder.EmitOpCode(ILOpCode.Ldftn)
End If
Dim targetMethod = If(method.CallsiteReducedFromMethod, method)
If Not isStatic AndAlso targetMethod.ContainingType.IsNullableType Then
Debug.Assert(targetMethod.IsOverrides, "Nullable cannot be truly boxed therefore delegates of methods that do not override cannot be created")
targetMethod = method.OverriddenMethod
End If
EmitSymbolToken(targetMethod, syntaxNode)
' TODO: check the ctor signature, and recover more gracefully from failure to
' find a single constructor with the correct signature
Dim ctor = DirectCast(delegateType.GetMembers(WellKnownMemberNames.InstanceConstructorName).Single(), MethodSymbol)
_builder.EmitOpCode(ILOpCode.Newobj, -1)
EmitSymbolToken(ctor, syntaxNode)
End Sub
Private Sub EmitMeOrMyClassReferenceExpression(thisRef As BoundExpression)
Debug.Assert(thisRef.Kind = BoundKind.MeReference OrElse thisRef.Kind = BoundKind.MyClassReference)
Dim thisType = thisRef.Type
Debug.Assert(thisType.TypeKind <> TypeKind.TypeParameter)
_builder.EmitOpCode(ILOpCode.Ldarg_0)
If thisType.IsValueType Then
_builder.EmitOpCode(ILOpCode.Ldobj)
EmitSymbolToken(thisRef.Type, thisRef.Syntax)
End If
End Sub
Private Sub EmitPseudoVariableValue(expression As BoundPseudoVariable, used As Boolean)
EmitExpression(expression.EmitExpressions.GetValue(expression, _diagnostics), used)
End Sub
Private Sub EmitSequenceExpression(sequence As BoundSequence, used As Boolean)
Dim hasLocals As Boolean = Not sequence.Locals.IsEmpty
If hasLocals Then
_builder.OpenLocalScope()
For Each local In sequence.Locals
Me.DefineLocal(local, sequence.Syntax)
Next
End If
Me.EmitSideEffects(sequence.SideEffects)
Debug.Assert(sequence.ValueOpt IsNot Nothing OrElse sequence.Type.SpecialType = SpecialType.System_Void)
Me.EmitExpression(sequence.ValueOpt, used)
If hasLocals Then
_builder.CloseLocalScope()
For Each local In sequence.Locals
Me.FreeLocal(local)
Next
End If
End Sub
Private Sub EmitSideEffects(sideEffects As ImmutableArray(Of BoundExpression))
If Not sideEffects.IsDefaultOrEmpty Then
For Each se In sideEffects
EmitExpression(se, False)
Next
End If
End Sub
Private Sub EmitExpressions(expressions As ImmutableArray(Of BoundExpression), used As Boolean)
Dim i As Integer = 0
While i < expressions.Length
Dim expression = expressions(i)
EmitExpression(expression, used)
i = i + 1
End While
End Sub
Private Sub EmitArguments(arguments As ImmutableArray(Of BoundExpression), parameters As ImmutableArray(Of ParameterSymbol))
Debug.Assert(arguments.Length = parameters.Length)
For i = 0 To arguments.Length - 1
Dim argument = arguments(i)
Dim parameter = parameters(i)
If parameter.IsByRef Then
Dim temp = EmitAddress(argument, AddressKind.Writeable)
Debug.Assert(temp Is Nothing, "passing args byref should not clone them into temps. That should be done in rewriter.")
Else
EmitExpression(argument, True)
End If
Next
End Sub
Private Sub EmitArrayElementLoad(arrayAccess As BoundArrayAccess, used As Boolean)
EmitExpression(arrayAccess.Expression, True)
EmitExpressions(arrayAccess.Indices, True)
If DirectCast(arrayAccess.Expression.Type, ArrayTypeSymbol).IsSZArray Then
Dim elementType = arrayAccess.Type
If elementType.IsEnumType() Then
elementType = (DirectCast(elementType, NamedTypeSymbol)).EnumUnderlyingType
End If
Select Case elementType.PrimitiveTypeCode
Case Microsoft.Cci.PrimitiveTypeCode.Int8
_builder.EmitOpCode(ILOpCode.Ldelem_i1)
Case Microsoft.Cci.PrimitiveTypeCode.Boolean,
Microsoft.Cci.PrimitiveTypeCode.UInt8
_builder.EmitOpCode(ILOpCode.Ldelem_u1)
Case Microsoft.Cci.PrimitiveTypeCode.Int16
_builder.EmitOpCode(ILOpCode.Ldelem_i2)
Case Microsoft.Cci.PrimitiveTypeCode.Char,
Microsoft.Cci.PrimitiveTypeCode.UInt16
_builder.EmitOpCode(ILOpCode.Ldelem_u2)
Case Microsoft.Cci.PrimitiveTypeCode.Int32
_builder.EmitOpCode(ILOpCode.Ldelem_i4)
Case Microsoft.Cci.PrimitiveTypeCode.UInt32
_builder.EmitOpCode(ILOpCode.Ldelem_u4)
Case Microsoft.Cci.PrimitiveTypeCode.Int64,
Microsoft.Cci.PrimitiveTypeCode.UInt64
_builder.EmitOpCode(ILOpCode.Ldelem_i8)
Case Microsoft.Cci.PrimitiveTypeCode.IntPtr,
Microsoft.Cci.PrimitiveTypeCode.UIntPtr,
Microsoft.Cci.PrimitiveTypeCode.Pointer
_builder.EmitOpCode(ILOpCode.Ldelem_i)
Case Microsoft.Cci.PrimitiveTypeCode.Float32
_builder.EmitOpCode(ILOpCode.Ldelem_r4)
Case Microsoft.Cci.PrimitiveTypeCode.Float64
_builder.EmitOpCode(ILOpCode.Ldelem_r8)
Case Else
If IsVerifierReference(elementType) Then
_builder.EmitOpCode(ILOpCode.Ldelem_ref)
Else
If used Then
_builder.EmitOpCode(ILOpCode.Ldelem)
Else
' no need to read whole element of nontrivial type/size here
' just take a reference to an element for array access side-effects
If elementType.TypeKind = TypeKind.TypeParameter Then
_builder.EmitOpCode(ILOpCode.Readonly)
End If
_builder.EmitOpCode(ILOpCode.Ldelema)
End If
EmitSymbolToken(elementType, arrayAccess.Expression.Syntax)
End If
End Select
Else
_builder.EmitArrayElementLoad(_module.Translate(DirectCast(arrayAccess.Expression.Type, ArrayTypeSymbol)), arrayAccess.Expression.Syntax, _diagnostics)
End If
EmitPopIfUnused(used)
End Sub
Private Sub EmitFieldLoad(fieldAccess As BoundFieldAccess, used As Boolean)
Dim field = fieldAccess.FieldSymbol
'TODO: For static field access this may require ..ctor to run. Is this a side-effect?
' Accessing unused instance field on a struct is a noop. Just emit the receiver.
If Not used AndAlso Not field.IsShared AndAlso fieldAccess.ReceiverOpt.Type.IsVerifierValue() Then
EmitExpression(fieldAccess.ReceiverOpt, used:=False)
Return
End If
Dim specType = field.Type.SpecialType
If field.IsConst AndAlso specType <> SpecialType.System_Decimal AndAlso specType <> SpecialType.System_DateTime Then
' constant fields are not really fields and should not get here
Throw ExceptionUtilities.Unreachable
Else
If field.IsShared Then
EmitStaticFieldLoad(field, used, fieldAccess.Syntax)
Else
EmitInstanceFieldLoad(fieldAccess, used)
End If
End If
End Sub
Private Sub EmitDupExpression(dupExpression As BoundDup, used As Boolean)
If Not dupExpression.IsReference Then
' unused dup is noop
If used Then
_builder.EmitOpCode(ILOpCode.Dup)
End If
Else
_builder.EmitOpCode(ILOpCode.Dup)
' must read in case if it is a null ref
EmitLoadIndirect(dupExpression.Type, dupExpression.Syntax)
EmitPopIfUnused(used)
End If
End Sub
Private Sub EmitStaticFieldLoad(field As FieldSymbol, used As Boolean, syntaxNode As SyntaxNode)
'TODO: this may require ..ctor to run. Is this a side-effect?
_builder.EmitOpCode(ILOpCode.Ldsfld)
EmitSymbolToken(field, syntaxNode)
EmitPopIfUnused(used)
End Sub
Private Sub EmitInstanceFieldLoad(fieldAccess As BoundFieldAccess, used As Boolean)
'TODO: access to a field on this/base has no side-effects.
Dim field As FieldSymbol = fieldAccess.FieldSymbol
Dim receiver = fieldAccess.ReceiverOpt
'ldfld can work with structs directly (taking address is optional)
'taking address is typically cheaper, but not for homeless exprs
'those would need to be loaded anyways.
If FieldLoadMustUseRef(receiver) OrElse FieldLoadPrefersRef(receiver) Then
If Not EmitFieldLoadReceiverAddress(receiver) Then
' Since we are simply loading the field value, the receiver reference is not going to be mutated.
Dim temp = EmitReceiverRef(receiver, isAccessConstrained:=False, addressKind:=AddressKind.Immutable)
Debug.Assert(temp Is Nothing OrElse receiver.Type.IsEnumType, "temp is unexpected, just reading a field")
End If
Else
EmitExpression(receiver, True)
End If
_builder.EmitOpCode(ILOpCode.Ldfld)
EmitSymbolToken(field, fieldAccess.Syntax)
EmitPopIfUnused(used)
End Sub
' In special case of loading the sequence of field accesses we can perform all the
' necessary field loads using the following IL:
'
' <expr>.a.b...y.z
' |
' V
' Unbox -or- Load.Ref (<expr>)
' Ldflda a
' Ldflda b
' ...
' Ldflda y
' Ldfld z
'
' Returns 'true' if the receiver was actually emitted this way
Private Function EmitFieldLoadReceiverAddress(receiver As BoundExpression) As Boolean
If receiver Is Nothing OrElse receiver.Type.IsReferenceType Then
Return False
ElseIf receiver.Kind = BoundKind.DirectCast AndAlso IsUnboxingDirectCast(DirectCast(receiver, BoundDirectCast)) Then
EmitExpression(DirectCast(receiver, BoundDirectCast).Operand, True)
Me._builder.EmitOpCode(ILOpCode.Unbox)
EmitSymbolToken(receiver.Type, receiver.Syntax)
Return True
ElseIf receiver.Kind = BoundKind.FieldAccess Then
Dim fieldAccess = DirectCast(receiver, BoundFieldAccess)
Dim field As FieldSymbol = fieldAccess.FieldSymbol
If Not field.IsShared AndAlso EmitFieldLoadReceiverAddress(fieldAccess.ReceiverOpt) Then
Me._builder.EmitOpCode(ILOpCode.Ldflda)
EmitSymbolToken(field, fieldAccess.Syntax)
Return True
End If
End If
Return False
End Function
' ldfld can work with structs directly or with their addresses
' In some cases it results in same native code emitted, but in some cases JIT pushes values for real
' resulting in much worse code (on x64 in particular).
' So, we will always prefer references here except when receiver is a struct non-ref local or parameter.
Private Function FieldLoadPrefersRef(receiver As BoundExpression) As Boolean
' only fields of structs can be accessed via value
If Not receiver.Type.IsVerifierValue() Then
Return True
End If
' can unbox directly into a ref.
If receiver.Kind = BoundKind.DirectCast AndAlso IsUnboxingDirectCast(DirectCast(receiver, BoundDirectCast)) Then
Return True
End If
' can we take address at all?
If Not HasHome(receiver) Then
Return False
End If
Select Case receiver.Kind
Case BoundKind.Parameter
' prefer ldarg over ldarga
Return DirectCast(receiver, BoundParameter).ParameterSymbol.IsByRef
Case BoundKind.Local
' prefer ldloc over ldloca
Return DirectCast(receiver, BoundLocal).LocalSymbol.IsByRef
Case BoundKind.Sequence
Return FieldLoadPrefersRef(DirectCast(receiver, BoundSequence).ValueOpt)
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(receiver, BoundFieldAccess)
Return fieldAccess.FieldSymbol.IsShared OrElse FieldLoadPrefersRef(fieldAccess.ReceiverOpt)
End Select
Return True
End Function
Friend Shared Function FieldLoadMustUseRef(expr As BoundExpression) As Boolean
' NOTE: we emit a ref when receiver is an Enum.
' that is needed only when accessing value__ of the enum and that cannot be done off the enum value.
If expr.Type.IsEnumType Then
Return True
End If
' type parameter values must be boxed to get access to fields
Return expr.Type.IsTypeParameter()
End Function
Private Function ParameterSlot(parameter As BoundParameter) As Integer
Dim sym = parameter.ParameterSymbol
Dim slot As Integer = sym.Ordinal
If Not sym.ContainingSymbol.IsShared Then
slot = slot + 1 ' skip this
End If
Return slot
End Function
Private Sub EmitParameterLoad(parameter As BoundParameter)
Dim slot As Integer = ParameterSlot(parameter)
_builder.EmitLoadArgumentOpcode(slot)
If parameter.ParameterSymbol.IsByRef Then
Dim parameterType = parameter.ParameterSymbol.Type
EmitLoadIndirect(parameterType, parameter.Syntax)
End If
End Sub
Private Sub EmitLoadIndirect(type As TypeSymbol, syntaxNode As SyntaxNode)
If type.IsEnumType() Then
'underlying primitives do not need type tokens.
type = (DirectCast(type, NamedTypeSymbol)).EnumUnderlyingType
End If
Select Case type.PrimitiveTypeCode
Case Microsoft.Cci.PrimitiveTypeCode.Int8
_builder.EmitOpCode(ILOpCode.Ldind_i1)
Case Microsoft.Cci.PrimitiveTypeCode.Boolean,
Microsoft.Cci.PrimitiveTypeCode.UInt8
_builder.EmitOpCode(ILOpCode.Ldind_u1)
Case Microsoft.Cci.PrimitiveTypeCode.Int16
_builder.EmitOpCode(ILOpCode.Ldind_i2)
Case Microsoft.Cci.PrimitiveTypeCode.Char,
Microsoft.Cci.PrimitiveTypeCode.UInt16
_builder.EmitOpCode(ILOpCode.Ldind_u2)
Case Microsoft.Cci.PrimitiveTypeCode.Int32
_builder.EmitOpCode(ILOpCode.Ldind_i4)
Case Microsoft.Cci.PrimitiveTypeCode.UInt32
_builder.EmitOpCode(ILOpCode.Ldind_u4)
Case Microsoft.Cci.PrimitiveTypeCode.Int64,
Microsoft.Cci.PrimitiveTypeCode.UInt64
_builder.EmitOpCode(ILOpCode.Ldind_i8)
Case Microsoft.Cci.PrimitiveTypeCode.IntPtr,
Microsoft.Cci.PrimitiveTypeCode.UIntPtr,
Microsoft.Cci.PrimitiveTypeCode.Pointer
_builder.EmitOpCode(ILOpCode.Ldind_i)
Case Microsoft.Cci.PrimitiveTypeCode.Float32
_builder.EmitOpCode(ILOpCode.Ldind_r4)
Case Microsoft.Cci.PrimitiveTypeCode.Float64
_builder.EmitOpCode(ILOpCode.Ldind_r8)
Case Else
If IsVerifierReference(type) Then
_builder.EmitOpCode(ILOpCode.Ldind_ref)
Else
_builder.EmitOpCode(ILOpCode.Ldobj)
EmitSymbolToken(type, syntaxNode)
End If
End Select
End Sub
''' <summary>
''' Used to decide if we need to emit call or callvirt.
''' It basically checks if the receiver expression cannot be null, but it is not 100% precise.
''' There are cases where it really can be null, but we do not care.
''' </summary>
Private Function CanUseCallOnRefTypeReceiver(receiver As BoundExpression) As Boolean
' It seems none of the ways that could produce a receiver typed as a type param
' can guarantee that it is not null.
If receiver.Type.IsTypeParameter() Then
Return False
End If
Debug.Assert(IsVerifierReference(receiver.Type), "this is not a reference")
Debug.Assert(receiver.Kind <> BoundKind.MyBaseReference, "MyBase should always use call")
Debug.Assert(receiver.Kind <> BoundKind.MyClassReference, "MyClass should always use call")
Dim constVal = receiver.ConstantValueOpt
If constVal IsNot Nothing Then
' only when this is a constant Nothing, we need a callvirt
Return Not constVal.IsNothing
End If
Select Case receiver.Kind
Case BoundKind.ArrayCreation
Return True
Case BoundKind.ObjectCreationExpression
'NOTE: there are cases involving ProxyAttribute
'where newobj may produce null
Return True
Case BoundKind.DirectCast
Dim convOperand = DirectCast(receiver, BoundDirectCast).Operand
If Not IsVerifierReference(convOperand.Type) Then
'this is boxing
'NOTE: it can produce null for Nullable, but any call through that
'will result in null reference exceptions anyways.
Return True
Else
Return CanUseCallOnRefTypeReceiver(convOperand)
End If
Case BoundKind.MeReference, BoundKind.MyBaseReference, BoundKind.MyClassReference
'NOTE: these actually can be null if called from a different language
'if that has already happen, we will just propagate the behavior.
Return True
Case BoundKind.DelegateCreationExpression, BoundKind.AddressOfOperator
Return True
Case BoundKind.Sequence
Dim seqValue = DirectCast(receiver, BoundSequence).ValueOpt
Return seqValue IsNot Nothing AndAlso CanUseCallOnRefTypeReceiver(seqValue)
Case BoundKind.AssignmentOperator
Dim rhs = DirectCast(receiver, BoundAssignmentOperator).Right
Return CanUseCallOnRefTypeReceiver(rhs)
Case BoundKind.GetType
Return True
Case BoundKind.FieldAccess
Return DirectCast(receiver, BoundFieldAccess).FieldSymbol.IsCapturedFrame
Case BoundKind.ConditionalAccessReceiverPlaceholder,
BoundKind.ComplexConditionalAccessReceiver
Return True
'TODO: there must be more non-null cases.
End Select
Return False
End Function
''' <summary>
''' checks if receiver is effectively ldarg.0
''' </summary>
Private Function IsMeReceiver(receiver As BoundExpression) As Boolean
Select Case receiver.Kind
Case BoundKind.MeReference,
BoundKind.MyClassReference
Return True
Case BoundKind.Sequence
Dim seqValue = DirectCast(receiver, BoundSequence).ValueOpt
Return IsMeReceiver(seqValue)
End Select
Return False
End Function
Private Enum CallKind
[Call]
CallVirt
ConstrainedCallVirt
End Enum
Private Sub EmitCallExpression([call] As BoundCall, useKind As UseKind)
Dim method = [call].Method
Dim receiver = [call].ReceiverOpt
Debug.Assert([call].MethodGroupOpt Is Nothing)
Debug.Assert(Not Me._module.AllowOmissionOfConditionalCalls OrElse Not method.CallsAreOmitted([call].Syntax, [call].SyntaxTree))
' is this a call to a default struct constructor?
' this happens in struct non-parameterless constructors calling
' Me.New()
If method.IsDefaultValueTypeConstructor() Then
EmitInitObjOnTarget(receiver)
Return
End If
Dim arguments = [call].Arguments
Dim stackBehavior = (If(method.IsSub, 0, 1)) - arguments.Length
Dim callKind As CallKind
Dim tempOpt As LocalDefinition = Nothing
If method.IsShared Then
callKind = CallKind.Call
Else
stackBehavior = stackBehavior - 1
Dim receiverType = receiver.Type
If IsVerifierReference(receiverType) Then
tempOpt = EmitReceiverRef(receiver, isAccessConstrained:=False, addressKind:=AddressKind.ReadOnly)
'TODO: it is ok to use Call with final methods.
' Dev10 does not do this, but perhaps we should.
' Call/Callvirt is decided in the following order:
' 1) MyBase/MyClass calls must use "call"
' 2) virtual methods must use "callvirt"
' 3) nonvirtual methods use "callvirt" too for the null check semantics.
' 3.a In some cases CanUseCallOnRefTypeReceiver returns true which means that
' null check is unnecessary and we can use "call"
If receiver.SuppressVirtualCalls OrElse (Not method.IsMetadataVirtual AndAlso CanUseCallOnRefTypeReceiver(receiver)) Then
callKind = CallKind.Call
Else
callKind = CallKind.CallVirt
End If
ElseIf IsVerifierValue(receiverType) Then
Dim methodContainingType = method.ContainingType
If IsVerifierValue(methodContainingType) AndAlso MayUseCallForStructMethod(method) Then
' NOTE: this should be either a method which overrides some abstract method or
' does not override anything (with few exceptions, see MayUseCallForStructMethod);
' otherwise we should not use direct 'call' and must use constrained call;
' calling a method defined in a value type considered a "write" to the target unless the target is "Me"
Debug.Assert(receiverType = method.ContainingType)
tempOpt = EmitReceiverRef(
receiver,
isAccessConstrained:=False, addressKind:=If(IsMeReceiver(receiver),
AddressKind.ReadOnly,
AddressKind.Writeable))
callKind = CallKind.Call
Else
If method.IsMetadataVirtual Then
' When calling a method that is virtual in metadata on a struct receiver,
' we use a constrained virtual call. If possible, it will skip boxing.
tempOpt = EmitReceiverRef(receiver, isAccessConstrained:=True, addressKind:=AddressKind.ReadOnly)
callKind = CallKind.ConstrainedCallVirt
' In case we plan to use 'callvirt' we need to be sure the method we call
' is not the one from the structure, so we take the one we override
If IsVerifierValue(methodContainingType) Then
' NOTE: the most overridden method needs to be used to match Dev10 behavior
While method.OverriddenMethod IsNot Nothing
method = method.OverriddenMethod
End While
End If
Else
' calling a method defined in a base class.
EmitExpression(receiver, True)
EmitBox(receiverType, receiver.Syntax)
callKind = CallKind.Call
End If
End If
Else
' receiver is generic and method must come from the base or an interface or a generic constraint
' if the receiver is actually a value type it would need to be boxed.
' let .constrained sort this out.
Debug.Assert(Not receiverType.IsReferenceType OrElse receiver.Kind <> BoundKind.ComplexConditionalAccessReceiver)
callKind = If(receiverType.IsReferenceType AndAlso
(receiver.Kind = BoundKind.ConditionalAccessReceiverPlaceholder OrElse Not AllowedToTakeRef(receiver, AddressKind.ReadOnly)),
CallKind.CallVirt,
CallKind.ConstrainedCallVirt)
tempOpt = EmitReceiverRef(receiver, isAccessConstrained:=callKind = CallKind.ConstrainedCallVirt, addressKind:=AddressKind.ReadOnly)
End If
End If
' Devirtualizing of calls to effectively sealed methods.
If callKind = CallKind.CallVirt AndAlso
method.ContainingModule Is Me._method.ContainingModule Then
' NOTE: we check that we call method in same module just to be sure
' that it cannot be recompiled as not final and make our call not verifiable.
' such change by adversarial user would arguably be a compat break, but better be safe...
' In reality we would typically have one method calling another method in the same class (one GetEnumerator calling another).
' Other scenarios are uncommon since base class cannot be sealed and
' referring to a derived type in a different module is not an easy thing to do.
If IsMeReceiver(receiver) AndAlso method.ContainingType.IsNotInheritable Then
' special case for target is in a sealed class and "this" receiver.
Debug.Assert(receiver.Type.IsVerifierReference())
callKind = CallKind.Call
ElseIf method.IsMetadataFinal AndAlso CanUseCallOnRefTypeReceiver(receiver) Then
' special case for calling 'final' virtual method on reference receiver
Debug.Assert(receiver.Type.IsVerifierReference())
callKind = CallKind.Call
End If
End If
EmitArguments(arguments, method.Parameters)
Select Case callKind
Case CallKind.Call
_builder.EmitOpCode(ILOpCode.Call, stackBehavior)
Case CallKind.CallVirt
_builder.EmitOpCode(ILOpCode.Callvirt, stackBehavior)
Case CallKind.ConstrainedCallVirt
_builder.EmitOpCode(ILOpCode.Constrained)
EmitSymbolToken(receiver.Type, receiver.Syntax)
_builder.EmitOpCode(ILOpCode.Callvirt, stackBehavior)
End Select
EmitSymbolToken(method, [call].Syntax)
If Not method.IsSub Then
EmitPopIfUnused(useKind <> UseKind.Unused)
ElseIf _ilEmitStyle = ILEmitStyle.Debug Then
Debug.Assert(useKind = UseKind.Unused, "Using the return value of a void method.")
Debug.Assert(_method.GenerateDebugInfo, "Implied by emitSequencePoints")
' DevDiv #15135. When a method like System.Diagnostics.Debugger.Break() is called, the
' debugger sees an event indicating that a user break (vs a breakpoint) has occurred.
' When this happens, it uses ICorDebugILFrame.GetIP(out uint, out CorDebugMappingResult)
' to determine the current instruction pointer. This method returns the instruction
' *after* the call. The source location is then given by the last sequence point before
' or on this instruction. As a result, if the instruction after the call has its own
' sequence point, then that sequence point will be used to determine the source location
' and the debugging experience will be disrupted. The easiest way to ensure that the next
' instruction does not have a sequence point is to insert a nop. Obviously, we only do this
' if debugging is enabled and optimization is disabled.
' From CodeGenerator::GenerateCall:
' The IP always points to the location where execution will return
' So we generate a NOP here so that the IP is still associated with
' the call statement and the user can double click in the callstack
' window and take him to the calling line.
' CONSIDER: The native compiler does not appear to consider whether we are optimizing or emitting debug info.
' CONSIDER: The native compiler also checks !(tree->flags & EXF_NODEBUGINFO). We don't have
' this mutable bit on our bound nodes, so we can't exactly match the behavior. We might be
' able to approximate the native behavior by inspecting call.WasCompilerGenerated, but it is
' Not in a reliable state after lowering.
_builder.EmitOpCode(ILOpCode.Nop)
End If
If useKind = UseKind.UsedAsValue AndAlso method.ReturnsByRef Then
EmitLoadIndirect(method.ReturnType, [call].Syntax)
ElseIf useKind = UseKind.UsedAsAddress Then
Debug.Assert(method.ReturnsByRef)
End If
FreeOptTemp(tempOpt)
' Dev10 #850039 Check if we must disable inlining and optimization for the enclosing proc.
If Me._checkCallsForUnsafeJITOptimization AndAlso method.IsDefinition Then
Dim disableJITOptimization As Boolean = False
If method.ContainingSymbol Is Me._module.Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_ErrObject) Then
If String.Equals(method.Name, "Raise", StringComparison.Ordinal) Then
disableJITOptimization = True
End If
ElseIf method.ContainingSymbol Is Me._module.Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData) Then
If String.Equals(method.Name, "EndApp", StringComparison.Ordinal) Then
disableJITOptimization = True
End If
ElseIf method.ContainingSymbol Is Me._module.Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_ApplicationServices_ApplicationBase) Then
If String.Equals(method.Name, "Info", StringComparison.Ordinal) Then
disableJITOptimization = True
End If
ElseIf method.ContainingSymbol Is Me._module.Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_ApplicationServices_WindowsFormsApplicationBase) Then
If String.Equals(method.Name, "Run", StringComparison.Ordinal) Then
disableJITOptimization = True
End If
ElseIf method.ContainingSymbol Is Me._module.Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_FileSystem) Then
Select Case method.Name
Case "Dir", "EOF", "FileAttr", "FileClose", "FileCopy", "FileGet", "FileGetObject", "FileOpen", "FilePut",
"FilePutObject", "FileWidth", "FreeFile", "Input", "InputString", "Kill", "LineInput", "Loc", "Lock",
"LOF", "Print", "PrintLine", "Rename", "Reset", "Seek", "SetAttr", "Unlock", "Write", "WriteLine"
disableJITOptimization = True
End Select
End If
If disableJITOptimization Then
Me._checkCallsForUnsafeJITOptimization = False
Me._module.SetDisableJITOptimization(Me._method)
End If
End If
End Sub
''' <summary>
''' Used to decide if we need to emit 'call' or 'callvirt' for structure method.
''' It basically checks if the method overrides any other and method's defining type
''' is not a 'special' or 'special-by-ref' type.
''' </summary>
Private Function MayUseCallForStructMethod(method As MethodSymbol) As Boolean
Debug.Assert(IsVerifierValue(method.ContainingType), "this is not a value type")
If Not method.IsMetadataVirtual Then
Return True
End If
Dim overriddenMethod = method.OverriddenMethod
If overriddenMethod Is Nothing OrElse overriddenMethod.IsMustOverride Then
Return True
End If
Dim containingType = method.ContainingType
' NOTE: current implementation of IsIntrinsicType treats DateTime as an
' intrinsic type which differs from C# version
' NOTE: VB Dev10 uses 'constrained'/'callvirt' for calls to methods of restricted types
' (those with IsRestrictedType = True); Roslyn uses 'call' to match C# behavior
Return containingType.IsIntrinsicType OrElse containingType.IsRestrictedType
End Function
Private Sub EmitTypeOfExpression(expression As BoundTypeOf, used As Boolean, Optional optimize As Boolean = False)
Dim operand = expression.Operand
Debug.Assert(operand.Type.IsReferenceType AndAlso Not operand.Type.IsTypeParameter(), "operand.Type.IsReferenceType")
EmitExpression(operand, True)
If used Then
Dim typeFrom = operand.Type
Dim typeTo = expression.TargetType
_builder.EmitOpCode(ILOpCode.Isinst)
EmitSymbolToken(typeTo, expression.Syntax)
' If this expression is the condition of an If we can save these instructions
' and let the parent condition emit branches instead
If Not optimize Then
_builder.EmitOpCode(ILOpCode.Ldnull)
If expression.IsTypeOfIsNotExpression Then
_builder.EmitOpCode(ILOpCode.Ceq)
Else
_builder.EmitOpCode(ILOpCode.Cgt_un)
End If
End If
End If
EmitPopIfUnused(used)
End Sub
''' <summary>
''' Emit code for a ternary conditional operator.
''' </summary>
''' <remarks>
''' if (b, x, y) becomes
''' push b
''' if pop then goto CONSEQUENCE
''' push y
''' goto DONE
''' CONSEQUENCE:
''' push x
''' DONE:
''' </remarks>
Private Sub EmitTernaryConditionalExpression(expr As BoundTernaryConditionalExpression, used As Boolean)
Debug.Assert(expr.ConstantValueOpt Is Nothing, "Constant value should have been emitted directly")
Dim consequenceLabel = New Object()
Dim doneLabel = New Object()
EmitCondBranch(expr.Condition, consequenceLabel, sense:=True)
EmitExpression(expr.WhenFalse, used)
'
' III.1.8.1.3 Merging stack states
' . . .
' Let T be the type from the slot on the newly computed state and S
' be the type from the corresponding slot on the previously stored state. The merged type, U, shall
' be computed as follows (recall that S := T is the compatibility function defined
' in §III.1.8.1.2.2):
' 1. if S := T then U=S
' 2. Otherwise, if T := S then U=T
' 3. Otherwise, if S and T are both object types, then let V be the closest common supertype of S and T then U=V.
' 4. Otherwise, the merge shall fail.
'
' The issue is that, if the types don't match exactly but share an interface,
' there's no guarantee that the runtime will be able to find the interface.
' However, if you convert one of the types to the interface type, then it will
' work for both expression, and either (1) or (2) will succeed.
' This explains both (a) why this only applies to interfaces and (b) why it's
' okay to only explicitly convert one branch.
'
Dim mergeTypeOfAlternative As TypeSymbol = StackMergeType(expr.WhenFalse)
If (used) Then
If (IsVarianceCast(expr.Type, mergeTypeOfAlternative)) Then
EmitStaticCast(expr.Type, expr.Syntax)
mergeTypeOfAlternative = expr.Type
End If
End If
_builder.EmitBranch(ILOpCode.Br, doneLabel)
If (used) Then
' If we get to consequenceLabel, we should not have WhenFalse on stack, adjust for that.
_builder.AdjustStack(-1)
End If
_builder.MarkLabel(consequenceLabel)
EmitExpression(expr.WhenTrue, used)
If (used) Then
Dim mergeTypeOfConsequence As TypeSymbol = StackMergeType(expr.WhenTrue)
If (IsVarianceCast(expr.Type, mergeTypeOfConsequence)) Then
EmitStaticCast(expr.Type, expr.Syntax)
mergeTypeOfConsequence = expr.Type
ElseIf (expr.Type.IsInterfaceType() AndAlso expr.Type <> mergeTypeOfAlternative AndAlso expr.Type <> mergeTypeOfConsequence) Then
EmitStaticCast(expr.Type, expr.Syntax)
End If
End If
_builder.MarkLabel(doneLabel)
End Sub
''' <summary>
''' Emit code for a null-coalescing operator.
''' </summary>
''' <remarks>
''' if(x, y) becomes
''' push x
''' dup x
''' if pop isnot null goto LEFT_NOT_NULL
''' pop
''' push y
''' LEFT_NOT_NULL:
''' </remarks>
Private Sub EmitBinaryConditionalExpression(expr As BoundBinaryConditionalExpression, used As Boolean)
Debug.Assert(expr.ConvertedTestExpression Is Nothing, "coalesce with nontrivial test conversions are lowered into ternary.")
Debug.Assert(expr.Type = expr.ElseExpression.Type)
Debug.Assert(Not expr.Type.IsValueType)
EmitExpression(expr.TestExpression, used:=True)
' See the notes about verification type merges in EmitConditionalOperator
Dim mergeTypeOfLeftValue As TypeSymbol = StackMergeType(expr.TestExpression)
If (used) Then
If (IsVarianceCast(expr.Type, mergeTypeOfLeftValue)) Then
EmitStaticCast(expr.Type, expr.Syntax)
mergeTypeOfLeftValue = expr.Type
End If
_builder.EmitOpCode(ILOpCode.Dup)
End If
If (expr.Type.IsTypeParameter()) Then
EmitBox(expr.Type, expr.TestExpression.Syntax)
End If
Dim ifLeftNotNullLabel = New Object()
_builder.EmitBranch(ILOpCode.Brtrue, ifLeftNotNullLabel)
If (used) Then
_builder.EmitOpCode(ILOpCode.Pop)
End If
EmitExpression(expr.ElseExpression, used)
If (used) Then
Dim mergeTypeOfRightValue As TypeSymbol = StackMergeType(expr.ElseExpression)
If (IsVarianceCast(expr.Type, mergeTypeOfRightValue)) Then
EmitStaticCast(expr.Type, expr.Syntax)
mergeTypeOfRightValue = expr.Type
ElseIf (expr.Type.IsInterfaceType() AndAlso expr.Type <> mergeTypeOfLeftValue AndAlso expr.Type <> mergeTypeOfRightValue) Then
EmitStaticCast(expr.Type, expr.Syntax)
End If
End If
_builder.MarkLabel(ifLeftNotNullLabel)
End Sub
' Implicit casts are not emitted. As a result verifier may operate on a different
' types from the types of operands when performing stack merges in coalesce/ternary.
' Such differences are in general irrelevant since merging rules work the same way
' for base and derived types.
'
' Situation becomes more complicated with delegates, arrays and interfaces since they
' allow implicit casts from types that do not derive from them. In such cases
' we may need to introduce static casts in the code to prod the verifier to the
' right direction
'
' This helper returns actual type of array|interface|delegate expression ignoring implicit
' casts. This would be the effective stack merge type in the verifier.
'
' NOTE: In cases where stack merge type cannot be determined, we just return null.
' We still must assume that it can be an array, delegate or interface though.
Private Function StackMergeType(expr As BoundExpression) As TypeSymbol
' these cases are not interesting. Merge type is the same or derived. No difference.
If (Not (expr.Type.IsArrayType OrElse expr.Type.IsInterfaceType OrElse expr.Type.IsDelegateType)) Then
Return expr.Type
End If
' Dig through casts. We only need to check for expressions that -
' 1) are implicit casts
' 2) may transparently return operands, so we need to dig deeper
' 3) stack values
Select Case (expr.Kind)
Case BoundKind.DirectCast
Dim conversion = DirectCast(expr, BoundDirectCast)
Dim conversionKind = conversion.ConversionKind
If (Conversions.IsWideningConversion(conversionKind)) Then
Return StackMergeType(conversion.Operand)
End If
Case BoundKind.TryCast
Dim conversion = DirectCast(expr, BoundTryCast)
Dim conversionKind = conversion.ConversionKind
If (Conversions.IsWideningConversion(conversionKind)) Then
Return StackMergeType(conversion.Operand)
End If
'Case BoundKind.Conversion
' Dim conversion = DirectCast(expr, BoundConversion)
' Dim conversionKind = conversion.ConversionKind
' If (Conversions.IsWideningConversion(conversionKind)) Then
' Return StackMergeType(conversion.Operand)
' End If
Case BoundKind.AssignmentOperator
Dim assignment = DirectCast(expr, BoundAssignmentOperator)
Return StackMergeType(assignment.Right)
Case BoundKind.Sequence
Dim sequence = DirectCast(expr, BoundSequence)
Return StackMergeType(sequence.ValueOpt)
Case BoundKind.Local
Dim local = DirectCast(expr, BoundLocal)
If (Me.IsStackLocal(local.LocalSymbol)) Then
' stack value, we cannot be sure what it is
Return Nothing
End If
Case BoundKind.Dup
' stack value, we cannot be sure what it is
Return Nothing
End Select
Return expr.Type
End Function
' Although III.1.8.1.3 seems to imply that verifier understands variance casts.
' It appears that verifier/JIT gets easily confused.
' So to not rely on whether that should work or not we will flag potentially
' "complicated" casts and make them static casts to ensure we are all on
' the same page with what type should be tracked.
Private Shared Function IsVarianceCast(toType As TypeSymbol, fromType As TypeSymbol) As Boolean
If (toType = fromType) Then
Return False
End If
If (fromType Is Nothing) Then
' from unknown type - this could be a variance conversion.
Return True
End If
' while technically variance casts, array conversions do not seem to be a problem
' unless the element types are converted via variance.
If (toType.IsArrayType) Then
Return IsVarianceCast(DirectCast(toType, ArrayTypeSymbol).ElementType, DirectCast(fromType, ArrayTypeSymbol).ElementType)
End If
Return (toType.IsDelegateType() AndAlso toType <> fromType) OrElse
(toType.IsInterfaceType() AndAlso fromType.IsInterfaceType() AndAlso
Not fromType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.ContainsKey(DirectCast(toType, NamedTypeSymbol)))
End Function
Private Sub EmitStaticCast(toType As TypeSymbol, syntax As SyntaxNode)
Debug.Assert(toType.IsVerifierReference())
' From ILGENREC::GenQMark
' See VSWhidbey Bugs #49619 and 108643. If the destination type is an interface we need
' to force a static cast to be generated for any cast result expressions. The static cast
' should be done before the unifying jump so the code is verifiable and to allow the JIT to
' optimize it away. NOTE: Since there is no staticcast instruction, we implement static cast
' with a stloc / ldloc to a temporary.
' Bug: VSWhidbey/49619
' Bug: VSWhidbey/108643
' Bug: DevDivBugs/42645
Dim temp = AllocateTemp(toType, syntax)
_builder.EmitLocalStore(temp)
_builder.EmitLocalLoad(temp)
FreeTemp(temp)
End Sub
Private Sub EmitArrayCreationExpression(expression As BoundArrayCreation, used As Boolean)
Dim arrayType = DirectCast(expression.Type, ArrayTypeSymbol)
EmitExpressions(expression.Bounds, True)
If arrayType.IsSZArray Then
_builder.EmitOpCode(ILOpCode.Newarr)
EmitSymbolToken(arrayType.ElementType, expression.Syntax)
Else
_builder.EmitArrayCreation(_module.Translate(arrayType), expression.Syntax, _diagnostics)
End If
If expression.InitializerOpt IsNot Nothing Then
EmitArrayInitializers(arrayType, expression.InitializerOpt)
End If
EmitPopIfUnused(used)
End Sub
Private Sub EmitArrayLengthExpression(expression As BoundArrayLength, used As Boolean)
Debug.Assert(expression.Type.SpecialType = SpecialType.System_Int32 OrElse expression.Type.SpecialType = SpecialType.System_Int64 OrElse expression.Type.SpecialType = SpecialType.System_UIntPtr)
EmitExpression(expression.Expression, used:=True)
_builder.EmitOpCode(ILOpCode.Ldlen)
Dim typeTo = expression.Type.PrimitiveTypeCode
' NOTE: ldlen returns native uint, but newarr takes native int, so the length value is always
' a positive native int. We can treat it as either signed or unsigned.
' We will use whatever typeTo says so we do not need to convert because of sign.
Dim typeFrom = If(typeTo.IsUnsigned(), Microsoft.Cci.PrimitiveTypeCode.UIntPtr, Microsoft.Cci.PrimitiveTypeCode.IntPtr)
' NOTE In Dev10 VB this cast Is checked.
'
' Emitting checked conversion however results in redundant overflow checks on 64bit And also inhibits range check hoisting in loops.
' Therefore we will emit unchecked conversion here as C# compiler always did.
_builder.EmitNumericConversion(typeFrom, typeTo, checked:=False)
EmitPopIfUnused(used)
End Sub
Private Sub EmitObjectCreationExpression(expression As BoundObjectCreationExpression, used As Boolean)
' if there is no constructor or it is synthesized, we do not call it, call initobj instead
If expression.IsDefaultValue Then
EmitInitObj(expression.Type, used, expression.Syntax)
Else
Dim constructor As MethodSymbol = expression.ConstructorOpt
EmitNewObj(expression.ConstructorOpt, expression.Arguments, used, expression.Syntax)
End If
End Sub
Private Sub EmitInitObj(type As TypeSymbol, used As Boolean, syntaxNode As SyntaxNode)
If (used) Then
Dim temp = Me.AllocateTemp(type, syntaxNode)
_builder.EmitLocalAddress(temp) ' ldloca temp
_builder.EmitOpCode(ILOpCode.Initobj) ' initobj <MyStruct>
EmitSymbolToken(type, syntaxNode)
_builder.EmitLocalLoad(temp) ' ldloc temp
FreeTemp(temp)
End If
End Sub
Private Sub EmitNewObj(constructor As MethodSymbol,
arguments As ImmutableArray(Of BoundExpression),
used As Boolean,
syntaxNode As SyntaxNode)
Debug.Assert(Not constructor.IsDefaultValueTypeConstructor(),
"do not call synthesized struct constructors, they do not exist")
EmitArguments(arguments, constructor.Parameters)
_builder.EmitOpCode(ILOpCode.Newobj, ILOpCode.Newobj.StackPushCount() - arguments.Length)
EmitSymbolToken(constructor, syntaxNode)
EmitPopIfUnused(used)
End Sub
Private Sub EmitLoadDefaultValueOfTypeParameter(type As TypeSymbol, used As Boolean, syntaxNode As SyntaxNode)
Debug.Assert(type.IsTypeParameter)
EmitLoadDefaultValueOfTypeFromNothingLiteral(type, used, syntaxNode)
End Sub
Private Sub EmitLoadDefaultValueOfTypeFromNothingLiteral(type As TypeSymbol, used As Boolean, syntaxNode As SyntaxNode)
EmitInitObj(type, used, syntaxNode)
End Sub
Private Sub EmitStructConstructorCallOnTarget(constructor As MethodSymbol,
arguments As ImmutableArray(Of BoundExpression),
target As BoundExpression,
syntaxNode As VisualBasicSyntaxNode)
Debug.Assert(target.IsLValue OrElse target.Kind = BoundKind.MeReference OrElse
(target.Kind = BoundKind.Local AndAlso DirectCast(target, BoundLocal).LocalSymbol.IsReadOnly))
If target.Kind = BoundKind.Local AndAlso IsStackLocal(DirectCast(target, BoundLocal).LocalSymbol) Then
' A newobj for a struct will create a new object on the stack for stack locals
EmitNewObj(constructor, arguments, True, syntaxNode)
Return
End If
' NOTE!!!: We are misusing isReadOnly here!!!
'
' We are creating a fully modifiable reference to a struct in order to initialize it.
' In fact we are going to pass the reference as a byref arg to a constructor
' (which can do whatever it wants with it - pass it byref to somebody else, etc...)
'
' We are still going to say the reference is immutable. Since we are initializing, there is nothing to mutate.
'
' Also note that we will not produce controlled mutability pointers here too.
' since the target is definitely a struct, it cannot be accessed covariantly.
'
EmitAddress(target, addressKind:=AddressKind.Immutable)
' otherwise instead of 'Initobj' the constructor should be called
' NOTE: we don't call initobj before calling constructor following Dev10 implementation. This
' may cause errors in some scenarios in case constructor does not initialize all the fields
' TODO: revise?
' emit constructor call
Dim stackBehavior = -constructor.ParameterCount - 1
EmitArguments(arguments, constructor.Parameters)
_builder.EmitOpCode(ILOpCode.Call, stackBehavior)
EmitSymbolToken(constructor, syntaxNode)
End Sub
Private Sub EmitInitObjOnTarget(target As BoundExpression)
' NOTE!!!: We are misusing isReadOnly here!!!
'
' We are creating a fully modifiable reference to a struct in order to initialize it.
' In fact we are going to wipe the target
'
' We are still going to say the reference is immutable. Since we are initializing,
' there is nothing to mutate.
' If we have to call an initobj a stack local, we still have to create a temp
If target.Kind = BoundKind.Local AndAlso IsStackLocal(DirectCast(target, BoundLocal).LocalSymbol) Then
EmitInitObj(target.Type, True, target.Syntax)
Return
End If
' Stack local should be on stack
Debug.Assert(target.Kind <> BoundKind.Local OrElse Not IsStackLocal(DirectCast(target, BoundLocal).LocalSymbol))
EmitAddress(target, addressKind:=AddressKind.Immutable)
_builder.EmitOpCode(ILOpCode.Initobj)
EmitSymbolToken(target.Type, target.Syntax)
End Sub
Private Sub EmitConstantExpression(type As TypeSymbol, constantValue As ConstantValue, used As Boolean, syntaxNode As SyntaxNode)
' unused constant has no side-effects
If used Then
' Null type parameter values must be emitted as 'initobj' rather than 'ldnull'.
If ((type IsNot Nothing) AndAlso (type.TypeKind = TypeKind.TypeParameter) AndAlso constantValue.IsNull) Then
EmitInitObj(type, used, syntaxNode)
Else
_builder.EmitConstantValue(constantValue)
End If
End If
End Sub
Private Sub EmitConstantExpression(expression As BoundExpression)
_builder.EmitConstantValue(expression.ConstantValueOpt)
End Sub
Private Sub EmitAssignmentExpression(assignmentOperator As BoundAssignmentOperator, used As Boolean)
If Me.TryEmitAssignmentInPlace(assignmentOperator, used) Then
Return
End If
' Assignment expression codegen has the following parts:
'
' * PreRHS: We need to emit instructions before the load of the right hand side if:
' - If the left hand side is a ref local or ref formal parameter and the right hand
' side is a value then we must put the ref on the stack early so that we can store
' indirectly into it.
' - If the left hand side is an array slot then we must evaluate the array and indices
' before we evaluate the right hand side. We ensure that the array and indices are
' on the stack when the store is executed.
' - Similarly, if the left hand side is a non-static field then its receiver must be
' evaluated before the right hand side.
'
' * RHS: There are three possible ways to do an assignment with respect to "refness",
' and all are found in the lowering of:
'
' N().s += 10;
'
' That expression is realized as
'
' ref int addr = ref N().s; ' Assign a ref on the right hand side to the left hand side.
' int sum = addr + 10; ' No refs at all; assign directly to sum.
' addr = sum; ' Assigns indirectly through the address.
'
' - If we are in the first case then assignmentOperator.RefKind is Ref and the left hand side is a
' ref local temporary. We simply assign the ref on the RHS to the storage on the LHS with no indirection.
'
' - If we are in the second case then nothing is ref; we have a value on one side an a local on the other.
' Again, there is no indirection.
'
' - If we are in the third case then we have a ref on the left and a value on the right. We must compute the
' value of the right hand side and then store it into the left hand side.
'
' * Duplication: The result of an assignment operation is the value that was assigned. It is possible that
' later codegen is expecting this value to be on the stack when we're done here. This is controlled by
' the "used" formal parameter. There are two possible cases:
' - If the preamble put stuff on the stack for the usage of the store, then we must not put an extra copy
' of the right hand side value on the stack; that will be between the value and the stuff needed to
' do the storage. In that case we put the right hand side value in a temporary and restore it later.
' - Otherwise we can just do a dup instruction; there's nothing before the dup on the stack that we'll need.
'
' * Storage: Either direct or indirect, depending. See the RHS section above for details.
'
' * Post-storage: If we stashed away the duplicated value in the temporary, we need to restore it back to the stack.
Dim lhsUsesStack As Boolean = Me.EmitAssignmentPreamble(assignmentOperator.Left)
Me.EmitExpression(assignmentOperator.Right, used:=True)
Dim temp As LocalDefinition = Me.EmitAssignmentDuplication(assignmentOperator, used, lhsUsesStack)
Me.EmitStore(assignmentOperator.Left)
Me.EmitAssignmentPostfix(temp)
End Sub
' sometimes it is possible and advantageous to get an address of the lHS and
' perform assignment as an in-place initialization via initobj or constructor invocation.
'
' 1) initobj
' is used when assigning default value to T that is not a verifier reference.
'
' 2) inplace ctor call
' is used when assigning a freshly created struct. "x = new S(arg)" can be
' replaced by x.S(arg) as long as partial assignment cannot be observed -
' i.e. target must not be on the heap and we should not be in a try block.
Private Function TryEmitAssignmentInPlace(assignmentOperator As BoundAssignmentOperator, used As Boolean) As Boolean
Dim left As BoundExpression = assignmentOperator.Left
' if result is used, and lives on heap, we must keep RHS value on the stack.
' otherwise we can try conjuring up the RHS value directly where it belongs.
If used AndAlso Not Me.TargetIsNotOnHeap(left) Then
Return False
End If
If Not SafeToGetWriteableReference(left) Then
' cannot take a ref
Return False
End If
Dim right As BoundExpression = assignmentOperator.Right
Dim rightType = right.Type
If Not rightType.IsTypeParameter Then
If rightType.IsReferenceType OrElse (right.ConstantValueOpt IsNot Nothing AndAlso rightType.SpecialType <> SpecialType.System_Decimal) Then
' in-place is not advantageous for reference types or constants
Return False
End If
End If
If right.IsDefaultValue() Then
Me.InPlaceInit(left, used)
Return True
Else
If right.Kind = BoundKind.ObjectCreationExpression Then
' It is desirable to do in-place ctor call if possible.
' we could do newobj/stloc, but inplace call
' produces same or better code in current JITs
If Me.PartialCtorResultCannotEscape(left) Then
Dim objCreation As BoundObjectCreationExpression = DirectCast(right, BoundObjectCreationExpression)
Me.InPlaceCtorCall(left, objCreation, used)
Return True
End If
End If
End If
Return False
End Function
' because of array covariance, taking a reference to an element of
' generic array may fail even though assignment "arr(i) = Nothing" would always succeed.
Private Function SafeToGetWriteableReference(left As BoundExpression) As Boolean
Return AllowedToTakeRef(left, AddressKind.Writeable) AndAlso Not (left.Kind = BoundKind.ArrayAccess AndAlso left.Type.TypeKind = TypeKind.TypeParameter)
End Function
Private Sub InPlaceInit(target As BoundExpression, used As Boolean)
Dim temp = Me.EmitAddress(target, AddressKind.Writeable)
Debug.Assert(temp Is Nothing, "temp is not expected when in-place assigning")
Me._builder.EmitOpCode(ILOpCode.Initobj) ' initobj <MyStruct>
Me.EmitSymbolToken(target.Type, target.Syntax)
If used Then
Debug.Assert(Me.TargetIsNotOnHeap(target), "cannot read-back the target since it could have been modified")
Me.EmitExpression(target, used = True)
End If
End Sub
Private Sub InPlaceCtorCall(target As BoundExpression, objCreation As BoundObjectCreationExpression, used As Boolean)
Dim temp = Me.EmitAddress(target, AddressKind.Writeable)
Debug.Assert(temp Is Nothing, "temp is not expected when in-place assigning")
Dim constructor As MethodSymbol = objCreation.ConstructorOpt
Me.EmitArguments(objCreation.Arguments, constructor.Parameters)
' +1 to adjust for consumed target address
Dim stackAdjustment As Integer = constructor.ParameterCount + 1
Me._builder.EmitOpCode(ILOpCode.[Call], -stackAdjustment)
Me.EmitSymbolToken(constructor, objCreation.Syntax)
If used Then
Debug.Assert(Me.TargetIsNotOnHeap(target), "cannot read-back the target since it could have been modified")
Me.EmitExpression(target, used = True)
End If
End Sub
' partial ctor results are not observable when target is not on the heap.
' we also must not be in a try, otherwise if ctor throws
' partially assigned value may be observed in the handler.
Private Function PartialCtorResultCannotEscape(left As BoundExpression) As Boolean
Return Me._tryNestingLevel = 0 AndAlso Me.TargetIsNotOnHeap(left)
End Function
Private Function TargetIsNotOnHeap(left As BoundExpression) As Boolean
Select Case left.Kind
Case BoundKind.Local
Return Not DirectCast(left, BoundLocal).LocalSymbol.IsByRef
Case BoundKind.Parameter
Return Not DirectCast(left, BoundParameter).ParameterSymbol.IsByRef
Case BoundKind.ReferenceAssignment
Return False
End Select
Return False
End Function
Private Function EmitAssignmentPreamble(assignmentTarget As BoundExpression) As Boolean
Dim lhsUsesStack = False
Select Case assignmentTarget.Kind
Case BoundKind.Local
Dim boundLocal = DirectCast(assignmentTarget, BoundLocal)
If boundLocal.LocalSymbol.IsByRef Then
If IsStackLocal(boundLocal.LocalSymbol) Then
' the address is supposed to already be on stack
Else
_builder.EmitLocalLoad(GetLocal(boundLocal))
End If
lhsUsesStack = True
End If
Case BoundKind.ReferenceAssignment
EmitReferenceAssignment(DirectCast(assignmentTarget, BoundReferenceAssignment), used:=True, needReference:=True)
lhsUsesStack = True
Case BoundKind.FieldAccess
Dim left = DirectCast(assignmentTarget, BoundFieldAccess)
If Not left.FieldSymbol.IsShared Then
' we will not write to the receiver, but will write into its field.
Dim temp = EmitReceiverRef(left.ReceiverOpt, isAccessConstrained:=False, addressKind:=AddressKind.ReadOnly)
Debug.Assert(temp Is Nothing, "temp is unexpected when writing to a field")
lhsUsesStack = True
End If
Case BoundKind.Parameter
Dim left = DirectCast(assignmentTarget, BoundParameter)
If left.ParameterSymbol.IsByRef Then
_builder.EmitLoadArgumentOpcode(ParameterSlot(left))
lhsUsesStack = True
End If
Case BoundKind.ArrayAccess
Dim left = DirectCast(assignmentTarget, BoundArrayAccess)
EmitExpression(left.Expression, True)
EmitExpressions(left.Indices, True)
lhsUsesStack = True
Case BoundKind.MeReference
Dim left = DirectCast(assignmentTarget, BoundMeReference)
' why do we even need to handle this case? VB doesn't allow assigning to 'Me'.
Debug.Assert(False)
Dim temp = EmitAddress(left, addressKind:=AddressKind.Writeable)
Debug.Assert(temp Is Nothing, "taking ref of Me should not create a temp")
lhsUsesStack = True
Case BoundKind.PseudoVariable
EmitPseudoVariableAddress(DirectCast(assignmentTarget, BoundPseudoVariable))
lhsUsesStack = True
Case BoundKind.Sequence
Dim sequence = DirectCast(assignmentTarget, BoundSequence)
If Not sequence.Locals.IsEmpty Then
_builder.OpenLocalScope()
For Each local In sequence.Locals
Me.DefineLocal(local, sequence.Syntax)
Next
End If
Me.EmitSideEffects(sequence.SideEffects)
lhsUsesStack = EmitAssignmentPreamble(sequence.ValueOpt)
Case BoundKind.Call
Dim left = DirectCast(assignmentTarget, BoundCall)
Debug.Assert(left.Method.ReturnsByRef)
EmitCallExpression(left, UseKind.UsedAsAddress)
lhsUsesStack = True
Case BoundKind.ModuleVersionId, BoundKind.InstrumentationPayloadRoot
Case Else
Throw ExceptionUtilities.UnexpectedValue(assignmentTarget.Kind)
End Select
Return lhsUsesStack
End Function
Private Function EmitAssignmentDuplication(assignmentOperator As BoundAssignmentOperator, used As Boolean, lhsUsesStack As Boolean) As LocalDefinition
Dim temp As LocalDefinition = Nothing
If used Then
Me._builder.EmitOpCode(ILOpCode.Dup)
If lhsUsesStack Then
temp = Me.AllocateTemp(assignmentOperator.Left.Type, assignmentOperator.Left.Syntax)
Me._builder.EmitLocalStore(temp)
End If
End If
Return temp
End Function
Private Sub EmitAssignmentPostfix(temp As LocalDefinition)
If temp IsNot Nothing Then
Me._builder.EmitLocalLoad(temp)
Me.FreeTemp(temp)
End If
End Sub
Private Sub EmitReferenceAssignment(capture As BoundReferenceAssignment, used As Boolean, Optional needReference As Boolean = False)
Debug.Assert(Not needReference OrElse used)
Dim temp = EmitAddress(capture.LValue, addressKind:=AddressKind.Writeable)
Debug.Assert(temp Is Nothing, "reference assignment should not clone the referent")
If used Then
_builder.EmitOpCode(ILOpCode.Dup)
End If
Dim boundLocal As BoundLocal = capture.ByRefLocal
Debug.Assert(boundLocal.LocalSymbol.IsByRef)
If IsStackLocal(boundLocal.LocalSymbol) Then
' just leave the address on stack
Else
Dim local = GetLocal(boundLocal)
_builder.EmitLocalStore(local)
End If
If used AndAlso Not needReference Then
EmitLoadIndirect(capture.Type, capture.Syntax)
End If
End Sub
Private Sub EmitStore(expression As BoundExpression)
Select Case expression.Kind
Case BoundKind.FieldAccess
EmitFieldStore(DirectCast(expression, BoundFieldAccess))
Case BoundKind.Local
Dim boundLocal = DirectCast(expression, BoundLocal)
If boundLocal.LocalSymbol.IsByRef Then
EmitStoreIndirect(boundLocal.LocalSymbol.Type, expression.Syntax)
ElseIf IsStackLocal(boundLocal.LocalSymbol) Then
' just leave original value on stack
Else
Dim local = GetLocal(boundLocal)
_builder.EmitLocalStore(local)
End If
Case BoundKind.ReferenceAssignment,
BoundKind.PseudoVariable
EmitStoreIndirect(expression.Type, expression.Syntax)
Case BoundKind.ArrayAccess
Dim array = DirectCast(expression, BoundArrayAccess).Expression
Dim arrayType = DirectCast(array.Type, ArrayTypeSymbol)
EmitArrayElementStore(arrayType, expression.Syntax)
Case BoundKind.MeReference
EmitMeStore(DirectCast(expression, BoundMeReference))
Case BoundKind.Parameter
EmitParameterStore(DirectCast(expression, BoundParameter))
Case BoundKind.Sequence
Dim sequence = DirectCast(expression, BoundSequence)
EmitStore(sequence.ValueOpt)
If Not sequence.Locals.IsEmpty Then
_builder.CloseLocalScope()
For Each local In sequence.Locals
Me.FreeLocal(local)
Next
End If
Case BoundKind.Call
Debug.Assert(DirectCast(expression, BoundCall).Method.ReturnsByRef)
EmitStoreIndirect(expression.Type, expression.Syntax)
Case BoundKind.ModuleVersionId
EmitModuleVersionIdStore(DirectCast(expression, BoundModuleVersionId))
Case BoundKind.InstrumentationPayloadRoot
EmitInstrumentationPayloadRootStore(DirectCast(expression, BoundInstrumentationPayloadRoot))
Case Else
Throw ExceptionUtilities.UnexpectedValue(expression.Kind)
End Select
End Sub
Private Sub EmitMeStore(thisRef As BoundMeReference)
Debug.Assert(thisRef.Type.IsValueType)
_builder.EmitOpCode(ILOpCode.Stobj)
EmitSymbolToken(thisRef.Type, thisRef.Syntax)
End Sub
Private Sub EmitArrayElementStore(arrayType As ArrayTypeSymbol, syntaxNode As SyntaxNode)
If arrayType.IsSZArray Then
EmitVectorElementStore(arrayType, syntaxNode)
Else
_builder.EmitArrayElementStore(_module.Translate(arrayType), syntaxNode, _diagnostics)
End If
End Sub
''' <summary>
''' Emit an element store instruction for a single dimensional array.
''' </summary>
Private Sub EmitVectorElementStore(arrayType As ArrayTypeSymbol, syntaxNode As SyntaxNode)
Dim elementType = arrayType.ElementType
If elementType.IsEnumType() Then
'underlying primitives do not need type tokens.
elementType = (DirectCast(elementType, NamedTypeSymbol)).EnumUnderlyingType
End If
Select Case elementType.PrimitiveTypeCode
Case Microsoft.Cci.PrimitiveTypeCode.Boolean,
Microsoft.Cci.PrimitiveTypeCode.Int8,
Microsoft.Cci.PrimitiveTypeCode.UInt8
_builder.EmitOpCode(ILOpCode.Stelem_i1)
Case Microsoft.Cci.PrimitiveTypeCode.Char,
Microsoft.Cci.PrimitiveTypeCode.Int16,
Microsoft.Cci.PrimitiveTypeCode.UInt16
_builder.EmitOpCode(ILOpCode.Stelem_i2)
Case Microsoft.Cci.PrimitiveTypeCode.Int32,
Microsoft.Cci.PrimitiveTypeCode.UInt32
_builder.EmitOpCode(ILOpCode.Stelem_i4)
Case Microsoft.Cci.PrimitiveTypeCode.Int64,
Microsoft.Cci.PrimitiveTypeCode.UInt64
_builder.EmitOpCode(ILOpCode.Stelem_i8)
Case Microsoft.Cci.PrimitiveTypeCode.IntPtr,
Microsoft.Cci.PrimitiveTypeCode.UIntPtr,
Microsoft.Cci.PrimitiveTypeCode.Pointer
_builder.EmitOpCode(ILOpCode.Stelem_i)
Case Microsoft.Cci.PrimitiveTypeCode.Float32
_builder.EmitOpCode(ILOpCode.Stelem_r4)
Case Microsoft.Cci.PrimitiveTypeCode.Float64
_builder.EmitOpCode(ILOpCode.Stelem_r8)
Case Else
If IsVerifierReference(elementType) Then
_builder.EmitOpCode(ILOpCode.Stelem_ref)
Else
_builder.EmitOpCode(ILOpCode.Stelem)
EmitSymbolToken(elementType, syntaxNode)
End If
End Select
End Sub
Private Sub EmitFieldStore(fieldAccess As BoundFieldAccess)
Dim field As FieldSymbol = fieldAccess.FieldSymbol
If field.IsShared Then
_builder.EmitOpCode(ILOpCode.Stsfld)
Else
_builder.EmitOpCode(ILOpCode.Stfld)
End If
EmitSymbolToken(field, fieldAccess.Syntax)
End Sub
Private Sub EmitParameterStore(parameter As BoundParameter)
If Not parameter.ParameterSymbol.IsByRef Then
Dim slot As Integer = ParameterSlot(parameter)
_builder.EmitStoreArgumentOpcode(slot)
Else
'NOTE: we should have the actual parameter already loaded,
'now need to do a store to where it points to
EmitStoreIndirect(parameter.ParameterSymbol.Type, parameter.Syntax)
End If
End Sub
Private Sub EmitStoreIndirect(type As TypeSymbol, syntaxNode As SyntaxNode)
If type.IsEnumType() Then
type = (DirectCast(type, NamedTypeSymbol)).EnumUnderlyingType
End If
Select Case type.PrimitiveTypeCode
Case Microsoft.Cci.PrimitiveTypeCode.Boolean,
Microsoft.Cci.PrimitiveTypeCode.Int8,
Microsoft.Cci.PrimitiveTypeCode.UInt8
_builder.EmitOpCode(ILOpCode.Stind_i1)
Case Microsoft.Cci.PrimitiveTypeCode.Char,
Microsoft.Cci.PrimitiveTypeCode.Int16,
Microsoft.Cci.PrimitiveTypeCode.UInt16
_builder.EmitOpCode(ILOpCode.Stind_i2)
Case Microsoft.Cci.PrimitiveTypeCode.Int32,
Microsoft.Cci.PrimitiveTypeCode.UInt32
_builder.EmitOpCode(ILOpCode.Stind_i4)
Case Microsoft.Cci.PrimitiveTypeCode.Int64,
Microsoft.Cci.PrimitiveTypeCode.UInt64
_builder.EmitOpCode(ILOpCode.Stind_i8)
Case Microsoft.Cci.PrimitiveTypeCode.IntPtr,
Microsoft.Cci.PrimitiveTypeCode.UIntPtr,
Microsoft.Cci.PrimitiveTypeCode.Pointer
_builder.EmitOpCode(ILOpCode.Stind_i)
Case Microsoft.Cci.PrimitiveTypeCode.Float32
_builder.EmitOpCode(ILOpCode.Stind_r4)
Case Microsoft.Cci.PrimitiveTypeCode.Float64
_builder.EmitOpCode(ILOpCode.Stind_r8)
Case Else
If IsVerifierReference(type) Then
_builder.EmitOpCode(ILOpCode.Stind_ref)
Else
_builder.EmitOpCode(ILOpCode.Stobj)
EmitSymbolToken(type, syntaxNode)
End If
End Select
End Sub
Private Sub EmitPopIfUnused(used As Boolean)
If Not used Then
_builder.EmitOpCode(ILOpCode.Pop)
End If
End Sub
Private Sub EmitGetType(boundTypeOfOperator As BoundGetType, used As Boolean)
' an unused GetType can have side effects because it can e.g. throw a TypeLoadException
Dim type As TypeSymbol = boundTypeOfOperator.SourceType.Type
_builder.EmitOpCode(ILOpCode.Ldtoken)
EmitSymbolToken(type, boundTypeOfOperator.SourceType.Syntax)
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment:=0) 'argument off, return value on
Dim getTypeMethod = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Type__GetTypeFromHandle), MethodSymbol)
Debug.Assert(getTypeMethod IsNot Nothing) ' Should have been checked during binding
EmitSymbolToken(getTypeMethod, boundTypeOfOperator.Syntax)
EmitPopIfUnused(used)
End Sub
Private Sub EmitFieldInfoExpression(node As BoundFieldInfo, used As Boolean)
_builder.EmitOpCode(ILOpCode.Ldtoken)
EmitSymbolToken(node.Field, node.Syntax)
Dim getField As MethodSymbol
If Not node.Field.ContainingType.IsGenericType Then
Debug.Assert(Not node.Field.ContainingType.IsAnonymousType) ' NO anonymous types field access expected
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment:=0) ' argument off, return value on
getField = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Reflection_FieldInfo__GetFieldFromHandle), MethodSymbol)
Else
_builder.EmitOpCode(ILOpCode.Ldtoken)
EmitSymbolToken(node.Field.ContainingType, node.Syntax)
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment:=-1) ' 2 arguments off, return value on
getField = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Reflection_FieldInfo__GetFieldFromHandle2), MethodSymbol)
End If
Debug.Assert(getField IsNot Nothing)
EmitSymbolToken(getField, node.Syntax)
If node.Type <> getField.ReturnType Then
_builder.EmitOpCode(ILOpCode.Castclass)
EmitSymbolToken(node.Type, node.Syntax)
End If
EmitPopIfUnused(used)
End Sub
Private Sub EmitMethodInfoExpression(node As BoundMethodInfo, used As Boolean)
_builder.EmitOpCode(ILOpCode.Ldtoken)
EmitSymbolToken(node.Method, node.Syntax)
Dim getMethod As MethodSymbol
If Not node.Method.ContainingType.IsGenericType AndAlso Not node.Method.ContainingType.IsAnonymousType Then ' anonymous types are generic under the hood.
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment:=0) ' argument off, return value on
getMethod = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Reflection_MethodBase__GetMethodFromHandle), MethodSymbol)
Else
_builder.EmitOpCode(ILOpCode.Ldtoken)
EmitSymbolToken(node.Method.ContainingType, node.Syntax)
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment:=-1) ' 2 arguments off, return value on
getMethod = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Reflection_MethodBase__GetMethodFromHandle2), MethodSymbol)
End If
Debug.Assert(getMethod IsNot Nothing)
EmitSymbolToken(getMethod, node.Syntax)
If node.Type <> getMethod.ReturnType Then
_builder.EmitOpCode(ILOpCode.Castclass)
EmitSymbolToken(node.Type, node.Syntax)
End If
EmitPopIfUnused(used)
End Sub
Private Sub EmitBox(type As TypeSymbol, syntaxNode As SyntaxNode)
_builder.EmitOpCode(ILOpCode.Box)
EmitSymbolToken(type, syntaxNode)
End Sub
Private Sub EmitUnboxAny(type As TypeSymbol, syntaxNode As SyntaxNode)
_builder.EmitOpCode(ILOpCode.Unbox_any)
EmitSymbolToken(type, syntaxNode)
End Sub
Private Sub EmitMethodDefIndexExpression(node As BoundMethodDefIndex)
Debug.Assert(node.Method.IsDefinition)
Debug.Assert(node.Type.SpecialType = SpecialType.System_Int32)
_builder.EmitOpCode(ILOpCode.Ldtoken)
' For partial methods, we emit pseudo token based on the symbol for the partial
' definition part as opposed to the symbol for the partial implementation part.
' We will need to resolve the symbol associated with each pseudo token in order
' to compute the real method definition tokens later. For partial methods, this
' resolution can only succeed if the associated symbol is the symbol for the
' partial definition and not the symbol for the partial implementation (see
' MethodSymbol.ResolvedMethodImpl()).
Dim symbol = If(node.Method.PartialDefinitionPart, node.Method)
EmitSymbolToken(symbol, node.Syntax, encodeAsRawDefinitionToken:=True)
End Sub
Private Sub EmitMaximumMethodDefIndexExpression(node As BoundMaximumMethodDefIndex)
Debug.Assert(node.Type.SpecialType = SpecialType.System_Int32)
_builder.EmitOpCode(ILOpCode.Ldtoken)
_builder.EmitGreatestMethodToken()
End Sub
Private Sub EmitModuleVersionIdLoad(node As BoundModuleVersionId)
_builder.EmitOpCode(ILOpCode.Ldsfld)
EmitModuleVersionIdToken(node)
End Sub
Private Sub EmitModuleVersionIdStore(node As BoundModuleVersionId)
_builder.EmitOpCode(ILOpCode.Stsfld)
EmitModuleVersionIdToken(node)
End Sub
Private Sub EmitModuleVersionIdToken(node As BoundModuleVersionId)
_builder.EmitToken(_module.GetModuleVersionId(_module.Translate(node.Type, node.Syntax, _diagnostics), node.Syntax, _diagnostics), node.Syntax, _diagnostics)
End Sub
Private Sub EmitModuleVersionIdStringLoad(node As BoundModuleVersionIdString)
_builder.EmitOpCode(ILOpCode.Ldstr)
_builder.EmitModuleVersionIdStringToken()
End Sub
Private Sub EmitInstrumentationPayloadRootLoad(node As BoundInstrumentationPayloadRoot)
_builder.EmitOpCode(ILOpCode.Ldsfld)
EmitInstrumentationPayloadRootToken(node)
End Sub
Private Sub EmitInstrumentationPayloadRootStore(node As BoundInstrumentationPayloadRoot)
_builder.EmitOpCode(ILOpCode.Stsfld)
EmitInstrumentationPayloadRootToken(node)
End Sub
Private Sub EmitInstrumentationPayloadRootToken(node As BoundInstrumentationPayloadRoot)
_builder.EmitToken(_module.GetInstrumentationPayloadRoot(node.AnalysisKind, _module.Translate(node.Type, node.Syntax, _diagnostics), node.Syntax, _diagnostics), node.Syntax, _diagnostics)
End Sub
Private Sub EmitSourceDocumentIndex(node As BoundSourceDocumentIndex)
Debug.Assert(node.Type.SpecialType = SpecialType.System_Int32)
_builder.EmitOpCode(ILOpCode.Ldtoken)
_builder.EmitSourceDocumentIndexToken(node.Document)
End Sub
End Class
End Namespace
|
DustinCampbell/roslyn
|
src/Compilers/VisualBasic/Portable/CodeGen/EmitExpression.vb
|
Visual Basic
|
apache-2.0
| 107,357
|
' 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.Simplification
Public Class NullableAnnotationSimplificationTests
Inherits AbstractSimplificationTests
#Region "CSharp tests"
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpLeaveAnnotationIfValidAndEnabled() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
#nullable enable
class C
{
void M()
{
{|SimplifyParent:string?|} x;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
#nullable enable
class C
{
void M()
{
string? x;
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpRemoveAnnotationIfDisabled() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
#nullable disable
class C
{
void M()
{
{|SimplifyParent:string?|} x;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
#nullable disable
class C
{
void M()
{
string x;
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpRemoveAnnotationLeavesTrivia() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
#nullable disable
class C
{
void M()
{
{|SimplifyParent:/*before*/string/*inner*/?/*after*/|} x;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
#nullable disable
class C
{
void M()
{
/*before*/string/*inner*//*after*/ x;
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpLeaveAnnotationIfStructType() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
#nullable disable
class C
{
void M()
{
{|SimplifyParent:int?|} x;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
#nullable disable
class C
{
void M()
{
int? x;
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpLeaveAnnotationIfUnconstrainedGeneric() As Task
' Putting a ? on a unconstrained generic is illegal, but for now we're going to be cautious and not remove any ?s on unconstrained generics.
' If we need extra smarts to clean these up it's not hard, but there's no reason to do it until we have a reason.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
#nullable disable
class C
{
void M<T>()
{
{|SimplifyParent:T?|} x;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
#nullable disable
class C
{
void M<T>()
{
T? x;
}
}
</code>
Await TestAsync(input, expected)
End Function
#End Region
End Class
End Namespace
|
aelij/roslyn
|
src/EditorFeatures/Test2/Simplification/NullableAnnotationSimplificationTests.vb
|
Visual Basic
|
apache-2.0
| 3,695
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.GoToDefinition
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities.GoToHelpers
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.GoToDefinition
Public Class GoToDefinitionApiTests
Private Async Function TestAsync(workspaceDefinition As XElement, expectSuccess As Boolean) As Tasks.Task
Using workspace = Await TestWorkspace.CreateAsync(workspaceDefinition, exportProvider:=GoToTestHelpers.ExportProvider)
Dim solution = workspace.CurrentSolution
Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue)
Dim cursorPosition = cursorDocument.CursorPosition.Value
Dim document = solution.GetDocument(cursorDocument.Id)
Dim root = Await document.GetSyntaxRootAsync()
Dim semanticModel = Await document.GetSemanticModelAsync()
Dim symbol = root.FindToken(cursorPosition).Parent _
.AncestorsAndSelf() _
.Select(Function(n) semanticModel.GetDeclaredSymbol(n, CancellationToken.None)) _
.FirstOrDefault()
Assert.NotNull(symbol)
Dim symbolId = symbol.GetSymbolKey()
Dim project = document.Project
Dim compilation = Await project.GetCompilationAsync()
Dim symbolInfo = symbolId.Resolve(compilation)
Assert.NotNull(symbolInfo.Symbol)
Dim presenter = New MockStreamingFindUsagesPresenter(Sub () Exit sub)
WpfTestCase.RequireWpfFact($"{NameOf(GoToDefinitionHelpers)}.{NameOf(GoToDefinitionHelpers.TryGoToDefinition)} assumes it's on the UI thread with a WaitAndGetResult call")
Dim success = GoToDefinitionHelpers.TryGoToDefinition(
symbolInfo.Symbol, document.Project,
{New Lazy(Of IStreamingFindUsagesPresenter)(Function() presenter)},
thirdPartyNavigationAllowed:=True, throwOnHiddenDefinition:=False,
cancellationToken:=CancellationToken.None)
Assert.Equal(expectSuccess, success)
End Using
End Function
Private Function TestSuccessAsync(workspaceDefinition As XElement) As Tasks.Task
Return TestAsync(workspaceDefinition, True)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)>
Public Async Function TestVBOperator() As Tasks.Task
Dim workspaceDefinition =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document>
''' <summary>
''' thin wrapper around a single int to test operators
''' </summary>
Structure IntWrapper
Private Value As Integer
Public Sub New(i As Integer)
Value = i
End Sub
Public Shared Widening Operator CType(i As IntWrapper) As Integer
Return i.Value
End Operator
' Repro operator
$$Public Shared Narrowing Operator CType(i As IntWrapper) As Byte
Return CByte(i.Value)
End Operator
Public Shared Narrowing Operator CType(i As IntWrapper) As String
Return String.Format("{0}", i.Value)
End Operator
End Structure
</Document>
</Project>
</Workspace>
Await TestSuccessAsync(workspaceDefinition)
End Function
End Class
End Namespace
|
bbarry/roslyn
|
src/VisualStudio/Core/Test/GoToDefinition/GoToDefinitionApiTests.vb
|
Visual Basic
|
apache-2.0
| 3,813
|
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("WebsitePanel.Providers.Mail.hMail5")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyProduct("WebsitePanel.Providers.Mail.hMail5")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("588fc69e-83fa-4db1-ae8c-2385bda82a42")>
' 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.*")>
|
simonegli8/Websitepanel
|
WebsitePanel/Sources/WebsitePanel.Providers.Mail.hMail5/My Project/AssemblyInfo.vb
|
Visual Basic
|
bsd-3-clause
| 1,047
|
' 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.VisualStudio.GraphModel
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression
Public Class InheritedByGraphQueryTests
<Fact, Trait(Traits.Feature, Traits.Features.Progression)>
Public Async Function TestInheritedByClassesCSharp() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj">
<Document FilePath="Z:\Project.cs">
using System;
interface IBlah {
}
abstract class $$Base
{
public abstract int CompareTo(object obj);
}
class Goo : Base, IComparable, IBlah
{
public override int CompareTo(object obj)
{
throw new NotImplementedException();
}
}
class Goo2 : Base, IBlah
{
public override int CompareTo(object obj)
{
throw new NotImplementedException();
}
}
class ReallyDerived : Goo // should not be shown as inherited by Base
{
}
</Document>
</Project>
</Workspace>)
Dim inputGraph = await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New InheritedByGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=Base)" Category="CodeSchema_Class" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsInternal="True" CommonLabel="Base" Icon="Microsoft.VisualStudio.Class.Internal" Label="Base"/>
<Node Id="(@1 Type=Goo)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Goo" Icon="Microsoft.VisualStudio.Class.Internal" Label="Goo"/>
<Node Id="(@1 Type=Goo2)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Goo2" Icon="Microsoft.VisualStudio.Class.Internal" Label="Goo2"/>
</Nodes>
<Links>
<Link Source="(@1 Type=Goo)" Target="(@1 Type=Base)" Category="InheritsFrom"/>
<Link Source="(@1 Type=Goo2)" Target="(@1 Type=Base)" Category="InheritsFrom"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression)>
Public Async Function TestInheritedByInterfacesCSharp() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj">
<Document FilePath="Z:\Project.cs">
using System;
public interface $$I { }
public class C : I { } // should appear as being derived from (implementing) I
public class C2 : C { } // should not appear as being derived from (implementing) I
interface I2 : I, IComparable
{
void M();
}
interface I3 : I2 // should not be shown as inherited by I
{
}
</Document>
</Project>
</Workspace>)
Dim inputGraph = await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New InheritedByGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=C)" Category="CodeSchema_Class" CodeSchemaProperty_IsPublic="True" CommonLabel="C" Icon="Microsoft.VisualStudio.Class.Public" Label="C"/>
<Node Id="(@1 Type=I)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsPublic="True" CommonLabel="I" Icon="Microsoft.VisualStudio.Interface.Public" Label="I"/>
<Node Id="(@1 Type=I2)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsInternal="True" CommonLabel="I2" Icon="Microsoft.VisualStudio.Interface.Internal" Label="I2"/>
</Nodes>
<Links>
<Link Source="(@1 Type=C)" Target="(@1 Type=I)" Category="InheritsFrom"/>
<Link Source="(@1 Type=I2)" Target="(@1 Type=I)" Category="InheritsFrom"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression)>
Public Async Function TestInheritedByClassesVisualBasic() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj">
<Document FilePath="Z:\Project.vb">
Imports System
Interface IBlah
End Interface
MustInherit Class $$Base
Public MustOverride Function CompareTo(obj As Object) As Integer
End Class
Class Goo
Inherits Base
Implements IComparable, IBlah
Public Overrides Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
Throw New NotImplementedException()
End Function
End Class
Class Goo2
Inherits Base
Implements IBlah
Public Overrides Function CompareTo(obj As Object) As Integer
Throw New NotImplementedException()
End Function
End Class
Class ReallyDerived ' should not be shown as inherited by Base
Inherits Goo
End Class
</Document>
</Project>
</Workspace>)
Dim inputGraph = await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New InheritedByGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=Base)" Category="CodeSchema_Class" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsInternal="True" CommonLabel="Base" Icon="Microsoft.VisualStudio.Class.Internal" Label="Base"/>
<Node Id="(@1 Type=Goo)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Goo" Icon="Microsoft.VisualStudio.Class.Internal" Label="Goo"/>
<Node Id="(@1 Type=Goo2)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Goo2" Icon="Microsoft.VisualStudio.Class.Internal" Label="Goo2"/>
</Nodes>
<Links>
<Link Source="(@1 Type=Goo)" Target="(@1 Type=Base)" Category="InheritsFrom"/>
<Link Source="(@1 Type=Goo2)" Target="(@1 Type=Base)" Category="InheritsFrom"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/VisualBasicAssembly1.dll"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression)>
Public Async Function TestInheritedByInterfacesVisualBasic() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj">
<Document FilePath="Z:\Project.vb">
Imports System
Public Interface $$I
End Interface
Public Class C ' should appear as being derived from (implementing) I
Implements I
End Class
Public Class C2 ' should not appear as being derived from (implementing) I
Inherits C
End Class
Interface I2
Inherits I, IComparable
Sub M()
End Interface
Interface I3 ' should not be shown as inherited by I
Inherits I2
End Interface
</Document>
</Project>
</Workspace>)
Dim inputGraph = await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New InheritedByGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=C)" Category="CodeSchema_Class" CodeSchemaProperty_IsPublic="True" CommonLabel="C" Icon="Microsoft.VisualStudio.Class.Public" Label="C"/>
<Node Id="(@1 Type=I)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsPublic="True" CommonLabel="I" Icon="Microsoft.VisualStudio.Interface.Public" Label="I"/>
<Node Id="(@1 Type=I2)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsInternal="True" CommonLabel="I2" Icon="Microsoft.VisualStudio.Interface.Internal" Label="I2"/>
</Nodes>
<Links>
<Link Source="(@1 Type=C)" Target="(@1 Type=I)" Category="InheritsFrom"/>
<Link Source="(@1 Type=I2)" Target="(@1 Type=I)" Category="InheritsFrom"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/VisualBasicAssembly1.dll"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
End Class
End Namespace
|
MattWindsor91/roslyn
|
src/VisualStudio/Core/Test/Progression/InheritedByGraphQueryTests.vb
|
Visual Basic
|
apache-2.0
| 10,947
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Runtime.InteropServices
Imports Microsoft.VisualStudio.Shell.Interop
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop
<Guid("782CB503-84B1-4b8f-9AAD-A12B75905015"), ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Friend Interface IVbCompilerHost
''' <summary>
''' Output a string to the standard output (console, file, pane, etc.)
''' </summary>
Sub OutputString(<MarshalAs(UnmanagedType.LPWStr)> [string] As String)
''' <summary>
''' Returns the system SDK directory, where mscorlib.dll and Microsoft.VisualBasic.dll is
''' located.
''' </summary>
Function GetSdkPath() As <MarshalAs(UnmanagedType.BStr)> String
''' <summary>
''' Get the target library type.
''' </summary>
Function GetTargetLibraryType() As VBTargetLibraryType
End Interface
End Namespace
|
ManishJayaswal/roslyn
|
src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/IVbCompilerHost.vb
|
Visual Basic
|
apache-2.0
| 1,110
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators
Friend NotInheritable Class MidAssignmentDocumentation
Inherits AbstractIntrinsicOperatorDocumentation
Public Overrides ReadOnly Property DocumentationText As String
Get
Return VBWorkspaceResources.Replaces_a_specified_number_of_characters_in_a_String_variable_with_characters_from_another_string
End Get
End Property
Public Overrides Function GetParameterDocumentation(index As Integer) As String
Select Case index
Case 0
Return VBWorkspaceResources.The_name_of_the_string_variable_to_modify
Case 1
Return VBWorkspaceResources.The_one_based_character_position_in_the_string_where_the_replacement_of_text_begins
Case 2
Return VBWorkspaceResources.The_number_of_characters_to_replace_If_omitted_the_length_of_stringExpression_is_used
Case Else
Throw New ArgumentException(NameOf(index))
End Select
End Function
Public Overrides Function GetParameterName(index As Integer) As String
Select Case index
Case 0
Return VBWorkspaceResources.stringName
Case 1
Return VBWorkspaceResources.startIndex
Case 2
Return VBWorkspaceResources.length
Case Else
Throw New ArgumentException(NameOf(index))
End Select
End Function
Public Overrides Function GetParameterDisplayParts(index As Integer) As IList(Of SymbolDisplayPart)
If index = 2 Then
Return {New SymbolDisplayPart(SymbolDisplayPartKind.ParameterName, Nothing, "[" + GetParameterName(2) + "]")}
Else
Return MyBase.GetParameterDisplayParts(index)
End If
End Function
Public Overrides ReadOnly Property IncludeAsType As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return 3
End Get
End Property
Public Overrides Function GetSuffix(semanticModel As SemanticModel, position As Integer, nodeToBind As SyntaxNode, cancellationToken As CancellationToken) As IList(Of SymbolDisplayPart)
Return {
New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, ")"),
New SymbolDisplayPart(SymbolDisplayPartKind.Space, Nothing, " "),
New SymbolDisplayPart(SymbolDisplayPartKind.Operator, Nothing, "="),
New SymbolDisplayPart(SymbolDisplayPartKind.Space, Nothing, " "),
New SymbolDisplayPart(SymbolDisplayPartKind.Text, Nothing, VBWorkspaceResources.stringExpression)
}
End Function
Public Overrides ReadOnly Property PrefixParts As IList(Of SymbolDisplayPart)
Get
Return {New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, "Mid"),
New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(")}
End Get
End Property
End Class
End Namespace
|
VSadov/roslyn
|
src/Workspaces/VisualBasic/Portable/Utilities/IntrinsicOperators/MidAssignmentDocumentation.vb
|
Visual Basic
|
apache-2.0
| 3,779
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Class CastAnalyzer
Private ReadOnly _castNode As ExpressionSyntax
Private ReadOnly _castExpressionNode As ExpressionSyntax
Private ReadOnly _semanticModel As SemanticModel
Private ReadOnly _assumeCallKeyword As Boolean
Private ReadOnly _cancellationToken As CancellationToken
Private Sub New(
castNode As ExpressionSyntax,
castExpressionNode As ExpressionSyntax,
semanticModel As SemanticModel,
assumeCallKeyword As Boolean,
cancellationToken As CancellationToken
)
_castNode = castNode
_castExpressionNode = castExpressionNode
_semanticModel = semanticModel
_assumeCallKeyword = assumeCallKeyword
_cancellationToken = cancellationToken
End Sub
Private Function CastPassedToParamArrayDefinitelyCantBeRemoved(castType As ITypeSymbol) As Boolean
If _castExpressionNode.WalkDownParentheses().IsKind(SyntaxKind.NothingLiteralExpression) Then
Dim argument = TryCast(_castNode.WalkUpParentheses().Parent, ArgumentSyntax)
If argument IsNot Nothing Then
Dim parameter = argument.DetermineParameter(_semanticModel, cancellationToken:=_cancellationToken)
If parameter IsNot Nothing AndAlso parameter.IsParams Then
Debug.Assert(TypeOf parameter.Type Is IArrayTypeSymbol)
Dim parameterType = DirectCast(parameter.Type, IArrayTypeSymbol)
Dim conversion = _semanticModel.Compilation.ClassifyConversion(castType, parameterType)
If conversion.Exists AndAlso conversion.IsWidening Then
Return False
End If
Dim conversionElementType = _semanticModel.Compilation.ClassifyConversion(castType, parameterType.ElementType)
If conversionElementType.Exists AndAlso (conversionElementType.IsIdentity OrElse conversionElementType.IsWidening) Then
Return True
End If
End If
End If
End If
Return False
End Function
Private Shared Function GetOuterCastType(expression As ExpressionSyntax, expressionTypeInfo As TypeInfo, semanticModel As SemanticModel, cancellationToken As CancellationToken) As ITypeSymbol
expression = expression.WalkUpParentheses()
Dim parent = expression.Parent
Dim parentExpression = TryCast(parent, ExpressionSyntax)
If parentExpression IsNot Nothing Then
If TypeOf parentExpression Is CastExpressionSyntax OrElse
TypeOf parentExpression Is PredefinedCastExpressionSyntax Then
Return semanticModel.GetTypeInfo(parentExpression, cancellationToken).Type
End If
End If
If Not Object.Equals(expressionTypeInfo.Type, expressionTypeInfo.ConvertedType) Then
Return expressionTypeInfo.ConvertedType
End If
Dim parentEqualsValue = TryCast(parent, EqualsValueSyntax)
If parentEqualsValue IsNot Nothing Then
Dim returnedType = AsTypeInVariableDeclarator(parentEqualsValue.Parent, semanticModel)
If returnedType IsNot Nothing Then
Return returnedType
End If
End If
Dim parentForEach = TryCast(parent, ForEachStatementSyntax)
If parentForEach IsNot Nothing Then
Dim returnedType = AsTypeInVariableDeclarator(parentForEach.ControlVariable, semanticModel)
If returnedType IsNot Nothing Then
Return returnedType
End If
End If
Dim parentAssignmentStatement = TryCast(parent, AssignmentStatementSyntax)
If parentAssignmentStatement IsNot Nothing AndAlso parent.Kind = SyntaxKind.SimpleAssignmentStatement Then
Return semanticModel.GetTypeInfo(parentAssignmentStatement.Left).Type
End If
Dim parentUnaryExpression = TryCast(parentExpression, UnaryExpressionSyntax)
If parentUnaryExpression IsNot Nothing AndAlso Not semanticModel.GetConversion(expression).IsUserDefined Then
Dim parentTypeInfo = semanticModel.GetTypeInfo(parentUnaryExpression, cancellationToken)
Return GetOuterCastType(parentUnaryExpression, parentTypeInfo, semanticModel, cancellationToken)
End If
Dim parentTernaryConditional = TryCast(parent, TernaryConditionalExpressionSyntax)
If parentTernaryConditional IsNot Nothing AndAlso
parentTernaryConditional.Condition IsNot expression Then
Dim otherExpression = If(parentTernaryConditional.WhenTrue Is expression,
parentTernaryConditional.WhenFalse,
parentTernaryConditional.WhenTrue)
Return semanticModel.GetTypeInfo(otherExpression).Type
End If
Return expressionTypeInfo.ConvertedType
End Function
Private Shared Function GetSpeculatedExpressionToOuterTypeConversion(speculatedExpression As ExpressionSyntax, speculationAnalyzer As SpeculationAnalyzer, cancellationToken As CancellationToken, <Out> ByRef speculatedExpressionOuterType As ITypeSymbol) As Conversion
Dim innerSpeculatedExpression = speculatedExpression.WalkDownParentheses()
Dim typeInfo = speculationAnalyzer.SpeculativeSemanticModel.GetTypeInfo(innerSpeculatedExpression, cancellationToken)
Dim conv = speculationAnalyzer.SpeculativeSemanticModel.GetConversion(innerSpeculatedExpression, cancellationToken)
If Not conv.IsIdentity OrElse Not Object.Equals(typeInfo.Type, typeInfo.ConvertedType) Then
speculatedExpressionOuterType = typeInfo.ConvertedType
Return conv
End If
speculatedExpression = speculatedExpression.WalkUpParentheses()
typeInfo = speculationAnalyzer.SpeculativeSemanticModel.GetTypeInfo(speculatedExpression, cancellationToken)
speculatedExpressionOuterType = GetOuterCastType(speculatedExpression, typeInfo, speculationAnalyzer.SpeculativeSemanticModel, cancellationToken)
If speculatedExpressionOuterType Is Nothing Then
Return Nothing
End If
Return speculationAnalyzer.SpeculativeSemanticModel.ClassifyConversion(speculatedExpression, speculatedExpressionOuterType)
End Function
Private Shared Function AsTypeInVariableDeclarator(node As SyntaxNode, semanticModel As SemanticModel) As ITypeSymbol
If node Is Nothing Then
Return Nothing
End If
Dim variableDeclarator = TryCast(node, VariableDeclaratorSyntax)
If variableDeclarator IsNot Nothing Then
Dim asClause = TryCast(variableDeclarator.AsClause, SimpleAsClauseSyntax)
If (asClause IsNot Nothing) Then
Return semanticModel.GetTypeInfo(asClause.Type).Type
End If
End If
Return Nothing
End Function
Private Function IsStartOfExecutableStatement() As Boolean
Dim parentExpression = _castNode.WalkUpParentheses()
Dim parentStatement = parentExpression.FirstAncestorOrSelf(Of ExecutableStatementSyntax)()
If parentStatement Is Nothing Then
Return False
End If
' If we are assuming that a call keyword will be inserted, then
' we can assume that we are not at the start of the part executable
' statement if it's a Call statement.
If _assumeCallKeyword AndAlso
parentStatement.IsKind(SyntaxKind.ExpressionStatement) AndAlso DirectCast(parentStatement, ExpressionStatementSyntax).Expression.IsKind(SyntaxKind.InvocationExpression) Then
Return False
End If
Return parentStatement.GetFirstToken() = parentExpression.GetFirstToken()
End Function
Private Function ExpressionCanStartExecutableStatement() As Boolean
Dim innerExpression = _castExpressionNode.WalkDownParentheses()
Return TypeOf innerExpression Is CastExpressionSyntax OrElse
TypeOf innerExpression Is PredefinedCastExpressionSyntax
End Function
Private Function IsUnnecessary() As Boolean
Dim speculationAnalyzer = New SpeculationAnalyzer(_castNode, _castExpressionNode, _semanticModel, _cancellationToken,
skipVerificationForReplacedNode:=True, failOnOverloadResolutionFailuresInOriginalCode:=True)
' First, check to see if the node ultimately parenting this cast has any
' syntax errors. If so, we bail.
If speculationAnalyzer.SemanticRootOfOriginalExpression.ContainsDiagnostics() Then
Return False
End If
If IsStartOfExecutableStatement() AndAlso Not ExpressionCanStartExecutableStatement() Then
Return False
End If
Dim castTypeInfo = _semanticModel.GetTypeInfo(_castNode, _cancellationToken)
Dim castType = castTypeInfo.Type
If castType Is Nothing OrElse castType.IsErrorType() Then
Return False
End If
Dim castExpressionType As ITypeSymbol
If _castExpressionNode.Kind = SyntaxKind.CollectionInitializer Then
' Get type of the array literal in context without the target type
castExpressionType = _semanticModel.GetSpeculativeTypeInfo(_castExpressionNode.SpanStart, _castExpressionNode, SpeculativeBindingOption.BindAsExpression).ConvertedType
Else
castExpressionType = _semanticModel.GetTypeInfo(_castExpressionNode, _cancellationToken).Type
End If
If castExpressionType IsNot Nothing AndAlso castExpressionType.IsErrorType() Then
Return False
End If
If CastPassedToParamArrayDefinitelyCantBeRemoved(castType) Then
Return False
End If
' A casts to object can always be removed from an expression inside of an interpolation, since it'll be converted to object
' in order to call string.Format(...) anyway.
If castType?.SpecialType = SpecialType.System_Object AndAlso
_castNode.WalkUpParentheses().IsParentKind(SyntaxKind.Interpolation) Then
Return True
End If
' If removing the cast will result in a change in semantics of any of the parenting nodes, we won't remove it.
' We do this even for identity casts in case removing that cast might affect type inference.
If speculationAnalyzer.ReplacementChangesSemantics() Then
Return False
End If
Dim expressionToCastType = _semanticModel.ClassifyConversion(_castNode.SpanStart, _castExpressionNode, castType)
If expressionToCastType.IsIdentity Then
' Simple case: If the conversion from the inner expression to the cast type is identity,
' the cast can be removed.
Return True
ElseIf expressionToCastType.IsNarrowing AndAlso expressionToCastType.IsReference
' If the conversion from the inner expression to the cast type is narrowing reference conversion,
' the cast cannot be removed.
Return False
End If
Dim outerType = GetOuterCastType(_castNode, castTypeInfo, _semanticModel, _cancellationToken)
If outerType IsNot Nothing Then
Dim castToOuterType As Conversion = _semanticModel.ClassifyConversion(_castNode.SpanStart, _castNode, outerType)
Dim expressionToOuterType As Conversion
Dim speculatedExpressionOuterType As ITypeSymbol = Nothing
Dim outerSpeculatedExpression = _castNode.WalkUpParentheses()
If outerSpeculatedExpression.IsParentKind(SyntaxKind.DirectCastExpression) OrElse
outerSpeculatedExpression.IsParentKind(SyntaxKind.TryCastExpression) OrElse
outerSpeculatedExpression.IsParentKind(SyntaxKind.CTypeExpression) Then
speculatedExpressionOuterType = outerType
expressionToOuterType = _semanticModel.ClassifyConversion(_castExpressionNode.WalkDownParentheses(), speculatedExpressionOuterType)
Else
expressionToOuterType = GetSpeculatedExpressionToOuterTypeConversion(speculationAnalyzer.ReplacedExpression, speculationAnalyzer, _cancellationToken, speculatedExpressionOuterType)
End If
' CONSIDER: Anonymous function conversions cannot be compared from different semantic models as lambda symbol comparison requires syntax tree equality. Should this be a compiler bug?
' For now, just revert back to computing expressionToOuterType using the original semantic model.
If expressionToOuterType.IsLambda Then
expressionToOuterType = _semanticModel.ClassifyConversion(_castNode.SpanStart, _castExpressionNode, outerType)
End If
' If there is an user-defined conversion from the expression to the cast type or the cast
' to the outer type, we need to make sure that the same user-defined conversion will be
' called if the cast is removed.
If castToOuterType.IsUserDefined OrElse expressionToCastType.IsUserDefined Then
Return (HaveSameUserDefinedConversion(expressionToCastType, expressionToOuterType) OrElse
HaveSameUserDefinedConversion(castToOuterType, expressionToOuterType)) AndAlso
(UserDefinedConversionIsAllowed(_castNode, _semanticModel) AndAlso
Not expressionToCastType.IsNarrowing)
ElseIf expressionToOuterType.IsUserDefined Then
Return False
End If
If (expressionToOuterType.IsIdentity OrElse
(_castExpressionNode.Kind = SyntaxKind.CollectionInitializer AndAlso expressionToOuterType.IsWidening AndAlso speculatedExpressionOuterType.IsArrayType())) AndAlso
expressionToCastType.IsWidening Then
Return True
End If
If Not (castToOuterType.IsNullableValueType AndAlso castToOuterType.IsWidening) Then
Dim expressionToCastTypeIsWideningRefOrDefault As Boolean = expressionToCastType.IsWidening AndAlso (expressionToCastType.IsReference OrElse expressionToCastType.IsDefault)
Dim expressionToOuterTypeIsWideningRefOrDefault As Boolean = expressionToOuterType.IsWidening AndAlso (expressionToOuterType.IsReference OrElse expressionToOuterType.IsDefault)
If (expressionToCastTypeIsWideningRefOrDefault AndAlso expressionToOuterTypeIsWideningRefOrDefault) Then
If expressionToCastType.IsDefault Then
Return Not CastRemovalChangesDefaultValue(castType, outerType)
End If
Return True
ElseIf expressionToCastTypeIsWideningRefOrDefault OrElse expressionToOuterTypeIsWideningRefOrDefault Then
Return castType Is speculatedExpressionOuterType
End If
If expressionToCastType.IsWidening AndAlso expressionToCastType.IsLambda AndAlso
expressionToOuterType.IsWidening AndAlso expressionToOuterType.IsLambda Then
Return Not speculationAnalyzer.ReplacementChangesSemanticsOfUnchangedLambda(_castExpressionNode, speculationAnalyzer.ReplacedExpression)
End If
End If
If Not castToOuterType.IsValueType AndAlso castToOuterType = expressionToOuterType Then
If (castToOuterType.IsNullableValueType) Then
Return expressionToOuterType.IsWidening AndAlso
DirectCast(castExpressionType.OriginalDefinition, ITypeSymbol).SpecialType = SpecialType.System_Nullable_T
ElseIf expressionToCastType.IsWidening AndAlso expressionToCastType.IsNumeric AndAlso Not castToOuterType.IsIdentity Then
' Some widening numeric conversions can cause loss of precision and must not be removed.
Return Not IsRequiredWideningNumericConversion(castExpressionType, castType)
End If
Return True
End If
If castToOuterType.IsIdentity AndAlso
expressionToCastType = expressionToOuterType Then
If expressionToCastType.Exists Then
If expressionToCastType.IsWidening Then
Return True
End If
If expressionToCastType.IsNarrowing AndAlso
Not _semanticModel.OptionStrict = OptionStrict.On Then
Return True
End If
Else
Return True
End If
End If
If expressionToOuterType.IsIdentity AndAlso
castToOuterType.IsWidening AndAlso
castToOuterType.IsReference Then
Debug.Assert(Not (expressionToCastType.IsNarrowing AndAlso expressionToCastType.IsReference))
Return True
End If
End If
Return False
End Function
Private Shared Function HaveSameUserDefinedConversion(conversion1 As Conversion, conversion2 As Conversion) As Boolean
Return conversion1.IsUserDefined AndAlso conversion2.IsUserDefined AndAlso conversion1.MethodSymbol.Equals(conversion2.MethodSymbol)
End Function
Private Shared Function UserDefinedConversionIsAllowed(expression As ExpressionSyntax, semanticModel As SemanticModel) As Boolean
expression = expression.WalkUpParentheses()
Dim parentNode = expression.Parent
If parentNode Is Nothing Then
Return False
End If
If parentNode.IsKind(SyntaxKind.ThrowStatement) Then
Return False
End If
Return True
End Function
Private Shared Function IsRequiredWideningNumericConversion(sourceType As ITypeSymbol, destinationType As ITypeSymbol) As Boolean
' VB Language Specification: Section 8.3 Numeric Conversions
' Conversions from UInteger, Integer, ULong, Long, or Decimal to Single or Double are rounded to the nearest Single or Double value.
' While this conversion may cause a loss of precision, it will never cause a loss of magnitude
Select Case destinationType.SpecialType
Case SpecialType.System_Single, SpecialType.System_Double
Select Case sourceType.SpecialType
Case SpecialType.System_UInt32, SpecialType.System_Int32,
SpecialType.System_UInt64, SpecialType.System_Int64,
SpecialType.System_Decimal
Return True
End Select
End Select
Return False
End Function
Private Shared Function CastRemovalChangesDefaultValue(castType As ITypeSymbol, outerType As ITypeSymbol) As Boolean
If castType.IsNumericType() Then
Return Not outerType.IsNumericType()
ElseIf castType.SpecialType = SpecialType.System_DateTime
Return Not outerType.SpecialType = SpecialType.System_DateTime
ElseIf castType.SpecialType = SpecialType.System_Boolean
Return Not (outerType.IsNumericType OrElse outerType.SpecialType = SpecialType.System_Boolean)
End If
If castType.OriginalDefinition?.SpecialType = SpecialType.System_Nullable_T Then
' Don't allow casts of Nothing to T? to be removed unless the outer type is T? or Object.
' Otherwise, Nothing will lose its "nullness" and get the default value of T.
'
' So, this is OK:
'
' Dim x As Object = DirectCast(Nothing, Integer?)
'
' But this is not:
'
' Dim x As Integer = DirectCast(Nothing, Integer?)
If castType.Equals(outerType) OrElse outerType.SpecialType = SpecialType.System_Object Then
Return False
End If
Return True
End If
Return False
End Function
Public Shared Function IsUnnecessary(
castNode As ExpressionSyntax,
castExpressionNode As ExpressionSyntax,
semanticModel As SemanticModel,
assumeCallKeyword As Boolean,
cancellationToken As CancellationToken
) As Boolean
Return New CastAnalyzer(castNode, castExpressionNode, semanticModel, assumeCallKeyword, cancellationToken).IsUnnecessary()
End Function
End Class
End Namespace
|
mmitche/roslyn
|
src/Workspaces/VisualBasic/Portable/Extensions/CastAnalyzer.vb
|
Visual Basic
|
apache-2.0
| 22,390
|
Imports System.Windows.Controls.Primitives
Public Class ClickEventBinding
Inherits EventBinding
Protected Overrides Sub OnAttached()
Dim c = DirectCast(Me.Element, Control)
c.AddHandler(ButtonBase.ClickEvent, New RoutedEventHandler(AddressOf Me.OnClick), True)
End Sub
Private Sub OnClick(sender As Object, e As RoutedEventArgs)
Me.ExecuteCommand()
End Sub
End Class
|
Symmex/Snowflake
|
Source/Symmex.Snowflake.Wpf/ClickEventBinding.vb
|
Visual Basic
|
mit
| 417
|
Partial Class TaskList
Inherits System.Web.UI.Page
Public Property DirectoryName() As String
Get
Return ViewState("DirectoryName")
End Get
Set(ByVal value As String)
ViewState("DirectoryName") = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
DirectoryName = DirectoryService.GetTasksDirectory
Directory1.Path = DirectoryName
End If
End Sub
Protected Sub lnkNewSubdirectory_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkNewSubdirectory.Click
Context.Items("DirectoryName") = DirectoryName
Server.Transfer("~/DirectoryNew.aspx")
End Sub
Protected Sub lnkNewFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkNewFile.Click
Context.Items("DirectoryName") = DirectoryName
Server.Transfer("~/FileNew.aspx")
End Sub
Protected Sub lnkUploadFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkUploadFile.Click
Context.Items("DirectoryName") = DirectoryName
Server.Transfer("~/FileUpload.aspx")
End Sub
Protected Sub lnkDownload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkDownload.Click
Dim zipfilename As String
zipfilename = ZipService.ZipDirectory(DirectoryName, "")
Response.Redirect(zipfilename)
End Sub
Protected Sub lnkUploadZip_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkUploadZip.Click
Context.Items("DirectoryName") = DirectoryName
Server.Transfer("~/ZipUpload.aspx")
End Sub
End Class
|
ajlopez/AjGenesis
|
src/AjGenesis.WebStudio/TaskList.aspx.vb
|
Visual Basic
|
mit
| 1,809
|
' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification:="<Pending>", Scope:="member", Target:="~M:BurnSoft.BSAP.BSSessionDetailsStats.getSessionAverage(System.Int64,System.String@,System.String@,System.String@,System.String@,System.Int64@,System.String)")>
|
burnsoftnet/BSApplicationProfiler
|
BSAP_UI_WebForms/BSAP_UI_WebForms/GlobalSuppressions1.vb
|
Visual Basic
|
mit
| 563
|
Imports DTIMediaManager.dsMedia
Imports DTIImageManager
Imports DTIImageManager.dsImageManager
Imports DTIVideoManager
Imports DTIVideoManager.dsDTIVideo
Imports System.Web.HttpServerUtility
Imports DTIServerControls.DTISharedVariables
#If DEBUG Then
Public Class SharedMediaVariables
#Else
<ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never), ComponentModel.ToolboxItem(False)> _
Public Class SharedMediaVariables
#End If
Public Shared ReadOnly Property PreviewList() As ArrayList
Get
If Session("DTIGalleryPreviewList") Is Nothing Then
Session("DTIGalleryPreviewList") = New ArrayList
End If
Return Session("DTIGalleryPreviewList")
End Get
End Property
Public Shared ReadOnly Property myMediaTable() As DTIMediaManagerDataTable
Get
Return dsMedia.DTIMediaManager
End Get
End Property
Private Shared _myDTIMediaTypes As DTIMediaTypesDataTable
Public Shared ReadOnly Property myDTIMediaTypes() As DTIMediaTypesDataTable
Get
initDTIMediaTypes()
Return _myDTIMediaTypes
End Get
End Property
Public Shared ReadOnly Property dsMedia() As dsMedia
Get
If Session("DTIGalleryDataset") Is Nothing Then
Session("DTIGalleryDataset") = New dsMedia
End If
Return Session("DTIGalleryDataset")
End Get
End Property
Public Shared ReadOnly Property myImages() As DTIImageManagerDataTable
Get
Return SharedImageVariables.myImages
End Get
End Property
Public Shared ReadOnly Property myVideos() As DTIVideoManagerDataTable
Get
Return MyFlashWrapper.videoSaveTable
End Get
End Property
Public Shared ReadOnly Property MyFlashWrapper() As ffmpegHelper
Get
If Session("MyFlashWrapper") Is Nothing Then
Session("MyFlashWrapper") = New ffmpegHelper(BaseClasses.DataBase.getHelper())
End If
Return Session("MyFlashWrapper")
End Get
End Property
Public Shared Sub initDTIMediaTypes()
If _myDTIMediaTypes Is Nothing Then
_myDTIMediaTypes = New DTIMediaTypesDataTable()
End If
SyncLock _myDTIMediaTypes
If _myDTIMediaTypes.Count = 0 Then
Dim sqlHelper As BaseClasses.BaseHelper = BaseClasses.DataBase.getHelper
sqlHelper.checkAndCreateTable(_myDTIMediaTypes)
sqlHelper.FillDataTable("select * from DTIMediaTypes", _myDTIMediaTypes)
If _myDTIMediaTypes.Count = 0 Then
_myDTIMediaTypes.AddDTIMediaTypesRow("~/res/DTIImageManager/ViewImage.aspx?Id=", _
"~/res/DTIImageManager/ViewImage.aspx?Id=", "Image", "Image")
_myDTIMediaTypes.AddDTIMediaTypesRow("~/res/DTIVideoManager/ViewVideoScreenShot.aspx?showPlayOverlay=1&Id=", _
"~/res/DTIVideoManager/VideoViewer.aspx?autoPlay=1&Id=", "Video", "Iframe")
_myDTIMediaTypes.AddDTIMediaTypesRow(Nothing, Nothing, "page", Nothing)
_myDTIMediaTypes.AddDTIMediaTypesRow(Nothing, Nothing, "editPanel", Nothing)
sqlHelper.Update(_myDTIMediaTypes)
End If
End If
End SyncLock
End Sub
End Class
|
Micmaz/DTIControls
|
DTIContentManagement/DTIMediaManager/SharedMediaVariables.vb
|
Visual Basic
|
mit
| 3,717
|
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
<TestClass()> Public Class Texten
<TestMethod()> Public Sub Texten_Aktivsaetze()
Dim generator As New TextGenerator.Aktivsatzmaschine
Dim satz = generator.Naechster_Satz()
Dim satz2 = generator.Naechster_Satz()
Dim satz3 = generator.Naechster_Satz()
Assert.IsNotNull(satz)
Assert.IsTrue(satz <> satz2)
Assert.IsTrue(satz2 <> satz3)
Assert.IsTrue(satz <> satz3)
End Sub
End Class
|
mk-prg-net/mk-prg-net.lib
|
TextGenerator.Test/Texten.vb
|
Visual Basic
|
mit
| 533
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.Linq2Acad.My.MySettings
Get
Return Global.Linq2Acad.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
wtertinek/Linq2Acad
|
src/Sources/Linq2Acad.SampleCode.VB/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,908
|
'***********************************************************************
' $Library: Protean.Providers.messaging.base
' $Revision: 3.1
' $Date: 2010-03-02
' $Author: Trevor Spink (trevor@eonic.co.uk)
' &Website: www.eonic.co.uk
' &Licence: All Rights Reserved.
' $Copyright: Copyright (c) 2002 - 2010 Eonic Ltd.
'***********************************************************************
Option Strict Off
Option Explicit On
Imports System
Imports System.Xml
Imports System.Web.HttpUtility
Imports System.Web.Configuration
Imports System.Configuration
Imports System.IO
Imports System.Collections
Imports System.Data
Imports System.Data.SqlClient
Imports System.Text.RegularExpressions
Imports System.Threading
Imports Protean.Cms
Imports Protean.Tools
Imports Protean.Tools.Xml
Imports Protean.Cms.Cart
Imports System.Net.Mail
Imports System.Reflection
Imports System.Net
Imports VB = Microsoft.VisualBasic
Imports Microsoft.WindowsAzure.MediaServices.Client
Imports System.Linq
Namespace Providers
Namespace Streaming
Public Class BaseProvider
Private Const mcModuleName As String = "Protean.Providers.Streaming.BaseProvider"
Private _AdminXforms As Object
Private _AdminProcess As Object
Private _Activities As Object
Protected moStreamingCfg As XmlNode
Public Property AdminXforms() As Object
Set(ByVal value As Object)
_AdminXforms = value
End Set
Get
Return _AdminXforms
End Get
End Property
Public Property AdminProcess() As Object
Set(ByVal value As Object)
_AdminProcess = value
End Set
Get
Return _AdminProcess
End Get
End Property
Public Property Activities() As Object
Set(ByVal value As Object)
_Activities = value
End Set
Get
Return _Activities
End Get
End Property
Public Sub New(ByRef myWeb As Protean.Cms, ByVal ProviderName As String)
Try
Dim calledType As Type
Dim oProviderCfg As XmlElement
moStreamingCfg = WebConfigurationManager.GetWebApplicationSection("protean/streaming")
oProviderCfg = moStreamingCfg.SelectSingleNode("provider[@name='" & ProviderName & "']")
Dim ProviderClass As String = ""
If Not oProviderCfg Is Nothing Then
If oProviderCfg.HasAttribute("class") Then
ProviderClass = oProviderCfg.GetAttribute("class")
End If
Else
'Asssume Eonic Provider
End If
If ProviderClass = "" Then
ProviderClass = "Protean.Providers.Streaming.EonicProvider"
calledType = System.Type.GetType(ProviderClass, True)
Else
Dim moPrvConfig As Protean.ProviderSectionHandler = WebConfigurationManager.GetWebApplicationSection("protean/paymentProviders")
If Not moPrvConfig.Providers(ProviderClass) Is Nothing Then
Dim assemblyInstance As [Assembly] = [Assembly].Load(moPrvConfig.Providers(ProviderClass).Type)
calledType = assemblyInstance.GetType("Protean.Providers.Payment." & ProviderClass, True)
Else
calledType = System.Type.GetType("Protean.Providers.Payment." & ProviderClass, True)
End If
End If
Dim o As Object = Activator.CreateInstance(calledType)
Dim args(4) As Object
args(0) = _AdminXforms
args(1) = _AdminProcess
args(2) = _Activities
args(3) = Me
args(4) = myWeb
calledType.InvokeMember("Initiate", BindingFlags.InvokeMethod, Nothing, o, args)
Catch ex As Exception
returnException(myWeb.msException, mcModuleName, "New", ex, "", ProviderName & " Could Not be Loaded", gbDebug)
End Try
End Sub
End Class
Public Class EonicProvider
Public Sub New()
'do nothing
End Sub
Public Sub Initiate(ByRef _AdminXforms As Object, ByRef _AdminProcess As Object, ByRef _Activities As Object, ByRef MemProvider As Object, ByRef myWeb As Protean.Cms)
MemProvider.AdminXforms = New AdminXForms(myWeb)
MemProvider.AdminProcess = New AdminProcess(myWeb)
MemProvider.AdminProcess.oAdXfm = MemProvider.AdminXforms
MemProvider.Activities = New Activities()
End Sub
Public Class AdminXForms
Inherits Cms.Admin.AdminXforms
Private Const mcModuleName As String = "Protean.Providers.Streaming.AdminXForms"
Sub New(ByRef aWeb As Cms)
MyBase.New(aWeb)
End Sub
End Class
Public Class AdminProcess
Inherits Cms.Admin
Dim _oAdXfm As Protean.Providers.Streaming.EonicProvider.AdminXForms
Public Property oAdXfm() As Object
Set(ByVal value As Object)
_oAdXfm = value
End Set
Get
Return _oAdXfm
End Get
End Property
Sub New(ByRef aWeb As Cms)
MyBase.New(aWeb)
End Sub
End Class
Public Class Activities
Private Const mcModuleName As String = "Protean.Providers.Streaming.Activities"
End Class
Public Class Modules
Public Event OnError(ByVal sender As Object, ByVal e As Protean.Tools.Errors.ErrorEventArgs)
Private Const mcModuleName As String = "Eonic.CampaignMonitorTools.Modules"
Dim moStreamingConfig As System.Collections.Specialized.NameValueCollection = WebConfigurationManager.GetWebApplicationSection("protean/streaming")
Public Sub New()
'do nowt
End Sub
Public Sub GetSteamURL(ByRef myWeb As Protean.Cms, ByRef oContentNode As XmlElement)
Try
Catch ex As Exception
RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "GetSteamURL", ex, ""))
End Try
End Sub
End Class
End Class
End Namespace
End Namespace
|
Eonic/EonicWeb5
|
Assemblies/ProteanCMS/Providers/Streaming.BaseProvider.vb
|
Visual Basic
|
apache-2.0
| 7,084
|
Imports System.Data
Imports bv.common.Enums
Imports EIDSS.model.Enums
Public Class Sample_DB
Inherits BaseDbService
Public Sub New()
ObjectName = "Sample"
End Sub
Public Const TableSample As String = "Sample"
Public Const TableDiagnosis As String = "Diagnosis"
Public Const TableTest As String = "Test"
Public Const TableTransferFrom As String = "TransferFrom"
Public Const TableTransferTo As String = "TransferTo"
Public Overrides Function GetDetail(ByVal ID As Object) As DataSet
Dim ds As New DataSet
ds.EnforceConstraints = False
Try
Dim cmd As IDbCommand = CreateSPCommand("spLabSample_SelectDetail")
AddParam(cmd, "@idfMaterial", ID)
AddParam(cmd, "@LangID", bv.model.Model.Core.ModelUserContext.CurrentLanguage)
'Fill the main object table
FillDataset(cmd, ds, TableSample)
CorrectTable(ds.Tables(0), TableSample)
CorrectTable(ds.Tables(1), TableTest)
CorrectTable(ds.Tables(2), TableTransferFrom)
CorrectTable(ds.Tables(3), TableTransferTo)
For Each col As DataColumn In ds.Tables(TableTest).Columns
col.ReadOnly = False
Next
'Dim idfCase As Object = -1
'If ds.Tables.Count > 0 AndAlso ds.Tables(0).Rows.Count > 0 Then
' If Not ds.Tables(0).Rows(0)("idfCase") Is DBNull.Value Then
' idfCase = ds.Tables(0).Rows(0)("idfCase")
' ElseIf Not ds.Tables(0).Rows(0)("idfMonitoringSession") Is DBNull.Value Then
' idfCase = ds.Tables(0).Rows(0)("idfMonitoringSession")
' ElseIf Not ds.Tables(0).Rows(0)("idfVectorSurveillanceSession") Is DBNull.Value Then
' idfCase = 0 'diagnosis for all vector sessions are the same and populated using predefined key = 0
' End If
'End If
cmd = CreateSPCommand("spLabTestEditable_GetSampleDiagnosis")
AddParam(cmd, "@idfMaterial", ID)
AddParam(cmd, "@idfCase", DBNull.Value)
AddParam(cmd, "@idfCaseType", DBNull.Value)
'AddParam(cmd, "@idfsDiagnosis", DBNull.Value)
AddParam(cmd, "@LangID", bv.model.Model.Core.ModelUserContext.CurrentLanguage)
FillDataset(cmd, ds, TableDiagnosis)
CorrectTable(ds.Tables(TableDiagnosis), TableDiagnosis)
m_ID = ID
Return ds
Catch ex As Exception
m_Error = New ErrorMessage(StandardError.FillDatasetError, ex)
Return Nothing
End Try
End Function
Public Overrides Function PostDetail(ByVal ds As DataSet, ByVal postType As Integer, Optional ByVal transaction As IDbTransaction = Nothing) As Boolean
If ds Is Nothing Then Return True
Try
Dim cmd As IDbCommand
Dim row As DataRow = ds.Tables(TableSample).Rows(0)
If row.RowState = DataRowState.Modified Then
cmd = CreateSPCommand("spLabSample_Post", transaction)
AddParam(cmd, "idfMaterial", ID)
AddParam(cmd, "@idfSubdivision", row("idfSubdivision"))
'AddParam(cmd, "@useDepartment", 1)
AddParam(cmd, "@idfInDepartment", row("idfInDepartment"))
AddParam(cmd, "@strNote", row("strNote"))
AddParam(cmd, "@strBarcode", row("strBarcode"))
ExecCommand(cmd, cmd.Connection, transaction, True)
End If
For Each testRow As DataRow In ds.Tables(TableTest).Rows
If testRow.RowState = DataRowState.Deleted _
OrElse testRow.RowState = DataRowState.Detached _
OrElse True.Equals(testRow("blnExternalTest")) Then
Continue For
End If
If (testRow.HasVersion(DataRowVersion.Original) AndAlso _
Not testRow("idfsTestStatus", DataRowVersion.Original).Equals(CLng(TestStatus.Finalized)) AndAlso _
testRow("idfsTestStatus").Equals(CLng(TestStatus.Finalized))) _
OrElse _
(Not testRow.HasVersion(DataRowVersion.Original) AndAlso testRow("idfsTestStatus").Equals(CLng(TestStatus.Finalized))) Then
Dim testID As Object = testRow("idfTesting")
If Not testID Is Nothing Then
If Not row("idfVectorSurveillanceSession") Is DBNull.Value Then
AddEvent(EventType.VsSessionTestResultRegistrationLocal, row("idfVectorSurveillanceSession"))
ElseIf Not row("idfMonitoringSession") Is DBNull.Value Then
AddEvent(EventType.AsSessionTestResultRegistrationLocal, row("idfMonitoringSession"))
ElseIf Not row("idfCase") Is DBNull.Value Then
If (CType(HACode.Human, Integer).Equals(row("intHACode"))) Then
AddEvent(EventType.HumanTestResultRegistrationLocal, row("idfCase"))
Else
AddEvent(EventType.VetCaseTestResultRegistrationLocal, row("idfCase"))
End If
End If
If (True.Equals(row("blnSampleTransferred"))) Then
AddEvent(EventType.TestResultForSampleTransferredIn, testID)
End If
End If
End If
Next
ExecPostProcedure("spLabSample_TestsPost", ds.Tables(TableTest), Connection, transaction)
Catch ex As Exception
m_Error = HandleError.ErrorMessage(ex)
Return False
End Try
Return True
End Function
End Class
|
EIDSS/EIDSS-Legacy
|
EIDSS v6.1/vb/EIDSS/EIDSS_Limps_db/Sample/Sample_DB.vb
|
Visual Basic
|
bsd-2-clause
| 5,972
|
Public Class KlemmleistenKorrigieren
<DeclareMenu()> _
Public Sub MenuFunction()
Dim oConMenuLoc As New Eplan.EplApi.Gui.ContextMenuLocation("TSGViewTree", "1004")
Dim oConMenu As New Eplan.EplApi.Gui.ContextMenu()
OConMenu.Addmenuitem(oConMenuLoc, "Klemmleisten korrigieren", "XTPCallAutoCorrectionDlgAction", False, False)
End Sub
End Class
|
LTS-AS/EplanScripting
|
EplanScriptingProjectBySuplanus/CorrectTerminalsInNavigator/CorrectTerminalsInNavigator.vb
|
Visual Basic
|
mit
| 380
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "fPermisos"
'-------------------------------------------------------------------------------------------'
Partial Class fPermisos
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 loConsulta As New StringBuilder()
loConsulta.AppendLine("")
loConsulta.AppendLine("SELECT Permisos.Documento,")
loConsulta.AppendLine(" Permisos.registro AS Fecha,")
loConsulta.AppendLine(" Permisos.status,")
loConsulta.AppendLine(" Permisos.cod_tra,")
loConsulta.AppendLine(" Trabajadores.nom_tra,")
loConsulta.AppendLine(" Trabajadores.cedula,")
loConsulta.AppendLine(" Permisos.remunerado,")
loConsulta.AppendLine(" Permisos.Fec_ini AS Desde,")
loConsulta.AppendLine(" Permisos.Fec_Fin AS hasta,")
loConsulta.AppendLine(" Permisos.Dias,")
loConsulta.AppendLine(" Permisos.justificado,")
loConsulta.AppendLine(" Permisos.comentario,")
loConsulta.AppendLine(" Permisos.motivo,")
loConsulta.AppendLine(" Motivos.nom_mot")
loConsulta.AppendLine("FROM Permisos")
loConsulta.AppendLine(" JOIN Trabajadores ON Trabajadores.cod_Tra = Permisos.Cod_Tra")
loConsulta.AppendLine(" JOIN Motivos ON Motivos.cod_mot = Permisos.motivo")
loConsulta.AppendLine("WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal)
loConsulta.AppendLine("")
loConsulta.AppendLine("")
loConsulta.AppendLine("")
Dim loServicios As New cusDatos.goDatos()
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loConsulta.ToString(), "curReportes")
Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa")
loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("fPermisos", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvfPermisos.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' RJG: 09/12/13: Programacion inicial
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
Reportes - Nomina/fPermisos.aspx.vb
|
Visual Basic
|
mit
| 3,747
|
Imports LyriX.Document
Imports DocumentViewModel
Partial Class LyriXPackageView
Implements IDocumentView
Private disposedValue As Boolean ' 检测冗余的调用
Private WithEvents CurrentDocument As LyriXPackageDocument
Private OutlineDictionary As New Dictionary(Of Document.ObjectModel.DataContainer, TreeViewItem)
Private Event ViewClosed(sender As Object, e As System.EventArgs) Implements DocumentViewModel.IDocumentView.Closed
Private Event ViewClosing(sender As Object, e As System.ComponentModel.CancelEventArgs) Implements DocumentViewModel.IDocumentView.Closing
Private Sub DocumentCommands_CanExecute(sender As System.Object, e As System.Windows.Input.CanExecuteRoutedEventArgs)
e.CanExecute = True
End Sub
Private Sub DocumentCommands_Executed(sender As System.Object, e As System.Windows.Input.ExecutedRoutedEventArgs)
If e.Command Is ApplicationCommands.[New] Then
DM.NewDocument()
ElseIf e.Command Is ApplicationCommands.Open Then
DM.OpenDocument()
ElseIf e.Command Is ApplicationCommands.Save Then
CurrentDocument.Save()
ElseIf e.Command Is ApplicationCommands.SaveAs Then
CurrentDocument.Save(True)
ElseIf e.Command Is ApplicationCommands.Close Then
CurrentDocument.Close()
ElseIf e.Command Is EditorCommands.CheckDocument Then
Dim cp As New Compilers.LyriXCompiler
cp.Compile(CurrentDocument.Package)
If cp.Output.Count = 0 Then
MsgBox(Prompts.CheckDocumentOver, MsgBoxStyle.Information)
Else
MsgBox(String.Format(
Prompts.CheckDocumentPrompt,
String.Join(vbCrLf,
From EachOutput In cp.Output Select ES = "- " & EachOutput.ToString)),
MsgBoxStyle.Information)
End If
ElseIf e.Command Is EditorCommands.NewWindow Then
DM.CreateView(CurrentDocument)
End If
End Sub
Public Sub Attach(newDocument As DocumentViewModel.Document) Implements DocumentViewModel.IDocumentView.Attach
CurrentDocument = DirectCast(newDocument, LyriXPackageDocument)
End Sub
Public Function Detach() As DocumentViewModel.Document Implements DocumentViewModel.IDocumentView.Detach
Dim PrevDocument = CurrentDocument
CurrentDocument = Nothing
Me.Close()
Return PrevDocument
End Function
Public Function GetDocument() As DocumentViewModel.Document Implements DocumentViewModel.IDocumentView.GetDocument
Return CurrentDocument
End Function
Public Sub Preview() Implements DocumentViewModel.IDocumentView.Preview
Me.Activate()
End Sub
Public Sub SetFoucs() Implements DocumentViewModel.IDocumentView.SetFoucs
Me.Activate()
End Sub
Public Sub Update(context As DocumentViewModel.UpdateContext) Implements DocumentViewModel.IDocumentView.Update
Me.Title = CurrentDocument.ToString
PackageOutline.Items.Clear()
OutlineDictionary.Clear()
PackageOutline.Items.Add(ConstructOutline(CurrentDocument.Package))
EditContainer(CurrentDocument.Package)
End Sub
''' <summary>
''' 从树状列表中移除指定项及其子项。
''' </summary>
Private Sub RemoveContainerOutline(container As Document.ObjectModel.DataContainer)
Debug.Assert(container IsNot Nothing)
Dim OutlineItem As TreeViewItem = Nothing
If OutlineDictionary.TryGetValue(container, OutlineItem) Then
OutlineDictionary.Remove(container)
Dim outlineParent = TryCast(OutlineItem.Parent, TreeViewItem)
outlineParent.Items.Remove(OutlineItem)
End If
For Each EachItem In container.Children
RemoveContainerOutline(EachItem)
Next
End Sub
''' <summary>
''' 由 DataContainer 获取其在树状列表中的项目。
''' </summary>
Private Function GetContainerOutline(container As Document.ObjectModel.DataContainer) As TreeViewItem
Dim item As TreeViewItem = Nothing
Debug.Assert(container IsNot Nothing)
OutlineDictionary.TryGetValue(container, item)
Return item
End Function
''' <summary>
''' 构造指定 DataContainer 的结构树。方向:隧道(从上到下)。
''' </summary>
''' <param name="forceConstruct">一定要构造项,而不是根据情况对某些类型的 DataContainer 返回 <c>null</c>。</param>
Private Function ConstructOutline(container As ObjectModel.DataContainer, Optional parent As TreeViewItem = Nothing,
Optional index As Integer = -1, Optional forceConstruct As Boolean = False) As TreeViewItem
'WARNING 此处不能使用 HierarchicalDataTemplate,
'因为在项目更新时,将列表绑定到 ListViewItem 的 ItemsSource 属性上会造成当前所选项来回移动
Debug.Assert(container IsNot Nothing)
Debug.Assert(TypeOf container.Tag Is LyriXDataContainerTag)
'添加本项
If Not forceConstruct AndAlso
(TypeOf container Is Document.Span OrElse
TypeOf container Is Document.LocalizedArtist OrElse
TypeOf container Is Document.LocalizedLine) Then
Return Nothing
End If
Dim Item As New TreeViewItem With {.Header = container}
If TypeOf container Is Document.LyriXPackage OrElse
TypeOf container Is Document.MusicInfo OrElse
TypeOf container Is Document.Lyrics OrElse
TypeOf container Is Document.Version OrElse
TypeOf container Is Document.LocalizedPackagePartsCollection Then
Item.IsExpanded = True
End If
If parent IsNot Nothing Then
If index >= 0 Then
parent.Items.Insert(index, Item)
Else
parent.Items.Add(Item)
End If
End If
OutlineDictionary.Add(container, Item)
'添加子项
For Each EachItem In container.Children
ConstructOutline(EachItem, Item)
Next
If TypeOf container.Children Is Specialized.INotifyCollectionChanged Then
'监听 NotifyCollectionChanged 事件,以便重构树状列表。
AddHandler DirectCast(container.Children, Specialized.INotifyCollectionChanged).CollectionChanged,
Sub(sender As Object, e As Specialized.NotifyCollectionChangedEventArgs)
Select Case e.Action
Case Specialized.NotifyCollectionChangedAction.Add
For Each EachItem As ObjectModel.DataContainer In e.NewItems
ConstructOutline(EachItem, Item, e.NewStartingIndex)
Next
Case Specialized.NotifyCollectionChangedAction.Remove
For Each EachItem As ObjectModel.DataContainer In e.OldItems
RemoveContainerOutline(EachItem)
Next
Case Specialized.NotifyCollectionChangedAction.Reset
'集合发生显著更改
Item.Items.Clear()
For Each EachItem As ObjectModel.DataContainer In container.Children
ConstructOutline(EachItem, Item)
Next
Case Specialized.NotifyCollectionChangedAction.Replace
Debug.Assert(e.OldItems.Count = e.NewItems.Count)
Dim I As Integer = 0
For Each EachItem As ObjectModel.DataContainer In e.OldItems
RemoveContainerOutline(EachItem)
ConstructOutline(EachItem, Item, e.NewStartingIndex)
I += 1
Next
End Select
End Sub
End If
Return Item
End Function
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
Me.Close()
End If
'释放非托管资源(非托管对象)并重写下面的 Finalize()。
'将大型字段设置为 null。
End If
Me.disposedValue = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Private Sub MainWindow_Closed(sender As Object, e As System.EventArgs) Handles Me.Closed
RaiseEvent ViewClosed(sender, e)
End Sub
Private Sub MainWindow_Closing(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles Me.Closing
CommitEditorChanges()
RaiseEvent ViewClosing(sender, e)
End Sub
Private Sub CurrentDocument_ModifiedChanged(sender As Object, e As System.EventArgs) Handles CurrentDocument.ModifiedChanged
Me.Title = CurrentDocument.ToString
End Sub
'提交编辑器焦点控件正在进行的修改
Private Sub CommitEditorChanges()
If TypeOf EditorFrame.Content Is DependencyObject Then
Dim FocusedElement = FocusManager.GetFocusedElement(Me)
If FocusedElement IsNot Nothing Then
FocusedElement.RaiseEvent(New RoutedEventArgs(UIElement.LostFocusEvent))
End If
End If
End Sub
Private Sub CurrentDocument_Saving(sender As Object, e As System.EventArgs) Handles CurrentDocument.Saving
CommitEditorChanges()
If CurrentDocument.IsModified Then
CurrentDocument.Package.Header.Revision += 1
End If
End Sub
End Class
|
CXuesong/legacy-LyriX
|
LyricsEditor/MainWindow_IView.vb
|
Visual Basic
|
mit
| 9,895
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.3.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(sender As Global.System.Object, e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.Symmex.Snowflake.DataAccess.My.MySettings
Get
Return Global.Symmex.Snowflake.DataAccess.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
Symmex/Snowflake
|
Source/Symmex.Snowflake.DataAccess/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,932
|
Option Infer On
Imports System
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim assemblyDocument As SolidEdgeAssembly.AssemblyDocument = Nothing
Dim physicalProperties As SolidEdgeAssembly.PhysicalProperties = 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)
assemblyDocument = TryCast(application.ActiveDocument, SolidEdgeAssembly.AssemblyDocument)
If assemblyDocument IsNot Nothing Then
physicalProperties = assemblyDocument.PhysicalProperties
physicalProperties.UserDefinedPropertiesStatus = True
Dim Volume As Double = 0.135
Dim Area As Double = 57
Dim Mass As Double = 5
Dim CenterOfMass = CType(New Double(), System.Array) { 15, 0.5, 5 }
Dim CenterOfVolume = CType(New Double(), System.Array) { 35, 0.05, 53 }
Dim GlobalMoments = CType(New Double(), System.Array) { 1, 4, 3, 5, 8, 7, 9 }
Dim PrincipalMoments = CType(New Double(), System.Array) { 4, 3, 5 }
Dim PrincipalAxis1 = CType(New Double(), System.Array) { 3, 9, 5 }
Dim PrincipalAxis2 = CType(New Double(), System.Array) { 7, 5, 6 }
Dim PrincipalAxis3 = CType(New Double(), System.Array) { 5, 8, 5 }
Dim RadiiOfGyration = CType(New Double(), System.Array) { 1, 5, 2 }
Dim OverrideMass As Double = 15
physicalProperties.SetUserDefinedAssemblyPhysicalProperties(Volume, Area, Mass, CenterOfMass, CenterOfVolume, GlobalMoments, PrincipalMoments, PrincipalAxis1, PrincipalAxis2, PrincipalAxis3, RadiiOfGyration, OverrideMass)
End If
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgeAssembly.PhysicalProperties.SetUserDefinedAssemblyPhysicalProperties.vb
|
Visual Basic
|
mit
| 2,481
|
' --- Copyright (c) notice NevoWeb ---
' Copyright (c) 2008 SARL NevoWeb. www.nevoweb.com. BSD License.
' Author: D.C.Lee
' ------------------------------------------------------------------------
' 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.
' ------------------------------------------------------------------------
' This copyright notice may NOT be removed, obscured or modified without written consent from the author.
' --- End copyright notice ---
Imports System
Imports System.IO
Imports DotNetNuke
Imports DotNetNuke.Common
Imports DotNetNuke.Common.Utilities.XmlUtils
Imports DotNetNuke.Common.Utilities
Imports NEvoWeb.Modules.NB_Store.SharedFunctions
Imports ICSharpCode.SharpZipLib.Zip
Imports ICSharpCode.SharpZipLib.Checksums
Imports ICSharpCode.SharpZipLib.GZip
Namespace NEvoWeb.Modules.NB_Store
Public Class Export
Public Function ExportImages(ByVal PortalID As Integer, ByVal strBackupFile As String, ByVal CategoryList As String) As String
Dim objPCtrl As New ProductController
Dim aryList As ArrayList
Dim hsTab As New Hashtable
Dim objPIInfo As NB_Store_ProductImageInfo
Dim objCCtrl As New CategoryController
Dim objCInfo As NB_Store_CategoriesInfo
Dim hsCatTab As Hashtable
hsCatTab = CategoryListToHashTable(CategoryList)
aryList = objPCtrl.GetProductImageExportList(PortalID)
For Each objPIInfo In aryList
If Not hsTab.ContainsValue(objPIInfo.ImagePath) Then
If hsCatTab.Count = 0 Then
hsTab.Add(objPIInfo.ImageID, objPIInfo.ImagePath)
Else
For Each CatID As String In hsCatTab.Keys
If IsNumeric(CatID) Then
If Not hsTab.ContainsKey(objPIInfo.ImageID) Then
If objPCtrl.IsInCategory(PortalID, objPIInfo.ProductID, CInt(CatID)) Then
hsTab.Add(objPIInfo.ImageID, objPIInfo.ImagePath)
End If
End If
End If
Next
End If
End If
Next
If hsCatTab.Count = 0 Then
aryList = objCCtrl.GetCategories(PortalID, GetCurrentCulture, -1, True, True)
For Each objCInfo In aryList
If objCInfo.ImageURL <> "" Then
If Not hsTab.ContainsValue(System.Web.Hosting.HostingEnvironment.MapPath(objCInfo.ImageURL)) Then
hsTab.Add("CAT" & objCInfo.CategoryID.ToString, System.Web.Hosting.HostingEnvironment.MapPath(objCInfo.ImageURL))
End If
End If
Next
Else
For Each CatID As String In hsCatTab.Keys
If IsNumeric(CatID) Then
objCInfo = objCCtrl.GetCategory(CInt(CatID), GetCurrentCulture)
If objCInfo.ImageURL <> "" Then
If Not hsTab.ContainsValue(System.Web.Hosting.HostingEnvironment.MapPath(objCInfo.ImageURL)) Then
hsTab.Add("CAT" & objCInfo.CategoryID.ToString, System.Web.Hosting.HostingEnvironment.MapPath(objCInfo.ImageURL))
End If
End If
End If
Next
End If
If ZipHashTable(hsTab, strBackupFile) Then
Return strBackupFile
Else
Return ""
End If
End Function
Private Function CategoryListToHashTable(ByVal CategoryList As String) As Hashtable
Dim catList As String()
Dim hashList As New Hashtable
If CategoryList <> "" Then
catList = Split(CategoryList, ",")
For lp As Integer = 0 To catList.GetUpperBound(0)
If Not hashList.ContainsKey(catList(lp)) Then
hashList.Add(catList(lp), catList(lp))
End If
Next
End If
Return hashList
End Function
Private Function ZipHashTable(ByVal list As Hashtable, ByVal ZipFileName As String) As Integer
Dim CompressionLevel As Integer = 0
Dim GUIDName As String = System.Guid.NewGuid.ToString
Dim fname As String
Dim ZipSize As Long
Dim Item As DictionaryEntry
'craete zip file
Dim strmZipFile As FileStream = Nothing
strmZipFile = File.Create(ZipFileName)
Dim strmZipStream As ZipOutputStream = Nothing
Try
strmZipStream = New ZipOutputStream(strmZipFile)
strmZipStream.SetLevel(CompressionLevel)
For Each Item In list
fname = Item.Value
If File.Exists(fname) Then
FileSystemUtils.AddToZip(strmZipStream, fname, System.IO.Path.GetFileName(fname), "")
End If
Next
Catch ex As Exception
Return False
Finally
If Not strmZipStream Is Nothing Then
ZipSize = strmZipStream.Length
strmZipStream.Finish()
strmZipStream.Close()
End If
End Try
Return True
End Function
Public Function ExportDocs(ByVal PortalID As Integer, ByVal strBackupFile As String) As String
Dim objPCtrl As New ProductController
Dim aryList As ArrayList
Dim hsTab As New Hashtable
Dim objDInfo As NB_Store_ProductDocInfo
aryList = objPCtrl.GetProductDocExportList(PortalID)
For Each objDInfo In aryList
If Not hsTab.ContainsValue(objDInfo.DocPath) Then
hsTab.Add(objDInfo.DocID, objDInfo.DocPath)
End If
Next
If ZipHashTable(hsTab, strBackupFile) Then
Return strBackupFile
Else
Return ""
End If
End Function
Public Function ExportProducts(ByVal PortalId As Integer, ByVal strBackupFile As String, ByVal blnExpOrders As Boolean, ByVal CategoryList As String) As String
Try
Dim strXML As String = ""
Dim objFile As New FileObj
Dim objPCtrl As New ProductController
Dim objPInfo As NB_Store_ProductsInfo
Dim objOCtrl As New OrderController
Dim objOInfo As NB_Store_OrdersInfo
Dim aryList As ArrayList
Dim supportedLanguages As LocaleCollection = GetValidLocales()
strXML &= "<root version=""1.0"">"
strXML &= "<products>"
For Each Lang As String In supportedLanguages
strXML &= "<" & Lang & ">"
aryList = objPCtrl.GetProductExportList(PortalId, Lang, False, CategoryList)
For Each objPInfo In aryList
strXML &= GetProductXML(objPInfo)
Next
strXML &= "</" & Lang & ">"
Next
strXML &= "</products>"
strXML &= GetCategoriesXML(PortalId, CategoryList)
'shipping now has it's own import export
'strXML &= GetShippingXML(PortalId)
strXML &= GetTaxXML(PortalId)
If blnExpOrders Then
strXML &= "<orders>"
aryList = objOCtrl.GetOrdersExportList(PortalId, -1)
For Each objOInfo In aryList
strXML &= GetOrderXML(objOInfo)
Next
strXML &= "</orders>"
End If
strXML &= "</root>"
objFile.SaveTextToFile(strXML, strBackupFile)
Return strBackupFile
Catch ex As Exception
Return ""
End Try
End Function
Public Function ExportShipping(ByVal PortalId As Integer, ByVal strBackupFile As String) As String
Try
Dim strXML As String = ""
Dim objFile As New FileObj
Dim objPCtrl As New ProductController
Dim supportedLanguages As LocaleCollection = GetValidLocales()
strXML &= "<root version=""1.0"">"
strXML &= GetShippingXML(PortalId)
strXML &= "</root>"
objFile.SaveTextToFile(strXML, strBackupFile)
Return strBackupFile
Catch ex As Exception
Return ""
End Try
End Function
Public Function ExportOrders(ByVal PortalID As Integer, ByVal ArchivedOnly As Boolean, ByVal strBackupFile As String) As String
Try
Dim strXML As String = ""
Dim objFile As New FileObj
Dim aryList As ArrayList
Dim supportedLanguages As LocaleCollection = GetValidLocales()
Dim objOCtrl As New OrderController
Dim objOInfo As NB_Store_OrdersInfo
strXML &= "<root version=""1.0"">"
strXML &= "<orders>"
If ArchivedOnly Then
aryList = objOCtrl.GetOrdersExportList(PortalID, 75)
Else
aryList = objOCtrl.GetOrdersExportList(PortalID, -1)
End If
For Each objOInfo In aryList
strXML &= GetOrderXML(objOInfo)
Next
strXML &= "</orders>"
strXML &= "</root>"
objFile.SaveTextToFile(strXML, strBackupFile)
Return strBackupFile
Catch ex As Exception
Return ""
End Try
End Function
Public Function GetCategoriesXML(ByVal PortalId As Integer, ByVal CategoryList As String) As String
Dim strXML As String = ""
Dim aryList As ArrayList
Dim objCCtrl As New CategoryController
Dim objCInfo As NB_Store_CategoriesInfo
Dim supportedLanguages As LocaleCollection = GetValidLocales()
Dim hsCatTab As Hashtable
hsCatTab = CategoryListToHashTable(CategoryList)
strXML &= "<categories>"
For Each Lang As String In supportedLanguages
strXML &= "<" & Lang & ">"
aryList = objCCtrl.GetCategories(PortalId, Lang)
For Each objCInfo In aryList
If hsCatTab.Count = 0 Then
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objCInfo)
Else
If hsCatTab.ContainsKey(objCInfo.CategoryID.ToString) Then
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objCInfo)
End If
End If
Next
strXML &= "</" & Lang & ">"
Next
strXML &= "</categories>"
Return strXML
End Function
Public Function GetShippingXML(ByVal PortalId As Integer) As String
Dim strXML As String = ""
Dim aryList As ArrayList
Dim objSCtrl As New ShipController
Dim objSInfo As NB_Store_ShippingRatesInfo
Dim supportedLanguages As LocaleCollection = GetValidLocales()
Dim arySMList As ArrayList
strXML &= "<shipping>"
arySMList = objSCtrl.GetShippingMethodList(PortalId)
For Each objSMInfo As NB_Store_ShippingMethodInfo In arySMList
strXML &= "<method>"
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objSMInfo)
strXML &= "<rate>"
aryList = objSCtrl.GetShippingRateList(PortalId, "", "", "", objSMInfo.ShipMethodID)
For Each objSInfo In aryList
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objSInfo)
Next
strXML &= "</rate>"
strXML &= "</method>"
Next
strXML &= "</shipping>"
Return strXML
End Function
Public Function GetTaxXML(ByVal PortalId As Integer) As String
Dim strXML As String = ""
Dim aryList As ArrayList
Dim objTCtrl As New TaxController
Dim objTInfo As NB_Store_TaxRatesInfo
Dim supportedLanguages As LocaleCollection = GetValidLocales()
strXML &= "<tax>"
aryList = objTCtrl.GetTaxRatesList(PortalId, "", "", "")
For Each objTInfo In aryList
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objTInfo)
Next
strXML &= "</tax>"
Return strXML
End Function
Public Function GetOrderXML(ByVal OrderID As Integer) As String
Dim objOCtrl As New OrderController
Dim objOInfo As NB_Store_OrdersInfo
objOInfo = objOCtrl.GetOrder(OrderID)
Return GetOrderXML(objOInfo)
End Function
Public Function GetOrderXML(ByVal objOInfo As NB_Store_OrdersInfo) As String
Dim strXML As String = ""
Dim objOCtrl As New OrderController
Dim aryList2 As ArrayList
Dim objODInfo As NB_Store_OrderDetailsInfo
Dim objAInfo As NB_Store_AddressInfo
strXML &= "<O>"
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objOInfo)
strXML &= "<BA>"
objAInfo = objOCtrl.GetOrderAddress(objOInfo.BillingAddressID)
If Not objAInfo Is Nothing Then
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objAInfo)
End If
strXML &= "</BA>"
strXML &= "<SA>"
objAInfo = objOCtrl.GetOrderAddress(objOInfo.ShippingAddressID)
If Not objAInfo Is Nothing Then
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objAInfo)
End If
strXML &= "</SA>"
strXML &= "<OD>"
aryList2 = objOCtrl.GetOrderDetailList(objOInfo.OrderID)
For Each objODInfo In aryList2
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objODInfo)
Next
strXML &= "</OD>"
strXML &= "</O>"
Return strXML
End Function
Public Function GetProductXML(ByVal ProductID As Integer, ByVal Lang As String) As String
Dim objPCtrl As New ProductController
Dim objPInfo As NB_Store_ProductsInfo
objPInfo = objPCtrl.GetProduct(ProductID, Lang)
If Not objPInfo Is Nothing Then
Return GetProductXML(objPInfo)
Else
Return ""
End If
End Function
Public Function GetProductXML(ByVal objPInfo As NB_Store_ProductsInfo) As String
Dim strXML As String = ""
Dim objPCtrl As New ProductController
Dim aryList2 As ArrayList
Dim aryList3 As ArrayList
Dim objMInfo As NB_Store_ModelInfo
Dim objPIInfo As NB_Store_ProductImageInfo
Dim objDInfo As NB_Store_ProductDocInfo
Dim objOInfo As NB_Store_OptionInfo
Dim objOVInfo As NB_Store_OptionValueInfo
strXML &= "<P>"
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objPInfo)
strXML &= "<M>"
aryList2 = objPCtrl.GetModelList(objPInfo.PortalID, objPInfo.ProductID, objPInfo.Lang, True)
For Each objMInfo In aryList2
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objMInfo)
Next
strXML &= "</M>"
strXML &= "<I>"
aryList2 = objPCtrl.GetProductImageList(objPInfo.ProductID, objPInfo.Lang)
For Each objPIInfo In aryList2
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objPIInfo)
Next
strXML &= "</I>"
strXML &= "<D>"
aryList2 = objPCtrl.GetProductDocList(objPInfo.ProductID, objPInfo.Lang)
For Each objDInfo In aryList2
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objDInfo)
Next
strXML &= "</D>"
strXML &= "<C>"
aryList2 = objPCtrl.GetCategoriesAssigned(objPInfo.ProductID)
For Each objCInfo As NB_Store_ProductCategoryInfo In aryList2
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objCInfo)
Next
strXML &= "</C>"
strXML &= "<R>"
aryList2 = objPCtrl.GetProductRelatedArray(objPInfo.PortalID, objPInfo.ProductID, objPInfo.Lang, -1, True)
For Each objRInfo As NB_Store_ProductRelatedInfo In aryList2
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objRInfo)
Next
strXML &= "</R>"
strXML &= "<options>"
aryList2 = objPCtrl.GetOptionList(objPInfo.ProductID, objPInfo.Lang)
For Each objOInfo In aryList2
strXML &= "<O>"
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objOInfo)
strXML &= "<OV>"
aryList3 = objPCtrl.GetOptionValueList(objOInfo.OptionID, objPInfo.Lang)
For Each objOVInfo In aryList3
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objOVInfo)
Next
strXML &= "</OV>"
strXML &= "</O>"
Next
strXML &= "</options>"
strXML &= "</P>"
Return strXML
End Function
Public Function GetSettingsXML(ByVal PortalId As Integer) As String
Return GetSettingsXML(PortalId, Nothing, Nothing)
End Function
Public Function GetSettingsXML(ByVal PortalId As Integer, ByVal chkList As CheckBoxList, ByVal LanguageList As Hashtable) As String
Dim strXML As String = ""
Dim objSCtrl As New SettingsController
Dim objOCtrl As New OrderController
Dim objSInfo As NB_Store_SettingsInfo
Dim aryList As ArrayList
strXML += "<settings>"
aryList = objSCtrl.GetSettingList(PortalId, "", True, "")
For Each objSInfo In aryList
If chkList Is Nothing Then
strXML += "<" & objSInfo.SettingName & " Lang=""" & objSInfo.Lang.Trim & """ CtrlType=""" & objSInfo.CtrlType & """" & " GroupRef=""" & objSInfo.GroupRef & """" & " HostOnly=""" & objSInfo.HostOnly & """><![CDATA[" & objSInfo.SettingValue & "]]></" & objSInfo.SettingName & ">"
Else
If Not chkList.Items.FindByValue(objSInfo.SettingName) Is Nothing Then
If chkList.Items.FindByValue(objSInfo.SettingName).Selected And LanguageList.Contains(objSInfo.Lang.Trim) Then
strXML += "<" & objSInfo.SettingName & " Lang=""" & objSInfo.Lang.Trim & """ CtrlType=""" & objSInfo.CtrlType & """" & " GroupRef=""" & objSInfo.GroupRef & """" & " HostOnly=""" & objSInfo.HostOnly & """><![CDATA[" & objSInfo.SettingValue & "]]></" & objSInfo.SettingName & ">"
End If
End If
End If
Next
strXML += "</settings>"
Return strXML
End Function
Public Function GetSettingsTextXML(ByVal PortalId As Integer) As String
Return GetSettingsTextXML(PortalId, Nothing, Nothing)
End Function
Public Function GetSettingsTextXML(ByVal PortalId As Integer, ByVal chkList As CheckBoxList, ByVal LanguageList As Hashtable) As String
Dim strXML As String = ""
Dim objSCtrl As New SettingsController
Dim objOCtrl As New OrderController
Dim objSTInfo As NB_Store_SettingsTextInfo
Dim aryList As ArrayList
strXML += "<settingstext>"
aryList = objSCtrl.GetSettingsTexts(PortalId, "", True, "")
For Each objSTInfo In aryList
If chkList Is Nothing Then
strXML += "<" & objSTInfo.SettingName & " Lang=""" & objSTInfo.Lang.Trim & """" & " CtrlType=""" & objSTInfo.CtrlType & """" & " GroupRef=""" & objSTInfo.GroupRef & """" & " HostOnly=""" & objSTInfo.HostOnly & """><![CDATA[" & objSTInfo.SettingText & "]]></" & objSTInfo.SettingName & ">"
Else
If Not chkList.Items.FindByValue(objSTInfo.SettingName) Is Nothing Then
If chkList.Items.FindByValue(objSTInfo.SettingName).Selected And LanguageList.Contains(objSTInfo.Lang.Trim) Then
strXML += "<" & objSTInfo.SettingName & " Lang=""" & objSTInfo.Lang.Trim & """" & " CtrlType=""" & objSTInfo.CtrlType & """" & " GroupRef=""" & objSTInfo.GroupRef & """" & " HostOnly=""" & objSTInfo.HostOnly & """><![CDATA[" & objSTInfo.SettingText & "]]></" & objSTInfo.SettingName & ">"
End If
End If
End If
Next
strXML += "</settingstext>"
Return strXML
End Function
Public Function GetStatusXML() As String
Dim strXML As String = ""
Dim objSCtrl As New SettingsController
Dim objOCtrl As New OrderController
Dim objOSInfo As NB_Store_OrderStatusInfo
Dim aryList As ArrayList
strXML += "<status>"
aryList = objOCtrl.GetOrderStatusList("")
For Each objOSInfo In aryList
strXML += "<ID" & objOSInfo.OrderStatusID.ToString & " Lang=""" & objOSInfo.Lang & """ ListOrder=""" & objOSInfo.ListOrder & """><![CDATA[" & objOSInfo.OrderStatusText & "]]></ID" & objOSInfo.OrderStatusID.ToString & ">"
Next
strXML += "</status>"
Return strXML
End Function
Public Function GetSQLReports(ByVal PortalID As Integer) As String
Dim strXML As String = ""
Dim objCtrl As New SQLReportController
Dim arySQLReportParams As ArrayList
Dim arySQLReports As ArrayList = objCtrl.GetSQLAdminReportList(PortalID, True, "")
Dim objSQLReport As NB_Store_SQLReportInfo
Dim objRPInfo As NB_Store_SQLReportParamInfo
Dim objXInfo As NB_Store_SQLReportXSLInfo
If arySQLReports.Count > 0 Then
strXML += "<SQLReports>"
For Each objSQLReport In arySQLReports
strXML += "<SQLReport>"
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objSQLReport)
strXML += "<SQLReportParams>"
arySQLReportParams = objCtrl.GetSQLReportParamList(objSQLReport.ReportID)
For Each objRPInfo In arySQLReportParams
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objRPInfo)
Next
strXML += "</SQLReportParams>"
strXML += "<SQLReportXSL>"
arySQLReportParams = objCtrl.GetSQLReportXSLList(objSQLReport.ReportID)
For Each objXInfo In arySQLReportParams
strXML &= DotNetNuke.Common.Utilities.XmlUtils.Serialize(objXInfo)
Next
strXML += "</SQLReportXSL>"
strXML += "</SQLReport>"
Next
strXML += "</SQLReports>"
End If
Return strXML
End Function
End Class
End Namespace
|
skamphuis/NB_Store
|
Components/General/Export.vb
|
Visual Basic
|
mit
| 25,126
|
Public Class Codabar
Inherits Barcode
Private Shared CODE_PATTERNS(,) As Byte = _
{{0, 0, 0, 0, 0, 1, 1}, _
{0, 0, 0, 0, 1, 1, 0}, _
{0, 0, 0, 1, 0, 0, 1}, _
{1, 1, 0, 0, 0, 0, 0}, _
{0, 0, 1, 0, 0, 1, 0}, _
{1, 0, 0, 0, 0, 1, 0}, _
{0, 1, 0, 0, 0, 0, 1}, _
{0, 1, 0, 0, 1, 0, 0}, _
{0, 1, 1, 0, 0, 0, 0}, _
{1, 0, 0, 1, 0, 0, 0}, _
{0, 0, 0, 1, 1, 0, 0}, _
{0, 0, 1, 1, 0, 0, 0}, _
{1, 0, 0, 0, 1, 0, 1}, _
{1, 0, 1, 0, 0, 0, 1}, _
{1, 0, 1, 0, 1, 0, 0}, _
{0, 0, 1, 0, 1, 0, 1}, _
{0, 0, 1, 1, 0, 1, 0}, _
{0, 1, 0, 1, 0, 0, 1}, _
{0, 0, 0, 1, 0, 1, 1}, _
{0, 0, 0, 1, 1, 1, 0}}
Private Const CHARS As String = "0123456789-$:/.+ABCD"
Private Const START_STOP_POINT As Integer = 16
Public GenerateCheckSum As Boolean = False
Public WithCheckSumText As Boolean = False
Public WithStartStopText As Boolean = False
Public Function Encode(ByVal codePoints As List(Of Integer)) As Byte()
Dim ret As New List(Of Byte)
For Each p As Integer In codePoints
Me.addCodes(ret, p)
Next
Return ret.ToArray
End Function
Public Function GetCodePoints(ByVal data As String) As List(Of Integer)
Dim ret As New List(Of Integer)
For i As Integer = 0 To data.Length - 1
Dim p As Integer = CHARS.IndexOf(Char.ToUpper(data(i)))
If p >= 0 Then
If i = 0 Or i = data.Length - 1 Then
If p < START_STOP_POINT Then
Throw New ArgumentException("(codabar)スタート/ストップ文字が含まれていません: " & data)
End If
Else
If p >= START_STOP_POINT Then
Throw New ArgumentException("(codabar)不正なデータです: " & data)
End If
End If
ret.Add(p)
Else
Throw New ArgumentException("(codabar)不正なデータです: " & data)
End If
Next
If ret.Count < 2 Then
Throw New ArgumentException("(codabar)不正なデータです: " & data)
End If
Return ret
End Function
Public Function CalcCheckDigit(ByVal ps As List(Of Integer)) As Integer
Dim s As Integer = 0
For Each p As Integer In ps
s += p
Next
Return (16 - (s Mod 16)) Mod 16
End Function
Public Sub AddCheckDigit(ByVal codePoints As List(Of Integer), ByVal cd As Integer)
codePoints.Insert(codePoints.Count - 1, cd)
End Sub
Public Function AddCheckDigit(ByVal txt As String, ByVal cd As Integer) As String
Dim ret As String = txt.Substring(0, txt.Length - 1)
ret &= CHARS(cd)
ret &= txt(txt.Length - 1)
Return ret
End Function
Public Function TrimStartStopText(ByVal txt As String) As String
Return txt.Substring(1, txt.Length - 2)
End Function
Private Sub addCodes(ByVal l As List(Of Byte), ByVal p As Integer)
If l.Count > 0 Then
l.Add(0)
End If
l.Add(CODE_PATTERNS(p, 0))
l.Add(CODE_PATTERNS(p, 1))
l.Add(CODE_PATTERNS(p, 2))
l.Add(CODE_PATTERNS(p, 3))
l.Add(CODE_PATTERNS(p, 4))
l.Add(CODE_PATTERNS(p, 5))
l.Add(CODE_PATTERNS(p, 6))
End Sub
Public Sub Render(ByVal g As Graphics, _
ByVal x As Single, ByVal y As Single, ByVal w As Single, ByVal h As Single, _
ByVal data As String)
Me.Render(g, New RectangleF(x, y, w, h), data)
End Sub
Public Sub Render(ByVal g As Graphics, ByVal r As RectangleF, ByVal data As String)
If data Is Nothing OrElse data.Length = 0 Then
Exit Sub
End If
Dim w As Single = r.Width - Me.MarginX * 2
Dim h As Single = r.Height - Me.MarginY * 2
Dim _h As Single = h
If Me.WithText Then
_h *= 0.7F
End If
If w <= 0 Or h <= 0 Then
Exit Sub
End If
Dim ps As List(Of Integer) = Me.GetCodePoints(data)
Dim txt As String = data
If Me.GenerateCheckSum Then
Dim cd As Integer = Me.CalcCheckDigit(ps)
Me.AddCheckDigit(ps, cd)
If Me.WithCheckSumText Then
txt = Me.AddCheckDigit(txt, cd)
End If
End If
If Not Me.WithStartStopText Then
txt = Me.TrimStartStopText(txt)
End If
Dim cs As Byte() = Me.Encode(ps)
Dim mw As Single
With Nothing
Dim l As Integer = 0
For Each c As Integer In cs
l += c + 1
Next
mw = w / l
End With
Dim draw As Boolean = True
Dim x As Single = MarginX
For i As Integer = 0 To cs.Length - 1
Dim dw As Single = (cs(i) + 1) * mw
If draw Then
g.FillRectangle(Brushes.Black, New RectangleF(r.X + x, r.Y + MarginY, dw * BarWidth, _h))
End If
draw = Not draw
x += dw
Next
If Me.WithText Then
Dim f As Font = GetFont(GetFontSize(g, txt, w, h))
Dim format As StringFormat = New StringFormat()
format.Alignment = StringAlignment.Center
g.DrawString(txt, f, Brushes.Black, r.X + w / 2 + MarginX, r.Y + _h + MarginY, format)
End If
End Sub
End Class
|
rapidreport/barcode-dotnet
|
barcode/Codabar.vb
|
Visual Basic
|
bsd-2-clause
| 5,559
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.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.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("a")> _
Public Property B1() As String
Get
Return CType(Me("B1"),String)
End Get
Set
Me("B1") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("b")> _
Public Property B2() As String
Get
Return CType(Me("B2"),String)
End Get
Set
Me("B2") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("c")> _
Public Property B3() As String
Get
Return CType(Me("B3"),String)
End Get
Set
Me("B3") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("d")> _
Public Property B4() As String
Get
Return CType(Me("B4"),String)
End Get
Set
Me("B4") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("e")> _
Public Property B5() As String
Get
Return CType(Me("B5"),String)
End Get
Set
Me("B5") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("f")> _
Public Property B6() As String
Get
Return CType(Me("B6"),String)
End Get
Set
Me("B6") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("g")> _
Public Property B7() As String
Get
Return CType(Me("B7"),String)
End Get
Set
Me("B7") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("h")> _
Public Property B8() As String
Get
Return CType(Me("B8"),String)
End Get
Set
Me("B8") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("i")> _
Public Property B9() As String
Get
Return CType(Me("B9"),String)
End Get
Set
Me("B9") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("j")> _
Public Property B10() As String
Get
Return CType(Me("B10"),String)
End Get
Set
Me("B10") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("k")> _
Public Property B11() As String
Get
Return CType(Me("B11"),String)
End Get
Set
Me("B11") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("w")> _
Public Property J1() As String
Get
Return CType(Me("J1"),String)
End Get
Set
Me("J1") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("y")> _
Public Property J2() As String
Get
Return CType(Me("J2"),String)
End Get
Set
Me("J2") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("False")> _
Public Property KeyboardEnabled() As Boolean
Get
Return CType(Me("KeyboardEnabled"),Boolean)
End Get
Set
Me("KeyboardEnabled") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("l")> _
Public Property B12() As String
Get
Return CType(Me("B12"),String)
End Get
Set
Me("B12") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("m")> _
Public Property B13() As String
Get
Return CType(Me("B13"),String)
End Get
Set
Me("B13") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("n")> _
Public Property B14() As String
Get
Return CType(Me("B14"),String)
End Get
Set
Me("B14") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("x")> _
Public Property K1() As String
Get
Return CType(Me("K1"),String)
End Get
Set
Me("K1") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("z")> _
Public Property K2() As String
Get
Return CType(Me("K2"),String)
End Get
Set
Me("K2") = value
End Set
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.WindowsReceiver.My.MySettings
Get
Return Global.WindowsReceiver.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
KaiserSoft/OpenSimButtonBox
|
Wheel Button Box/Arduino Nano/WindowsReceiver/My Project/Settings.Designer.vb
|
Visual Basic
|
bsd-3-clause
| 11,546
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators
Friend NotInheritable Class BinaryConditionalExpressionDocumentation
Inherits AbstractIntrinsicOperatorDocumentation
Public Overrides ReadOnly Property DocumentationText As String
Get
Return VBWorkspaceResources.If_expression_evaluates_to_a_reference_or_Nullable_value_that_is_not_Nothing_the_function_returns_that_value_Otherwise_it_calculates_and_returns_expressionIfNothing
End Get
End Property
Public Overrides Function GetParameterDocumentation(index As Integer) As String
Select Case index
Case 0
Return VBWorkspaceResources.Returned_if_it_evaluates_to_a_reference_or_nullable_type_that_is_not_Nothing
Case 1
Return VBWorkspaceResources.Evaluated_and_returned_if_expression_evaluates_to_Nothing
Case Else
Throw New ArgumentException(NameOf(index))
End Select
End Function
Public Overrides Function GetParameterName(index As Integer) As String
Select Case index
Case 0
Return VBWorkspaceResources.expression
Case 1
Return VBWorkspaceResources.expressionIfNothing
Case Else
Throw New ArgumentException(NameOf(index))
End Select
End Function
Public Overrides ReadOnly Property IncludeAsType As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return 2
End Get
End Property
Public Overrides ReadOnly Property PrefixParts As IList(Of SymbolDisplayPart)
Get
Return {New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, "If"),
New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(")}
End Get
End Property
End Class
End Namespace
|
abock/roslyn
|
src/Workspaces/VisualBasic/Portable/Utilities/IntrinsicOperators/BinaryConditionalExpressionDocumentation.vb
|
Visual Basic
|
mit
| 2,569
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.431
'
' 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("OpenCover.Samples.VB.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
|
mtscout6/opencover
|
samples/OpenCover.Samples.VB/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,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 Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenSelectCase
Inherits BasicTestBase
Private Shared Sub VerifySynthesizedStringHashMethod(compVerifier As CompilationVerifier, expected As Boolean)
Dim methodName = PrivateImplementationDetails.SynthesizedStringHashFunctionName + "(String)"
compVerifier.VerifyMemberInIL(methodName, expected)
If expected Then
compVerifier.VerifyIL(methodName, <![CDATA[
{
// Code size 44 (0x2c)
.maxstack 2
.locals init (UInteger V_0,
Integer V_1)
IL_0000: ldc.i4 0x811c9dc5
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: brfalse.s IL_002a
IL_0009: ldc.i4.0
IL_000a: stloc.1
IL_000b: br.s IL_0021
IL_000d: ldarg.0
IL_000e: ldloc.1
IL_000f: callvirt "Function String.get_Chars(Integer) As Char"
IL_0014: ldloc.0
IL_0015: xor
IL_0016: ldc.i4 0x1000193
IL_001b: mul
IL_001c: stloc.0
IL_001d: ldloc.1
IL_001e: ldc.i4.1
IL_001f: add
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldarg.0
IL_0023: callvirt "Function String.get_Length() As Integer"
IL_0028: blt.s IL_000d
IL_002a: ldloc.0
IL_002b: ret
}
]]>)
End If
End Sub
<Fact()>
Public Sub SelectCase_Empty()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.WriteLine("Foo")
Return 0
End Function
Sub Main()
Select Case Foo()
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:="Foo").VerifyIL("M1.Main", <![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: call "Function M1.Foo() As Integer"
IL_0005: pop
IL_0006: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact()>
Public Sub SimpleSelectCase_IfList()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(number as Integer)
Select Case number
Case Is < 1
Console.WriteLine("Less than 1")
Case 1 To 5
Console.WriteLine("Between 1 and 5, inclusive")
Case 6, 7, 8
Console.WriteLine("Between 6 and 8, inclusive")
Case 9 To 10
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:Less than 1
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 91 (0x5b)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: bge.s IL_0011
IL_0006: ldstr "Less than 1"
IL_000b: call "Sub System.Console.WriteLine(String)"
IL_0010: ret
IL_0011: ldloc.0
IL_0012: ldc.i4.1
IL_0013: blt.s IL_0024
IL_0015: ldloc.0
IL_0016: ldc.i4.5
IL_0017: bgt.s IL_0024
IL_0019: ldstr "Between 1 and 5, inclusive"
IL_001e: call "Sub System.Console.WriteLine(String)"
IL_0023: ret
IL_0024: ldloc.0
IL_0025: ldc.i4.6
IL_0026: beq.s IL_0030
IL_0028: ldloc.0
IL_0029: ldc.i4.7
IL_002a: beq.s IL_0030
IL_002c: ldloc.0
IL_002d: ldc.i4.8
IL_002e: bne.un.s IL_003b
IL_0030: ldstr "Between 6 and 8, inclusive"
IL_0035: call "Sub System.Console.WriteLine(String)"
IL_003a: ret
IL_003b: ldloc.0
IL_003c: ldc.i4.s 9
IL_003e: blt.s IL_0050
IL_0040: ldloc.0
IL_0041: ldc.i4.s 10
IL_0043: bgt.s IL_0050
IL_0045: ldstr "Equal to 9 or 10"
IL_004a: call "Sub System.Console.WriteLine(String)"
IL_004f: ret
IL_0050: ldstr "Greater than 10"
IL_0055: call "Sub System.Console.WriteLine(String)"
IL_005a: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SimpleSelectCase_Boolean()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 To 11
Console.Write(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(count As Integer)
Dim b As Boolean = count
Select Case b
Case 9, 10
If count <> 0 Then
Console.WriteLine("Non zero")
End If
Case 0
If count = 0 Then
Console.WriteLine("Equal to 0")
End If
Case 6, 7, 8
Case 1, 2, 3, 4, 5
Case Else
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:Equal to 0
1:Non zero
2:Non zero
3:Non zero
4:Non zero
5:Non zero
6:Non zero
7:Non zero
8:Non zero
9:Non zero
10:Non zero
11:Non zero]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 40 (0x28)
.maxstack 2
.locals init (Boolean V_0) //b
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: cgt.un
IL_0004: stloc.0
IL_0005: ldloc.0
IL_0006: brfalse.s IL_001a
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: bne.un.s IL_0027
IL_000c: ldarg.0
IL_000d: brfalse.s IL_0027
IL_000f: ldstr "Non zero"
IL_0014: call "Sub System.Console.WriteLine(String)"
IL_0019: ret
IL_001a: ldarg.0
IL_001b: brtrue.s IL_0027
IL_001d: ldstr "Equal to 0"
IL_0022: call "Sub System.Console.WriteLine(String)"
IL_0027: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SimpleSelectCase_DateTime()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Test(Nothing)
Test(#1/1/0001 12:00:00 AM#)
Test(#8/13/2002 12:15:10 PM#)
Test(#8/13/2002 12:00:00 PM#)
Test(#8/13/2002 12:16 PM#)
Test(#8/13/2002 12:15 PM#)
Test(#8/13/2002 12:05 PM#)
Test(#8/13/2002 12:17 PM#)
Test(#8/13/2002#)
End Sub
Dim cul = System.Globalization.CultureInfo.InvariantCulture
Sub Test(d as DateTime)
Console.WriteLine(d.ToString("M/d/yyyy h:mm:ss tt", cul))
Select Case d
Case #8/13/2002 12:15:10 PM#, #8/13/2002 12 PM#
Console.WriteLine("Case #8/13/2002 12:15:10 PM#, #8/13/2002 12 PM#")
Case Is >= #8/13/2002 12:16:15 PM#
Console.WriteLine("Case Is >= #8/13/2002 12:16:15 PM#")
Case #8/13/2002 12:14 PM# To #8/13/2002 12:16 PM#
Console.WriteLine("Case #8/13/2002 12:14 PM# To #8/13/2002 12:16 PM#")
Case #8/13/2002 12 PM#
Console.WriteLine("Case #8/13/2002 12 PM#")
Case #8/13/2002 12:05 PM#
Console.WriteLine("Case #8/13/2002 12:05 PM#")
Case Nothing
Console.WriteLine("Case Nothing")
Case Else
Console.WriteLine("Case Else")
End Select
Console.WriteLine()
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[1/1/0001 12:00:00 AM
Case Nothing
1/1/0001 12:00:00 AM
Case Nothing
8/13/2002 12:15:10 PM
Case #8/13/2002 12:15:10 PM#, #8/13/2002 12 PM#
8/13/2002 12:00:00 PM
Case #8/13/2002 12:15:10 PM#, #8/13/2002 12 PM#
8/13/2002 12:16:00 PM
Case #8/13/2002 12:14 PM# To #8/13/2002 12:16 PM#
8/13/2002 12:15:00 PM
Case #8/13/2002 12:14 PM# To #8/13/2002 12:16 PM#
8/13/2002 12:05:00 PM
Case #8/13/2002 12:05 PM#
8/13/2002 12:17:00 PM
Case Is >= #8/13/2002 12:16:15 PM#
8/13/2002 12:00:00 AM
Case Else]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 293 (0x125)
.maxstack 3
.locals init (Date V_0)
IL_0000: ldarga.s V_0
IL_0002: ldstr "M/d/yyyy h:mm:ss tt"
IL_0007: ldsfld "M1.cul As Object"
IL_000c: castclass "System.IFormatProvider"
IL_0011: call "Function Date.ToString(String, System.IFormatProvider) As String"
IL_0016: call "Sub System.Console.WriteLine(String)"
IL_001b: ldarg.0
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: ldc.i8 0x8c410da33ff5b00
IL_0027: newobj "Sub Date..ctor(Long)"
IL_002c: call "Function Date.Compare(Date, Date) As Integer"
IL_0031: brfalse.s IL_0049
IL_0033: ldloc.0
IL_0034: ldc.i8 0x8c410d815986000
IL_003d: newobj "Sub Date..ctor(Long)"
IL_0042: call "Function Date.Compare(Date, Date) As Integer"
IL_0047: brtrue.s IL_0058
IL_0049: ldstr "Case #8/13/2002 12:15:10 PM#, #8/13/2002 12 PM#"
IL_004e: call "Sub System.Console.WriteLine(String)"
IL_0053: br IL_011f
IL_0058: ldloc.0
IL_0059: ldc.i8 0x8c410da5abd9180
IL_0062: newobj "Sub Date..ctor(Long)"
IL_0067: call "Function Date.Compare(Date, Date) As Integer"
IL_006c: ldc.i4.0
IL_006d: blt.s IL_007e
IL_006f: ldstr "Case Is >= #8/13/2002 12:16:15 PM#"
IL_0074: call "Sub System.Console.WriteLine(String)"
IL_0079: br IL_011f
IL_007e: ldloc.0
IL_007f: ldc.i8 0x8c410da0a463400
IL_0088: newobj "Sub Date..ctor(Long)"
IL_008d: call "Function Date.Compare(Date, Date) As Integer"
IL_0092: ldc.i4.0
IL_0093: blt.s IL_00b8
IL_0095: ldloc.0
IL_0096: ldc.i8 0x8c410da51ccc000
IL_009f: newobj "Sub Date..ctor(Long)"
IL_00a4: call "Function Date.Compare(Date, Date) As Integer"
IL_00a9: ldc.i4.0
IL_00aa: bgt.s IL_00b8
IL_00ac: ldstr "Case #8/13/2002 12:14 PM# To #8/13/2002 12:16 PM#"
IL_00b1: call "Sub System.Console.WriteLine(String)"
IL_00b6: br.s IL_011f
IL_00b8: ldloc.0
IL_00b9: ldc.i8 0x8c410d815986000
IL_00c2: newobj "Sub Date..ctor(Long)"
IL_00c7: call "Function Date.Compare(Date, Date) As Integer"
IL_00cc: brtrue.s IL_00da
IL_00ce: ldstr "Case #8/13/2002 12 PM#"
IL_00d3: call "Sub System.Console.WriteLine(String)"
IL_00d8: br.s IL_011f
IL_00da: ldloc.0
IL_00db: ldc.i8 0x8c410d8c868be00
IL_00e4: newobj "Sub Date..ctor(Long)"
IL_00e9: call "Function Date.Compare(Date, Date) As Integer"
IL_00ee: brtrue.s IL_00fc
IL_00f0: ldstr "Case #8/13/2002 12:05 PM#"
IL_00f5: call "Sub System.Console.WriteLine(String)"
IL_00fa: br.s IL_011f
IL_00fc: ldloc.0
IL_00fd: ldsfld "Date.MinValue As Date"
IL_0102: call "Function Date.Compare(Date, Date) As Integer"
IL_0107: brtrue.s IL_0115
IL_0109: ldstr "Case Nothing"
IL_010e: call "Sub System.Console.WriteLine(String)"
IL_0113: br.s IL_011f
IL_0115: ldstr "Case Else"
IL_011a: call "Sub System.Console.WriteLine(String)"
IL_011f: call "Sub System.Console.WriteLine()"
IL_0124: ret
}]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SimpleSelectCase_SwitchTable_Integer()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(number as Integer)
Select Case number
Case 0
Console.WriteLine("Equal to 0")
Case 1, 2, 3, 4, 5
Console.WriteLine("Between 1 and 5, inclusive")
Case 6, 7, 8
Console.WriteLine("Between 6 and 8, inclusive")
Case 9, 10
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 109 (0x6d)
.maxstack 1
.locals init (Integer V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: switch (
IL_0036,
IL_0041,
IL_0041,
IL_0041,
IL_0041,
IL_0041,
IL_004c,
IL_004c,
IL_004c,
IL_0057,
IL_0057)
IL_0034: br.s IL_0062
IL_0036: ldstr "Equal to 0"
IL_003b: call "Sub System.Console.WriteLine(String)"
IL_0040: ret
IL_0041: ldstr "Between 1 and 5, inclusive"
IL_0046: call "Sub System.Console.WriteLine(String)"
IL_004b: ret
IL_004c: ldstr "Between 6 and 8, inclusive"
IL_0051: call "Sub System.Console.WriteLine(String)"
IL_0056: ret
IL_0057: ldstr "Equal to 9 or 10"
IL_005c: call "Sub System.Console.WriteLine(String)"
IL_0061: ret
IL_0062: ldstr "Greater than 10"
IL_0067: call "Sub System.Console.WriteLine(String)"
IL_006c: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SimpleSelectCase_SwitchTable_Signed()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 To 11
Console.WriteLine(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(count As Integer)
Dim i8 As SByte = count
Dim i16 As Int16 = count
Dim i64 As Int64 = count
Select Case i8
Case 9, 10
If count >= 9 AndAlso count <= 10 Then
Console.WriteLine("Equal to 9 or 10")
End If
Case 0
If count = 0 Then
Console.WriteLine("Equal to 0")
End If
Case 6, 7, 8
If count >= 6 AndAlso count <= 8 Then
Console.WriteLine("Between 6 and 8, inclusive")
End If
Case 1, 2, 3, 4, 5
If count >= 1 AndAlso count <= 10 Then
Console.WriteLine("Between 1 and 5, inclusive")
End If
Case Else
If count > 10 Then
Console.WriteLine("Greater than 10")
End If
End Select
Select Case i16
Case 9, 10
If count >= 9 AndAlso count <= 10 Then
Console.WriteLine("Equal to 9 or 10")
End If
Case 0
If count = 0 Then
Console.WriteLine("Equal to 0")
End If
Case 6, 7, 8
If count >= 6 AndAlso count <= 8 Then
Console.WriteLine("Between 6 and 8, inclusive")
End If
Case 1, 2, 3, 4, 5
If count >= 1 AndAlso count <= 10 Then
Console.WriteLine("Between 1 and 5, inclusive")
End If
Case Else
If count > 10 Then
Console.WriteLine("Greater than 10")
End If
End Select
Select Case i64
Case 9, 10
If count >= 9 AndAlso count <= 10 Then
Console.WriteLine("Equal to 9 or 10")
End If
Case 0
If count = 0 Then
Console.WriteLine("Equal to 0")
End If
Case 6, 7, 8
If count >= 6 AndAlso count <= 8 Then
Console.WriteLine("Between 6 and 8, inclusive")
End If
Case 1, 2, 3, 4, 5
If count >= 1 AndAlso count <= 10 Then
Console.WriteLine("Between 1 and 5, inclusive")
End If
Case Else
If count > 10 Then
Console.WriteLine("Greater than 10")
End If
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:
Equal to 0
Equal to 0
Equal to 0
1:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
2:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
3:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
4:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
5:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
6:
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
7:
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
8:
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
9:
Equal to 9 or 10
Equal to 9 or 10
Equal to 9 or 10
10:
Equal to 9 or 10
Equal to 9 or 10
Equal to 9 or 10
11:
Greater than 10
Greater than 10
Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 451 (0x1c3)
.maxstack 3
.locals init (SByte V_0, //i8
Short V_1, //i16
Long V_2) //i64
IL_0000: ldarg.0
IL_0001: conv.ovf.i1
IL_0002: stloc.0
IL_0003: ldarg.0
IL_0004: conv.ovf.i2
IL_0005: stloc.1
IL_0006: ldarg.0
IL_0007: conv.i8
IL_0008: stloc.2
IL_0009: ldloc.0
IL_000a: switch (
IL_0053,
IL_0076,
IL_0076,
IL_0076,
IL_0076,
IL_0076,
IL_0062,
IL_0062,
IL_0062,
IL_003d,
IL_003d)
IL_003b: br.s IL_008b
IL_003d: ldarg.0
IL_003e: ldc.i4.s 9
IL_0040: blt.s IL_009a
IL_0042: ldarg.0
IL_0043: ldc.i4.s 10
IL_0045: bgt.s IL_009a
IL_0047: ldstr "Equal to 9 or 10"
IL_004c: call "Sub System.Console.WriteLine(String)"
IL_0051: br.s IL_009a
IL_0053: ldarg.0
IL_0054: brtrue.s IL_009a
IL_0056: ldstr "Equal to 0"
IL_005b: call "Sub System.Console.WriteLine(String)"
IL_0060: br.s IL_009a
IL_0062: ldarg.0
IL_0063: ldc.i4.6
IL_0064: blt.s IL_009a
IL_0066: ldarg.0
IL_0067: ldc.i4.8
IL_0068: bgt.s IL_009a
IL_006a: ldstr "Between 6 and 8, inclusive"
IL_006f: call "Sub System.Console.WriteLine(String)"
IL_0074: br.s IL_009a
IL_0076: ldarg.0
IL_0077: ldc.i4.1
IL_0078: blt.s IL_009a
IL_007a: ldarg.0
IL_007b: ldc.i4.s 10
IL_007d: bgt.s IL_009a
IL_007f: ldstr "Between 1 and 5, inclusive"
IL_0084: call "Sub System.Console.WriteLine(String)"
IL_0089: br.s IL_009a
IL_008b: ldarg.0
IL_008c: ldc.i4.s 10
IL_008e: ble.s IL_009a
IL_0090: ldstr "Greater than 10"
IL_0095: call "Sub System.Console.WriteLine(String)"
IL_009a: ldloc.1
IL_009b: switch (
IL_00e4,
IL_0107,
IL_0107,
IL_0107,
IL_0107,
IL_0107,
IL_00f3,
IL_00f3,
IL_00f3,
IL_00ce,
IL_00ce)
IL_00cc: br.s IL_011c
IL_00ce: ldarg.0
IL_00cf: ldc.i4.s 9
IL_00d1: blt.s IL_012b
IL_00d3: ldarg.0
IL_00d4: ldc.i4.s 10
IL_00d6: bgt.s IL_012b
IL_00d8: ldstr "Equal to 9 or 10"
IL_00dd: call "Sub System.Console.WriteLine(String)"
IL_00e2: br.s IL_012b
IL_00e4: ldarg.0
IL_00e5: brtrue.s IL_012b
IL_00e7: ldstr "Equal to 0"
IL_00ec: call "Sub System.Console.WriteLine(String)"
IL_00f1: br.s IL_012b
IL_00f3: ldarg.0
IL_00f4: ldc.i4.6
IL_00f5: blt.s IL_012b
IL_00f7: ldarg.0
IL_00f8: ldc.i4.8
IL_00f9: bgt.s IL_012b
IL_00fb: ldstr "Between 6 and 8, inclusive"
IL_0100: call "Sub System.Console.WriteLine(String)"
IL_0105: br.s IL_012b
IL_0107: ldarg.0
IL_0108: ldc.i4.1
IL_0109: blt.s IL_012b
IL_010b: ldarg.0
IL_010c: ldc.i4.s 10
IL_010e: bgt.s IL_012b
IL_0110: ldstr "Between 1 and 5, inclusive"
IL_0115: call "Sub System.Console.WriteLine(String)"
IL_011a: br.s IL_012b
IL_011c: ldarg.0
IL_011d: ldc.i4.s 10
IL_011f: ble.s IL_012b
IL_0121: ldstr "Greater than 10"
IL_0126: call "Sub System.Console.WriteLine(String)"
IL_012b: ldloc.2
IL_012c: dup
IL_012d: ldc.i4.s 10
IL_012f: conv.i8
IL_0130: ble.un.s IL_0135
IL_0132: pop
IL_0133: br.s IL_01b3
IL_0135: conv.u4
IL_0136: switch (
IL_017e,
IL_019f,
IL_019f,
IL_019f,
IL_019f,
IL_019f,
IL_018c,
IL_018c,
IL_018c,
IL_0169,
IL_0169)
IL_0167: br.s IL_01b3
IL_0169: ldarg.0
IL_016a: ldc.i4.s 9
IL_016c: blt.s IL_01c2
IL_016e: ldarg.0
IL_016f: ldc.i4.s 10
IL_0171: bgt.s IL_01c2
IL_0173: ldstr "Equal to 9 or 10"
IL_0178: call "Sub System.Console.WriteLine(String)"
IL_017d: ret
IL_017e: ldarg.0
IL_017f: brtrue.s IL_01c2
IL_0181: ldstr "Equal to 0"
IL_0186: call "Sub System.Console.WriteLine(String)"
IL_018b: ret
IL_018c: ldarg.0
IL_018d: ldc.i4.6
IL_018e: blt.s IL_01c2
IL_0190: ldarg.0
IL_0191: ldc.i4.8
IL_0192: bgt.s IL_01c2
IL_0194: ldstr "Between 6 and 8, inclusive"
IL_0199: call "Sub System.Console.WriteLine(String)"
IL_019e: ret
IL_019f: ldarg.0
IL_01a0: ldc.i4.1
IL_01a1: blt.s IL_01c2
IL_01a3: ldarg.0
IL_01a4: ldc.i4.s 10
IL_01a6: bgt.s IL_01c2
IL_01a8: ldstr "Between 1 and 5, inclusive"
IL_01ad: call "Sub System.Console.WriteLine(String)"
IL_01b2: ret
IL_01b3: ldarg.0
IL_01b4: ldc.i4.s 10
IL_01b6: ble.s IL_01c2
IL_01b8: ldstr "Greater than 10"
IL_01bd: call "Sub System.Console.WriteLine(String)"
IL_01c2: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SimpleSelectCase_SwitchTable_Unsigned()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 To 11
Console.WriteLine(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(count As Integer)
Dim b As Byte = count
Dim ui16 As UInt16 = count
Dim ui32 As UInt32 = count
Dim ui64 As UInt64 = count
Select Case b
Case 9, 10
If count >= 9 AndAlso count <= 10 Then
Console.WriteLine("Equal to 9 or 10")
End If
Case 0
If count = 0 Then
Console.WriteLine("Equal to 0")
End If
Case 6, 7, 8
If count >= 6 AndAlso count <= 8 Then
Console.WriteLine("Between 6 and 8, inclusive")
End If
Case 1, 2, 3, 4, 5
If count >= 1 AndAlso count <= 10 Then
Console.WriteLine("Between 1 and 5, inclusive")
End If
Case Else
If count > 10 Then
Console.WriteLine("Greater than 10")
End If
End Select
Select Case ui16
Case 9, 10
If count >= 9 AndAlso count <= 10 Then
Console.WriteLine("Equal to 9 or 10")
End If
Case 0
If count = 0 Then
Console.WriteLine("Equal to 0")
End If
Case 6, 7, 8
If count >= 6 AndAlso count <= 8 Then
Console.WriteLine("Between 6 and 8, inclusive")
End If
Case 1, 2, 3, 4, 5
If count >= 1 AndAlso count <= 10 Then
Console.WriteLine("Between 1 and 5, inclusive")
End If
Case Else
If count > 10 Then
Console.WriteLine("Greater than 10")
End If
End Select
Select Case ui32
Case 9, 10
If count >= 9 AndAlso count <= 10 Then
Console.WriteLine("Equal to 9 or 10")
End If
Case 0
If count = 0 Then
Console.WriteLine("Equal to 0")
End If
Case 6, 7, 8
If count >= 6 AndAlso count <= 8 Then
Console.WriteLine("Between 6 and 8, inclusive")
End If
Case 1, 2, 3, 4, 5
If count >= 1 AndAlso count <= 10 Then
Console.WriteLine("Between 1 and 5, inclusive")
End If
Case Else
If count > 10 Then
Console.WriteLine("Greater than 10")
End If
End Select
Select Case ui64
Case 9, 10
If count >= 9 AndAlso count <= 10 Then
Console.WriteLine("Equal to 9 or 10")
End If
Case 0
If count = 0 Then
Console.WriteLine("Equal to 0")
End If
Case 6, 7, 8
If count >= 6 AndAlso count <= 8 Then
Console.WriteLine("Between 6 and 8, inclusive")
End If
Case 1, 2, 3, 4, 5
If count >= 1 AndAlso count <= 10 Then
Console.WriteLine("Between 1 and 5, inclusive")
End If
Case Else
If count > 10 Then
Console.WriteLine("Greater than 10")
End If
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:
Equal to 0
Equal to 0
Equal to 0
Equal to 0
1:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
2:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
3:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
4:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
5:
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
Between 1 and 5, inclusive
6:
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
7:
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
8:
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
Between 6 and 8, inclusive
9:
Equal to 9 or 10
Equal to 9 or 10
Equal to 9 or 10
Equal to 9 or 10
10:
Equal to 9 or 10
Equal to 9 or 10
Equal to 9 or 10
Equal to 9 or 10
11:
Greater than 10
Greater than 10
Greater than 10
Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 599 (0x257)
.maxstack 3
.locals init (Byte V_0, //b
UShort V_1, //ui16
UInteger V_2, //ui32
ULong V_3) //ui64
IL_0000: ldarg.0
IL_0001: conv.ovf.u1
IL_0002: stloc.0
IL_0003: ldarg.0
IL_0004: conv.ovf.u2
IL_0005: stloc.1
IL_0006: ldarg.0
IL_0007: conv.ovf.u4
IL_0008: stloc.2
IL_0009: ldarg.0
IL_000a: conv.ovf.u8
IL_000b: stloc.3
IL_000c: ldloc.0
IL_000d: switch (
IL_0056,
IL_0079,
IL_0079,
IL_0079,
IL_0079,
IL_0079,
IL_0065,
IL_0065,
IL_0065,
IL_0040,
IL_0040)
IL_003e: br.s IL_008e
IL_0040: ldarg.0
IL_0041: ldc.i4.s 9
IL_0043: blt.s IL_009d
IL_0045: ldarg.0
IL_0046: ldc.i4.s 10
IL_0048: bgt.s IL_009d
IL_004a: ldstr "Equal to 9 or 10"
IL_004f: call "Sub System.Console.WriteLine(String)"
IL_0054: br.s IL_009d
IL_0056: ldarg.0
IL_0057: brtrue.s IL_009d
IL_0059: ldstr "Equal to 0"
IL_005e: call "Sub System.Console.WriteLine(String)"
IL_0063: br.s IL_009d
IL_0065: ldarg.0
IL_0066: ldc.i4.6
IL_0067: blt.s IL_009d
IL_0069: ldarg.0
IL_006a: ldc.i4.8
IL_006b: bgt.s IL_009d
IL_006d: ldstr "Between 6 and 8, inclusive"
IL_0072: call "Sub System.Console.WriteLine(String)"
IL_0077: br.s IL_009d
IL_0079: ldarg.0
IL_007a: ldc.i4.1
IL_007b: blt.s IL_009d
IL_007d: ldarg.0
IL_007e: ldc.i4.s 10
IL_0080: bgt.s IL_009d
IL_0082: ldstr "Between 1 and 5, inclusive"
IL_0087: call "Sub System.Console.WriteLine(String)"
IL_008c: br.s IL_009d
IL_008e: ldarg.0
IL_008f: ldc.i4.s 10
IL_0091: ble.s IL_009d
IL_0093: ldstr "Greater than 10"
IL_0098: call "Sub System.Console.WriteLine(String)"
IL_009d: ldloc.1
IL_009e: switch (
IL_00e7,
IL_010a,
IL_010a,
IL_010a,
IL_010a,
IL_010a,
IL_00f6,
IL_00f6,
IL_00f6,
IL_00d1,
IL_00d1)
IL_00cf: br.s IL_011f
IL_00d1: ldarg.0
IL_00d2: ldc.i4.s 9
IL_00d4: blt.s IL_012e
IL_00d6: ldarg.0
IL_00d7: ldc.i4.s 10
IL_00d9: bgt.s IL_012e
IL_00db: ldstr "Equal to 9 or 10"
IL_00e0: call "Sub System.Console.WriteLine(String)"
IL_00e5: br.s IL_012e
IL_00e7: ldarg.0
IL_00e8: brtrue.s IL_012e
IL_00ea: ldstr "Equal to 0"
IL_00ef: call "Sub System.Console.WriteLine(String)"
IL_00f4: br.s IL_012e
IL_00f6: ldarg.0
IL_00f7: ldc.i4.6
IL_00f8: blt.s IL_012e
IL_00fa: ldarg.0
IL_00fb: ldc.i4.8
IL_00fc: bgt.s IL_012e
IL_00fe: ldstr "Between 6 and 8, inclusive"
IL_0103: call "Sub System.Console.WriteLine(String)"
IL_0108: br.s IL_012e
IL_010a: ldarg.0
IL_010b: ldc.i4.1
IL_010c: blt.s IL_012e
IL_010e: ldarg.0
IL_010f: ldc.i4.s 10
IL_0111: bgt.s IL_012e
IL_0113: ldstr "Between 1 and 5, inclusive"
IL_0118: call "Sub System.Console.WriteLine(String)"
IL_011d: br.s IL_012e
IL_011f: ldarg.0
IL_0120: ldc.i4.s 10
IL_0122: ble.s IL_012e
IL_0124: ldstr "Greater than 10"
IL_0129: call "Sub System.Console.WriteLine(String)"
IL_012e: ldloc.2
IL_012f: switch (
IL_0178,
IL_019b,
IL_019b,
IL_019b,
IL_019b,
IL_019b,
IL_0187,
IL_0187,
IL_0187,
IL_0162,
IL_0162)
IL_0160: br.s IL_01b0
IL_0162: ldarg.0
IL_0163: ldc.i4.s 9
IL_0165: blt.s IL_01bf
IL_0167: ldarg.0
IL_0168: ldc.i4.s 10
IL_016a: bgt.s IL_01bf
IL_016c: ldstr "Equal to 9 or 10"
IL_0171: call "Sub System.Console.WriteLine(String)"
IL_0176: br.s IL_01bf
IL_0178: ldarg.0
IL_0179: brtrue.s IL_01bf
IL_017b: ldstr "Equal to 0"
IL_0180: call "Sub System.Console.WriteLine(String)"
IL_0185: br.s IL_01bf
IL_0187: ldarg.0
IL_0188: ldc.i4.6
IL_0189: blt.s IL_01bf
IL_018b: ldarg.0
IL_018c: ldc.i4.8
IL_018d: bgt.s IL_01bf
IL_018f: ldstr "Between 6 and 8, inclusive"
IL_0194: call "Sub System.Console.WriteLine(String)"
IL_0199: br.s IL_01bf
IL_019b: ldarg.0
IL_019c: ldc.i4.1
IL_019d: blt.s IL_01bf
IL_019f: ldarg.0
IL_01a0: ldc.i4.s 10
IL_01a2: bgt.s IL_01bf
IL_01a4: ldstr "Between 1 and 5, inclusive"
IL_01a9: call "Sub System.Console.WriteLine(String)"
IL_01ae: br.s IL_01bf
IL_01b0: ldarg.0
IL_01b1: ldc.i4.s 10
IL_01b3: ble.s IL_01bf
IL_01b5: ldstr "Greater than 10"
IL_01ba: call "Sub System.Console.WriteLine(String)"
IL_01bf: ldloc.3
IL_01c0: dup
IL_01c1: ldc.i4.s 10
IL_01c3: conv.i8
IL_01c4: ble.un.s IL_01c9
IL_01c6: pop
IL_01c7: br.s IL_0247
IL_01c9: conv.u4
IL_01ca: switch (
IL_0212,
IL_0233,
IL_0233,
IL_0233,
IL_0233,
IL_0233,
IL_0220,
IL_0220,
IL_0220,
IL_01fd,
IL_01fd)
IL_01fb: br.s IL_0247
IL_01fd: ldarg.0
IL_01fe: ldc.i4.s 9
IL_0200: blt.s IL_0256
IL_0202: ldarg.0
IL_0203: ldc.i4.s 10
IL_0205: bgt.s IL_0256
IL_0207: ldstr "Equal to 9 or 10"
IL_020c: call "Sub System.Console.WriteLine(String)"
IL_0211: ret
IL_0212: ldarg.0
IL_0213: brtrue.s IL_0256
IL_0215: ldstr "Equal to 0"
IL_021a: call "Sub System.Console.WriteLine(String)"
IL_021f: ret
IL_0220: ldarg.0
IL_0221: ldc.i4.6
IL_0222: blt.s IL_0256
IL_0224: ldarg.0
IL_0225: ldc.i4.8
IL_0226: bgt.s IL_0256
IL_0228: ldstr "Between 6 and 8, inclusive"
IL_022d: call "Sub System.Console.WriteLine(String)"
IL_0232: ret
IL_0233: ldarg.0
IL_0234: ldc.i4.1
IL_0235: blt.s IL_0256
IL_0237: ldarg.0
IL_0238: ldc.i4.s 10
IL_023a: bgt.s IL_0256
IL_023c: ldstr "Between 1 and 5, inclusive"
IL_0241: call "Sub System.Console.WriteLine(String)"
IL_0246: ret
IL_0247: ldarg.0
IL_0248: ldc.i4.s 10
IL_024a: ble.s IL_0256
IL_024c: ldstr "Greater than 10"
IL_0251: call "Sub System.Console.WriteLine(String)"
IL_0256: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub CaseElseOnlySelectCase()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Dim number As Integer = 0
Select Case number
Case Else
Console.WriteLine("CaseElse")
End Select
Select Case 0
Case Else
Console.WriteLine("CaseElse")
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[CaseElse
CaseElse]]>).VerifyIL("M1.Main", <![CDATA[
{
// Code size 25 (0x19)
.maxstack 1
.locals init (Integer V_0, //number
Integer V_1)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldstr "CaseElse"
IL_0007: call "Sub System.Console.WriteLine(String)"
IL_000c: ldc.i4.0
IL_000d: stloc.1
IL_000e: ldstr "CaseElse"
IL_0013: call "Sub System.Console.WriteLine(String)"
IL_0018: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_NonNullableExpr_NothingCaseClause()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Dim x As Integer
Select Case x
Case Nothing, 1, 2, 3, 4
Console.Write("Success")
Case 0
Console.Write("Fail")
Case Else
Console.Write("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 57 (0x39)
.maxstack 2
.locals init (Integer V_0, //x
Integer V_1)
IL_0000: ldloc.0
IL_0001: stloc.1
IL_0002: ldloc.1
IL_0003: brfalse.s IL_0015
IL_0005: ldloc.1
IL_0006: ldc.i4.1
IL_0007: beq.s IL_0015
IL_0009: ldloc.1
IL_000a: ldc.i4.2
IL_000b: beq.s IL_0015
IL_000d: ldloc.1
IL_000e: ldc.i4.3
IL_000f: beq.s IL_0015
IL_0011: ldloc.1
IL_0012: ldc.i4.4
IL_0013: bne.un.s IL_0020
IL_0015: ldstr "Success"
IL_001a: call "Sub System.Console.Write(String)"
IL_001f: ret
IL_0020: ldloc.1
IL_0021: brtrue.s IL_002e
IL_0023: ldstr "Fail"
IL_0028: call "Sub System.Console.Write(String)"
IL_002d: ret
IL_002e: ldstr "Fail"
IL_0033: call "Sub System.Console.Write(String)"
IL_0038: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_NothingSelectExpr()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Select Case Nothing
Case 1, 2, 3, 4
Console.Write("Fail")
Case 0
Console.Write("Success")
Case Else
Console.Write("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 143 (0x8f)
.maxstack 3
.locals init (Object V_0)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: box "Integer"
IL_0009: ldc.i4.0
IL_000a: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectEqual(Object, Object, Boolean) As Object"
IL_000f: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_0014: brtrue.s IL_0052
IL_0016: ldloc.0
IL_0017: ldc.i4.2
IL_0018: box "Integer"
IL_001d: ldc.i4.0
IL_001e: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectEqual(Object, Object, Boolean) As Object"
IL_0023: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_0028: brtrue.s IL_0052
IL_002a: ldloc.0
IL_002b: ldc.i4.3
IL_002c: box "Integer"
IL_0031: ldc.i4.0
IL_0032: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectEqual(Object, Object, Boolean) As Object"
IL_0037: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_003c: brtrue.s IL_0052
IL_003e: ldloc.0
IL_003f: ldc.i4.4
IL_0040: box "Integer"
IL_0045: ldc.i4.0
IL_0046: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectEqual(Object, Object, Boolean) As Object"
IL_004b: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_0050: br.s IL_0053
IL_0052: ldc.i4.1
IL_0053: box "Boolean"
IL_0058: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_005d: brfalse.s IL_006a
IL_005f: ldstr "Fail"
IL_0064: call "Sub System.Console.Write(String)"
IL_0069: ret
IL_006a: ldloc.0
IL_006b: ldc.i4.0
IL_006c: box "Integer"
IL_0071: ldc.i4.0
IL_0072: call "Function Microsoft.VisualBasic.CompilerServices.Operators.ConditionalCompareObjectEqual(Object, Object, Boolean) As Boolean"
IL_0077: brfalse.s IL_0084
IL_0079: ldstr "Success"
IL_007e: call "Sub System.Console.Write(String)"
IL_0083: ret
IL_0084: ldstr "Fail"
IL_0089: call "Sub System.Console.Write(String)"
IL_008e: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ValueClause_01()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Select Case 0
Case 0, 1
Console.WriteLine("Success")
Case 1 - 1
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brfalse.s IL_0009
IL_0005: ldloc.0
IL_0006: ldc.i4.1
IL_0007: bne.un.s IL_0014
IL_0009: ldstr "Success"
IL_000e: call "Sub System.Console.WriteLine(String)"
IL_0013: ret
IL_0014: ldstr "Fail"
IL_0019: call "Sub System.Console.WriteLine(String)"
IL_001e: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ValueClause_02()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Select Case 0
Case 1, 2
Console.WriteLine("Fail")
Case 1 - 1
Console.WriteLine("Success")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 55 (0x37)
.maxstack 1
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: switch (
IL_0021,
IL_0016,
IL_0016)
IL_0014: br.s IL_002c
IL_0016: ldstr "Fail"
IL_001b: call "Sub System.Console.WriteLine(String)"
IL_0020: ret
IL_0021: ldstr "Success"
IL_0026: call "Sub System.Console.WriteLine(String)"
IL_002b: ret
IL_002c: ldstr "Fail"
IL_0031: call "Sub System.Console.WriteLine(String)"
IL_0036: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ValueClause_03()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Select Case 0
Case 1, 2
Console.WriteLine("Fail")
Case 3, 4
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Success")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 61 (0x3d)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: sub
IL_0005: switch (
IL_001c,
IL_001c,
IL_0027,
IL_0027)
IL_001a: br.s IL_0032
IL_001c: ldstr "Fail"
IL_0021: call "Sub System.Console.WriteLine(String)"
IL_0026: ret
IL_0027: ldstr "Fail"
IL_002c: call "Sub System.Console.WriteLine(String)"
IL_0031: ret
IL_0032: ldstr "Success"
IL_0037: call "Sub System.Console.WriteLine(String)"
IL_003c: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_RelationalClause()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Select Case 0
Case Is < 1
Console.WriteLine("Success")
Case 0
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 42 (0x2a)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: bge.s IL_0011
IL_0006: ldstr "Success"
IL_000b: call "Sub System.Console.WriteLine(String)"
IL_0010: ret
IL_0011: ldloc.0
IL_0012: brtrue.s IL_001f
IL_0014: ldstr "Fail"
IL_0019: call "Sub System.Console.WriteLine(String)"
IL_001e: ret
IL_001f: ldstr "Fail"
IL_0024: call "Sub System.Console.WriteLine(String)"
IL_0029: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_RelationalAndRangeClause_01()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Select Case 0
Case Is < 0
Console.WriteLine("Fail")
Case -1 To 1
Console.WriteLine("Success")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: bge.s IL_0011
IL_0006: ldstr "Fail"
IL_000b: call "Sub System.Console.WriteLine(String)"
IL_0010: ret
IL_0011: ldloc.0
IL_0012: ldc.i4.m1
IL_0013: blt.s IL_0024
IL_0015: ldloc.0
IL_0016: ldc.i4.1
IL_0017: bgt.s IL_0024
IL_0019: ldstr "Success"
IL_001e: call "Sub System.Console.WriteLine(String)"
IL_0023: ret
IL_0024: ldstr "Fail"
IL_0029: call "Sub System.Console.WriteLine(String)"
IL_002e: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_RelationalAndRangeClause_02()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Select Case 0
Case Is < 0
Console.WriteLine("Fail")
Case -2 To -1
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Success")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 48 (0x30)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: bge.s IL_0011
IL_0006: ldstr "Fail"
IL_000b: call "Sub System.Console.WriteLine(String)"
IL_0010: ret
IL_0011: ldloc.0
IL_0012: ldc.i4.s -2
IL_0014: blt.s IL_0025
IL_0016: ldloc.0
IL_0017: ldc.i4.m1
IL_0018: bgt.s IL_0025
IL_001a: ldstr "Fail"
IL_001f: call "Sub System.Console.WriteLine(String)"
IL_0024: ret
IL_0025: ldstr "Success"
IL_002a: call "Sub System.Console.WriteLine(String)"
IL_002f: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_NoTrueClause()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Select Case 0
Case Is < 0
Console.WriteLine("Fail")
Return
Case -2 To -1
Console.WriteLine("Fail")
Return
End Select
Console.WriteLine("Success")
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 48 (0x30)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: bge.s IL_0011
IL_0006: ldstr "Fail"
IL_000b: call "Sub System.Console.WriteLine(String)"
IL_0010: ret
IL_0011: ldloc.0
IL_0012: ldc.i4.s -2
IL_0014: blt.s IL_0025
IL_0016: ldloc.0
IL_0017: ldc.i4.m1
IL_0018: bgt.s IL_0025
IL_001a: ldstr "Fail"
IL_001f: call "Sub System.Console.WriteLine(String)"
IL_0024: ret
IL_0025: ldstr "Success"
IL_002a: call "Sub System.Console.WriteLine(String)"
IL_002f: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation_01()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Return 0
End Function
Sub Main()
Select Case 0
Case Foo()
Console.WriteLine("Success")
Case 0
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function M1.Foo() As Integer"
IL_0008: bne.un.s IL_0015
IL_000a: ldstr "Success"
IL_000f: call "Sub System.Console.WriteLine(String)"
IL_0014: ret
IL_0015: ldloc.0
IL_0016: brtrue.s IL_0023
IL_0018: ldstr "Fail"
IL_001d: call "Sub System.Console.WriteLine(String)"
IL_0022: ret
IL_0023: ldstr "Fail"
IL_0028: call "Sub System.Console.WriteLine(String)"
IL_002d: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation__02()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Return 0
End Function
Sub Main()
Select Case 0
Case Foo(), 0
Console.WriteLine("Success")
Case 1 - 1
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 49 (0x31)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function M1.Foo() As Integer"
IL_0008: beq.s IL_000d
IL_000a: ldloc.0
IL_000b: brtrue.s IL_0018
IL_000d: ldstr "Success"
IL_0012: call "Sub System.Console.WriteLine(String)"
IL_0017: ret
IL_0018: ldloc.0
IL_0019: brtrue.s IL_0026
IL_001b: ldstr "Fail"
IL_0020: call "Sub System.Console.WriteLine(String)"
IL_0025: ret
IL_0026: ldstr "Fail"
IL_002b: call "Sub System.Console.WriteLine(String)"
IL_0030: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation__03()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Return 0
End Function
Sub Main()
Select Case 0
Case Foo() + 1, 2
Console.WriteLine("Fail")
Case 3, 4
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Success")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 57 (0x39)
.maxstack 3
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function M1.Foo() As Integer"
IL_0008: ldc.i4.1
IL_0009: add.ovf
IL_000a: beq.s IL_0010
IL_000c: ldloc.0
IL_000d: ldc.i4.2
IL_000e: bne.un.s IL_001b
IL_0010: ldstr "Fail"
IL_0015: call "Sub System.Console.WriteLine(String)"
IL_001a: ret
IL_001b: ldloc.0
IL_001c: ldc.i4.3
IL_001d: beq.s IL_0023
IL_001f: ldloc.0
IL_0020: ldc.i4.4
IL_0021: bne.un.s IL_002e
IL_0023: ldstr "Fail"
IL_0028: call "Sub System.Console.WriteLine(String)"
IL_002d: ret
IL_002e: ldstr "Success"
IL_0033: call "Sub System.Console.WriteLine(String)"
IL_0038: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation_04()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Return 0
End Function
Sub Main()
Select Case 0
Case Is < Foo() + 1
Console.WriteLine("Success")
Case 0
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 48 (0x30)
.maxstack 3
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function M1.Foo() As Integer"
IL_0008: ldc.i4.1
IL_0009: add.ovf
IL_000a: bge.s IL_0017
IL_000c: ldstr "Success"
IL_0011: call "Sub System.Console.WriteLine(String)"
IL_0016: ret
IL_0017: ldloc.0
IL_0018: brtrue.s IL_0025
IL_001a: ldstr "Fail"
IL_001f: call "Sub System.Console.WriteLine(String)"
IL_0024: ret
IL_0025: ldstr "Fail"
IL_002a: call "Sub System.Console.WriteLine(String)"
IL_002f: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation_05()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.Write("Foo,")
Return 0
End Function
Sub Main()
Select Case 0
Case Foo() - 1 To Foo() + 1
Console.WriteLine("Success")
Case 0
Console.Write("Fail")
Case Else
Console.Write("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Foo,Foo,Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 58 (0x3a)
.maxstack 3
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function M1.Foo() As Integer"
IL_0008: ldc.i4.1
IL_0009: sub.ovf
IL_000a: blt.s IL_0021
IL_000c: ldloc.0
IL_000d: call "Function M1.Foo() As Integer"
IL_0012: ldc.i4.1
IL_0013: add.ovf
IL_0014: bgt.s IL_0021
IL_0016: ldstr "Success"
IL_001b: call "Sub System.Console.WriteLine(String)"
IL_0020: ret
IL_0021: ldloc.0
IL_0022: brtrue.s IL_002f
IL_0024: ldstr "Fail"
IL_0029: call "Sub System.Console.Write(String)"
IL_002e: ret
IL_002f: ldstr "Fail"
IL_0034: call "Sub System.Console.Write(String)"
IL_0039: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation_06_ShortCircuit()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.Write("Foo,")
Return 0
End Function
Sub Main()
Select Case 0
Case Foo() + 1 To Foo() + 2
Console.WriteLine("Fail")
Case 0
Console.WriteLine("Success")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Foo,Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 58 (0x3a)
.maxstack 3
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function M1.Foo() As Integer"
IL_0008: ldc.i4.1
IL_0009: add.ovf
IL_000a: blt.s IL_0021
IL_000c: ldloc.0
IL_000d: call "Function M1.Foo() As Integer"
IL_0012: ldc.i4.2
IL_0013: add.ovf
IL_0014: bgt.s IL_0021
IL_0016: ldstr "Fail"
IL_001b: call "Sub System.Console.WriteLine(String)"
IL_0020: ret
IL_0021: ldloc.0
IL_0022: brtrue.s IL_002f
IL_0024: ldstr "Success"
IL_0029: call "Sub System.Console.WriteLine(String)"
IL_002e: ret
IL_002f: ldstr "Fail"
IL_0034: call "Sub System.Console.WriteLine(String)"
IL_0039: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation_07_ShortCircuit()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.Write("Foo,")
Return 0
End Function
Sub Main()
Select Case 0
Case Foo() - 1 To 1
Console.Write("Success,")
Case 0
Console.Write("Fail,")
Case Else
Console.Write("Fail")
End Select
Select Case 0
Case 1 To Foo()
Console.Write("Fail,")
Case Else
Console.Write("Success,")
End Select
Select Case 0
Case Foo() - 1 To -2
Console.WriteLine("Fail")
Case 0
Console.WriteLine("Success")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Foo,Success,Success,Foo,Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 142 (0x8e)
.maxstack 3
.locals init (Integer V_0,
Integer V_1,
Integer V_2)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function M1.Foo() As Integer"
IL_0008: ldc.i4.1
IL_0009: sub.ovf
IL_000a: blt.s IL_001c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: bgt.s IL_001c
IL_0010: ldstr "Success,"
IL_0015: call "Sub System.Console.Write(String)"
IL_001a: br.s IL_0035
IL_001c: ldloc.0
IL_001d: brtrue.s IL_002b
IL_001f: ldstr "Fail,"
IL_0024: call "Sub System.Console.Write(String)"
IL_0029: br.s IL_0035
IL_002b: ldstr "Fail"
IL_0030: call "Sub System.Console.Write(String)"
IL_0035: ldc.i4.0
IL_0036: stloc.1
IL_0037: ldloc.1
IL_0038: ldc.i4.1
IL_0039: blt.s IL_004f
IL_003b: ldloc.1
IL_003c: call "Function M1.Foo() As Integer"
IL_0041: bgt.s IL_004f
IL_0043: ldstr "Fail,"
IL_0048: call "Sub System.Console.Write(String)"
IL_004d: br.s IL_0059
IL_004f: ldstr "Success,"
IL_0054: call "Sub System.Console.Write(String)"
IL_0059: ldc.i4.0
IL_005a: stloc.2
IL_005b: ldloc.2
IL_005c: call "Function M1.Foo() As Integer"
IL_0061: ldc.i4.1
IL_0062: sub.ovf
IL_0063: blt.s IL_0075
IL_0065: ldloc.2
IL_0066: ldc.i4.s -2
IL_0068: bgt.s IL_0075
IL_006a: ldstr "Fail"
IL_006f: call "Sub System.Console.WriteLine(String)"
IL_0074: ret
IL_0075: ldloc.2
IL_0076: brtrue.s IL_0083
IL_0078: ldstr "Success"
IL_007d: call "Sub System.Console.WriteLine(String)"
IL_0082: ret
IL_0083: ldstr "Fail"
IL_0088: call "Sub System.Console.WriteLine(String)"
IL_008d: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation_08()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Return 0
End Function
Sub Main()
Select Case 0
Case -1 To Foo() + 1
Console.WriteLine("Success")
Case 0
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 52 (0x34)
.maxstack 3
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.m1
IL_0004: blt.s IL_001b
IL_0006: ldloc.0
IL_0007: call "Function M1.Foo() As Integer"
IL_000c: ldc.i4.1
IL_000d: add.ovf
IL_000e: bgt.s IL_001b
IL_0010: ldstr "Success"
IL_0015: call "Sub System.Console.WriteLine(String)"
IL_001a: ret
IL_001b: ldloc.0
IL_001c: brtrue.s IL_0029
IL_001e: ldstr "Fail"
IL_0023: call "Sub System.Console.WriteLine(String)"
IL_0028: ret
IL_0029: ldstr "Fail"
IL_002e: call "Sub System.Console.WriteLine(String)"
IL_0033: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_ClauseExprEvaluation_09()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.Write("Foo,")
Return 0
End Function
Sub Main()
Select Case 0
Case Is < 0
Console.WriteLine("Fail")
Case Foo() - 1 To Foo() + 1
Console.WriteLine("Success")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Foo,Foo,Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (Integer V_0)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: bge.s IL_0011
IL_0006: ldstr "Fail"
IL_000b: call "Sub System.Console.WriteLine(String)"
IL_0010: ret
IL_0011: ldloc.0
IL_0012: call "Function M1.Foo() As Integer"
IL_0017: ldc.i4.1
IL_0018: sub.ovf
IL_0019: blt.s IL_0030
IL_001b: ldloc.0
IL_001c: call "Function M1.Foo() As Integer"
IL_0021: ldc.i4.1
IL_0022: add.ovf
IL_0023: bgt.s IL_0030
IL_0025: ldstr "Success"
IL_002a: call "Sub System.Console.WriteLine(String)"
IL_002f: ret
IL_0030: ldstr "Fail"
IL_0035: call "Sub System.Console.WriteLine(String)"
IL_003a: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_SelectExprEvaluation_IfList()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.Write("Foo,")
Return 0
End Function
Sub Main()
Select Case Foo()
Case -2 To -1
Console.WriteLine("Fail")
Case 1
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Success")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Foo,Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 52 (0x34)
.maxstack 2
.locals init (Integer V_0)
IL_0000: call "Function M1.Foo() As Integer"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.s -2
IL_0009: blt.s IL_001a
IL_000b: ldloc.0
IL_000c: ldc.i4.m1
IL_000d: bgt.s IL_001a
IL_000f: ldstr "Fail"
IL_0014: call "Sub System.Console.WriteLine(String)"
IL_0019: ret
IL_001a: ldloc.0
IL_001b: ldc.i4.1
IL_001c: bne.un.s IL_0029
IL_001e: ldstr "Fail"
IL_0023: call "Sub System.Console.WriteLine(String)"
IL_0028: ret
IL_0029: ldstr "Success"
IL_002e: call "Sub System.Console.WriteLine(String)"
IL_0033: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_SelectExprEvaluation_SwitchTable()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.Write("Foo,")
Return 0
End Function
Sub Main()
Select Case Foo()
Case -1, 1, 3
Console.WriteLine("Fail")
Case -2, 0, 2
Console.WriteLine("Success")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Foo,Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 74 (0x4a)
.maxstack 2
.locals init (Integer V_0)
IL_0000: call "Function M1.Foo() As Integer"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.s -2
IL_0009: sub
IL_000a: switch (
IL_0034,
IL_0029,
IL_0034,
IL_0029,
IL_0034,
IL_0029)
IL_0027: br.s IL_003f
IL_0029: ldstr "Fail"
IL_002e: call "Sub System.Console.WriteLine(String)"
IL_0033: ret
IL_0034: ldstr "Success"
IL_0039: call "Sub System.Console.WriteLine(String)"
IL_003e: ret
IL_003f: ldstr "Fail"
IL_0044: call "Sub System.Console.WriteLine(String)"
IL_0049: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_SwitchTable_DuplicateCase()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.Write("Foo,")
Return 0
End Function
Sub Main()
Select Case Foo()
Case -1, 1, 3
Console.WriteLine("Fail")
Case 2.5 - 2.4
Console.WriteLine("Success")
Case -2, 0, 2
Console.WriteLine("Fail")
Case 0
Console.WriteLine("Fail")
Case 1 - 1
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Foo,Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 85 (0x55)
.maxstack 2
.locals init (Integer V_0)
IL_0000: call "Function M1.Foo() As Integer"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.s -2
IL_0009: sub
IL_000a: switch (
IL_003f,
IL_0029,
IL_0034,
IL_0029,
IL_003f,
IL_0029)
IL_0027: br.s IL_004a
IL_0029: ldstr "Fail"
IL_002e: call "Sub System.Console.WriteLine(String)"
IL_0033: ret
IL_0034: ldstr "Success"
IL_0039: call "Sub System.Console.WriteLine(String)"
IL_003e: ret
IL_003f: ldstr "Fail"
IL_0044: call "Sub System.Console.WriteLine(String)"
IL_0049: ret
IL_004a: ldstr "Fail"
IL_004f: call "Sub System.Console.WriteLine(String)"
IL_0054: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_IfList_Conversions()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Dim success As Boolean = True
For count = 0 To 13
Test(count, success)
Next
If success Then
Console.Write("Success")
Else
Console.Write("Fail")
End If
End Sub
Sub Test(count As Integer, ByRef success As Boolean)
Dim Bo As Boolean
Dim Ob As Object
Dim SB As SByte
Dim By As Byte
Dim Sh As Short
Dim US As UShort
Dim [In] As Integer
Dim UI As UInteger
Dim Lo As Long
Dim UL As ULong
Dim De As Decimal
Dim Si As Single
Dim [Do] As Double
Dim St As String
Bo = False
Ob = 1
SB = 2
By = 3
Sh = 4
US = 5
[In] = 6
UI = 7
Lo = 8
UL = 9
Si = 10
[Do] = 11
De = 12D
St = "13"
Select Case count
Case Bo
success = success AndAlso If(count = 0, True, False)
Case Ob
success = success AndAlso If(count = 1, True, False)
Case SB
success = success AndAlso If(count = 2, True, False)
Case By
success = success AndAlso If(count = 3, True, False)
Case Sh
success = success AndAlso If(count = 4, True, False)
Case US
success = success AndAlso If(count = 5, True, False)
Case [In]
success = success AndAlso If(count = 6, True, False)
Case UI
success = success AndAlso If(count = 7, True, False)
Case Lo
success = success AndAlso If(count = 8, True, False)
Case UL
success = success AndAlso If(count = 9, True, False)
Case Si
success = success AndAlso If(count = 10, True, False)
Case [Do]
success = success AndAlso If(count = 11, True, False)
Case De
success = success AndAlso If(count = 12, True, False)
Case St
success = success AndAlso If(count = 13, True, False)
Case Else
success = False
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Test", <![CDATA[
{
// Code size 453 (0x1c5)
.maxstack 3
.locals init (Boolean V_0, //Bo
Object V_1, //Ob
SByte V_2, //SB
Byte V_3, //By
Short V_4, //Sh
UShort V_5, //US
Integer V_6, //In
UInteger V_7, //UI
Long V_8, //Lo
ULong V_9, //UL
Decimal V_10, //De
Single V_11, //Si
Double V_12, //Do
String V_13, //St
Integer V_14)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldc.i4.1
IL_0003: box "Integer"
IL_0008: stloc.1
IL_0009: ldc.i4.2
IL_000a: stloc.2
IL_000b: ldc.i4.3
IL_000c: stloc.3
IL_000d: ldc.i4.4
IL_000e: stloc.s V_4
IL_0010: ldc.i4.5
IL_0011: stloc.s V_5
IL_0013: ldc.i4.6
IL_0014: stloc.s V_6
IL_0016: ldc.i4.7
IL_0017: stloc.s V_7
IL_0019: ldc.i4.8
IL_001a: conv.i8
IL_001b: stloc.s V_8
IL_001d: ldc.i4.s 9
IL_001f: conv.i8
IL_0020: stloc.s V_9
IL_0022: ldc.r4 10
IL_0027: stloc.s V_11
IL_0029: ldc.r8 11
IL_0032: stloc.s V_12
IL_0034: ldloca.s V_10
IL_0036: ldc.i4.s 12
IL_0038: conv.i8
IL_0039: call "Sub Decimal..ctor(Long)"
IL_003e: ldstr "13"
IL_0043: stloc.s V_13
IL_0045: ldarg.0
IL_0046: stloc.s V_14
IL_0048: ldloc.s V_14
IL_004a: ldloc.0
IL_004b: ldc.i4.0
IL_004c: cgt.un
IL_004e: neg
IL_004f: bne.un.s IL_0062
IL_0051: ldarg.1
IL_0052: dup
IL_0053: ldind.u1
IL_0054: brfalse.s IL_005f
IL_0056: ldarg.0
IL_0057: brfalse.s IL_005c
IL_0059: ldc.i4.0
IL_005a: br.s IL_0060
IL_005c: ldc.i4.1
IL_005d: br.s IL_0060
IL_005f: ldc.i4.0
IL_0060: stind.i1
IL_0061: ret
IL_0062: ldloc.s V_14
IL_0064: box "Integer"
IL_0069: ldloc.1
IL_006a: ldc.i4.0
IL_006b: call "Function Microsoft.VisualBasic.CompilerServices.Operators.ConditionalCompareObjectEqual(Object, Object, Boolean) As Boolean"
IL_0070: brfalse.s IL_0084
IL_0072: ldarg.1
IL_0073: dup
IL_0074: ldind.u1
IL_0075: brfalse.s IL_0081
IL_0077: ldarg.0
IL_0078: ldc.i4.1
IL_0079: beq.s IL_007e
IL_007b: ldc.i4.0
IL_007c: br.s IL_0082
IL_007e: ldc.i4.1
IL_007f: br.s IL_0082
IL_0081: ldc.i4.0
IL_0082: stind.i1
IL_0083: ret
IL_0084: ldloc.s V_14
IL_0086: ldloc.2
IL_0087: bne.un.s IL_009b
IL_0089: ldarg.1
IL_008a: dup
IL_008b: ldind.u1
IL_008c: brfalse.s IL_0098
IL_008e: ldarg.0
IL_008f: ldc.i4.2
IL_0090: beq.s IL_0095
IL_0092: ldc.i4.0
IL_0093: br.s IL_0099
IL_0095: ldc.i4.1
IL_0096: br.s IL_0099
IL_0098: ldc.i4.0
IL_0099: stind.i1
IL_009a: ret
IL_009b: ldloc.s V_14
IL_009d: ldloc.3
IL_009e: bne.un.s IL_00b2
IL_00a0: ldarg.1
IL_00a1: dup
IL_00a2: ldind.u1
IL_00a3: brfalse.s IL_00af
IL_00a5: ldarg.0
IL_00a6: ldc.i4.3
IL_00a7: beq.s IL_00ac
IL_00a9: ldc.i4.0
IL_00aa: br.s IL_00b0
IL_00ac: ldc.i4.1
IL_00ad: br.s IL_00b0
IL_00af: ldc.i4.0
IL_00b0: stind.i1
IL_00b1: ret
IL_00b2: ldloc.s V_14
IL_00b4: ldloc.s V_4
IL_00b6: bne.un.s IL_00ca
IL_00b8: ldarg.1
IL_00b9: dup
IL_00ba: ldind.u1
IL_00bb: brfalse.s IL_00c7
IL_00bd: ldarg.0
IL_00be: ldc.i4.4
IL_00bf: beq.s IL_00c4
IL_00c1: ldc.i4.0
IL_00c2: br.s IL_00c8
IL_00c4: ldc.i4.1
IL_00c5: br.s IL_00c8
IL_00c7: ldc.i4.0
IL_00c8: stind.i1
IL_00c9: ret
IL_00ca: ldloc.s V_14
IL_00cc: ldloc.s V_5
IL_00ce: bne.un.s IL_00e2
IL_00d0: ldarg.1
IL_00d1: dup
IL_00d2: ldind.u1
IL_00d3: brfalse.s IL_00df
IL_00d5: ldarg.0
IL_00d6: ldc.i4.5
IL_00d7: beq.s IL_00dc
IL_00d9: ldc.i4.0
IL_00da: br.s IL_00e0
IL_00dc: ldc.i4.1
IL_00dd: br.s IL_00e0
IL_00df: ldc.i4.0
IL_00e0: stind.i1
IL_00e1: ret
IL_00e2: ldloc.s V_14
IL_00e4: ldloc.s V_6
IL_00e6: bne.un.s IL_00fa
IL_00e8: ldarg.1
IL_00e9: dup
IL_00ea: ldind.u1
IL_00eb: brfalse.s IL_00f7
IL_00ed: ldarg.0
IL_00ee: ldc.i4.6
IL_00ef: beq.s IL_00f4
IL_00f1: ldc.i4.0
IL_00f2: br.s IL_00f8
IL_00f4: ldc.i4.1
IL_00f5: br.s IL_00f8
IL_00f7: ldc.i4.0
IL_00f8: stind.i1
IL_00f9: ret
IL_00fa: ldloc.s V_14
IL_00fc: ldloc.s V_7
IL_00fe: conv.ovf.i4.un
IL_00ff: bne.un.s IL_0113
IL_0101: ldarg.1
IL_0102: dup
IL_0103: ldind.u1
IL_0104: brfalse.s IL_0110
IL_0106: ldarg.0
IL_0107: ldc.i4.7
IL_0108: beq.s IL_010d
IL_010a: ldc.i4.0
IL_010b: br.s IL_0111
IL_010d: ldc.i4.1
IL_010e: br.s IL_0111
IL_0110: ldc.i4.0
IL_0111: stind.i1
IL_0112: ret
IL_0113: ldloc.s V_14
IL_0115: ldloc.s V_8
IL_0117: conv.ovf.i4
IL_0118: bne.un.s IL_012c
IL_011a: ldarg.1
IL_011b: dup
IL_011c: ldind.u1
IL_011d: brfalse.s IL_0129
IL_011f: ldarg.0
IL_0120: ldc.i4.8
IL_0121: beq.s IL_0126
IL_0123: ldc.i4.0
IL_0124: br.s IL_012a
IL_0126: ldc.i4.1
IL_0127: br.s IL_012a
IL_0129: ldc.i4.0
IL_012a: stind.i1
IL_012b: ret
IL_012c: ldloc.s V_14
IL_012e: ldloc.s V_9
IL_0130: conv.ovf.i4.un
IL_0131: bne.un.s IL_0146
IL_0133: ldarg.1
IL_0134: dup
IL_0135: ldind.u1
IL_0136: brfalse.s IL_0143
IL_0138: ldarg.0
IL_0139: ldc.i4.s 9
IL_013b: beq.s IL_0140
IL_013d: ldc.i4.0
IL_013e: br.s IL_0144
IL_0140: ldc.i4.1
IL_0141: br.s IL_0144
IL_0143: ldc.i4.0
IL_0144: stind.i1
IL_0145: ret
IL_0146: ldloc.s V_14
IL_0148: ldloc.s V_11
IL_014a: conv.r8
IL_014b: call "Function System.Math.Round(Double) As Double"
IL_0150: conv.ovf.i4
IL_0151: bne.un.s IL_0166
IL_0153: ldarg.1
IL_0154: dup
IL_0155: ldind.u1
IL_0156: brfalse.s IL_0163
IL_0158: ldarg.0
IL_0159: ldc.i4.s 10
IL_015b: beq.s IL_0160
IL_015d: ldc.i4.0
IL_015e: br.s IL_0164
IL_0160: ldc.i4.1
IL_0161: br.s IL_0164
IL_0163: ldc.i4.0
IL_0164: stind.i1
IL_0165: ret
IL_0166: ldloc.s V_14
IL_0168: ldloc.s V_12
IL_016a: call "Function System.Math.Round(Double) As Double"
IL_016f: conv.ovf.i4
IL_0170: bne.un.s IL_0185
IL_0172: ldarg.1
IL_0173: dup
IL_0174: ldind.u1
IL_0175: brfalse.s IL_0182
IL_0177: ldarg.0
IL_0178: ldc.i4.s 11
IL_017a: beq.s IL_017f
IL_017c: ldc.i4.0
IL_017d: br.s IL_0183
IL_017f: ldc.i4.1
IL_0180: br.s IL_0183
IL_0182: ldc.i4.0
IL_0183: stind.i1
IL_0184: ret
IL_0185: ldloc.s V_14
IL_0187: ldloc.s V_10
IL_0189: call "Function System.Convert.ToInt32(Decimal) As Integer"
IL_018e: bne.un.s IL_01a3
IL_0190: ldarg.1
IL_0191: dup
IL_0192: ldind.u1
IL_0193: brfalse.s IL_01a0
IL_0195: ldarg.0
IL_0196: ldc.i4.s 12
IL_0198: beq.s IL_019d
IL_019a: ldc.i4.0
IL_019b: br.s IL_01a1
IL_019d: ldc.i4.1
IL_019e: br.s IL_01a1
IL_01a0: ldc.i4.0
IL_01a1: stind.i1
IL_01a2: ret
IL_01a3: ldloc.s V_14
IL_01a5: ldloc.s V_13
IL_01a7: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String) As Integer"
IL_01ac: bne.un.s IL_01c1
IL_01ae: ldarg.1
IL_01af: dup
IL_01b0: ldind.u1
IL_01b1: brfalse.s IL_01be
IL_01b3: ldarg.0
IL_01b4: ldc.i4.s 13
IL_01b6: beq.s IL_01bb
IL_01b8: ldc.i4.0
IL_01b9: br.s IL_01bf
IL_01bb: ldc.i4.1
IL_01bc: br.s IL_01bf
IL_01be: ldc.i4.0
IL_01bf: stind.i1
IL_01c0: ret
IL_01c1: ldarg.1
IL_01c2: ldc.i4.0
IL_01c3: stind.i1
IL_01c4: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
' TODO: Update test case once bug 10352 and bug 10354 are fixed.
' TODO: Verify switch table is used in codegen for select case statement.
<WorkItem(542910, "DevDiv")>
<WorkItem(10354)>
<Fact()>
Public Sub SelectCase_SwitchTable_Conversions_01()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Dim success As Boolean = True
For count = 0 To 12
Test(count, success)
Next
If success Then
Console.Write("Success")
Else
Console.Write("Fail")
End If
End Sub
Sub Test(count As Integer, ByRef success As Boolean)
Const Bo As Boolean = False
'Const Ob As Object = 1
Const SB As SByte = 2
Const By As Byte = 3
Const Sh As Short = 4
Const US As UShort = 5
Const [In] As Integer = 6
Const UI As UInteger = 7
Const Lo As Long = 8
Const UL As ULong = 9
Const Si As Single = 10
Const [Do] As Double = 11
Const De As Decimal = 12D
Select Case count
Case Bo
success = success AndAlso If(count = 0, True, False)
' Case Ob
Case 1
success = success AndAlso If(count = 1, True, False)
Case SB
success = success AndAlso If(count = 2, True, False)
Case By
success = success AndAlso If(count = 3, True, False)
Case Sh
success = success AndAlso If(count = 4, True, False)
Case US
success = success AndAlso If(count = 5, True, False)
Case [In]
success = success AndAlso If(count = 6, True, False)
Case UI
success = success AndAlso If(count = 7, True, False)
Case Lo
success = success AndAlso If(count = 8, True, False)
Case UL
success = success AndAlso If(count = 9, True, False)
Case Si
success = success AndAlso If(count = 10, True, False)
Case [Do]
success = success AndAlso If(count = 11, True, False)
Case De
success = success AndAlso If(count = 12, True, False)
Case Else
success = False
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Success").VerifyIL("M1.Test", <![CDATA[
{
// Code size 306 (0x132)
.maxstack 3
.locals init (Integer V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: switch (
IL_0041,
IL_0052,
IL_0064,
IL_0076,
IL_0088,
IL_009a,
IL_00ac,
IL_00be,
IL_00d0,
IL_00e2,
IL_00f5,
IL_0108,
IL_011b)
IL_003c: br IL_012e
IL_0041: ldarg.1
IL_0042: dup
IL_0043: ldind.u1
IL_0044: brfalse.s IL_004f
IL_0046: ldarg.0
IL_0047: brfalse.s IL_004c
IL_0049: ldc.i4.0
IL_004a: br.s IL_0050
IL_004c: ldc.i4.1
IL_004d: br.s IL_0050
IL_004f: ldc.i4.0
IL_0050: stind.i1
IL_0051: ret
IL_0052: ldarg.1
IL_0053: dup
IL_0054: ldind.u1
IL_0055: brfalse.s IL_0061
IL_0057: ldarg.0
IL_0058: ldc.i4.1
IL_0059: beq.s IL_005e
IL_005b: ldc.i4.0
IL_005c: br.s IL_0062
IL_005e: ldc.i4.1
IL_005f: br.s IL_0062
IL_0061: ldc.i4.0
IL_0062: stind.i1
IL_0063: ret
IL_0064: ldarg.1
IL_0065: dup
IL_0066: ldind.u1
IL_0067: brfalse.s IL_0073
IL_0069: ldarg.0
IL_006a: ldc.i4.2
IL_006b: beq.s IL_0070
IL_006d: ldc.i4.0
IL_006e: br.s IL_0074
IL_0070: ldc.i4.1
IL_0071: br.s IL_0074
IL_0073: ldc.i4.0
IL_0074: stind.i1
IL_0075: ret
IL_0076: ldarg.1
IL_0077: dup
IL_0078: ldind.u1
IL_0079: brfalse.s IL_0085
IL_007b: ldarg.0
IL_007c: ldc.i4.3
IL_007d: beq.s IL_0082
IL_007f: ldc.i4.0
IL_0080: br.s IL_0086
IL_0082: ldc.i4.1
IL_0083: br.s IL_0086
IL_0085: ldc.i4.0
IL_0086: stind.i1
IL_0087: ret
IL_0088: ldarg.1
IL_0089: dup
IL_008a: ldind.u1
IL_008b: brfalse.s IL_0097
IL_008d: ldarg.0
IL_008e: ldc.i4.4
IL_008f: beq.s IL_0094
IL_0091: ldc.i4.0
IL_0092: br.s IL_0098
IL_0094: ldc.i4.1
IL_0095: br.s IL_0098
IL_0097: ldc.i4.0
IL_0098: stind.i1
IL_0099: ret
IL_009a: ldarg.1
IL_009b: dup
IL_009c: ldind.u1
IL_009d: brfalse.s IL_00a9
IL_009f: ldarg.0
IL_00a0: ldc.i4.5
IL_00a1: beq.s IL_00a6
IL_00a3: ldc.i4.0
IL_00a4: br.s IL_00aa
IL_00a6: ldc.i4.1
IL_00a7: br.s IL_00aa
IL_00a9: ldc.i4.0
IL_00aa: stind.i1
IL_00ab: ret
IL_00ac: ldarg.1
IL_00ad: dup
IL_00ae: ldind.u1
IL_00af: brfalse.s IL_00bb
IL_00b1: ldarg.0
IL_00b2: ldc.i4.6
IL_00b3: beq.s IL_00b8
IL_00b5: ldc.i4.0
IL_00b6: br.s IL_00bc
IL_00b8: ldc.i4.1
IL_00b9: br.s IL_00bc
IL_00bb: ldc.i4.0
IL_00bc: stind.i1
IL_00bd: ret
IL_00be: ldarg.1
IL_00bf: dup
IL_00c0: ldind.u1
IL_00c1: brfalse.s IL_00cd
IL_00c3: ldarg.0
IL_00c4: ldc.i4.7
IL_00c5: beq.s IL_00ca
IL_00c7: ldc.i4.0
IL_00c8: br.s IL_00ce
IL_00ca: ldc.i4.1
IL_00cb: br.s IL_00ce
IL_00cd: ldc.i4.0
IL_00ce: stind.i1
IL_00cf: ret
IL_00d0: ldarg.1
IL_00d1: dup
IL_00d2: ldind.u1
IL_00d3: brfalse.s IL_00df
IL_00d5: ldarg.0
IL_00d6: ldc.i4.8
IL_00d7: beq.s IL_00dc
IL_00d9: ldc.i4.0
IL_00da: br.s IL_00e0
IL_00dc: ldc.i4.1
IL_00dd: br.s IL_00e0
IL_00df: ldc.i4.0
IL_00e0: stind.i1
IL_00e1: ret
IL_00e2: ldarg.1
IL_00e3: dup
IL_00e4: ldind.u1
IL_00e5: brfalse.s IL_00f2
IL_00e7: ldarg.0
IL_00e8: ldc.i4.s 9
IL_00ea: beq.s IL_00ef
IL_00ec: ldc.i4.0
IL_00ed: br.s IL_00f3
IL_00ef: ldc.i4.1
IL_00f0: br.s IL_00f3
IL_00f2: ldc.i4.0
IL_00f3: stind.i1
IL_00f4: ret
IL_00f5: ldarg.1
IL_00f6: dup
IL_00f7: ldind.u1
IL_00f8: brfalse.s IL_0105
IL_00fa: ldarg.0
IL_00fb: ldc.i4.s 10
IL_00fd: beq.s IL_0102
IL_00ff: ldc.i4.0
IL_0100: br.s IL_0106
IL_0102: ldc.i4.1
IL_0103: br.s IL_0106
IL_0105: ldc.i4.0
IL_0106: stind.i1
IL_0107: ret
IL_0108: ldarg.1
IL_0109: dup
IL_010a: ldind.u1
IL_010b: brfalse.s IL_0118
IL_010d: ldarg.0
IL_010e: ldc.i4.s 11
IL_0110: beq.s IL_0115
IL_0112: ldc.i4.0
IL_0113: br.s IL_0119
IL_0115: ldc.i4.1
IL_0116: br.s IL_0119
IL_0118: ldc.i4.0
IL_0119: stind.i1
IL_011a: ret
IL_011b: ldarg.1
IL_011c: dup
IL_011d: ldind.u1
IL_011e: brfalse.s IL_012b
IL_0120: ldarg.0
IL_0121: ldc.i4.s 12
IL_0123: beq.s IL_0128
IL_0125: ldc.i4.0
IL_0126: br.s IL_012c
IL_0128: ldc.i4.1
IL_0129: br.s IL_012c
IL_012b: ldc.i4.0
IL_012c: stind.i1
IL_012d: ret
IL_012e: ldarg.1
IL_012f: ldc.i4.0
IL_0130: stind.i1
IL_0131: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_SwitchTable_Conversions_02()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function Foo() As Integer
Console.Write("Foo,")
Return 0
End Function
Sub Main()
Select Case Foo()
Case -1, 1, 3
Console.WriteLine("Fail")
Case 2.5 - 2.4
Console.WriteLine("Success")
Case -2, 0, 2
Console.WriteLine("Fail")
Case 0
Console.WriteLine("Fail")
Case 1 - 1
Console.WriteLine("Fail")
Case Else
Console.WriteLine("Fail")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="Foo,Success").VerifyIL("M1.Main", <![CDATA[
{
// Code size 85 (0x55)
.maxstack 2
.locals init (Integer V_0)
IL_0000: call "Function M1.Foo() As Integer"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.s -2
IL_0009: sub
IL_000a: switch (
IL_003f,
IL_0029,
IL_0034,
IL_0029,
IL_003f,
IL_0029)
IL_0027: br.s IL_004a
IL_0029: ldstr "Fail"
IL_002e: call "Sub System.Console.WriteLine(String)"
IL_0033: ret
IL_0034: ldstr "Success"
IL_0039: call "Sub System.Console.WriteLine(String)"
IL_003e: ret
IL_003f: ldstr "Fail"
IL_0044: call "Sub System.Console.WriteLine(String)"
IL_0049: ret
IL_004a: ldstr "Fail"
IL_004f: call "Sub System.Console.WriteLine(String)"
IL_0054: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
#Region "Select case string tests"
<Fact, WorkItem(651996, "DevDiv")>
Public Sub SelectCase_Hash_SwitchTable_String_OptionCompareBinary()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x.ToString())
Next
End Sub
Sub Test(number as String)
Select Case number
Case "0"
Console.WriteLine("Equal to 0")
Case "1", "2", "3", "4", "5"
Console.WriteLine("Between 1 and 5, inclusive")
Case "6", "7", "8"
Console.WriteLine("Between 6 and 8, inclusive")
Case "9", "10"
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(False),
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 420 (0x1a4)
.maxstack 3
.locals init (String V_0,
UInteger V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function $$method0x6000001-ComputeStringHash(String) As UInteger"
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldc.i4 0x330ca589
IL_000f: bgt.un.s IL_005a
IL_0011: ldloc.1
IL_0012: ldc.i4 0x300ca0d0
IL_0017: bgt.un.s IL_0034
IL_0019: ldloc.1
IL_001a: ldc.i4 0x1beb2a44
IL_001f: beq IL_015d
IL_0024: ldloc.1
IL_0025: ldc.i4 0x300ca0d0
IL_002a: beq IL_010d
IL_002f: br IL_0199
IL_0034: ldloc.1
IL_0035: ldc.i4 0x310ca263
IL_003a: beq IL_00fa
IL_003f: ldloc.1
IL_0040: ldc.i4 0x320ca3f6
IL_0045: beq IL_012d
IL_004a: ldloc.1
IL_004b: ldc.i4 0x330ca589
IL_0050: beq IL_011d
IL_0055: br IL_0199
IL_005a: ldloc.1
IL_005b: ldc.i4 0x360caa42
IL_0060: bgt.un.s IL_007f
IL_0062: ldloc.1
IL_0063: ldc.i4 0x340ca71c
IL_0068: beq.s IL_00b8
IL_006a: ldloc.1
IL_006b: ldc.i4 0x350ca8af
IL_0070: beq.s IL_00a2
IL_0072: ldloc.1
IL_0073: ldc.i4 0x360caa42
IL_0078: beq.s IL_00e4
IL_007a: br IL_0199
IL_007f: ldloc.1
IL_0080: ldc.i4 0x370cabd5
IL_0085: beq.s IL_00ce
IL_0087: ldloc.1
IL_0088: ldc.i4 0x3c0cb3b4
IL_008d: beq IL_014d
IL_0092: ldloc.1
IL_0093: ldc.i4 0x3d0cb547
IL_0098: beq IL_013d
IL_009d: br IL_0199
IL_00a2: ldloc.0
IL_00a3: ldstr "0"
IL_00a8: ldc.i4.0
IL_00a9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00ae: brfalse IL_016d
IL_00b3: br IL_0199
IL_00b8: ldloc.0
IL_00b9: ldstr "1"
IL_00be: ldc.i4.0
IL_00bf: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00c4: brfalse IL_0178
IL_00c9: br IL_0199
IL_00ce: ldloc.0
IL_00cf: ldstr "2"
IL_00d4: ldc.i4.0
IL_00d5: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00da: brfalse IL_0178
IL_00df: br IL_0199
IL_00e4: ldloc.0
IL_00e5: ldstr "3"
IL_00ea: ldc.i4.0
IL_00eb: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00f0: brfalse IL_0178
IL_00f5: br IL_0199
IL_00fa: ldloc.0
IL_00fb: ldstr "4"
IL_0100: ldc.i4.0
IL_0101: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0106: brfalse.s IL_0178
IL_0108: br IL_0199
IL_010d: ldloc.0
IL_010e: ldstr "5"
IL_0113: ldc.i4.0
IL_0114: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0119: brfalse.s IL_0178
IL_011b: br.s IL_0199
IL_011d: ldloc.0
IL_011e: ldstr "6"
IL_0123: ldc.i4.0
IL_0124: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0129: brfalse.s IL_0183
IL_012b: br.s IL_0199
IL_012d: ldloc.0
IL_012e: ldstr "7"
IL_0133: ldc.i4.0
IL_0134: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0139: brfalse.s IL_0183
IL_013b: br.s IL_0199
IL_013d: ldloc.0
IL_013e: ldstr "8"
IL_0143: ldc.i4.0
IL_0144: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0149: brfalse.s IL_0183
IL_014b: br.s IL_0199
IL_014d: ldloc.0
IL_014e: ldstr "9"
IL_0153: ldc.i4.0
IL_0154: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0159: brfalse.s IL_018e
IL_015b: br.s IL_0199
IL_015d: ldloc.0
IL_015e: ldstr "10"
IL_0163: ldc.i4.0
IL_0164: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0169: brfalse.s IL_018e
IL_016b: br.s IL_0199
IL_016d: ldstr "Equal to 0"
IL_0172: call "Sub System.Console.WriteLine(String)"
IL_0177: ret
IL_0178: ldstr "Between 1 and 5, inclusive"
IL_017d: call "Sub System.Console.WriteLine(String)"
IL_0182: ret
IL_0183: ldstr "Between 6 and 8, inclusive"
IL_0188: call "Sub System.Console.WriteLine(String)"
IL_018d: ret
IL_018e: ldstr "Equal to 9 or 10"
IL_0193: call "Sub System.Console.WriteLine(String)"
IL_0198: ret
IL_0199: ldstr "Greater than 10"
IL_019e: call "Sub System.Console.WriteLine(String)"
IL_01a3: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=True)
' verify that hash method is Friend
Dim reference = compVerifier.Compilation.EmitToImageReference()
Dim comp = VisualBasicCompilation.Create("Name", references:={reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal))
Dim pid = DirectCast(comp.GlobalNamespace.GetMembers().Where(Function(s) s.Name.StartsWith("<PrivateImplementationDetails>")).Single(), NamedTypeSymbol)
Dim member = pid.GetMembers(PrivateImplementationDetails.SynthesizedStringHashFunctionName).Single()
Assert.Equal(Accessibility.Friend, member.DeclaredAccessibility)
End Sub
<Fact()>
Public Sub SelectCase_NonHash_SwitchTable_String_OptionCompareBinary()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 6
Console.Write(x.ToString() + ":")
Test(x.ToString())
Next
End Sub
Sub Test(number as String)
Select Case number
Case "0"
Console.WriteLine("Equal to 0")
Case "1", "2", "3", "4", "5"
Console.WriteLine("Between 1 and 5, inclusive")
Case Else
Console.WriteLine("Greater than 5")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(False),
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Greater than 5]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 121 (0x79)
.maxstack 3
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldstr "0"
IL_0008: ldc.i4.0
IL_0009: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_000e: brfalse.s IL_0058
IL_0010: ldloc.0
IL_0011: ldstr "1"
IL_0016: ldc.i4.0
IL_0017: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_001c: brfalse.s IL_0063
IL_001e: ldloc.0
IL_001f: ldstr "2"
IL_0024: ldc.i4.0
IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_002a: brfalse.s IL_0063
IL_002c: ldloc.0
IL_002d: ldstr "3"
IL_0032: ldc.i4.0
IL_0033: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0038: brfalse.s IL_0063
IL_003a: ldloc.0
IL_003b: ldstr "4"
IL_0040: ldc.i4.0
IL_0041: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0046: brfalse.s IL_0063
IL_0048: ldloc.0
IL_0049: ldstr "5"
IL_004e: ldc.i4.0
IL_004f: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0054: brfalse.s IL_0063
IL_0056: br.s IL_006e
IL_0058: ldstr "Equal to 0"
IL_005d: call "Sub System.Console.WriteLine(String)"
IL_0062: ret
IL_0063: ldstr "Between 1 and 5, inclusive"
IL_0068: call "Sub System.Console.WriteLine(String)"
IL_006d: ret
IL_006e: ldstr "Greater than 5"
IL_0073: call "Sub System.Console.WriteLine(String)"
IL_0078: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact()>
Public Sub SelectCase_IfList_String_OptionCompareText()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x.ToString())
Next
End Sub
Sub Test(number as String)
Select Case number
Case "0"
Console.WriteLine("Equal to 0")
Case "1", "2", "3", "4", "5"
Console.WriteLine("Between 1 and 5, inclusive")
Case "6", "7", "8"
Console.WriteLine("Between 6 and 8, inclusive")
Case "9", "10"
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(True),
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 211 (0xd3)
.maxstack 3
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldstr "0"
IL_0008: ldc.i4.1
IL_0009: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_000e: brtrue.s IL_001b
IL_0010: ldstr "Equal to 0"
IL_0015: call "Sub System.Console.WriteLine(String)"
IL_001a: ret
IL_001b: ldloc.0
IL_001c: ldstr "1"
IL_0021: ldc.i4.1
IL_0022: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0027: brfalse.s IL_0061
IL_0029: ldloc.0
IL_002a: ldstr "2"
IL_002f: ldc.i4.1
IL_0030: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0035: brfalse.s IL_0061
IL_0037: ldloc.0
IL_0038: ldstr "3"
IL_003d: ldc.i4.1
IL_003e: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0043: brfalse.s IL_0061
IL_0045: ldloc.0
IL_0046: ldstr "4"
IL_004b: ldc.i4.1
IL_004c: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0051: brfalse.s IL_0061
IL_0053: ldloc.0
IL_0054: ldstr "5"
IL_0059: ldc.i4.1
IL_005a: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_005f: brtrue.s IL_006c
IL_0061: ldstr "Between 1 and 5, inclusive"
IL_0066: call "Sub System.Console.WriteLine(String)"
IL_006b: ret
IL_006c: ldloc.0
IL_006d: ldstr "6"
IL_0072: ldc.i4.1
IL_0073: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0078: brfalse.s IL_0096
IL_007a: ldloc.0
IL_007b: ldstr "7"
IL_0080: ldc.i4.1
IL_0081: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0086: brfalse.s IL_0096
IL_0088: ldloc.0
IL_0089: ldstr "8"
IL_008e: ldc.i4.1
IL_008f: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0094: brtrue.s IL_00a1
IL_0096: ldstr "Between 6 and 8, inclusive"
IL_009b: call "Sub System.Console.WriteLine(String)"
IL_00a0: ret
IL_00a1: ldloc.0
IL_00a2: ldstr "9"
IL_00a7: ldc.i4.1
IL_00a8: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00ad: brfalse.s IL_00bd
IL_00af: ldloc.0
IL_00b0: ldstr "10"
IL_00b5: ldc.i4.1
IL_00b6: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00bb: brtrue.s IL_00c8
IL_00bd: ldstr "Equal to 9 or 10"
IL_00c2: call "Sub System.Console.WriteLine(String)"
IL_00c7: ret
IL_00c8: ldstr "Greater than 10"
IL_00cd: call "Sub System.Console.WriteLine(String)"
IL_00d2: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact()>
Public Sub SelectCase_Hash_SwitchTable_String_MDConstant()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Test("a")
Test("A")
End Sub
Sub Test(str as String)
Dim x As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}
Select Case str
Case "a"
Console.WriteLine("Equal to a")
Case "A"
Console.WriteLine("Equal to A")
Case "1", "2", "3", "4", "5", "6", "4", "5", "6"
Console.WriteLine("Error")
Case Else
Console.WriteLine("Error")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(False),
expectedOutput:=<![CDATA[Equal to a
Equal to A]]>)
End Sub
<Fact, WorkItem(651996, "DevDiv")>
Public Sub SelectCase_Hash_SwitchTable_String_OptionCompareBinary_02()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Test("a")
Test("A")
End Sub
Sub Test(str as String)
Select Case str
Case "a"
Console.WriteLine("Equal to a")
Case "A"
Console.WriteLine("Equal to A")
Case "1", "2", "3", "4", "5", "6", "4", "5", "6"
Console.WriteLine("Error")
Case Else
Console.WriteLine("Error")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(False),
expectedOutput:=<![CDATA[Equal to a
Equal to A]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 302 (0x12e)
.maxstack 3
.locals init (String V_0,
UInteger V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function $$method0x6000001-ComputeStringHash(String) As UInteger"
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldc.i4 0x340ca71c
IL_000f: bgt.un.s IL_004c
IL_0011: ldloc.1
IL_0012: ldc.i4 0x310ca263
IL_0017: bgt.un.s IL_0034
IL_0019: ldloc.1
IL_001a: ldc.i4 0x300ca0d0
IL_001f: beq IL_00e2
IL_0024: ldloc.1
IL_0025: ldc.i4 0x310ca263
IL_002a: beq IL_00d2
IL_002f: br IL_0123
IL_0034: ldloc.1
IL_0035: ldc.i4 0x330ca589
IL_003a: beq IL_00f2
IL_003f: ldloc.1
IL_0040: ldc.i4 0x340ca71c
IL_0045: beq.s IL_00a2
IL_0047: br IL_0123
IL_004c: ldloc.1
IL_004d: ldc.i4 0x370cabd5
IL_0052: bgt.un.s IL_0069
IL_0054: ldloc.1
IL_0055: ldc.i4 0x360caa42
IL_005a: beq.s IL_00c2
IL_005c: ldloc.1
IL_005d: ldc.i4 0x370cabd5
IL_0062: beq.s IL_00b2
IL_0064: br IL_0123
IL_0069: ldloc.1
IL_006a: ldc.i4 0xc40bf6cc
IL_006f: beq.s IL_008f
IL_0071: ldloc.1
IL_0072: ldc.i4 0xe40c292c
IL_0077: bne.un IL_0123
IL_007c: ldloc.0
IL_007d: ldstr "a"
IL_0082: ldc.i4.0
IL_0083: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0088: brfalse.s IL_0102
IL_008a: br IL_0123
IL_008f: ldloc.0
IL_0090: ldstr "A"
IL_0095: ldc.i4.0
IL_0096: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_009b: brfalse.s IL_010d
IL_009d: br IL_0123
IL_00a2: ldloc.0
IL_00a3: ldstr "1"
IL_00a8: ldc.i4.0
IL_00a9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00ae: brfalse.s IL_0118
IL_00b0: br.s IL_0123
IL_00b2: ldloc.0
IL_00b3: ldstr "2"
IL_00b8: ldc.i4.0
IL_00b9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00be: brfalse.s IL_0118
IL_00c0: br.s IL_0123
IL_00c2: ldloc.0
IL_00c3: ldstr "3"
IL_00c8: ldc.i4.0
IL_00c9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00ce: brfalse.s IL_0118
IL_00d0: br.s IL_0123
IL_00d2: ldloc.0
IL_00d3: ldstr "4"
IL_00d8: ldc.i4.0
IL_00d9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00de: brfalse.s IL_0118
IL_00e0: br.s IL_0123
IL_00e2: ldloc.0
IL_00e3: ldstr "5"
IL_00e8: ldc.i4.0
IL_00e9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00ee: brfalse.s IL_0118
IL_00f0: br.s IL_0123
IL_00f2: ldloc.0
IL_00f3: ldstr "6"
IL_00f8: ldc.i4.0
IL_00f9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00fe: brfalse.s IL_0118
IL_0100: br.s IL_0123
IL_0102: ldstr "Equal to a"
IL_0107: call "Sub System.Console.WriteLine(String)"
IL_010c: ret
IL_010d: ldstr "Equal to A"
IL_0112: call "Sub System.Console.WriteLine(String)"
IL_0117: ret
IL_0118: ldstr "Error"
IL_011d: call "Sub System.Console.WriteLine(String)"
IL_0122: ret
IL_0123: ldstr "Error"
IL_0128: call "Sub System.Console.WriteLine(String)"
IL_012d: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=True)
End Sub
<Fact()>
Public Sub SelectCase_NonHash_SwitchTable_String_OptionCompareBinary_02()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Test("a")
Test("A")
End Sub
Sub Test(str as String)
Select Case str
Case "a"
Console.WriteLine("Equal to a")
Case "A"
Console.WriteLine("Equal to A")
Case "1", "1", "1", "1", "1", "1", "1", "1"
Console.WriteLine("Error")
Case "1"
Console.WriteLine("Error")
Case "1"
Console.WriteLine("Error")
Case "1"
Console.WriteLine("Error")
Case "1"
Console.WriteLine("Error")
Case "1"
Console.WriteLine("Error")
Case "1"
Console.WriteLine("Error")
Case Else
Console.WriteLine("Error")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(False),
expectedOutput:=<![CDATA[Equal to a
Equal to A]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 90 (0x5a)
.maxstack 3
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldstr "a"
IL_0008: ldc.i4.0
IL_0009: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_000e: brfalse.s IL_002e
IL_0010: ldloc.0
IL_0011: ldstr "A"
IL_0016: ldc.i4.0
IL_0017: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_001c: brfalse.s IL_0039
IL_001e: ldloc.0
IL_001f: ldstr "1"
IL_0024: ldc.i4.0
IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_002a: brfalse.s IL_0044
IL_002c: br.s IL_004f
IL_002e: ldstr "Equal to a"
IL_0033: call "Sub System.Console.WriteLine(String)"
IL_0038: ret
IL_0039: ldstr "Equal to A"
IL_003e: call "Sub System.Console.WriteLine(String)"
IL_0043: ret
IL_0044: ldstr "Error"
IL_0049: call "Sub System.Console.WriteLine(String)"
IL_004e: ret
IL_004f: ldstr "Error"
IL_0054: call "Sub System.Console.WriteLine(String)"
IL_0059: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact()>
Public Sub SelectCase_IfList_String_OptionCompareText_02()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
Test("a")
Test("A")
End Sub
Sub Test(str as String)
Select Case str
Case "a"
Console.WriteLine("Equal to a")
Case "A"
Console.WriteLine("Error")
Case "1", "2", "3", "4", "5", "6", "4", "5", "6"
Console.WriteLine("Error")
Case Else
Console.WriteLine("Error")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(True),
expectedOutput:=<![CDATA[Equal to a
Equal to a]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 200 (0xc8)
.maxstack 3
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldstr "a"
IL_0008: ldc.i4.1
IL_0009: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_000e: brtrue.s IL_001b
IL_0010: ldstr "Equal to a"
IL_0015: call "Sub System.Console.WriteLine(String)"
IL_001a: ret
IL_001b: ldloc.0
IL_001c: ldstr "A"
IL_0021: ldc.i4.1
IL_0022: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0027: brtrue.s IL_0034
IL_0029: ldstr "Error"
IL_002e: call "Sub System.Console.WriteLine(String)"
IL_0033: ret
IL_0034: ldloc.0
IL_0035: ldstr "1"
IL_003a: ldc.i4.1
IL_003b: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0040: brfalse.s IL_00b2
IL_0042: ldloc.0
IL_0043: ldstr "2"
IL_0048: ldc.i4.1
IL_0049: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_004e: brfalse.s IL_00b2
IL_0050: ldloc.0
IL_0051: ldstr "3"
IL_0056: ldc.i4.1
IL_0057: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_005c: brfalse.s IL_00b2
IL_005e: ldloc.0
IL_005f: ldstr "4"
IL_0064: ldc.i4.1
IL_0065: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_006a: brfalse.s IL_00b2
IL_006c: ldloc.0
IL_006d: ldstr "5"
IL_0072: ldc.i4.1
IL_0073: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0078: brfalse.s IL_00b2
IL_007a: ldloc.0
IL_007b: ldstr "6"
IL_0080: ldc.i4.1
IL_0081: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0086: brfalse.s IL_00b2
IL_0088: ldloc.0
IL_0089: ldstr "4"
IL_008e: ldc.i4.1
IL_008f: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0094: brfalse.s IL_00b2
IL_0096: ldloc.0
IL_0097: ldstr "5"
IL_009c: ldc.i4.1
IL_009d: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00a2: brfalse.s IL_00b2
IL_00a4: ldloc.0
IL_00a5: ldstr "6"
IL_00aa: ldc.i4.1
IL_00ab: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00b0: brtrue.s IL_00bd
IL_00b2: ldstr "Error"
IL_00b7: call "Sub System.Console.WriteLine(String)"
IL_00bc: ret
IL_00bd: ldstr "Error"
IL_00c2: call "Sub System.Console.WriteLine(String)"
IL_00c7: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact, WorkItem(651996, "DevDiv")>
Public Sub SelectCase_SwitchTable_String_RelationalEqualityClause()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x.ToString())
Next
End Sub
Sub Test(number as String)
Select Case number
Case "0"
Console.WriteLine("Equal to 0")
Case "1", "2", = "3", "4", "5"
Console.WriteLine("Between 1 and 5, inclusive")
Case "6", "7", "8"
Console.WriteLine("Between 6 and 8, inclusive")
Case Is = "9", "10"
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(False),
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 420 (0x1a4)
.maxstack 3
.locals init (String V_0,
UInteger V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function $$method0x6000001-ComputeStringHash(String) As UInteger"
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldc.i4 0x330ca589
IL_000f: bgt.un.s IL_005a
IL_0011: ldloc.1
IL_0012: ldc.i4 0x300ca0d0
IL_0017: bgt.un.s IL_0034
IL_0019: ldloc.1
IL_001a: ldc.i4 0x1beb2a44
IL_001f: beq IL_015d
IL_0024: ldloc.1
IL_0025: ldc.i4 0x300ca0d0
IL_002a: beq IL_010d
IL_002f: br IL_0199
IL_0034: ldloc.1
IL_0035: ldc.i4 0x310ca263
IL_003a: beq IL_00fa
IL_003f: ldloc.1
IL_0040: ldc.i4 0x320ca3f6
IL_0045: beq IL_012d
IL_004a: ldloc.1
IL_004b: ldc.i4 0x330ca589
IL_0050: beq IL_011d
IL_0055: br IL_0199
IL_005a: ldloc.1
IL_005b: ldc.i4 0x360caa42
IL_0060: bgt.un.s IL_007f
IL_0062: ldloc.1
IL_0063: ldc.i4 0x340ca71c
IL_0068: beq.s IL_00b8
IL_006a: ldloc.1
IL_006b: ldc.i4 0x350ca8af
IL_0070: beq.s IL_00a2
IL_0072: ldloc.1
IL_0073: ldc.i4 0x360caa42
IL_0078: beq.s IL_00e4
IL_007a: br IL_0199
IL_007f: ldloc.1
IL_0080: ldc.i4 0x370cabd5
IL_0085: beq.s IL_00ce
IL_0087: ldloc.1
IL_0088: ldc.i4 0x3c0cb3b4
IL_008d: beq IL_014d
IL_0092: ldloc.1
IL_0093: ldc.i4 0x3d0cb547
IL_0098: beq IL_013d
IL_009d: br IL_0199
IL_00a2: ldloc.0
IL_00a3: ldstr "0"
IL_00a8: ldc.i4.0
IL_00a9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00ae: brfalse IL_016d
IL_00b3: br IL_0199
IL_00b8: ldloc.0
IL_00b9: ldstr "1"
IL_00be: ldc.i4.0
IL_00bf: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00c4: brfalse IL_0178
IL_00c9: br IL_0199
IL_00ce: ldloc.0
IL_00cf: ldstr "2"
IL_00d4: ldc.i4.0
IL_00d5: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00da: brfalse IL_0178
IL_00df: br IL_0199
IL_00e4: ldloc.0
IL_00e5: ldstr "3"
IL_00ea: ldc.i4.0
IL_00eb: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00f0: brfalse IL_0178
IL_00f5: br IL_0199
IL_00fa: ldloc.0
IL_00fb: ldstr "4"
IL_0100: ldc.i4.0
IL_0101: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0106: brfalse.s IL_0178
IL_0108: br IL_0199
IL_010d: ldloc.0
IL_010e: ldstr "5"
IL_0113: ldc.i4.0
IL_0114: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0119: brfalse.s IL_0178
IL_011b: br.s IL_0199
IL_011d: ldloc.0
IL_011e: ldstr "6"
IL_0123: ldc.i4.0
IL_0124: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0129: brfalse.s IL_0183
IL_012b: br.s IL_0199
IL_012d: ldloc.0
IL_012e: ldstr "7"
IL_0133: ldc.i4.0
IL_0134: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0139: brfalse.s IL_0183
IL_013b: br.s IL_0199
IL_013d: ldloc.0
IL_013e: ldstr "8"
IL_0143: ldc.i4.0
IL_0144: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0149: brfalse.s IL_0183
IL_014b: br.s IL_0199
IL_014d: ldloc.0
IL_014e: ldstr "9"
IL_0153: ldc.i4.0
IL_0154: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0159: brfalse.s IL_018e
IL_015b: br.s IL_0199
IL_015d: ldloc.0
IL_015e: ldstr "10"
IL_0163: ldc.i4.0
IL_0164: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0169: brfalse.s IL_018e
IL_016b: br.s IL_0199
IL_016d: ldstr "Equal to 0"
IL_0172: call "Sub System.Console.WriteLine(String)"
IL_0177: ret
IL_0178: ldstr "Between 1 and 5, inclusive"
IL_017d: call "Sub System.Console.WriteLine(String)"
IL_0182: ret
IL_0183: ldstr "Between 6 and 8, inclusive"
IL_0188: call "Sub System.Console.WriteLine(String)"
IL_018d: ret
IL_018e: ldstr "Equal to 9 or 10"
IL_0193: call "Sub System.Console.WriteLine(String)"
IL_0198: ret
IL_0199: ldstr "Greater than 10"
IL_019e: call "Sub System.Console.WriteLine(String)"
IL_01a3: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=True)
End Sub
<Fact()>
Public Sub SelectCase_IfList_String_RelationalRangeClauses()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x.ToString())
Next
End Sub
Sub Test(number as String)
Select Case number
Case "0"
Console.WriteLine("Equal to 0")
Case "1", "2", "3", "4", "5"
Console.WriteLine("Between 1 and 5, inclusive")
Case "6" To "8"
Console.WriteLine("Between 6 and 8, inclusive")
Case "9" To "8"
Console.WriteLine("Fail")
Case >= "9", <= "10"
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(True),
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 242 (0xf2)
.maxstack 3
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldstr "0"
IL_0008: ldc.i4.1
IL_0009: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_000e: brtrue.s IL_001b
IL_0010: ldstr "Equal to 0"
IL_0015: call "Sub System.Console.WriteLine(String)"
IL_001a: ret
IL_001b: ldloc.0
IL_001c: ldstr "1"
IL_0021: ldc.i4.1
IL_0022: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0027: brfalse.s IL_0061
IL_0029: ldloc.0
IL_002a: ldstr "2"
IL_002f: ldc.i4.1
IL_0030: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0035: brfalse.s IL_0061
IL_0037: ldloc.0
IL_0038: ldstr "3"
IL_003d: ldc.i4.1
IL_003e: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0043: brfalse.s IL_0061
IL_0045: ldloc.0
IL_0046: ldstr "4"
IL_004b: ldc.i4.1
IL_004c: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0051: brfalse.s IL_0061
IL_0053: ldloc.0
IL_0054: ldstr "5"
IL_0059: ldc.i4.1
IL_005a: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_005f: brtrue.s IL_006c
IL_0061: ldstr "Between 1 and 5, inclusive"
IL_0066: call "Sub System.Console.WriteLine(String)"
IL_006b: ret
IL_006c: ldloc.0
IL_006d: ldstr "6"
IL_0072: ldc.i4.1
IL_0073: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0078: ldc.i4.0
IL_0079: blt.s IL_0095
IL_007b: ldloc.0
IL_007c: ldstr "8"
IL_0081: ldc.i4.1
IL_0082: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0087: ldc.i4.0
IL_0088: bgt.s IL_0095
IL_008a: ldstr "Between 6 and 8, inclusive"
IL_008f: call "Sub System.Console.WriteLine(String)"
IL_0094: ret
IL_0095: ldloc.0
IL_0096: ldstr "9"
IL_009b: ldc.i4.1
IL_009c: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00a1: ldc.i4.0
IL_00a2: blt.s IL_00be
IL_00a4: ldloc.0
IL_00a5: ldstr "8"
IL_00aa: ldc.i4.1
IL_00ab: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00b0: ldc.i4.0
IL_00b1: bgt.s IL_00be
IL_00b3: ldstr "Fail"
IL_00b8: call "Sub System.Console.WriteLine(String)"
IL_00bd: ret
IL_00be: ldloc.0
IL_00bf: ldstr "9"
IL_00c4: ldc.i4.1
IL_00c5: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00ca: ldc.i4.0
IL_00cb: bge.s IL_00dc
IL_00cd: ldloc.0
IL_00ce: ldstr "10"
IL_00d3: ldc.i4.1
IL_00d4: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00d9: ldc.i4.0
IL_00da: bgt.s IL_00e7
IL_00dc: ldstr "Equal to 9 or 10"
IL_00e1: call "Sub System.Console.WriteLine(String)"
IL_00e6: ret
IL_00e7: ldstr "Greater than 10"
IL_00ec: call "Sub System.Console.WriteLine(String)"
IL_00f1: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact, WorkItem(651996, "DevDiv")>
Public Sub SelectCase_String_Multiple_Hash_SwitchTable()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x.ToString())
Console.Write(x.ToString() + ":")
Test2(x.ToString())
Next
End Sub
Sub Test(number as String)
Select Case number
Case "0"
Console.WriteLine("Equal to 0")
Case "1", "2", "3", "4", "5"
Console.WriteLine("Between 1 and 5, inclusive")
Case "6", "7", "8"
Console.WriteLine("Between 6 and 8, inclusive")
Case "9", "10"
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
Sub Test2(number as String)
Select Case number
Case "0"
Console.WriteLine("Equal to 0")
Case "1", "2", "3", "4", "5"
Console.WriteLine("Between 1 and 5, inclusive")
Case "6", "7", "8"
Console.WriteLine("Between 6 and 8, inclusive")
Case "9", "10"
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
options:=TestOptions.ReleaseExe.WithOptionCompareText(False),
expectedOutput:=<![CDATA[0:Equal to 0
0:Equal to 0
1:Between 1 and 5, inclusive
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
9:Equal to 9 or 10
10:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10
11:Greater than 10]]>).VerifyIL("M1.Test", <![CDATA[
{
// Code size 420 (0x1a4)
.maxstack 3
.locals init (String V_0,
UInteger V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call "Function $$method0x6000001-ComputeStringHash(String) As UInteger"
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldc.i4 0x330ca589
IL_000f: bgt.un.s IL_005a
IL_0011: ldloc.1
IL_0012: ldc.i4 0x300ca0d0
IL_0017: bgt.un.s IL_0034
IL_0019: ldloc.1
IL_001a: ldc.i4 0x1beb2a44
IL_001f: beq IL_015d
IL_0024: ldloc.1
IL_0025: ldc.i4 0x300ca0d0
IL_002a: beq IL_010d
IL_002f: br IL_0199
IL_0034: ldloc.1
IL_0035: ldc.i4 0x310ca263
IL_003a: beq IL_00fa
IL_003f: ldloc.1
IL_0040: ldc.i4 0x320ca3f6
IL_0045: beq IL_012d
IL_004a: ldloc.1
IL_004b: ldc.i4 0x330ca589
IL_0050: beq IL_011d
IL_0055: br IL_0199
IL_005a: ldloc.1
IL_005b: ldc.i4 0x360caa42
IL_0060: bgt.un.s IL_007f
IL_0062: ldloc.1
IL_0063: ldc.i4 0x340ca71c
IL_0068: beq.s IL_00b8
IL_006a: ldloc.1
IL_006b: ldc.i4 0x350ca8af
IL_0070: beq.s IL_00a2
IL_0072: ldloc.1
IL_0073: ldc.i4 0x360caa42
IL_0078: beq.s IL_00e4
IL_007a: br IL_0199
IL_007f: ldloc.1
IL_0080: ldc.i4 0x370cabd5
IL_0085: beq.s IL_00ce
IL_0087: ldloc.1
IL_0088: ldc.i4 0x3c0cb3b4
IL_008d: beq IL_014d
IL_0092: ldloc.1
IL_0093: ldc.i4 0x3d0cb547
IL_0098: beq IL_013d
IL_009d: br IL_0199
IL_00a2: ldloc.0
IL_00a3: ldstr "0"
IL_00a8: ldc.i4.0
IL_00a9: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00ae: brfalse IL_016d
IL_00b3: br IL_0199
IL_00b8: ldloc.0
IL_00b9: ldstr "1"
IL_00be: ldc.i4.0
IL_00bf: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00c4: brfalse IL_0178
IL_00c9: br IL_0199
IL_00ce: ldloc.0
IL_00cf: ldstr "2"
IL_00d4: ldc.i4.0
IL_00d5: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00da: brfalse IL_0178
IL_00df: br IL_0199
IL_00e4: ldloc.0
IL_00e5: ldstr "3"
IL_00ea: ldc.i4.0
IL_00eb: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00f0: brfalse IL_0178
IL_00f5: br IL_0199
IL_00fa: ldloc.0
IL_00fb: ldstr "4"
IL_0100: ldc.i4.0
IL_0101: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0106: brfalse.s IL_0178
IL_0108: br IL_0199
IL_010d: ldloc.0
IL_010e: ldstr "5"
IL_0113: ldc.i4.0
IL_0114: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0119: brfalse.s IL_0178
IL_011b: br.s IL_0199
IL_011d: ldloc.0
IL_011e: ldstr "6"
IL_0123: ldc.i4.0
IL_0124: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0129: brfalse.s IL_0183
IL_012b: br.s IL_0199
IL_012d: ldloc.0
IL_012e: ldstr "7"
IL_0133: ldc.i4.0
IL_0134: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0139: brfalse.s IL_0183
IL_013b: br.s IL_0199
IL_013d: ldloc.0
IL_013e: ldstr "8"
IL_0143: ldc.i4.0
IL_0144: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0149: brfalse.s IL_0183
IL_014b: br.s IL_0199
IL_014d: ldloc.0
IL_014e: ldstr "9"
IL_0153: ldc.i4.0
IL_0154: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0159: brfalse.s IL_018e
IL_015b: br.s IL_0199
IL_015d: ldloc.0
IL_015e: ldstr "10"
IL_0163: ldc.i4.0
IL_0164: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0169: brfalse.s IL_018e
IL_016b: br.s IL_0199
IL_016d: ldstr "Equal to 0"
IL_0172: call "Sub System.Console.WriteLine(String)"
IL_0177: ret
IL_0178: ldstr "Between 1 and 5, inclusive"
IL_017d: call "Sub System.Console.WriteLine(String)"
IL_0182: ret
IL_0183: ldstr "Between 6 and 8, inclusive"
IL_0188: call "Sub System.Console.WriteLine(String)"
IL_018d: ret
IL_018e: ldstr "Equal to 9 or 10"
IL_0193: call "Sub System.Console.WriteLine(String)"
IL_0198: ret
IL_0199: ldstr "Greater than 10"
IL_019e: call "Sub System.Console.WriteLine(String)"
IL_01a3: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=True)
End Sub
<Fact()>
Public Sub MissingReferenceToVBRuntime()
CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Sub Test(number as String)
Select Case number
Case "0"
Console.WriteLine("Equal to 0")
Case "1", "2", "3", "4", "5"
Console.WriteLine("Between 1 and 5, inclusive")
Case "6", "7", "8"
Console.WriteLine("Between 6 and 8, inclusive")
Case "9", "10"
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Class
]]></file>
</compilation>, OutputKind.DynamicallyLinkedLibrary).
VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_MissingRuntimeHelper, "number").WithArguments("Microsoft.VisualBasic.CompilerServices.Operators.CompareString"))
End Sub
<WorkItem(529047, "DevDiv")>
<Fact>
Public Sub SelectOutOfMethod()
CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Class m1
Select ""
End Select
End Class
]]></file>
</compilation>).
VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Select """""),
Diagnostic(ERRID.ERR_EndSelectNoSelect, "End Select"))
End Sub
<WorkItem(529047, "DevDiv")>
<Fact>
Public Sub SelectOutOfMethod_1()
CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Select ""
End Select
]]></file>
</compilation>).
VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Select """""),
Diagnostic(ERRID.ERR_EndSelectNoSelect, "End Select"))
End Sub
<WorkItem(543410, "DevDiv")>
<Fact()>
Public Sub SelectCase_GetType()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Module M1
Sub Main()
Select GetType(Object)
End Select
End Sub
End Module
]]></file>
</compilation>).VerifyIL("M1.Main", <![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldtoken "Object"
IL_0005: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_000a: pop
IL_000b: ret
}
]]>)
End Sub
<WorkItem(634404, "DevDiv")>
<WorkItem(913556, "DevDiv")>
<Fact()>
Public Sub MissingCharsProperty()
CompilationUtils.CreateCompilationWithReferences(
<compilation>
<file name="a.vb"><![CDATA[
Class M1
Shared Sub Main()
End Sub
Shared Function Test(number as String) as string
Select Case number
Case "0"
return "0"
Case "1"
return "1"
Case "2"
return "2"
Case "3"
return "3"
Case "4"
return "4"
Case Else
return "Else"
End Select
End Function
End Class
]]></file>
</compilation>, references:={AacorlibRef}).
VerifyEmitDiagnostics(
Diagnostic(ERRID.ERR_MissingRuntimeHelper, "number").WithArguments("System.String.get_Chars"),
Diagnostic(ERRID.ERR_MissingRuntimeHelper, "number").WithArguments("Microsoft.VisualBasic.CompilerServices.Operators.CompareString"))
End Sub
<Fact>
Public Sub SelectCase_Nothing001()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub Main()
Dim str As String = ""
Select Case str
Case CStr(Nothing)
System.Console.WriteLine("null")
Case "1"
System.Console.WriteLine("1")
'Case "1"
' System.Console.WriteLine("2")
'Case "3"
' System.Console.WriteLine("3")
'Case "4"
' System.Console.WriteLine("4")
'Case "5"
' System.Console.WriteLine("5")
'Case "6"
' System.Console.WriteLine("6")
'Case "7"
' System.Console.WriteLine("7")
'Case "8"
' System.Console.WriteLine("8")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="null").VerifyIL("Module1.Main", <![CDATA[
{
// Code size 53 (0x35)
.maxstack 3
.locals init (String V_0) //str
IL_0000: ldstr ""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldnull
IL_0008: ldc.i4.0
IL_0009: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_000e: brfalse.s IL_001f
IL_0010: ldloc.0
IL_0011: ldstr "1"
IL_0016: ldc.i4.0
IL_0017: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_001c: brfalse.s IL_002a
IL_001e: ret
IL_001f: ldstr "null"
IL_0024: call "Sub System.Console.WriteLine(String)"
IL_0029: ret
IL_002a: ldstr "1"
IL_002f: call "Sub System.Console.WriteLine(String)"
IL_0034: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub SelectCase_Nothing002()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub Main()
Dim str As String = ""
Select Case str
Case CStr(Nothing)
System.Console.WriteLine("null")
Case "1"
System.Console.WriteLine("1")
Case "1"
System.Console.WriteLine("2")
Case "3"
System.Console.WriteLine("3")
Case "4"
System.Console.WriteLine("4")
Case "5"
System.Console.WriteLine("5")
Case "6"
System.Console.WriteLine("6")
Case "7"
System.Console.WriteLine("7")
Case "8"
System.Console.WriteLine("8")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="null").VerifyIL("Module1.Main", <![CDATA[
{
// Code size 317 (0x13d)
.maxstack 3
.locals init (String V_0, //str
UInteger V_1)
IL_0000: ldstr ""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: call "Function $$method0x6000001-ComputeStringHash(String) As UInteger"
IL_000c: stloc.1
IL_000d: ldloc.1
IL_000e: ldc.i4 0x330ca589
IL_0013: bgt.un.s IL_0045
IL_0015: ldloc.1
IL_0016: ldc.i4 0x310ca263
IL_001b: bgt.un.s IL_0031
IL_001d: ldloc.1
IL_001e: ldc.i4 0x300ca0d0
IL_0023: beq IL_00a9
IL_0028: ldloc.1
IL_0029: ldc.i4 0x310ca263
IL_002e: beq.s IL_009a
IL_0030: ret
IL_0031: ldloc.1
IL_0032: ldc.i4 0x320ca3f6
IL_0037: beq IL_00c7
IL_003c: ldloc.1
IL_003d: ldc.i4 0x330ca589
IL_0042: beq.s IL_00b8
IL_0044: ret
IL_0045: ldloc.1
IL_0046: ldc.i4 0x360caa42
IL_004b: bgt.un.s IL_005e
IL_004d: ldloc.1
IL_004e: ldc.i4 0x340ca71c
IL_0053: beq.s IL_007c
IL_0055: ldloc.1
IL_0056: ldc.i4 0x360caa42
IL_005b: beq.s IL_008b
IL_005d: ret
IL_005e: ldloc.1
IL_005f: ldc.i4 0x3d0cb547
IL_0064: beq.s IL_00d6
IL_0066: ldloc.1
IL_0067: ldc.i4 0x811c9dc5
IL_006c: bne.un IL_013c
IL_0071: ldloc.0
IL_0072: ldnull
IL_0073: ldc.i4.0
IL_0074: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0079: brfalse.s IL_00e5
IL_007b: ret
IL_007c: ldloc.0
IL_007d: ldstr "1"
IL_0082: ldc.i4.0
IL_0083: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0088: brfalse.s IL_00f0
IL_008a: ret
IL_008b: ldloc.0
IL_008c: ldstr "3"
IL_0091: ldc.i4.0
IL_0092: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0097: brfalse.s IL_00fb
IL_0099: ret
IL_009a: ldloc.0
IL_009b: ldstr "4"
IL_00a0: ldc.i4.0
IL_00a1: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00a6: brfalse.s IL_0106
IL_00a8: ret
IL_00a9: ldloc.0
IL_00aa: ldstr "5"
IL_00af: ldc.i4.0
IL_00b0: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00b5: brfalse.s IL_0111
IL_00b7: ret
IL_00b8: ldloc.0
IL_00b9: ldstr "6"
IL_00be: ldc.i4.0
IL_00bf: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00c4: brfalse.s IL_011c
IL_00c6: ret
IL_00c7: ldloc.0
IL_00c8: ldstr "7"
IL_00cd: ldc.i4.0
IL_00ce: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00d3: brfalse.s IL_0127
IL_00d5: ret
IL_00d6: ldloc.0
IL_00d7: ldstr "8"
IL_00dc: ldc.i4.0
IL_00dd: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_00e2: brfalse.s IL_0132
IL_00e4: ret
IL_00e5: ldstr "null"
IL_00ea: call "Sub System.Console.WriteLine(String)"
IL_00ef: ret
IL_00f0: ldstr "1"
IL_00f5: call "Sub System.Console.WriteLine(String)"
IL_00fa: ret
IL_00fb: ldstr "3"
IL_0100: call "Sub System.Console.WriteLine(String)"
IL_0105: ret
IL_0106: ldstr "4"
IL_010b: call "Sub System.Console.WriteLine(String)"
IL_0110: ret
IL_0111: ldstr "5"
IL_0116: call "Sub System.Console.WriteLine(String)"
IL_011b: ret
IL_011c: ldstr "6"
IL_0121: call "Sub System.Console.WriteLine(String)"
IL_0126: ret
IL_0127: ldstr "7"
IL_012c: call "Sub System.Console.WriteLine(String)"
IL_0131: ret
IL_0132: ldstr "8"
IL_0137: call "Sub System.Console.WriteLine(String)"
IL_013c: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=True)
End Sub
<Fact>
Public Sub SelectCase_Nothing003()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub Main()
Dim str As String = ""
Select Case str
Case CStr("")
System.Console.WriteLine("empty")
Case CStr(Nothing)
System.Console.WriteLine("null")
Case "1"
System.Console.WriteLine("1")
Case "1"
System.Console.WriteLine("2")
Case "3"
System.Console.WriteLine("3")
Case "4"
System.Console.WriteLine("4")
Case "5"
System.Console.WriteLine("5")
Case "6"
System.Console.WriteLine("6")
Case "7"
System.Console.WriteLine("7")
Case "8"
System.Console.WriteLine("8")
End Select
End Sub
End Module
]]></file>
</compilation>, expectedOutput:="empty")
VerifySynthesizedStringHashMethod(compVerifier, expected:=True)
End Sub
<Fact>
Public Sub Regression947580()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module Module1
Sub Main()
boo(42)
End Sub
Function boo(i As Integer) As String
Select Case i
Case 42
Dim x = "foo"
If x <> "bar" Then
Exit Select
End If
Return x
End Select
Return Nothing
End Function
End Module
]]></file>
</compilation>, expectedOutput:="").VerifyIL("Module1.boo", <![CDATA[
{
// Code size 35 (0x23)
.maxstack 3
.locals init (String V_0, //boo
Integer V_1,
String V_2) //x
IL_0000: ldarg.0
IL_0001: stloc.1
IL_0002: ldloc.1
IL_0003: ldc.i4.s 42
IL_0005: bne.un.s IL_001f
IL_0007: ldstr "foo"
IL_000c: stloc.2
IL_000d: ldloc.2
IL_000e: ldstr "bar"
IL_0013: ldc.i4.0
IL_0014: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0019: brtrue.s IL_001f
IL_001b: ldloc.2
IL_001c: stloc.0
IL_001d: br.s IL_0021
IL_001f: ldnull
IL_0020: stloc.0
IL_0021: ldloc.0
IL_0022: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
<Fact>
Public Sub Regression947580a()
Dim compVerifier = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module Module1
Sub Main()
boo(42)
End Sub
Function boo(i As Integer) As String
Select Case i
Case 42
Dim x = "foo"
If x <> "bar" Then
Exit Select
End If
Exit Select
End Select
Return Nothing
End Function
End Module
]]></file>
</compilation>, expectedOutput:="").VerifyIL("Module1.boo", <![CDATA[
{
// Code size 26 (0x1a)
.maxstack 3
.locals init (Integer V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.s 42
IL_0005: bne.un.s IL_0018
IL_0007: ldstr "foo"
IL_000c: ldstr "bar"
IL_0011: ldc.i4.0
IL_0012: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_0017: pop
IL_0018: ldnull
IL_0019: ret
}
]]>)
VerifySynthesizedStringHashMethod(compVerifier, expected:=False)
End Sub
#End Region
End Class
End Namespace
|
JohnHamby/roslyn
|
src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenSelectCase.vb
|
Visual Basic
|
apache-2.0
| 148,733
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.ConvertForToForEach
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertForToForEach
<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=NameOf(VisualBasicConvertForToForEachCodeRefactoringProvider)), [Shared]>
Friend Class VisualBasicConvertForToForEachCodeRefactoringProvider
Inherits AbstractConvertForToForEachCodeRefactoringProvider(Of
StatementSyntax,
ForBlockSyntax,
ExpressionSyntax,
MemberAccessExpressionSyntax,
TypeSyntax,
VariableDeclaratorSyntax)
<ImportingConstructor>
Public Sub New()
End Sub
Protected Overrides Function GetTitle() As String
Return VBFeaturesResources.Convert_to_For_Each
End Function
Protected Overrides Function GetBodyStatements(forStatement As ForBlockSyntax) As SyntaxList(Of StatementSyntax)
Return forStatement.Statements
End Function
Protected Overrides Function IsValidVariableDeclarator(firstVariable As VariableDeclaratorSyntax) As Boolean
' we only support local declarations in vb that have a single identifier. i.e.
' dim x = list(i)
Return firstVariable.Names.Count = 1
End Function
Protected Overrides Function TryGetForStatementComponents(
forBlock As ForBlockSyntax,
ByRef iterationVariable As SyntaxToken,
ByRef initializer As ExpressionSyntax,
ByRef memberAccess As MemberAccessExpressionSyntax,
ByRef stepValueExpressionOpt As ExpressionSyntax,
cancellationToken As CancellationToken) As Boolean
Dim forStatement As ForStatementSyntax = forBlock.ForStatement
Dim identifierName = TryCast(forStatement.ControlVariable, IdentifierNameSyntax)
If identifierName IsNot Nothing Then
iterationVariable = identifierName.Identifier
If forStatement.FromValue IsNot Nothing Then
initializer = forStatement.FromValue
Dim subtraction = TryCast(forStatement.ToValue, BinaryExpressionSyntax)
If subtraction?.Kind() = SyntaxKind.SubtractExpression Then
Dim subtractionRight = TryCast(subtraction.Right, LiteralExpressionSyntax)
If TypeOf subtractionRight.Token.Value Is Integer AndAlso
DirectCast(subtractionRight.Token.Value, Integer) = 1 Then
memberAccess = TryCast(subtraction.Left, MemberAccessExpressionSyntax)
If memberAccess IsNot Nothing Then
stepValueExpressionOpt = forStatement.StepClause?.StepValue
Return True
End If
End If
End If
End If
End If
Return False
End Function
Protected Overrides Function ConvertForNode(
currentFor As ForBlockSyntax, typeNode As TypeSyntax,
foreachIdentifier As SyntaxToken, collectionExpression As ExpressionSyntax, iterationVariableType As ITypeSymbol, options As OptionSet) As SyntaxNode
Dim forStatement = currentFor.ForStatement
Return SyntaxFactory.ForEachBlock(
SyntaxFactory.ForEachStatement(
forStatement.ForKeyword,
SyntaxFactory.Token(SyntaxKind.EachKeyword),
SyntaxFactory.VariableDeclarator(
SyntaxFactory.SingletonSeparatedList(SyntaxFactory.ModifiedIdentifier(foreachIdentifier)),
If(typeNode IsNot Nothing, SyntaxFactory.SimpleAsClause(typeNode), Nothing),
Nothing),
SyntaxFactory.Token(SyntaxKind.InKeyword),
collectionExpression).WithTriviaFrom(forStatement),
currentFor.Statements,
currentFor.NextStatement)
End Function
End Class
End Namespace
|
nguerrera/roslyn
|
src/Features/VisualBasic/Portable/ConvertForToForEach/VisualBasicConvertForToForEachCodeRefactoringProvider.vb
|
Visual Basic
|
apache-2.0
| 4,557
|
Public Partial Class Insert2
Inherits System.Web.UI.Page
Protected _db As New Samples.ApplicationDbContext()
Protected Sub Page_Load(sender As Object, e As EventArgs)
End Sub
' This is the Insert method to insert the entered Category item
' USAGE: <asp:FormView InsertMethod="InsertItem">
Public Sub InsertItem()
Using _db
Dim item = New Samples.Category()
TryUpdateModel(item)
If ModelState.IsValid Then
' Save changes
_db.Categories.Add(item)
_db.SaveChanges()
Response.Redirect("Default")
End If
End Using
End Sub
Protected Sub ItemCommand(sender As Object, e As FormViewCommandEventArgs)
If e.CommandName.Equals("Cancel", StringComparison.OrdinalIgnoreCase) Then
Response.Redirect("Default")
End If
End Sub
End Class
|
neozhu/WebFormsScaffolding
|
Samples.VB/3_Associations/Categories/Insert.aspx.vb
|
Visual Basic
|
apache-2.0
| 781
|
'*******************************************************************************************'
' '
' Download Free Evaluation Version From: https://bytescout.com/download/web-installer '
' '
' Also available as Web API! Get free API Key https://app.pdf.co/signup '
' '
' Copyright © 2017-2020 ByteScout, Inc. All rights reserved. '
' https://www.bytescout.com '
' https://www.pdf.co '
'*******************************************************************************************'
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("Read format type of cells (VB.NET)")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("Read format type of cells (VB.NET)")>
<Assembly: AssemblyCopyright("Copyright © 2008")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("91fac8d3-ba0e-41af-b3d5-7daec41fa301")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
bytescout/ByteScout-SDK-SourceCode
|
Spreadsheet SDK/VB.NET/Read Number Format In Cell/My Project/AssemblyInfo.vb
|
Visual Basic
|
apache-2.0
| 2,161
|
' 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.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Shared.TestHooks
Imports Microsoft.CodeAnalysis.Snippets
Imports Microsoft.VisualStudio.LanguageServices.CSharp.Snippets
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Completion
<ExportLanguageService(GetType(ISnippetInfoService), LanguageNames.CSharp), [Shared]>
Friend Class TestCSharpSnippetInfoService
Inherits CSharpSnippetInfoService
<ImportingConstructor>
Friend Sub New(listenerProvider As IAsynchronousOperationListenerProvider)
MyBase.New(Nothing, listenerProvider)
End Sub
Friend Sub SetSnippetShortcuts(newSnippetShortcuts As String())
SyncLock cacheGuard
snippets = newSnippetShortcuts.Select(Function(shortcut) New SnippetInfo(shortcut, "title", "description", "path")).ToImmutableArray()
snippetShortcuts = GetShortcutsHashFromSnippets(snippets)
End SyncLock
End Sub
End Class
End Namespace
|
OmarTawfik/roslyn
|
src/VisualStudio/Core/Test/Completion/TestCSharpSnippetInfoService.vb
|
Visual Basic
|
apache-2.0
| 1,343
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Imports Microsoft.VisualStudio.Debugger.Evaluation
Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class StatementTests
Inherits ExpressionCompilerTestBase
<Fact>
Public Sub AddAssignmentStatement()
Const source = "
Class C
Sub M()
Dim d As Double = 0
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="d += 1.1",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 13 (0xd)
.maxstack 2
.locals init (Double V_0) //d
IL_0000: ldloc.0
IL_0001: ldc.r8 1.1
IL_000a: add
IL_000b: stloc.0
IL_000c: ret
}
")
End Sub
<Fact>
Public Sub AddHandlerStatement()
Const source = "
Class C
Event a()
Sub M()
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:=" AddHandler a, AddressOf System.Console.WriteLine",
errorMessage:=errorMessage)
'Statements of type 'AddHandlerStatement' are not allowed in the Immediate window.
Assert.Equal(String.Format(ExpressionEvaluator.Resources.InvalidDebuggerStatement, SyntaxKind.AddHandlerStatement), errorMessage)
End Sub
<Fact>
Public Sub ArrayAccess()
Const source = "
Module Module1
Sub Main(args() As String)
End Sub
End Module
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="Module1.Main",
expr:="args(1)",
errorMessage:=errorMessage)
Assert.Equal("error BC30454: Expression is not a method.", errorMessage)
testData = EvaluateStatement(
source,
methodName:="Module1.Main",
expr:="args(1) = ""Hi""",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 9 (0x9)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: ldstr ""Hi""
IL_0007: stelem.ref
IL_0008: ret
}
")
testData = EvaluateStatement(
source,
methodName:="Module1.Main",
expr:="?args(1)",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: ldelem.ref
IL_0003: ret
}
")
testData = EvaluateStatement(
source,
methodName:="Module1.Main",
expr:="?args(1) = ""Hi""",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 18 (0x12)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: ldelem.ref
IL_0003: ldstr ""Hi""
IL_0008: ldc.i4.0
IL_0009: call ""Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer""
IL_000e: ldc.i4.0
IL_000f: ceq
IL_0011: ret
}
")
End Sub
<Fact>
Public Sub CallStatement()
Const source = "
Class C
Private member As Integer = 1
Public Sub Increment()
member += 1
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.Increment",
expr:="Call (New C).Increment()",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 11 (0xb)
.maxstack 1
.locals init (Integer& V_0)
IL_0000: newobj ""Sub C..ctor()""
IL_0005: call ""Sub C.Increment()""
IL_000a: ret
}
")
End Sub
<Fact>
Public Sub ConcatenateAssignmentStatement()
Const source = "
Module Module1
Sub M()
Dim s As String = ""a""
End Sub
End Module
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="Module1.M",
expr:="s &= 1",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 14 (0xe)
.maxstack 2
.locals init (String V_0) //s
IL_0000: ldloc.0
IL_0001: ldc.i4.1
IL_0002: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String""
IL_0007: call ""Function String.Concat(String, String) As String""
IL_000c: stloc.0
IL_000d: ret
}
")
End Sub
<Fact>
Public Sub DivideAssignmentStatement()
Const source = "
Class C
Sub M()
Dim b As Byte = 1
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="b /= 0",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 20 (0x14)
.maxstack 2
.locals init (Byte V_0) //b
IL_0000: ldloc.0
IL_0001: conv.r8
IL_0002: ldc.r8 0
IL_000b: div
IL_000c: call ""Function System.Math.Round(Double) As Double""
IL_0011: conv.ovf.u1
IL_0012: stloc.0
IL_0013: ret
}
")
End Sub
<Fact>
Public Sub EmptyStatement()
Const source = "
Class C
Sub M()
End Sub
End Class
"
' We should never hit this case in the VS scenario, but testing to make
' sure we do something reasonable if we ever did.
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="",
errorMessage:=errorMessage)
'Statements of type 'EmptyStatement' are not allowed in the Immediate window.
Assert.Equal(String.Format(ExpressionEvaluator.Resources.InvalidDebuggerStatement, SyntaxKind.EmptyStatement), errorMessage)
End Sub
<Fact>
Public Sub EndStatement()
Const source = "
Class C
Sub M()
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="End",
errorMessage:=errorMessage)
'Statements of type 'EndStatement' are not allowed in the Immediate window.
Assert.Equal(String.Format(ExpressionEvaluator.Resources.InvalidDebuggerStatement, SyntaxKind.EndStatement), errorMessage)
End Sub
<Fact>
Public Sub ExponentiateAssignmentStatement()
Const source = "
Class C
Sub M()
Dim m As Decimal
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="m ^= 2",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 28 (0x1c)
.maxstack 3
.locals init (Decimal V_0) //m
IL_0000: ldloca.s V_0
IL_0002: ldloc.0
IL_0003: call ""Function System.Convert.ToDouble(Decimal) As Double""
IL_0008: ldc.r8 2
IL_0011: call ""Function System.Math.Pow(Double, Double) As Double""
IL_0016: call ""Sub Decimal..ctor(Double)""
IL_001b: ret
}
")
End Sub
<Fact>
Public Sub ExpressionStatement()
Const source = "
Class C
Public Sub M()
Dim x As Integer = 1
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="System.Console.WriteLine()",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 6 (0x6)
.maxstack 0
.locals init (Integer V_0) //x
IL_0000: call ""Sub System.Console.WriteLine()""
IL_0005: ret
}
")
testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="System.Console.Read()",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 7 (0x7)
.maxstack 1
.locals init (Integer V_0) //x
IL_0000: call ""Function System.Console.Read() As Integer""
IL_0005: pop
IL_0006: ret
}
")
testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="x",
errorMessage:=errorMessage)
Assert.Equal("error BC30454: Expression is not a method.", errorMessage)
End Sub
<Fact>
Public Sub IfStatement()
Const source = "
Class C
Sub M()
Dim x As Integer = 0
End Sub
End Class
"
' The old EE used to support single-line If statements, but Roslyn does not. This is because Parser.ParseStatementInMethodBody
' does directly handle the single-line case. If we end up needing to support single-line if, then we either need to fix parsing
' of single-line Ifs in ParseStatementInMethodBody (ADGreen knows more), or we need to duplicate the parser logic for handling
' them in the EE.
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:=" If True Then x = 1",
errorMessage:=errorMessage)
Assert.Equal("error BC30035: Syntax error.", errorMessage)
testData = EvaluateStatement(
source,
methodName:="C.M",
expr:=" If True Then x = 1 Else x = 2",
errorMessage:=errorMessage)
Assert.Equal("error BC30035: Syntax error.", errorMessage)
End Sub
<Fact>
Public Sub IntegerDivideAssignmentStatement()
Const source = "
Class C
Sub M()
Dim odd As UInteger
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="odd \= 2",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 8 (0x8)
.maxstack 2
.locals init (UInteger V_0) //odd
IL_0000: ldloc.0
IL_0001: conv.u8
IL_0002: ldc.i4.2
IL_0003: conv.i8
IL_0004: div
IL_0005: conv.ovf.u4
IL_0006: stloc.0
IL_0007: ret
}
")
End Sub
<Fact>
Public Sub LeftShiftAssignmentStatement()
Const source = "
Class C
Sub M()
Dim s As Short
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="s <<= 16",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 10 (0xa)
.maxstack 3
.locals init (Short V_0) //s
IL_0000: ldloc.0
IL_0001: ldc.i4.s 16
IL_0003: ldc.i4.s 15
IL_0005: and
IL_0006: shl
IL_0007: conv.i2
IL_0008: stloc.0
IL_0009: ret
}
")
End Sub
<Fact>
Public Sub MultiplyAssignmentStatement()
Const source = "
Class C
Sub M()
Dim l As ULong
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="l *= l",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 5 (0x5)
.maxstack 2
.locals init (ULong V_0) //l
IL_0000: ldloc.0
IL_0001: ldloc.0
IL_0002: mul.ovf.un
IL_0003: stloc.0
IL_0004: ret
}
")
End Sub
<Fact>
Public Sub OnErrorResumeNextStatement()
Const source = "
Class C
Sub M()
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="On Error Resume Next",
errorMessage:=errorMessage)
'Statements of type 'OnErrorResumeNextStatement' are not allowed in the Immediate window.
Assert.Equal(String.Format(ExpressionEvaluator.Resources.InvalidDebuggerStatement, SyntaxKind.OnErrorResumeNextStatement), errorMessage)
End Sub
<Fact>
Public Sub PrintStatement()
Const source = "
Class C
Public Sub M()
Dim x As Integer = 1
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="?x = 1",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 5 (0x5)
.maxstack 2
.locals init (Integer V_0) //x
IL_0000: ldloc.0
IL_0001: ldc.i4.1
IL_0002: ceq
IL_0004: ret
}
")
' We should never hit this case in the VS scenario, but testing to make
' sure we do something reasonable if we ever did.
testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="? ",
errorMessage:=errorMessage)
Assert.Equal("error BC30201: Expression expected.", errorMessage)
testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="??x = 1",
errorMessage:=errorMessage)
Assert.Equal("error BC30201: Expression expected.", errorMessage)
testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="?System.Console.WriteLine()",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 6 (0x6)
.maxstack 0
.locals init (Integer V_0) //x
IL_0000: call ""Sub System.Console.WriteLine()""
IL_0005: ret
}
")
testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="?System.Console.Read()",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 6 (0x6)
.maxstack 1
.locals init (Integer V_0) //x
IL_0000: call ""Function System.Console.Read() As Integer""
IL_0005: ret
}
")
testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="?AddressOf System.Console.WriteLine",
errorMessage:=errorMessage)
Assert.Equal("error BC30491: Expression does not produce a value.", errorMessage)
testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="?x += 1",
errorMessage:=errorMessage)
Assert.Equal("error BC37237: '+=' is not a valid format specifier", errorMessage) ' not the best error, but not worth modifying parsing to improve...
End Sub
<Fact>
Public Sub RedimStatement()
Const source = "
Class C
Public Sub M()
Dim a(1) As Integer
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="ReDim a(2), a(3)",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 15 (0xf)
.maxstack 1
.locals init (Integer() V_0) //a
IL_0000: ldc.i4.3
IL_0001: newarr ""Integer""
IL_0006: stloc.0
IL_0007: ldc.i4.4
IL_0008: newarr ""Integer""
IL_000d: stloc.0
IL_000e: ret
}
")
testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="?ReDim a(2), a(3)",
errorMessage:=errorMessage)
Assert.Equal("error BC30201: Expression expected.", errorMessage)
End Sub
<Fact>
Public Sub RedimPreserveStatement()
Const source = "
Module Module1
Public Sub M()
Dim a(1) As Integer
End Sub
End Module
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="Module1.M",
expr:="ReDim Preserve a(2)",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 19 (0x13)
.maxstack 2
.locals init (Integer() V_0) //a
IL_0000: ldloc.0
IL_0001: ldc.i4.3
IL_0002: newarr ""Integer""
IL_0007: call ""Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(System.Array, System.Array) As System.Array""
IL_000c: castclass ""Integer()""
IL_0011: stloc.0
IL_0012: ret
}
")
End Sub
<Fact>
Public Sub RightShiftAssignmentStatement()
Const source = "
Class C
Sub M()
Dim u As UShort = &H8000
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="u >>= &H1",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 6 (0x6)
.maxstack 2
.locals init (UShort V_0) //u
IL_0000: ldloc.0
IL_0001: ldc.i4.1
IL_0002: shr.un
IL_0003: conv.u2
IL_0004: stloc.0
IL_0005: ret
}
")
End Sub
<Fact>
Public Sub SimpleAssignmentStatement()
Const source = "
Class C
Private field As Integer = 1
Property Prop As C
Public Sub M()
Dim c1 As New C()
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="field = 2",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 8 (0x8)
.maxstack 2
.locals init (C V_0) //c1
IL_0000: ldarg.0
IL_0001: ldc.i4.2
IL_0002: stfld ""C.field As Integer""
IL_0007: ret
}
")
testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="c1.Prop.field = 2",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 13 (0xd)
.maxstack 2
.locals init (C V_0) //c1
IL_0000: ldloc.0
IL_0001: callvirt ""Function C.get_Prop() As C""
IL_0006: ldc.i4.2
IL_0007: stfld ""C.field As Integer""
IL_000c: ret
}
")
End Sub
<Fact>
Public Sub StopStatement()
Const source = "
Class C
Sub M()
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="Stop",
errorMessage:=errorMessage)
'Statements of type 'StopStatement' are not allowed in the Immediate window.
Assert.Equal(String.Format(ExpressionEvaluator.Resources.InvalidDebuggerStatement, SyntaxKind.StopStatement), errorMessage)
End Sub
<Fact>
Public Sub SubtractAssignmentStatement()
Const source = "
Class C
Property D As Decimal
Sub M()
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:="d -= 3.14159D",
errorMessage:=errorMessage)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 34 (0x22)
.maxstack 7
.locals init (C V_0)
IL_0000: ldarg.0
IL_0001: dup
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: callvirt ""Function C.get_D() As Decimal""
IL_0009: ldc.i4 0x4cb2f
IL_000e: ldc.i4.0
IL_000f: ldc.i4.0
IL_0010: ldc.i4.0
IL_0011: ldc.i4.5
IL_0012: newobj ""Sub Decimal..ctor(Integer, Integer, Integer, Boolean, Byte)""
IL_0017: call ""Function Decimal.Subtract(Decimal, Decimal) As Decimal""
IL_001c: callvirt ""Sub C.set_D(Decimal)""
IL_0021: ret
}
")
End Sub
<Fact>
Public Sub WhileStatement()
Const source = "
Class C
Sub M()
End Sub
End Class
"
Dim errorMessage As String = Nothing
Dim testData = EvaluateStatement(
source,
methodName:="C.M",
expr:=" While True :: End While",
errorMessage:=errorMessage)
Assert.Equal("error BC30035: Syntax error.", errorMessage) ' not the best error, but not worth modifying parsing to improve...
End Sub
Private Function EvaluateStatement(source As String, methodName As String, expr As String, <Out> ByRef errorMessage As String, Optional atLineNumber As Integer = -1) As CompilationTestData
Dim compilationFlags = DkmEvaluationFlags.None
If expr IsNot Nothing AndAlso expr.StartsWith("?", StringComparison.Ordinal) Then
' This mimics Immediate Window behavior...
compilationFlags = DkmEvaluationFlags.TreatAsExpression
expr = expr.Substring(1)
End If
Dim compilation0 = CreateCompilationWithReferences(
{Parse(source)},
{MscorlibRef_v4_0_30316_17626, SystemRef, MsvbRef},
options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(compilation0)
Dim context = CreateMethodContext(runtime, methodName, atLineNumber)
Dim testData = New CompilationTestData()
Dim resultProperties As ResultProperties = Nothing
Dim missingAssemblyIdentities As ImmutableArray(Of AssemblyIdentity) = Nothing
Dim result = context.CompileExpression(
expr,
compilationFlags,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
resultProperties,
errorMessage,
missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData)
Assert.Empty(missingAssemblyIdentities)
Return testData
End Function
End Class
End Namespace
|
VPashkov/roslyn
|
src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/StatementTests.vb
|
Visual Basic
|
apache-2.0
| 24,869
|
Public Class Form1
Dim WithEvents serialPort As New IO.Ports.SerialPort
Public jpeg_grab As Byte
Public myStr As String
Private Sub Form1_Load( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
For i As Integer = 0 To _
My.Computer.Ports.SerialPortNames.Count - 1
cbbCOMPorts.Items.Add( _
My.Computer.Ports.SerialPortNames(i))
Next
cbbCOMPorts.SelectedIndex = 0
baudBox.Items.Add("115200")
baudBox.Items.Add("57600")
baudBox.Items.Add("38400")
baudBox.Items.Add("28800")
baudBox.Items.Add("14400")
baudBox.Items.Add("9600")
baudBox.Items.Add("4800")
baudBox.Items.Add("2400")
baudBox.Items.Add("1200")
baudBox.SelectedIndex = 0
btnDisconnect.Enabled = False
jpeg_grab = 0
End Sub
Private Sub DataReceived( _
ByVal sender As Object, _
ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _
Handles serialPort.DataReceived
If (jpeg_grab = 0) Then
txtDataReceived.Invoke(New _
myDelegate(AddressOf updateTextBox), _
New Object() {})
End If
End Sub
Public Delegate Sub myDelegate()
Public Sub updateTextBox()
With txtDataReceived
.Font = New Font("Courier", 9.0!, FontStyle.Bold)
.SelectionColor = Color.Red
.AppendText(serialPort.ReadExisting)
.ScrollToCaret()
End With
End Sub
Private Sub StreamStop()
Try
Timer1.Stop()
serialPort.DiscardInBuffer()
serialPort.DiscardOutBuffer()
jpeg_grab = 0
Catch ex As Exception
End Try
End Sub
Private Sub grab_jpeg()
Try
Dim i As Integer
Dim buf() As Byte
jpeg_grab = 1
serialPort.DiscardInBuffer()
serialPort.Write("SJ" & vbCr)
serialPort.ReadTo("ACK" & vbCr)
myStr = serialPort.ReadTo("JPG_END" & vbCr & ":")
ReDim buf(myStr.Length())
For i = 0 To myStr.Length() - 1
buf(i) = CByte(Asc(myStr(i)))
Next
My.Computer.FileSystem.WriteAllBytes("test.jpg", buf, False)
jpeg_grab = 0
PictureBox1.ImageLocation = "test.jpg"
PictureBox1.Refresh()
Catch ex As Exception
MsgBox("Frame Grab Comm. Error")
StreamStop()
End Try
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If jpeg_grab = 1 Then
StreamStop()
MsgBox("Refresh Interval Too Short!")
Return
End If
grab_jpeg()
End Sub
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
If serialPort.IsOpen Then
serialPort.Close()
End If
Try
With serialPort
.PortName = cbbCOMPorts.Text
.BaudRate = Val(baudBox.SelectedItem().ToString())
.Parity = IO.Ports.Parity.None
.DataBits = 8
.StopBits = IO.Ports.StopBits.One
.ReadTimeout = Val(serialTOBox.Text())
'.Encoding = System.Text.Encoding.Unicode
.Encoding = System.Text.Encoding.Default
End With
serialPort.Open()
serialPort.DiscardInBuffer()
serialPort.DiscardOutBuffer()
lblMessage.Text = cbbCOMPorts.Text & " connected."
btnConnect.Enabled = False
btnDisconnect.Enabled = True
grabButton.Enabled = True
btnSend.Enabled = True
stopButton.Enabled = True
configPanel.Enabled = True
ServoPanel.Enabled = True
txtDataToSend.Focus()
Catch ex As Exception
MsgBox("Communication Error")
StreamStop()
End Try
End Sub
Private Sub btnDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnect.Click
Try
serialPort.Close()
lblMessage.Text = serialPort.PortName & " disconnected."
btnConnect.Enabled = True
btnDisconnect.Enabled = False
grabButton.Enabled = False
btnSend.Enabled = False
stopButton.Enabled = False
configPanel.Enabled = False
ServoPanel.Enabled = False
Catch ex As Exception
MsgBox("Communication Error")
StreamStop()
End Try
End Sub
Private Sub grabButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles grabButton.Click
serialPort.ReadTimeout = Val(serialTOBox.Text())
If stop_box1.Checked() = True Then
Timer1.Interval = Val(timerTimeout.Text())
Timer1.Start()
End If
grab_jpeg()
End Sub
Private Sub stopButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles stopButton.Click
Timer1.Stop()
End Sub
Private Sub CIFradio_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CIFradio.CheckedChanged
PictureBox1.Height = 288
PictureBox1.Width = 352
End Sub
Private Sub QCIFradio_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles QCIFradio.CheckedChanged
PictureBox1.Height = 144
PictureBox1.Width = 176
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
Try
serialPort.Write(txtDataToSend.Text & vbCr)
With txtDataReceived
.SelectionColor = Color.Black
.AppendText(txtDataToSend.Text & vbCr)
.ScrollToCaret()
End With
txtDataToSend.Text = String.Empty
Catch ex As Exception
MsgBox("Communication Error")
StreamStop()
End Try
End Sub
Private Sub vwSet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles vwSet.Click
serialPort.Write("VW " & X0_textbox.Text & " " & Y0_textbox.Text & " " & X1_textbox.Text & " " & Y1_textbox.Text & vbCr)
End Sub
Private Sub HiResRadio_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HiResRadio.CheckedChanged
serialPort.Write("HR 1" & vbCr)
End Sub
Private Sub loResRadio_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles loResRadio.CheckedChanged
If (configPanel.Enabled = True) Then
serialPort.Write("HR 0" & vbCr)
End If
End Sub
Private Sub RGBRadio_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RGBRadio.CheckedChanged
If (configPanel.Enabled = True) Then
serialPort.Write("CR 18 44" & vbCr)
End If
End Sub
Private Sub YCrCbButton_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles YCrCbButton.CheckedChanged
If (configPanel.Enabled = True) Then
serialPort.Write("CR 18 36" & vbCr)
End If
End Sub
Private Sub dsSetButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dsSetButton.Click
If (configPanel.Enabled = True) Then
serialPort.Write("DS " & dsX.Value & " " & dsY.Value & vbCr)
End If
End Sub
Private Sub TrackBar1_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar1.Scroll
servo0_textbox.Clear()
servo0_textbox.AppendText(TrackBar1.Value)
serialPort.Write("SV 0 " & servo0_textbox.Text & vbCr)
End Sub
Private Sub TrackBar2_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar2.Scroll
servo1_textbox.Clear()
servo1_textbox.AppendText(TrackBar2.Value)
serialPort.Write("SV 1 " & servo1_textbox.Text & vbCr)
End Sub
Private Sub TrackBar3_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar3.Scroll
servo2_textbox.Clear()
servo2_textbox.AppendText(TrackBar3.Value)
serialPort.Write("SV 2 " & servo2_textbox.Text & vbCr)
End Sub
Private Sub TrackBar4_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar4.Scroll
servo3_textbox.Clear()
servo3_textbox.AppendText(TrackBar4.Value)
serialPort.Write("SV 3 " & servo3_textbox.Text & vbCr)
End Sub
End Class
|
rcrowder/Burt
|
cmucam3_r556/cc3/tools/cc3_image_viewer/Form1.vb
|
Visual Basic
|
mit
| 8,900
|
'------------------------------------------------------------------------------
' <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 All_Sessions_By_Agent
'''<summary>
'''Sessions_by_Agent1 control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents Sessions_by_Agent1 As Global.BSAP_UI_WebForms.Sessions_by_Agent
End Class
|
burnsoftnet/BSApplicationProfiler
|
BSAP_UI_WebForms/BSAP_UI_WebForms/All_Sessions_By_Agent.aspx.designer.vb
|
Visual Basic
|
mit
| 777
|
Option Infer On
Imports System
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim environments As SolidEdgeFramework.Environments = 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)
' Get the environments collection.
environments = application.Environments
Dim count = environments.Count
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgeFramework.Environments.Count.vb
|
Visual Basic
|
mit
| 1,059
|
Imports System.Security
Imports System.Security.Cryptography
Imports System.IO
Imports System.Text
Imports System.Reflection
Module Hash
'File Hashing
Public Function fileMD5(ByVal fileName As String)
Dim md5 = Cryptography.MD5.Create
Dim md5hash As Byte()
Dim sysSB As New StringBuilder
Using st As New FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
md5hash = md5.ComputeHash(st)
End Using
For Each b In md5hash
sysSB.Append(b.ToString("X2"))
Next
Return sysSB.ToString
End Function
Public Function fileSHA1(ByVal fileName As String)
Dim sha1 = Cryptography.SHA1.Create
Dim sha1hash As Byte()
Dim sysSB As New StringBuilder
Using st As New FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
sha1hash = sha1.ComputeHash(st)
End Using
For Each b In sha1hash
sysSB.Append(b.ToString("X2"))
Next
Return sysSB.ToString
End Function
Public Function fileSHA256(ByVal fileName As String)
Dim sha256 = Cryptography.SHA256.Create
Dim sha256hash As Byte()
Dim sysSB As New StringBuilder
Using st As New FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
sha256hash = sha256.ComputeHash(st)
End Using
For Each b In sha256hash
sysSB.Append(b.ToString("X2"))
Next
Return sysSB.ToString
End Function
Public Function fileSHA512(ByVal fileName As String)
Dim sha512 = Cryptography.SHA512.Create
Dim sha512hash As Byte()
Dim sysSB As New StringBuilder
Using st As New FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
sha512hash = sha512.ComputeHash(st)
End Using
For Each b In sha512hash
sysSB.Append(b.ToString("X2"))
Next
Return sysSB.ToString
End Function
'String Hashing
Public Function stringSHA1(ByVal str As String)
Dim sha1 As New SHA1CryptoServiceProvider()
Dim sha1hash As Byte()
Dim sysSB1 As New StringBuilder
sha1hash = Encoding.ASCII.GetBytes(str)
sha1hash = sha1.ComputeHash(sha1hash)
For Each b In sha1hash
sysSB1.Append(b.ToString("X2"))
Next
Return sysSB1.ToString.ToLower()
End Function
End Module
|
TheDoxMedia/TDM-Hash-Calc
|
TDM Hash Calc/inc/Hash.vb
|
Visual Basic
|
mit
| 2,492
|
Public Module Person
Dim _Personen() As String = {"Alexander", "Karl der Große", "Siegfried", "Brünhilde", "Hagen", "Iwan der Schreckliche", "Helmut", "Dshingis Kahn", "Buffalo Bill", _
"Neil Amstrong", "Juri Gagarin", "Alf", "E.T.", "Albert Einstein", "Newton", "Kepler", "James Watt", "Archimedes"}
Dim _Count As Integer
Public ReadOnly Property Count As Integer
Get
Return _Count
End Get
End Property
Sub New()
_Count = _Personen.Length
End Sub
Public ReadOnly Property Item(ix As Integer) As String
Get
Return _Personen(ix)
End Get
End Property
End Module
|
mk-prg-net/mk-prg-net.lib
|
TextGenerator/Person.vb
|
Visual Basic
|
mit
| 704
|
''' <summary>
''' Builder for total section
''' </summary>
''' <remarks></remarks>
Friend Class TotalBuilder
Inherits BaseSectionBuilder
Public Sub New(section As IBaseSection, controller As ReportController)
Me.Section = section
Me.Controller = controller
End Sub
Protected Overrides Function CanBuild() As Boolean
Return Me.Controller.HasData AndAlso Me.Controller.LastRow
End Function
End Class
|
pagotti/vrx
|
Core/Engine/Sections/TotalBuilder.vb
|
Visual Basic
|
mit
| 449
|
Public Class ListeOrigineTransactions
Sub LoadOrigines()
Try
Dim cmd = Database.GetCommand
cmd.CommandText = "SELECT id, designation, description, type_origine FROM origine_transactions"
Dim result = cmd.ExecuteReader
ListOrigine.Items.Clear()
While result.Read
Dim item As New ListViewItem(result.GetValue(0).ToString)
item.SubItems.Add(result.GetValue(1).ToString)
item.SubItems.Add(result.GetValue(2).ToString)
If result.GetValue(3).ToString = "1" Then
item.SubItems.Add("RECETTE")
Else
item.SubItems.Add("DEPENSE")
End If
ListOrigine.Items.Add(item)
End While
result.Close()
cmd.Dispose()
cmd.Connection.Close()
Catch ex As Exception
If My.Settings.app_debug_mode Then
Util.ShowMessage(ex.ToString, 2)
Else
Util.ShowMessage("Echec de connexion à la base de données", 2)
End If
End Try
End Sub
Private Sub btnNouveau_Click(sender As Object, e As EventArgs) Handles btnNouveau.Click
Dim form As New OrigineTransactions
form.ShowDialog()
LoadOrigines()
End Sub
Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
If ListOrigine.SelectedItems.Count = 0 Then
Util.ShowMessage("Selectionner un element avant de continuer", 1)
Exit Sub
End If
Dim form As New OrigineTransactions
form.id = ListOrigine.SelectedItems(0).Text
form.ShowDialog()
LoadOrigines()
End Sub
Private Sub ListeOrigineTransactions_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Util.setupFrame(Me)
LoadOrigines()
End Sub
End Class
|
lepresk/HG
|
HG/ListeOrigineTransactions.vb
|
Visual Basic
|
mit
| 1,950
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' Bir bütünleştirilmiş koda ilişkin Genel Bilgiler aşağıdaki öznitelikler kümesiyle
' denetlenir. Bütünleştirilmiş kod ile ilişkili bilgileri değiştirmek için
' bu öznitelik değerlerini değiştirin.
' Bütünleştirilmiş kod özniteliklerinin değerlerini gözden geçirin
<Assembly: AssemblyTitle("SLight Optimize")>
<Assembly: AssemblyDescription("Safe your computer and for performance booster")>
<Assembly: AssemblyCompany("Pr0gramc2")>
<Assembly: AssemblyProduct("PcOptimize_v2")>
<Assembly: AssemblyCopyright("github.com/ssilistre")>
<Assembly: AssemblyTrademark("github.com/ssilistre")>
<Assembly: ComVisible(False)>
'Bu proje COM'un kullanımına sunulursa, aşağıdaki GUID tür kitaplığının kimliği içindir
<Assembly: Guid("675e78f0-b8aa-480b-baa3-c7764d990a4f")>
' Bir derlemenin sürüm bilgileri aşağıdaki dört değerden oluşur:
'
' Ana Sürüm
' İkincil Sürüm
' Yapı Numarası
' Düzeltme
'
' Tüm değerleri belirtebilir veya varsayılan Derleme ve Düzeltme Numaralarını kullanmak için
' '*' kullanarak varsayılana ayarlayabilirsiniz:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("2.0.0.0")>
<Assembly: AssemblyFileVersion("2.0.0.0")>
|
pr0gramc2/pcoptimize
|
PcOptimize_v2/PcOptimize_v2/My Project/AssemblyInfo.vb
|
Visual Basic
|
apache-2.0
| 1,360
|
Imports bv.model.BLToolkit
Imports bv.common
Imports bv.common.Diagnostics
Imports bv.common.Configuration
Imports eidss.model.Core
Imports System.IO
Imports bv.common.Core
Public Class ServiceBase
Private m_NotificationListenWorker As EmNotifyLstn
Private m_Subscribed As Boolean = False
Private m_EventProcessor As EventProcessor
Private m_ClientID As String
Private m_ConfigFile As String
Private m_TymerType As Integer
Private m_Credentials As ConnectionCredentials
Private m_TimerServiceAlive As Timers.Timer = Nothing
Public Delegate Sub DataRowEvent(ByVal sender As Object, ByVal row As DataRow, ByVal objectId As Object)
Private m_Started As Boolean = False
Private m_RestartTmr As Timers.Timer
''' <summary>
'''
''' </summary>
''' <param name="enabled"></param>
''' <remarks></remarks>
Private Sub ConnectionsEnabled(ByVal enabled As Boolean)
If (enabled) Then
m_NotificationListenWorker.Listen()
m_EventProcessor.Listen()
Else
m_NotificationListenWorker.Stop()
m_EventProcessor.Stop()
End If
End Sub
Public Sub SubscribeToAllEvents()
If Not m_Subscribed Then
Dim tempDb As New EmNotify_DB(m_Credentials, m_ClientID)
m_Subscribed = tempDb.SubscribeToAllEvents()
Try
Dim g As Guid = New Guid(tempDb.ClientID)
Catch ex As Exception
Trace.WriteLine(Trace.Kind.Warning, "Incorrect clientID:{0}", Utils.Str(tempDb.ClientID))
End Try
tempDb = Nothing
End If
End Sub
'Public ReadOnly Property Connection() As IDbConnection
' Get
' If Not m_EventProcessor Is Nothing Then
' Return m_EventProcessor.Connection
' End If
' Return Nothing
' End Get
'End Property
Public ReadOnly Property ServerName() As String
Get
Return m_Credentials.SQLServer
End Get
End Property
Private Sub TestConnection()
Using cn As New SqlClient.SqlConnection(m_Credentials.ConnectionString)
cn.Open()
cn.Close()
End Using
End Sub
Private m_LastRestartError As String
Private m_UpdateMessenger As AUM.UpdateMessenger
''' <summary>
'''
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Private ReadOnly Property UpdateMessenger() As AUM.UpdateMessenger
Get
Return m_UpdateMessenger
End Get
End Property
Private m_CanRunApplication As Boolean
Private Const AppCode As String = "ns"
Public Sub OnTimerServiceAlive(ByVal sender As Object, ByVal e As Timers.ElapsedEventArgs)
'refresh: service still alive
If Not UpdateMessenger.CanConnect() Then Return
UpdateMessenger.CreateRunningApps(EidssUserContext.ClientID, AppCode)
Dim isNotUpdateNow As Boolean = UpdateMessenger.CanRunApplication(EidssUserContext.ClientID, AppCode)
If (m_CanRunApplication <> isNotUpdateNow) Then
ConnectionsEnabled(isNotUpdateNow)
m_CanRunApplication = isNotUpdateNow
End If
End Sub
Public Sub OnTimerUpdate(ByVal sender As Object, ByVal e As Timers.ElapsedEventArgs)
'CheckForUpdates()
End Sub
Private Sub CheckForUpdates()
'Check for updates
Try
Dim dir As String = Utils.GetExecutingPath()
Dim updaterFilename As String = Path.Combine(dir, "bvupdater.exe")
Dim updaterDllFilename As String = Path.Combine(dir, "BVUpdate.dll")
If File.Exists(updaterFilename) And File.Exists(updaterDllFilename) Then
Using process As Process = New Process()
process.StartInfo = New ProcessStartInfo(updaterFilename)
process.StartInfo.Arguments = String.Format("\u \pns \a{0} \c{1} \s:""{2}""", Utils.Str(EidssUserContext.User.ID), EidssUserContext.ClientID, dir)
process.StartInfo.CreateNoWindow = True
process.StartInfo.ErrorDialog = False
process.StartInfo.RedirectStandardError = True
process.StartInfo.RedirectStandardInput = True
process.StartInfo.RedirectStandardOutput = True
process.StartInfo.UseShellExecute = False
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
process.Start()
'do some other things while you wait...
Threading.Thread.Sleep(10000) ' simulate doing other things...
process.StandardInput.WriteLine("exit") 'tell console to exit
If Not (process.HasExited) Then
process.WaitForExit(120000) 'give 2 minutes for process to finish
If Not (process.HasExited) Then process.Kill() 'took too long, kill it off
End If
End Using
End If
Catch ex As Exception
Dbg.Debug("CheckForUpdates {0}", ex.ToString)
End Try
End Sub
''' <summary>
'''
''' </summary>
''' <param name="timerType"></param>
''' <param name="configFile"></param>
''' <remarks></remarks>
Public Function Start(Optional ByVal timerType As Integer = 0, Optional ByVal configFile As String = Nothing) As Boolean
SecurityLog.AppName = "EIDSS Notification Service"
Dim serviceConfig As ServiceConfiguration = Nothing
Try
Trace.WriteLine(Trace.Kind.Info, "Notification Service is starting")
m_ConfigFile = configFile
m_TymerType = timerType
m_Credentials = New ConnectionCredentials(configFile)
serviceConfig = New ServiceConfiguration(configFile)
serviceConfig.ReadConfiguration()
TestConnection()
DbManagerFactory.SetSqlFactory(m_Credentials.ConnectionString)
If Utils.Str(serviceConfig.ClientID) = "" Then
m_ClientID = EidssUserContext.ClientID
Else
m_ClientID = serviceConfig.ClientID
End If
SubscribeToAllEvents()
m_NotificationListenWorker = New EmNotifyLstn(configFile)
m_NotificationListenWorker.Listen()
JobAccessor.Instance = New JobAccessor(m_Credentials.SQLServer, m_Credentials.SQLUser, m_Credentials.SQLPassword)
Trace.WriteLine(Trace.Kind.Info, "Ntfy_Start: Notification listener is started for database {0}\{1}", m_Credentials.SQLServer, m_Credentials.SQLDatabase)
m_EventProcessor = New EventProcessor(configFile)
m_EventProcessor.Listen()
'AUM messenger init
m_UpdateMessenger = New AUM.UpdateMessenger(m_Credentials)
'set record from journal
If (UpdateMessenger.CanConnect()) Then
If Not (UpdateMessenger.CanRunApplication(EidssUserContext.ClientID, AppCode)) Then Return False
UpdateMessenger.CreateRunningApps(EidssUserContext.ClientID, AppCode)
End If
m_CanRunApplication = True
'create timer, which refresh service alive status
m_TimerServiceAlive = UpdateMessenger.CreateTimerListener()
AddHandler m_TimerServiceAlive.Elapsed, AddressOf OnTimerServiceAlive
m_TimerServiceAlive.Start()
m_Started = True
EidssUserContext.User.IsAuthenticated = True
Trace.WriteLine(Trace.Kind.Info, "Notification Service is started successfully")
Catch ex As Exception
EidssUserContext.User.IsAuthenticated = False
Dim actualException As Exception = ex
If Not ex.InnerException Is Nothing Then
actualException = ex.InnerException
End If
Dim errorText As String
If TypeOf (actualException) Is SqlClient.SqlException Then
errorText = CType(actualException, SqlClient.SqlException).ErrorCode.ToString
Else
errorText = actualException.Message
End If
If m_LastRestartError <> errorText Then
Trace.WriteLine(Trace.Kind.Error, "Notification Service start fault:", actualException)
Trace.WriteLine(Trace.Kind.Info, "Notification Service start is not started for database {0}\{1} and user {2}", m_Credentials.SQLServer, m_Credentials.SQLDatabase, m_Credentials.SQLUser)
Else
Trace.WriteLine(Trace.Kind.Info, "Notification Service start is not started for database {0}\{1} and user {2}", m_Credentials.SQLServer, m_Credentials.SQLDatabase, m_Credentials.SQLUser)
End If
m_LastRestartError = errorText
Finish()
m_Started = False
If m_RestartTmr Is Nothing Then
m_RestartTmr = New Timers.Timer
End If
m_RestartTmr.AutoReset = False
AddHandler m_RestartTmr.Elapsed, AddressOf RestartProc
If serviceConfig IsNot Nothing Then
m_RestartTmr.Interval = serviceConfig.RestartInterval
Else
m_RestartTmr.Interval = 30000
End If
m_RestartTmr.Start()
End Try
Return True
End Function
Public Sub Finish()
' Add code here to perform any tear-down necessary to stop your service.
If Not m_NotificationListenWorker Is Nothing Then
m_NotificationListenWorker.Stop()
End If
If Not m_EventProcessor Is Nothing Then
m_EventProcessor.Stop()
End If
If Not m_EventProcessor Is Nothing AndAlso Not m_OnEventOccured Is Nothing Then
RemoveHandler m_EventProcessor.EventOccured, m_OnEventOccured
End If
If Not m_NotificationListenWorker Is Nothing AndAlso Not m_OnNotificationReceived Is Nothing Then
RemoveHandler m_NotificationListenWorker.NotificationReceived, m_OnNotificationReceived
End If
'delete record from journal
If Not UpdateMessenger Is Nothing Then
UpdateMessenger.DeleteRunningApps(EidssUserContext.ClientID, AppCode)
End If
End Sub
Private m_OnNotificationReceived As DataRowEvent
Public Property OnNotificationReceived() As DataRowEvent
Get
Return m_OnNotificationReceived
End Get
Set(ByVal value As DataRowEvent)
m_OnNotificationReceived = value
If Not m_NotificationListenWorker Is Nothing AndAlso Not m_OnNotificationReceived Is Nothing Then
AddHandler m_NotificationListenWorker.NotificationReceived, m_OnNotificationReceived
End If
End Set
End Property
Private m_OnEventOccured As DataRowEvent
Public Property OnEventOccured() As DataRowEvent
Get
Return m_OnEventOccured
End Get
Set(ByVal value As DataRowEvent)
m_OnEventOccured = value
If Not m_EventProcessor Is Nothing AndAlso Not m_OnEventOccured Is Nothing Then
AddHandler m_EventProcessor.EventOccured, m_OnEventOccured
End If
End Set
End Property
Public Sub SkipExistingEvents()
If Not m_EventProcessor Is Nothing Then
m_EventProcessor.SkipExistingEvents()
End If
End Sub
Private Sub RestartProc(ByVal sender As Object, ByVal e As Timers.ElapsedEventArgs)
RemoveHandler CType(sender, Timers.Timer).Elapsed, AddressOf RestartProc
If m_Started Then
Return
End If
CType(sender, Timers.Timer).Stop()
MemoryManager.Flush(True)
EidssUserContext.User.IsAuthenticated = False
Start(m_TymerType, m_ConfigFile)
End Sub
End Class
|
EIDSS/EIDSS-Legacy
|
EIDSS v5/vb/EIDSS/EIDSS_NOTIFICATION_SVC/ServiceBase.vb
|
Visual Basic
|
bsd-2-clause
| 12,232
|
Imports Xunit
Public Class InvalidPropertyDataReference
' TEST: PropertyData attribute value should be marked invalid
<Theory(Skip:="Invalid PropertyDataAttribute")>
<MemberData("InvalidAccessibilityTheoryDataEnumerator")>
Public Sub UsingInvalidDataProperty(ByVal value As Int32)
Throw New InvalidOperationException("Should not run")
End Sub
End Class
|
derigel23/resharper-xunit
|
resharper/tests.manual/tests.xunit.vb/tests.xunit.eyeball.vb/PropertyDataReferences/InvalidPropertyDataReference.vb
|
Visual Basic
|
apache-2.0
| 386
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Runtime.InteropServices
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeStyle
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Editor.Shared.Options
Imports Microsoft.CodeAnalysis.ExtractMethod
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Shared.Options
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.SymbolSearch
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
<ComVisible(True)>
Public Class AutomationObject
Private ReadOnly _workspace As Workspace
Friend Sub New(workspace As Workspace)
_workspace = workspace
End Sub
Public Property AutoComment As Boolean
Get
Return GetBooleanOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration)
End Get
Set(value As Boolean)
SetBooleanOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration, value)
End Set
End Property
Public Property AutoEndInsert As Boolean
Get
Return GetBooleanOption(FeatureOnOffOptions.EndConstruct)
End Get
Set(value As Boolean)
SetBooleanOption(FeatureOnOffOptions.EndConstruct, value)
End Set
End Property
Public Property AutoRequiredMemberInsert As Boolean
Get
Return GetBooleanOption(FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers)
End Get
Set(value As Boolean)
SetBooleanOption(FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers, value)
End Set
End Property
<Obsolete("This SettingStore option has now been deprecated in favor of BasicClosedFileDiagnostics")>
Public Property ClosedFileDiagnostics As Boolean
Get
Return ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(_workspace.Options, LanguageNames.VisualBasic)
End Get
Set(value As Boolean)
' Even though this option has been deprecated, we want to respect the setting if the user has explicitly turned off closed file diagnostics (which is the non-default value for 'ClosedFileDiagnostics').
' So, we invoke the setter only for value = False.
If Not value Then
SetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, value:=0)
End If
End Set
End Property
Public Property BasicClosedFileDiagnostics As Integer
Get
Return GetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic)
End Get
Set(value As Integer)
SetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, value)
End Set
End Property
Public Property RenameTrackingPreview As Boolean
Get
Return GetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview)
End Get
Set(value As Boolean)
SetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview, value)
End Set
End Property
Public Property DisplayLineSeparators As Boolean
Get
Return GetBooleanOption(FeatureOnOffOptions.LineSeparator)
End Get
Set(value As Boolean)
SetBooleanOption(FeatureOnOffOptions.LineSeparator, value)
End Set
End Property
Public Property EnableHighlightReferences As Boolean
Get
Return GetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting)
End Get
Set(value As Boolean)
SetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting, value)
End Set
End Property
Public Property EnableHighlightRelatedKeywords As Boolean
Get
Return GetBooleanOption(FeatureOnOffOptions.KeywordHighlighting)
End Get
Set(value As Boolean)
SetBooleanOption(FeatureOnOffOptions.KeywordHighlighting, value)
End Set
End Property
Public Property ExtractMethod_DoNotPutOutOrRefOnStruct As Boolean
Get
Return GetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct)
End Get
Set(value As Boolean)
SetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, value)
End Set
End Property
Public Property ExtractMethod_AllowMovingDeclaration As Boolean
Get
Return GetBooleanOption(ExtractMethodOptions.AllowMovingDeclaration)
End Get
Set(value As Boolean)
SetBooleanOption(ExtractMethodOptions.AllowMovingDeclaration, value)
End Set
End Property
Public Property Outlining As Boolean
Get
Return GetBooleanOption(FeatureOnOffOptions.Outlining)
End Get
Set(value As Boolean)
SetBooleanOption(FeatureOnOffOptions.Outlining, value)
End Set
End Property
Public Property PrettyListing As Boolean
Get
Return GetBooleanOption(FeatureOnOffOptions.PrettyListing)
End Get
Set(value As Boolean)
SetBooleanOption(FeatureOnOffOptions.PrettyListing, value)
End Set
End Property
Public Property Style_PreferIntrinsicPredefinedTypeKeywordInDeclaration_CodeStyle As String
Get
Return GetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration)
End Get
Set(value As String)
SetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, value)
End Set
End Property
Public Property Style_PreferIntrinsicPredefinedTypeKeywordInMemberAccess_CodeStyle As String
Get
Return GetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess)
End Get
Set(value As String)
SetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, value)
End Set
End Property
Public Property Style_QualifyFieldAccess As String
Get
Return GetXmlOption(CodeStyleOptions.QualifyFieldAccess)
End Get
Set(value As String)
SetXmlOption(CodeStyleOptions.QualifyFieldAccess, value)
End Set
End Property
Public Property Style_QualifyPropertyAccess As String
Get
Return GetXmlOption(CodeStyleOptions.QualifyPropertyAccess)
End Get
Set(value As String)
SetXmlOption(CodeStyleOptions.QualifyPropertyAccess, value)
End Set
End Property
Public Property Style_QualifyMethodAccess As String
Get
Return GetXmlOption(CodeStyleOptions.QualifyMethodAccess)
End Get
Set(value As String)
SetXmlOption(CodeStyleOptions.QualifyMethodAccess, value)
End Set
End Property
Public Property Style_QualifyEventAccess As String
Get
Return GetXmlOption(CodeStyleOptions.QualifyEventAccess)
End Get
Set(value As String)
SetXmlOption(CodeStyleOptions.QualifyEventAccess, value)
End Set
End Property
Public Property Style_PreferThrowExpression As String
Get
Return GetXmlOption(CodeStyleOptions.PreferThrowExpression)
End Get
Set(value As String)
SetXmlOption(CodeStyleOptions.PreferThrowExpression, value)
End Set
End Property
Public Property Style_PreferObjectInitializer As String
Get
Return GetXmlOption(CodeStyleOptions.PreferObjectInitializer)
End Get
Set(value As String)
SetXmlOption(CodeStyleOptions.PreferObjectInitializer, value)
End Set
End Property
Public Property Style_PreferCollectionInitializer As String
Get
Return GetXmlOption(CodeStyleOptions.PreferCollectionInitializer)
End Get
Set(value As String)
SetXmlOption(CodeStyleOptions.PreferCollectionInitializer, value)
End Set
End Property
Public Property Style_PreferCoalesceExpression As String
Get
Return GetXmlOption(CodeStyleOptions.PreferCoalesceExpression)
End Get
Set(value As String)
SetXmlOption(CodeStyleOptions.PreferCoalesceExpression, value)
End Set
End Property
Public Property Style_PreferNullPropagation As String
Get
Return GetXmlOption(CodeStyleOptions.PreferNullPropagation)
End Get
Set(value As String)
SetXmlOption(CodeStyleOptions.PreferNullPropagation, value)
End Set
End Property
Public Property Style_PreferInlinedVariableDeclaration As String
Get
Return GetXmlOption(CodeStyleOptions.PreferInlinedVariableDeclaration)
End Get
Set(value As String)
SetXmlOption(CodeStyleOptions.PreferInlinedVariableDeclaration, value)
End Set
End Property
Public Property Style_PreferExplicitTupleNames As String
Get
Return GetXmlOption(CodeStyleOptions.PreferExplicitTupleNames)
End Get
Set(value As String)
SetXmlOption(CodeStyleOptions.PreferExplicitTupleNames, value)
End Set
End Property
Public Property Option_PlaceSystemNamespaceFirst As Boolean
Get
Return GetBooleanOption(GenerationOptions.PlaceSystemNamespaceFirst)
End Get
Set(value As Boolean)
SetBooleanOption(GenerationOptions.PlaceSystemNamespaceFirst, value)
End Set
End Property
Public Property Option_SuggestImportsForTypesInReferenceAssemblies As Boolean
Get
Return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies)
End Get
Set(value As Boolean)
SetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, value)
End Set
End Property
Public Property Option_SuggestImportsForTypesInNuGetPackages As Boolean
Get
Return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages)
End Get
Set(value As Boolean)
SetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, value)
End Set
End Property
Private Function GetBooleanOption(key As [PerLanguageOption](Of Boolean)) As Boolean
Return _workspace.Options.GetOption(key, LanguageNames.VisualBasic)
End Function
Private Function GetXmlOption(key As PerLanguageOption(Of CodeStyleOption(Of Boolean))) As String
Return _workspace.Options.GetOption(key, LanguageNames.VisualBasic).ToXElement().ToString()
End Function
Private Sub SetBooleanOption(key As [PerLanguageOption](Of Boolean), value As Boolean)
_workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.VisualBasic, value)
End Sub
Private Function GetBooleanOption(key As PerLanguageOption(Of Boolean?)) As Integer
Dim [option] = _workspace.Options.GetOption(key, LanguageNames.VisualBasic)
If Not [option].HasValue Then
Return -1
End If
Return If([option].Value, 1, 0)
End Function
Private Sub SetBooleanOption(key As PerLanguageOption(Of Boolean?), value As Integer)
Dim boolValue As Boolean? = If(value < 0, Nothing, value > 0)
_workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.VisualBasic, boolValue)
End Sub
Private Sub SetXmlOption(key As PerLanguageOption(Of CodeStyleOption(Of Boolean)), value As String)
Dim convertedValue = CodeStyleOption(Of Boolean).FromXElement(XElement.Parse(value))
_workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.VisualBasic, convertedValue)
End Sub
End Class
End Namespace
|
kelltrick/roslyn
|
src/VisualStudio/VisualBasic/Impl/Options/AutomationObject.vb
|
Visual Basic
|
apache-2.0
| 13,010
|
' 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.
' vbc /t:module /out:Source3Module.netmodule /vbruntime- Source3.vb /r:c1.dll,c4.dll,c7.dll
' vbc /t:library /out:c3.dll /vbruntime- Source3.vb /r:c1.dll,c4.dll,c7.dll
Public Class C3
Public Function Goo() As C1(Of C3).C2(Of C4)
Return Nothing
End Function
Public Shared Function Bar() As C6(Of C4)
Return Nothing
End Function
Public Function Goo1() As C8(Of C7)
Return Nothing
End Function
Public Sub Goo2(ByRef x1(,) As C300,
<System.Runtime.InteropServices.Out()> ByRef x2 As C4,
ByRef x3() As C7,
Optional ByVal x4 As C4 = Nothing)
End Sub
Friend Overridable Function Goo3(Of TGoo3 As C4)() As TGoo3
Return Nothing
End Function
Public Function Goo4() As C8(Of C4)
Return Nothing
End Function
Public MustInherit Class C301
Implements I1
End Class
Friend Class C302
End Class
End Class
Public Class C6(Of T As New)
End Class
Public Class C300
End Class
Public Interface I1
End Interface
Namespace ns1
Namespace ns2
Public Class C303
End Class
End Namespace
Public Class C304
Public Class C305
End Class
End Class
End Namespace
|
physhi/roslyn
|
src/Compilers/Test/Resources/Core/SymbolsTests/MultiTargeting/Source3.vb
|
Visual Basic
|
apache-2.0
| 1,476
|
Imports Scheduler
Imports HomeSeerAPI
Imports HSCF.Communication.Scs.Communication.EndPoints.Tcp
Imports HSCF.Communication.ScsServices.Client
Imports HSCF.Communication.ScsServices.Service
Module Main
Public WithEvents client As HSCF.Communication.ScsServices.Client.IScsServiceClient(Of IHSApplication)
Dim WithEvents clientCallback As HSCF.Communication.ScsServices.Client.IScsServiceClient(Of IAppCallbackAPI)
Private host As HomeSeerAPI.IHSApplication
Private gAppAPI As HSPI = Nothing
Sub Main()
Dim sIp As String = "127.0.0.1"
Dim argv As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
argv = My.Application.CommandLineArgs
Dim sCmd As String
For Each sCmd In argv
Dim ch(0) As String
ch(0) = "="
Dim parts() As String = sCmd.Split(ch, StringSplitOptions.None)
Select Case parts(0).ToLower
Case "server" : sIp = parts(1)
Case "instance"
Try
Instance = parts(1)
Catch ex As Exception
Instance = ""
End Try
End Select
Next
gAppAPI = New HSPI
Console.WriteLine("Connecting to server at " & sIp & "...")
client = ScsServiceClientBuilder.CreateClient(Of IHSApplication)(New ScsTcpEndPoint(sIp, 10400), gAppAPI)
clientCallback = ScsServiceClientBuilder.CreateClient(Of IAppCallbackAPI)(New ScsTcpEndPoint(sIp, 10400), gAppAPI)
Dim Attempts As Integer = 1
TryAgain:
Try
client.Connect()
clientCallback.Connect()
host = client.ServiceProxy
Dim APIVersion As Double = host.APIVersion ' will cause an error if not really connected
callback = clientCallback.ServiceProxy
APIVersion = callback.APIVersion ' will cause an error if not really connected
Catch ex As Exception
Console.WriteLine("Cannot connect attempt " & Attempts.ToString & ": " & ex.Message)
If ex.Message.ToLower.Contains("timeout occurred.") Then
Attempts += 1
If Attempts < 6 Then GoTo TryAgain
End If
If client IsNot Nothing Then
client.Dispose()
client = Nothing
End If
If clientCallback IsNot Nothing Then
clientCallback.Dispose()
clientCallback = Nothing
End If
wait(4)
Return
End Try
Try
' create the user object that is the real plugin, accessed from the pluginAPI wrapper
callback = callback
hs = host
' connect to HS so it can register a callback to us
host.Connect(IFACE_NAME, "")
Console.WriteLine("Connected, waiting to be initialized...")
Do
Threading.Thread.Sleep(30)
Loop While client.CommunicationState = HSCF.Communication.Scs.Communication.CommunicationStates.Connected And Not bShutDown
If Not bShutDown Then
gAppAPI.ShutdownIO()
Console.WriteLine("Connection lost, exiting")
Else
Console.WriteLine("Shutting down plugin")
End If
' disconnect from server for good here
client.Disconnect()
clientCallback.Disconnect()
wait(2)
End
Catch ex As Exception
Console.WriteLine("Cannot connect(2): " & ex.Message)
wait(2)
End
Return
End Try
End Sub
Private Sub client_Disconnected(ByVal sender As Object, ByVal e As System.EventArgs) Handles client.Disconnected
Console.WriteLine("Disconnected from server - client")
End Sub
Private Sub wait(ByVal secs As Integer)
Threading.Thread.Sleep(secs * 1000)
End Sub
End Module
|
alexdresko/HSPI
|
Templates/HspiSampleTemplate.Dev/main.vb
|
Visual Basic
|
mit
| 4,000
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace DotNetNuke.Modules.Feedback
Partial Public Class Settings
'''<summary>
'''valSummary control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents valSummary As Global.System.Web.UI.WebControls.ValidationSummary
'''<summary>
'''plSendTo control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSendTo As Global.System.Web.UI.UserControl
'''<summary>
'''txtSendTo control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtSendTo As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''valSendTo control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents valSendTo As Global.System.Web.UI.WebControls.RegularExpressionValidator
'''<summary>
'''plSendToRoles control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSendToRoles As Global.System.Web.UI.UserControl
'''<summary>
'''dgSelectedRoles control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents dgSelectedRoles As Global.DotNetNuke.UI.WebControls.RolesSelectionGrid
'''<summary>
'''plSendFrom control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSendFrom As Global.System.Web.UI.UserControl
'''<summary>
'''txtSendFrom control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtSendFrom As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''valSendFrom control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents valSendFrom As Global.System.Web.UI.WebControls.RegularExpressionValidator
'''<summary>
'''plSendCopy control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSendCopy As Global.System.Web.UI.UserControl
'''<summary>
'''chkSendCopy control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkSendCopy As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plOptout control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plOptout As Global.System.Web.UI.UserControl
'''<summary>
'''chkOptout control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkOptout As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plAsync control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plAsync As Global.System.Web.UI.UserControl
'''<summary>
'''chkAsync control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkAsync As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plCategory control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plCategory As Global.System.Web.UI.UserControl
'''<summary>
'''cboCategory control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents cboCategory As Global.System.Web.UI.WebControls.DropDownList
'''<summary>
'''plCategorySelectable control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plCategorySelectable As Global.System.Web.UI.UserControl
'''<summary>
'''chkCategory control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkCategory As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''valCategory control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents valCategory As Global.System.Web.UI.WebControls.CustomValidator
'''<summary>
'''plCategoryReq control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plCategoryReq As Global.System.Web.UI.UserControl
'''<summary>
'''chkCategoryReq control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkCategoryReq As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plUseCategoryAsEmail control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plUseCategoryAsEmail As Global.System.Web.UI.UserControl
'''<summary>
'''chkCategoryMailto control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkCategoryMailto As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''valCategoryMailto control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents valCategoryMailto As Global.System.Web.UI.WebControls.CustomValidator
'''<summary>
'''plLabelDisplay control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plLabelDisplay As Global.System.Web.UI.UserControl
'''<summary>
'''rblLabelDisplay control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents rblLabelDisplay As Global.System.Web.UI.WebControls.RadioButtonList
'''<summary>
'''plWidth control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plWidth As Global.System.Web.UI.UserControl
'''<summary>
'''txtWidth control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtWidth As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''valWidth control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents valWidth As Global.System.Web.UI.WebControls.RegularExpressionValidator
'''<summary>
'''plSubject control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSubject As Global.System.Web.UI.UserControl
'''<summary>
'''cboSubject control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents cboSubject As Global.System.Web.UI.WebControls.DropDownList
'''<summary>
'''plSubjectEditField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSubjectEditField As Global.System.Web.UI.UserControl
'''<summary>
'''rblSubjectEditField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents rblSubjectEditField As Global.System.Web.UI.WebControls.RadioButtonList
'''<summary>
'''plEmailField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plEmailField As Global.System.Web.UI.UserControl
'''<summary>
'''rblEmailField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents rblEmailField As Global.System.Web.UI.WebControls.RadioButtonList
'''<summary>
'''plEmailConfirmField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plEmailConfirmField As Global.System.Web.UI.UserControl
'''<summary>
'''rblEmailConfirmField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents rblEmailConfirmField As Global.System.Web.UI.WebControls.RadioButtonList
'''<summary>
'''plNameField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plNameField As Global.System.Web.UI.UserControl
'''<summary>
'''rblNameField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents rblNameField As Global.System.Web.UI.WebControls.RadioButtonList
'''<summary>
'''plStreetField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plStreetField As Global.System.Web.UI.UserControl
'''<summary>
'''rblStreetField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents rblStreetField As Global.System.Web.UI.WebControls.RadioButtonList
'''<summary>
'''plCityField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plCityField As Global.System.Web.UI.UserControl
'''<summary>
'''rblCityField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents rblCityField As Global.System.Web.UI.WebControls.RadioButtonList
'''<summary>
'''plRegionField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plRegionField As Global.System.Web.UI.UserControl
'''<summary>
'''rblRegionField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents rblRegionField As Global.System.Web.UI.WebControls.RadioButtonList
'''<summary>
'''plCountryField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plCountryField As Global.System.Web.UI.UserControl
'''<summary>
'''rblCountryField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents rblCountryField As Global.System.Web.UI.WebControls.RadioButtonList
'''<summary>
'''plPostalCodeField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plPostalCodeField As Global.System.Web.UI.UserControl
'''<summary>
'''rblPostalCodeField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents rblPostalCodeField As Global.System.Web.UI.WebControls.RadioButtonList
'''<summary>
'''plTelephoneField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plTelephoneField As Global.System.Web.UI.UserControl
'''<summary>
'''rblTelephoneField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents rblTelephoneField As Global.System.Web.UI.WebControls.RadioButtonList
'''<summary>
'''plMessageField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plMessageField As Global.System.Web.UI.UserControl
'''<summary>
'''rblMessageField control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents rblMessageField As Global.System.Web.UI.WebControls.RadioButtonList
'''<summary>
'''plEmailRegex control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plEmailRegex As Global.System.Web.UI.UserControl
'''<summary>
'''txtEmailRegex control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtEmailRegex As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''btnResetEmailRegex control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents btnResetEmailRegex As Global.System.Web.UI.WebControls.Button
'''<summary>
'''valEmailRegex control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents valEmailRegex As Global.System.Web.UI.WebControls.RequiredFieldValidator
'''<summary>
'''plPostalCodeRegex control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plPostalCodeRegex As Global.System.Web.UI.UserControl
'''<summary>
'''txtPostalCodeRegex control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtPostalCodeRegex As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''btnResetPostalCodeRegex control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents btnResetPostalCodeRegex As Global.System.Web.UI.WebControls.Button
'''<summary>
'''plTelephoneRegex control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plTelephoneRegex As Global.System.Web.UI.UserControl
'''<summary>
'''txtTelephoneRegex control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtTelephoneRegex As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''btnResetTelephoneRegex control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents btnResetTelephoneRegex As Global.System.Web.UI.WebControls.Button
'''<summary>
'''plRows control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plRows As Global.System.Web.UI.UserControl
'''<summary>
'''txtrows control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtrows As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''valRows control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents valRows As Global.System.Web.UI.WebControls.RegularExpressionValidator
'''<summary>
'''plMaxMessage control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plMaxMessage As Global.System.Web.UI.UserControl
'''<summary>
'''txtMaxMessage control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtMaxMessage As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''valMaxMessage control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents valMaxMessage As Global.System.Web.UI.WebControls.RegularExpressionValidator
'''<summary>
'''plCaptchaVisibility control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plCaptchaVisibility As Global.System.Web.UI.UserControl
'''<summary>
'''rblCaptchaVisibility control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents rblCaptchaVisibility As Global.System.Web.UI.WebControls.RadioButtonList
'''<summary>
'''plNoCaptcha control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plNoCaptcha As Global.System.Web.UI.UserControl
'''<summary>
'''chkNoCaptcha control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkNoCaptcha As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plNoCaptchaSiteKey control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plNoCaptchaSiteKey As Global.System.Web.UI.UserControl
'''<summary>
'''txtNoCaptchaSiteKey control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtNoCaptchaSiteKey As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''valNoCaptchaSiteKey control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents valNoCaptchaSiteKey As Global.System.Web.UI.WebControls.RequiredFieldValidator
'''<summary>
'''plNoCaptchaSecretKey control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plNoCaptchaSecretKey As Global.System.Web.UI.UserControl
'''<summary>
'''txtNoCaptchaSecretKey control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtNoCaptchaSecretKey As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''valNoCaptchaSecretKey control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents valNoCaptchaSecretKey As Global.System.Web.UI.WebControls.RequiredFieldValidator
'''<summary>
'''plRepeatSubmissionFilter control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plRepeatSubmissionFilter As Global.System.Web.UI.UserControl
'''<summary>
'''rblRepeatSubmissionFilter control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents rblRepeatSubmissionFilter As Global.System.Web.UI.WebControls.RadioButtonList
'''<summary>
'''plMinSubmissionInteval control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plMinSubmissionInteval As Global.System.Web.UI.UserControl
'''<summary>
'''txtMinSubmissionInteval control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtMinSubmissionInteval As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''valMinSubmissionInteval control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents valMinSubmissionInteval As Global.System.Web.UI.WebControls.RegularExpressionValidator
'''<summary>
'''plDuplicateSubmission control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plDuplicateSubmission As Global.System.Web.UI.UserControl
'''<summary>
'''chkDuplicateSubmission control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkDuplicateSubmission As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plRedirectTabOnSubmission control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plRedirectTabOnSubmission As Global.System.Web.UI.UserControl
'''<summary>
'''ddlRedirectTabOnSubmission control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents ddlRedirectTabOnSubmission As Global.System.Web.UI.WebControls.DropDownList
'''<summary>
'''plAkismetEnable control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plAkismetEnable As Global.System.Web.UI.UserControl
'''<summary>
'''chkAkismetEnable control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkAkismetEnable As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plAkismetKey control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plAkismetKey As Global.System.Web.UI.UserControl
'''<summary>
'''txtAkismetKey control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtAkismetKey As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''valAkismetKey control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents valAkismetKey As Global.System.Web.UI.WebControls.CustomValidator
'''<summary>
'''plAkismetSendModerator control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plAkismetSendModerator As Global.System.Web.UI.UserControl
'''<summary>
'''chkAkismetSendModerator control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkAkismetSendModerator As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plScope control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plScope As Global.System.Web.UI.UserControl
'''<summary>
'''rblScope control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents rblScope As Global.System.Web.UI.WebControls.RadioButtonList
'''<summary>
'''divOrphanedData control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents divOrphanedData As Global.System.Web.UI.HtmlControls.HtmlGenericControl
'''<summary>
'''plOrphanedData control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plOrphanedData As Global.System.Web.UI.UserControl
'''<summary>
'''dgOrphanedData control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents dgOrphanedData As Global.System.Web.UI.WebControls.DataGrid
'''<summary>
'''cmdDeleteOrphanedData control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents cmdDeleteOrphanedData As Global.System.Web.UI.WebControls.Button
'''<summary>
'''plModerated control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plModerated As Global.System.Web.UI.UserControl
'''<summary>
'''chkModerated control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkModerated As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plModerationAdminEmails control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plModerationAdminEmails As Global.System.Web.UI.UserControl
'''<summary>
'''chkModerationAdminEmails control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkModerationAdminEmails As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''divEmailOnly control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents divEmailOnly As Global.System.Web.UI.HtmlControls.HtmlGenericControl
'''<summary>
'''plEmailOnly control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plEmailOnly As Global.System.Web.UI.UserControl
'''<summary>
'''chkEmailOnly control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkEmailOnly As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''divSendWhenPublished control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents divSendWhenPublished As Global.System.Web.UI.HtmlControls.HtmlGenericControl
'''<summary>
'''plSendWhenPublished control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSendWhenPublished As Global.System.Web.UI.UserControl
'''<summary>
'''chkSendWhenPublished control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkSendWhenPublished As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''divModerationCategories control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents divModerationCategories As Global.System.Web.UI.HtmlControls.HtmlGenericControl
'''<summary>
'''plModerationCategory control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plModerationCategory As Global.System.Web.UI.UserControl
'''<summary>
'''cblModerationCategories control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents cblModerationCategories As Global.System.Web.UI.WebControls.CheckBoxList
'''<summary>
'''divUnmoderatedStatus control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents divUnmoderatedStatus As Global.System.Web.UI.HtmlControls.HtmlGenericControl
'''<summary>
'''plUnmoderatedStatus control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plUnmoderatedStatus As Global.System.Web.UI.UserControl
'''<summary>
'''ddlUnmoderatedStatus control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents ddlUnmoderatedStatus As Global.System.Web.UI.WebControls.DropDownList
'''<summary>
'''plPrintTemplate control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plPrintTemplate As Global.System.Web.UI.UserControl
'''<summary>
'''txtPrintTemplate control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtPrintTemplate As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''btnLoadDefaultPrintTemplate control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents btnLoadDefaultPrintTemplate As Global.System.Web.UI.WebControls.Button
'''<summary>
'''plPrintAction control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plPrintAction As Global.System.Web.UI.UserControl
'''<summary>
'''rblPrintAction control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents rblPrintAction As Global.System.Web.UI.WebControls.RadioButtonList
'''<summary>
'''plModerationPageSize control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plModerationPageSize As Global.System.Web.UI.UserControl
'''<summary>
'''ddlModerationPageSize control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents ddlModerationPageSize As Global.System.Web.UI.WebControls.DropDownList
'''<summary>
'''plCleanupPending control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plCleanupPending As Global.System.Web.UI.UserControl
'''<summary>
'''chkCleanupPending control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkCleanupPending As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plCleanupPrivate control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plCleanupPrivate As Global.System.Web.UI.UserControl
'''<summary>
'''chkCleanupPrivate control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkCleanupPrivate As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plCleanupPublished control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plCleanupPublished As Global.System.Web.UI.UserControl
'''<summary>
'''chkCleanupPublished control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkCleanupPublished As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plCleanupArchived control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plCleanupArchived As Global.System.Web.UI.UserControl
'''<summary>
'''chkCleanupArchived control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkCleanupArchived As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plCleanupSpam control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plCleanupSpam As Global.System.Web.UI.UserControl
'''<summary>
'''chkCleanupSpam control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkCleanupSpam As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plCleanupDaysBefore control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plCleanupDaysBefore As Global.System.Web.UI.UserControl
'''<summary>
'''txtCleanupDaysBefore control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtCleanupDaysBefore As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''Regularexpressionvalidator1 control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents Regularexpressionvalidator1 As Global.System.Web.UI.WebControls.RegularExpressionValidator
'''<summary>
'''plCleanupMaxEntries control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plCleanupMaxEntries As Global.System.Web.UI.UserControl
'''<summary>
'''txtCleanupMaxEntries control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtCleanupMaxEntries As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''Regularexpressionvalidator2 control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents Regularexpressionvalidator2 As Global.System.Web.UI.WebControls.RegularExpressionValidator
End Class
End Namespace
|
DNNCommunity/DNN.Feedback
|
Settings.ascx.designer.vb
|
Visual Basic
|
mit
| 47,090
|
' Fw Self Test base class
'
' Part of ASP.NET osa framework www.osalabs.com/osafw/asp.net
' (c) 2009-2018 Oleg Savchuk www.osalabs.com
Imports System.IO
Public Class FwSelfTest
Protected fw As FW
Protected db As DB
Public is_logged As Boolean = False
Public is_db As Boolean = False 'set to true after db connection test if db connection successful
Public ok_ctr As Integer = 0 'number of successfull tests
Public warn_ctr As Integer = 0 'number of warning tests
Public err_ctr As Integer = 0 'number of errorneous tests
Public total_ctr As Integer = 0 'total tests
'Test results for self-test
Public Enum Result As Integer
OK
WARN
ERR
End Enum
Public test_email As String = "" 'if empty, will use "test"+mail_from
Public existing_tables As String = "users settings spages att att_table_link att_categories events event_log lookup_manager_tables user_views user_lists user_lists_items" 'check if these tables exists
Public exclude_controllers As String = ""
Public Sub New(fw As FW)
Me.fw = fw
Me.db = fw.db
is_logged = Utils.f2bool(fw.SESSION("is_logged"))
End Sub
''''''''''''''''''''''''''' high level tests
''' <summary>
''' run all tests
''' </summary>
Public Overridable Sub all()
configuration()
database_tables()
controllers()
End Sub
''' <summary>
''' test config values. Override to make additional config tests
''' </summary>
Public Overridable Sub configuration()
'test important config settings
echo("<strong>Config</strong>")
echo("hostname: " & fw.config("hostname"))
is_notempty("site_root", fw.config("site_root"))
'log_level: higher than debug - OK, debug - warn, trace or below - red (not for prod)
Dim log_level = CType(fw.config("log_level"), LogLevel)
If log_level >= LogLevel.TRACE Then
plus_err()
echo("log_level", [Enum].GetName(GetType(LogLevel), log_level), Result.ERR)
ElseIf log_level = LogLevel.DEBUG Then
plus_warn()
echo("log_level", [Enum].GetName(GetType(LogLevel), log_level), Result.WARN)
Else
plus_ok()
echo("log_level", "OK")
End If
is_false("is_test", fw.config("is_test"), "Turned ON")
'template directory should exists - TODO test parser to actually see templates work?
is_true("template", Directory.Exists(fw.config("template")), fw.config("template"))
is_true("access_levels", fw.config("access_levels") IsNot Nothing AndAlso fw.config("access_levels").Count > 0, "Not defined")
'UPLOAD_DIR upload dir is writeable
Try
Dim upload_filepath As String = UploadUtils.getUploadDir(fw, "selftest", 1) & "/txt"
FW.set_file_content(upload_filepath, "test")
File.Delete(upload_filepath)
plus_ok()
echo("upload dir", "OK")
Catch ex As Exception
plus_err()
echo("upload dir", ex.Message(), Result.ERR)
End Try
'emails set
is_notempty("mail_from", fw.config("mail_from"))
is_notempty("support_email", fw.config("support_email"))
'test send email to "test+mail_from"
is_true("Send Emails", fw.send_email("", IIf(String.IsNullOrEmpty(test_email), "test+" & fw.config("mail_from"), test_email), "test email", "test body"), "Failed")
Try
db.connect()
is_db = True
plus_ok()
echo("DB connection", "OK")
Catch ex As Exception
plus_err()
echo("DB connection", ex.Message(), Result.ERR)
End Try
End Sub
Public Overridable Sub database_tables()
If is_db Then
echo("<strong>DB Tables</strong>")
'fw core db tables exists and we can read from it
'(select count(*) from: users, settings, spages, att, att_table_link, att_categories, events, event_log)
Dim tables As String() = Utils.qw(existing_tables)
For Each table In tables
Try
db.value("select TOP 1 * from " & table)
plus_ok()
echo("table " & table, "OK")
Catch ex As Exception
plus_err()
echo("table " & table, ex.Message(), Result.ERR)
End Try
Next
End If
End Sub
Public Overridable Sub controllers()
'test controllers (TODO - only for logged admin user)
echo("<strong>Controllers</strong>")
'get all classes ending with "Controller" and not starting with "Fw"
Dim aControllers = Reflection.Assembly.GetExecutingAssembly().GetTypes() _
.Where(Function(t) t.Name <> "AdminSelfTestController" AndAlso Right(t.Name, 10) = "Controller" AndAlso Left(t.Name, 2) <> "Fw") _
.OrderBy(Function(t) t.Name) _
.ToList()
If aControllers.Count = 0 Then
plus_err()
echo("Controllers", "None found", FwSelfTest.Result.ERR)
End If
Dim hexclude As Hashtable = Utils.qh(exclude_controllers)
For Each t In aControllers
Dim controller_name As String = Replace(t.Name, "Controller", "")
'omit controllers we don't need to test
If hexclude.ContainsKey(controller_name) Then Continue For
fw.logger("Testing Controller:" & controller_name)
Dim calledType As Type = Type.GetType(t.Name, False, True)
If calledType Is Nothing Then
plus_err()
echo(t.Name, "Not found", FwSelfTest.Result.ERR)
Continue For
End If
Try
'check controller have SelfTest method
'SelfTest method should accept one argument FwSelfTest
'and return FwSelfTest.Result
'sample Controller.SelfTest declaration:
'
' Public Function SelfTest(t As FwSelfTest) As FwSelfTest.Result
' Dim res As Boolean = True
' res = res AndAlso t.is_true("Inner var check", (var = 1)) = FwSelfTest.Result.OK
' Return IIf(res, FwSelfTest.Result.OK, FwSelfTest.Result.ERR)
' End Function
Dim mInfo As Reflection.MethodInfo = calledType.GetMethod("SelfTest")
If mInfo Is Nothing Then
'if no SelfTest - test IndexAction method
mInfo = calledType.GetMethod("IndexAction")
If mInfo Is Nothing Then
plus_warn()
echo(t.Name, "No SelfTest or IndexAction methods found", FwSelfTest.Result.WARN)
Continue For
End If
'test using IndexAction
'need to buffer output from controller to clear it later
fw.resp.BufferOutput = True
fw._auth(controller_name, "Index")
fw.setController(controller_name, "Index")
Dim new_controller As FwController = Activator.CreateInstance(calledType)
new_controller.init(fw)
Dim ps As Hashtable = mInfo.Invoke(new_controller, Nothing)
fw.resp.Clear()
fw.resp.BufferOutput = False
If ps Is Nothing OrElse ps.Count = 0 Then
plus_warn()
echo(t.Name, "Empty result", FwSelfTest.Result.WARN)
Else
plus_ok()
echo(t.Name, "OK")
End If
Else
'test using SelfTest
fw._auth(controller_name, "SelfTest")
Dim new_controller As FwController = Activator.CreateInstance(calledType)
new_controller.init(fw)
Dim res As Result = mInfo.Invoke(new_controller, New Object() {Me})
If res = Result.OK Then
plus_ok()
echo(t.Name, "OK")
ElseIf res = Result.WARN Then
plus_warn()
echo(t.Name, "Warning", res)
ElseIf res = Result.ERR Then
plus_err()
echo(t.Name, "Error", res)
End If
End If
Catch ex As AuthException
'just skip controllers not authorized to current user
fw.logger(controller_name & " controller test skipped, user no authorized")
Catch ex As Exception
If fw.resp.BufferOutput Then
fw.resp.Clear()
fw.resp.BufferOutput = False
End If
If ex.InnerException IsNot Nothing Then
If TypeOf (ex.InnerException) Is RedirectException OrElse ex.InnerException.Message.Contains("Cannot redirect after HTTP headers have been sent.") Then
'just redirect in Controller.Index - it's OK
plus_ok()
echo(t.Name, "OK")
Else
'something really wrong
fw.logger(ex.InnerException.ToString())
plus_err()
echo(t.Name, ex.InnerException.Message(), FwSelfTest.Result.ERR)
End If
ElseIf TypeOf (ex) Is RedirectException OrElse ex.Message.Contains("Cannot redirect after HTTP headers have been sent.") Then
'just redirect in Controller.Index - it's OK
plus_ok()
echo(t.Name, "OK")
Else
'something really wrong
fw.logger(ex.ToString())
plus_err()
echo(t.Name, ex.Message(), FwSelfTest.Result.ERR)
End If
End Try
Next
End Sub
''' <summary>
''' default stub to output test header
''' </summary>
Public Overridable Sub echo_start()
echo("<h1>Site Self Test</h1>")
'If Not is_logged Then echo("<a href='" & fw.config("ROOT_URL") & "/Login'>Login</a> as an administrator to see error details and perform additional tests")
echo("<a href='#summary'>Test Summary</a>")
End Sub
''' <summary>
''' ouput test totals, success, warnings, errors
''' </summary>
Public Overridable Sub echo_totals()
echo("<a name='summary' />")
echo("<h2>Test Summary</h2>")
echo("Total : " & total_ctr)
echo("Success", ok_ctr)
echo("Warnings", warn_ctr, Result.WARN)
echo("Errors", err_ctr, Result.ERR)
'self check
If total_ctr <> ok_ctr + warn_ctr + err_ctr Then
echo("Test count error", "total != ok+warn+err", Result.ERR)
End If
echo("<br><br><br><br><br>") 'add some footer spacing for easier review
End Sub
''''''''''''''''''''''''''' low level tests
''' <summary>
''' test of value is false and ouput OK. If true output ERROR or custom string
''' </summary>
''' <param name="label"></param>
''' <param name="value"></param>
''' <param name="err_str"></param>
Public Function is_false(label As String, value As Boolean, Optional err_str As String = "ERROR") As Result
Dim res As Result = Result.ERR
total_ctr += 1
If value Then
err_ctr += 1
Else
ok_ctr += 1
err_str = "OK"
res = Result.OK
End If
echo(label, err_str, res)
Return res
End Function
''' <summary>
''' test of value is true and ouput OK. If false output ERROR or custom string
''' </summary>
''' <param name="label"></param>
''' <param name="value"></param>
''' <param name="err_str"></param>
Public Function is_true(label As String, value As Boolean, Optional err_str As String = "ERROR") As Result
Dim res As Result = Result.ERR
total_ctr += 1
If value Then
ok_ctr += 1
err_str = "OK"
res = Result.OK
Else
err_ctr += 1
End If
echo(label, err_str, res)
Return res
End Function
''' <summary>
''' test of value is not nothing and not empty string and ouput OK. If value is empty output ERROR or custom string
''' </summary>
''' <param name="label"></param>
''' <param name="value"></param>
Public Function is_notempty(label As String, value As Object, Optional err_str As String = "EMPTY") As Result
Dim res As Result = Result.ERR
total_ctr += 1
If String.IsNullOrEmpty(value) Then
err_ctr += 1
Else
ok_ctr += 1
err_str = "OK"
res = Result.OK
End If
echo(label, err_str, res)
Return res
End Function
''' <summary>
''' test of value is nothing or empty string and ouput OK. If false output ERROR or custom string
''' </summary>
''' <param name="label"></param>
''' <param name="value"></param>
Public Function is_empty(label As String, value As Object, Optional err_str As String = "EMPTY") As Result
Dim res As Result = Result.ERR
total_ctr += 1
If String.IsNullOrEmpty(value) Then
ok_ctr += 1
err_str = "OK"
res = Result.OK
Else
err_ctr += 1
End If
echo(label, err_str, res)
Return res
End Function
''' <summary>
''' output test result to browser, optionally with color.
''' </summary>
''' <param name="label">string to use as label</param>
''' <param name="str">test result value or just OK, ERROR</param>
''' <param name="res">result category</param>
Public Sub echo(label As String, Optional str As String = "", Optional res As Result = Result.OK)
If res = Result.WARN Then
str = "<span style='background-color:#FF7200;color:#fff'>" & str & "</span>"
ElseIf res = Result.ERR Then
str = "<span style='background-color:#DD0000;color:#fff'>" & str & "</span>"
Else
If str > "" Then
str = "<span style='color:#009900;'>" & str & "</span>"
End If
End If
'Output without parser because templates might not exists/configured
If str > "" Then
fw.resp.Write(label & " : " & str)
Else
fw.resp.Write(label)
End If
fw.resp.Write("<br>" & vbCrLf)
fw.resp.Flush()
End Sub
''' <summary>
''' helper to add 1 to OK count
''' </summary>
Public Sub plus_ok()
ok_ctr += 1
total_ctr += 1
End Sub
''' <summary>
''' helper to add 1 to WARN count
''' </summary>
Public Sub plus_warn()
warn_ctr += 1
total_ctr += 1
End Sub
''' <summary>
''' helper to add 1 to ERR count
''' </summary>
Public Sub plus_err()
err_ctr += 1
total_ctr += 1
End Sub
End Class
|
osalabs/osafw-asp.net
|
www/App_Code/fw/FwSelfTest.vb
|
Visual Basic
|
mit
| 15,392
|
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 linearStyles As SolidEdgeFramework.LinearStyles = 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
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
linearStyles = CType(partDocument.LinearStyles, SolidEdgeFramework.LinearStyles)
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.05, 0.05, 0.09, 0.12, 0.14, 0.05, 0.19, 0.18, 0.25, 0.09 }
bSplineCurve2d = bSplineCurves2d.AddByPoints(4, Points.Length \ 2, Points)
bSplineCurve2d.AddSegmentedStyle(0.05, 0.05, 0.14, 0.05, linearStyles.Item(3))
bSplineCurve2d.AddSegmentedStyle(0.14, 0.05, 0.19, 0.18, linearStyles.Item(2))
Dim Index As Integer = 1
Dim x1 As Double = Nothing
Dim y1 As Double = Nothing
Dim x2 As Double = Nothing
Dim y2 As Double = Nothing
Dim Style As Object = Nothing
bSplineCurve2d.GetSegmentedStyle(Index, x1, y1, x2, y2, Style)
Dim linearStyle = DirectCast(Style, SolidEdgeFramework.LinearStyle)
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.GetSegmentedStyle.vb
|
Visual Basic
|
mit
| 3,038
|
Module MagicSquares
Function MagicSquareDoublyEven(n As Integer) As Integer(,)
If n < 4 OrElse n Mod 4 <> 0 Then
Throw New ArgumentException("base must be a positive multiple of 4")
End If
'pattern of count-up vs count-down zones
Dim bits = Convert.ToInt32("1001011001101001", 2)
Dim size = n * n
Dim mult As Integer = n / 4 ' how many multiples of 4
Dim result(n - 1, n - 1) As Integer
Dim i = 0
For r = 0 To n - 1
For c = 0 To n - 1
Dim bitPos As Integer = Math.Floor(c / mult) + Math.Floor(r / mult) * 4
Dim test = (bits And (1 << bitPos)) <> 0
If test Then
result(r, c) = i + 1
Else
result(r, c) = size - i
End If
i = i + 1
Next
Console.WriteLine()
Next
Return result
End Function
Sub Main()
Dim n = 8
Dim result = MagicSquareDoublyEven(n)
For i = 0 To result.GetLength(0) - 1
For j = 0 To result.GetLength(1) - 1
Console.Write("{0,2} ", result(i, j))
Next
Console.WriteLine()
Next
Console.WriteLine()
Console.WriteLine("Magic constant: {0} ", (n * n + 1) * n / 2)
End Sub
End Module
|
ncoe/rosetta
|
Magic_squares_of_doubly_even_order/Visual Basic .NET/MagicSquares/MagicSquares/MagicSquares.vb
|
Visual Basic
|
mit
| 1,387
|
Imports System.Collections.ObjectModel
Imports System.Collections.Specialized
Imports System.ComponentModel
Imports System.IO
Imports System.Runtime.CompilerServices
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports System.Drawing
Imports System.Runtime.Serialization
Imports LampCommon
<DataContract>
<JsonObject(MemberSerialization.OptIn)>
<KnownType(GetType(LampTemplate))>
<KnownType(GetType(LampProfile))>
Public Class LampTemplateMetadata
Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Protected Sub NotifyPropertyChanged(<CallerMemberName()> Optional ByVal propertyName As String = Nothing)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
Public Function ToLampTemplate() As LampTemplate
Dim ret As New LampTemplate()
ret.GUID = GUID
ret.Name = Name
ret.ShortDescription = ShortDescription
ret.LongDescription = LongDescription
ret.Material = Material
ret.Width = Width
ret.Height = Height
ret.MaterialThickness = MaterialThickness
ret.IsComplete = IsComplete
ret.ApproverProfile = ApproverProfile
ret.CreatorProfile = CreatorProfile
ret.SubmitDate = SubmitDate
ret.IsComplete = IsComplete
ret.BoundsLock = BoundsLock
Return ret
End Function
Private _guid As String
''' <summary>
''' a unique identifer for each different template
''' </summary>
''' <returns></returns>
<JsonProperty("guid")>
<DataMember()>
Public Property GUID As String
Get
Return _guid
End Get
Set(value As String)
_guid = value
NotifyPropertyChanged()
End Set
End Property
Private _name As String = ""
''' <summary>
''' a unique identifer for each different template
''' </summary>
''' <returns></returns>
<JsonProperty("Name")>
<DataMember()>
Public Property Name As String
Get
Return _name
End Get
Set(value As String)
_name = value
NotifyPropertyChanged()
End Set
End Property
Private _shortDescription As String = ""
''' <summary>
''' a unique identifer for each different template
''' </summary>
''' <returns></returns>
<JsonProperty("ShortDescription")>
<DataMember()>
Public Property ShortDescription As String
Get
Return _shortDescription
End Get
Set(value As String)
_shortDescription = value
NotifyPropertyChanged()
End Set
End Property
Private _longDescription As String = ""
''' <summary>
''' a unique identifer for each different template
''' </summary>
''' <returns></returns>
<JsonProperty("LongDescription")>
<DataMember()>
Public Property LongDescription As String
Get
Return _longDescription
End Get
Set(value As String)
_longDescription = value
NotifyPropertyChanged()
End Set
End Property
Private _material As String = "Unspecified"
''' <summary>
''' material the trophy is made out of
''' </summary>
''' <returns></returns>
<JsonProperty("material")>
<DataMember()>
Public Property Material As String
Get
Return _material
End Get
Set(value As String)
_material = value
NotifyPropertyChanged()
End Set
End Property
Private _width As Double
''' <summary>
''' The length of all of the template
''' </summary>
''' <returns></returns>
<JsonProperty("width")>
<DataMember()>
Public Property Width As Double
Get
Return _width
End Get
Set(value As Double)
_width = value
NotifyPropertyChanged()
End Set
End Property
Private _height As Double
''' <summary>
''' The height of all the template
''' </summary>
''' <returns></returns>
<JsonProperty("height")>
<DataMember()>
Public Property Height As Double
Get
Return _height
End Get
Set(value As Double)
_height = value
NotifyPropertyChanged()
End Set
End Property
<JsonProperty("bound_lock")>
<DataMember>
Private _boundsLock As Boolean = False
Public Property BoundsLock As Boolean
Get
Return _boundsLock
End Get
Set(value As Boolean)
_boundsLock = value
NotifyPropertyChanged()
End Set
End Property
Private _materialThickness As Double
''' <summary>
''' The thickness of the material used
''' </summary>
''' <returns></returns>
<JsonProperty("material_thickness")>
<DataMember()>
Public Property MaterialThickness As Double
Get
Return _materialThickness
End Get
Set(value As Double)
_materialThickness = value
NotifyPropertyChanged()
End Set
End Property
''' <summary>
''' Name, email of creator if exists
''' </summary>
''' <returns></returns>
<JsonProperty("creator_profile")>
<DataMember>
Public Property CreatorProfile As LampProfile = Nothing
<IgnoreDataMember>
Public ReadOnly Property CreatorId As String
Get
Return CreatorProfile?.UserId
End Get
End Property
''' <summary>
''' name, email of approver if exists
''' </summary>
''' <returns></returns>
<JsonProperty("approver_profile")>
<DataMember>
Public Property ApproverProfile As LampProfile = Nothing
<IgnoreDataMember>
Public ReadOnly Property Approved As Boolean
Get
Return ApproverProfile IsNot Nothing
End Get
End Property
Private _submitDate As Date?
''' <summary>
''' The date item was submitted
''' </summary>
''' <returns></returns>
<JsonProperty("submit_date")>
<DataMember()>
Public Property SubmitDate As Date?
Get
Return _submitDate
End Get
Set(value As Date?)
_submitDate = value
NotifyPropertyChanged()
End Set
End Property
Private _complete As Boolean
''' <summary>
''' The date item was submitted
''' </summary>
''' <returns></returns>
<JsonProperty("is_complete")>
<DataMember()>
Public Property IsComplete As Boolean
Get
Return _complete
End Get
Set(value As Boolean)
_complete = value
NotifyPropertyChanged()
End Set
End Property
Public Sub New()
Me.New(GetNewGuid())
End Sub
Public Sub New(guid As String)
Me.GUID = guid
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Nothing Then
Return False
End If
Dim data = TryCast(obj, LampTemplateMetadata)
If data Is Nothing Then
Return False
End If
If data.GUID IsNot Nothing Then
If Not data.GUID.Equals(GUID) Then
Return False
End If
Else ' is nothing
If GUID IsNot Nothing Then
Return False
End If
End If
If data.ShortDescription IsNot Nothing Then
If Not data.ShortDescription.Equals(ShortDescription) Then
Return False
End If
Else ' is nothing
If ShortDescription IsNot Nothing Then
Return False
End If
End If
If Not data.LongDescription.Equals(LongDescription) Then
Return False
End If
If Not data.Material.Equals(Material) Then
Return False
End If
If Not data.Width.Equals(Width) Then
Return False
End If
If Not data.Height.Equals(Height) Then
Return False
End If
If Not data.MaterialThickness.Equals(MaterialThickness) Then
Return False
End If
If data.CreatorProfile IsNot Nothing Then
If Not data.CreatorProfile.Equals(CreatorProfile) Then
Return False
End If
Else ' is nothing
If CreatorProfile IsNot Nothing Then
Return False
End If
End If
If data.ApproverProfile IsNot Nothing Then
If Not data.CreatorProfile.Equals(CreatorProfile) Then
Return False
End If
Else ' is nothing
If ApproverProfile IsNot Nothing Then
Return False
End If
End If
If Not data.SubmitDate.Equals(SubmitDate) Then
Return False
End If
If Not data.IsComplete.Equals(IsComplete) Then
Return False
End If
If Not data.BoundsLock.Equals(BoundsLock) Then
Return False
End If
Return True
End Function
Public Overrides Function GetHashCode() As Integer
Return Me.GUID.GetHashCode()
End Function
End Class
<JsonObject(MemberSerialization.OptIn)>
<DataContract()>
<KnownType(GetType(LampTemplateMetadata))>
<KnownType(GetType(LampProfile))>
<KnownType(GetType(LampDxfDocument))>
Public NotInheritable Class LampTemplate
Inherits LampTemplateMetadata
Public Const MaxImages As Integer = 3
#Region "Instance Variables"
Private _baseDrawing As LampDxfDocument = New LampDxfDocument
''' <summary>
''' The actual template : contains just 1 of drawing
''' Is serialized last in the file
''' </summary>
<JsonProperty("template", Order:=1000, Required:=Required.Always)>
<DataMember>
Public Property BaseDrawing As LampDxfDocument
Get
Return _baseDrawing
End Get
Set(value As LampDxfDocument)
If value Is Nothing Then
Throw New ArgumentNullException(NameOf(value))
End If
If _baseDrawing IsNot Nothing Then
RemoveHandler _baseDrawing.PropertyChanged, AddressOf BaseDrawing_PropertyChanged
End If
_baseDrawing = value
If _baseDrawing IsNot Nothing Then
AddHandler _baseDrawing.PropertyChanged, AddressOf BaseDrawing_PropertyChanged
End If
If Not BoundsLock Then
UpdateBoundsFromDrawing()
End If
NotifyPropertyChanged()
End Set
End Property
Private Sub UpdateBoundsFromDrawing()
If BaseDrawing IsNot Nothing Then
Me.Width = BaseDrawing.Width
Me.Height = BaseDrawing.Height
End If
End Sub
''' <summary>
''' handler for base drawing mutating
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub BaseDrawing_PropertyChanged(sender As Object, e As PropertyChangedEventArgs)
If Not BoundsLock Then
UpdateBoundsFromDrawing()
End If
NotifyPropertyChanged(NameOf(BaseDrawing))
End Sub
Private _tags As ObservableCollection(Of String)
''' <summary>
''' A list of tags.
''' </summary>
''' <returns></returns>
<JsonProperty("tags")>
<DataMember>
Public Property Tags As ObservableCollection(Of String)
Get
Return _tags
End Get
Private Set(value As ObservableCollection(Of String))
If _tags IsNot Nothing Then
RemoveHandler _tags.CollectionChanged, AddressOf Tags_CollectionChanged
End If
_tags = value
If _tags IsNot Nothing Then
AddHandler _tags.CollectionChanged, AddressOf Tags_CollectionChanged
End If
NotifyPropertyChanged()
End Set
End Property
''' <summary>
''' Handler for tags changing
''' </summary>
''' <param name="sender"></param>
''' <param name="args"></param>
Private Sub Tags_CollectionChanged(sender As Object, args As NotifyCollectionChangedEventArgs)
NotifyPropertyChanged(NameOf(Tags))
End Sub
Private _dynamicTextList As ObservableCollection(Of DynamicTextKey)
''' <summary>
''' Where the dynamic text will be stored:
''' </summary>
''' <returns></returns>
<JsonProperty("dynamic_text_list")>
<DataMember>
Public Property DynamicTextList As ObservableCollection(Of DynamicTextKey)
Get
Return _dynamicTextList
End Get
Private Set(value As ObservableCollection(Of DynamicTextKey))
If _dynamicTextList IsNot Nothing Then
RemoveHandler _dynamicTextList.CollectionChanged, AddressOf DynamicTextList_PropertyChanged
End If
_dynamicTextList = value
If _dynamicTextList IsNot Nothing Then
AddHandler _dynamicTextList.CollectionChanged, AddressOf DynamicTextList_PropertyChanged
End If
End Set
End Property
''' <summary>
''' see algorithm for in depth explaination
''' </summary>
Public Sub SortTags()
Dim copy As New List(Of String)
copy.AddRange(Tags)
copy.Sort()
Tags.Clear()
Tags.AddRange(copy)
End Sub
''' <summary>
''' Handler for dynamic text changes
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub DynamicTextList_PropertyChanged(sender As Object, e As NotifyCollectionChangedEventArgs)
NotifyPropertyChanged(NameOf(DynamicTextList))
End Sub
''' <summary>
''' Dummy member for WCF to serialize images
''' DONT USE
''' </summary>
''' <returns></returns>
<DataMember>
<JsonIgnore>
Private Property _serializePreviewImages As IEnumerable(Of String)
Get
Return LampDxfDocument.ImageListToBase64(PreviewImages)
End Get
Set(value As IEnumerable(Of String))
PreviewImages = LampDxfDocument.Base64ListToImage(value).ToObservableList
End Set
End Property
Private _previewImage As ObservableCollection(Of Image)
''' <summary>
''' List of 3 images
''' </summary>
''' <returns></returns>
<JsonProperty("preview_images")>
<JsonConverter(GetType(ImageListJsonConverter))>
Public Property PreviewImages As ObservableCollection(Of Image)
Get
Return _previewImage
End Get
Private Set(value As ObservableCollection(Of Image))
If _previewImage IsNot Nothing Then
RemoveHandler PreviewImages.CollectionChanged, AddressOf PreviewImages_CollectionChanged
End If
_previewImage = value
If _previewImage IsNot Nothing Then
AddHandler PreviewImages.CollectionChanged, AddressOf PreviewImages_CollectionChanged
End If
NotifyPropertyChanged()
End Set
End Property
''' <summary>
''' Handler for previewImages change
''' </summary>
''' <param name="sender"></param>
''' <param name="args"></param>
Private Sub PreviewImages_CollectionChanged(sender As Object, args As NotifyCollectionChangedEventArgs)
NotifyPropertyChanged(NameOf(PreviewImages))
End Sub
#End Region
''' <summary>
''' Load from a file on disk
''' </summary>
''' <param name="fileName"></param>
''' <returns></returns>
Public Shared Function FromFile(fileName As String) As LampTemplate
Using file As New StreamReader(fileName)
Return Deserialize(file.ReadToEnd())
End Using
End Function
Public Shared Async Function FromFileAsync(fileName As String) As Task(Of LampTemplate)
Using file As New StreamReader(fileName)
Return Deserialize(Await file.ReadToEndAsync())
End Using
End Function
''' <summary>
''' Loads from a json string
''' </summary>
''' <param name="json"></param>
''' <returns></returns>
Private Shared Function Deserialize(json As String) As LampTemplate
Return JsonConvert.DeserializeObject(Of LampTemplate)(json)
End Function
''' <summary>
''' Gets whether or not it has text that is filled in by the user
''' during creation
''' </summary>
''' <returns></returns>
Public ReadOnly Property HasDynamicText As Boolean
Get
Return DynamicTextList.Count() = 0
End Get
End Property
''' <summary>
''' Gets an empty lamptemplte
''' </summary>
''' <returns></returns>
Public Shared ReadOnly Property Empty As LampTemplate
Get
Return New LampTemplate(GetNewGuid()) 'Gets a New Default guid (0000-0000-0000...)
End Get
End Property
''' <summary>
''' Converts -> json format to be saved as a .spf
''' </summary>
''' <returns></returns>
Public Function ToJson(Optional formatting As Formatting = Formatting.None) As String
Return JsonConvert.SerializeObject(Me, formatting)
End Function
''' <summary>
''' Saves to file on disk
''' </summary>
''' <param name="path"></param>
''' <param name="compress"></param>
#If DEBUG Then
Public Sub Save(path As String, Optional compress As Boolean = False)
#Else
Public Sub Save(path As String, Optional compress as boolean = True)
#End If
Dim formatting As Newtonsoft.Json.Formatting
If compress Then
formatting = Formatting.None
Else
formatting = Formatting.Indented
End If
If Not BoundsLock Then
UpdateBoundsFromDrawing()
End If
Using fileStream As New StreamWriter(path)
fileStream.Write(ToJson(formatting))
End Using
End Sub
''' <summary>
''' Create a new LampTemplate with default Everything
''' </summary>
Sub New()
Me.New(New LampDxfDocument(), System.Guid.NewGuid.ToString)
End Sub
''' <summary>
''' Creates a new <see cref="LampTemplate"></see> with default LampDxfDocument
''' </summary>
''' <param name="guid"></param>
<JsonConstructor>
Sub New(guid As String)
Me.New(New LampDxfDocument, guid)
End Sub
''' <summary>
''' Creates a new <see cref="LampTemplate"></see> with default guid
''' also sets the bounds
''' </summary>
''' <param name="dxf"></param>
Sub New(dxf As LampDxfDocument)
Me.New(dxf, System.Guid.NewGuid.ToString)
End Sub
''' <summary>
''' Creates a new <see cref="LampTemplate"></see>
''' </summary>
''' <param name="dxf"></param>
''' <param name="guid"></param>
Sub New(dxf As LampDxfDocument, guid As String)
Me.GUID = guid
Me.BaseDrawing = dxf
Me.Tags = New ObservableCollection(Of String)
Me.DynamicTextList = New ObservableCollection(Of DynamicTextKey)
PreviewImages = New ObservableCollection(Of Image)
PreviewImages.ClearAsArray()
If Not BoundsLock Then
UpdateBoundsFromDrawing()
End If
End Sub
Public Shared Sub SortByMaterial(listOfTemplate As List(Of LampTemplate))
listOfTemplate.Sort(AddressOf CompareMaterial)
End Sub
Private Shared Function CompareMaterial(x As LampTemplate, y As LampTemplate) As Integer
Return x.Material.CompareTo(y.Material)
End Function
Private Shared Function CompareDate(x As LampTemplate, y As LampTemplate) As Integer
Return x.Material.CompareTo(y.Material)
End Function
Public Overrides Function ToString() As String
Return String.Format("LampTemplate Guid:{0}", Me.GUID)
End Function
Public Overrides Function GetHashCode() As Integer
Return MyBase.GetHashCode()
End Function
Public Function GeneratePreviewImages() As Boolean
If Me.Width <= 0 OrElse Me.Height <= 0 Then
Return False
End If
Me.PreviewImages(0) = Me.BaseDrawing.ToImage()
Return True
End Function
End Class
<DataContract>
<KnownType(GetType(LampTemplate))>
<KnownType(GetType(LampStatus))>
Public Class LampTemplateWrapper
<DataMember>
Public Property Template As LampTemplate
<DataMember>
Public Property Status As LampStatus
End Class
|
KameQuazi/Software-Major-Assignment-2k18
|
LampCommon/template/LampTemplate.vb
|
Visual Basic
|
mit
| 20,591
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.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.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("")> _
Public Property Connection() As String
Get
Return CType(Me("Connection"),String)
End Get
Set
Me("Connection") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("")> _
Public Property LIC() As String
Get
Return CType(Me("LIC"),String)
End Get
Set
Me("LIC") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("")> _
Public Property Username() As String
Get
Return CType(Me("Username"),String)
End Get
Set
Me("Username") = value
End Set
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.SIMARSIP.My.MySettings
Get
Return Global.SIMARSIP.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
anakpantai/busus
|
SIMARSIP/My Project/Settings.Designer.vb
|
Visual Basic
|
apache-2.0
| 4,362
|
'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 ESRI.ArcGIS.Carto
Imports ESRI.ArcGIS.Controls
Imports ESRI.ArcGIS.ADF.BaseClasses
Imports ESRI.ArcGIS.ADF.CATIDs
Imports System.Runtime.InteropServices
<ComClass(GoToNextExtent.ClassId, GoToNextExtent.InterfaceId, GoToNextExtent.EventsId)> _
Public NotInheritable Class GoToNextExtent
Inherits BaseCommand
#Region "COM GUIDs"
' These GUIDs provide the COM identity for this class
' and its COM interfaces. If you change them, existing
' clients will no longer be able to access the class.
Public Const ClassId As String = "D743251A-37A6-4BC4-A9A3-1BE3225E3A82"
Public Const InterfaceId As String = "908A25F6-64D5-44C3-9901-3B208F6C5110"
Public Const EventsId As String = "8F9FCC92-3432-4148-AC16-F02838938013"
#End Region
#Region "COM Registration Function(s)"
<ComRegisterFunction(), ComVisibleAttribute(False)> _
Public Shared Sub RegisterFunction(ByVal registerType As Type)
' Required for ArcGIS Component Category Registrar support
ArcGISCategoryRegistration(registerType)
'Add any COM registration code after the ArcGISCategoryRegistration() call
End Sub
<ComUnregisterFunction(), ComVisibleAttribute(False)> _
Public Shared Sub UnregisterFunction(ByVal registerType As Type)
' Required for ArcGIS Component Category Registrar support
ArcGISCategoryUnregistration(registerType)
'Add any COM unregistration code after the ArcGISCategoryUnregistration() call
End Sub
#Region "ArcGIS Component Category Registrar generated code"
''' <summary>
''' Required method for ArcGIS Component Category registration -
''' Do not modify the contents of this method with the code editor.
''' </summary>
Private Shared Sub ArcGISCategoryRegistration(ByVal registerType As Type)
Dim regKey As String = String.Format("HKEY_CLASSES_ROOT\CLSID\{{{0}}}", registerType.GUID)
ControlsCommands.Register(regKey)
End Sub
''' <summary>
''' Required method for ArcGIS Component Category unregistration -
''' Do not modify the contents of this method with the code editor.
''' </summary>
Private Shared Sub ArcGISCategoryUnregistration(ByVal registerType As Type)
Dim regKey As String = String.Format("HKEY_CLASSES_ROOT\CLSID\{{{0}}}", registerType.GUID)
ControlsCommands.Unregister(regKey)
End Sub
#End Region
#End Region
Private m_pEnabled As Boolean
Private m_pHookHelper As IHookHelper
' A creatable COM class must have a Public Sub New()
' with no parameters, otherwise, the class will not be
' registered in the COM registry and cannot be created
' via CreateObject.
Public Sub New()
MyBase.New()
MyBase.m_category = "Sample_Pan_VBNET/Zoom"
MyBase.m_caption = "Redo Extent"
MyBase.m_message = "Redo Previous Screen location"
MyBase.m_toolTip = "Redo Previous Extent"
MyBase.m_name = "Sample_Pan/Zoom_Redo Extent"
Dim res() As String = GetType(GoToNextExtent).Assembly.GetManifestResourceNames()
If res.GetLength(0) > 0 Then
MyBase.m_bitmap = New System.Drawing.Bitmap(GetType(GoToNextExtent).Assembly.GetManifestResourceStream("PanZoomVBNET.ReDoDraw.bmp"))
End If
m_pHookHelper = New HookHelperClass
End Sub
Public Overrides Sub OnClick()
'Get the active view
Dim pActiveView As IActiveView = CType(m_pHookHelper.FocusMap, IActiveView)
'Get the extent stack
Dim pMapExtent As IExtentStack = CType(pActiveView.ExtentStack, IExtentStack)
'Redo the extent
If pMapExtent.CanRedo() Then
pMapExtent.Redo()
End If
End Sub
Public Overrides Sub OnCreate(ByVal hook As Object)
m_pHookHelper.Hook = hook
m_pEnabled = True
End Sub
Public Overrides ReadOnly Property Enabled() As Boolean
Get
If m_pHookHelper.FocusMap Is Nothing Then Exit Property
'Get the active view
Dim pActiveView As IActiveView = CType(m_pHookHelper.FocusMap, IActiveView)
'Get the extent stack
Dim pMapStack As IExtentStack = CType(pActiveView.ExtentStack, IExtentStack)
'Can the extent be undone
Return m_pEnabled = pMapStack.CanRedo()
End Get
End Property
End Class
|
Esri/arcobjects-sdk-community-samples
|
Net/Controls/ControlsCommandsPanZoomCommands/VBNet/GoToNextExtent.vb
|
Visual Basic
|
apache-2.0
| 4,919
|
'' Copyright (c) 2013, Kcchouette and b-dauphin on Github
'' All rights reserved.
''
'' Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
''
'' Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
'' Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
'' Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
''
'' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Public Class FrmAccueil
Private Sub btnInscrire_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnInscrire.Click
Me.Hide()
persActu = bidon
FrmInscripRens.modif = False
FrmInscripRens.Show()
FrmInscripRens.Reinit()
End Sub
Private Sub FrmAccueil_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
tmrHeureActu.Start()
Call tmrHeureActu_Tick(sender, e)
End Sub
Private Sub FrmAccueil_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
tmrHeureActu.Start()
Me.Tag = Me.Text & " "
ReDim persActu.tIndEcrit(3)
ReDim persActu.tIndOral(2)
ReDim bidon.tIndEcrit(3)
ReDim bidon.tIndOral(2)
FileOpen(numFicInscrit, "inscriptions.dat", OpenMode.Random, OpenAccess.ReadWrite, OpenShare.Shared, lgEnr)
'Call creerFichier()
End Sub
Sub tmrHeureActu_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrHeureActu.Tick
On Error Resume Next
ActiveForm.Text = ActiveForm.Tag & TimeOfDay
End Sub
Private Sub btnFin_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnFin.Click
Me.Hide()
FrmAffichBilan.fin = True
FrmAffichBilan.Show()
End Sub
Private Sub btnBilan_Click(sender As Object, e As EventArgs) Handles btnBilan.Click
Me.Hide()
FrmAffichBilan.Show()
End Sub
Private Sub btnAff_Click(sender As Object, e As EventArgs) Handles btnAff.Click
Me.Hide()
FrmEtatActuInscrip.Show()
FrmEtatActuInscrip.Reinit()
End Sub
Private Sub btnModifSuppr_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnModifSuppr.Click
Me.Hide()
FrmModifSuppr.Show()
FrmModifSuppr.Reinit()
End Sub
End Class
|
Kcchouette/Inscription-au-bac
|
FrmAccueil.vb
|
Visual Basic
|
bsd-3-clause
| 3,492
|
Option Strict On
Namespace Xeora.Web.Controller.Directive
Public Interface ILevelable
ReadOnly Property Level As Integer
ReadOnly Property LevelExecutionOnly As Boolean
End Interface
End Namespace
|
xeora/XeoraCube
|
Framework/Xeora.Web/Controller/Directive/Interface/ILevelable.vb
|
Visual Basic
|
mit
| 224
|
' 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.Threading
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Module SourceDocumentationCommentUtils
Friend Function GetAndCacheDocumentationComment(
symbol As Symbol,
preferredCulture As CultureInfo,
expandIncludes As Boolean,
ByRef lazyXmlText As String,
cancellationToken As CancellationToken
) As String
If lazyXmlText Is Nothing Then
Dim xmlText = GetDocumentationCommentForSymbol(symbol, preferredCulture, expandIncludes, cancellationToken)
Interlocked.CompareExchange(lazyXmlText, xmlText, Nothing)
End If
Return lazyXmlText
End Function
''' <summary>
''' Returns documentation comment for a type, field, property, event or method,
''' discards all the diagnostics
''' </summary>
''' <returns>
''' Returns Nothing if there is no documentation comment on the type or
''' there were errors preventing such a comment from being generated,
''' XML string otherwise
''' </returns>
Friend Function GetDocumentationCommentForSymbol(symbol As Symbol,
preferredCulture As CultureInfo,
expandIncludes As Boolean,
cancellationToken As CancellationToken) As String
Return VisualBasicCompilation.DocumentationCommentCompiler.
GetDocumentationCommentXml(symbol, expandIncludes, preferredCulture, cancellationToken)
End Function
End Module
End Namespace
|
nguerrera/roslyn
|
src/Compilers/VisualBasic/Portable/DocumentationComments/SourceDocumentationCommentUtils.vb
|
Visual Basic
|
apache-2.0
| 1,917
|
' 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.Text
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 BasicEditorConfigGeneratorTests
Inherits TestBase
<ConditionalFact(GetType(IsEnglishLocal))>
Public Sub TestEditorConfigGeneratorDefault()
Using workspace = TestWorkspace.CreateVisualBasic("")
Dim expectedText = "# Remove the line below if you want to inherit .editorconfig settings from higher directories
root = true
# Visual Basic files
[*.vb]
#### 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
file_header_template = unset
# 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
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_operator_placement_when_wrapping = beginning_of_line
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
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
dotnet_style_prefer_simplified_interpolation = true:suggestion
# Field preferences
dotnet_style_readonly_field = true:suggestion
# Parameter preferences
dotnet_code_quality_unused_parameters = all:suggestion
# Suppression preferences
dotnet_remove_unnecessary_suppression_exclusions = none
#### VB Coding Conventions ####
# Modifier preferences
visual_basic_preferred_modifier_order = partial,default,private,protected,public,friend,notoverridable,overridable,mustoverride,overloads,overrides,mustinherit,notinheritable,static,shared,shadows,readonly,writeonly,dim,const,withevents,widening,narrowing,custom,async,iterator:silent
# Expression-level preferences
visual_basic_style_prefer_isnot_expression = true:suggestion
visual_basic_style_unused_value_assignment_preference = unused_local_variable:suggestion
visual_basic_style_unused_value_expression_statement_preference = unused_local_variable:silent
#### 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, friend, private, protected, protected_friend, 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, friend, private, protected, protected_friend, 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, friend, private, protected, protected_friend, 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 = VisualBasic.Options.Formatting.CodeStylePage.TestAccessor.GetEditorConfigOptions()
Dim actualText = EditorConfigFileGenerator.Generate(editorConfigOptions, workspace.Options, LanguageNames.VisualBasic)
AssertEx.EqualOrDiff(expectedText, actualText)
End Using
End Sub
<ConditionalFact(GetType(IsEnglishLocal))>
Public Sub TestEditorConfigGeneratorToggleOptions()
Using workspace = TestWorkspace.CreateVisualBasic("")
Dim changedOptions = workspace.Options.WithChangedOption(New OptionKey2(CodeStyleOptions2.PreferExplicitTupleNames, LanguageNames.VisualBasic),
New CodeStyleOption2(Of Boolean)(False, NotificationOption2.[Error]))
Dim expectedText = "# Remove the line below if you want to inherit .editorconfig settings from higher directories
root = true
# Visual Basic files
[*.vb]
#### 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
file_header_template = unset
# 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
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_operator_placement_when_wrapping = beginning_of_line
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
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
dotnet_style_prefer_simplified_interpolation = true:suggestion
# Field preferences
dotnet_style_readonly_field = true:suggestion
# Parameter preferences
dotnet_code_quality_unused_parameters = all:suggestion
# Suppression preferences
dotnet_remove_unnecessary_suppression_exclusions = none
#### VB Coding Conventions ####
# Modifier preferences
visual_basic_preferred_modifier_order = partial,default,private,protected,public,friend,notoverridable,overridable,mustoverride,overloads,overrides,mustinherit,notinheritable,static,shared,shadows,readonly,writeonly,dim,const,withevents,widening,narrowing,custom,async,iterator:silent
# Expression-level preferences
visual_basic_style_prefer_isnot_expression = true:suggestion
visual_basic_style_unused_value_assignment_preference = unused_local_variable:suggestion
visual_basic_style_unused_value_expression_statement_preference = unused_local_variable:silent
#### 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, friend, private, protected, protected_friend, 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, friend, private, protected, protected_friend, 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, friend, private, protected, protected_friend, 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 = VisualBasic.Options.Formatting.CodeStylePage.TestAccessor.GetEditorConfigOptions()
Dim actualText = EditorConfigFileGenerator.Generate(editorConfigOptions, changedOptions, LanguageNames.VisualBasic)
AssertEx.EqualOrDiff(expectedText, actualText)
End Using
End Sub
End Class
End Namespace
|
jmarolf/roslyn
|
src/VisualStudio/Core/Test/Options/BasicEditorConfigGeneratorTests.vb
|
Visual Basic
|
mit
| 12,416
|
' 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_70
''' <summary>
''' Returns the larger of two 8-bit unsigned integers.
''' </summary>
''' <param name="val1">The first of two 8-bit unsigned integers to compare.</param>
''' <param name="val2">The second of two 8-bit unsigned integers to compare.</param>
''' <returns>Parameter or , whichever is larger.</returns>
<System.Runtime.CompilerServices.Extension> _
Public Function Max(val1 As [Byte], val2 As [Byte]) As [Byte]
Return Math.Max(val1, val2)
End Function
End Module
|
huoxudong125/Z.ExtensionMethods
|
src (VB.NET)/Z.ExtensionMethods.VB/Z.Core/System.Byte/System.Math/Byte.Max.vb
|
Visual Basic
|
mit
| 900
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
<[UseExportProvider]>
Public Class TypeBlockTests
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterClassStatement()
VerifyStatementEndConstructApplied(
before:="Class c1",
beforeCaret:={0, -1},
after:="Class c1
End Class",
afterCaret:={1, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterModuleStatement()
VerifyStatementEndConstructApplied(
before:="Module m1",
beforeCaret:={0, -1},
after:="Module m1
End Module",
afterCaret:={1, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub DontApplyForMatchedClass()
VerifyStatementEndConstructNotApplied(
text:="Class c1
End Class",
caret:={0, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterInterfaceStatement()
VerifyStatementEndConstructApplied(
before:="Interface IGoo",
beforeCaret:={0, -1},
after:="Interface IGoo
End Interface",
afterCaret:={1, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterStructureStatement()
VerifyStatementEndConstructApplied(
before:="Structure Goo",
beforeCaret:={0, -1},
after:="Structure Goo
End Structure",
afterCaret:={1, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterEnumStatement()
VerifyStatementEndConstructApplied(
before:="Enum Goo",
beforeCaret:={0, -1},
after:="Enum Goo
End Enum",
afterCaret:={1, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyGenericClass()
VerifyStatementEndConstructApplied(
before:="NameSpace X
Class C(of T)",
beforeCaret:={1, -1},
after:="NameSpace X
Class C(of T)
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyStructInAClass()
VerifyStatementEndConstructApplied(
before:="Class C
Structure s
End Class",
beforeCaret:={1, -1},
after:="Class C
Structure s
End Structure
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyClassInAModule()
VerifyStatementEndConstructApplied(
before:="Module M
Class C
End Module",
beforeCaret:={1, -1},
after:="Module M
Class C
End Class
End Module",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyClassDeclaration()
VerifyStatementEndConstructApplied(
before:="Partial Friend MustInherit Class C",
beforeCaret:={0, -1},
after:="Partial Friend MustInherit Class C
End Class",
afterCaret:={1, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyEnumInAClass()
VerifyStatementEndConstructApplied(
before:="Class C
Public Enum e
End Class",
beforeCaret:={1, -1},
after:="Class C
Public Enum e
End Enum
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidSyntax()
VerifyStatementEndConstructNotApplied(
text:="Class EC
Sub S
Class B
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidSyntax01()
VerifyStatementEndConstructNotApplied(
text:="Enum e(Of T)",
caret:={0, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidSyntax02()
VerifyStatementEndConstructNotApplied(
text:="Class C Class",
caret:={0, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyInheritsDecl()
VerifyStatementEndConstructApplied(
before:="Class C : Inherits B",
beforeCaret:={0, -1},
after:="Class C : Inherits B
End Class",
afterCaret:={1, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInheritsDeclNotApplied()
VerifyStatementEndConstructNotApplied(
text:="Class C : Inherits B
End Class",
caret:={0, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyImplementsDecl()
VerifyStatementEndConstructApplied(
before:="Class C : Implements IB",
beforeCaret:={0, -1},
after:="Class C : Implements IB
End Class",
afterCaret:={1, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyImplementsDeclNotApplied()
VerifyStatementEndConstructNotApplied(
text:="Class C : Implements IB
End Class",
caret:={0, -1})
End Sub
End Class
End Namespace
|
abock/roslyn
|
src/EditorFeatures/VisualBasicTest/EndConstructGeneration/TypeBlockTests.vb
|
Visual Basic
|
mit
| 6,622
|
' 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 Microsoft.CodeAnalysis.RuntimeMembers
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitRaiseEventStatement(node As BoundRaiseEventStatement) As BoundNode
Dim syntax = node.Syntax
Dim saveState As UnstructuredExceptionHandlingContext = LeaveUnstructuredExceptionHandlingContext(node)
' in the absence of errors invocation must be a call
'(could also be BadExpression, but that would have errors)
Dim raiseCallExpression = DirectCast(node.EventInvocation, BoundCall)
Dim result As BoundStatement
Dim receiver = raiseCallExpression.ReceiverOpt
If receiver Is Nothing OrElse receiver.IsMeReference Then
result = New BoundExpressionStatement(
syntax,
VisitExpressionNode(raiseCallExpression))
Else
Debug.Assert(receiver.Kind = BoundKind.FieldAccess)
#If DEBUG Then
' NOTE: The receiver is always as lowered as it's going to get (generally, a MeReference), so there's no need to Visit it.
Dim fieldAccess As BoundFieldAccess = DirectCast(receiver, BoundFieldAccess)
Dim fieldAccessReceiver = fieldAccess.ReceiverOpt
Debug.Assert(fieldAccessReceiver Is Nothing OrElse
fieldAccessReceiver.Kind = BoundKind.MeReference)
#End If
If node.EventSymbol.IsWindowsRuntimeEvent Then
receiver = GetWindowsRuntimeEventReceiver(syntax, receiver)
End If
' Need to null-check the receiver before invoking raise -
'
' eventField.raiseCallExpression === becomes ===>
'
' Block
' Dim temp = eventField
' if temp is Nothing GoTo skipEventRaise
' Call temp.raiseCallExpression
' skipEventRaise:
' End Block
'
Dim temp As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, receiver.Type, SynthesizedLocalKind.LoweringTemp)
Dim tempAccess As BoundLocal = New BoundLocal(syntax, temp, temp.Type).MakeCompilerGenerated
Dim tempInit = New BoundExpressionStatement(syntax,
New BoundAssignmentOperator(syntax, tempAccess, receiver, True, receiver.Type)).MakeCompilerGenerated
' replace receiver with temp.
raiseCallExpression = raiseCallExpression.Update(raiseCallExpression.Method,
raiseCallExpression.MethodGroupOpt,
tempAccess,
raiseCallExpression.Arguments,
raiseCallExpression.DefaultArguments,
raiseCallExpression.ConstantValueOpt,
isLValue:=raiseCallExpression.IsLValue,
suppressObjectClone:=raiseCallExpression.SuppressObjectClone,
type:=raiseCallExpression.Type)
Dim invokeStatement = New BoundExpressionStatement(
syntax,
VisitExpressionNode(raiseCallExpression))
Dim condition = New BoundBinaryOperator(syntax,
BinaryOperatorKind.Is,
tempAccess.MakeRValue(),
New BoundLiteral(syntax, ConstantValue.Nothing,
Me.Compilation.GetSpecialType(SpecialType.System_Object)),
False,
Me.Compilation.GetSpecialType(SpecialType.System_Boolean)).MakeCompilerGenerated
Dim skipEventRaise As New GeneratedLabelSymbol("skipEventRaise")
Dim ifNullSkip = New BoundConditionalGoto(syntax, condition, True, skipEventRaise).MakeCompilerGenerated
result = New BoundBlock(syntax,
Nothing,
ImmutableArray.Create(temp),
ImmutableArray.Create(Of BoundStatement)(
tempInit,
ifNullSkip,
invokeStatement,
New BoundLabelStatement(syntax, skipEventRaise)))
End If
RestoreUnstructuredExceptionHandlingContext(node, saveState)
If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then
result = RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, result, canThrow:=True)
End If
If Instrument(node, result) Then
result = _instrumenterOpt.InstrumentRaiseEventStatement(node, result)
End If
Return result
End Function
' If the event is a WinRT event, then the backing field is actually an EventRegistrationTokenTable,
' rather than a delegate. If this is the case, then we replace the receiver with
' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(eventField).InvocationList.
Private Function GetWindowsRuntimeEventReceiver(syntax As SyntaxNode, rewrittenReceiver As BoundExpression) As BoundExpression
Dim fieldType As NamedTypeSymbol = DirectCast(rewrittenReceiver.Type, NamedTypeSymbol)
Debug.Assert(fieldType.Name = "EventRegistrationTokenTable")
Dim getOrCreateMethod As MethodSymbol = DirectCast(Compilation.GetWellKnownTypeMember(
WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable), MethodSymbol)
Debug.Assert(getOrCreateMethod IsNot Nothing, "Checked during initial binding")
Debug.Assert(TypeSymbol.Equals(getOrCreateMethod.ReturnType, fieldType.OriginalDefinition, TypeCompareKind.ConsiderEverything), "Shape of well-known member")
getOrCreateMethod = getOrCreateMethod.AsMember(fieldType)
Dim invocationListProperty As PropertySymbol = Nothing
If TryGetWellknownMember(invocationListProperty, WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList, syntax) Then
Dim invocationListAccessor As MethodSymbol = invocationListProperty.GetMethod
If invocationListAccessor IsNot Nothing Then
invocationListAccessor = invocationListAccessor.AsMember(fieldType)
' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(_tokenTable)
Dim getOrCreateCall = New BoundCall(syntax:=syntax,
method:=getOrCreateMethod,
methodGroupOpt:=Nothing,
receiverOpt:=Nothing,
arguments:=ImmutableArray.Create(Of BoundExpression)(rewrittenReceiver),
constantValueOpt:=Nothing,
isLValue:=False,
suppressObjectClone:=False,
type:=getOrCreateMethod.ReturnType).MakeCompilerGenerated()
' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(_tokenTable).InvocationList
Dim invocationListAccessorCall = New BoundCall(syntax:=syntax,
method:=invocationListAccessor,
methodGroupOpt:=Nothing,
receiverOpt:=getOrCreateCall,
arguments:=ImmutableArray(Of BoundExpression).Empty,
constantValueOpt:=Nothing,
isLValue:=False,
suppressObjectClone:=False,
type:=invocationListAccessor.ReturnType).MakeCompilerGenerated()
Return invocationListAccessorCall
End If
Dim memberDescriptor As MemberDescriptor = WellKnownMembers.GetDescriptor(WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList)
' isWinMd only matters for set accessors, we can safely say false here
Dim accessorName As String = Binder.GetAccessorName(invocationListProperty.Name, MethodKind.PropertyGet, isWinMd:=False)
Dim info = GetDiagnosticForMissingRuntimeHelper(memberDescriptor.DeclaringTypeMetadataName, accessorName, _compilationState.Compilation.Options.EmbedVbCoreRuntime)
_diagnostics.Add(info, syntax.GetLocation())
End If
Return New BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(rewrittenReceiver), ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
End Function
End Class
End Namespace
|
VSadov/roslyn
|
src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_RaiseEvent.vb
|
Visual Basic
|
apache-2.0
| 10,539
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Implementation.EndConstructGeneration
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Internal.Log
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods
Imports Microsoft.VisualStudio.Text.Operations
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration
<ExportLanguageService(GetType(IEndConstructGenerationService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicEndConstructService
Implements IEndConstructGenerationService
Private ReadOnly _smartIndentationService As ISmartIndentationService
Private ReadOnly _undoHistoryRegistry As ITextUndoHistoryRegistry
Private ReadOnly _editorOperationsFactoryService As IEditorOperationsFactoryService
Private ReadOnly _editorOptionsFactoryService As IEditorOptionsFactoryService
<ImportingConstructor()>
Public Sub New(
smartIndentationService As ISmartIndentationService,
undoHistoryRegistry As ITextUndoHistoryRegistry,
editorOperationsFactoryService As IEditorOperationsFactoryService,
editorOptionsFactoryService As IEditorOptionsFactoryService)
ThrowIfNull(smartIndentationService)
ThrowIfNull(undoHistoryRegistry)
ThrowIfNull(editorOperationsFactoryService)
ThrowIfNull(editorOptionsFactoryService)
_smartIndentationService = smartIndentationService
_undoHistoryRegistry = undoHistoryRegistry
_editorOperationsFactoryService = editorOperationsFactoryService
_editorOptionsFactoryService = editorOptionsFactoryService
End Sub
Private Shared Function IsMissingStatementError(statement As SyntaxNode, [error] As String) As Boolean
Select Case [error]
' TODO(jasonmal): get rid of this. It is an open design goal to move missing end errors from the
' statement to the block. Besides making incremental parsing easier, it will also clean this mess up.
' Until then, I'm content with this hack.
Case "BC30012" ' Missing #End If
Return True
Case "BC30481" ' Missing End Class
Return True
Case "BC30625" ' Missing End Module
Return True
Case "BC30185" ' Missing End Enum
Return True
Case "BC30253" ' Missing End Interface
Return True
Case "BC30624" ' Missing End Structure
Return True
Case "BC30626" ' Missing End Namespace
Return True
Case "BC30026" ' Missing End Sub
Return True
Case "BC30027" ' Missing End Function
Return True
Case "BC30631" ' Missing End Get
Return True
Case "BC30633" ' Missing End Set
Return True
Case "BC30025" ' Missing End Property
Return True
Case "BC30081" ' Missing End If
Return True
Case "BC30082" ' Missing End While
Return True
Case "BC30083" ' Missing Loop
Return True
Case "BC30084" ' Missing Next
Return True
Case "BC30085" ' Missing End With
Return True
Case "BC30095" ' Missing End Select
Return True
Case "BC36008" ' Missing End Using
Return True
Case "BC30675" ' Missing End SyncLock
Return True
Case "BC30681" ' Missing #End Region
Return True
Case "BC33005" ' Missing End Operator
Return True
Case "BC36759" ' Auto-implemented properties cannot have parameters
Return True
Case "BC36673" ' Missing End Sub for Lambda
Return True
Case "BC36674" ' Missing End Function for Lambda
Return True
Case "BC30384" ' Missing End Try
Return True
Case "BC30198", "BC30199"
' These happen if I type Dim x = Function without parenthesis, so as long as we are in that content,
' count this as an acceptable error.
Return TypeOf statement Is LambdaHeaderSyntax
Case "BC31114" ' Missing End Event
Return True
End Select
Return False
End Function
Private Shared Function IsExpectedXmlNameError([error] As String) As Boolean
Return [error] = "BC31146"
End Function
Private Shared Function IsMissingXmlEndTagError([error] As String) As Boolean
Return [error] = "BC31151"
End Function
Private Shared Function IsExpectedXmlEndEmbeddedError([error] As String) As Boolean
Return [error] = "BC31159"
End Function
Private Shared Function IsExpectedXmlEndPIError([error] As String) As Boolean
Return [error] = "BC31160"
End Function
Private Shared Function IsExpectedXmlEndCommentError([error] As String) As Boolean
Return [error] = "BC31161"
End Function
Private Shared Function IsExpectedXmlEndCDataError([error] As String) As Boolean
Return [error] = "BC31162"
End Function
Private Function GetEndConstructState(textView As ITextView,
subjectBuffer As ITextBuffer,
cancellationToken As CancellationToken) As EndConstructState
Dim caretPosition = textView.GetCaretPoint(subjectBuffer)
If caretPosition Is Nothing Then
Return Nothing
End If
Dim document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges()
If document Is Nothing Then
Return Nothing
End If
Dim tree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken)
Dim tokenToLeft = tree.FindTokenOnLeftOfPosition(caretPosition.Value, cancellationToken, includeDirectives:=True, includeDocumentationComments:=True)
If tokenToLeft.Kind = SyntaxKind.None Then
Return Nothing
End If
Dim bufferOptions = _editorOptionsFactoryService.GetOptions(subjectBuffer)
Return New EndConstructState(
caretPosition.Value, New Lazy(Of SemanticModel)(Function() document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken)), tree, tokenToLeft, bufferOptions.GetNewLineCharacter())
End Function
Friend Overridable Function TryDoEndConstructForEnterKey(textView As ITextView,
subjectBuffer As ITextBuffer,
cancellationToken As CancellationToken) As Boolean
Using Logger.LogBlock(FunctionId.EndConstruct_DoStatement, cancellationToken)
Using transaction = New CaretPreservingEditTransaction(VBEditorResources.EndConstruct, textView, _undoHistoryRegistry, _editorOperationsFactoryService)
transaction.MergePolicy = AutomaticCodeChangeMergePolicy.Instance
' The user may have some text selected. In this scenario, we want to guarantee
' two things:
'
' 1) the text that was selected is deleted, as a normal pressing of an enter key
' would do. Since we're not letting the editor do it's own thing during end
' construct generation, we need to make sure the selection is deleted.
' 2) that we compute what statements we should spit assuming the selected text
' is no longer there. Consider a scenario where the user has something like:
'
' If True Then ~~~~
'
' and the completely invalid "~~~~" is selected. In VS2010, if you pressed
' enter, we would still spit enter, since we effectively view that code as
' "no longer there."
'
' The fix is simple: as a part of our transaction, we'll just delete anything
' under our selection. As long as our transaction goes through, the user won't
' suspect anything was fishy. If we don't spit, we'll cancel the transaction
' which will roll back this edit.
_editorOperationsFactoryService.GetEditorOperations(textView).ReplaceSelection("")
Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken)
If state Is Nothing Then
Return False
End If
' Are we in the middle of XML tags?
If state.TokenToLeft.Kind = SyntaxKind.GreaterThanToken Then
Dim element = state.TokenToLeft.GetAncestor(Of XmlElementSyntax)
If element IsNot Nothing Then
If element.StartTag IsNot Nothing AndAlso element.StartTag.Span.End = state.CaretPosition AndAlso
element.EndTag IsNot Nothing AndAlso element.EndTag.SpanStart = state.CaretPosition Then
InsertBlankLineBetweenXmlTags(state, textView, subjectBuffer, element)
transaction.Complete()
Return True
End If
End If
End If
' Figure out which statement that is to the left of us
Dim statement = state.TokenToLeft.FirstAncestorOrSelf(Function(n) TypeOf n Is StatementSyntax OrElse TypeOf n Is DirectiveTriviaSyntax)
' Make sure we are after the last token of the statement or
' if the statement is a single-line If statement that
' we're after the "Then" or "Else" token.
If statement Is Nothing Then
Return False
ElseIf statement.Kind = SyntaxKind.SingleLineIfStatement Then
Dim asSingleLine = DirectCast(statement, SingleLineIfStatementSyntax)
If state.TokenToLeft <> asSingleLine.ThenKeyword AndAlso
(asSingleLine.ElseClause Is Nothing OrElse
state.TokenToLeft <> asSingleLine.ElseClause.ElseKeyword) Then
Return False
End If
ElseIf statement.GetLastToken() <> state.TokenToLeft Then
Return False
End If
' Make sure we were on the same line as the last token.
Dim caretLine = subjectBuffer.CurrentSnapshot.GetLineNumberFromPosition(state.CaretPosition)
Dim lineOfLastToken = subjectBuffer.CurrentSnapshot.GetLineNumberFromPosition(state.TokenToLeft.SpanStart)
If caretLine <> lineOfLastToken Then
Return False
End If
' Make sure that we don't have any skipped trivia between our target token and
' the end of the line
Dim nextToken = state.TokenToLeft.GetNextTokenOrEndOfFile()
Dim nextTokenLine = subjectBuffer.CurrentSnapshot.GetLineNumberFromPosition(nextToken.SpanStart)
If nextToken.IsKind(SyntaxKind.EndOfFileToken) AndAlso nextTokenLine = caretLine Then
If nextToken.LeadingTrivia.Any(Function(trivia) trivia.IsKind(SyntaxKind.SkippedTokensTrivia)) Then
Return False
End If
End If
' If this is an Imports or Implements declaration, we should use the enclosing type declaration.
If TypeOf statement Is InheritsOrImplementsStatementSyntax Then
Dim baseDeclaration = DirectCast(statement, InheritsOrImplementsStatementSyntax)
Dim typeBlock = baseDeclaration.GetAncestor(Of TypeBlockSyntax)()
If typeBlock Is Nothing Then
Return False
End If
statement = typeBlock.BlockStatement
End If
If statement Is Nothing Then
Return False
End If
Dim errors = state.SyntaxTree.GetDiagnostics(statement)
If errors.Any(Function(e) Not IsMissingStatementError(statement, e.Id)) Then
If statement.Kind = SyntaxKind.SingleLineIfStatement Then
Dim asSingleLine = DirectCast(statement, SingleLineIfStatementSyntax)
Dim span = TextSpan.FromBounds(asSingleLine.IfKeyword.SpanStart, asSingleLine.ThenKeyword.Span.End)
If errors.Any(Function(e) span.Contains(e.Location.SourceSpan)) Then
Return False
End If
Else
Return False
End If
End If
' Make sure this statement does not end with the line continuation character
If statement.GetLastToken(includeZeroWidth:=True).TrailingTrivia.Any(Function(t) t.Kind = SyntaxKind.LineContinuationTrivia) Then
Return False
End If
Dim visitor = New EndConstructStatementVisitor(textView, subjectBuffer, state, cancellationToken)
Dim result = visitor.Visit(statement)
If result Is Nothing Then
Return False
End If
result.Apply(textView, subjectBuffer, state.CaretPosition, _smartIndentationService, _undoHistoryRegistry, _editorOperationsFactoryService)
transaction.Complete()
End Using
End Using
Return True
End Function
Private Sub InsertBlankLineBetweenXmlTags(state As EndConstructState, textView As ITextView, subjectBuffer As ITextBuffer, nodeToReplace As XmlElementSyntax)
' Add an extra newline first
Using edit = subjectBuffer.CreateEdit()
Dim aligningWhitespace = subjectBuffer.CurrentSnapshot.GetAligningWhitespace(state.TokenToLeft.Parent.Span.Start)
edit.Insert(state.CaretPosition, state.NewLineCharacter + aligningWhitespace)
edit.Apply()
End Using
' And now just send down a normal enter
textView.TryMoveCaretToAndEnsureVisible(New SnapshotPoint(subjectBuffer.CurrentSnapshot, state.CaretPosition))
_editorOperationsFactoryService.GetEditorOperations(textView).InsertNewLine()
End Sub
Private Shared Function GetNodeFromToken(Of T As SyntaxNode)(syntaxTree As SyntaxTree, token As SyntaxToken, expectedKind As SyntaxKind) As T
If token.Kind <> expectedKind Then
Return Nothing
End If
Return TryCast(token.Parent, T)
End Function
Private Function InsertEndTextAndUpdateCaretPosition(
view As ITextView,
subjectBuffer As ITextBuffer,
insertPosition As Integer,
caretPosition As Integer,
endText As String,
cancellationToken As CancellationToken
) As Boolean
Dim document = view.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges()
If document Is Nothing Then
Return False
End If
document.Project.Solution.Workspace.ApplyTextChanges(
document.Id, SpecializedCollections.SingletonEnumerable(
New TextChange(New TextSpan(insertPosition, 0), endText)), cancellationToken)
Dim caretPosAfterEdit = New SnapshotPoint(view.TextSnapshot, caretPosition)
view.TryMoveCaretToAndEnsureVisible(caretPosAfterEdit)
Return True
End Function
Friend Function TryDoXmlCDataEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean
Using Logger.LogBlock(FunctionId.EndConstruct_XmlCData, cancellationToken)
Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken)
If state Is Nothing Then
Return False
End If
Dim xmlCData = GetNodeFromToken(Of XmlCDataSectionSyntax)(state.SyntaxTree, state.TokenToLeft, expectedKind:=SyntaxKind.BeginCDataToken)
If xmlCData Is Nothing Then
Return False
End If
Dim errors = state.SyntaxTree.GetDiagnostics(xmlCData)
' Exactly one error is expected: ERRID_ExpectedXmlEndCData
If errors.Count <> 1 Then
Return False
End If
If Not IsExpectedXmlEndCDataError(errors(0).Id) Then
Return False
End If
Dim endText = "]]>"
Return InsertEndTextAndUpdateCaretPosition(textView, subjectBuffer, state.CaretPosition, state.TokenToLeft.Span.End, endText, cancellationToken)
End Using
End Function
Friend Function TryDoXmlCommentEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean
Using Logger.LogBlock(FunctionId.EndConstruct_XmlComment, cancellationToken)
Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken)
If state Is Nothing Then
Return False
End If
Dim xmlComment = GetNodeFromToken(Of XmlCommentSyntax)(state.SyntaxTree, state.TokenToLeft, expectedKind:=SyntaxKind.LessThanExclamationMinusMinusToken)
If xmlComment Is Nothing Then
Return False
End If
Dim errors = state.SyntaxTree.GetDiagnostics(xmlComment)
' Exactly one error is expected: ERRID_ExpectedXmlEndComment
If errors.Count <> 1 Then
Return False
End If
If Not IsExpectedXmlEndCommentError(errors(0).Id) Then
Return False
End If
Dim endText = "-->"
Return InsertEndTextAndUpdateCaretPosition(textView, subjectBuffer, state.CaretPosition, state.TokenToLeft.Span.End, endText, cancellationToken)
End Using
End Function
Friend Function TryDoXmlElementEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean
Using Logger.LogBlock(FunctionId.EndConstruct_XmlElement, cancellationToken)
Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken)
If state Is Nothing Then
Return False
End If
Dim xmlStartElement = GetNodeFromToken(Of XmlElementStartTagSyntax)(state.SyntaxTree, state.TokenToLeft, expectedKind:=SyntaxKind.GreaterThanToken)
If xmlStartElement Is Nothing Then
Return False
End If
Dim errors = state.SyntaxTree.GetDiagnostics(xmlStartElement)
' Exactly one error is expected: ERRID_MissingXmlEndTag
If errors.Count <> 1 Then
Return False
End If
If Not IsMissingXmlEndTagError(errors(0).Id) Then
Return False
End If
Dim endTagText = "</" & xmlStartElement.Name.ToString & ">"
Return InsertEndTextAndUpdateCaretPosition(textView, subjectBuffer, state.CaretPosition, state.TokenToLeft.Span.End, endTagText, cancellationToken)
End Using
End Function
Friend Function TryDoXmlEmbeddedExpressionEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean
Using Logger.LogBlock(FunctionId.EndConstruct_XmlEmbeddedExpression, cancellationToken)
Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken)
If state Is Nothing Then
Return False
End If
Dim xmlEmbeddedExpression = GetNodeFromToken(Of XmlEmbeddedExpressionSyntax)(state.SyntaxTree, state.TokenToLeft, expectedKind:=SyntaxKind.LessThanPercentEqualsToken)
If xmlEmbeddedExpression Is Nothing Then
Return False
End If
Dim errors = state.SyntaxTree.GetDiagnostics(xmlEmbeddedExpression)
' Errors should contain ERRID_ExpectedXmlEndEmbedded
If Not errors.Any(Function(e) IsExpectedXmlEndEmbeddedError(e.Id)) Then
Return False
End If
Dim endText = " %>" ' NOTE: two spaces are inserted. The caret will be moved between them
Return InsertEndTextAndUpdateCaretPosition(textView, subjectBuffer, state.CaretPosition, state.TokenToLeft.Span.End + 1, endText, cancellationToken)
End Using
End Function
Friend Function TryDoXmlProcessingInstructionEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean
Using Logger.LogBlock(FunctionId.EndConstruct_XmlProcessingInstruction, cancellationToken)
Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken)
If state Is Nothing Then
Return False
End If
Dim xmlProcessingInstruction = GetNodeFromToken(Of XmlProcessingInstructionSyntax)(state.SyntaxTree, state.TokenToLeft, expectedKind:=SyntaxKind.LessThanQuestionToken)
If xmlProcessingInstruction Is Nothing Then
Return False
End If
Dim errors = state.SyntaxTree.GetDiagnostics(xmlProcessingInstruction)
' Exactly two errors are expected: ERRID_ExpectedXmlName and ERRID_ExpectedXmlEndPI
If errors.Count <> 2 Then
Return False
End If
If Not (errors.Any(Function(e) IsExpectedXmlNameError(e.Id)) AndAlso
errors.Any(Function(e) IsExpectedXmlEndPIError(e.Id))) Then
Return False
End If
Dim endText = "?>"
Return InsertEndTextAndUpdateCaretPosition(textView, subjectBuffer, state.CaretPosition, state.TokenToLeft.Span.End, endText, cancellationToken)
End Using
End Function
Public Function TryDo(textView As ITextView, subjectBuffer As ITextBuffer, typedChar As Char, cancellationToken As CancellationToken) As Boolean Implements IEndConstructGenerationService.TryDo
Select Case typedChar
Case vbLf(0)
Return Me.TryDoEndConstructForEnterKey(textView, subjectBuffer, cancellationToken)
Case ">"c
Return Me.TryDoXmlElementEndConstruct(textView, subjectBuffer, cancellationToken)
Case "-"c
Return Me.TryDoXmlCommentEndConstruct(textView, subjectBuffer, cancellationToken)
Case "="c
Return Me.TryDoXmlEmbeddedExpressionEndConstruct(textView, subjectBuffer, cancellationToken)
Case "["c
Return Me.TryDoXmlCDataEndConstruct(textView, subjectBuffer, cancellationToken)
Case "?"c
Return Me.TryDoXmlProcessingInstructionEndConstruct(textView, subjectBuffer, cancellationToken)
End Select
Return False
End Function
End Class
End Namespace
|
droyad/roslyn
|
src/EditorFeatures/VisualBasic/EndConstructGeneration/VisualBasicEndConstructGenerationService.vb
|
Visual Basic
|
apache-2.0
| 25,400
|
' 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 My.Resources
Namespace BasicAnalyzers
''' <summary>
''' Analyzer for reporting syntax tree diagnostics, that require some semantic analysis.
''' It reports diagnostics for all source files which have at least one declaration diagnostic.
''' </summary>
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Public Class SemanticModelAnalyzer
Inherits DiagnosticAnalyzer
#Region "Descriptor fields"
Friend Shared ReadOnly Title As LocalizableString = New LocalizableResourceString(NameOf(Resources.SemanticModelAnalyzerTitle), Resources.ResourceManager, GetType(Resources))
Friend Shared ReadOnly MessageFormat As LocalizableString = New LocalizableResourceString(NameOf(Resources.SemanticModelAnalyzerMessageFormat), Resources.ResourceManager, GetType(Resources))
Friend Shared ReadOnly Description As LocalizableString = New LocalizableResourceString(NameOf(Resources.SemanticModelAnalyzerDescription), Resources.ResourceManager, GetType(Resources))
Friend Shared Rule As New DiagnosticDescriptor(DiagnosticIds.SemanticModelAnalyzerRuleId, Title, MessageFormat, DiagnosticCategories.Stateless, DiagnosticSeverity.Warning, isEnabledByDefault:=True, description:=Description)
#End Region
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(Rule)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSemanticModelAction(AddressOf AnalyzeSemanticModel)
End Sub
Private Shared Sub AnalyzeSemanticModel(context As SemanticModelAnalysisContext)
' Find just those source files with declaration diagnostics.
Dim diagnosticsCount = context.SemanticModel.GetDeclarationDiagnostics().Length
If diagnosticsCount > 0 Then
' For all such files, produce a diagnostic.
Dim diag = Diagnostic.Create(Rule, Location.None, Path.GetFileName(context.SemanticModel.SyntaxTree.FilePath), diagnosticsCount)
context.ReportDiagnostic(diag)
End If
End Sub
End Class
End Namespace
|
bbarry/roslyn
|
src/Samples/VisualBasic/Analyzers/BasicAnalyzers/BasicAnalyzers/StatelessAnalyzers/SemanticModelAnalyzer.vb
|
Visual Basic
|
apache-2.0
| 2,430
|
Class Application
' Application-level events, such as Startup, Exit, and DispatcherUnhandledException
' can be handled in this file.
End Class
|
Arc3D/arcgis-runtime-samples-dotnet
|
src/WPF/ArcGISRuntime.WPF.Samples/Samples/Security/TokenSecuredKnownUserVB/Application.xaml.vb
|
Visual Basic
|
apache-2.0
| 156
|
Namespace Ribbons.Transmittal.Search
Public Class NonBuiltTransmittals
Inherits RibbonButtonBase
Public Sub New()
_Image = ""
_Order = 1
_Text = "Non-Built Transmittals"
_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/Transmittal/Search/NonBuiltTransmittals.vb
|
Visual Basic
|
mit
| 439
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rTCobros_Año"
'-------------------------------------------------------------------------------------------'
Partial Class rTCobros_Año
Inherits vis2Formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1))
Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1))
Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
Dim lcParametro3Desde As String = goServicios.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 lcParametro6Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6))
Dim lcParametro6Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(6))
Dim lcParametro7Desde As String = cusAplicacion.goReportes.paParametrosFinales(7)
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim loComandoSeleccionar As New StringBuilder()
loComandoSeleccionar.AppendLine(" SELECT ")
loComandoSeleccionar.AppendLine(" datepart(YEAR, fec_ini) AS Año,")
loComandoSeleccionar.AppendLine(" SUM(ISNULL(Mon_Net,0)) AS Mon_Net")
loComandoSeleccionar.AppendLine(" INTO #Temporal")
loComandoSeleccionar.AppendLine(" FROM Cuentas_Cobrar")
loComandoSeleccionar.AppendLine(" WHERE Cod_Tip = 'Fact'")
loComandoSeleccionar.AppendLine(" AND Fec_Ini BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Cod_Cli BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Cod_Ven BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Status IN (" & lcParametro3Desde & ")")
loComandoSeleccionar.AppendLine(" AND Cod_Mon BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Cod_Suc BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
If lcParametro7Desde = "Igual" Then
loComandoSeleccionar.AppendLine(" AND Cuentas_Cobrar.Cod_Rev between " & lcParametro6Desde)
Else
loComandoSeleccionar.AppendLine(" AND Cuentas_Cobrar.Cod_Rev NOT between " & lcParametro6Desde)
End If
loComandoSeleccionar.AppendLine(" And " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" GROUP BY DATEPART(YEAR, fec_ini)")
loComandoSeleccionar.AppendLine(" SELECT")
loComandoSeleccionar.AppendLine(" datepart(YEAR, Cobros.fec_ini) AS Año,")
loComandoSeleccionar.AppendLine(" CASE")
loComandoSeleccionar.AppendLine(" WHEN Detalles_Cobros.Tip_Ope = 'Efectivo' THEN SUM(ISNULL(Detalles_Cobros.Mon_Net,0))")
loComandoSeleccionar.AppendLine(" ELSE 0")
loComandoSeleccionar.AppendLine(" END AS Efectivo,")
loComandoSeleccionar.AppendLine(" CASE")
loComandoSeleccionar.AppendLine(" WHEN Detalles_Cobros.Tip_Ope = 'Ticket' THEN SUM(ISNULL(Detalles_Cobros.Mon_Net,0))")
loComandoSeleccionar.AppendLine(" ELSE 0")
loComandoSeleccionar.AppendLine(" END AS Ticket,")
loComandoSeleccionar.AppendLine(" CASE")
loComandoSeleccionar.AppendLine(" WHEN Detalles_Cobros.Tip_Ope = 'Cheque' THEN SUM(ISNULL(Detalles_Cobros.Mon_Net,0))")
loComandoSeleccionar.AppendLine(" ELSE 0")
loComandoSeleccionar.AppendLine(" END AS Cheque,")
loComandoSeleccionar.AppendLine(" CASE")
loComandoSeleccionar.AppendLine(" WHEN Detalles_Cobros.Tip_Ope = 'Tarjeta' THEN SUM(ISNULL(Detalles_Cobros.Mon_Net,0))")
loComandoSeleccionar.AppendLine(" ELSE 0")
loComandoSeleccionar.AppendLine(" END AS Tarjeta,")
loComandoSeleccionar.AppendLine(" CASE")
loComandoSeleccionar.AppendLine(" WHEN Detalles_Cobros.Tip_Ope = 'Deposito' THEN SUM(ISNULL(Detalles_Cobros.Mon_Net,0))")
loComandoSeleccionar.AppendLine(" ELSE 0")
loComandoSeleccionar.AppendLine(" END AS Deposito,")
loComandoSeleccionar.AppendLine(" CASE")
loComandoSeleccionar.AppendLine(" WHEN Detalles_Cobros.Tip_Ope = 'Transferencia' THEN SUM(ISNULL(Detalles_Cobros.Mon_Net,0))")
loComandoSeleccionar.AppendLine(" ELSE 0")
loComandoSeleccionar.AppendLine(" END AS Transferencia")
loComandoSeleccionar.AppendLine(" INTO #Temporal3 ")
loComandoSeleccionar.AppendLine(" FROM Cobros Cobros")
loComandoSeleccionar.AppendLine(" JOIN Vendedores AS Vendedores ON Vendedores.Cod_Ven = Cobros.Cod_Ven ")
loComandoSeleccionar.AppendLine(" JOIN Detalles_Cobros AS Detalles_Cobros ON Detalles_Cobros.Documento = Cobros.Documento")
loComandoSeleccionar.AppendLine(" WHERE Cobros.Fec_Ini BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.Cod_Cli BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.Cod_Ven BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.Status IN (" & lcParametro3Desde & ")")
loComandoSeleccionar.AppendLine(" AND Cobros.Cod_Mon BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.Cod_Suc BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
If lcParametro7Desde = "Igual" Then
loComandoSeleccionar.AppendLine(" AND Cobros.Cod_Rev between " & lcParametro6Desde)
Else
loComandoSeleccionar.AppendLine(" AND Cobros.Cod_Rev NOT between " & lcParametro6Desde)
End If
loComandoSeleccionar.AppendLine(" And " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" GROUP BY DATEPART(YEAR, Cobros.fec_ini), Detalles_Cobros.Tip_Ope")
loComandoSeleccionar.AppendLine(" SELECT ")
loComandoSeleccionar.AppendLine(" Año, ")
loComandoSeleccionar.AppendLine(" SUM(Efectivo) AS Efectivo, ")
loComandoSeleccionar.AppendLine(" SUM(Ticket) AS Ticket, ")
loComandoSeleccionar.AppendLine(" SUM(Cheque) AS Cheque, ")
loComandoSeleccionar.AppendLine(" SUM(Tarjeta) AS Tarjeta, ")
loComandoSeleccionar.AppendLine(" SUM(Deposito) AS Deposito, ")
loComandoSeleccionar.AppendLine(" SUM(Transferencia) AS Transferencia ")
loComandoSeleccionar.AppendLine(" INTO #Temporal2 ")
loComandoSeleccionar.AppendLine(" FROM #Temporal3 ")
loComandoSeleccionar.AppendLine(" GROUP BY Año")
loComandoSeleccionar.AppendLine(" SELECT ")
loComandoSeleccionar.AppendLine(" ISNULL(#temporal.Año, #temporal2.Año) AS Año, ")
loComandoSeleccionar.AppendLine(" SUM(ISNULL(#temporal.Mon_Net,0)) AS Mon_Net,")
loComandoSeleccionar.AppendLine(" SUM(ISNULL(#temporal2.Efectivo,0)) AS Efectivo,")
loComandoSeleccionar.AppendLine(" SUM(ISNULL(#temporal2.Ticket,0)) AS Ticket,")
loComandoSeleccionar.AppendLine(" SUM(ISNULL(#temporal2.Cheque,0)) AS Cheque,")
loComandoSeleccionar.AppendLine(" SUM(ISNULL(#temporal2.Tarjeta,0)) AS Tarjeta,")
loComandoSeleccionar.AppendLine(" SUM(ISNULL(#temporal2.Deposito,0)) AS Deposito,")
loComandoSeleccionar.AppendLine(" SUM(ISNULL(#temporal2.Transferencia,0)) AS Transferencia,")
loComandoSeleccionar.AppendLine(" SUM(ISNULL(#temporal2.Efectivo,0) + ISNULL(#temporal2.Cheque,0) + ISNULL(#temporal2.Tarjeta,0) + ISNULL(#temporal2.Deposito,0) + ISNULL(#temporal2.Transferencia,0) + ISNULL(#temporal2.Ticket,0)) AS Total_Cobros")
loComandoSeleccionar.AppendLine(" FROM #Temporal #Temporal ")
loComandoSeleccionar.AppendLine(" FULL JOIN #temporal2 AS #temporal2 ON ((#temporal.Año = #temporal2.Año) ) ")
loComandoSeleccionar.AppendLine(" GROUP BY ISNULL(#temporal.Año, #temporal2.Año) ")
loComandoSeleccionar.AppendLine(" ORDER BY " & lcOrdenamiento )
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes")
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rTCobros_Año", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrTCobros_Año.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: 23/06/10: Programacion inicial
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rTCobros_Año.aspx.vb
|
Visual Basic
|
mit
| 13,884
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rAjustes_Numeros"
'-------------------------------------------------------------------------------------------'
Partial Class rAjustes_Numeros
Inherits vis2formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0))
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0))
Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
Dim lcParametro2Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(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
Dim loComandoSeleccionar As New StringBuilder()
loComandoSeleccionar.AppendLine(" SELECT Ajustes.Documento, ")
loComandoSeleccionar.AppendLine(" Ajustes.Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Ajustes.Comentario, ")
loComandoSeleccionar.AppendLine(" Ajustes.Status, ")
loComandoSeleccionar.AppendLine(" Ajustes.Cod_Mon, ")
loComandoSeleccionar.AppendLine(" Ajustes.Tip_Ori, ")
loComandoSeleccionar.AppendLine(" Ajustes.Doc_Ori, ")
loComandoSeleccionar.AppendLine(" Ajustes.Mon_Net, ")
loComandoSeleccionar.AppendLine(" Ajustes.Can_Art1 ")
loComandoSeleccionar.AppendLine(" FROM Ajustes ")
loComandoSeleccionar.AppendLine(" WHERE Ajustes.Documento between " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" And " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" And Ajustes.Fec_Ini between " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" And " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" And Ajustes.Status IN (" & lcParametro2Desde & ")")
loComandoSeleccionar.AppendLine(" And Ajustes.Tipo IN (" & lcParametro3Desde & ")")
loComandoSeleccionar.AppendLine(" And Ajustes.Cod_Rev between " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" And " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" And Ajustes.Cod_Suc between " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" And " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine("ORDER BY " & lcOrdenamiento)
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes")
' Me.mEscribirConsulta(loComandoSeleccionar.ToString())
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rAjustes_Numeros", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrAjustes_Numeros.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' JJD: 25/07/08: Codigo inicial
'-------------------------------------------------------------------------------------------'
' MVP: 01/08/08: Cambios para multi idioma, mensaje de error y clase padre.
'-------------------------------------------------------------------------------------------'
' GCR: 16/03/09: Estandarizacion de codigo y ajustes al diseño
'-------------------------------------------------------------------------------------------'
' CMS: 12/05/09: Ordenamiento
'-------------------------------------------------------------------------------------------'
' CMS: 14/05/09: Filtro “Revisión:”
'-------------------------------------------------------------------------------------------'
' AAP: 29/06/09: Filtro “Sucursal:”
'-------------------------------------------------------------------------------------------'
' CMS: 27/03/09: Filtro Tipo de Ajuste, se aplico el metodo de validacion de registro cero
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rAjustes_Numeros.aspx.vb
|
Visual Basic
|
mit
| 7,310
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rOPagos_aBeneficiarios"
'-------------------------------------------------------------------------------------------'
Partial Class rOPagos_aBeneficiarios
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(" Proveedores.Cod_Pro, ")
loComandoSeleccionar.AppendLine(" Proveedores.Nom_Pro, ")
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.Cod_Pro, ")
loComandoSeleccionar.AppendLine(" #tmpTemporal.Nom_Con, ")
loComandoSeleccionar.AppendLine(" #tmpTemporal.Nom_Pro, ")
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_Pro, ")
loComandoSeleccionar.AppendLine(" Cod_Con, ")
loComandoSeleccionar.AppendLine(" Nom_Con, ")
loComandoSeleccionar.AppendLine(" Nom_Pro ")
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_aBeneficiarios", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrOPagos_aBeneficiarios.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: 04/05/09: Codigo inicial
'-------------------------------------------------------------------------------------------'
' CMS: 17/08/09: Se Agrego el campo Proveedores.Cod_Pro
'-------------------------------------------------------------------------------------------'
' CMS: 26/03/10: Se cambio la funcion DATENAME por DATEPART
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rOPagos_aBeneficiarios.aspx.vb
|
Visual Basic
|
mit
| 13,159
|
Imports Microsoft.CodeAnalysis.Diagnostics
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Public Class MisAssignmentConstructor_Analyzer1Analyzer
Inherits Diagnostics.DiagnosticAnalyzer
Public Const DiagnosticId = "MA_001"
Friend Const Title = "Did you mean to assign to a parameter arguement?"
Friend Const MessageFormat = "Did you mean to assign to a parameter arguement? (Parameter name '{0}') "
Friend Const Category = "Naming"
Friend Shared Rule As New DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(Rule)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(Of SyntaxKind)(AddressOf AnalyzeNode, SyntaxKind.SubNewStatement)
End Sub
Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Dim constructor = TryCast(context.Node, Syntax.SubNewStatementSyntax)
If constructor Is Nothing Then Exit Sub
Dim st = constructor.SyntaxTree
Dim names = constructor.ParameterList.Parameters.Select(Function(p) p.Identifier.Identifier.GetIdentifierText)
For Each statement In DirectCast(constructor.Parent, ConstructorBlockSyntax).Statements.OfType(Of AssignmentStatementSyntax).Where(Function(a) TypeOf a.Left Is SimpleNameSyntax)
Dim lhs_Id = CType(statement.Left, SimpleNameSyntax).Identifier
If names.Contains(lhs_Id.GetIdentifierText()) Then context.ReportDiagnostic(Diagnostic.Create(Rule, Location.Create(st, statement.Left.Span), lhs_Id))
Next
End Sub
End Class
|
DotNetAnalyzers/DotNetAnalyzers
|
Analyzer_Constructor_Mis-Assignment/Analyzer_VB/Analyzer_VB/DiagnosticAnalyzer.vb
|
Visual Basic
|
mit
| 1,721
|
Imports System.Collections.ObjectModel
Public Class DataScriptInfoCollection
Inherits KeyedCollection(Of Guid, DataScriptInfo)
Protected Overrides Function GetKeyForItem(item As DataScriptInfo) As Guid
Return item.Id
End Function
End Class
|
Symmex/Snowflake
|
Source/Symmex.Snowflake.DataDeployment/DataScriptInfoCollection.vb
|
Visual Basic
|
mit
| 265
|
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 circles2d As SolidEdgeFrameworkSupport.Circles2d = Nothing
Dim circle2d As SolidEdgeFrameworkSupport.Circle2d = 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))
circles2d = profile.Circles2d
circle2d = circles2d.AddByCenterRadius(0, 0, 0.01)
circle2d.Copy()
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.Circle2d.Copy.vb
|
Visual Basic
|
mit
| 2,009
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Data.Linq
Imports System.Data.Linq.Mapping
Imports System.Linq
Imports System.Linq.Expressions
Imports System.Reflection
Namespace GMA
<Global.System.Data.Linq.Mapping.DatabaseAttribute(Name:="AgapeConnect")> _
Partial Public Class gmaDataContext
Inherits System.Data.Linq.DataContext
Private Shared mappingSource As System.Data.Linq.Mapping.MappingSource = New AttributeMappingSource()
#Region "Extensibility Method Definitions"
Partial Private Sub OnCreated()
End Sub
Partial Private Sub Insertgma_Server(instance As gma_Server)
End Sub
Partial Private Sub Updategma_Server(instance As gma_Server)
End Sub
Partial Private Sub Deletegma_Server(instance As gma_Server)
End Sub
#End Region
Public Sub New()
MyBase.New(Global.System.Configuration.ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString, mappingSource)
OnCreated
End Sub
Public Sub New(ByVal connection As String)
MyBase.New(connection, mappingSource)
OnCreated
End Sub
Public Sub New(ByVal connection As System.Data.IDbConnection)
MyBase.New(connection, mappingSource)
OnCreated
End Sub
Public Sub New(ByVal connection As String, ByVal mappingSource As System.Data.Linq.Mapping.MappingSource)
MyBase.New(connection, mappingSource)
OnCreated
End Sub
Public Sub New(ByVal connection As System.Data.IDbConnection, ByVal mappingSource As System.Data.Linq.Mapping.MappingSource)
MyBase.New(connection, mappingSource)
OnCreated
End Sub
Public ReadOnly Property gma_Servers() As System.Data.Linq.Table(Of gma_Server)
Get
Return Me.GetTable(Of gma_Server)
End Get
End Property
End Class
<Global.System.Data.Linq.Mapping.TableAttribute(Name:="dbo.gma_Servers")> _
Partial Public Class gma_Server
Implements System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
Private Shared emptyChangingEventArgs As PropertyChangingEventArgs = New PropertyChangingEventArgs(String.Empty)
Private _gmaServerId As Integer
Private _displayName As String
Private _rootUrl As String
Private _serviceURL As String
Private _addedByUser As System.Nullable(Of Integer)
#Region "Extensibility Method Definitions"
Partial Private Sub OnLoaded()
End Sub
Partial Private Sub OnValidate(action As System.Data.Linq.ChangeAction)
End Sub
Partial Private Sub OnCreated()
End Sub
Partial Private Sub OngmaServerIdChanging(value As Integer)
End Sub
Partial Private Sub OngmaServerIdChanged()
End Sub
Partial Private Sub OndisplayNameChanging(value As String)
End Sub
Partial Private Sub OndisplayNameChanged()
End Sub
Partial Private Sub OnrootUrlChanging(value As String)
End Sub
Partial Private Sub OnrootUrlChanged()
End Sub
Partial Private Sub OnserviceUrlChanging(value As String)
End Sub
Partial Private Sub OnserviceUrlChanged()
End Sub
Partial Private Sub OnaddedByUserChanging(value As System.Nullable(Of Integer))
End Sub
Partial Private Sub OnaddedByUserChanged()
End Sub
#End Region
Public Sub New()
MyBase.New
OnCreated
End Sub
<Global.System.Data.Linq.Mapping.ColumnAttribute(Storage:="_gmaServerId", AutoSync:=AutoSync.OnInsert, DbType:="Int NOT NULL IDENTITY", IsPrimaryKey:=true, IsDbGenerated:=true)> _
Public Property gmaServerId() As Integer
Get
Return Me._gmaServerId
End Get
Set
If ((Me._gmaServerId = value) _
= false) Then
Me.OngmaServerIdChanging(value)
Me.SendPropertyChanging
Me._gmaServerId = value
Me.SendPropertyChanged("gmaServerId")
Me.OngmaServerIdChanged
End If
End Set
End Property
<Global.System.Data.Linq.Mapping.ColumnAttribute(Storage:="_displayName", DbType:="NVarChar(200) NOT NULL", CanBeNull:=false)> _
Public Property displayName() As String
Get
Return Me._displayName
End Get
Set
If (String.Equals(Me._displayName, value) = false) Then
Me.OndisplayNameChanging(value)
Me.SendPropertyChanging
Me._displayName = value
Me.SendPropertyChanged("displayName")
Me.OndisplayNameChanged
End If
End Set
End Property
<Global.System.Data.Linq.Mapping.ColumnAttribute(Storage:="_rootUrl", DbType:="NVarChar(400) NOT NULL", CanBeNull:=false)> _
Public Property rootUrl() As String
Get
Return Me._rootUrl
End Get
Set
If (String.Equals(Me._rootUrl, value) = false) Then
Me.OnrootUrlChanging(value)
Me.SendPropertyChanging
Me._rootUrl = value
Me.SendPropertyChanged("rootUrl")
Me.OnrootUrlChanged
End If
End Set
End Property
<Global.System.Data.Linq.Mapping.ColumnAttribute(Storage:="_serviceURL", DbType:="NVarChar(400)")> _
Public Property serviceUrl() As String
Get
Return Me._serviceURL
End Get
Set
If (String.Equals(Me._serviceURL, value) = false) Then
Me.OnserviceUrlChanging(value)
Me.SendPropertyChanging
Me._serviceURL = value
Me.SendPropertyChanged("serviceUrl")
Me.OnserviceUrlChanged
End If
End Set
End Property
<Global.System.Data.Linq.Mapping.ColumnAttribute(Storage:="_addedByUser", DbType:="Int")> _
Public Property addedByUser() As System.Nullable(Of Integer)
Get
Return Me._addedByUser
End Get
Set
If (Me._addedByUser.Equals(value) = false) Then
Me.OnaddedByUserChanging(value)
Me.SendPropertyChanging
Me._addedByUser = value
Me.SendPropertyChanged("addedByUser")
Me.OnaddedByUserChanged
End If
End Set
End Property
Public Event PropertyChanging As PropertyChangingEventHandler Implements System.ComponentModel.INotifyPropertyChanging.PropertyChanging
Public Event PropertyChanged As PropertyChangedEventHandler Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
Protected Overridable Sub SendPropertyChanging()
If ((Me.PropertyChangingEvent Is Nothing) _
= false) Then
RaiseEvent PropertyChanging(Me, emptyChangingEventArgs)
End If
End Sub
Protected Overridable Sub SendPropertyChanged(ByVal propertyName As [String])
If ((Me.PropertyChangedEvent Is Nothing) _
= false) Then
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End If
End Sub
End Class
End Namespace
|
GlobalTechnology/OpsInABox
|
App_Code/GMA/gma.designer.vb
|
Visual Basic
|
mit
| 6,944
|
' --- Copyright (c) notice NevoWeb ---
' Copyright (c) 2008 SARL NevoWeb. www.nevoweb.com. All rights are reserved.
' Author: D.C.Lee
' ------------------------------------------------------------------------
' 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.
' ------------------------------------------------------------------------
' This copyright notice may NOT be removed, obscured or modified without written consent from the author.
' --- End copyright notice ---
Imports System
Imports System.Web
Imports System.Net
Imports System.IO
Imports NEvoWeb.Modules.NB_Store.SharedFunctions
Imports System.Collections.Specialized
Namespace NEvoWeb.Modules.NB_Store.Gateway
Public Class GatewayCheque
Inherits ChequeInterface
Public Overrides Sub CompleteOrder(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String, ByVal UpdateStock As Boolean)
Dim ordID As Integer = CurrentCart.GetCurrentCart(PortalID).OrderID
Dim ordNumber As String = ""
Dim objOCtrl As New OrderController
Dim objOInfo As NB_Store_OrdersInfo
objOInfo = objOCtrl.GetOrder(ordID)
Dim UsrID As Integer = objOInfo.UserID
If UsrID = -1 Then UsrID = 0
ordNumber = Format(PortalID, "00") & "-" & UsrID.ToString("0000#") & "-" & objOInfo.OrderID.ToString("0000#") & "-" & objOInfo.OrderDate.ToString("yyyyMMdd")
objOInfo.OrderNumber = ordNumber
objOInfo.PayType = "CHQ"
objOInfo.OrderStatusID = 80
objOInfo.OrderIsPlaced = True
If UpdateStock Then
Dim objPCtrl As New ProductController
'update stock tranction in progress
objPCtrl.UpdateModelQtyTrans(objOInfo.OrderID)
'remove qty in trans
objPCtrl.UpdateStockLevel(objOInfo.OrderID)
End If
objOCtrl.UpdateObjOrder(objOInfo)
Dim strEmailTemplate As String = GetStoreSetting(PortalID, "clientchqemail.name", Lang)
If strEmailTemplate = "" Then strEmailTemplate = "chqpayment.email"
SendEmailToClient(PortalID, GetClientEmail(PortalID, objOInfo), objOInfo.OrderNumber, objOInfo, strEmailTemplate, Lang)
strEmailTemplate = GetStoreSetting(PortalID, "managerchqemail.name", Lang)
If strEmailTemplate = "" Then strEmailTemplate = "chqpayment.email"
SendEmailToManager(PortalID, objOInfo.OrderNumber, objOInfo, strEmailTemplate)
End Sub
End Class
End Namespace
|
skamphuis/NB_Store
|
Providers/Gateway/GatewayCheque/GatewayCheque.vb
|
Visual Basic
|
mit
| 3,063
|
Public Class XErrorLogEntry
Private _LogDate As Date
Public Property LogDate() As Date
Get
Return _LogDate
End Get
Set(ByVal value As Date)
_LogDate = value
End Set
End Property
Private _Message As String
Public Property Message() As String
Get
Return _Message
End Get
Set(ByVal value As String)
_Message = value
End Set
End Property
Private _MoreDetail As String
Public Property MoreDetail() As String
Get
Return _MoreDetail
End Get
Set(ByVal value As String)
_MoreDetail = value
End Set
End Property
Public ReadOnly Property LogDateString() As String
Get
Return _LogDate.ToShortDateString
End Get
End Property
Public ReadOnly Property FulLText() As String
Get
Return LogDate
End Get
End Property
End Class
|
acrojax-open/photos2folders
|
Photos2Folders/XErrorLogEntry.vb
|
Visual Basic
|
mit
| 994
|
' 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.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Class LocalRewriter
Friend Function AddConditionSequencePoint(condition As BoundExpression, containingStatement As BoundStatement) As BoundExpression
Dim local As LocalSymbol = Nothing
Return AddConditionSequencePoint(condition, containingStatement, local, shareLocal:=False)
End Function
Friend Function AddConditionSequencePoint(condition As BoundExpression, containingStatement As BoundStatement, ByRef lazyConditionalBranchLocal As LocalSymbol) As BoundExpression
Return AddConditionSequencePoint(condition, containingStatement, lazyConditionalBranchLocal, shareLocal:=True)
End Function
Private Function AddConditionSequencePoint(condition As BoundExpression,
containingStatement As BoundStatement,
ByRef lazyConditionalBranchLocal As LocalSymbol,
shareLocal As Boolean) As BoundExpression
If condition Is Nothing OrElse Not _compilationState.Compilation.Options.EnableEditAndContinue OrElse containingStatement.WasCompilerGenerated Then
Return condition
End If
Dim conditionSyntax = condition.Syntax
' The local has to be associated with the syntax of the statement containing the condition since
' EnC source mapping only operates on statements.
If lazyConditionalBranchLocal Is Nothing Then
lazyConditionalBranchLocal = New SynthesizedLocal(_currentMethodOrLambda, condition.Type, SynthesizedLocalKind.ConditionalBranchDiscriminator, containingStatement.Syntax)
Else
Debug.Assert(lazyConditionalBranchLocal.SynthesizedKind = SynthesizedLocalKind.ConditionalBranchDiscriminator)
Debug.Assert(lazyConditionalBranchLocal.Type Is condition.Type)
End If
' Add hidden sequence point unless the condition is a constant expression.
' Constant expression must stay a const to not invalidate results of control flow analysis.
Dim valueExpression = If(condition.ConstantValueOpt Is Nothing,
New BoundSequencePointExpression(Nothing, MakeLocalRead(conditionSyntax, lazyConditionalBranchLocal), condition.Type),
condition)
Return New BoundSequence(
conditionSyntax,
If(shareLocal, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(lazyConditionalBranchLocal)),
ImmutableArray.Create(MakeAssignmentExpression(conditionSyntax, MakeLocalWrite(conditionSyntax, lazyConditionalBranchLocal), condition)),
valueExpression,
condition.Type)
End Function
Friend Function AddConditionSequencePoint(condition As BoundExpression,
conditionalBranchLocal As LocalSymbol) As BoundExpression
Debug.Assert(condition IsNot Nothing AndAlso
_compilationState.Compilation.Options.EnableEditAndContinue)
Debug.Assert(conditionalBranchLocal.SynthesizedKind = SynthesizedLocalKind.ConditionalBranchDiscriminator)
Dim conditionSyntax = condition.Syntax
' Add hidden sequence point unless the condition is a constant expression.
' Constant expression must stay a const to not invalidate results of control flow analysis.
Dim valueExpression = If(condition.ConstantValueOpt Is Nothing,
New BoundSequencePointExpression(Nothing, MakeLocalRead(conditionSyntax, conditionalBranchLocal), condition.Type),
condition)
Return New BoundSequence(
conditionSyntax,
ImmutableArray(Of LocalSymbol).Empty,
ImmutableArray.Create(MakeAssignmentExpression(conditionSyntax, MakeLocalWrite(conditionSyntax, conditionalBranchLocal), condition)),
valueExpression,
condition.Type)
End Function
Private Shared Function MakeLocalRead(syntax As VisualBasicSyntaxNode, localSym As LocalSymbol) As BoundLocal
Dim boundNode = New BoundLocal(syntax, localSym, isLValue:=False, type:=localSym.Type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Private Shared Function MakeLocalWrite(syntax As VisualBasicSyntaxNode, localSym As LocalSymbol) As BoundLocal
Dim boundNode = New BoundLocal(syntax, localSym, isLValue:=True, type:=localSym.Type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Private Shared Function MakeAssignmentExpression(syntax As VisualBasicSyntaxNode, left As BoundExpression, right As BoundExpression) As BoundExpression
Debug.Assert(left.Type = right.Type)
Dim boundNode = New BoundAssignmentOperator(syntax, left, right, suppressObjectClone:=True)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
End Class
End Namespace
|
paladique/roslyn
|
src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_SequencePoints.vb
|
Visual Basic
|
apache-2.0
| 5,571
|
Imports bv.common.Resources
Imports bv.winclient.Layout
Imports bv.winclient.Core
Public Class AboutForm
Inherits BvForm
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
HelpTopicId = Help2.HomePage
'Add any initialization after the InitializeComponent() call
'lbAppName.Text = Application.ProductName
lbVersionNumber.Text = Application.ProductVersion
lbCopyright.Text = BvMessages.Get("msgEIDSSCopyright")
LayoutCorrector.ApplySystemFont(Me)
If (Localizer.IsRtl) Then
Dim l As Integer = lbVersionNumber.Left + lbVersionNumber.Width
lbVersionNumber.Left = lbVersion.Left
lbVersion.Left = l - lbVersion.Width
End If
End Sub
'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
Friend WithEvents lbVersionNumber As DevExpress.XtraEditors.LabelControl
Private WithEvents panel1 As System.Windows.Forms.Panel
Friend WithEvents lbVersion As DevExpress.XtraEditors.LabelControl
Friend WithEvents lbCopyright As DevExpress.XtraEditors.LabelControl
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents btnOk As DevExpress.XtraEditors.SimpleButton
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(AboutForm))
Me.btnOk = New DevExpress.XtraEditors.SimpleButton()
Me.lbVersionNumber = New DevExpress.XtraEditors.LabelControl()
Me.panel1 = New System.Windows.Forms.Panel()
Me.lbVersion = New DevExpress.XtraEditors.LabelControl()
Me.lbCopyright = New DevExpress.XtraEditors.LabelControl()
Me.panel1.SuspendLayout()
Me.SuspendLayout()
'
'btnOk
'
resources.ApplyResources(Me.btnOk, "btnOk")
Me.btnOk.DialogResult = System.Windows.Forms.DialogResult.OK
Me.btnOk.Name = "btnOk"
'
'lbVersionNumber
'
Me.lbVersionNumber.Appearance.Font = CType(resources.GetObject("lbVersionNumber.Appearance.Font"), System.Drawing.Font)
Me.lbVersionNumber.Appearance.ForeColor = CType(resources.GetObject("lbVersionNumber.Appearance.ForeColor"), System.Drawing.Color)
resources.ApplyResources(Me.lbVersionNumber, "lbVersionNumber")
Me.lbVersionNumber.Name = "lbVersionNumber"
'
'panel1
'
resources.ApplyResources(Me.panel1, "panel1")
Me.panel1.Controls.Add(Me.lbCopyright)
Me.panel1.Controls.Add(Me.lbVersion)
Me.panel1.Controls.Add(Me.lbVersionNumber)
Me.panel1.Name = "panel1"
'
'lbVersion
'
Me.lbVersion.Appearance.Font = CType(resources.GetObject("LabelControl1.Appearance.Font1"), System.Drawing.Font)
Me.lbVersion.Appearance.ForeColor = CType(resources.GetObject("LabelControl1.Appearance.ForeColor"), System.Drawing.Color)
resources.ApplyResources(Me.lbVersion, "lbVersion")
Me.lbVersion.Name = "lbVersion"
'
'lbCopyright
'
Me.lbCopyright.Appearance.Font = CType(resources.GetObject("LabelControl1.Appearance.Font"), System.Drawing.Font)
Me.lbCopyright.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center
resources.ApplyResources(Me.lbCopyright, "lbCopyright")
Me.lbCopyright.Name = "lbCopyright"
'
'AboutForm
'
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None
Me.BackgroundImageLayoutStore = System.Windows.Forms.ImageLayout.None
Me.BackgroundImageStore = CType(resources.GetObject("$this.BackgroundImageStore"), System.Drawing.Image)
resources.ApplyResources(Me, "$this")
Me.Controls.Add(Me.btnOk)
Me.Controls.Add(Me.panel1)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.Name = "AboutForm"
Me.ShowInTaskbar = False
Me.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide
Me.TransparencyKey = System.Drawing.Color.FromArgb(CType(CType(192, Byte), Integer), CType(CType(192, Byte), Integer), CType(CType(0, Byte), Integer))
Me.panel1.ResumeLayout(False)
Me.ResumeLayout(False)
End Sub
#End Region
Public Shared Sub ShowMe()
Using frm As New AboutForm
frm.ShowDialog()
End Using
End Sub
End Class
|
EIDSS/EIDSS-Legacy
|
EIDSS v6.1/vb/Shared/bvwin_common/Common/AboutForm.vb
|
Visual Basic
|
bsd-2-clause
| 5,273
|
' Draws a rotating 3D tunnel
' Algorithm based on http://www.student.kuleuven.be/~m0216922/CG/tunnel.html
Public NotInheritable Class TunnelGenerator
Private _drawingSurface As Control
Private _tunnelTexture As Bitmap
Private _frameCount As Integer = -1
Private _distances(1, 1) As Integer
Private _angles(1, 1) As Integer
Public Property DrawingSurface As Control
Get
Return _drawingSurface
End Get
Private Set(value As Control)
_drawingSurface = value
End Set
End Property
Public Property TunnelTexture As Bitmap
Get
Return _tunnelTexture
End Get
Private Set(value As Bitmap)
_tunnelTexture = value
End Set
End Property
Private Function GetFrameCount() As Integer
_frameCount += 1
Return _frameCount
End Function
Public Sub New(surface As Control, texture As Bitmap)
DrawingSurface = surface
AddHandler surface.Paint, AddressOf Draw
TunnelTexture = texture
InitializeLookupTables()
End Sub
Private Sub InitializeLookupTables()
Dim textureWidth = TunnelTexture.Width
Dim textureHeight = TunnelTexture.Height
Dim w = DrawingSurface.ClientRectangle.Width
Dim h = DrawingSurface.ClientRectangle.Height
ReDim _distances(0 To w - 1, 0 To h - 1)
ReDim _angles(0 To w - 1, 0 To h - 1)
For x As Integer = 0 To w - 1
For y As Integer = 0 To h - 1
Dim ratio As Double = 32.0
_distances(x, y) = CInt(ratio * textureHeight / Math.Sqrt((x - w / 2.0) * (x - w / 2.0) + (y - h / 2.0) * (y - h / 2.0))) Mod textureHeight
_angles(x, y) = 0.5 * textureWidth * Math.Atan2(y - h / 2.0, x - w / 2.0) / Math.PI
Next
Next
End Sub
Public Sub Draw(ByVal sender As Object, ByVal e As PaintEventArgs)
Dim textureWidth = TunnelTexture.Width
Dim textureHeight = TunnelTexture.Height
Dim w = DrawingSurface.ClientRectangle.Width
Dim h = DrawingSurface.ClientRectangle.Height
Dim currentFrame = GetFrameCount()
' Calculate the shift values out of the animation value
Dim shiftX = CInt(textureWidth * 1.0 * currentFrame)
Dim shiftY = CInt(textureHeight * 0.25 * currentFrame)
Using b As New Bitmap(w, h, e.Graphics)
For x As Integer = 0 To w - 1
For y As Integer = 0 To h - 1
' Get the texel from the texture by using the tables, shifted with the animation values
Dim newX = (_distances(x, y) + shiftX) Mod textureWidth
Dim newY = Math.Abs((_angles(x, y) + shiftY) Mod textureHeight)
Dim c = TunnelTexture.GetPixel(newX, newY)
b.SetPixel(x, y, c)
Next
Next
e.Graphics.DrawImage(b, 0, 0)
End Using
End Sub
End Class
|
kaiaie/DisplayHacks
|
Tunnel/TunnelGenerator.vb
|
Visual Basic
|
bsd-3-clause
| 3,012
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Imports System
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("Demos.WPF.VisualBasic.GanttChartDataGrid.SpecialDays.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
|
DlhSoftTeam/GanttChartLightLibrary-Demos
|
GanttChartLightLibraryDemos/Demos/Samples/WPF-VisualBasic/GanttChartDataGrid/SpecialDays/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,758
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.EventHandling
Public Class AddHandlerKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AddHandlerHelpTextTest() As Task
Await VerifyRecommendationDescriptionTextIsAsync(<MethodBody>|</MethodBody>, "AddHandler",
$"{VBFeaturesResources.AddHandler_statement}
{VBWorkspaceResources.Associates_an_event_with_an_event_handler_delegate_or_lambda_expression_at_run_time}
AddHandler {VBWorkspaceResources.event_}, {VBWorkspaceResources.handler}")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AddHandlerInMethodBodyTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>|</MethodBody>, "AddHandler")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AddHandlerAfterStatementTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>
Dim x
|</MethodBody>, "AddHandler")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AddHandlerMissingInClassBlockTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>|</ClassDeclaration>, "AddHandler")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AddHandlerInSingleLineLambdaTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = Sub() |</MethodBody>, "AddHandler")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AddHandlerInSingleLineFunctionLambdaTest() As Task
Await VerifyRecommendationsMissingAsync(<MethodBody>Dim x = Function() |</MethodBody>, "AddHandler")
End Function
<Fact>
<WorkItem(808406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/808406")>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AddHandlerInCustomEventTest() As Task
Dim code = <File>
Public Class Z
Public Custom Event E As Action
|
End Event
End Class</File>
Await VerifyRecommendationsContainAsync(code, "AddHandler")
End Function
<Fact>
<WorkItem(808406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/808406")>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NotAddHandlerInCustomEventWithAddHandlerTest() As Task
Dim code = <File>
Public Class Z
Public Custom Event E As Action
AddHandler(z as Action)
End AddHandler
|
End Event
End Class</File>
Await VerifyRecommendationsMissingAsync(code, "AddHandler")
End Function
End Class
End Namespace
|
abock/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/EventHandling/AddHandlerKeywordRecommenderTests.vb
|
Visual Basic
|
mit
| 3,281
|
' 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 Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.MakeMethodAsynchronous
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.MakeMethodAsynchronous
<ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicMakeMethodAsynchronousCodeFixProvider
Inherits AbstractMakeMethodAsynchronousCodeFixProvider
Friend Const BC36937 As String = "BC36937" ' error BC36937: 'Await' can only be used when contained within a method or lambda expression marked with the 'Async' modifier.
Friend Const BC37057 As String = "BC37057" ' error BC37057: 'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task'.
Friend Const BC37058 As String = "BC37058" ' error BC37058: 'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task'.
Friend Const BC37059 As String = "BC37059" ' error BC37059: 'Await' can only be used within an Async lambda expression. Consider marking this expression with the 'Async' modifier and changing its return type to 'Task'.
Private Shared ReadOnly s_diagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(
BC36937, BC37057, BC37058, BC37059)
Private Shared ReadOnly s_asyncToken As SyntaxToken = SyntaxFactory.Token(SyntaxKind.AsyncKeyword)
Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String)
Get
Return s_diagnosticIds
End Get
End Property
Protected Overrides Function GetMakeAsyncTaskFunctionResource() As String
Return VBFeaturesResources.Make_Async_Function
End Function
Protected Overrides Function GetMakeAsyncVoidFunctionResource() As String
Return VBFeaturesResources.Make_Async_Sub
End Function
Protected Overrides Function IsAsyncSupportingFunctionSyntax(node As SyntaxNode) As Boolean
Return node.IsAsyncSupportedFunctionSyntax()
End Function
Protected Overrides Function AddAsyncTokenAndFixReturnType(
keepVoid As Boolean, methodSymbolOpt As IMethodSymbol, node As SyntaxNode,
taskType As INamedTypeSymbol, taskOfTType As INamedTypeSymbol, valueTaskOfTType As INamedTypeSymbol) As SyntaxNode
If node.IsKind(SyntaxKind.SingleLineSubLambdaExpression) OrElse
node.IsKind(SyntaxKind.SingleLineFunctionLambdaExpression) Then
Return FixSingleLineLambdaExpression(DirectCast(node, SingleLineLambdaExpressionSyntax))
ElseIf node.IsKind(SyntaxKind.MultiLineSubLambdaExpression) OrElse
node.IsKind(SyntaxKind.MultiLineFunctionLambdaExpression) Then
Return FixMultiLineLambdaExpression(DirectCast(node, MultiLineLambdaExpressionSyntax))
ElseIf node.IsKind(SyntaxKind.SubBlock) Then
Return FixSubBlock(keepVoid, DirectCast(node, MethodBlockSyntax), taskType)
Else
Return FixFunctionBlock(
methodSymbolOpt, DirectCast(node, MethodBlockSyntax), taskType, taskOfTType, valueTaskOfTType)
End If
End Function
Private Function FixFunctionBlock(methodSymbol As IMethodSymbol, node As MethodBlockSyntax,
taskType As INamedTypeSymbol, taskOfTType As INamedTypeSymbol, valueTaskOfTType As INamedTypeSymbol) As SyntaxNode
Dim functionStatement = node.SubOrFunctionStatement
Dim newFunctionStatement = AddAsyncKeyword(functionStatement)
If Not IsTaskLike(methodSymbol.ReturnType, taskType, taskOfTType, valueTaskOfTType) Then
' if the current return type is not already task-list, then wrap it in Task(of ...)
Dim returnType = taskOfTType.Construct(methodSymbol.ReturnType).GenerateTypeSyntax()
newFunctionStatement = newFunctionStatement.WithAsClause(
newFunctionStatement.AsClause.WithType(returnType))
End If
Return node.WithSubOrFunctionStatement(newFunctionStatement)
End Function
Private Function FixSubBlock(
keepVoid As Boolean, node As MethodBlockSyntax, taskType As INamedTypeSymbol) As SyntaxNode
If keepVoid Then
' User wants to keep this a void method, so keep this as a sub.
Dim newSubStatement = AddAsyncKeyword(node.SubOrFunctionStatement)
Return node.WithSubOrFunctionStatement(newSubStatement)
End If
' Have to convert this sub into a func.
Dim subStatement = node.SubOrFunctionStatement
Dim asClause =
SyntaxFactory.SimpleAsClause(taskType.GenerateTypeSyntax()).
WithTrailingTrivia(
If(subStatement.ParameterList?.GetTrailingTrivia(),
subStatement.GetTrailingTrivia()))
Dim functionStatement = SyntaxFactory.FunctionStatement(
subStatement.AttributeLists,
subStatement.Modifiers.Add(s_asyncToken),
SyntaxFactory.Token(SyntaxKind.FunctionKeyword).WithTriviaFrom(subStatement.SubOrFunctionKeyword),
subStatement.Identifier.WithTrailingTrivia(),
subStatement.TypeParameterList?.WithoutTrailingTrivia(),
subStatement.ParameterList?.WithoutTrailingTrivia(),
asClause,
subStatement.HandlesClause,
subStatement.ImplementsClause)
Dim endFunctionStatement = SyntaxFactory.EndFunctionStatement(
node.EndSubOrFunctionStatement.EndKeyword,
SyntaxFactory.Token(SyntaxKind.FunctionKeyword).WithTriviaFrom(node.EndSubOrFunctionStatement.BlockKeyword))
Dim block = SyntaxFactory.FunctionBlock(
functionStatement,
node.Statements,
endFunctionStatement)
Return block
End Function
Private Shared Function AddAsyncKeyword(subOrFunctionStatement As MethodStatementSyntax) As MethodStatementSyntax
Dim modifiers = subOrFunctionStatement.Modifiers
Dim newModifiers = modifiers.Add(s_asyncToken)
Return subOrFunctionStatement.WithModifiers(newModifiers)
End Function
Private Function FixMultiLineLambdaExpression(node As MultiLineLambdaExpressionSyntax) As SyntaxNode
Dim header As LambdaHeaderSyntax = GetNewHeader(node)
Return node.WithSubOrFunctionHeader(header).WithLeadingTrivia(node.GetLeadingTrivia())
End Function
Private Function FixSingleLineLambdaExpression(node As SingleLineLambdaExpressionSyntax) As SingleLineLambdaExpressionSyntax
Dim header As LambdaHeaderSyntax = GetNewHeader(node)
Return node.WithSubOrFunctionHeader(header).WithLeadingTrivia(node.GetLeadingTrivia())
End Function
Private Shared Function GetNewHeader(node As LambdaExpressionSyntax) As LambdaHeaderSyntax
Dim header = DirectCast(node.SubOrFunctionHeader, LambdaHeaderSyntax)
Dim newModifiers = header.Modifiers.Add(s_asyncToken)
Dim newHeader = header.WithModifiers(newModifiers)
Return newHeader
End Function
End Class
End Namespace
|
yeaicc/roslyn
|
src/Features/VisualBasic/Portable/MakeMethodAsynchronous/VisualBasicMakeMethodAsynchronousCodeFixProvider.vb
|
Visual Basic
|
apache-2.0
| 7,818
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Test.Extensions
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class PartialMethodsTest
Inherits BasicTestBase
<Fact()>
Public Sub MergePartialMethodAndParameterSymbols()
Dim text1 = <text>
Imports System
Partial Public Class C1
Partial Private Sub M(i As Integer)
End Sub
End Class
</text>.Value.Trim()
Dim text2 = <text>
Imports System
Partial Public Class C1
Private Sub M(i As Integer)
Console.WriteLine()
End Sub
End Class
</text>.Value.Trim()
Dim tree1 = ParseAndVerify(text1)
Dim tree2 = ParseAndVerify(text2)
Dim comp = CreateCompilationWithMscorlib40({tree1, tree2})
Dim pTypeSym = comp.SourceModule.GlobalNamespace.GetTypeMembers("C1").Single()
Assert.Equal("C1", pTypeSym.ToDisplayString())
Dim methods = pTypeSym.GetMembers("M")
Assert.Equal(1, methods.Length)
Dim methodDecl = TryCast(methods(0), MethodSymbol)
Assert.NotNull(methodDecl)
Assert.Equal("Private Sub M(i As Integer)", methodDecl.ToDisplayString())
Dim methodImpl = methodDecl.PartialImplementationPart
Assert.NotNull(methodImpl)
Assert.Equal("Private Sub M(i As Integer)", methodImpl.ToDisplayString())
Assert.Same(methodDecl, methodImpl.PartialDefinitionPart)
Assert.Null(methodImpl.PartialImplementationPart)
Assert.Null(methodDecl.PartialDefinitionPart)
Dim model1 = comp.GetSemanticModel(tree1)
Dim pType01 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of ClassBlockSyntax)().First()
Dim model2 = comp.GetSemanticModel(tree2)
Dim pType02 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of ClassBlockSyntax)().First()
Assert.NotEqual(pType01, pType02)
Dim ptSym01 = model1.GetDeclaredSymbol(pType01)
Dim ptSym02 = model2.GetDeclaredSymbol(pType02)
Assert.Same(ptSym01, ptSym02)
Assert.Equal(2, ptSym01.Locations.Length)
Dim pMethod01 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodBlockSyntax)().First()
Dim pMethod02 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodBlockSyntax)().First()
Assert.NotEqual(pMethod01, pMethod02)
Dim pmSym01 = model1.GetDeclaredSymbol(pMethod01)
Dim pmSym02 = model2.GetDeclaredSymbol(pMethod02)
Assert.NotSame(pmSym01, pmSym02)
Assert.Same(methodDecl, pmSym01)
Assert.Same(methodImpl, pmSym02)
Assert.Equal(1, pmSym01.Locations.Length)
Assert.Equal(1, pmSym02.Locations.Length)
Dim pParam01 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of ParameterSyntax)().First()
Dim pParam02 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of ParameterSyntax)().First()
Assert.NotEqual(pParam01, pParam02)
Dim ppSym01 = model1.GetDeclaredSymbol(pParam01)
Dim ppSym02 = model2.GetDeclaredSymbol(pParam02)
Assert.NotSame(ppSym01, ppSym02)
Assert.Equal(1, ppSym01.Locations.Length)
Assert.Equal(1, ppSym02.Locations.Length)
End Sub
<Fact()>
Public Sub MergePartialMethodAndTypeParameterSymbols()
Dim text1 = <text>
Imports System
Partial Public Class C1
Partial Private Sub M(Of T)(i As T)
End Sub
End Class
</text>.Value.Trim()
Dim text2 = <text>
Imports System
Partial Public Class C1
Private Sub M(Of T)(i As T)
Console.WriteLine()
End Sub
End Class
</text>.Value.Trim()
Dim tree1 = ParseAndVerify(text1)
Dim tree2 = ParseAndVerify(text2)
Dim comp = CreateCompilationWithMscorlib40({tree1, tree2})
Dim pTypeSym = comp.SourceModule.GlobalNamespace.GetTypeMembers("C1").Single()
Assert.Equal("C1", pTypeSym.ToDisplayString())
Dim methods = pTypeSym.GetMembers("M")
Assert.Equal(1, methods.Length)
Dim methodDecl = TryCast(methods(0), MethodSymbol)
Assert.NotNull(methodDecl)
Assert.Equal("Private Sub M(Of T)(i As T)", methodDecl.ToDisplayString())
Dim methodImpl = methodDecl.PartialImplementationPart
Assert.NotNull(methodImpl)
Assert.Equal("Private Sub M(Of T)(i As T)", methodImpl.ToDisplayString())
Assert.Same(methodDecl, methodImpl.PartialDefinitionPart)
Assert.Null(methodImpl.PartialImplementationPart)
Assert.Null(methodDecl.PartialDefinitionPart)
Dim model1 = comp.GetSemanticModel(tree1)
Dim pType01 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of ClassBlockSyntax)().First()
Dim model2 = comp.GetSemanticModel(tree2)
Dim pType02 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of ClassBlockSyntax)().First()
Assert.NotEqual(pType01, pType02)
Dim ptSym01 = model1.GetDeclaredSymbol(pType01)
Dim ptSym02 = model2.GetDeclaredSymbol(pType02)
Assert.Same(ptSym01, ptSym02)
Assert.Equal(2, ptSym01.Locations.Length)
Dim pMethod01 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodBlockSyntax)().First()
Dim pMethod02 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodBlockSyntax)().First()
Assert.NotEqual(pMethod01, pMethod02)
Dim pmSym01 = model1.GetDeclaredSymbol(pMethod01)
Dim pmSym02 = model2.GetDeclaredSymbol(pMethod02)
Assert.NotSame(pmSym01, pmSym02)
Assert.Same(methodDecl, pmSym01)
Assert.Same(methodImpl, pmSym02)
Assert.Equal(1, pmSym01.Locations.Length)
Assert.Equal(1, pmSym02.Locations.Length)
Dim pTypeParam01 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of TypeParameterSyntax)().First()
Dim pTypeParam02 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of TypeParameterSyntax)().First()
Assert.NotEqual(pTypeParam01, pTypeParam02)
Dim ppSym01 = model1.GetDeclaredSymbol(pTypeParam01)
Dim ppSym02 = model2.GetDeclaredSymbol(pTypeParam02)
Assert.NotSame(ppSym01, ppSym02)
Assert.Equal(1, ppSym01.Locations.Length)
Assert.Equal(1, ppSym02.Locations.Length)
End Sub
<Fact()>
Public Sub ConflictingPartialMethodDeclarations()
Dim text1 = <text>
Imports System
Partial Public Class C1
Partial Private Sub M(i As Integer)
End Sub
End Class
</text>.Value.Trim()
Dim text2 = <text>
Imports System
Partial Public Class C1
Partial Private Sub M(i As Integer)
Console.WriteLine()
End Sub
End Class
</text>.Value.Trim()
Dim tree1 = ParseAndVerify(text1)
Dim tree2 = ParseAndVerify(text2)
Dim comp = CreateCompilationWithMscorlib40({tree1, tree2})
Dim pTypeSym = comp.SourceModule.GlobalNamespace.GetTypeMembers("C1").Single()
Assert.Equal("C1", pTypeSym.ToDisplayString())
Dim methods = pTypeSym.GetMembers("M")
Assert.Equal(2, methods.Length)
Dim methodDecl1 = TryCast(methods(0), MethodSymbol)
Assert.NotNull(methodDecl1)
Assert.Equal("Private Sub M(i As Integer)", methodDecl1.ToDisplayString())
Assert.Null(methodDecl1.PartialImplementationPart)
Assert.Null(methodDecl1.PartialDefinitionPart)
Dim methodDecl2 = TryCast(methods(1), MethodSymbol)
Assert.NotNull(methodDecl2)
Assert.Equal("Private Sub M(i As Integer)", methodDecl2.ToDisplayString())
Assert.Null(methodDecl2.PartialImplementationPart)
Assert.Null(methodDecl2.PartialDefinitionPart)
Assert.NotSame(methodDecl1, methodDecl2)
Dim model1 = comp.GetSemanticModel(tree1)
Dim pType01 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of ClassBlockSyntax)().First()
Dim model2 = comp.GetSemanticModel(tree2)
Dim pType02 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of ClassBlockSyntax)().First()
Assert.NotEqual(pType01, pType02)
Dim ptSym01 = model1.GetDeclaredSymbol(pType01)
Dim ptSym02 = model2.GetDeclaredSymbol(pType02)
Assert.Same(ptSym01, ptSym02)
Assert.Equal(2, ptSym01.Locations.Length)
Dim pMethod01 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodBlockSyntax)().First()
Dim pMethod02 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodBlockSyntax)().First()
Assert.NotEqual(pMethod01, pMethod02)
Dim pmSym01 = model1.GetDeclaredSymbol(pMethod01)
Dim pmSym02 = model2.GetDeclaredSymbol(pMethod02)
Assert.NotSame(pmSym01, pmSym02)
Assert.Same(methodDecl1, pmSym01)
Assert.Same(methodDecl2, pmSym02)
Assert.Equal(1, pmSym01.Locations.Length)
Assert.Equal(1, pmSym02.Locations.Length)
Dim pParam01 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of ParameterSyntax)().First()
Dim pParam02 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of ParameterSyntax)().First()
Assert.NotEqual(pParam01, pParam02)
Dim ppSym01 = model1.GetDeclaredSymbol(pParam01)
Dim ppSym02 = model2.GetDeclaredSymbol(pParam02)
Assert.NotSame(ppSym01, ppSym02)
Assert.Equal(1, ppSym01.Locations.Length)
Assert.Equal(1, ppSym02.Locations.Length)
End Sub
<WorkItem(545469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545469")>
<Fact()>
Public Sub MetadataNameOnPartialMethodImplementation()
Dim text1 = <text>
Imports System
Public Module Module1
Partial Private Sub GOo(Of T As Class, U As T, V As {U, Exception})(aa As T, y As U, z As V)
End Sub
Private Sub goo(Of T As Class, U As T, V As {U, Exception})(aa As T, y As U, z As V)
Console.WriteLine("goo")
End Sub
Sub Main()
End Sub
End Module
</text>.Value.Trim()
Dim tree1 = ParseAndVerify(text1)
Dim comp = CreateCompilationWithMscorlib40({tree1})
Dim model = comp.GetSemanticModel(tree1)
Dim id = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodStatementSyntax).
Where(Function(node) node.Identifier.ValueText = "goo").First()
Dim method = model.GetDeclaredSymbol(id)
Dim unused = method.MetadataName
End Sub
<Fact()>
Public Sub ConflictingPartialMethodImplementations()
Dim text1 = <text>
Imports System
Partial Public Class C1
Partial Private Sub M(i As Integer)
End Sub
End Class
</text>.Value.Trim()
Dim text2 = <text>
Imports System
Partial Public Class C1
Private Sub M(i As Integer)
Console.WriteLine()
End Sub
End Class
</text>.Value.Trim()
Dim text3 = <text>
Imports System
Partial Public Class C1
Private Sub M(i As Integer)
Console.WriteLine()
End Sub
End Class
</text>.Value.Trim()
Dim tree1 = ParseAndVerify(text1)
Dim tree2 = ParseAndVerify(text2)
Dim tree3 = ParseAndVerify(text3)
Dim comp = CreateCompilationWithMscorlib40({tree1, tree2, tree3})
Dim pTypeSym = comp.SourceModule.GlobalNamespace.GetTypeMembers("C1").Single()
Assert.Equal("C1", pTypeSym.ToDisplayString())
Assert.Equal(3, pTypeSym.Locations.Length)
Dim methods = pTypeSym.GetMembers("M")
Assert.Equal(2, methods.Length)
Dim methodDecl = TryCast(methods(0), MethodSymbol)
Assert.NotNull(methodDecl)
Assert.Equal("Private Sub M(i As Integer)", methodDecl.ToDisplayString())
Dim methodImpl = methodDecl.PartialImplementationPart
Assert.NotNull(methodImpl)
Assert.Equal("Private Sub M(i As Integer)", methodImpl.ToDisplayString())
Assert.Same(methodDecl, methodImpl.PartialDefinitionPart)
Assert.Null(methodImpl.PartialImplementationPart)
Assert.Null(methodDecl.PartialDefinitionPart)
Dim methodImplBad = TryCast(methods(1), MethodSymbol)
Assert.NotNull(methodImplBad)
Assert.Equal("Private Sub M(i As Integer)", methodImplBad.ToDisplayString())
Assert.NotSame(methodDecl, methodImplBad)
Assert.NotSame(methodImpl, methodImplBad)
Assert.Null(methodImplBad.PartialImplementationPart)
Assert.Null(methodImplBad.PartialDefinitionPart)
Dim model1 = comp.GetSemanticModel(tree1)
Dim pType01 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of ClassBlockSyntax)().First()
Dim model2 = comp.GetSemanticModel(tree2)
Dim pType02 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of ClassBlockSyntax)().First()
Assert.NotEqual(pType01, pType02)
Dim model3 = comp.GetSemanticModel(tree3)
Dim pType03 = tree3.GetCompilationUnitRoot().DescendantNodes().OfType(Of ClassBlockSyntax)().First()
Assert.NotEqual(pType01, pType03)
Assert.NotEqual(pType02, pType03)
Dim ptSym01 = model1.GetDeclaredSymbol(pType01)
Dim ptSym02 = model2.GetDeclaredSymbol(pType02)
Dim ptSym03 = model2.GetDeclaredSymbol(pType02)
Assert.Same(pTypeSym, ptSym01)
Assert.Same(pTypeSym, ptSym02)
Assert.Same(pTypeSym, ptSym03)
Dim pMethod01 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodBlockSyntax)().First()
Dim pMethod02 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodBlockSyntax)().First()
Dim pMethod03 = tree3.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodBlockSyntax)().First()
Assert.NotEqual(pMethod01, pMethod02)
Assert.NotEqual(pMethod01, pMethod03)
Assert.NotEqual(pMethod03, pMethod02)
Dim pmSym01 = model1.GetDeclaredSymbol(pMethod01)
Dim pmSym02 = model2.GetDeclaredSymbol(pMethod02)
Dim pmSym03 = model3.GetDeclaredSymbol(pMethod03)
Assert.NotSame(pmSym01, pmSym02)
Assert.NotSame(pmSym01, pmSym03)
Assert.NotSame(pmSym03, pmSym02)
Assert.Same(methodDecl, pmSym01)
Assert.Same(methodImpl, pmSym02)
Assert.Same(methodImplBad, pmSym03)
Assert.Equal(1, pmSym01.Locations.Length)
Assert.Equal(1, pmSym02.Locations.Length)
End Sub
<Fact()>
Public Sub MergeMethodAttributes()
Dim text1 = <text>
Imports System
Imports System.Reflection
<AttributeUsage(AttributeTargets.All, AllowMultiple:=False)>
Class A1
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.All, AllowMultiple:=True)>
Class A2
Inherits Attribute
End Class
Partial Public Class C1
<A1(), A2()>
Partial Private Sub M(i As Integer)
End Sub
End Class
</text>.Value.Trim()
Dim text2 = <text>
Imports System
Partial Public Class C1
<A2()>
Private Sub M(i As Integer)
Console.WriteLine()
End Sub
End Class
</text>.Value.Trim()
Dim tree1 = ParseAndVerify(text1)
Dim tree2 = ParseAndVerify(text2)
Dim comp = CreateCompilationWithMscorlib40({tree1, tree2})
Dim pTypeSym = comp.SourceModule.GlobalNamespace.GetTypeMembers("C1").Single()
Assert.Equal("C1", pTypeSym.ToDisplayString())
Dim methods = pTypeSym.GetMembers("M")
Assert.Equal(1, methods.Length)
Dim methodDecl = TryCast(methods(0), MethodSymbol)
Assert.NotNull(methodDecl)
Assert.Equal("Private Sub M(i As Integer)", methodDecl.ToDisplayString())
Dim attributes = methodDecl.GetAttributes()
Assert.Equal(3, attributes.Length)
End Sub
<Fact()>
Public Sub MergeMethodParametersAttributes()
Dim text1 = <text>
Imports System
Imports System.Reflection
<AttributeUsage(AttributeTargets.All, AllowMultiple:=False)>
Class A1
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.All, AllowMultiple:=True)>
Class A2
Inherits Attribute
End Class
Partial Public Class C1
Partial Private Sub M(<A1(), A2()> i As Integer)
End Sub
End Class
</text>.Value.Trim()
Dim text2 = <text>
Imports System
Partial Public Class C1
Private Sub M(<A2()> i As Integer)
Console.WriteLine()
End Sub
End Class
</text>.Value.Trim()
Dim tree1 = ParseAndVerify(text1)
Dim tree2 = ParseAndVerify(text2)
Dim comp = CreateCompilationWithMscorlib40({tree1, tree2})
Dim pTypeSym = comp.SourceModule.GlobalNamespace.GetTypeMembers("C1").Single()
Assert.Equal("C1", pTypeSym.ToDisplayString())
Dim methods = pTypeSym.GetMembers("M")
Assert.Equal(1, methods.Length)
Dim methodDecl = TryCast(methods(0), MethodSymbol)
Assert.NotNull(methodDecl)
Assert.Equal("Private Sub M(i As Integer)", methodDecl.ToDisplayString())
Assert.Equal(1, methodDecl.ParameterCount)
Dim parameter = TryCast(methodDecl.Parameters(0), ParameterSymbol)
Assert.NotNull(parameter)
Assert.Equal("i As Integer", parameter.ToDisplayString())
Dim attributes = parameter.GetAttributes()
Assert.Equal(3, attributes.Length)
End Sub
<Fact()>
Public Sub MergeMethodParametersAttributes2()
Dim text1 = <text>
Imports System
Imports System.Reflection
<AttributeUsage(AttributeTargets.All, AllowMultiple:=False)>
Class A1
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.All, AllowMultiple:=True)>
Class A2
Inherits Attribute
End Class
Partial Public Class C1
Partial Private Sub M(i As Integer)
End Sub
End Class
</text>.Value.Trim()
Dim text2 = <text>
Imports System
Partial Public Class C1
Private Sub M(<A1(), A2()> i As Integer)
Console.WriteLine()
End Sub
End Class
</text>.Value.Trim()
Dim tree1 = ParseAndVerify(text1)
Dim tree2 = ParseAndVerify(text2)
Dim comp = CreateCompilationWithMscorlib40({tree1, tree2})
Dim pTypeSym = comp.SourceModule.GlobalNamespace.GetTypeMembers("C1").Single()
Assert.Equal("C1", pTypeSym.ToDisplayString())
Dim methods = pTypeSym.GetMembers("M")
Assert.Equal(1, methods.Length)
Dim methodDecl = TryCast(methods(0), MethodSymbol)
Assert.NotNull(methodDecl)
Assert.Equal("Private Sub M(i As Integer)", methodDecl.ToDisplayString())
Assert.Equal(1, methodDecl.ParameterCount)
Dim parameter = TryCast(methodDecl.Parameters(0), ParameterSymbol)
Assert.NotNull(parameter)
Assert.Equal("i As Integer", parameter.ToDisplayString())
Dim attributes = parameter.GetAttributes()
Assert.Equal(2, attributes.Length)
End Sub
<Fact()>
Public Sub MergeMethodParametersAttributes_NoDuplication()
Dim text1 = <text><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All, AllowMultiple:=False)>
Class A1
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.All, AllowMultiple:=True)>
Class A2
Inherits Attribute
End Class
Partial Public Class C1
Partial Private Sub M(<A2()> i As Integer)
End Sub
End Class
]]>
</text>.Value.Trim()
Dim text2 = <text><![CDATA[
Imports System
Partial Public Class C1
Private Sub M(<A1(), A1(), A2()> i As Integer)
Console.WriteLine()
End Sub
End Class
]]>
</text>.Value.Trim()
Dim tree1 = ParseAndVerify(text1)
Dim tree2 = ParseAndVerify(text2)
Dim comp = CreateCompilationWithMscorlib40({tree1, tree2}, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim pTypeSym = comp.SourceModule.GlobalNamespace.GetTypeMembers("C1").Single()
Assert.Equal("C1", pTypeSym.ToDisplayString())
Dim methods = pTypeSym.GetMembers("M")
Assert.Equal(1, methods.Length)
Dim methodDecl = TryCast(methods(0), MethodSymbol)
Assert.NotNull(methodDecl)
Assert.Equal("Private Sub M(i As Integer)", methodDecl.ToDisplayString())
Assert.Equal(1, methodDecl.ParameterCount)
Dim parameter = TryCast(methodDecl.Parameters(0), ParameterSymbol)
Assert.NotNull(parameter)
Assert.Equal("i As Integer", parameter.ToDisplayString())
Dim attributes = parameter.GetAttributes()
Assert.Equal(4, attributes.Length)
parameter = TryCast(methodDecl.PartialImplementationPart.Parameters(0), ParameterSymbol)
Assert.NotNull(parameter)
Assert.Equal("i As Integer", parameter.ToDisplayString())
attributes = parameter.GetAttributes()
Assert.Equal(4, attributes.Length)
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "A1()").WithArguments("A1"))
End Sub
<Fact>
Public Sub MergeMethodParametersAttributesComplexVsSimple()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Reflection
Class A1
Inherits Attribute
End Class
Class A2
Inherits Attribute
End Class
Partial Public Class X
Partial Private Sub SimpleDefSimpleImpl(i As Integer)
End Sub
Private Sub SimpleDefSimpleImpl(i As Integer)
End Sub
Partial Private Sub SimpleDefComplexImpl(i As Integer)
End Sub
Private Sub SimpleDefComplexImpl(<A2> i As Integer)
End Sub
Partial Private Sub ComplexDefSimpleImpl(<A1>i As Integer)
End Sub
Private Sub ComplexDefSimpleImpl(i As Integer)
End Sub
Partial Private Sub ComplexDefComplexImpl(<A1>i As Integer)
End Sub
Private Sub ComplexDefComplexImpl(<A2>i As Integer)
End Sub
End Class
]]>
</file>
</compilation>
' first access def then impl
CompileAndVerify(source, sourceSymbolValidator:=
Sub(m)
Dim x = DirectCast(m.GlobalNamespace.GetMember("X"), TypeSymbol)
Dim SimpleDefSimpleImpl = DirectCast(x.GetMembers("SimpleDefSimpleImpl").Single(), MethodSymbol)
Dim ComplexDefSimpleImpl = DirectCast(x.GetMembers("ComplexDefSimpleImpl").Single(), MethodSymbol)
Dim SimpleDefComplexImpl = DirectCast(x.GetMembers("SimpleDefComplexImpl").Single(), MethodSymbol)
Dim ComplexDefComplexImpl = DirectCast(x.GetMembers("ComplexDefComplexImpl").Single(), MethodSymbol)
Assert.Equal(0, SimpleDefSimpleImpl.Parameters(0).GetAttributes().Length)
Assert.Equal(0, SimpleDefSimpleImpl.PartialImplementationPart.Parameters(0).GetAttributes().Length)
Assert.Equal(1, ComplexDefSimpleImpl.Parameters(0).GetAttributes().Length)
Assert.Equal(1, ComplexDefSimpleImpl.PartialImplementationPart.Parameters(0).GetAttributes().Length)
Assert.Equal(1, SimpleDefComplexImpl.Parameters(0).GetAttributes().Length)
Assert.Equal(1, SimpleDefComplexImpl.PartialImplementationPart.Parameters(0).GetAttributes().Length)
Assert.Equal(2, ComplexDefComplexImpl.Parameters(0).GetAttributes().Length)
Assert.Equal(2, ComplexDefComplexImpl.PartialImplementationPart.Parameters(0).GetAttributes().Length)
End Sub)
' first access impl then def
CompileAndVerify(source, sourceSymbolValidator:=
Sub(m)
Dim x = DirectCast(m.GlobalNamespace.GetMember("X"), TypeSymbol)
Dim SimpleDefSimpleImpl = DirectCast(x.GetMembers("SimpleDefSimpleImpl").Single(), MethodSymbol)
Dim ComplexDefSimpleImpl = DirectCast(x.GetMembers("ComplexDefSimpleImpl").Single(), MethodSymbol)
Dim SimpleDefComplexImpl = DirectCast(x.GetMembers("SimpleDefComplexImpl").Single(), MethodSymbol)
Dim ComplexDefComplexImpl = DirectCast(x.GetMembers("ComplexDefComplexImpl").Single(), MethodSymbol)
Assert.Equal(0, SimpleDefSimpleImpl.PartialImplementationPart.Parameters(0).GetAttributes().Length)
Assert.Equal(0, SimpleDefSimpleImpl.Parameters(0).GetAttributes().Length)
Assert.Equal(1, ComplexDefSimpleImpl.PartialImplementationPart.Parameters(0).GetAttributes().Length)
Assert.Equal(1, ComplexDefSimpleImpl.Parameters(0).GetAttributes().Length)
Assert.Equal(1, SimpleDefComplexImpl.PartialImplementationPart.Parameters(0).GetAttributes().Length)
Assert.Equal(1, SimpleDefComplexImpl.Parameters(0).GetAttributes().Length)
Assert.Equal(2, ComplexDefComplexImpl.PartialImplementationPart.Parameters(0).GetAttributes().Length)
Assert.Equal(2, ComplexDefComplexImpl.Parameters(0).GetAttributes().Length)
End Sub)
End Sub
<WorkItem(544502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544502")>
<Fact()>
Public Sub MergePartialMethodEvents()
CompileAndVerify(
<compilation name="MergePartialMethodEvents">
<file name="a.vb">
Imports System
Partial Class C1
Private Event E1(int As Integer)
Private Event E2(int As Integer)
Partial Private Sub M(i As Integer) Handles Me.E1, Me.E2
End Sub
Sub Raise()
RaiseEvent E1(1)
RaiseEvent E2(2)
RaiseEvent E3(3)
End Sub
Shared Sub Main()
Call New C1().Raise()
End Sub
End Class
</file>
<file name="b.vb">
Imports System
Partial Class C1
Private Event E3(int As Integer)
Private Sub M(i As Integer) Handles Me.E2, Me.E3
Console.Write(i.ToString())
Console.Write(";")
End Sub
End Class
</file>
</compilation>,
expectedOutput:="1;2;2;3;")
End Sub
<WorkItem(544502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544502")>
<Fact()>
Public Sub MergePartialMethodEvents2()
CompileAndVerify(
<compilation name="MergePartialMethodEvents2">
<file name="a.vb">
Imports System
Partial Class C1
Private Sub M(i As Integer) Handles Me.E2, Me.E3
Console.Write(i.ToString())
Console.Write(";")
End Sub
Private Event E1(int As Integer)
Private Event E2(int As Integer)
Sub Raise()
RaiseEvent E1(1)
RaiseEvent E2(2)
RaiseEvent E3(3)
End Sub
Shared Sub Main()
Call New C1().Raise()
End Sub
End Class
</file>
<file name="b.vb">
Imports System
Partial Class C1
Private Event E3(int As Integer)
Partial Private Sub M(i As Integer) Handles Me.E1, Me.E2
End Sub
End Class
</file>
</compilation>,
expectedOutput:="1;2;2;3;")
End Sub
<WorkItem(544502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544502")>
<Fact()>
Public Sub MergePartialMethodEvents3()
CompileAndVerify(
<compilation name="MergePartialMethodEvents3">
<file name="a.vb">
Imports System
Partial Class c1
Private Handler1 As Action(Of Integer)
Private Handler2 As Action(Of Integer)
Private Custom Event E1 As Action(Of Integer)
AddHandler(value As Action(Of Integer))
Handler1 = CType([Delegate].Combine(Handler1, value), Action(Of Integer))
End AddHandler
RemoveHandler(value As Action(Of Integer))
Handler1 = CType([Delegate].Remove(Handler1, value), Action(Of Integer))
End RemoveHandler
RaiseEvent(obj As Integer)
If Handler1 IsNot Nothing Then Handler1(1)
End RaiseEvent
End Event
Private Custom Event E2 As Action(Of Integer)
AddHandler(value As Action(Of Integer))
Handler2 = CType([Delegate].Combine(Handler2, value), Action(Of Integer))
End AddHandler
RemoveHandler(value As Action(Of Integer))
Handler2 = CType([Delegate].Remove(Handler2, value), Action(Of Integer))
End RemoveHandler
RaiseEvent(obj As Integer)
If Handler2 IsNot Nothing Then Handler2(2)
End RaiseEvent
End Event
Partial Private Sub M(i As Integer) Handles Me.E1, Me.E2
End Sub
Sub Raise()
RaiseEvent E1(1)
RaiseEvent E2(2)
RaiseEvent E3(3)
End Sub
Shared Sub Main()
Call New c1().Raise()
End Sub
End Class
Partial Class C1
Private Event E3(int As Integer)
Private Sub M(i As Integer) Handles Me.E2, Me.E3
Console.Write(i.ToString())
Console.Write(";")
End Sub
End Class
</file>
</compilation>,
expectedOutput:="1;2;2;3;")
End Sub
<Fact()>
Public Sub MergePartialMethodWithEvents()
CompileAndVerify(
<compilation name="MergePartialMethodWithEvents">
<file name="a.vb">
Imports System
Class C
Public Event E1(int As Integer)
Public Event E2(int As Integer)
Public Event E3(int As Integer)
Sub Raise()
RaiseEvent E1(1)
RaiseEvent E2(2)
RaiseEvent E3(3)
End Sub
End Class
Partial Class C1
WithEvents e As New C
Private Sub M(i As Integer) Handles e.E2, e.E3
Console.Write(i.ToString())
Console.Write(";")
End Sub
Sub Test()
Call e.Raise()
End Sub
Shared Sub Main()
Dim x = New C1
x.Test()
End Sub
End Class
</file>
<file name="b.vb">
Imports System
Partial Class C1
Partial Private Sub M(i As Integer) Handles e.E1, e.E2
End Sub
End Class
</file>
</compilation>,
expectedOutput:="1;2;2;3;")
End Sub
<Fact()>
Public Sub ExplicitInterfaceDiagnosticsNotDuplicated()
Dim text1 = <text>
Public Interface A
Sub B()
End Interface
Partial Public Class C1
Partial Private Sub M(i As Integer)
End Sub
End Class
</text>.Value.Trim()
Dim text2 = <text>
Partial Public Class C1
Private Sub M(i As Integer) Implements A.B
End Sub
End Class
</text>.Value.Trim()
Dim tree1 = ParseAndVerify(text1)
Dim tree2 = ParseAndVerify(text2)
Dim comp = CreateCompilationWithMscorlib40({tree1, tree2}, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim pTypeSym = comp.SourceModule.GlobalNamespace.GetTypeMembers("C1").Single()
Assert.Equal("C1", pTypeSym.ToDisplayString())
Dim methods = pTypeSym.GetMembers("M")
Assert.Equal(1, methods.Length)
Dim methodDecl = TryCast(methods(0), MethodSymbol)
Assert.NotNull(methodDecl)
Assert.Equal(0, methodDecl.ExplicitInterfaceImplementations.Length)
Dim methodImpl = methodDecl.PartialImplementationPart
Assert.NotNull(methodImpl)
Assert.Equal(0, methodImpl.ExplicitInterfaceImplementations.Length)
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_InterfaceNotImplemented1, "A").WithArguments("A"))
End Sub
<WorkItem(544432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544432")>
<Fact()>
Public Sub TestCaseWithTypeArgumentsAndConstraints()
Dim text1 = <text>
Imports System
Module Module1
Partial Private Sub M(Of A As Class, U As A, V As {U, Exception}, W As Structure)(aa As A, uu As U, vv As V(), ww As W?)
End Sub
Private Sub M(Of A As Class, U As A, V As {U, Exception}, W As Structure)(aa As A, uu As U, vv As V(), ww As W?)
End Sub
Sub Main()
End Sub
End Module
</text>.Value.Trim()
Dim tree1 = ParseAndVerify(text1)
Dim comp = CreateCompilationWithMscorlib40({tree1}, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim pTypeSym = comp.SourceModule.GlobalNamespace.GetTypeMembers("Module1").Single()
Assert.Equal("Module1", pTypeSym.ToDisplayString())
Dim methods = pTypeSym.GetMembers("M")
Assert.Equal(1, methods.Length)
Dim methodDecl = TryCast(methods(0), MethodSymbol)
Assert.NotNull(methodDecl)
Dim methodImpl = methodDecl.PartialImplementationPart
Assert.NotNull(methodImpl)
Assert.NotSame(methodDecl, methodImpl)
Assert.Same(methodDecl.PartialImplementationPart, methodImpl)
Assert.Same(methodImpl.PartialDefinitionPart, methodDecl)
End Sub
<WorkItem(544445, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544445")>
<Fact()>
Public Sub TestCaseWithTypeArgumentsAndConstraints2()
Dim text1 = <text>
Imports System
Module Module1
Sub Main()
End Sub
Partial Private Sub M(Of T As {Exception,}, U As T, V)()
End Sub
Private Sub M(Of T As {Exception}, U As T, V)()
End Sub
End Module
</text>.Value.Trim()
Dim tree1 = VisualBasicSyntaxTree.ParseText(text1)
Dim comp = CreateCompilationWithMscorlib40({tree1}, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim pTypeSym = comp.SourceModule.GlobalNamespace.GetTypeMembers("Module1").Single()
Assert.Equal("Module1", pTypeSym.ToDisplayString())
Dim methods = pTypeSym.GetMembers("M")
Assert.Equal(1, methods.Length)
Dim methodDecl = TryCast(methods(0), MethodSymbol)
Assert.NotNull(methodDecl)
Dim methodImpl = methodDecl.PartialImplementationPart
Assert.NotNull(methodImpl)
Assert.NotSame(methodDecl, methodImpl)
Assert.Same(methodDecl.PartialImplementationPart, methodImpl)
Assert.Same(methodImpl.PartialDefinitionPart, methodDecl)
End Sub
<Fact()>
Public Sub GetDeclaredSymbolsForParamsAndTypeParams()
'This is to make sure that the issues from C# bugs 12468 and 12819 don't repro in VB.
Dim text1 = <text>
Imports System
Partial Class C1
Partial Private Shared Sub M(Of U As {T, Exception}, T)(x As T)
End Sub
End Class
</text>.Value.Trim()
Dim text2 = <text>
Imports System
Partial Class C1
Private Shared Sub M(Of U As {Exception, T}, T)(x As T)
End Sub
Shared Function Bar() As Integer
Return 1
End Function
End Class
</text>.Value.Trim()
Dim tree1 = ParseAndVerify(text1)
Dim tree2 = ParseAndVerify(text2)
Dim comp = CreateCompilationWithMscorlib40({tree1, tree2}, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim model1 = comp.GetSemanticModel(tree1)
Dim model2 = comp.GetSemanticModel(tree2)
Dim root1 = tree1.GetCompilationUnitRoot()
Dim root2 = tree1.GetCompilationUnitRoot()
Dim para1 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of ParameterSyntax)().First()
Dim para2 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of ParameterSyntax)().First()
Dim typePara1 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of TypeParameterSyntax)().First()
Dim typePara2 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of TypeParameterSyntax)().First()
Dim paraSym1 = model1.GetDeclaredSymbol(para1)
Dim paraSym2 = model2.GetDeclaredSymbol(para2)
Assert.NotNull(paraSym1)
Assert.NotNull(paraSym2)
Assert.Equal("x As T", paraSym1.ToTestDisplayString())
Assert.Equal("x As T", paraSym2.ToTestDisplayString())
Assert.NotEqual(paraSym1.Locations(0), paraSym2.Locations(0))
Dim typeParaSym1 = model1.GetDeclaredSymbol(typePara1)
Dim typeParaSym2 = model2.GetDeclaredSymbol(typePara2)
Assert.NotNull(typeParaSym1)
Assert.NotNull(typeParaSym2)
Assert.Equal("U", typeParaSym1.ToTestDisplayString)
Assert.Equal(2, typeParaSym1.ConstraintTypes.Length)
Assert.Equal("U", typeParaSym2.ToTestDisplayString)
Assert.Equal(2, typeParaSym2.ConstraintTypes.Length)
Assert.NotEqual(typeParaSym1.Locations(0), typeParaSym2.Locations(0))
End Sub
<Fact()>
Public Sub GetDeclaredSymbolsForParamsAndTypeParams2()
'This is to make sure that the issues from C# bugs 12468 and 12819 don't repro in VB.
Dim text1 = <text>
Imports System
Partial Class C1
Partial Private Shared Sub M(Of U As {T, Exception}, T)(x As T)
End Sub
End Class
</text>.Value.Trim()
Dim text2 = <text>
Imports System
Partial Class C1
Shared Function Bar() As Integer
Return 1
End Function
Private Shared Sub M(Of U As {Exception, T}, T)(x As T)
End Sub
End Class
</text>.Value.Trim()
Dim tree1 = ParseAndVerify(text1)
Dim tree2 = ParseAndVerify(text2)
Dim comp = CreateCompilationWithMscorlib40({tree1, tree2}, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim model1 = comp.GetSemanticModel(tree1)
Dim model2 = comp.GetSemanticModel(tree2)
Dim root1 = tree1.GetCompilationUnitRoot()
Dim root2 = tree1.GetCompilationUnitRoot()
Dim para1 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of ParameterSyntax)().First()
Dim para2 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of ParameterSyntax)().First()
Dim typePara1 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType(Of TypeParameterSyntax)().First()
Dim typePara2 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType(Of TypeParameterSyntax)().First()
Dim paraSym1 = model1.GetDeclaredSymbol(para1)
Dim paraSym2 = model2.GetDeclaredSymbol(para2)
Assert.NotNull(paraSym1)
Assert.NotNull(paraSym2)
Assert.Equal("x As T", paraSym1.ToTestDisplayString())
Assert.Equal("x As T", paraSym2.ToTestDisplayString())
Assert.NotEqual(paraSym1.Locations(0), paraSym2.Locations(0))
Dim typeParaSym1 = model1.GetDeclaredSymbol(typePara1)
Dim typeParaSym2 = model2.GetDeclaredSymbol(typePara2)
Assert.NotNull(typeParaSym1)
Assert.NotNull(typeParaSym2)
Assert.Equal("U", typeParaSym1.ToTestDisplayString)
Assert.Equal(2, typeParaSym1.ConstraintTypes.Length)
Assert.Equal("U", typeParaSym2.ToTestDisplayString)
Assert.Equal(2, typeParaSym2.ConstraintTypes.Length)
Assert.NotEqual(typeParaSym1.Locations(0), typeParaSym2.Locations(0))
End Sub
<WorkItem(544499, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544499")>
<Fact()>
Public Sub GetMembersForMustoverridePartialMethod()
'TODO: Please add any additional verification below if necessary.
Dim text = <text>
Partial Class C1
Partial Mustoverride Private Sub M()
End Sub
End Class
</text>.Value.Trim()
Dim tree = VisualBasicSyntaxTree.ParseText(text)
Dim comp = CreateCompilationWithMscorlib40({tree}, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim typeSym = comp.GetTypeByMetadataName("C1")
Assert.NotNull(typeSym)
Dim methodSym = typeSym.GetMembers("M").Single()
Assert.NotNull(methodSym)
End Sub
<WorkItem(921704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/921704")>
<Fact()>
Public Sub Bug921704()
CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Partial Private Sub BeforeInitializeComponent(ByRef isInitialized as Boolean)
End Sub
Private Sub BeforeInitializeComponent(ByRef isInitialized as Boolean)
isInitialized = true
End Sub
End Module
</file>
</compilation>)
End Sub
End Class
End Namespace
|
jmarolf/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/Semantics/PartialMethodsTest.vb
|
Visual Basic
|
mit
| 41,568
|
' 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.Editor.Commands
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.LineCommit
Public Class CommitOnEnterTests
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Async Function TestCommitAfterEnterOnSimpleStatement() As Task
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>[|
imports System$$|]
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=True)
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Async Function TestNoCommitAfterEnterAfterQuery() As Task
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()
Dim x = From x In { 1, 2, 3 }$$
End Sub
End Class
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=False)
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
<WorkItem(531421, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531421")>
Public Async Function TestNoCommitAfterExplicitLineContinuation() As Task
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()
M() _$$
End Sub
End Class
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=False)
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
<WorkItem(531421, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531421")>
Public Async Function TestCommitAfterBlankLineFollowingExplicitLineContinuation() As Task
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()[|
M() _
|]$$
End Sub
End Class
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=True)
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Async Function TestCommitAfterDeclaration() As Task
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>[|
Class C$$
Sub M()
m() _
End Sub
End Class|]
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=True)
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Async Function TestCommitAfterEndConstruct() As Task
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>[|
Class C
Sub M()
m() _
End Sub
End Class$$|]
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=True, usedSemantics:=False)
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Async Function TestCommitAfterBlankLineAfterQuery() As Task
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()[|
Dim x = From x In { 1, 2, 3 }
$$|]
End Sub
End Class
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=True)
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Async Function TestNoCommitAfterEnterAfterPartialExpression() As Task
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()
Dim x = 1 + $$
End Sub
End Class
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=False)
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Async Function TestCommitAfterEnterAfterPartialExpression() As Task
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()
Dim x = 1 + [|
$$|]
End Sub
End Class
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=True)
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Async Function TestCommitAfterEnterOnBlankLine() As Task
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()[|
$$|]
End Sub
End Class
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=True)
End Function
<WpfFact>
<WorkItem(539451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539451")>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Async Function TestCommitAfterColon() As Task
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()[|
Call M() : $$|]
End Sub
End Class
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=True)
End Function
<WpfFact>
<WorkItem(539408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539408")>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Async Function TestCommitAfterConstDirective() As Task
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>[|
#const foo = 42$$|]
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=True)
End Function
<WpfFact>
<WorkItem(539408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539408")>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Async Function TestCommitAfterComment() As Task
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>[|
rem Hello World$$|]
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=True)
End Function
<WpfFact>
<WorkItem(544372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544372")>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Async Function UndoAfterCommitOnBlankLine() As Threading.Tasks.Task
Using testData = Await CommitTestData.CreateAsync(<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>$$
</Document>
</Project>
</Workspace>)
testData.CommandHandler.ExecuteCommand(New ReturnKeyCommandArgs(testData.View, testData.Buffer), Sub() testData.EditorOperations.InsertNewLine())
testData.UndoHistory.Undo(count:=1)
Assert.Equal(0, testData.View.Caret.Position.BufferPosition.GetContainingLine().LineNumber)
End Using
End Function
<WpfFact>
<WorkItem(540210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540210")>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Async Function TestCommitAfterThenTouchingThen() As Task
' Note that the source we are starting this test with is *not* syntactically correct,
' but by having the extra "End If" we guarantee the ending code will be as if End
' Construct generation happened.
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()[|
If True Then$$ q = Sub()
End Sub|]
End If
End Sub
End Class
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=True)
End Function
<WpfFact>
<WorkItem(540210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540210")>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Async Function TestCommitAfterThenTouchingStatement() As Task
' Note that the source we are starting this test with is *not* syntactically correct,
' but by having the extra "End If" we guarantee the ending code will be as if End
' Construct generation happened.
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()[|
If True Then $$q = Sub()
End Sub|]
End If
End Sub
End Class
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=True)
End Function
<WpfFact>
<WorkItem(530463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530463")>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Async Function TestCommitAfterPropertyStatement() As Task
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Property P1[|
Property P2$$|]
Property P3
End Class
Class E
Property P1
End Class
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=True)
End Function
<WpfFact>
<WorkItem(986168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/986168")>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Async Function TestDontCommitInsideStringLiteral() As Task
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module M
Sub M()
Dim s = "$$
Console.WriteLine("The method or operation is not implemented.")
End Sub
End Module
</Document>
</Project>
</Workspace>
Await AssertCommitsStatementAsync(test, expectCommit:=False)
End Function
Private Async Function AssertCommitsStatementAsync(test As XElement, expectCommit As Boolean, Optional usedSemantics As Boolean = True) As Threading.Tasks.Task
Using testData = Await CommitTestData.CreateAsync(test)
Dim lineNumber = testData.View.Caret.Position.BufferPosition.GetContainingLine().LineNumber
testData.CommandHandler.ExecuteCommand(New ReturnKeyCommandArgs(testData.View, testData.Buffer), Sub() testData.EditorOperations.InsertNewLine())
testData.AssertHadCommit(expectCommit)
If expectCommit Then
testData.AssertUsedSemantics(usedSemantics)
End If
Assert.Equal(lineNumber + 1, testData.View.Caret.Position.BufferPosition.GetContainingLine().LineNumber)
End Using
End Function
End Class
End Namespace
|
vslsnap/roslyn
|
src/EditorFeatures/VisualBasicTest/LineCommit/CommitOnEnterTests.vb
|
Visual Basic
|
apache-2.0
| 13,932
|
' 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 Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Module ErrorMessageHelpers
<Extension()>
Public Function ToDisplay(access As Accessibility) As String
Select Case access
Case Accessibility.NotApplicable
Return ""
Case Accessibility.Private
Return "Private"
Case Accessibility.Protected
Return "Protected"
Case Accessibility.ProtectedOrFriend
Return "Protected Friend"
Case Accessibility.ProtectedAndFriend
Return "Private Protected"
Case Accessibility.Friend
Return "Friend"
Case Accessibility.Public
Return "Public"
Case Else
Throw ExceptionUtilities.UnexpectedValue(access)
End Select
End Function
End Module
End Namespace
|
physhi/roslyn
|
src/Compilers/VisualBasic/Portable/Errors/ErrorMessageHelpers.vb
|
Visual Basic
|
apache-2.0
| 1,355
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Runtime.CompilerServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module SemanticModelExtensions
Private Const s_defaultParameterName = "p"
Private Const s_defaultBuiltInParameterName = "v"
<Extension()>
Public Function LookupTypeRegardlessOfArity(semanticModel As SemanticModel,
name As SyntaxToken,
cancellationToken As CancellationToken) As IList(Of ITypeSymbol)
Dim expression = TryCast(name.Parent, ExpressionSyntax)
If expression IsNot Nothing Then
Dim results = semanticModel.LookupName(expression, namespacesAndTypesOnly:=True, cancellationToken:=cancellationToken)
If results.Count > 0 Then
Return results.OfType(Of ITypeSymbol)().ToList()
End If
End If
Return SpecializedCollections.EmptyList(Of ITypeSymbol)()
End Function
<Extension()>
Public Function LookupName(semanticModel As SemanticModel, name As SyntaxToken,
namespacesAndTypesOnly As Boolean,
cancellationToken As CancellationToken) As IList(Of ISymbol)
Dim expression = TryCast(name.Parent, ExpressionSyntax)
If expression IsNot Nothing Then
Return semanticModel.LookupName(expression, namespacesAndTypesOnly, cancellationToken)
End If
Return SpecializedCollections.EmptyList(Of ISymbol)()
End Function
<Extension()>
Public Function LookupName(semanticModel As SemanticModel,
expression As ExpressionSyntax,
namespacesAndTypesOnly As Boolean,
cancellationToken As CancellationToken) As IList(Of ISymbol)
Dim expr = SyntaxFactory.GetStandaloneExpression(expression)
Dim qualifier As ExpressionSyntax = Nothing
Dim name As String = Nothing
Dim arity As Integer = Nothing
expr.DecomposeName(qualifier, name, arity)
Dim symbol As INamespaceOrTypeSymbol = Nothing
If qualifier IsNot Nothing AndAlso TypeOf qualifier Is TypeSyntax Then
Dim typeInfo = semanticModel.GetTypeInfo(qualifier, cancellationToken)
Dim symbolInfo = semanticModel.GetSymbolInfo(qualifier, cancellationToken)
If typeInfo.Type IsNot Nothing Then
symbol = typeInfo.Type
ElseIf symbolInfo.Symbol IsNot Nothing Then
symbol = TryCast(symbolInfo.Symbol, INamespaceOrTypeSymbol)
End If
End If
Return If(
namespacesAndTypesOnly,
semanticModel.LookupNamespacesAndTypes(expr.SpanStart, container:=symbol, name:=name),
semanticModel.LookupSymbols(expr.SpanStart, container:=symbol, name:=name))
End Function
<Extension()>
Public Function GetSymbolInfo(semanticModel As SemanticModel, token As SyntaxToken) As SymbolInfo
Dim expression = TryCast(token.Parent, ExpressionSyntax)
If expression Is Nothing Then
Return Nothing
End If
Return semanticModel.GetSymbolInfo(expression)
End Function
<Extension()>
Public Function GenerateNameForArgument(semanticModel As SemanticModel,
argument As ArgumentSyntax,
cancellationToken As CancellationToken) As String
Dim result = GenerateNameForArgumentWorker(semanticModel, argument, cancellationToken)
Return If(String.IsNullOrWhiteSpace(result), s_defaultParameterName, result)
End Function
Private Function GenerateNameForArgumentWorker(semanticModel As SemanticModel,
argument As ArgumentSyntax,
cancellationToken As CancellationToken) As String
If argument.IsNamed Then
Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText
ElseIf Not argument.IsOmitted Then
Return semanticModel.GenerateNameForExpression(
argument.GetExpression(), capitalize:=False, cancellationToken:=cancellationToken)
Else
Return s_defaultParameterName
End If
End Function
''' <summary>
''' Given an expression node, tries to generate an appropriate name that can be used for
''' that expression.
''' </summary>
<Extension()>
Public Function GenerateNameForExpression(semanticModel As SemanticModel,
expression As ExpressionSyntax,
capitalize As Boolean,
cancellationToken As CancellationToken) As String
' Try to find a usable name node that we can use to name the
' parameter. If we have an expression that has a name as part of it
' then we try to use that part.
Dim current = expression
While True
current = current.WalkDownParentheses()
If current.Kind = SyntaxKind.IdentifierName Then
Return (DirectCast(current, IdentifierNameSyntax)).Identifier.ValueText.ToCamelCase()
ElseIf TypeOf current Is MemberAccessExpressionSyntax Then
Return (DirectCast(current, MemberAccessExpressionSyntax)).Name.Identifier.ValueText.ToCamelCase()
ElseIf TypeOf current Is CastExpressionSyntax Then
current = (DirectCast(current, CastExpressionSyntax)).Expression
Else
Exit While
End If
End While
' there was nothing in the expression to signify a name. If we're in an argument
' location, then try to choose a name based on the argument name.
Dim argumentName = TryGenerateNameForArgumentExpression(
semanticModel, expression, cancellationToken)
If argumentName IsNot Nothing Then
Return If(capitalize, argumentName.ToPascalCase(), argumentName.ToCamelCase())
End If
' Otherwise, figure out the type of the expression and generate a name from that
' instead.
Dim info = semanticModel.GetTypeInfo(expression, cancellationToken)
' If we can't determine the type, then fallback to some placeholders.
Dim [type] = info.Type
Return [type].CreateParameterName(capitalize)
End Function
Private Function TryGenerateNameForArgumentExpression(semanticModel As SemanticModel, expression As ExpressionSyntax, cancellationToken As CancellationToken) As String
Dim topExpression = expression.WalkUpParentheses()
If TypeOf topExpression.Parent Is ArgumentSyntax Then
Dim argument = DirectCast(topExpression.Parent, ArgumentSyntax)
Dim simpleArgument = TryCast(argument, SimpleArgumentSyntax)
If simpleArgument?.NameColonEquals IsNot Nothing Then
Return simpleArgument.NameColonEquals.Name.Identifier.ValueText
End If
Dim argumentList = TryCast(argument.Parent, ArgumentListSyntax)
If argumentList IsNot Nothing Then
Dim index = argumentList.Arguments.IndexOf(argument)
Dim member = TryCast(semanticModel.GetSymbolInfo(argumentList.Parent, cancellationToken).Symbol, IMethodSymbol)
If member IsNot Nothing AndAlso index < member.Parameters.Length Then
Dim parameter = member.Parameters(index)
If parameter.Type.TypeKind <> TypeKind.TypeParameter Then
Return parameter.Name
End If
End If
End If
End If
Return Nothing
End Function
<Extension()>
Public Function GenerateParameterNames(semanticModel As SemanticModel,
arguments As ArgumentListSyntax,
reservedNames As IEnumerable(Of String),
cancellationToken As CancellationToken) As ImmutableArray(Of ParameterName)
If arguments Is Nothing Then
Return ImmutableArray(Of ParameterName).Empty
End If
Return GenerateParameterNames(
semanticModel, arguments.Arguments.ToList(),
reservedNames, cancellationToken)
End Function
<Extension()>
Public Function GenerateParameterNames(semanticModel As SemanticModel,
arguments As IList(Of ArgumentSyntax),
reservedNames As IEnumerable(Of String),
cancellationToken As CancellationToken) As ImmutableArray(Of ParameterName)
reservedNames = If(reservedNames, SpecializedCollections.EmptyEnumerable(Of String))
Return semanticModel.GenerateParameterNames(
arguments,
Function(s) Not reservedNames.Any(Function(n) CaseInsensitiveComparison.Equals(s, n)),
cancellationToken)
End Function
<Extension()>
Public Function GenerateParameterNames(semanticModel As SemanticModel,
arguments As IList(Of ArgumentSyntax),
canUse As Func(Of String, Boolean),
cancellationToken As CancellationToken) As ImmutableArray(Of ParameterName)
If arguments.Count = 0 Then
Return ImmutableArray(Of ParameterName).Empty
End If
' We can't change the names of named parameters. Any other names we're flexible on.
Dim isFixed = Aggregate arg In arguments
Select arg = TryCast(arg, SimpleArgumentSyntax)
Select arg IsNot Nothing AndAlso arg.NameColonEquals IsNot Nothing
Into ToList()
Dim parameterNames = arguments.Select(Function(a) semanticModel.GenerateNameForArgument(a, cancellationToken)).ToList()
Return NameGenerator.EnsureUniqueness(parameterNames, isFixed, canUse).
Select(Function(name, index) New ParameterName(name, isFixed(index))).
ToImmutableArray()
End Function
Private Function SetEquals(array1 As ImmutableArray(Of ISymbol), array2 As ImmutableArray(Of ISymbol)) As Boolean
' Do some quick up front checks so we won't have to allocate memory below.
If array1.Length = 0 AndAlso array2.Length = 0 Then
Return True
End If
If array1.Length = 0 OrElse array2.Length = 0 Then
Return False
End If
If array1.Length = 1 AndAlso array2.Length = 1 Then
Return array1(0).Equals(array2(0))
End If
Dim [set] = New HashSet(Of ISymbol)(array1)
Return [set].SetEquals(array2)
End Function
<Extension()>
Public Function GetImportNamespacesInScope(semanticModel As SemanticModel, location As SyntaxNode) As ISet(Of INamespaceSymbol)
Dim q =
From u In location.GetAncestorOrThis(Of CompilationUnitSyntax).Imports
From importClause In u.ImportsClauses.OfType(Of SimpleImportsClauseSyntax)()
Where importClause.Alias Is Nothing
Let info = semanticModel.GetSymbolInfo(importClause.Name)
Let ns = TryCast(info.Symbol, INamespaceSymbol)
Where ns IsNot Nothing
Select ns
Return q.ToSet()
End Function
<Extension()>
Public Function GetAliasInfo(semanticModel As SemanticModel, expression As ExpressionSyntax, cancellationToken As CancellationToken) As IAliasSymbol
Dim nameSyntax = TryCast(expression, IdentifierNameSyntax)
If nameSyntax Is Nothing Then
Return Nothing
Else
Return semanticModel.GetAliasInfo(nameSyntax, cancellationToken)
End If
End Function
<Extension()>
Public Function DetermineAccessibilityConstraint(semanticModel As SemanticModel,
type As TypeSyntax,
cancellationToken As CancellationToken) As Accessibility
If type Is Nothing Then
Return Accessibility.Private
End If
type = type.GetAncestorsOrThis(Of TypeSyntax)().Last()
If type.IsParentKind(SyntaxKind.InheritsStatement) Then
Dim containingType = semanticModel.GetEnclosingNamedType(type.SpanStart, cancellationToken)
Return containingType.DeclaredAccessibility
End If
' Determine accessibility of field or event
' Public B as B
If type.IsParentKind(SyntaxKind.SimpleAsClause) AndAlso
type.Parent.IsParentKind(SyntaxKind.VariableDeclarator) Then
If type.Parent.Parent.IsParentKind(SyntaxKind.FieldDeclaration) OrElse
type.Parent.Parent.IsParentKind(SyntaxKind.EventStatement) Then
Dim variableDeclarator = DirectCast(type.Parent.Parent, VariableDeclaratorSyntax)
If variableDeclarator.Names.Count > 0 Then
Dim variableDeclaration = semanticModel.GetDeclaredSymbol(variableDeclarator.Names(0), cancellationToken)
Return variableDeclaration.DeclaredAccessibility
End If
End If
End If
' Determine accessibility of field or event
' Public B as New B()
If type.IsParentKind(SyntaxKind.ObjectCreationExpression) AndAlso
type.Parent.IsParentKind(SyntaxKind.AsNewClause) AndAlso
type.Parent.Parent.IsParentKind(SyntaxKind.VariableDeclarator) Then
If type.Parent.Parent.Parent.IsParentKind(SyntaxKind.FieldDeclaration) OrElse
type.Parent.Parent.Parent.IsParentKind(SyntaxKind.EventStatement) Then
Dim variableDeclarator = DirectCast(type.Parent.Parent.Parent, VariableDeclaratorSyntax)
If variableDeclarator.Names.Count > 0 Then
Dim variableDeclaration = semanticModel.GetDeclaredSymbol(variableDeclarator.Names(0), cancellationToken)
Return variableDeclaration.DeclaredAccessibility
End If
End If
End If
If type.IsParentKind(SyntaxKind.SimpleAsClause) Then
If type.Parent.IsParentKind(SyntaxKind.DelegateFunctionStatement) OrElse
type.Parent.IsParentKind(SyntaxKind.FunctionStatement) OrElse
type.Parent.IsParentKind(SyntaxKind.PropertyStatement) OrElse
type.Parent.IsParentKind(SyntaxKind.EventStatement) OrElse
type.Parent.IsParentKind(SyntaxKind.OperatorStatement) Then
Return semanticModel.GetDeclaredSymbol(
type.Parent.Parent, cancellationToken).DeclaredAccessibility
End If
End If
If type.IsParentKind(SyntaxKind.SimpleAsClause) AndAlso
type.Parent.IsParentKind(SyntaxKind.Parameter) AndAlso
type.Parent.Parent.IsParentKind(SyntaxKind.ParameterList) Then
If type.Parent.Parent.Parent.IsParentKind(SyntaxKind.DelegateFunctionStatement) OrElse
type.Parent.Parent.Parent.IsParentKind(SyntaxKind.FunctionStatement) OrElse
type.Parent.Parent.Parent.IsParentKind(SyntaxKind.PropertyStatement) OrElse
type.Parent.Parent.Parent.IsParentKind(SyntaxKind.OperatorStatement) OrElse
type.Parent.Parent.Parent.IsParentKind(SyntaxKind.SubNewStatement) OrElse
type.Parent.Parent.Parent.IsParentKind(SyntaxKind.SubStatement) Then
Return semanticModel.GetDeclaredSymbol(
type.Parent.Parent.Parent.Parent, cancellationToken).DeclaredAccessibility
End If
End If
Return Accessibility.Private
End Function
<Extension()>
Public Iterator Function GetAliasSymbols(semanticModel As SemanticModel) As IEnumerable(Of IAliasSymbol)
semanticModel = DirectCast(semanticModel.GetOriginalSemanticModel(), SemanticModel)
Dim root = semanticModel.SyntaxTree.GetCompilationUnitRoot()
For Each importsClause In root.GetAliasImportsClauses()
Dim [alias] = DirectCast(semanticModel.GetDeclaredSymbol(importsClause), IAliasSymbol)
If [alias] IsNot Nothing Then
Yield [alias]
End If
Next
End Function
End Module
End Namespace
|
MattWindsor91/roslyn
|
src/Workspaces/VisualBasic/Portable/Extensions/SemanticModelExtensions.vb
|
Visual Basic
|
apache-2.0
| 18,176
|
Imports System.Globalization
Imports GemBox.Document
Module Program
Sub Main()
' If using Professional version, put your serial key below.
ComponentInfo.SetLicense("FREE-LIMITED-KEY")
Dim document As New DocumentModel()
document.DefaultCharacterFormat.FontName = "Arial"
document.DefaultCharacterFormat.Size = 16
Dim lineBreakElement As New SpecialCharacter(document, SpecialCharacterType.LineBreak)
document.Sections.Add(
New Section(document,
New Paragraph(document,
New Run(document, "All caps") With {.CharacterFormat = New CharacterFormat With {.AllCaps = True}},
lineBreakElement,
New Run(document, "Text with background color") With {.CharacterFormat = New CharacterFormat With {.BackgroundColor = Color.Cyan}},
lineBreakElement.Clone(),
New Run(document, "Bold text") With {.CharacterFormat = New CharacterFormat With {.Bold = True}},
lineBreakElement.Clone(),
New Run(document, "Text with borders") With {.CharacterFormat = New CharacterFormat With {.Border = New SingleBorder(BorderStyle.Single, Color.Red, 1)}},
lineBreakElement.Clone(),
New Run(document, "Double strikethrough text") With {.CharacterFormat = New CharacterFormat With {.DoubleStrikethrough = True}},
lineBreakElement.Clone(),
New Run(document, "Blue text") With {.CharacterFormat = New CharacterFormat With {.FontColor = Color.Blue}},
lineBreakElement.Clone(),
New Run(document, "Text with 'Consolas' font") With {.CharacterFormat = New CharacterFormat With {.FontName = "Consolas"}},
lineBreakElement.Clone(),
New Run(document, "Hidden text") With {.CharacterFormat = New CharacterFormat With {.Hidden = True}},
lineBreakElement.Clone(),
New Run(document, "Text with highlight color") With {.CharacterFormat = New CharacterFormat With {.HighlightColor = Color.Yellow}},
lineBreakElement.Clone(),
New Run(document, "Italic text") With {.CharacterFormat = New CharacterFormat With {.Italic = True}},
lineBreakElement.Clone(),
New Run(document, "Kerning is 15 points") With {.CharacterFormat = New CharacterFormat With {.Kerning = 15}},
lineBreakElement.Clone(),
New Run(document, "Position is 3 points") With {.CharacterFormat = New CharacterFormat With {.Position = 3}},
lineBreakElement.Clone(),
New Run(document, "Scale is 125%") With {.CharacterFormat = New CharacterFormat With {.Scaling = 125}},
lineBreakElement.Clone(),
New Run(document, "Font size is 24 points") With {.CharacterFormat = New CharacterFormat With {.Size = 24}},
lineBreakElement.Clone(),
New Run(document, "Small caps") With {.CharacterFormat = New CharacterFormat With {.SmallCaps = True}},
lineBreakElement.Clone(),
New Run(document, "Spacing is 3 point") With {.CharacterFormat = New CharacterFormat With {.Spacing = 3}},
lineBreakElement.Clone(),
New Run(document, "Strikethrough text") With {.CharacterFormat = New CharacterFormat With {.Strikethrough = True}},
lineBreakElement.Clone(),
New Run(document, "Subscript text") With {.CharacterFormat = New CharacterFormat With {.Subscript = True}},
lineBreakElement.Clone(),
New Run(document, "Superscript text") With {.CharacterFormat = New CharacterFormat With {.Superscript = True}},
lineBreakElement.Clone(),
New Run(document, "Underline color is orange") With {.CharacterFormat = New CharacterFormat With {.UnderlineColor = Color.Orange, .UnderlineStyle = UnderlineType.Single}},
lineBreakElement.Clone(),
New Run(document, "Underline style is double") With {.CharacterFormat = New CharacterFormat With {.UnderlineStyle = UnderlineType.Double}},
lineBreakElement.Clone(),
New Field(document, FieldType.Date, "\@ ""dddd, d. MMMM yyyy""") With {.CharacterFormat = New CharacterFormat With {.Language = CultureInfo.GetCultureInfo("de-DE")}})))
document.Save("Character Formatting.docx")
End Sub
End Module
|
gemboxsoftware-dev-team/GemBox.Document.Examples
|
VB.NET/Formatting/Character Formatting/Program.vb
|
Visual Basic
|
mit
| 4,680
|
Public Class DynamicTextCreator
End Class
|
KameQuazi/Software-Major-Assignment-2k18
|
LampClient/DialogBoxes/DynamicTextCreator.vb
|
Visual Basic
|
mit
| 45
|
Public Class RenameForm
Public Filename As String
Private Sub DoneButton_Click(sender As Object, e As EventArgs) Handles DoneButton.Click
If String.IsNullOrWhiteSpace(NameBox.Text) Then
MessageBox.Show("The name can not be empty.", "Naming Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
filename = NameBox.Text
DialogResult = Windows.Forms.DialogResult.OK
End If
End Sub
Private Sub RenameForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
NameBox.Text = filename
End Sub
End Class
|
NoSpread/SLAM-EXTRA
|
SLAM/RenameForm.vb
|
Visual Basic
|
mit
| 598
|
NameSpace Models.DMSCON
Partial Public Class SecurityMaskRevisionScheme
Inherits DMS.Base.Models.GenericEntity
#Region " Properties "
Public Overrides Property ID As String
Get
Return "{0}_{1}".FormatWith(SecurityMaskID,RevisionSchemeID)
End Get
Set(value as String)
End Set
End Property
Private _RevisionSchemeID As Integer = -1 ' Column 1
Public Property RevisionSchemeID As Integer
Get
Return _RevisionSchemeID
End Get
Set(value as Integer)
SetProperty(_RevisionSchemeID,value,"RevisionSchemeID",{"ID"})
End Set
End Property
Private _SecurityMaskID As Integer = -1 ' Column 0
Public Property SecurityMaskID As Integer
Get
Return _SecurityMaskID
End Get
Set(value as Integer)
SetProperty(_SecurityMaskID,value,"SecurityMaskID",{"ID"})
End Set
End Property
#End Region
Public Async Function Delete(dbAccess as DMS.Base.Data.IDBAccess) As Task
Await Delete(dbAccess,Me)
End Function
Public Overrides Sub LoadFromEntity(genericEntity As DMS.Base.Models.GenericEntity)
If Me Is genericEntity Then
Return
End If
If Not (TypeOf (genericEntity) Is SecurityMaskRevisionScheme) Then
Return
End If
Dim Entity As SecurityMaskRevisionScheme = DirectCast(genericEntity, SecurityMaskRevisionScheme)
Me.SecurityMaskID = Entity.SecurityMaskID
Me.RevisionSchemeID = Entity.RevisionSchemeID
End Sub
Public Overrides Sub LoadFromReader(reader As IDataReader)
Me.SecurityMaskID = ToIntegerDB(reader(0))
Me.RevisionSchemeID = ToIntegerDB(reader(1))
End Sub
Public Overrides Sub PopulateDataRow(ByRef dataRow As System.Data.DataRow)
dataRow.Item(0) = Me.SecurityMaskID
dataRow.Item(1) = Me.RevisionSchemeID
End Sub
Public Async Function Upsert(dbAccess As DMS.Base.Data.IDBAccess) As Task
Await Upsert(dbAccess, Me)
End Function
Public Overrides Function GetParameters() As IDictionary(Of String, Object)
Dim Results As New Dictionary(Of String, Object)
Results.Add("SecurityMaskID", Me.SecurityMaskID)
Results.Add("RevisionSchemeID", Me.RevisionSchemeID)
Return Results
End Function
#Region " Shared "
Private Shared _DBDetails As DMS.Base.Models.DBDetails = Nothing
Public Shared Async Function Delete(dbAccess As DMS.Base.Data.IDBAccess, entities As IEnumerable(Of SecurityMaskRevisionScheme)) As Task
Dim Tasks As New List(Of Task)
For Each Entity As SecurityMaskRevisionScheme In entities
Tasks.Add(Delete(dbAccess, Entity))
Next
Await Task.WhenAll(Tasks)
End Function
Public Shared Async Function Delete(dbAccess As DMS.Base.Data.IDBAccess, entity As SecurityMaskRevisionScheme) As Task
Await dbAccess.ExecuteNonQuery(GetDBDetails.Delete, entity.GetParameters())
End Function
Public Shared Async Function Upsert(dbAccess As DMS.Base.Data.IDBAccess, entities As IEnumerable(Of SecurityMaskRevisionScheme)) As Task
If entities.Count = 1 Then
Await Upsert(dbAccess, entities.FirstOrDefault())
Else
Dim DBDetails As DMS.Base.Models.DBDetails = GetDBDetails()
Using DataTable As DataTable = GetDataTable()
For Each Entity As SecurityMaskRevisionScheme In entities
Dim DataRow As DataRow = DataTable.NewRow
Entity.PopulateDataRow(DataRow)
DataTable.Rows.Add(DataRow)
Next
Await dbAccess.Merge(DBDetails.CreateTemp, DBDetails.DropTemp, DataTable, DBDetails.Merge, DBDetails.TableName)
End Using
End If
End Function
Public Shared Async Function Upsert(dbAccess As DMS.Base.Data.IDBAccess, entity As SecurityMaskRevisionScheme) As Task
Dim Parameters As IDictionary(Of String, Object) = entity.GetParameters()
If String.IsNullOrEmpty(entity.ID) OrElse entity.ID.Equals("-1") OrElse ToIntegerDB(Await dbAccess.ExecuteScalar(GetDBDetails.CountSingle, Parameters)) <= 0 Then
Await dbAccess.ExecuteNonQuery(GetDBDetails.Insert, Parameters)
Else
Await dbAccess.ExecuteNonQuery(GetDBDetails.Update, Parameters)
End If
End Function
Public Shared Async Function GetAll(dbAccess As DMS.Base.Data.IDBAccess) As Threading.Tasks.Task(Of IEnumerable(Of SecurityMaskRevisionScheme))
Return Await dbAccess.ExecuteReader(Of SecurityMaskRevisionScheme)(GetDBDetails.SelectAll)
End Function
Public Shared Function GetDataTable() As DataTable
Dim DataTable As New DataTable
DataTable.Columns.Add("SecurityMaskID")
DataTable.Columns.Add("RevisionSchemeID")
Return DataTable
End Function
Public Shared Function GetDBDetails() As DMS.Base.Models.DBDetails
If _DBDetails Is Nothing Then
_DBDetails = New DMS.Base.Models.DBDetails
_DBDetails.CountAll = "SELECT COUNT(*) FROM [SecurityMaskRevisionSchemes]"
_DBDetails.CountSingle = "SELECT COUNT(*) FROM [SecurityMaskRevisionSchemes] WHERE (([SecurityMaskID]=@SecurityMaskID) AND ([RevisionSchemeID]=@RevisionSchemeID))"
_DBDetails.CreateTemp = "CREATE TABLE #SecurityMaskRevisionSchemes ([SecurityMaskID] [int] NULL,[RevisionSchemeID] [int] NULL)"
_DBDetails.Delete = "DELETE FROM [SecurityMaskRevisionSchemes] WHERE (([SecurityMaskID]=@SecurityMaskID) AND ([RevisionSchemeID]=@RevisionSchemeID))"
_DBDetails.DropTemp = "DROP TABLE #SecurityMaskRevisionSchemes"
_DBDetails.GetDataTable = New DMS.Base.Delegates.GetDataTable(AddressOf GetDataTable)
_DBDetails.Insert = "INSERT INTO [SecurityMaskRevisionSchemes] ([SecurityMaskID],[RevisionSchemeID]) VALUES (@SecurityMaskID,@RevisionSchemeID)"
_DBDetails.Merge = "MERGE INTO [SecurityMaskRevisionSchemes] As [Target] USING #SecurityMaskRevisionSchemes As [Source] ON [Target].[SecurityMaskID]=[Source].[SecurityMaskID] AND [Target].[RevisionSchemeID]=[Source].[RevisionSchemeID] WHEN MATCHED THEN UPDATE SET WHEN NOT MATCHED THEN INSERT ([SecurityMaskID],[RevisionSchemeID]) VALUES ([Source].[SecurityMaskID],[Source].[RevisionSchemeID]);"
_DBDetails.ModelName = "SecurityMaskRevisionScheme"
_DBDetails.SelectAll = "SELECT [SecurityMaskID],[RevisionSchemeID] FROM [SecurityMaskRevisionSchemes]"
_DBDetails.TableName = "SecurityMaskRevisionSchemes"
_DBDetails.Update = "UPDATE [SecurityMaskRevisionSchemes] SET WHERE (([SecurityMaskID]=@SecurityMaskID) AND ([RevisionSchemeID]=@RevisionSchemeID))"
End If
Return _DBDetails
End Function
#End Region
End Class
End Namespace
|
nublet/DMS
|
DMS.Base/Models/DMSCON/Base/SecurityMaskRevisionScheme.vb
|
Visual Basic
|
mit
| 6,373
|
Public Class DeconstructQAgent
Inherits GH_Component
Sub New()
MyBase.New("Deconstruct QAgent", "DeQAgent", "Deconstruct QAgent", "Owl.Learning", "Reinforcement")
End Sub
Public Overrides ReadOnly Property ComponentGuid As Guid
Get
Return New Guid("{33D6505D-C355-4409-83A4-E9015FE691FB}")
End Get
End Property
Protected Overrides ReadOnly Property Icon As Bitmap
Get
Return My.Resources.Icons_new_15
End Get
End Property
Public Overrides ReadOnly Property Exposure As GH_Exposure
Get
Return GH_Exposure.primary
End Get
End Property
Protected Overrides Sub RegisterInputParams(pManager As GH_InputParamManager)
pManager.AddParameter(New Param_OwlQAgent)
End Sub
Protected Overrides Sub RegisterOutputParams(pManager As GH_OutputParamManager)
pManager.AddParameter(New Param_OwlTensor(), "QMatrix", "Q", "QMatrix", GH_ParamAccess.item)
pManager.AddNumberParameter("Alpha", "A", "Alpha, learning rate.", GH_ParamAccess.item)
pManager.AddNumberParameter("Gamma", "G", "Gamma, discount factor.", GH_ParamAccess.item)
pManager.AddIntegerParameter("Seed", "S", "Randomness seed.", GH_ParamAccess.item)
pManager.AddIntegerParameter("Count", "C", "Randomness count. A value required to reconstruct the pseudo random generator of the QAgent.", GH_ParamAccess.item)
End Sub
Protected Overrides Sub SolveInstance(DA As IGH_DataAccess)
Dim qa As QAgent = Nothing
If Not DA.GetData(0, qa) Then Return
DA.SetData(0, qa.QMatrix)
DA.SetData(1, qa.Alpha)
DA.SetData(2, qa.Gamma)
DA.SetData(3, qa.RndSeed)
DA.SetData(4, qa.RndCount)
End Sub
End Class
|
mateuszzwierzycki/Owl
|
Owl.GH/Components/Owl.Learning/Reinforcement/1/DeconstructQLearn.vb
|
Visual Basic
|
mit
| 1,734
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.