Search is not available for this dataset
text
stringlengths 0
1.63M
|
---|
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("FichaVBNET_ex4")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("FichaVBNET_ex4")>
<Assembly: AssemblyCopyright("Copyright © 2016")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("bde413dc-2c9d-474f-835a-817f40829dea")>
' 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")>
|
Public Class UC_LiteEditor
Inherits System.Web.UI.UserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
End Class |
'------------------------------------------------------------------------------
' <auto-generated>
' Este código se generó a partir de una plantilla.
'
' Los cambios manuales en este archivo pueden causar un comportamiento inesperado de la aplicación.
' Los cambios manuales en este archivo se sobrescribirán si se regenera el código.
' </auto-generated>
'------------------------------------------------------------------------------
Imports System
Imports System.Data.Entity
Imports System.Data.Entity.Infrastructure
Namespace TomaFisica.Entities
Partial Public Class ITSEntities
Inherits DbContext
Public Sub New()
MyBase.New("name=ITSEntities")
End Sub
Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
Throw New UnintentionalCodeFirstException()
End Sub
Public Overridable Property FISICO_DETALLE() As DbSet(Of FISICO_DETALLE)
Public Overridable Property FISICO_MAESTRO() As DbSet(Of FISICO_MAESTRO)
End Class
End Namespace
|
Option Explicit On
Option Strict On
Option Infer On
#Region " --------------->> Imports/ usings "
Imports System.Text
#End Region
Namespace Cryptography.Hashes
''' <summary>
''' Copyright (c) 2000 Oren Novotny ([email protected])
''' Permission is granted to use this code for anything.
''' Derived from the RSA Data Security, Inc. MD4 Message-Digest Algorithm.
''' http://www.rsasecurity.com">RSA Data Security, Inc. requires
''' attribution for any work that is derived from the MD4 Message-Digest
''' Algorithm; for details see http://www.roxen.com/rfc/rfc1320.html.
''' This code is ported from Norbert Hranitzky'''s
''' ([email protected])
''' Java version.
''' Copyright (c) 2008 Luca Mauri (http://www.lucamauri.com)
''' The orginal version found at http://www.derkeiler.com/Newsgroups/microsoft.public.dotnet.security/2004-08/0004.html
''' was not working. I corrected and modified it so the current version is
''' now calculating proper MD4 checksum.
''' Implements the MD4 message digest algorithm in VB.Net
''' Ronald L. Rivest,
''' http://www.roxen.com/rfc/rfc1320.html
''' The MD4 Message-Digest Algorithm
''' IETF RFC-1320 (informational).
''' </summary>
''' <remarks></remarks>
Public Class MD4Hash
#Region " --------------->> Enumerationen der Klasse "
#End Region
#Region " --------------->> Eigenschaften der Klasse "
Private Const _blockLength As Int32 = 64 ' = 512 / 8
Private _context(4 - 1) As UInt32
Private _count As Int64
Private _buffer(_blockLength - 1) As Byte
Private _x(16 - 1) As UInt32
#End Region
#Region " --------------->> Konstruktor und Destruktor der Klasse "
Public Sub New()
EngineReset()
End Sub
' This constructor is here to implement the clonability of this class
Private Sub New(ByVal md As MD4Hash)
Initialize(md)
End Sub
Private Sub Initialize(ByVal md As MD4Hash)
_context = CType(md._context.Clone(), UInt32())
_buffer = CType(md._buffer.Clone(), Byte())
_count = md._count
End Sub
#End Region
#Region " --------------->> Zugriffsmethoden der Klasse "
#End Region
#Region " --------------->> Ereignismethoden Methoden der Klasse "
#End Region
#Region " --------------->> Private Methoden der Klasse "
''' <summary>
''' Resets this object disregarding any temporary data present at the
''' time of the invocation of this call.
''' </summary>
Private Sub EngineReset()
_context = New UInt32() {1732584193, 4023233417, 2562383102, 271733878}
_count = 0
For i = 0 To _blockLength - 1
_buffer(i) = 0
Next i
End Sub
''' <summary>
''' Continues an MD4 message digest using the input byte
''' </summary>
''' <param name="b">byte to input</param>
Private Sub EngineUpdate(ByVal b As Byte)
' compute number of bytes still unhashed; ie. present in buffer
Dim i = Convert.ToInt32(_count Mod _blockLength)
_count += 1 ' update number of bytes
_buffer(i) = b
If i = (_blockLength - 1) Then Transform(_buffer, 0)
End Sub
''' <summary>
''' MD4 block update operation
''' Continues an MD4 message digest operation by filling the buffer,
''' transform(ing) data in 512-bit message block(s), updating the variables
''' context and count, and leaving (buffering) the remaining bytes in buffer
''' for the next update or finish.
''' </summary>
''' <param name="input">input block</param>
''' <param name="offset">start of meaningful bytes in input</param>
''' <param name="len">count of bytes in input blcok to consider</param>
Private Sub EngineUpdate(ByVal input() As Byte, ByVal offset As Int32, ByVal len As Int32)
' make sure we don't exceed input's allocated size/length
If ((offset < 0) OrElse (len < 0) OrElse (offset + len > input.Length)) Then
Throw New ArgumentOutOfRangeException()
End If
' compute number of bytes still unhashed; ie. present in buffer
Dim bufferNdx = Convert.ToInt32(_count Mod _blockLength)
_count += len ' update number of bytes
Dim partLen = (_blockLength - bufferNdx)
Dim i = 0
If len >= partLen Then
Array.Copy(input, offset + i, _buffer, bufferNdx, partLen)
Transform(_buffer, 0)
i = partLen
While (i + _blockLength - 1) < len
Transform(input, offset + i)
i += _blockLength
End While
bufferNdx = 0
End If
' buffer remaining input
If i < len Then Array.Copy(input, offset + i, _buffer, bufferNdx, len - i)
End Sub
''' <summary>
''' Completes the hash computation by performing final operations
''' such as padding. At the return of this engineDigest, the MD
''' engine is reset.
''' </summary>
''' <returns>returns the array of bytes for the resulting hash value.</returns>
Private Function EngineDigest() As Byte()
' pad output to 56 mod 64; as RFC1320 puts it: congruent to 448 mod 512
Dim bufferNdx = Convert.ToInt32(_count Mod _blockLength)
Dim padLen As Int32
padLen = If(bufferNdx < 56, 56, 120) - bufferNdx
' padding is always binary 1 followed by binary 0's
Dim tail(padLen + 8 - 1) As Byte
tail(0) = Convert.ToByte(128)
' append length before final transform
' save number of bits, casting the long to an array of 8 bytes
' save low-order byte first.
Dim tempArray As Byte()
tempArray = BitConverter.GetBytes(_count * 8)
tempArray.CopyTo(tail, padLen)
EngineUpdate(tail, 0, tail.Length)
Dim result(16 - 1) As Byte
For i = 0 To 3
Dim tempStore(4 - 1) As Byte
tempStore = BitConverter.GetBytes(_context(i))
tempStore.CopyTo(result, i * 4)
Next i
' reset the engine
EngineReset()
Return result
End Function
Private Shared Function BytesToHex(ByVal a() As Byte, ByVal len As Int32) As String
Dim temp = BitConverter.ToString(a)
' We need to remove the dashes that come from the BitConverter
' This should be the final size
Dim sb = New StringBuilder(Convert.ToInt32((len - 2) / 2))
For i = 0 To temp.Length - 1 Step 1
If temp(i) <> "-" Then sb.Append(temp(i))
Next i
Return sb.ToString()
End Function
''' <summary>
''' MD4 basic transformation
''' Transforms context based on 512 bits from input block starting
''' from the offset'th byte.
''' </summary>
''' <param name="block">input sub-array</param>
''' <param name="offset">starting position of sub-array</param>
Private Sub Transform(ByRef block() As Byte, ByVal offset As Int32)
' decodes 64 bytes from input block into an array of 16 32-bit
' entities. Use A as a temp var.
For i = 0 To 15 Step 1
If offset >= block.Length Then Exit For
_x(i) = Convert.ToUInt32((Convert.ToUInt32(block(offset + 0)) And 255) _
Or (Convert.ToUInt32(block(offset + 1)) And 255) << 8 _
Or (Convert.ToUInt32(block(offset + 2)) And 255) << 16 _
Or (Convert.ToUInt32(block(offset + 3)) And 255) << 24)
offset += 4
Next i
Dim a = _context(0)
Dim b = _context(1)
Dim c = _context(2)
Dim d = _context(3)
a = FF(a, b, c, d, _x(0), 3)
d = FF(d, a, b, c, _x(1), 7)
c = FF(c, d, a, b, _x(2), 11)
b = FF(b, c, d, a, _x(3), 19)
a = FF(a, b, c, d, _x(4), 3)
d = FF(d, a, b, c, _x(5), 7)
c = FF(c, d, a, b, _x(6), 11)
b = FF(b, c, d, a, _x(7), 19)
a = FF(a, b, c, d, _x(8), 3)
d = FF(d, a, b, c, _x(9), 7)
c = FF(c, d, a, b, _x(10), 11)
b = FF(b, c, d, a, _x(11), 19)
a = FF(a, b, c, d, _x(12), 3)
d = FF(d, a, b, c, _x(13), 7)
c = FF(c, d, a, b, _x(14), 11)
b = FF(b, c, d, a, _x(15), 19)
a = GG(a, b, c, d, _x(0), 3)
d = GG(d, a, b, c, _x(4), 5)
c = GG(c, d, a, b, _x(8), 9)
b = GG(b, c, d, a, _x(12), 13)
a = GG(a, b, c, d, _x(1), 3)
d = GG(d, a, b, c, _x(5), 5)
c = GG(c, d, a, b, _x(9), 9)
b = GG(b, c, d, a, _x(13), 13)
a = GG(a, b, c, d, _x(2), 3)
d = GG(d, a, b, c, _x(6), 5)
c = GG(c, d, a, b, _x(10), 9)
b = GG(b, c, d, a, _x(14), 13)
a = GG(a, b, c, d, _x(3), 3)
d = GG(d, a, b, c, _x(7), 5)
c = GG(c, d, a, b, _x(11), 9)
b = GG(b, c, d, a, _x(15), 13)
a = HH(a, b, c, d, _x(0), 3)
d = HH(d, a, b, c, _x(8), 9)
c = HH(c, d, a, b, _x(4), 11)
b = HH(b, c, d, a, _x(12), 15)
a = HH(a, b, c, d, _x(2), 3)
d = HH(d, a, b, c, _x(10), 9)
c = HH(c, d, a, b, _x(6), 11)
b = HH(b, c, d, a, _x(14), 15)
a = HH(a, b, c, d, _x(1), 3)
d = HH(d, a, b, c, _x(9), 9)
c = HH(c, d, a, b, _x(5), 11)
b = HH(b, c, d, a, _x(13), 15)
a = HH(a, b, c, d, _x(3), 3)
d = HH(d, a, b, c, _x(11), 9)
c = HH(c, d, a, b, _x(7), 11)
b = HH(b, c, d, a, _x(15), 15)
_context(0) = TruncateHex(Convert.ToUInt64(_context(0) + Convert.ToInt64(a)))
_context(1) = TruncateHex(Convert.ToUInt64(_context(1) + Convert.ToInt64(b)))
_context(2) = TruncateHex(Convert.ToUInt64(_context(2) + Convert.ToInt64(c)))
_context(3) = TruncateHex(Convert.ToUInt64(_context(3) + Convert.ToInt64(d)))
End Sub
Private Function FF _
(ByVal a As UInt32 _
, ByVal b As UInt32 _
, ByVal c As UInt32 _
, ByVal d As UInt32 _
, ByVal x As UInt32 _
, ByVal s As Int32) As UInt32
Dim t As UInt32
Try
t = TruncateHex(Convert.ToUInt64(TruncateHex(Convert.ToUInt64(Convert.ToInt64(a) _
+ ((b And c) Or ((Not b) And d)))) + Convert.ToInt64(x)))
Return (t << s) Or (t >> (32 - s))
Catch ex As Exception
Return (t << s) Or (t >> (32 - s))
End Try
End Function
Private Function GG _
(ByVal a As UInt32 _
, ByVal b As UInt32 _
, ByVal c As UInt32 _
, ByVal d As UInt32 _
, ByVal x As UInt32 _
, ByVal s As Int32) As UInt32
Dim t As UInt32
Try
t = TruncateHex(CULng(TruncateHex(Convert.ToUInt64(Convert.ToInt64(a) _
+ ((b And (c Or d)) Or (c And d)))) + Convert.ToInt64(x) + 1518500249)) '&H5A827999
Return t << s Or t >> (32 - s)
Catch
Return t << s Or t >> (32 - s)
End Try
End Function
Private Function HH _
(ByVal a As UInt32 _
, ByVal b As UInt32 _
, ByVal c As UInt32 _
, ByVal d As UInt32 _
, ByVal x As UInt32 _
, ByVal s As Int32) As UInt32
Dim t As UInt32
Try
t = TruncateHex(Convert.ToUInt64(TruncateHex _
(Convert.ToUInt64(Convert.ToInt64(a) + (b Xor c Xor d))) _
+ Convert.ToInt64(x) + 1859775393)) '&H6ED9EBA1
Return t << s Or t >> (32 - s)
Catch
Return t << s Or t >> (32 - s)
End Try
End Function
Private Function TruncateHex(ByVal number64 As UInt64) As UInt32
Dim hexString = number64.ToString("x")
Dim hexStringLimited = If(hexString.Length < 8 _
, hexString.PadLeft(8, Convert.ToChar("0")), hexString.Substring(hexString.Length - 8))
Return UInt32.Parse(hexStringLimited, Globalization.NumberStyles.HexNumber)
End Function
#End Region
#Region " --------------->> Öffentliche Methoden der Klasse "
Public Function Clone() As Object
Return New MD4Hash(Me)
End Function
''' <summary>Returns a byte hash from a string</summary>
''' <param name="s">string to hash</param>
''' <returns>returns byte-array that contains the hash</returns>
Public Function GetByteHashFromString(ByVal s As String) As Byte()
Dim b = Encoding.UTF8.GetBytes(s)
Dim md4 = New MD4Hash()
md4.EngineUpdate(b, 0, b.Length)
Return md4.EngineDigest()
End Function
''' <summary>Returns a binary hash from an input byte array</summary>
''' <param name="b">byte-array to hash</param>
''' <returns>returns binary hash of input</returns>
Public Function GetByteHashFromBytes(ByVal b() As Byte) As Byte()
Dim md4 = New MD4Hash()
md4.EngineUpdate(b, 0, b.Length)
Return md4.EngineDigest()
End Function
''' <summary>Returns a string that contains the hexadecimal hash</summary>
''' <param name="b">byte-array to input</param>
''' <returns>returns String that contains the hex of the hash</returns>
Public Function GetHexHashFromBytes(ByVal b() As Byte) As String
Dim e = GetByteHashFromBytes(b)
Return BytesToHex(e, e.Length)
End Function
''' <summary>Returns a byte hash from the input byte</summary>
''' <param name="b">byte to hash</param>
''' <returns>returns binary hash of the input byte</returns>
Public Function GetByteHashFromByte(ByVal b As Byte) As Byte()
Dim md4 = New MD4Hash()
md4.EngineUpdate(b)
Return md4.EngineDigest()
End Function
''' <summary>Returns a string that contains the hexadecimal hash</summary>
''' <param name="b">byte to hash</param>
''' <returns>returns String that contains the hex of the hash</returns>
Public Function GetHexHashFromByte(ByVal b As Byte) As String
Dim e = GetByteHashFromByte(b)
Return BytesToHex(e, e.Length)
End Function
''' <summary>Returns a string that contains the hexadecimal hash</summary>
''' <param name="s">string to hash</param>
''' <returns>returns String that contains the hex of the hash</returns>
Public Function GetHexHashFromString(ByVal s As String) As String
Dim b = GetByteHashFromString(s)
Return BytesToHex(b, b.Length)
End Function
#End Region
End Class
End Namespace
|
Public Partial Class AccordionTest
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Accordion1.ActivePaneIndex = 1
End Sub
Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i = 0
End Sub
End Class |
Imports System.Data
Partial Class PAS_rTrabajadores
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
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0))
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0))
Dim lcParametro1Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1))
Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))
Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4))
Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4))
Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim lcComandoSeleccionar As New StringBuilder()
Try
lcComandoSeleccionar.AppendLine("DECLARE @CodTra_Fin AS VARCHAR(15);")
lcComandoSeleccionar.AppendLine("DECLARE @CodTra_Ini AS VARCHAR(15);")
lcComandoSeleccionar.AppendLine("DECLARE @Contrato_Ini AS VARCHAR(2);")
lcComandoSeleccionar.AppendLine("DECLARE @Contrato_Fin AS VARCHAR(2);")
lcComandoSeleccionar.AppendLine("DECLARE @Dep_Ini AS VARCHAR(3);")
lcComandoSeleccionar.AppendLine("DECLARE @Dep_Fin AS VARCHAR(3);")
lcComandoSeleccionar.AppendLine("DECLARE @Cargo_Ini AS VARCHAR(10);")
lcComandoSeleccionar.AppendLine("DECLARE @Cargo_Fin AS VARCHAR(10);")
lcComandoSeleccionar.AppendLine("DECLARE @Fecha_Ini AS DATETIME;")
lcComandoSeleccionar.AppendLine("DECLARE @Fecha_Fin AS DATETIME;")
lcComandoSeleccionar.AppendLine("")
lcComandoSeleccionar.AppendLine("SET @CodTra_Ini = " & lcParametro0Desde)
lcComandoSeleccionar.AppendLine("SET @CodTra_Fin = " & lcParametro0Hasta)
lcComandoSeleccionar.AppendLine("SET @Contrato_Ini = " & lcParametro2Desde)
lcComandoSeleccionar.AppendLine("SET @Contrato_Fin = " & lcParametro2Hasta)
lcComandoSeleccionar.AppendLine("SET @Dep_Ini = " & lcParametro3Desde)
lcComandoSeleccionar.AppendLine("SET @Dep_Fin = " & lcParametro3Hasta)
lcComandoSeleccionar.AppendLine("SET @Cargo_Ini = " & lcParametro4Desde)
lcComandoSeleccionar.AppendLine("SET @Cargo_Fin = " & lcParametro4Hasta)
lcComandoSeleccionar.AppendLine("SET @Fecha_Ini = " & lcParametro5Desde)
lcComandoSeleccionar.AppendLine("SET @Fecha_Fin = " & lcParametro5Hasta)
lcComandoSeleccionar.AppendLine("")
lcComandoSeleccionar.AppendLine("SELECT DISTINCT ")
lcComandoSeleccionar.AppendLine(" Trabajadores.Rif AS Cod_Tra,")
lcComandoSeleccionar.AppendLine(" Trabajadores.Nom_Tra AS Nom_Tra,")
lcComandoSeleccionar.AppendLine(" Cargos.Nom_Car AS Cargo,")
lcComandoSeleccionar.AppendLine(" Trabajadores.Fec_Ini AS Ingreso,")
lcComandoSeleccionar.AppendLine(" Renglones_Recibos.Mon_Net AS Sueldo,")
lcComandoSeleccionar.AppendLine(" Trabajadores.Status AS Status,")
lcComandoSeleccionar.AppendLine(" @Fecha_Ini AS Desde,")
lcComandoSeleccionar.AppendLine(" @Fecha_Fin AS Hasta")
lcComandoSeleccionar.AppendLine("FROM Recibos")
lcComandoSeleccionar.AppendLine(" JOIN Renglones_Recibos ON Recibos.Documento = Renglones_Recibos.Documento")
lcComandoSeleccionar.AppendLine(" JOIN Trabajadores ON Trabajadores.Cod_Tra = Recibos.Cod_Tra")
lcComandoSeleccionar.AppendLine(" JOIN Contratos ON Trabajadores.Cod_Con = Contratos.Cod_Con")
lcComandoSeleccionar.AppendLine(" JOIN Departamentos_Nomina ON Departamentos_Nomina.Cod_Dep = Trabajadores.Cod_Dep")
lcComandoSeleccionar.AppendLine(" JOIN Cargos ON Cargos.Cod_Car = Trabajadores.Cod_Car")
lcComandoSeleccionar.AppendLine("WHERE Recibos.Fecha >= @Fecha_Ini AND Recibos.Fecha < DATEADD(dd, DATEDIFF(dd, 0, @Fecha_Fin) + 1, 0)")
lcComandoSeleccionar.AppendLine(" AND Renglones_Recibos.Cod_Con = 'Q024'")
lcComandoSeleccionar.AppendLine(" AND Trabajadores.Cod_Tra BETWEEN @CodTra_Ini AND @CodTra_Fin")
lcComandoSeleccionar.AppendLine(" AND Contratos.Cod_Con BETWEEN @Contrato_Ini AND @Contrato_Fin")
lcComandoSeleccionar.AppendLine(" AND Departamentos_Nomina.Cod_Dep BETWEEN @Dep_Ini AND @Dep_Fin")
lcComandoSeleccionar.AppendLine(" AND Cargos.Cod_Car BETWEEN @Cargo_Ini AND @Cargo_Fin")
lcComandoSeleccionar.AppendLine(" AND Trabajadores.Status IN (" & lcParametro1Desde & " )")
lcComandoSeleccionar.AppendLine("ORDER BY Trabajadores.Rif, Trabajadores.Nom_Tra")
'Me.mEscribirConsulta(lcComandoSeleccionar.ToString())
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(lcComandoSeleccionar.ToString, "curReportes")
Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa")
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("PAS_rTrabajadores", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvPAS_rTrabajadores.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
'-------------------------------------------------------------------------------------------'
' JJD: 06/12/08: Programacion inicial
'-------------------------------------------------------------------------------------------'
' YJP: 14/05/09: Agregar filtro revisión
'-------------------------------------------------------------------------------------------'
' CMS: 22/06/09: Metodo de ordenamiento
'-------------------------------------------------------------------------------------------'
' AAP: 01/07/09: Filtro "Sucursal:"
'-------------------------------------------------------------------------------------------'
|
Imports INDArray = org.nd4j.linalg.api.ndarray.INDArray
Imports ArrayUtil = org.nd4j.common.util.ArrayUtil
'
' * ******************************************************************************
' * *
' * *
' * * This program and the accompanying materials are made available under the
' * * terms of the Apache License, Version 2.0 which is available at
' * * https://www.apache.org/licenses/LICENSE-2.0.
' * *
' * * See the NOTICE file distributed with this work for additional
' * * information regarding copyright ownership.
' * * 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.
' * *
' * * SPDX-License-Identifier: Apache-2.0
' * *****************************************************************************
'
Namespace org.nd4j.linalg.convolution
Public MustInherit Class BaseConvolution
Implements ConvolutionInstance
Public MustOverride Function convn(ByVal input As INDArray, ByVal kernel As INDArray, ByVal type As Convolution.Type, ByVal axes() As Integer) As INDArray
''' <summary>
''' 2d convolution (aka the last 2 dimensions
''' </summary>
''' <param name="input"> the input to op </param>
''' <param name="kernel"> the kernel to convolve with </param>
''' <param name="type">
''' @return </param>
Public Overridable Function conv2d(ByVal input As INDArray, ByVal kernel As INDArray, ByVal type As Convolution.Type) As INDArray Implements ConvolutionInstance.conv2d
Dim axes() As Integer = If(input.shape().Length < 2, ArrayUtil.range(0, 1), ArrayUtil.range(input.shape().Length - 2, input.shape().Length))
Return convn(input, kernel, type, axes)
End Function
''' <summary>
''' ND Convolution
''' </summary>
''' <param name="input"> the input to transform </param>
''' <param name="kernel"> the kernel to transform with </param>
''' <param name="type"> the opType of convolution </param>
''' <returns> the convolution of the given input and kernel </returns>
Public Overridable Function convn(ByVal input As INDArray, ByVal kernel As INDArray, ByVal type As Convolution.Type) As INDArray Implements ConvolutionInstance.convn
Return convn(input, kernel, type, ArrayUtil.range(0, input.shape().Length))
End Function
End Class
End Namespace |
Namespace ByteBank
Public Class Cliente
#Region "PROPRIEDADES"
Private m_Nome As String
Public Property Nome As String
Get
Return m_Nome
End Get
Set(value As String)
m_Nome = value
End Set
End Property
Private m_CPF As String
Public Property CPF As String
Get
Return m_CPF
End Get
Set(value As String)
m_CPF = TestaCPF(value)
End Set
End Property
Public Property Profissao As String
Public Property Cidade As String
#End Region
#Region "FUNÇÕES ESPECIAIS"
Private Function TestaCPF(CPF As String) As String
Dim dadosArray() As String = {"11111111111", "22222222222", "33333333333", "44444444444",
"55555555555", "66666666666", "77777777777", "88888888888", "99999999999"}
Dim vResultado As Boolean = True
Dim i, x, n1, n2 As Integer
CPF = CPF.Trim
For i = 0 To dadosArray.Length - 1
If CPF.Length <> 11 Or dadosArray(i).Equals(CPF) Then
vResultado = False
End If
Next
If vResultado = False Then
Return "00000000000"
Else
For x = 0 To 1
n1 = 0
For i = 0 To 8 + x
n1 = n1 + Val(CPF.Substring(i, 1)) * (10 + x - i)
Next
n2 = 11 - (n1 - (Int(n1 / 11) * 11))
If n2 = 10 Or n2 = 11 Then n2 = 0
If n2 <> Val(CPF.Substring(9 + x, 1)) Then
vResultado = False
Exit For
End If
Next
If vResultado = False Then
Return "00000000000"
End If
End If
Return CPF
End Function
#End Region
End Class
End Namespace
|
'The MIT License (MIT)
'Copyright(c) 2016 M ABD AZIZ ALFIAN (http://about.me/azizalfian)
'Permission Is hereby granted, free Of charge, to any person obtaining a copy of this software And associated documentation
'files(the "Software"), To deal In the Software without restriction, including without limitation the rights To use, copy, modify,
'merge, publish, distribute, sublicense, And/Or sell copies Of the Software, And to permit persons to whom the Software Is furnished
'to do so, subject to the following conditions:
'The above copyright notice And this permission notice shall be included In all copies Or substantial portions Of the Software.
'THE SOFTWARE Is PROVIDED "AS IS", WITHOUT WARRANTY Of ANY KIND, EXPRESS Or IMPLIED, INCLUDING BUT Not LIMITED To THE WARRANTIES Of
'MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE And NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS Or COPYRIGHT HOLDERS BE LIABLE
'For ANY CLAIM, DAMAGES Or OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT Or OTHERWISE, ARISING FROM, OUT OF Or IN CONNECTION
'With THE SOFTWARE Or THE USE Or OTHER DEALINGS In THE SOFTWARE.
Imports System.Text
Imports System.Windows.Forms
Imports Crypto = System.Security.Cryptography
Namespace crypt
''' <summary>Class MD5</summary>
''' <author>M ABD AZIZ ALFIAN</author>
''' <lastupdate>19 April 2016</lastupdate>
''' <url>http://about.me/azizalfian</url>
''' <version>2.1.0</version>
''' <requirement>
''' - Imports System.Text
''' - Imports System.Windows.Forms
''' - Imports Crypto = System.Security.Cryptography
''' </requirement>
Public Class MD5
''' <summary>
''' Standar MD5
''' </summary>
Public Class MD5
Private ReadOnly _md5 As Crypto.MD5 = Crypto.MD5.Create()
''' <summary>
''' Membuat hash MD5
''' </summary>
''' <param name="input">Karakter string yang akan di hash MD5</param>
''' <param name="secretKey">Input secret key value</param>
''' <param name="showException">Tampilkan log exception? Default = True</param>
''' <returns>String()</returns>
Public Function Generate(input As String, secretKey As String, Optional showException As Boolean = True) As String
Try
Dim data = _md5.ComputeHash(Encoding.UTF8.GetBytes(secretKey + input + secretKey))
Dim sb As New StringBuilder()
Array.ForEach(data, Function(x) sb.Append(x.ToString("X2")))
Return sb.ToString()
Catch ex As Exception
If showException = True Then momolite.globals.Dev.CatchException(ex, globals.Dev.Icons.Errors, "momolite.crypt.MD5.MD5")
Return Nothing
Finally
GC.Collect()
End Try
End Function
''' <summary>
''' Memverifikasi enkripsi hash MD5 dengan string sebelum di enkripsi hash MD5
''' </summary>
''' <param name="input">Karakter sebelum enkripsi MD5</param>
''' <param name="secretKey">Input secret key value</param>
''' <param name="hash">Karakter setelah enkripsi MD5</param>
''' <param name="showException">Tampilkan log exception? Default = True</param>
''' <returns>Boolean</returns>
Public Function Validate(input As String, secretKey As String, hash As String, Optional showException As Boolean = True) As Boolean
Try
Dim sourceHash = Generate(input, secretKey)
Dim comparer As StringComparer = StringComparer.OrdinalIgnoreCase
Return If(comparer.Compare(sourceHash, hash) = 0, True, False)
Catch ex As Exception
If showException = True Then momolite.globals.Dev.CatchException(ex, globals.Dev.Icons.Errors, "momolite.crypt.MD5.MD5")
Return False
Finally
GC.Collect()
End Try
End Function
End Class
''' <summary>
''' MD5 mix dengan base 64
''' </summary>
Public Class MD5Base64
Private ReadOnly _md5 As Crypto.MD5 = Crypto.MD5.Create()
''' <summary>
''' Generate hash MD5 base64
''' </summary>
''' <param name="input">Karakter string yang akan di hash MD5 base64</param>
''' <param name="secretKey">Input secret key value</param>
''' <param name="showException">Tampilkan log exception? Default = True</param>
''' <returns>String</returns>
Public Function Generate(input As String, secretKey As String, Optional showException As Boolean = True) As String
Try
Dim data = _md5.ComputeHash(Encoding.UTF8.GetBytes(secretKey + input + secretKey))
Return Convert.ToBase64String(data)
Catch ex As Exception
If showException = True Then momolite.globals.Dev.CatchException(ex, globals.Dev.Icons.Errors, "momolite.crypt.MD5.MD5Base64")
Return Nothing
Finally
GC.Collect()
End Try
End Function
''' <summary>
''' Memvalidasi enkripsi hash MD5 base64 dengan string sebelum di enkripsi hash MD5 base64
''' </summary>
''' <param name="input">Karakter sebelum enkripsi MD5 base64</param>
''' <param name="secretKey">Input secret key value</param>
''' <param name="hash">Karakter setelah enkripsi MD5 base64</param>
''' <param name="showException">Tampilkan log exception? Default = True</param>
''' <returns>Boolean</returns>
Public Function Validate(input As String, secretKey As String, hash As String, Optional showException As Boolean = True) As Boolean
Try
Dim sourceHash = Generate(input, secretKey)
Dim comparer As StringComparer = StringComparer.OrdinalIgnoreCase
Return If(comparer.Compare(sourceHash, hash) = 0, True, False)
Catch ex As Exception
If showException = True Then momolite.globals.Dev.CatchException(ex, globals.Dev.Icons.Errors, "momolite.crypt.MD5.MD5Base64")
Return False
Finally
GC.Collect()
End Try
End Function
End Class
End Class
End Namespace |
'------------------------------------------------------------------------------
' <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 Uploader
End Class
|
' Copyright (c) Microsoft Open Technologies, Inc. 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 System.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Class DataFlowPass
Inherits AbstractFlowPass(Of LocalState)
Enum SlotKind
''' <summary>
''' Special slot for untracked variables
''' </summary>
NotTracked = -1
''' <summary>
''' Special slot for tracking whether code is reachable
''' </summary>
Unreachable = 0
''' <summary>
''' Special slot for tracking the implicit local for the function return value
''' </summary>
FunctionValue = 1
''' <summary>
''' The first available slot for variables
''' </summary>
''' <remarks></remarks>
FirstAvailable = 2
End Enum
''' <summary>
''' Some variables that should be considered initially assigned. Used for region analysis.
''' </summary>
Protected ReadOnly initiallyAssignedVariables As HashSet(Of Symbol)
''' <summary>
''' Defines whether or not fields of intrinsic type should be tracked. Such fields should
''' not be tracked for error reporting purposes, but should be tracked for region flow analysis
''' </summary>
Private _trackStructsWithIntrinsicTypedFields As Boolean
''' <summary>
''' Variables that were used anywhere, in the sense required to suppress warnings about unused variables.
''' </summary>
Private ReadOnly _unusedVariables As HashSet(Of LocalSymbol) = New HashSet(Of LocalSymbol)()
''' <summary>
''' Variables that were initialized or written anywhere.
''' </summary>
Private ReadOnly writtenVariables As HashSet(Of Symbol) = New HashSet(Of Symbol)()
''' <summary>
''' A mapping from local variables to the index of their slot in a flow analysis local state.
''' WARNING: if variable identifier maps into SlotKind.NotTracked, it may mean that VariableIdentifier
''' is a structure without traceable fields. This mapping is created in MakeSlotImpl(...)
''' </summary>
Dim _variableSlot As Dictionary(Of VariableIdentifier, Integer) = New Dictionary(Of VariableIdentifier, Integer)()
''' <summary>
''' A mapping from the local variable slot to the symbol for the local variable itself. This is used in the
''' implementation of region analysis (support for extract method) to compute the set of variables "always
''' assigned" in a region of code.
''' </summary>
Protected variableBySlot As VariableIdentifier() = New VariableIdentifier(10) {}
''' <summary>
''' Variable slots are allocated to local variables sequentially and never reused. This is
''' the index of the next slot number to use.
''' </summary>
Protected nextVariableSlot As Integer = SlotKind.FirstAvailable
''' <summary>
''' Tracks variables for which we have already reported a definite assignment error. This
''' allows us to report at most one such error per variable.
''' </summary>
Private alreadyReported As BitArray
''' <summary>
''' Did we see [On Error] or [Resume] statement? Used to suppress some diagnostics.
''' </summary>
Private seenOnErrorOrResume As Boolean
Friend Sub New(info As FlowAnalysisInfo, suppressConstExpressionsSupport As Boolean, Optional trackStructsWithIntrinsicTypedFields As Boolean = False)
MyBase.New(info, suppressConstExpressionsSupport)
Me.initiallyAssignedVariables = Nothing
Me._trackStructsWithIntrinsicTypedFields = trackStructsWithIntrinsicTypedFields
End Sub
Friend Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo,
suppressConstExpressionsSupport As Boolean,
Optional initiallyAssignedVariables As HashSet(Of Symbol) = Nothing,
Optional trackUnassignments As Boolean = False,
Optional trackStructsWithIntrinsicTypedFields As Boolean = False)
MyBase.New(info, region, suppressConstExpressionsSupport, trackUnassignments)
Me.initiallyAssignedVariables = initiallyAssignedVariables
Me._trackStructsWithIntrinsicTypedFields = trackStructsWithIntrinsicTypedFields
End Sub
Protected Overrides Sub InitForScan()
MyBase.InitForScan()
For Each parameter In MethodParameters
MakeSlot(parameter)
Next
Me.alreadyReported = BitArray.Empty ' no variables yet reported unassigned
Me.EnterParameters(MethodParameters) ' with parameters assigned
Dim methodMeParameter = Me.MeParameter ' and with 'Me' assigned as well
If methodMeParameter IsNot Nothing Then
Me.MakeSlot(methodMeParameter)
Me.EnterParameter(methodMeParameter)
End If
' Usually we need to treat locals used without being assigned first as assigned in the beginning of the block.
' When data flow analysis determines that the variable is sometimes used without being assigned first, we want
' to treat that variable, during region analysis, as assigned where it is introduced.
' However with goto statements that branch into for/foreach/using statements (error case) we need to treat them
' as assigned in the beginning of the method body.
'
' Example:
' Goto label1
' For x = 0 to 10
' label1:
' Dim y = [| x |] ' x should not be in dataFlowsOut.
' Next
'
' This can only happen in VB because the labels are visible in the whole method. In C# the labels are not visible
' this case.
'
If initiallyAssignedVariables IsNot Nothing Then
For Each local In initiallyAssignedVariables
SetSlotAssigned(MakeSlot(local))
Next
End If
End Sub
Protected Overrides Function Scan() As Boolean
If Not MyBase.Scan() Then
Return False
End If
' check unused variables
If Not seenOnErrorOrResume Then
For Each local In _unusedVariables
ReportUnused(local)
Next
End If
' VB doesn't support "out" so it doesn't warn for unassigned parameters. However, check variables passed
' byref are assigned so that data flow analysis detects parameters flowing out.
If ShouldAnalyzeByRefParameters Then
LeaveParameters(MethodParameters)
End If
Dim methodMeParameter = Me.MeParameter ' and also 'Me'
If methodMeParameter IsNot Nothing Then
Me.LeaveParameter(methodMeParameter)
End If
Return True
End Function
Private Sub ReportUnused(local As LocalSymbol)
' Never report that the function value is unused
' Never report that local with empty name is unused
' Locals with empty name can be generated in code with syntax errors and
' we shouldn't report such locals as unused because they were not explicitly declared
' by the user in the code
If Not local.IsFunctionValue AndAlso Not String.IsNullOrEmpty(local.Name) Then
If writtenVariables.Contains(local) Then
If local.IsConst Then
Me.diagnostics.Add(ERRID.WRN_UnusedLocalConst, local.Locations(0), If(local.Name, "dummy"))
End If
Else
Me.diagnostics.Add(ERRID.WRN_UnusedLocal, local.Locations(0), If(local.Name, "dummy"))
End If
End If
End Sub
Protected Overridable Sub ReportUnassignedByRefParameter(parameter As ParameterSymbol)
End Sub
''' <summary>
''' Perform data flow analysis, reporting all necessary diagnostics.
''' </summary>
Public Overloads Shared Sub Analyze(info As FlowAnalysisInfo, diagnostics As DiagnosticBag, suppressConstExpressionsSupport As Boolean)
Dim walker = New DataFlowPass(info, suppressConstExpressionsSupport)
Try
Dim result As Boolean = walker.Analyze()
Debug.Assert(result)
If diagnostics IsNot Nothing Then
diagnostics.AddRange(walker.diagnostics)
End If
Finally
walker.Free()
End Try
End Sub
Protected Overrides Sub Free()
Me.alreadyReported = BitArray.Null
MyBase.Free()
End Sub
Protected Overrides Function Dump(state As LocalState) As String
Dim builder As New StringBuilder()
builder.Append("[assigned ")
AppendBitNames(state.Assigned, builder)
builder.Append("]")
Return builder.ToString()
End Function
Protected Sub AppendBitNames(a As BitArray, builder As StringBuilder)
Dim any As Boolean = False
For Each bit In a.TrueBits
If any Then
builder.Append(", ")
End If
any = True
AppendBitName(bit, builder)
Next
End Sub
Protected Sub AppendBitName(bit As Integer, builder As StringBuilder)
Dim id As VariableIdentifier = variableBySlot(bit)
If id.ContainingSlot > 0 Then
AppendBitName(id.ContainingSlot, builder)
builder.Append(".")
End If
builder.Append(If(bit = 0, "*", id.Symbol.Name))
End Sub
#Region "Note Read/Write"
Protected Overridable Sub NoteRead(variable As Symbol)
If variable IsNot Nothing AndAlso variable.Kind = SymbolKind.Local Then
_unusedVariables.Remove(DirectCast(variable, LocalSymbol))
End If
End Sub
Protected Overridable Sub NoteWrite(variable As Symbol, value As BoundExpression)
If variable IsNot Nothing Then
writtenVariables.Add(variable)
Dim local = TryCast(variable, LocalSymbol)
If value IsNot Nothing AndAlso (local IsNot Nothing AndAlso Not local.IsConst AndAlso local.Type.IsReferenceType OrElse value.HasErrors) Then
' We duplicate Dev10's behavior here. The reasoning is, I would guess, that otherwise unread
' variables of reference type are useful because they keep objects alive, i.e., they are read by the
' VM. And variables that are initialized by non-constant expressions presumably are useful because
' they enable us to clearly document a discarded return value from a method invocation, e.g. var
' discardedValue = F(); >shrug<
' Note, this rule only applies to local variables and not to const locals, i.e. we always report unused
' const locals. In addition, if the value has errors then supress these diagnostics in all cases.
_unusedVariables.Remove(local)
End If
End If
End Sub
Protected Function GetNodeSymbol(node As BoundNode) As Symbol
While node IsNot Nothing
Select Case node.Kind
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(node, BoundFieldAccess)
If FieldAccessMayRequireTracking(fieldAccess) Then
node = fieldAccess.ReceiverOpt
Continue While
End If
Return Nothing
Case BoundKind.PropertyAccess
node = DirectCast(node, BoundPropertyAccess).ReceiverOpt
Continue While
Case BoundKind.MeReference
Return MeParameter
Case BoundKind.Local
Return DirectCast(node, BoundLocal).LocalSymbol
Case BoundKind.RangeVariable
Return DirectCast(node, BoundRangeVariable).RangeVariable
Case BoundKind.Parameter
Return DirectCast(node, BoundParameter).ParameterSymbol
Case BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder
Dim substitute As BoundExpression = GetPlaceholderSubstitute(DirectCast(node, BoundValuePlaceholderBase))
If substitute IsNot Nothing Then
Return GetNodeSymbol(substitute)
End If
Return Nothing
Case BoundKind.LocalDeclaration
Return DirectCast(node, BoundLocalDeclaration).LocalSymbol
Case BoundKind.ForToStatement,
BoundKind.ForEachStatement
Return DirectCast(node, BoundForStatement).DeclaredOrInferredLocalOpt
Case BoundKind.ByRefArgumentWithCopyBack
node = DirectCast(node, BoundByRefArgumentWithCopyBack).OriginalArgument
Continue While
Case Else
Return Nothing
End Select
End While
Return Nothing
End Function
Protected Overridable Sub NoteWrite(node As BoundExpression, value As BoundExpression)
Dim symbol As Symbol = GetNodeSymbol(node)
If symbol IsNot Nothing Then
If symbol.Kind = SymbolKind.Local AndAlso DirectCast(symbol, LocalSymbol).DeclarationKind = LocalDeclarationKind.AmbiguousLocals Then
' We have several locals grouped in AmbiguousLocalsPseudoSymbol
For Each local In DirectCast(symbol, AmbiguousLocalsPseudoSymbol).Locals
NoteWrite(local, value)
Next
Else
NoteWrite(symbol, value)
End If
End If
End Sub
Protected Overridable Sub NoteRead(fieldAccess As BoundFieldAccess)
Dim symbol As Symbol = GetNodeSymbol(fieldAccess)
If symbol IsNot Nothing Then
If symbol.Kind = SymbolKind.Local AndAlso DirectCast(symbol, LocalSymbol).DeclarationKind = LocalDeclarationKind.AmbiguousLocals Then
' We have several locals grouped in AmbiguousLocalsPseudoSymbol
For Each local In DirectCast(symbol, AmbiguousLocalsPseudoSymbol).Locals
NoteRead(local)
Next
Else
NoteRead(symbol)
End If
End If
End Sub
#End Region
#Region "Operations with slots"
''' <summary>
''' Locals are given slots when their declarations are encountered. We only need give slots to local variables, and
''' the "Me" variable of a structure constructs. Other variables are not given slots, and are therefore not tracked
''' by the analysis. This returns SlotKind.NotTracked for a variable that is not tracked, for fields of structs
''' that have the same assigned status as the container, and for structs that (recursively) contain no data members.
''' We do not need to track references to variables that occur before the variable is declared, as those are reported
''' in an earlier phase as "use before declaration". That allows us to avoid giving slots to local variables before
''' processing their declarations.
''' </summary>
Protected Function VariableSlot(local As Symbol, Optional containingSlot As Integer = 0) As Integer
If local Is Nothing Then
' NOTE: This point may be hit in erroneous code, like
' referencing instance members from static methods
Return SlotKind.NotTracked
End If
Dim slot As Integer
Return If((_variableSlot.TryGetValue(New VariableIdentifier(local, containingSlot), slot)), slot, SlotKind.NotTracked)
End Function
''' <summary>
''' Return the slot for a variable, or SlotKind.NotTracked if it is not tracked (because, for example, it is an empty struct).
''' </summary>
Protected Function MakeSlotsForExpression(node As BoundExpression) As SlotCollection
Dim result As New SlotCollection() ' empty
Select Case node.Kind
Case BoundKind.MeReference, BoundKind.MyBaseReference, BoundKind.MyClassReference
If MeParameter IsNot Nothing Then
result.Append(MakeSlot(MeParameter))
End If
Case BoundKind.Local
Dim local As LocalSymbol = DirectCast(node, BoundLocal).LocalSymbol
If local.DeclarationKind = LocalDeclarationKind.AmbiguousLocals Then
' multiple locals
For Each loc In DirectCast(local, AmbiguousLocalsPseudoSymbol).Locals
result.Append(MakeSlot(loc))
Next
Else
' just one simple local
result.Append(MakeSlot(local))
End If
Case BoundKind.RangeVariable
result.Append(MakeSlot(DirectCast(node, BoundRangeVariable).RangeVariable))
Case BoundKind.Parameter
result.Append(MakeSlot(DirectCast(node, BoundParameter).ParameterSymbol))
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(node, BoundFieldAccess)
Dim fieldsymbol = fieldAccess.FieldSymbol
Dim receiverOpt = fieldAccess.ReceiverOpt
' do not track static fields
If fieldsymbol.IsShared OrElse receiverOpt Is Nothing OrElse receiverOpt.Kind = BoundKind.TypeExpression Then
Exit Select ' empty result
End If
' do not track fields of non-structs
If receiverOpt.Type Is Nothing OrElse receiverOpt.Type.TypeKind <> TypeKind.Structure Then
Exit Select ' empty result
End If
result = MakeSlotsForExpression(receiverOpt)
' update slots, reuse collection
' NOTE: we don't filter out SlotKind.NotTracked values
For i = 0 To result.Count - 1
result(i) = MakeSlot(fieldAccess.FieldSymbol, result(0))
Next
Case BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder
Dim substitute As BoundExpression = Me.GetPlaceholderSubstitute(DirectCast(node, BoundValuePlaceholderBase))
If substitute IsNot Nothing Then
Return MakeSlotsForExpression(substitute)
End If
End Select
Return result
End Function
''' <summary>
''' Force a variable to have a slot.
''' </summary>
''' <param name = "local"></param>
''' <returns></returns>
Protected Function MakeSlot(local As Symbol, Optional containingSlot As Integer = 0) As Integer
If containingSlot = SlotKind.NotTracked Then
Return SlotKind.NotTracked
End If
' Check if the slot already exists
Dim varIdentifier As New VariableIdentifier(local, containingSlot)
Dim slot As Integer
If Not _variableSlot.TryGetValue(varIdentifier, slot) Then
If local.Kind = SymbolKind.Local Then
Me._unusedVariables.Add(DirectCast(local, LocalSymbol))
End If
Dim variableType As TypeSymbol = GetVariableType(local)
If IsEmptyStructType(variableType) Then
Return SlotKind.NotTracked
End If
' Create a slot
slot = nextVariableSlot
nextVariableSlot = nextVariableSlot + 1
_variableSlot.Add(varIdentifier, slot)
If slot >= variableBySlot.Length Then
Array.Resize(Me.variableBySlot, slot * 2)
End If
variableBySlot(slot) = varIdentifier
End If
Me.Normalize(Me.State)
Return slot
End Function
' In C#, we moved this cache to a separate cache held onto by the compilation, so we didn't
' recompute it each time.
'
' This is not so simple in VB, because we'd have to move the cache for members of the
' struct, and we'd need two different caches depending on _trackStructsWithIntrinsicTypedFields.
' So this optimization is not done for now in VB.
Private _isEmptyStructType As New Dictionary(Of NamedTypeSymbol, Boolean)()
Protected Overridable Function IsEmptyStructType(type As TypeSymbol) As Boolean
Dim namedType = TryCast(type, NamedTypeSymbol)
If namedType Is Nothing Then
Return False
End If
If Not IsTrackableStructType(namedType) Then
Return False
End If
Dim result As Boolean = False
If _isEmptyStructType.TryGetValue(namedType, result) Then
Return result
End If
' to break cycles
_isEmptyStructType(namedType) = True
For Each field In GetStructInstanceFields(namedType)
If Not IsEmptyStructType(field.Type) Then
_isEmptyStructType(namedType) = False
Return False
End If
Next
_isEmptyStructType(namedType) = True
Return True
End Function
Private Function IsTrackableStructType(symbol As TypeSymbol) As Boolean
If IsNonPrimitiveValueType(symbol) Then
Dim type = TryCast(symbol.OriginalDefinition, NamedTypeSymbol)
Return (type IsNot Nothing) AndAlso Not type.KnownCircularStruct
End If
Return False
End Function
''' <summary> Calculates the flag of being already reported; for structure types
''' the slot may be reported if ALL the children are reported </summary>
Private Function IsSlotAlreadyReported(symbolType As TypeSymbol, slot As Integer) As Boolean
If alreadyReported(slot) Then
Return True
End If
' not applicable for 'special slots'
If slot <= SlotKind.FunctionValue Then
Return False
End If
If Not IsTrackableStructType(symbolType) Then
Return False
End If
' For structures - check field slots
For Each field In GetStructInstanceFields(symbolType)
Dim childSlot = VariableSlot(field, slot)
If childSlot <> SlotKind.NotTracked Then
If Not IsSlotAlreadyReported(field.Type, childSlot) Then
Return False
End If
Else
Return False ' slot not created yet
End If
Next
' Seems to be assigned through children
alreadyReported(slot) = True
Return True
End Function
''' <summary> Marks slot as reported, propagates 'reported' flag to the children if necessary </summary>
Private Sub MarkSlotAsReported(symbolType As TypeSymbol, slot As Integer)
If alreadyReported(slot) Then
Return
End If
alreadyReported(slot) = True
' not applicable for 'special slots'
If slot <= SlotKind.FunctionValue Then
Return
End If
If Not IsTrackableStructType(symbolType) Then
Return
End If
' For structures - propagate to field slots
For Each field In GetStructInstanceFields(symbolType)
Dim childSlot = VariableSlot(field, slot)
If childSlot <> SlotKind.NotTracked Then
MarkSlotAsReported(field.Type, childSlot)
End If
Next
End Sub
''' <summary> Unassign a slot for a regular variable </summary>
Private Sub SetSlotUnassigned(slot As Integer)
Dim id As VariableIdentifier = variableBySlot(slot)
Dim type As TypeSymbol = GetVariableType(id.Symbol)
Debug.Assert(Not IsEmptyStructType(type))
If slot >= Me.State.Assigned.Capacity Then
Normalize(Me.State)
End If
' If the state of the slot is 'assigned' we need to clear it
' and possibly propagate it to all the parents
If Me.State.IsAssigned(slot) Then
Me.State.Unassign(slot)
If Me.tryState IsNot Nothing Then
Dim tryState = Me.tryState.Value
tryState.Unassign(slot)
Me.tryState = tryState
End If
' propagate to parents
While id.ContainingSlot > 0
' check the parent
Dim parentSlot = id.ContainingSlot
Dim parentIdentifier = variableBySlot(parentSlot)
Dim parentSymbol As Symbol = parentIdentifier.Symbol
If Not Me.State.IsAssigned(parentSlot) Then
Exit While
End If
' unassign and continue loop
Me.State.Unassign(parentSlot)
If Me.tryState IsNot Nothing Then
Dim tryState = Me.tryState.Value
tryState.Unassign(parentSlot)
Me.tryState = tryState
End If
If parentSymbol.Kind = SymbolKind.Local AndAlso DirectCast(parentSymbol, LocalSymbol).DeclarationKind = LocalDeclarationKind.FunctionValue Then
Me.State.Unassign(SlotKind.FunctionValue)
If Me.tryState IsNot Nothing Then
Dim tryState = Me.tryState.Value
tryState.Unassign(SlotKind.FunctionValue)
Me.tryState = tryState
End If
End If
id = parentIdentifier
End While
End If
If IsTrackableStructType(type) Then
' NOTE: we need to unassign the children in all cases
For Each field In GetStructInstanceFields(type)
' get child's slot
' NOTE: we don't need to care about possible cycles here because we took care of it
' in MakeSlotImpl when we created slots; we will just get SlotKind.NotTracked in worst case
Dim childSlot = VariableSlot(field, slot)
If childSlot >= SlotKind.FirstAvailable Then
SetSlotUnassigned(childSlot)
End If
Next
End If
End Sub
''' <summary>Assign a slot for a regular variable in a given state.</summary>
Private Sub SetSlotAssigned(slot As Integer, ByRef state As LocalState)
Dim id As VariableIdentifier = variableBySlot(slot)
Dim type As TypeSymbol = GetVariableType(id.Symbol)
Debug.Assert(Not IsEmptyStructType(type))
If slot >= Me.State.Assigned.Capacity Then
Normalize(Me.State)
End If
If Not state.IsAssigned(slot) Then
' assign this slot
state.Assign(slot)
If IsTrackableStructType(type) Then
' propagate to children
For Each field In GetStructInstanceFields(type)
' get child's slot
' NOTE: we don't need to care about possible cycles here because we took care of it
' in MakeSlotImpl when we created slots; we will just get SlotKind.NotTracked in worst case
Dim childSlot = VariableSlot(field, slot)
If childSlot >= SlotKind.FirstAvailable Then
SetSlotAssigned(childSlot, state)
End If
Next
End If
' propagate to parents
While id.ContainingSlot > 0
' check if all parent's children are set
Dim parentSlot = id.ContainingSlot
Dim parentIdentifier = variableBySlot(parentSlot)
Dim parentSymbol As Symbol = parentIdentifier.Symbol
Dim parentStructType = GetVariableType(parentSymbol)
' exit while if there is at least one child with a slot which is not assigned
For Each childSymbol In GetStructInstanceFields(parentStructType)
Dim childSlot = MakeSlot(childSymbol, parentSlot)
If childSlot <> SlotKind.NotTracked AndAlso Not state.IsAssigned(childSlot) Then
Exit While
End If
Next
' otherwise the parent can be set to assigned
state.Assign(parentSlot)
If parentSymbol.Kind = SymbolKind.Local AndAlso DirectCast(parentSymbol, LocalSymbol).DeclarationKind = LocalDeclarationKind.FunctionValue Then
state.Assign(SlotKind.FunctionValue)
End If
id = parentIdentifier
End While
End If
End Sub
''' <summary>Assign a slot for a regular variable.</summary>
Private Sub SetSlotAssigned(slot As Integer)
SetSlotAssigned(slot, Me.State)
End Sub
''' <summary> Hash structure fields as we may query them many times </summary>
Private typeToMembersCache As Dictionary(Of TypeSymbol, ImmutableArray(Of FieldSymbol)) = Nothing
Private Function ShouldIgnoreStructField(field As FieldSymbol) As Boolean
If field.IsShared Then
Return True
End If
If Me._trackStructsWithIntrinsicTypedFields Then
' If the flag is set we do not ignore any structure instance fields
Return False
End If
Dim fieldType As TypeSymbol = field.Type
' otherwise of fields of intrinsic type are ignored
If fieldType.IsIntrinsicValueType() Then
Return True
End If
' it the type is a type parameter and also type does NOT guarantee it is
' always a reference type, we igrore the field following Dev11 implementation
If fieldType.IsTypeParameter() Then
Dim typeParam = DirectCast(fieldType, TypeParameterSymbol)
If Not typeParam.IsReferenceType Then
Return True
End If
End If
' We also do NOT ignore all non-private fields
If field.DeclaredAccessibility <> Accessibility.Private Then
Return False
End If
' Do NOT ignore private fields from source
' NOTE: We should do this for all fields, but dev11 ignores private fields from
' metadata, so we need to as well to avoid breaking people. That's why we're
' distinguishing between source and metadata, rather than between the current
' compilation and another compilation.
If field.Dangerous_IsFromSomeCompilationIncludingRetargeting Then
' NOTE: Dev11 ignores fields auto-generated for events
Dim eventOrProperty As Symbol = field.AssociatedSymbol
If eventOrProperty Is Nothing OrElse eventOrProperty.Kind <> SymbolKind.Event Then
Return False
End If
End If
'' If the field is private we don't ignore it if it is a field of a generic struct
If field.ContainingType.IsGenericType Then
Return False
End If
Return True
End Function
Private Function GetStructInstanceFields(type As TypeSymbol) As ImmutableArray(Of FieldSymbol)
Dim result As ImmutableArray(Of FieldSymbol) = Nothing
If typeToMembersCache Is Nothing OrElse Not typeToMembersCache.TryGetValue(type, result) Then
' load and add to cache
Dim builder = ArrayBuilder(Of FieldSymbol).GetInstance()
For Each member In type.GetMembersUnordered()
' only fields
If member.Kind = SymbolKind.Field Then
Dim field = DirectCast(member, FieldSymbol)
' only instance fields
If Not ShouldIgnoreStructField(field) Then
' NOTE: DO NOT skip fields of intrinsic types if _trackStructsWithIntrinsicTypedFields is True
builder.Add(field)
End If
End If
Next
result = builder.ToImmutableAndFree()
If typeToMembersCache Is Nothing Then
typeToMembersCache = New Dictionary(Of TypeSymbol, ImmutableArray(Of FieldSymbol))
End If
typeToMembersCache.Add(type, result)
End If
Return result
End Function
Private Function GetVariableType(symbol As Symbol) As TypeSymbol
Select Case symbol.Kind
Case SymbolKind.Local
Return DirectCast(symbol, LocalSymbol).Type
Case SymbolKind.RangeVariable
Return DirectCast(symbol, RangeVariableSymbol).Type
Case SymbolKind.Field
Return DirectCast(symbol, FieldSymbol).Type
Case SymbolKind.Parameter
Return DirectCast(symbol, ParameterSymbol).Type
Case Else
Throw ExceptionUtilities.UnexpectedValue(symbol.Kind)
End Select
End Function
Protected Sub SetSlotState(slot As Integer, assigned As Boolean)
Debug.Assert(slot <> SlotKind.Unreachable)
If slot = SlotKind.NotTracked Then
Return
ElseIf slot = SlotKind.FunctionValue Then
' Function value slot is treated in a special way. For example it does not have Symbol assigned
' Just do a simple assign/unassign
If assigned Then
Me.State.Assign(slot)
Else
Me.State.Unassign(slot)
End If
Else
' The rest should be a regular slot
If assigned Then
SetSlotAssigned(slot)
Else
SetSlotUnassigned(slot)
End If
End If
End Sub
#End Region
#Region "Assignments: Check and Report"
''' <summary>
''' Check that the given variable is definitely assigned. If not, produce an error.
''' </summary>
Protected Sub CheckAssigned(symbol As Symbol, node As VisualBasicSyntaxNode, Optional rwContext As ReadWriteContext = ReadWriteContext.None)
If symbol IsNot Nothing Then
Dim local = TryCast(symbol, LocalSymbol)
If local IsNot Nothing AndAlso local.IsCompilerGenerated AndAlso Not Me.ProcessCompilerGeneratedLocals Then
' Do not process compiler generated temporary locals
Return
End If
' 'local' can be a pseudo-local representing a set of real locals
If local IsNot Nothing AndAlso local.DeclarationKind = LocalDeclarationKind.AmbiguousLocals Then
Dim ambiguous = DirectCast(local, AmbiguousLocalsPseudoSymbol)
' Ambiguous implicit receiver is always considered to be assigned
VisitAmbiguousLocalSymbol(ambiguous)
' Note reads of locals
For Each subLocal In ambiguous.Locals
NoteRead(subLocal)
Next
Else
Dim slot As Integer = MakeSlot(symbol)
If slot >= Me.State.Assigned.Capacity Then
Normalize(Me.State)
End If
If slot >= SlotKind.FirstAvailable AndAlso Me.State.Reachable AndAlso Not Me.State.IsAssigned(slot) Then
ReportUnassigned(symbol, node, rwContext)
End If
NoteRead(symbol)
End If
End If
End Sub
''' <summary> Version of CheckAssigned for bound field access </summary>
Private Sub CheckAssigned(fieldAccess As BoundFieldAccess, node As VisualBasicSyntaxNode, Optional rwContext As ReadWriteContext = ReadWriteContext.None)
Dim unassignedSlot As Integer
If Me.State.Reachable AndAlso Not IsAssigned(fieldAccess, unassignedSlot) Then
ReportUnassigned(fieldAccess.FieldSymbol, node, rwContext, unassignedSlot, fieldAccess)
End If
NoteRead(fieldAccess)
End Sub
Protected Overridable Sub VisitAmbiguousLocalSymbol(ambiguous As AmbiguousLocalsPseudoSymbol)
End Sub
Protected Overrides Sub VisitLvalue(node As BoundExpression, Optional dontLeaveRegion As Boolean = False)
MyBase.VisitLvalue(node, True) ' Don't leave region
If node.Kind = BoundKind.Local Then
Dim symbol As LocalSymbol = DirectCast(node, BoundLocal).LocalSymbol
If symbol.DeclarationKind = LocalDeclarationKind.AmbiguousLocals Then
VisitAmbiguousLocalSymbol(DirectCast(symbol, AmbiguousLocalsPseudoSymbol))
End If
End If
' NOTE: we can skip checking if Me._firstInRegion is nothing because 'node' is not nothing
If Not dontLeaveRegion AndAlso node Is Me._lastInRegion AndAlso IsInside Then
Me.LeaveRegion()
End If
End Sub
''' <summary> Check node for being assigned, return the value of unassigned slot in unassignedSlot </summary>
Private Function IsAssigned(node As BoundExpression, ByRef unassignedSlot As Integer) As Boolean
unassignedSlot = SlotKind.NotTracked
If IsEmptyStructType(node.Type) Then
Return True
End If
Select Case node.Kind
Case BoundKind.MeReference
unassignedSlot = VariableSlot(MeParameter)
Case BoundKind.Local
Dim local As LocalSymbol = DirectCast(node, BoundLocal).LocalSymbol
If local.DeclarationKind <> LocalDeclarationKind.AmbiguousLocals Then
unassignedSlot = VariableSlot(local)
Else
' We never report ambiguous locals pseudo-symbol as unassigned,
unassignedSlot = SlotKind.NotTracked
VisitAmbiguousLocalSymbol(DirectCast(local, AmbiguousLocalsPseudoSymbol))
End If
Case BoundKind.RangeVariable
' range variables are always assigned
unassignedSlot = -1
Return True
Case BoundKind.Parameter
unassignedSlot = VariableSlot(DirectCast(node, BoundParameter).ParameterSymbol)
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(node, BoundFieldAccess)
If Not FieldAccessMayRequireTracking(fieldAccess) OrElse IsAssigned(fieldAccess.ReceiverOpt, unassignedSlot) Then
Return True
End If
' NOTE: unassignedSlot must have been set by previous call to IsAssigned(...)
unassignedSlot = MakeSlot(fieldAccess.FieldSymbol, unassignedSlot)
Case BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder
Dim substitute As BoundExpression = Me.GetPlaceholderSubstitute(DirectCast(node, BoundValuePlaceholderBase))
If substitute IsNot Nothing Then
Return IsAssigned(substitute, unassignedSlot)
End If
unassignedSlot = SlotKind.NotTracked
Case Else
' The value is a method call return value or something else we can assume is assigned.
unassignedSlot = SlotKind.NotTracked
End Select
Return Me.State.IsAssigned(unassignedSlot)
End Function
''' <summary>
''' Property controls Roslyn data flow analysis features which are disabled in command-line
''' compiler mode to maintain backward compatibility (mostly diagnostics not reported by Dev11),
''' but *enabled* in flow analysis API
''' </summary>
Protected Overridable ReadOnly Property EnableBreakingFlowAnalysisFeatures As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Specifies if the analysis should process compiler generated locals.
'''
''' Note that data flow API should never report compiler generated variables
''' as well as those should not generate any diagnostics (like being unassigned, etc...).
'''
''' But when the analysis is used for iterators or anync captures it should process
''' compiler generated locals as well...
''' </summary>
Protected Overridable ReadOnly Property ProcessCompilerGeneratedLocals As Boolean
Get
Return False
End Get
End Property
Private Function GetUnassignedSymbolFirstLocation(sym As Symbol, boundFieldAccess As BoundFieldAccess) As Location
Select Case sym.Kind
Case SymbolKind.Parameter
Return Nothing
Case SymbolKind.RangeVariable
Return Nothing
Case SymbolKind.Local
Dim locations As ImmutableArray(Of Location) = sym.Locations
Return If(locations.IsEmpty, Nothing, locations(0))
Case SymbolKind.Field
Debug.Assert(boundFieldAccess IsNot Nothing)
If sym.IsShared Then
Return Nothing
End If
Dim receiver As BoundExpression = boundFieldAccess.ReceiverOpt
Debug.Assert(receiver IsNot Nothing)
Select Case receiver.Kind
Case BoundKind.Local
Return GetUnassignedSymbolFirstLocation(DirectCast(receiver, BoundLocal).LocalSymbol, Nothing)
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(receiver, BoundFieldAccess)
Return GetUnassignedSymbolFirstLocation(fieldAccess.FieldSymbol, fieldAccess)
Case Else
Return Nothing
End Select
Case Else
Debug.Assert(False, "Why is this reachable?")
Return Nothing
End Select
End Function
''' <summary>
''' Report a given variable as not definitely assigned. Once a variable has been so
''' reported, we suppress further reports of that variable.
''' </summary>
Protected Overridable Sub ReportUnassigned(sym As Symbol,
node As VisualBasicSyntaxNode,
rwContext As ReadWriteContext,
Optional slot As Integer = SlotKind.NotTracked,
Optional boundFieldAccess As BoundFieldAccess = Nothing)
If slot < SlotKind.FirstAvailable Then
slot = VariableSlot(sym)
End If
If slot >= Me.alreadyReported.Capacity Then
alreadyReported.EnsureCapacity(Me.nextVariableSlot)
End If
If sym.Kind = SymbolKind.Parameter Then
' Because there are no Out parameters in VB, general workflow should not hit this point;
' but in region analysis parameters are being unassigned, so it is reachable
Return
End If
If sym.Kind = SymbolKind.RangeVariable Then
' Range variables are always assigned for the purpose of error reporting.
Return
End If
Debug.Assert(sym.Kind = SymbolKind.Local OrElse sym.Kind = SymbolKind.Field)
Dim localOrFieldType As TypeSymbol
Dim isFunctionValue As Boolean
Dim isStaticLocal As Boolean
Dim isImplicityDeclared As Boolean = False
If sym.Kind = SymbolKind.Local Then
Dim locSym = DirectCast(sym, LocalSymbol)
localOrFieldType = locSym.Type
isFunctionValue = locSym.IsFunctionValue AndAlso EnableBreakingFlowAnalysisFeatures
isStaticLocal = locSym.IsStatic
isImplicityDeclared = locSym.IsImplicitlyDeclared
Else
isFunctionValue = False
isStaticLocal = False
localOrFieldType = DirectCast(sym, FieldSymbol).Type
End If
If Not IsSlotAlreadyReported(localOrFieldType, slot) Then
Dim warning As ERRID = Nothing
' NOTE: When a variable is being used before declaration VB generates ERR_UseOfLocalBeforeDeclaration1
' NOTE: error, thus we don't want to generate redundant warning; we base such an analysis on node
' NOTE: and symbol locations
Dim firstLocation As Location = GetUnassignedSymbolFirstLocation(sym, boundFieldAccess)
If isImplicityDeclared OrElse firstLocation Is Nothing OrElse firstLocation.SourceSpan.Start < node.SpanStart Then
' Because VB does not support out parameters, only locals OR fields of local structures can be unassigned.
If localOrFieldType IsNot Nothing AndAlso Not isStaticLocal Then
If localOrFieldType.IsIntrinsicValueType OrElse localOrFieldType.IsReferenceType Then
If localOrFieldType.IsIntrinsicValueType AndAlso Not isFunctionValue Then
warning = Nothing
Else
warning = If(rwContext = ReadWriteContext.ByRefArgument, ERRID.WRN_DefAsgUseNullRefByRef, ERRID.WRN_DefAsgUseNullRef)
End If
ElseIf localOrFieldType.IsValueType Then
' This is only reported for structures with reference type fields.
warning = If(rwContext = ReadWriteContext.ByRefArgument, ERRID.WRN_DefAsgUseNullRefByRefStr, ERRID.WRN_DefAsgUseNullRefStr)
Else
Debug.Assert(localOrFieldType.IsTypeParameter)
End If
If warning <> Nothing Then
Me.diagnostics.Add(warning, node.GetLocation(), If(sym.Name, "dummy"))
End If
End If
MarkSlotAsReported(localOrFieldType, slot)
End If
End If
End Sub
Private Sub CheckAssignedFunctionValue(local As LocalSymbol, node As VisualBasicSyntaxNode)
If Not Me.State.FunctionAssignedValue AndAlso Not seenOnErrorOrResume Then
Dim type As TypeSymbol = local.Type
' NOTE: Dev11 does NOT report warning on user-defined empty value types
' Special case: We specifically want to give a warning if the user doesn't return from a WinRT AddHandler.
' NOTE: Strictly speaking, dev11 actually checks whether the return type is EventRegistrationToken (see IsWinRTEventAddHandler),
' but the conditions should be equivalent (i.e. return EventRegistrationToken if and only if WinRT).
If EnableBreakingFlowAnalysisFeatures OrElse Not type.IsValueType OrElse type.IsIntrinsicOrEnumType OrElse Not IsEmptyStructType(type) OrElse
(Me.MethodSymbol.MethodKind = MethodKind.EventAdd AndAlso DirectCast(Me.MethodSymbol.AssociatedSymbol, EventSymbol).IsWindowsRuntimeEvent) Then
ReportUnassignedFunctionValue(local, node)
End If
End If
End Sub
Private Sub ReportUnassignedFunctionValue(local As LocalSymbol, node As VisualBasicSyntaxNode)
If Not alreadyReported(SlotKind.FunctionValue) Then
Dim type As TypeSymbol = Nothing
type = MethodReturnType
If type IsNot Nothing AndAlso
Not (MethodSymbol.IsIterator OrElse
(MethodSymbol.IsAsync AndAlso type.Equals(compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task)))) Then
Dim warning As ERRID = Nothing
Dim localName As String = GetFunctionLocalName(MethodSymbol.MethodKind, local)
type = type.GetEnumUnderlyingTypeOrSelf
' Actual warning depends on whether the local is a function,
' property, or operator value versus reference type.
If type.IsIntrinsicValueType Then
Select Case MethodSymbol.MethodKind
Case MethodKind.Conversion, MethodKind.UserDefinedOperator
warning = ERRID.WRN_DefAsgNoRetValOpVal1
Case MethodKind.PropertyGet
warning = ERRID.WRN_DefAsgNoRetValPropVal1
Case Else
Debug.Assert(MethodSymbol.MethodKind = MethodKind.Ordinary OrElse MethodSymbol.MethodKind = MethodKind.LambdaMethod)
warning = ERRID.WRN_DefAsgNoRetValFuncVal1
End Select
ElseIf type.IsReferenceType Then
Select Case MethodSymbol.MethodKind
Case MethodKind.Conversion, MethodKind.UserDefinedOperator
warning = ERRID.WRN_DefAsgNoRetValOpRef1
Case MethodKind.PropertyGet
warning = ERRID.WRN_DefAsgNoRetValPropRef1
Case Else
Debug.Assert(MethodSymbol.MethodKind = MethodKind.Ordinary OrElse MethodSymbol.MethodKind = MethodKind.LambdaMethod)
warning = ERRID.WRN_DefAsgNoRetValFuncRef1
End Select
ElseIf type.TypeKind = TypeKind.TypeParameter Then
' IsReferenceType was false, so this type parameter was not known to be a reference type.
' Following past practice, no warning is given in this case.
Else
Debug.Assert(type.IsValueType)
Select Case MethodSymbol.MethodKind
Case MethodKind.Conversion, MethodKind.UserDefinedOperator
' no warning is given in this case.
Case MethodKind.PropertyGet
warning = ERRID.WRN_DefAsgNoRetValPropRef1
Case MethodKind.EventAdd
' In Dev11, there wasn't time to change the syntax of AddHandler to allow the user
' to specify a return type (necessarily, EventRegistrationToken) for WinRT events.
' DevDiv #376690 reflects the fact that this leads to an incredibly confusing user
' experience if nothing is return: no diagnostics are reported, but RemoveHandler
' statements will silently fail. To prompt the user, (1) warn if there is no
' explicit return, and (2) modify the error message to say "AddHandler As
' EventRegistrationToken" to hint at the nature of the problem.
' Update: Dev11 just mangles an existing error message, but we'll introduce a new,
' clearer, one.
warning = ERRID.WRN_DefAsgNoRetValWinRtEventVal1
localName = MethodSymbol.AssociatedSymbol.Name
Case Else
warning = ERRID.WRN_DefAsgNoRetValFuncRef1
End Select
End If
If warning <> Nothing Then
Debug.Assert(localName IsNot Nothing)
Me.diagnostics.Add(warning, node.GetLocation(), localName)
End If
End If
alreadyReported(SlotKind.FunctionValue) = True
End If
End Sub
Private Shared Function GetFunctionLocalName(methodKind As MethodKind, local As LocalSymbol) As String
Select Case methodKind
Case MethodKind.LambdaMethod
Return StringConstants.AnonymousMethodName
Case MethodKind.Conversion, MethodKind.UserDefinedOperator
' the operator's function local is op_<something> and not
' VB's operator name, so we need to take the identifier token
' directly
Return local.IdentifierToken.ToString
Case Else
Return local.Name
End Select
End Function
''' <summary>
''' Mark a variable as assigned (or unassigned).
''' </summary>
Protected Overridable Sub Assign(node As BoundNode, value As BoundExpression, Optional assigned As Boolean = True)
Select Case node.Kind
Case BoundKind.LocalDeclaration
Dim local = DirectCast(node, BoundLocalDeclaration)
Debug.Assert(local.InitializerOpt Is value OrElse local.InitializedByAsNew)
Dim symbol = local.LocalSymbol
Dim slot As Integer = MakeSlot(symbol)
Dim written As Boolean = assigned OrElse Not Me.State.Reachable
SetSlotState(slot, written)
' Note write if the local has an initializer or if it is part of an as-new.
If assigned AndAlso (value IsNot Nothing OrElse local.InitializedByAsNew) Then NoteWrite(symbol, value)
Case BoundKind.ForToStatement,
BoundKind.ForEachStatement
Dim forStatement = DirectCast(node, BoundForStatement)
Dim symbol = forStatement.DeclaredOrInferredLocalOpt
Debug.Assert(symbol IsNot Nothing)
Dim slot As Integer = MakeSlot(symbol)
Dim written As Boolean = assigned OrElse Not Me.State.Reachable
SetSlotState(slot, written)
Case BoundKind.Local
Dim local = DirectCast(node, BoundLocal)
Dim symbol = local.LocalSymbol
If symbol.IsCompilerGenerated AndAlso Not Me.ProcessCompilerGeneratedLocals Then
' Do not process compiler generated temporary locals.
Return
End If
' Regular variable
Dim slot As Integer = MakeSlot(symbol)
SetSlotState(slot, assigned)
If symbol.IsFunctionValue Then
SetSlotState(SlotKind.FunctionValue, assigned)
End If
If assigned Then
NoteWrite(symbol, value)
End If
Case BoundKind.Parameter
Dim local = DirectCast(node, BoundParameter)
Dim symbol = local.ParameterSymbol
Dim slot As Integer = MakeSlot(symbol)
SetSlotState(slot, assigned)
If assigned Then NoteWrite(symbol, value)
Case BoundKind.MeReference
' var local = node as BoundThisReference;
Dim slot As Integer = MakeSlot(MeParameter)
SetSlotState(slot, assigned)
If assigned Then NoteWrite(MeParameter, value)
Case BoundKind.FieldAccess, BoundKind.PropertyAccess
Dim expression = DirectCast(node, BoundExpression)
Dim slots As SlotCollection = MakeSlotsForExpression(expression)
For i = 0 To slots.Count - 1
SetSlotState(slots(i), assigned)
Next
slots.Free()
If assigned Then NoteWrite(expression, value)
Case BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder
Dim substitute As BoundExpression = Me.GetPlaceholderSubstitute(DirectCast(node, BoundValuePlaceholderBase))
If substitute IsNot Nothing Then
Assign(substitute, value, assigned)
End If
Case BoundKind.ByRefArgumentWithCopyBack
Assign(DirectCast(node, BoundByRefArgumentWithCopyBack).OriginalArgument, value, assigned)
Case Else
' Other kinds of left-hand-sides either represent things not tracked (e.g. array elements)
' or errors that have been reported earlier (e.g. assignment to a unary increment)
End Select
End Sub
#End Region
#Region "Try statements"
' When assignments happen inside a region, they are treated as UN-assignments.
' Generally this is enough.
'
' The tricky part is that any instruction in Try/Catch/Finally must be considered as potentially throwing.
' Even if a subsequent write outside of the region may kill an assignment inside the region, it cannot prevent escape of
' the previous assignment.
'
' === Example:
'
' Dim x as integer = 0
' Try
' [| region starts here
' x = 1
' Blah() ' <- this statement may throw. (any instruction can).
' |] region ends here
' x = 2 ' <- it may seem that this assignment kills one above, where in fact "x = 1" can easily escape.
' Finally
' SomeUse(x) ' we can see side effects of "x = 1" here
' End Try
'
' As a result, when dealing with exception handling flows we need to maintain a separate state
' that collects UN-assignments only and is not affected by subsequent assignments.
Private tryState As LocalState?
Protected Overrides Sub VisitTryBlock(tryBlock As BoundStatement, node As BoundTryStatement, ByRef _tryState As LocalState)
If Me.TrackUnassignments Then
' store original try state
Dim oldTryState As LocalState? = Me.tryState
' start with AllBitsSet (means there were no assignments)
Me.tryState = AllBitsSet()
' visit try block. Any assignment inside the region will UN-assign corresponding bit in the tryState.
MyBase.VisitTryBlock(tryBlock, node, _tryState)
' merge resulting tryState into tryState that we were given.
Me.IntersectWith(_tryState, Me.tryState.Value)
' restore and merge old state with new changes.
If oldTryState IsNot Nothing Then
Dim tryState = Me.tryState.Value
Me.IntersectWith(tryState, oldTryState.Value)
Me.tryState = tryState
Else
Me.tryState = oldTryState
End If
Else
MyBase.VisitTryBlock(tryBlock, node, _tryState)
End If
End Sub
Protected Overrides Sub VisitCatchBlock(catchBlock As BoundCatchBlock, ByRef finallyState As LocalState)
If Me.TrackUnassignments Then
Dim oldTryState As LocalState? = Me.tryState
Me.tryState = AllBitsSet()
Me.VisitCatchBlockInternal(catchBlock, finallyState)
Me.IntersectWith(finallyState, Me.tryState.Value)
If oldTryState IsNot Nothing Then
Dim tryState = Me.tryState.Value
Me.IntersectWith(tryState, oldTryState.Value)
Me.tryState = tryState
Else
Me.tryState = oldTryState
End If
Else
Me.VisitCatchBlockInternal(catchBlock, finallyState)
End If
End Sub
Private Sub VisitCatchBlockInternal(catchBlock As BoundCatchBlock, ByRef finallyState As LocalState)
Dim local = catchBlock.LocalOpt
If local IsNot Nothing Then
MakeSlot(local)
End If
Dim exceptionSource = catchBlock.ExceptionSourceOpt
If exceptionSource IsNot Nothing Then
Assign(exceptionSource, value:=Nothing, assigned:=True)
End If
MyBase.VisitCatchBlock(catchBlock, finallyState)
End Sub
Protected Overrides Sub VisitFinallyBlock(finallyBlock As BoundStatement, ByRef unsetInFinally As LocalState)
If Me.TrackUnassignments Then
Dim oldTryState As LocalState? = Me.tryState
Me.tryState = AllBitsSet()
MyBase.VisitFinallyBlock(finallyBlock, unsetInFinally)
Me.IntersectWith(unsetInFinally, Me.tryState.Value)
If oldTryState IsNot Nothing Then
Dim tryState = Me.tryState.Value
Me.IntersectWith(tryState, oldTryState.Value)
Me.tryState = tryState
Else
Me.tryState = oldTryState
End If
Else
MyBase.VisitFinallyBlock(finallyBlock, unsetInFinally)
End If
End Sub
#End Region
Protected Overrides Function ReachableState() As LocalState
Return New LocalState(BitArray.Empty)
End Function
Private Sub EnterParameters(parameters As ImmutableArray(Of ParameterSymbol))
For Each parameter In parameters
EnterParameter(parameter)
Next
End Sub
Protected Overridable Sub EnterParameter(parameter As ParameterSymbol)
' this code has no effect except in the region analysis APIs, which assign
' variable slots to all parameters.
Dim slot As Integer = VariableSlot(parameter)
If slot >= SlotKind.FirstAvailable Then
Me.State.Assign(slot)
End If
NoteWrite(parameter, Nothing)
End Sub
Private Sub LeaveParameters(parameters As ImmutableArray(Of ParameterSymbol))
If Me.State.Reachable Then
For Each parameter In parameters
LeaveParameter(parameter)
Next
End If
End Sub
Private Sub LeaveParameter(parameter As ParameterSymbol)
If parameter.IsByRef Then
Dim slot = VariableSlot(parameter)
If Not Me.State.IsAssigned(slot) Then
ReportUnassignedByRefParameter(parameter)
End If
NoteRead(parameter)
End If
End Sub
Protected Overrides Function UnreachableState() As LocalState
' at this point we don't know what size of the bitarray to use, so we only set
' 'reachable' flag which mean 'all bits are set' in intersect/union
Return New LocalState(UnreachableBitsSet)
End Function
Protected Overrides Function AllBitsSet() As LocalState
Dim result = New LocalState(BitArray.AllSet(nextVariableSlot))
result.Unassign(SlotKind.Unreachable)
Return result
End Function
Protected Overrides Sub VisitLocalInReadWriteContext(node As BoundLocal, rwContext As ReadWriteContext)
MyBase.VisitLocalInReadWriteContext(node, rwContext)
CheckAssigned(node.LocalSymbol, node.Syntax, rwContext)
End Sub
Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode
CheckAssigned(node.LocalSymbol, node.Syntax, ReadWriteContext.None)
Return Nothing
End Function
Public Overrides Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
' Sometimes query expressions refer to query range variable just to
' copy its value to a new compound variable. There is no reference
' to the range variable in code and, from user point of view, there is
' no access to it.
If Not node.WasCompilerGenerated Then
CheckAssigned(node.RangeVariable, node.Syntax, ReadWriteContext.None)
End If
Return Nothing
End Function
' Should this local variable be considered assigned at first? It is if in the set of initially
' assigned variables, or else the current state is not reachable.
Protected Function ConsiderLocalInitiallyAssigned(variable As LocalSymbol) As Boolean
Return Not Me.State.Reachable OrElse
initiallyAssignedVariables IsNot Nothing AndAlso initiallyAssignedVariables.Contains(variable)
End Function
Public Overrides Function VisitLocalDeclaration(node As BoundLocalDeclaration) As BoundNode
Dim placeholder As BoundValuePlaceholderBase = Nothing
Dim variableIsUsedDirectlyAndIsAlwaysAssigned = DeclaredVariableIsAlwaysAssignedBeforeInitializer(node.Syntax.Parent, node.InitializerOpt, placeholder)
Dim local As LocalSymbol = node.LocalSymbol
If variableIsUsedDirectlyAndIsAlwaysAssigned Then
SetPlaceholderSubstitute(placeholder, New BoundLocal(node.Syntax, local, local.Type))
End If
' Create a slot for the declared variable to be able to track it.
Dim slot As Integer = MakeSlot(local)
'If initializer is a lambda, we need to treat the local as assigned within the lambda.
Assign(node, node.InitializerOpt,
ConsiderLocalInitiallyAssigned(local) OrElse
variableIsUsedDirectlyAndIsAlwaysAssigned OrElse
TreatTheLocalAsAssignedWithinTheLambda(local, node.InitializerOpt))
If node.InitializerOpt IsNot Nothing OrElse node.InitializedByAsNew Then
' Assign must be called after the initializer is analyzed, because the variable needs to be
' consider unassigned which the initializer is being analyzed.
MyBase.VisitLocalDeclaration(node)
End If
AssignLocalOnDeclaration(local, node)
If variableIsUsedDirectlyAndIsAlwaysAssigned Then
RemovePlaceholderSubstitute(placeholder)
End If
Return Nothing
End Function
Protected Overridable Function TreatTheLocalAsAssignedWithinTheLambda(local As LocalSymbol, right As BoundExpression) As Boolean
Return IsConvertedLambda(right)
End Function
Private Shared Function IsConvertedLambda(value As BoundExpression) As Boolean
If value Is Nothing Then
Return False
End If
Do
Select Case value.Kind
Case BoundKind.Lambda
Return True
Case BoundKind.Conversion
value = DirectCast(value, BoundConversion).Operand
Case BoundKind.DirectCast
value = DirectCast(value, BoundDirectCast).Operand
Case BoundKind.TryCast
value = DirectCast(value, BoundTryCast).Operand
Case BoundKind.Parenthesized
value = DirectCast(value, BoundParenthesized).Expression
Case Else
Return False
End Select
Loop
End Function
Friend Overridable Sub AssignLocalOnDeclaration(local As LocalSymbol, node As BoundLocalDeclaration)
If node.InitializerOpt IsNot Nothing OrElse node.InitializedByAsNew Then
Assign(node, node.InitializerOpt)
End If
End Sub
Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode
' Implicitly declared local variables don't have LocalDeclarations nodes for them. Thus,
' we need to create slots for any implicitly declared local variables in this block.
' For flow analysis purposes, we treat an implicit declared local as equivalent to a variable declared at the
' start of the method body (this block) with no initializer.
Dim localVariables = node.Locals
For Each local In localVariables
If local.IsImplicitlyDeclared Then
SetSlotState(MakeSlot(local), ConsiderLocalInitiallyAssigned(local))
End If
Next
Return MyBase.VisitBlock(node)
End Function
Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode
Dim oldPending As SavedPending = SavePending()
Dim oldSymbol = Me.symbol
Me.symbol = node.LambdaSymbol
Dim finalState As LocalState = Me.State
Me.SetState(If(finalState.Reachable, finalState.Clone(), Me.AllBitsSet()))
Me.State.Assigned(SlotKind.FunctionValue) = False
Dim save_alreadyReportedFunctionValue = alreadyReported(SlotKind.FunctionValue)
alreadyReported(SlotKind.FunctionValue) = False
EnterParameters(node.LambdaSymbol.Parameters)
VisitBlock(node.Body)
LeaveParameters(node.LambdaSymbol.Parameters)
Me.symbol = oldSymbol
alreadyReported(SlotKind.FunctionValue) = save_alreadyReportedFunctionValue
Me.State.Assigned(SlotKind.FunctionValue) = True
RestorePending(oldPending)
Me.IntersectWith(finalState, Me.State)
Me.SetState(finalState)
Return Nothing
End Function
Public Overrides Function VisitQueryLambda(node As BoundQueryLambda) As BoundNode
Dim oldSymbol = Me.symbol
Me.symbol = node.LambdaSymbol
Dim finalState As LocalState = Me.State.Clone()
VisitRvalue(node.Expression)
Me.symbol = oldSymbol
Me.IntersectWith(finalState, Me.State)
Me.SetState(finalState)
Return Nothing
End Function
Public Overrides Function VisitQueryExpression(node As BoundQueryExpression) As BoundNode
Visit(node.LastOperator)
Return Nothing
End Function
Public Overrides Function VisitQuerySource(node As BoundQuerySource) As BoundNode
Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitQueryableSource(node As BoundQueryableSource) As BoundNode
Visit(node.Source)
Return Nothing
End Function
Public Overrides Function VisitToQueryableCollectionConversion(node As BoundToQueryableCollectionConversion) As BoundNode
Visit(node.ConversionCall)
Return Nothing
End Function
Public Overrides Function VisitQueryClause(node As BoundQueryClause) As BoundNode
Visit(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitAggregateClause(node As BoundAggregateClause) As BoundNode
If node.CapturedGroupOpt IsNot Nothing Then
Visit(node.CapturedGroupOpt)
End If
Visit(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitOrdering(node As BoundOrdering) As BoundNode
Visit(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitRangeVariableAssignment(node As BoundRangeVariableAssignment) As BoundNode
Visit(node.Value)
Return Nothing
End Function
Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode
CheckAssigned(MeParameter, node.Syntax)
Return Nothing
End Function
Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode
If Not node.WasCompilerGenerated Then
CheckAssigned(node.ParameterSymbol, node.Syntax)
End If
Return Nothing
End Function
Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode
Dim result = MyBase.VisitFieldAccess(node)
If FieldAccessMayRequireTracking(node) Then
CheckAssigned(node, node.Syntax, ReadWriteContext.None)
End If
Return result
End Function
Protected Overrides Sub VisitFieldAccessInReadWriteContext(node As BoundFieldAccess, rwContext As ReadWriteContext)
MyBase.VisitFieldAccessInReadWriteContext(node, rwContext)
If FieldAccessMayRequireTracking(node) Then
CheckAssigned(node, node.Syntax, rwContext)
End If
End Sub
Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode
Dim left As BoundExpression = node.Left
'If right expression is a lambda, we need to treat the left side as assigned within the lambda.
Dim treatLocalAsAssigned As Boolean = False
If left.Kind = BoundKind.Local Then
treatLocalAsAssigned = TreatTheLocalAsAssignedWithinTheLambda(
DirectCast(left, BoundLocal).LocalSymbol, node.Right)
End If
If treatLocalAsAssigned Then
Assign(left, node.Right)
End If
MyBase.VisitAssignmentOperator(node)
If Not treatLocalAsAssigned Then
Assign(left, node.Right)
End If
Return Nothing
End Function
Protected Overrides ReadOnly Property SuppressRedimOperandRvalueOnPreserve As Boolean
Get
Return True
End Get
End Property
Public Overrides Function VisitRedimClause(node As BoundRedimClause) As BoundNode
MyBase.VisitRedimClause(node)
Assign(node.Operand, Nothing)
Return Nothing
End Function
Public Overrides Function VisitReferenceAssignment(node As BoundReferenceAssignment) As BoundNode
MyBase.VisitReferenceAssignment(node)
Assign(node.ByRefLocal, node.LValue)
Return Nothing
End Function
Protected Overrides Sub VisitForControlInitialization(node As BoundForToStatement)
MyBase.VisitForControlInitialization(node)
Assign(node.ControlVariable, node.InitialValue)
End Sub
Protected Overrides Sub VisitForControlInitialization(node As BoundForEachStatement)
MyBase.VisitForControlInitialization(node)
Assign(node.ControlVariable, Nothing)
End Sub
Protected Overrides Sub VisitForStatementVariableDeclation(node As BoundForStatement)
' if the for each statement declared a variable explicitly or by using local type inference we'll
' need to create a new slot for the new variable that is initially unassigned.
If node.DeclaredOrInferredLocalOpt IsNot Nothing Then
Dim slot As Integer = MakeSlot(node.DeclaredOrInferredLocalOpt) 'not initially assigned
Assign(node, Nothing, ConsiderLocalInitiallyAssigned(node.DeclaredOrInferredLocalOpt))
End If
End Sub
Public Overrides Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression) As BoundNode
MyBase.VisitAnonymousTypeCreationExpression(node)
Return Nothing
End Function
Public Overrides Function VisitWithStatement(node As BoundWithStatement) As BoundNode
Me.SetPlaceholderSubstitute(node.ExpressionPlaceholder, node.DraftPlaceholderSubstitute)
MyBase.VisitWithStatement(node)
Me.RemovePlaceholderSubstitute(node.ExpressionPlaceholder)
Return Nothing
End Function
Public Overrides Function VisitUsingStatement(node As BoundUsingStatement) As BoundNode
If node.ResourceList.IsDefaultOrEmpty Then
' only an expression. Let the base class' implementation deal with digging into the expression
Return MyBase.VisitUsingStatement(node)
End If
' all locals are considered initially assigned, even if the initialization expression is missing in source (error case)
For Each variableDeclarations In node.ResourceList
If variableDeclarations.Kind = BoundKind.AsNewLocalDeclarations Then
For Each variableDeclaration In DirectCast(variableDeclarations, BoundAsNewLocalDeclarations).LocalDeclarations
Dim local = variableDeclaration.LocalSymbol
Dim slot = MakeSlot(local)
If slot >= 0 Then
SetSlotAssigned(slot)
NoteWrite(local, Nothing)
Else
Debug.Assert(IsEmptyStructType(local.Type))
End If
Next
Else
Dim local = DirectCast(variableDeclarations, BoundLocalDeclaration).LocalSymbol
Dim slot = MakeSlot(local)
If slot >= 0 Then
SetSlotAssigned(slot)
NoteWrite(local, Nothing)
Else
Debug.Assert(IsEmptyStructType(local.Type))
End If
End If
Next
Dim result = MyBase.VisitUsingStatement(node)
' all locals are being read in the finally block.
For Each variableDeclarations In node.ResourceList
If variableDeclarations.Kind = BoundKind.AsNewLocalDeclarations Then
For Each variableDeclaration In DirectCast(variableDeclarations, BoundAsNewLocalDeclarations).LocalDeclarations
NoteRead(variableDeclaration.LocalSymbol)
Next
Else
NoteRead(DirectCast(variableDeclarations, BoundLocalDeclaration).LocalSymbol)
End If
Next
Return result
End Function
Protected Overridable ReadOnly Property IgnoreOutSemantics As Boolean
Get
Return True
End Get
End Property
Protected NotOverridable Overrides Sub VisitArgument(arg As BoundExpression, p As ParameterSymbol)
Debug.Assert(arg IsNot Nothing)
If p.IsByRef Then
If p.IsOut And Not Me.IgnoreOutSemantics Then
VisitLvalue(arg)
Else
VisitRvalue(arg, rwContext:=ReadWriteContext.ByRefArgument)
End If
Else
VisitRvalue(arg)
End If
End Sub
Protected Overrides Sub WriteArgument(arg As BoundExpression, isOut As Boolean)
If Not isOut Then
CheckAssignedFromArgumentWrite(arg, arg.Syntax)
End If
Assign(arg, Nothing)
MyBase.WriteArgument(arg, isOut)
End Sub
Protected Sub CheckAssignedFromArgumentWrite(expr As BoundExpression, node As VisualBasicSyntaxNode)
If Not Me.State.Reachable Then
Return
End If
Select Case expr.Kind
Case BoundKind.Local
CheckAssigned(DirectCast(expr, BoundLocal).LocalSymbol, node)
Case BoundKind.Parameter
CheckAssigned(DirectCast(expr, BoundParameter).ParameterSymbol, node)
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(expr, BoundFieldAccess)
Dim field As FieldSymbol = fieldAccess.FieldSymbol
If FieldAccessMayRequireTracking(fieldAccess) Then
CheckAssigned(fieldAccess, node, ReadWriteContext.ByRefArgument)
End If
Case BoundKind.EventAccess
Debug.Assert(False) ' TODO: is this reachable at all?
Case BoundKind.MeReference,
BoundKind.MyClassReference,
BoundKind.MyBaseReference
CheckAssigned(MeParameter, node)
End Select
End Sub
Protected Overrides Sub VisitLateBoundArgument(arg As BoundExpression, isByRef As Boolean)
If isByRef Then
VisitRvalue(arg, rwContext:=ReadWriteContext.ByRefArgument)
Else
VisitRvalue(arg)
End If
End Sub
Public Overrides Function VisitReturnStatement(node As BoundReturnStatement) As BoundNode
If Not node.IsEndOfMethodReturn Then
' We should mark it as set disregarding whether or not there is an expression; if there
' is no expression, error 30654 will be generated which in Dev10 suppresses this error
SetSlotState(SlotKind.FunctionValue, True)
Else
Dim functionLocal = TryCast(node.ExpressionOpt, BoundLocal)
If functionLocal IsNot Nothing Then
CheckAssignedFunctionValue(functionLocal.LocalSymbol, node.Syntax)
End If
End If
MyBase.VisitReturnStatement(node)
Return Nothing
End Function
Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode
CheckAssigned(MeParameter, node.Syntax)
Return Nothing
End Function
Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode
CheckAssigned(MeParameter, node.Syntax)
Return Nothing
End Function
''' <summary>
''' A variable declared with As New can be considered assigned before the initializer is executed in case the variable
''' is a value type. The reason is that in this case the initialization happens in place (not in a temporary) and
''' the variable already got the object creation expression assigned.
''' </summary>
Private Function DeclaredVariableIsAlwaysAssignedBeforeInitializer(syntax As VisualBasicSyntaxNode, boundInitializer As BoundExpression,
<Out> ByRef placeholder As BoundValuePlaceholderBase) As Boolean
placeholder = Nothing
If boundInitializer IsNot Nothing AndAlso
(boundInitializer.Kind = BoundKind.ObjectCreationExpression OrElse boundInitializer.Kind = BoundKind.NewT) Then
Dim boundInitializerBase = DirectCast(boundInitializer, BoundObjectCreationExpressionBase).InitializerOpt
If boundInitializerBase IsNot Nothing AndAlso boundInitializerBase.Kind = BoundKind.ObjectInitializerExpression Then
Dim objectInitializer = DirectCast(boundInitializerBase, BoundObjectInitializerExpression)
If syntax IsNot Nothing AndAlso syntax.Kind = SyntaxKind.VariableDeclarator Then
Dim declarator = DirectCast(syntax, VariableDeclaratorSyntax)
If declarator.AsClause IsNot Nothing AndAlso declarator.AsClause.Kind = SyntaxKind.AsNewClause Then
placeholder = objectInitializer.PlaceholderOpt
Return Not objectInitializer.CreateTemporaryLocalForInitialization
End If
End If
End If
End If
Return False
End Function
Public Overrides Function VisitAsNewLocalDeclarations(node As BoundAsNewLocalDeclarations) As BoundNode
Dim placeholder As BoundValuePlaceholderBase = Nothing
Dim variableIsUsedDirectlyAndIsAlwaysAssigned =
DeclaredVariableIsAlwaysAssignedBeforeInitializer(node.Syntax, node.Initializer, placeholder)
Dim declarations As ImmutableArray(Of BoundLocalDeclaration) = node.LocalDeclarations
If declarations.IsEmpty Then
Return Nothing
End If
' An initializer might access the declared variables in the initializer and therefore need to create a slot to
' track them
For Each localDeclaration In declarations
MakeSlot(localDeclaration.LocalSymbol)
Next
' NOTE: in case 'variableIsUsedDirectlyAndIsAlwaysAssigned' is set it must be
' Dim a[, b, ...] As New Struct(...) With { ... }.
'
' In this case Roslyn (following Dev10/Dev11) consecutively calls constructors
' and executes initializers for all declared variables. Thus, when the first
' initialzier is being executed, all other locals are not assigned yet.
'
' This behavior is emulated below by assigning the first local and visiting
' the initializer before assigning all the other locals. We don't really need
' to revisit initializer after because all errors/warnings will be property
' reported in the first visit.
Dim localToUseAsSubstitute As LocalSymbol = CreateLocalSymbolForVariables(declarations)
' process the first local declaration once
Dim localDecl As BoundLocalDeclaration = declarations(0)
' A valuetype variable declared with AsNew and initialized by an object initializer is considered
' assigned when visiting the initializer, because the initialization happens inplace and the
' variable already got the object creation expression assigned (this assignment will be created
' in the local rewriter).
Assign(localDecl, node.Initializer, ConsiderLocalInitiallyAssigned(localDecl.LocalSymbol) OrElse variableIsUsedDirectlyAndIsAlwaysAssigned)
' if needed, replace the placeholders with the bound local for the current declared variable.
If variableIsUsedDirectlyAndIsAlwaysAssigned Then
Me.SetPlaceholderSubstitute(placeholder, New BoundLocal(localDecl.Syntax, localToUseAsSubstitute, localToUseAsSubstitute.Type))
End If
Visit(node.Initializer)
Visit(localDecl) ' TODO: do we really need that?
' Visit all other declarations
For index = 1 To declarations.Length - 1
localDecl = declarations(index)
' A valuetype variable declared with AsNew and initialized by an object initializer is considered
' assigned when visiting the initializer, because the initialization happens inplace and the
' variable already got the object creation expression assigned (this assignment will be created
'in the local rewriter).
Assign(localDecl, node.Initializer, ConsiderLocalInitiallyAssigned(localDecl.LocalSymbol) OrElse variableIsUsedDirectlyAndIsAlwaysAssigned)
Visit(localDecl) ' TODO: do we really need that?
Next
' We also need to mark all
If variableIsUsedDirectlyAndIsAlwaysAssigned Then
Me.RemovePlaceholderSubstitute(placeholder)
End If
Return Nothing
End Function
Protected Overridable Function CreateLocalSymbolForVariables(declarations As ImmutableArray(Of BoundLocalDeclaration)) As LocalSymbol
Debug.Assert(declarations.Length > 0)
Return declarations(0).LocalSymbol
End Function
Protected Overrides Sub VisitObjectCreationExpressionInitializer(node As BoundObjectInitializerExpressionBase)
Dim resetPlaceholder As Boolean = node IsNot Nothing AndAlso
node.Kind = BoundKind.ObjectInitializerExpression AndAlso
DirectCast(node, BoundObjectInitializerExpression).CreateTemporaryLocalForInitialization
If resetPlaceholder Then
Me.SetPlaceholderSubstitute(DirectCast(node, BoundObjectInitializerExpression).PlaceholderOpt, Nothing) ' Override substitute
End If
MyBase.VisitObjectCreationExpressionInitializer(node)
If resetPlaceholder Then
Me.RemovePlaceholderSubstitute(DirectCast(node, BoundObjectInitializerExpression).PlaceholderOpt)
End If
End Sub
Public Overrides Function VisitOnErrorStatement(node As BoundOnErrorStatement) As BoundNode
seenOnErrorOrResume = True
Return MyBase.VisitOnErrorStatement(node)
End Function
Public Overrides Function VisitResumeStatement(node As BoundResumeStatement) As BoundNode
seenOnErrorOrResume = True
Return MyBase.VisitResumeStatement(node)
End Function
End Class
End Namespace
|
Option Explicit On
Option Infer On
Option Strict On
#Region " --------------->> Imports/ usings "
Imports System.ComponentModel.DataAnnotations
Imports System.ComponentModel.DataAnnotations.Schema
Imports SSP.Data.EntityFrameworkX.Contexts
Imports SSP.Data.EntityFrameworkX.Models.Core
Imports SSP.Data.EntityFrameworkX.Models.Core.Interfaces
#End Region
Namespace Models.GitModels
Partial Public Class RepositoryProductowner
Inherits ModelBase(Of RepositoryProductowner)
Implements IModelBase(Of RepositoryProductowner, PropertyNames, GitContext)
#Region " --------------->> Enumerationen der Klasse "
Public Enum PropertyNames
RowId
id
RepositoryFID
PersonFID
End Enum
#End Region '{Enumerationen der Klasse}
#Region " --------------->> Eigenschaften der Klasse "
Private Shared _modelCore As ModelCore(Of RepositoryProductowner, PropertyNames, GitContext)
Private _rowId as Int64
Private _id AS Int64
Private _repositoryFID AS Int64
Private _personFID AS Int64
#End Region '{Eigenschaften der Klasse}
#Region " --------------->> Konstruktor und Destruktor der Klasse "
Shared Sub New()
_modelCore = New ModelCore(Of RepositoryProductowner, PropertyNames, GitContext)("git.t_repository_productowner")
_modelCore.AddMappingInformation(PropertyNames.RowId, My.Settings.RowIdName)
_modelCore.AddMappingInformation(PropertyNames.id, "id")
_modelCore.AddMappingInformation(PropertyNames.RepositoryFID, "RepositoryFID")
_modelCore.AddMappingInformation(PropertyNames.PersonFID, "PersonFID")
End Sub
#End Region '{Konstruktor und Destruktor der Klasse}
#Region " --------------->> Zugriffsmethoden der Klasse "
<DatabaseGenerated(DatabaseGeneratedOption.Identity)>
Public Property RowId As Int64 Implements IModelBase _
(Of RepositoryProductowner, PropertyNames, GitContext).RowId
Get
Return _rowId
End Get
Set(value As Int64)
MyBase.SetPropertyValueAndRaisePropertyChanged _
(Of Int64)(NameOf(Me.RowId), _rowId, value)
End Set
End Property
<DatabaseGenerated(DatabaseGeneratedOption.Identity)>
<Key>
Public Property Id As Int64
Get
Return _id
End Get
Set(value As Int64)
MyBase.SetPropertyValueAndRaisePropertyChanged _
(Of Int64)(NameOf(Me.Id), _id, value)
End Set
End Property
Public Property RepositoryFID As Int64
Get
Return _repositoryFID
End Get
Set(value As Int64)
MyBase.SetPropertyValueAndRaisePropertyChanged _
(Of Int64)(NameOf(Me.RepositoryFID), _repositoryFID, value)
End Set
End Property
Public Property PersonFID As Int64
Get
Return _personFID
End Get
Set(value As Int64)
MyBase.SetPropertyValueAndRaisePropertyChanged _
(Of Int64)(NameOf(Me.PersonFID), _personFID, value)
End Set
End Property
#End Region '{Zugriffsmethoden der Klasse}
#Region " --------------->> Ereignismethoden Methoden der Klasse "
#End Region '{Ereignismethoden der Klasse}
#Region " --------------->> Private Methoden der Klasse "
#End Region '{Private Methoden der Klasse}
#Region " --------------->> Öffentliche Methoden der Klasse "
Public Overrides Function ToString() As String
Return MyBase.ToString
End Function
Public Shared Function GetModelCore() As ModelCore _
(Of RepositoryProductowner, PropertyNames, GitContext)
Return _modelCore
End Function
Private Function IModelBase_ModelCore() As ModelCore(Of RepositoryProductowner, PropertyNames, GitContext) _
Implements IModelBase(Of RepositoryProductowner, PropertyNames, GitContext).ModelCore
Return _modelCore
End Function
Private Function IModelBase_ModelBase() As ModelBase(Of RepositoryProductowner) _
Implements IModelBase(Of RepositoryProductowner, PropertyNames, GitContext).ModelBase
Return DirectCast(Me, ModelBase(Of RepositoryProductowner))
End Function
#End Region '{Öffentliche Methoden der Klasse}
End Class
End Namespace |
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.34014
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.admin.main
End Sub
End Class
End Namespace
|
Imports System.Xml
Namespace VecchieClassi
Public Class Provincia
#Region " PROPRIETA "
Private mID As Long
Private mIdProvincia As String
Private mDescrizione As String
Private mCodRegione As Integer
Private mErrore As Boolean
Public ReadOnly Property ID() As Long
Get
Return Me.mID
End Get
End Property
Public Property codice() As String
Get
Return mIdProvincia
End Get
Set(ByVal Value As String)
mIdProvincia = Value
End Set
End Property
Public ReadOnly Property CodiceRegione() As Integer
Get
Return Me.mCodRegione
End Get
End Property
Public Property descrizione() As String
Get
Return mDescrizione
End Get
Set(ByVal Value As String)
mDescrizione = Value.ToUpper
End Set
End Property
Public Property Errore() As Boolean
Get
Return mErrore
End Get
Set(ByVal Value As Boolean)
mErrore = Value
End Set
End Property
#End Region
#Region " METODI PUBBLICI "
Public Sub New()
Provincia()
End Sub
Public Sub New(ByVal codiceIn As String)
Provincia(codiceIn)
End Sub
Public Sub New(ByVal idProvincia As Long, ByVal fake1 As Boolean)
Provincia(idProvincia, fake1)
End Sub
#End Region
#Region " METODI PRIVATI "
Private Sub Provincia()
mIdProvincia = ""
mDescrizione = ""
Me.mID = 0
Me.mCodRegione = 0
End Sub
Private Sub Provincia(ByVal codiceIn As String)
Dim sQuery As String
Dim db As New DataBase
Dim iRet As Long
Provincia()
sQuery = "SELECT * "
sQuery = sQuery & "FROM Province "
sQuery = sQuery & "WHERE IdProvincia = '" & codiceIn & "'"
Try
With db
.SQL = sQuery
iRet = .OpenQuery()
If iRet >= 0 Then
Dim xmlDoc As New XmlDocument
xmlDoc.LoadXml(.strXML)
Me.mID = xmlDoc.GetElementsByTagName("Id").Item(0).InnerText
mIdProvincia = xmlDoc.GetElementsByTagName("IdProvincia").Item(0).InnerText
mDescrizione = xmlDoc.GetElementsByTagName("DescrizioneProvincia").Item(0).InnerText
Me.mCodRegione = xmlDoc.GetElementsByTagName("CodRegione").Item(0).InnerText
mErrore = False
ElseIf iRet < 0 Then
'listaMessaggi.aggiungi(New Messaggio(1, "Registrazione", "CodiceAccesso"))
mErrore = True
End If
End With
Catch ex As Exception
'listaMessaggi.aggiungi(New Messaggio(1, "Registrazione", "CodiceAccesso"))
mErrore = True
End Try
End Sub
Private Sub Provincia(ByVal idProvincia As Long, ByVal fake1 As Boolean)
Dim db As New DataBase
Dim iRet As Long
Provincia()
Try
With db
.SQL = "SELECT * FROM province WHERE id=" & idProvincia
iRet = .OpenQuery()
If iRet >= 0 Then
Dim xmlDoc As New XmlDocument
xmlDoc.LoadXml(.strXML)
Me.mID = xmlDoc.GetElementsByTagName("Id").Item(0).InnerText
mIdProvincia = xmlDoc.GetElementsByTagName("IdProvincia").Item(0).InnerText
mDescrizione = xmlDoc.GetElementsByTagName("DescrizioneProvincia").Item(0).InnerText
Me.mCodRegione = xmlDoc.GetElementsByTagName("CodRegione").Item(0).InnerText
mErrore = False
ElseIf iRet < 0 Then
'listaMessaggi.aggiungi(New Messaggio(1, "Registrazione", "CodiceAccesso"))
mErrore = True
End If
End With
Catch ex As Exception
'listaMessaggi.aggiungi(New Messaggio(1, "Registrazione", "CodiceAccesso"))
mErrore = True
End Try
End Sub
#End Region
End Class
End Namespace
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class absen2
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container()
Dim DataGridViewCellStyle1 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle()
Dim DataGridViewCellStyle2 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle()
Dim DataGridViewCellStyle3 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle()
Me.Label6 = New System.Windows.Forms.Label()
Me.rdalpa = New System.Windows.Forms.RadioButton()
Me.rdsakit = New System.Windows.Forms.RadioButton()
Me.rdizin = New System.Windows.Forms.RadioButton()
Me.rdhadir = New System.Windows.Forms.RadioButton()
Me.GroupBox1 = New System.Windows.Forms.GroupBox()
Me.txtalpa = New System.Windows.Forms.TextBox()
Me.Label8 = New System.Windows.Forms.Label()
Me.txtizin = New System.Windows.Forms.TextBox()
Me.Label9 = New System.Windows.Forms.Label()
Me.Label10 = New System.Windows.Forms.Label()
Me.txtsakit = New System.Windows.Forms.TextBox()
Me.Label11 = New System.Windows.Forms.Label()
Me.txthadir = New System.Windows.Forms.TextBox()
Me.txtcari = New System.Windows.Forms.TextBox()
Me.Label12 = New System.Windows.Forms.Label()
Me.Button3 = New System.Windows.Forms.Button()
Me.Button2 = New System.Windows.Forms.Button()
Me.GroupBox2 = New System.Windows.Forms.GroupBox()
Me.Timer1 = New System.Windows.Forms.Timer(Me.components)
Me.Label5 = New System.Windows.Forms.Label()
Me.txttglakhir = New System.Windows.Forms.TextBox()
Me.DataGridView1 = New System.Windows.Forms.DataGridView()
Me.FileToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
Me.MasterDataToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
Me.txtnama = New System.Windows.Forms.TextBox()
Me.LaporanToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
Me.Label1 = New System.Windows.Forms.Label()
Me.MenuStrip1 = New System.Windows.Forms.MenuStrip()
Me.AbsensiToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
Me.HelpToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
Me.txtnip = New System.Windows.Forms.TextBox()
Me.Button4 = New System.Windows.Forms.Button()
Me.btnhapus = New System.Windows.Forms.Button()
Me.btnedit = New System.Windows.Forms.Button()
Me.btntambah = New System.Windows.Forms.Button()
Me.Label4 = New System.Windows.Forms.Label()
Me.Label3 = New System.Windows.Forms.Label()
Me.Label2 = New System.Windows.Forms.Label()
Me.cbmulai = New System.Windows.Forms.CheckBox()
Me.Label7 = New System.Windows.Forms.Label()
Me.txttglawal = New System.Windows.Forms.DateTimePicker()
Me.GroupBox1.SuspendLayout()
Me.GroupBox2.SuspendLayout()
CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.MenuStrip1.SuspendLayout()
Me.SuspendLayout()
'
'Label6
'
Me.Label6.AutoSize = True
Me.Label6.Font = New System.Drawing.Font("Trebuchet MS", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label6.Location = New System.Drawing.Point(542, 274)
Me.Label6.Name = "Label6"
Me.Label6.Size = New System.Drawing.Size(70, 22)
Me.Label6.TabIndex = 73
Me.Label6.Text = "Cari :"
'
'rdalpa
'
Me.rdalpa.AutoSize = True
Me.rdalpa.Font = New System.Drawing.Font("Segoe UI", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.rdalpa.Location = New System.Drawing.Point(182, 43)
Me.rdalpa.Name = "rdalpa"
Me.rdalpa.Size = New System.Drawing.Size(58, 24)
Me.rdalpa.TabIndex = 3
Me.rdalpa.TabStop = True
Me.rdalpa.Text = "Alpa"
Me.rdalpa.UseVisualStyleBackColor = True
'
'rdsakit
'
Me.rdsakit.AutoSize = True
Me.rdsakit.Font = New System.Drawing.Font("Segoe UI", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.rdsakit.Location = New System.Drawing.Point(182, 22)
Me.rdsakit.Name = "rdsakit"
Me.rdsakit.Size = New System.Drawing.Size(59, 24)
Me.rdsakit.TabIndex = 2
Me.rdsakit.TabStop = True
Me.rdsakit.Text = "Sakit"
Me.rdsakit.UseVisualStyleBackColor = True
'
'rdizin
'
Me.rdizin.AutoSize = True
Me.rdizin.Font = New System.Drawing.Font("Segoe UI", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.rdizin.Location = New System.Drawing.Point(107, 42)
Me.rdizin.Name = "rdizin"
Me.rdizin.Size = New System.Drawing.Size(50, 24)
Me.rdizin.TabIndex = 1
Me.rdizin.TabStop = True
Me.rdizin.Text = "Izin"
Me.rdizin.UseVisualStyleBackColor = True
'
'rdhadir
'
Me.rdhadir.AutoSize = True
Me.rdhadir.Font = New System.Drawing.Font("Segoe UI", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.rdhadir.Location = New System.Drawing.Point(107, 19)
Me.rdhadir.Name = "rdhadir"
Me.rdhadir.Size = New System.Drawing.Size(64, 24)
Me.rdhadir.TabIndex = 0
Me.rdhadir.TabStop = True
Me.rdhadir.Text = "Hadir"
Me.rdhadir.UseVisualStyleBackColor = True
'
'GroupBox1
'
Me.GroupBox1.Controls.Add(Me.rdalpa)
Me.GroupBox1.Controls.Add(Me.rdsakit)
Me.GroupBox1.Controls.Add(Me.rdizin)
Me.GroupBox1.Controls.Add(Me.rdhadir)
Me.GroupBox1.Font = New System.Drawing.Font("Microsoft Sans Serif", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.GroupBox1.Location = New System.Drawing.Point(6, 236)
Me.GroupBox1.Name = "GroupBox1"
Me.GroupBox1.Size = New System.Drawing.Size(247, 73)
Me.GroupBox1.TabIndex = 68
Me.GroupBox1.TabStop = False
Me.GroupBox1.Text = "Keterangan :"
'
'txtalpa
'
Me.txtalpa.Font = New System.Drawing.Font("Segoe UI", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.txtalpa.Location = New System.Drawing.Point(94, 117)
Me.txtalpa.Multiline = True
Me.txtalpa.Name = "txtalpa"
Me.txtalpa.Size = New System.Drawing.Size(98, 25)
Me.txtalpa.TabIndex = 43
Me.txtalpa.Text = "0"
Me.txtalpa.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
'
'Label8
'
Me.Label8.AutoSize = True
Me.Label8.Font = New System.Drawing.Font("Trebuchet MS", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label8.Location = New System.Drawing.Point(6, 120)
Me.Label8.Name = "Label8"
Me.Label8.Size = New System.Drawing.Size(61, 22)
Me.Label8.TabIndex = 22
Me.Label8.Text = "Alpa :"
'
'txtizin
'
Me.txtizin.Font = New System.Drawing.Font("Segoe UI", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.txtizin.Location = New System.Drawing.Point(94, 87)
Me.txtizin.Multiline = True
Me.txtizin.Name = "txtizin"
Me.txtizin.Size = New System.Drawing.Size(98, 25)
Me.txtizin.TabIndex = 45
Me.txtizin.Text = "0"
Me.txtizin.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
'
'Label9
'
Me.Label9.AutoSize = True
Me.Label9.Font = New System.Drawing.Font("Trebuchet MS", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label9.Location = New System.Drawing.Point(6, 87)
Me.Label9.Name = "Label9"
Me.Label9.Size = New System.Drawing.Size(61, 22)
Me.Label9.TabIndex = 21
Me.Label9.Text = "Izin :"
'
'Label10
'
Me.Label10.AutoSize = True
Me.Label10.Font = New System.Drawing.Font("Trebuchet MS", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label10.Location = New System.Drawing.Point(6, 56)
Me.Label10.Name = "Label10"
Me.Label10.Size = New System.Drawing.Size(61, 22)
Me.Label10.TabIndex = 20
Me.Label10.Text = "Sakit :"
'
'txtsakit
'
Me.txtsakit.Font = New System.Drawing.Font("Segoe UI", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.txtsakit.Location = New System.Drawing.Point(94, 56)
Me.txtsakit.Multiline = True
Me.txtsakit.Name = "txtsakit"
Me.txtsakit.Size = New System.Drawing.Size(98, 25)
Me.txtsakit.TabIndex = 44
Me.txtsakit.Text = "0"
Me.txtsakit.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
'
'Label11
'
Me.Label11.AutoSize = True
Me.Label11.Font = New System.Drawing.Font("Trebuchet MS", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label11.Location = New System.Drawing.Point(6, 23)
Me.Label11.Name = "Label11"
Me.Label11.Size = New System.Drawing.Size(59, 22)
Me.Label11.TabIndex = 19
Me.Label11.Text = "Hadir :"
'
'txthadir
'
Me.txthadir.Font = New System.Drawing.Font("Segoe UI", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.txthadir.Location = New System.Drawing.Point(94, 23)
Me.txthadir.Multiline = True
Me.txthadir.Name = "txthadir"
Me.txthadir.Size = New System.Drawing.Size(98, 25)
Me.txthadir.TabIndex = 43
Me.txthadir.Text = "0"
Me.txthadir.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
'
'txtcari
'
Me.txtcari.Font = New System.Drawing.Font("Segoe UI", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.txtcari.Location = New System.Drawing.Point(640, 272)
Me.txtcari.Name = "txtcari"
Me.txtcari.Size = New System.Drawing.Size(150, 27)
Me.txtcari.TabIndex = 74
'
'Label12
'
Me.Label12.AutoSize = True
Me.Label12.Font = New System.Drawing.Font("Segoe UI Semibold", 11.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label12.Location = New System.Drawing.Point(525, 36)
Me.Label12.Name = "Label12"
Me.Label12.Size = New System.Drawing.Size(71, 20)
Me.Label12.TabIndex = 72
Me.Label12.Text = "Tanggal :"
'
'Button3
'
Me.Button3.BackColor = System.Drawing.SystemColors.ButtonHighlight
Me.Button3.Font = New System.Drawing.Font("Segoe UI", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Button3.Location = New System.Drawing.Point(255, 262)
Me.Button3.Name = "Button3"
Me.Button3.Size = New System.Drawing.Size(36, 35)
Me.Button3.TabIndex = 71
Me.Button3.Text = "C"
Me.Button3.UseVisualStyleBackColor = False
'
'Button2
'
Me.Button2.BackColor = System.Drawing.SystemColors.ButtonHighlight
Me.Button2.Font = New System.Drawing.Font("Segoe UI Semibold", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Button2.ForeColor = System.Drawing.Color.Black
Me.Button2.Location = New System.Drawing.Point(490, 183)
Me.Button2.Name = "Button2"
Me.Button2.Size = New System.Drawing.Size(82, 30)
Me.Button2.TabIndex = 70
Me.Button2.Text = "Clear"
Me.Button2.UseVisualStyleBackColor = False
'
'GroupBox2
'
Me.GroupBox2.Controls.Add(Me.txtalpa)
Me.GroupBox2.Controls.Add(Me.Label8)
Me.GroupBox2.Controls.Add(Me.txtizin)
Me.GroupBox2.Controls.Add(Me.Label9)
Me.GroupBox2.Controls.Add(Me.Label10)
Me.GroupBox2.Controls.Add(Me.txtsakit)
Me.GroupBox2.Controls.Add(Me.Label11)
Me.GroupBox2.Controls.Add(Me.txthadir)
Me.GroupBox2.Font = New System.Drawing.Font("Segoe UI", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.GroupBox2.Location = New System.Drawing.Point(582, 83)
Me.GroupBox2.Name = "GroupBox2"
Me.GroupBox2.Size = New System.Drawing.Size(213, 162)
Me.GroupBox2.TabIndex = 69
Me.GroupBox2.TabStop = False
Me.GroupBox2.Text = "Ringkasan Absen"
'
'Timer1
'
Me.Timer1.Enabled = True
Me.Timer1.Interval = 1000
'
'Label5
'
Me.Label5.AutoSize = True
Me.Label5.Font = New System.Drawing.Font("Segoe UI", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label5.Location = New System.Drawing.Point(595, 36)
Me.Label5.Name = "Label5"
Me.Label5.Size = New System.Drawing.Size(61, 20)
Me.Label5.TabIndex = 67
Me.Label5.Text = "Tanggal"
'
'txttglakhir
'
Me.txttglakhir.Enabled = False
Me.txttglakhir.Font = New System.Drawing.Font("Segoe UI", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.txttglakhir.Location = New System.Drawing.Point(142, 205)
Me.txttglakhir.Multiline = True
Me.txttglakhir.Name = "txttglakhir"
Me.txttglakhir.Size = New System.Drawing.Size(191, 25)
Me.txttglakhir.TabIndex = 66
'
'DataGridView1
'
DataGridViewCellStyle1.Font = New System.Drawing.Font("Segoe UI", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.DataGridView1.AlternatingRowsDefaultCellStyle = DataGridViewCellStyle1
DataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft
DataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Control
DataGridViewCellStyle2.Font = New System.Drawing.Font("Segoe UI Semibold", 12.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
DataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText
DataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight
DataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText
DataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.[True]
Me.DataGridView1.ColumnHeadersDefaultCellStyle = DataGridViewCellStyle2
Me.DataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
DataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft
DataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Window
DataGridViewCellStyle3.Font = New System.Drawing.Font("Segoe UI", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
DataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.ControlText
DataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight
DataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText
DataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.[False]
Me.DataGridView1.DefaultCellStyle = DataGridViewCellStyle3
Me.DataGridView1.Dock = System.Windows.Forms.DockStyle.Bottom
Me.DataGridView1.Location = New System.Drawing.Point(0, 309)
Me.DataGridView1.Name = "DataGridView1"
Me.DataGridView1.Size = New System.Drawing.Size(811, 140)
Me.DataGridView1.TabIndex = 65
'
'FileToolStripMenuItem
'
Me.FileToolStripMenuItem.Name = "FileToolStripMenuItem"
Me.FileToolStripMenuItem.Size = New System.Drawing.Size(55, 21)
Me.FileToolStripMenuItem.Text = "Home"
'
'MasterDataToolStripMenuItem
'
Me.MasterDataToolStripMenuItem.Name = "MasterDataToolStripMenuItem"
Me.MasterDataToolStripMenuItem.Size = New System.Drawing.Size(99, 21)
Me.MasterDataToolStripMenuItem.Text = "Data Pegawai"
'
'txtnama
'
Me.txtnama.Font = New System.Drawing.Font("Segoe UI", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.txtnama.Location = New System.Drawing.Point(142, 116)
Me.txtnama.Name = "txtnama"
Me.txtnama.Size = New System.Drawing.Size(191, 27)
Me.txtnama.TabIndex = 63
'
'LaporanToolStripMenuItem
'
Me.LaporanToolStripMenuItem.Name = "LaporanToolStripMenuItem"
Me.LaporanToolStripMenuItem.Size = New System.Drawing.Size(68, 21)
Me.LaporanToolStripMenuItem.Text = "Laporan"
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Font = New System.Drawing.Font("Sitka Text", 18.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label1.Location = New System.Drawing.Point(222, 21)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(283, 35)
Me.Label1.TabIndex = 54
Me.Label1.Text = "ABSENSI TANDINGAN"
'
'MenuStrip1
'
Me.MenuStrip1.BackColor = System.Drawing.SystemColors.Control
Me.MenuStrip1.Font = New System.Drawing.Font("Segoe UI", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.MenuStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.FileToolStripMenuItem, Me.MasterDataToolStripMenuItem, Me.AbsensiToolStripMenuItem, Me.LaporanToolStripMenuItem, Me.HelpToolStripMenuItem})
Me.MenuStrip1.Location = New System.Drawing.Point(0, 0)
Me.MenuStrip1.Name = "MenuStrip1"
Me.MenuStrip1.Size = New System.Drawing.Size(811, 25)
Me.MenuStrip1.TabIndex = 64
Me.MenuStrip1.Text = "MenuStrip1"
'
'AbsensiToolStripMenuItem
'
Me.AbsensiToolStripMenuItem.Name = "AbsensiToolStripMenuItem"
Me.AbsensiToolStripMenuItem.Size = New System.Drawing.Size(65, 21)
Me.AbsensiToolStripMenuItem.Text = "Absensi"
'
'HelpToolStripMenuItem
'
Me.HelpToolStripMenuItem.Name = "HelpToolStripMenuItem"
Me.HelpToolStripMenuItem.Size = New System.Drawing.Size(66, 21)
Me.HelpToolStripMenuItem.Text = "Tentang"
'
'txtnip
'
Me.txtnip.Font = New System.Drawing.Font("Segoe UI", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.txtnip.Location = New System.Drawing.Point(142, 83)
Me.txtnip.Name = "txtnip"
Me.txtnip.Size = New System.Drawing.Size(191, 27)
Me.txtnip.TabIndex = 62
'
'Button4
'
Me.Button4.BackColor = System.Drawing.SystemColors.ButtonHighlight
Me.Button4.Font = New System.Drawing.Font("Segoe UI Semibold", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Button4.ForeColor = System.Drawing.Color.Black
Me.Button4.Location = New System.Drawing.Point(490, 215)
Me.Button4.Name = "Button4"
Me.Button4.Size = New System.Drawing.Size(82, 30)
Me.Button4.TabIndex = 61
Me.Button4.Text = "Keluar"
Me.Button4.UseVisualStyleBackColor = False
'
'btnhapus
'
Me.btnhapus.BackColor = System.Drawing.SystemColors.ButtonHighlight
Me.btnhapus.Font = New System.Drawing.Font("Segoe UI Semibold", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.btnhapus.ForeColor = System.Drawing.Color.Black
Me.btnhapus.Location = New System.Drawing.Point(490, 152)
Me.btnhapus.Name = "btnhapus"
Me.btnhapus.Size = New System.Drawing.Size(82, 30)
Me.btnhapus.TabIndex = 60
Me.btnhapus.Text = "Hapus"
Me.btnhapus.UseVisualStyleBackColor = False
'
'btnedit
'
Me.btnedit.BackColor = System.Drawing.SystemColors.ButtonHighlight
Me.btnedit.Font = New System.Drawing.Font("Segoe UI Semibold", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.btnedit.ForeColor = System.Drawing.Color.Black
Me.btnedit.Location = New System.Drawing.Point(490, 119)
Me.btnedit.Name = "btnedit"
Me.btnedit.Size = New System.Drawing.Size(82, 30)
Me.btnedit.TabIndex = 59
Me.btnedit.Text = "Absen"
Me.btnedit.UseVisualStyleBackColor = False
'
'btntambah
'
Me.btntambah.BackColor = System.Drawing.SystemColors.ButtonHighlight
Me.btntambah.Font = New System.Drawing.Font("Segoe UI Semibold", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.btntambah.ForeColor = System.Drawing.Color.Black
Me.btntambah.Location = New System.Drawing.Point(490, 84)
Me.btntambah.Name = "btntambah"
Me.btntambah.Size = New System.Drawing.Size(82, 30)
Me.btntambah.TabIndex = 58
Me.btntambah.Text = "Tambah"
Me.btntambah.UseVisualStyleBackColor = False
'
'Label4
'
Me.Label4.AutoSize = True
Me.Label4.Font = New System.Drawing.Font("Trebuchet MS", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label4.Location = New System.Drawing.Point(12, 190)
Me.Label4.Name = "Label4"
Me.Label4.Size = New System.Drawing.Size(124, 44)
Me.Label4.TabIndex = 57
Me.Label4.Text = "Tanggal Terakhir" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "Kali Update :"
'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.Font = New System.Drawing.Font("Trebuchet MS", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label3.Location = New System.Drawing.Point(10, 117)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(125, 22)
Me.Label3.TabIndex = 56
Me.Label3.Text = "Nama :"
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.Font = New System.Drawing.Font("Trebuchet MS", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label2.Location = New System.Drawing.Point(10, 85)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(124, 22)
Me.Label2.TabIndex = 55
Me.Label2.Text = "NIP :"
'
'cbmulai
'
Me.cbmulai.AutoSize = True
Me.cbmulai.Checked = True
Me.cbmulai.CheckState = System.Windows.Forms.CheckState.Checked
Me.cbmulai.Font = New System.Drawing.Font("Segoe UI", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.cbmulai.Location = New System.Drawing.Point(340, 163)
Me.cbmulai.Name = "cbmulai"
Me.cbmulai.Size = New System.Drawing.Size(108, 24)
Me.cbmulai.TabIndex = 75
Me.cbmulai.Text = "Mulai Ulang"
Me.cbmulai.UseVisualStyleBackColor = True
'
'Label7
'
Me.Label7.AutoSize = True
Me.Label7.Font = New System.Drawing.Font("Trebuchet MS", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label7.Location = New System.Drawing.Point(10, 143)
Me.Label7.Name = "Label7"
Me.Label7.Size = New System.Drawing.Size(122, 44)
Me.Label7.TabIndex = 77
Me.Label7.Text = "Tanggal Awal" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "Update :"
'
'txttglawal
'
Me.txttglawal.CustomFormat = "yyyy/MM/dd"
Me.txttglawal.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.txttglawal.Format = System.Windows.Forms.DateTimePickerFormat.Custom
Me.txttglawal.Location = New System.Drawing.Point(142, 164)
Me.txttglawal.Name = "txttglawal"
Me.txttglawal.Size = New System.Drawing.Size(191, 22)
Me.txttglawal.TabIndex = 78
Me.txttglawal.Value = New Date(2019, 1, 11, 11, 1, 3, 0)
'
'absen2
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(811, 449)
Me.Controls.Add(Me.txttglawal)
Me.Controls.Add(Me.Label7)
Me.Controls.Add(Me.Label6)
Me.Controls.Add(Me.txtcari)
Me.Controls.Add(Me.Label12)
Me.Controls.Add(Me.Button3)
Me.Controls.Add(Me.Button2)
Me.Controls.Add(Me.GroupBox2)
Me.Controls.Add(Me.Label5)
Me.Controls.Add(Me.txttglakhir)
Me.Controls.Add(Me.DataGridView1)
Me.Controls.Add(Me.txtnama)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.MenuStrip1)
Me.Controls.Add(Me.txtnip)
Me.Controls.Add(Me.Button4)
Me.Controls.Add(Me.btnhapus)
Me.Controls.Add(Me.btnedit)
Me.Controls.Add(Me.btntambah)
Me.Controls.Add(Me.Label4)
Me.Controls.Add(Me.Label3)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.GroupBox1)
Me.Controls.Add(Me.cbmulai)
Me.MaximizeBox = False
Me.Name = "absen2"
Me.Text = "absen2"
Me.GroupBox1.ResumeLayout(False)
Me.GroupBox1.PerformLayout()
Me.GroupBox2.ResumeLayout(False)
Me.GroupBox2.PerformLayout()
CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).EndInit()
Me.MenuStrip1.ResumeLayout(False)
Me.MenuStrip1.PerformLayout()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents Label6 As Label
Friend WithEvents rdalpa As RadioButton
Friend WithEvents rdsakit As RadioButton
Friend WithEvents rdizin As RadioButton
Friend WithEvents rdhadir As RadioButton
Friend WithEvents GroupBox1 As GroupBox
Friend WithEvents txtalpa As TextBox
Friend WithEvents Label8 As Label
Friend WithEvents txtizin As TextBox
Friend WithEvents Label9 As Label
Friend WithEvents Label10 As Label
Friend WithEvents txtsakit As TextBox
Friend WithEvents Label11 As Label
Friend WithEvents txthadir As TextBox
Friend WithEvents txtcari As TextBox
Friend WithEvents Label12 As Label
Friend WithEvents Button3 As Button
Friend WithEvents Button2 As Button
Friend WithEvents GroupBox2 As GroupBox
Friend WithEvents Timer1 As Timer
Friend WithEvents Label5 As Label
Friend WithEvents txttglakhir As TextBox
Friend WithEvents DataGridView1 As DataGridView
Friend WithEvents FileToolStripMenuItem As ToolStripMenuItem
Friend WithEvents MasterDataToolStripMenuItem As ToolStripMenuItem
Friend WithEvents txtnama As TextBox
Friend WithEvents LaporanToolStripMenuItem As ToolStripMenuItem
Friend WithEvents Label1 As Label
Friend WithEvents MenuStrip1 As MenuStrip
Friend WithEvents AbsensiToolStripMenuItem As ToolStripMenuItem
Friend WithEvents HelpToolStripMenuItem As ToolStripMenuItem
Friend WithEvents txtnip As TextBox
Friend WithEvents Button4 As Button
Friend WithEvents btnhapus As Button
Friend WithEvents btnedit As Button
Friend WithEvents btntambah As Button
Friend WithEvents Label4 As Label
Friend WithEvents Label3 As Label
Friend WithEvents Label2 As Label
Friend WithEvents cbmulai As CheckBox
Friend WithEvents Label7 As Label
Friend WithEvents txttglawal As DateTimePicker
End Class
|
Imports lm.Comol.UI.Presentation
Imports lm.Comol.Core.DomainModel
Imports lm.Comol.Core.BaseModules.ProviderManagement
Imports lm.Comol.Core.BaseModules.ProviderManagement.Presentation
Public Class ListAuthenticationProvider
Inherits PageBase
Implements IViewProvidersManagement
#Region "Context"
Private _CurrentContext As lm.Comol.Core.DomainModel.iApplicationContext
Private ReadOnly Property CurrentContext() As lm.Comol.Core.DomainModel.iApplicationContext
Get
If IsNothing(_CurrentContext) Then
_CurrentContext = New lm.Comol.Core.DomainModel.ApplicationContext() With {.UserContext = SessionHelpers.CurrentUserContext, .DataContext = SessionHelpers.CurrentDataContext}
End If
Return _CurrentContext
End Get
End Property
Private _Presenter As ProvidersManagementPresenter
Private ReadOnly Property CurrentPresenter() As ProvidersManagementPresenter
Get
If IsNothing(_Presenter) Then
_Presenter = New ProvidersManagementPresenter(Me.CurrentContext, Me)
End If
Return _Presenter
End Get
End Property
#End Region
#Region "Implements"
Public ReadOnly Property PreLoadedPageSize As Integer Implements IViewProvidersManagement.PreLoadedPageSize
Get
If IsNumeric(Request.QueryString("PageSize")) Then
Return CInt(Request.QueryString("PageSize"))
Else
Return Me.DDLpage.Items(0).Value
End If
End Get
End Property
Public Property CurrentPageSize As Integer Implements IViewProvidersManagement.CurrentPageSize
Get
Return Me.DDLpage.SelectedValue
End Get
Set(value As Integer)
Me.DDLpage.SelectedValue = value
End Set
End Property
Public Property Pager As PagerBase Implements IViewProvidersManagement.Pager
Get
Return ViewStateOrDefault("Pager", New lm.Comol.Core.DomainModel.PagerBase With {.PageSize = CurrentPageSize})
End Get
Set(value As PagerBase)
Me.ViewState("Pager") = value
Me.PGgrid.Pager = value
Me.PGgrid.Visible = Not value.Count = 0 AndAlso (value.Count + 1 > value.PageSize)
Me.DVpageSize.Visible = (Not value.Count < Me.DefaultPageSize)
End Set
End Property
#End Region
#Region "Inherits"
Public Overrides ReadOnly Property VerifyAuthentication() As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property AlwaysBind() As Boolean
Get
Return False
End Get
End Property
#End Region
#Region "Property"
Public ReadOnly Property OnLoadingTranslation As String
Get
Return Resource.getValue("LTprogress.text")
End Get
End Property
Public Function TranslateModalView(viewName As String) As String
Return Resource.getValue(viewName)
End Function
Public ReadOnly Property BackGroundItem(ByVal deleted As lm.Comol.Core.DomainModel.BaseStatusDeleted, itemType As ListItemType) As String
Get
If deleted = lm.Comol.Core.DomainModel.BaseStatusDeleted.None Then
Return IIf(itemType = ListItemType.AlternatingItem, "ROW_Alternate_Small", "ROW_Normal_Small")
Else
Return "ROW_Disabilitate_Small"
End If
End Get
End Property
Public ReadOnly Property DefaultPageSize() As Integer
Get
Return 25
End Get
End Property
#End Region
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.PGgrid.Pager = Pager
Me.Page.Form.DefaultFocus = Me.DDLpage.UniqueID
Me.Master.Page.Form.DefaultFocus = Me.DDLpage.UniqueID
End Sub
#Region "Inherits"
Public Overrides Sub BindDati()
Me.Master.ShowNoPermission = False
If Page.IsPostBack = False Then
CurrentPresenter.InitView()
End If
End Sub
Public Overrides Sub BindNoPermessi()
Me.Master.ShowNoPermission = True
End Sub
Public Overrides Function HasPermessi() As Boolean
Return True
End Function
Public Overrides Sub RegistraAccessoPagina()
End Sub
Public Overrides Sub SetCultureSettings()
MyBase.SetCulture("pg_ProviderManagement", "Modules", "ProviderManagement")
End Sub
Public Overrides Sub SetInternazionalizzazione()
With MyBase.Resource
Me.Master.ServiceTitle = .getValue("serviceManagementTitle")
Me.Master.ServiceNopermission = .getValue("serviceManagementNopermission")
.setHyperLink(Me.HYPaddProvider, True, True)
Me.HYPaddProvider.NavigateUrl = Me.BaseUrl & RootObject.AddProvider
.setLabel(LBpagesize)
.setLabel(LBproviderDisplayInfoDescription)
.setButton(BTNcloseProviderDisplayInfo, True)
End With
End Sub
Public Overrides Sub ShowMessageToPage(ByVal errorMessage As String)
End Sub
#End Region
#Region "Grid Management"
Private Sub RPTproviders_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles RPTproviders.ItemDataBound
If e.Item.ItemType = ListItemType.Header Then
Dim oLabel As Label = e.Item.FindControl("LBactions_t")
Me.Resource.setLabel(oLabel)
oLabel = e.Item.FindControl("LBproviderIsEnabled_t")
Me.Resource.setLabel(oLabel)
oLabel = e.Item.FindControl("LBproviderName_t")
Me.Resource.setLabel(oLabel)
oLabel = e.Item.FindControl("LBproviderType_t")
Me.Resource.setLabel(oLabel)
oLabel = e.Item.FindControl("LBproviderUsedBy_t")
Me.Resource.setLabel(oLabel)
ElseIf e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
Dim provider As dtoProvider = DirectCast(e.Item.DataItem, dtoProviderPermission).Provider
Dim permission As dtoPermission = DirectCast(e.Item.DataItem, dtoProviderPermission).Permission
Dim link As LinkButton = e.Item.FindControl("LNBproviderInfo")
link.Visible = permission.Info
If permission.Info Then
Resource.setLinkButton(link, True, True)
End If
Dim hyperlink As HyperLink = e.Item.FindControl("HYPedit")
hyperlink.Visible = permission.Edit
If permission.Edit Then
Dim div As HtmlControl = e.Item.FindControl("DVsettings")
Resource.setHyperLink(hyperlink, True, True)
hyperlink.NavigateUrl = Me.BaseUrl & RootObject.EditProvider(provider.IdProvider)
hyperlink = e.Item.FindControl("HYPadvancedSettings")
div.Visible = False
If (provider.Type = lm.Comol.Core.Authentication.AuthenticationProviderType.Internal OrElse provider.Type = lm.Comol.Core.Authentication.AuthenticationProviderType.None) Then
hyperlink.Visible = False
Else
div.Visible = True
hyperlink.Visible = True
Resource.setHyperLink(hyperlink, True, True)
hyperlink.NavigateUrl = Me.BaseUrl & RootObject.EditProviderSettings(provider.IdProvider, provider.Type)
End If
End If
If permission.Delete AndAlso provider.Type <> lm.Comol.Core.Authentication.AuthenticationProviderType.Internal Then
link = e.Item.FindControl("LNBdelete")
link.Visible = True
Resource.setLinkButton(link, True, True, , True)
End If
If permission.VirtualUndelete Then
link = e.Item.FindControl("LNBvirtualUnDelete")
link.Visible = True
Resource.setLinkButton(link, True, True)
ElseIf permission.VirtualDelete Then
link = e.Item.FindControl("LNBvirtualDelete")
link.Visible = True
Resource.setLinkButton(link, True, True)
End If
Dim label As Label = e.Item.FindControl("LBproviderName")
If Not IsNothing(provider.Translation) AndAlso String.IsNullOrEmpty(provider.Translation.Name) = False Then
label.Text = provider.Translation.Name
Else
label.Text = provider.Name
End If
label = e.Item.FindControl("LBproviderType")
label.Text = Resource.getValue("AuthenticationProviderType." & provider.Type.ToString)
label = e.Item.FindControl("LBproviderUsedBy")
label.Text = provider.UsedBy
label = e.Item.FindControl("LBproviderIsEnabled")
label.Text = Resource.getValue("isEnabled." & provider.isEnabled.ToString)
End If
End Sub
Private Sub PGgrid_OnPageSelected() Handles PGgrid.OnPageSelected
Me.CurrentPresenter.LoadProviders(Me.PGgrid.Pager.PageIndex, Me.CurrentPageSize)
End Sub
Private Sub RPTproviders_ItemCommand(source As Object, e As System.Web.UI.WebControls.RepeaterCommandEventArgs) Handles RPTproviders.ItemCommand
Dim idProvider As Long = 0
If IsNumeric(e.CommandArgument) Then
idProvider = CLng(e.CommandArgument)
End If
If idProvider > 0 Then
Select Case e.CommandName.ToLower
Case "infoprovider"
Me.LoadProviderInfo(idProvider)
Case "virtualdelete"
Me.CurrentPresenter.VirtualDelete(idProvider)
Case "undelete"
Me.CurrentPresenter.VirtualUndelete(idProvider)
Case "delete"
Me.CurrentPresenter.PhisicalDelete(idProvider)
End Select
Else
Me.CurrentPresenter.LoadProviders(Me.PGgrid.Pager.PageIndex, Me.CurrentPageSize)
End If
End Sub
#End Region
#Region "Implements"
Public Sub LoadProviderInfo(idProvider As Long) Implements IViewProvidersManagement.LoadProviderInfo
Me.CTRLinfoProvider.InitializeControl(idProvider)
Me.DVproviderInfo.Visible = True
End Sub
Public Sub LoadProviders(items As List(Of dtoProviderPermission)) Implements IViewProvidersManagement.LoadProviders
Me.RPTproviders.Visible = (items.Count > 0)
If items.Count > 0 Then
Me.RPTproviders.DataSource = items
Me.RPTproviders.DataBind()
End If
End Sub
Public Sub DisplaySessionTimeout() Implements IViewProvidersManagement.DisplaySessionTimeout
Dim webPost As New lm.Comol.Core.DomainModel.Helpers.LogoutWebPost(PageUtility.GetDefaultLogoutPage)
Dim dto As New lm.Comol.Core.DomainModel.Helpers.dtoExpiredAccessUrl()
dto.Display = lm.Comol.Core.DomainModel.Helpers.dtoExpiredAccessUrl.DisplayMode.SameWindow
dto.DestinationUrl = RootObject.Management
webPost.Redirect(dto)
End Sub
Public Sub NoPermission() Implements IViewProvidersManagement.NoPermission
Me.BindNoPermessi()
End Sub
#End Region
Private Sub BTNcloseProviderDisplayInfo_Click(sender As Object, e As System.EventArgs) Handles BTNcloseProviderDisplayInfo.Click
Me.DVproviderInfo.Visible = False
End Sub
End Class |
Imports System, System.IO, System.Collections.Generic
Imports System.Drawing, System.Drawing.Drawing2D
Imports System.ComponentModel, System.Windows.Forms
Imports System.Runtime.InteropServices
Imports System.Drawing.Imaging
Imports System.Windows.Forms.TabControl
Imports System.ComponentModel.Design
'---------/CREDITS/-----------
'
'Themebase creator: Aeonhack
'Site: elitevs.net
'Created: 08/02/2011
'Changed: 12/06/2011
'Version: 1.5.4
'
'Theme creator: Mavamaarten
'Created: 9/12/2011
'Changed: 3/03/2012
'Version: 2.0
'
'Thanks to Tedd for helping
'with combobox & tabcontrol!
'--------/CREDITS/------------
#Region "THEMEBASE"
MustInherit Class ThemeContainer154
Inherits ContainerControl
#Region " Initialization "
Protected G As Graphics, B As Bitmap
Sub New()
SetStyle(DirectCast(139270, ControlStyles), True)
_ImageSize = Size.Empty
Font = New Font("Verdana", 8S)
MeasureBitmap = New Bitmap(1, 1)
MeasureGraphics = Graphics.FromImage(MeasureBitmap)
DrawRadialPath = New GraphicsPath
InvalidateCustimization()
End Sub
Protected NotOverridable Overrides Sub OnHandleCreated(ByVal e As EventArgs)
If DoneCreation Then InitializeMessages()
InvalidateCustimization()
ColorHook()
If Not _LockWidth = 0 Then Width = _LockWidth
If Not _LockHeight = 0 Then Height = _LockHeight
If Not _ControlMode Then MyBase.Dock = DockStyle.Fill
Transparent = _Transparent
If _Transparent AndAlso _BackColor Then BackColor = Color.Transparent
MyBase.OnHandleCreated(e)
End Sub
Private DoneCreation As Boolean
Protected NotOverridable Overrides Sub OnParentChanged(ByVal e As EventArgs)
MyBase.OnParentChanged(e)
If Parent Is Nothing Then Return
_IsParentForm = TypeOf Parent Is Form
If Not _ControlMode Then
InitializeMessages()
If _IsParentForm Then
ParentForm.FormBorderStyle = _BorderStyle
ParentForm.TransparencyKey = _TransparencyKey
If Not DesignMode Then
AddHandler ParentForm.Shown, AddressOf FormShown
End If
End If
Parent.BackColor = BackColor
End If
OnCreation()
DoneCreation = True
InvalidateTimer()
End Sub
#End Region
Private Sub DoAnimation(ByVal i As Boolean)
OnAnimation()
If i Then Invalidate()
End Sub
Protected NotOverridable Overrides Sub OnPaint(ByVal e As PaintEventArgs)
If Width = 0 OrElse Height = 0 Then Return
If _Transparent AndAlso _ControlMode Then
PaintHook()
e.Graphics.DrawImage(B, 0, 0)
Else
G = e.Graphics
PaintHook()
End If
End Sub
Protected Overrides Sub OnHandleDestroyed(ByVal e As EventArgs)
RemoveAnimationCallback(AddressOf DoAnimation)
MyBase.OnHandleDestroyed(e)
End Sub
Private HasShown As Boolean
Private Sub FormShown(ByVal sender As Object, ByVal e As EventArgs)
If _ControlMode OrElse HasShown Then Return
If _StartPosition = FormStartPosition.CenterParent OrElse _StartPosition = FormStartPosition.CenterScreen Then
Dim SB As Rectangle = Screen.PrimaryScreen.Bounds
Dim CB As Rectangle = ParentForm.Bounds
ParentForm.Location = New Point(SB.Width \ 2 - CB.Width \ 2, SB.Height \ 2 - CB.Width \ 2)
End If
HasShown = True
End Sub
#Region " Size Handling "
Private Frame As Rectangle
Protected NotOverridable Overrides Sub OnSizeChanged(ByVal e As EventArgs)
If _Movable AndAlso Not _ControlMode Then
Frame = New Rectangle(7, 7, Width - 14, _Header - 7)
End If
InvalidateBitmap()
Invalidate()
MyBase.OnSizeChanged(e)
End Sub
Protected Overrides Sub SetBoundsCore(ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal specified As BoundsSpecified)
If Not _LockWidth = 0 Then width = _LockWidth
If Not _LockHeight = 0 Then height = _LockHeight
MyBase.SetBoundsCore(x, y, width, height, specified)
End Sub
#End Region
#Region " State Handling "
Protected State As MouseState
Private Sub SetState(ByVal current As MouseState)
State = current
Invalidate()
End Sub
Protected Overrides Sub OnMouseMove(ByVal e As MouseEventArgs)
If Not (_IsParentForm AndAlso ParentForm.WindowState = FormWindowState.Maximized) Then
If _Sizable AndAlso Not _ControlMode Then InvalidateMouse()
End If
MyBase.OnMouseMove(e)
End Sub
Protected Overrides Sub OnEnabledChanged(ByVal e As EventArgs)
If Enabled Then SetState(MouseState.None) Else SetState(MouseState.Block)
MyBase.OnEnabledChanged(e)
End Sub
Protected Overrides Sub OnMouseEnter(ByVal e As EventArgs)
SetState(MouseState.Over)
MyBase.OnMouseEnter(e)
End Sub
Protected Overrides Sub OnMouseUp(ByVal e As MouseEventArgs)
SetState(MouseState.Over)
MyBase.OnMouseUp(e)
End Sub
Protected Overrides Sub OnMouseLeave(ByVal e As EventArgs)
SetState(MouseState.None)
If GetChildAtPoint(PointToClient(MousePosition)) IsNot Nothing Then
If _Sizable AndAlso Not _ControlMode Then
Cursor = Cursors.Default
Previous = 0
End If
End If
MyBase.OnMouseLeave(e)
End Sub
Protected Overrides Sub OnMouseDown(ByVal e As MouseEventArgs)
If e.Button = Windows.Forms.MouseButtons.Left Then SetState(MouseState.Down)
If Not (_IsParentForm AndAlso ParentForm.WindowState = FormWindowState.Maximized OrElse _ControlMode) Then
If _Movable AndAlso Frame.Contains(e.Location) Then
Capture = False
WM_LMBUTTONDOWN = True
DefWndProc(Messages(0))
ElseIf _Sizable AndAlso Not Previous = 0 Then
Capture = False
WM_LMBUTTONDOWN = True
DefWndProc(Messages(Previous))
End If
End If
MyBase.OnMouseDown(e)
End Sub
Private WM_LMBUTTONDOWN As Boolean
Protected Overrides Sub WndProc(ByRef m As Message)
MyBase.WndProc(m)
If WM_LMBUTTONDOWN AndAlso m.Msg = 513 Then
WM_LMBUTTONDOWN = False
SetState(MouseState.Over)
If Not _SmartBounds Then Return
If IsParentMdi Then
CorrectBounds(New Rectangle(Point.Empty, Parent.Parent.Size))
Else
CorrectBounds(Screen.FromControl(Parent).WorkingArea)
End If
End If
End Sub
Private GetIndexPoint As Point
Private B1, B2, B3, B4 As Boolean
Private Function GetIndex() As Integer
GetIndexPoint = PointToClient(MousePosition)
B1 = GetIndexPoint.X < 7
B2 = GetIndexPoint.X > Width - 7
B3 = GetIndexPoint.Y < 7
B4 = GetIndexPoint.Y > Height - 7
If B1 AndAlso B3 Then Return 4
If B1 AndAlso B4 Then Return 7
If B2 AndAlso B3 Then Return 5
If B2 AndAlso B4 Then Return 8
If B1 Then Return 1
If B2 Then Return 2
If B3 Then Return 3
If B4 Then Return 6
Return 0
End Function
Private Current, Previous As Integer
Private Sub InvalidateMouse()
Current = GetIndex()
If Current = Previous Then Return
Previous = Current
Select Case Previous
Case 0
Cursor = Cursors.Default
Case 1, 2
Cursor = Cursors.SizeWE
Case 3, 6
Cursor = Cursors.SizeNS
Case 4, 8
Cursor = Cursors.SizeNWSE
Case 5, 7
Cursor = Cursors.SizeNESW
End Select
End Sub
Private Messages(8) As Message
Private Sub InitializeMessages()
Messages(0) = Message.Create(Parent.Handle, 161, New IntPtr(2), IntPtr.Zero)
For I As Integer = 1 To 8
Messages(I) = Message.Create(Parent.Handle, 161, New IntPtr(I + 9), IntPtr.Zero)
Next
End Sub
Private Sub CorrectBounds(ByVal bounds As Rectangle)
If Parent.Width > bounds.Width Then Parent.Width = bounds.Width
If Parent.Height > bounds.Height Then Parent.Height = bounds.Height
Dim X As Integer = Parent.Location.X
Dim Y As Integer = Parent.Location.Y
If X < bounds.X Then X = bounds.X
If Y < bounds.Y Then Y = bounds.Y
Dim Width As Integer = bounds.X + bounds.Width
Dim Height As Integer = bounds.Y + bounds.Height
If X + Parent.Width > Width Then X = Width - Parent.Width
If Y + Parent.Height > Height Then Y = Height - Parent.Height
Parent.Location = New Point(X, Y)
End Sub
#End Region
#Region " Base Properties "
Overrides Property Dock As DockStyle
Get
Return MyBase.Dock
End Get
Set(ByVal value As DockStyle)
If Not _ControlMode Then Return
MyBase.Dock = value
End Set
End Property
Private _BackColor As Boolean
<Category("Misc")>
Overrides Property BackColor() As Color
Get
Return MyBase.BackColor
End Get
Set(ByVal value As Color)
If value = MyBase.BackColor Then Return
If Not IsHandleCreated AndAlso _ControlMode AndAlso value = Color.Transparent Then
_BackColor = True
Return
End If
MyBase.BackColor = value
If Parent IsNot Nothing Then
If Not _ControlMode Then Parent.BackColor = value
ColorHook()
End If
End Set
End Property
Overrides Property MinimumSize As Size
Get
Return MyBase.MinimumSize
End Get
Set(ByVal value As Size)
MyBase.MinimumSize = value
If Parent IsNot Nothing Then Parent.MinimumSize = value
End Set
End Property
Overrides Property MaximumSize As Size
Get
Return MyBase.MaximumSize
End Get
Set(ByVal value As Size)
MyBase.MaximumSize = value
If Parent IsNot Nothing Then Parent.MaximumSize = value
End Set
End Property
Overrides Property Text() As String
Get
Return MyBase.Text
End Get
Set(ByVal value As String)
MyBase.Text = value
Invalidate()
End Set
End Property
Overrides Property Font() As Font
Get
Return MyBase.Font
End Get
Set(ByVal value As Font)
MyBase.Font = value
Invalidate()
End Set
End Property
<Browsable(False), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
Overrides Property ForeColor() As Color
Get
Return Color.Empty
End Get
Set(ByVal value As Color)
End Set
End Property
<Browsable(False), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
Overrides Property BackgroundImage() As Image
Get
Return Nothing
End Get
Set(ByVal value As Image)
End Set
End Property
<Browsable(False), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
Overrides Property BackgroundImageLayout() As ImageLayout
Get
Return ImageLayout.None
End Get
Set(ByVal value As ImageLayout)
End Set
End Property
#End Region
#Region " Public Properties "
Private _SmartBounds As Boolean = True
Property SmartBounds() As Boolean
Get
Return _SmartBounds
End Get
Set(ByVal value As Boolean)
_SmartBounds = value
End Set
End Property
Private _Movable As Boolean = True
Property Movable() As Boolean
Get
Return _Movable
End Get
Set(ByVal value As Boolean)
_Movable = value
End Set
End Property
Private _Sizable As Boolean = True
Property Sizable() As Boolean
Get
Return _Sizable
End Get
Set(ByVal value As Boolean)
_Sizable = value
End Set
End Property
Private _TransparencyKey As Color
Property TransparencyKey() As Color
Get
If _IsParentForm AndAlso Not _ControlMode Then Return ParentForm.TransparencyKey Else Return _TransparencyKey
End Get
Set(ByVal value As Color)
If value = _TransparencyKey Then Return
_TransparencyKey = value
If _IsParentForm AndAlso Not _ControlMode Then
ParentForm.TransparencyKey = value
ColorHook()
End If
End Set
End Property
Private _BorderStyle As FormBorderStyle
Property BorderStyle() As FormBorderStyle
Get
If _IsParentForm AndAlso Not _ControlMode Then Return ParentForm.FormBorderStyle Else Return _BorderStyle
End Get
Set(ByVal value As FormBorderStyle)
_BorderStyle = value
If _IsParentForm AndAlso Not _ControlMode Then
ParentForm.FormBorderStyle = value
If Not value = FormBorderStyle.None Then
Movable = False
Sizable = False
End If
End If
End Set
End Property
Private _StartPosition As FormStartPosition
Property StartPosition As FormStartPosition
Get
If _IsParentForm AndAlso Not _ControlMode Then Return ParentForm.StartPosition Else Return _StartPosition
End Get
Set(ByVal value As FormStartPosition)
_StartPosition = value
If _IsParentForm AndAlso Not _ControlMode Then
ParentForm.StartPosition = value
End If
End Set
End Property
Private _NoRounding As Boolean
Property NoRounding() As Boolean
Get
Return _NoRounding
End Get
Set(ByVal v As Boolean)
_NoRounding = v
Invalidate()
End Set
End Property
Private _Image As Image
Property Image() As Image
Get
Return _Image
End Get
Set(ByVal value As Image)
If value Is Nothing Then _ImageSize = Size.Empty Else _ImageSize = value.Size
_Image = value
Invalidate()
End Set
End Property
Private Items As New Dictionary(Of String, Color)
Property Colors() As Bloom()
Get
Dim T As New List(Of Bloom)
Dim E As Dictionary(Of String, Color).Enumerator = Items.GetEnumerator
While E.MoveNext
T.Add(New Bloom(E.Current.Key, E.Current.Value))
End While
Return T.ToArray
End Get
Set(ByVal value As Bloom())
For Each B As Bloom In value
If Items.ContainsKey(B.Name) Then Items(B.Name) = B.Value
Next
InvalidateCustimization()
ColorHook()
Invalidate()
End Set
End Property
Private _Customization As String
Property Customization() As String
Get
Return _Customization
End Get
Set(ByVal value As String)
If value = _Customization Then Return
Dim Data As Byte()
Dim Items As Bloom() = Colors
Try
Data = Convert.FromBase64String(value)
For I As Integer = 0 To Items.Length - 1
Items(I).Value = Color.FromArgb(BitConverter.ToInt32(Data, I * 4))
Next
Catch
Return
End Try
_Customization = value
Colors = Items
ColorHook()
Invalidate()
End Set
End Property
Private _Transparent As Boolean
Property Transparent() As Boolean
Get
Return _Transparent
End Get
Set(ByVal value As Boolean)
_Transparent = value
If Not (IsHandleCreated OrElse _ControlMode) Then Return
If Not value AndAlso Not BackColor.A = 255 Then
Throw New Exception("Unable to change value to false while a transparent BackColor is in use.")
End If
SetStyle(ControlStyles.Opaque, Not value)
SetStyle(ControlStyles.SupportsTransparentBackColor, value)
InvalidateBitmap()
Invalidate()
End Set
End Property
#End Region
#Region " Private Properties "
Private _ImageSize As Size
Protected ReadOnly Property ImageSize() As Size
Get
Return _ImageSize
End Get
End Property
Private _IsParentForm As Boolean
Protected ReadOnly Property IsParentForm As Boolean
Get
Return _IsParentForm
End Get
End Property
Protected ReadOnly Property IsParentMdi As Boolean
Get
If Parent Is Nothing Then Return False
Return Parent.Parent IsNot Nothing
End Get
End Property
Private _LockWidth As Integer
Protected Property LockWidth() As Integer
Get
Return _LockWidth
End Get
Set(ByVal value As Integer)
_LockWidth = value
If Not LockWidth = 0 AndAlso IsHandleCreated Then Width = LockWidth
End Set
End Property
Private _LockHeight As Integer
Protected Property LockHeight() As Integer
Get
Return _LockHeight
End Get
Set(ByVal value As Integer)
_LockHeight = value
If Not LockHeight = 0 AndAlso IsHandleCreated Then Height = LockHeight
End Set
End Property
Private _Header As Integer = 24
Protected Property Header() As Integer
Get
Return _Header
End Get
Set(ByVal v As Integer)
_Header = v
If Not _ControlMode Then
Frame = New Rectangle(7, 7, Width - 14, v - 7)
Invalidate()
End If
End Set
End Property
Private _ControlMode As Boolean
Protected Property ControlMode() As Boolean
Get
Return _ControlMode
End Get
Set(ByVal v As Boolean)
_ControlMode = v
Transparent = _Transparent
If _Transparent AndAlso _BackColor Then BackColor = Color.Transparent
InvalidateBitmap()
Invalidate()
End Set
End Property
Private _IsAnimated As Boolean
Protected Property IsAnimated() As Boolean
Get
Return _IsAnimated
End Get
Set(ByVal value As Boolean)
_IsAnimated = value
InvalidateTimer()
End Set
End Property
#End Region
#Region " Property Helpers "
Protected Function GetPen(ByVal name As String) As Pen
Return New Pen(Items(name))
End Function
Protected Function GetPen(ByVal name As String, ByVal width As Single) As Pen
Return New Pen(Items(name), width)
End Function
Protected Function GetBrush(ByVal name As String) As SolidBrush
Return New SolidBrush(Items(name))
End Function
Protected Function GetColor(ByVal name As String) As Color
Return Items(name)
End Function
Protected Sub SetColor(ByVal name As String, ByVal value As Color)
If Items.ContainsKey(name) Then Items(name) = value Else Items.Add(name, value)
End Sub
Protected Sub SetColor(ByVal name As String, ByVal r As Byte, ByVal g As Byte, ByVal b As Byte)
SetColor(name, Color.FromArgb(r, g, b))
End Sub
Protected Sub SetColor(ByVal name As String, ByVal a As Byte, ByVal r As Byte, ByVal g As Byte, ByVal b As Byte)
SetColor(name, Color.FromArgb(a, r, g, b))
End Sub
Protected Sub SetColor(ByVal name As String, ByVal a As Byte, ByVal value As Color)
SetColor(name, Color.FromArgb(a, value))
End Sub
Private Sub InvalidateBitmap()
If _Transparent AndAlso _ControlMode Then
If Width = 0 OrElse Height = 0 Then Return
B = New Bitmap(Width, Height, PixelFormat.Format32bppPArgb)
G = Graphics.FromImage(B)
Else
G = Nothing
B = Nothing
End If
End Sub
Private Sub InvalidateCustimization()
Dim M As New MemoryStream(Items.Count * 4)
For Each B As Bloom In Colors
M.Write(BitConverter.GetBytes(B.Value.ToArgb), 0, 4)
Next
M.Close()
_Customization = Convert.ToBase64String(M.ToArray)
End Sub
Private Sub InvalidateTimer()
If DesignMode OrElse Not DoneCreation Then Return
If _IsAnimated Then
AddAnimationCallback(AddressOf DoAnimation)
Else
RemoveAnimationCallback(AddressOf DoAnimation)
End If
End Sub
#End Region
#Region " User Hooks "
Protected MustOverride Sub ColorHook()
Protected MustOverride Sub PaintHook()
Protected Overridable Sub OnCreation()
End Sub
Protected Overridable Sub OnAnimation()
End Sub
#End Region
#Region " Offset "
Private OffsetReturnRectangle As Rectangle
Protected Function Offset(ByVal r As Rectangle, ByVal amount As Integer) As Rectangle
OffsetReturnRectangle = New Rectangle(r.X + amount, r.Y + amount, r.Width - (amount * 2), r.Height - (amount * 2))
Return OffsetReturnRectangle
End Function
Private OffsetReturnSize As Size
Protected Function Offset(ByVal s As Size, ByVal amount As Integer) As Size
OffsetReturnSize = New Size(s.Width + amount, s.Height + amount)
Return OffsetReturnSize
End Function
Private OffsetReturnPoint As Point
Protected Function Offset(ByVal p As Point, ByVal amount As Integer) As Point
OffsetReturnPoint = New Point(p.X + amount, p.Y + amount)
Return OffsetReturnPoint
End Function
#End Region
#Region " Center "
Private CenterReturn As Point
Protected Function Center(ByVal p As Rectangle, ByVal c As Rectangle) As Point
CenterReturn = New Point((p.Width \ 2 - c.Width \ 2) + p.X + c.X, (p.Height \ 2 - c.Height \ 2) + p.Y + c.Y)
Return CenterReturn
End Function
Protected Function Center(ByVal p As Rectangle, ByVal c As Size) As Point
CenterReturn = New Point((p.Width \ 2 - c.Width \ 2) + p.X, (p.Height \ 2 - c.Height \ 2) + p.Y)
Return CenterReturn
End Function
Protected Function Center(ByVal child As Rectangle) As Point
Return Center(Width, Height, child.Width, child.Height)
End Function
Protected Function Center(ByVal child As Size) As Point
Return Center(Width, Height, child.Width, child.Height)
End Function
Protected Function Center(ByVal childWidth As Integer, ByVal childHeight As Integer) As Point
Return Center(Width, Height, childWidth, childHeight)
End Function
Protected Function Center(ByVal p As Size, ByVal c As Size) As Point
Return Center(p.Width, p.Height, c.Width, c.Height)
End Function
Protected Function Center(ByVal pWidth As Integer, ByVal pHeight As Integer, ByVal cWidth As Integer, ByVal cHeight As Integer) As Point
CenterReturn = New Point(pWidth \ 2 - cWidth \ 2, pHeight \ 2 - cHeight \ 2)
Return CenterReturn
End Function
#End Region
#Region " Measure "
Private MeasureBitmap As Bitmap
Private MeasureGraphics As Graphics
Protected Function Measure() As Size
SyncLock MeasureGraphics
Return MeasureGraphics.MeasureString(Text, Font, Width).ToSize
End SyncLock
End Function
Protected Function Measure(ByVal text As String) As Size
SyncLock MeasureGraphics
Return MeasureGraphics.MeasureString(text, Font, Width).ToSize
End SyncLock
End Function
#End Region
#Region " DrawPixel "
Private DrawPixelBrush As SolidBrush
Protected Sub DrawPixel(ByVal c1 As Color, ByVal x As Integer, ByVal y As Integer)
If _Transparent Then
B.SetPixel(x, y, c1)
Else
DrawPixelBrush = New SolidBrush(c1)
G.FillRectangle(DrawPixelBrush, x, y, 1, 1)
End If
End Sub
#End Region
#Region " DrawCorners "
Private DrawCornersBrush As SolidBrush
Protected Sub DrawCorners(ByVal c1 As Color, ByVal offset As Integer)
DrawCorners(c1, 0, 0, Width, Height, offset)
End Sub
Protected Sub DrawCorners(ByVal c1 As Color, ByVal r1 As Rectangle, ByVal offset As Integer)
DrawCorners(c1, r1.X, r1.Y, r1.Width, r1.Height, offset)
End Sub
Protected Sub DrawCorners(ByVal c1 As Color, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal offset As Integer)
DrawCorners(c1, x + offset, y + offset, width - (offset * 2), height - (offset * 2))
End Sub
Protected Sub DrawCorners(ByVal c1 As Color)
DrawCorners(c1, 0, 0, Width, Height)
End Sub
Protected Sub DrawCorners(ByVal c1 As Color, ByVal r1 As Rectangle)
DrawCorners(c1, r1.X, r1.Y, r1.Width, r1.Height)
End Sub
Protected Sub DrawCorners(ByVal c1 As Color, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer)
If _NoRounding Then Return
If _Transparent Then
B.SetPixel(x, y, c1)
B.SetPixel(x + (width - 1), y, c1)
B.SetPixel(x, y + (height - 1), c1)
B.SetPixel(x + (width - 1), y + (height - 1), c1)
Else
DrawCornersBrush = New SolidBrush(c1)
G.FillRectangle(DrawCornersBrush, x, y, 1, 1)
G.FillRectangle(DrawCornersBrush, x + (width - 1), y, 1, 1)
G.FillRectangle(DrawCornersBrush, x, y + (height - 1), 1, 1)
G.FillRectangle(DrawCornersBrush, x + (width - 1), y + (height - 1), 1, 1)
End If
End Sub
#End Region
#Region " DrawBorders "
Protected Sub DrawBorders(ByVal p1 As Pen, ByVal offset As Integer)
DrawBorders(p1, 0, 0, Width, Height, offset)
End Sub
Protected Sub DrawBorders(ByVal p1 As Pen, ByVal r As Rectangle, ByVal offset As Integer)
DrawBorders(p1, r.X, r.Y, r.Width, r.Height, offset)
End Sub
Protected Sub DrawBorders(ByVal p1 As Pen, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal offset As Integer)
DrawBorders(p1, x + offset, y + offset, width - (offset * 2), height - (offset * 2))
End Sub
Protected Sub DrawBorders(ByVal p1 As Pen)
DrawBorders(p1, 0, 0, Width, Height)
End Sub
Protected Sub DrawBorders(ByVal p1 As Pen, ByVal r As Rectangle)
DrawBorders(p1, r.X, r.Y, r.Width, r.Height)
End Sub
Protected Sub DrawBorders(ByVal p1 As Pen, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer)
G.DrawRectangle(p1, x, y, width - 1, height - 1)
End Sub
#End Region
#Region " DrawText "
Private DrawTextPoint As Point
Private DrawTextSize As Size
Protected Sub DrawText(ByVal b1 As Brush, ByVal a As HorizontalAlignment, ByVal x As Integer, ByVal y As Integer)
DrawText(b1, Text, a, x, y)
End Sub
Protected Sub DrawText(ByVal b1 As Brush, ByVal text As String, ByVal a As HorizontalAlignment, ByVal x As Integer, ByVal y As Integer)
If text.Length = 0 Then Return
DrawTextSize = Measure(text)
DrawTextPoint = New Point(Width \ 2 - DrawTextSize.Width \ 2, Header \ 2 - DrawTextSize.Height \ 2)
Select Case a
Case HorizontalAlignment.Left
G.DrawString(text, Font, b1, x, DrawTextPoint.Y + y)
Case HorizontalAlignment.Center
G.DrawString(text, Font, b1, DrawTextPoint.X + x, DrawTextPoint.Y + y)
Case HorizontalAlignment.Right
G.DrawString(text, Font, b1, Width - DrawTextSize.Width - x, DrawTextPoint.Y + y)
End Select
End Sub
Protected Sub DrawText(ByVal b1 As Brush, ByVal p1 As Point)
If Text.Length = 0 Then Return
G.DrawString(Text, Font, b1, p1)
End Sub
Protected Sub DrawText(ByVal b1 As Brush, ByVal x As Integer, ByVal y As Integer)
If Text.Length = 0 Then Return
G.DrawString(Text, Font, b1, x, y)
End Sub
#End Region
#Region " DrawImage "
Private DrawImagePoint As Point
Protected Sub DrawImage(ByVal a As HorizontalAlignment, ByVal x As Integer, ByVal y As Integer)
DrawImage(_Image, a, x, y)
End Sub
Protected Sub DrawImage(ByVal image As Image, ByVal a As HorizontalAlignment, ByVal x As Integer, ByVal y As Integer)
If image Is Nothing Then Return
DrawImagePoint = New Point(Width \ 2 - image.Width \ 2, Header \ 2 - image.Height \ 2)
Select Case a
Case HorizontalAlignment.Left
G.DrawImage(image, x, DrawImagePoint.Y + y, image.Width, image.Height)
Case HorizontalAlignment.Center
G.DrawImage(image, DrawImagePoint.X + x, DrawImagePoint.Y + y, image.Width, image.Height)
Case HorizontalAlignment.Right
G.DrawImage(image, Width - image.Width - x, DrawImagePoint.Y + y, image.Width, image.Height)
End Select
End Sub
Protected Sub DrawImage(ByVal p1 As Point)
DrawImage(_Image, p1.X, p1.Y)
End Sub
Protected Sub DrawImage(ByVal x As Integer, ByVal y As Integer)
DrawImage(_Image, x, y)
End Sub
Protected Sub DrawImage(ByVal image As Image, ByVal p1 As Point)
DrawImage(image, p1.X, p1.Y)
End Sub
Protected Sub DrawImage(ByVal image As Image, ByVal x As Integer, ByVal y As Integer)
If image Is Nothing Then Return
G.DrawImage(image, x, y, image.Width, image.Height)
End Sub
#End Region
#Region " DrawGradient "
Private DrawGradientBrush As LinearGradientBrush
Private DrawGradientRectangle As Rectangle
Protected Sub DrawGradient(ByVal blend As ColorBlend, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer)
DrawGradientRectangle = New Rectangle(x, y, width, height)
DrawGradient(blend, DrawGradientRectangle)
End Sub
Protected Sub DrawGradient(ByVal blend As ColorBlend, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal angle As Single)
DrawGradientRectangle = New Rectangle(x, y, width, height)
DrawGradient(blend, DrawGradientRectangle, angle)
End Sub
Protected Sub DrawGradient(ByVal blend As ColorBlend, ByVal r As Rectangle)
DrawGradientBrush = New LinearGradientBrush(r, Color.Empty, Color.Empty, 90.0F)
DrawGradientBrush.InterpolationColors = blend
G.FillRectangle(DrawGradientBrush, r)
End Sub
Protected Sub DrawGradient(ByVal blend As ColorBlend, ByVal r As Rectangle, ByVal angle As Single)
DrawGradientBrush = New LinearGradientBrush(r, Color.Empty, Color.Empty, angle)
DrawGradientBrush.InterpolationColors = blend
G.FillRectangle(DrawGradientBrush, r)
End Sub
Protected Sub DrawGradient(ByVal c1 As Color, ByVal c2 As Color, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer)
DrawGradientRectangle = New Rectangle(x, y, width, height)
DrawGradient(c1, c2, DrawGradientRectangle)
End Sub
Protected Sub DrawGradient(ByVal c1 As Color, ByVal c2 As Color, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal angle As Single)
DrawGradientRectangle = New Rectangle(x, y, width, height)
DrawGradient(c1, c2, DrawGradientRectangle, angle)
End Sub
Protected Sub DrawGradient(ByVal c1 As Color, ByVal c2 As Color, ByVal r As Rectangle)
DrawGradientBrush = New LinearGradientBrush(r, c1, c2, 90.0F)
G.FillRectangle(DrawGradientBrush, r)
End Sub
Protected Sub DrawGradient(ByVal c1 As Color, ByVal c2 As Color, ByVal r As Rectangle, ByVal angle As Single)
DrawGradientBrush = New LinearGradientBrush(r, c1, c2, angle)
G.FillRectangle(DrawGradientBrush, r)
End Sub
#End Region
#Region " DrawRadial "
Private DrawRadialPath As GraphicsPath
Private DrawRadialBrush1 As PathGradientBrush
Private DrawRadialBrush2 As LinearGradientBrush
Private DrawRadialRectangle As Rectangle
Sub DrawRadial(ByVal blend As ColorBlend, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer)
DrawRadialRectangle = New Rectangle(x, y, width, height)
DrawRadial(blend, DrawRadialRectangle, width \ 2, height \ 2)
End Sub
Sub DrawRadial(ByVal blend As ColorBlend, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal center As Point)
DrawRadialRectangle = New Rectangle(x, y, width, height)
DrawRadial(blend, DrawRadialRectangle, center.X, center.Y)
End Sub
Sub DrawRadial(ByVal blend As ColorBlend, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal cx As Integer, ByVal cy As Integer)
DrawRadialRectangle = New Rectangle(x, y, width, height)
DrawRadial(blend, DrawRadialRectangle, cx, cy)
End Sub
Sub DrawRadial(ByVal blend As ColorBlend, ByVal r As Rectangle)
DrawRadial(blend, r, r.Width \ 2, r.Height \ 2)
End Sub
Sub DrawRadial(ByVal blend As ColorBlend, ByVal r As Rectangle, ByVal center As Point)
DrawRadial(blend, r, center.X, center.Y)
End Sub
Sub DrawRadial(ByVal blend As ColorBlend, ByVal r As Rectangle, ByVal cx As Integer, ByVal cy As Integer)
DrawRadialPath.Reset()
DrawRadialPath.AddEllipse(r.X, r.Y, r.Width - 1, r.Height - 1)
DrawRadialBrush1 = New PathGradientBrush(DrawRadialPath)
DrawRadialBrush1.CenterPoint = New Point(r.X + cx, r.Y + cy)
DrawRadialBrush1.InterpolationColors = blend
If G.SmoothingMode = SmoothingMode.AntiAlias Then
G.FillEllipse(DrawRadialBrush1, r.X + 1, r.Y + 1, r.Width - 3, r.Height - 3)
Else
G.FillEllipse(DrawRadialBrush1, r)
End If
End Sub
Protected Sub DrawRadial(ByVal c1 As Color, ByVal c2 As Color, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer)
DrawRadialRectangle = New Rectangle(x, y, width, height)
DrawRadial(c1, c2, DrawGradientRectangle)
End Sub
Protected Sub DrawRadial(ByVal c1 As Color, ByVal c2 As Color, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal angle As Single)
DrawRadialRectangle = New Rectangle(x, y, width, height)
DrawRadial(c1, c2, DrawGradientRectangle, angle)
End Sub
Protected Sub DrawRadial(ByVal c1 As Color, ByVal c2 As Color, ByVal r As Rectangle)
DrawRadialBrush2 = New LinearGradientBrush(r, c1, c2, 90.0F)
G.FillRectangle(DrawGradientBrush, r)
End Sub
Protected Sub DrawRadial(ByVal c1 As Color, ByVal c2 As Color, ByVal r As Rectangle, ByVal angle As Single)
DrawRadialBrush2 = New LinearGradientBrush(r, c1, c2, angle)
G.FillEllipse(DrawGradientBrush, r)
End Sub
#End Region
#Region " CreateRound "
Private CreateRoundPath As GraphicsPath
Private CreateRoundRectangle As Rectangle
Function CreateRound(ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal slope As Integer) As GraphicsPath
CreateRoundRectangle = New Rectangle(x, y, width, height)
Return CreateRound(CreateRoundRectangle, slope)
End Function
Function CreateRound(ByVal r As Rectangle, ByVal slope As Integer) As GraphicsPath
CreateRoundPath = New GraphicsPath(FillMode.Winding)
CreateRoundPath.AddArc(r.X, r.Y, slope, slope, 180.0F, 90.0F)
CreateRoundPath.AddArc(r.Right - slope, r.Y, slope, slope, 270.0F, 90.0F)
CreateRoundPath.AddArc(r.Right - slope, r.Bottom - slope, slope, slope, 0.0F, 90.0F)
CreateRoundPath.AddArc(r.X, r.Bottom - slope, slope, slope, 90.0F, 90.0F)
CreateRoundPath.CloseFigure()
Return CreateRoundPath
End Function
#End Region
End Class
MustInherit Class ThemeControl154
Inherits Control
#Region " Initialization "
Protected G As Graphics, B As Bitmap
Sub New()
SetStyle(DirectCast(139270, ControlStyles), True)
_ImageSize = Size.Empty
Font = New Font("Verdana", 8S)
MeasureBitmap = New Bitmap(1, 1)
MeasureGraphics = Graphics.FromImage(MeasureBitmap)
DrawRadialPath = New GraphicsPath
InvalidateCustimization() 'Remove?
End Sub
Protected NotOverridable Overrides Sub OnHandleCreated(ByVal e As EventArgs)
InvalidateCustimization()
ColorHook()
If Not _LockWidth = 0 Then Width = _LockWidth
If Not _LockHeight = 0 Then Height = _LockHeight
Transparent = _Transparent
If _Transparent AndAlso _BackColor Then BackColor = Color.Transparent
MyBase.OnHandleCreated(e)
End Sub
Private DoneCreation As Boolean
Protected NotOverridable Overrides Sub OnParentChanged(ByVal e As EventArgs)
If Parent IsNot Nothing Then
OnCreation()
DoneCreation = True
InvalidateTimer()
End If
MyBase.OnParentChanged(e)
End Sub
#End Region
Private Sub DoAnimation(ByVal i As Boolean)
OnAnimation()
If i Then Invalidate()
End Sub
Protected NotOverridable Overrides Sub OnPaint(ByVal e As PaintEventArgs)
If Width = 0 OrElse Height = 0 Then Return
If _Transparent Then
PaintHook()
e.Graphics.DrawImage(B, 0, 0)
Else
G = e.Graphics
PaintHook()
End If
End Sub
Protected Overrides Sub OnHandleDestroyed(ByVal e As EventArgs)
RemoveAnimationCallback(AddressOf DoAnimation)
MyBase.OnHandleDestroyed(e)
End Sub
#Region " Size Handling "
Protected NotOverridable Overrides Sub OnSizeChanged(ByVal e As EventArgs)
If _Transparent Then
InvalidateBitmap()
End If
Invalidate()
MyBase.OnSizeChanged(e)
End Sub
Protected Overrides Sub SetBoundsCore(ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal specified As BoundsSpecified)
If Not _LockWidth = 0 Then width = _LockWidth
If Not _LockHeight = 0 Then height = _LockHeight
MyBase.SetBoundsCore(x, y, width, height, specified)
End Sub
#End Region
#Region " State Handling "
Private InPosition As Boolean
Protected Overrides Sub OnMouseEnter(ByVal e As EventArgs)
InPosition = True
SetState(MouseState.Over)
MyBase.OnMouseEnter(e)
End Sub
Protected Overrides Sub OnMouseUp(ByVal e As MouseEventArgs)
If InPosition Then SetState(MouseState.Over)
MyBase.OnMouseUp(e)
End Sub
Protected Overrides Sub OnMouseDown(ByVal e As MouseEventArgs)
If e.Button = Windows.Forms.MouseButtons.Left Then SetState(MouseState.Down)
MyBase.OnMouseDown(e)
End Sub
Protected Overrides Sub OnMouseLeave(ByVal e As EventArgs)
InPosition = False
SetState(MouseState.None)
MyBase.OnMouseLeave(e)
End Sub
Protected Overrides Sub OnEnabledChanged(ByVal e As EventArgs)
If Enabled Then SetState(MouseState.None) Else SetState(MouseState.Block)
MyBase.OnEnabledChanged(e)
End Sub
Protected State As MouseState
Private Sub SetState(ByVal current As MouseState)
State = current
Invalidate()
End Sub
#End Region
#Region " Base Properties "
<Browsable(False), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
Overrides Property ForeColor() As Color
Get
Return Color.Empty
End Get
Set(ByVal value As Color)
End Set
End Property
<Browsable(False), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
Overrides Property BackgroundImage() As Image
Get
Return Nothing
End Get
Set(ByVal value As Image)
End Set
End Property
<Browsable(False), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
Overrides Property BackgroundImageLayout() As ImageLayout
Get
Return ImageLayout.None
End Get
Set(ByVal value As ImageLayout)
End Set
End Property
Overrides Property Text() As String
Get
Return MyBase.Text
End Get
Set(ByVal value As String)
MyBase.Text = value
Invalidate()
End Set
End Property
Overrides Property Font() As Font
Get
Return MyBase.Font
End Get
Set(ByVal value As Font)
MyBase.Font = value
Invalidate()
End Set
End Property
Private _BackColor As Boolean
<Category("Misc")>
Overrides Property BackColor() As Color
Get
Return MyBase.BackColor
End Get
Set(ByVal value As Color)
If Not IsHandleCreated AndAlso value = Color.Transparent Then
_BackColor = True
Return
End If
MyBase.BackColor = value
If Parent IsNot Nothing Then ColorHook()
End Set
End Property
#End Region
#Region " Public Properties "
Private _NoRounding As Boolean
Property NoRounding() As Boolean
Get
Return _NoRounding
End Get
Set(ByVal v As Boolean)
_NoRounding = v
Invalidate()
End Set
End Property
Private _Image As Image
Property Image() As Image
Get
Return _Image
End Get
Set(ByVal value As Image)
If value Is Nothing Then
_ImageSize = Size.Empty
Else
_ImageSize = value.Size
End If
_Image = value
Invalidate()
End Set
End Property
Private _Transparent As Boolean
Property Transparent() As Boolean
Get
Return _Transparent
End Get
Set(ByVal value As Boolean)
_Transparent = value
If Not IsHandleCreated Then Return
If Not value AndAlso Not BackColor.A = 255 Then
Throw New Exception("Unable to change value to false while a transparent BackColor is in use.")
End If
SetStyle(ControlStyles.Opaque, Not value)
SetStyle(ControlStyles.SupportsTransparentBackColor, value)
If value Then InvalidateBitmap() Else B = Nothing
Invalidate()
End Set
End Property
Private Items As New Dictionary(Of String, Color)
Property Colors() As Bloom()
Get
Dim T As New List(Of Bloom)
Dim E As Dictionary(Of String, Color).Enumerator = Items.GetEnumerator
While E.MoveNext
T.Add(New Bloom(E.Current.Key, E.Current.Value))
End While
Return T.ToArray
End Get
Set(ByVal value As Bloom())
For Each B As Bloom In value
If Items.ContainsKey(B.Name) Then Items(B.Name) = B.Value
Next
InvalidateCustimization()
ColorHook()
Invalidate()
End Set
End Property
Private _Customization As String
Property Customization() As String
Get
Return _Customization
End Get
Set(ByVal value As String)
If value = _Customization Then Return
Dim Data As Byte()
Dim Items As Bloom() = Colors
Try
Data = Convert.FromBase64String(value)
For I As Integer = 0 To Items.Length - 1
Items(I).Value = Color.FromArgb(BitConverter.ToInt32(Data, I * 4))
Next
Catch
Return
End Try
_Customization = value
Colors = Items
ColorHook()
Invalidate()
End Set
End Property
#End Region
#Region " Private Properties "
Private _ImageSize As Size
Protected ReadOnly Property ImageSize() As Size
Get
Return _ImageSize
End Get
End Property
Private _LockWidth As Integer
Protected Property LockWidth() As Integer
Get
Return _LockWidth
End Get
Set(ByVal value As Integer)
_LockWidth = value
If Not LockWidth = 0 AndAlso IsHandleCreated Then Width = LockWidth
End Set
End Property
Private _LockHeight As Integer
Protected Property LockHeight() As Integer
Get
Return _LockHeight
End Get
Set(ByVal value As Integer)
_LockHeight = value
If Not LockHeight = 0 AndAlso IsHandleCreated Then Height = LockHeight
End Set
End Property
Private _IsAnimated As Boolean
Protected Property IsAnimated() As Boolean
Get
Return _IsAnimated
End Get
Set(ByVal value As Boolean)
_IsAnimated = value
InvalidateTimer()
End Set
End Property
#End Region
#Region " Property Helpers "
Protected Function GetPen(ByVal name As String) As Pen
Return New Pen(Items(name))
End Function
Protected Function GetPen(ByVal name As String, ByVal width As Single) As Pen
Return New Pen(Items(name), width)
End Function
Protected Function GetBrush(ByVal name As String) As SolidBrush
Return New SolidBrush(Items(name))
End Function
Protected Function GetColor(ByVal name As String) As Color
Return Items(name)
End Function
Protected Sub SetColor(ByVal name As String, ByVal value As Color)
If Items.ContainsKey(name) Then Items(name) = value Else Items.Add(name, value)
End Sub
Protected Sub SetColor(ByVal name As String, ByVal r As Byte, ByVal g As Byte, ByVal b As Byte)
SetColor(name, Color.FromArgb(r, g, b))
End Sub
Protected Sub SetColor(ByVal name As String, ByVal a As Byte, ByVal r As Byte, ByVal g As Byte, ByVal b As Byte)
SetColor(name, Color.FromArgb(a, r, g, b))
End Sub
Protected Sub SetColor(ByVal name As String, ByVal a As Byte, ByVal value As Color)
SetColor(name, Color.FromArgb(a, value))
End Sub
Private Sub InvalidateBitmap()
If Width = 0 OrElse Height = 0 Then Return
B = New Bitmap(Width, Height, PixelFormat.Format32bppPArgb)
G = Graphics.FromImage(B)
End Sub
Private Sub InvalidateCustimization()
Dim M As New MemoryStream(Items.Count * 4)
For Each B As Bloom In Colors
M.Write(BitConverter.GetBytes(B.Value.ToArgb), 0, 4)
Next
M.Close()
_Customization = Convert.ToBase64String(M.ToArray)
End Sub
Private Sub InvalidateTimer()
If DesignMode OrElse Not DoneCreation Then Return
If _IsAnimated Then
AddAnimationCallback(AddressOf DoAnimation)
Else
RemoveAnimationCallback(AddressOf DoAnimation)
End If
End Sub
#End Region
#Region " User Hooks "
Protected MustOverride Sub ColorHook()
Protected MustOverride Sub PaintHook()
Protected Overridable Sub OnCreation()
End Sub
Protected Overridable Sub OnAnimation()
End Sub
#End Region
#Region " Offset "
Private OffsetReturnRectangle As Rectangle
Protected Function Offset(ByVal r As Rectangle, ByVal amount As Integer) As Rectangle
OffsetReturnRectangle = New Rectangle(r.X + amount, r.Y + amount, r.Width - (amount * 2), r.Height - (amount * 2))
Return OffsetReturnRectangle
End Function
Private OffsetReturnSize As Size
Protected Function Offset(ByVal s As Size, ByVal amount As Integer) As Size
OffsetReturnSize = New Size(s.Width + amount, s.Height + amount)
Return OffsetReturnSize
End Function
Private OffsetReturnPoint As Point
Protected Function Offset(ByVal p As Point, ByVal amount As Integer) As Point
OffsetReturnPoint = New Point(p.X + amount, p.Y + amount)
Return OffsetReturnPoint
End Function
#End Region
#Region " Center "
Private CenterReturn As Point
Protected Function Center(ByVal p As Rectangle, ByVal c As Rectangle) As Point
CenterReturn = New Point((p.Width \ 2 - c.Width \ 2) + p.X + c.X, (p.Height \ 2 - c.Height \ 2) + p.Y + c.Y)
Return CenterReturn
End Function
Protected Function Center(ByVal p As Rectangle, ByVal c As Size) As Point
CenterReturn = New Point((p.Width \ 2 - c.Width \ 2) + p.X, (p.Height \ 2 - c.Height \ 2) + p.Y)
Return CenterReturn
End Function
Protected Function Center(ByVal child As Rectangle) As Point
Return Center(Width, Height, child.Width, child.Height)
End Function
Protected Function Center(ByVal child As Size) As Point
Return Center(Width, Height, child.Width, child.Height)
End Function
Protected Function Center(ByVal childWidth As Integer, ByVal childHeight As Integer) As Point
Return Center(Width, Height, childWidth, childHeight)
End Function
Protected Function Center(ByVal p As Size, ByVal c As Size) As Point
Return Center(p.Width, p.Height, c.Width, c.Height)
End Function
Protected Function Center(ByVal pWidth As Integer, ByVal pHeight As Integer, ByVal cWidth As Integer, ByVal cHeight As Integer) As Point
CenterReturn = New Point(pWidth \ 2 - cWidth \ 2, pHeight \ 2 - cHeight \ 2)
Return CenterReturn
End Function
#End Region
#Region " Measure "
Private MeasureBitmap As Bitmap
Private MeasureGraphics As Graphics 'TODO: Potential issues during multi-threading.
Protected Function Measure() As Size
Return MeasureGraphics.MeasureString(Text, Font, Width).ToSize
End Function
Protected Function Measure(ByVal text As String) As Size
Return MeasureGraphics.MeasureString(text, Font, Width).ToSize
End Function
#End Region
#Region " DrawPixel "
Private DrawPixelBrush As SolidBrush
Protected Sub DrawPixel(ByVal c1 As Color, ByVal x As Integer, ByVal y As Integer)
If _Transparent Then
B.SetPixel(x, y, c1)
Else
DrawPixelBrush = New SolidBrush(c1)
G.FillRectangle(DrawPixelBrush, x, y, 1, 1)
End If
End Sub
#End Region
#Region " DrawCorners "
Private DrawCornersBrush As SolidBrush
Protected Sub DrawCorners(ByVal c1 As Color, ByVal offset As Integer)
DrawCorners(c1, 0, 0, Width, Height, offset)
End Sub
Protected Sub DrawCorners(ByVal c1 As Color, ByVal r1 As Rectangle, ByVal offset As Integer)
DrawCorners(c1, r1.X, r1.Y, r1.Width, r1.Height, offset)
End Sub
Protected Sub DrawCorners(ByVal c1 As Color, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal offset As Integer)
DrawCorners(c1, x + offset, y + offset, width - (offset * 2), height - (offset * 2))
End Sub
Protected Sub DrawCorners(ByVal c1 As Color)
DrawCorners(c1, 0, 0, Width, Height)
End Sub
Protected Sub DrawCorners(ByVal c1 As Color, ByVal r1 As Rectangle)
DrawCorners(c1, r1.X, r1.Y, r1.Width, r1.Height)
End Sub
Protected Sub DrawCorners(ByVal c1 As Color, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer)
If _NoRounding Then Return
If _Transparent Then
B.SetPixel(x, y, c1)
B.SetPixel(x + (width - 1), y, c1)
B.SetPixel(x, y + (height - 1), c1)
B.SetPixel(x + (width - 1), y + (height - 1), c1)
Else
DrawCornersBrush = New SolidBrush(c1)
G.FillRectangle(DrawCornersBrush, x, y, 1, 1)
G.FillRectangle(DrawCornersBrush, x + (width - 1), y, 1, 1)
G.FillRectangle(DrawCornersBrush, x, y + (height - 1), 1, 1)
G.FillRectangle(DrawCornersBrush, x + (width - 1), y + (height - 1), 1, 1)
End If
End Sub
#End Region
#Region " DrawBorders "
Protected Sub DrawBorders(ByVal p1 As Pen, ByVal offset As Integer)
DrawBorders(p1, 0, 0, Width, Height, offset)
End Sub
Protected Sub DrawBorders(ByVal p1 As Pen, ByVal r As Rectangle, ByVal offset As Integer)
DrawBorders(p1, r.X, r.Y, r.Width, r.Height, offset)
End Sub
Protected Sub DrawBorders(ByVal p1 As Pen, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal offset As Integer)
DrawBorders(p1, x + offset, y + offset, width - (offset * 2), height - (offset * 2))
End Sub
Protected Sub DrawBorders(ByVal p1 As Pen)
DrawBorders(p1, 0, 0, Width, Height)
End Sub
Protected Sub DrawBorders(ByVal p1 As Pen, ByVal r As Rectangle)
DrawBorders(p1, r.X, r.Y, r.Width, r.Height)
End Sub
Protected Sub DrawBorders(ByVal p1 As Pen, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer)
G.DrawRectangle(p1, x, y, width - 1, height - 1)
End Sub
#End Region
#Region " DrawText "
Private DrawTextPoint As Point
Private DrawTextSize As Size
Protected Sub DrawText(ByVal b1 As Brush, ByVal a As HorizontalAlignment, ByVal x As Integer, ByVal y As Integer)
DrawText(b1, Text, a, x, y)
End Sub
Protected Sub DrawText(ByVal b1 As Brush, ByVal text As String, ByVal a As HorizontalAlignment, ByVal x As Integer, ByVal y As Integer)
If text.Length = 0 Then Return
DrawTextSize = Measure(text)
DrawTextPoint = Center(DrawTextSize)
Select Case a
Case HorizontalAlignment.Left
G.DrawString(text, Font, b1, x, DrawTextPoint.Y + y)
Case HorizontalAlignment.Center
G.DrawString(text, Font, b1, DrawTextPoint.X + x, DrawTextPoint.Y + y)
Case HorizontalAlignment.Right
G.DrawString(text, Font, b1, Width - DrawTextSize.Width - x, DrawTextPoint.Y + y)
End Select
End Sub
Protected Sub DrawText(ByVal b1 As Brush, ByVal p1 As Point)
If Text.Length = 0 Then Return
G.DrawString(Text, Font, b1, p1)
End Sub
Protected Sub DrawText(ByVal b1 As Brush, ByVal x As Integer, ByVal y As Integer)
If Text.Length = 0 Then Return
G.DrawString(Text, Font, b1, x, y)
End Sub
#End Region
#Region " DrawImage "
Private DrawImagePoint As Point
Protected Sub DrawImage(ByVal a As HorizontalAlignment, ByVal x As Integer, ByVal y As Integer)
DrawImage(_Image, a, x, y)
End Sub
Protected Sub DrawImage(ByVal image As Image, ByVal a As HorizontalAlignment, ByVal x As Integer, ByVal y As Integer)
If image Is Nothing Then Return
DrawImagePoint = Center(image.Size)
Select Case a
Case HorizontalAlignment.Left
G.DrawImage(image, x, DrawImagePoint.Y + y, image.Width, image.Height)
Case HorizontalAlignment.Center
G.DrawImage(image, DrawImagePoint.X + x, DrawImagePoint.Y + y, image.Width, image.Height)
Case HorizontalAlignment.Right
G.DrawImage(image, Width - image.Width - x, DrawImagePoint.Y + y, image.Width, image.Height)
End Select
End Sub
Protected Sub DrawImage(ByVal p1 As Point)
DrawImage(_Image, p1.X, p1.Y)
End Sub
Protected Sub DrawImage(ByVal x As Integer, ByVal y As Integer)
DrawImage(_Image, x, y)
End Sub
Protected Sub DrawImage(ByVal image As Image, ByVal p1 As Point)
DrawImage(image, p1.X, p1.Y)
End Sub
Protected Sub DrawImage(ByVal image As Image, ByVal x As Integer, ByVal y As Integer)
If image Is Nothing Then Return
G.DrawImage(image, x, y, image.Width, image.Height)
End Sub
#End Region
#Region " DrawGradient "
Private DrawGradientBrush As LinearGradientBrush
Private DrawGradientRectangle As Rectangle
Protected Sub DrawGradient(ByVal blend As ColorBlend, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer)
DrawGradientRectangle = New Rectangle(x, y, width, height)
DrawGradient(blend, DrawGradientRectangle)
End Sub
Protected Sub DrawGradient(ByVal blend As ColorBlend, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal angle As Single)
DrawGradientRectangle = New Rectangle(x, y, width, height)
DrawGradient(blend, DrawGradientRectangle, angle)
End Sub
Protected Sub DrawGradient(ByVal blend As ColorBlend, ByVal r As Rectangle)
DrawGradientBrush = New LinearGradientBrush(r, Color.Empty, Color.Empty, 90.0F)
DrawGradientBrush.InterpolationColors = blend
G.FillRectangle(DrawGradientBrush, r)
End Sub
Protected Sub DrawGradient(ByVal blend As ColorBlend, ByVal r As Rectangle, ByVal angle As Single)
DrawGradientBrush = New LinearGradientBrush(r, Color.Empty, Color.Empty, angle)
DrawGradientBrush.InterpolationColors = blend
G.FillRectangle(DrawGradientBrush, r)
End Sub
Protected Sub DrawGradient(ByVal c1 As Color, ByVal c2 As Color, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer)
DrawGradientRectangle = New Rectangle(x, y, width, height)
DrawGradient(c1, c2, DrawGradientRectangle)
End Sub
Protected Sub DrawGradient(ByVal c1 As Color, ByVal c2 As Color, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal angle As Single)
DrawGradientRectangle = New Rectangle(x, y, width, height)
DrawGradient(c1, c2, DrawGradientRectangle, angle)
End Sub
Protected Sub DrawGradient(ByVal c1 As Color, ByVal c2 As Color, ByVal r As Rectangle)
DrawGradientBrush = New LinearGradientBrush(r, c1, c2, 90.0F)
G.FillRectangle(DrawGradientBrush, r)
End Sub
Protected Sub DrawGradient(ByVal c1 As Color, ByVal c2 As Color, ByVal r As Rectangle, ByVal angle As Single)
DrawGradientBrush = New LinearGradientBrush(r, c1, c2, angle)
G.FillRectangle(DrawGradientBrush, r)
End Sub
#End Region
#Region " DrawRadial "
Private DrawRadialPath As GraphicsPath
Private DrawRadialBrush1 As PathGradientBrush
Private DrawRadialBrush2 As LinearGradientBrush
Private DrawRadialRectangle As Rectangle
Sub DrawRadial(ByVal blend As ColorBlend, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer)
DrawRadialRectangle = New Rectangle(x, y, width, height)
DrawRadial(blend, DrawRadialRectangle, width \ 2, height \ 2)
End Sub
Sub DrawRadial(ByVal blend As ColorBlend, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal center As Point)
DrawRadialRectangle = New Rectangle(x, y, width, height)
DrawRadial(blend, DrawRadialRectangle, center.X, center.Y)
End Sub
Sub DrawRadial(ByVal blend As ColorBlend, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal cx As Integer, ByVal cy As Integer)
DrawRadialRectangle = New Rectangle(x, y, width, height)
DrawRadial(blend, DrawRadialRectangle, cx, cy)
End Sub
Sub DrawRadial(ByVal blend As ColorBlend, ByVal r As Rectangle)
DrawRadial(blend, r, r.Width \ 2, r.Height \ 2)
End Sub
Sub DrawRadial(ByVal blend As ColorBlend, ByVal r As Rectangle, ByVal center As Point)
DrawRadial(blend, r, center.X, center.Y)
End Sub
Sub DrawRadial(ByVal blend As ColorBlend, ByVal r As Rectangle, ByVal cx As Integer, ByVal cy As Integer)
DrawRadialPath.Reset()
DrawRadialPath.AddEllipse(r.X, r.Y, r.Width - 1, r.Height - 1)
DrawRadialBrush1 = New PathGradientBrush(DrawRadialPath)
DrawRadialBrush1.CenterPoint = New Point(r.X + cx, r.Y + cy)
DrawRadialBrush1.InterpolationColors = blend
If G.SmoothingMode = SmoothingMode.AntiAlias Then
G.FillEllipse(DrawRadialBrush1, r.X + 1, r.Y + 1, r.Width - 3, r.Height - 3)
Else
G.FillEllipse(DrawRadialBrush1, r)
End If
End Sub
Protected Sub DrawRadial(ByVal c1 As Color, ByVal c2 As Color, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer)
DrawRadialRectangle = New Rectangle(x, y, width, height)
DrawRadial(c1, c2, DrawRadialRectangle)
End Sub
Protected Sub DrawRadial(ByVal c1 As Color, ByVal c2 As Color, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal angle As Single)
DrawRadialRectangle = New Rectangle(x, y, width, height)
DrawRadial(c1, c2, DrawRadialRectangle, angle)
End Sub
Protected Sub DrawRadial(ByVal c1 As Color, ByVal c2 As Color, ByVal r As Rectangle)
DrawRadialBrush2 = New LinearGradientBrush(r, c1, c2, 90.0F)
G.FillEllipse(DrawRadialBrush2, r)
End Sub
Protected Sub DrawRadial(ByVal c1 As Color, ByVal c2 As Color, ByVal r As Rectangle, ByVal angle As Single)
DrawRadialBrush2 = New LinearGradientBrush(r, c1, c2, angle)
G.FillEllipse(DrawRadialBrush2, r)
End Sub
#End Region
#Region " CreateRound "
Private CreateRoundPath As GraphicsPath
Private CreateRoundRectangle As Rectangle
Function CreateRound(ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal slope As Integer) As GraphicsPath
CreateRoundRectangle = New Rectangle(x, y, width, height)
Return CreateRound(CreateRoundRectangle, slope)
End Function
Function CreateRound(ByVal r As Rectangle, ByVal slope As Integer) As GraphicsPath
CreateRoundPath = New GraphicsPath(FillMode.Winding)
CreateRoundPath.AddArc(r.X, r.Y, slope, slope, 180.0F, 90.0F)
CreateRoundPath.AddArc(r.Right - slope, r.Y, slope, slope, 270.0F, 90.0F)
CreateRoundPath.AddArc(r.Right - slope, r.Bottom - slope, slope, slope, 0.0F, 90.0F)
CreateRoundPath.AddArc(r.X, r.Bottom - slope, slope, slope, 90.0F, 90.0F)
CreateRoundPath.CloseFigure()
Return CreateRoundPath
End Function
#End Region
End Class
Module ThemeShare
#Region " Animation "
Private Frames As Integer
Private Invalidate As Boolean
Public ThemeTimer As New PrecisionTimer
Public FPS As Integer = 20 '1000 / 50 = 20 FPS
Public Rate As Integer = 50
Public Delegate Sub AnimationDelegate(ByVal invalidate As Boolean)
Private Callbacks As New List(Of AnimationDelegate)
Private Sub HandleCallbacks(ByVal state As IntPtr, ByVal reserve As Boolean)
Invalidate = (Frames >= FPS)
If Invalidate Then Frames = 0
SyncLock Callbacks
For I As Integer = 0 To Callbacks.Count - 1
Callbacks(I).Invoke(Invalidate)
Next
End SyncLock
Frames += Rate
End Sub
Private Sub InvalidateThemeTimer()
If Callbacks.Count = 0 Then
ThemeTimer.Delete()
Else
ThemeTimer.Create(0, Rate, AddressOf HandleCallbacks)
End If
End Sub
Sub AddAnimationCallback(ByVal callback As AnimationDelegate)
SyncLock Callbacks
If Callbacks.Contains(callback) Then Return
Callbacks.Add(callback)
InvalidateThemeTimer()
End SyncLock
End Sub
Sub RemoveAnimationCallback(ByVal callback As AnimationDelegate)
SyncLock Callbacks
If Not Callbacks.Contains(callback) Then Return
Callbacks.Remove(callback)
InvalidateThemeTimer()
End SyncLock
End Sub
#End Region
End Module
Enum MouseState As Byte
None = 0
Over = 1
Down = 2
Block = 3
End Enum
Structure Bloom
Public _Name As String
ReadOnly Property Name() As String
Get
Return _Name
End Get
End Property
Private _Value As Color
Property Value() As Color
Get
Return _Value
End Get
Set(ByVal value As Color)
_Value = value
End Set
End Property
Property ValueHex() As String
Get
Return String.Concat("#",
_Value.R.ToString("X2", Nothing),
_Value.G.ToString("X2", Nothing),
_Value.B.ToString("X2", Nothing))
End Get
Set(ByVal value As String)
Try
_Value = ColorTranslator.FromHtml(value)
Catch
Return
End Try
End Set
End Property
Sub New(ByVal name As String, ByVal value As Color)
_Name = name
_Value = value
End Sub
End Structure
'------------------
'Creator: aeonhack
'Site: elitevs.net
'Created: 11/30/2011
'Changed: 11/30/2011
'Version: 1.0.0
'------------------
Class PrecisionTimer
Implements IDisposable
Private _Enabled As Boolean
ReadOnly Property Enabled() As Boolean
Get
Return _Enabled
End Get
End Property
Private Handle As IntPtr
Private TimerCallback As TimerDelegate
<DllImport("kernel32.dll", EntryPoint:="CreateTimerQueueTimer")>
Private Shared Function CreateTimerQueueTimer(
ByRef handle As IntPtr,
ByVal queue As IntPtr,
ByVal callback As TimerDelegate,
ByVal state As IntPtr,
ByVal dueTime As UInteger,
ByVal period As UInteger,
ByVal flags As UInteger) As Boolean
End Function
<DllImport("kernel32.dll", EntryPoint:="DeleteTimerQueueTimer")>
Private Shared Function DeleteTimerQueueTimer(
ByVal queue As IntPtr,
ByVal handle As IntPtr,
ByVal callback As IntPtr) As Boolean
End Function
Delegate Sub TimerDelegate(ByVal r1 As IntPtr, ByVal r2 As Boolean)
Sub Create(ByVal dueTime As UInteger, ByVal period As UInteger, ByVal callback As TimerDelegate)
If _Enabled Then Return
TimerCallback = callback
Dim Success As Boolean = CreateTimerQueueTimer(Handle, IntPtr.Zero, TimerCallback, IntPtr.Zero, dueTime, period, 0)
If Not Success Then ThrowNewException("CreateTimerQueueTimer")
_Enabled = Success
End Sub
Sub Delete()
If Not _Enabled Then Return
Dim Success As Boolean = DeleteTimerQueueTimer(IntPtr.Zero, Handle, IntPtr.Zero)
If Not Success AndAlso Not Marshal.GetLastWin32Error = 997 Then
'ThrowNewException("DeleteTimerQueueTimer")
End If
_Enabled = Not Success
End Sub
Private Sub ThrowNewException(ByVal name As String)
Throw New Exception(String.Format("{0} failed. Win32Error: {1}", name, Marshal.GetLastWin32Error))
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Delete()
End Sub
End Class
#End Region
Class GhostTheme
Inherits ThemeContainer154
Protected Overrides Sub ColorHook()
End Sub
Private _ShowIcon As Boolean
Public Property ShowIcon As Boolean
Get
Return _ShowIcon
End Get
Set(value As Boolean)
_ShowIcon = value
Invalidate()
End Set
End Property
Protected Overrides Sub PaintHook()
G.Clear(Color.DimGray)
Dim hatch As New ColorBlend(2)
DrawBorders(Pens.Gray, 1)
hatch.Colors(0) = Color.DimGray
hatch.Colors(1) = Color.FromArgb(60, 60, 60)
hatch.Positions(0) = 0
hatch.Positions(1) = 1
DrawGradient(hatch, New Rectangle(0, 0, Width, 24))
hatch.Colors(0) = Color.FromArgb(100, 100, 100)
hatch.Colors(1) = Color.DimGray
DrawGradient(hatch, New Rectangle(0, 0, Width, 12))
Dim asdf As HatchBrush
asdf = New HatchBrush(HatchStyle.DarkDownwardDiagonal, Color.FromArgb(15, Color.Black), Color.FromArgb(0, Color.Gray))
hatch.Colors(0) = Color.FromArgb(120, Color.Black)
hatch.Colors(1) = Color.FromArgb(0, Color.Black)
DrawGradient(hatch, New Rectangle(0, 0, Width, 30))
G.FillRectangle(asdf, 0, 0, Width, 24)
G.DrawLine(Pens.Black, 6, 24, Width - 7, 24)
G.DrawLine(Pens.Black, 6, 24, 6, Height - 7)
G.DrawLine(Pens.Black, 6, Height - 7, Width - 7, Height - 7)
G.DrawLine(Pens.Black, Width - 7, 24, Width - 7, Height - 7)
G.FillRectangle(New SolidBrush(Color.FromArgb(60, 60, 60)), New Rectangle(1, 24, 5, Height - 6 - 24))
G.FillRectangle(asdf, 1, 24, 5, Height - 6 - 24)
G.FillRectangle(New SolidBrush(Color.FromArgb(60, 60, 60)), New Rectangle(Width - 6, 24, Width - 1, Height - 6 - 24))
G.FillRectangle(asdf, Width - 6, 24, Width - 2, Height - 6 - 24)
G.FillRectangle(New SolidBrush(Color.FromArgb(60, 60, 60)), New Rectangle(1, Height - 6, Width - 2, Height - 1))
G.FillRectangle(asdf, 1, Height - 6, Width - 2, Height - 1)
DrawBorders(Pens.Black)
asdf = New HatchBrush(HatchStyle.LightDownwardDiagonal, Color.DimGray)
G.FillRectangle(asdf, 7, 25, Width - 14, Height - 24 - 8)
G.FillRectangle(New SolidBrush(Color.FromArgb(230, 20, 20, 20)), 7, 25, Width - 14, Height - 24 - 8)
DrawCorners(Color.Fuchsia)
DrawCorners(Color.Fuchsia, 0, 1, 1, 1)
DrawCorners(Color.Fuchsia, 1, 0, 1, 1)
DrawPixel(Color.Black, 1, 1)
DrawCorners(Color.Fuchsia, 0, Height - 2, 1, 1)
DrawCorners(Color.Fuchsia, 1, Height - 1, 1, 1)
DrawPixel(Color.Black, Width - 2, 1)
DrawCorners(Color.Fuchsia, Width - 1, 1, 1, 1)
DrawCorners(Color.Fuchsia, Width - 2, 0, 1, 1)
DrawPixel(Color.Black, 1, Height - 2)
DrawCorners(Color.Fuchsia, Width - 1, Height - 2, 1, 1)
DrawCorners(Color.Fuchsia, Width - 2, Height - 1, 1, 1)
DrawPixel(Color.Black, Width - 2, Height - 2)
Dim cblend As New ColorBlend(2)
cblend.Colors(0) = Color.FromArgb(35, Color.Black)
cblend.Colors(1) = Color.FromArgb(0, 0, 0, 0)
cblend.Positions(0) = 0
cblend.Positions(1) = 1
DrawGradient(cblend, 7, 25, 15, Height - 6 - 24, 0)
cblend.Colors(0) = Color.FromArgb(0, 0, 0, 0)
cblend.Colors(1) = Color.FromArgb(35, Color.Black)
DrawGradient(cblend, Width - 24, 25, 17, Height - 6 - 24, 0)
cblend.Colors(1) = Color.FromArgb(0, 0, 0, 0)
cblend.Colors(0) = Color.FromArgb(35, Color.Black)
DrawGradient(cblend, 7, 25, Me.Width - 14, 17, 90)
cblend.Colors(0) = Color.FromArgb(0, 0, 0, 0)
cblend.Colors(1) = Color.FromArgb(35, Color.Black)
DrawGradient(cblend, 8, Me.Height - 24, Me.Width - 14, 17, 90)
If _ShowIcon = False Then
G.DrawString(Text, Font, Brushes.White, New Point(6, 6))
Else
G.DrawIcon(FindForm.Icon, New Rectangle(New Point(9, 5), New Size(16, 16)))
G.DrawString(Text, Font, Brushes.White, New Point(28, 6))
End If
End Sub
Public Sub New()
TransparencyKey = Color.Fuchsia
End Sub
End Class
Class GhostButton
Inherits ThemeControl154
Private Glass As Boolean = True
Private _color As Color
Dim a As Integer = 0
Protected Overrides Sub ColorHook()
End Sub
Protected Overrides Sub OnAnimation()
MyBase.OnAnimation()
Select Case State
Case MouseState.Over
If a < 20 Then
a += 5
Invalidate()
Application.DoEvents()
End If
Case MouseState.None
If a > 0 Then
a -= 5
If a < 0 Then a = 0
Invalidate()
Application.DoEvents()
End If
End Select
End Sub
Public Property EnableGlass As Boolean
Get
Return Glass
End Get
Set(ByVal value As Boolean)
Glass = value
End Set
End Property
Public Property Color As Color
Get
Return _color
End Get
Set(value As Color)
_color = value
End Set
End Property
Protected Overrides Sub OnTextChanged(ByVal e As System.EventArgs)
MyBase.OnTextChanged(e)
Dim gg As Graphics = Me.CreateGraphics
Dim textSize As SizeF = Me.CreateGraphics.MeasureString(Text, Font)
gg.DrawString(Text, Font, Brushes.White, New RectangleF(0, 0, Me.Width, Me.Height))
End Sub
Protected Overrides Sub PaintHook()
G.Clear(_color)
If State = MouseState.Over Then
Dim cblend As New ColorBlend(2)
cblend.Colors(0) = Color.FromArgb(200, 50, 50, 50)
cblend.Colors(1) = Color.FromArgb(200, 70, 70, 70)
cblend.Positions(0) = 0
cblend.Positions(1) = 1
DrawGradient(cblend, New Rectangle(0, 0, Width, Height))
cblend.Colors(0) = Color.FromArgb(0, 0, 0, 0)
cblend.Colors(1) = Color.FromArgb(40, Color.White)
If Glass Then DrawGradient(cblend, New Rectangle(0, 0, Width, Height / 5 * 2))
ElseIf State = MouseState.None Then
Dim cblend As New ColorBlend(2)
cblend.Colors(0) = Color.FromArgb(200, 50, 50, 50)
cblend.Colors(1) = Color.FromArgb(200, 70, 70, 70)
cblend.Positions(0) = 0
cblend.Positions(1) = 1
DrawGradient(cblend, New Rectangle(0, 0, Width, Height))
cblend.Colors(0) = Color.FromArgb(0, 0, 0, 0)
cblend.Colors(1) = Color.FromArgb(40, Color.White)
If Glass Then DrawGradient(cblend, New Rectangle(0, 0, Width, Height / 5 * 2))
Else
Dim cblend As New ColorBlend(2)
cblend.Colors(0) = Color.FromArgb(200, 30, 30, 30)
cblend.Colors(1) = Color.FromArgb(200, 50, 50, 50)
cblend.Positions(0) = 0
cblend.Positions(1) = 1
DrawGradient(cblend, New Rectangle(0, 0, Width, Height))
cblend.Colors(0) = Color.FromArgb(0, 0, 0, 0)
cblend.Colors(1) = Color.FromArgb(40, Color.White)
If Glass Then DrawGradient(cblend, New Rectangle(0, 0, Width, Height / 5 * 2))
End If
G.FillRectangle(New SolidBrush(Color.FromArgb(a, Drawing.Color.White)), 0, 0, Width, Height)
Dim hatch As HatchBrush
hatch = New HatchBrush(HatchStyle.DarkDownwardDiagonal, Color.FromArgb(25, Color.Black), Color.FromArgb(0, Color.Gray))
G.FillRectangle(hatch, 0, 0, Width, Height)
Dim textSize As SizeF = Me.CreateGraphics.MeasureString(Text, Font, Width - 4)
Dim sf As New StringFormat
sf.LineAlignment = StringAlignment.Center
sf.Alignment = StringAlignment.Center
G.DrawString(Text, Font, Brushes.White, New RectangleF(2, 2, Me.Width - 5, Me.Height - 4), sf)
DrawBorders(Pens.Black)
DrawBorders(New Pen(Color.FromArgb(90, 90, 90)), 1)
End Sub
Sub New()
IsAnimated = True
End Sub
End Class
Class GhostProgressbar
Inherits ThemeControl154
Private _Maximum As Integer = 100
Private _Value As Integer
Private HOffset As Integer = 0
Private Progress As Integer
Protected Overrides Sub ColorHook()
End Sub
Public Property Maximum As Integer
Get
Return _Maximum
End Get
Set(ByVal V As Integer)
If V < 1 Then V = 1
If V < _Value Then _Value = V
_Maximum = V
Invalidate()
End Set
End Property
Public Property Value As Integer
Get
Return _Value
End Get
Set(ByVal V As Integer)
If V > _Maximum Then V = Maximum
_Value = V
Invalidate()
End Set
End Property
Public Property Animated As Boolean
Get
Return IsAnimated
End Get
Set(ByVal V As Boolean)
IsAnimated = V
Invalidate()
End Set
End Property
Protected Overrides Sub OnAnimation()
HOffset -= 1
If HOffset = 7 Then HOffset = 0
End Sub
Protected Overrides Sub PaintHook()
Dim hatch As New HatchBrush(HatchStyle.DarkDownwardDiagonal, Color.FromArgb(60, Color.Black))
G.Clear(Color.FromArgb(0, 30, 30, 30))
Dim cblend As New ColorBlend(2)
cblend.Colors(0) = Color.FromArgb(50, 50, 50)
cblend.Colors(1) = Color.FromArgb(70, 70, 70)
cblend.Positions(0) = 0
cblend.Positions(1) = 1
DrawGradient(cblend, New Rectangle(0, 0, CInt(((Width / _Maximum) * _Value) - 2), Height - 2))
cblend.Colors(1) = Color.FromArgb(80, 80, 80)
DrawGradient(cblend, New Rectangle(0, 0, CInt(((Width / _Maximum) * _Value) - 2), Height / 5 * 2))
G.RenderingOrigin = New Point(HOffset, 0)
hatch = New HatchBrush(HatchStyle.ForwardDiagonal, Color.FromArgb(40, Color.Black), Color.FromArgb(0, Color.Gray))
G.FillRectangle(hatch, 0, 0, CInt(((Width / _Maximum) * _Value) - 2), Height - 2)
DrawBorders(Pens.Black)
DrawBorders(New Pen(Color.FromArgb(90, 90, 90)), 1)
DrawCorners(Color.Black)
G.DrawLine(New Pen(Color.FromArgb(200, 90, 90, 90)), CInt(((Width / _Maximum) * _Value) - 2), 1, CInt(((Width / _Maximum) * _Value) - 2), Height - 2)
G.DrawLine(Pens.Black, CInt(((Width / _Maximum) * _Value) - 2) + 1, 2, CInt(((Width / _Maximum) * _Value) - 2) + 1, Height - 3)
Progress = CInt(((Width / _Maximum) * _Value))
Dim cblend2 As New ColorBlend(3)
cblend2.Colors(0) = Color.FromArgb(0, Color.Gray)
cblend2.Colors(1) = Color.FromArgb(80, Color.DimGray)
cblend2.Colors(2) = Color.FromArgb(0, Color.Gray)
cblend2.Positions = {0, 0.5, 1}
If Value > 0 Then G.FillRectangle(New SolidBrush(Color.FromArgb(5, 5, 5)), CInt(((Width / _Maximum) * _Value)) - 1, 2, Width - CInt(((Width / _Maximum) * _Value)) - 1, Height - 4)
End Sub
Public Sub New()
_Maximum = 100
IsAnimated = True
End Sub
End Class
<DefaultEvent("CheckedChanged")>
Class GhostCheckbox
Inherits ThemeControl154
Private _Checked As Boolean
Private X As Integer
Event CheckedChanged(ByVal sender As Object)
Public Property Checked As Boolean
Get
Return _Checked
End Get
Set(ByVal V As Boolean)
_Checked = V
Invalidate()
RaiseEvent CheckedChanged(Me)
End Set
End Property
Protected Overrides Sub ColorHook()
End Sub
Protected Overrides Sub OnTextChanged(ByVal e As System.EventArgs)
MyBase.OnTextChanged(e)
Dim textSize As Integer
textSize = Me.CreateGraphics.MeasureString(Text, Font).Width
Me.Width = 20 + textSize
End Sub
Protected Overrides Sub OnMouseMove(e As System.Windows.Forms.MouseEventArgs)
MyBase.OnMouseMove(e)
X = e.X
Invalidate()
End Sub
Protected Overrides Sub OnMouseDown(e As System.Windows.Forms.MouseEventArgs)
MyBase.OnMouseDown(e)
If _Checked = True Then _Checked = False Else _Checked = True
End Sub
Protected Overrides Sub PaintHook()
G.Clear(Color.FromArgb(60, 60, 60))
Dim asdf As HatchBrush
asdf = New HatchBrush(HatchStyle.DarkDownwardDiagonal, Color.FromArgb(35, Color.Black), Color.FromArgb(0, Color.Gray))
G.FillRectangle(New SolidBrush(Color.FromArgb(60, 60, 60)), New Rectangle(0, 0, Width, Height))
asdf = New HatchBrush(HatchStyle.LightDownwardDiagonal, Color.DimGray)
G.FillRectangle(asdf, 0, 0, Width, Height)
G.FillRectangle(New SolidBrush(Color.FromArgb(230, 20, 20, 20)), 0, 0, Width, Height)
G.FillRectangle(New SolidBrush(Color.FromArgb(10, 10, 10)), 3, 3, 10, 10)
If _Checked Then
Dim cblend As New ColorBlend(2)
cblend.Colors(0) = Color.FromArgb(60, 60, 60)
cblend.Colors(1) = Color.FromArgb(80, 80, 80)
cblend.Positions(0) = 0
cblend.Positions(1) = 1
DrawGradient(cblend, New Rectangle(3, 3, 10, 10))
cblend.Colors(0) = Color.FromArgb(70, 70, 70)
cblend.Colors(1) = Color.FromArgb(100, 100, 100)
DrawGradient(cblend, New Rectangle(3, 3, 10, 4))
Dim hatch As HatchBrush
hatch = New HatchBrush(HatchStyle.LightDownwardDiagonal, Color.FromArgb(60, Color.Black), Color.FromArgb(0, Color.Gray))
G.FillRectangle(hatch, 3, 3, 10, 10)
Else
Dim hatch As HatchBrush
hatch = New HatchBrush(HatchStyle.LightDownwardDiagonal, Color.FromArgb(20, Color.White), Color.FromArgb(0, Color.Gray))
G.FillRectangle(hatch, 3, 3, 10, 10)
End If
If State = MouseState.Over And X < 15 Then
G.FillRectangle(New SolidBrush(Color.FromArgb(30, Color.Gray)), New Rectangle(3, 3, 10, 10))
ElseIf State = MouseState.Down Then
G.FillRectangle(New SolidBrush(Color.FromArgb(30, Color.Black)), New Rectangle(3, 3, 10, 10))
End If
G.DrawRectangle(Pens.Black, 0, 0, 15, 15)
G.DrawRectangle(New Pen(Color.FromArgb(90, 90, 90)), 1, 1, 13, 13)
G.DrawString(Text, Font, Brushes.White, 17, 1)
End Sub
Public Sub New()
Me.Size = New Point(16, 50)
End Sub
End Class
<DefaultEvent("CheckedChanged")>
Class GhostRadiobutton
Inherits ThemeControl154
Private X As Integer
Private _Checked As Boolean
Property Checked() As Boolean
Get
Return _Checked
End Get
Set(ByVal value As Boolean)
_Checked = value
InvalidateControls()
RaiseEvent CheckedChanged(Me)
Invalidate()
End Set
End Property
Event CheckedChanged(ByVal sender As Object)
Protected Overrides Sub OnCreation()
InvalidateControls()
End Sub
Private Sub InvalidateControls()
If Not IsHandleCreated OrElse Not _Checked Then Return
For Each C As Control In Parent.Controls
If C IsNot Me AndAlso TypeOf C Is GhostRadiobutton Then
DirectCast(C, GhostRadiobutton).Checked = False
End If
Next
End Sub
Protected Overrides Sub OnMouseDown(ByVal e As System.Windows.Forms.MouseEventArgs)
If Not _Checked Then Checked = True
MyBase.OnMouseDown(e)
End Sub
Protected Overrides Sub OnMouseMove(e As System.Windows.Forms.MouseEventArgs)
MyBase.OnMouseMove(e)
X = e.X
Invalidate()
End Sub
Protected Overrides Sub ColorHook()
End Sub
Protected Overrides Sub OnTextChanged(ByVal e As System.EventArgs)
MyBase.OnTextChanged(e)
Dim textSize As Integer
textSize = Me.CreateGraphics.MeasureString(Text, Font).Width
Me.Width = 20 + textSize
End Sub
Protected Overrides Sub PaintHook()
G.Clear(Color.FromArgb(60, 60, 60))
Dim asdf As HatchBrush
asdf = New HatchBrush(HatchStyle.DarkDownwardDiagonal, Color.FromArgb(35, Color.Black), Color.FromArgb(0, Color.Gray))
G.FillRectangle(New SolidBrush(Color.FromArgb(60, 60, 60)), New Rectangle(0, 0, Width, Height))
asdf = New HatchBrush(HatchStyle.LightDownwardDiagonal, Color.DimGray)
G.FillRectangle(asdf, 0, 0, Width, Height)
G.FillRectangle(New SolidBrush(Color.FromArgb(230, 20, 20, 20)), 0, 0, Width, Height)
G.SmoothingMode = SmoothingMode.AntiAlias
G.FillEllipse(New SolidBrush(Color.Black), 2, 2, 11, 11)
G.DrawEllipse(Pens.Black, 0, 0, 13, 13)
G.DrawEllipse(New Pen(Color.FromArgb(90, 90, 90)), 1, 1, 11, 11)
If _Checked = False Then
Dim hatch As HatchBrush
hatch = New HatchBrush(HatchStyle.LightDownwardDiagonal, Color.FromArgb(20, Color.White), Color.FromArgb(0, Color.Gray))
G.FillEllipse(hatch, 2, 2, 10, 10)
Else
G.FillEllipse(New SolidBrush(Color.FromArgb(80, 80, 80)), 3, 3, 7, 7)
Dim hatch As HatchBrush
hatch = New HatchBrush(HatchStyle.LightDownwardDiagonal, Color.FromArgb(60, Color.Black), Color.FromArgb(0, Color.Gray))
G.FillRectangle(hatch, 3, 3, 7, 7)
End If
If State = MouseState.Over And X < 13 Then
G.FillEllipse(New SolidBrush(Color.FromArgb(20, Color.White)), 2, 2, 11, 11)
End If
G.DrawString(Text, Font, Brushes.White, 16, 0)
End Sub
Public Sub New()
Me.Size = New Point(50, 14)
End Sub
End Class
Class GhostTabControl
Inherits TabControl
Private Xstart(9999) As Integer 'Stupid VB.Net bug. Please don't use more than 9999 tabs :3
Private Xstop(9999) As Integer 'Stupid VB.Net bug. Please don't use more than 9999 tabs :3
Sub New()
SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.ResizeRedraw Or ControlStyles.UserPaint Or ControlStyles.DoubleBuffer, True)
DoubleBuffered = True
For Each p As TabPage In TabPages
p.BackColor = Color.White
Application.DoEvents()
p.BackColor = Color.Transparent
Next
End Sub
Protected Overrides Sub CreateHandle()
MyBase.CreateHandle()
Alignment = TabAlignment.Top
End Sub
Protected Overrides Sub OnMouseClick(ByVal e As System.Windows.Forms.MouseEventArgs)
MyBase.OnMouseClick(e)
Dim index As Integer = 0
Dim height As Integer = Me.CreateGraphics.MeasureString("Mava is awesome", Font).Height + 8
For Each a As Integer In Xstart
If e.X > a And e.X < Xstop(index) And e.Y < height And e.Button = Windows.Forms.MouseButtons.Left Then
SelectedIndex = index
Invalidate()
Else
End If
index += 1
Next
End Sub
Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
Dim B As New Bitmap(Width, Height)
Dim G As Graphics = Graphics.FromImage(B)
G.Clear(Color.FromArgb(60, 60, 60))
Dim asdf As HatchBrush
asdf = New HatchBrush(HatchStyle.DarkDownwardDiagonal, Color.FromArgb(35, Color.Black), Color.FromArgb(0, Color.Gray))
G.FillRectangle(New SolidBrush(Color.FromArgb(60, 60, 60)), New Rectangle(0, 0, Width, Height))
asdf = New HatchBrush(HatchStyle.LightDownwardDiagonal, Color.DimGray)
G.FillRectangle(asdf, 0, 0, Width, Height)
G.FillRectangle(New SolidBrush(Color.FromArgb(230, 20, 20, 20)), 0, 0, Width, Height)
G.FillRectangle(Brushes.Black, 0, 0, Width, Me.CreateGraphics.MeasureString("Mava is awesome", Font).Height + 8)
G.FillRectangle(New SolidBrush(Color.FromArgb(20, Color.Black)), 2, Me.CreateGraphics.MeasureString("Mava is awesome", Font).Height + 7, Width - 2, Height - 2)
Dim totallength As Integer = 0
Dim index As Integer = 0
For Each tab As TabPage In TabPages
If SelectedIndex = index Then
G.FillRectangle(New SolidBrush(Color.FromArgb(60, 60, 60)), totallength, 1, Me.CreateGraphics.MeasureString(tab.Text, Font).Width + 15, Me.CreateGraphics.MeasureString("Mava is awesome", Font).Height + 10)
asdf = New HatchBrush(HatchStyle.DarkDownwardDiagonal, Color.FromArgb(35, Color.Black), Color.FromArgb(0, Color.Gray))
G.FillRectangle(New SolidBrush(Color.FromArgb(60, 60, 60)), totallength, 1, Me.CreateGraphics.MeasureString(tab.Text, Font).Width + 15, Me.CreateGraphics.MeasureString("Mava is awesome", Font).Height + 10)
asdf = New HatchBrush(HatchStyle.LightDownwardDiagonal, Color.DimGray)
G.FillRectangle(asdf, totallength, 1, Me.CreateGraphics.MeasureString(tab.Text, Font).Width + 15, Me.CreateGraphics.MeasureString("Mava is awesome", Font).Height + 10)
G.FillRectangle(New SolidBrush(Color.FromArgb(230, 20, 20, 20)), totallength, 1, Me.CreateGraphics.MeasureString(tab.Text, Font).Width + 15, Me.CreateGraphics.MeasureString("Mava is awesome", Font).Height + 10)
Dim gradient As New LinearGradientBrush(New Point(totallength, 1), New Point(totallength, Me.CreateGraphics.MeasureString("Mava is awesome", Font).Height + 8), Color.FromArgb(15, Color.White), Color.Transparent)
G.FillRectangle(gradient, totallength, 1, Me.CreateGraphics.MeasureString(tab.Text, Font).Width + 15, Me.CreateGraphics.MeasureString("Mava is awesome", Font).Height + 5)
G.DrawLine(New Pen(Color.FromArgb(60, 60, 60)), totallength + Me.CreateGraphics.MeasureString(tab.Text, Font).Width + 15, 2, totallength + Me.CreateGraphics.MeasureString(tab.Text, Font).Width + 15, Me.CreateGraphics.MeasureString("Mava is awesome", Font).Height + 8)
G.DrawLine(New Pen(Color.FromArgb(60, 60, 60)), totallength, 2, totallength, Me.CreateGraphics.MeasureString("Mava is awesome", Font).Height + 8)
G.DrawLine(New Pen(Color.FromArgb(60, 60, 60)), totallength + Me.CreateGraphics.MeasureString(tab.Text, Font).Width + 15, Me.CreateGraphics.MeasureString("Mava is awesome", Font).Height + 8, Width - 1, Me.CreateGraphics.MeasureString("Mava is awesome", Font).Height + 8)
G.DrawLine(New Pen(Color.FromArgb(60, 60, 60)), 1, Me.CreateGraphics.MeasureString("Mava is awesome", Font).Height + 8, totallength, Me.CreateGraphics.MeasureString("Mava is awesome", Font).Height + 8)
End If
Xstart(index) = totallength
Xstop(index) = totallength + Me.CreateGraphics.MeasureString(tab.Text, Font).Width + 15
G.DrawString(tab.Text, Font, Brushes.White, totallength + 8, 5)
totallength += Me.CreateGraphics.MeasureString(tab.Text, Font).Width + 15
index += 1
Next
G.DrawLine(New Pen(Color.FromArgb(90, 90, 90)), 1, 1, Width - 2, 1) 'boven
G.DrawLine(New Pen(Color.FromArgb(90, 90, 90)), 1, Height - 2, Width - 2, Height - 2) 'onder
G.DrawLine(New Pen(Color.FromArgb(90, 90, 90)), 1, 1, 1, Height - 2) 'links
G.DrawLine(New Pen(Color.FromArgb(90, 90, 90)), Width - 2, 1, Width - 2, Height - 2) 'rechts
G.DrawLine(Pens.Black, 0, 0, Width - 1, 0) 'boven
G.DrawLine(Pens.Black, 0, Height - 1, Width, Height - 1) 'onder
G.DrawLine(Pens.Black, 0, 0, 0, Height - 1) 'links
G.DrawLine(Pens.Black, Width - 1, 0, Width - 1, Height - 1) 'rechts
e.Graphics.DrawImage(B.Clone, 0, 0)
G.Dispose() : B.Dispose()
End Sub
Protected Overrides Sub OnSelectedIndexChanged(ByVal e As System.EventArgs)
MyBase.OnSelectedIndexChanged(e)
Invalidate()
End Sub
End Class
Class GhostTabControlLagFree
Inherits TabControl
Private _Forecolor As Color = Color.White
Public Property ForeColor As Color
Get
Return _Forecolor
End Get
Set(value As Color)
_Forecolor = value
End Set
End Property
Sub New()
SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.ResizeRedraw Or ControlStyles.UserPaint Or ControlStyles.DoubleBuffer, True)
DoubleBuffered = True
For Each p As TabPage In TabPages
Try
p.BackColor = Color.Black
p.BackColor = Color.Transparent
Catch ex As Exception
End Try
Next
End Sub
Protected Overrides Sub CreateHandle()
MyBase.CreateHandle()
Alignment = TabAlignment.Top
For Each p As TabPage In TabPages
Try
p.BackColor = Color.Black
p.BackColor = Color.Transparent
Catch ex As Exception
End Try
Next
End Sub
Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
Dim B As New Bitmap(Width, Height)
Dim G As Graphics = Graphics.FromImage(B)
G.Clear(Color.FromArgb(60, 60, 60))
Dim asdf As HatchBrush
asdf = New HatchBrush(HatchStyle.DarkDownwardDiagonal, Color.FromArgb(35, Color.Black), Color.FromArgb(0, Color.Gray))
G.FillRectangle(New SolidBrush(Color.FromArgb(60, 60, 60)), New Rectangle(0, 0, Width, Height))
asdf = New HatchBrush(HatchStyle.LightDownwardDiagonal, Color.DimGray)
G.FillRectangle(asdf, 0, 0, Width, Height)
G.FillRectangle(New SolidBrush(Color.FromArgb(230, 20, 20, 20)), 0, 0, Width, Height)
G.FillRectangle(Brushes.Black, New Rectangle(New Point(0, 4), New Size(Width - 2, 20)))
G.DrawRectangle(Pens.Black, New Rectangle(New Point(0, 3), New Size(Width - 1, Height - 4)))
G.DrawRectangle(New Pen(Color.FromArgb(90, 90, 90)), New Rectangle(New Point(1, 4), New Size(Width - 3, Height - 6)))
For i = 0 To TabCount - 1
If i = SelectedIndex Then
Dim x2 As Rectangle = New Rectangle(GetTabRect(i).X, GetTabRect(i).Y + 2, GetTabRect(i).Width + 2, GetTabRect(i).Height - 1)
asdf = New HatchBrush(HatchStyle.DarkDownwardDiagonal, Color.FromArgb(35, Color.Black), Color.FromArgb(0, Color.Gray))
G.FillRectangle(New SolidBrush(Color.FromArgb(60, 60, 60)), New Rectangle(GetTabRect(i).X, GetTabRect(i).Y + 3, GetTabRect(i).Width + 1, GetTabRect(i).Height - 2))
asdf = New HatchBrush(HatchStyle.LightDownwardDiagonal, Color.DimGray)
G.FillRectangle(asdf, New Rectangle(GetTabRect(i).X, GetTabRect(i).Y + 3, GetTabRect(i).Width + 1, GetTabRect(i).Height - 2))
G.FillRectangle(New SolidBrush(Color.FromArgb(230, 20, 20, 20)), New Rectangle(GetTabRect(i).X, GetTabRect(i).Y + 3, GetTabRect(i).Width + 1, GetTabRect(i).Height - 2))
Dim gradient As New LinearGradientBrush(New Rectangle(GetTabRect(i).X, GetTabRect(i).Y + 2, GetTabRect(i).Width + 2, GetTabRect(i).Height - 1), Color.FromArgb(15, Color.White), Color.Transparent, 90.0F)
G.FillRectangle(gradient, New Rectangle(GetTabRect(i).X, GetTabRect(i).Y + 2, GetTabRect(i).Width + 2, GetTabRect(i).Height - 1))
G.DrawLine(New Pen(Color.FromArgb(90, 90, 90)), New Point(GetTabRect(i).Right, 4), New Point(GetTabRect(i).Right, GetTabRect(i).Height + 3))
If Not SelectedIndex = 0 Then
G.DrawLine(New Pen(Color.FromArgb(90, 90, 90)), New Point(GetTabRect(i).X, 4), New Point(GetTabRect(i).X, GetTabRect(i).Height + 3))
G.DrawLine(New Pen(Color.FromArgb(90, 90, 90)), New Point(1, GetTabRect(i).Height + 3), New Point(GetTabRect(i).X, GetTabRect(i).Height + 3))
End If
G.DrawLine(New Pen(Color.FromArgb(90, 90, 90)), New Point(GetTabRect(i).Right, GetTabRect(i).Height + 3), New Point(Width - 2, GetTabRect(i).Height + 3))
G.DrawString(TabPages(i).Text, Font, New SolidBrush(_Forecolor), x2, New StringFormat With {.LineAlignment = StringAlignment.Center, .Alignment = StringAlignment.Center})
Else
Dim x2 As Rectangle = New Rectangle(GetTabRect(i).X, GetTabRect(i).Y + 2, GetTabRect(i).Width + 2, GetTabRect(i).Height - 1)
G.DrawString(TabPages(i).Text, Font, New SolidBrush(_Forecolor), x2, New StringFormat With {.LineAlignment = StringAlignment.Center, .Alignment = StringAlignment.Center})
End If
Next
e.Graphics.DrawImage(B.Clone, 0, 0)
G.Dispose() : B.Dispose()
End Sub
End Class
Class GhostListBoxPretty
Inherits ThemeControl154
Public WithEvents LBox As New ListBox
Private __Items As String() = {""}
Public Property Items As String()
Get
Return __Items
Invalidate()
End Get
Set(ByVal value As String())
__Items = value
LBox.Items.Clear()
Invalidate()
LBox.Items.AddRange(value)
Invalidate()
End Set
End Property
Public ReadOnly Property SelectedItem() As String
Get
Return LBox.SelectedItem
End Get
End Property
Sub New()
Controls.Add(LBox)
Size = New Size(131, 101)
LBox.BackColor = Color.FromArgb(0, 0, 0)
LBox.BorderStyle = BorderStyle.None
LBox.DrawMode = Windows.Forms.DrawMode.OwnerDrawVariable
LBox.Location = New Point(3, 3)
LBox.ForeColor = Color.White
LBox.ItemHeight = 20
LBox.Items.Clear()
LBox.IntegralHeight = False
Invalidate()
End Sub
Protected Overrides Sub ColorHook()
End Sub
Protected Overrides Sub OnResize(e As System.EventArgs)
MyBase.OnResize(e)
LBox.Width = Width - 4
LBox.Height = Height - 4
End Sub
Protected Overrides Sub PaintHook()
G.Clear(Color.Black)
G.DrawRectangle(Pens.Black, 0, 0, Width - 2, Height - 2)
G.DrawRectangle(New Pen(Color.FromArgb(90, 90, 90)), 1, 1, Width - 3, Height - 3)
LBox.Size = New Size(Width - 5, Height - 5)
End Sub
Sub DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles LBox.DrawItem
If e.Index < 0 Then Exit Sub
e.DrawBackground()
e.DrawFocusRectangle()
If InStr(e.State.ToString, "Selected,") > 0 Then
e.Graphics.FillRectangle(Brushes.Black, e.Bounds)
Dim x2 As Rectangle = New Rectangle(e.Bounds.Location, New Size(e.Bounds.Width - 1, e.Bounds.Height))
Dim x3 As Rectangle = New Rectangle(x2.Location, New Size(x2.Width, (x2.Height / 2) - 2))
Dim G1 As New LinearGradientBrush(New Point(x2.X, x2.Y), New Point(x2.X, x2.Y + x2.Height), Color.FromArgb(60, 60, 60), Color.FromArgb(50, 50, 50))
Dim H As New HatchBrush(HatchStyle.DarkDownwardDiagonal, Color.FromArgb(15, Color.Black), Color.Transparent)
e.Graphics.FillRectangle(G1, x2) : G1.Dispose()
e.Graphics.FillRectangle(New SolidBrush(Color.FromArgb(25, Color.White)), x3)
e.Graphics.FillRectangle(H, x2) : G1.Dispose()
e.Graphics.DrawString(" " & LBox.Items(e.Index).ToString(), Font, Brushes.White, e.Bounds.X, e.Bounds.Y + 2)
Else
e.Graphics.DrawString(" " & LBox.Items(e.Index).ToString(), Font, Brushes.White, e.Bounds.X, e.Bounds.Y + 2)
End If
End Sub
Sub AddRange(ByVal Items As Object())
LBox.Items.Remove("")
LBox.Items.AddRange(Items)
Invalidate()
End Sub
Sub AddItem(ByVal Item As Object)
LBox.Items.Remove("")
LBox.Items.Add(Item)
Invalidate()
End Sub
End Class
Class GhostListboxLessPretty
Inherits ListBox
Sub New()
SetStyle(ControlStyles.DoubleBuffer, True)
Font = New Font("Microsoft Sans Serif", 9)
BorderStyle = Windows.Forms.BorderStyle.None
DrawMode = Windows.Forms.DrawMode.OwnerDrawFixed
ItemHeight = 20
ForeColor = Color.DeepSkyBlue
BackColor = Color.FromArgb(7, 7, 7)
IntegralHeight = False
End Sub
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
MyBase.WndProc(m)
If m.Msg = 15 Then CustomPaint()
End Sub
Protected Overrides Sub OnDrawItem(e As System.Windows.Forms.DrawItemEventArgs)
Try
If e.Index < 0 Then Exit Sub
e.DrawBackground()
Dim rect As New Rectangle(New Point(e.Bounds.Left, e.Bounds.Top + 2), New Size(Bounds.Width, 16))
e.DrawFocusRectangle()
If InStr(e.State.ToString, "Selected,") > 0 Then
e.Graphics.FillRectangle(Brushes.Black, e.Bounds)
Dim x2 As Rectangle = New Rectangle(e.Bounds.Location, New Size(e.Bounds.Width - 1, e.Bounds.Height))
Dim x3 As Rectangle = New Rectangle(x2.Location, New Size(x2.Width, (x2.Height / 2)))
Dim G1 As New LinearGradientBrush(New Point(x2.X, x2.Y), New Point(x2.X, x2.Y + x2.Height), Color.FromArgb(60, 60, 60), Color.FromArgb(50, 50, 50))
Dim H As New HatchBrush(HatchStyle.DarkDownwardDiagonal, Color.FromArgb(15, Color.Black), Color.Transparent)
e.Graphics.FillRectangle(G1, x2) : G1.Dispose()
e.Graphics.FillRectangle(New SolidBrush(Color.FromArgb(25, Color.White)), x3)
e.Graphics.FillRectangle(H, x2) : G1.Dispose()
e.Graphics.DrawString(" " & Items(e.Index).ToString(), Font, Brushes.White, e.Bounds.X, e.Bounds.Y + 1)
Else
e.Graphics.DrawString(" " & Items(e.Index).ToString(), Font, Brushes.White, e.Bounds.X, e.Bounds.Y + 1)
End If
e.Graphics.DrawRectangle(New Pen(Color.FromArgb(0, 0, 0)), New Rectangle(1, 1, Width - 3, Height - 3))
e.Graphics.DrawRectangle(New Pen(Color.FromArgb(90, 90, 90)), New Rectangle(0, 0, Width - 1, Height - 1))
MyBase.OnDrawItem(e)
Catch ex As Exception : End Try
End Sub
Sub CustomPaint()
CreateGraphics.DrawRectangle(New Pen(Color.FromArgb(0, 0, 0)), New Rectangle(1, 1, Width - 3, Height - 3))
CreateGraphics.DrawRectangle(New Pen(Color.FromArgb(90, 90, 90)), New Rectangle(0, 0, Width - 1, Height - 1))
End Sub
End Class
Class GhostComboBox
Inherits ComboBox
Private X As Integer
Sub New()
MyBase.New()
SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.ResizeRedraw Or ControlStyles.UserPaint Or ControlStyles.DoubleBuffer, True)
DrawMode = Windows.Forms.DrawMode.OwnerDrawFixed
ItemHeight = 20
BackColor = Color.FromArgb(30, 30, 30)
DropDownStyle = ComboBoxStyle.DropDownList
End Sub
Protected Overrides Sub OnMouseMove(e As System.Windows.Forms.MouseEventArgs)
MyBase.OnMouseMove(e)
X = e.X
Invalidate()
End Sub
Protected Overrides Sub OnMouseLeave(e As System.EventArgs)
MyBase.OnMouseLeave(e)
X = -1
Invalidate()
End Sub
Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
If Not DropDownStyle = ComboBoxStyle.DropDownList Then DropDownStyle = ComboBoxStyle.DropDownList
Dim B As New Bitmap(Width, Height)
Dim G As Graphics = Graphics.FromImage(B)
G.Clear(Color.FromArgb(50, 50, 50))
Dim GradientBrush As LinearGradientBrush = New LinearGradientBrush(New Rectangle(0, 0, Width, Height / 5 * 2), Color.FromArgb(20, 0, 0, 0), Color.FromArgb(15, Color.White), 90.0F)
G.FillRectangle(GradientBrush, New Rectangle(0, 0, Width, Height / 5 * 2))
Dim hatch As HatchBrush
hatch = New HatchBrush(HatchStyle.DarkDownwardDiagonal, Color.FromArgb(20, Color.Black), Color.FromArgb(0, Color.Gray))
G.FillRectangle(hatch, 0, 0, Width, Height)
Dim S1 As Integer = G.MeasureString("...", Font).Height
If SelectedIndex <> -1 Then
G.DrawString(Items(SelectedIndex), Font, New SolidBrush(Color.White), 4, Height \ 2 - S1 \ 2)
Else
If Not Items Is Nothing And Items.Count > 0 Then
G.DrawString(Items(0), Font, New SolidBrush(Color.White), 4, Height \ 2 - S1 \ 2)
Else
G.DrawString("...", Font, New SolidBrush(Color.White), 4, Height \ 2 - S1 \ 2)
End If
End If
If MouseButtons = Windows.Forms.MouseButtons.None And X > Width - 25 Then
G.FillRectangle(New SolidBrush(Color.FromArgb(7, Color.White)), Width - 25, 1, Width - 25, Height - 3)
ElseIf MouseButtons = Windows.Forms.MouseButtons.None And X < Width - 25 And X >= 0 Then
G.FillRectangle(New SolidBrush(Color.FromArgb(7, Color.White)), 2, 1, Width - 27, Height - 3)
End If
G.DrawRectangle(Pens.Black, 0, 0, Width - 1, Height - 1)
G.DrawRectangle(New Pen(Color.FromArgb(90, 90, 90)), 1, 1, Width - 3, Height - 3)
G.DrawLine(New Pen(Color.FromArgb(90, 90, 90)), Width - 25, 1, Width - 25, Height - 3)
G.DrawLine(Pens.Black, Width - 24, 0, Width - 24, Height)
G.DrawLine(New Pen(Color.FromArgb(90, 90, 90)), Width - 23, 1, Width - 23, Height - 3)
G.FillPolygon(Brushes.Black, Triangle(New Point(Width - 14, Height \ 2), New Size(5, 3)))
G.FillPolygon(Brushes.White, Triangle(New Point(Width - 15, Height \ 2 - 1), New Size(5, 3)))
e.Graphics.DrawImage(B.Clone, 0, 0)
G.Dispose() : B.Dispose()
End Sub
Protected Overrides Sub OnDrawItem(e As DrawItemEventArgs)
If e.Index < 0 Then Exit Sub
Dim rect As New Rectangle()
rect.X = e.Bounds.X
rect.Y = e.Bounds.Y
rect.Width = e.Bounds.Width - 1
rect.Height = e.Bounds.Height - 1
e.DrawBackground()
If e.State = 785 Or e.State = 17 Then
e.Graphics.FillRectangle(Brushes.Black, e.Bounds)
Dim x2 As Rectangle = New Rectangle(e.Bounds.Location, New Size(e.Bounds.Width - 1, e.Bounds.Height))
Dim x3 As Rectangle = New Rectangle(x2.Location, New Size(x2.Width, (x2.Height / 2) - 1))
Dim G1 As New LinearGradientBrush(New Point(x2.X, x2.Y), New Point(x2.X, x2.Y + x2.Height), Color.FromArgb(60, 60, 60), Color.FromArgb(50, 50, 50))
Dim H As New HatchBrush(HatchStyle.DarkDownwardDiagonal, Color.FromArgb(15, Color.Black), Color.Transparent)
e.Graphics.FillRectangle(G1, x2) : G1.Dispose()
e.Graphics.FillRectangle(New SolidBrush(Color.FromArgb(25, Color.White)), x3)
e.Graphics.FillRectangle(H, x2) : G1.Dispose()
e.Graphics.DrawString(" " & Items(e.Index).ToString(), Font, Brushes.White, e.Bounds.X, e.Bounds.Y + 2)
Else
e.Graphics.FillRectangle(New SolidBrush(BackColor), e.Bounds)
e.Graphics.DrawString(" " & Items(e.Index).ToString(), Font, Brushes.White, e.Bounds.X, e.Bounds.Y + 2)
End If
MyBase.OnDrawItem(e)
End Sub
Public Function Triangle(ByVal Location As Point, ByVal Size As Size) As Point()
Dim ReturnPoints(0 To 3) As Point
ReturnPoints(0) = Location
ReturnPoints(1) = New Point(Location.X + Size.Width, Location.Y)
ReturnPoints(2) = New Point(Location.X + Size.Width \ 2, Location.Y + Size.Height)
ReturnPoints(3) = Location
Return ReturnPoints
End Function
Private Sub GhostComboBox_DropDownClosed(sender As Object, e As System.EventArgs) Handles Me.DropDownClosed
DropDownStyle = ComboBoxStyle.Simple
Application.DoEvents()
DropDownStyle = ComboBoxStyle.DropDownList
End Sub
Private Sub GhostCombo_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.TextChanged
Invalidate()
End Sub
End Class
<Designer("System.Windows.Forms.Design.ParentControlDesigner,System.Design", GetType(IDesigner))>
Class GhostGroupBox
Inherits ThemeControl154
Sub New()
MyBase.New()
SetStyle(ControlStyles.ResizeRedraw, True)
SetStyle(ControlStyles.ContainerControl, True)
DoubleBuffered = True
BackColor = Color.Transparent
End Sub
Protected Overrides Sub ColorHook()
End Sub
Protected Overrides Sub PaintHook()
G.Clear(Color.FromArgb(60, 60, 60))
Dim asdf As HatchBrush
asdf = New HatchBrush(HatchStyle.DarkDownwardDiagonal, Color.FromArgb(35, Color.Black), Color.FromArgb(0, Color.Gray))
G.FillRectangle(New SolidBrush(Color.FromArgb(60, 60, 60)), New Rectangle(0, 0, Width, Height))
asdf = New HatchBrush(HatchStyle.LightDownwardDiagonal, Color.DimGray)
G.FillRectangle(asdf, 0, 0, Width, Height)
G.FillRectangle(New SolidBrush(Color.FromArgb(230, 20, 20, 20)), 0, 0, Width, Height)
G.FillRectangle(New SolidBrush(Color.FromArgb(70, Color.Black)), 1, 1, Width - 2, Me.CreateGraphics.MeasureString(Text, Font).Height + 8)
G.DrawLine(New Pen(Color.FromArgb(90, 90, 90)), 1, Me.CreateGraphics.MeasureString(Text, Font).Height + 8, Width - 2, Me.CreateGraphics.MeasureString(Text, Font).Height + 8)
DrawBorders(Pens.Black)
DrawBorders(New Pen(Color.FromArgb(90, 90, 90)), 1)
G.DrawString(Text, Font, Brushes.White, 5, 5)
End Sub
End Class
<DefaultEvent("TextChanged")>
Class GhostTextBox
Inherits ThemeControl154
Private _TextAlign As HorizontalAlignment = HorizontalAlignment.Left
Property TextAlign() As HorizontalAlignment
Get
Return _TextAlign
End Get
Set(ByVal value As HorizontalAlignment)
_TextAlign = value
If Base IsNot Nothing Then
Base.TextAlign = value
End If
End Set
End Property
Private _MaxLength As Integer = 32767
Property MaxLength() As Integer
Get
Return _MaxLength
End Get
Set(ByVal value As Integer)
_MaxLength = value
If Base IsNot Nothing Then
Base.MaxLength = value
End If
End Set
End Property
Private _ReadOnly As Boolean
Property [ReadOnly]() As Boolean
Get
Return _ReadOnly
End Get
Set(ByVal value As Boolean)
_ReadOnly = value
If Base IsNot Nothing Then
Base.ReadOnly = value
End If
End Set
End Property
Private _UseSystemPasswordChar As Boolean
Property UseSystemPasswordChar() As Boolean
Get
Return _UseSystemPasswordChar
End Get
Set(ByVal value As Boolean)
_UseSystemPasswordChar = value
If Base IsNot Nothing Then
Base.UseSystemPasswordChar = value
End If
End Set
End Property
Private _Multiline As Boolean
Property Multiline() As Boolean
Get
Return _Multiline
End Get
Set(ByVal value As Boolean)
_Multiline = value
If Base IsNot Nothing Then
Base.Multiline = value
If value Then
LockHeight = 0
Base.Height = Height - 11
Else
LockHeight = Base.Height + 11
End If
End If
End Set
End Property
Overrides Property Text As String
Get
Return MyBase.Text
End Get
Set(ByVal value As String)
MyBase.Text = value
If Base IsNot Nothing Then
Base.Text = value
End If
End Set
End Property
Overrides Property Font As Font
Get
Return MyBase.Font
End Get
Set(ByVal value As Font)
MyBase.Font = value
If Base IsNot Nothing Then
Base.Font = value
Base.Location = New Point(3, 5)
Base.Width = Width - 6
If Not _Multiline Then
LockHeight = Base.Height + 11
End If
End If
End Set
End Property
Protected Overrides Sub OnCreation()
If Not Controls.Contains(Base) Then
Controls.Add(Base)
End If
End Sub
Private Base As TextBox
Sub New()
Base = New TextBox
Base.Font = Font
Base.Text = Text
Base.MaxLength = _MaxLength
Base.Multiline = _Multiline
Base.ReadOnly = _ReadOnly
Base.UseSystemPasswordChar = _UseSystemPasswordChar
Base.BorderStyle = BorderStyle.None
Base.Location = New Point(5, 5)
Base.Width = Width - 10
If _Multiline Then
Base.Height = Height - 11
Else
LockHeight = Base.Height + 11
End If
AddHandler Base.TextChanged, AddressOf OnBaseTextChanged
AddHandler Base.KeyDown, AddressOf OnBaseKeyDown
SetColor("Text", Color.White)
SetColor("Back", 0, 0, 0)
SetColor("Border1", Color.Black)
SetColor("Border2", 90, 90, 90)
End Sub
Private C1 As Color
Private P1, P2 As Pen
Protected Overrides Sub ColorHook()
C1 = GetColor("Back")
P1 = GetPen("Border1")
P2 = GetPen("Border2")
Base.ForeColor = GetColor("Text")
Base.BackColor = C1
End Sub
Protected Overrides Sub PaintHook()
G.Clear(C1)
DrawBorders(P1, 1)
DrawBorders(P2)
End Sub
Private Sub OnBaseTextChanged(ByVal s As Object, ByVal e As EventArgs)
Text = Base.Text
End Sub
Private Sub OnBaseKeyDown(ByVal s As Object, ByVal e As KeyEventArgs)
If e.Control AndAlso e.KeyCode = Keys.A Then
Base.SelectAll()
e.SuppressKeyPress = True
End If
End Sub
Protected Overrides Sub OnResize(ByVal e As EventArgs)
Base.Location = New Point(5, 5)
Base.Width = Width - 10
If _Multiline Then
Base.Height = Height - 11
End If
MyBase.OnResize(e)
End Sub
End Class
Class GhostControlBox
Inherits ThemeControl154
Private X As Integer
Dim BG, Edge As Color
Dim BEdge As Pen
Protected Overrides Sub ColorHook()
BG = GetColor("Background")
Edge = GetColor("Edge color")
BEdge = New Pen(GetColor("Button edge color"))
End Sub
Sub New()
SetColor("Background", Color.FromArgb(64, 64, 64))
SetColor("Edge color", Color.Black)
SetColor("Button edge color", Color.FromArgb(90, 90, 90))
Me.Size = New Size(71, 19)
Me.Anchor = AnchorStyles.Top Or AnchorStyles.Right
End Sub
Protected Overrides Sub OnMouseMove(e As System.Windows.Forms.MouseEventArgs)
MyBase.OnMouseMove(e)
X = e.X
Invalidate()
End Sub
Protected Overrides Sub OnClick(e As System.EventArgs)
MyBase.OnClick(e)
If X <= 22 Then
FindForm.WindowState = FormWindowState.Minimized
ElseIf X > 22 And X <= 44 Then
If FindForm.WindowState <> FormWindowState.Maximized Then FindForm.WindowState = FormWindowState.Maximized Else FindForm.WindowState = FormWindowState.Normal
ElseIf X > 44 Then
FindForm.Close()
End If
End Sub
Protected Overrides Sub PaintHook()
'Draw outer edge
G.Clear(Edge)
'Fill buttons
Dim SB As New LinearGradientBrush(New Rectangle(New Point(1, 1), New Size(Width - 2, Height - 2)), BG, Color.FromArgb(30, 30, 30), 90.0F)
G.FillRectangle(SB, New Rectangle(New Point(1, 1), New Size(Width - 2, Height - 2)))
'Draw icons
G.DrawString("0", New Font("Marlett", 8.25), Brushes.White, New Point(5, 5))
If FindForm.WindowState <> FormWindowState.Maximized Then G.DrawString("1", New Font("Marlett", 8.25), Brushes.White, New Point(27, 4)) Else G.DrawString("2", New Font("Marlett", 8.25), Brushes.White, New Point(27, 4))
G.DrawString("r", New Font("Marlett", 10), Brushes.White, New Point(49, 3))
'Glassy effect
Dim CBlend As New ColorBlend(2)
CBlend.Colors = {Color.FromArgb(100, Color.Black), Color.Transparent}
CBlend.Positions = {0, 1}
DrawGradient(CBlend, New Rectangle(New Point(1, 8), New Size(68, 8)), 90.0F)
'Draw button outlines
G.DrawRectangle(BEdge, New Rectangle(New Point(1, 1), New Size(20, 16)))
G.DrawRectangle(BEdge, New Rectangle(New Point(23, 1), New Size(20, 16)))
G.DrawRectangle(BEdge, New Rectangle(New Point(45, 1), New Size(24, 16)))
'Mouse states
Select Case State
Case MouseState.Over
If X <= 22 Then
G.FillRectangle(New SolidBrush(Color.FromArgb(20, Color.White)), New Rectangle(New Point(1, 1), New Size(21, Height - 2)))
ElseIf X > 22 And X <= 44 Then
G.FillRectangle(New SolidBrush(Color.FromArgb(20, Color.White)), New Rectangle(New Point(23, 1), New Size(21, Height - 2)))
ElseIf X > 44 Then
G.FillRectangle(New SolidBrush(Color.FromArgb(20, Color.White)), New Rectangle(New Point(45, 1), New Size(25, Height - 2)))
End If
Case MouseState.Down
If X <= 22 Then
G.FillRectangle(New SolidBrush(Color.FromArgb(20, Color.Black)), New Rectangle(New Point(1, 1), New Size(21, Height - 2)))
ElseIf X > 22 And X <= 44 Then
G.FillRectangle(New SolidBrush(Color.FromArgb(20, Color.Black)), New Rectangle(New Point(23, 1), New Size(21, Height - 2)))
ElseIf X > 44 Then
G.FillRectangle(New SolidBrush(Color.FromArgb(20, Color.Black)), New Rectangle(New Point(45, 1), New Size(25, Height - 2)))
End If
End Select
End Sub
End Class
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.CodeFixes.GenerateMember
Imports System.Composition
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateMethod
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.GenerateMethod), [Shared]>
<ExtensionOrder(After:=PredefinedCodeFixProviderNames.GenerateEvent)>
Friend Class GenerateParameterizedMemberCodeFixProvider
Inherits AbstractGenerateMemberCodeFixProvider
Friend Const BC30057 As String = "BC30057" ' error BC30057: Too many arguments to 'Public Sub Baz()'
Friend Const BC30518 As String = "BC30518" ' error BC30518: Overload resolution failed because no accessible 'sub1' can be called with these arguments.
Friend Const BC30519 As String = "BC30519" ' error BC30519: Overload resolution failed because no accessible 'sub1' can be called without a narrowing conversion.
Friend Const BC30520 As String = "BC30520" ' error BC30520: Argument matching parameter 'blah' narrows from 'A' to 'B'.
Friend Const BC30521 As String = "BC30521" ' error BC30521: Overload resolution failed because no accessible 'Baz' is most specific for these arguments.
Friend Const BC30112 As String = "BC30112" ' error BC30112: 'blah' is a namespace and cannot be used as a type/
Friend Const BC30451 As String = "BC30451" ' error BC30451: 'Foo' is not declared. It may be inaccessible due to its protection level.
Friend Const BC30455 As String = "BC30455" ' error BC30455: Argument not specified for parameter 'two' of 'Public Sub Baz(one As System.Func(Of String), two As Integer)'.
Friend Const BC30456 As String = "BC30456" ' error BC30456: 'Foo' is not a member of 'Sibling'.
Friend Const BC30401 As String = "BC30401" ' error BC30401: 'Blah' cannot implement 'Snarf' because there is no matching sub on interface 'IFoo'.
Friend Const BC30516 As String = "BC30516" ' error BC30516: Overload resolution failed because no accessible 'Blah' accepts this number of arguments.
Friend Const BC32016 As String = "BC32016" ' error BC32016: 'blah' has no parameters and its return type cannot be indexed.
Friend Const BC32045 As String = "BC32045" ' error BC32045: 'Private Sub Blah()' has no type parameters and so cannot have type arguments.
Friend Const BC32087 As String = "BC32087" ' error BC32087: Overload resolution failed because no accessible 'Blah' accepts this number of type arguments.
Friend Const BC36625 As String = "BC36625" ' error BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type.
Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String)
Get
Return ImmutableArray.Create(BC30518, BC30519, BC30520, BC30521, BC30057, BC30112, BC30451, BC30455, BC30456, BC30401, BC30516, BC32016, BC32045, BC32087, BC36625)
End Get
End Property
Protected Overrides Function GetCodeActionsAsync(document As Document, node As SyntaxNode, cancellationToken As CancellationToken) As Task(Of IEnumerable(Of CodeAction))
Dim service = document.GetLanguageService(Of IGenerateParameterizedMemberService)()
Return service.GenerateMethodAsync(document, node, cancellationToken)
End Function
Protected Overrides Function IsCandidate(node As SyntaxNode, diagnostic As Diagnostic) As Boolean
Return TypeOf node Is QualifiedNameSyntax OrElse
TypeOf node Is SimpleNameSyntax OrElse
TypeOf node Is MemberAccessExpressionSyntax OrElse
TypeOf node Is InvocationExpressionSyntax OrElse
TypeOf node Is ExpressionSyntax OrElse
TypeOf node Is IdentifierNameSyntax
End Function
Protected Overrides Function GetTargetNode(node As SyntaxNode) As SyntaxNode
Dim memberAccess = TryCast(node, MemberAccessExpressionSyntax)
If memberAccess IsNot Nothing Then
Return memberAccess.Name
End If
Dim invocationExpression = TryCast(node, InvocationExpressionSyntax)
If invocationExpression IsNot Nothing Then
Return invocationExpression.Expression
End If
Return node
End Function
End Class
End Namespace
|
'{**
' This code block adds the method `GetSampleModelDataAsync()` to the SampleDataService of your project.
'**}
'{[{
Imports System.Threading.Tasks
'}]}
Namespace Services
Public Module SampleDataService
'^^
'{[{
' TODO WTS: Remove this once your MasterDetail pages are displaying real data
Public Async Function GetSampleModelDataAsync() As Task(Of IEnumerable(Of SampleOrder))
Await Task.CompletedTask
Return AllOrders()
End Function
'}]}
End Module
End Namespace
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class FormTraHobi
Inherits DevExpress.XtraEditors.XtraForm
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(FormTraHobi))
Me.DataSetPelengkapPendaftaran = New StudentEnrollment.DataSetPelengkapPendaftaran()
Me.PelamarHobiBindingSource = New System.Windows.Forms.BindingSource(Me.components)
Me.PelamarHobiTableAdapter = New StudentEnrollment.DataSetPelengkapPendaftaranTableAdapters.pelamarHobiTableAdapter()
Me.TableAdapterManager = New StudentEnrollment.DataSetPelengkapPendaftaranTableAdapters.TableAdapterManager()
Me.PelamarHobiBindingNavigator = New System.Windows.Forms.BindingNavigator(Me.components)
Me.BindingNavigatorAddNewItem = New System.Windows.Forms.ToolStripButton()
Me.BindingNavigatorCountItem = New System.Windows.Forms.ToolStripLabel()
Me.BindingNavigatorDeleteItem = New System.Windows.Forms.ToolStripButton()
Me.BindingNavigatorMoveFirstItem = New System.Windows.Forms.ToolStripButton()
Me.BindingNavigatorMovePreviousItem = New System.Windows.Forms.ToolStripButton()
Me.BindingNavigatorSeparator = New System.Windows.Forms.ToolStripSeparator()
Me.BindingNavigatorPositionItem = New System.Windows.Forms.ToolStripTextBox()
Me.BindingNavigatorSeparator1 = New System.Windows.Forms.ToolStripSeparator()
Me.BindingNavigatorMoveNextItem = New System.Windows.Forms.ToolStripButton()
Me.BindingNavigatorMoveLastItem = New System.Windows.Forms.ToolStripButton()
Me.BindingNavigatorSeparator2 = New System.Windows.Forms.ToolStripSeparator()
Me.PelamarHobiBindingNavigatorSaveItem = New System.Windows.Forms.ToolStripButton()
Me.PelamarHobiGridControl = New DevExpress.XtraGrid.GridControl()
Me.GridView1 = New DevExpress.XtraGrid.Views.Grid.GridView()
Me.colid = New DevExpress.XtraGrid.Columns.GridColumn()
Me.colidPelamar = New DevExpress.XtraGrid.Columns.GridColumn()
Me.colidHobi = New DevExpress.XtraGrid.Columns.GridColumn()
Me.RepositoryItemLookUpEdit1 = New DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit()
Me.PelamarHobiBindingSource1 = New System.Windows.Forms.BindingSource(Me.components)
Me.MstHobiBindingSource = New System.Windows.Forms.BindingSource(Me.components)
Me.MstHobiTableAdapter = New StudentEnrollment.DataSetPelengkapPendaftaranTableAdapters.mstHobiTableAdapter()
Me.LayoutControl1 = New DevExpress.XtraLayout.LayoutControl()
Me.LayoutControlGroup1 = New DevExpress.XtraLayout.LayoutControlGroup()
Me.LayoutControlItem1 = New DevExpress.XtraLayout.LayoutControlItem()
Me.LabelControl1 = New DevExpress.XtraEditors.LabelControl()
Me.LayoutControlItem2 = New DevExpress.XtraLayout.LayoutControlItem()
CType(Me.DataSetPelengkapPendaftaran, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.PelamarHobiBindingSource, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.PelamarHobiBindingNavigator, System.ComponentModel.ISupportInitialize).BeginInit()
Me.PelamarHobiBindingNavigator.SuspendLayout()
CType(Me.PelamarHobiGridControl, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.GridView1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.RepositoryItemLookUpEdit1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.PelamarHobiBindingSource1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.MstHobiBindingSource, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.LayoutControl1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.LayoutControl1.SuspendLayout()
CType(Me.LayoutControlGroup1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.LayoutControlItem1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.LayoutControlItem2, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'DataSetPelengkapPendaftaran
'
Me.DataSetPelengkapPendaftaran.DataSetName = "DataSetPelengkapPendaftaran"
Me.DataSetPelengkapPendaftaran.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema
'
'PelamarHobiBindingSource
'
Me.PelamarHobiBindingSource.DataMember = "pelamarHobi"
Me.PelamarHobiBindingSource.DataSource = Me.DataSetPelengkapPendaftaran
'
'PelamarHobiTableAdapter
'
Me.PelamarHobiTableAdapter.ClearBeforeFill = True
'
'TableAdapterManager
'
Me.TableAdapterManager.BackupDataSetBeforeUpdate = False
Me.TableAdapterManager.pelamarHobiTableAdapter = Me.PelamarHobiTableAdapter
Me.TableAdapterManager.pendidikanNonFormalTableAdapter = Nothing
Me.TableAdapterManager.pengalamanOrganisasiTableAdapter = Nothing
Me.TableAdapterManager.prestasiTableAdapter = Nothing
Me.TableAdapterManager.traNilaiUNTableAdapter = Nothing
Me.TableAdapterManager.UpdateOrder = StudentEnrollment.DataSetPelengkapPendaftaranTableAdapters.TableAdapterManager.UpdateOrderOption.InsertUpdateDelete
'
'PelamarHobiBindingNavigator
'
Me.PelamarHobiBindingNavigator.AddNewItem = Me.BindingNavigatorAddNewItem
Me.PelamarHobiBindingNavigator.BindingSource = Me.PelamarHobiBindingSource
Me.PelamarHobiBindingNavigator.CountItem = Me.BindingNavigatorCountItem
Me.PelamarHobiBindingNavigator.DeleteItem = Me.BindingNavigatorDeleteItem
Me.PelamarHobiBindingNavigator.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.BindingNavigatorMoveFirstItem, Me.BindingNavigatorMovePreviousItem, Me.BindingNavigatorSeparator, Me.BindingNavigatorPositionItem, Me.BindingNavigatorCountItem, Me.BindingNavigatorSeparator1, Me.BindingNavigatorMoveNextItem, Me.BindingNavigatorMoveLastItem, Me.BindingNavigatorSeparator2, Me.BindingNavigatorAddNewItem, Me.BindingNavigatorDeleteItem, Me.PelamarHobiBindingNavigatorSaveItem})
Me.PelamarHobiBindingNavigator.Location = New System.Drawing.Point(0, 0)
Me.PelamarHobiBindingNavigator.MoveFirstItem = Me.BindingNavigatorMoveFirstItem
Me.PelamarHobiBindingNavigator.MoveLastItem = Me.BindingNavigatorMoveLastItem
Me.PelamarHobiBindingNavigator.MoveNextItem = Me.BindingNavigatorMoveNextItem
Me.PelamarHobiBindingNavigator.MovePreviousItem = Me.BindingNavigatorMovePreviousItem
Me.PelamarHobiBindingNavigator.Name = "PelamarHobiBindingNavigator"
Me.PelamarHobiBindingNavigator.PositionItem = Me.BindingNavigatorPositionItem
Me.PelamarHobiBindingNavigator.Size = New System.Drawing.Size(686, 25)
Me.PelamarHobiBindingNavigator.TabIndex = 0
Me.PelamarHobiBindingNavigator.Text = "BindingNavigator1"
'
'BindingNavigatorAddNewItem
'
Me.BindingNavigatorAddNewItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
Me.BindingNavigatorAddNewItem.Image = CType(resources.GetObject("BindingNavigatorAddNewItem.Image"), System.Drawing.Image)
Me.BindingNavigatorAddNewItem.Name = "BindingNavigatorAddNewItem"
Me.BindingNavigatorAddNewItem.RightToLeftAutoMirrorImage = True
Me.BindingNavigatorAddNewItem.Size = New System.Drawing.Size(23, 22)
Me.BindingNavigatorAddNewItem.Text = "Add new"
'
'BindingNavigatorCountItem
'
Me.BindingNavigatorCountItem.Name = "BindingNavigatorCountItem"
Me.BindingNavigatorCountItem.Size = New System.Drawing.Size(35, 22)
Me.BindingNavigatorCountItem.Text = "of {0}"
Me.BindingNavigatorCountItem.ToolTipText = "Total number of items"
'
'BindingNavigatorDeleteItem
'
Me.BindingNavigatorDeleteItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
Me.BindingNavigatorDeleteItem.Image = CType(resources.GetObject("BindingNavigatorDeleteItem.Image"), System.Drawing.Image)
Me.BindingNavigatorDeleteItem.Name = "BindingNavigatorDeleteItem"
Me.BindingNavigatorDeleteItem.RightToLeftAutoMirrorImage = True
Me.BindingNavigatorDeleteItem.Size = New System.Drawing.Size(23, 22)
Me.BindingNavigatorDeleteItem.Text = "Delete"
'
'BindingNavigatorMoveFirstItem
'
Me.BindingNavigatorMoveFirstItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
Me.BindingNavigatorMoveFirstItem.Image = CType(resources.GetObject("BindingNavigatorMoveFirstItem.Image"), System.Drawing.Image)
Me.BindingNavigatorMoveFirstItem.Name = "BindingNavigatorMoveFirstItem"
Me.BindingNavigatorMoveFirstItem.RightToLeftAutoMirrorImage = True
Me.BindingNavigatorMoveFirstItem.Size = New System.Drawing.Size(23, 22)
Me.BindingNavigatorMoveFirstItem.Text = "Move first"
'
'BindingNavigatorMovePreviousItem
'
Me.BindingNavigatorMovePreviousItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
Me.BindingNavigatorMovePreviousItem.Image = CType(resources.GetObject("BindingNavigatorMovePreviousItem.Image"), System.Drawing.Image)
Me.BindingNavigatorMovePreviousItem.Name = "BindingNavigatorMovePreviousItem"
Me.BindingNavigatorMovePreviousItem.RightToLeftAutoMirrorImage = True
Me.BindingNavigatorMovePreviousItem.Size = New System.Drawing.Size(23, 22)
Me.BindingNavigatorMovePreviousItem.Text = "Move previous"
'
'BindingNavigatorSeparator
'
Me.BindingNavigatorSeparator.Name = "BindingNavigatorSeparator"
Me.BindingNavigatorSeparator.Size = New System.Drawing.Size(6, 25)
'
'BindingNavigatorPositionItem
'
Me.BindingNavigatorPositionItem.AccessibleName = "Position"
Me.BindingNavigatorPositionItem.AutoSize = False
Me.BindingNavigatorPositionItem.Name = "BindingNavigatorPositionItem"
Me.BindingNavigatorPositionItem.Size = New System.Drawing.Size(50, 23)
Me.BindingNavigatorPositionItem.Text = "0"
Me.BindingNavigatorPositionItem.ToolTipText = "Current position"
'
'BindingNavigatorSeparator1
'
Me.BindingNavigatorSeparator1.Name = "BindingNavigatorSeparator1"
Me.BindingNavigatorSeparator1.Size = New System.Drawing.Size(6, 25)
'
'BindingNavigatorMoveNextItem
'
Me.BindingNavigatorMoveNextItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
Me.BindingNavigatorMoveNextItem.Image = CType(resources.GetObject("BindingNavigatorMoveNextItem.Image"), System.Drawing.Image)
Me.BindingNavigatorMoveNextItem.Name = "BindingNavigatorMoveNextItem"
Me.BindingNavigatorMoveNextItem.RightToLeftAutoMirrorImage = True
Me.BindingNavigatorMoveNextItem.Size = New System.Drawing.Size(23, 22)
Me.BindingNavigatorMoveNextItem.Text = "Move next"
'
'BindingNavigatorMoveLastItem
'
Me.BindingNavigatorMoveLastItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
Me.BindingNavigatorMoveLastItem.Image = CType(resources.GetObject("BindingNavigatorMoveLastItem.Image"), System.Drawing.Image)
Me.BindingNavigatorMoveLastItem.Name = "BindingNavigatorMoveLastItem"
Me.BindingNavigatorMoveLastItem.RightToLeftAutoMirrorImage = True
Me.BindingNavigatorMoveLastItem.Size = New System.Drawing.Size(23, 22)
Me.BindingNavigatorMoveLastItem.Text = "Move last"
'
'BindingNavigatorSeparator2
'
Me.BindingNavigatorSeparator2.Name = "BindingNavigatorSeparator2"
Me.BindingNavigatorSeparator2.Size = New System.Drawing.Size(6, 25)
'
'PelamarHobiBindingNavigatorSaveItem
'
Me.PelamarHobiBindingNavigatorSaveItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
Me.PelamarHobiBindingNavigatorSaveItem.Image = CType(resources.GetObject("PelamarHobiBindingNavigatorSaveItem.Image"), System.Drawing.Image)
Me.PelamarHobiBindingNavigatorSaveItem.Name = "PelamarHobiBindingNavigatorSaveItem"
Me.PelamarHobiBindingNavigatorSaveItem.Size = New System.Drawing.Size(23, 22)
Me.PelamarHobiBindingNavigatorSaveItem.Text = "Save Data"
'
'PelamarHobiGridControl
'
Me.PelamarHobiGridControl.DataSource = Me.PelamarHobiBindingSource
Me.PelamarHobiGridControl.Location = New System.Drawing.Point(12, 29)
Me.PelamarHobiGridControl.MainView = Me.GridView1
Me.PelamarHobiGridControl.Name = "PelamarHobiGridControl"
Me.PelamarHobiGridControl.RepositoryItems.AddRange(New DevExpress.XtraEditors.Repository.RepositoryItem() {Me.RepositoryItemLookUpEdit1})
Me.PelamarHobiGridControl.Size = New System.Drawing.Size(662, 495)
Me.PelamarHobiGridControl.TabIndex = 2
Me.PelamarHobiGridControl.ViewCollection.AddRange(New DevExpress.XtraGrid.Views.Base.BaseView() {Me.GridView1})
'
'GridView1
'
Me.GridView1.Columns.AddRange(New DevExpress.XtraGrid.Columns.GridColumn() {Me.colid, Me.colidPelamar, Me.colidHobi})
Me.GridView1.GridControl = Me.PelamarHobiGridControl
Me.GridView1.Name = "GridView1"
'
'colid
'
Me.colid.FieldName = "id"
Me.colid.Name = "colid"
'
'colidPelamar
'
Me.colidPelamar.FieldName = "idPelamar"
Me.colidPelamar.Name = "colidPelamar"
'
'colidHobi
'
Me.colidHobi.ColumnEdit = Me.RepositoryItemLookUpEdit1
Me.colidHobi.FieldName = "idHobi"
Me.colidHobi.Name = "colidHobi"
Me.colidHobi.Visible = True
Me.colidHobi.VisibleIndex = 0
'
'RepositoryItemLookUpEdit1
'
Me.RepositoryItemLookUpEdit1.AutoHeight = False
Me.RepositoryItemLookUpEdit1.Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)})
Me.RepositoryItemLookUpEdit1.DataSource = Me.MstHobiBindingSource
Me.RepositoryItemLookUpEdit1.DisplayMember = "varchar"
Me.RepositoryItemLookUpEdit1.Name = "RepositoryItemLookUpEdit1"
Me.RepositoryItemLookUpEdit1.ValueMember = "id"
'
'PelamarHobiBindingSource1
'
Me.PelamarHobiBindingSource1.DataMember = "pelamarHobi"
Me.PelamarHobiBindingSource1.DataSource = Me.DataSetPelengkapPendaftaran
'
'MstHobiBindingSource
'
Me.MstHobiBindingSource.DataMember = "mstHobi"
Me.MstHobiBindingSource.DataSource = Me.DataSetPelengkapPendaftaran
'
'MstHobiTableAdapter
'
Me.MstHobiTableAdapter.ClearBeforeFill = True
'
'LayoutControl1
'
Me.LayoutControl1.Controls.Add(Me.LabelControl1)
Me.LayoutControl1.Controls.Add(Me.PelamarHobiGridControl)
Me.LayoutControl1.Dock = System.Windows.Forms.DockStyle.Fill
Me.LayoutControl1.Location = New System.Drawing.Point(0, 25)
Me.LayoutControl1.Name = "LayoutControl1"
Me.LayoutControl1.Root = Me.LayoutControlGroup1
Me.LayoutControl1.Size = New System.Drawing.Size(686, 536)
Me.LayoutControl1.TabIndex = 3
Me.LayoutControl1.Text = "LayoutControl1"
'
'LayoutControlGroup1
'
Me.LayoutControlGroup1.EnableIndentsWithoutBorders = DevExpress.Utils.DefaultBoolean.[True]
Me.LayoutControlGroup1.GroupBordersVisible = False
Me.LayoutControlGroup1.Items.AddRange(New DevExpress.XtraLayout.BaseLayoutItem() {Me.LayoutControlItem1, Me.LayoutControlItem2})
Me.LayoutControlGroup1.Location = New System.Drawing.Point(0, 0)
Me.LayoutControlGroup1.Name = "LayoutControlGroup1"
Me.LayoutControlGroup1.Size = New System.Drawing.Size(686, 536)
Me.LayoutControlGroup1.TextVisible = False
'
'LayoutControlItem1
'
Me.LayoutControlItem1.Control = Me.PelamarHobiGridControl
Me.LayoutControlItem1.Location = New System.Drawing.Point(0, 17)
Me.LayoutControlItem1.Name = "LayoutControlItem1"
Me.LayoutControlItem1.Size = New System.Drawing.Size(666, 499)
Me.LayoutControlItem1.TextSize = New System.Drawing.Size(0, 0)
Me.LayoutControlItem1.TextVisible = False
'
'LabelControl1
'
Me.LabelControl1.Location = New System.Drawing.Point(12, 12)
Me.LabelControl1.Name = "LabelControl1"
Me.LabelControl1.Size = New System.Drawing.Size(66, 13)
Me.LabelControl1.StyleController = Me.LayoutControl1
Me.LabelControl1.TabIndex = 4
Me.LabelControl1.Text = "LabelControl1"
'
'LayoutControlItem2
'
Me.LayoutControlItem2.Control = Me.LabelControl1
Me.LayoutControlItem2.Location = New System.Drawing.Point(0, 0)
Me.LayoutControlItem2.Name = "LayoutControlItem2"
Me.LayoutControlItem2.Size = New System.Drawing.Size(666, 17)
Me.LayoutControlItem2.TextSize = New System.Drawing.Size(0, 0)
Me.LayoutControlItem2.TextVisible = False
'
'FormTraHobi
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(686, 561)
Me.Controls.Add(Me.LayoutControl1)
Me.Controls.Add(Me.PelamarHobiBindingNavigator)
Me.Name = "FormTraHobi"
Me.Text = "FormTraHobi"
CType(Me.DataSetPelengkapPendaftaran, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.PelamarHobiBindingSource, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.PelamarHobiBindingNavigator, System.ComponentModel.ISupportInitialize).EndInit()
Me.PelamarHobiBindingNavigator.ResumeLayout(False)
Me.PelamarHobiBindingNavigator.PerformLayout()
CType(Me.PelamarHobiGridControl, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.GridView1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.RepositoryItemLookUpEdit1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.PelamarHobiBindingSource1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.MstHobiBindingSource, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.LayoutControl1, System.ComponentModel.ISupportInitialize).EndInit()
Me.LayoutControl1.ResumeLayout(False)
CType(Me.LayoutControlGroup1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.LayoutControlItem1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.LayoutControlItem2, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents DataSetPelengkapPendaftaran As DataSetPelengkapPendaftaran
Friend WithEvents PelamarHobiBindingSource As BindingSource
Friend WithEvents PelamarHobiTableAdapter As DataSetPelengkapPendaftaranTableAdapters.pelamarHobiTableAdapter
Friend WithEvents TableAdapterManager As DataSetPelengkapPendaftaranTableAdapters.TableAdapterManager
Friend WithEvents PelamarHobiBindingNavigator As BindingNavigator
Friend WithEvents BindingNavigatorAddNewItem As ToolStripButton
Friend WithEvents BindingNavigatorCountItem As ToolStripLabel
Friend WithEvents BindingNavigatorDeleteItem As ToolStripButton
Friend WithEvents BindingNavigatorMoveFirstItem As ToolStripButton
Friend WithEvents BindingNavigatorMovePreviousItem As ToolStripButton
Friend WithEvents BindingNavigatorSeparator As ToolStripSeparator
Friend WithEvents BindingNavigatorPositionItem As ToolStripTextBox
Friend WithEvents BindingNavigatorSeparator1 As ToolStripSeparator
Friend WithEvents BindingNavigatorMoveNextItem As ToolStripButton
Friend WithEvents BindingNavigatorMoveLastItem As ToolStripButton
Friend WithEvents BindingNavigatorSeparator2 As ToolStripSeparator
Friend WithEvents PelamarHobiBindingNavigatorSaveItem As ToolStripButton
Friend WithEvents PelamarHobiGridControl As XtraGrid.GridControl
Friend WithEvents GridView1 As XtraGrid.Views.Grid.GridView
Friend WithEvents colid As XtraGrid.Columns.GridColumn
Friend WithEvents colidPelamar As XtraGrid.Columns.GridColumn
Friend WithEvents colidHobi As XtraGrid.Columns.GridColumn
Friend WithEvents RepositoryItemLookUpEdit1 As Repository.RepositoryItemLookUpEdit
Friend WithEvents PelamarHobiBindingSource1 As BindingSource
Friend WithEvents MstHobiBindingSource As BindingSource
Friend WithEvents MstHobiTableAdapter As DataSetPelengkapPendaftaranTableAdapters.mstHobiTableAdapter
Friend WithEvents LayoutControl1 As XtraLayout.LayoutControl
Friend WithEvents LabelControl1 As LabelControl
Friend WithEvents LayoutControlGroup1 As XtraLayout.LayoutControlGroup
Friend WithEvents LayoutControlItem1 As XtraLayout.LayoutControlItem
Friend WithEvents LayoutControlItem2 As XtraLayout.LayoutControlItem
End Class
|
Imports System
Imports System.Collections.Generic
Imports INDArray = org.nd4j.linalg.api.ndarray.INDArray
Imports org.nd4j.linalg.learning
Imports ISchedule = org.nd4j.linalg.schedule.ISchedule
Imports JsonAutoDetect = org.nd4j.shade.jackson.annotation.JsonAutoDetect
Imports JsonInclude = org.nd4j.shade.jackson.annotation.JsonInclude
Imports JsonTypeInfo = org.nd4j.shade.jackson.annotation.JsonTypeInfo
'
' * ******************************************************************************
' * *
' * *
' * * This program and the accompanying materials are made available under the
' * * terms of the Apache License, Version 2.0 which is available at
' * * https://www.apache.org/licenses/LICENSE-2.0.
' * *
' * * See the NOTICE file distributed with this work for additional
' * * information regarding copyright ownership.
' * * 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.
' * *
' * * SPDX-License-Identifier: Apache-2.0
' * *****************************************************************************
'
Namespace org.nd4j.linalg.learning.config
'JAVA TO VB CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
'ORIGINAL LINE: @JsonInclude(JsonInclude.Include.NON_NULL) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE) @JsonTypeInfo(use = JsonTypeInfo.Id.@CLASS, include = JsonTypeInfo.@As.@PROPERTY, property = "@class") public interface IUpdater extends java.io.Serializable, Cloneable
Public Interface IUpdater
Inherits ICloneable
''' <summary>
''' Determine the updater state size for the given number of parameters. Usually a integer multiple (0,1 or 2)
''' times the number of parameters in a layer.
''' </summary>
''' <param name="numParams"> Number of parameters </param>
''' <returns> Updater state size for the given number of parameters </returns>
Function stateSize(ByVal numParams As Long) As Long
''' <summary>
''' Create a new gradient updater
''' </summary>
''' <param name="viewArray"> The updater state size view away </param>
''' <param name="initializeViewArray"> If true: initialise the updater state
''' @return </param>
Function instantiate(ByVal viewArray As INDArray, ByVal initializeViewArray As Boolean) As GradientUpdater
Function instantiate(ByVal updaterState As IDictionary(Of String, INDArray), ByVal initializeStateArrays As Boolean) As GradientUpdater
Function Equals(ByVal updater As Object) As Boolean
''' <summary>
''' Clone the updater
''' </summary>
Function clone() As IUpdater
''' <summary>
''' Get the learning rate - if any - for the updater, at the specified iteration and epoch.
''' Note that if no learning rate is applicable (AdaDelta, NoOp updaters etc) then Double.NaN should
''' be return
''' </summary>
''' <param name="iteration"> Iteration at which to get the learning rate </param>
''' <param name="epoch"> Epoch at which to get the learning rate </param>
''' <returns> Learning rate, or Double.NaN if no learning rate is applicable for this updater </returns>
Function getLearningRate(ByVal iteration As Integer, ByVal epoch As Integer) As Double
''' <returns> True if the updater has a learning rate hyperparameter, false otherwise </returns>
Function hasLearningRate() As Boolean
''' <summary>
''' Set the learning rate and schedule. Note: may throw an exception if <seealso cref="hasLearningRate()"/> returns false. </summary>
''' <param name="lr"> Learning rate to set (typically not used if LR schedule is non-null) </param>
''' <param name="lrSchedule"> Learning rate schedule to set (may be null) </param>
Sub setLrAndSchedule(ByVal lr As Double, ByVal lrSchedule As ISchedule)
End Interface
End Namespace |
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.1
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.AsyncDataPortalWinTest.Form1
End Sub
End Class
End Namespace
|
'
' News Articles for DotNetNuke - http://www.dotnetnuke.com
' Copyright (c) 2002-2008
' by Ventrian ( [email protected] ) ( http://www.ventrian.com )
'
Imports System.IO
Imports System.Xml
Imports DotNetNuke.Application
Imports DotNetNuke.Common
Imports DotNetNuke.Common.Utilities
Imports DotNetNuke.Entities.Host
Imports DotNetNuke.Entities.Portals
Imports DotNetNuke.Services.Cache
Imports DotNetNuke.Services.Localization
Namespace Ventrian.NewsArticles.Components.Utility
Public Class LocalizationUtil
#Region " Private Members "
Private Shared _strUseLanguageInUrlDefault As String = Null.NullString
#End Region
#Region " Public Methods "
'Private Shared Function GetHostSettingAsBoolean(ByVal key As String, ByVal defaultValue As Boolean) As Boolean
' Dim retValue As Boolean = defaultValue
' Try
' Dim setting As String = DotNetNuke.Entities.Host.HostSettings.GetHostSetting(key)
' If String.IsNullOrEmpty(setting) = False Then
' retValue = (setting.ToUpperInvariant().StartsWith("Y") OrElse setting.ToUpperInvariant = "TRUE")
' End If
' Catch ex As Exception
' 'we just want to trap the error as we may not be installed so there will be no Settings
' End Try
' Return retValue
'End Function
'Private Shared Function GetPortalSettingAsBoolean(ByVal portalID As Integer, ByVal key As String, ByVal defaultValue As Boolean) As Boolean
' Dim retValue As Boolean = defaultValue
' Try
' Dim setting As String = DotNetNuke.Entities.Portals.PortalSettings.GetSiteSetting(portalID, key)
' If String.IsNullOrEmpty(setting) = False Then
' retValue = (setting.ToUpperInvariant().StartsWith("Y") OrElse setting.ToUpperInvariant = "TRUE")
' End If
' Catch ex As Exception
' 'we just want to trap the error as we may not be installed so there will be no Settings
' End Try
' Return retValue
'End Function
Public Shared Function UseLanguageInUrl() As Boolean
If (Host.EnableUrlLanguage) Then
Return Host.EnableUrlLanguage
End If
If (PortalSettings.Current.EnableUrlLanguage) Then
Return PortalSettings.Current.EnableUrlLanguage
End If
If (File.Exists(HttpContext.Current.Server.MapPath(Localization.ApplicationResourceDirectory + "/Locales.xml")) = False) Then
Return Host.EnableUrlLanguage
End If
Dim cacheKey As String = ""
Dim objPortalSettings As PortalSettings = PortalController.Instance.GetCurrentPortalSettings()
Dim useLanguage As Boolean = False
' check default host setting
If String.IsNullOrEmpty(_strUseLanguageInUrlDefault) Then
Dim xmldoc As New XmlDocument
Dim languageInUrl As XmlNode
xmldoc.Load(HttpContext.Current.Server.MapPath(Localization.ApplicationResourceDirectory + "/Locales.xml"))
languageInUrl = xmldoc.SelectSingleNode("//root/languageInUrl")
If Not languageInUrl Is Nothing Then
_strUseLanguageInUrlDefault = languageInUrl.Attributes("enabled").InnerText
Else
Try
Dim version As Integer = Convert.ToInt32(DotNetNukeContext.Current.Application.Version.ToString().Replace(".", ""))
If (version >= 490) Then
_strUseLanguageInUrlDefault = "true"
Else
_strUseLanguageInUrlDefault = "false"
End If
Catch
_strUseLanguageInUrlDefault = "false"
End Try
End If
End If
useLanguage = Boolean.Parse(_strUseLanguageInUrlDefault)
' check current portal setting
Dim FilePath As String = HttpContext.Current.Server.MapPath(Localization.ApplicationResourceDirectory + "/Locales.Portal-" + objPortalSettings.PortalId.ToString + ".xml")
If File.Exists(FilePath) Then
cacheKey = "dotnetnuke-uselanguageinurl" & objPortalSettings.PortalId.ToString
Try
Dim o As Object = DataCache.GetCache(cacheKey)
If o Is Nothing Then
Dim xmlLocales As New XmlDocument
Dim bXmlLoaded As Boolean = False
xmlLocales.Load(FilePath)
bXmlLoaded = True
Dim d As New XmlDocument
d.Load(FilePath)
If bXmlLoaded AndAlso Not xmlLocales.SelectSingleNode("//locales/languageInUrl") Is Nothing Then
useLanguage = Boolean.Parse(xmlLocales.SelectSingleNode("//locales/languageInUrl").Attributes("enabled").InnerText)
End If
If Host.PerformanceSetting <> Globals.PerformanceSettings.NoCaching Then
Dim dp As New DNNCacheDependency(FilePath)
DataCache.SetCache(cacheKey, useLanguage, dp)
End If
Else
useLanguage = CType(o, Boolean)
End If
Catch ex As Exception
End Try
Return useLanguage
Else
Return useLanguage
End If
End Function
#End Region
End Class
End Namespace
|
Public Class ThisWorkbook
Private Sub ThisWorkbook_Startup() Handles Me.Startup
End Sub
Private Sub ThisWorkbook_Shutdown() Handles Me.Shutdown
End Sub
End Class
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class home
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(home))
Me.lg = New System.Windows.Forms.PictureBox()
Me.Timer1 = New System.Windows.Forms.Timer(Me.components)
Me.Label1 = New System.Windows.Forms.Label()
Me.b1 = New System.Windows.Forms.PictureBox()
Me.b3 = New System.Windows.Forms.PictureBox()
Me.b4 = New System.Windows.Forms.PictureBox()
Me.b2 = New System.Windows.Forms.PictureBox()
CType(Me.lg, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.b1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.b3, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.b4, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.b2, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'lg
'
Me.lg.BackColor = System.Drawing.Color.Transparent
Me.lg.Location = New System.Drawing.Point(12, 12)
Me.lg.Name = "lg"
Me.lg.Size = New System.Drawing.Size(273, 243)
Me.lg.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
Me.lg.TabIndex = 1
Me.lg.TabStop = False
'
'Timer1
'
Me.Timer1.Enabled = True
Me.Timer1.Interval = 5000
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(957, 707)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(13, 13)
Me.Label1.TabIndex = 2
Me.Label1.Text = "0"
'
'home
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(1008, 729)
Me.Controls.Add(Me.b2)
Me.Controls.Add(Me.b4)
Me.Controls.Add(Me.b3)
Me.Controls.Add(Me.b1)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.lg)
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.MaximizeBox = False
Me.Name = "home"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "Check Knowledge"
CType(Me.lg, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.b1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.b3, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.b4, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.b2, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents lg As System.Windows.Forms.PictureBox
Friend WithEvents Timer1 As System.Windows.Forms.Timer
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents b1 As System.Windows.Forms.PictureBox
Friend WithEvents b3 As System.Windows.Forms.PictureBox
Friend WithEvents b4 As System.Windows.Forms.PictureBox
Friend WithEvents b2 As System.Windows.Forms.PictureBox
End Class
|
Imports CefSharp
Imports CefSharp.Wpf
Public Class Navegador
Dim pwd As String
Dim usr As String
Public Sub SetAux(l As String())
pwd = l(1)
usr = l(0)
End Sub
Private Sub BtnAtras_Click(sender As Object, e As RoutedEventArgs) Handles BtnAtras.Click
Dim WinAdminMenu As New MenuAdministrador
Dim winMenu As New Menu
If (My.Settings.USER_ROLE.ToString = "administrador ") Then
WinAdminMenu.Show()
Close()
ElseIf (My.Settings.USER_ROLE.ToString = "transportista ") Then
winMenu.Show()
Close()
End If
End Sub
Private Sub Browser_FrameLoadEnd(sender As Object, e As FrameLoadEndEventArgs)
Browser.SetZoomLevel(-5.0)
Browser.ExecuteScriptAsync("document.getElementById('identifierId').value=""" & usr & """")
Browser.ExecuteScriptAsync("document.getElementById('identifierNext').click()")
End Sub
Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
TxtBoxContraseña.Text = pwd
End Sub
End Class
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.18213
'
' 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("Login_Server.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
|
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("MeuOS browser")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("HP Inc.")>
<Assembly: AssemblyProduct("MeuOS browser")>
<Assembly: AssemblyCopyright("Copyright © HP Inc. 2021")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("f50d2a61-eb85-4c68-9b8d-b00619c89cdd")>
' 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")>
|
' Copyright 2018 Google LLC
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201806
Namespace Google.Api.Ads.AdWords.Examples.VB.v201806
''' <summary>
''' This code example illustrates how to retrieve all the ad groups for a
''' campaign. To create an ad group, run AddAdGroup.vb.
''' </summary>
Public Class GetAdGroups
Inherits ExampleBase
''' <summary>
''' Main method, to run this code example as a standalone application.
''' </summary>
''' <param name="args">The command line arguments.</param>
Public Shared Sub Main(ByVal args As String())
Dim codeExample As New GetAdGroups
Console.WriteLine(codeExample.Description)
Try
Dim campaignId As Long = Long.Parse("INSERT_CAMPAIGN_ID_HERE")
codeExample.Run(New AdWordsUser, campaignId)
Catch e As Exception
Console.WriteLine("An exception occurred while running this code example. {0}",
ExampleUtilities.FormatException(e))
End Try
End Sub
''' <summary>
''' Returns a description about the code example.
''' </summary>
Public Overrides ReadOnly Property Description() As String
Get
Return "This code example illustrates how to retrieve all the ad groups for a " &
"campaign. To create an ad group, run AddAdGroup.vb."
End Get
End Property
''' <summary>
''' Runs the code example.
''' </summary>
''' <param name="user">The AdWords user.</param>
''' <param name="campaignId">Id of the campaign for which ad groups are
''' retrieved.</param>
Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long)
Using adGroupService As AdGroupService = CType(user.GetService(
AdWordsService.v201806.AdGroupService), AdGroupService)
' Create the selector.
Dim selector As New Selector
selector.fields = New String() {
AdGroup.Fields.Id, AdGroup.Fields.Name
}
selector.predicates = New Predicate() {
Predicate.Equals(AdGroup.Fields.CampaignId, campaignId)
}
selector.ordering = New OrderBy() {OrderBy.Asc(AdGroup.Fields.Name)}
selector.paging = Paging.Default
Dim page As New AdGroupPage
Try
Do
' Get the ad groups.
page = adGroupService.get(selector)
' Display the results.
If ((Not page Is Nothing) AndAlso (Not page.entries Is Nothing)) Then
Dim i As Integer = selector.paging.startIndex
For Each adGroup As AdGroup In page.entries
Console.WriteLine("{0}) Ad group name is ""{1}"" and id is ""{2}"".", i + 1,
adGroup.name, adGroup.id)
i += 1
Next
End If
selector.paging.IncreaseOffset()
Loop While (selector.paging.startIndex < page.totalNumEntries)
Console.WriteLine("Number of ad groups found: {0}", page.totalNumEntries)
Catch e As Exception
Throw New System.ApplicationException("Failed to retrieve ad group(s).", e)
End Try
End Using
End Sub
End Class
End Namespace
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class VetAggregateSummaryActionDetail
Inherits bv.common.win.BaseDetailForm
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
AggregateCaseDbService = New VetAggregateSummaryAction_DB
DbService = AggregateCaseDbService
PermissionObject = eidss.model.Enums.EIDSSPermissionObject.VetCase
AggregateSummaryHeader1.CaseType = model.Enums.AggregateCaseType.VetAggregateAction
'AggregateSummaryHeader1.UseParentDataset = True
'RegisterChildObject(AggregateSummaryHeader1, RelatedPostOrder.SkipPost)
'RegisterChildObject(fgDiagnosticAction, RelatedPostOrder.PostLast)
'RegisterChildObject(fgProphylacticAction, RelatedPostOrder.PostLast)
'RegisterChildObject(fgSanitaryAction, RelatedPostOrder.PostLast)
'minYear = 1900
End Sub
'Public Sub New(ByVal _MinYear As Integer)
' MyBase.New()
' 'This call is required by the Windows Form Designer.
' InitializeComponent()
' 'Add any initialization after the InitializeComponent() call
' AggregateCaseDbService = New VetAggregateSummaryAction_DB
' DbService = AggregateCaseDbService
' PermissionObject = eidss.model.Enums.EIDSSPermissionObject.VetCase
' RegisterChildObject(fgDiagnosticAction, RelatedPostOrder.PostLast)
' RegisterChildObject(fgProphylacticAction, RelatedPostOrder.PostLast)
' RegisterChildObject(fgSanitaryAction, RelatedPostOrder.PostLast)
' If (_MinYear) > 0 AndAlso (_MinYear <= Date.Today.Year) Then
' minYear = _MinYear
' Else
' minYear = 1900
' End If
'End Sub
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(VetAggregateSummaryActionDetail))
Me.btnRefresh = New DevExpress.XtraEditors.SimpleButton()
Me.btnClose = New DevExpress.XtraEditors.SimpleButton()
Me.btnViewDetailForm = New DevExpress.XtraEditors.SimpleButton()
Me.btnShowSummary = New DevExpress.XtraEditors.SimpleButton()
Me.PopUpButton1 = New bv.common.win.PopUpButton()
Me.cmRep = New System.Windows.Forms.ContextMenu()
Me.MenuItem1 = New System.Windows.Forms.MenuItem()
Me.AggregateSummaryHeader1 = New EIDSS.winclient.AggregateCase.AggregateSummaryHeader()
Me.xtcDetailInfo = New DevExpress.XtraTab.XtraTabControl()
Me.xtpDiagnosticAction = New DevExpress.XtraTab.XtraTabPage()
Me.fgDiagnosticAction = New EIDSS.FlexibleForms.FFPresenter()
Me.lbNoDiagnosticActionMatrix = New DevExpress.XtraEditors.LabelControl()
Me.xtpProphilacticAction = New DevExpress.XtraTab.XtraTabPage()
Me.fgProphylacticAction = New EIDSS.FlexibleForms.FFPresenter()
Me.lbNoProphylacticActionMatrix = New DevExpress.XtraEditors.LabelControl()
Me.xtpSanitaryAction = New DevExpress.XtraTab.XtraTabPage()
Me.fgSanitaryAction = New EIDSS.FlexibleForms.FFPresenter()
Me.lbNoSanitaryActionMatrix = New DevExpress.XtraEditors.LabelControl()
CType(Me.xtcDetailInfo, System.ComponentModel.ISupportInitialize).BeginInit()
Me.xtcDetailInfo.SuspendLayout()
Me.xtpDiagnosticAction.SuspendLayout()
Me.xtpProphilacticAction.SuspendLayout()
Me.xtpSanitaryAction.SuspendLayout()
Me.SuspendLayout()
'
'btnRefresh
'
resources.ApplyResources(Me.btnRefresh, "btnRefresh")
Me.btnRefresh.Image = Global.EIDSS.My.Resources.Resources.refresh
Me.btnRefresh.Name = "btnRefresh"
'
'btnClose
'
resources.ApplyResources(Me.btnClose, "btnClose")
Me.btnClose.Image = Global.EIDSS.My.Resources.Resources.Close
Me.btnClose.Name = "btnClose"
'
'btnViewDetailForm
'
resources.ApplyResources(Me.btnViewDetailForm, "btnViewDetailForm")
Me.btnViewDetailForm.Image = Global.EIDSS.My.Resources.Resources.View1
Me.btnViewDetailForm.Name = "btnViewDetailForm"
'
'btnShowSummary
'
resources.ApplyResources(Me.btnShowSummary, "btnShowSummary")
Me.btnShowSummary.Name = "btnShowSummary"
'
'PopUpButton1
'
resources.ApplyResources(Me.PopUpButton1, "PopUpButton1")
Me.PopUpButton1.ButtonType = bv.common.win.PopUpButton.PopUpButtonStyles.Reports
Me.PopUpButton1.Name = "PopUpButton1"
Me.PopUpButton1.PopUpMenu = Me.cmRep
Me.PopUpButton1.Tag = "{Immovable}{AlwaysEditable}"
'
'cmRep
'
Me.cmRep.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuItem1})
'
'MenuItem1
'
Me.MenuItem1.Index = 0
resources.ApplyResources(Me.MenuItem1, "MenuItem1")
'
'AggregateSummaryHeader1
'
resources.ApplyResources(Me.AggregateSummaryHeader1, "AggregateSummaryHeader1")
Me.AggregateSummaryHeader1.CaseType = EIDSS.model.Enums.AggregateCaseType.VetAggregateAction
Me.AggregateSummaryHeader1.Name = "AggregateSummaryHeader1"
'
'xtcDetailInfo
'
resources.ApplyResources(Me.xtcDetailInfo, "xtcDetailInfo")
Me.xtcDetailInfo.Name = "xtcDetailInfo"
Me.xtcDetailInfo.SelectedTabPage = Me.xtpDiagnosticAction
Me.xtcDetailInfo.TabPages.AddRange(New DevExpress.XtraTab.XtraTabPage() {Me.xtpDiagnosticAction, Me.xtpProphilacticAction, Me.xtpSanitaryAction})
'
'xtpDiagnosticAction
'
Me.xtpDiagnosticAction.Controls.Add(Me.fgDiagnosticAction)
Me.xtpDiagnosticAction.Controls.Add(Me.lbNoDiagnosticActionMatrix)
Me.xtpDiagnosticAction.Name = "xtpDiagnosticAction"
resources.ApplyResources(Me.xtpDiagnosticAction, "xtpDiagnosticAction")
'
'fgDiagnosticAction
'
resources.ApplyResources(Me.fgDiagnosticAction, "fgDiagnosticAction")
Me.fgDiagnosticAction.DefaultFormState = System.Windows.Forms.FormWindowState.Normal
Me.fgDiagnosticAction.DynamicParameterEnabled = False
Me.fgDiagnosticAction.FormID = Nothing
Me.fgDiagnosticAction.HelpTopicID = Nothing
Me.fgDiagnosticAction.IsStatusReadOnly = False
Me.fgDiagnosticAction.KeyFieldName = Nothing
Me.fgDiagnosticAction.MultiSelect = False
Me.fgDiagnosticAction.Name = "fgDiagnosticAction"
Me.fgDiagnosticAction.ObjectName = Nothing
Me.fgDiagnosticAction.SectionTableCaptionsIsVisible = True
Me.fgDiagnosticAction.Status = bv.common.win.FormStatus.Draft
Me.fgDiagnosticAction.TableName = Nothing
'
'lbNoDiagnosticActionMatrix
'
Me.lbNoDiagnosticActionMatrix.Appearance.ForeColor = CType(resources.GetObject("lbNoDiagnosticActionMatrix.Appearance.ForeColor"), System.Drawing.Color)
Me.lbNoDiagnosticActionMatrix.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center
Me.lbNoDiagnosticActionMatrix.Appearance.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap
resources.ApplyResources(Me.lbNoDiagnosticActionMatrix, "lbNoDiagnosticActionMatrix")
Me.lbNoDiagnosticActionMatrix.Name = "lbNoDiagnosticActionMatrix"
'
'xtpProphilacticAction
'
Me.xtpProphilacticAction.Controls.Add(Me.fgProphylacticAction)
Me.xtpProphilacticAction.Controls.Add(Me.lbNoProphylacticActionMatrix)
Me.xtpProphilacticAction.Name = "xtpProphilacticAction"
resources.ApplyResources(Me.xtpProphilacticAction, "xtpProphilacticAction")
'
'fgProphylacticAction
'
resources.ApplyResources(Me.fgProphylacticAction, "fgProphylacticAction")
Me.fgProphylacticAction.DefaultFormState = System.Windows.Forms.FormWindowState.Normal
Me.fgProphylacticAction.DynamicParameterEnabled = False
Me.fgProphylacticAction.FormID = Nothing
Me.fgProphylacticAction.HelpTopicID = Nothing
Me.fgProphylacticAction.IsStatusReadOnly = False
Me.fgProphylacticAction.KeyFieldName = Nothing
Me.fgProphylacticAction.MultiSelect = False
Me.fgProphylacticAction.Name = "fgProphylacticAction"
Me.fgProphylacticAction.ObjectName = Nothing
Me.fgProphylacticAction.SectionTableCaptionsIsVisible = True
Me.fgProphylacticAction.Status = bv.common.win.FormStatus.Draft
Me.fgProphylacticAction.TableName = Nothing
'
'lbNoProphylacticActionMatrix
'
Me.lbNoProphylacticActionMatrix.Appearance.ForeColor = CType(resources.GetObject("lbNoProphylacticActionMatrix.Appearance.ForeColor"), System.Drawing.Color)
Me.lbNoProphylacticActionMatrix.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center
Me.lbNoProphylacticActionMatrix.Appearance.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap
resources.ApplyResources(Me.lbNoProphylacticActionMatrix, "lbNoProphylacticActionMatrix")
Me.lbNoProphylacticActionMatrix.Name = "lbNoProphylacticActionMatrix"
'
'xtpSanitaryAction
'
Me.xtpSanitaryAction.Controls.Add(Me.fgSanitaryAction)
Me.xtpSanitaryAction.Controls.Add(Me.lbNoSanitaryActionMatrix)
Me.xtpSanitaryAction.Name = "xtpSanitaryAction"
resources.ApplyResources(Me.xtpSanitaryAction, "xtpSanitaryAction")
'
'fgSanitaryAction
'
resources.ApplyResources(Me.fgSanitaryAction, "fgSanitaryAction")
Me.fgSanitaryAction.DefaultFormState = System.Windows.Forms.FormWindowState.Normal
Me.fgSanitaryAction.DynamicParameterEnabled = False
Me.fgSanitaryAction.FormID = Nothing
Me.fgSanitaryAction.HelpTopicID = Nothing
Me.fgSanitaryAction.IsStatusReadOnly = False
Me.fgSanitaryAction.KeyFieldName = Nothing
Me.fgSanitaryAction.MultiSelect = False
Me.fgSanitaryAction.Name = "fgSanitaryAction"
Me.fgSanitaryAction.ObjectName = Nothing
Me.fgSanitaryAction.SectionTableCaptionsIsVisible = True
Me.fgSanitaryAction.Status = bv.common.win.FormStatus.Draft
Me.fgSanitaryAction.TableName = Nothing
'
'lbNoSanitaryActionMatrix
'
Me.lbNoSanitaryActionMatrix.Appearance.ForeColor = CType(resources.GetObject("lbNoSanitaryActionMatrix.Appearance.ForeColor"), System.Drawing.Color)
Me.lbNoSanitaryActionMatrix.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center
Me.lbNoSanitaryActionMatrix.Appearance.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap
resources.ApplyResources(Me.lbNoSanitaryActionMatrix, "lbNoSanitaryActionMatrix")
Me.lbNoSanitaryActionMatrix.Name = "lbNoSanitaryActionMatrix"
'
'VetAggregateSummaryActionDetail
'
resources.ApplyResources(Me, "$this")
Me.Controls.Add(Me.xtcDetailInfo)
Me.Controls.Add(Me.AggregateSummaryHeader1)
Me.Controls.Add(Me.PopUpButton1)
Me.Controls.Add(Me.btnClose)
Me.Controls.Add(Me.btnViewDetailForm)
Me.Controls.Add(Me.btnShowSummary)
Me.Controls.Add(Me.btnRefresh)
Me.FormID = "V14"
Me.HelpTopicID = "VetAggregateActionSummary"
Me.KeyFieldName = "idfAggrCase"
Me.LeftIcon = Global.EIDSS.My.Resources.Resources.Vet_Aggregate_Actions_Summary__large__06_
Me.Name = "VetAggregateSummaryActionDetail"
Me.ObjectName = "VetAggregateSummaryAction"
Me.ShowCancelButton = False
Me.ShowDeleteButton = False
Me.ShowOkButton = False
Me.ShowSaveButton = False
Me.Sizable = True
Me.TableName = "AggregateHeader"
Me.Controls.SetChildIndex(Me.btnRefresh, 0)
Me.Controls.SetChildIndex(Me.btnShowSummary, 0)
Me.Controls.SetChildIndex(Me.btnViewDetailForm, 0)
Me.Controls.SetChildIndex(Me.btnClose, 0)
Me.Controls.SetChildIndex(Me.PopUpButton1, 0)
Me.Controls.SetChildIndex(Me.AggregateSummaryHeader1, 0)
Me.Controls.SetChildIndex(Me.xtcDetailInfo, 0)
CType(Me.xtcDetailInfo, System.ComponentModel.ISupportInitialize).EndInit()
Me.xtcDetailInfo.ResumeLayout(False)
Me.xtpDiagnosticAction.ResumeLayout(False)
Me.xtpProphilacticAction.ResumeLayout(False)
Me.xtpSanitaryAction.ResumeLayout(False)
Me.ResumeLayout(False)
End Sub
Friend WithEvents btnRefresh As DevExpress.XtraEditors.SimpleButton
Friend WithEvents btnClose As DevExpress.XtraEditors.SimpleButton
Friend WithEvents btnViewDetailForm As DevExpress.XtraEditors.SimpleButton
Friend WithEvents btnShowSummary As DevExpress.XtraEditors.SimpleButton
Friend WithEvents PopUpButton1 As bv.common.win.PopUpButton
Friend WithEvents cmRep As System.Windows.Forms.ContextMenu
Friend WithEvents MenuItem1 As System.Windows.Forms.MenuItem
Friend WithEvents AggregateSummaryHeader1 As EIDSS.winclient.AggregateCase.AggregateSummaryHeader
Friend WithEvents xtcDetailInfo As DevExpress.XtraTab.XtraTabControl
Friend WithEvents xtpDiagnosticAction As DevExpress.XtraTab.XtraTabPage
Friend WithEvents fgDiagnosticAction As EIDSS.FlexibleForms.FFPresenter
Friend WithEvents lbNoDiagnosticActionMatrix As DevExpress.XtraEditors.LabelControl
Friend WithEvents xtpProphilacticAction As DevExpress.XtraTab.XtraTabPage
Friend WithEvents fgProphylacticAction As EIDSS.FlexibleForms.FFPresenter
Friend WithEvents lbNoProphylacticActionMatrix As DevExpress.XtraEditors.LabelControl
Friend WithEvents xtpSanitaryAction As DevExpress.XtraTab.XtraTabPage
Friend WithEvents fgSanitaryAction As EIDSS.FlexibleForms.FFPresenter
Friend WithEvents lbNoSanitaryActionMatrix As DevExpress.XtraEditors.LabelControl
End Class
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System
Imports System.Globalization
Imports System.Text
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class ImplementsTests
Inherits BasicTestBase
<Fact>
Public Sub SimpleImplementation()
CompileAndVerify(
<compilation name="SimpleImplementation">
<file name="a.vb">
Option Strict On
Interface IFoo
Sub SayItWithStyle(ByVal style As String)
Sub SayItWithStyle(ByVal answer As Integer)
End Interface
Class Foo
Implements IFoo
Public Sub X(ByVal style As String) Implements IFoo.SayItWithStyle
System.Console.WriteLine("I said: {0}", style)
End Sub
Public Sub Y(ByVal a As Integer) Implements IFoo.SayItWithStyle
System.Console.WriteLine("The answer is: {0}", a)
End Sub
Public Overridable Sub SayItWithStyle(ByVal style As String)
System.Console.WriteLine("You don't say: {0}", style)
End Sub
End Class
Class Bar
Inherits Foo
Public Overrides Sub SayItWithStyle(ByVal style As String)
System.Console.WriteLine("You don't say: {0}", style)
End Sub
End Class
Module Module1
Sub Main()
Dim f As IFoo = New Foo
f.SayItWithStyle("Eric Clapton rocks!")
f.SayItWithStyle(42)
Dim g As IFoo = New Bar
g.SayItWithStyle("Lady Gaga rules!")
g.SayItWithStyle(13)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
I said: Eric Clapton rocks!
The answer is: 42
I said: Lady Gaga rules!
The answer is: 13
]]>)
End Sub
<Fact>
Public Sub SimpleImplementationProperties()
CompileAndVerify(
<compilation name="SimpleImplementationProperties">
<file name="a.vb">
Option Strict On
Interface IFoo
Property MyString As String
Property MyInt As Integer
End Interface
Class Foo
Implements IFoo
Private s As String
Public Property IGotYourInt As Integer Implements IFoo.MyInt
Public Property IGotYourString As String Implements IFoo.MyString
Get
Return "You got: " + s
End Get
Set(value As String)
s = value
End Set
End Property
Public Overridable Property MyString As String
End Class
Class Bar
Inherits Foo
Private s As String
Public Overrides Property MyString As String
Get
Return "I got: " + s
End Get
Set(value As String)
s = value + " and then some"
End Set
End Property
End Class
Module Module1
Sub Main()
Dim f As IFoo = New Foo
f.MyInt = 178
f.MyString = "Lady Gaga"
System.Console.WriteLine(f.MyInt)
System.Console.WriteLine(f.MyString)
Dim g As IFoo = New Bar
g.MyInt = 12
g.MyString = "Eric Clapton"
System.Console.WriteLine(g.MyInt)
System.Console.WriteLine(g.MyString)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
178
You got: Lady Gaga
12
You got: Eric Clapton
]]>)
End Sub
<Fact>
Public Sub SimpleImplementationOverloadedProperties()
CompileAndVerify(
<compilation name="SimpleImplementationOverloadedProperties">
<file name="a.vb">
Option Strict On
Interface IFoo
Property MyString As String
Property MyString(x As Integer) As String
Property MyString(x As String) As String
Property MyInt As Integer
End Interface
Class Foo
Implements IFoo
Private s, t, u As String
Public Property IGotYourInt As Integer Implements IFoo.MyInt
Public Property IGotYourString As String Implements IFoo.MyString
Get
Return "You got: " + s
End Get
Set(value As String)
s = value
End Set
End Property
Public Property IGotYourString2(x As Integer) As String Implements IFoo.MyString
Get
Return "You got: " & t & " and " & x
End Get
Set(value As String)
t = value + "2"
End Set
End Property
Public Property IGotYourString3(x As String) As String Implements IFoo.MyString
Get
Return "You used to have: " & u & " and " & x
End Get
Set(value As String)
u = value + "3"
End Set
End Property
Public Overridable Property MyString As String
End Class
Module Module1
Sub Main()
Dim f As IFoo = New Foo
f.MyInt = 178
f.MyString = "Lady Gaga"
f.MyString(8) = "Eric Clapton"
f.MyString("foo") = "Katy Perry"
System.Console.WriteLine(f.MyInt)
System.Console.WriteLine(f.MyString)
System.Console.WriteLine(f.MyString(4))
System.Console.WriteLine(f.MyString("Bob Marley"))
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
178
You got: Lady Gaga
You got: Eric Clapton2 and 4
You used to have: Katy Perry3 and Bob Marley
]]>)
End Sub
<Fact>
Public Sub ReImplementation()
CompileAndVerify(
<compilation name="ReImplementation">
<file name="a.vb">
Option Strict On
Interface IFoo
Sub SayItWithStyle(ByVal style As String)
Sub SayItWithStyle(ByVal answer As Integer)
End Interface
Class Foo
Implements IFoo
Public Sub X(ByVal style As String) Implements IFoo.SayItWithStyle
System.Console.WriteLine("I said: {0}", style)
End Sub
Public Sub Y(ByVal a As Integer) Implements IFoo.SayItWithStyle
System.Console.WriteLine("The answer is: {0}", a)
End Sub
Public Overridable Sub SayItWithStyle(ByVal style As String)
System.Console.WriteLine("You don't say: {0}", style)
End Sub
End Class
Class Bar
Inherits Foo
Implements IFoo
Private Sub Z(ByVal a As Integer) Implements IFoo.SayItWithStyle
System.Console.WriteLine("The question is: {0}", a)
End Sub
Public Overrides Sub SayItWithStyle(ByVal style As String)
System.Console.WriteLine("I don't say: {0}", style)
End Sub
End Class
Module Module1
Sub Main()
Dim f As IFoo = New Foo
f.SayItWithStyle("Eric Clapton rocks!")
f.SayItWithStyle(42)
Dim g As IFoo = New Bar
g.SayItWithStyle("Lady Gaga rules!")
g.SayItWithStyle(13)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
I said: Eric Clapton rocks!
The answer is: 42
I said: Lady Gaga rules!
The question is: 13
]]>)
End Sub
<Fact>
Public Sub ReImplementationProperties()
CompileAndVerify(
<compilation name="ReImplementationProperties">
<file name="a.vb">
Option Strict On
Interface IFoo
Property MyString As String
Property MyInt As Integer
End Interface
Class Foo
Implements IFoo
Private s As String
Public Property IGotYourInt As Integer Implements IFoo.MyInt
Public Property IGotYourString As String Implements IFoo.MyString
Get
Return "You got: " + s
End Get
Set(value As String)
s = value
End Set
End Property
Public Overridable Property MyString As String
End Class
Class Bar
Inherits Foo
Implements IFoo
Private s As String
Public Property AnotherString As String Implements IFoo.MyString
Get
Return "I got your: " + s
End Get
Set(value As String)
s = value + " right here"
End Set
End Property
End Class
Module Module1
Sub Main()
Dim f As IFoo = New Foo
f.MyInt = 178
f.MyString = "Lady Gaga"
System.Console.WriteLine(f.MyInt)
System.Console.WriteLine(f.MyString)
Dim g As IFoo = New Bar
g.MyInt = 12
g.MyString = "Eric Clapton"
System.Console.WriteLine(g.MyInt)
System.Console.WriteLine(g.MyString)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
178
You got: Lady Gaga
12
I got your: Eric Clapton right here
]]>)
End Sub
<Fact>
Public Sub ImplementationOfGenericMethod()
CompileAndVerify(
<compilation name="ImplementationOfGenericMethod">
<file name="a.vb">
Option Strict On
Imports System
Imports System.Collections.Generic
Interface IFoo
Sub SayItWithStyle(Of T)(ByVal style As T)
Sub SayItWithStyle(Of T)(ByVal style As IList(Of T))
End Interface
Class Foo
Implements IFoo
Public Sub SayItWithStyle(Of U)(ByVal style As System.Collections.Generic.IList(Of U)) Implements IFoo.SayItWithStyle
System.Console.WriteLine("style is IList(Of U)")
End Sub
Public Sub SayItWithStyle(Of V)(ByVal style As V) Implements IFoo.SayItWithStyle
System.Console.WriteLine("style is V")
End Sub
End Class
Module Module1
Sub Main()
Dim f As IFoo = New Foo
Dim g As List(Of Integer) = New List(Of Integer)
g.Add(42)
g.Add(13)
g.Add(14)
f.SayItWithStyle(Of String)("Eric Clapton rocks!")
f.SayItWithStyle(Of Integer)(g)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
style is V
style is IList(Of U)
]]>)
End Sub
<Fact>
Public Sub ImplementationOfGenericMethod2()
CompileAndVerify(
<compilation name="ImplementationOfGenericMethod2">
<file name="a.vb">
Option Strict On
Imports System
Imports System.Collections.Generic
Interface IFoo(Of K, L)
Sub SayItWithStyle(Of T)(ByVal style As T, ByVal a As K, ByVal b As Dictionary(Of L, K))
Sub SayItWithStyle(Of T)(ByVal style As IList(Of T), ByVal a As L, ByVal b As Dictionary(Of K, L))
End Interface
Class Foo(Of M)
Implements IFoo(Of M, ULong)
Public Sub SayItWithStyle(Of T)(ByVal style As T, ByVal a As M, ByVal b As Dictionary(Of ULong, M)) Implements IFoo(Of M, ULong).SayItWithStyle
Console.WriteLine("first")
End Sub
Public Sub SayItWithStyle(Of T)(ByVal style As System.Collections.Generic.IList(Of T), ByVal a As ULong, ByVal b As Dictionary(Of M, ULong)) Implements IFoo(Of M, ULong).SayItWithStyle
Console.WriteLine("second")
End Sub
End Class
Module Module1
Sub Main()
Dim f As IFoo(Of String, ULong) = New Foo(Of String)()
Dim g As List(Of Integer) = New List(Of Integer)
g.Add(42)
g.Add(13)
g.Add(14)
Dim h As Dictionary(Of String, ULong) = Nothing
Dim i As Dictionary(Of ULong, String) = Nothing
f.SayItWithStyle(Of String)("Eric Clapton rocks!", "hi", i)
f.SayItWithStyle(Of Integer)(g, 17, h)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
first
second
]]>)
End Sub
<Fact>
Public Sub ImplementationOfGenericMethod3()
CompileAndVerify(
<compilation name="ImplementationOfGenericMethod3">
<file name="a.vb">
Option Strict On
Namespace MyNS
Interface I1(Of T)
Sub Foo(ByVal i As T, ByVal j As String)
End Interface
Interface I2
Inherits I1(Of String)
End Interface
Public Class Class1
Implements I2
Public Sub A2(ByVal i As String, ByVal j As String) Implements I1(Of String).Foo
System.Console.WriteLine("{0} {1}", i, j)
End Sub
End Class
End Namespace
Module Module1
Sub Main()
Dim x As MyNS.I2 = New MyNS.Class1()
x.Foo("hello", "world")
End Sub
End Module
</file>
</compilation>,
expectedOutput:="hello world")
End Sub
<Fact>
Public Sub ImplementNonInterface()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementNonInterface">
<file name="a.vb">
Option Strict On
Public Structure S1
Public Sub foo()
End Sub
Public Property Zip As Integer
End Structure
Public Enum E1
Red
green
End Enum
Public Delegate Sub D1(ByVal x As Integer)
Public Class Class1
Public Sub foo() Implements S1.foo
End Sub
Public Property zap As Integer Implements S1.Zip
Get
return 3
End Get
Set
End Set
End Property
Public Sub bar() Implements E1.Red
End Sub
Public Sub baz() Implements System.Object.GetHashCode
End Sub
Public Sub quux() Implements D1.Invoke
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30232: Implemented type must be an interface.
Public Sub foo() Implements S1.foo
~~
BC30232: Implemented type must be an interface.
Public Property zap As Integer Implements S1.Zip
~~
BC30232: Implemented type must be an interface.
Public Sub bar() Implements E1.Red
~~
BC30232: Implemented type must be an interface.
Public Sub baz() Implements System.Object.GetHashCode
~~~~~~~~~~~~~
BC30232: Implemented type must be an interface.
Public Sub quux() Implements D1.Invoke
~~
</expected>)
End Sub
<WorkItem(531308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531308")>
<Fact>
Public Sub ImplementsClauseAndObsoleteAttribute()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementsClauseAndObsoleteAttribute">
<file name="a.vb">
Imports System
Interface i1
<Obsolete("", True)> Sub foo()
<Obsolete("", True)> Property moo()
<Obsolete("", True)> Event goo()
End Interface
Class c1
Implements i1
'COMPILEERROR: BC30668, "i1.foo"
Public Sub foo() Implements i1.foo
End Sub
'COMPILEERROR: BC30668, "i1.moo"
Public Property moo() As Object Implements i1.moo
Get
Return Nothing
End Get
Set(ByVal Value As Object)
End Set
End Property
'COMPILEERROR: BC30668, "i1.goo"
Public Event goo() Implements i1.goo
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31075: 'Sub foo()' is obsolete.
Public Sub foo() Implements i1.foo
~~~~~~~~~~~~~~~~~
BC31075: 'Property moo As Object' is obsolete.
Public Property moo() As Object Implements i1.moo
~~~~~~~~~~~~~~~~~
BC31075: 'Event goo()' is obsolete.
Public Event goo() Implements i1.goo
~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub UnimplementedInterface()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnimplementedInterface">
<file name="a.vb">
Option Strict On
Namespace MyNS
Interface I1
Sub Bar(ByVal x As String)
Property Zap As Integer
End Interface
Public Class Class1
Public Sub Foo(ByVal x As String) Implements I1.Bar
End Sub
Public Property Quuz As Integer Implements I1.Zap
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC31035: Interface 'I1' is not implemented by this class.
Public Sub Foo(ByVal x As String) Implements I1.Bar
~~
BC31035: Interface 'I1' is not implemented by this class.
Public Property Quuz As Integer Implements I1.Zap
~~
</expected>)
End Sub
<Fact>
Public Sub UnimplementedInterface2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnimplementedInterface2">
<file name="a.vb">
Option Strict On
Namespace MyNS
Interface I1
Sub Bar(ByVal x As String)
Property Zap As Integer
End Interface
Public Class Class1
Implements I1
Public Sub Foo(ByVal x As String) Implements I1.Bar
End Sub
Public Property Quuz As Integer Implements I1.Zap
End Class
Public Class Class2
Inherits Class1
Public Sub Quux(ByVal x As String) Implements I1.Bar
End Sub
Public Property Dingo As Integer Implements I1.Zap
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC31035: Interface 'I1' is not implemented by this class.
Public Sub Quux(ByVal x As String) Implements I1.Bar
~~
BC31035: Interface 'I1' is not implemented by this class.
Public Property Dingo As Integer Implements I1.Zap
~~
</expected>)
End Sub
<Fact>
Public Sub ImplementUnknownType()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementUnknownType">
<file name="a.vb">
Option Strict On
Public Class Class1
Public Sub foo() Implements UnknownType.foo
End Sub
Public Sub bar() Implements System.UnknownType(Of String).bar
End Sub
Public Property quux As Integer Implements UnknownType.foo
Public Property quuz As String Implements System.UnknownType(Of String).bar
Get
return ""
End Get
Set
End Set
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30002: Type 'UnknownType' is not defined.
Public Sub foo() Implements UnknownType.foo
~~~~~~~~~~~
BC30002: Type 'System.UnknownType' is not defined.
Public Sub bar() Implements System.UnknownType(Of String).bar
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30002: Type 'UnknownType' is not defined.
Public Property quux As Integer Implements UnknownType.foo
~~~~~~~~~~~
BC30002: Type 'System.UnknownType' is not defined.
Public Property quuz As String Implements System.UnknownType(Of String).bar
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub AmbiguousInterface_01()
' Somewhat surprisingly, perhaps, I3.Foo is considered ambiguous between I1.Foo(String, String) and
' I2.Foo(Integer), even though only I2.Foo(String, String) matches the method arguments provided. This
' matches Dev10 behavior.
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousInterface">
<file name="a.vb">
Option Strict On
Interface I1
Sub Foo(ByVal i As String, ByVal j As String)
End Interface
Interface I2
Sub Foo(ByVal x As Integer)
End Interface
Interface I3
Inherits I1, I2
End Interface
Public Class Class1
Implements I3
Public Sub Foo(ByVal i As String, ByVal j As String) Implements I3.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Sub Foo(x As Integer)' for interface 'I2'.
Implements I3
~~
</expected>)
End Sub
<Fact>
Public Sub AmbiguousInterface_02()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousInterface">
<file name="a.vb">
Option Strict On
Interface I1
Sub Foo(ByVal i As String, ByVal j As String)
End Interface
Interface I2
Sub Foo(ByVal i As String, ByVal j As String)
End Interface
Interface I3
Inherits I1, I2
End Interface
Public Class Class1
Implements I3
Public Sub Foo(ByVal i As String, ByVal j As String) Implements I3.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Sub Foo(i As String, j As String)' for interface 'I2'.
Implements I3
~~
BC31040: 'Foo' exists in multiple base interfaces. Use the name of the interface that declares 'Foo' in the 'Implements' clause instead of the name of the derived interface.
Public Sub Foo(ByVal i As String, ByVal j As String) Implements I3.Foo
~~~~~~
</expected>)
End Sub
<Fact>
Public Sub AmbiguousInterface_03()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousInterface">
<file name="a.vb">
Option Strict On
Interface I1(Of T, S)
Sub Foo(ByVal i As T, ByVal j As S)
Sub Foo(ByVal i As S, ByVal j As T)
End Interface
Interface I3
Inherits I1(Of Integer, Short), I1(Of Short, Integer)
End Interface
Public Class Class1
Implements I3
Public Sub Foo(ByVal i As Integer, ByVal j As Short) Implements I3.Foo
End Sub
Public Sub Foo(ByVal i As Short, ByVal j As Integer) Implements I3.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Sub Foo(i As Integer, j As Short)' for interface 'I1(Of Short, Integer)'.
Implements I3
~~
BC30149: Class 'Class1' must implement 'Sub Foo(i As Short, j As Integer)' for interface 'I1(Of Short, Integer)'.
Implements I3
~~
BC31040: 'Foo' exists in multiple base interfaces. Use the name of the interface that declares 'Foo' in the 'Implements' clause instead of the name of the derived interface.
Public Sub Foo(ByVal i As Integer, ByVal j As Short) Implements I3.Foo
~~~~~~
BC31040: 'Foo' exists in multiple base interfaces. Use the name of the interface that declares 'Foo' in the 'Implements' clause instead of the name of the derived interface.
Public Sub Foo(ByVal i As Short, ByVal j As Integer) Implements I3.Foo
~~~~~~
</expected>)
End Sub
<Fact>
Public Sub AmbiguousInterface_04()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousInterface">
<file name="a.vb">
Option Strict On
Interface I1(Of T, S)
Sub Foo(ByVal i As T)
Sub Foo(ByVal i As S)
End Interface
Public Class Class1
Implements I1(Of Integer, Integer)
Public Sub Foo(ByVal i As Integer) Implements I1(Of Integer, Integer).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Sub Foo(i As Integer)' for interface 'I1(Of Integer, Integer)'.
Implements I1(Of Integer, Integer)
~~~~~~~~~~~~~~~~~~~~~~~
BC30937: Member 'I1(Of Integer, Integer).Foo' that matches this signature cannot be implemented because the interface 'I1(Of Integer, Integer)' contains multiple members with this same name and signature:
'Sub Foo(i As Integer)'
'Sub Foo(i As Integer)'
Public Sub Foo(ByVal i As Integer) Implements I1(Of Integer, Integer).Foo
~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub AmbiguousInterface_05()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousInterface">
<file name="a.vb">
Option Strict On
Interface I1
Sub Foo(ByVal i As String)
End Interface
Interface I2
Inherits I1
Overloads Sub Foo(ByVal i As String)
End Interface
Interface I3
Inherits I1, I2
End Interface
Interface I4
Inherits I2, I1
End Interface
Public Class Class1
Implements I3
Public Sub Foo(ByVal i As String) Implements I3.Foo
End Sub
End Class
Public Class Class2
Implements I4
Public Sub Foo(ByVal i As String) Implements I4.Foo
End Sub
End Class
Public Class Class3
Implements I3
Public Sub Foo1(ByVal i As String) Implements I3.Foo
End Sub
Public Sub Foo2(ByVal i As String) Implements I1.Foo
End Sub
End Class
Public Class Class4
Implements I4
Public Sub Foo1(ByVal i As String) Implements I4.Foo
End Sub
Public Sub Foo2(ByVal i As String) Implements I1.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Sub Foo(i As String)' for interface 'I1'.
Implements I3
~~
BC30149: Class 'Class2' must implement 'Sub Foo(i As String)' for interface 'I1'.
Implements I4
~~
</expected>)
End Sub
<Fact>
Public Sub AmbiguousInterfaceProperty()
' Somewhat surprisingly, perhaps, I3.Foo is considered ambiguous between I1.Foo(String, String) and
' I2.Foo(Integer), even though only I2.Foo(String, String) matches the method arguments provided. This
' matches Dev10 behavior.
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousInterfaceProperty">
<file name="a.vb">
Option Strict On
Interface I1
Sub Foo(ByVal i As String, ByVal j As String)
End Interface
Interface I2
Property Foo As Integer
End Interface
Interface I3
Inherits I1, I2
End Interface
Public Class Class1
Implements I3
Public Property Bar As Integer Implements I3.Foo
Get
Return 3
End Get
Set(value As Integer)
End Set
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Property Foo As Integer' for interface 'I2'.
Implements I3
~~
BC30149: Class 'Class1' must implement 'Sub Foo(i As String, j As String)' for interface 'I1'.
Implements I3
~~
BC31040: 'Foo' exists in multiple base interfaces. Use the name of the interface that declares 'Foo' in the 'Implements' clause instead of the name of the derived interface.
Public Property Bar As Integer Implements I3.Foo
~~~~~~
</expected>)
End Sub
<Fact>
Public Sub NoMethodOfSig()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NoMethodOfSig">
<file name="a.vb">
Option Strict On
Namespace MyNS
Interface I1
Sub Foo(ByVal i As String, ByVal j As String)
Function Foo(ByVal i As Long) As Integer
Property P(i As Long) As Integer
End Interface
Public Class Class1
Implements I1
Public Sub X(ByVal i As Long) Implements I1.Foo
End Sub
Public Sub Y(ByRef i As String, ByVal j As String) Implements I1.Foo
End Sub
Public Property Z1 As Integer Implements I1.P
Public Property Z2(i as Integer) As Integer Implements I1.P
Get
return 3
End Get
Set
End Set
End Property
Public Property Z3 As Integer Implements I1.Foo
End Class
End Namespace</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Function Foo(i As Long) As Integer' for interface 'I1'.
Implements I1
~~
BC30149: Class 'Class1' must implement 'Property P(i As Long) As Integer' for interface 'I1'.
Implements I1
~~
BC30149: Class 'Class1' must implement 'Sub Foo(i As String, j As String)' for interface 'I1'.
Implements I1
~~
BC30401: 'X' cannot implement 'Foo' because there is no matching sub on interface 'I1'.
Public Sub X(ByVal i As Long) Implements I1.Foo
~~~~~~
BC30401: 'Y' cannot implement 'Foo' because there is no matching sub on interface 'I1'.
Public Sub Y(ByRef i As String, ByVal j As String) Implements I1.Foo
~~~~~~
BC30401: 'Z1' cannot implement 'P' because there is no matching property on interface 'I1'.
Public Property Z1 As Integer Implements I1.P
~~~~
BC30401: 'Z2' cannot implement 'P' because there is no matching property on interface 'I1'.
Public Property Z2(i as Integer) As Integer Implements I1.P
~~~~
BC30401: 'Z3' cannot implement 'Foo' because there is no matching property on interface 'I1'.
Public Property Z3 As Integer Implements I1.Foo
~~~~~~
</expected>)
End Sub
<WorkItem(577934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577934")>
<Fact>
Public Sub Bug577934a()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Option Strict On
Interface I
Sub Foo(Of T)(Optional x As T = CType(Nothing, T))
End Interface
Class C
Implements I
Public Sub Foo(Of T)(Optional x As T = Nothing) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<WorkItem(577934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577934")>
<Fact>
Public Sub Bug577934b()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Option Strict On
Interface I
Sub Foo(Of T)(Optional x As T = DirectCast(Nothing, T))
End Interface
Class C
Implements I
Public Sub Foo(Of T)(Optional x As T = Nothing) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<WorkItem(577934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577934")>
<Fact>
Public Sub Bug577934c()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Option Strict On
Interface I
Sub Foo(Of T As Class)(Optional x As T = TryCast(Nothing, T))
End Interface
Class C
Implements I
Public Sub Foo(Of T As Class)(Optional x As T = Nothing) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<Fact>
Public Sub NoMethodOfName()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NoMethodOfName">
<file name="a.vb">
Option Strict On
Namespace MyNS
Interface I1
Sub Foo(ByVal i As String, ByVal j As String)
End Interface
Public Class Class1
Implements I1
Public Sub Foo(ByVal i As String, ByVal j As String) Implements I1.Foo
End Sub
Public Sub Bar() Implements MyNS.I1.Quux
End Sub
Public Function Zap() As Integer Implements I1.GetHashCode
Return 0
End Function
Public Property Zip As Integer Implements I1.GetHashCode
Public ReadOnly Property Zing(x As String) As String Implements I1.Zing, I1.Foo
Get
return ""
End Get
End Property
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30401: 'Bar' cannot implement 'Quux' because there is no matching sub on interface 'I1'.
Public Sub Bar() Implements MyNS.I1.Quux
~~~~~~~~~~~~
BC30401: 'Zap' cannot implement 'GetHashCode' because there is no matching function on interface 'I1'.
Public Function Zap() As Integer Implements I1.GetHashCode
~~~~~~~~~~~~~~
BC30401: 'Zip' cannot implement 'GetHashCode' because there is no matching property on interface 'I1'.
Public Property Zip As Integer Implements I1.GetHashCode
~~~~~~~~~~~~~~
BC30401: 'Zing' cannot implement 'Zing' because there is no matching property on interface 'I1'.
Public ReadOnly Property Zing(x As String) As String Implements I1.Zing, I1.Foo
~~~~~~~
BC30401: 'Zing' cannot implement 'Foo' because there is no matching property on interface 'I1'.
Public ReadOnly Property Zing(x As String) As String Implements I1.Zing, I1.Foo
~~~~~~
</expected>)
End Sub
<Fact>
Public Sub GenericSubstitutionAmbiguity()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="GenericSubstitutionAmbiguity">
<file name="a.vb">
Option Strict On
Namespace MyNS
Interface I1(Of T)
Sub Foo(ByVal i As T, ByVal j As String)
Sub Bar(ByVal x As T)
Sub Bar(ByVal x As String)
End Interface
Interface I2
Inherits I1(Of String)
Overloads Sub Foo(ByVal i As String, ByVal j As String)
End Interface
Public Class Class1
Implements I2
Public Sub A1(ByVal i As String, ByVal j As String) Implements I2.Foo
End Sub
Public Sub A2(ByVal i As String, ByVal j As String) Implements I1(Of String).Foo
End Sub
Public Sub B(ByVal x As String) Implements I2.Bar
End Sub
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Sub Bar(x As String)' for interface 'I1(Of String)'.
Implements I2
~~
BC30937: Member 'I1(Of String).Bar' that matches this signature cannot be implemented because the interface 'I1(Of String)' contains multiple members with this same name and signature:
'Sub Bar(x As String)'
'Sub Bar(x As String)'
Public Sub B(ByVal x As String) Implements I2.Bar
~~~~~~
</expected>)
End Sub
<Fact>
Public Sub GenericSubstitutionAmbiguityProperty()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="GenericSubstitutionAmbiguityProperty">
<file name="a.vb">
Option Strict On
Namespace MyNS
Interface I1(Of T)
Property Foo As T
Property Bar(ByVal x As T) As Integer
Property Bar(ByVal x As String) As Integer
End Interface
Interface I2
Inherits I1(Of String)
Overloads Property Foo As String
End Interface
Public Class Class1
Implements I2
Public Property A1 As String Implements I1(Of String).Foo
Get
Return ""
End Get
Set(value As String)
End Set
End Property
Public Overloads Property A2 As String Implements I2.Foo
Get
Return ""
End Get
Set(value As String)
End Set
End Property
Public Property B(x As String) As Integer Implements I1(Of String).Bar
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'Property Bar(x As String) As Integer' for interface 'I1(Of String)'.
Implements I2
~~
BC30937: Member 'I1(Of String).Bar' that matches this signature cannot be implemented because the interface 'I1(Of String)' contains multiple members with this same name and signature:
'Property Bar(x As String) As Integer'
'Property Bar(x As String) As Integer'
Public Property B(x As String) As Integer Implements I1(Of String).Bar
~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub InterfaceReimplementation2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceReimplementation2">
<file name="a.vb">
Option Strict On
Namespace MyNS
Interface I1
Sub Bar(ByVal x As String)
Function Baz() As Integer
ReadOnly Property Zip As Integer
End Interface
Interface I2
Inherits I1
End Interface
Public Class Class1
Implements I1
Public Sub FooXX(ByVal x As String) Implements I1.Bar
End Sub
Public Function BazXX() As Integer Implements I1.Baz
Return 0
End Function
Public ReadOnly Property ZipXX As Integer Implements I1.Zip
Get
Return 0
End Get
End Property
End Class
Public Class Class2
Inherits Class1
Implements I2
Public Sub Quux(ByVal x As String) Implements I1.Bar
End Sub
Public Function Quux2() As Integer Implements I1.Baz
Return 0
End Function
Public ReadOnly Property Quux3 As Integer Implements I1.Zip
Get
Return 0
End Get
End Property
End Class
Public Class Class3
Inherits Class1
Implements I1
Public Sub Zap(ByVal x As String) Implements I1.Bar
End Sub
Public Function Zap2() As Integer Implements I1.Baz
Return 0
End Function
Public ReadOnly Property Zap3 As Integer Implements I1.Zip
Get
Return 0
End Get
End Property
End Class
End Namespace
</file>
</compilation>)
' BC42015 is deprecated
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
</expected>)
End Sub
<Fact>
Public Sub UnimplementedMembers()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnimplementedMembers">
<file name="a.vb">
Option Strict On
Imports System
Imports System.Collections.Generic
Namespace MyNS
Interface I1(Of T, U)
Sub Foo(ByVal i As T, ByVal j As U)
Function Quack(ByVal o As Integer) As Long
ReadOnly Property Zing(i As U) As T
End Interface
Interface I2(Of W)
Inherits I1(Of String, IEnumerable(Of W))
Sub Bar(ByVal i As Long)
End Interface
Interface I3
Sub Zap()
End Interface
Public Class Class1(Of T)
Implements I2(Of T), I3
Public Function Quack(ByVal o As Integer) As Long Implements I1(Of String, System.Collections.Generic.IEnumerable(Of T)).Quack
Return 0
End Function
End Class
End Namespace
Module Module1
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'Class1' must implement 'ReadOnly Property Zing(i As IEnumerable(Of T)) As String' for interface 'I1(Of String, IEnumerable(Of T))'.
Implements I2(Of T), I3
~~~~~~~~
BC30149: Class 'Class1' must implement 'Sub Bar(i As Long)' for interface 'I2(Of T)'.
Implements I2(Of T), I3
~~~~~~~~
BC30149: Class 'Class1' must implement 'Sub Foo(i As String, j As IEnumerable(Of T))' for interface 'I1(Of String, IEnumerable(Of T))'.
Implements I2(Of T), I3
~~~~~~~~
BC30149: Class 'Class1' must implement 'Sub Zap()' for interface 'I3'.
Implements I2(Of T), I3
~~
</expected>)
End Sub
<Fact>
Public Sub ImplementTwice()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementTwice">
<file name="a.vb">
Interface IFoo
Sub Foo(x As Integer)
WriteOnly Property Bang As Integer
End Interface
Interface IBar
Sub Bar(x As Integer)
End Interface
Public Class Class1
Implements IFoo, IBar
Public Sub Foo(x As Integer) Implements IFoo.Foo
End Sub
Public Sub Baz(x As Integer) Implements IBar.Bar, IFoo.Foo
End Sub
Public WriteOnly Property A As Integer Implements IFoo.Bang
Set
End Set
End Property
Public Property B As Integer Implements IFoo.Bang
Get
Return 0
End Get
Set
End Set
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30583: 'IFoo.Foo' cannot be implemented more than once.
Public Sub Baz(x As Integer) Implements IBar.Bar, IFoo.Foo
~~~~~~~~
BC30583: 'IFoo.Bang' cannot be implemented more than once.
Public Property B As Integer Implements IFoo.Bang
~~~~~~~~~
</expected>)
End Sub
' DEV10 gave BC31415 for this case, but (at least for now), just use BC30401 since BC31415 is such a bad
' error message.
<Fact>
Public Sub ImplementStatic()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="ImplementStatic">
<file name="a.vb">
Public Class Class1
Implements ContainsStatic
Public Sub Foo() Implements ContainsStatic.Bar
End Sub
Public Sub Baz() Implements ContainsStatic.StaticMethod
End Sub
End Class
</file>
</compilation>, {TestReferences.SymbolsTests.Interface.StaticMethodInInterface})
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30401: 'Baz' cannot implement 'StaticMethod' because there is no matching sub on interface 'ContainsStatic'.
Public Sub Baz() Implements ContainsStatic.StaticMethod
~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub InterfaceUnification1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceUnification1">
<file name="a.vb">
Imports System.Collections.Generic
Namespace Q
Interface IFoo(Of T)
Sub M(i As T)
End Interface
Interface Z(Of W)
Inherits IFoo(Of W)
End Interface
Class Outer(Of X)
Class Inner(Of Y)
Implements IFoo(Of List(Of X)), Z(Of Y)
Public Sub M1(i As List(Of X)) Implements IFoo(Of List(Of X)).M
End Sub
Public Sub M2(i As Y) Implements IFoo(Of Y).M
End Sub
End Class
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC32131: Cannot implement interface 'Z(Of Y)' because the interface 'IFoo(Of Y)' from which it inherits could be identical to implemented interface 'IFoo(Of List(Of X))' for some type arguments.
Implements IFoo(Of List(Of X)), Z(Of Y)
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub InterfaceUnification2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceUnification2">
<file name="a.vb">
Interface I(Of T)
End Interface
Class G1(Of T1, T2)
Implements I(Of T1), I(Of T2) 'bad
End Class
Class G2(Of T1, T2)
Implements I(Of Integer), I(Of T2) 'bad
End Class
Class G3(Of T1, T2)
Implements I(Of Integer), I(Of Short) 'ok
End Class
Class G4(Of T1, T2)
Implements I(Of I(Of T1)), I(Of T1) 'ok
End Class
Class G5(Of T1, T2)
Implements I(Of I(Of T1)), I(Of T2) 'bad
End Class
Interface I2(Of T)
Inherits I(Of T)
End Interface
Class G6(Of T1, T2)
Implements I(Of T1), I2(Of T2) 'bad
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC32072: Cannot implement interface 'I(Of T2)' because its implementation could conflict with the implementation of another implemented interface 'I(Of T1)' for some type arguments.
Implements I(Of T1), I(Of T2) 'bad
~~~~~~~~
BC32072: Cannot implement interface 'I(Of T2)' because its implementation could conflict with the implementation of another implemented interface 'I(Of Integer)' for some type arguments.
Implements I(Of Integer), I(Of T2) 'bad
~~~~~~~~
BC32072: Cannot implement interface 'I(Of T2)' because its implementation could conflict with the implementation of another implemented interface 'I(Of I(Of T1))' for some type arguments.
Implements I(Of I(Of T1)), I(Of T2) 'bad
~~~~~~~~
BC32131: Cannot implement interface 'I2(Of T2)' because the interface 'I(Of T2)' from which it inherits could be identical to implemented interface 'I(Of T1)' for some type arguments.
Implements I(Of T1), I2(Of T2) 'bad
~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub InterfaceUnification3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceUnification1">
<file name="a.vb">
Interface I(Of T, S)
End Interface
Class A(Of T, S)
Implements I(Of I(Of T, T), T)
Implements I(Of I(Of T, S), S)
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC32072: Cannot implement interface 'I(Of I(Of T, S), S)' because its implementation could conflict with the implementation of another implemented interface 'I(Of I(Of T, T), T)' for some type arguments.
Implements I(Of I(Of T, S), S)
~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub InterfaceUnification4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceUnification4">
<file name="a.vb">
Class A(Of T, S)
Class B
Inherits A(Of B, B)
End Class
Interface IA
Sub M()
End Interface
Interface IB
Inherits B.IA
Inherits B.B.IA
End Interface 'ok
End Class
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub InterfaceUnification5()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceUnification5">
<file name="a.vb">
Option Strict On
Imports System.Collections.Generic
Class Outer(Of X, Y)
Interface IFoo(Of T, U)
End Interface
End Class
Class OuterFoo(Of A, B)
Class Foo(Of C, D)
Implements Outer(Of C, B).IFoo(Of A, D), Outer(Of D, A).IFoo(Of B, C) 'error
End Class
Class Bar(Of C, D)
Implements Outer(Of C, B).IFoo(Of A, D), Outer(Of D, A).IFoo(Of B, List(Of C)) ' ok
End Class
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC32072: Cannot implement interface 'Outer(Of D, A).IFoo(Of B, C)' because its implementation could conflict with the implementation of another implemented interface 'Outer(Of C, B).IFoo(Of A, D)' for some type arguments.
Implements Outer(Of C, B).IFoo(Of A, D), Outer(Of D, A).IFoo(Of B, C) 'error
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub SimpleImplementationApi()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SimpleImplementation">
<file name="a.vb">
Option Strict On
Interface IFoo
Sub SayItWithStyle(ByVal style As String)
Sub SayItWithStyle(ByVal answer As Integer)
End Interface
Class Foo
Implements IFoo
Public Sub X(ByVal style As String) Implements IFoo.SayItWithStyle
System.Console.WriteLine("I said: {0}", style)
End Sub
Public Sub Y(ByVal a As Integer) Implements IFoo.SayItWithStyle
System.Console.WriteLine("The answer is: {0}", a)
End Sub
Public Overridable Sub SayItWithStyle(ByVal style As String)
System.Console.WriteLine("You don't say: {0}", style)
End Sub
End Class
Class Bar
Inherits Foo
Public Overrides Sub SayItWithStyle(ByVal style As String)
System.Console.WriteLine("You don't say: {0}", style)
End Sub
End Class
</file>
</compilation>)
Dim globalNS = comp.GlobalNamespace
Dim iFooType = DirectCast(globalNS.GetMembers("IFoo").First(), NamedTypeSymbol)
Dim fooType = DirectCast(globalNS.GetMembers("Foo").First(), NamedTypeSymbol)
Dim barType = DirectCast(globalNS.GetMembers("Bar").First(), NamedTypeSymbol)
Dim ifooMethods = iFooType.GetMembers("SayItWithStyle").AsEnumerable().Cast(Of MethodSymbol)()
Dim ifooTypeSayWithString = (From m In ifooMethods Where m.Parameters(0).Type.SpecialType = SpecialType.System_String).First()
Dim ifooTypeSayWithInt = (From m In ifooMethods Where m.Parameters(0).Type.SpecialType = SpecialType.System_Int32).First()
Dim fooX = DirectCast(fooType.GetMembers("X").First(), MethodSymbol)
Dim fooY = DirectCast(fooType.GetMembers("Y").First(), MethodSymbol)
Dim fooSay = DirectCast(fooType.GetMembers("SayItWithStyle").First(), MethodSymbol)
Dim barSay = DirectCast(barType.GetMembers("SayItWithStyle").First(), MethodSymbol)
Assert.Equal(fooY, barType.FindImplementationForInterfaceMember(ifooTypeSayWithInt))
Assert.Equal(fooX, barType.FindImplementationForInterfaceMember(ifooTypeSayWithString))
Assert.Equal(fooY, fooType.FindImplementationForInterfaceMember(ifooTypeSayWithInt))
Assert.Equal(fooX, fooType.FindImplementationForInterfaceMember(ifooTypeSayWithString))
Assert.Equal(1, fooX.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeSayWithString, fooX.ExplicitInterfaceImplementations(0))
Assert.Equal(1, fooY.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeSayWithInt, fooY.ExplicitInterfaceImplementations(0))
Assert.Equal(0, fooSay.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, barSay.ExplicitInterfaceImplementations.Length)
CompilationUtils.AssertNoErrors(comp)
End Sub
<WorkItem(545581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545581")>
<Fact>
Public Sub ImplementInterfaceMethodWithNothingDefaultValue()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNothingDefaultValue">
<file name="a.vb">
Option Strict On
Interface I(Of T)
Sub Foo(Optional x As T = Nothing)
End Interface
Class C
Implements I(Of Integer)
Sub Foo(Optional x As Integer = 0) Implements I(Of Integer).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545581")>
<Fact>
Public Sub ImplementInterfaceMethodWithNothingDefaultValue2()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNothingDefaultValue2">
<file name="a.vb">
Option Strict On
Interface I(Of T)
Sub Foo(Optional x As T = Nothing)
End Interface
Class C
Implements I(Of Date)
Sub Foo(Optional x As Date = Nothing) Implements I(Of Date).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545581")>
<Fact>
Public Sub ImplementInterfaceMethodWithNothingDefaultValue3()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ImplementInterfaceMethodWithNothingDefaultValue3">
<file name="a.vb">
Option Strict On
Imports Microsoft.VisualBasic
Interface I(Of T)
Sub Foo(Optional x As T = Nothing)
End Interface
Class C
Implements I(Of Char)
Sub Foo(Optional x As Char = ChrW(0)) Implements I(Of Char).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545581")>
<Fact>
Public Sub ImplementInterfaceMethodWithNothingDefaultValue4()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNothingDefaultValue4">
<file name="a.vb">
Option Strict On
Interface I(Of T)
Sub Foo(Optional x As T = Nothing)
End Interface
Class C
Implements I(Of Single)
Sub Foo(Optional x As Single = Nothing) Implements I(Of Single).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545581")>
<Fact>
Public Sub ImplementInterfaceMethodWithNothingDefaultValue5()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNothingDefaultValue5">
<file name="a.vb">
Option Strict On
Imports System
Interface I(Of T)
Sub Foo(Optional x As T = Nothing)
End Interface
Class C
Implements I(Of DayOfWeek)
Public Sub Foo(Optional x As DayOfWeek = 0) Implements I(Of DayOfWeek).Foo
Throw New NotImplementedException()
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545891")>
<Fact>
Public Sub ImplementInterfaceMethodWithNothingDefaultValue6()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNothingDefaultValue6">
<file name="a.vb">
Interface I(Of T)
Sub Foo(Optional x As T = Nothing)
End Interface
Class C
Implements I(Of Decimal)
Public Sub Foo(Optional x As Decimal = 0.0D) Implements I(Of Decimal).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545891")>
<Fact>
Public Sub ImplementInterfaceMethodWithNothingDefaultValue7()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNothingDefaultValue7">
<file name="a.vb">
Interface I(Of T)
Sub Foo(Optional x As T = Nothing)
End Interface
Class C
Implements I(Of Double)
Public Sub Foo(Optional x As Double = -0D) Implements I(Of Double).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545891")>
<Fact>
Public Sub ImplementInterfaceMethodWithNothingDefaultValue8()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNothingDefaultValue7">
<file name="a.vb">
Interface I(Of T)
Sub Foo(Optional x As T = Nothing)
End Interface
Class C
Implements I(Of Single)
Public Sub Foo(Optional x As Single = -0D) Implements I(Of Single).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545596")>
<Fact>
Public Sub ImplementInterfaceMethodWithNanDefaultValue()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNanDefaultValue">
<file name="a.vb">
Option Strict On
Interface I
Sub Foo(Optional x As Double = Double.NaN)
End Interface
Class C
Implements I
Sub Foo(Optional x As Double = Double.NaN) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545596")>
<Fact>
Public Sub ImplementInterfaceMethodWithNanDefaultValue2()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNanDefaultValue2">
<file name="a.vb">
Option Strict On
Interface I
Sub Foo(Optional x As Single = Single.NaN)
End Interface
Class C
Implements I
Sub Foo(Optional x As Single = Single.NaN) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545596")>
<Fact>
Public Sub ImplementInterfaceMethodWithNanDefaultValue3()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNanDefaultValue3">
<file name="a.vb">
Option Strict On
Interface I
Sub Foo(Optional x As Single = Single.NaN)
End Interface
Class C
Implements I
Sub Foo(Optional x As Single = Double.NaN) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545596")>
<Fact>
Public Sub ImplementInterfaceMethodWithNanDefaultValue4()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfaceMethodWithNanDefaultValue4">
<file name="a.vb">
Option Strict On
Interface I
Sub Foo(Optional x As Single = Single.NaN)
End Interface
Class C
Implements I
Sub Foo(Optional x As Single = 0/0) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545596")>
<Fact>
Public Sub ImplementInterfacePropertyWithNanDefaultValue()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfacePropertyWithNanDefaultValue">
<file name="a.vb">
Option Strict On
Interface I
ReadOnly Property Foo(Optional x As Double = Double.NaN) As Integer
End Interface
Class C
Implements I
Public ReadOnly Property Foo(Optional x As Double = Double.NaN) As Integer Implements I.Foo
Get
Return 0
End Get
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545596")>
<Fact>
Public Sub ImplementInterfacePropertyWithNanDefaultValue2()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfacePropertyWithNanDefaultValue2">
<file name="a.vb">
Option Strict On
Interface I
ReadOnly Property Foo(Optional x As Double = Double.NegativeInfinity) As Integer
End Interface
Class C
Implements I
Public ReadOnly Property Foo(Optional x As Double = Single.NegativeInfinity) As Integer Implements I.Foo
Get
Return 0
End Get
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545596")>
<Fact>
Public Sub ImplementInterfacePropertyWithNanDefaultValue3()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfacePropertyWithNanDefaultValue3">
<file name="a.vb">
Option Strict On
Interface I
ReadOnly Property Foo(Optional x As Double = Double.NegativeInfinity) As Integer
End Interface
Class C
Implements I
Public ReadOnly Property Foo(Optional x As Double = (-1.0)/0) As Integer Implements I.Foo
Get
Return 0
End Get
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(545596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545596")>
<Fact>
Public Sub ImplementInterfacePropertyWithNanDefaultValue4()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementInterfacePropertyWithNanDefaultValue4">
<file name="a.vb">
Option Strict On
Interface I
ReadOnly Property Foo(Optional x As Double = Double.NegativeInfinity) As Integer
End Interface
Class C
Implements I
Public ReadOnly Property Foo(Optional x As Double = 1.0/0) As Integer Implements I.Foo
Get
Return 0
End Get
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp,
<errors>
BC30149: Class 'C' must implement 'ReadOnly Property Foo([x As Double = -Infinity]) As Integer' for interface 'I'.
Implements I
~
BC30401: 'Foo' cannot implement 'Foo' because there is no matching property on interface 'I'.
Public ReadOnly Property Foo(Optional x As Double = 1.0/0) As Integer Implements I.Foo
~~~~~
</errors>)
End Sub
<Fact>
Public Sub SimpleImplementationApiProperty()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SimpleImplementationProperty">
<file name="a.vb">
Option Strict On
Interface IFoo
ReadOnly Property Style(ByVal s As String) As String
ReadOnly Property Style(ByVal answer As Integer) As String
End Interface
Class Foo
Implements IFoo
Public Property X(ByVal style As String) As String Implements IFoo.Style
Get
Return "I said: " + style
End Get
Set
End Set
End Property
Public ReadOnly Property Y(ByVal a As Integer) As String Implements IFoo.Style
Get
Return "I said: " + a.ToString()
End Get
End Property
Public Overridable ReadOnly Property Style(ByVal s As String) As String
Get
Return "You dont say: " + s
End Get
End Property
End Class
Class Bar
Inherits Foo
Public Overrides ReadOnly Property Style(ByVal s As String) As String
Get
Return "I dont say: " + s
End Get
End Property
End Class
</file>
</compilation>)
Dim globalNS = comp.GlobalNamespace
Dim iFooType = DirectCast(globalNS.GetMembers("IFoo").First(), NamedTypeSymbol)
Dim fooType = DirectCast(globalNS.GetMembers("Foo").First(), NamedTypeSymbol)
Dim barType = DirectCast(globalNS.GetMembers("Bar").First(), NamedTypeSymbol)
Dim ifooProps = iFooType.GetMembers("Style").AsEnumerable().Cast(Of PropertySymbol)()
Dim ifooTypeStyleWithString = (From m In ifooProps Where m.Parameters(0).Type.SpecialType = SpecialType.System_String).First()
Dim ifooTypeStyleWithStringGetter = ifooTypeStyleWithString.GetMethod
Dim ifooTypeStyleWithInt = (From m In ifooProps Where m.Parameters(0).Type.SpecialType = SpecialType.System_Int32).First()
Dim ifooTypeStyleWithIntGetter = ifooTypeStyleWithInt.GetMethod
Dim fooX = DirectCast(fooType.GetMembers("X").First(), PropertySymbol)
Dim fooXGetter = fooX.GetMethod
Dim fooXSetter = fooX.SetMethod
Dim fooY = DirectCast(fooType.GetMembers("Y").First(), PropertySymbol)
Dim fooYGetter = fooY.GetMethod
Dim fooStyle = DirectCast(fooType.GetMembers("Style").First(), PropertySymbol)
Dim fooStyleGetter = fooStyle.GetMethod
Dim barStyle = DirectCast(barType.GetMembers("Style").First(), PropertySymbol)
Dim barStyleGetter = barStyle.GetMethod
Assert.Equal(fooY, barType.FindImplementationForInterfaceMember(ifooTypeStyleWithInt))
Assert.Equal(fooYGetter, barType.FindImplementationForInterfaceMember(ifooTypeStyleWithIntGetter))
Assert.Equal(fooX, barType.FindImplementationForInterfaceMember(ifooTypeStyleWithString))
Assert.Equal(fooXGetter, barType.FindImplementationForInterfaceMember(ifooTypeStyleWithStringGetter))
Assert.Equal(fooY, fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithInt))
Assert.Equal(fooYGetter, fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithIntGetter))
Assert.Equal(fooX, fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithString))
Assert.Equal(fooXGetter, fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithStringGetter))
Assert.Equal(1, fooX.ExplicitInterfaceImplementations.Length)
Assert.Equal(1, fooXGetter.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, fooXSetter.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeStyleWithString, fooX.ExplicitInterfaceImplementations(0))
Assert.Equal(ifooTypeStyleWithStringGetter, fooXGetter.ExplicitInterfaceImplementations(0))
Assert.Equal(1, fooY.ExplicitInterfaceImplementations.Length)
Assert.Equal(1, fooYGetter.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeStyleWithInt, fooY.ExplicitInterfaceImplementations(0))
Assert.Equal(ifooTypeStyleWithIntGetter, fooYGetter.ExplicitInterfaceImplementations(0))
Assert.Equal(0, fooStyle.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, barStyle.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, fooStyleGetter.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, barStyleGetter.ExplicitInterfaceImplementations.Length)
CompilationUtils.AssertNoErrors(comp)
End Sub
<Fact>
Public Sub UnimplementedMethods()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SimpleImplementation">
<file name="a.vb">
Option Strict On
Interface IFoo
Sub SayItWithStyle(ByVal style As String)
Sub SayItWithStyle(ByVal answer As Integer)
Sub SayItWithStyle(ByVal answer As Long)
End Interface
Class Foo
Implements IFoo
Public Sub Y(ByVal a As Integer) Implements IFoo.SayItWithStyle
System.Console.WriteLine("The answer is: {0}", a)
End Sub
Public Overridable Sub SayItWithStyle(ByVal answer As Long)
System.Console.WriteLine("You don't say: {0}", answer)
End Sub
End Class
Class Bar
Inherits Foo
Implements IFoo
Public Overrides Sub SayItWithStyle(ByVal answer As Long)
System.Console.WriteLine("You don't say: {0}", answer)
End Sub
Public Sub X(ByVal style As String) Implements IFoo.SayItWithStyle
System.Console.WriteLine("I said: {0}", style)
End Sub
End Class
</file>
</compilation>)
Dim globalNS = comp.GlobalNamespace
Dim iFooType = DirectCast(globalNS.GetMembers("IFoo").First(), NamedTypeSymbol)
Dim fooType = DirectCast(globalNS.GetMembers("Foo").First(), NamedTypeSymbol)
Dim barType = DirectCast(globalNS.GetMembers("Bar").First(), NamedTypeSymbol)
Dim ifooMethods = iFooType.GetMembers("SayItWithStyle").AsEnumerable().Cast(Of MethodSymbol)()
Dim ifooTypeSayWithString = (From m In ifooMethods Where m.Parameters(0).Type.SpecialType = SpecialType.System_String).First()
Dim ifooTypeSayWithInt = (From m In ifooMethods Where m.Parameters(0).Type.SpecialType = SpecialType.System_Int32).First()
Dim ifooTypeSayWithLong = (From m In ifooMethods Where m.Parameters(0).Type.SpecialType = SpecialType.System_Int64).First()
Dim barX = DirectCast(barType.GetMembers("X").First(), MethodSymbol)
Dim fooY = DirectCast(fooType.GetMembers("Y").First(), MethodSymbol)
Dim fooSay = DirectCast(fooType.GetMembers("SayItWithStyle").First(), MethodSymbol)
Dim barSay = DirectCast(barType.GetMembers("SayItWithStyle").First(), MethodSymbol)
Assert.Equal(fooY, barType.FindImplementationForInterfaceMember(ifooTypeSayWithInt))
Assert.Equal(barX, barType.FindImplementationForInterfaceMember(ifooTypeSayWithString))
Assert.Equal(fooY, fooType.FindImplementationForInterfaceMember(ifooTypeSayWithInt))
Assert.Null(fooType.FindImplementationForInterfaceMember(ifooTypeSayWithString))
Assert.Null(fooType.FindImplementationForInterfaceMember(ifooTypeSayWithLong))
Assert.Null(barType.FindImplementationForInterfaceMember(ifooTypeSayWithLong))
Assert.Equal(1, barX.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeSayWithString, barX.ExplicitInterfaceImplementations(0))
Assert.Equal(1, fooY.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeSayWithInt, fooY.ExplicitInterfaceImplementations(0))
Assert.Equal(0, fooSay.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, barSay.ExplicitInterfaceImplementations.Length)
CompilationUtils.AssertTheseDiagnostics(comp, <expected>
BC30149: Class 'Foo' must implement 'Sub SayItWithStyle(answer As Long)' for interface 'IFoo'.
Implements IFoo
~~~~
BC30149: Class 'Foo' must implement 'Sub SayItWithStyle(style As String)' for interface 'IFoo'.
Implements IFoo
~~~~
</expected>)
End Sub
<Fact>
Public Sub UnimplementedProperties()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnimplementedProperties">
<file name="a.vb">
Option Strict On
Interface IFoo
ReadOnly Property Style(ByVal s As String) As String
ReadOnly Property Style(ByVal answer As Integer) As String
ReadOnly Property Style(ByVal answer As Long) As String
End Interface
Class Foo
Implements IFoo
Public ReadOnly Property Y(ByVal a As Integer) As String Implements IFoo.Style
Get
Return "I said: " + a.ToString()
End Get
End Property
Public Overridable ReadOnly Property Style(ByVal s As Long) As String
Get
Return "You dont say: "
End Get
End Property
End Class
Class Bar
Inherits Foo
Implements IFoo
Public Overrides ReadOnly Property Style(ByVal s As Long) As String
Get
Return "You dont say: "
End Get
End Property
Public ReadOnly Property X(ByVal a As String) As String Implements IFoo.Style
Get
Return "I said: " + a.ToString()
End Get
End Property
End Class
</file>
</compilation>)
Dim globalNS = comp.GlobalNamespace
Dim iFooType = DirectCast(globalNS.GetMembers("IFoo").First(), NamedTypeSymbol)
Dim fooType = DirectCast(globalNS.GetMembers("Foo").First(), NamedTypeSymbol)
Dim barType = DirectCast(globalNS.GetMembers("Bar").First(), NamedTypeSymbol)
Dim ifooProps = iFooType.GetMembers("Style").AsEnumerable().Cast(Of PropertySymbol)()
Dim ifooTypeStyleWithString = (From m In ifooProps Where m.Parameters(0).Type.SpecialType = SpecialType.System_String).First()
Dim ifooTypeStyleWithStringGetter = ifooTypeStyleWithString.GetMethod
Dim ifooTypeStyleWithInt = (From m In ifooProps Where m.Parameters(0).Type.SpecialType = SpecialType.System_Int32).First()
Dim ifooTypeStyleWithIntGetter = ifooTypeStyleWithInt.GetMethod
Dim ifooTypeStyleWithLong = (From m In ifooProps Where m.Parameters(0).Type.SpecialType = SpecialType.System_Int64).First()
Dim ifooTypeStyleWithLongGetter = ifooTypeStyleWithLong.GetMethod
Dim barX = DirectCast(barType.GetMembers("X").First(), PropertySymbol)
Dim barXGetter = barX.GetMethod
Dim fooY = DirectCast(fooType.GetMembers("Y").First(), PropertySymbol)
Dim fooYGetter = fooY.GetMethod
Dim fooStyle = DirectCast(fooType.GetMembers("Style").First(), PropertySymbol)
Dim fooStyleGetter = fooStyle.GetMethod
Dim barStyle = DirectCast(barType.GetMembers("Style").First(), PropertySymbol)
Dim barStyleGetter = barStyle.GetMethod
Assert.Equal(fooY, barType.FindImplementationForInterfaceMember(ifooTypeStyleWithInt))
Assert.Equal(fooYGetter, barType.FindImplementationForInterfaceMember(ifooTypeStyleWithIntGetter))
Assert.Equal(barX, barType.FindImplementationForInterfaceMember(ifooTypeStyleWithString))
Assert.Equal(barXGetter, barType.FindImplementationForInterfaceMember(ifooTypeStyleWithStringGetter))
Assert.Equal(fooY, fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithInt))
Assert.Equal(fooYGetter, fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithIntGetter))
Assert.Null(fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithString))
Assert.Null(fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithStringGetter))
Assert.Null(fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithLong))
Assert.Null(fooType.FindImplementationForInterfaceMember(ifooTypeStyleWithLongGetter))
Assert.Null(barType.FindImplementationForInterfaceMember(ifooTypeStyleWithLong))
Assert.Null(barType.FindImplementationForInterfaceMember(ifooTypeStyleWithLongGetter))
Assert.Equal(1, barX.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeStyleWithString, barX.ExplicitInterfaceImplementations(0))
Assert.Equal(1, barXGetter.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeStyleWithStringGetter, barXGetter.ExplicitInterfaceImplementations(0))
Assert.Equal(1, fooY.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeStyleWithInt, fooY.ExplicitInterfaceImplementations(0))
Assert.Equal(1, fooYGetter.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeStyleWithIntGetter, fooYGetter.ExplicitInterfaceImplementations(0))
Assert.Equal(0, fooStyle.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, fooStyleGetter.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, barStyle.ExplicitInterfaceImplementations.Length)
Assert.Equal(0, barStyleGetter.ExplicitInterfaceImplementations.Length)
CompilationUtils.AssertTheseDiagnostics(comp, <expected>
BC30149: Class 'Foo' must implement 'ReadOnly Property Style(answer As Long) As String' for interface 'IFoo'.
Implements IFoo
~~~~
BC30149: Class 'Foo' must implement 'ReadOnly Property Style(s As String) As String' for interface 'IFoo'.
Implements IFoo
~~~~
</expected>)
End Sub
<Fact>
Public Sub UnimplementedInterfaceAPI()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnimplementedInterfaceAPI">
<file name="a.vb">
Option Strict On
Interface IFoo
Sub SayItWithStyle(ByVal a As Integer)
End Interface
Class Foo
Public Sub Y(ByVal a As Integer) Implements IFoo.SayItWithStyle
System.Console.WriteLine("The answer is: {0}", a)
End Sub
Public Overridable Sub SayItWithStyle(ByVal answer As Long)
System.Console.WriteLine("You don't say: {0}", answer)
End Sub
End Class
</file>
</compilation>)
Dim globalNS = comp.GlobalNamespace
Dim iFooType = DirectCast(globalNS.GetMembers("IFoo").First(), NamedTypeSymbol)
Dim fooType = DirectCast(globalNS.GetMembers("Foo").First(), NamedTypeSymbol)
Dim ifooMethods = iFooType.GetMembers("SayItWithStyle").AsEnumerable().Cast(Of MethodSymbol)()
Dim ifooTypeSayWithInt = (From m In ifooMethods Where m.Parameters(0).Type.SpecialType = SpecialType.System_Int32).First()
Dim fooY = DirectCast(fooType.GetMembers("Y").First(), MethodSymbol)
Assert.Null(fooType.FindImplementationForInterfaceMember(ifooTypeSayWithInt))
Assert.Equal(1, fooY.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooTypeSayWithInt, fooY.ExplicitInterfaceImplementations(0))
CompilationUtils.AssertTheseDiagnostics(comp, <expected>
BC31035: Interface 'IFoo' is not implemented by this class.
Public Sub Y(ByVal a As Integer) Implements IFoo.SayItWithStyle
~~~~
</expected>)
End Sub
<Fact>
Public Sub GenericInterface()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SimpleImplementation">
<file name="a.vb"><![CDATA[
Option Strict On
Imports System.Collections.Generic
Class Outer(Of X)
Interface IFoo(Of T, U)
Sub SayItWithStyle(ByVal a As T, c As X)
Sub SayItWithStyle(ByVal b As U, c As X)
End Interface
Class Foo(Of Y)
Implements IFoo(Of X, List(Of Y))
Public Sub M1(a As X, c As X) Implements Outer(Of X).IFoo(Of X, List(Of Y)).SayItWithStyle
End Sub
Public Sub M2(b As List(Of Y), c As X) Implements Outer(Of X).IFoo(Of X, List(Of Y)).SayItWithStyle
End Sub
End Class
<System.Serializable>
Class FooS(Of T, U)
End Class
End Class
]]></file>
</compilation>)
Dim globalNS = comp.GlobalNamespace
Dim listOfT = comp.GetTypeByMetadataName("System.Collections.Generic.List`1")
Dim listOfString = listOfT.Construct(comp.GetSpecialType(SpecialType.System_String))
Dim outerOfX = DirectCast(globalNS.GetMembers("Outer").First(), NamedTypeSymbol)
Dim outerOfInt = outerOfX.Construct(comp.GetSpecialType(SpecialType.System_Int32))
Dim iFooOfIntTU = DirectCast(outerOfInt.GetMembers("IFoo").First(), NamedTypeSymbol)
Assert.IsType(Of SubstitutedNamedType.SpecializedGenericType)(iFooOfIntTU)
Assert.False(DirectCast(iFooOfIntTU, INamedTypeSymbol).IsSerializable)
Dim fooSOfIntTU = DirectCast(outerOfInt.GetMembers("FooS").First(), NamedTypeSymbol)
Assert.IsType(Of SubstitutedNamedType.SpecializedGenericType)(fooSOfIntTU)
Assert.True(DirectCast(fooSOfIntTU, INamedTypeSymbol).IsSerializable)
Dim iFooOfIntIntListOfString = iFooOfIntTU.Construct(comp.GetSpecialType(SpecialType.System_Int32), listOfString)
Dim fooOfIntY = DirectCast(outerOfInt.GetMembers("Foo").First(), NamedTypeSymbol)
Dim fooOfIntString = fooOfIntY.Construct(comp.GetSpecialType(SpecialType.System_String))
Dim iFooOfIntIntListOfStringMethods = iFooOfIntIntListOfString.GetMembers("SayItWithStyle").AsEnumerable().Cast(Of MethodSymbol)()
Dim ifooOfIntIntStringSay1 = (From m In iFooOfIntIntListOfStringMethods Where TypeSymbol.Equals(m.Parameters(0).Type, comp.GetSpecialType(SpecialType.System_Int32), TypeCompareKind.ConsiderEverything)).First()
Dim ifooOfIntIntStringSay2 = (From m In iFooOfIntIntListOfStringMethods Where Not TypeSymbol.Equals(m.Parameters(0).Type, comp.GetSpecialType(SpecialType.System_Int32), TypeCompareKind.ConsiderEverything)).First()
Dim fooOfIntStringM1 = DirectCast(fooOfIntString.GetMembers("M1").First(), MethodSymbol)
Dim fooOfIntStringM2 = DirectCast(fooOfIntString.GetMembers("M2").First(), MethodSymbol)
Assert.Equal(1, fooOfIntStringM1.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooOfIntIntStringSay1, fooOfIntStringM1.ExplicitInterfaceImplementations(0))
Assert.Equal(1, fooOfIntStringM2.ExplicitInterfaceImplementations.Length)
Assert.Equal(ifooOfIntIntStringSay2, fooOfIntStringM2.ExplicitInterfaceImplementations(0))
CompilationUtils.AssertNoErrors(comp)
End Sub
' See MDInterfaceMapping.cs to understand this test case.
<Fact>
Public Sub MetadataInterfaceMapping()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="ImplementStatic">
<file name="a.vb">
Public Class D
Inherits C
Implements IFoo
End Class
</file>
</compilation>, {TestReferences.SymbolsTests.Interface.MDInterfaceMapping})
Dim globalNS = comp.GlobalNamespace
Dim iFoo = DirectCast(globalNS.GetMembers("IFoo").Single(), NamedTypeSymbol)
Dim dClass = DirectCast(globalNS.GetMembers("D").Single(), NamedTypeSymbol)
Dim iFooMethod = DirectCast(iFoo.GetMembers("Foo").Single(), MethodSymbol)
' IFoo.Foo should be found in A.
Dim implementedMethod = dClass.FindImplementationForInterfaceMember(iFooMethod)
Assert.Equal("A", implementedMethod.ContainingType.Name)
CompilationUtils.AssertNoErrors(comp)
End Sub
<Fact>
Public Sub InterfaceReimplementation()
CompileAndVerify(
<compilation name="InterfaceReimplementation">
<file name="a.vb">
Imports System
Interface I1
Sub foo()
Sub quux()
End Interface
Interface I2
Inherits I1
Sub bar()
End Interface
Class X
Implements I1
Public Sub foo1() Implements I1.foo
Console.WriteLine("X.foo1")
End Sub
Public Sub quux1() Implements I1.quux
Console.WriteLine("X.quux1")
End Sub
Public Overridable Sub foo()
Console.WriteLine("x.foo")
End Sub
End Class
Class Y
Inherits X
Implements I2
Public Overridable Sub bar()
Console.WriteLine("Y.bar")
End Sub
Public Overridable Sub quux()
Console.WriteLine("Y.quux")
End Sub
Public Overrides Sub foo()
Console.WriteLine("Y.foo")
End Sub
Public Sub bar1() Implements I2.bar
Console.WriteLine("Y.bar1")
End Sub
End Class
Module Module1
Sub Main()
Dim a As Y = New Y()
a.foo()
a.bar()
a.quux()
Dim b As I2 = a
b.foo()
b.bar()
b.quux()
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Y.foo
Y.bar
Y.quux
X.foo1
Y.bar1
X.quux1
]]>)
End Sub
<Fact>
Public Sub Bug6095()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug6095">
<file name="a.vb">
Imports System
Namespace ArExtByVal001
Friend Module ArExtByVal001mod
Class Cls7
Implements I7
Interface I7
Function Scen7(ByVal Ary() As Single)
End Interface
Function Cls7_Scen7(ByVal Ary() As Single) Implements I7.Scen7
Ary(70) = Ary(70) + 100
Return Ary(0)
End Function
End Class
End Module
End Namespace
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub Bug7931()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Bug6095">
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Namespace NS
Interface IFoo(Of T)
Function F(Of R)(ParamArray p As R()) As R
End Interface
Interface IBar(Of R)
Function F(ParamArray p As R()) As R
End Interface
Class Impl
Implements NS.IFoo(Of Char)
Implements IBar(Of Short)
Function F(ParamArray p As Short()) As Short Implements IFoo(Of Char).F, IBar(Of Short).F
Return Nothing
End Function
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30149: Class 'Impl' must implement 'Function F(Of R)(ParamArray p As R()) As R' for interface 'IFoo(Of Char)'.
Implements NS.IFoo(Of Char)
~~~~~~~~~~~~~~~~
BC30401: 'F' cannot implement 'F' because there is no matching function on interface 'IFoo(Of Char)'.
Function F(ParamArray p As Short()) As Short Implements IFoo(Of Char).F, IBar(Of Short).F
~~~~~~~~~~~~~~~
</expected>)
End Sub
<WorkItem(543664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543664")>
<Fact()>
Public Sub Bug11554()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Bug11554">
<file name="a.vb">
Interface I
Sub M(Optional ByRef x As Short = 1)
End Interface
Class C
'COMPILEERROR: BC30149, "I"
Implements I
'COMPILEERROR: BC30401, "I.M"
Sub M(Optional ByRef x As Short = 0) Implements I.M
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30149: Class 'C' must implement 'Sub M([ByRef x As Short = 1])' for interface 'I'.
Implements I
~
BC30401: 'M' cannot implement 'M' because there is no matching sub on interface 'I'.
Sub M(Optional ByRef x As Short = 0) Implements I.M
~~~
</expected>)
End Sub
<Fact>
Public Sub PropAccessorAgreement()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PropAccessorAgreement">
<file name="a.vb">
Interface I1
Property rw1 As Integer
Property rw2 As Integer
Property rw3 As Integer
ReadOnly Property ro1 As Integer
ReadOnly Property ro2 As Integer
ReadOnly Property ro3 As Integer
WriteOnly Property wo1 As Integer
WriteOnly Property wo2 As Integer
WriteOnly Property wo3 As Integer
End Interface
Class X
Implements I1
Public Property a As Integer Implements I1.ro1
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public ReadOnly Property b As Integer Implements I1.ro2
Get
Return 0
End Get
End Property
Public WriteOnly Property c As Integer Implements I1.ro3
Set(value As Integer)
End Set
End Property
Public Property d As Integer Implements I1.rw1
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public ReadOnly Property e As Integer Implements I1.rw2
Get
Return 0
End Get
End Property
Public WriteOnly Property f As Integer Implements I1.rw3
Set(value As Integer)
End Set
End Property
Public Property g As Integer Implements I1.wo1
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public ReadOnly Property h As Integer Implements I1.wo2
Get
Return 0
End Get
End Property
Public WriteOnly Property i As Integer Implements I1.wo3
Set(value As Integer)
End Set
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC31444: 'ReadOnly Property ro3 As Integer' cannot be implemented by a WriteOnly property.
Public WriteOnly Property c As Integer Implements I1.ro3
~~~~~~
BC31444: 'Property rw2 As Integer' cannot be implemented by a ReadOnly property.
Public ReadOnly Property e As Integer Implements I1.rw2
~~~~~~
BC31444: 'Property rw3 As Integer' cannot be implemented by a WriteOnly property.
Public WriteOnly Property f As Integer Implements I1.rw3
~~~~~~
BC31444: 'WriteOnly Property wo2 As Integer' cannot be implemented by a ReadOnly property.
Public ReadOnly Property h As Integer Implements I1.wo2
~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ImplementDefaultProperty()
Dim source =
<compilation>
<file name="a.vb">
Interface I1
Default Property P1(param1 As Integer) As String
End Interface
Class C1 : Implements I1
Private _p1 As String
Private _p2 As String
Public Property P1(param1 As Integer) As String Implements I1.P1
Get
Return _p1
End Get
Set(value As String)
_p1 = value
End Set
End Property
Default Public Property P2(param1 As Integer) As String
Get
Return _p2
End Get
Set(value As String)
_p2 = value
End Set
End Property
End Class
Module Program
Sub Main(args As String())
Dim c As C1 = New C1()
DirectCast(c, I1)(1) = "P1"
c(1) = "P2"
System.Console.WriteLine(String.Join(",", c.P1(1), c.P2(1)))
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source, expectedOutput:="P1,P2")
End Sub
<Fact>
Public Sub ImplementReadOnlyUsingReadWriteWithPrivateSet()
Dim source =
<compilation>
<file name="a.vb">
Interface I1
ReadOnly Property bar() As Integer
End Interface
Public Class C2
Implements I1
Public Property bar() As Integer Implements I1.bar
Get
Return 2
End Get
Private Set(ByVal value As Integer)
End Set
End Property
End Class
</file>
</compilation>
CompileAndVerify(source)
End Sub
<WorkItem(541934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541934")>
<Fact>
Public Sub ImplementGenericInterfaceProperties()
Dim source =
<compilation>
<file name="a.vb">
Imports ImportedAlias = System.Int32
Interface I1(Of T)
ReadOnly Property P1() As T
End Interface
Public Class C1(Of T)
Implements I1(Of T)
Public ReadOnly Property P() As T Implements I1(Of T).P1
Get
Return Nothing
End Get
End Property
End Class
Public Class C2
Implements I1(Of Integer)
Public ReadOnly Property P1() As Integer Implements I1(Of Integer).P1
Get
Return 2
End Get
End Property
End Class
</file>
</compilation>
CompileAndVerify(source)
End Sub
<Fact>
Public Sub ImplementGenericInterfaceMethods()
Dim source =
<compilation>
<file name="a.vb">
Imports System.Collections.Generic
Imports ImportedAlias = System.Int32
Interface I1(Of T)
Sub M1()
Function M1(Of U)(x As U, y As List(Of U), z As T, w As List(Of T)) As Dictionary(Of T, List(Of U))
End Interface
Public Class C1(Of T)
Implements I1(Of T)
Public Sub M() Implements I1(Of T).M1
End Sub
Public Function M(Of U)(x As U, y As List(Of U), z As T, w As List(Of T)) As Dictionary(Of T, List(Of U)) Implements I1(Of T).M1
Return Nothing
End Function
End Class
Public Class C2
Implements I1(Of Integer)
Public Sub M1() Implements I1(Of ImportedAlias).M1
End Sub
Public Function M1(Of U)(x As U, y As List(Of U), z As ImportedAlias, w As List(Of ImportedAlias)) As Dictionary(Of ImportedAlias, List(Of U)) Implements I1(Of ImportedAlias).M1
Return Nothing
End Function
End Class
</file>
</compilation>
CompileAndVerify(source)
End Sub
<WorkItem(543253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543253")>
<Fact()>
Public Sub ImplementMethodWithOptionalParameter()
Dim source =
<compilation>
<file name="a.vb">
Public Enum E1
A
B
C
End Enum
Public Interface I1
Sub S1(i as integer, optional j as integer = 10, optional e as E1 = E1.B)
End Interface
Public Class C1
Implements I1
Sub C1_S1(i as integer, optional j as integer = 10, optional e as E1 = E1.B) implements I1.S1
End Sub
End Class
</file>
</compilation>
CompileAndVerify(source).VerifyDiagnostics()
End Sub
<Fact, WorkItem(544531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544531")>
Public Sub VarianceAmbiguity1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceAmbiguity1">
<file name="a.vb">
Option Strict On
Class Animals : End Class
Class Mammals : Inherits Animals
End Class
Class Fish
Inherits Mammals
End Class
Interface IEnumerable(Of Out T)
Function Foo() As T
End Interface
Class C
Implements IEnumerable(Of Fish)
Implements IEnumerable(Of Mammals)
Implements IEnumerable(Of Animals)
Public Function Foo() As Fish Implements IEnumerable(Of Fish).Foo
Return New Fish
End Function
Public Function Foo1() As Mammals Implements IEnumerable(Of Mammals).Foo
Return New Mammals
End Function
Public Function Foo2() As Animals Implements IEnumerable(Of Animals).Foo
Return New Animals
End Function
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC42333: Interface 'IEnumerable(Of Mammals)' is ambiguous with another implemented interface 'IEnumerable(Of Fish)' due to the 'In' and 'Out' parameters in 'Interface IEnumerable(Of Out T)'.
Implements IEnumerable(Of Mammals)
~~~~~~~~~~~~~~~~~~~~~~~
BC42333: Interface 'IEnumerable(Of Animals)' is ambiguous with another implemented interface 'IEnumerable(Of Fish)' due to the 'In' and 'Out' parameters in 'Interface IEnumerable(Of Out T)'.
Implements IEnumerable(Of Animals)
~~~~~~~~~~~~~~~~~~~~~~~
BC42333: Interface 'IEnumerable(Of Animals)' is ambiguous with another implemented interface 'IEnumerable(Of Mammals)' due to the 'In' and 'Out' parameters in 'Interface IEnumerable(Of Out T)'.
Implements IEnumerable(Of Animals)
~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact, WorkItem(544531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544531")>
Public Sub VarianceAmbiguity2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceAmbiguity2">
<file name="a.vb">
Option Strict On
Class Animals : End Class
Class Mammals : Inherits Animals
End Class
Class Fish
Inherits Mammals
End Class
Interface IEnumerable(Of Out T)
Function Foo() As T
End Interface
Interface EnumFish
Inherits IEnumerable(Of Fish)
End Interface
Interface EnumAnimals
Inherits IEnumerable(Of Animals)
End Interface
Interface I
Inherits EnumFish, EnumAnimals, IEnumerable(Of Mammals)
End Interface
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC42333: Interface 'EnumAnimals' is ambiguous with another implemented interface 'EnumFish' due to the 'In' and 'Out' parameters in 'Interface IEnumerable(Of Out T)'.
Inherits EnumFish, EnumAnimals, IEnumerable(Of Mammals)
~~~~~~~~~~~
BC42333: Interface 'IEnumerable(Of Mammals)' is ambiguous with another implemented interface 'EnumAnimals' due to the 'In' and 'Out' parameters in 'Interface IEnumerable(Of Out T)'.
Inherits EnumFish, EnumAnimals, IEnumerable(Of Mammals)
~~~~~~~~~~~~~~~~~~~~~~~
BC42333: Interface 'IEnumerable(Of Mammals)' is ambiguous with another implemented interface 'EnumFish' due to the 'In' and 'Out' parameters in 'Interface IEnumerable(Of Out T)'.
Inherits EnumFish, EnumAnimals, IEnumerable(Of Mammals)
~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub VarianceAmbiguity3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceAmbiguity3">
<file name="a.vb">
Option Strict On
Public Interface IFoo(Of Out T, U)
End Interface
Class X
End Class
Class Y
End Class
Class GX(Of T)
End Class
Class GY(Of T)
End Class
Class A
' Not conflicting: 2nd type parameter is invariant, types are different and cannot unify
' Dev11 reports not conflicting
Implements IFoo(Of X, X), IFoo(Of Y, Y)
End Class
Class B(Of T)
' Not conflicting: 2nd type parameter is invariant, types are different and cannot unify
' Dev11 reports conflicting
Implements IFoo(Of X, GX(Of Integer)), IFoo(Of Y, GY(Of Integer))
End Class
Class C(Of T, U)
' Conflicting: 2nd type parameter is invariant, GX(Of T) and GX(Of U) might unify
' Dev11 reports conflicting
Implements IFoo(Of X, GX(Of T)), IFoo(Of Y, GX(Of U))
End Class
Class D(Of T, U)
' Conflicting: 2nd type parameter is invariant, T and U might unify
' E.g., If D(Of String, String) is cast to IFoo(Of Object, String), its implementation is ambiguous.
' Dev11 reports non-conflicting
Implements IFoo(Of X, T), IFoo(Of Y, U)
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC42333: Interface 'IFoo(Of Y, GX(Of U))' is ambiguous with another implemented interface 'IFoo(Of X, GX(Of T))' due to the 'In' and 'Out' parameters in 'Interface IFoo(Of Out T, U)'.
Implements IFoo(Of X, GX(Of T)), IFoo(Of Y, GX(Of U))
~~~~~~~~~~~~~~~~~~~~
BC42333: Interface 'IFoo(Of Y, U)' is ambiguous with another implemented interface 'IFoo(Of X, T)' due to the 'In' and 'Out' parameters in 'Interface IFoo(Of Out T, U)'.
Implements IFoo(Of X, T), IFoo(Of Y, U)
~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub VarianceAmbiguity4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceAmbiguity4">
<file name="a.vb">
Option Strict On
Public Interface IFoo(Of Out T, Out U)
End Interface
Class X
End Class
Class Y
End Class
Class GX(Of T)
End Class
Class GY(Of T)
End Class
Structure S(Of T)
End Structure
Class A
' Not conflicting: 2nd type parameter is "Out", types can't unify and one is value type
' Dev11 reports not conflicting
Implements IFoo(Of X, Integer), IFoo(Of Y, Y)
End Class
Class B(Of T)
' Conflicting: 2nd type parameter is "Out", 2nd type parameter could unify in B(Of Integer)
' Dev11 reports not conflicting
Implements IFoo(Of X, Integer), IFoo(Of Y, T)
End Class
Class C(Of T, U)
' Conflicting: 2nd type parameter is "Out", , S(Of T) and S(Of U) might unify
' Dev11 reports conflicting
Implements IFoo(Of X, S(Of T)), IFoo(Of Y, S(Of U))
End Class
Class D(Of T, U)
' Not Conflicting: 2nd type parameter is "Out", String and S(Of U) can't unify and S(Of U) is a value type.
' Dev11 reports conflicting
Implements IFoo(Of X, String), IFoo(Of Y, S(Of U))
End Class
Class E(Of T, U)
' Not Conflicting: 1st type parameter; one is Object; 2nd type parameter is "Out", S(Of T) is a value type.
' Dev11 reports not conflicting
Implements IFoo(Of Object, S(Of T)), IFoo(Of X, S(Of U))
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC42333: Interface 'IFoo(Of Y, T)' is ambiguous with another implemented interface 'IFoo(Of X, Integer)' due to the 'In' and 'Out' parameters in 'Interface IFoo(Of Out T, Out U)'.
Implements IFoo(Of X, Integer), IFoo(Of Y, T)
~~~~~~~~~~~~~
BC42333: Interface 'IFoo(Of Y, S(Of U))' is ambiguous with another implemented interface 'IFoo(Of X, S(Of T))' due to the 'In' and 'Out' parameters in 'Interface IFoo(Of Out T, Out U)'.
Implements IFoo(Of X, S(Of T)), IFoo(Of Y, S(Of U))
~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub VarianceAmbiguity5()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceAmbiguity5">
<file name="a.vb">
Option Strict On
Public Interface IFoo(Of In T, In U)
End Interface
Class X
End Class
Class Y
End Class
NotInheritable Class Z
End Class
Class W
Inherits X
End Class
Interface J
End Interface
Interface K
End Interface
Class GX(Of T)
End Class
Class GY(Of T)
End Class
Structure S(Of T)
End Structure
Class A
' Not conflicting: Neither X or Y derives from each other
' Dev11 reports conflicting
Implements IFoo(Of X, Integer), IFoo(Of Y, Integer)
End Class
Class B
' Conflicting: 1st type argument could convert to type deriving from X implementing J.
' Dev11 reports conflicting
Implements IFoo(Of X, Integer), IFoo(Of J, Integer)
End Class
Class C(Of T, U)
' Not conflicting: 1st type argument has sealed type Z.
' Dev11 reports conflicting
Implements IFoo(Of J, Integer), IFoo(Of Z, Integer)
End Class
Class D(Of T, U)
' Not conflicting: 1st type argument has value type Integer.
' Dev11 reports not conflicting
Implements IFoo(Of Integer, Integer), IFoo(Of X, Integer)
End Class
Class E
' Conflicting, W derives from X
' Dev11 reports conflicting
Implements IFoo(Of W, Integer), IFoo(Of X, Integer)
End Class
Class F(Of T)
' Conflicting: X and J cause ambiguity, T and Integer could unify
' Dev11 reports not conflicting
Implements IFoo(Of X, Integer), IFoo(Of J, T)
End Class
Class G(Of T)
' Not conflicting: X and J cause ambiguity, GX(Of T) and Integer can't unify, Integer is value type prevents ambiguity
' Dev11 reports conflicting
Implements IFoo(Of X, Integer), IFoo(Of J, GX(Of T))
End Class
Class H
' Not conflicting, X and J cause ambiguity, neither X or Z derive from each other.
' Dev11 reports conflicting
Implements IFoo(Of X, Z), IFoo(Of J, X)
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC42333: Interface 'IFoo(Of J, Integer)' is ambiguous with another implemented interface 'IFoo(Of X, Integer)' due to the 'In' and 'Out' parameters in 'Interface IFoo(Of In T, In U)'.
Implements IFoo(Of X, Integer), IFoo(Of J, Integer)
~~~~~~~~~~~~~~~~~~~
BC42333: Interface 'IFoo(Of X, Integer)' is ambiguous with another implemented interface 'IFoo(Of W, Integer)' due to the 'In' and 'Out' parameters in 'Interface IFoo(Of In T, In U)'.
Implements IFoo(Of W, Integer), IFoo(Of X, Integer)
~~~~~~~~~~~~~~~~~~~
BC42333: Interface 'IFoo(Of J, T)' is ambiguous with another implemented interface 'IFoo(Of X, Integer)' due to the 'In' and 'Out' parameters in 'Interface IFoo(Of In T, In U)'.
Implements IFoo(Of X, Integer), IFoo(Of J, T)
~~~~~~~~~~~~~
</expected>)
End Sub
<WorkItem(545863, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545863")>
<Fact>
Public Sub Bug14589()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Bug14589">
<file name="a.vb">
Interface I(Of T)
Sub Foo(x As T)
End Interface
Class A(Of T)
Class B
Inherits A(Of B)
Implements I(Of B.B)
End Class
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30149: Class 'B' must implement 'Sub Foo(x As A(Of A(Of A(Of T).B).B).B)' for interface 'I(Of B)'.
Implements I(Of B.B)
~~~~~~~~~
</expected>)
End Sub
<WorkItem(578706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578706")>
<Fact>
Public Sub ImplicitImplementationSourceVsMetadata()
Dim source1 = <![CDATA[
public interface I
{
void Implicit();
void Explicit();
}
public class A
{
public void Implicit()
{
System.Console.WriteLine("A.Implicit");
}
public void Explicit()
{
System.Console.WriteLine("A.Explicit");
}
}
public class B : A, I
{
}
]]>
Dim source2 =
<compilation name="Lib2">
<file name="a.vb">
Public Class C
Inherits B
Public Shadows Sub Implicit()
System.Console.WriteLine("C.Implicit")
End Sub
Public Shadows Sub Explicit()
System.Console.WriteLine("C.Explicit")
End Sub
End Class
Public Class D
Inherits C
Implements I
Public Shadows Sub Explicit() Implements I.Explicit
System.Console.WriteLine("D.Explicit")
End Sub
End Class
</file>
</compilation>
Dim source3 =
<compilation name="Test">
<file name="a.vb">
Module Test
Sub Main()
Dim a As New A()
Dim b As New B()
Dim c As New C()
Dim d As New D()
a.Implicit()
b.Implicit()
c.Implicit()
d.Implicit()
System.Console.WriteLine()
a.Explicit()
b.Explicit()
c.Explicit()
d.Explicit()
System.Console.WriteLine()
Dim i As I
'i = a
'i.Implicit()
'i.Explicit()
i = b
i.Implicit()
i.Explicit()
i = c
i.Implicit()
i.Explicit()
i = d
i.Implicit()
i.Explicit()
End Sub
End Module
</file>
</compilation>
Dim expectedOutput = <![CDATA[
A.Implicit
A.Implicit
C.Implicit
C.Implicit
A.Explicit
A.Explicit
C.Explicit
D.Explicit
A.Implicit
A.Explicit
A.Implicit
A.Explicit
A.Implicit
D.Explicit
]]>
Dim comp1 = CreateCSharpCompilation("Lib1", source1)
Dim ref1a = comp1.EmitToImageReference()
Dim ref1b = comp1.EmitToImageReference()
Dim comp2 = CreateCompilationWithMscorlib40AndReferences(source2, {ref1a})
Dim ref2Metadata = comp2.EmitToImageReference()
Dim ref2Source = New VisualBasicCompilationReference(comp2)
Dim verifyComp3 As Action(Of MetadataReference, MetadataReference) =
Sub(ref1, ref2)
Dim comp3 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source3, {ref1, ref2}, TestOptions.ReleaseExe)
CompileAndVerify(comp3, expectedOutput:=expectedOutput)
Dim globalNamespace = comp3.GlobalNamespace
Dim typeI = globalNamespace.GetMember(Of NamedTypeSymbol)("I")
Dim typeA = globalNamespace.GetMember(Of NamedTypeSymbol)("A")
Dim typeB = globalNamespace.GetMember(Of NamedTypeSymbol)("B")
Dim typeC = globalNamespace.GetMember(Of NamedTypeSymbol)("C")
Dim typeD = globalNamespace.GetMember(Of NamedTypeSymbol)("D")
Dim interfaceImplicit = typeI.GetMember(Of MethodSymbol)("Implicit")
Dim interfaceExplicit = typeI.GetMember(Of MethodSymbol)("Explicit")
Assert.Null(typeA.FindImplementationForInterfaceMember(interfaceImplicit))
Assert.Null(typeA.FindImplementationForInterfaceMember(interfaceExplicit))
Assert.Equal(typeA, typeB.FindImplementationForInterfaceMember(interfaceImplicit).ContainingType)
Assert.Equal(typeA, typeB.FindImplementationForInterfaceMember(interfaceExplicit).ContainingType)
Assert.Equal(typeA, typeC.FindImplementationForInterfaceMember(interfaceImplicit).ContainingType)
Assert.Equal(typeA, typeC.FindImplementationForInterfaceMember(interfaceExplicit).ContainingType)
Assert.Equal(typeA, typeD.FindImplementationForInterfaceMember(interfaceImplicit).ContainingType)
Assert.Equal(typeD, typeD.FindImplementationForInterfaceMember(interfaceExplicit).ContainingType)
' In metadata, D does not declare that it implements I.
Assert.Equal(If(TypeOf ref2 Is MetadataImageReference, 0, 1), typeD.Interfaces.Length)
End Sub
' Normal
verifyComp3(ref1a, ref2Metadata)
verifyComp3(ref1a, ref2Source)
' Retargeting
verifyComp3(ref1b, ref2Metadata)
verifyComp3(ref1b, ref2Source)
End Sub
<WorkItem(578746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578746")>
<Fact>
Public Sub Bug578746a()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Interface I(Of T)
Sub Foo(Optional x As Integer = Nothing)
End Interface
Class C
Implements I(Of Integer)
Public Sub Foo(Optional x As Integer = 0) Implements I(Of Integer).Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<WorkItem(578746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578746")>
<Fact>
Public Sub Bug578746b()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Interface I
Sub Foo(Optional x As Decimal = Nothing)
End Interface
Class C
Implements I
Public Sub Foo(Optional x As Decimal = 0.0f) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<WorkItem(578746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578746")>
<Fact>
Public Sub Bug578746c()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Interface I
Sub Foo(Optional x As Object = Nothing)
End Interface
Class C
Implements I
Public Sub Foo(Optional x As Object = 0) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30149: Class 'C' must implement 'Sub Foo([x As Object = Nothing])' for interface 'I'.
Implements I
~
BC30401: 'Foo' cannot implement 'Foo' because there is no matching sub on interface 'I'.
Public Sub Foo(Optional x As Object = 0) Implements I.Foo
~~~~~
</expected>)
End Sub
<WorkItem(578746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578746")>
<Fact>
Public Sub Bug578746d()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Class A : End Class
Interface I
Sub Foo(Of T As A)(Optional x As A = DirectCast(Nothing, T))
End Interface
Class C: Implements I
Public Sub Foo(Of T As A)(Optional x As A = Nothing) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<WorkItem(578074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578074")>
<Fact>
Public Sub Bug578074()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Interface I
Sub Foo(Optional x As Object = 1D)
End Interface
Class C
Implements I
Public Sub Foo(Optional x As Object = 1.0D) Implements I.Foo
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<WorkItem(608228, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608228")>
<Fact>
Public Sub ImplementPropertyWithByRefParameter()
Dim il = <![CDATA[
.class interface public abstract auto ansi IRef
{
.method public newslot specialname abstract strict virtual
instance string get_P(int32& x) cil managed
{
} // end of method IRef::get_P
.method public newslot specialname abstract strict virtual
instance void set_P(int32& x,
string Value) cil managed
{
} // end of method IRef::set_P
.property instance string P(int32&)
{
.get instance string IRef::get_P(int32&)
.set instance void IRef::set_P(int32&,
string)
} // end of property IRef::P
} // end of class IRef
]]>
Dim source =
<compilation>
<file name="a.vb">
Public Class Impl
Implements IRef
Public Property P(x As Integer) As String Implements IRef.P
Get
Return Nothing
End Get
Set(value As String)
End Set
End Property
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(source, il)
' CONSIDER: Dev11 doesn't report ERR_UnimplementedMember3.
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_IdentNotMemberOfInterface4, "IRef.P").WithArguments("P", "P", "property", "IRef"),
Diagnostic(ERRID.ERR_UnimplementedMember3, "IRef").WithArguments("Class", "Impl", "Property P(ByRef x As Integer) As String", "IRef"))
Dim globalNamespace = compilation.GlobalNamespace
Dim interfaceType = globalNamespace.GetMember(Of NamedTypeSymbol)("IRef")
Dim interfaceProperty = interfaceType.GetMember(Of PropertySymbol)("P")
Assert.True(interfaceProperty.Parameters.Single().IsByRef)
Dim classType = globalNamespace.GetMember(Of NamedTypeSymbol)("Impl")
Dim classProperty = classType.GetMember(Of PropertySymbol)("P")
Assert.False(classProperty.Parameters.Single().IsByRef)
Assert.Null(classType.FindImplementationForInterfaceMember(interfaceProperty))
End Sub
<WorkItem(718115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718115")>
<Fact>
Public Sub ExplicitlyImplementedAccessorsWithoutEvent()
Dim il = <![CDATA[
.class interface public abstract auto ansi I
{
.method public hidebysig newslot specialname abstract virtual
instance void add_E(class [mscorlib]System.Action 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void remove_E(class [mscorlib]System.Action 'value') cil managed
{
}
.event [mscorlib]System.Action E
{
.addon instance void I::add_E(class [mscorlib]System.Action)
.removeon instance void I::remove_E(class [mscorlib]System.Action)
}
} // end of class I
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
implements I
{
.method private hidebysig newslot specialname virtual final
instance void I.add_E(class [mscorlib]System.Action 'value') cil managed
{
.override I::add_E
ldstr "Explicit implementation"
call void [mscorlib]System.Console::WriteLine(string)
ret
}
.method private hidebysig newslot specialname virtual final
instance void I.remove_E(class [mscorlib]System.Action 'value') cil managed
{
.override I::remove_E
ret
}
.method family hidebysig specialname instance void
add_E(class [mscorlib]System.Action 'value') cil managed
{
ldstr "Protected event"
call void [mscorlib]System.Console::WriteLine(string)
ret
}
.method family hidebysig specialname instance void
remove_E(class [mscorlib]System.Action 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
// NOTE: No event I.E
.event [mscorlib]System.Action E
{
.addon instance void Base::add_E(class [mscorlib]System.Action)
.removeon instance void Base::remove_E(class [mscorlib]System.Action)
}
} // end of class Base
]]>
Dim source =
<compilation>
<file name="a.vb">
Public Class Derived
Inherits Base
Implements I
Public Sub Test()
AddHandler DirectCast(Me, I).E, Nothing
End Sub
End Class
Module Program
Sub Main()
Dim d As New Derived()
d.Test()
Dim id As I = d
AddHandler id.E, Nothing
End Sub
End Module
</file>
</compilation>
Dim ilRef = CompileIL(il.Value)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {ilRef}, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[
Explicit implementation
Explicit implementation
]]>)
Dim [global] = compilation.GlobalNamespace
Dim [interface] = [global].GetMember(Of NamedTypeSymbol)("I")
Dim baseType = [global].GetMember(Of NamedTypeSymbol)("Base")
Dim derivedType = [global].GetMember(Of NamedTypeSymbol)("Derived")
Dim interfaceEvent = [interface].GetMember(Of EventSymbol)("E")
Dim interfaceAdder = interfaceEvent.AddMethod
Dim baseAdder = baseType.GetMembers().OfType(Of MethodSymbol)().
Where(Function(m) m.ExplicitInterfaceImplementations.Any()).
Single(Function(m) m.ExplicitInterfaceImplementations.Single().MethodKind = MethodKind.EventAdd)
Assert.Equal(baseAdder, derivedType.FindImplementationForInterfaceMember(interfaceAdder))
Assert.Equal(baseAdder, baseType.FindImplementationForInterfaceMember(interfaceAdder))
Assert.Null(derivedType.FindImplementationForInterfaceMember(interfaceEvent))
Assert.Null(baseType.FindImplementationForInterfaceMember(interfaceEvent))
End Sub
<WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")>
<Fact>
Public Sub CustomModifiers_01()
Dim ilSource = <![CDATA[
.class interface public abstract auto ansi I1
{
.method public newslot abstract strict virtual
instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method I1::M1
.method public newslot abstract strict virtual
instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed
{
} // end of method I1::M2
} // end of class I1
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
Dim v As I1 = New Implementation()
v.M1(Nothing)
v.M2(Nothing)
End Sub
End Module
Class Implementation
Implements I1
Public Function M1(x As Integer) As Integer() Implements I1.M1
System.Console.WriteLine("Implementation.M1")
Return Nothing
End Function
Public Function M2(x() As Integer) As Integer Implements I1.M2
System.Console.WriteLine("Implementation.M2")
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim reference As MetadataReference = Nothing
Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)
reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path))
End Using
Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation,
<![CDATA[
Implementation.M1
Implementation.M2
]]>,
symbolValidator:=Sub(m As ModuleSymbol)
Dim t = m.GlobalNamespace.GetTypeMember("Implementation")
Dim m1 = t.GetMember(Of MethodSymbol)("M1")
Assert.Equal(0, m1.ExplicitInterfaceImplementations.Length)
Dim m1_stub = t.GetMember(Of MethodSymbol)("$VB$Stub_M1")
Assert.Equal("Function Implementation.$VB$Stub_M1(x As System.Int32 modopt(System.Runtime.CompilerServices.IsLong)) As System.Int32 modopt(System.Runtime.CompilerServices.IsLong) ()", m1_stub.ToTestDisplayString())
Assert.Equal(1, m1_stub.ExplicitInterfaceImplementations.Length)
Assert.Equal("Function I1.M1(x As System.Int32 modopt(System.Runtime.CompilerServices.IsLong)) As System.Int32 modopt(System.Runtime.CompilerServices.IsLong) ()", m1_stub.ExplicitInterfaceImplementations(0).ToTestDisplayString())
Assert.Equal(Accessibility.Private, m1_stub.DeclaredAccessibility)
Assert.True(m1_stub.IsMetadataVirtual)
Assert.True(m1_stub.IsMetadataNewSlot)
Assert.False(m1_stub.IsOverridable)
End Sub)
End Sub
<WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")>
<Fact>
Public Sub CustomModifiers_02()
Dim ilSource = <![CDATA[
.class interface public abstract auto ansi I1
{
.method public newslot abstract strict virtual
instance !!T[] M1<T>(!!T modopt([mscorlib]System.Runtime.CompilerServices.IsLong) & x) cil managed
{
} // end of method I1::M1
.method public newslot abstract strict virtual
instance !!S modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M2<S>(!!S modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []& x) cil managed
{
} // end of method I1::M2
} // end of class I1
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
Dim v As I1 = New Implementation()
Dim x1 As Integer = 1
Dim x2 As Integer() = Nothing
v.M1(Of Integer)(x1)
System.Console.WriteLine(x1)
v.M2(Of Integer)(x2)
System.Console.WriteLine(x2)
End Sub
End Module
Class Implementation
Implements I1
Public Function M1(Of U)(ByRef x As U) As U() Implements I1.M1
System.Console.WriteLine("Implementation.M1")
x = Nothing
Return Nothing
End Function
Public Function M2(Of W)(ByRef x() As W) As W Implements I1.M2
System.Console.WriteLine("Implementation.M2")
x = New W() {}
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim reference As MetadataReference = Nothing
Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)
reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path))
End Using
Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation,
<![CDATA[
Implementation.M1
0
Implementation.M2
System.Int32[]
]]>,
symbolValidator:=Sub(m As ModuleSymbol)
Dim t = m.GlobalNamespace.GetTypeMember("Implementation")
Dim m1_stub = t.GetMember(Of MethodSymbol)("$VB$Stub_M1")
Assert.Equal("Function Implementation.$VB$Stub_M1(Of U)(ByRef x As U modopt(System.Runtime.CompilerServices.IsLong)) As U()", m1_stub.ToTestDisplayString())
End Sub)
End Sub
<WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")>
<Fact>
Public Sub CustomModifiers_03()
Dim ilSource = <![CDATA[
.class interface public abstract auto ansi I1
{
.method public newslot specialname abstract strict virtual
instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method I1::get_P1
.method public newslot specialname abstract strict virtual
instance void modopt([mscorlib]System.Runtime.CompilerServices.IsLong) set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x,
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Value) cil managed
{
} // end of method I1::set_P1
.method public newslot specialname abstract strict virtual
instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2() cil managed
{
} // end of method I1::get_P2
.method public newslot specialname abstract strict virtual
instance void modopt([mscorlib]System.Runtime.CompilerServices.IsLong) set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Value) cil managed
{
} // end of method I1::set_P2
.property instance int32[] P1(int32)
{
.get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] I1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) )
.set instance void modopt([mscorlib]System.Runtime.CompilerServices.IsLong) I1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) ,
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [])
} // end of property I1::P1
.property instance int32 P2()
{
.get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) I1::get_P2()
.set instance void modopt([mscorlib]System.Runtime.CompilerServices.IsLong) I1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) )
} // end of property I1::P2
} // end of class I1
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
Dim v As I1 = New Implementation()
v.P1(Nothing) = v.P1(Nothing)
v.P2 = 123
System.Console.WriteLine(v.P2)
System.Console.WriteLine(DirectCast(v, Implementation).P2)
End Sub
End Module
Class Implementation
Implements I1
Public Property P1(x As Integer) As Integer() Implements I1.P1
Get
System.Console.WriteLine("Implementation.P1_get")
Return Nothing
End Get
Set(value As Integer())
System.Console.WriteLine("Implementation.P1_set")
End Set
End Property
Public Property P2 As Integer Implements I1.P2
End Class
]]>
</file>
</compilation>
Dim reference As MetadataReference = Nothing
Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)
reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path))
End Using
Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation,
<![CDATA[
Implementation.P1_get
Implementation.P1_set
123
123
]]>)
End Sub
<WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")>
<Fact>
Public Sub CustomModifiers_04()
Dim ilSource = <![CDATA[
.class interface public abstract auto ansi I1
{
.method public newslot abstract strict virtual
instance int32[] M1(int32 x) cil managed
{
} // end of method I1::M1
.method public newslot abstract strict virtual
instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] M2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method I1::M1
} // end of class I1
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
Dim v As I1 = New Implementation()
v.M1(Nothing)
v.M2(Nothing)
End Sub
End Module
Class Implementation
Implements I1
Public Function M12(x As Integer) As Integer() Implements I1.M1, I1.M2
System.Console.WriteLine("Implementation.M12")
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim reference As MetadataReference = Nothing
Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)
reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path))
End Using
Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation,
<![CDATA[
Implementation.M12
Implementation.M12
]]>,
symbolValidator:=Sub(m As ModuleSymbol)
Dim t = m.GlobalNamespace.GetTypeMember("Implementation")
Dim m1 = t.GetMember(Of MethodSymbol)("M12")
Assert.Equal(1, m1.ExplicitInterfaceImplementations.Length)
Assert.Equal("Function I1.M1(x As System.Int32) As System.Int32()", m1.ExplicitInterfaceImplementations(0).ToTestDisplayString())
Dim m1_stub = t.GetMember(Of MethodSymbol)("$VB$Stub_M12")
Assert.Equal("Function Implementation.$VB$Stub_M12(x As System.Int32 modopt(System.Runtime.CompilerServices.IsLong)) As System.Int32 modopt(System.Runtime.CompilerServices.IsLong) ()", m1_stub.ToTestDisplayString())
Assert.Equal(1, m1_stub.ExplicitInterfaceImplementations.Length)
Assert.Equal("Function I1.M2(x As System.Int32 modopt(System.Runtime.CompilerServices.IsLong)) As System.Int32 modopt(System.Runtime.CompilerServices.IsLong) ()", m1_stub.ExplicitInterfaceImplementations(0).ToTestDisplayString())
End Sub)
End Sub
<WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")>
<Fact>
Public Sub CustomModifiers_05()
Dim ilSource = <![CDATA[
.class interface public abstract auto ansi I1
{
.method public newslot abstract strict virtual
instance int32[] M1(int32 x) cil managed
{
} // end of method I1::M1
.method public newslot abstract strict virtual
instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] M2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method I1::M1
} // end of class I1
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
Dim v As I1 = New Implementation()
v.M1(Nothing)
v.M2(Nothing)
End Sub
End Module
Class Implementation
Implements I1
Public Function M12(x As Integer) As Integer() Implements I1.M2, I1.M1
System.Console.WriteLine("Implementation.M12")
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim reference As MetadataReference = Nothing
Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)
reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path))
End Using
Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation,
<![CDATA[
Implementation.M12
Implementation.M12
]]>,
symbolValidator:=Sub(m As ModuleSymbol)
Dim t = m.GlobalNamespace.GetTypeMember("Implementation")
Dim m1 = t.GetMember(Of MethodSymbol)("M12")
Assert.Equal(1, m1.ExplicitInterfaceImplementations.Length)
Assert.Equal("Function I1.M1(x As System.Int32) As System.Int32()", m1.ExplicitInterfaceImplementations(0).ToTestDisplayString())
Dim m1_stub = t.GetMember(Of MethodSymbol)("$VB$Stub_M12")
Assert.Equal("Function Implementation.$VB$Stub_M12(x As System.Int32 modopt(System.Runtime.CompilerServices.IsLong)) As System.Int32 modopt(System.Runtime.CompilerServices.IsLong) ()", m1_stub.ToTestDisplayString())
Assert.Equal(1, m1_stub.ExplicitInterfaceImplementations.Length)
Assert.Equal("Function I1.M2(x As System.Int32 modopt(System.Runtime.CompilerServices.IsLong)) As System.Int32 modopt(System.Runtime.CompilerServices.IsLong) ()", m1_stub.ExplicitInterfaceImplementations(0).ToTestDisplayString())
End Sub)
End Sub
<WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")>
<Fact>
Public Sub CustomModifiers_06()
Dim ilSource = <![CDATA[
.class interface public abstract auto ansi I1
{
.method public newslot abstract strict virtual
instance int32[] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method I1::M1
.method public newslot abstract strict virtual
instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] M2(int32 x) cil managed
{
} // end of method I1::M1
} // end of class I1
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
Dim v As I1 = New Implementation()
v.M1(Nothing)
v.M2(Nothing)
End Sub
End Module
Class Implementation
Implements I1
Public Function M12(x As Integer) As Integer() Implements I1.M2, I1.M1
System.Console.WriteLine("Implementation.M12")
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim reference As MetadataReference = Nothing
Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)
reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path))
End Using
Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation,
<![CDATA[
Implementation.M12
Implementation.M12
]]>,
symbolValidator:=Sub(m As ModuleSymbol)
Dim t = m.GlobalNamespace.GetTypeMember("Implementation")
Dim m1 = t.GetMember(Of MethodSymbol)("M12")
Assert.Equal(0, m1.ExplicitInterfaceImplementations.Length)
Dim m12_stubs = t.GetMembers("$VB$Stub_M12")
Assert.Equal(2, m12_stubs.Length)
Dim m1_stub As MethodSymbol
Dim m2_stub As MethodSymbol
If DirectCast(m12_stubs(0), MethodSymbol).ReturnTypeCustomModifiers.IsEmpty Then
m2_stub = DirectCast(m12_stubs(0), MethodSymbol)
m1_stub = DirectCast(m12_stubs(1), MethodSymbol)
Else
m2_stub = DirectCast(m12_stubs(1), MethodSymbol)
m1_stub = DirectCast(m12_stubs(0), MethodSymbol)
End If
Assert.Equal("Function Implementation.$VB$Stub_M12(x As System.Int32 modopt(System.Runtime.CompilerServices.IsLong)) As System.Int32() modopt(System.Runtime.CompilerServices.IsLong)", m1_stub.ToTestDisplayString())
Assert.Equal(1, m1_stub.ExplicitInterfaceImplementations.Length)
Assert.Equal("Function I1.M1(x As System.Int32 modopt(System.Runtime.CompilerServices.IsLong)) As System.Int32() modopt(System.Runtime.CompilerServices.IsLong)", m1_stub.ExplicitInterfaceImplementations(0).ToTestDisplayString())
Assert.Equal("Function Implementation.$VB$Stub_M12(x As System.Int32) As System.Int32 modopt(System.Runtime.CompilerServices.IsLong) ()", m2_stub.ToTestDisplayString())
Assert.Equal(1, m2_stub.ExplicitInterfaceImplementations.Length)
Assert.Equal("Function I1.M2(x As System.Int32) As System.Int32 modopt(System.Runtime.CompilerServices.IsLong) ()", m2_stub.ExplicitInterfaceImplementations(0).ToTestDisplayString())
End Sub)
End Sub
<WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")>
<Fact>
Public Sub CustomModifiers_07()
Dim ilSource = <![CDATA[
.class interface public abstract auto ansi I1
{
.method public newslot abstract strict virtual
instance int32[] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method I1::M1
.method public newslot abstract strict virtual
instance int32[] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method I1::M1
} // end of class I1
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
Dim v As I1 = New Implementation()
v.M1(Nothing)
v.M2(Nothing)
End Sub
End Module
Class Implementation
Implements I1
Public Function M12(x As Integer) As Integer() Implements I1.M2, I1.M1
System.Console.WriteLine("Implementation.M12")
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim reference As MetadataReference = Nothing
Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)
reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path))
End Using
Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation,
<![CDATA[
Implementation.M12
Implementation.M12
]]>,
symbolValidator:=Sub(m As ModuleSymbol)
Dim t = m.GlobalNamespace.GetTypeMember("Implementation")
Dim m1 = t.GetMember(Of MethodSymbol)("M12")
Assert.Equal(0, m1.ExplicitInterfaceImplementations.Length)
Dim m12_stub = t.GetMember(Of MethodSymbol)("$VB$Stub_M12")
Assert.Equal(2, m12_stub.ExplicitInterfaceImplementations.Length)
End Sub)
End Sub
<WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")>
<Fact>
Public Sub CustomModifiers_08()
Dim ilSource = <![CDATA[
.class interface public abstract auto ansi I1
{
.method public newslot abstract strict virtual
instance int32[] M1(int32 & modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method I1::M1
.method public newslot abstract strict virtual
instance int32[] M2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) & x) cil managed
{
} // end of method I1::M1
} // end of class I1
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module Module1
Sub Main()
Dim v As I1 = New Implementation()
v.M1(Nothing)
v.M2(Nothing)
End Sub
End Module
Class Implementation
Implements I1
Public Function M12(ByRef x As Integer) As Integer() Implements I1.M2, I1.M1
System.Console.WriteLine("Implementation.M12")
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim reference As MetadataReference = Nothing
Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)
reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path))
End Using
Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation,
<![CDATA[
Implementation.M12
Implementation.M12
]]>,
symbolValidator:=Sub(m As ModuleSymbol)
Dim t = m.GlobalNamespace.GetTypeMember("Implementation")
Dim m1 = t.GetMember(Of MethodSymbol)("M12")
Assert.Equal(0, m1.ExplicitInterfaceImplementations.Length)
Dim m12_stubs = t.GetMembers("$VB$Stub_M12")
Assert.Equal(2, m12_stubs.Length)
For Each stub As MethodSymbol In m12_stubs
Assert.Equal(1, stub.ExplicitInterfaceImplementations.Length)
Next
End Sub)
End Sub
End Class
End Namespace
|
Imports System
Imports Data = lombok.Data
Imports EqualsAndHashCode = lombok.EqualsAndHashCode
Imports val = lombok.val
Imports InputType = org.deeplearning4j.nn.conf.inputs.InputType
Imports InvalidInputTypeException = org.deeplearning4j.nn.conf.inputs.InvalidInputTypeException
Imports LayerMemoryReport = org.deeplearning4j.nn.conf.memory.LayerMemoryReport
Imports MemoryReport = org.deeplearning4j.nn.conf.memory.MemoryReport
Imports ComputationGraph = org.deeplearning4j.nn.graph.ComputationGraph
Imports DataType = org.nd4j.linalg.api.buffer.DataType
Imports INDArray = org.nd4j.linalg.api.ndarray.INDArray
Imports JsonProperty = org.nd4j.shade.jackson.annotation.JsonProperty
'
' * ******************************************************************************
' * *
' * *
' * * This program and the accompanying materials are made available under the
' * * terms of the Apache License, Version 2.0 which is available at
' * * https://www.apache.org/licenses/LICENSE-2.0.
' * *
' * * See the NOTICE file distributed with this work for additional
' * * information regarding copyright ownership.
' * * 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.
' * *
' * * SPDX-License-Identifier: Apache-2.0
' * *****************************************************************************
'
Namespace org.deeplearning4j.nn.conf.graph
'JAVA TO VB CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
'ORIGINAL LINE: @Data @EqualsAndHashCode(callSuper = false) public class L2NormalizeVertex extends GraphVertex
<Serializable>
Public Class L2NormalizeVertex
Inherits GraphVertex
Public Const DEFAULT_EPS As Double = 1e-8
Protected Friend dimension() As Integer
Protected Friend eps As Double
Public Sub New()
Me.New(Nothing, DEFAULT_EPS)
End Sub
'JAVA TO VB CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
'ORIGINAL LINE: public L2NormalizeVertex(@JsonProperty("dimension") int[] dimension, @JsonProperty("eps") double eps)
Public Sub New(ByVal dimension() As Integer, ByVal eps As Double)
Me.dimension = dimension
Me.eps = eps
End Sub
Public Overrides Function clone() As L2NormalizeVertex
Return New L2NormalizeVertex(dimension, eps)
End Function
Public Overrides Function numParams(ByVal backprop As Boolean) As Long
Return 0
End Function
Public Overrides Function minVertexInputs() As Integer
Return 1
End Function
Public Overrides Function maxVertexInputs() As Integer
Return 1
End Function
Public Overrides Function instantiate(ByVal graph As ComputationGraph, ByVal name As String, ByVal idx As Integer, ByVal paramsView As INDArray, ByVal initializeParams As Boolean, ByVal networkDatatype As DataType) As org.deeplearning4j.nn.graph.vertex.GraphVertex
Return New org.deeplearning4j.nn.graph.vertex.impl.L2NormalizeVertex(graph, name, idx, dimension, eps, networkDatatype)
End Function
'JAVA TO VB CONVERTER WARNING: Method 'throws' clauses are not available in VB:
'ORIGINAL LINE: @Override public org.deeplearning4j.nn.conf.inputs.InputType getOutputType(int layerIndex, org.deeplearning4j.nn.conf.inputs.InputType... vertexInputs) throws org.deeplearning4j.nn.conf.inputs.InvalidInputTypeException
Public Overrides Function getOutputType(ByVal layerIndex As Integer, ParamArray ByVal vertexInputs() As InputType) As InputType
If vertexInputs.Length = 1 Then
Return vertexInputs(0)
End If
Dim first As InputType = vertexInputs(0)
Return first 'Same output shape/size as
End Function
Public Overrides Function getMemoryReport(ParamArray ByVal inputTypes() As InputType) As MemoryReport
Dim outputType As InputType = getOutputType(-1, inputTypes)
'norm2 value (inference working mem): 1 per example during forward pass
'Training working mem: 2 per example + 2x input size + 1 per example (in addition to epsilons)
Dim trainModePerEx As val = 3 + 2 * inputTypes(0).arrayElementsPerExample()
Return (New LayerMemoryReport.Builder(Nothing, GetType(L2NormalizeVertex), inputTypes(0), outputType)).standardMemory(0, 0).workingMemory(0, 1, 0, trainModePerEx).cacheMemory(0, 0).build()
End Function
End Class
End Namespace |
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("WindowsApplication1")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("WindowsApplication1")>
<Assembly: AssemblyCopyright("Copyright © 2012")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("c84f09af-85a8-4e4b-9a52-bd5bbd67b323")>
' 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")>
|
Imports org.deeplearning4j.models.sequencevectors
Imports ListenerEvent = org.deeplearning4j.models.sequencevectors.enums.ListenerEvent
Imports SequenceElement = org.deeplearning4j.models.sequencevectors.sequence.SequenceElement
'
' * ******************************************************************************
' * *
' * *
' * * This program and the accompanying materials are made available under the
' * * terms of the Apache License, Version 2.0 which is available at
' * * https://www.apache.org/licenses/LICENSE-2.0.
' * *
' * * See the NOTICE file distributed with this work for additional
' * * information regarding copyright ownership.
' * * 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.
' * *
' * * SPDX-License-Identifier: Apache-2.0
' * *****************************************************************************
'
Namespace org.deeplearning4j.models.sequencevectors.interfaces
Public Interface VectorsListener(Of T As org.deeplearning4j.models.sequencevectors.sequence.SequenceElement)
''' <summary>
''' This method is called prior each processEvent call, to check if this specific VectorsListener implementation is viable for specific event
''' </summary>
''' <param name="event"> </param>
''' <param name="argument"> </param>
''' <returns> TRUE, if this event can and should be processed with this listener, FALSE otherwise </returns>
Function validateEvent(ByVal [event] As ListenerEvent, ByVal argument As Long) As Boolean
''' <summary>
''' This method is called at each epoch end
''' </summary>
''' <param name="event"> </param>
''' <param name="sequenceVectors"> </param>
Sub processEvent(ByVal [event] As ListenerEvent, ByVal sequenceVectors As SequenceVectors(Of T), ByVal argument As Long)
End Interface
End Namespace |
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.3053
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict Off
Option Explicit On
'''<summary>
'''Represents a strongly typed in-memory cache of data.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0"), _
Global.System.Serializable(), _
Global.System.ComponentModel.DesignerCategoryAttribute("code"), _
Global.System.ComponentModel.ToolboxItem(true), _
Global.System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema"), _
Global.System.Xml.Serialization.XmlRootAttribute("DataSetCashCountDaily"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")> _
Partial Public Class DataSetCashCountDaily
Inherits Global.System.Data.DataSet
Private tabletblPatientReceipt As tblPatientReceiptDataTable
Private _schemaSerializationMode As Global.System.Data.SchemaSerializationMode = Global.System.Data.SchemaSerializationMode.IncludeSchema
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub New()
MyBase.New
Me.BeginInit
Me.InitClass
Dim schemaChangedHandler As Global.System.ComponentModel.CollectionChangeEventHandler = AddressOf Me.SchemaChanged
AddHandler MyBase.Tables.CollectionChanged, schemaChangedHandler
AddHandler MyBase.Relations.CollectionChanged, schemaChangedHandler
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Protected Sub New(ByVal info As Global.System.Runtime.Serialization.SerializationInfo, ByVal context As Global.System.Runtime.Serialization.StreamingContext)
MyBase.New(info, context, false)
If (Me.IsBinarySerialized(info, context) = true) Then
Me.InitVars(false)
Dim schemaChangedHandler1 As Global.System.ComponentModel.CollectionChangeEventHandler = AddressOf Me.SchemaChanged
AddHandler Me.Tables.CollectionChanged, schemaChangedHandler1
AddHandler Me.Relations.CollectionChanged, schemaChangedHandler1
Return
End If
Dim strSchema As String = CType(info.GetValue("XmlSchema", GetType(String)),String)
If (Me.DetermineSchemaSerializationMode(info, context) = Global.System.Data.SchemaSerializationMode.IncludeSchema) Then
Dim ds As Global.System.Data.DataSet = New Global.System.Data.DataSet
ds.ReadXmlSchema(New Global.System.Xml.XmlTextReader(New Global.System.IO.StringReader(strSchema)))
If (Not (ds.Tables("tblPatientReceipt")) Is Nothing) Then
MyBase.Tables.Add(New tblPatientReceiptDataTable(ds.Tables("tblPatientReceipt")))
End If
Me.DataSetName = ds.DataSetName
Me.Prefix = ds.Prefix
Me.Namespace = ds.Namespace
Me.Locale = ds.Locale
Me.CaseSensitive = ds.CaseSensitive
Me.EnforceConstraints = ds.EnforceConstraints
Me.Merge(ds, false, Global.System.Data.MissingSchemaAction.Add)
Me.InitVars
Else
Me.ReadXmlSchema(New Global.System.Xml.XmlTextReader(New Global.System.IO.StringReader(strSchema)))
End If
Me.GetSerializationData(info, context)
Dim schemaChangedHandler As Global.System.ComponentModel.CollectionChangeEventHandler = AddressOf Me.SchemaChanged
AddHandler MyBase.Tables.CollectionChanged, schemaChangedHandler
AddHandler Me.Relations.CollectionChanged, schemaChangedHandler
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.ComponentModel.Browsable(false), _
Global.System.ComponentModel.DesignerSerializationVisibility(Global.System.ComponentModel.DesignerSerializationVisibility.Content)> _
Public ReadOnly Property tblPatientReceipt() As tblPatientReceiptDataTable
Get
Return Me.tabletblPatientReceipt
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.ComponentModel.BrowsableAttribute(true), _
Global.System.ComponentModel.DesignerSerializationVisibilityAttribute(Global.System.ComponentModel.DesignerSerializationVisibility.Visible)> _
Public Overrides Property SchemaSerializationMode() As Global.System.Data.SchemaSerializationMode
Get
Return Me._schemaSerializationMode
End Get
Set
Me._schemaSerializationMode = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.ComponentModel.DesignerSerializationVisibilityAttribute(Global.System.ComponentModel.DesignerSerializationVisibility.Hidden)> _
Public Shadows ReadOnly Property Tables() As Global.System.Data.DataTableCollection
Get
Return MyBase.Tables
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.ComponentModel.DesignerSerializationVisibilityAttribute(Global.System.ComponentModel.DesignerSerializationVisibility.Hidden)> _
Public Shadows ReadOnly Property Relations() As Global.System.Data.DataRelationCollection
Get
Return MyBase.Relations
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Protected Overrides Sub InitializeDerivedDataSet()
Me.BeginInit
Me.InitClass
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Overrides Function Clone() As Global.System.Data.DataSet
Dim cln As DataSetCashCountDaily = CType(MyBase.Clone,DataSetCashCountDaily)
cln.InitVars
cln.SchemaSerializationMode = Me.SchemaSerializationMode
Return cln
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Protected Overrides Function ShouldSerializeTables() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Protected Overrides Function ShouldSerializeRelations() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Protected Overrides Sub ReadXmlSerializable(ByVal reader As Global.System.Xml.XmlReader)
If (Me.DetermineSchemaSerializationMode(reader) = Global.System.Data.SchemaSerializationMode.IncludeSchema) Then
Me.Reset
Dim ds As Global.System.Data.DataSet = New Global.System.Data.DataSet
ds.ReadXml(reader)
If (Not (ds.Tables("tblPatientReceipt")) Is Nothing) Then
MyBase.Tables.Add(New tblPatientReceiptDataTable(ds.Tables("tblPatientReceipt")))
End If
Me.DataSetName = ds.DataSetName
Me.Prefix = ds.Prefix
Me.Namespace = ds.Namespace
Me.Locale = ds.Locale
Me.CaseSensitive = ds.CaseSensitive
Me.EnforceConstraints = ds.EnforceConstraints
Me.Merge(ds, false, Global.System.Data.MissingSchemaAction.Add)
Me.InitVars
Else
Me.ReadXml(reader)
Me.InitVars
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Protected Overrides Function GetSchemaSerializable() As Global.System.Xml.Schema.XmlSchema
Dim stream As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream
Me.WriteXmlSchema(New Global.System.Xml.XmlTextWriter(stream, Nothing))
stream.Position = 0
Return Global.System.Xml.Schema.XmlSchema.Read(New Global.System.Xml.XmlTextReader(stream), Nothing)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Friend Overloads Sub InitVars()
Me.InitVars(true)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Friend Overloads Sub InitVars(ByVal initTable As Boolean)
Me.tabletblPatientReceipt = CType(MyBase.Tables("tblPatientReceipt"),tblPatientReceiptDataTable)
If (initTable = true) Then
If (Not (Me.tabletblPatientReceipt) Is Nothing) Then
Me.tabletblPatientReceipt.InitVars
End If
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Private Sub InitClass()
Me.DataSetName = "DataSetCashCountDaily"
Me.Prefix = ""
Me.Namespace = "http://tempuri.org/DataSetCashCountDaily.xsd"
Me.EnforceConstraints = true
Me.SchemaSerializationMode = Global.System.Data.SchemaSerializationMode.IncludeSchema
Me.tabletblPatientReceipt = New tblPatientReceiptDataTable
MyBase.Tables.Add(Me.tabletblPatientReceipt)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Private Function ShouldSerializetblPatientReceipt() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Private Sub SchemaChanged(ByVal sender As Object, ByVal e As Global.System.ComponentModel.CollectionChangeEventArgs)
If (e.Action = Global.System.ComponentModel.CollectionChangeAction.Remove) Then
Me.InitVars
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Shared Function GetTypedDataSetSchema(ByVal xs As Global.System.Xml.Schema.XmlSchemaSet) As Global.System.Xml.Schema.XmlSchemaComplexType
Dim ds As DataSetCashCountDaily = New DataSetCashCountDaily
Dim type As Global.System.Xml.Schema.XmlSchemaComplexType = New Global.System.Xml.Schema.XmlSchemaComplexType
Dim sequence As Global.System.Xml.Schema.XmlSchemaSequence = New Global.System.Xml.Schema.XmlSchemaSequence
Dim any As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny
any.Namespace = ds.Namespace
sequence.Items.Add(any)
type.Particle = sequence
Dim dsSchema As Global.System.Xml.Schema.XmlSchema = ds.GetSchemaSerializable
If xs.Contains(dsSchema.TargetNamespace) Then
Dim s1 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream
Dim s2 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream
Try
Dim schema As Global.System.Xml.Schema.XmlSchema = Nothing
dsSchema.Write(s1)
Dim schemas As Global.System.Collections.IEnumerator = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator
Do While schemas.MoveNext
schema = CType(schemas.Current,Global.System.Xml.Schema.XmlSchema)
s2.SetLength(0)
schema.Write(s2)
If (s1.Length = s2.Length) Then
s1.Position = 0
s2.Position = 0
Do While ((s1.Position <> s1.Length) _
AndAlso (s1.ReadByte = s2.ReadByte))
Loop
If (s1.Position = s1.Length) Then
Return type
End If
End If
Loop
Finally
If (Not (s1) Is Nothing) Then
s1.Close
End If
If (Not (s2) Is Nothing) Then
s2.Close
End If
End Try
End If
xs.Add(dsSchema)
Return type
End Function
Public Delegate Sub tblPatientReceiptRowChangeEventHandler(ByVal sender As Object, ByVal e As tblPatientReceiptRowChangeEvent)
'''<summary>
'''Represents the strongly named DataTable class.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0"), _
Global.System.Serializable(), _
Global.System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")> _
Partial Public Class tblPatientReceiptDataTable
Inherits Global.System.Data.DataTable
Implements Global.System.Collections.IEnumerable
Private columnDateIn As Global.System.Data.DataColumn
Private columnCashUSD As Global.System.Data.DataColumn
Private columnCashRiel As Global.System.Data.DataColumn
Private columnOutPatientUSD As Global.System.Data.DataColumn
Private columnOutPatientRiel As Global.System.Data.DataColumn
Private columnInPatientUSD As Global.System.Data.DataColumn
Private columnInPatientRiel As Global.System.Data.DataColumn
Private columnGlassFeeUSD As Global.System.Data.DataColumn
Private columnGlassFeeRiel As Global.System.Data.DataColumn
Private columnArtificialEyeFeeUSD As Global.System.Data.DataColumn
Private columnArtificialEyeFeeRiel As Global.System.Data.DataColumn
Private columnOtherFeeUSD As Global.System.Data.DataColumn
Private columnOtherFeeRiel As Global.System.Data.DataColumn
Private columnHN As Global.System.Data.DataColumn
Private columnID As Global.System.Data.DataColumn
Private columnIDCashReceipt As Global.System.Data.DataColumn
Private columnReceiptNo As Global.System.Data.DataColumn
Private columnHN1 As Global.System.Data.DataColumn
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub New()
MyBase.New
Me.TableName = "tblPatientReceipt"
Me.BeginInit
Me.InitClass
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Friend Sub New(ByVal table As Global.System.Data.DataTable)
MyBase.New
Me.TableName = table.TableName
If (table.CaseSensitive <> table.DataSet.CaseSensitive) Then
Me.CaseSensitive = table.CaseSensitive
End If
If (table.Locale.ToString <> table.DataSet.Locale.ToString) Then
Me.Locale = table.Locale
End If
If (table.Namespace <> table.DataSet.Namespace) Then
Me.Namespace = table.Namespace
End If
Me.Prefix = table.Prefix
Me.MinimumCapacity = table.MinimumCapacity
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Protected Sub New(ByVal info As Global.System.Runtime.Serialization.SerializationInfo, ByVal context As Global.System.Runtime.Serialization.StreamingContext)
MyBase.New(info, context)
Me.InitVars
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property DateInColumn() As Global.System.Data.DataColumn
Get
Return Me.columnDateIn
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property CashUSDColumn() As Global.System.Data.DataColumn
Get
Return Me.columnCashUSD
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property CashRielColumn() As Global.System.Data.DataColumn
Get
Return Me.columnCashRiel
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property OutPatientUSDColumn() As Global.System.Data.DataColumn
Get
Return Me.columnOutPatientUSD
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property OutPatientRielColumn() As Global.System.Data.DataColumn
Get
Return Me.columnOutPatientRiel
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property InPatientUSDColumn() As Global.System.Data.DataColumn
Get
Return Me.columnInPatientUSD
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property InPatientRielColumn() As Global.System.Data.DataColumn
Get
Return Me.columnInPatientRiel
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property GlassFeeUSDColumn() As Global.System.Data.DataColumn
Get
Return Me.columnGlassFeeUSD
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property GlassFeeRielColumn() As Global.System.Data.DataColumn
Get
Return Me.columnGlassFeeRiel
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property ArtificialEyeFeeUSDColumn() As Global.System.Data.DataColumn
Get
Return Me.columnArtificialEyeFeeUSD
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property ArtificialEyeFeeRielColumn() As Global.System.Data.DataColumn
Get
Return Me.columnArtificialEyeFeeRiel
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property OtherFeeUSDColumn() As Global.System.Data.DataColumn
Get
Return Me.columnOtherFeeUSD
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property OtherFeeRielColumn() As Global.System.Data.DataColumn
Get
Return Me.columnOtherFeeRiel
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property HNColumn() As Global.System.Data.DataColumn
Get
Return Me.columnHN
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property IDColumn() As Global.System.Data.DataColumn
Get
Return Me.columnID
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property IDCashReceiptColumn() As Global.System.Data.DataColumn
Get
Return Me.columnIDCashReceipt
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property ReceiptNoColumn() As Global.System.Data.DataColumn
Get
Return Me.columnReceiptNo
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property HN1Column() As Global.System.Data.DataColumn
Get
Return Me.columnHN1
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.ComponentModel.Browsable(false)> _
Public ReadOnly Property Count() As Integer
Get
Return Me.Rows.Count
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Default ReadOnly Property Item(ByVal index As Integer) As tblPatientReceiptRow
Get
Return CType(Me.Rows(index),tblPatientReceiptRow)
End Get
End Property
Public Event tblPatientReceiptRowChanging As tblPatientReceiptRowChangeEventHandler
Public Event tblPatientReceiptRowChanged As tblPatientReceiptRowChangeEventHandler
Public Event tblPatientReceiptRowDeleting As tblPatientReceiptRowChangeEventHandler
Public Event tblPatientReceiptRowDeleted As tblPatientReceiptRowChangeEventHandler
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Overloads Sub AddtblPatientReceiptRow(ByVal row As tblPatientReceiptRow)
Me.Rows.Add(row)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Overloads Function AddtblPatientReceiptRow( _
ByVal DateIn As String, _
ByVal CashUSD As Double, _
ByVal CashRiel As Double, _
ByVal OutPatientUSD As Double, _
ByVal OutPatientRiel As Double, _
ByVal InPatientUSD As Double, _
ByVal InPatientRiel As Double, _
ByVal GlassFeeUSD As Double, _
ByVal GlassFeeRiel As Double, _
ByVal ArtificialEyeFeeUSD As Double, _
ByVal ArtificialEyeFeeRiel As Double, _
ByVal OtherFeeUSD As Double, _
ByVal OtherFeeRiel As Double, _
ByVal HN As Long, _
ByVal IDCashReceipt As String, _
ByVal ReceiptNo As Long, _
ByVal HN1 As Decimal) As tblPatientReceiptRow
Dim rowtblPatientReceiptRow As tblPatientReceiptRow = CType(Me.NewRow,tblPatientReceiptRow)
Dim columnValuesArray() As Object = New Object() {DateIn, CashUSD, CashRiel, OutPatientUSD, OutPatientRiel, InPatientUSD, InPatientRiel, GlassFeeUSD, GlassFeeRiel, ArtificialEyeFeeUSD, ArtificialEyeFeeRiel, OtherFeeUSD, OtherFeeRiel, HN, Nothing, IDCashReceipt, ReceiptNo, HN1}
rowtblPatientReceiptRow.ItemArray = columnValuesArray
Me.Rows.Add(rowtblPatientReceiptRow)
Return rowtblPatientReceiptRow
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Function FindByIDReceiptNo(ByVal ID As Long, ByVal ReceiptNo As Long) As tblPatientReceiptRow
Return CType(Me.Rows.Find(New Object() {ID, ReceiptNo}),tblPatientReceiptRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Overridable Function GetEnumerator() As Global.System.Collections.IEnumerator Implements Global.System.Collections.IEnumerable.GetEnumerator
Return Me.Rows.GetEnumerator
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Overrides Function Clone() As Global.System.Data.DataTable
Dim cln As tblPatientReceiptDataTable = CType(MyBase.Clone,tblPatientReceiptDataTable)
cln.InitVars
Return cln
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Protected Overrides Function CreateInstance() As Global.System.Data.DataTable
Return New tblPatientReceiptDataTable
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Friend Sub InitVars()
Me.columnDateIn = MyBase.Columns("DateIn")
Me.columnCashUSD = MyBase.Columns("CashUSD")
Me.columnCashRiel = MyBase.Columns("CashRiel")
Me.columnOutPatientUSD = MyBase.Columns("OutPatientUSD")
Me.columnOutPatientRiel = MyBase.Columns("OutPatientRiel")
Me.columnInPatientUSD = MyBase.Columns("InPatientUSD")
Me.columnInPatientRiel = MyBase.Columns("InPatientRiel")
Me.columnGlassFeeUSD = MyBase.Columns("GlassFeeUSD")
Me.columnGlassFeeRiel = MyBase.Columns("GlassFeeRiel")
Me.columnArtificialEyeFeeUSD = MyBase.Columns("ArtificialEyeFeeUSD")
Me.columnArtificialEyeFeeRiel = MyBase.Columns("ArtificialEyeFeeRiel")
Me.columnOtherFeeUSD = MyBase.Columns("OtherFeeUSD")
Me.columnOtherFeeRiel = MyBase.Columns("OtherFeeRiel")
Me.columnHN = MyBase.Columns("HN")
Me.columnID = MyBase.Columns("ID")
Me.columnIDCashReceipt = MyBase.Columns("IDCashReceipt")
Me.columnReceiptNo = MyBase.Columns("ReceiptNo")
Me.columnHN1 = MyBase.Columns("HN1")
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Private Sub InitClass()
Me.columnDateIn = New Global.System.Data.DataColumn("DateIn", GetType(String), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnDateIn)
Me.columnCashUSD = New Global.System.Data.DataColumn("CashUSD", GetType(Double), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnCashUSD)
Me.columnCashRiel = New Global.System.Data.DataColumn("CashRiel", GetType(Double), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnCashRiel)
Me.columnOutPatientUSD = New Global.System.Data.DataColumn("OutPatientUSD", GetType(Double), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnOutPatientUSD)
Me.columnOutPatientRiel = New Global.System.Data.DataColumn("OutPatientRiel", GetType(Double), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnOutPatientRiel)
Me.columnInPatientUSD = New Global.System.Data.DataColumn("InPatientUSD", GetType(Double), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnInPatientUSD)
Me.columnInPatientRiel = New Global.System.Data.DataColumn("InPatientRiel", GetType(Double), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnInPatientRiel)
Me.columnGlassFeeUSD = New Global.System.Data.DataColumn("GlassFeeUSD", GetType(Double), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnGlassFeeUSD)
Me.columnGlassFeeRiel = New Global.System.Data.DataColumn("GlassFeeRiel", GetType(Double), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnGlassFeeRiel)
Me.columnArtificialEyeFeeUSD = New Global.System.Data.DataColumn("ArtificialEyeFeeUSD", GetType(Double), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnArtificialEyeFeeUSD)
Me.columnArtificialEyeFeeRiel = New Global.System.Data.DataColumn("ArtificialEyeFeeRiel", GetType(Double), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnArtificialEyeFeeRiel)
Me.columnOtherFeeUSD = New Global.System.Data.DataColumn("OtherFeeUSD", GetType(Double), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnOtherFeeUSD)
Me.columnOtherFeeRiel = New Global.System.Data.DataColumn("OtherFeeRiel", GetType(Double), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnOtherFeeRiel)
Me.columnHN = New Global.System.Data.DataColumn("HN", GetType(Long), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnHN)
Me.columnID = New Global.System.Data.DataColumn("ID", GetType(Long), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnID)
Me.columnIDCashReceipt = New Global.System.Data.DataColumn("IDCashReceipt", GetType(String), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnIDCashReceipt)
Me.columnReceiptNo = New Global.System.Data.DataColumn("ReceiptNo", GetType(Long), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnReceiptNo)
Me.columnHN1 = New Global.System.Data.DataColumn("HN1", GetType(Decimal), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnHN1)
Me.Constraints.Add(New Global.System.Data.UniqueConstraint("Constraint1", New Global.System.Data.DataColumn() {Me.columnID, Me.columnReceiptNo}, true))
Me.columnDateIn.ReadOnly = true
Me.columnDateIn.MaxLength = 11
Me.columnOutPatientUSD.ReadOnly = true
Me.columnOutPatientRiel.ReadOnly = true
Me.columnInPatientUSD.ReadOnly = true
Me.columnInPatientRiel.ReadOnly = true
Me.columnHN.AllowDBNull = false
Me.columnID.AutoIncrement = true
Me.columnID.AllowDBNull = false
Me.columnID.ReadOnly = true
Me.columnIDCashReceipt.AllowDBNull = false
Me.columnIDCashReceipt.MaxLength = 50
Me.columnReceiptNo.AllowDBNull = false
Me.columnHN1.AllowDBNull = false
Me.columnHN1.Caption = "HN"
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Function NewtblPatientReceiptRow() As tblPatientReceiptRow
Return CType(Me.NewRow,tblPatientReceiptRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Protected Overrides Function NewRowFromBuilder(ByVal builder As Global.System.Data.DataRowBuilder) As Global.System.Data.DataRow
Return New tblPatientReceiptRow(builder)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Protected Overrides Function GetRowType() As Global.System.Type
Return GetType(tblPatientReceiptRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Protected Overrides Sub OnRowChanged(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowChanged(e)
If (Not (Me.tblPatientReceiptRowChangedEvent) Is Nothing) Then
RaiseEvent tblPatientReceiptRowChanged(Me, New tblPatientReceiptRowChangeEvent(CType(e.Row,tblPatientReceiptRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Protected Overrides Sub OnRowChanging(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowChanging(e)
If (Not (Me.tblPatientReceiptRowChangingEvent) Is Nothing) Then
RaiseEvent tblPatientReceiptRowChanging(Me, New tblPatientReceiptRowChangeEvent(CType(e.Row,tblPatientReceiptRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Protected Overrides Sub OnRowDeleted(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowDeleted(e)
If (Not (Me.tblPatientReceiptRowDeletedEvent) Is Nothing) Then
RaiseEvent tblPatientReceiptRowDeleted(Me, New tblPatientReceiptRowChangeEvent(CType(e.Row,tblPatientReceiptRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Protected Overrides Sub OnRowDeleting(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowDeleting(e)
If (Not (Me.tblPatientReceiptRowDeletingEvent) Is Nothing) Then
RaiseEvent tblPatientReceiptRowDeleting(Me, New tblPatientReceiptRowChangeEvent(CType(e.Row,tblPatientReceiptRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub RemovetblPatientReceiptRow(ByVal row As tblPatientReceiptRow)
Me.Rows.Remove(row)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Shared Function GetTypedTableSchema(ByVal xs As Global.System.Xml.Schema.XmlSchemaSet) As Global.System.Xml.Schema.XmlSchemaComplexType
Dim type As Global.System.Xml.Schema.XmlSchemaComplexType = New Global.System.Xml.Schema.XmlSchemaComplexType
Dim sequence As Global.System.Xml.Schema.XmlSchemaSequence = New Global.System.Xml.Schema.XmlSchemaSequence
Dim ds As DataSetCashCountDaily = New DataSetCashCountDaily
Dim any1 As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny
any1.Namespace = "http://www.w3.org/2001/XMLSchema"
any1.MinOccurs = New Decimal(0)
any1.MaxOccurs = Decimal.MaxValue
any1.ProcessContents = Global.System.Xml.Schema.XmlSchemaContentProcessing.Lax
sequence.Items.Add(any1)
Dim any2 As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny
any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"
any2.MinOccurs = New Decimal(1)
any2.ProcessContents = Global.System.Xml.Schema.XmlSchemaContentProcessing.Lax
sequence.Items.Add(any2)
Dim attribute1 As Global.System.Xml.Schema.XmlSchemaAttribute = New Global.System.Xml.Schema.XmlSchemaAttribute
attribute1.Name = "namespace"
attribute1.FixedValue = ds.Namespace
type.Attributes.Add(attribute1)
Dim attribute2 As Global.System.Xml.Schema.XmlSchemaAttribute = New Global.System.Xml.Schema.XmlSchemaAttribute
attribute2.Name = "tableTypeName"
attribute2.FixedValue = "tblPatientReceiptDataTable"
type.Attributes.Add(attribute2)
type.Particle = sequence
Dim dsSchema As Global.System.Xml.Schema.XmlSchema = ds.GetSchemaSerializable
If xs.Contains(dsSchema.TargetNamespace) Then
Dim s1 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream
Dim s2 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream
Try
Dim schema As Global.System.Xml.Schema.XmlSchema = Nothing
dsSchema.Write(s1)
Dim schemas As Global.System.Collections.IEnumerator = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator
Do While schemas.MoveNext
schema = CType(schemas.Current,Global.System.Xml.Schema.XmlSchema)
s2.SetLength(0)
schema.Write(s2)
If (s1.Length = s2.Length) Then
s1.Position = 0
s2.Position = 0
Do While ((s1.Position <> s1.Length) _
AndAlso (s1.ReadByte = s2.ReadByte))
Loop
If (s1.Position = s1.Length) Then
Return type
End If
End If
Loop
Finally
If (Not (s1) Is Nothing) Then
s1.Close
End If
If (Not (s2) Is Nothing) Then
s2.Close
End If
End Try
End If
xs.Add(dsSchema)
Return type
End Function
End Class
'''<summary>
'''Represents strongly named DataRow class.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0")> _
Partial Public Class tblPatientReceiptRow
Inherits Global.System.Data.DataRow
Private tabletblPatientReceipt As tblPatientReceiptDataTable
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Friend Sub New(ByVal rb As Global.System.Data.DataRowBuilder)
MyBase.New(rb)
Me.tabletblPatientReceipt = CType(Me.Table,tblPatientReceiptDataTable)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property DateIn() As String
Get
Try
Return CType(Me(Me.tabletblPatientReceipt.DateInColumn),String)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'DateIn' in table 'tblPatientReceipt' is DBNull.", e)
End Try
End Get
Set
Me(Me.tabletblPatientReceipt.DateInColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property CashUSD() As Double
Get
Try
Return CType(Me(Me.tabletblPatientReceipt.CashUSDColumn),Double)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'CashUSD' in table 'tblPatientReceipt' is DBNull.", e)
End Try
End Get
Set
Me(Me.tabletblPatientReceipt.CashUSDColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property CashRiel() As Double
Get
Try
Return CType(Me(Me.tabletblPatientReceipt.CashRielColumn),Double)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'CashRiel' in table 'tblPatientReceipt' is DBNull.", e)
End Try
End Get
Set
Me(Me.tabletblPatientReceipt.CashRielColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property OutPatientUSD() As Double
Get
Try
Return CType(Me(Me.tabletblPatientReceipt.OutPatientUSDColumn),Double)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'OutPatientUSD' in table 'tblPatientReceipt' is DBNull.", e)
End Try
End Get
Set
Me(Me.tabletblPatientReceipt.OutPatientUSDColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property OutPatientRiel() As Double
Get
Try
Return CType(Me(Me.tabletblPatientReceipt.OutPatientRielColumn),Double)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'OutPatientRiel' in table 'tblPatientReceipt' is DBNull.", e)
End Try
End Get
Set
Me(Me.tabletblPatientReceipt.OutPatientRielColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property InPatientUSD() As Double
Get
Try
Return CType(Me(Me.tabletblPatientReceipt.InPatientUSDColumn),Double)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'InPatientUSD' in table 'tblPatientReceipt' is DBNull.", e)
End Try
End Get
Set
Me(Me.tabletblPatientReceipt.InPatientUSDColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property InPatientRiel() As Double
Get
Try
Return CType(Me(Me.tabletblPatientReceipt.InPatientRielColumn),Double)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'InPatientRiel' in table 'tblPatientReceipt' is DBNull.", e)
End Try
End Get
Set
Me(Me.tabletblPatientReceipt.InPatientRielColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property GlassFeeUSD() As Double
Get
Try
Return CType(Me(Me.tabletblPatientReceipt.GlassFeeUSDColumn),Double)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'GlassFeeUSD' in table 'tblPatientReceipt' is DBNull.", e)
End Try
End Get
Set
Me(Me.tabletblPatientReceipt.GlassFeeUSDColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property GlassFeeRiel() As Double
Get
Try
Return CType(Me(Me.tabletblPatientReceipt.GlassFeeRielColumn),Double)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'GlassFeeRiel' in table 'tblPatientReceipt' is DBNull.", e)
End Try
End Get
Set
Me(Me.tabletblPatientReceipt.GlassFeeRielColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property ArtificialEyeFeeUSD() As Double
Get
Try
Return CType(Me(Me.tabletblPatientReceipt.ArtificialEyeFeeUSDColumn),Double)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'ArtificialEyeFeeUSD' in table 'tblPatientReceipt' is DBNull"& _
".", e)
End Try
End Get
Set
Me(Me.tabletblPatientReceipt.ArtificialEyeFeeUSDColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property ArtificialEyeFeeRiel() As Double
Get
Try
Return CType(Me(Me.tabletblPatientReceipt.ArtificialEyeFeeRielColumn),Double)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'ArtificialEyeFeeRiel' in table 'tblPatientReceipt' is DBNul"& _
"l.", e)
End Try
End Get
Set
Me(Me.tabletblPatientReceipt.ArtificialEyeFeeRielColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property OtherFeeUSD() As Double
Get
Try
Return CType(Me(Me.tabletblPatientReceipt.OtherFeeUSDColumn),Double)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'OtherFeeUSD' in table 'tblPatientReceipt' is DBNull.", e)
End Try
End Get
Set
Me(Me.tabletblPatientReceipt.OtherFeeUSDColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property OtherFeeRiel() As Double
Get
Try
Return CType(Me(Me.tabletblPatientReceipt.OtherFeeRielColumn),Double)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'OtherFeeRiel' in table 'tblPatientReceipt' is DBNull.", e)
End Try
End Get
Set
Me(Me.tabletblPatientReceipt.OtherFeeRielColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property HN() As Long
Get
Return CType(Me(Me.tabletblPatientReceipt.HNColumn),Long)
End Get
Set
Me(Me.tabletblPatientReceipt.HNColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property ID() As Long
Get
Return CType(Me(Me.tabletblPatientReceipt.IDColumn),Long)
End Get
Set
Me(Me.tabletblPatientReceipt.IDColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property IDCashReceipt() As String
Get
Return CType(Me(Me.tabletblPatientReceipt.IDCashReceiptColumn),String)
End Get
Set
Me(Me.tabletblPatientReceipt.IDCashReceiptColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property ReceiptNo() As Long
Get
Return CType(Me(Me.tabletblPatientReceipt.ReceiptNoColumn),Long)
End Get
Set
Me(Me.tabletblPatientReceipt.ReceiptNoColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property HN1() As Decimal
Get
Return CType(Me(Me.tabletblPatientReceipt.HN1Column),Decimal)
End Get
Set
Me(Me.tabletblPatientReceipt.HN1Column) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Function IsDateInNull() As Boolean
Return Me.IsNull(Me.tabletblPatientReceipt.DateInColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub SetDateInNull()
Me(Me.tabletblPatientReceipt.DateInColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Function IsCashUSDNull() As Boolean
Return Me.IsNull(Me.tabletblPatientReceipt.CashUSDColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub SetCashUSDNull()
Me(Me.tabletblPatientReceipt.CashUSDColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Function IsCashRielNull() As Boolean
Return Me.IsNull(Me.tabletblPatientReceipt.CashRielColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub SetCashRielNull()
Me(Me.tabletblPatientReceipt.CashRielColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Function IsOutPatientUSDNull() As Boolean
Return Me.IsNull(Me.tabletblPatientReceipt.OutPatientUSDColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub SetOutPatientUSDNull()
Me(Me.tabletblPatientReceipt.OutPatientUSDColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Function IsOutPatientRielNull() As Boolean
Return Me.IsNull(Me.tabletblPatientReceipt.OutPatientRielColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub SetOutPatientRielNull()
Me(Me.tabletblPatientReceipt.OutPatientRielColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Function IsInPatientUSDNull() As Boolean
Return Me.IsNull(Me.tabletblPatientReceipt.InPatientUSDColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub SetInPatientUSDNull()
Me(Me.tabletblPatientReceipt.InPatientUSDColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Function IsInPatientRielNull() As Boolean
Return Me.IsNull(Me.tabletblPatientReceipt.InPatientRielColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub SetInPatientRielNull()
Me(Me.tabletblPatientReceipt.InPatientRielColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Function IsGlassFeeUSDNull() As Boolean
Return Me.IsNull(Me.tabletblPatientReceipt.GlassFeeUSDColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub SetGlassFeeUSDNull()
Me(Me.tabletblPatientReceipt.GlassFeeUSDColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Function IsGlassFeeRielNull() As Boolean
Return Me.IsNull(Me.tabletblPatientReceipt.GlassFeeRielColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub SetGlassFeeRielNull()
Me(Me.tabletblPatientReceipt.GlassFeeRielColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Function IsArtificialEyeFeeUSDNull() As Boolean
Return Me.IsNull(Me.tabletblPatientReceipt.ArtificialEyeFeeUSDColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub SetArtificialEyeFeeUSDNull()
Me(Me.tabletblPatientReceipt.ArtificialEyeFeeUSDColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Function IsArtificialEyeFeeRielNull() As Boolean
Return Me.IsNull(Me.tabletblPatientReceipt.ArtificialEyeFeeRielColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub SetArtificialEyeFeeRielNull()
Me(Me.tabletblPatientReceipt.ArtificialEyeFeeRielColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Function IsOtherFeeUSDNull() As Boolean
Return Me.IsNull(Me.tabletblPatientReceipt.OtherFeeUSDColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub SetOtherFeeUSDNull()
Me(Me.tabletblPatientReceipt.OtherFeeUSDColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Function IsOtherFeeRielNull() As Boolean
Return Me.IsNull(Me.tabletblPatientReceipt.OtherFeeRielColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub SetOtherFeeRielNull()
Me(Me.tabletblPatientReceipt.OtherFeeRielColumn) = Global.System.Convert.DBNull
End Sub
End Class
'''<summary>
'''Row event argument class
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0")> _
Public Class tblPatientReceiptRowChangeEvent
Inherits Global.System.EventArgs
Private eventRow As tblPatientReceiptRow
Private eventAction As Global.System.Data.DataRowAction
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub New(ByVal row As tblPatientReceiptRow, ByVal action As Global.System.Data.DataRowAction)
MyBase.New
Me.eventRow = row
Me.eventAction = action
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property Row() As tblPatientReceiptRow
Get
Return Me.eventRow
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public ReadOnly Property Action() As Global.System.Data.DataRowAction
Get
Return Me.eventAction
End Get
End Property
End Class
End Class
Namespace DataSetCashCountDailyTableAdapters
'''<summary>
'''Represents the connection and commands used to retrieve and save data.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0"), _
Global.System.ComponentModel.DesignerCategoryAttribute("code"), _
Global.System.ComponentModel.ToolboxItem(true), _
Global.System.ComponentModel.DataObjectAttribute(true), _
Global.System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterDesigner, Microsoft.VSDesigner"& _
", Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Partial Public Class tblPatientReceiptTableAdapter
Inherits Global.System.ComponentModel.Component
Private WithEvents _adapter As Global.System.Data.SqlClient.SqlDataAdapter
Private _connection As Global.System.Data.SqlClient.SqlConnection
Private _commandCollection() As Global.System.Data.SqlClient.SqlCommand
Private _clearBeforeFill As Boolean
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Sub New()
MyBase.New
Me.ClearBeforeFill = true
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Private ReadOnly Property Adapter() As Global.System.Data.SqlClient.SqlDataAdapter
Get
If (Me._adapter Is Nothing) Then
Me.InitAdapter
End If
Return Me._adapter
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Friend Property Connection() As Global.System.Data.SqlClient.SqlConnection
Get
If (Me._connection Is Nothing) Then
Me.InitConnection
End If
Return Me._connection
End Get
Set
Me._connection = value
If (Not (Me.Adapter.InsertCommand) Is Nothing) Then
Me.Adapter.InsertCommand.Connection = value
End If
If (Not (Me.Adapter.DeleteCommand) Is Nothing) Then
Me.Adapter.DeleteCommand.Connection = value
End If
If (Not (Me.Adapter.UpdateCommand) Is Nothing) Then
Me.Adapter.UpdateCommand.Connection = value
End If
Dim i As Integer = 0
Do While (i < Me.CommandCollection.Length)
If (Not (Me.CommandCollection(i)) Is Nothing) Then
CType(Me.CommandCollection(i),Global.System.Data.SqlClient.SqlCommand).Connection = value
End If
i = (i + 1)
Loop
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Protected ReadOnly Property CommandCollection() As Global.System.Data.SqlClient.SqlCommand()
Get
If (Me._commandCollection Is Nothing) Then
Me.InitCommandCollection
End If
Return Me._commandCollection
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Public Property ClearBeforeFill() As Boolean
Get
Return Me._clearBeforeFill
End Get
Set
Me._clearBeforeFill = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Private Sub InitAdapter()
Me._adapter = New Global.System.Data.SqlClient.SqlDataAdapter
Dim tableMapping As Global.System.Data.Common.DataTableMapping = New Global.System.Data.Common.DataTableMapping
tableMapping.SourceTable = "Table"
tableMapping.DataSetTable = "tblPatientReceipt"
tableMapping.ColumnMappings.Add("DateIn", "DateIn")
tableMapping.ColumnMappings.Add("CashUSD", "CashUSD")
tableMapping.ColumnMappings.Add("CashRiel", "CashRiel")
tableMapping.ColumnMappings.Add("OutPatientUSD", "OutPatientUSD")
tableMapping.ColumnMappings.Add("OutPatientRiel", "OutPatientRiel")
tableMapping.ColumnMappings.Add("InPatientUSD", "InPatientUSD")
tableMapping.ColumnMappings.Add("InPatientRiel", "InPatientRiel")
tableMapping.ColumnMappings.Add("GlassFeeUSD", "GlassFeeUSD")
tableMapping.ColumnMappings.Add("GlassFeeRiel", "GlassFeeRiel")
tableMapping.ColumnMappings.Add("ArtificialEyeFeeUSD", "ArtificialEyeFeeUSD")
tableMapping.ColumnMappings.Add("ArtificialEyeFeeRiel", "ArtificialEyeFeeRiel")
tableMapping.ColumnMappings.Add("OtherFeeUSD", "OtherFeeUSD")
tableMapping.ColumnMappings.Add("OtherFeeRiel", "OtherFeeRiel")
tableMapping.ColumnMappings.Add("ID", "ID")
tableMapping.ColumnMappings.Add("IDCashReceipt", "IDCashReceipt")
tableMapping.ColumnMappings.Add("ReceiptNo", "ReceiptNo")
tableMapping.ColumnMappings.Add("HN", "HN1")
Me._adapter.TableMappings.Add(tableMapping)
Me._adapter.DeleteCommand = New Global.System.Data.SqlClient.SqlCommand
Me._adapter.DeleteCommand.Connection = Me.Connection
Me._adapter.DeleteCommand.CommandText = "DELETE FROM [tblPatientReceipt] WHERE (((@IsNull_CashUSD = 1 AND [CashUSD] IS NUL"& _
"L) OR ([CashUSD] = @Original_CashUSD)) AND ((@IsNull_CashRiel = 1 AND [CashRiel]"& _
" IS NULL) OR ([CashRiel] = @Original_CashRiel)) AND ((@IsNull_InPatientRiel = 1 "& _
"AND [OperationFeeRiel] IS NULL) OR ([OperationFeeRiel] = @Original_InPatientRiel"& _
")) AND ((@IsNull_GlassFeeUSD = 1 AND [GlassFeeUSD] IS NULL) OR ([GlassFeeUSD] = "& _
"@Original_GlassFeeUSD)) AND ((@IsNull_GlassFeeRiel = 1 AND [GlassFeeRiel] IS NUL"& _
"L) OR ([GlassFeeRiel] = @Original_GlassFeeRiel)) AND ((@IsNull_ArtificialEyeFeeU"& _
"SD = 1 AND [ArtificialEyeFeeUSD] IS NULL) OR ([ArtificialEyeFeeUSD] = @Original_"& _
"ArtificialEyeFeeUSD)) AND ((@IsNull_ArtificialEyeFeeRiel = 1 AND [ArtificialEyeF"& _
"eeRiel] IS NULL) OR ([ArtificialEyeFeeRiel] = @Original_ArtificialEyeFeeRiel)) A"& _
"ND ((@IsNull_OtherFeeUSD = 1 AND [OtherFeeUSD] IS NULL) OR ([OtherFeeUSD] = @Ori"& _
"ginal_OtherFeeUSD)) AND ((@IsNull_OtherFeeRiel = 1 AND [OtherFeeRiel] IS NULL) O"& _
"R ([OtherFeeRiel] = @Original_OtherFeeRiel)) AND ([HN] = @Original_HN) AND ([ID]"& _
" = @Original_ID) AND ([IDCashReceipt] = @Original_IDCashReceipt) AND ([ReceiptNo"& _
"] = @Original_ReceiptNo))"
Me._adapter.DeleteCommand.CommandType = Global.System.Data.CommandType.Text
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_CashUSD", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "CashUSD", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_CashUSD", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "CashUSD", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_CashRiel", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "CashRiel", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_CashRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "CashRiel", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_InPatientRiel", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "InPatientRiel", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_InPatientRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "InPatientRiel", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_GlassFeeUSD", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "GlassFeeUSD", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_GlassFeeUSD", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "GlassFeeUSD", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_GlassFeeRiel", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "GlassFeeRiel", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_GlassFeeRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "GlassFeeRiel", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_ArtificialEyeFeeUSD", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ArtificialEyeFeeUSD", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_ArtificialEyeFeeUSD", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ArtificialEyeFeeUSD", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_ArtificialEyeFeeRiel", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ArtificialEyeFeeRiel", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_ArtificialEyeFeeRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ArtificialEyeFeeRiel", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_OtherFeeUSD", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "OtherFeeUSD", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_OtherFeeUSD", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "OtherFeeUSD", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_OtherFeeRiel", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "OtherFeeRiel", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_OtherFeeRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "OtherFeeRiel", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_HN", Global.System.Data.SqlDbType.[Decimal], 0, Global.System.Data.ParameterDirection.Input, 18, 0, "HN", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_ID", Global.System.Data.SqlDbType.BigInt, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ID", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_IDCashReceipt", Global.System.Data.SqlDbType.VarChar, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "IDCashReceipt", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_ReceiptNo", Global.System.Data.SqlDbType.BigInt, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ReceiptNo", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.InsertCommand = New Global.System.Data.SqlClient.SqlCommand
Me._adapter.InsertCommand.Connection = Me.Connection
Me._adapter.InsertCommand.CommandText = "INSERT INTO [tblPatientReceipt] ([CashUSD], [CashRiel], [OperationFeeRiel], [Glas"& _
"sFeeUSD], [GlassFeeRiel], [ArtificialEyeFeeUSD], [ArtificialEyeFeeRiel], [OtherF"& _
"eeUSD], [OtherFeeRiel], [HN], [IDCashReceipt], [ReceiptNo]) VALUES (@CashUSD, @C"& _
"ashRiel, @InPatientRiel, @GlassFeeUSD, @GlassFeeRiel, @ArtificialEyeFeeUSD, @Art"& _
"ificialEyeFeeRiel, @OtherFeeUSD, @OtherFeeRiel, @HN, @IDCashReceipt, @ReceiptNo)"& _
";"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"SELECT CONVERT (VARCHAR(11), DateIn, 106) AS DateIn, CashUSD, CashRiel, Consu"& _
"ltationFeeUSD + FollowUpFeeUSD AS OutPatientUSD, ConsultationFeeRiel + FollowUpF"& _
"eeRiel AS OutPatientRiel, OperationFeeUSD + MedicineFeeUSD AS InPatientUSD, Oper"& _
"ationFeeRiel AS InPatientRiel, GlassFeeUSD, GlassFeeRiel, ArtificialEyeFeeUSD, A"& _
"rtificialEyeFeeRiel, OtherFeeUSD, OtherFeeRiel, HN, ID, IDCashReceipt, ReceiptNo"& _
" FROM tblPatientReceipt WHERE (ID = SCOPE_IDENTITY()) AND (ReceiptNo = @ReceiptN"& _
"o)"
Me._adapter.InsertCommand.CommandType = Global.System.Data.CommandType.Text
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@CashUSD", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "CashUSD", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@CashRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "CashRiel", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@InPatientRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "InPatientRiel", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@GlassFeeUSD", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "GlassFeeUSD", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@GlassFeeRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "GlassFeeRiel", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@ArtificialEyeFeeUSD", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ArtificialEyeFeeUSD", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@ArtificialEyeFeeRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ArtificialEyeFeeRiel", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@OtherFeeUSD", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "OtherFeeUSD", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@OtherFeeRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "OtherFeeRiel", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@HN", Global.System.Data.SqlDbType.[Decimal], 0, Global.System.Data.ParameterDirection.Input, 18, 0, "HN", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IDCashReceipt", Global.System.Data.SqlDbType.VarChar, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "IDCashReceipt", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@ReceiptNo", Global.System.Data.SqlDbType.BigInt, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ReceiptNo", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand = New Global.System.Data.SqlClient.SqlCommand
Me._adapter.UpdateCommand.Connection = Me.Connection
Me._adapter.UpdateCommand.CommandText = "UPDATE [tblPatientReceipt] SET [CashUSD] = @CashUSD, [CashRiel] = @CashRiel, [Ope"& _
"rationFeeRiel] = @InPatientRiel, [GlassFeeUSD] = @GlassFeeUSD, [GlassFeeRiel] = "& _
"@GlassFeeRiel, [ArtificialEyeFeeUSD] = @ArtificialEyeFeeUSD, [ArtificialEyeFeeRi"& _
"el] = @ArtificialEyeFeeRiel, [OtherFeeUSD] = @OtherFeeUSD, [OtherFeeRiel] = @Oth"& _
"erFeeRiel, [HN] = @HN, [IDCashReceipt] = @IDCashReceipt, [ReceiptNo] = @ReceiptN"& _
"o WHERE (((@IsNull_CashUSD = 1 AND [CashUSD] IS NULL) OR ([CashUSD] = @Original_"& _
"CashUSD)) AND ((@IsNull_CashRiel = 1 AND [CashRiel] IS NULL) OR ([CashRiel] = @O"& _
"riginal_CashRiel)) AND ((@IsNull_InPatientRiel = 1 AND [OperationFeeRiel] IS NUL"& _
"L) OR ([OperationFeeRiel] = @Original_InPatientRiel)) AND ((@IsNull_GlassFeeUSD "& _
"= 1 AND [GlassFeeUSD] IS NULL) OR ([GlassFeeUSD] = @Original_GlassFeeUSD)) AND ("& _
"(@IsNull_GlassFeeRiel = 1 AND [GlassFeeRiel] IS NULL) OR ([GlassFeeRiel] = @Orig"& _
"inal_GlassFeeRiel)) AND ((@IsNull_ArtificialEyeFeeUSD = 1 AND [ArtificialEyeFeeU"& _
"SD] IS NULL) OR ([ArtificialEyeFeeUSD] = @Original_ArtificialEyeFeeUSD)) AND ((@"& _
"IsNull_ArtificialEyeFeeRiel = 1 AND [ArtificialEyeFeeRiel] IS NULL) OR ([Artific"& _
"ialEyeFeeRiel] = @Original_ArtificialEyeFeeRiel)) AND ((@IsNull_OtherFeeUSD = 1 "& _
"AND [OtherFeeUSD] IS NULL) OR ([OtherFeeUSD] = @Original_OtherFeeUSD)) AND ((@Is"& _
"Null_OtherFeeRiel = 1 AND [OtherFeeRiel] IS NULL) OR ([OtherFeeRiel] = @Original"& _
"_OtherFeeRiel)) AND ([HN] = @Original_HN) AND ([ID] = @Original_ID) AND ([IDCash"& _
"Receipt] = @Original_IDCashReceipt) AND ([ReceiptNo] = @Original_ReceiptNo));"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&"S"& _
"ELECT CONVERT (VARCHAR(11), DateIn, 106) AS DateIn, CashUSD, CashRiel, Consultat"& _
"ionFeeUSD + FollowUpFeeUSD AS OutPatientUSD, ConsultationFeeRiel + FollowUpFeeRi"& _
"el AS OutPatientRiel, OperationFeeUSD + MedicineFeeUSD AS InPatientUSD, Operatio"& _
"nFeeRiel AS InPatientRiel, GlassFeeUSD, GlassFeeRiel, ArtificialEyeFeeUSD, Artif"& _
"icialEyeFeeRiel, OtherFeeUSD, OtherFeeRiel, HN, ID, IDCashReceipt, ReceiptNo FRO"& _
"M tblPatientReceipt WHERE (ID = @ID) AND (ReceiptNo = @ReceiptNo)"
Me._adapter.UpdateCommand.CommandType = Global.System.Data.CommandType.Text
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@CashUSD", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "CashUSD", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@CashRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "CashRiel", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@InPatientRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "InPatientRiel", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@GlassFeeUSD", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "GlassFeeUSD", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@GlassFeeRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "GlassFeeRiel", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@ArtificialEyeFeeUSD", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ArtificialEyeFeeUSD", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@ArtificialEyeFeeRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ArtificialEyeFeeRiel", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@OtherFeeUSD", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "OtherFeeUSD", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@OtherFeeRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "OtherFeeRiel", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@HN", Global.System.Data.SqlDbType.[Decimal], 0, Global.System.Data.ParameterDirection.Input, 18, 0, "HN", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IDCashReceipt", Global.System.Data.SqlDbType.VarChar, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "IDCashReceipt", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@ReceiptNo", Global.System.Data.SqlDbType.BigInt, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ReceiptNo", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_CashUSD", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "CashUSD", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_CashUSD", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "CashUSD", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_CashRiel", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "CashRiel", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_CashRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "CashRiel", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_InPatientRiel", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "InPatientRiel", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_InPatientRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "InPatientRiel", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_GlassFeeUSD", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "GlassFeeUSD", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_GlassFeeUSD", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "GlassFeeUSD", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_GlassFeeRiel", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "GlassFeeRiel", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_GlassFeeRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "GlassFeeRiel", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_ArtificialEyeFeeUSD", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ArtificialEyeFeeUSD", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_ArtificialEyeFeeUSD", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ArtificialEyeFeeUSD", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_ArtificialEyeFeeRiel", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ArtificialEyeFeeRiel", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_ArtificialEyeFeeRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ArtificialEyeFeeRiel", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_OtherFeeUSD", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "OtherFeeUSD", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_OtherFeeUSD", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "OtherFeeUSD", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@IsNull_OtherFeeRiel", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "OtherFeeRiel", Global.System.Data.DataRowVersion.Original, true, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_OtherFeeRiel", Global.System.Data.SqlDbType.Float, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "OtherFeeRiel", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_HN", Global.System.Data.SqlDbType.[Decimal], 0, Global.System.Data.ParameterDirection.Input, 18, 0, "HN", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_ID", Global.System.Data.SqlDbType.BigInt, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ID", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_IDCashReceipt", Global.System.Data.SqlDbType.VarChar, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "IDCashReceipt", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@Original_ReceiptNo", Global.System.Data.SqlDbType.BigInt, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "ReceiptNo", Global.System.Data.DataRowVersion.Original, false, Nothing, "", "", ""))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@ID", Global.System.Data.SqlDbType.BigInt, 8, Global.System.Data.ParameterDirection.Input, 0, 0, "ID", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Private Sub InitConnection()
Me._connection = New Global.System.Data.SqlClient.SqlConnection
Me._connection.ConnectionString = Global.TakeoHospitalInventory.My.MySettings.Default.TakeoDBConnectionString
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Private Sub InitCommandCollection()
Me._commandCollection = New Global.System.Data.SqlClient.SqlCommand(0) {}
Me._commandCollection(0) = New Global.System.Data.SqlClient.SqlCommand
Me._commandCollection(0).Connection = Me.Connection
Me._commandCollection(0).CommandText = "SELECT CONVERT (VARCHAR(11), DateIn, 106) AS DateIn, CashUSD, CashRiel, Consultat"& _
"ionFeeUSD + FollowUpFeeUSD AS OutPatientUSD, ConsultationFeeRiel + FollowUpFeeRi"& _
"el AS OutPatientRiel, OperationFeeUSD + MedicineFeeUSD AS InPatientUSD, Operatio"& _
"nFeeRiel AS InPatientRiel, GlassFeeUSD, GlassFeeRiel, ArtificialEyeFeeUSD, Artif"& _
"icialEyeFeeRiel, OtherFeeUSD, OtherFeeRiel, HN, ID, IDCashReceipt, ReceiptNo FRO"& _
"M tblPatientReceipt"
Me._commandCollection(0).CommandType = Global.System.Data.CommandType.Text
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.Fill, true)> _
Public Overloads Overridable Function Fill(ByVal dataTable As DataSetCashCountDaily.tblPatientReceiptDataTable) As Integer
Me.Adapter.SelectCommand = Me.CommandCollection(0)
If (Me.ClearBeforeFill = true) Then
dataTable.Clear
End If
Dim returnValue As Integer = Me.Adapter.Fill(dataTable)
Return returnValue
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.[Select], true)> _
Public Overloads Overridable Function GetData() As DataSetCashCountDaily.tblPatientReceiptDataTable
Me.Adapter.SelectCommand = Me.CommandCollection(0)
Dim dataTable As DataSetCashCountDaily.tblPatientReceiptDataTable = New DataSetCashCountDaily.tblPatientReceiptDataTable
Me.Adapter.Fill(dataTable)
Return dataTable
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Public Overloads Overridable Function Update(ByVal dataTable As DataSetCashCountDaily.tblPatientReceiptDataTable) As Integer
Return Me.Adapter.Update(dataTable)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Public Overloads Overridable Function Update(ByVal dataSet As DataSetCashCountDaily) As Integer
Return Me.Adapter.Update(dataSet, "tblPatientReceipt")
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Public Overloads Overridable Function Update(ByVal dataRow As Global.System.Data.DataRow) As Integer
Return Me.Adapter.Update(New Global.System.Data.DataRow() {dataRow})
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Public Overloads Overridable Function Update(ByVal dataRows() As Global.System.Data.DataRow) As Integer
Return Me.Adapter.Update(dataRows)
End Function
End Class
End Namespace
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> Partial Class frmItemItem
#Region "Windows Form Designer generated code "
<System.Diagnostics.DebuggerNonUserCode()> Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
End Sub
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> Protected Overloads Overrides Sub Dispose(ByVal Disposing As Boolean)
If Disposing Then
If Not components Is Nothing Then
components.Dispose()
End If
End If
MyBase.Dispose(Disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
Public ToolTip1 As System.Windows.Forms.ToolTip
Public WithEvents _cmdClear_10 As System.Windows.Forms.Button
Public WithEvents _cmdStockItem_10 As System.Windows.Forms.Button
Public WithEvents _cmdClear_9 As System.Windows.Forms.Button
Public WithEvents _cmdStockItem_9 As System.Windows.Forms.Button
Public WithEvents _cmdClear_8 As System.Windows.Forms.Button
Public WithEvents _cmdStockItem_8 As System.Windows.Forms.Button
Public WithEvents _cmdClear_7 As System.Windows.Forms.Button
Public WithEvents _cmdStockItem_7 As System.Windows.Forms.Button
Public WithEvents _cmdClear_6 As System.Windows.Forms.Button
Public WithEvents _cmdStockItem_6 As System.Windows.Forms.Button
Public WithEvents _cmdClear_5 As System.Windows.Forms.Button
Public WithEvents _cmdStockItem_5 As System.Windows.Forms.Button
Public WithEvents _cmdClear_4 As System.Windows.Forms.Button
Public WithEvents _cmdStockItem_4 As System.Windows.Forms.Button
Public WithEvents _cmdClear_3 As System.Windows.Forms.Button
Public WithEvents _cmdStockItem_3 As System.Windows.Forms.Button
Public WithEvents _cmdClear_2 As System.Windows.Forms.Button
Public WithEvents _cmdStockItem_2 As System.Windows.Forms.Button
Public WithEvents _cmdClear_1 As System.Windows.Forms.Button
Public WithEvents _cmdStockItem_1 As System.Windows.Forms.Button
Public WithEvents cmdExit As System.Windows.Forms.Button
Public WithEvents cmdLoad As System.Windows.Forms.Button
Public WithEvents _optDataType_1 As System.Windows.Forms.RadioButton
Public WithEvents _optDataType_0 As System.Windows.Forms.RadioButton
Public WithEvents _lbl_11 As System.Windows.Forms.Label
Public WithEvents _lbl_10 As System.Windows.Forms.Label
Public WithEvents _lbl_9 As System.Windows.Forms.Label
Public WithEvents _lbl_8 As System.Windows.Forms.Label
Public WithEvents _lbl_7 As System.Windows.Forms.Label
Public WithEvents _lbl_6 As System.Windows.Forms.Label
Public WithEvents _lbl_5 As System.Windows.Forms.Label
Public WithEvents _lbl_4 As System.Windows.Forms.Label
Public WithEvents _lbl_3 As System.Windows.Forms.Label
Public WithEvents _lbl_2 As System.Windows.Forms.Label
Public WithEvents _lblItem_10 As System.Windows.Forms.Label
Public WithEvents _lblItem_9 As System.Windows.Forms.Label
Public WithEvents _lblItem_8 As System.Windows.Forms.Label
Public WithEvents _lblItem_7 As System.Windows.Forms.Label
Public WithEvents _lblItem_6 As System.Windows.Forms.Label
Public WithEvents _lblItem_5 As System.Windows.Forms.Label
Public WithEvents _lblItem_4 As System.Windows.Forms.Label
Public WithEvents _lblItem_3 As System.Windows.Forms.Label
Public WithEvents _lblItem_2 As System.Windows.Forms.Label
Public WithEvents _lblItem_1 As System.Windows.Forms.Label
Public WithEvents _lbl_0 As System.Windows.Forms.Label
Public WithEvents _Shape1_1 As Microsoft.VisualBasic.PowerPacks.RectangleShape
'Public WithEvents cmdClear As Microsoft.VisualBasic.Compatibility.VB6.ButtonArray
'Public WithEvents cmdStockItem As Microsoft.VisualBasic.Compatibility.VB6.ButtonArray
'Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
'Public WithEvents lblItem As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
'Public WithEvents optDataType As Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray
Public WithEvents Shape1 As RectangleShapeArray
Public WithEvents ShapeContainer1 As Microsoft.VisualBasic.PowerPacks.ShapeContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(frmItemItem))
Me.components = New System.ComponentModel.Container()
Me.ToolTip1 = New System.Windows.Forms.ToolTip(components)
Me.ShapeContainer1 = New Microsoft.VisualBasic.PowerPacks.ShapeContainer
Me._cmdClear_10 = New System.Windows.Forms.Button
Me._cmdStockItem_10 = New System.Windows.Forms.Button
Me._cmdClear_9 = New System.Windows.Forms.Button
Me._cmdStockItem_9 = New System.Windows.Forms.Button
Me._cmdClear_8 = New System.Windows.Forms.Button
Me._cmdStockItem_8 = New System.Windows.Forms.Button
Me._cmdClear_7 = New System.Windows.Forms.Button
Me._cmdStockItem_7 = New System.Windows.Forms.Button
Me._cmdClear_6 = New System.Windows.Forms.Button
Me._cmdStockItem_6 = New System.Windows.Forms.Button
Me._cmdClear_5 = New System.Windows.Forms.Button
Me._cmdStockItem_5 = New System.Windows.Forms.Button
Me._cmdClear_4 = New System.Windows.Forms.Button
Me._cmdStockItem_4 = New System.Windows.Forms.Button
Me._cmdClear_3 = New System.Windows.Forms.Button
Me._cmdStockItem_3 = New System.Windows.Forms.Button
Me._cmdClear_2 = New System.Windows.Forms.Button
Me._cmdStockItem_2 = New System.Windows.Forms.Button
Me._cmdClear_1 = New System.Windows.Forms.Button
Me._cmdStockItem_1 = New System.Windows.Forms.Button
Me.cmdExit = New System.Windows.Forms.Button
Me.cmdLoad = New System.Windows.Forms.Button
Me._optDataType_1 = New System.Windows.Forms.RadioButton
Me._optDataType_0 = New System.Windows.Forms.RadioButton
Me._lbl_11 = New System.Windows.Forms.Label
Me._lbl_10 = New System.Windows.Forms.Label
Me._lbl_9 = New System.Windows.Forms.Label
Me._lbl_8 = New System.Windows.Forms.Label
Me._lbl_7 = New System.Windows.Forms.Label
Me._lbl_6 = New System.Windows.Forms.Label
Me._lbl_5 = New System.Windows.Forms.Label
Me._lbl_4 = New System.Windows.Forms.Label
Me._lbl_3 = New System.Windows.Forms.Label
Me._lbl_2 = New System.Windows.Forms.Label
Me._lblItem_10 = New System.Windows.Forms.Label
Me._lblItem_9 = New System.Windows.Forms.Label
Me._lblItem_8 = New System.Windows.Forms.Label
Me._lblItem_7 = New System.Windows.Forms.Label
Me._lblItem_6 = New System.Windows.Forms.Label
Me._lblItem_5 = New System.Windows.Forms.Label
Me._lblItem_4 = New System.Windows.Forms.Label
Me._lblItem_3 = New System.Windows.Forms.Label
Me._lblItem_2 = New System.Windows.Forms.Label
Me._lblItem_1 = New System.Windows.Forms.Label
Me._lbl_0 = New System.Windows.Forms.Label
Me._Shape1_1 = New Microsoft.VisualBasic.PowerPacks.RectangleShape
'Me.cmdClear = New Microsoft.VisualBasic.Compatibility.VB6.ButtonArray(components)
'Me.cmdStockItem = New Microsoft.VisualBasic.Compatibility.VB6.ButtonArray(components)
'Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
'Me.lblItem = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
'Me.optDataType = New Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray(components)
Me.Shape1 = New RectangleShapeArray(components)
Me.SuspendLayout()
Me.ToolTip1.Active = True
'CType(Me.cmdClear, System.ComponentModel.ISupportInitialize).BeginInit()
'CType(Me.cmdStockItem, System.ComponentModel.ISupportInitialize).BeginInit()
'CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
'CType(Me.lblItem, System.ComponentModel.ISupportInitialize).BeginInit()
'CType(Me.optDataType, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.Shape1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
Me.Text = "Compare Stock Item to Stock Item"
Me.ClientSize = New System.Drawing.Size(506, 369)
Me.Location = New System.Drawing.Point(3, 22)
Me.ControlBox = False
Me.KeyPreview = True
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.ShowInTaskbar = False
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.SystemColors.Control
Me.Enabled = True
Me.Cursor = System.Windows.Forms.Cursors.Default
Me.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.HelpButton = False
Me.WindowState = System.Windows.Forms.FormWindowState.Normal
Me.Name = "frmItemItem"
Me._cmdClear_10.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdClear_10.Text = "&Clear"
Me._cmdClear_10.Size = New System.Drawing.Size(34, 19)
Me._cmdClear_10.Location = New System.Drawing.Point(453, 282)
Me._cmdClear_10.TabIndex = 34
Me._cmdClear_10.TabStop = False
Me._cmdClear_10.BackColor = System.Drawing.SystemColors.Control
Me._cmdClear_10.CausesValidation = True
Me._cmdClear_10.Enabled = True
Me._cmdClear_10.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdClear_10.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdClear_10.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdClear_10.Name = "_cmdClear_10"
Me._cmdStockItem_10.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdStockItem_10.Text = "..."
Me._cmdStockItem_10.Size = New System.Drawing.Size(34, 19)
Me._cmdStockItem_10.Location = New System.Drawing.Point(414, 282)
Me._cmdStockItem_10.TabIndex = 32
Me._cmdStockItem_10.BackColor = System.Drawing.SystemColors.Control
Me._cmdStockItem_10.CausesValidation = True
Me._cmdStockItem_10.Enabled = True
Me._cmdStockItem_10.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdStockItem_10.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdStockItem_10.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdStockItem_10.TabStop = True
Me._cmdStockItem_10.Name = "_cmdStockItem_10"
Me._cmdClear_9.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdClear_9.Text = "&Clear"
Me._cmdClear_9.Size = New System.Drawing.Size(34, 19)
Me._cmdClear_9.Location = New System.Drawing.Point(453, 255)
Me._cmdClear_9.TabIndex = 31
Me._cmdClear_9.TabStop = False
Me._cmdClear_9.BackColor = System.Drawing.SystemColors.Control
Me._cmdClear_9.CausesValidation = True
Me._cmdClear_9.Enabled = True
Me._cmdClear_9.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdClear_9.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdClear_9.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdClear_9.Name = "_cmdClear_9"
Me._cmdStockItem_9.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdStockItem_9.Text = "..."
Me._cmdStockItem_9.Size = New System.Drawing.Size(34, 19)
Me._cmdStockItem_9.Location = New System.Drawing.Point(414, 255)
Me._cmdStockItem_9.TabIndex = 29
Me._cmdStockItem_9.BackColor = System.Drawing.SystemColors.Control
Me._cmdStockItem_9.CausesValidation = True
Me._cmdStockItem_9.Enabled = True
Me._cmdStockItem_9.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdStockItem_9.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdStockItem_9.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdStockItem_9.TabStop = True
Me._cmdStockItem_9.Name = "_cmdStockItem_9"
Me._cmdClear_8.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdClear_8.Text = "&Clear"
Me._cmdClear_8.Size = New System.Drawing.Size(34, 19)
Me._cmdClear_8.Location = New System.Drawing.Point(453, 228)
Me._cmdClear_8.TabIndex = 28
Me._cmdClear_8.TabStop = False
Me._cmdClear_8.BackColor = System.Drawing.SystemColors.Control
Me._cmdClear_8.CausesValidation = True
Me._cmdClear_8.Enabled = True
Me._cmdClear_8.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdClear_8.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdClear_8.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdClear_8.Name = "_cmdClear_8"
Me._cmdStockItem_8.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdStockItem_8.Text = "..."
Me._cmdStockItem_8.Size = New System.Drawing.Size(34, 19)
Me._cmdStockItem_8.Location = New System.Drawing.Point(414, 228)
Me._cmdStockItem_8.TabIndex = 26
Me._cmdStockItem_8.BackColor = System.Drawing.SystemColors.Control
Me._cmdStockItem_8.CausesValidation = True
Me._cmdStockItem_8.Enabled = True
Me._cmdStockItem_8.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdStockItem_8.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdStockItem_8.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdStockItem_8.TabStop = True
Me._cmdStockItem_8.Name = "_cmdStockItem_8"
Me._cmdClear_7.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdClear_7.Text = "&Clear"
Me._cmdClear_7.Size = New System.Drawing.Size(34, 19)
Me._cmdClear_7.Location = New System.Drawing.Point(453, 201)
Me._cmdClear_7.TabIndex = 25
Me._cmdClear_7.TabStop = False
Me._cmdClear_7.BackColor = System.Drawing.SystemColors.Control
Me._cmdClear_7.CausesValidation = True
Me._cmdClear_7.Enabled = True
Me._cmdClear_7.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdClear_7.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdClear_7.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdClear_7.Name = "_cmdClear_7"
Me._cmdStockItem_7.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdStockItem_7.Text = "..."
Me._cmdStockItem_7.Size = New System.Drawing.Size(34, 19)
Me._cmdStockItem_7.Location = New System.Drawing.Point(414, 201)
Me._cmdStockItem_7.TabIndex = 23
Me._cmdStockItem_7.BackColor = System.Drawing.SystemColors.Control
Me._cmdStockItem_7.CausesValidation = True
Me._cmdStockItem_7.Enabled = True
Me._cmdStockItem_7.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdStockItem_7.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdStockItem_7.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdStockItem_7.TabStop = True
Me._cmdStockItem_7.Name = "_cmdStockItem_7"
Me._cmdClear_6.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdClear_6.Text = "&Clear"
Me._cmdClear_6.Size = New System.Drawing.Size(34, 19)
Me._cmdClear_6.Location = New System.Drawing.Point(453, 174)
Me._cmdClear_6.TabIndex = 22
Me._cmdClear_6.TabStop = False
Me._cmdClear_6.BackColor = System.Drawing.SystemColors.Control
Me._cmdClear_6.CausesValidation = True
Me._cmdClear_6.Enabled = True
Me._cmdClear_6.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdClear_6.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdClear_6.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdClear_6.Name = "_cmdClear_6"
Me._cmdStockItem_6.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdStockItem_6.Text = "..."
Me._cmdStockItem_6.Size = New System.Drawing.Size(34, 19)
Me._cmdStockItem_6.Location = New System.Drawing.Point(414, 174)
Me._cmdStockItem_6.TabIndex = 20
Me._cmdStockItem_6.BackColor = System.Drawing.SystemColors.Control
Me._cmdStockItem_6.CausesValidation = True
Me._cmdStockItem_6.Enabled = True
Me._cmdStockItem_6.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdStockItem_6.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdStockItem_6.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdStockItem_6.TabStop = True
Me._cmdStockItem_6.Name = "_cmdStockItem_6"
Me._cmdClear_5.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdClear_5.Text = "&Clear"
Me._cmdClear_5.Size = New System.Drawing.Size(34, 19)
Me._cmdClear_5.Location = New System.Drawing.Point(453, 147)
Me._cmdClear_5.TabIndex = 19
Me._cmdClear_5.TabStop = False
Me._cmdClear_5.BackColor = System.Drawing.SystemColors.Control
Me._cmdClear_5.CausesValidation = True
Me._cmdClear_5.Enabled = True
Me._cmdClear_5.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdClear_5.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdClear_5.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdClear_5.Name = "_cmdClear_5"
Me._cmdStockItem_5.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdStockItem_5.Text = "..."
Me._cmdStockItem_5.Size = New System.Drawing.Size(34, 19)
Me._cmdStockItem_5.Location = New System.Drawing.Point(414, 147)
Me._cmdStockItem_5.TabIndex = 17
Me._cmdStockItem_5.BackColor = System.Drawing.SystemColors.Control
Me._cmdStockItem_5.CausesValidation = True
Me._cmdStockItem_5.Enabled = True
Me._cmdStockItem_5.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdStockItem_5.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdStockItem_5.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdStockItem_5.TabStop = True
Me._cmdStockItem_5.Name = "_cmdStockItem_5"
Me._cmdClear_4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdClear_4.Text = "&Clear"
Me._cmdClear_4.Size = New System.Drawing.Size(34, 19)
Me._cmdClear_4.Location = New System.Drawing.Point(453, 120)
Me._cmdClear_4.TabIndex = 16
Me._cmdClear_4.TabStop = False
Me._cmdClear_4.BackColor = System.Drawing.SystemColors.Control
Me._cmdClear_4.CausesValidation = True
Me._cmdClear_4.Enabled = True
Me._cmdClear_4.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdClear_4.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdClear_4.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdClear_4.Name = "_cmdClear_4"
Me._cmdStockItem_4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdStockItem_4.Text = "..."
Me._cmdStockItem_4.Size = New System.Drawing.Size(34, 19)
Me._cmdStockItem_4.Location = New System.Drawing.Point(414, 120)
Me._cmdStockItem_4.TabIndex = 14
Me._cmdStockItem_4.BackColor = System.Drawing.SystemColors.Control
Me._cmdStockItem_4.CausesValidation = True
Me._cmdStockItem_4.Enabled = True
Me._cmdStockItem_4.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdStockItem_4.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdStockItem_4.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdStockItem_4.TabStop = True
Me._cmdStockItem_4.Name = "_cmdStockItem_4"
Me._cmdClear_3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdClear_3.Text = "&Clear"
Me._cmdClear_3.Size = New System.Drawing.Size(34, 19)
Me._cmdClear_3.Location = New System.Drawing.Point(453, 93)
Me._cmdClear_3.TabIndex = 13
Me._cmdClear_3.TabStop = False
Me._cmdClear_3.BackColor = System.Drawing.SystemColors.Control
Me._cmdClear_3.CausesValidation = True
Me._cmdClear_3.Enabled = True
Me._cmdClear_3.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdClear_3.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdClear_3.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdClear_3.Name = "_cmdClear_3"
Me._cmdStockItem_3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdStockItem_3.Text = "..."
Me._cmdStockItem_3.Size = New System.Drawing.Size(34, 19)
Me._cmdStockItem_3.Location = New System.Drawing.Point(414, 93)
Me._cmdStockItem_3.TabIndex = 11
Me._cmdStockItem_3.BackColor = System.Drawing.SystemColors.Control
Me._cmdStockItem_3.CausesValidation = True
Me._cmdStockItem_3.Enabled = True
Me._cmdStockItem_3.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdStockItem_3.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdStockItem_3.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdStockItem_3.TabStop = True
Me._cmdStockItem_3.Name = "_cmdStockItem_3"
Me._cmdClear_2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdClear_2.Text = "&Clear"
Me._cmdClear_2.Size = New System.Drawing.Size(34, 19)
Me._cmdClear_2.Location = New System.Drawing.Point(453, 66)
Me._cmdClear_2.TabIndex = 10
Me._cmdClear_2.TabStop = False
Me._cmdClear_2.BackColor = System.Drawing.SystemColors.Control
Me._cmdClear_2.CausesValidation = True
Me._cmdClear_2.Enabled = True
Me._cmdClear_2.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdClear_2.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdClear_2.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdClear_2.Name = "_cmdClear_2"
Me._cmdStockItem_2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdStockItem_2.Text = "..."
Me._cmdStockItem_2.Size = New System.Drawing.Size(34, 19)
Me._cmdStockItem_2.Location = New System.Drawing.Point(414, 66)
Me._cmdStockItem_2.TabIndex = 8
Me._cmdStockItem_2.BackColor = System.Drawing.SystemColors.Control
Me._cmdStockItem_2.CausesValidation = True
Me._cmdStockItem_2.Enabled = True
Me._cmdStockItem_2.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdStockItem_2.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdStockItem_2.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdStockItem_2.TabStop = True
Me._cmdStockItem_2.Name = "_cmdStockItem_2"
Me._cmdClear_1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdClear_1.Text = "&Clear"
Me._cmdClear_1.Size = New System.Drawing.Size(34, 19)
Me._cmdClear_1.Location = New System.Drawing.Point(453, 39)
Me._cmdClear_1.TabIndex = 7
Me._cmdClear_1.TabStop = False
Me._cmdClear_1.BackColor = System.Drawing.SystemColors.Control
Me._cmdClear_1.CausesValidation = True
Me._cmdClear_1.Enabled = True
Me._cmdClear_1.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdClear_1.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdClear_1.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdClear_1.Name = "_cmdClear_1"
Me._cmdStockItem_1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me._cmdStockItem_1.Text = "..."
Me._cmdStockItem_1.Size = New System.Drawing.Size(34, 19)
Me._cmdStockItem_1.Location = New System.Drawing.Point(414, 39)
Me._cmdStockItem_1.TabIndex = 5
Me._cmdStockItem_1.BackColor = System.Drawing.SystemColors.Control
Me._cmdStockItem_1.CausesValidation = True
Me._cmdStockItem_1.Enabled = True
Me._cmdStockItem_1.ForeColor = System.Drawing.SystemColors.ControlText
Me._cmdStockItem_1.Cursor = System.Windows.Forms.Cursors.Default
Me._cmdStockItem_1.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._cmdStockItem_1.TabStop = True
Me._cmdStockItem_1.Name = "_cmdStockItem_1"
Me.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.cmdExit.Text = "E&xit"
Me.cmdExit.Size = New System.Drawing.Size(79, 31)
Me.cmdExit.Location = New System.Drawing.Point(12, 321)
Me.cmdExit.TabIndex = 4
Me.cmdExit.BackColor = System.Drawing.SystemColors.Control
Me.cmdExit.CausesValidation = True
Me.cmdExit.Enabled = True
Me.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdExit.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdExit.TabStop = True
Me.cmdExit.Name = "cmdExit"
Me.cmdLoad.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.cmdLoad.Text = "&Load report >>"
Me.cmdLoad.Size = New System.Drawing.Size(79, 31)
Me.cmdLoad.Location = New System.Drawing.Point(417, 321)
Me.cmdLoad.TabIndex = 3
Me.cmdLoad.BackColor = System.Drawing.SystemColors.Control
Me.cmdLoad.CausesValidation = True
Me.cmdLoad.Enabled = True
Me.cmdLoad.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdLoad.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdLoad.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdLoad.TabStop = True
Me.cmdLoad.Name = "cmdLoad"
Me._optDataType_1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
Me._optDataType_1.Text = "Sales &Value"
Me._optDataType_1.Size = New System.Drawing.Size(145, 13)
Me._optDataType_1.Location = New System.Drawing.Point(267, 339)
Me._optDataType_1.TabIndex = 2
Me._optDataType_1.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft
Me._optDataType_1.BackColor = System.Drawing.SystemColors.Control
Me._optDataType_1.CausesValidation = True
Me._optDataType_1.Enabled = True
Me._optDataType_1.ForeColor = System.Drawing.SystemColors.ControlText
Me._optDataType_1.Cursor = System.Windows.Forms.Cursors.Default
Me._optDataType_1.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._optDataType_1.Appearance = System.Windows.Forms.Appearance.Normal
Me._optDataType_1.TabStop = True
Me._optDataType_1.Checked = False
Me._optDataType_1.Visible = True
Me._optDataType_1.Name = "_optDataType_1"
Me._optDataType_0.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
Me._optDataType_0.Text = "Sales &Quantity"
Me._optDataType_0.Size = New System.Drawing.Size(145, 13)
Me._optDataType_0.Location = New System.Drawing.Point(267, 321)
Me._optDataType_0.TabIndex = 1
Me._optDataType_0.Checked = True
Me._optDataType_0.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft
Me._optDataType_0.BackColor = System.Drawing.SystemColors.Control
Me._optDataType_0.CausesValidation = True
Me._optDataType_0.Enabled = True
Me._optDataType_0.ForeColor = System.Drawing.SystemColors.ControlText
Me._optDataType_0.Cursor = System.Windows.Forms.Cursors.Default
Me._optDataType_0.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._optDataType_0.Appearance = System.Windows.Forms.Appearance.Normal
Me._optDataType_0.TabStop = True
Me._optDataType_0.Visible = True
Me._optDataType_0.Name = "_optDataType_0"
Me._lbl_11.TextAlign = System.Drawing.ContentAlignment.TopRight
Me._lbl_11.Text = "1&0"
Me._lbl_11.Size = New System.Drawing.Size(17, 13)
Me._lbl_11.Location = New System.Drawing.Point(9, 285)
Me._lbl_11.TabIndex = 44
Me._lbl_11.BackColor = System.Drawing.Color.Transparent
Me._lbl_11.Enabled = True
Me._lbl_11.ForeColor = System.Drawing.SystemColors.ControlText
Me._lbl_11.Cursor = System.Windows.Forms.Cursors.Default
Me._lbl_11.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lbl_11.UseMnemonic = True
Me._lbl_11.Visible = True
Me._lbl_11.AutoSize = False
Me._lbl_11.BorderStyle = System.Windows.Forms.BorderStyle.None
Me._lbl_11.Name = "_lbl_11"
Me._lbl_10.TextAlign = System.Drawing.ContentAlignment.TopRight
Me._lbl_10.Text = "&9"
Me._lbl_10.Size = New System.Drawing.Size(17, 13)
Me._lbl_10.Location = New System.Drawing.Point(9, 258)
Me._lbl_10.TabIndex = 43
Me._lbl_10.BackColor = System.Drawing.Color.Transparent
Me._lbl_10.Enabled = True
Me._lbl_10.ForeColor = System.Drawing.SystemColors.ControlText
Me._lbl_10.Cursor = System.Windows.Forms.Cursors.Default
Me._lbl_10.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lbl_10.UseMnemonic = True
Me._lbl_10.Visible = True
Me._lbl_10.AutoSize = False
Me._lbl_10.BorderStyle = System.Windows.Forms.BorderStyle.None
Me._lbl_10.Name = "_lbl_10"
Me._lbl_9.TextAlign = System.Drawing.ContentAlignment.TopRight
Me._lbl_9.Text = "&8"
Me._lbl_9.Size = New System.Drawing.Size(17, 13)
Me._lbl_9.Location = New System.Drawing.Point(9, 231)
Me._lbl_9.TabIndex = 42
Me._lbl_9.BackColor = System.Drawing.Color.Transparent
Me._lbl_9.Enabled = True
Me._lbl_9.ForeColor = System.Drawing.SystemColors.ControlText
Me._lbl_9.Cursor = System.Windows.Forms.Cursors.Default
Me._lbl_9.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lbl_9.UseMnemonic = True
Me._lbl_9.Visible = True
Me._lbl_9.AutoSize = False
Me._lbl_9.BorderStyle = System.Windows.Forms.BorderStyle.None
Me._lbl_9.Name = "_lbl_9"
Me._lbl_8.TextAlign = System.Drawing.ContentAlignment.TopRight
Me._lbl_8.Text = "&7"
Me._lbl_8.Size = New System.Drawing.Size(17, 13)
Me._lbl_8.Location = New System.Drawing.Point(9, 204)
Me._lbl_8.TabIndex = 41
Me._lbl_8.BackColor = System.Drawing.Color.Transparent
Me._lbl_8.Enabled = True
Me._lbl_8.ForeColor = System.Drawing.SystemColors.ControlText
Me._lbl_8.Cursor = System.Windows.Forms.Cursors.Default
Me._lbl_8.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lbl_8.UseMnemonic = True
Me._lbl_8.Visible = True
Me._lbl_8.AutoSize = False
Me._lbl_8.BorderStyle = System.Windows.Forms.BorderStyle.None
Me._lbl_8.Name = "_lbl_8"
Me._lbl_7.TextAlign = System.Drawing.ContentAlignment.TopRight
Me._lbl_7.Text = "&6"
Me._lbl_7.Size = New System.Drawing.Size(17, 13)
Me._lbl_7.Location = New System.Drawing.Point(9, 177)
Me._lbl_7.TabIndex = 40
Me._lbl_7.BackColor = System.Drawing.Color.Transparent
Me._lbl_7.Enabled = True
Me._lbl_7.ForeColor = System.Drawing.SystemColors.ControlText
Me._lbl_7.Cursor = System.Windows.Forms.Cursors.Default
Me._lbl_7.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lbl_7.UseMnemonic = True
Me._lbl_7.Visible = True
Me._lbl_7.AutoSize = False
Me._lbl_7.BorderStyle = System.Windows.Forms.BorderStyle.None
Me._lbl_7.Name = "_lbl_7"
Me._lbl_6.TextAlign = System.Drawing.ContentAlignment.TopRight
Me._lbl_6.Text = "&5"
Me._lbl_6.Size = New System.Drawing.Size(17, 13)
Me._lbl_6.Location = New System.Drawing.Point(9, 150)
Me._lbl_6.TabIndex = 39
Me._lbl_6.BackColor = System.Drawing.Color.Transparent
Me._lbl_6.Enabled = True
Me._lbl_6.ForeColor = System.Drawing.SystemColors.ControlText
Me._lbl_6.Cursor = System.Windows.Forms.Cursors.Default
Me._lbl_6.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lbl_6.UseMnemonic = True
Me._lbl_6.Visible = True
Me._lbl_6.AutoSize = False
Me._lbl_6.BorderStyle = System.Windows.Forms.BorderStyle.None
Me._lbl_6.Name = "_lbl_6"
Me._lbl_5.TextAlign = System.Drawing.ContentAlignment.TopRight
Me._lbl_5.Text = "&4"
Me._lbl_5.Size = New System.Drawing.Size(17, 13)
Me._lbl_5.Location = New System.Drawing.Point(9, 123)
Me._lbl_5.TabIndex = 38
Me._lbl_5.BackColor = System.Drawing.Color.Transparent
Me._lbl_5.Enabled = True
Me._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText
Me._lbl_5.Cursor = System.Windows.Forms.Cursors.Default
Me._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lbl_5.UseMnemonic = True
Me._lbl_5.Visible = True
Me._lbl_5.AutoSize = False
Me._lbl_5.BorderStyle = System.Windows.Forms.BorderStyle.None
Me._lbl_5.Name = "_lbl_5"
Me._lbl_4.TextAlign = System.Drawing.ContentAlignment.TopRight
Me._lbl_4.Text = "&3"
Me._lbl_4.Size = New System.Drawing.Size(17, 13)
Me._lbl_4.Location = New System.Drawing.Point(9, 96)
Me._lbl_4.TabIndex = 37
Me._lbl_4.BackColor = System.Drawing.Color.Transparent
Me._lbl_4.Enabled = True
Me._lbl_4.ForeColor = System.Drawing.SystemColors.ControlText
Me._lbl_4.Cursor = System.Windows.Forms.Cursors.Default
Me._lbl_4.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lbl_4.UseMnemonic = True
Me._lbl_4.Visible = True
Me._lbl_4.AutoSize = False
Me._lbl_4.BorderStyle = System.Windows.Forms.BorderStyle.None
Me._lbl_4.Name = "_lbl_4"
Me._lbl_3.TextAlign = System.Drawing.ContentAlignment.TopRight
Me._lbl_3.Text = "&2"
Me._lbl_3.Size = New System.Drawing.Size(17, 13)
Me._lbl_3.Location = New System.Drawing.Point(9, 69)
Me._lbl_3.TabIndex = 36
Me._lbl_3.BackColor = System.Drawing.Color.Transparent
Me._lbl_3.Enabled = True
Me._lbl_3.ForeColor = System.Drawing.SystemColors.ControlText
Me._lbl_3.Cursor = System.Windows.Forms.Cursors.Default
Me._lbl_3.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lbl_3.UseMnemonic = True
Me._lbl_3.Visible = True
Me._lbl_3.AutoSize = False
Me._lbl_3.BorderStyle = System.Windows.Forms.BorderStyle.None
Me._lbl_3.Name = "_lbl_3"
Me._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopRight
Me._lbl_2.Text = "&1"
Me._lbl_2.Size = New System.Drawing.Size(17, 13)
Me._lbl_2.Location = New System.Drawing.Point(9, 42)
Me._lbl_2.TabIndex = 35
Me._lbl_2.BackColor = System.Drawing.Color.Transparent
Me._lbl_2.Enabled = True
Me._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText
Me._lbl_2.Cursor = System.Windows.Forms.Cursors.Default
Me._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lbl_2.UseMnemonic = True
Me._lbl_2.Visible = True
Me._lbl_2.AutoSize = False
Me._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None
Me._lbl_2.Name = "_lbl_2"
Me._lblItem_10.Size = New System.Drawing.Size(382, 19)
Me._lblItem_10.Location = New System.Drawing.Point(30, 282)
Me._lblItem_10.TabIndex = 33
Me._lblItem_10.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me._lblItem_10.BackColor = System.Drawing.SystemColors.Control
Me._lblItem_10.Enabled = True
Me._lblItem_10.ForeColor = System.Drawing.SystemColors.ControlText
Me._lblItem_10.Cursor = System.Windows.Forms.Cursors.Default
Me._lblItem_10.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lblItem_10.UseMnemonic = True
Me._lblItem_10.Visible = True
Me._lblItem_10.AutoSize = False
Me._lblItem_10.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me._lblItem_10.Name = "_lblItem_10"
Me._lblItem_9.Size = New System.Drawing.Size(382, 19)
Me._lblItem_9.Location = New System.Drawing.Point(30, 255)
Me._lblItem_9.TabIndex = 30
Me._lblItem_9.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me._lblItem_9.BackColor = System.Drawing.SystemColors.Control
Me._lblItem_9.Enabled = True
Me._lblItem_9.ForeColor = System.Drawing.SystemColors.ControlText
Me._lblItem_9.Cursor = System.Windows.Forms.Cursors.Default
Me._lblItem_9.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lblItem_9.UseMnemonic = True
Me._lblItem_9.Visible = True
Me._lblItem_9.AutoSize = False
Me._lblItem_9.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me._lblItem_9.Name = "_lblItem_9"
Me._lblItem_8.Size = New System.Drawing.Size(382, 19)
Me._lblItem_8.Location = New System.Drawing.Point(30, 228)
Me._lblItem_8.TabIndex = 27
Me._lblItem_8.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me._lblItem_8.BackColor = System.Drawing.SystemColors.Control
Me._lblItem_8.Enabled = True
Me._lblItem_8.ForeColor = System.Drawing.SystemColors.ControlText
Me._lblItem_8.Cursor = System.Windows.Forms.Cursors.Default
Me._lblItem_8.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lblItem_8.UseMnemonic = True
Me._lblItem_8.Visible = True
Me._lblItem_8.AutoSize = False
Me._lblItem_8.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me._lblItem_8.Name = "_lblItem_8"
Me._lblItem_7.Size = New System.Drawing.Size(382, 19)
Me._lblItem_7.Location = New System.Drawing.Point(30, 201)
Me._lblItem_7.TabIndex = 24
Me._lblItem_7.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me._lblItem_7.BackColor = System.Drawing.SystemColors.Control
Me._lblItem_7.Enabled = True
Me._lblItem_7.ForeColor = System.Drawing.SystemColors.ControlText
Me._lblItem_7.Cursor = System.Windows.Forms.Cursors.Default
Me._lblItem_7.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lblItem_7.UseMnemonic = True
Me._lblItem_7.Visible = True
Me._lblItem_7.AutoSize = False
Me._lblItem_7.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me._lblItem_7.Name = "_lblItem_7"
Me._lblItem_6.Size = New System.Drawing.Size(382, 19)
Me._lblItem_6.Location = New System.Drawing.Point(30, 174)
Me._lblItem_6.TabIndex = 21
Me._lblItem_6.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me._lblItem_6.BackColor = System.Drawing.SystemColors.Control
Me._lblItem_6.Enabled = True
Me._lblItem_6.ForeColor = System.Drawing.SystemColors.ControlText
Me._lblItem_6.Cursor = System.Windows.Forms.Cursors.Default
Me._lblItem_6.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lblItem_6.UseMnemonic = True
Me._lblItem_6.Visible = True
Me._lblItem_6.AutoSize = False
Me._lblItem_6.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me._lblItem_6.Name = "_lblItem_6"
Me._lblItem_5.Size = New System.Drawing.Size(382, 19)
Me._lblItem_5.Location = New System.Drawing.Point(30, 147)
Me._lblItem_5.TabIndex = 18
Me._lblItem_5.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me._lblItem_5.BackColor = System.Drawing.SystemColors.Control
Me._lblItem_5.Enabled = True
Me._lblItem_5.ForeColor = System.Drawing.SystemColors.ControlText
Me._lblItem_5.Cursor = System.Windows.Forms.Cursors.Default
Me._lblItem_5.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lblItem_5.UseMnemonic = True
Me._lblItem_5.Visible = True
Me._lblItem_5.AutoSize = False
Me._lblItem_5.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me._lblItem_5.Name = "_lblItem_5"
Me._lblItem_4.Size = New System.Drawing.Size(382, 19)
Me._lblItem_4.Location = New System.Drawing.Point(30, 120)
Me._lblItem_4.TabIndex = 15
Me._lblItem_4.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me._lblItem_4.BackColor = System.Drawing.SystemColors.Control
Me._lblItem_4.Enabled = True
Me._lblItem_4.ForeColor = System.Drawing.SystemColors.ControlText
Me._lblItem_4.Cursor = System.Windows.Forms.Cursors.Default
Me._lblItem_4.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lblItem_4.UseMnemonic = True
Me._lblItem_4.Visible = True
Me._lblItem_4.AutoSize = False
Me._lblItem_4.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me._lblItem_4.Name = "_lblItem_4"
Me._lblItem_3.Size = New System.Drawing.Size(382, 19)
Me._lblItem_3.Location = New System.Drawing.Point(30, 93)
Me._lblItem_3.TabIndex = 12
Me._lblItem_3.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me._lblItem_3.BackColor = System.Drawing.SystemColors.Control
Me._lblItem_3.Enabled = True
Me._lblItem_3.ForeColor = System.Drawing.SystemColors.ControlText
Me._lblItem_3.Cursor = System.Windows.Forms.Cursors.Default
Me._lblItem_3.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lblItem_3.UseMnemonic = True
Me._lblItem_3.Visible = True
Me._lblItem_3.AutoSize = False
Me._lblItem_3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me._lblItem_3.Name = "_lblItem_3"
Me._lblItem_2.Size = New System.Drawing.Size(382, 19)
Me._lblItem_2.Location = New System.Drawing.Point(30, 66)
Me._lblItem_2.TabIndex = 9
Me._lblItem_2.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me._lblItem_2.BackColor = System.Drawing.SystemColors.Control
Me._lblItem_2.Enabled = True
Me._lblItem_2.ForeColor = System.Drawing.SystemColors.ControlText
Me._lblItem_2.Cursor = System.Windows.Forms.Cursors.Default
Me._lblItem_2.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lblItem_2.UseMnemonic = True
Me._lblItem_2.Visible = True
Me._lblItem_2.AutoSize = False
Me._lblItem_2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me._lblItem_2.Name = "_lblItem_2"
Me._lblItem_1.Size = New System.Drawing.Size(382, 19)
Me._lblItem_1.Location = New System.Drawing.Point(30, 39)
Me._lblItem_1.TabIndex = 6
Me._lblItem_1.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me._lblItem_1.BackColor = System.Drawing.SystemColors.Control
Me._lblItem_1.Enabled = True
Me._lblItem_1.ForeColor = System.Drawing.SystemColors.ControlText
Me._lblItem_1.Cursor = System.Windows.Forms.Cursors.Default
Me._lblItem_1.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lblItem_1.UseMnemonic = True
Me._lblItem_1.Visible = True
Me._lblItem_1.AutoSize = False
Me._lblItem_1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me._lblItem_1.Name = "_lblItem_1"
Me._lbl_0.Text = "&1. Select Stock Items"
Me._lbl_0.Size = New System.Drawing.Size(123, 13)
Me._lbl_0.Location = New System.Drawing.Point(9, 9)
Me._lbl_0.TabIndex = 0
Me._lbl_0.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me._lbl_0.BackColor = System.Drawing.Color.Transparent
Me._lbl_0.Enabled = True
Me._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText
Me._lbl_0.Cursor = System.Windows.Forms.Cursors.Default
Me._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No
Me._lbl_0.UseMnemonic = True
Me._lbl_0.Visible = True
Me._lbl_0.AutoSize = True
Me._lbl_0.BorderStyle = System.Windows.Forms.BorderStyle.None
Me._lbl_0.Name = "_lbl_0"
Me._Shape1_1.BackColor = System.Drawing.Color.FromARGB(192, 192, 255)
Me._Shape1_1.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque
Me._Shape1_1.Size = New System.Drawing.Size(487, 283)
Me._Shape1_1.Location = New System.Drawing.Point(9, 30)
Me._Shape1_1.BorderColor = System.Drawing.SystemColors.WindowText
Me._Shape1_1.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid
Me._Shape1_1.BorderWidth = 1
Me._Shape1_1.FillColor = System.Drawing.Color.Black
Me._Shape1_1.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent
Me._Shape1_1.Visible = True
Me._Shape1_1.Name = "_Shape1_1"
Me.Controls.Add(_cmdClear_10)
Me.Controls.Add(_cmdStockItem_10)
Me.Controls.Add(_cmdClear_9)
Me.Controls.Add(_cmdStockItem_9)
Me.Controls.Add(_cmdClear_8)
Me.Controls.Add(_cmdStockItem_8)
Me.Controls.Add(_cmdClear_7)
Me.Controls.Add(_cmdStockItem_7)
Me.Controls.Add(_cmdClear_6)
Me.Controls.Add(_cmdStockItem_6)
Me.Controls.Add(_cmdClear_5)
Me.Controls.Add(_cmdStockItem_5)
Me.Controls.Add(_cmdClear_4)
Me.Controls.Add(_cmdStockItem_4)
Me.Controls.Add(_cmdClear_3)
Me.Controls.Add(_cmdStockItem_3)
Me.Controls.Add(_cmdClear_2)
Me.Controls.Add(_cmdStockItem_2)
Me.Controls.Add(_cmdClear_1)
Me.Controls.Add(_cmdStockItem_1)
Me.Controls.Add(cmdExit)
Me.Controls.Add(cmdLoad)
Me.Controls.Add(_optDataType_1)
Me.Controls.Add(_optDataType_0)
Me.Controls.Add(_lbl_11)
Me.Controls.Add(_lbl_10)
Me.Controls.Add(_lbl_9)
Me.Controls.Add(_lbl_8)
Me.Controls.Add(_lbl_7)
Me.Controls.Add(_lbl_6)
Me.Controls.Add(_lbl_5)
Me.Controls.Add(_lbl_4)
Me.Controls.Add(_lbl_3)
Me.Controls.Add(_lbl_2)
Me.Controls.Add(_lblItem_10)
Me.Controls.Add(_lblItem_9)
Me.Controls.Add(_lblItem_8)
Me.Controls.Add(_lblItem_7)
Me.Controls.Add(_lblItem_6)
Me.Controls.Add(_lblItem_5)
Me.Controls.Add(_lblItem_4)
Me.Controls.Add(_lblItem_3)
Me.Controls.Add(_lblItem_2)
Me.Controls.Add(_lblItem_1)
Me.Controls.Add(_lbl_0)
Me.ShapeContainer1.Shapes.Add(_Shape1_1)
Me.Controls.Add(ShapeContainer1)
'Me.cmdClear.SetIndex(_cmdClear_10, CType(10, Short))
'Me.cmdClear.SetIndex(_cmdClear_9, CType(9, Short))
'Me.cmdClear.SetIndex(_cmdClear_8, CType(8, Short))
'Me.cmdClear.SetIndex(_cmdClear_7, CType(7, Short))
'Me.cmdClear.SetIndex(_cmdClear_6, CType(6, Short))
'Me.cmdClear.SetIndex(_cmdClear_5, CType(5, Short))
'Me.cmdClear.SetIndex(_cmdClear_4, CType(4, Short))
'Me.cmdClear.SetIndex(_cmdClear_3, CType(3, Short))
'Me.cmdClear.SetIndex(_cmdClear_2, CType(2, Short))
'Me.cmdClear.SetIndex(_cmdClear_1, CType(1, Short))
'Me.cmdStockItem.SetIndex(_cmdStockItem_10, CType(10, Short))
'Me.cmdStockItem.SetIndex(_cmdStockItem_9, CType(9, Short))
'Me.cmdStockItem.SetIndex(_cmdStockItem_8, CType(8, Short))
'Me.cmdStockItem.SetIndex(_cmdStockItem_7, CType(7, Short))
'Me.cmdStockItem.SetIndex(_cmdStockItem_6, CType(6, Short))
'Me.cmdStockItem.SetIndex(_cmdStockItem_5, CType(5, Short))
'Me.cmdStockItem.SetIndex(_cmdStockItem_4, CType(4, Short))
'Me.cmdStockItem.SetIndex(_cmdStockItem_3, CType(3, Short))
'Me.cmdStockItem.SetIndex(_cmdStockItem_2, CType(2, Short))
'Me.cmdStockItem.SetIndex(_cmdStockItem_1, CType(1, Short))
'Me.lbl.SetIndex(_lbl_11, CType(11, Short))
'Me.lbl.SetIndex(_lbl_10, CType(10, Short))
'Me.lbl.SetIndex(_lbl_9, CType(9, Short))
'Me.lbl.SetIndex(_lbl_8, CType(8, Short))
'Me.lbl.SetIndex(_lbl_7, CType(7, Short))
'Me.lbl.SetIndex(_lbl_6, CType(6, Short))
'Me.lbl.SetIndex(_lbl_5, CType(5, Short))
'Me.lbl.SetIndex(_lbl_4, CType(4, Short))
'Me.lbl.SetIndex(_lbl_3, CType(3, Short))
'Me.lbl.SetIndex(_lbl_2, CType(2, Short))
'Me.lbl.SetIndex(_lbl_0, CType(0, Short))
'Me.lblItem.SetIndex(_lblItem_10, CType(10, Short))
'Me.lblItem.SetIndex(_lblItem_9, CType(9, Short))
'Me.lblItem.SetIndex(_lblItem_8, CType(8, Short))
'Me.lblItem.SetIndex(_lblItem_7, CType(7, Short))
'Me.lblItem.SetIndex(_lblItem_6, CType(6, Short))
'Me.lblItem.SetIndex(_lblItem_5, CType(5, Short))
'Me.lblItem.SetIndex(_lblItem_4, CType(4, Short))
'Me.lblItem.SetIndex(_lblItem_3, CType(3, Short))
'Me.lblItem.SetIndex(_lblItem_2, CType(2, Short))
'Me.lblItem.SetIndex(_lblItem_1, CType(1, Short))
'Me.optDataType.SetIndex(_optDataType_1, CType(1, Short))
'Me.optDataType.SetIndex(_optDataType_0, CType(0, Short))
Me.Shape1.SetIndex(_Shape1_1, CType(1, Short))
CType(Me.Shape1, System.ComponentModel.ISupportInitialize).EndInit()
'CType(Me.optDataType, System.ComponentModel.ISupportInitialize).EndInit()
'CType(Me.lblItem, System.ComponentModel.ISupportInitialize).EndInit()
'CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
'CType(Me.cmdStockItem, System.ComponentModel.ISupportInitialize).EndInit()
'CType(Me.cmdClear, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
#End Region
End Class |
' Copyright (c) Microsoft Corporation. All rights reserved.
Imports System.ServiceModel
Imports System.ServiceModel.Channels
Namespace Microsoft.ServiceModel.Samples
Public Class TransactionFlowProperty
Public Const PropertyName = "TransactionFlowProperty"
Private propToken() As Byte
Private Sub New()
End Sub
Public Shared Function [Get](ByVal message As Message) As Byte()
If message Is Nothing Then
Return Nothing
End If
If message.Properties.ContainsKey(PropertyName) Then
Dim tfp As TransactionFlowProperty = CType(message.Properties(PropertyName), TransactionFlowProperty)
Return tfp.propToken
End If
Return Nothing
End Function
Public Shared Sub [Set](ByVal propToken() As Byte, ByVal message As Message)
If message.Properties.ContainsKey(PropertyName) Then
Throw New CommunicationException("A transaction flow property is already set on the message.")
End If
Dim [property] As New TransactionFlowProperty()
[property].propToken = propToken
message.Properties.Add(PropertyName, [property])
End Sub
End Class
End Namespace
|
Imports System
Namespace Waf.DotNetPad.Samples
Module AutoPropertyInitializers
Sub Main()
Dim customer = New Customer(3)
Console.WriteLine("Customer {0}: {1}, {2}", customer.Id, customer.First, customer.Last)
End Sub
End Module
Class Customer
Sub New(id As Integer)
Me.Id = id
End Sub
Public ReadOnly Property Id As Integer
Public Property First As String = "Luke"
Public Property Last As String = "Skywalker"
End Class
End Namespace |
Imports ProdCon
Public Class MathWorkItem
Inherits WorkItem(Of IEnumerable(Of Integer), MathResult)
Public Sub New(ByVal Data As IEnumerable(Of Integer))
MyBase.New(Data)
_work = getWork()
End Sub
Private Function getWork() As Func(Of IEnumerable(Of Integer), MathResult)
Static rand As New Random
Dim index As Integer = rand.Next(0, 2)
Dim res As Func(Of IEnumerable(Of Integer), MathResult) = Nothing
Select Case index
Case 0
res = Function(d)
Dim sw As New Stopwatch
sw.Start()
Dim value As Decimal = d.Select(Function(n) CDec(n)).Sum
Threading.Thread.Sleep(rand.Next(500, 1301)) 'artificially make work take time
sw.Stop()
Return New MathResult(value, Data, sw.Elapsed, Threading.Thread.CurrentThread.ManagedThreadId)
End Function
Case 1
res = Function(d)
Dim sw As New Stopwatch
sw.Start()
Dim value As Decimal = d.Aggregate(1D, Function(c, n) c * n)
Threading.Thread.Sleep(rand.Next(500, 1301)) 'artificially make work take time
sw.Stop()
Return New MathResult(value, Data, sw.Elapsed, Threading.Thread.CurrentThread.ManagedThreadId)
End Function
End Select
Return res
End Function
Private _work As Func(Of IEnumerable(Of Integer), MathResult)
Public Overrides Property Work As Func(Of IEnumerable(Of Integer), MathResult)
Get
Return _work
End Get
Set(value As Func(Of IEnumerable(Of Integer), MathResult))
_work = value
End Set
End Property
End Class
|
' 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
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Imports System.Xml.Linq
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Retargeting
Public Class NoPia
Inherits BasicTestBase
''' <summary>
''' Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\Pia1.vb
''' </summary>
Private Shared ReadOnly s_sourcePia1 As XElement = <compilation name="Pia1"><file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<Assembly: ImportedFromTypeLib("Pia1.dll")>
<ComImport, Guid("27e3e649-994b-4f58-b3c6-f8089a5f2c01"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface I1
Sub Sub1(ByVal x As Integer)
End Interface
Public Structure S1
Public F1 As Integer
End Structure
Namespace NS1
<ComImport, Guid("27e3e649-994b-4f58-b3c6-f8089a5f2c02"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface I2
Sub Sub1(ByVal x As Integer)
End Interface
Public Structure S2
Public F1 As Integer
End Structure
End Namespace
]]></file></compilation>
''' <summary>
''' Disassembly of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes1.dll
''' </summary>
Private Shared ReadOnly s_sourceLocalTypes1_IL As XElement = <compilation name="LocalTypes1"><file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<ComImport, CompilerGenerated, Guid("27e3e649-994b-4f58-b3c6-f8089a5f2c01"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), TypeIdentifier>
Public Interface I1
End Interface
Namespace NS1
<ComImport, CompilerGenerated, Guid("27e3e649-994b-4f58-b3c6-f8089a5f2c02"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), TypeIdentifier>
Public Interface I2
End Interface
End Namespace
Public Class LocalTypes1
Public Sub Test1(x As I1, y As NS1.I2)
End Sub
End Class
]]></file></compilation>
''' <summary>
''' Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes1.vb
''' </summary>
Private Shared ReadOnly s_sourceLocalTypes1 As XElement = <compilation name="LocalTypes1"><file name="a.vb"><![CDATA[
Public Class LocalTypes1
Public Sub Test1(x As I1, y As NS1.I2)
End Sub
End Class
]]></file></compilation>
''' <summary>
''' Disassembly of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes2.dll
''' </summary>
Private Shared ReadOnly s_sourceLocalTypes2_IL As XElement = <compilation name="LocalTypes2"><file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<CompilerGenerated(), TypeIdentifier("f9c2d51d-4f44-45f0-9eda-c9d599b58257", "S1")>
Public Structure S1
Public F1 As Integer
End Structure
Namespace NS1
<CompilerGenerated(), TypeIdentifier("f9c2d51d-4f44-45f0-9eda-c9d599b58257", "NS1.S2")>
Public Structure S2
Public F1 As Integer
End Structure
End Namespace
Public Class LocalTypes2
Public Sub Test2(x As S1, y As NS1.S2)
End Sub
End Class
]]></file></compilation>
''' <summary>
''' Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes2.vb
''' </summary>
Private Shared ReadOnly s_sourceLocalTypes2 As XElement = <compilation name="LocalTypes2"><file name="a.vb"><![CDATA[
Public Class LocalTypes2
Public Sub Test2(ByVal x As S1, ByVal y As NS1.S2)
End Sub
End Class
]]></file></compilation>
''' <summary>
''' Disassembly of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes3.dll
''' </summary>
Private Shared ReadOnly s_sourceLocalTypes3_IL As XElement = <compilation name="LocalTypes3"><file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C31(Of T)
Public Interface I31(Of S)
End Interface
End Class
Public Class C32(Of T)
End Class
Public Class C33
End Class
<ComImport, CompilerGenerated, Guid("27e3e649-994b-4f58-b3c6-f8089a5f2c01"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), TypeIdentifier>
Public Interface I1
End Interface
Public Interface I32(Of S)
End Interface
Public Class LocalTypes3
Public Function Test1() As C31(Of C33).I31(Of C33)
Return Nothing
End Function
Public Function Test2() As C31(Of C33).I31(Of I1)
Return Nothing
End Function
Public Function Test3() As C31(Of I1).I31(Of C33)
Return Nothing
End Function
Public Function Test4() As C31(Of C33).I31(Of I32(Of I1))
Return Nothing
End Function
Public Function Test5() As C31(Of I32(Of I1)).I31(Of C33)
Return Nothing
End Function
Public Function Test6() As List(Of I1)
Return Nothing
End Function
End Class
]]></file></compilation>
''' <summary>
''' Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes3.vb
''' </summary>
Private Shared ReadOnly s_sourceLocalTypes3 As XElement = <compilation name="LocalTypes3"><file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Public Class LocalTypes3
Public Function Test1() As C31(Of C33).I31(Of C33)
Return Nothing
End Function
Public Function Test2() As C31(Of C33).I31(Of I1)
Return Nothing
End Function
Public Function Test3() As C31(Of I1).I31(Of C33)
Return Nothing
End Function
Public Function Test4() As C31(Of C33).I31(Of I32(Of I1))
Return Nothing
End Function
Public Function Test5() As C31(Of I32(Of I1)).I31(Of C33)
Return Nothing
End Function
Public Function Test6() As List(Of I1)
Return Nothing
End Function
End Class
Public Class C31(Of T)
Public Interface I31(Of S)
End Interface
End Class
Public Class C32(Of T)
End Class
Public Interface I32(Of S)
End Interface
Public Class C33
End Class
]]></file></compilation>
<Fact()>
Public Sub HideLocalTypeDefinitions()
Dim compilation1 = CreateCompilationWithMscorlib(s_sourceLocalTypes1_IL)
CompileAndVerify(compilation1)
Dim compilation2 = CreateCompilationWithMscorlib(s_sourceLocalTypes2_IL)
CompileAndVerify(compilation2)
Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences(New Object() {
compilation1,
compilation2,
MscorlibRef
})
Dim localTypes1 = assemblies(0).Modules(0)
Dim localTypes2 = assemblies(1).Modules(0)
Assert.Same(assemblies(2), compilation1.Assembly.CorLibrary)
Assert.Same(assemblies(2), compilation2.Assembly.CorLibrary)
Assert.Equal(2, localTypes1.GlobalNamespace.GetMembers().Length)
Assert.Equal(2, localTypes1.GlobalNamespace.GetMembersUnordered().Length)
Assert.Equal(0, localTypes1.GlobalNamespace.GetMembers("I1").Length)
Assert.Equal(0, localTypes1.GlobalNamespace.GetMembers("S1").Length)
Assert.Equal(1, localTypes1.GlobalNamespace.GetTypeMembers().Length)
Assert.Equal(0, localTypes1.GlobalNamespace.GetTypeMembers("I1").Length)
Assert.Equal(0, localTypes1.GlobalNamespace.GetTypeMembers("S1").Length)
Assert.Equal(0, localTypes1.GlobalNamespace.GetTypeMembers("I1", 0).Length)
Assert.Equal(0, localTypes1.GlobalNamespace.GetTypeMembers("S1", 0).Length)
Assert.Equal(0, localTypes1.GlobalNamespace.GetMember(Of NamespaceSymbol)("NS1").GetTypeMembers().Length())
Assert.Equal(2, localTypes2.GlobalNamespace.GetMembers().Length)
Assert.Equal(2, localTypes2.GlobalNamespace.GetMembersUnordered().Length)
Assert.Equal(0, localTypes2.GlobalNamespace.GetMembers("I1").Length)
Assert.Equal(0, localTypes2.GlobalNamespace.GetMembers("S1").Length)
Assert.Equal(1, localTypes2.GlobalNamespace.GetTypeMembers().Length)
Assert.Equal(0, localTypes2.GlobalNamespace.GetTypeMembers("I1").Length)
Assert.Equal(0, localTypes2.GlobalNamespace.GetTypeMembers("S1").Length)
Assert.Equal(0, localTypes2.GlobalNamespace.GetTypeMembers("I1", 0).Length)
Assert.Equal(0, localTypes2.GlobalNamespace.GetTypeMembers("S1", 0).Length)
Assert.Equal(0, localTypes2.GlobalNamespace.GetMember(Of NamespaceSymbol)("NS1").GetTypeMembers().Length())
Dim fullName_I1 = MetadataTypeName.FromFullName("I1")
Dim fullName_I2 = MetadataTypeName.FromFullName("NS1.I2")
Dim fullName_S1 = MetadataTypeName.FromFullName("S1")
Dim fullName_S2 = MetadataTypeName.FromFullName("NS1.S2")
Assert.IsType(Of MissingMetadataTypeSymbol.TopLevel)(localTypes1.LookupTopLevelMetadataType(fullName_I1))
Assert.IsType(Of MissingMetadataTypeSymbol.TopLevel)(localTypes1.LookupTopLevelMetadataType(fullName_I2))
Assert.IsType(Of MissingMetadataTypeSymbol.TopLevel)(localTypes1.LookupTopLevelMetadataType(fullName_S1))
Assert.IsType(Of MissingMetadataTypeSymbol.TopLevel)(localTypes1.LookupTopLevelMetadataType(fullName_S2))
Assert.Null(assemblies(0).GetTypeByMetadataName(fullName_I1.FullName))
Assert.Null(assemblies(0).GetTypeByMetadataName(fullName_I2.FullName))
Assert.Null(assemblies(0).GetTypeByMetadataName(fullName_S1.FullName))
Assert.Null(assemblies(0).GetTypeByMetadataName(fullName_S2.FullName))
Assert.IsType(Of MissingMetadataTypeSymbol.TopLevel)(localTypes2.LookupTopLevelMetadataType(fullName_I1))
Assert.IsType(Of MissingMetadataTypeSymbol.TopLevel)(localTypes2.LookupTopLevelMetadataType(fullName_I2))
Assert.IsType(Of MissingMetadataTypeSymbol.TopLevel)(localTypes2.LookupTopLevelMetadataType(fullName_S1))
Assert.IsType(Of MissingMetadataTypeSymbol.TopLevel)(localTypes2.LookupTopLevelMetadataType(fullName_S2))
Assert.Null(assemblies(1).GetTypeByMetadataName(fullName_I1.FullName))
Assert.Null(assemblies(1).GetTypeByMetadataName(fullName_I2.FullName))
Assert.Null(assemblies(1).GetTypeByMetadataName(fullName_S1.FullName))
Assert.Null(assemblies(1).GetTypeByMetadataName(fullName_S2.FullName))
End Sub
<Fact()>
Public Sub LocalTypeSubstitution1_1()
Dim compilation1 = CreateCompilationWithMscorlib(s_sourceLocalTypes1_IL)
CompileAndVerify(compilation1)
Dim compilation2 = CreateCompilationWithMscorlib(s_sourceLocalTypes2_IL)
CompileAndVerify(compilation2)
LocalTypeSubstitution1(compilation1, compilation2)
End Sub
<Fact()>
Public Sub LocalTypeSubstitution1_2()
Dim compilation1 = CreateCompilationWithMscorlib(
s_sourceLocalTypes1,
references:={TestReferences.SymbolsTests.NoPia.Pia1.WithEmbedInteropTypes(True)})
CompileAndVerify(compilation1)
Dim compilation2 = CreateCompilationWithMscorlib(
s_sourceLocalTypes2,
references:={TestReferences.SymbolsTests.NoPia.Pia1.WithEmbedInteropTypes(True)})
CompileAndVerify(compilation2)
LocalTypeSubstitution1(compilation1, compilation2)
End Sub
<Fact()>
Public Sub LocalTypeSubstitution1_3()
Dim compilation0 = CreateCompilationWithMscorlib(s_sourcePia1)
CompileAndVerify(compilation0)
Dim compilation1 = CreateCompilationWithMscorlib(
s_sourceLocalTypes1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
CompileAndVerify(compilation1)
Dim compilation2 = CreateCompilationWithMscorlib(
s_sourceLocalTypes2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
CompileAndVerify(compilation2)
LocalTypeSubstitution1(compilation1, compilation2)
End Sub
Private Sub LocalTypeSubstitution1(compilation1 As VisualBasicCompilation, compilation2 As VisualBasicCompilation)
Dim assemblies1 = MetadataTestHelpers.GetSymbolsForReferences(New Object() {
compilation1,
compilation2,
TestReferences.SymbolsTests.NoPia.Pia1,
MscorlibRef,
TestReferences.SymbolsTests.MDTestLib1
})
Dim localTypes1_1 = assemblies1(0)
Dim localTypes2_1 = assemblies1(1)
Dim pia1_1 = assemblies1(2)
Dim varI1 = pia1_1.GlobalNamespace.GetTypeMembers("I1").Single()
Dim varS1 = pia1_1.GlobalNamespace.GetTypeMembers("S1").Single()
Dim varNS1 = pia1_1.GlobalNamespace.GetMember(Of NamespaceSymbol)("NS1")
Dim varI2 = varNS1.GetTypeMembers("I2").Single()
Dim varS2 = varNS1.GetTypeMembers("S2").Single()
Dim classLocalTypes1 As NamedTypeSymbol
Dim classLocalTypes2 As NamedTypeSymbol
classLocalTypes1 = localTypes1_1.GlobalNamespace.GetTypeMembers("LocalTypes1").Single()
classLocalTypes2 = localTypes2_1.GlobalNamespace.GetTypeMembers("LocalTypes2").Single()
Dim test1 As MethodSymbol
Dim test2 As MethodSymbol
test1 = classLocalTypes1.GetMember(Of MethodSymbol)("Test1")
test2 = classLocalTypes2.GetMember(Of MethodSymbol)("Test2")
Dim param As ImmutableArray(Of ParameterSymbol)
param = test1.Parameters
Assert.Same(varI1, param(0).[Type])
Assert.Same(varI2, param(1).[Type])
param = test2.Parameters
Assert.Same(varS1, param(0).[Type])
Assert.Same(varS2, param(1).[Type])
Dim assemblies2 = MetadataTestHelpers.GetSymbolsForReferences(New Object() {
compilation1,
compilation2,
TestReferences.SymbolsTests.NoPia.Pia1,
MscorlibRef
})
Dim localTypes1_2 = assemblies2(0)
Dim localTypes2_2 = assemblies2(1)
Assert.NotSame(localTypes1_1, localTypes1_2)
Assert.NotSame(localTypes2_1, localTypes2_2)
Assert.Same(pia1_1, assemblies2(2))
classLocalTypes1 = localTypes1_2.GlobalNamespace.GetTypeMembers("LocalTypes1").Single()
classLocalTypes2 = localTypes2_2.GlobalNamespace.GetTypeMembers("LocalTypes2").Single()
test1 = classLocalTypes1.GetMember(Of MethodSymbol)("Test1")
test2 = classLocalTypes2.GetMember(Of MethodSymbol)("Test2")
param = test1.Parameters
Assert.Same(varI1, param(0).[Type])
Assert.Same(varI2, param(1).[Type])
param = test2.Parameters
Assert.Same(varS1, param(0).[Type])
Assert.Same(varS2, param(1).[Type])
Dim assemblies3 = MetadataTestHelpers.GetSymbolsForReferences(New Object() {
compilation1,
compilation2,
TestReferences.SymbolsTests.NoPia.Pia1
})
Dim localTypes1_3 = assemblies3(0)
Dim localTypes2_3 = assemblies3(1)
Dim pia1_3 = assemblies3(2)
Assert.NotSame(localTypes1_1, localTypes1_3)
Assert.NotSame(localTypes2_1, localTypes2_3)
Assert.NotSame(localTypes1_2, localTypes1_3)
Assert.NotSame(localTypes2_2, localTypes2_3)
Assert.NotSame(pia1_1, pia1_3)
classLocalTypes1 = localTypes1_3.GlobalNamespace.GetTypeMembers("LocalTypes1").Single()
classLocalTypes2 = localTypes2_3.GlobalNamespace.GetTypeMembers("LocalTypes2").Single()
test1 = classLocalTypes1.GetMember(Of MethodSymbol)("Test1")
test2 = classLocalTypes2.GetMember(Of MethodSymbol)("Test2")
param = test1.Parameters
Assert.Same(pia1_3.GlobalNamespace.GetTypeMembers("I1").Single(), param(0).[Type])
Assert.Same(pia1_3.GlobalNamespace.GetMember(Of NamespaceSymbol)("NS1").GetTypeMembers("I2").[Single](), param(1).[Type])
param = test2.Parameters
Dim missing As NoPiaMissingCanonicalTypeSymbol
Assert.Equal(SymbolKind.ErrorType, param(0).[Type].Kind)
missing = DirectCast(param(0).[Type], NoPiaMissingCanonicalTypeSymbol)
Assert.Same(localTypes2_3, missing.EmbeddingAssembly)
Assert.Null(missing.Guid)
Assert.Equal(varS1.ToTestDisplayString(), missing.FullTypeName)
Assert.Equal("f9c2d51d-4f44-45f0-9eda-c9d599b58257", missing.Scope)
Assert.Equal(varS1.ToTestDisplayString(), missing.Identifier)
Assert.Equal(SymbolKind.ErrorType, param(1).[Type].Kind)
Assert.IsType(Of NoPiaMissingCanonicalTypeSymbol)(param(1).[Type])
Dim assemblies4 = MetadataTestHelpers.GetSymbolsForReferences(New Object() {
compilation1,
compilation2,
TestReferences.SymbolsTests.NoPia.Pia1,
MscorlibRef,
TestReferences.SymbolsTests.MDTestLib1
})
For i As Integer = 0 To assemblies1.Length - 1 Step 1
Assert.Same(assemblies1(i), assemblies4(i))
Next
Dim assemblies5 = MetadataTestHelpers.GetSymbolsForReferences(New Object() {
compilation1,
compilation2,
TestReferences.SymbolsTests.NoPia.Pia2,
MscorlibRef
})
Dim localTypes1_5 = assemblies5(0)
Dim localTypes2_5 = assemblies5(1)
classLocalTypes1 = localTypes1_5.GlobalNamespace.GetTypeMembers("LocalTypes1").Single()
classLocalTypes2 = localTypes2_5.GlobalNamespace.GetTypeMembers("LocalTypes2").Single()
test1 = classLocalTypes1.GetMember(Of MethodSymbol)("Test1")
test2 = classLocalTypes2.GetMember(Of MethodSymbol)("Test2")
param = test1.Parameters
Assert.Equal(SymbolKind.ErrorType, param(0).[Type].Kind)
missing = DirectCast(param(0).[Type], NoPiaMissingCanonicalTypeSymbol)
Assert.Same(localTypes1_5, missing.EmbeddingAssembly)
Assert.Equal("27e3e649-994b-4f58-b3c6-f8089a5f2c01", missing.Guid)
Assert.Equal(varI1.ToTestDisplayString(), missing.FullTypeName)
Assert.Null(missing.Scope)
Assert.Null(missing.Identifier)
Assert.Equal(SymbolKind.ErrorType, param(1).[Type].Kind)
Assert.IsType(Of NoPiaMissingCanonicalTypeSymbol)(param(1).[Type])
param = test2.Parameters
Assert.Equal(SymbolKind.ErrorType, param(0).[Type].Kind)
Assert.IsType(Of NoPiaMissingCanonicalTypeSymbol)(param(0).[Type])
Assert.Equal(SymbolKind.ErrorType, param(1).[Type].Kind)
Assert.IsType(Of NoPiaMissingCanonicalTypeSymbol)(param(1).[Type])
Dim assemblies6 = MetadataTestHelpers.GetSymbolsForReferences(New Object() {
compilation1,
compilation2,
TestReferences.SymbolsTests.NoPia.Pia3,
MscorlibRef
})
Dim localTypes1_6 = assemblies6(0)
Dim localTypes2_6 = assemblies6(1)
classLocalTypes1 = localTypes1_6.GlobalNamespace.GetTypeMembers("LocalTypes1").Single()
classLocalTypes2 = localTypes2_6.GlobalNamespace.GetTypeMembers("LocalTypes2").Single()
test1 = classLocalTypes1.GetMember(Of MethodSymbol)("Test1")
test2 = classLocalTypes2.GetMember(Of MethodSymbol)("Test2")
param = test1.Parameters
Assert.Equal(SymbolKind.ErrorType, param(0).[Type].Kind)
Assert.IsType(Of NoPiaMissingCanonicalTypeSymbol)(param(0).[Type])
Assert.Equal(SymbolKind.ErrorType, param(1).[Type].Kind)
Assert.IsType(Of NoPiaMissingCanonicalTypeSymbol)(param(1).[Type])
param = test2.Parameters
Assert.Equal(SymbolKind.ErrorType, param(0).[Type].Kind)
Assert.IsType(Of NoPiaMissingCanonicalTypeSymbol)(param(0).[Type])
Assert.Equal(SymbolKind.ErrorType, param(1).[Type].Kind)
Assert.IsType(Of NoPiaMissingCanonicalTypeSymbol)(param(1).[Type])
Dim assemblies7 = MetadataTestHelpers.GetSymbolsForReferences(New Object() {
compilation1,
compilation2,
TestReferences.SymbolsTests.NoPia.Pia4,
MscorlibRef
})
Dim localTypes1_7 = assemblies7(0)
Dim localTypes2_7 = assemblies7(1)
classLocalTypes1 = localTypes1_7.GlobalNamespace.GetTypeMembers("LocalTypes1").Single()
classLocalTypes2 = localTypes2_7.GlobalNamespace.GetTypeMembers("LocalTypes2").Single()
test1 = classLocalTypes1.GetMember(Of MethodSymbol)("Test1")
test2 = classLocalTypes2.GetMember(Of MethodSymbol)("Test2")
param = test1.Parameters
Assert.Equal(TypeKind.[Interface], param(0).[Type].TypeKind)
Assert.Equal(TypeKind.[Interface], param(1).[Type].TypeKind)
Assert.NotEqual(SymbolKind.ErrorType, param(0).[Type].Kind)
Assert.NotEqual(SymbolKind.ErrorType, param(1).[Type].Kind)
param = test2.Parameters
Assert.Equal(SymbolKind.ErrorType, param(0).[Type].Kind)
Assert.IsType(Of NoPiaMissingCanonicalTypeSymbol)(param(0).[Type])
Assert.Equal(SymbolKind.ErrorType, param(1).[Type].Kind)
Assert.IsType(Of NoPiaMissingCanonicalTypeSymbol)(param(1).[Type])
Dim assemblies8 = MetadataTestHelpers.GetSymbolsForReferences(New Object() {
compilation1,
compilation2,
TestReferences.SymbolsTests.NoPia.Pia4,
TestReferences.SymbolsTests.NoPia.Pia1,
MscorlibRef
})
Dim localTypes1_8 = assemblies8(0)
Dim localTypes2_8 = assemblies8(1)
Dim pia4_8 = assemblies8(2)
Dim pia1_8 = assemblies8(3)
classLocalTypes1 = localTypes1_8.GlobalNamespace.GetTypeMembers("LocalTypes1").Single()
classLocalTypes2 = localTypes2_8.GlobalNamespace.GetTypeMembers("LocalTypes2").Single()
test1 = classLocalTypes1.GetMember(Of MethodSymbol)("Test1")
test2 = classLocalTypes2.GetMember(Of MethodSymbol)("Test2")
param = test1.Parameters
Dim ambiguous As NoPiaAmbiguousCanonicalTypeSymbol
Assert.Equal(SymbolKind.ErrorType, param(0).[Type].Kind)
ambiguous = DirectCast(param(0).[Type], NoPiaAmbiguousCanonicalTypeSymbol)
Assert.Same(localTypes1_8, ambiguous.EmbeddingAssembly)
Assert.Same(pia4_8.GlobalNamespace.GetTypeMembers("I1").Single(), ambiguous.FirstCandidate)
Assert.Same(pia1_8.GlobalNamespace.GetTypeMembers("I1").Single(), ambiguous.SecondCandidate)
Assert.Equal(SymbolKind.ErrorType, param(1).[Type].Kind)
Assert.IsType(Of NoPiaAmbiguousCanonicalTypeSymbol)(param(1).[Type])
Dim assemblies9 = MetadataTestHelpers.GetSymbolsForReferences(New Object() {
compilation1,
compilation2,
TestReferences.SymbolsTests.NoPia.Pia4,
MscorlibRef
})
Dim localTypes1_9 = assemblies9(0)
Dim localTypes2_9 = assemblies9(1)
Dim assemblies10 = MetadataTestHelpers.GetSymbolsForReferences(New Object() {
compilation1,
compilation2,
TestReferences.SymbolsTests.NoPia.Pia4,
MscorlibRef,
TestReferences.SymbolsTests.MDTestLib1
})
Dim localTypes1_10 = assemblies10(0)
Dim localTypes2_10 = assemblies10(1)
Assert.NotSame(localTypes1_9, localTypes1_10)
Assert.NotSame(localTypes2_9, localTypes2_10)
GC.KeepAlive(localTypes1_1)
GC.KeepAlive(localTypes2_1)
GC.KeepAlive(pia1_1)
GC.KeepAlive(localTypes2_9)
GC.KeepAlive(localTypes1_9)
End Sub
<Fact()>
Public Sub CyclicReference_1()
Dim piaRef = TestReferences.SymbolsTests.NoPia.Pia1
Dim compilation1 = CreateCompilationWithMscorlib(s_sourceLocalTypes1_IL)
CompileAndVerify(compilation1)
Dim localTypes1Ref = New VisualBasicCompilationReference(compilation1)
CyclicReference(piaRef, localTypes1Ref)
End Sub
<Fact()>
Public Sub CyclicReference_2()
Dim piaRef = TestReferences.SymbolsTests.NoPia.Pia1
Dim compilation1 = CreateCompilationWithMscorlib(
s_sourceLocalTypes1,
references:={TestReferences.SymbolsTests.NoPia.Pia1.WithEmbedInteropTypes(True)})
CompileAndVerify(compilation1)
Dim localTypes1Ref = New VisualBasicCompilationReference(compilation1)
CyclicReference(piaRef, localTypes1Ref)
End Sub
<Fact()>
Public Sub CyclicReference_3()
Dim pia1 = CreateCompilationWithMscorlib(s_sourcePia1)
CompileAndVerify(pia1)
Dim piaRef = New VisualBasicCompilationReference(pia1)
Dim compilation1 = CreateCompilationWithMscorlib(
s_sourceLocalTypes1,
references:={New VisualBasicCompilationReference(pia1, embedInteropTypes:=True)})
CompileAndVerify(compilation1)
Dim localTypes1Ref = New VisualBasicCompilationReference(compilation1)
CyclicReference(piaRef, localTypes1Ref)
End Sub
Private Sub CyclicReference(piaRef As MetadataReference, localTypes1Ref As CompilationReference)
Dim mscorlibRef = TestReferences.SymbolsTests.MDTestLib1
Dim cyclic2Ref = TestReferences.SymbolsTests.Cyclic.Cyclic2.dll
Dim tc1 = VisualBasicCompilation.Create("Cyclic1", references:={mscorlibRef, cyclic2Ref, piaRef, localTypes1Ref})
Assert.NotNull(tc1.Assembly)
Dim tc2 = VisualBasicCompilation.Create("Cyclic1", references:={mscorlibRef, cyclic2Ref, piaRef, localTypes1Ref})
Assert.NotNull(tc2.Assembly)
Assert.NotSame(tc1.GetReferencedAssemblySymbol(localTypes1Ref), tc2.GetReferencedAssemblySymbol(localTypes1Ref))
GC.KeepAlive(tc1)
GC.KeepAlive(tc2)
End Sub
<Fact()>
Public Sub GenericsClosedOverLocalTypes1_1()
Dim compilation3 = CreateCompilationWithMscorlib(s_sourceLocalTypes3_IL)
CompileAndVerify(compilation3)
GenericsClosedOverLocalTypes1(compilation3)
End Sub
<ClrOnlyFact>
Public Sub ValueTupleWithMissingCanonicalType()
Dim source = "
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Sub New(item1 As T1, item2 As T2)
End Sub
End Structure
End Namespace
<CompilerGenerated>
<TypeIdentifier(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""S1"")>
Public Structure S1
End Structure
Public Class C
Public Function Test1() As ValueTuple(Of S1, S1)
Throw New Exception()
End Function
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.ReleaseDll, assemblyName:="comp")
comp.VerifyDiagnostics()
CompileAndVerify(comp)
Dim assemblies1 = MetadataTestHelpers.GetSymbolsForReferences({comp})
Assert.Equal(SymbolKind.ErrorType, assemblies1(0).GlobalNamespace.GetMember(Of MethodSymbol)("C.Test1").ReturnType.Kind)
Dim assemblies2 = MetadataTestHelpers.GetSymbolsForReferences({comp.ToMetadataReference()})
Assert.Equal(SymbolKind.ErrorType, assemblies2(0).GlobalNamespace.GetMember(Of MethodSymbol)("C.Test1").ReturnType.Kind)
End Sub
<ClrOnlyFact>
Public Sub EmbeddedValueTuple()
Dim source = "
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Namespace System
<CompilerGenerated>
<TypeIdentifier(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""ValueTuple"")>
Public Structure ValueTuple(Of T1, T2)
Public Sub New(item1 As T1, item2 As T2)
End Sub
End Structure
End Namespace
Public Class C
Public Function Test1() As ValueTuple(Of Integer, Integer)
Throw New Exception()
End Function
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.ReleaseDll, assemblyName:="comp")
comp.VerifyDiagnostics()
Dim assemblies1 = MetadataTestHelpers.GetSymbolsForReferences({comp})
Assert.Equal(SymbolKind.ErrorType, assemblies1(0).GlobalNamespace.GetMember(Of MethodSymbol)("C.Test1").ReturnType.Kind)
Dim assemblies2 = MetadataTestHelpers.GetSymbolsForReferences({comp.ToMetadataReference()})
Assert.Equal(SymbolKind.ErrorType, assemblies2(0).GlobalNamespace.GetMember(Of MethodSymbol)("C.Test1").ReturnType.Kind)
End Sub
<ClrOnlyFact>
Public Sub CannotEmbedValueTuple()
Dim piaSource = "
Imports System.Runtime.InteropServices
<assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")>
<assembly: ImportedFromTypeLib(""Pia1.dll"")>
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Sub New(item1 As T1, item2 As T2)
End Sub
End Structure
End Namespace
"
Dim pia = CreateCompilationWithMscorlib({piaSource}, options:=TestOptions.ReleaseDll, assemblyName:="comp")
pia.VerifyDiagnostics()
Dim source = "
Imports System.Runtime.InteropServices
Public Class C
Public Function TestValueTuple() As System.ValueTuple(Of String, String)
Throw New System.Exception()
End Function
Public Function TestTuple() As (Integer, Integer)
Throw New System.Exception()
End Function
Public Function TestTupleLiteral() As Object
Return (1, 2)
End Function
'Public Sub TestDeconstruction()
' Dim x, y As Integer
' (x, y) = New C()
'End Sub
public Sub Deconstruct(<Out> a As Integer, <Out> b As Integer)
a = 1
b = 1
End Sub
End Class
"
Dim expected = <errors>
BC36923: Type 'ValueTuple(Of T1, T2)' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.
Public Function TestValueTuple() As System.ValueTuple(Of String, String)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36923: Type 'ValueTuple(Of T1, T2)' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.
Public Function TestTuple() As (Integer, Integer)
~~~~~~~~~~~~~~~~~~
BC36923: Type 'ValueTuple(Of T1, T2)' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.
Public Function TestTuple() As (Integer, Integer)
~~~~~~~~~~~~~~~~~~
BC36923: Type 'ValueTuple(Of T1, T2)' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.
Return (1, 2)
~~~~~~
</errors>
Dim comp1 = CreateCompilationWithMscorlib({source}, options:=TestOptions.ReleaseDll,
references:={pia.ToMetadataReference(embedInteropTypes:=True)})
comp1.AssertTheseDiagnostics(expected)
Dim comp2 = CreateCompilationWithMscorlib({source}, options:=TestOptions.ReleaseDll,
references:={pia.EmitToImageReference(embedInteropTypes:=True)})
comp2.AssertTheseDiagnostics(expected)
End Sub
<ClrOnlyFact(Skip:="https://github.com/dotnet/roslyn/issues/13200")>
Public Sub CannotEmbedValueTupleImplicitlyReferenced()
Dim piaSource = "
Imports System.Runtime.InteropServices
<assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")>
<assembly: ImportedFromTypeLib(""Pia1.dll"")>
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Sub New(item1 As T1, item2 As T2)
End Sub
End Structure
End Namespace
Public Structure S(Of T)
End Structure
<ComImport>
<Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")>
Public Interface ITest1
Function M() As (Integer, Integer)
Function M2() As S(Of Integer)
End Interface
"
Dim pia = CreateCompilationWithMscorlib({piaSource}, options:=TestOptions.ReleaseDll, assemblyName:="comp")
pia.VerifyDiagnostics()
Dim source = "
Public Interface ITest2
Inherits ITest1
End Interface
"
' We should expect errors as generic types cannot be embedded
' Issue https://github.com/dotnet/roslyn/issues/13200 tracks this
Dim expected = <errors>
</errors>
Dim comp1 = CreateCompilationWithMscorlib({source}, options:=TestOptions.ReleaseDll,
references:={pia.ToMetadataReference(embedInteropTypes:=True)})
comp1.AssertTheseDiagnostics(expected)
Dim comp2 = CreateCompilationWithMscorlib({source}, options:=TestOptions.ReleaseDll,
references:={pia.EmitToImageReference(embedInteropTypes:=True)})
comp2.AssertTheseDiagnostics(expected)
End Sub
<ClrOnlyFact(Skip:="https://github.com/dotnet/roslyn/issues/13200")>
Public Sub CannotEmbedValueTupleImplicitlyReferredFromMetadata()
Dim piaSource = "
Imports System.Runtime.InteropServices
<assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")>
<assembly: ImportedFromTypeLib(""Pia1.dll"")>
Public Structure S(Of T)
End Structure
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Sub New(item1 As T1, item2 As T2)
End Sub
End Structure
End Namespace
"
Dim libSource = "
Public Class D
Function M() As (Integer, Integer)
Throw New System.Exception()
End Function
Function M2() As S(Of Integer)
Throw New System.Exception()
End Function
End Class
"
Dim pia = CreateCompilationWithMscorlib({piaSource}, options:=TestOptions.ReleaseDll, assemblyName:="pia")
pia.VerifyDiagnostics()
Dim [lib] = CreateCompilationWithMscorlib({libSource}, options:=TestOptions.ReleaseDll, references:={pia.ToMetadataReference()})
[lib].VerifyDiagnostics()
Dim source = "
Public Class C
Public Sub TestTupleFromMetadata()
D.M()
D.M2()
End Sub
Public Sub TestTupleAssignmentFromMetadata()
Dim t = D.M()
t.ToString()
Dim t2 = D.M2()
t2.ToString()
End Sub
End Class
"
' We should expect errors as generic types cannot be embedded
' Issue https://github.com/dotnet/roslyn/issues/13200 tracks this
Dim expectedDiagnostics = <errors>
</errors>
Dim comp1 = CreateCompilationWithMscorlib({source}, options:=TestOptions.ReleaseDll,
references:={pia.ToMetadataReference(embedInteropTypes:=True)})
comp1.AssertTheseDiagnostics(expectedDiagnostics)
Dim comp2 = CreateCompilationWithMscorlib({source}, options:=TestOptions.ReleaseDll,
references:={pia.EmitToImageReference(embedInteropTypes:=True)})
comp2.AssertTheseDiagnostics(expectedDiagnostics)
End Sub
<ClrOnlyFact>
Public Sub CheckForUnembeddableTypesInTuples()
Dim piaSource = "
Imports System.Runtime.InteropServices
<assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")>
<assembly: ImportedFromTypeLib(""Pia1.dll"")>
Public Structure Generic(Of T1)
End Structure
"
Dim pia = CreateCompilationWithMscorlib({piaSource}, options:=TestOptions.ReleaseDll, assemblyName:="pia")
pia.VerifyDiagnostics()
Dim source = "
Public Class C
Function Test1() As System.ValueTuple(Of Generic(Of String), Generic(Of String))
Throw New System.Exception()
End Function
Function Test2() As (Generic(Of String), Generic(Of String))
Throw New System.Exception()
End Function
End Class
Namespace System
Public Structure ValueTuple(Of T1, T2)
Public Sub New(item1 As T1, item2 As T2)
End Sub
End Structure
End Namespace
"
Dim expectedDiagnostics = <errors>
BC36923: Type 'Generic(Of T1)' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.
Function Test1() As System.ValueTuple(Of Generic(Of String), Generic(Of String))
~~~~~~~~~~~~~~~~~~
BC36923: Type 'Generic(Of T1)' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.
Function Test1() As System.ValueTuple(Of Generic(Of String), Generic(Of String))
~~~~~~~~~~~~~~~~~~
BC36923: Type 'Generic(Of T1)' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.
Function Test2() As (Generic(Of String), Generic(Of String))
~~~~~~~~~~~~~~~~~~
BC36923: Type 'Generic(Of T1)' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.
Function Test2() As (Generic(Of String), Generic(Of String))
~~~~~~~~~~~~~~~~~~
</errors>
Dim comp1 = CreateCompilationWithMscorlib({source}, options:=TestOptions.ReleaseDll,
references:={pia.ToMetadataReference(embedInteropTypes:=True)})
comp1.AssertTheseDiagnostics(expectedDiagnostics)
Dim comp2 = CreateCompilationWithMscorlib({source}, options:=TestOptions.ReleaseDll,
references:={pia.EmitToImageReference(embedInteropTypes:=True)})
comp2.AssertTheseDiagnostics(expectedDiagnostics)
End Sub
<Fact()>
Public Sub GenericsClosedOverLocalTypes1_2()
Dim compilation3 = CreateCompilationWithMscorlib(
s_sourceLocalTypes3,
references:={TestReferences.SymbolsTests.NoPia.Pia1.WithEmbedInteropTypes(True)})
CompileAndVerify(compilation3)
GenericsClosedOverLocalTypes1(compilation3)
End Sub
<Fact()>
Public Sub GenericsClosedOverLocalTypes1_3()
Dim pia1 = CreateCompilationWithMscorlib(s_sourcePia1)
CompileAndVerify(pia1)
Dim compilation3 = CreateCompilationWithMscorlib(
s_sourceLocalTypes3,
references:={New VisualBasicCompilationReference(pia1, embedInteropTypes:=True)})
CompileAndVerify(compilation3)
GenericsClosedOverLocalTypes1(compilation3)
End Sub
Private Sub GenericsClosedOverLocalTypes1(compilation3 As VisualBasicCompilation)
Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({
compilation3,
TestReferences.SymbolsTests.NoPia.Pia1
})
Dim asmLocalTypes3 = assemblies(0)
Dim localTypes3 = asmLocalTypes3.GlobalNamespace.GetTypeMembers("LocalTypes3").Single()
Assert.NotEqual(SymbolKind.ErrorType, localTypes3.GetMember(Of MethodSymbol)("Test1").ReturnType.Kind)
Assert.NotEqual(SymbolKind.ErrorType, localTypes3.GetMember(Of MethodSymbol)("Test2").ReturnType.Kind)
Assert.Equal(SymbolKind.ErrorType, localTypes3.GetMember(Of MethodSymbol)("Test3").ReturnType.Kind)
Dim illegal As NoPiaIllegalGenericInstantiationSymbol = DirectCast(localTypes3.GetMember(Of MethodSymbol)("Test3").ReturnType, NoPiaIllegalGenericInstantiationSymbol)
Assert.Equal("C31(Of I1).I31(Of C33)", illegal.UnderlyingSymbol.ToTestDisplayString())
Assert.NotEqual(SymbolKind.ErrorType, localTypes3.GetMember(Of MethodSymbol)("Test4").ReturnType.Kind)
Assert.IsType(Of NoPiaIllegalGenericInstantiationSymbol)(localTypes3.GetMember(Of MethodSymbol)("Test5").ReturnType)
assemblies = MetadataTestHelpers.GetSymbolsForReferences({
compilation3,
TestReferences.SymbolsTests.NoPia.Pia1,
MscorlibRef
})
localTypes3 = assemblies(0).GlobalNamespace.GetTypeMembers("LocalTypes3").Single()
Assert.NotEqual(SymbolKind.ErrorType, localTypes3.GetMember(Of MethodSymbol)("Test1").ReturnType.Kind)
Assert.NotEqual(SymbolKind.ErrorType, localTypes3.GetMember(Of MethodSymbol)("Test2").ReturnType.Kind)
Assert.IsType(Of NoPiaIllegalGenericInstantiationSymbol)(localTypes3.GetMember(Of MethodSymbol)("Test3").ReturnType)
Assert.NotEqual(SymbolKind.ErrorType, localTypes3.GetMember(Of MethodSymbol)("Test4").ReturnType.Kind)
Assert.IsType(Of NoPiaIllegalGenericInstantiationSymbol)(localTypes3.GetMember(Of MethodSymbol)("Test5").ReturnType)
Assert.IsType(Of NoPiaIllegalGenericInstantiationSymbol)(localTypes3.GetMember(Of MethodSymbol)("Test6").ReturnType)
End Sub
<Fact()>
Public Sub NestedType1()
Dim piaSource = <compilation name="Pia"><file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<Assembly: ImportedFromTypeLib("Pia1.dll")>
Public Structure S1
Public F1 As Integer
Public Structure S2
Public F1 As Integer
End Structure
End Structure
]]></file></compilation>
Dim pia = CreateCompilationWithMscorlib(piaSource)
CompileAndVerify(pia)
Dim piaImage = MetadataReference.CreateFromImage(pia.EmitToArray())
Dim source = <compilation name="LocalTypes2"><file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class LocalTypes2
Public Sub Test2(x As S1, y As S1.S2)
End Sub
End Class
<CompilerGenerated(), TypeIdentifier("f9c2d51d-4f44-45f0-9eda-c9d599b58257", "S1")>
Public Structure S1
Public F1 As Integer
<CompilerGenerated(), TypeIdentifier("f9c2d51d-4f44-45f0-9eda-c9d599b58257", "S1.S2")>
Public Structure S2
Public F1 As Integer
End Structure
End Structure
<ComEventInterface(GetType(S1), GetType(S1.S2))>
Interface AttrTest1
End Interface
]]></file></compilation>
Dim localTypes2 = CreateCompilationWithMscorlib(source)
CompileAndVerify(localTypes2)
Dim localTypes2Image = MetadataReference.CreateFromImage(localTypes2.EmitToArray())
Dim compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {New VisualBasicCompilationReference(localTypes2), New VisualBasicCompilationReference(pia)})
Dim lt = compilation.GetTypeByMetadataName("LocalTypes2")
Dim test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("Pia", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(test2.Parameters(1).Type)
Dim attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
Dim args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("Pia", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(args(1).Value)
compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {localTypes2Image, New VisualBasicCompilationReference(pia)})
lt = compilation.GetTypeByMetadataName("LocalTypes2")
test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("Pia", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(test2.Parameters(1).Type)
attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("Pia", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(args(1).Value)
compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {New VisualBasicCompilationReference(localTypes2), piaImage})
lt = compilation.GetTypeByMetadataName("LocalTypes2")
test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("Pia", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(test2.Parameters(1).Type)
attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("Pia", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(args(1).Value)
compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {localTypes2Image, piaImage})
lt = compilation.GetTypeByMetadataName("LocalTypes2")
test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("Pia", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(test2.Parameters(1).Type)
attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("Pia", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(args(1).Value)
End Sub
<Fact()>
Public Sub NestedType2()
Dim piaSource = <compilation name="Pia"><file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<Assembly: ImportedFromTypeLib("Pia1.dll")>
Public Structure S1
Public F1 As Integer
Public Structure S2
Public F1 As Integer
End Structure
End Structure
]]></file></compilation>
Dim pia = CreateCompilationWithMscorlib(piaSource)
CompileAndVerify(pia)
Dim piaImage = MetadataReference.CreateFromImage(pia.EmitToArray())
Dim source = <compilation name="LocalTypes2"><file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class LocalTypes2
Public Sub Test2(x As S1, y As S1.S2)
End Sub
End Class
<CompilerGenerated(), TypeIdentifier("f9c2d51d-4f44-45f0-9eda-c9d599b58257", "S1")>
Public Structure S1
Public F1 As Integer
Public Structure S2
Public F1 As Integer
End Structure
End Structure
<ComEventInterface(GetType(S1), GetType(S1.S2))>
Interface AttrTest1
End Interface
]]></file></compilation>
Dim localTypes2 = CreateCompilationWithMscorlib(source)
CompileAndVerify(localTypes2)
Dim localTypes2Image = MetadataReference.CreateFromImage(localTypes2.EmitToArray())
Dim compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {New VisualBasicCompilationReference(localTypes2), New VisualBasicCompilationReference(pia)})
Dim lt = compilation.GetTypeByMetadataName("LocalTypes2")
Dim test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("Pia", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(test2.Parameters(1).Type)
Dim attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
Dim args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("Pia", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(args(1).Value)
compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {localTypes2Image, New VisualBasicCompilationReference(pia)})
lt = compilation.GetTypeByMetadataName("LocalTypes2")
test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("Pia", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(test2.Parameters(1).Type)
attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("Pia", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(args(1).Value)
compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {New VisualBasicCompilationReference(localTypes2), piaImage})
lt = compilation.GetTypeByMetadataName("LocalTypes2")
test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("Pia", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(test2.Parameters(1).Type)
attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("Pia", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(args(1).Value)
compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {localTypes2Image, piaImage})
lt = compilation.GetTypeByMetadataName("LocalTypes2")
test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("Pia", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(test2.Parameters(1).Type)
attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("Pia", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(args(1).Value)
End Sub
<Fact()>
Public Sub NestedType3()
Dim piaSource = <compilation name="Pia"><file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<Assembly: ImportedFromTypeLib("Pia1.dll")>
Public Structure S1
Public F1 As Integer
Public Structure S2
Public F1 As Integer
End Structure
End Structure
]]></file></compilation>
Dim pia = CreateCompilationWithMscorlib(piaSource)
CompileAndVerify(pia)
Dim piaImage = MetadataReference.CreateFromImage(pia.EmitToArray())
Dim source = <compilation name="LocalTypes2"><file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class LocalTypes2
Public Sub Test2(x As S1, y As S1.S2)
End Sub
End Class
Public Structure S1
Public F1 As Integer
<CompilerGenerated(), TypeIdentifier("f9c2d51d-4f44-45f0-9eda-c9d599b58257", "S1.S2")>
Public Structure S2
Public F1 As Integer
End Structure
End Structure
<ComEventInterface(GetType(S1), GetType(S1.S2))>
Interface AttrTest1
End Interface
]]></file></compilation>
Dim localTypes2 = CreateCompilationWithMscorlib(source)
'CompileAndVerify(localTypes2)
Dim localTypes2Image = MetadataReference.CreateFromImage(localTypes2.EmitToArray())
Dim compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {New VisualBasicCompilationReference(localTypes2), New VisualBasicCompilationReference(pia)})
Dim lt = compilation.GetTypeByMetadataName("LocalTypes2")
Dim test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("LocalTypes2", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.Equal("LocalTypes2", test2.Parameters(1).Type.ContainingAssembly.Name)
Dim attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
Dim args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("LocalTypes2", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.Equal("LocalTypes2", DirectCast(args(1).Value, TypeSymbol).ContainingAssembly.Name)
compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {localTypes2Image, New VisualBasicCompilationReference(pia)})
lt = compilation.GetTypeByMetadataName("LocalTypes2")
test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("LocalTypes2", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.Equal("LocalTypes2", test2.Parameters(1).Type.ContainingAssembly.Name)
attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("LocalTypes2", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.Equal("LocalTypes2", DirectCast(args(1).Value, TypeSymbol).ContainingAssembly.Name)
compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {New VisualBasicCompilationReference(localTypes2), piaImage})
lt = compilation.GetTypeByMetadataName("LocalTypes2")
test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("LocalTypes2", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.Equal("LocalTypes2", test2.Parameters(1).Type.ContainingAssembly.Name)
attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("LocalTypes2", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.Equal("LocalTypes2", DirectCast(args(1).Value, TypeSymbol).ContainingAssembly.Name)
compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {localTypes2Image, piaImage})
lt = compilation.GetTypeByMetadataName("LocalTypes2")
test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("LocalTypes2", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.Equal("LocalTypes2", test2.Parameters(1).Type.ContainingAssembly.Name)
attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("LocalTypes2", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.Equal("LocalTypes2", DirectCast(args(1).Value, TypeSymbol).ContainingAssembly.Name)
End Sub
<Fact()>
Public Sub NestedType4()
Dim piaSource = <compilation name="Pia"><file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<Assembly: ImportedFromTypeLib("Pia1.dll")>
Public Structure S1
Public F1 As Integer
Public Structure S2
Public F1 As Integer
End Structure
End Structure
]]></file></compilation>
Dim pia = CreateCompilationWithMscorlib(piaSource)
CompileAndVerify(pia)
Dim piaImage = MetadataReference.CreateFromImage(pia.EmitToArray())
Dim source = <compilation name="LocalTypes2"><file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class LocalTypes2
Public Sub Test2(x As S1, y As S1.S2)
End Sub
End Class
<ComEventInterface(GetType(S1), GetType(S1.S2))>
Interface AttrTest1
End Interface
]]></file></compilation>
Dim localTypes2 = CreateCompilationWithMscorlib(source,
references:=New MetadataReference() {New VisualBasicCompilationReference(pia, embedInteropTypes:=True)})
'CompileAndVerify(localTypes2)
Dim compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {New VisualBasicCompilationReference(localTypes2), New VisualBasicCompilationReference(pia)})
Dim lt = compilation.GetTypeByMetadataName("LocalTypes2")
Dim test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("Pia", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(test2.Parameters(1).Type)
Dim attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
Dim args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("Pia", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(args(1).Value)
compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {New VisualBasicCompilationReference(localTypes2), piaImage})
lt = compilation.GetTypeByMetadataName("LocalTypes2")
test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("Pia", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(test2.Parameters(1).Type)
attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("Pia", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(args(1).Value)
End Sub
<Fact()>
Public Sub GenericType1()
Dim piaSource = <compilation name="Pia"><file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<Assembly: ImportedFromTypeLib("Pia1.dll")>
Public Structure S1
Public F1 As Integer
End Structure
Public Structure S2(Of T)
Public F1 As Integer
End Structure
]]></file></compilation>
Dim pia = CreateCompilationWithMscorlib(piaSource)
CompileAndVerify(pia)
Dim piaImage = MetadataReference.CreateFromImage(pia.EmitToArray())
Dim source = <compilation name="LocalTypes2"><file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class LocalTypes2
Public Sub Test2(x As S1, y As S2(Of Integer))
End Sub
End Class
<CompilerGenerated(), TypeIdentifier("f9c2d51d-4f44-45f0-9eda-c9d599b58257", "S1")>
Public Structure S1
Public F1 As Integer
End Structure
<CompilerGenerated(), TypeIdentifier("f9c2d51d-4f44-45f0-9eda-c9d599b58257", "S2`1")>
Public Structure S2(Of T)
Public F1 As Integer
End Structure
<ComEventInterface(GetType(S1), GetType(S2(Of)))>
Interface AttrTest1
End Interface
]]></file></compilation>
Dim localTypes2 = CreateCompilationWithMscorlib(source)
'CompileAndVerify(localTypes2)
Dim localTypes2Image = MetadataReference.CreateFromImage(localTypes2.EmitToArray())
Dim compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {New VisualBasicCompilationReference(localTypes2), New VisualBasicCompilationReference(pia)})
Dim lt = compilation.GetTypeByMetadataName("LocalTypes2")
Dim test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("Pia", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(test2.Parameters(1).Type)
Dim attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
Dim args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("Pia", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(args(1).Value)
compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {localTypes2Image, New VisualBasicCompilationReference(pia)})
lt = compilation.GetTypeByMetadataName("LocalTypes2")
test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("Pia", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(test2.Parameters(1).Type)
attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("Pia", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(args(1).Value)
compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {New VisualBasicCompilationReference(localTypes2), piaImage})
lt = compilation.GetTypeByMetadataName("LocalTypes2")
test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("Pia", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(test2.Parameters(1).Type)
attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("Pia", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(args(1).Value)
compilation = CreateCompilationWithMscorlib(<compilation/>,
references:=New MetadataReference() {localTypes2Image, piaImage})
lt = compilation.GetTypeByMetadataName("LocalTypes2")
test2 = lt.GetMember(Of MethodSymbol)("Test2")
Assert.Equal("Pia", test2.Parameters(0).Type.ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(test2.Parameters(1).Type)
attrTest1 = compilation.GetTypeByMetadataName("AttrTest1")
args = attrTest1.GetAttributes()(0).CommonConstructorArguments
Assert.Equal("Pia", DirectCast(args(0).Value, TypeSymbol).ContainingAssembly.Name)
Assert.IsType(Of UnsupportedMetadataTypeSymbol)(args(1).Value)
End Sub
<Fact()>
Public Sub FullyQualifiedCaseSensitiveNames()
Dim pia1 = CreateCSharpCompilation(<![CDATA[
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib("Pia.dll")]
[assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")]
[ComImport, Guid("27e3e649-994b-4f58-b3c6-f8089a5f2c01")]
public interface I {}
namespace N1.N2
{
[ComImport, Guid("27e3e649-994b-4f58-b3c6-f8089a5f2c01")]
public interface I {}
}
namespace n1.n2
{
[ComImport, Guid("27e3e649-994b-4f58-b3c6-f8089a5f2c01")]
public interface i {}
}
]]>.Value,
assemblyName:="Pia1",
referencedAssemblies:=New MetadataReference() {MscorlibRef})
Dim pia1Image = pia1.EmitToImageReference(embedInteropTypes:=True)
Dim pia2 = CreateCSharpCompilation(<![CDATA[
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib("Pia.dll")]
[assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")]
namespace N1.N2
{
[ComImport, Guid("27e3e649-994b-4f58-b3c6-f8089a5f2c01")]
public interface I {}
}
]]>.Value,
assemblyName:="Pia2",
referencedAssemblies:=New MetadataReference() {MscorlibRef})
Dim pia2Image = pia2.EmitToImageReference(embedInteropTypes:=True)
Dim compilation1 = CreateCSharpCompilation(<![CDATA[
using System;
class A : Attribute
{
public A(object o) {}
}
[A(typeof(I))]
class C1 {}
[A(typeof(N1.N2.I))]
class C2 {}
[A(typeof(n1.n2.i))]
class C3 {}
]]>.Value,
assemblyName:="1",
referencedAssemblies:=New MetadataReference() {MscorlibRef, pia1Image})
compilation1.VerifyDiagnostics()
Dim compilation1Image = MetadataReference.CreateFromImage(compilation1.EmitToArray())
Dim compilation2 = CreateCompilationWithMscorlib(<compilation name="2"/>,
references:=New MetadataReference() {compilation1Image, pia1Image})
Dim type = compilation2.GetTypeByMetadataName("C1")
Dim argType = DirectCast(type.GetAttributes()(0).CommonConstructorArguments(0).Value, TypeSymbol)
Assert.Equal("Pia1", argType.ContainingAssembly.Name)
Assert.Equal("I", argType.ToString())
type = compilation2.GetTypeByMetadataName("C2")
argType = DirectCast(type.GetAttributes()(0).CommonConstructorArguments(0).Value, TypeSymbol)
Assert.Equal("Pia1", argType.ContainingAssembly.Name)
Assert.Equal("N1.N2.I", argType.ToString())
type = compilation2.GetTypeByMetadataName("C3")
argType = DirectCast(type.GetAttributes()(0).CommonConstructorArguments(0).Value, TypeSymbol)
Assert.Equal("Pia1", argType.ContainingAssembly.Name)
Assert.Equal("n1.n2.i", argType.ToString())
compilation2 = CreateCompilationWithMscorlib(<compilation name="2"/>,
references:=New MetadataReference() {compilation1Image, pia2Image})
type = compilation2.GetTypeByMetadataName("C1")
argType = DirectCast(type.GetAttributes()(0).CommonConstructorArguments(0).Value, TypeSymbol)
Assert.IsType(Of NoPiaMissingCanonicalTypeSymbol)(argType)
type = compilation2.GetTypeByMetadataName("C2")
argType = DirectCast(type.GetAttributes()(0).CommonConstructorArguments(0).Value, TypeSymbol)
Assert.Equal("Pia2", argType.ContainingAssembly.Name)
Assert.Equal("N1.N2.I", argType.ToString())
type = compilation2.GetTypeByMetadataName("C3")
argType = DirectCast(type.GetAttributes()(0).CommonConstructorArguments(0).Value, TypeSymbol)
Assert.IsType(Of NoPiaMissingCanonicalTypeSymbol)(argType)
End Sub
<Fact, WorkItem(685240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685240")>
Public Sub Bug685240()
Dim piaSource =
<compilation name="Pia1">
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<Assembly: ImportedFromTypeLib("Pia1.dll")>
<ComImport, Guid("27e3e649-994b-4f58-b3c6-f8089a5f2c01"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface I1
Sub Sub1(ByVal x As Integer)
End Interface
]]></file>
</compilation>
Dim pia1 = CreateCompilationWithMscorlib(piaSource, options:=TestOptions.ReleaseDll)
CompileAndVerify(pia1)
Dim moduleSource =
<compilation name="Module1">
<file name="a.vb"><![CDATA[
Public Class Test
Public Shared Function M1() As I1
return Nothing
End Function
End Class
]]></file>
</compilation>
Dim module1 = CreateCompilationWithMscorlib(moduleSource, options:=TestOptions.ReleaseModule,
references:={New VisualBasicCompilationReference(pia1, embedInteropTypes:=True)})
Dim emptySource =
<compilation>
<file name="a.vb"><![CDATA[
]]></file>
</compilation>
Dim multiModule = CreateCompilationWithMscorlib(emptySource, options:=TestOptions.ReleaseDll,
references:={module1.EmitToImageReference()})
CompileAndVerify(multiModule)
Dim consumerSource =
<compilation>
<file name="a.vb"><![CDATA[
Public Class Consumer
public shared sub M2()
Dim x = Test.M1()
End Sub
End Class
]]></file>
</compilation>
Dim consumer = CreateCompilationWithMscorlib(consumerSource, options:=TestOptions.ReleaseDll,
references:={New VisualBasicCompilationReference(multiModule),
New VisualBasicCompilationReference(pia1)})
CompileAndVerify(consumer)
End Sub
<Fact, WorkItem(528047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528047")>
Public Sub OverloadResolutionWithEmbeddedInteropType()
Dim source1 =
<compilation>
<file name="a.vb"><![CDATA[
imports System
imports System.Collections.Generic
imports stdole
public class A
public shared Sub Foo(func As Func(Of X))
System.Console.WriteLine("X")
end Sub
public shared Sub Foo(func As Func(Of Y))
System.Console.WriteLine("Y")
end Sub
End Class
public delegate Sub X(addin As List(Of IDispatch))
public delegate Sub Y(addin As List(Of string))
]]></file>
</compilation>
Dim comp1 = CreateCompilationWithMscorlib(source1, options:=TestOptions.ReleaseDll,
references:={TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(True)})
Dim source2 =
<compilation>
<file name="a.vb"><![CDATA[
public module Program
public Sub Main()
A.Foo(Function() Sub(x) x.ToString())
End Sub
End Module
]]></file>
</compilation>
Dim comp2 = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2,
{comp1.EmitToImageReference(),
TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(True)},
TestOptions.ReleaseExe)
CompileAndVerify(comp2, expectedOutput:="Y").Diagnostics.Verify()
Dim comp3 = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source2,
{New VisualBasicCompilationReference(comp1),
TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(True)},
TestOptions.ReleaseExe)
CompileAndVerify(comp3, expectedOutput:="Y").Diagnostics.Verify()
End Sub
End Class
End Namespace
|
Imports Windows10Design
Public Class Program
Inherits Win32Application
<STAThread>
Public Shared Sub Main(args As String())
Dim app As New Program(args)
Dim window As New Form1()
app.Run(New Form1())
End Sub
Public Sub New(args As String())
MyBase.New(args)
End Sub
Public Overrides Function CreateUWPApplication() As IDisposable
Return New UI.App(Me)
End Function
Public Overrides Function GetXamlContent() As Object
Return New UI.MainPage()
End Function
End Class
|
Public Class EarthDistanceCounter
Private ReadOnly _gameConfig As GameConfig
Private ReadOnly _playArea As Form2
Private ReadOnly _screenSize As ScreenSize
Private _counter As Integer
Public Sub New(ByVal frames As Frames, ByVal playArea As Form2, ByVal gameConfig As GameConfig, ByVal game As LaserDefender, ByVal screen As ScreenSize)
_gameConfig = gameConfig
_playArea = playArea
_screenSize = screen
AddHandler frames.Update, AddressOf Add
AddHandler game.GameStart, AddressOf InitializeCounter
End Sub
Private Sub InitializeCounter()
_counter = 0
_playArea.EarthImage.Top = _screenSize.yMax - 60
_playArea.DistanceEarthCounter.Text = _counter
End Sub
Public Sub Add()
_counter += _gameConfig.EarthDistanceCounterSpeed
If Math.Floor(_counter / 5) = _counter / 5 Then
_playArea.EarthImage.Top += _gameConfig.EarthDistanceCounterEarthSpeed
End If
_playArea.DistanceEarthCounter.Text = _counter
End Sub
End Class
|
Namespace XeoraCube.VSAddIn.Forms
Public Class TranslationSearch
Inherits ISFormBase
Public Sub New(ByVal Selection As EnvDTE.TextSelection, ByVal BeginningOffset As Integer)
MyBase.New(Selection, BeginningOffset)
Me.InitializeComponent()
MyBase.lwControls.SmallImageList = ilTranslations
End Sub
Private _TranslationsPath As String = String.Empty
Private _TranslationID As String = String.Empty
Public WriteOnly Property TranslationsPath() As String
Set(ByVal value As String)
Me._TranslationsPath = value
End Set
End Property
Public ReadOnly Property TranslationID() As String
Get
Return Me._TranslationID
End Get
End Property
Public Overrides Sub FillList()
Me._FillList(Me._TranslationsPath)
Dim ParentDI As IO.DirectoryInfo = _
IO.Directory.GetParent(Me._TranslationsPath)
If ParentDI.GetDirectories("Addons").Length = 0 Then _
Me._FillList(IO.Path.GetFullPath(IO.Path.Combine(Me._TranslationsPath, "../../../../Translations")))
MyBase.Sort()
End Sub
Private Sub _FillList(ByVal TranslationsPath As String)
Dim cFStream As IO.FileStream = Nothing
Try
Dim TranslationFileNames As String() = _
IO.Directory.GetFiles(TranslationsPath, "*.xml")
Dim TranslationCompile As New Generic.Dictionary(Of String, Integer)
For Each TranslationFileName As String In TranslationFileNames
Try
cFStream = New IO.FileStream( _
TranslationFileName, IO.FileMode.Open, _
IO.FileAccess.Read, IO.FileShare.ReadWrite)
Dim xPathDocument As New Xml.XPath.XPathDocument(cFStream)
Dim xPathNavigator As Xml.XPath.XPathNavigator = _
xPathDocument.CreateNavigator()
Dim xPathIter As Xml.XPath.XPathNodeIterator
xPathIter = xPathNavigator.Select("/translations/translation")
Do While xPathIter.MoveNext()
Dim TransID As String = _
xPathIter.Current.GetAttribute("id", xPathIter.Current.NamespaceURI)
If TranslationCompile.ContainsKey(TransID) Then _
TranslationCompile.Item(TransID) += 1 Else TranslationCompile.Add(TransID, 1)
Loop
Catch ex As Exception
' Just Handle Exceptions
Finally
If Not cFStream Is Nothing Then cFStream.Close()
End Try
Next
Dim ImageIndex As Integer = 0
For Each TransIDKey As String In TranslationCompile.Keys
If TranslationCompile.Item(TransIDKey) = TranslationFileNames.Length AndAlso _
Not MyBase.lwControls.Items.ContainsKey(TransIDKey) Then
MyBase.lwControls.Items.Add(TransIDKey, String.Empty, ImageIndex)
MyBase.lwControls.Items(MyBase.lwControls.Items.Count - 1).SubItems.Add(TransIDKey)
End If
Next
Catch ex As Exception
' Just Handle Exceptions
End Try
End Sub
Public Overrides Sub AcceptSelection()
If MyBase.lwControls.SelectedItems.Count > 0 Then
Me._TranslationID = MyBase.lwControls.SelectedItems.Item(0).SubItems.Item(1).Text
Else
Me.CancelSelection()
End If
End Sub
Public Overrides Sub CancelSelection()
Me._TranslationID = String.Empty
End Sub
Public Overrides Sub HandleResult()
MyBase.HandleResultDelegate.BeginInvoke(MyBase.WindowHandler, Me.DialogResult = System.Windows.Forms.DialogResult.OK, Me.BeginningOffset, Me.CurrentSelection, Globals.ISTypes.TranslationSearch, Me.AcceptChar, Me.UseCloseChar, New Object() {Me.TranslationID}, New AsyncCallback(Sub(aR As IAsyncResult)
Try
CType(aR.AsyncState, AddInControl.HandleResultDelegate).EndInvoke(Nothing, aR)
Catch ex As Exception
' Just handle to prevent crash
End Try
End Sub), MyBase.HandleResultDelegate)
End Sub
#Region " Form Designer Generated Codes "
Friend WithEvents ilTranslations As System.Windows.Forms.ImageList
Private components As System.ComponentModel.IContainer
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(TranslationSearch))
Me.ilTranslations = New System.Windows.Forms.ImageList(Me.components)
Me.SuspendLayout()
'
'ilTranslations
'
Me.ilTranslations.ImageStream = CType(resources.GetObject("ilTranslations.ImageStream"), System.Windows.Forms.ImageListStreamer)
Me.ilTranslations.TransparentColor = System.Drawing.Color.Transparent
Me.ilTranslations.Images.SetKeyName(0, "0translation.png")
'
'TranslationSearch
'
Me.ClientSize = New System.Drawing.Size(184, 184)
Me.Name = "TranslationSearch"
Me.ResumeLayout(False)
End Sub
#End Region
End Class
End Namespace |
Imports System.Drawing.Drawing2D
Imports System.IO
Public Class frmImageEditor
Dim fileAddress As String
Dim Job As Integer = 0 ' 1:crop 2:contrast
Dim timerTik As Boolean = False
Dim img As New ImageProcessor.ImageFactory
Dim tempCnt As Boolean 'check weather the roller is used or not
Dim bm_dest As Bitmap
Dim bm_source As Bitmap
Dim i As Int16 = 0.5
Dim cropX As Integer
Dim cropY As Integer
Dim cropWidth As Integer
Dim cropHeight As Integer
Dim oCropX As Integer
Dim oCropY As Integer
Dim cropBitmap As Bitmap
Public cropPen As Pen
Public cropPenSize As Integer = 1 '2
Public cropDashStyle As Drawing2D.DashStyle = DashStyle.Solid
Public cropPenColor As Color = Color.Yellow
Dim tmppoint As Point
Dim isStart As Boolean = False
Sub New()
InitializeComponent()
End Sub
Sub New(FileAddress As String)
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.fileAddress = FileAddress
Try
Dim xx As Image
Using str As Stream = File.OpenRead(FileAddress)
xx = Image.FromStream(str)
End Using
pic.Image = xx
resizer()
lblTaqir.Text = ""
Catch ex As Exception
MessageBox.Show(ex.Message)
Me.Close()
End Try
End Sub
Private Sub frmImageEditor_Load(sender As Object, e As EventArgs) Handles MyBase.Load
btnOK.BackgroundImage = IMGcache.img($"{Application.StartupPath}\data\app\icon\tick11.png")
btnCancel.BackgroundImage = IMGcache.img($"{Application.StartupPath}\data\app\icon\cross106.png")
End Sub
Private Sub resizer()
If pic.Image Is Nothing Then Exit Sub
Dim ix, iy, iw, ih As Double
If pic.Image.Width / pic.Image.Height > picPanel.Width / picPanel.Height Then
iw = picPanel.Width
ih = picPanel.Width / pic.Image.Width * pic.Image.Height
ix = 0
iy = (picPanel.Height - ih) / 2
ElseIf pic.Image.Width / pic.Image.Height < picPanel.Width / picPanel.Height Then
iw = picPanel.Height / pic.Image.Height * pic.Image.Width
ih = picPanel.Height
ix = (picPanel.Width - iw) / 2
iy = 0
Else
iw = picPanel.Width
ih = picPanel.Height
ix = 0
iy = 0
End If
pic.Dock = DockStyle.None
pic.Size = New Size(iw, ih)
pic.Location = New Point(ix, iy)
End Sub
Private Sub btnEnseraf_Click(sender As Object, e As EventArgs) Handles btnEnseraf.Click
Me.Close()
End Sub
Private Sub btnCrop_Click(sender As Object, e As EventArgs) Handles btnCrop.Click
Job = 1
lblTaqir.Text = "برش"
Abzar.Enabled = False
btnOK.Visible = True
btnCancel.Visible = True
btnTaeed.Enabled = False
End Sub
Private Sub pic_MouseDown(sender As Object, e As MouseEventArgs) Handles pic.MouseDown
Try
If Job = 1 Then
If e.Button = Windows.Forms.MouseButtons.Left Then
cropX = e.X
cropY = e.Y
cropPen = New Pen(cropPenColor, cropPenSize)
cropPen.DashStyle = DashStyle.DashDotDot
Cursor = Cursors.Cross
End If
pic.Refresh()
End If
Catch exc As Exception
End Try
End Sub
Private Sub pic_MouseMove(sender As Object, e As MouseEventArgs) Handles pic.MouseMove
Try
If Job = 1 Then
If pic.Image Is Nothing Then Exit Sub
If e.Button = Windows.Forms.MouseButtons.Left Then
isStart = True
If Not MouseIsOverControl(pic) Then Exit Sub
pic.Refresh()
cropWidth = Math.Max(e.X, cropX) - Math.Min(e.X, cropX)
cropHeight = Math.Max(e.Y, cropY) - Math.Min(e.Y, cropY)
pic.CreateGraphics.DrawRectangle(cropPen, Math.Min(cropX, e.X), Math.Min(cropY, e.Y), cropWidth, cropHeight)
End If
End If
Catch exc As Exception
If Err.Number = 5 Then Exit Sub
End Try
End Sub
Public Function MouseIsOverControl(ByVal c As Control) As Boolean
Return c.ClientRectangle.Contains(c.PointToClient(Control.MousePosition))
End Function
Private Sub pic_MouseUp(sender As Object, e As MouseEventArgs) Handles pic.MouseUp
Try
If Job = 1 Then
Cursor = Cursors.Default
Try
If cropWidth < 10 Or cropHeight < 10 Or Not isStart Then
pic.Refresh()
Exit Sub
End If
isStart = False
Dim rect As Rectangle = New Rectangle(Math.Min(cropX, e.X), Math.Min(cropY, e.Y), cropWidth, cropHeight)
Dim bit As Bitmap = New Bitmap(pic.Image, pic.Width, pic.Height)
'cropBitmap = New Bitmap(cropWidth, cropHeight)
'Dim g As Graphics = Graphics.FromImage(cropBitmap)
'g.InterpolationMode = InterpolationMode.HighQualityBicubic
'g.PixelOffsetMode = PixelOffsetMode.HighQuality
'g.CompositingQuality = CompositingQuality.HighQuality
'g.DrawImage(bit, 0, 0, rect, GraphicsUnit.Pixel)
'preview.Image = cropBitmap
img = New ImageProcessor.ImageFactory
img.Quality(100)
img.Load(bit)
preview.Image = img.Crop(rect).Image
Catch exc As Exception
End Try
End If
Catch exc As Exception
End Try
End Sub
Private Sub frmImageEditor_Resize(sender As Object, e As EventArgs) Handles Me.Resize
resizer()
End Sub
Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
If preview.Image IsNot Nothing Then
pic.Image = preview.Image
resizer()
btnOK.Visible = False
btnCancel.Visible = False
Abzar.Enabled = True
btnTaeed.Enabled = True
Job = 0
lblTaqir.Text = ""
trackContrast.Visible = False
resizer()
pic.Refresh()
preview.Image = Nothing
End If
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
Job = 0
lblTaqir.Text = ""
trackContrast.Visible = False
resizer()
pic.Refresh()
preview.Image = Nothing
btnOK.Visible = False
btnCancel.Visible = False
Abzar.Enabled = True
btnTaeed.Enabled = True
End Sub
Private Sub btnTaeed_Click(sender As Object, e As EventArgs) Handles btnTaeed.Click
Try
pic.Image.Save(fileAddress)
IMGcache.Remove(fileAddress)
MessageBox.Show("تصویر با موفقیت ویرایش و ذخیره شد")
Me.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If timerTik Then
' btnOK.BackColor = Color.FromArgb(100, Color.Green)
' btnCancel.BackColor = Color.FromArgb(255, Color.Orange)
GroupBox1.ForeColor = Color.White
Else
' btnOK.BackColor = Color.FromArgb(255, Color.Orange)
' btnCancel.BackColor = Color.FromArgb(100, Color.Red)
GroupBox1.ForeColor = Color.Black
End If
If Job > 0 Then
timerTik = Not timerTik
GroupBox1.Visible = True
Else
'GroupBox1.ForeColor = Color.Black
GroupBox1.Visible = False
End If
End Sub
Private Sub btnRotateC_Click(sender As Object, e As EventArgs) Handles btnRotateC.Click
img = New ImageProcessor.ImageFactory
img.Load(New Bitmap(pic.Image))
pic.Image = img.Rotate(90).Image
resizer()
btnTaeed.Enabled = True
End Sub
Private Sub btnRotateAC_Click(sender As Object, e As EventArgs) Handles btnRotateAC.Click
img = New ImageProcessor.ImageFactory
img.Load(New Bitmap(pic.Image))
pic.Image = img.Rotate(-90).Image
resizer()
btnTaeed.Enabled = True
End Sub
Private Sub btnFilipV_Click(sender As Object, e As EventArgs) Handles btnFilipV.Click
img = New ImageProcessor.ImageFactory
img.Load(New Bitmap(pic.Image))
pic.Image = img.Flip(True, False).Image
resizer()
btnTaeed.Enabled = True
End Sub
Private Sub btnFilipH_Click(sender As Object, e As EventArgs) Handles btnFilipH.Click
img = New ImageProcessor.ImageFactory
img.Load(New Bitmap(pic.Image))
pic.Image = img.Flip(False, False).Image
resizer()
btnTaeed.Enabled = True
End Sub
Private Sub btnContrast_Click(sender As Object, e As EventArgs) Handles btnContrast.Click
Job = 2
lblTaqir.Tag = 0
lblTaqir.Text = $"میزان روشنایی : {lblTaqir.Tag}%"
preview.Image = pic.Image
img = New ImageProcessor.ImageFactory
img.Load(pic.Image)
trackContrast.Value = 0
trackContrast.Visible = True
Abzar.Enabled = False
btnOK.Visible = True
btnCancel.Visible = True
btnTaeed.Enabled = False
End Sub
Private Sub trackContrast_Scroll(sender As Object, e As EventArgs) Handles trackContrast.Scroll
img.Reset()
preview.Image = img.Contrast(trackContrast.Value).Image
lblTaqir.Tag = trackContrast.Value
lblTaqir.Text = $"میزان روشنایی : {lblTaqir.Tag}%"
End Sub
End Class |
Imports System.Text
Namespace BomCompare
Public Class BomCompareRow
Implements IComparable
Public Enum ChangeTypeEnum
Unchanged
Added
Removed
Updated
Replaced
End Enum
Public Sub New(ByVal index As String, ByVal changeType As ChangeTypeEnum, ByVal changeDescription As List(Of String), compareItem As BomCompareItem, baseItem As BomCompareItem)
Me.Index = index
Me.ChangeType = changeType
Me.ChangeDescription = changeDescription
Me.CompareItem = compareItem
Me.BaseItem = baseItem
End Sub
Public Property Index As String
Property ChangeType As ChangeTypeEnum
Property ChangeDescription As List(Of String)
Property CompareItem As BomCompareItem
Property BaseItem As BomCompareItem
Public Overrides Function ToString() As String
Dim sb As New StringBuilder
sb.AppendLine("Index: " & Index)
sb.AppendLine("ChangeType: " & ChangeType.ToString)
sb.AppendLine("Change description:")
For Each changeDesc In ChangeDescription
sb.AppendLine(changeDesc)
Next
If CompareItem Is Nothing Then
sb.AppendLine("No compare item")
Else
sb.AppendLine("Compare Item:")
sb.Append(BomCompareItemToString(CompareItem))
End If
If BaseItem Is Nothing Then
sb.AppendLine("No base item")
Else
sb.AppendLine("BaseItem Item:")
sb.Append(BomCompareItemToString(BaseItem))
End If
Return sb.ToString()
End Function
Private Function BomCompareItemToString(ByVal item As BomCompareItem) As String
Dim sb As New StringBuilder
For Each prop As IBomCompareItemProperty In item.BomCompareItemProperties
sb.Append(prop.PropertyName)
sb.Append("=")
sb.Append(prop.Value)
sb.Append(" Changed?=" & prop.Changed)
sb.AppendLine()
Next
Return sb.ToString()
End Function
Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
Dim otherBomCompareRow As BomCompareRow = TryCast(obj, BomCompareRow)
If otherBomCompareRow Is Nothing Then
Return 0
End If
' Try to sort by integer if possible
Dim otherIndex As Integer
Dim thisIndex As Integer
If Integer.TryParse(otherBomCompareRow.Index, otherIndex) AndAlso Integer.TryParse(Me.Index, thisIndex) Then
If thisIndex > otherIndex Then
Return 1
ElseIf thisIndex < otherIndex Then
Return -1
End If
Return 0
Else
If Me.Index > otherBomCompareRow.Index Then
Return 1
ElseIf Me.Index < otherBomCompareRow.Index Then
Return -1
End If
Return 0
End If
End Function
End Class
End Namespace |
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Windows
<Assembly: AssemblyTitle("HVIFViewer")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("HVIFViewer")>
<Assembly: AssemblyCopyright("Copyright © 2022")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(false)>
'<Assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)>
<Assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)>
<Assembly: Guid("d22f4d27-a8f8-4161-8ad3-d3c9dab907eb")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
Imports System.Data.SqlClient
Public Class OtobuslerFormu
Private SQLBaglanti As New SqlConnection(SqlBaglantiCumlesi)
Private OtobusTablosuSDA As SqlDataAdapter
Private Sub OtobuslerFormu_Load(sender As Object, e As EventArgs) Handles MyBase.Load
OtobusBilgileriniGetir()
MarkaModelBilgileriniGetir()
OtobusTablosuBindingSource.CancelEdit()
End Sub
Private Sub OtobusBilgileriniGetir()
Dim Sorgu As String = "SELECT * FROM OtobusTablosu"
OtobusTablosuSDA = New SqlDataAdapter(Sorgu, SQLBaglanti)
OtobusTablosuSDA.Fill(BipBusDataSet, "OtobusTablosu")
'Insert, Update ve Delete Komutlarını Ekle
Dim SQLKomutOlusturucu As New SqlCommandBuilder(OtobusTablosuSDA)
OtobusTablosuSDA.InsertCommand = SQLKomutOlusturucu.GetInsertCommand
OtobusTablosuSDA.UpdateCommand = SQLKomutOlusturucu.GetUpdateCommand
OtobusTablosuSDA.DeleteCommand = SQLKomutOlusturucu.GetDeleteCommand
'**********************************
OtobusTablosuBindingSource.DataSource = BipBusDataSet
OtobusTablosuBindingSource.DataMember = "OtobusTablosu"
OtobusTablosuBindingNavigator.BindingSource = OtobusTablosuBindingSource
OtobuslerDataGridView.DataSource = OtobusTablosuBindingSource
FormNesneleriniBagla()
End Sub
Private Sub FormNesneleriniBagla()
PlakaTextBox.DataBindings.Add("Text", OtobusTablosuBindingSource, "Plaka")
MarkaNoComboBox.DataBindings.Add("SelectedValue", OtobusTablosuBindingSource, "MarkaNo")
ModelNoComboBox.DataBindings.Add("SelectedValue", OtobusTablosuBindingSource, "ModelNo")
KoltukSayisiNUD.DataBindings.Add("Value", OtobusTablosuBindingSource, "KoltukSayisi", True)
TelefonTextBox.DataBindings.Add("Text", OtobusTablosuBindingSource, "Telefon")
KoltukDizilisiComboBox.DataBindings.Add("Text", OtobusTablosuBindingSource, "KoltukDizilisi")
KatNUD.DataBindings.Add("Value", OtobusTablosuBindingSource, "Kat", True)
End Sub
Private Sub MarkaModelBilgileriniGetir()
Try
SQLBaglanti.Open()
'Marka Bilgilerini Getir
Dim Sorgu As String = "SELECT * FROM MarkaTablosu"
Dim SQLKomut As New SqlCommand(Sorgu, SQLBaglanti)
BipBusDataSet.Tables.Add("MarkaTablosu").Load(SQLKomut.ExecuteReader)
'Model Bilgilerini Getir
Sorgu = "SELECT * FROM ModelTablosu"
SQLKomut.CommandText = Sorgu
BipBusDataSet.Tables.Add("ModelTablosu").Load(SQLKomut.ExecuteReader)
'Marka ve Model Tabloları Arasında DataSet Üzerinde İlişki Kurma************
'MarkaNo Alanlarını Değişkenlere Ata
Dim Marka_MarkaNo As DataColumn = BipBusDataSet.Tables("MarkaTablosu").Columns("MarkaNo")
Dim Model_MarkaNo As DataColumn = BipBusDataSet.Tables("ModelTablosu").Columns("MarkaNo")
'İlişki Değişkenini Oluştur New DataRelation("İlişki Adı", PK Olan Alan, FK Olan Alan)
Dim MarkaModelRelation As New DataRelation("MarkaModel", Marka_MarkaNo, Model_MarkaNo)
'İlişkiyi DataSet'e Ekle
BipBusDataSet.Relations.Add(MarkaModelRelation)
'BindingSource'ler ile Bağlantı Kur
MarkaBindingSource.DataSource = BipBusDataSet
MarkaBindingSource.DataMember = "MarkaTablosu"
'Buraya Dikkat
ModelBindingSource.DataSource = MarkaBindingSource
ModelBindingSource.DataMember = "MarkaModel" 'İlişkiye Verdiğimiz İsmi Yazıyoruz
'***************************************************************
'ComboBox'lar ile Bağlantı Kur
MarkaNoComboBox.DataSource = MarkaBindingSource
MarkaNoComboBox.DisplayMember = "Marka"
MarkaNoComboBox.ValueMember = "MarkaNo"
ModelNoComboBox.DataSource = ModelBindingSource
ModelNoComboBox.DisplayMember = "ModelAdi"
ModelNoComboBox.ValueMember = "ModelNo"
'DataGridView İçerisindeki Tipi ComboBox Olan Alanlar İle Bağlantı Kur
Dim MarkaNoCB As DataGridViewComboBoxColumn = OtobuslerDataGridView.Columns("MarkaNo")
MarkaNoCB.DataSource = MarkaBindingSource
MarkaNoCB.DisplayMember = "Marka"
MarkaNoCB.ValueMember = "MarkaNo"
Dim ModelNoCB As DataGridViewComboBoxColumn = OtobuslerDataGridView.Columns("ModelNo")
ModelNoCB.DataSource = ModelBindingSource
ModelNoCB.DisplayMember = "ModelAdi"
ModelNoCB.ValueMember = "ModelNo"
Catch ex As Exception
Finally
SQLBaglanti.Close()
End Try
End Sub
Private Sub MarkaNoComboBox_SelectedValueChanged(sender As Object, e As EventArgs) Handles MarkaNoComboBox.SelectedValueChanged
' MarkaBindingSource.Position = MarkaNoComboBox.SelectedIndex
End Sub
Private Sub BindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles BindingNavigatorSaveItem.Click
Me.Validate()
OtobusTablosuBindingSource.EndEdit()
OtobusTablosuSDA.Update(BipBusDataSet, "OtobusTablosu")
MsgBox("Yapılan Değişiklikler (Ekle, Değiştir, Sil) Veri Tabanına Aktarıldı.")
End Sub
Private Sub AraButton_Click(sender As Object, e As EventArgs) Handles AraButton.Click
OtobusAramaFormu.ShowDialog(Me)
End Sub
Private Sub OtobuslerDataGridView_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles OtobuslerDataGridView.DataError
If e.Exception.Message = "DataGridViewComboBoxCell value is not valid." Then
Dim value As Object = OtobuslerDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
If Not (CType(OtobuslerDataGridView.Columns(e.ColumnIndex), DataGridViewComboBoxColumn)).Items.Contains(value) Then
CType(OtobuslerDataGridView.Columns(e.ColumnIndex), DataGridViewComboBoxColumn).Items.Add(value)
e.ThrowException = False
End If
End If
End Sub
End Class |
Public Class FrmFindVA
Private Sub BtnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnCancel.Click
Me.Close()
Me.Dispose()
End Sub
Private Sub BtnOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnOk.Click
Me.DialogResult = Windows.Forms.DialogResult.OK
End Sub
Private Sub TxtValue_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TxtValue.KeyPress
SetDisableKeyString(e)
End Sub
End Class |
'------------------------------------------------------------------------------
' <auto-generated>
' 此代码由工具生成。
' 运行时版本:4.0.30319.42000
'
' 对此文件的更改可能会导致不正确的行为,并且如果
' 重新生成代码,这些更改将会丢失。
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.9.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 自动保存功能"
#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.舰娘大战塞壬启动器.My.MySettings
Get
Return Global.舰娘大战塞壬启动器.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
Public Class PalindromeForm
Private Sub btnAnalyze_Click(sender As Object, e As EventArgs) Handles btnAnalyze.Click
Dim word as String = txtWord.Text
Dim wordNoPunctuation as String = ""
For i as Integer = 0 To word.Length - 1
Dim character as Char = Cchar(word.Substring(i,1).ToUpper())
If Asc(character) >= 65 And Asc(character) <= 90 Then
wordNoPunctuation += character
End If
Next
If IsPalindrome(wordNoPunctuation) Then
txtOutput.Text = "YES"
Else
txtOutput.Text = "NO"
End If
End Sub
Private Function IsPalindrome(word As String) As Boolean
Dim reversedWord as String = ""
For i as Integer = word.Length To 1 Step -1
reversedWord += word.Substring(i - 1, 1)
Next
If reversedWord = word Then
Return True
Else
Return False
End If
End Function
End Class
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("SaberLibreriasWindows.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
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
'-----------------------------------------------------------------------------------------------------------
' This is the code that actually outputs the VB code that defines the tree. It is passed a read and validated
' ParseTree, and outputs the code to defined the node classes for that tree, and also additional data
' structures like the kinds, visitor, etc.
'-----------------------------------------------------------------------------------------------------------
Imports System.IO
' Class to write out the code for the code tree.
Friend Class GreenNodeWriter
Inherits WriteUtils
Private _writer As TextWriter 'output is sent here.
Private ReadOnly _nonterminalsWithOneChild As List(Of String) = New List(Of String)
Private ReadOnly _nonterminalsWithTwoChildren As List(Of String) = New List(Of String)
' Initialize the class with the parse tree to write.
Public Sub New(parseTree As ParseTree)
MyBase.New(parseTree)
End Sub
' Write out the code defining the tree to the give file.
Public Sub WriteTreeAsCode(writer As TextWriter)
_writer = writer
GenerateFile()
End Sub
Private Sub GenerateFile()
GenerateNamespace()
End Sub
Private Sub GenerateNamespace()
_writer.WriteLine()
If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then
_writer.WriteLine("Namespace {0}", Ident(_parseTree.NamespaceName) + ".Syntax.InternalSyntax")
_writer.WriteLine()
End If
GenerateNodeStructures()
If Not String.IsNullOrEmpty(_parseTree.VisitorName) Then
GenerateVisitorClass()
End If
If Not String.IsNullOrEmpty(_parseTree.RewriteVisitorName) Then
GenerateRewriteVisitorClass()
End If
If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then
_writer.WriteLine("End Namespace")
End If
'DumpNames("Nodes with One Child", _nonterminalsWithOneChild)
'DumpNames("Nodes with Two Children", _nonterminalsWithTwoChildren)
End Sub
Private Sub DumpNames(title As String, names As List(Of String))
Console.WriteLine(title)
Console.WriteLine("=======================================")
Dim sortedNames = From n In names Order By n
For Each name In sortedNames
Console.WriteLine(name)
Next
Console.WriteLine()
End Sub
Private Sub GenerateNodeStructures()
For Each nodeStructure In _parseTree.NodeStructures.Values
If Not nodeStructure.NoFactory Then
GenerateNodeStructureClass(nodeStructure)
End If
Next
End Sub
' Generate an constant value
Private Function GetConstantValue(val As Long) As String
Return val.ToString()
End Function
' Generate a class declaration for a node structure.
Private Sub GenerateNodeStructureClass(nodeStructure As ParseNodeStructure)
' XML comment
GenerateXmlComment(_writer, nodeStructure, 4)
' Class name
_writer.Write(" ")
If (nodeStructure.PartialClass) Then
_writer.Write("Partial ")
End If
Dim visibility As String = "Friend"
If _parseTree.IsAbstract(nodeStructure) Then
_writer.WriteLine("{0} MustInherit Class {1}", visibility, StructureTypeName(nodeStructure))
ElseIf Not nodeStructure.HasDerivedStructure Then
_writer.WriteLine("{0} NotInheritable Class {1}", visibility, StructureTypeName(nodeStructure))
Else
_writer.WriteLine("{0} Class {1}", visibility, StructureTypeName(nodeStructure))
End If
' Base class
If Not IsRoot(nodeStructure) Then
_writer.WriteLine(" Inherits {0}", StructureTypeName(nodeStructure.ParentStructure))
End If
_writer.WriteLine()
'Create members
GenerateNodeStructureMembers(nodeStructure)
' Create the constructor.
GenerateNodeStructureConstructor(nodeStructure, False, noExtra:=True)
GenerateNodeStructureConstructor(nodeStructure, False, noExtra:=True, contextual:=True)
GenerateNodeStructureConstructor(nodeStructure, False)
' Serialization
GenerateNodeStructureSerialization(nodeStructure)
GenerateCreateRed(nodeStructure)
' Create the property accessor for each of the fields
Dim fields = nodeStructure.Fields
For i = 0 To fields.Count - 1
GenerateNodeFieldProperty(fields(i), i, fields(i).ContainingStructure IsNot nodeStructure)
Next
' Create the property accessor for each of the children
Dim children = nodeStructure.Children
For i = 0 To children.Count - 1
GenerateNodeChildProperty(nodeStructure, children(i), i)
GenerateNodeWithChildProperty(children(i), i, nodeStructure)
Next
If Not (_parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken) Then
If children.Count = 1 Then
If Not children(0).IsList AndAlso Not KindTypeStructure(children(0).ChildKind).Name = "ExpressionSyntax" Then
_nonterminalsWithOneChild.Add(nodeStructure.Name)
End If
ElseIf children.Count = 2 Then
If Not children(0).IsList AndAlso Not KindTypeStructure(children(0).ChildKind).Name = "ExpressionSyntax" AndAlso Not children(1).IsList AndAlso Not KindTypeStructure(children(1).ChildKind).Name = "ExpressionSyntax" Then
_nonterminalsWithTwoChildren.Add(nodeStructure.Name)
End If
End If
End If
'Create GetChild
GenerateGetChild(nodeStructure)
GenerateWithTrivia(nodeStructure)
GenerateSetDiagnostics(nodeStructure)
GenerateSetAnnotations(nodeStructure)
' Visitor accept method
If Not String.IsNullOrEmpty(_parseTree.VisitorName) Then
GenerateAccept(nodeStructure)
End If
'GenerateUpdate(nodeStructure)
' Special methods for the root node.
If IsRoot(nodeStructure) Then
GenerateRootNodeSpecialMethods(nodeStructure)
End If
' End the class
_writer.WriteLine(" End Class")
_writer.WriteLine()
End Sub
' Generate CreateRed method
Private Sub GenerateCreateRed(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then
Return
End If
_writer.WriteLine(" Friend Overrides Function CreateRed(ByVal parent As SyntaxNode, ByVal startLocation As Integer) As SyntaxNode")
_writer.WriteLine(" Return new {0}.Syntax.{1}(Me, parent, startLocation)", _parseTree.NamespaceName, StructureTypeName(nodeStructure))
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate SetDiagnostics method
Private Sub GenerateSetDiagnostics(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) Then
Return
End If
_writer.WriteLine(" Friend Overrides Function SetDiagnostics(ByVal newErrors As DiagnosticInfo()) As GreenNode")
_writer.Write(" Return new {0}", StructureTypeName(nodeStructure))
GenerateNodeStructureConstructorParameters(nodeStructure, "newErrors", "GetAnnotations", "GetLeadingTrivia", "GetTrailingTrivia")
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate SetAnnotations method
Private Sub GenerateSetAnnotations(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) Then
Return
End If
_writer.WriteLine(" Friend Overrides Function SetAnnotations(ByVal annotations As SyntaxAnnotation()) As GreenNode")
_writer.Write(" Return new {0}", StructureTypeName(nodeStructure))
GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "annotations", "GetLeadingTrivia", "GetTrailingTrivia")
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate Update method . But only for non terminals
Private Sub GenerateUpdate(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then
Return
End If
Dim structureName = StructureTypeName(nodeStructure)
Dim factory = FactoryName(nodeStructure)
Dim needComma = False
_writer.Write(" Friend ")
If nodeStructure.ParentStructure IsNot Nothing AndAlso Not nodeStructure.ParentStructure.Abstract Then
_writer.Write("Shadows ")
End If
_writer.Write("Function Update(")
For Each child In GetAllChildrenOfStructure(nodeStructure)
If needComma Then
_writer.Write(", ")
End If
GenerateFactoryChildParameter(nodeStructure, child, Nothing, False)
needComma = True
Next
_writer.WriteLine(") As {0}", structureName)
needComma = False
_writer.Write(" If ")
For Each child In GetAllChildrenOfStructure(nodeStructure)
If needComma Then
_writer.Write(" OrElse ")
End If
If child.IsList OrElse KindTypeStructure(child.ChildKind).IsToken Then
_writer.Write("{0}.Node IsNot Me.{1}", ChildParamName(child), ChildVarName(child))
Else
_writer.Write("{0} IsNot Me.{1}", ChildParamName(child), ChildVarName(child))
End If
needComma = True
Next
_writer.WriteLine(" Then")
needComma = False
_writer.Write(" Return SyntaxFactory.{0}(", factory)
If nodeStructure.NodeKinds.Count >= 2 And Not _parseTree.NodeKinds.ContainsKey(FactoryName(nodeStructure)) Then
_writer.Write("Me.Kind, ")
End If
For Each child In GetAllChildrenOfStructure(nodeStructure)
If needComma Then
_writer.Write(", ")
End If
_writer.Write("{0}", ChildParamName(child))
needComma = True
Next
_writer.WriteLine(")")
_writer.WriteLine(" End If")
_writer.WriteLine(" Return Me")
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate WithTrivia method s
Private Sub GenerateWithTrivia(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) OrElse Not nodeStructure.IsToken Then
Return
End If
_writer.WriteLine(" Public Overrides Function WithLeadingTrivia(ByVal trivia As GreenNode) As GreenNode")
_writer.Write(" Return new {0}", StructureTypeName(nodeStructure))
GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "GetAnnotations", "trivia", "GetTrailingTrivia")
_writer.WriteLine(" End Function")
_writer.WriteLine()
_writer.WriteLine(" Public Overrides Function WithTrailingTrivia(ByVal trivia As GreenNode) As GreenNode")
_writer.Write(" Return new {0}", StructureTypeName(nodeStructure))
GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "GetAnnotations", "GetLeadingTrivia", "trivia")
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate GetChild, GetChildrenCount so members can be accessed by index
Private Sub GenerateGetChild(nodeStructure As ParseNodeStructure)
If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken Then
Return
End If
Dim allChildren = GetAllChildrenOfStructure(nodeStructure)
Dim childrenCount = allChildren.Count
If childrenCount = 0 Then
Return
End If
_writer.WriteLine(" Friend Overrides Function GetSlot(i as Integer) as GreenNode")
' Create the property accessor for each of the children
Dim children = allChildren
If childrenCount <> 1 Then
_writer.WriteLine(" Select case i")
For i = 0 To childrenCount - 1
_writer.WriteLine(" Case {0}", i)
_writer.WriteLine(" Return Me.{0}", ChildVarName(children(i)))
Next
_writer.WriteLine(" Case Else")
_writer.WriteLine(" Debug.Assert(false, ""child index out of range"")")
_writer.WriteLine(" Return Nothing")
_writer.WriteLine(" End Select")
Else
_writer.WriteLine(" If i = 0 Then")
_writer.WriteLine(" Return Me.{0}", ChildVarName(children(0)))
_writer.WriteLine(" Else")
_writer.WriteLine(" Debug.Assert(false, ""child index out of range"")")
_writer.WriteLine(" Return Nothing")
_writer.WriteLine(" End If")
End If
_writer.WriteLine(" End Function")
_writer.WriteLine()
'_writer.WriteLine(" Friend Overrides ReadOnly Property SlotCount() As Integer")
'_writer.WriteLine(" Get")
'_writer.WriteLine(" Return {0}", childrenCount)
'_writer.WriteLine(" End Get")
'_writer.WriteLine(" End Property")
_writer.WriteLine()
End Sub
' Generate IsTerminal property.
Private Sub GenerateIsTerminal(nodeStructure As ParseNodeStructure)
_writer.WriteLine(" Friend Overrides ReadOnly Property IsTerminal As Boolean")
_writer.WriteLine(" Get")
_writer.WriteLine(" Return {0}", If(nodeStructure.IsTerminal, "True", "False"))
_writer.WriteLine(" End Get")
_writer.WriteLine(" End Property")
_writer.WriteLine()
End Sub
Private Sub GenerateNodeStructureMembers(nodeStructure As ParseNodeStructure)
Dim fields = nodeStructure.Fields
For Each field In fields
_writer.WriteLine(" Friend ReadOnly {0} as {1}", FieldVarName(field), FieldTypeRef(field))
Next
Dim children = nodeStructure.Children
For Each child In children
_writer.WriteLine(" Friend ReadOnly {0} as {1}", ChildVarName(child), ChildFieldTypeRef(child, True))
Next
_writer.WriteLine()
End Sub
Private Sub GenerateNodeStructureSerialization(nodeStructure As ParseNodeStructure)
If nodeStructure.IsTokenRoot OrElse nodeStructure.IsTriviaRoot OrElse nodeStructure.IsPredefined OrElse nodeStructure.Name = "StructuredTriviaSyntax" Then
Return
End If
_writer.WriteLine(" Friend Sub New(reader as ObjectReader)")
_writer.WriteLine(" MyBase.New(reader)")
If Not nodeStructure.Abstract Then
Dim allChildren = GetAllChildrenOfStructure(nodeStructure)
Dim childrenCount = allChildren.Count
If childrenCount <> 0 Then
_writer.WriteLine(" MyBase._slotCount = {0}", childrenCount)
End If
End If
For Each child In nodeStructure.Children
_writer.WriteLine(" Dim {0} = DirectCast(reader.ReadValue(), {1})", ChildVarName(child), ChildFieldTypeRef(child, isGreen:=True))
_writer.WriteLine(" If {0} isnot Nothing ", ChildVarName(child))
_writer.WriteLine(" AdjustFlagsAndWidth({0})", ChildVarName(child))
_writer.WriteLine(" Me.{0} = {0}", ChildVarName(child))
_writer.WriteLine(" End If")
Next
For Each field In nodeStructure.Fields
_writer.WriteLine(" Me.{0} = CType(reader.{1}(), {2})", FieldVarName(field), ReaderMethod(FieldTypeRef(field)), FieldTypeRef(field))
Next
'TODO: BLUE
If StructureTypeName(nodeStructure) = "DirectiveTriviaSyntax" Then
_writer.WriteLine(" SetFlags(NodeFlags.ContainsDirectives)")
End If
_writer.WriteLine(" End Sub")
If Not nodeStructure.Abstract Then
' Friend Shared CreateInstance As Func(Of ObjectReader, Object) = Function(o) New BinaryExpressionSyntax(o)
_writer.WriteLine(" Friend Shared CreateInstance As Func(Of ObjectReader, Object) = Function(o) New {0}(o)", StructureTypeName(nodeStructure))
_writer.WriteLine()
End If
If nodeStructure.Children.Count > 0 OrElse nodeStructure.Fields.Count > 0 Then
_writer.WriteLine()
_writer.WriteLine(" Friend Overrides Sub WriteTo(writer as ObjectWriter)")
_writer.WriteLine(" MyBase.WriteTo(writer)")
For Each child In nodeStructure.Children
_writer.WriteLine(" writer.WriteValue(Me.{0})", ChildVarName(child))
Next
For Each field In nodeStructure.Fields
_writer.WriteLine(" writer.{0}(Me.{1})", WriterMethod(FieldTypeRef(field)), FieldVarName(field))
Next
_writer.WriteLine(" End Sub")
End If
If Not _parseTree.IsAbstract(nodeStructure) Then
_writer.WriteLine()
_writer.WriteLine(" Shared Sub New()")
_writer.WriteLine(" ObjectBinder.RegisterTypeReader(GetType({0}), Function(r) New {0}(r))", StructureTypeName(nodeStructure))
_writer.WriteLine(" End Sub")
End If
_writer.WriteLine()
End Sub
Private Function ReaderMethod(type As String) As String
Select Case type
Case "Integer", "SyntaxKind", "TypeCharacter"
Return "ReadInt32"
Case "Boolean"
Return "ReadBoolean"
Case Else
Return "ReadValue"
End Select
End Function
Private Function WriterMethod(type As String) As String
Select Case type
Case "Integer", "SyntaxKind", "TypeCharacter"
Return "WriteInt32"
Case "Boolean"
Return "WriteBoolean"
Case Else
Return "WriteValue"
End Select
End Function
' Generate constructor for a node structure
Private Sub GenerateNodeStructureConstructor(nodeStructure As ParseNodeStructure,
isRaw As Boolean,
Optional noExtra As Boolean = False,
Optional contextual As Boolean = False)
' these constructors are hardcoded
If nodeStructure.IsTokenRoot OrElse nodeStructure.IsTriviaRoot OrElse nodeStructure.Name = "StructuredTriviaSyntax" Then
Return
End If
If nodeStructure.ParentStructure Is Nothing Then
Return
End If
Dim allFields = GetAllFieldsOfStructure(nodeStructure)
_writer.Write(" Friend Sub New(")
' Generate each of the field parameters
_writer.Write("ByVal kind As {0}", NodeKindType())
If Not noExtra Then
_writer.Write(", ByVal errors as DiagnosticInfo(), ByVal annotations as SyntaxAnnotation()", NodeKindType())
End If
If nodeStructure.IsTerminal Then
' terminals have a text
_writer.Write(", text as String")
End If
If nodeStructure.IsToken Then
' tokens have trivia
_writer.Write(", leadingTrivia As GreenNode, trailingTrivia As GreenNode", StructureTypeName(_parseTree.RootStructure))
End If
For Each field In allFields
_writer.Write(", ")
GenerateNodeStructureFieldParameter(field)
Next
For Each child In GetAllChildrenOfStructure(nodeStructure)
_writer.Write(", ")
GenerateNodeStructureChildParameter(child, Nothing, True)
Next
If contextual Then
_writer.Write(", context As ISyntaxFactoryContext")
End If
_writer.WriteLine(")")
' Generate each of the field parameters
_writer.Write(" MyBase.New(kind", NodeKindType())
If Not noExtra Then
_writer.Write(", errors, annotations")
End If
If nodeStructure.IsToken AndAlso Not nodeStructure.IsTokenRoot Then
' nonterminals have text.
_writer.Write(", text")
If Not nodeStructure.IsTrivia Then
' tokens have trivia, but only if they are not trivia.
_writer.Write(", leadingTrivia, trailingTrivia")
End If
End If
Dim baseClass = nodeStructure.ParentStructure
If baseClass IsNot Nothing Then
For Each child In GetAllChildrenOfStructure(baseClass)
_writer.Write(", {0}", ChildParamName(child))
Next
End If
_writer.WriteLine(")")
If Not nodeStructure.Abstract Then
Dim allChildren = GetAllChildrenOfStructure(nodeStructure)
Dim childrenCount = allChildren.Count
If childrenCount <> 0 Then
_writer.WriteLine(" MyBase._slotCount = {0}", childrenCount)
End If
End If
' Generate code to initialize this class
If contextual Then
_writer.WriteLine(" Me.SetFactoryContext(context)")
End If
If allFields.Count > 0 Then
For i = 0 To allFields.Count - 1
_writer.WriteLine(" Me.{0} = {1}", FieldVarName(allFields(i)), FieldParamName(allFields(i)))
Next
End If
If nodeStructure.Children.Count > 0 Then
'_writer.WriteLine(" Dim fullWidth as integer")
_writer.WriteLine()
For Each child In nodeStructure.Children
Dim indent = ""
If child.IsOptional OrElse child.IsList Then
'If endKeyword IsNot Nothing Then
_writer.WriteLine(" If {0} IsNot Nothing Then", ChildParamName(child))
indent = " "
End If
'_writer.WriteLine("{0} fullWidth += {1}.FullWidth", indent, ChildParamName(child))
_writer.WriteLine("{0} AdjustFlagsAndWidth({1})", indent, ChildParamName(child))
_writer.WriteLine("{0} Me.{1} = {2}", indent, ChildVarName(child), ChildParamName(child))
If child.IsOptional OrElse child.IsList Then
'If endKeyword IsNot Nothing Then
_writer.WriteLine(" End If", ChildParamName(child))
End If
Next
'_writer.WriteLine(" Me._fullWidth += fullWidth")
_writer.WriteLine()
End If
'TODO: BLUE
If StructureTypeName(nodeStructure) = "DirectiveTriviaSyntax" Then
_writer.WriteLine(" SetFlags(NodeFlags.ContainsDirectives)")
End If
' Generate End Sub
_writer.WriteLine(" End Sub")
_writer.WriteLine()
End Sub
Private Sub GenerateNodeStructureConstructorParameters(nodeStructure As ParseNodeStructure, errorParam As String, annotationParam As String, precedingTriviaParam As String, followingTriviaParam As String)
' Generate each of the field parameters
_writer.Write("(Me.Kind")
_writer.Write(", {0}", errorParam)
_writer.Write(", {0}", annotationParam)
If nodeStructure.IsToken Then
' nonterminals have text.
_writer.Write(", text")
If Not nodeStructure.IsTrivia Then
' tokens have trivia, but only if they are not trivia.
_writer.Write(", {0}, {1}", precedingTriviaParam, followingTriviaParam)
End If
ElseIf nodeStructure.IsTrivia AndAlso nodeStructure.IsTriviaRoot Then
_writer.Write(", Me.Text")
End If
For Each field In GetAllFieldsOfStructure(nodeStructure)
_writer.Write(", {0}", FieldVarName(field))
Next
For Each child In GetAllChildrenOfStructure(nodeStructure)
_writer.Write(", {0}", ChildVarName(child))
Next
_writer.WriteLine(")")
End Sub
' Generate a parameter corresponding to a node structure field
Private Sub GenerateNodeStructureFieldParameter(field As ParseNodeField, Optional conflictName As String = Nothing)
_writer.Write("{0} As {1}", FieldParamName(field, conflictName), FieldTypeRef(field))
End Sub
' Generate a parameter corresponding to a node structure child
Private Sub GenerateNodeStructureChildParameter(child As ParseNodeChild, Optional conflictName As String = Nothing, Optional isGreen As Boolean = False)
_writer.Write("{0} As {1}", ChildParamName(child, conflictName), ChildConstructorTypeRef(child, isGreen))
End Sub
' Generate a parameter corresponding to a node structure child
Private Sub GenerateFactoryChildParameter(node As ParseNodeStructure, child As ParseNodeChild, Optional conflictName As String = Nothing, Optional internalForm As Boolean = False)
_writer.Write("{0} As {1}", ChildParamName(child, conflictName), ChildFactoryTypeRef(node, child, True, internalForm))
End Sub
' Get modifiers
Private Function GetModifiers(containingStructure As ParseNodeStructure, isOverride As Boolean, name As String) As String
' Is this overridable or an override?
Dim modifiers = ""
'If isOverride Then
' modifiers = "Overrides"
'ElseIf containingStructure.HasDerivedStructure Then
' modifiers = "Overridable"
'End If
' Put Shadows modifier on if useful.
' Object has Equals and GetType
' root name has members for every kind and structure (factory methods)
If (name = "Equals" OrElse name = "GetType") Then 'OrElse _parseTree.NodeKinds.ContainsKey(name) OrElse _parseTree.NodeStructures.ContainsKey(name)) Then
modifiers = "Shadows " + modifiers
End If
Return modifiers
End Function
' Generate a public property for a node field
Private Sub GenerateNodeFieldProperty(field As ParseNodeField, fieldIndex As Integer, isOverride As Boolean)
' XML comment
GenerateXmlComment(_writer, field, 8)
_writer.WriteLine(" Friend {2} ReadOnly Property {0} As {1}", FieldPropertyName(field), FieldTypeRef(field), GetModifiers(field.ContainingStructure, isOverride, field.Name))
_writer.WriteLine(" Get")
_writer.WriteLine(" Return Me.{0}", FieldVarName(field))
_writer.WriteLine(" End Get")
_writer.WriteLine(" End Property")
_writer.WriteLine("")
End Sub
' Generate a public property for a child
Private Sub GenerateNodeChildProperty(node As ParseNodeStructure, child As ParseNodeChild, childIndex As Integer)
' XML comment
GenerateXmlComment(_writer, child, 8)
Dim isToken = KindTypeStructure(child.ChildKind).IsToken
_writer.WriteLine(" Friend {2} ReadOnly Property {0} As {1}", ChildPropertyName(child), ChildPropertyTypeRef(node, child, True), GetModifiers(child.ContainingStructure, False, child.Name))
_writer.WriteLine(" Get")
If Not child.IsList Then
_writer.WriteLine(" Return Me.{0}", ChildVarName(child))
ElseIf child.IsSeparated Then
_writer.WriteLine(" Return new {0}(New Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList(of {1})(Me.{2}))", ChildPropertyTypeRef(node, child, True), BaseTypeReference(child), ChildVarName(child))
ElseIf KindTypeStructure(child.ChildKind).IsToken Then
_writer.WriteLine(" Return New Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList(of GreenNode)(Me.{1})", BaseTypeReference(child), ChildVarName(child))
Else
_writer.WriteLine(" Return new {0}(Me.{1})", ChildPropertyTypeRef(node, child, True), ChildVarName(child))
End If
_writer.WriteLine(" End Get")
_writer.WriteLine(" End Property")
_writer.WriteLine("")
End Sub
' Generate a public property for a child
Private Sub GenerateNodeWithChildProperty(withChild As ParseNodeChild, childIndex As Integer, nodeStructure As ParseNodeStructure)
Dim isOverride As Boolean = withChild.ContainingStructure IsNot nodeStructure
If withChild.GenerateWith Then
Dim isAbstract As Boolean = _parseTree.IsAbstract(nodeStructure)
If Not isAbstract Then
' XML comment
GenerateWithXmlComment(_writer, withChild, 8)
_writer.WriteLine(" Friend {2} Function {0}({3} as {4}) As {1}", ChildWithFunctionName(withChild), StructureTypeName(withChild.ContainingStructure), GetModifiers(withChild.ContainingStructure, isOverride, withChild.Name), Ident(UpperFirstCharacter(withChild.Name)), ChildConstructorTypeRef(withChild))
_writer.WriteLine(" Ensures(Result(Of {0}) IsNot Nothing)", StructureTypeName(withChild.ContainingStructure))
_writer.Write(" return New {0}(", StructureTypeName(nodeStructure))
_writer.Write("Kind, Green.Errors")
Dim allFields = GetAllFieldsOfStructure(nodeStructure)
If allFields.Count > 0 Then
For i = 0 To allFields.Count - 1
_writer.Write(", {0}", FieldParamName(allFields(i)))
Next
End If
For Each child In nodeStructure.Children
If child IsNot withChild Then
_writer.Write(", {0}", ChildParamName(child))
Else
_writer.Write(", {0}", Ident(UpperFirstCharacter(child.Name)))
End If
Next
_writer.WriteLine(")")
_writer.WriteLine(" End Function")
ElseIf nodeStructure.Children.Contains(withChild) Then
' XML comment
GenerateWithXmlComment(_writer, withChild, 8)
_writer.WriteLine(" Friend {2} Function {0}({3} as {4}) As {1}", ChildWithFunctionName(withChild), StructureTypeName(withChild.ContainingStructure), "MustOverride", Ident(UpperFirstCharacter(withChild.Name)), ChildConstructorTypeRef(withChild))
End If
_writer.WriteLine("")
End If
End Sub
' Generate public properties for a child that is a separated list
Private Sub GenerateAccept(nodeStructure As ParseNodeStructure)
If nodeStructure.ParentStructure IsNot Nothing AndAlso (_parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia) Then
Return
End If
_writer.WriteLine(" Public {0} Function Accept(ByVal visitor As {1}) As VisualBasicSyntaxNode", If(IsRoot(nodeStructure), "Overridable", "Overrides"), _parseTree.VisitorName)
_writer.WriteLine(" Return visitor.{0}(Me)", VisitorMethodName(nodeStructure))
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
' Generate special methods and properties for the root node. These only appear in the root node.
Private Sub GenerateRootNodeSpecialMethods(nodeStructure As ParseNodeStructure)
_writer.WriteLine()
End Sub
' Generate the Visitor class definition
Private Sub GenerateVisitorClass()
_writer.WriteLine(" Friend MustInherit Class {0}", Ident(_parseTree.VisitorName))
' Basic Visit method that dispatches.
_writer.WriteLine(" Public Overridable Function Visit(ByVal node As {0}) As VisualBasicSyntaxNode", StructureTypeName(_parseTree.RootStructure))
_writer.WriteLine(" If node IsNot Nothing")
_writer.WriteLine(" Return node.Accept(Me)")
_writer.WriteLine(" Else")
_writer.WriteLine(" Return Nothing")
_writer.WriteLine(" End If")
_writer.WriteLine(" End Function")
For Each nodeStructure In _parseTree.NodeStructures.Values
GenerateVisitorMethod(nodeStructure)
Next
_writer.WriteLine(" End Class")
_writer.WriteLine()
End Sub
' Generate a method in the Visitor class
Private Sub GenerateVisitorMethod(nodeStructure As ParseNodeStructure)
If nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then
Return
End If
Dim methodName = VisitorMethodName(nodeStructure)
Dim structureName = StructureTypeName(nodeStructure)
_writer.WriteLine(" Public Overridable Function {0}(ByVal node As {1}) As VisualBasicSyntaxNode",
methodName,
structureName)
_writer.WriteLine(" Debug.Assert(node IsNot Nothing)")
If Not IsRoot(nodeStructure) Then
_writer.WriteLine(" Return {0}(node)", VisitorMethodName(nodeStructure.ParentStructure))
Else
_writer.WriteLine(" Return node")
End If
_writer.WriteLine(" End Function")
End Sub
' Generate the RewriteVisitor class definition
Private Sub GenerateRewriteVisitorClass()
_writer.WriteLine(" Friend MustInherit Class {0}", Ident(_parseTree.RewriteVisitorName))
_writer.WriteLine(" Inherits {0}", Ident(_parseTree.VisitorName), StructureTypeName(_parseTree.RootStructure))
_writer.WriteLine()
For Each nodeStructure In _parseTree.NodeStructures.Values
GenerateRewriteVisitorMethod(nodeStructure)
Next
_writer.WriteLine(" End Class")
_writer.WriteLine()
End Sub
' Generate a method in the RewriteVisitor class
Private Sub GenerateRewriteVisitorMethod(nodeStructure As ParseNodeStructure)
If nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then
Return
End If
If nodeStructure.Abstract Then
' do nothing for abstract nodes
Return
End If
Dim methodName = VisitorMethodName(nodeStructure)
Dim structureName = StructureTypeName(nodeStructure)
_writer.WriteLine(" Public Overrides Function {0}(ByVal node As {1}) As {2}",
methodName,
structureName,
StructureTypeName(_parseTree.RootStructure))
' non-abstract non-terminals need to rewrite their children and recreate as needed.
Dim allFields = GetAllFieldsOfStructure(nodeStructure)
Dim allChildren = GetAllChildrenOfStructure(nodeStructure)
' create anyChanges variable
_writer.WriteLine(" Dim anyChanges As Boolean = False")
_writer.WriteLine()
' visit all children
For i = 0 To allChildren.Count - 1
If allChildren(i).IsList Then
_writer.WriteLine(" Dim {0} = VisitList(node.{1})" + vbCrLf +
" If node.{2} IsNot {0}.Node Then anyChanges = True",
ChildNewVarName(allChildren(i)), ChildPropertyName(allChildren(i)), ChildVarName(allChildren(i)))
ElseIf KindTypeStructure(allChildren(i).ChildKind).IsToken Then
_writer.WriteLine(" Dim {0} = DirectCast(Visit(node.{2}), {1})" + vbCrLf +
" If node.{3} IsNot {0} Then anyChanges = True",
ChildNewVarName(allChildren(i)), BaseTypeReference(allChildren(i)), ChildPropertyName(allChildren(i)), ChildVarName(allChildren(i)))
Else
_writer.WriteLine(" Dim {0} = DirectCast(Visit(node.{2}), {1})" + vbCrLf +
" If node.{2} IsNot {0} Then anyChanges = True",
ChildNewVarName(allChildren(i)), ChildPropertyTypeRef(nodeStructure, allChildren(i)), ChildVarName(allChildren(i)))
End If
Next
_writer.WriteLine()
' check if any changes.
_writer.WriteLine(" If anyChanges Then")
_writer.Write(" Return New {0}(node.Kind", StructureTypeName(nodeStructure))
_writer.Write(", node.GetDiagnostics, node.GetAnnotations")
For Each field In allFields
_writer.Write(", node.{0}", FieldPropertyName(field))
Next
For Each child In allChildren
If child.IsList Then
_writer.Write(", {0}.Node", ChildNewVarName(child))
ElseIf KindTypeStructure(child.ChildKind).IsToken Then
_writer.Write(", {0}", ChildNewVarName(child))
Else
_writer.Write(", {0}", ChildNewVarName(child))
End If
Next
_writer.WriteLine(")")
_writer.WriteLine(" Else")
_writer.WriteLine(" Return node")
_writer.WriteLine(" End If")
_writer.WriteLine(" End Function")
_writer.WriteLine()
End Sub
End Class
|
#Region "Microsoft.VisualBasic::d65445f67976c5d9470b8a3ab0b384b8, mzkit\src\metadb\Massbank\Public\TMIC\HMDB\Tables\ChemicalDescriptor.vb"
' Author:
'
' xieguigang ([email protected], BioNovoGene Co., LTD.)
'
' Copyright (c) 2018 [email protected], 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:
' Code Statistics:
' Total Lines: 151
' Code Lines: 126
' Comment Lines: 12
' Blank Lines: 13
' File Size: 6.82 KB
' Class ChemicalDescriptor
'
' Properties: acceptor_count, accession, bioavailability, descriptors, donor_count
' formal_charge, ghose_filter, kegg_id, logp, mddr_like_rule
' melting_point, name, number_of_rings, physiological_charge, pka_strongest_acidic
' pka_strongest_basic, polar_surface_area, polarizability, refractivity, rotatable_bond_count
' rule_of_five, state, veber_rule
'
' Constructor: (+1 Overloads) Sub New
'
' Function: FromMetabolite, ToDescriptor
'
' Sub: WriteTable
'
'
' /********************************************************************************/
#End Region
Imports System.IO
Imports System.Reflection
Imports Microsoft.VisualBasic.ComponentModel.Collection
Imports Microsoft.VisualBasic.ComponentModel.DataSourceModel
Imports Microsoft.VisualBasic.Data.csv.IO.Linq
Namespace TMIC.HMDB
Public Class ChemicalDescriptor
''' <summary>
''' HMDB main accession
''' </summary>
''' <returns></returns>
Public Property accession As String
Public Property name As String
Public Property kegg_id As String
Public Property state As String
Public Property melting_point As Double
Public Property logp As Double
Public Property pka_strongest_acidic As Double
Public Property pka_strongest_basic As Double
Public Property polar_surface_area As Double
Public Property refractivity As Double
Public Property polarizability As Double
Public Property rotatable_bond_count As Double
Public Property acceptor_count As Double
Public Property donor_count As Double
Public Property physiological_charge As Double
Public Property formal_charge As Double
Public Property number_of_rings As Double
Public Property bioavailability As Double
Public Property rule_of_five As String
Public Property ghose_filter As String
Public Property veber_rule As String
Public Property mddr_like_rule As String
''' <summary>
''' The chemical descriptor names
''' </summary>
''' <returns></returns>
Public Shared ReadOnly Property descriptors As Index(Of String)
Shared ReadOnly readers As PropertyInfo()
Shared Sub New()
readers = DataFramework _
.Schema(GetType(ChemicalDescriptor), PropertyAccess.Readable, nonIndex:=True) _
.Values _
.ToArray
descriptors = readers _
.Where(Function(p)
Return p.PropertyType Is GetType(Double)
End Function) _
.Select(Function(p) p.Name) _
.AsList + {
NameOf(state),
NameOf(rule_of_five),
NameOf(ghose_filter),
NameOf(veber_rule),
NameOf(mddr_like_rule)
}
readers = readers _
.Where(Function(p) p.Name Like descriptors) _
.ToArray
End Sub
''' <summary>
''' Create descriptor data set for machine learning
''' </summary>
''' <returns></returns>
Public Function ToDescriptor() As Dictionary(Of String, Double)
Return readers _
.ToDictionary(Function(p) p.Name,
Function(p)
Dim value As Object = p.GetValue(Me)
If p.PropertyType Is GetType(Double) Then
Return CDbl(value)
ElseIf p.Name = NameOf(state) Then
If CStr(value).TextEquals("Solid") Then
Return 1
Else
Return 0
End If
Else
If CStr(value).ParseBoolean = False Then
Return 0
Else
Return 1
End If
End If
End Function)
End Function
Public Shared Function FromMetabolite(metabolite As metabolite) As ChemicalDescriptor
Dim properties = metabolite.experimental_properties.PropertyList.AsList +
metabolite.predicted_properties.PropertyList
Dim propertyTable As Dictionary(Of String, String) = properties _
.GroupBy(Function(p) p.kind) _
.ToDictionary(Function(p) p.Key,
Function(g)
If g.Any(Function(f) IsBooleanFactor(f.value)) Then
Return g.Select(Function(x) x.value).TopMostFrequent
Else
Return g.Select(Function(x) Val(x.value)) _
.Average _
.ToString
End If
End Function)
Dim read = Function(key As String, default$) As String
Return propertyTable.TryGetValue(key, [default]:=[default])
End Function
Return New ChemicalDescriptor With {
.accession = metabolite.accession,
.name = metabolite.name,
.kegg_id = metabolite.kegg_id,
.state = metabolite.state,
.acceptor_count = read(NameOf(.acceptor_count), 0),
.bioavailability = read(NameOf(.bioavailability), 0),
.donor_count = read(NameOf(.donor_count), 0),
.formal_charge = read(NameOf(.formal_charge), 0),
.ghose_filter = read(NameOf(.ghose_filter), "no"),
.logp = read(NameOf(.logp), 0),
.mddr_like_rule = read(NameOf(.mddr_like_rule), "no"),
.melting_point = read(NameOf(melting_point), 0),
.number_of_rings = read(NameOf(.number_of_rings), 0),
.physiological_charge = read(NameOf(.physiological_charge), 0),
.pka_strongest_acidic = read(NameOf(.pka_strongest_acidic), 0),
.pka_strongest_basic = read(NameOf(.pka_strongest_basic), 0),
.polarizability = read(NameOf(.polarizability), 0),
.polar_surface_area = read(NameOf(.polar_surface_area), 0),
.refractivity = read(NameOf(.refractivity), 0),
.rotatable_bond_count = read(NameOf(.rotatable_bond_count), 0),
.rule_of_five = read(NameOf(.rule_of_five), "no"),
.veber_rule = read(NameOf(.veber_rule), "no")
}
End Function
Public Shared Sub WriteTable(metabolites As IEnumerable(Of metabolite), out As Stream)
Using table As New WriteStream(Of ChemicalDescriptor)(New StreamWriter(out))
For Each metabolite As metabolite In metabolites
Call table.Flush(FromMetabolite(metabolite))
Next
End Using
End Sub
End Class
End Namespace
|
Public Class UserControl1
End Class
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class SplashScreen1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
Friend WithEvents ApplicationTitle As System.Windows.Forms.Label
Friend WithEvents Version As System.Windows.Forms.Label
Friend WithEvents Copyright As System.Windows.Forms.Label
Friend WithEvents MainLayoutPanel As System.Windows.Forms.TableLayoutPanel
Friend WithEvents DetailsLayoutPanel As System.Windows.Forms.TableLayoutPanel
Friend WithEvents UserName As System.Windows.Forms.Label
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(SplashScreen1))
Me.MainLayoutPanel = New System.Windows.Forms.TableLayoutPanel()
Me.DetailsLayoutPanel = New System.Windows.Forms.TableLayoutPanel()
Me.ApplicationTitle = New System.Windows.Forms.Label()
Me.Copyright = New System.Windows.Forms.Label()
Me.UserName = New System.Windows.Forms.Label()
Me.Version = New System.Windows.Forms.Label()
Me.MainLayoutPanel.SuspendLayout()
Me.DetailsLayoutPanel.SuspendLayout()
Me.SuspendLayout()
'
'MainLayoutPanel
'
Me.MainLayoutPanel.BackgroundImage = CType(resources.GetObject("MainLayoutPanel.BackgroundImage"), System.Drawing.Image)
Me.MainLayoutPanel.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch
Me.MainLayoutPanel.ColumnCount = 2
Me.MainLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 314.0!))
Me.MainLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 265.0!))
Me.MainLayoutPanel.Controls.Add(Me.DetailsLayoutPanel, 0, 1)
Me.MainLayoutPanel.Controls.Add(Me.ApplicationTitle, 1, 1)
Me.MainLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill
Me.MainLayoutPanel.Location = New System.Drawing.Point(0, 0)
Me.MainLayoutPanel.Name = "MainLayoutPanel"
Me.MainLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 285.0!))
Me.MainLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 22.0!))
Me.MainLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.MainLayoutPanel.Size = New System.Drawing.Size(579, 350)
Me.MainLayoutPanel.TabIndex = 0
'
'DetailsLayoutPanel
'
Me.DetailsLayoutPanel.Anchor = System.Windows.Forms.AnchorStyles.None
Me.DetailsLayoutPanel.BackColor = System.Drawing.Color.White
Me.DetailsLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 308.0!))
Me.DetailsLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
Me.DetailsLayoutPanel.Controls.Add(Me.Version, 0, 0)
Me.DetailsLayoutPanel.Controls.Add(Me.UserName, 0, 1)
Me.DetailsLayoutPanel.Controls.Add(Me.Copyright, 0, 2)
Me.DetailsLayoutPanel.Location = New System.Drawing.Point(3, 288)
Me.DetailsLayoutPanel.Name = "DetailsLayoutPanel"
Me.DetailsLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.0!))
Me.DetailsLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.0!))
Me.DetailsLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 34.0!))
Me.DetailsLayoutPanel.Size = New System.Drawing.Size(308, 58)
Me.DetailsLayoutPanel.TabIndex = 1
'
'Version
'
Me.Version.Anchor = System.Windows.Forms.AnchorStyles.Left
Me.Version.AutoSize = True
Me.Version.BackColor = System.Drawing.Color.White
Me.Version.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point)
Me.Version.Location = New System.Drawing.Point(3, 2)
Me.Version.Name = "Version"
Me.Version.Size = New System.Drawing.Size(140, 15)
Me.Version.TabIndex = 1
Me.Version.Text = "Version: {0}.{1:00}.{2}.{3}"
Me.Version.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'UserName
'
Me.UserName.Anchor = System.Windows.Forms.AnchorStyles.Left
Me.UserName.AutoSize = True
Me.UserName.BackColor = System.Drawing.Color.White
Me.UserName.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point)
Me.UserName.Location = New System.Drawing.Point(3, 21)
Me.UserName.Name = "UserName"
Me.UserName.Size = New System.Drawing.Size(69, 15)
Me.UserName.TabIndex = 2
Me.UserName.Text = "User Name"
Me.UserName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'Copyright
'
Me.Copyright.Anchor = System.Windows.Forms.AnchorStyles.Left
Me.Copyright.AutoSize = True
Me.Copyright.BackColor = System.Drawing.Color.White
Me.Copyright.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point)
Me.Copyright.Location = New System.Drawing.Point(3, 40)
Me.Copyright.Name = "Copyright"
Me.Copyright.Size = New System.Drawing.Size(61, 15)
Me.Copyright.TabIndex = 2
Me.Copyright.Text = "Copyright"
Me.Copyright.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'ApplicationTitle
'
Me.ApplicationTitle.AutoSize = True
Me.ApplicationTitle.BackColor = System.Drawing.Color.Transparent
Me.ApplicationTitle.Dock = System.Windows.Forms.DockStyle.Bottom
Me.ApplicationTitle.Font = New System.Drawing.Font("Segoe UI", 15.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point)
Me.ApplicationTitle.ForeColor = System.Drawing.SystemColors.MenuHighlight
Me.ApplicationTitle.Location = New System.Drawing.Point(317, 320)
Me.ApplicationTitle.Name = "ApplicationTitle"
Me.ApplicationTitle.Size = New System.Drawing.Size(259, 30)
Me.ApplicationTitle.TabIndex = 0
Me.ApplicationTitle.Text = "Application Title"
Me.ApplicationTitle.TextAlign = System.Drawing.ContentAlignment.MiddleRight
'
'SplashScreen1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(579, 350)
Me.ControlBox = False
Me.Controls.Add(Me.MainLayoutPanel)
Me.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.Name = "SplashScreen1"
Me.ShowInTaskbar = False
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.MainLayoutPanel.ResumeLayout(False)
Me.MainLayoutPanel.PerformLayout()
Me.DetailsLayoutPanel.ResumeLayout(False)
Me.DetailsLayoutPanel.PerformLayout()
Me.ResumeLayout(False)
End Sub
End Class
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.Ammo_Keeper.My.MySettings
Get
Return Global.Ammo_Keeper.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements
Public Class LoopKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub LoopNotInMethodBody()
VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Loop")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub LoopNotInLambda()
VerifyRecommendationsMissing(<MethodBody>
Dim x = Sub()
|
End Sub</MethodBody>, "Loop")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub LoopNotAfterStatement()
VerifyRecommendationsMissing(<MethodBody>
Dim x
|</MethodBody>, "Loop")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub LoopAfterDoStatement()
VerifyRecommendationsContain(<MethodBody>
Do
|</MethodBody>, "Loop", "Loop Until", "Loop While")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub LoopAfterDoUntilStatement()
VerifyRecommendationsContain(<MethodBody>
Do Until True
|</MethodBody>, "Loop")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub LoopUntilNotAfterDoUntilStatement()
VerifyRecommendationsMissing(<MethodBody>
Do Until True
|</MethodBody>, "Loop Until", "Loop While")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub LoopNotInDoLoopUntilBlock()
VerifyRecommendationsMissing(<MethodBody>
Do
|
Loop Until True</MethodBody>, "Loop")
End Sub
End Class
End Namespace
|
' 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.Diagnostics
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Formatting.Rules
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
' the default provider that will be called by the engine at the end of provider's chain.
' there is no way for a user to be remove this provider.
'
' to reduce number of unnecessary heap allocations, most of them just return null.
Friend NotInheritable Class DefaultOperationProvider
Inherits CompatAbstractFormattingRule
Public Shared ReadOnly Instance As New DefaultOperationProvider()
Private ReadOnly _options As CachedOptions
Private Sub New()
MyClass.New(New CachedOptions(Nothing))
End Sub
Private Sub New(options As CachedOptions)
_options = options
End Sub
Public Overrides Function WithOptions(options As AnalyzerConfigOptions) As AbstractFormattingRule
Dim cachedOptions = New CachedOptions(options)
If cachedOptions = _options Then
Return Me
End If
Return New DefaultOperationProvider(cachedOptions)
End Function
Public Overrides Sub AddSuppressOperationsSlow(operations As List(Of SuppressOperation), node As SyntaxNode, ByRef nextAction As NextSuppressOperationAction)
End Sub
Public Overrides Sub AddAnchorIndentationOperationsSlow(operations As List(Of AnchorIndentationOperation), node As SyntaxNode, ByRef nextAction As NextAnchorIndentationOperationAction)
End Sub
Public Overrides Sub AddIndentBlockOperationsSlow(operations As List(Of IndentBlockOperation), node As SyntaxNode, ByRef nextAction As NextIndentBlockOperationAction)
End Sub
Public Overrides Sub AddAlignTokensOperationsSlow(operations As List(Of AlignTokensOperation), node As SyntaxNode, ByRef nextAction As NextAlignTokensOperationAction)
End Sub
<PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowCaptures:=False, AllowImplicitBoxing:=False)>
Public Overrides Function GetAdjustNewLinesOperationSlow(
ByRef previousToken As SyntaxToken,
ByRef currentToken As SyntaxToken,
ByRef nextOperation As NextGetAdjustNewLinesOperation) As AdjustNewLinesOperation
If previousToken.Parent Is Nothing Then
Return Nothing
End If
Dim combinedTrivia = (previousToken.TrailingTrivia, currentToken.LeadingTrivia)
Dim lastTrivia = LastOrDefaultTrivia(
combinedTrivia,
Function(trivia As SyntaxTrivia) ColonOrLineContinuationTrivia(trivia))
If lastTrivia.RawKind = SyntaxKind.ColonTrivia Then
Return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines)
ElseIf lastTrivia.RawKind = SyntaxKind.LineContinuationTrivia AndAlso previousToken.Parent.GetAncestorsOrThis(Of SyntaxNode)().Any(Function(node As SyntaxNode) IsSingleLineIfOrElseClauseSyntax(node)) Then
Return Nothing
End If
' return line break operation after statement terminator token so that we can enforce
' indentation for the line
Dim previousStatement As StatementSyntax = Nothing
If previousToken.IsLastTokenOfStatement(statement:=previousStatement) AndAlso ContainEndOfLine(previousToken, currentToken) AndAlso currentToken.Kind <> SyntaxKind.EmptyToken Then
Return AdjustNewLinesBetweenStatements(previousStatement, currentToken)
End If
If previousToken.Kind = SyntaxKind.GreaterThanToken AndAlso previousToken.Parent IsNot Nothing AndAlso TypeOf previousToken.Parent Is AttributeListSyntax Then
' This AttributeList is the last applied attribute
' If this AttributeList belongs to a parameter then apply no line operation
If previousToken.Parent.Parent IsNot Nothing AndAlso TypeOf previousToken.Parent.Parent Is ParameterSyntax Then
Return Nothing
End If
Return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines)
End If
If currentToken.Kind = SyntaxKind.LessThanToken AndAlso currentToken.Parent IsNot Nothing AndAlso TypeOf currentToken.Parent Is AttributeListSyntax Then
' The case of the previousToken belonging to another AttributeList is handled in the previous condition
If (previousToken.Kind = SyntaxKind.CommaToken OrElse previousToken.Kind = SyntaxKind.OpenParenToken) AndAlso
currentToken.Parent.Parent IsNot Nothing AndAlso TypeOf currentToken.Parent.Parent Is ParameterSyntax Then
Return Nothing
End If
Return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines)
End If
' return line break operation after xml tag token so that we can enforce indentation for the xml tag
' the very first xml literal tag case
If IsFirstXmlTag(currentToken) Then
Return Nothing
End If
Dim xmlDeclaration = TryCast(previousToken.Parent, XmlDeclarationSyntax)
If xmlDeclaration IsNot Nothing AndAlso xmlDeclaration.GetLastToken(includeZeroWidth:=True) = previousToken Then
Return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines)
End If
If TypeOf previousToken.Parent Is XmlNodeSyntax OrElse TypeOf currentToken.Parent Is XmlNodeSyntax Then
Return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines)
End If
Return Nothing
End Function
Private Function AdjustNewLinesBetweenStatements(
previousStatement As StatementSyntax,
currentToken As SyntaxToken) As AdjustNewLinesOperation
' if the user is separating import-groups, And we're between two imports, and these
' imports *should* be separated, then do so (if the imports were already properly
' sorted).
If currentToken.Kind() = SyntaxKind.ImportsKeyword AndAlso
TypeOf currentToken.Parent Is ImportsStatementSyntax AndAlso
TypeOf previousStatement Is ImportsStatementSyntax Then
Dim previousImports = DirectCast(previousStatement, ImportsStatementSyntax)
Dim currentImports = DirectCast(currentToken.Parent, ImportsStatementSyntax)
If _options.SeparateImportDirectiveGroups AndAlso
ImportsOrganizer.NeedsGrouping(previousImports, currentImports) Then
Dim [imports] = DirectCast(previousImports.Parent, CompilationUnitSyntax).Imports
If [imports].IsSorted(ImportsStatementComparer.SystemFirstInstance) OrElse
[imports].IsSorted(ImportsStatementComparer.NormalInstance) Then
' Force at least one blank line here.
Return FormattingOperations.CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.PreserveLines)
End If
End If
End If
' For any other two statements we will normally ensure at least one new-line between
' them.
Return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines)
End Function
Private Shared Function IsSingleLineIfOrElseClauseSyntax(node As SyntaxNode) As Boolean
Return TypeOf node Is SingleLineIfStatementSyntax OrElse TypeOf node Is SingleLineElseClauseSyntax
End Function
Private Shared Function ColonOrLineContinuationTrivia(trivia As SyntaxTrivia) As Boolean
Return trivia.RawKind = SyntaxKind.ColonTrivia OrElse trivia.RawKind = SyntaxKind.LineContinuationTrivia
End Function
<PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowCaptures:=False, AllowImplicitBoxing:=False)>
Private Shared Function LastOrDefaultTrivia(triviaListPair As (SyntaxTriviaList, SyntaxTriviaList), predicate As Func(Of SyntaxTrivia, Boolean)) As SyntaxTrivia
For Each trivia In triviaListPair.Item2.Reverse()
If predicate(trivia) Then
Return trivia
End If
Next
For Each trivia In triviaListPair.Item1.Reverse()
If predicate(trivia) Then
Return trivia
End If
Next
Return Nothing
End Function
Private Shared Function ContainEndOfLine(previousToken As SyntaxToken, nextToken As SyntaxToken) As Boolean
Return previousToken.TrailingTrivia.Any(SyntaxKind.EndOfLineTrivia) OrElse nextToken.LeadingTrivia.Any(SyntaxKind.EndOfLineTrivia)
End Function
Private Shared Function IsFirstXmlTag(currentToken As SyntaxToken) As Boolean
Dim xmlDeclaration = TryCast(currentToken.Parent, XmlDeclarationSyntax)
If xmlDeclaration IsNot Nothing AndAlso
xmlDeclaration.LessThanQuestionToken = currentToken AndAlso
TypeOf xmlDeclaration.Parent Is XmlDocumentSyntax AndAlso
Not TypeOf xmlDeclaration.Parent.Parent Is XmlNodeSyntax Then
Return True
End If
Dim startTag = TryCast(currentToken.Parent, XmlElementStartTagSyntax)
If startTag IsNot Nothing AndAlso
startTag.LessThanToken = currentToken AndAlso
TypeOf startTag.Parent Is XmlElementSyntax AndAlso
Not TypeOf startTag.Parent.Parent Is XmlNodeSyntax Then
Return True
End If
Dim emptyTag = TryCast(currentToken.Parent, XmlEmptyElementSyntax)
If emptyTag IsNot Nothing AndAlso
emptyTag.LessThanToken = currentToken AndAlso
Not TypeOf emptyTag.Parent Is XmlNodeSyntax Then
Return True
End If
Return False
End Function
' return 1 space for every token pairs as a default operation
Public Overrides Function GetAdjustSpacesOperationSlow(ByRef previousToken As SyntaxToken, ByRef currentToken As SyntaxToken, ByRef nextOperation As NextGetAdjustSpacesOperation) As AdjustSpacesOperation
If previousToken.Kind = SyntaxKind.ColonToken AndAlso
TypeOf previousToken.Parent Is LabelStatementSyntax AndAlso
currentToken.Kind <> SyntaxKind.EndOfFileToken Then
Return FormattingOperations.CreateAdjustSpacesOperation(1, AdjustSpacesOption.DynamicSpaceToIndentationIfOnSingleLine)
End If
Dim space As Integer = If(currentToken.Kind = SyntaxKind.EndOfFileToken, 0, 1)
Return FormattingOperations.CreateAdjustSpacesOperation(space, AdjustSpacesOption.DefaultSpacesIfOnSingleLine)
End Function
Private Structure CachedOptions
Implements IEquatable(Of CachedOptions)
Public ReadOnly SeparateImportDirectiveGroups As Boolean
Public Sub New(options As AnalyzerConfigOptions)
SeparateImportDirectiveGroups = GetOptionOrDefault(options, GenerationOptions.SeparateImportDirectiveGroups)
End Sub
Public Shared Operator =(left As CachedOptions, right As CachedOptions) As Boolean
Return left.Equals(right)
End Operator
Public Shared Operator <>(left As CachedOptions, right As CachedOptions) As Boolean
Return Not left = right
End Operator
Private Shared Function GetOptionOrDefault(Of T)(options As AnalyzerConfigOptions, [option] As PerLanguageOption2(Of T)) As T
If options Is Nothing Then
Return [option].DefaultValue
End If
Return options.GetOption([option])
End Function
Public Overrides Function Equals(obj As Object) As Boolean
Return (TypeOf obj Is CachedOptions) AndAlso Equals(DirectCast(obj, CachedOptions))
End Function
Public Overloads Function Equals(other As CachedOptions) As Boolean Implements IEquatable(Of CachedOptions).Equals
Return SeparateImportDirectiveGroups = other.SeparateImportDirectiveGroups
End Function
Public Overrides Function GetHashCode() As Integer
Dim hashCode = 0
hashCode = (hashCode << 1) + If(SeparateImportDirectiveGroups, 1, 0)
Return hashCode
End Function
End Structure
End Class
End Namespace
|
Imports Microsoft.VisualC
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Namespace std
<DebugInfoInPDB(), MiscellaneousBits(64), NativeCppClass()>
<StructLayout(LayoutKind.Sequential, Size = 3)>
Friend Structure _Tree_ptr<std::_Tmap_traits<unsigned long,Mvsn::DeadLetterBox::MVSN_DEAD_DROP_STRUCT *,std::less<unsigned long>,std::allocator<std::pair<unsigned long const ,Mvsn::DeadLetterBox::MVSN_DEAD_DROP_STRUCT *> >,0> >
End Structure
<DebugInfoInPDB(), MiscellaneousBits(64), NativeCppClass()>
<StructLayout(LayoutKind.Sequential, Size = 3)>
Friend Structure _Tree_ptr<std::_Tmap_traits<unsigned long,unsigned long,std::less<unsigned long>,std::allocator<std::pair<unsigned long const ,unsigned long> >,0> >
End Structure
<DebugInfoInPDB(), MiscellaneousBits(64), NativeCppClass()>
<StructLayout(LayoutKind.Sequential, Size = 3)>
Friend Structure _Tree_ptr<std::_Tset_traits<unsigned long,std::less<unsigned long>,std::allocator<unsigned long>,0> >
End Structure
End Namespace
|
' Copyright 2018 Google LLC
'
' Licensed under the Apache License, Version 2.0 (the "License")
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http:'www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201806
Imports Google.Api.Ads.Common.Util
Namespace Google.Api.Ads.AdWords.Examples.VB.v201806
''' <summary>
''' This code example adds an HTML5 ad to a given ad group. To get ad
''' groups, run GetAdGroups.vb.
''' </summary>
Public Class AddHtml5Ad
Inherits ExampleBase
''' <summary>
''' Main method, to run this code example as a standalone application.
''' </summary>
''' <param name="args">The command line arguments.</param>
Public Shared Sub Main(ByVal args As String())
Dim codeExample As New AddHtml5Ad
Console.WriteLine(codeExample.Description)
Try
Dim adGroupId As Long = Long.Parse("INSERT_ADGROUP_ID_HERE")
codeExample.Run(New AdWordsUser(), adGroupId)
Catch e As Exception
Console.WriteLine("An exception occurred while running this code example. {0}",
ExampleUtilities.FormatException(e))
End Try
End Sub
''' <summary>
''' Returns a description about the code example.
''' </summary>
Public Overrides ReadOnly Property Description() As String
Get
Return "This code example adds an HTML5 ad to a given ad group. To get ad" &
"groups, run GetAdGroups.vb."
End Get
End Property
''' <summary>
''' Runs the code example.
''' </summary>
''' <param name="user">The AdWords user.</param>
''' <param name="adGroupId">Id of the first adgroup to which ad is added.</param>
Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long)
Using adGroupAdService As AdGroupAdService = CType(user.GetService(
AdWordsService.v201806.AdGroupAdService), AdGroupAdService)
' Create the HTML5 template ad. See
' https://developers.google.com/adwords/api/docs/guides/template-ads#html5_ads
' for more details.
Dim html5Ad As New TemplateAd()
html5Ad.name = "Ad for HTML5"
html5Ad.templateId = 419
html5Ad.finalUrls = New String() {"http://example.com/html5"}
html5Ad.displayUrl = "www.example.com/html5"
html5Ad.dimensions = New Dimensions()
html5Ad.dimensions.width = 300
html5Ad.dimensions.height = 250
' The HTML5 zip file contains all the HTML, CSS, and images needed for the
' HTML5 ad. For help on creating an HTML5 zip file, check out Google Web
' Designer (https://www.google.com/webdesigner/).
Dim html5Zip As Byte() = MediaUtilities.GetAssetDataFromUrl("https://goo.gl/9Y7qI2",
user.Config)
' Create a media bundle containing the zip file with all the HTML5 components.
Dim mediaBundle As New MediaBundle()
' You may also upload an HTML5 zip using MediaService.upload() method
' set the mediaId field. See UploadMediaBundle.vb for an example on how to
' upload HTML5 zip files.
mediaBundle.data = html5Zip
mediaBundle.entryPoint = "carousel/index.html"
mediaBundle.type = MediaMediaType.MEDIA_BUNDLE
' Create the template elements for the ad. You can refer to
' https://developers.google.com/adwords/api/docs/appendix/templateads
' for the list of available template fields.
Dim adData As New TemplateElement
adData.uniqueName = "adData"
Dim customLayout As New TemplateElementField
customLayout.name = "Custom_layout"
customLayout.fieldMedia = mediaBundle
customLayout.type = TemplateElementFieldType.MEDIA_BUNDLE
Dim layout As New TemplateElementField
layout.name = "layout"
layout.fieldText = "Custom"
layout.type = TemplateElementFieldType.ENUM
adData.fields = New TemplateElementField() {customLayout, layout}
html5Ad.templateElements = New TemplateElement() {adData}
' Create the AdGroupAd.
Dim html5AdGroupAd As New AdGroupAd()
html5AdGroupAd.adGroupId = adGroupId
html5AdGroupAd.ad = html5Ad
' Additional properties (non-required).
html5AdGroupAd.status = AdGroupAdStatus.PAUSED
Dim adGroupAdOperation As New AdGroupAdOperation()
adGroupAdOperation.operator = [Operator].ADD
adGroupAdOperation.operand = html5AdGroupAd
Try
' Add HTML5 ad.
Dim result As AdGroupAdReturnValue =
adGroupAdService.mutate(New AdGroupAdOperation() {adGroupAdOperation})
' Display results.
If (Not result Is Nothing) AndAlso (Not result.value Is Nothing) AndAlso
(result.value.Length > 0) Then
For Each adGroupAd As AdGroupAd In result.value
Console.WriteLine("New HTML5 ad with id '{0}' and display url '{1}' was added.",
adGroupAd.ad.id, adGroupAd.ad.displayUrl)
Next
Else
Console.WriteLine("No HTML5 ads were added.")
End If
Catch e As Exception
Throw New System.ApplicationException("Failed to create HTML5 ad.", e)
End Try
End Using
End Sub
End Class
End Namespace
|
Imports CodeCracker.VisualBasic.Design
Imports Xunit
Namespace Design
Public Class EmptyCatchBlockTests
Inherits CodeFixVerifier(Of EmptyCatchBlockAnalyzer, EmptyCatchBlockCodeFixProvider)
Private test As String = "
Imports System
Namespace ConsoleApplication1
Class TypeName
Public Sub Foo()
Try
Dim a = ""A""
Catch
End Try
End Sub
End Class
End Namespace"
<Fact>
Public Async Function EmptyCatchBlockAnalyzerCreateDiagnostic() As Task
Const testWithBlock = "
Imports System
Namespace ConsoleApplication1
Class TypeName
Public Sub Foo()
Try
Dim a = ""A""
Catch
Throw
End Try
End Sub
End Class
End Namespace"
Await VerifyBasicHasNoDiagnosticsAsync(testWithBlock)
End Function
<Fact>
Public Async Function WhenRemoveTryCatchStatement() As Task
Const fix = "
Imports System
Namespace ConsoleApplication1
Class TypeName
Public Sub Foo()
Dim a = ""A""
End Sub
End Class
End Namespace"
Await VerifyBasicFixAsync(test, fix)
End Function
<Fact>
Public Async Function WhenPutExceptionClassInCatchBlock() As Task
Const fix = "
Imports System
Namespace ConsoleApplication1
Class TypeName
Public Sub Foo()
Try
Dim a = ""A""
Catch ex As Exception
Throw
End Try
End Sub
End Class
End Namespace"
Await VerifyBasicFixAsync(test, fix, 1)
End Function
<Fact>
Public Async Function WhenMultipleCatchRemoveOnlySelectedEmpty() As Task
Const multipleTest As String = "
Imports System
Namespace ConsoleApplication1
Class TypeName
Public Async Function Foo() As Task
Try
Dim a = ""A""
Catch aex As ArgumentException
Catch ex As Exception
a = ""B""
End Try
End Function
End Class
End Namespace"
Const multipleFix = "
Imports System
Namespace ConsoleApplication1
Class TypeName
Public Async Function Foo() As Task
Try
Dim a = ""A""
Catch ex As Exception
a = ""B""
End Try
End Function
End Class
End Namespace"
Await VerifyBasicFixAsync(multipleTest, multipleFix, 0)
End Function
End Class
End Namespace |
Imports System.Data.OleDb
Public Class RegisterBookTransaction
Private Sub RegisterBookTransaction_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con = New OleDbConnection(ConnectionString)
OleConnection(sql)
Me.coolgreeterLabel.Text = LoginForm.cool_name
End Sub
Public fullname, librarian As String
Private Sub BorrowerButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BorrowerButton.Click
BorrowersForm.Show()
End Sub
Private Sub LibraryButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LibraryButton.Click
LibraryForm.Show()
End Sub
Private Sub TransactionsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TransactionsButton.Click
TransactionForm.Show()
End Sub
Private Sub LogoutButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LogoutButton.Click
End
End Sub
End Class
|
'------------------------------------------------------------------------------
' <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 Off
Option Explicit On
'''<summary>
'''Represents a strongly typed in-memory cache of data.
'''</summary>
<Global.System.Serializable(), _
Global.System.ComponentModel.DesignerCategoryAttribute("code"), _
Global.System.ComponentModel.ToolboxItem(true), _
Global.System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema"), _
Global.System.Xml.Serialization.XmlRootAttribute("STOCKDataSet9"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")> _
Partial Public Class STOCKDataSet9
Inherits Global.System.Data.DataSet
Private tableSTOCK As STOCKDataTable
Private _schemaSerializationMode As Global.System.Data.SchemaSerializationMode = Global.System.Data.SchemaSerializationMode.IncludeSchema
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New()
MyBase.New
Me.BeginInit
Me.InitClass
Dim schemaChangedHandler As Global.System.ComponentModel.CollectionChangeEventHandler = AddressOf Me.SchemaChanged
AddHandler MyBase.Tables.CollectionChanged, schemaChangedHandler
AddHandler MyBase.Relations.CollectionChanged, schemaChangedHandler
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Sub New(ByVal info As Global.System.Runtime.Serialization.SerializationInfo, ByVal context As Global.System.Runtime.Serialization.StreamingContext)
MyBase.New(info, context, false)
If (Me.IsBinarySerialized(info, context) = true) Then
Me.InitVars(false)
Dim schemaChangedHandler1 As Global.System.ComponentModel.CollectionChangeEventHandler = AddressOf Me.SchemaChanged
AddHandler Me.Tables.CollectionChanged, schemaChangedHandler1
AddHandler Me.Relations.CollectionChanged, schemaChangedHandler1
Return
End If
Dim strSchema As String = CType(info.GetValue("XmlSchema", GetType(String)),String)
If (Me.DetermineSchemaSerializationMode(info, context) = Global.System.Data.SchemaSerializationMode.IncludeSchema) Then
Dim ds As Global.System.Data.DataSet = New Global.System.Data.DataSet()
ds.ReadXmlSchema(New Global.System.Xml.XmlTextReader(New Global.System.IO.StringReader(strSchema)))
If (Not (ds.Tables("STOCK")) Is Nothing) Then
MyBase.Tables.Add(New STOCKDataTable(ds.Tables("STOCK")))
End If
Me.DataSetName = ds.DataSetName
Me.Prefix = ds.Prefix
Me.Namespace = ds.Namespace
Me.Locale = ds.Locale
Me.CaseSensitive = ds.CaseSensitive
Me.EnforceConstraints = ds.EnforceConstraints
Me.Merge(ds, false, Global.System.Data.MissingSchemaAction.Add)
Me.InitVars
Else
Me.ReadXmlSchema(New Global.System.Xml.XmlTextReader(New Global.System.IO.StringReader(strSchema)))
End If
Me.GetSerializationData(info, context)
Dim schemaChangedHandler As Global.System.ComponentModel.CollectionChangeEventHandler = AddressOf Me.SchemaChanged
AddHandler MyBase.Tables.CollectionChanged, schemaChangedHandler
AddHandler Me.Relations.CollectionChanged, schemaChangedHandler
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false), _
Global.System.ComponentModel.DesignerSerializationVisibility(Global.System.ComponentModel.DesignerSerializationVisibility.Content)> _
Public ReadOnly Property STOCK() As STOCKDataTable
Get
Return Me.tableSTOCK
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.BrowsableAttribute(true), _
Global.System.ComponentModel.DesignerSerializationVisibilityAttribute(Global.System.ComponentModel.DesignerSerializationVisibility.Visible)> _
Public Overrides Property SchemaSerializationMode() As Global.System.Data.SchemaSerializationMode
Get
Return Me._schemaSerializationMode
End Get
Set
Me._schemaSerializationMode = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.DesignerSerializationVisibilityAttribute(Global.System.ComponentModel.DesignerSerializationVisibility.Hidden)> _
Public Shadows ReadOnly Property Tables() As Global.System.Data.DataTableCollection
Get
Return MyBase.Tables
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.DesignerSerializationVisibilityAttribute(Global.System.ComponentModel.DesignerSerializationVisibility.Hidden)> _
Public Shadows ReadOnly Property Relations() As Global.System.Data.DataRelationCollection
Get
Return MyBase.Relations
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub InitializeDerivedDataSet()
Me.BeginInit
Me.InitClass
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overrides Function Clone() As Global.System.Data.DataSet
Dim cln As STOCKDataSet9 = CType(MyBase.Clone,STOCKDataSet9)
cln.InitVars
cln.SchemaSerializationMode = Me.SchemaSerializationMode
Return cln
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function ShouldSerializeTables() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function ShouldSerializeRelations() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub ReadXmlSerializable(ByVal reader As Global.System.Xml.XmlReader)
If (Me.DetermineSchemaSerializationMode(reader) = Global.System.Data.SchemaSerializationMode.IncludeSchema) Then
Me.Reset
Dim ds As Global.System.Data.DataSet = New Global.System.Data.DataSet()
ds.ReadXml(reader)
If (Not (ds.Tables("STOCK")) Is Nothing) Then
MyBase.Tables.Add(New STOCKDataTable(ds.Tables("STOCK")))
End If
Me.DataSetName = ds.DataSetName
Me.Prefix = ds.Prefix
Me.Namespace = ds.Namespace
Me.Locale = ds.Locale
Me.CaseSensitive = ds.CaseSensitive
Me.EnforceConstraints = ds.EnforceConstraints
Me.Merge(ds, false, Global.System.Data.MissingSchemaAction.Add)
Me.InitVars
Else
Me.ReadXml(reader)
Me.InitVars
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function GetSchemaSerializable() As Global.System.Xml.Schema.XmlSchema
Dim stream As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Me.WriteXmlSchema(New Global.System.Xml.XmlTextWriter(stream, Nothing))
stream.Position = 0
Return Global.System.Xml.Schema.XmlSchema.Read(New Global.System.Xml.XmlTextReader(stream), Nothing)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Overloads Sub InitVars()
Me.InitVars(true)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Overloads Sub InitVars(ByVal initTable As Boolean)
Me.tableSTOCK = CType(MyBase.Tables("STOCK"),STOCKDataTable)
If (initTable = true) Then
If (Not (Me.tableSTOCK) Is Nothing) Then
Me.tableSTOCK.InitVars
End If
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitClass()
Me.DataSetName = "STOCKDataSet9"
Me.Prefix = ""
Me.Namespace = "http://tempuri.org/STOCKDataSet9.xsd"
Me.EnforceConstraints = true
Me.SchemaSerializationMode = Global.System.Data.SchemaSerializationMode.IncludeSchema
Me.tableSTOCK = New STOCKDataTable()
MyBase.Tables.Add(Me.tableSTOCK)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function ShouldSerializeSTOCK() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub SchemaChanged(ByVal sender As Object, ByVal e As Global.System.ComponentModel.CollectionChangeEventArgs)
If (e.Action = Global.System.ComponentModel.CollectionChangeAction.Remove) Then
Me.InitVars
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Shared Function GetTypedDataSetSchema(ByVal xs As Global.System.Xml.Schema.XmlSchemaSet) As Global.System.Xml.Schema.XmlSchemaComplexType
Dim ds As STOCKDataSet9 = New STOCKDataSet9()
Dim type As Global.System.Xml.Schema.XmlSchemaComplexType = New Global.System.Xml.Schema.XmlSchemaComplexType()
Dim sequence As Global.System.Xml.Schema.XmlSchemaSequence = New Global.System.Xml.Schema.XmlSchemaSequence()
Dim any As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny()
any.Namespace = ds.Namespace
sequence.Items.Add(any)
type.Particle = sequence
Dim dsSchema As Global.System.Xml.Schema.XmlSchema = ds.GetSchemaSerializable
If xs.Contains(dsSchema.TargetNamespace) Then
Dim s1 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Dim s2 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Try
Dim schema As Global.System.Xml.Schema.XmlSchema = Nothing
dsSchema.Write(s1)
Dim schemas As Global.System.Collections.IEnumerator = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator
Do While schemas.MoveNext
schema = CType(schemas.Current,Global.System.Xml.Schema.XmlSchema)
s2.SetLength(0)
schema.Write(s2)
If (s1.Length = s2.Length) Then
s1.Position = 0
s2.Position = 0
Do While ((s1.Position <> s1.Length) _
AndAlso (s1.ReadByte = s2.ReadByte))
Loop
If (s1.Position = s1.Length) Then
Return type
End If
End If
Loop
Finally
If (Not (s1) Is Nothing) Then
s1.Close
End If
If (Not (s2) Is Nothing) Then
s2.Close
End If
End Try
End If
xs.Add(dsSchema)
Return type
End Function
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Delegate Sub STOCKRowChangeEventHandler(ByVal sender As Object, ByVal e As STOCKRowChangeEvent)
'''<summary>
'''Represents the strongly named DataTable class.
'''</summary>
<Global.System.Serializable(), _
Global.System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")> _
Partial Public Class STOCKDataTable
Inherits Global.System.Data.TypedTableBase(Of STOCKRow)
Private columnID As Global.System.Data.DataColumn
Private columnNAME As Global.System.Data.DataColumn
Private columnMFDDATE As Global.System.Data.DataColumn
Private columnQUANTITY As Global.System.Data.DataColumn
Private columnPRICE As Global.System.Data.DataColumn
Private columnAMOUNT As Global.System.Data.DataColumn
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New()
MyBase.New
Me.TableName = "STOCK"
Me.BeginInit
Me.InitClass
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub New(ByVal table As Global.System.Data.DataTable)
MyBase.New
Me.TableName = table.TableName
If (table.CaseSensitive <> table.DataSet.CaseSensitive) Then
Me.CaseSensitive = table.CaseSensitive
End If
If (table.Locale.ToString <> table.DataSet.Locale.ToString) Then
Me.Locale = table.Locale
End If
If (table.Namespace <> table.DataSet.Namespace) Then
Me.Namespace = table.Namespace
End If
Me.Prefix = table.Prefix
Me.MinimumCapacity = table.MinimumCapacity
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Sub New(ByVal info As Global.System.Runtime.Serialization.SerializationInfo, ByVal context As Global.System.Runtime.Serialization.StreamingContext)
MyBase.New(info, context)
Me.InitVars
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property IDColumn() As Global.System.Data.DataColumn
Get
Return Me.columnID
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property NAMEColumn() As Global.System.Data.DataColumn
Get
Return Me.columnNAME
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property MFDDATEColumn() As Global.System.Data.DataColumn
Get
Return Me.columnMFDDATE
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property QUANTITYColumn() As Global.System.Data.DataColumn
Get
Return Me.columnQUANTITY
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property PRICEColumn() As Global.System.Data.DataColumn
Get
Return Me.columnPRICE
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property AMOUNTColumn() As Global.System.Data.DataColumn
Get
Return Me.columnAMOUNT
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false)> _
Public ReadOnly Property Count() As Integer
Get
Return Me.Rows.Count
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Default ReadOnly Property Item(ByVal index As Integer) As STOCKRow
Get
Return CType(Me.Rows(index),STOCKRow)
End Get
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event STOCKRowChanging As STOCKRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event STOCKRowChanged As STOCKRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event STOCKRowDeleting As STOCKRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event STOCKRowDeleted As STOCKRowChangeEventHandler
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overloads Sub AddSTOCKRow(ByVal row As STOCKRow)
Me.Rows.Add(row)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overloads Function AddSTOCKRow(ByVal NAME As String, ByVal MFDDATE As String, ByVal QUANTITY As Integer, ByVal PRICE As Integer, ByVal AMOUNT As Integer) As STOCKRow
Dim rowSTOCKRow As STOCKRow = CType(Me.NewRow,STOCKRow)
Dim columnValuesArray() As Object = New Object() {Nothing, NAME, MFDDATE, QUANTITY, PRICE, AMOUNT}
rowSTOCKRow.ItemArray = columnValuesArray
Me.Rows.Add(rowSTOCKRow)
Return rowSTOCKRow
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overrides Function Clone() As Global.System.Data.DataTable
Dim cln As STOCKDataTable = CType(MyBase.Clone,STOCKDataTable)
cln.InitVars
Return cln
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function CreateInstance() As Global.System.Data.DataTable
Return New STOCKDataTable()
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub InitVars()
Me.columnID = MyBase.Columns("ID")
Me.columnNAME = MyBase.Columns("NAME")
Me.columnMFDDATE = MyBase.Columns("MFDDATE")
Me.columnQUANTITY = MyBase.Columns("QUANTITY")
Me.columnPRICE = MyBase.Columns("PRICE")
Me.columnAMOUNT = MyBase.Columns("AMOUNT")
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitClass()
Me.columnID = New Global.System.Data.DataColumn("ID", GetType(Integer), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnID)
Me.columnNAME = New Global.System.Data.DataColumn("NAME", GetType(String), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnNAME)
Me.columnMFDDATE = New Global.System.Data.DataColumn("MFDDATE", GetType(String), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnMFDDATE)
Me.columnQUANTITY = New Global.System.Data.DataColumn("QUANTITY", GetType(Integer), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnQUANTITY)
Me.columnPRICE = New Global.System.Data.DataColumn("PRICE", GetType(Integer), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnPRICE)
Me.columnAMOUNT = New Global.System.Data.DataColumn("AMOUNT", GetType(Integer), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnAMOUNT)
Me.columnID.AutoIncrement = true
Me.columnID.AutoIncrementSeed = -1
Me.columnID.AutoIncrementStep = -1
Me.columnID.AllowDBNull = false
Me.columnID.ReadOnly = true
Me.columnNAME.MaxLength = 2147483647
Me.columnMFDDATE.MaxLength = 2147483647
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function NewSTOCKRow() As STOCKRow
Return CType(Me.NewRow,STOCKRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function NewRowFromBuilder(ByVal builder As Global.System.Data.DataRowBuilder) As Global.System.Data.DataRow
Return New STOCKRow(builder)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function GetRowType() As Global.System.Type
Return GetType(STOCKRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowChanged(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowChanged(e)
If (Not (Me.STOCKRowChangedEvent) Is Nothing) Then
RaiseEvent STOCKRowChanged(Me, New STOCKRowChangeEvent(CType(e.Row,STOCKRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowChanging(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowChanging(e)
If (Not (Me.STOCKRowChangingEvent) Is Nothing) Then
RaiseEvent STOCKRowChanging(Me, New STOCKRowChangeEvent(CType(e.Row,STOCKRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowDeleted(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowDeleted(e)
If (Not (Me.STOCKRowDeletedEvent) Is Nothing) Then
RaiseEvent STOCKRowDeleted(Me, New STOCKRowChangeEvent(CType(e.Row,STOCKRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowDeleting(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowDeleting(e)
If (Not (Me.STOCKRowDeletingEvent) Is Nothing) Then
RaiseEvent STOCKRowDeleting(Me, New STOCKRowChangeEvent(CType(e.Row,STOCKRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub RemoveSTOCKRow(ByVal row As STOCKRow)
Me.Rows.Remove(row)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Shared Function GetTypedTableSchema(ByVal xs As Global.System.Xml.Schema.XmlSchemaSet) As Global.System.Xml.Schema.XmlSchemaComplexType
Dim type As Global.System.Xml.Schema.XmlSchemaComplexType = New Global.System.Xml.Schema.XmlSchemaComplexType()
Dim sequence As Global.System.Xml.Schema.XmlSchemaSequence = New Global.System.Xml.Schema.XmlSchemaSequence()
Dim ds As STOCKDataSet9 = New STOCKDataSet9()
Dim any1 As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny()
any1.Namespace = "http://www.w3.org/2001/XMLSchema"
any1.MinOccurs = New Decimal(0)
any1.MaxOccurs = Decimal.MaxValue
any1.ProcessContents = Global.System.Xml.Schema.XmlSchemaContentProcessing.Lax
sequence.Items.Add(any1)
Dim any2 As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny()
any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"
any2.MinOccurs = New Decimal(1)
any2.ProcessContents = Global.System.Xml.Schema.XmlSchemaContentProcessing.Lax
sequence.Items.Add(any2)
Dim attribute1 As Global.System.Xml.Schema.XmlSchemaAttribute = New Global.System.Xml.Schema.XmlSchemaAttribute()
attribute1.Name = "namespace"
attribute1.FixedValue = ds.Namespace
type.Attributes.Add(attribute1)
Dim attribute2 As Global.System.Xml.Schema.XmlSchemaAttribute = New Global.System.Xml.Schema.XmlSchemaAttribute()
attribute2.Name = "tableTypeName"
attribute2.FixedValue = "STOCKDataTable"
type.Attributes.Add(attribute2)
type.Particle = sequence
Dim dsSchema As Global.System.Xml.Schema.XmlSchema = ds.GetSchemaSerializable
If xs.Contains(dsSchema.TargetNamespace) Then
Dim s1 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Dim s2 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Try
Dim schema As Global.System.Xml.Schema.XmlSchema = Nothing
dsSchema.Write(s1)
Dim schemas As Global.System.Collections.IEnumerator = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator
Do While schemas.MoveNext
schema = CType(schemas.Current,Global.System.Xml.Schema.XmlSchema)
s2.SetLength(0)
schema.Write(s2)
If (s1.Length = s2.Length) Then
s1.Position = 0
s2.Position = 0
Do While ((s1.Position <> s1.Length) _
AndAlso (s1.ReadByte = s2.ReadByte))
Loop
If (s1.Position = s1.Length) Then
Return type
End If
End If
Loop
Finally
If (Not (s1) Is Nothing) Then
s1.Close
End If
If (Not (s2) Is Nothing) Then
s2.Close
End If
End Try
End If
xs.Add(dsSchema)
Return type
End Function
End Class
'''<summary>
'''Represents strongly named DataRow class.
'''</summary>
Partial Public Class STOCKRow
Inherits Global.System.Data.DataRow
Private tableSTOCK As STOCKDataTable
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub New(ByVal rb As Global.System.Data.DataRowBuilder)
MyBase.New(rb)
Me.tableSTOCK = CType(Me.Table,STOCKDataTable)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property ID() As Integer
Get
Return CType(Me(Me.tableSTOCK.IDColumn),Integer)
End Get
Set
Me(Me.tableSTOCK.IDColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property NAME() As String
Get
Try
Return CType(Me(Me.tableSTOCK.NAMEColumn),String)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'NAME' in table 'STOCK' is DBNull.", e)
End Try
End Get
Set
Me(Me.tableSTOCK.NAMEColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property MFDDATE() As String
Get
Try
Return CType(Me(Me.tableSTOCK.MFDDATEColumn),String)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'MFDDATE' in table 'STOCK' is DBNull.", e)
End Try
End Get
Set
Me(Me.tableSTOCK.MFDDATEColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property QUANTITY() As Integer
Get
Try
Return CType(Me(Me.tableSTOCK.QUANTITYColumn),Integer)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'QUANTITY' in table 'STOCK' is DBNull.", e)
End Try
End Get
Set
Me(Me.tableSTOCK.QUANTITYColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property PRICE() As Integer
Get
Try
Return CType(Me(Me.tableSTOCK.PRICEColumn),Integer)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'PRICE' in table 'STOCK' is DBNull.", e)
End Try
End Get
Set
Me(Me.tableSTOCK.PRICEColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property AMOUNT() As Integer
Get
Try
Return CType(Me(Me.tableSTOCK.AMOUNTColumn),Integer)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'AMOUNT' in table 'STOCK' is DBNull.", e)
End Try
End Get
Set
Me(Me.tableSTOCK.AMOUNTColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function IsNAMENull() As Boolean
Return Me.IsNull(Me.tableSTOCK.NAMEColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub SetNAMENull()
Me(Me.tableSTOCK.NAMEColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function IsMFDDATENull() As Boolean
Return Me.IsNull(Me.tableSTOCK.MFDDATEColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub SetMFDDATENull()
Me(Me.tableSTOCK.MFDDATEColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function IsQUANTITYNull() As Boolean
Return Me.IsNull(Me.tableSTOCK.QUANTITYColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub SetQUANTITYNull()
Me(Me.tableSTOCK.QUANTITYColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function IsPRICENull() As Boolean
Return Me.IsNull(Me.tableSTOCK.PRICEColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub SetPRICENull()
Me(Me.tableSTOCK.PRICEColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function IsAMOUNTNull() As Boolean
Return Me.IsNull(Me.tableSTOCK.AMOUNTColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub SetAMOUNTNull()
Me(Me.tableSTOCK.AMOUNTColumn) = Global.System.Convert.DBNull
End Sub
End Class
'''<summary>
'''Row event argument class
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Class STOCKRowChangeEvent
Inherits Global.System.EventArgs
Private eventRow As STOCKRow
Private eventAction As Global.System.Data.DataRowAction
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New(ByVal row As STOCKRow, ByVal action As Global.System.Data.DataRowAction)
MyBase.New
Me.eventRow = row
Me.eventAction = action
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Row() As STOCKRow
Get
Return Me.eventRow
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Action() As Global.System.Data.DataRowAction
Get
Return Me.eventAction
End Get
End Property
End Class
End Class
Namespace STOCKDataSet9TableAdapters
'''<summary>
'''Represents the connection and commands used to retrieve and save data.
'''</summary>
<Global.System.ComponentModel.DesignerCategoryAttribute("code"), _
Global.System.ComponentModel.ToolboxItem(true), _
Global.System.ComponentModel.DataObjectAttribute(true), _
Global.System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterDesigner, Microsoft.VSDesigner"& _
", Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Partial Public Class STOCKTableAdapter
Inherits Global.System.ComponentModel.Component
Private WithEvents _adapter As Global.System.Data.SqlClient.SqlDataAdapter
Private _connection As Global.System.Data.SqlClient.SqlConnection
Private _transaction As Global.System.Data.SqlClient.SqlTransaction
Private _commandCollection() As Global.System.Data.SqlClient.SqlCommand
Private _clearBeforeFill As Boolean
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New()
MyBase.New
Me.ClearBeforeFill = true
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Friend ReadOnly Property Adapter() As Global.System.Data.SqlClient.SqlDataAdapter
Get
If (Me._adapter Is Nothing) Then
Me.InitAdapter
End If
Return Me._adapter
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Property Connection() As Global.System.Data.SqlClient.SqlConnection
Get
If (Me._connection Is Nothing) Then
Me.InitConnection
End If
Return Me._connection
End Get
Set
Me._connection = value
If (Not (Me.Adapter.InsertCommand) Is Nothing) Then
Me.Adapter.InsertCommand.Connection = value
End If
If (Not (Me.Adapter.DeleteCommand) Is Nothing) Then
Me.Adapter.DeleteCommand.Connection = value
End If
If (Not (Me.Adapter.UpdateCommand) Is Nothing) Then
Me.Adapter.UpdateCommand.Connection = value
End If
Dim i As Integer = 0
Do While (i < Me.CommandCollection.Length)
If (Not (Me.CommandCollection(i)) Is Nothing) Then
CType(Me.CommandCollection(i),Global.System.Data.SqlClient.SqlCommand).Connection = value
End If
i = (i + 1)
Loop
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Property Transaction() As Global.System.Data.SqlClient.SqlTransaction
Get
Return Me._transaction
End Get
Set
Me._transaction = value
Dim i As Integer = 0
Do While (i < Me.CommandCollection.Length)
Me.CommandCollection(i).Transaction = Me._transaction
i = (i + 1)
Loop
If ((Not (Me.Adapter) Is Nothing) _
AndAlso (Not (Me.Adapter.DeleteCommand) Is Nothing)) Then
Me.Adapter.DeleteCommand.Transaction = Me._transaction
End If
If ((Not (Me.Adapter) Is Nothing) _
AndAlso (Not (Me.Adapter.InsertCommand) Is Nothing)) Then
Me.Adapter.InsertCommand.Transaction = Me._transaction
End If
If ((Not (Me.Adapter) Is Nothing) _
AndAlso (Not (Me.Adapter.UpdateCommand) Is Nothing)) Then
Me.Adapter.UpdateCommand.Transaction = Me._transaction
End If
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected ReadOnly Property CommandCollection() As Global.System.Data.SqlClient.SqlCommand()
Get
If (Me._commandCollection Is Nothing) Then
Me.InitCommandCollection
End If
Return Me._commandCollection
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property ClearBeforeFill() As Boolean
Get
Return Me._clearBeforeFill
End Get
Set
Me._clearBeforeFill = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitAdapter()
Me._adapter = New Global.System.Data.SqlClient.SqlDataAdapter()
Dim tableMapping As Global.System.Data.Common.DataTableMapping = New Global.System.Data.Common.DataTableMapping()
tableMapping.SourceTable = "Table"
tableMapping.DataSetTable = "STOCK"
tableMapping.ColumnMappings.Add("ID", "ID")
tableMapping.ColumnMappings.Add("NAME", "NAME")
tableMapping.ColumnMappings.Add("MFDDATE", "MFDDATE")
tableMapping.ColumnMappings.Add("QUANTITY", "QUANTITY")
tableMapping.ColumnMappings.Add("PRICE", "PRICE")
tableMapping.ColumnMappings.Add("AMOUNT", "AMOUNT")
Me._adapter.TableMappings.Add(tableMapping)
Me._adapter.InsertCommand = New Global.System.Data.SqlClient.SqlCommand()
Me._adapter.InsertCommand.Connection = Me.Connection
Me._adapter.InsertCommand.CommandText = "INSERT INTO [dbo].[STOCK] ([NAME], [MFDDATE], [QUANTITY], [PRICE], [AMOUNT]) VALU"& _
"ES (@NAME, @MFDDATE, @QUANTITY, @PRICE, @AMOUNT)"
Me._adapter.InsertCommand.CommandType = Global.System.Data.CommandType.Text
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@NAME", Global.System.Data.SqlDbType.NVarChar, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "NAME", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@MFDDATE", Global.System.Data.SqlDbType.NVarChar, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "MFDDATE", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@QUANTITY", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "QUANTITY", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@PRICE", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "PRICE", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
Me._adapter.InsertCommand.Parameters.Add(New Global.System.Data.SqlClient.SqlParameter("@AMOUNT", Global.System.Data.SqlDbType.Int, 0, Global.System.Data.ParameterDirection.Input, 0, 0, "AMOUNT", Global.System.Data.DataRowVersion.Current, false, Nothing, "", "", ""))
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitConnection()
Me._connection = New Global.System.Data.SqlClient.SqlConnection()
Me._connection.ConnectionString = Global.STOCK_MANAGEMENT_SYSTEM.My.MySettings.Default.STOCKConnectionString
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitCommandCollection()
Me._commandCollection = New Global.System.Data.SqlClient.SqlCommand(0) {}
Me._commandCollection(0) = New Global.System.Data.SqlClient.SqlCommand()
Me._commandCollection(0).Connection = Me.Connection
Me._commandCollection(0).CommandText = "SELECT ID, NAME, MFDDATE, QUANTITY, PRICE, AMOUNT FROM dbo.STOCK"
Me._commandCollection(0).CommandType = Global.System.Data.CommandType.Text
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.Fill, true)> _
Public Overloads Overridable Function Fill(ByVal dataTable As STOCKDataSet9.STOCKDataTable) As Integer
Me.Adapter.SelectCommand = Me.CommandCollection(0)
If (Me.ClearBeforeFill = true) Then
dataTable.Clear
End If
Dim returnValue As Integer = Me.Adapter.Fill(dataTable)
Return returnValue
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.[Select], true)> _
Public Overloads Overridable Function GetData() As STOCKDataSet9.STOCKDataTable
Me.Adapter.SelectCommand = Me.CommandCollection(0)
Dim dataTable As STOCKDataSet9.STOCKDataTable = New STOCKDataSet9.STOCKDataTable()
Me.Adapter.Fill(dataTable)
Return dataTable
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Public Overloads Overridable Function Update(ByVal dataTable As STOCKDataSet9.STOCKDataTable) As Integer
Return Me.Adapter.Update(dataTable)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Public Overloads Overridable Function Update(ByVal dataSet As STOCKDataSet9) As Integer
Return Me.Adapter.Update(dataSet, "STOCK")
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Public Overloads Overridable Function Update(ByVal dataRow As Global.System.Data.DataRow) As Integer
Return Me.Adapter.Update(New Global.System.Data.DataRow() {dataRow})
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Public Overloads Overridable Function Update(ByVal dataRows() As Global.System.Data.DataRow) As Integer
Return Me.Adapter.Update(dataRows)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.Insert, true)> _
Public Overloads Overridable Function Insert(ByVal NAME As String, ByVal MFDDATE As String, ByVal QUANTITY As Global.System.Nullable(Of Integer), ByVal PRICE As Global.System.Nullable(Of Integer), ByVal AMOUNT As Global.System.Nullable(Of Integer)) As Integer
If (NAME Is Nothing) Then
Me.Adapter.InsertCommand.Parameters(0).Value = Global.System.DBNull.Value
Else
Me.Adapter.InsertCommand.Parameters(0).Value = CType(NAME,String)
End If
If (MFDDATE Is Nothing) Then
Me.Adapter.InsertCommand.Parameters(1).Value = Global.System.DBNull.Value
Else
Me.Adapter.InsertCommand.Parameters(1).Value = CType(MFDDATE,String)
End If
If (QUANTITY.HasValue = true) Then
Me.Adapter.InsertCommand.Parameters(2).Value = CType(QUANTITY.Value,Integer)
Else
Me.Adapter.InsertCommand.Parameters(2).Value = Global.System.DBNull.Value
End If
If (PRICE.HasValue = true) Then
Me.Adapter.InsertCommand.Parameters(3).Value = CType(PRICE.Value,Integer)
Else
Me.Adapter.InsertCommand.Parameters(3).Value = Global.System.DBNull.Value
End If
If (AMOUNT.HasValue = true) Then
Me.Adapter.InsertCommand.Parameters(4).Value = CType(AMOUNT.Value,Integer)
Else
Me.Adapter.InsertCommand.Parameters(4).Value = Global.System.DBNull.Value
End If
Dim previousConnectionState As Global.System.Data.ConnectionState = Me.Adapter.InsertCommand.Connection.State
If ((Me.Adapter.InsertCommand.Connection.State And Global.System.Data.ConnectionState.Open) _
<> Global.System.Data.ConnectionState.Open) Then
Me.Adapter.InsertCommand.Connection.Open
End If
Try
Dim returnValue As Integer = Me.Adapter.InsertCommand.ExecuteNonQuery
Return returnValue
Finally
If (previousConnectionState = Global.System.Data.ConnectionState.Closed) Then
Me.Adapter.InsertCommand.Connection.Close
End If
End Try
End Function
End Class
'''<summary>
'''TableAdapterManager is used to coordinate TableAdapters in the dataset to enable Hierarchical Update scenarios
'''</summary>
<Global.System.ComponentModel.DesignerCategoryAttribute("code"), _
Global.System.ComponentModel.ToolboxItem(true), _
Global.System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerDesigner, Microsoft.VSD"& _
"esigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapterManager")> _
Partial Public Class TableAdapterManager
Inherits Global.System.ComponentModel.Component
Private _updateOrder As UpdateOrderOption
Private _sTOCKTableAdapter As STOCKTableAdapter
Private _backupDataSetBeforeUpdate As Boolean
Private _connection As Global.System.Data.IDbConnection
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property UpdateOrder() As UpdateOrderOption
Get
Return Me._updateOrder
End Get
Set
Me._updateOrder = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.EditorAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerPropertyEditor, Microso"& _
"ft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3"& _
"a", "System.Drawing.Design.UITypeEditor")> _
Public Property STOCKTableAdapter() As STOCKTableAdapter
Get
Return Me._sTOCKTableAdapter
End Get
Set
Me._sTOCKTableAdapter = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property BackupDataSetBeforeUpdate() As Boolean
Get
Return Me._backupDataSetBeforeUpdate
End Get
Set
Me._backupDataSetBeforeUpdate = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false)> _
Public Property Connection() As Global.System.Data.IDbConnection
Get
If (Not (Me._connection) Is Nothing) Then
Return Me._connection
End If
If ((Not (Me._sTOCKTableAdapter) Is Nothing) _
AndAlso (Not (Me._sTOCKTableAdapter.Connection) Is Nothing)) Then
Return Me._sTOCKTableAdapter.Connection
End If
Return Nothing
End Get
Set
Me._connection = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false)> _
Public ReadOnly Property TableAdapterInstanceCount() As Integer
Get
Dim count As Integer = 0
If (Not (Me._sTOCKTableAdapter) Is Nothing) Then
count = (count + 1)
End If
Return count
End Get
End Property
'''<summary>
'''Update rows in top-down order.
'''</summary>
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function UpdateUpdatedRows(ByVal dataSet As STOCKDataSet9, ByVal allChangedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow), ByVal allAddedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)) As Integer
Dim result As Integer = 0
If (Not (Me._sTOCKTableAdapter) Is Nothing) Then
Dim updatedRows() As Global.System.Data.DataRow = dataSet.STOCK.Select(Nothing, Nothing, Global.System.Data.DataViewRowState.ModifiedCurrent)
updatedRows = Me.GetRealUpdatedRows(updatedRows, allAddedRows)
If ((Not (updatedRows) Is Nothing) _
AndAlso (0 < updatedRows.Length)) Then
result = (result + Me._sTOCKTableAdapter.Update(updatedRows))
allChangedRows.AddRange(updatedRows)
End If
End If
Return result
End Function
'''<summary>
'''Insert rows in top-down order.
'''</summary>
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function UpdateInsertedRows(ByVal dataSet As STOCKDataSet9, ByVal allAddedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)) As Integer
Dim result As Integer = 0
If (Not (Me._sTOCKTableAdapter) Is Nothing) Then
Dim addedRows() As Global.System.Data.DataRow = dataSet.STOCK.Select(Nothing, Nothing, Global.System.Data.DataViewRowState.Added)
If ((Not (addedRows) Is Nothing) _
AndAlso (0 < addedRows.Length)) Then
result = (result + Me._sTOCKTableAdapter.Update(addedRows))
allAddedRows.AddRange(addedRows)
End If
End If
Return result
End Function
'''<summary>
'''Delete rows in bottom-up order.
'''</summary>
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function UpdateDeletedRows(ByVal dataSet As STOCKDataSet9, ByVal allChangedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)) As Integer
Dim result As Integer = 0
If (Not (Me._sTOCKTableAdapter) Is Nothing) Then
Dim deletedRows() As Global.System.Data.DataRow = dataSet.STOCK.Select(Nothing, Nothing, Global.System.Data.DataViewRowState.Deleted)
If ((Not (deletedRows) Is Nothing) _
AndAlso (0 < deletedRows.Length)) Then
result = (result + Me._sTOCKTableAdapter.Update(deletedRows))
allChangedRows.AddRange(deletedRows)
End If
End If
Return result
End Function
'''<summary>
'''Remove inserted rows that become updated rows after calling TableAdapter.Update(inserted rows) first
'''</summary>
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function GetRealUpdatedRows(ByVal updatedRows() As Global.System.Data.DataRow, ByVal allAddedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)) As Global.System.Data.DataRow()
If ((updatedRows Is Nothing) _
OrElse (updatedRows.Length < 1)) Then
Return updatedRows
End If
If ((allAddedRows Is Nothing) _
OrElse (allAddedRows.Count < 1)) Then
Return updatedRows
End If
Dim realUpdatedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow) = New Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)()
Dim i As Integer = 0
Do While (i < updatedRows.Length)
Dim row As Global.System.Data.DataRow = updatedRows(i)
If (allAddedRows.Contains(row) = false) Then
realUpdatedRows.Add(row)
End If
i = (i + 1)
Loop
Return realUpdatedRows.ToArray
End Function
'''<summary>
'''Update all changes to the dataset.
'''</summary>
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overridable Function UpdateAll(ByVal dataSet As STOCKDataSet9) As Integer
If (dataSet Is Nothing) Then
Throw New Global.System.ArgumentNullException("dataSet")
End If
If (dataSet.HasChanges = false) Then
Return 0
End If
If ((Not (Me._sTOCKTableAdapter) Is Nothing) _
AndAlso (Me.MatchTableAdapterConnection(Me._sTOCKTableAdapter.Connection) = false)) Then
Throw New Global.System.ArgumentException("All TableAdapters managed by a TableAdapterManager must use the same connection s"& _
"tring.")
End If
Dim workConnection As Global.System.Data.IDbConnection = Me.Connection
If (workConnection Is Nothing) Then
Throw New Global.System.ApplicationException("TableAdapterManager contains no connection information. Set each TableAdapterMana"& _
"ger TableAdapter property to a valid TableAdapter instance.")
End If
Dim workConnOpened As Boolean = false
If ((workConnection.State And Global.System.Data.ConnectionState.Broken) _
= Global.System.Data.ConnectionState.Broken) Then
workConnection.Close
End If
If (workConnection.State = Global.System.Data.ConnectionState.Closed) Then
workConnection.Open
workConnOpened = true
End If
Dim workTransaction As Global.System.Data.IDbTransaction = workConnection.BeginTransaction
If (workTransaction Is Nothing) Then
Throw New Global.System.ApplicationException("The transaction cannot begin. The current data connection does not support transa"& _
"ctions or the current state is not allowing the transaction to begin.")
End If
Dim allChangedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow) = New Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)()
Dim allAddedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow) = New Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)()
Dim adaptersWithAcceptChangesDuringUpdate As Global.System.Collections.Generic.List(Of Global.System.Data.Common.DataAdapter) = New Global.System.Collections.Generic.List(Of Global.System.Data.Common.DataAdapter)()
Dim revertConnections As Global.System.Collections.Generic.Dictionary(Of Object, Global.System.Data.IDbConnection) = New Global.System.Collections.Generic.Dictionary(Of Object, Global.System.Data.IDbConnection)()
Dim result As Integer = 0
Dim backupDataSet As Global.System.Data.DataSet = Nothing
If Me.BackupDataSetBeforeUpdate Then
backupDataSet = New Global.System.Data.DataSet()
backupDataSet.Merge(dataSet)
End If
Try
'---- Prepare for update -----------
'
If (Not (Me._sTOCKTableAdapter) Is Nothing) Then
revertConnections.Add(Me._sTOCKTableAdapter, Me._sTOCKTableAdapter.Connection)
Me._sTOCKTableAdapter.Connection = CType(workConnection,Global.System.Data.SqlClient.SqlConnection)
Me._sTOCKTableAdapter.Transaction = CType(workTransaction,Global.System.Data.SqlClient.SqlTransaction)
If Me._sTOCKTableAdapter.Adapter.AcceptChangesDuringUpdate Then
Me._sTOCKTableAdapter.Adapter.AcceptChangesDuringUpdate = false
adaptersWithAcceptChangesDuringUpdate.Add(Me._sTOCKTableAdapter.Adapter)
End If
End If
'
'---- Perform updates -----------
'
If (Me.UpdateOrder = UpdateOrderOption.UpdateInsertDelete) Then
result = (result + Me.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows))
result = (result + Me.UpdateInsertedRows(dataSet, allAddedRows))
Else
result = (result + Me.UpdateInsertedRows(dataSet, allAddedRows))
result = (result + Me.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows))
End If
result = (result + Me.UpdateDeletedRows(dataSet, allChangedRows))
'
'---- Commit updates -----------
'
workTransaction.Commit
If (0 < allAddedRows.Count) Then
Dim rows((allAddedRows.Count) - 1) As Global.System.Data.DataRow
allAddedRows.CopyTo(rows)
Dim i As Integer = 0
Do While (i < rows.Length)
Dim row As Global.System.Data.DataRow = rows(i)
row.AcceptChanges
i = (i + 1)
Loop
End If
If (0 < allChangedRows.Count) Then
Dim rows((allChangedRows.Count) - 1) As Global.System.Data.DataRow
allChangedRows.CopyTo(rows)
Dim i As Integer = 0
Do While (i < rows.Length)
Dim row As Global.System.Data.DataRow = rows(i)
row.AcceptChanges
i = (i + 1)
Loop
End If
Catch ex As Global.System.Exception
workTransaction.Rollback
'---- Restore the dataset -----------
If Me.BackupDataSetBeforeUpdate Then
Global.System.Diagnostics.Debug.Assert((Not (backupDataSet) Is Nothing))
dataSet.Clear
dataSet.Merge(backupDataSet)
Else
If (0 < allAddedRows.Count) Then
Dim rows((allAddedRows.Count) - 1) As Global.System.Data.DataRow
allAddedRows.CopyTo(rows)
Dim i As Integer = 0
Do While (i < rows.Length)
Dim row As Global.System.Data.DataRow = rows(i)
row.AcceptChanges
row.SetAdded
i = (i + 1)
Loop
End If
End If
Throw ex
Finally
If workConnOpened Then
workConnection.Close
End If
If (Not (Me._sTOCKTableAdapter) Is Nothing) Then
Me._sTOCKTableAdapter.Connection = CType(revertConnections(Me._sTOCKTableAdapter),Global.System.Data.SqlClient.SqlConnection)
Me._sTOCKTableAdapter.Transaction = Nothing
End If
If (0 < adaptersWithAcceptChangesDuringUpdate.Count) Then
Dim adapters((adaptersWithAcceptChangesDuringUpdate.Count) - 1) As Global.System.Data.Common.DataAdapter
adaptersWithAcceptChangesDuringUpdate.CopyTo(adapters)
Dim i As Integer = 0
Do While (i < adapters.Length)
Dim adapter As Global.System.Data.Common.DataAdapter = adapters(i)
adapter.AcceptChangesDuringUpdate = true
i = (i + 1)
Loop
End If
End Try
Return result
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overridable Sub SortSelfReferenceRows(ByVal rows() As Global.System.Data.DataRow, ByVal relation As Global.System.Data.DataRelation, ByVal childFirst As Boolean)
Global.System.Array.Sort(Of Global.System.Data.DataRow)(rows, New SelfReferenceComparer(relation, childFirst))
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overridable Function MatchTableAdapterConnection(ByVal inputConnection As Global.System.Data.IDbConnection) As Boolean
If (Not (Me._connection) Is Nothing) Then
Return true
End If
If ((Me.Connection Is Nothing) _
OrElse (inputConnection Is Nothing)) Then
Return true
End If
If String.Equals(Me.Connection.ConnectionString, inputConnection.ConnectionString, Global.System.StringComparison.Ordinal) Then
Return true
End If
Return false
End Function
'''<summary>
'''Update Order Option
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Enum UpdateOrderOption
InsertUpdateDelete = 0
UpdateInsertDelete = 1
End Enum
'''<summary>
'''Used to sort self-referenced table's rows
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Class SelfReferenceComparer
Inherits Object
Implements Global.System.Collections.Generic.IComparer(Of Global.System.Data.DataRow)
Private _relation As Global.System.Data.DataRelation
Private _childFirst As Integer
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub New(ByVal relation As Global.System.Data.DataRelation, ByVal childFirst As Boolean)
MyBase.New
Me._relation = relation
If childFirst Then
Me._childFirst = -1
Else
Me._childFirst = 1
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function GetRoot(ByVal row As Global.System.Data.DataRow, ByRef distance As Integer) As Global.System.Data.DataRow
Global.System.Diagnostics.Debug.Assert((Not (row) Is Nothing))
Dim root As Global.System.Data.DataRow = row
distance = 0
Dim traversedRows As Global.System.Collections.Generic.IDictionary(Of Global.System.Data.DataRow, Global.System.Data.DataRow) = New Global.System.Collections.Generic.Dictionary(Of Global.System.Data.DataRow, Global.System.Data.DataRow)()
traversedRows(row) = row
Dim parent As Global.System.Data.DataRow = row.GetParentRow(Me._relation, Global.System.Data.DataRowVersion.[Default])
Do While ((Not (parent) Is Nothing) _
AndAlso (traversedRows.ContainsKey(parent) = false))
distance = (distance + 1)
root = parent
traversedRows(parent) = parent
parent = parent.GetParentRow(Me._relation, Global.System.Data.DataRowVersion.[Default])
Loop
If (distance = 0) Then
traversedRows.Clear
traversedRows(row) = row
parent = row.GetParentRow(Me._relation, Global.System.Data.DataRowVersion.Original)
Do While ((Not (parent) Is Nothing) _
AndAlso (traversedRows.ContainsKey(parent) = false))
distance = (distance + 1)
root = parent
traversedRows(parent) = parent
parent = parent.GetParentRow(Me._relation, Global.System.Data.DataRowVersion.Original)
Loop
End If
Return root
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function Compare(ByVal row1 As Global.System.Data.DataRow, ByVal row2 As Global.System.Data.DataRow) As Integer Implements Global.System.Collections.Generic.IComparer(Of Global.System.Data.DataRow).Compare
If Object.ReferenceEquals(row1, row2) Then
Return 0
End If
If (row1 Is Nothing) Then
Return -1
End If
If (row2 Is Nothing) Then
Return 1
End If
Dim distance1 As Integer = 0
Dim root1 As Global.System.Data.DataRow = Me.GetRoot(row1, distance1)
Dim distance2 As Integer = 0
Dim root2 As Global.System.Data.DataRow = Me.GetRoot(row2, distance2)
If Object.ReferenceEquals(root1, root2) Then
Return (Me._childFirst * distance1.CompareTo(distance2))
Else
Global.System.Diagnostics.Debug.Assert(((Not (root1.Table) Is Nothing) _
AndAlso (Not (root2.Table) Is Nothing)))
If (root1.Table.Rows.IndexOf(root1) < root2.Table.Rows.IndexOf(root2)) Then
Return -1
Else
Return 1
End If
End If
End Function
End Class
End Class
End Namespace
|
#Region "Microsoft.VisualBasic::a391223bbdc7f6f1e7d5240085008dee, src\mzkit\ControlLibrary\MSI\Editor\Edge.vb"
' Author:
'
' xieguigang ([email protected], BioNovoGene Co., LTD.)
'
' Copyright (c) 2018 [email protected], BioNovoGene Co., LTD.
'
'
' MIT License
'
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
' /********************************************************************************/
' Summaries:
' Enum EdgeType
'
' [In], Out
'
'
'
'
'
' Class Edge
'
' Properties: [To], From, InRelation, Relation
'
' Constructor: (+2 Overloads) Sub New
'
'
' /********************************************************************************/
#End Region
Namespace PolygonEditor
Public Enum EdgeType
[In]
Out
End Enum
Friend Class Edge
Public Property From As Vertex
Public Property [To] As Vertex
Public Property InRelation As Edge
Public Property Relation As Relation
Public Sub New(ByVal from As Vertex, ByVal [to] As Vertex, ByVal Optional inRelation As Edge = Nothing)
Relation = Relation.None
Me.InRelation = inRelation
from.Edges.Add(Me)
[to].Edges.Add(Me)
Me.From = from
Me.To = [to]
End Sub
Public Sub New(ByVal x1 As Integer, ByVal y1 As Integer, ByVal x2 As Integer, ByVal y2 As Integer)
From = New Vertex(x1, y1)
[To] = New Vertex(x2, y2)
End Sub
End Class
End Namespace
|
' Generated by MyGeneration Version # (1.1.3.0)
Namespace MyGeneration.dOOdads.Tests.VistaDB
Public Class AggregateTest
Inherits _AggregateTest
End Class
End Namespace
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
Friend Class AccessorDeclarationStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of AccessorStatementSyntax)
Protected Overrides Sub CollectBlockSpans(accessorDeclaration As AccessorStatementSyntax,
spans As ArrayBuilder(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
CollectCommentsRegions(accessorDeclaration, spans, optionProvider)
Dim block = TryCast(accessorDeclaration.Parent, AccessorBlockSyntax)
If Not block?.EndBlockStatement.IsMissing Then
spans.AddIfNotNull(CreateBlockSpanFromBlock(
block, bannerNode:=accessorDeclaration,
autoCollapse:=True, type:=BlockTypes.Member,
isCollapsible:=True))
End If
End Sub
End Class
End Namespace
|
'*********************************************************
'
' Copyright (c) Microsoft. All rights reserved.
' THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
' ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
' IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
' PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
'
'*********************************************************
''' <summary>
''' An empty page that can be used on its own or navigated to within a Frame.
''' </summary>
Partial Public NotInheritable Class Scenario2
Inherits SDKTemplate.Common.LayoutAwarePage
' A pointer back to the main page. This is needed if you want to call methods in MainPage such
' as NotifyUser()
'MainPage rootPage = MainPage.Current;
Private messageData As MessageData = Nothing
Public Sub New()
Me.InitializeComponent()
messageData = New MessageData()
ItemListView.ItemsSource = messageData.Collection
End Sub
End Class
|
Imports System
Imports System.IO
Imports System.IO.Stream
Imports System.Xml
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Public Class clsChatCor
''' <summary>
''' 챗봇 데이터 파싱 구조체
''' </summary>
Structure Dic
Public dicname As String
Public lists() As String
End Structure
''' <summary>
''' 도로공사의 챗봇 데이터에서 내용 추출. 다이얼로그 플로우의 데이터에 삽입
''' </summary>
Public Sub ProcDFChat()
Dim sr As System.IO.StreamReader
Dim sw As System.IO.StreamWriter
Dim tstr, tarr() As String
Dim filePath, filePathArr() As String
Dim fileInformation As System.IO.FileInfo
Dim intentName As String
Dim tempDic, dicList() As Dic
Dim arr As JArray
Dim text As JObject = New JObject()
Dim cntr As Integer = 0
' 일단 반복관용어구를 읽어 사전으로 저장
sr = New StreamReader("J: \exChatbot_1007\dic\lists.txt", System.Text.Encoding.UTF8)
Do Until sr.EndOfStream
ReDim Preserve dicList(cntr)
tstr = sr.ReadLine
tarr = tstr.Split(":")
tempDic.dicname = tarr(0).Trim
tempDic.lists = tarr(1).Split(",")
dicList(cntr) = tempDic
cntr += 1
Loop
sr.Close()
'패턴 파일 목록을 읽고 패턴 내의 각 문장을 traversal
filePathArr = Directory.GetFiles("J:\exChatbot_1007\pattern")
For Each filePath In filePathArr
'기존 다이얼로그 플로우 자료 읽기
fileInformation = New FileInfo(filePath)
intentName = fileInformation.Name.Split("_")(1).Replace(".txt", "")
tstr = New StreamReader("J:\exChatbot_1007\intents\" & intentName & "_usersays_ko.json").ReadToEnd
arr = JArray.Parse(tstr)
'패턴 파일 내에서 각 패턴 읽기
sr = New StreamReader(filePath)
Do Until sr.EndOfStream
tstr = sr.ReadLine
ProcSentence(tstr, dicList, arr)
Loop
sr.Close()
' 파일로 출력
sw = New StreamWriter("j:\izawa\" & intentName & "_usersays_ko.json")
sw.Write(arr.ToString())
sw.Close()
Next
End Sub
''' <summary>
''' 패턴 문장을 하나 받으면 이를 토크나이징 하고 JSON array로 만들어서 반환함. 단 용언 사전별로 문장을 반복 생성.
''' </summary>
''' <param name="sentence">입력되는 문장</param>
''' <param name="pattern">반복되는 용언 패턴</param>
''' <param name="intentDoc">실제 적용을 할 문서 이름</param>
Public Sub ProcSentence(sentence As String, pattern() As Dic, ByRef intentDoc As JArray)
Dim stack As String = ""
Dim stack2 As String
Dim cntr, acntr, tcntr As Integer
Dim arr(0), entity() As String
Dim doc As New JArray
Dim tDoc As Dic
Dim tPhrase As String '반복관용어구 생성시 들어가는 반복 문장
Dim hasPattern As Boolean
Dim tToken As String '임시 토큰
Dim obj As JObject
acntr = 0
'문장을 토크나이징 함
Do Until cntr >= sentence.Length
Select Case sentence(cntr)
'entity 인식 태그 확인 (시스템에는 <> 형식으로 마킹)
Case "<"
' 만약 이전에 스택이 차 있는 곳이 있다면 채우고 지나감
If stack <> "" Then
arr(acntr) = stack
stack = ""
acntr += 1
ReDim Preserve arr(acntr)
End If
' 특수 토큰 처리
tcntr = cntr
stack2 = ""
Do Until sentence(tcntr) = ">" Or tcntr >= sentence.Length
stack2 &= sentence(tcntr)
tcntr += 1
Loop
arr(acntr) = stack2.Replace("<", "@")
cntr = tcntr
acntr += 1
ReDim Preserve arr(acntr)
'반복관용여구 인식 태그 확인(시스템에는 #; 형식으로 마킹)
Case "#"
' 만약 이전에 스택이 차 있는 곳이 있다면 채우고 지나감
If stack <> "" Then
arr(acntr) = stack
stack = ""
acntr += 1
ReDim Preserve arr(acntr)
End If
tcntr = cntr
stack2 = ""
Do Until sentence(tcntr) = ";" Or tcntr >= sentence.Length
stack2 &= sentence(tcntr)
tcntr += 1
Loop
arr(acntr) = stack2
cntr = tcntr
acntr += 1
ReDim Preserve arr(acntr)
Case Else
stack &= sentence(cntr)
End Select
cntr += 1
Loop
'만약 최종 스택이 다른 문자열로 있다면 문자열을 넣어주고, 비어있다면 스택의 길이를 줄일 것
If stack <> "" Then
arr(acntr) = stack
Else
ReDim Preserve arr(acntr - 1)
End If
'패턴별로 루틴을 돌고 해당 문장의 sequence에 해당 패턴이 있을 경우 JArray에 문장을 추가
'하나의 패턴 문장에는 하나의 반복관용어구만 허용(일단 버전 1)
For Each tDoc In pattern '패턴 인식 루틴 구동
hasPattern = False
For Each tstr In arr '입력받은 문장의 토큰에서 패턴 인식이 있는 지확인
If "#" & tDoc.dicname = tstr Then
hasPattern = True
End If
Next
' 만약 패턴이 있으면 반복해서 운영
If hasPattern = True Then
For Each tPhrase In tDoc.lists
Dim jSenDoc = New JArray
For Each tToken In arr
Select Case tToken(0)
Case "@"
entity = tToken.Replace("@", "").Split(":")
obj = New JObject
If entity.Length > 1 Then
obj.Add(New JProperty("text", entity(1)))
obj.Add(New JProperty("alias", entity(0)))
obj.Add(New JProperty("meta", "@" & entity(0)))
Else
obj.Add(New JProperty("text", tToken.Replace("@", "")))
obj.Add(New JProperty("alias", tToken.Replace("@", "")))
obj.Add(New JProperty("meta", tToken))
End If
obj.Add(New JProperty("userdefined", False))
Case "#"
obj = New JObject
obj.Add(New JProperty("text", tPhrase))
obj.Add(New JProperty("userdefined", False))
Case Else
obj = New JObject
obj.Add(New JProperty("text", tToken))
obj.Add(New JProperty("userdefined", False))
End Select
jSenDoc.Add(obj)
Next
Dim jMotherDoc As New JObject
jMotherDoc.Add(New JProperty("data", jSenDoc))
jMotherDoc.Add(New JProperty("isTemplate", False))
jMotherDoc.Add(New JProperty("count", 0))
jMotherDoc.Add(New JProperty("updated", 0))
'문장을 새로운 속성값으로 하여 Object 형태로 추가
intentDoc.Children.Last.AddAfterSelf(jMotherDoc)
Next
End If
Next
End Sub
End Class
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.Label1 = New System.Windows.Forms.Label()
Me.TextBox1 = New System.Windows.Forms.TextBox()
Me.Button1 = New System.Windows.Forms.Button()
Me.TabControl1 = New System.Windows.Forms.TabControl()
Me.TabPage1 = New System.Windows.Forms.TabPage()
Me.Button3 = New System.Windows.Forms.Button()
Me.Button2 = New System.Windows.Forms.Button()
Me.ListBox1 = New System.Windows.Forms.ListBox()
Me.TabPage2 = New System.Windows.Forms.TabPage()
Me.CheckBox1 = New System.Windows.Forms.CheckBox()
Me.Label2 = New System.Windows.Forms.Label()
Me.NumericUpDown1 = New System.Windows.Forms.NumericUpDown()
Me.NumericUpDown2 = New System.Windows.Forms.NumericUpDown()
Me.Label3 = New System.Windows.Forms.Label()
Me.CheckBox2 = New System.Windows.Forms.CheckBox()
Me.CheckBox3 = New System.Windows.Forms.CheckBox()
Me.TextBox2 = New System.Windows.Forms.TextBox()
Me.GroupBox1 = New System.Windows.Forms.GroupBox()
Me.TabControl1.SuspendLayout()
Me.TabPage1.SuspendLayout()
Me.TabPage2.SuspendLayout()
CType(Me.NumericUpDown1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.NumericUpDown2, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(12, 15)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(76, 13)
Me.Label1.TabIndex = 0
Me.Label1.Text = "Source Folder:"
'
'TextBox1
'
Me.TextBox1.Location = New System.Drawing.Point(94, 12)
Me.TextBox1.Name = "TextBox1"
Me.TextBox1.ReadOnly = True
Me.TextBox1.Size = New System.Drawing.Size(249, 20)
Me.TextBox1.TabIndex = 1
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(349, 12)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(46, 20)
Me.Button1.TabIndex = 2
Me.Button1.Text = "..."
Me.Button1.UseVisualStyleBackColor = True
'
'TabControl1
'
Me.TabControl1.Controls.Add(Me.TabPage1)
Me.TabControl1.Controls.Add(Me.TabPage2)
Me.TabControl1.Location = New System.Drawing.Point(12, 38)
Me.TabControl1.Name = "TabControl1"
Me.TabControl1.SelectedIndex = 0
Me.TabControl1.Size = New System.Drawing.Size(383, 258)
Me.TabControl1.TabIndex = 3
'
'TabPage1
'
Me.TabPage1.Controls.Add(Me.NumericUpDown2)
Me.TabPage1.Controls.Add(Me.Label3)
Me.TabPage1.Controls.Add(Me.NumericUpDown1)
Me.TabPage1.Controls.Add(Me.Label2)
Me.TabPage1.Controls.Add(Me.CheckBox1)
Me.TabPage1.Controls.Add(Me.Button3)
Me.TabPage1.Controls.Add(Me.Button2)
Me.TabPage1.Controls.Add(Me.ListBox1)
Me.TabPage1.Location = New System.Drawing.Point(4, 22)
Me.TabPage1.Name = "TabPage1"
Me.TabPage1.Padding = New System.Windows.Forms.Padding(3)
Me.TabPage1.Size = New System.Drawing.Size(375, 232)
Me.TabPage1.TabIndex = 0
Me.TabPage1.Text = "Connection"
Me.TabPage1.UseVisualStyleBackColor = True
'
'Button3
'
Me.Button3.Location = New System.Drawing.Point(130, 203)
Me.Button3.Name = "Button3"
Me.Button3.Size = New System.Drawing.Size(75, 23)
Me.Button3.TabIndex = 2
Me.Button3.Text = "-"
Me.Button3.UseVisualStyleBackColor = True
'
'Button2
'
Me.Button2.Location = New System.Drawing.Point(6, 203)
Me.Button2.Name = "Button2"
Me.Button2.Size = New System.Drawing.Size(75, 23)
Me.Button2.TabIndex = 1
Me.Button2.Text = "+"
Me.Button2.UseVisualStyleBackColor = True
'
'ListBox1
'
Me.ListBox1.FormattingEnabled = True
Me.ListBox1.Items.AddRange(New Object() {"https://127.0.0.1/"})
Me.ListBox1.Location = New System.Drawing.Point(6, 6)
Me.ListBox1.Name = "ListBox1"
Me.ListBox1.ScrollAlwaysVisible = True
Me.ListBox1.Size = New System.Drawing.Size(199, 186)
Me.ListBox1.TabIndex = 0
'
'TabPage2
'
Me.TabPage2.Controls.Add(Me.GroupBox1)
Me.TabPage2.Controls.Add(Me.TextBox2)
Me.TabPage2.Controls.Add(Me.CheckBox3)
Me.TabPage2.Controls.Add(Me.CheckBox2)
Me.TabPage2.Location = New System.Drawing.Point(4, 22)
Me.TabPage2.Name = "TabPage2"
Me.TabPage2.Padding = New System.Windows.Forms.Padding(3)
Me.TabPage2.Size = New System.Drawing.Size(375, 232)
Me.TabPage2.TabIndex = 1
Me.TabPage2.Text = "Installation"
Me.TabPage2.UseVisualStyleBackColor = True
'
'CheckBox1
'
Me.CheckBox1.AutoSize = True
Me.CheckBox1.Location = New System.Drawing.Point(211, 6)
Me.CheckBox1.Name = "CheckBox1"
Me.CheckBox1.Size = New System.Drawing.Size(68, 17)
Me.CheckBox1.TabIndex = 3
Me.CheckBox1.Text = "Use SSL"
Me.CheckBox1.UseVisualStyleBackColor = True
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.Location = New System.Drawing.Point(208, 36)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(93, 13)
Me.Label2.TabIndex = 4
Me.Label2.Text = "Min Connect Time"
'
'NumericUpDown1
'
Me.NumericUpDown1.Location = New System.Drawing.Point(307, 34)
Me.NumericUpDown1.Maximum = New Decimal(New Integer() {999999, 0, 0, 0})
Me.NumericUpDown1.Minimum = New Decimal(New Integer() {1, 0, 0, 0})
Me.NumericUpDown1.Name = "NumericUpDown1"
Me.NumericUpDown1.Size = New System.Drawing.Size(62, 20)
Me.NumericUpDown1.TabIndex = 5
Me.NumericUpDown1.Value = New Decimal(New Integer() {1, 0, 0, 0})
'
'NumericUpDown2
'
Me.NumericUpDown2.Location = New System.Drawing.Point(307, 60)
Me.NumericUpDown2.Maximum = New Decimal(New Integer() {999999, 0, 0, 0})
Me.NumericUpDown2.Minimum = New Decimal(New Integer() {2, 0, 0, 0})
Me.NumericUpDown2.Name = "NumericUpDown2"
Me.NumericUpDown2.Size = New System.Drawing.Size(62, 20)
Me.NumericUpDown2.TabIndex = 7
Me.NumericUpDown2.Value = New Decimal(New Integer() {2, 0, 0, 0})
'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.Location = New System.Drawing.Point(208, 62)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(96, 13)
Me.Label3.TabIndex = 6
Me.Label3.Text = "Max Connect Time"
'
'CheckBox2
'
Me.CheckBox2.AutoSize = True
Me.CheckBox2.Location = New System.Drawing.Point(6, 6)
Me.CheckBox2.Name = "CheckBox2"
Me.CheckBox2.Size = New System.Drawing.Size(53, 17)
Me.CheckBox2.TabIndex = 0
Me.CheckBox2.Text = "Install"
Me.CheckBox2.UseVisualStyleBackColor = True
'
'CheckBox3
'
Me.CheckBox3.AutoSize = True
Me.CheckBox3.Location = New System.Drawing.Point(6, 29)
Me.CheckBox3.Name = "CheckBox3"
Me.CheckBox3.Size = New System.Drawing.Size(99, 17)
Me.CheckBox3.TabIndex = 1
Me.CheckBox3.Text = "Single Instance"
Me.CheckBox3.UseVisualStyleBackColor = True
'
'TextBox2
'
Me.TextBox2.Location = New System.Drawing.Point(111, 27)
Me.TextBox2.Name = "TextBox2"
Me.TextBox2.Size = New System.Drawing.Size(258, 20)
Me.TextBox2.TabIndex = 2
'
'GroupBox1
'
Me.GroupBox1.Location = New System.Drawing.Point(6, 52)
Me.GroupBox1.Name = "GroupBox1"
Me.GroupBox1.Size = New System.Drawing.Size(192, 174)
Me.GroupBox1.TabIndex = 3
Me.GroupBox1.TabStop = False
Me.GroupBox1.Text = "File Names"
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(404, 308)
Me.Controls.Add(Me.TabControl1)
Me.Controls.Add(Me.Button1)
Me.Controls.Add(Me.TextBox1)
Me.Controls.Add(Me.Label1)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
Me.MaximizeBox = False
Me.Name = "Form1"
Me.Text = "Builder"
Me.TabControl1.ResumeLayout(False)
Me.TabPage1.ResumeLayout(False)
Me.TabPage1.PerformLayout()
Me.TabPage2.ResumeLayout(False)
Me.TabPage2.PerformLayout()
CType(Me.NumericUpDown1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.NumericUpDown2, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents Label1 As Label
Friend WithEvents TextBox1 As TextBox
Friend WithEvents Button1 As Button
Friend WithEvents TabControl1 As TabControl
Friend WithEvents TabPage1 As TabPage
Friend WithEvents Button3 As Button
Friend WithEvents Button2 As Button
Friend WithEvents ListBox1 As ListBox
Friend WithEvents TabPage2 As TabPage
Friend WithEvents NumericUpDown2 As NumericUpDown
Friend WithEvents Label3 As Label
Friend WithEvents NumericUpDown1 As NumericUpDown
Friend WithEvents Label2 As Label
Friend WithEvents CheckBox1 As CheckBox
Friend WithEvents TextBox2 As TextBox
Friend WithEvents CheckBox3 As CheckBox
Friend WithEvents CheckBox2 As CheckBox
Friend WithEvents GroupBox1 As GroupBox
End Class
|
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("Chimex OS")>
<Assembly: AssemblyDescription("Chimex OS")>
<Assembly: AssemblyCompany("ChimexSoft")>
<Assembly: AssemblyProduct("Chimex OS")>
<Assembly: AssemblyCopyright("Copyright © ChimexSoft 2018")>
<Assembly: AssemblyTrademark("ChimexSoft")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("8eb4d949-13cb-4a60-ac23-62bbfd4083f4")>
' 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")>
|
Imports System.Linq
Partial Public Class PivotTableAdapter
Private Class CellMapManager
Private Property PositionMappingList As New List(Of CellMap)
Public Sub SetPositionMap(sourceModelPosition As CellPosition, targetModelPosition As CellPosition)
Me.PositionMappingList.RemoveAll(Function(map) map.SourcePosition = sourceModelPosition OrElse map.TargetPosition = targetModelPosition)
Me.PositionMappingList.Add(New CellMap(sourceModelPosition, targetModelPosition))
End Sub
Public Sub ClearPositionMaps()
Me.PositionMappingList.Clear()
End Sub
Public Function GetTargetPosition(sourceModelPosition As CellPosition) As CellPosition
Dim foundMap = Me.PositionMappingList.Find(Function(map) map.SourcePosition = sourceModelPosition)
If foundMap Is Nothing Then Return Nothing
Return foundMap.TargetPosition
End Function
Public Function GetSourcePosition(targetModelPosition As CellPosition) As CellPosition
Dim foundMap = Me.PositionMappingList.Find(Function(map) map.TargetPosition = targetModelPosition)
If foundMap Is Nothing Then Return Nothing
Return foundMap.SourcePosition
End Function
Public Sub AdjustSourceRowsAfterRowsRemoved(rows As Integer())
'将被删除行相应的映射记录删除
Me.PositionMappingList.RemoveAll(Function(m) rows.Contains(m.SourcePosition.Row))
'将其他行的映射记录的行相应前移
For Each map In Me.PositionMappingList
map.SourcePosition.Row -= rows.Aggregate(0, Function(sum, row) If(row < map.SourcePosition.Row, sum + 1, sum))
Next
End Sub
Public Sub AdjustSourceRowsAfterRowsInserted(rows As Integer())
Dim sourcePositions = Me.PositionMappingList.Select(Function(m) m.SourcePosition).ToArray
For i = 0 To sourcePositions.Length - 1
Dim sourcePosition = sourcePositions(i)
sourcePosition.Row += rows.Aggregate(0, Function(sum, row) If(row <= sourcePosition.Row, sum + 1, sum))
Next
End Sub
End Class
End Class |
Option Strict Off
Option Explicit On
Module modReport
Public cnnDBreport As ADODB.Connection
Public cnnDBConsReport As ADODB.Connection
Public Function getRSreport(ByRef sql As String) As ADODB.Recordset
Dim Path As String
Dim strDBPath As String
On Error GoTo getRSreport_Error
getRSreport = New ADODB.Recordset
getRSreport.CursorLocation = ADODB.CursorLocationEnum.adUseClient
Debug.Print(sql)
getRSreport.Open(sql, cnnDBreport, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic)
Exit Function
getRSreport_Error:
If cnnDBreport Is Nothing Then
MsgBox(Err.Number & " " & Err.Description & " " & Err.Source & vbCrLf & vbCrLf & " cnnDBreport object has not been made.")
ElseIf Err.Description = "Not a valid password." Then
MsgBox("Error while getRSreport and Error is :" & Err.Number & " " & Err.Description & " " & Err.Source & vbCrLf & vbCrLf & cnnDBreport.ConnectionString & vbCrLf & vbCrLf & " --- " & cnnDBreport.State)
cnnDB.Close()
'UPGRADE_NOTE: Object cnnDB may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
cnnDB = Nothing
cnnDB = New ADODB.Connection
'UPGRADE_WARNING: Couldn't resolve default property of object strDBPath. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
strDBPath = serverPath & "pricing.mdb"
'UPGRADE_WARNING: Couldn't resolve default property of object strDBPath. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
'UPGRADE_WARNING: Couldn't resolve default property of object Path. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
Path = strDBPath & ";Jet " & "OLEDB:Database Password=lqd"
'cnnDB.CursorLocation = adUseClient
'UPGRADE_WARNING: Couldn't resolve default property of object Path. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
cnnDB.Open("Provider=Microsoft.ACE.OLEDB.12.0;Mode=Share Deny Read|Share Deny Write;Persist Security Info=False;Data Source= " & Path)
cnnDB.Execute("ALTER DATABASE PASSWORD Null " & " " & "lqd")
cnnDB.Close()
'UPGRADE_NOTE: Object cnnDB may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
cnnDB = Nothing
openConnection()
Else
MsgBox("Error while getRSreport and Error is :" & Err.Number & " " & Err.Description & " " & Err.Source & vbCrLf & vbCrLf & cnnDBreport.ConnectionString & vbCrLf & vbCrLf & " --- " & cnnDBreport.State)
End If
Resume Next
End Function
Public Function getRSreport1(ByRef sql As Object) As ADODB.Recordset
On Error GoTo getRSreport1_Error
getRSreport1 = New ADODB.Recordset
getRSreport1.CursorLocation = ADODB.CursorLocationEnum.adUseClient
getRSreport1.Open(sql, cnnDBConsReport, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic)
Exit Function
getRSreport1_Error:
If cnnDBConsReport Is Nothing Then
MsgBox(Err.Number & " " & Err.Description & " " & Err.Source & vbCrLf & vbCrLf & " cnnDBConsReport object has not been made.")
Else
MsgBox("Error while getRSreport1 and Error is :" & Err.Number & " " & Err.Description & " " & Err.Source & vbCrLf & vbCrLf & " --- " & cnnDBConsReport.ConnectionString & vbCrLf & vbCrLf & " --- " & cnnDBConsReport.State)
End If
Resume Next
End Function
Public Function openConnectionReport() As Boolean
Dim Path As String
On Error GoTo openConnection_Error
Dim createDayend As Boolean
Dim strDBPath As String
Dim fso As New Scripting.FileSystemObject
createDayend = False
openConnectionReport = True
cnnDBreport = New ADODB.Connection
strDBPath = serverPath & "report" & frmMenu.lblUser.Tag & ".mdb"
With cnnDBreport
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Properties("Jet OLEDB:System Database").Value = serverPath & "Secured.mdw"
.Open(strDBPath, "liquid", "lqd")
End With
Exit Function
withPass:
'If serverPath = "" Then setNewServerPath
'If serverPath <> "" Then
cnnDBreport = New ADODB.Connection
strDBPath = serverPath & "report" & frmMenu.lblUser.Tag & ".mdb"
'UPGRADE_WARNING: Couldn't resolve default property of object Path. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
Path = strDBPath & ";Jet " & "OLEDB:Database Password=lqd"
cnnDBreport.CursorLocation = ADODB.CursorLocationEnum.adUseClient
'UPGRADE_WARNING: Couldn't resolve default property of object Path. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
cnnDBreport.Open("Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;Data Source= " & Path)
openConnectionReport = True
'End If
Exit Function
openConnection_Error:
If Err.Description = "[Microsoft][ODBC Microsoft Access Driver] Not a valid password." Then
GoTo withPass
ElseIf Err.Description = "Not a valid password." Then
GoTo withPass
End If
openConnectionReport = False
MsgBox(Err.Number & " " & Err.Description & " " & Err.Source & vbCrLf & vbCrLf & " openConnectionReport object has not been made.")
End Function
Public Function openConsReport(ByRef strL As String) As Boolean
Dim strTable As String
Dim createDayend As Boolean
Dim strDBPath As String
On Error GoTo openConnection_Error
createDayend = False
cnnDBConsReport = New ADODB.Connection
strDBPath = StrLocRep & "report" & frmMenu.lblUser.Tag & ".mdb"
cnnDBConsReport.Open("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source= " & strDBPath & ";")
openConnection_Error:
openConsReport = False
MsgBox(Err.Number & " " & Err.Description & " " & Err.Source & vbCrLf & vbCrLf & " openConsReport object has not been made.")
End Function
Public Sub closeConnectionReport()
cnnDBreport.Close()
'UPGRADE_NOTE: Object cnnDBreport may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
cnnDBreport = Nothing
End Sub
End Module |
Imports System.Data
Imports System.Data.Common
Imports bv.common.db.Core
Public Class StatisticType_DB
Inherits BaseDbService
Public Sub New()
ObjectName = "BaseReference"
Me.UseDatasetCopyInPost = False
End Sub
Public Overrides Function GetDetail(ByVal ID As Object) As System.Data.DataSet
Dim ds As New DataSet
Try
Dim cmd As IDbCommand = CreateSPCommand("spStatisticType_SelectDetail")
AddParam(cmd, "@LangID", bv.model.Model.Core.ModelUserContext.CurrentLanguage)
Dim StatisticTypeDetail_Adapter As IDataAdapter = CreateAdapter(cmd)
StatisticTypeDetail_Adapter.Fill(ds)
CorrectTable(ds.Tables(0), "BaseReference")
ds.Tables("BaseReference").Columns("Name").ReadOnly = False
ds.Tables("BaseReference").Columns("idfsStatisticAreaType").AllowDBNull = True
ds.Tables("BaseReference").Columns("idfsBaseReference").AutoIncrement = True
ds.Tables("BaseReference").Columns("idfsBaseReference").AutoIncrementSeed = -1
ds.Tables("BaseReference").Columns("idfsBaseReference").AutoIncrementStep = -1
m_ID = ID
Return ds
Catch ex As Exception
m_Error = New ErrorMessage(StandardError.FillDatasetError, ex)
Return Nothing
End Try
Return Nothing
End Function
Public Overrides Function PostDetail(ByVal ds As System.Data.DataSet, ByVal PostType As Integer, Optional ByVal transaction As System.Data.IDbTransaction = Nothing) As Boolean
If ds Is Nothing Then Return True
Try
ExecPostProcedure("spStatisticType_Post", ds.Tables("BaseReference"), Connection, transaction)
bv.common.db.Core.LookupCache.NotifyChange("rftStatisticDataType", transaction)
bv.common.db.Core.LookupCache.NotifyChange("rftStatisticPeriodType", transaction)
bv.common.db.Core.LookupCache.NotifyChange("rftStatisticAreaType", transaction)
Catch ex As Exception
m_Error = New ErrorMessage(StandardError.PostError, ex)
Return False
End Try
Return True
End Function
End Class
|
Public Class Form1
Dim s As Integer
Dim Start As Integer = 3
Dim mve As Boolean = False
Dim life As Integer
Dim car(2) As PictureBox
Dim road(7) As PictureBox
Dim h(2) As PictureBox
Dim flag As Boolean
Dim gme_ovr As Boolean = False
Dim speed As Integer = 10
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
road(0) = line00
road(1) = line10
road(2) = line20
road(3) = line30
road(4) = line01
road(5) = line11
road(6) = line21
road(7) = line31
car(0) = op_car1
car(1) = op_car2
car(2) = op_car3
h(0) = life1
h(1) = life2
h(2) = life3
For y = 0 To 2
car(y).Top = -Int(Rnd() * 550)
Next
gme_ovr = False
End Sub
Private Sub Form1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
If e.KeyCode = Keys.Return Then
speed = 0
gear.Text = "0"
sped.Text = "0"
new_gme()
End If
If e.KeyCode = Keys.Escape Then
Application.Exit()
End If
If e.KeyCode = Keys.Right And mve = True Then
right_mve.Start()
End If
If e.KeyCode = Keys.Left And mve = True Then
left_mve.Start()
End If
If e.KeyCode = Keys.Up And mve = True Then
If speed <= 50 Then
speed = speed + 10
car_tmr.Interval = car_tmr.Interval - 10
End If
End If
If e.KeyCode = Keys.Down And mve = True Then
If speed >= 20 Then
speed = speed - 10
car_tmr.Interval = car_tmr.Interval + 10
End If
End If
sped.Text = speed
gear.Text = speed / 10
End Sub
Private Sub Form1_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyUp
left_mve.Stop()
right_mve.Stop()
End Sub
Private Sub right_mve_Tick(sender As Object, e As EventArgs) Handles right_mve.Tick
If my_car.Location.X < 733 Then
my_car.Left += 5
End If
End Sub
Private Sub left_mve_Tick(sender As Object, e As EventArgs) Handles left_mve.Tick
If my_car.Location.X > 80 Then
my_car.Left -= 5
End If
End Sub
Private Sub line_tmr_Tick(sender As Object, e As EventArgs) Handles line_tmr.Tick
For x = 0 To 7
road(x).Top += speed
If road(x).Top >= Me.Height Then
road(x).Top = -road(x).Height
End If
Next
End Sub
Private Sub time_tmr_Tick(sender As Object, e As EventArgs) Handles time_tmr.Tick
s += 1
scre.Text = s
End Sub
Private Sub Timer_strt_Tick(sender As Object, e As EventArgs) Handles Timer_strt.Tick
If Start > 0 Then
Start -= 1
End If
count.Text = Start
If Start = 0 Then
speed = 10
sped.Text = speed
gear.Text = speed / 10
time_tmr.Start()
line_tmr.Start()
car_tmr.Start()
count.Visible = False
mve = True
Timer_strt.Stop()
flag = True
End If
flag = True
End Sub
Private Sub car_tmr_Tick(sender As Object, e As EventArgs) Handles car_tmr.Tick
For y = 0 To 2
car(y).Top += 15
If car(y).Top > Me.Height Then
car(y).Top = -Int(Rnd() * 550)
End If
If my_car.Bounds.IntersectsWith(car(y).Bounds) Then
life += 1
car(y).Top = -Int(Rnd() * 550)
h(life - 1).Hide()
If life = 3 Then
car_tmr.Stop()
time_tmr.Stop()
left_mve.Stop()
right_mve.Stop()
line_tmr.Stop()
mve = False
life = 0
count.Visible = True
count.Text = "Game Over"
gme_ovr = True
End If
End If
Next
End Sub
Private Sub new_gme()
scre.Text = "0"
gear.Text = "0"
sped.Text = "0"
For y = 0 To 2
car(y).Top = -Int(Rnd() * 550)
Next
flag = True
Timer_strt.Start()
count.Text = 3
my_car.Left = 425
my_car.Top = 634
Start = 3
time_tmr.Stop()
line_tmr.Stop()
car_tmr.Stop()
count.Visible = True
mve = False
flag = False
gme_ovr = False
End Sub
End Class
|
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("XmlSample")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Microsoft")>
<Assembly: AssemblyProduct("XmlSample")>
<Assembly: AssemblyCopyright("Copyright Microsoft 2005")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("e8b2a78d-9f4c-4cc9-ae7b-d2f9b95f4301")>
' 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")>
|
' Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Globalization
Imports System.IO
Imports System.Text
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Instrumentation
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Public Class VisualBasicCompilation
Partial Friend Class DocumentationCommentCompiler
Inherits VisualBasicSymbolVisitor
Public Overrides Sub VisitField(symbol As FieldSymbol)
Me._cancellationToken.ThrowIfCancellationRequested()
If Not ShouldSkipSymbol(symbol) Then
Dim sourceField = TryCast(symbol, SourceFieldSymbol)
If sourceField IsNot Nothing Then
WriteDocumentationCommentForField(sourceField)
End If
End If
End Sub
Private Sub WriteDocumentationCommentForField(field As SourceFieldSymbol)
Dim docCommentTrivia As DocumentationCommentTriviaSyntax =
TryGetDocCommentTriviaAndGenerateDiagnostics(field.DeclarationSyntax)
If docCommentTrivia Is Nothing Then
Return
End If
Dim wellKnownElementNodes As New Dictionary(Of WellKnownTag, ArrayBuilder(Of XmlNodeSyntax))
Dim docCommentXml As String =
GetDocumentationCommentForSymbol(field, docCommentTrivia, wellKnownElementNodes)
' No further processing
If docCommentXml Is Nothing Then
FreeWellKnownElementNodes(wellKnownElementNodes)
Return
End If
If docCommentTrivia.SyntaxTree.ReportDocumentationCommentDiagnostics OrElse _writer.IsSpecified Then
Dim symbolName As String = GetSymbolName(field)
' Duplicate top-level well known tags
ReportWarningsForDuplicatedTags(wellKnownElementNodes)
' <exception>
ReportIllegalWellKnownTagIfAny(WellKnownTag.Exception, wellKnownElementNodes, symbolName)
' <returns>
ReportIllegalWellKnownTagIfAny(WellKnownTag.Returns, wellKnownElementNodes, symbolName)
' <param>
ReportIllegalWellKnownTagIfAny(WellKnownTag.Param, wellKnownElementNodes, symbolName)
' <paramref>
ReportIllegalWellKnownTagIfAny(WellKnownTag.ParamRef, wellKnownElementNodes, symbolName)
' <value>
ReportIllegalWellKnownTagIfAny(WellKnownTag.Value, wellKnownElementNodes, symbolName)
' <typeparam>
ReportIllegalWellKnownTagIfAny(WellKnownTag.TypeParam, wellKnownElementNodes, symbolName)
' <typeparamref>
ReportWarningsForTypeParamRefTags(wellKnownElementNodes, symbolName, field, docCommentTrivia.SyntaxTree)
End If
FreeWellKnownElementNodes(wellKnownElementNodes)
WriteDocumentationCommentForSymbol(docCommentXml)
End Sub
End Class
End Class
End Namespace
|
Public Class AgregarArticulo
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim lcArticulo As String
Dim lnPrecio As Decimal
lcArticulo = Request.QueryString("lcArticulo").Trim
lnPrecio = Request.QueryString("lnPrecio").Trim
If Not Me.IsPostBack Then
If AInt(Session("nCliente")) <> 0 Then
Agregar_Articulo_Carrito(
AInt(Session("nCliente")),
AInt(Session("nPedido")),
lcArticulo,
ADec(lnPrecio)
)
Response.Redirect(Session("lcRegresar").ToString.Trim)
Else
Response.Redirect("Login.aspx?lcArticulo=" + lcArticulo + "&lnPrecio=" + lnPrecio.ToString)
End If
Else
Response.Redirect("Login.aspx?lcArticulo=" + lcArticulo + "&lnPrecio=" + lnPrecio.ToString)
End If
End Sub
End Class |
' Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Linq
Imports System.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend MustInherit Class MergedNamespaceOrTypeDeclaration
Inherits Declaration
Protected Sub New(name As String)
MyBase.New(name)
End Sub
End Class
End Namespace |
Imports Microsoft.VisualBasic
Imports System
Imports System.Runtime.InteropServices
Namespace CommandMessenger
Public Class ConsoleUtils
Public Shared ConsoleClose As EventHandler = AddressOf AnonymousMethod1
Shared Sub New()
_handler = AddressOf ConsoleEventCallback
SetConsoleCtrlHandler(_handler, True)
End Sub
Private Sub AnonymousMethod1(ByVal sender As Object, ByVal e As System.EventArgs)
End Sub
Private Shared Function ConsoleEventCallback(ByVal eventType As Integer) As Boolean
If eventType = 2 Then
ConsoleClose(Nothing, EventArgs.Empty)
End If
ConsoleClose= Nothing
_handler = Nothing
Return False
End Function
Private Shared _handler As ConsoleEventDelegate ' Keeps it from getting garbage collected
Private Delegate Function ConsoleEventDelegate(ByVal eventType As Integer) As Boolean
<DllImport("kernel32.dll", SetLastError := True)> _
Private Shared Function SetConsoleCtrlHandler(ByVal callback As ConsoleEventDelegate, ByVal add As Boolean) As Boolean
End Function
End Class
End Namespace
|
'------------------------------------------------------------------------------
' <generado automáticamente>
' Este código fue generado por una herramienta.
'
' Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
' se vuelve a generar el código.
' </generado automáticamente>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Partial Public Class tablero_cursos
End Class
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitFieldInitializer(node As BoundFieldInitializer) As BoundNode
Return VisitFieldOrPropertyInitializer(node, ImmutableArray(Of Symbol).CastUp(node.InitializedFields))
End Function
Public Overrides Function VisitPropertyInitializer(node As BoundPropertyInitializer) As BoundNode
Return VisitFieldOrPropertyInitializer(node, ImmutableArray(Of Symbol).CastUp(node.InitializedProperties))
End Function
''' <summary>
''' Field initializers need to be rewritten multiple times in case of an AsNew declaration with multiple field names because the
''' initializer may contain references to the current field like in the following example:
''' Class C1
''' Public x, y As New RefType() With {.Field1 = .Field2}
''' End Class
'''
''' in this example .Field2 references the temp that is created for x and y.
'''
''' We moved the final rewriting for field initializers to the local
''' rewriters because here we already have the infrastructure to replace placeholders.
''' </summary>
Private Function VisitFieldOrPropertyInitializer(node As BoundFieldOrPropertyInitializer, initializedSymbols As ImmutableArray(Of Symbol)) As BoundNode
Dim syntax = node.Syntax
Debug.Assert(
syntax.IsKind(SyntaxKind.AsNewClause) OrElse ' Dim a As New C(); Dim a,b As New C(); Property P As New C()
syntax.IsKind(SyntaxKind.ModifiedIdentifier) OrElse ' Dim a(1) As Integer
syntax.IsKind(SyntaxKind.EqualsValue)) ' Dim a = 1; Property P As Integer = 1
Dim rewrittenStatements = ArrayBuilder(Of BoundStatement).GetInstance(initializedSymbols.Length)
' it's enough to create one me reference if the symbols are not shared that gets reused for all following rewritings.
Dim meReferenceOpt As BoundExpression = Nothing
If Not initializedSymbols.First.IsShared Then
' create me reference if needed
Debug.Assert(_currentMethodOrLambda IsNot Nothing)
meReferenceOpt = New BoundMeReference(syntax, _currentMethodOrLambda.ContainingType)
meReferenceOpt.SetWasCompilerGenerated()
End If
Dim objectInitializer As BoundObjectInitializerExpression = Nothing
Dim createTemporary = True
If node.InitialValue.Kind = BoundKind.ObjectCreationExpression OrElse node.InitialValue.Kind = BoundKind.NewT Then
Dim objectCreationExpression = DirectCast(node.InitialValue, BoundObjectCreationExpressionBase)
If objectCreationExpression.InitializerOpt IsNot Nothing AndAlso
objectCreationExpression.InitializerOpt.Kind = BoundKind.ObjectInitializerExpression Then
objectInitializer = DirectCast(objectCreationExpression.InitializerOpt, BoundObjectInitializerExpression)
createTemporary = objectInitializer.CreateTemporaryLocalForInitialization
End If
End If
Dim instrument As Boolean = Me.Instrument(node)
For symbolIndex = 0 To initializedSymbols.Length - 1
Dim symbol = initializedSymbols(symbolIndex)
Dim accessExpression As BoundExpression
' if there are more than one symbol we need to create a field or property access for each of them
If initializedSymbols.Length > 1 Then
If symbol.Kind = SymbolKind.Field Then
Dim fieldSymbol = DirectCast(symbol, FieldSymbol)
accessExpression = New BoundFieldAccess(syntax, meReferenceOpt, fieldSymbol, True, fieldSymbol.Type)
Else
' We can get here when multiple WithEvents fields are initialized with As New ...
Dim propertySymbol = DirectCast(symbol, PropertySymbol)
accessExpression = New BoundPropertyAccess(syntax,
propertySymbol,
propertyGroupOpt:=Nothing,
accessKind:=PropertyAccessKind.Set,
isWriteable:=propertySymbol.HasSet,
receiverOpt:=meReferenceOpt,
arguments:=ImmutableArray(Of BoundExpression).Empty)
End If
Else
Debug.Assert(node.MemberAccessExpressionOpt IsNot Nothing)
' otherwise use the node stored in the bound initializer node
accessExpression = node.MemberAccessExpressionOpt
End If
Dim rewrittenStatement As BoundStatement
If Not createTemporary Then
Debug.Assert(objectInitializer.PlaceholderOpt IsNot Nothing)
' we need to replace the placeholder with it, so add it to the replacement map
AddPlaceholderReplacement(objectInitializer.PlaceholderOpt, accessExpression)
rewrittenStatement = VisitExpressionNode(node.InitialValue).ToStatement
RemovePlaceholderReplacement(objectInitializer.PlaceholderOpt)
Else
' in all other cases we want the initial value be assigned to the member (field or property)
rewrittenStatement = VisitExpression(New BoundAssignmentOperator(syntax,
accessExpression,
node.InitialValue,
suppressObjectClone:=False)).ToStatement
End If
If instrument Then
rewrittenStatement = _instrumenterOpt.InstrumentFieldOrPropertyInitializer(node, rewrittenStatement, symbolIndex, createTemporary)
End If
rewrittenStatements.Add(rewrittenStatement)
Next
Return New BoundStatementList(node.Syntax, rewrittenStatements.ToImmutableAndFree())
End Function
End Class
End Namespace
|
Public Class ProgramInfo
Public Id As UInt16 = 0
Public Name As String = ""
Public Added_Date As String = ""
Public Allow_View_Site As Boolean = 1
Public Allow_Download_Site As Boolean = 1
Public Allow_Download_Updater As Boolean = 1
Public Icon As String = ""
Public Description As String = ""
Public Platform As String = ""
Public Price As Single = 0
Public updates As New List(Of UpdateInfo)
Public Sub New()
End Sub
Public Sub New(name As String)
Load(name)
End Sub
Public Sub LoadThis()
Load(Reflection.Assembly.GetEntryAssembly.GetName.Name)
End Sub
Public Sub Load(name As String)
Dim p As New Dictionary(Of String, String)
p.Add("program", name)
Dim response = api.GetAPIResponse(APIAction.program_all, p)
If response IsNot Nothing AndAlso response <> "" Then LoadXML(response)
End Sub
Public Sub LoadXML(xml As String)
Try
Dim xmldoc As New Xml.XmlDocument()
xmldoc.LoadXml(xml)
Name = xmldoc.GetElementsByTagName("program")(0).Attributes("name").Value
Id = CInt(xmldoc.GetElementsByTagName("pid")(0).Value)
Platform = xmldoc.GetElementsByTagName("platform")(0).Value
Price = CSng(xmldoc.GetElementsByTagName("price")(0).Value)
Description = xmldoc.GetElementsByTagName("description")(0).Value
Icon = xmldoc.GetElementsByTagName("icon")(0).Value
Added_Date = xmldoc.GetElementsByTagName("added_date")(0).Value
Allow_Download_Site = (xmldoc.GetElementsByTagName("allow_download_site")(0).Value = "1")
Allow_Download_Updater = (xmldoc.GetElementsByTagName("allow_download_updater")(0).Value = "1")
Allow_View_Site = (xmldoc.GetElementsByTagName("allow_view_site")(0).Value = "1")
updates = New List(Of UpdateInfo)
For Each update As Xml.XmlElement In xmldoc.GetElementsByTagName("update")
Try
Dim ui As New UpdateInfo
ui.LoadXML(update)
updates.Add(ui)
Catch slex As Exception
Trace.WriteLine("Failed to load update for programinfo! : " + slex.Message)
End Try
Next
Catch ex As Exception
Trace.WriteLine("Failed to load XML for programinfo! : " + ex.Message)
End Try
End Sub
End Class
|
Imports System.Collections.Generic
Imports Slf4j = lombok.extern.slf4j.Slf4j
Imports Word2Vec = org.deeplearning4j.models.word2vec.Word2Vec
Imports Preconditions = org.nd4j.common.base.Preconditions
Imports INDArray = org.nd4j.linalg.api.ndarray.INDArray
Imports Nd4j = org.nd4j.linalg.factory.Nd4j
Imports INDArrayIndex = org.nd4j.linalg.indexing.INDArrayIndex
Imports NDArrayIndex = org.nd4j.linalg.indexing.NDArrayIndex
'
' * ******************************************************************************
' * *
' * *
' * * This program and the accompanying materials are made available under the
' * * terms of the Apache License, Version 2.0 which is available at
' * * https://www.apache.org/licenses/LICENSE-2.0.
' * *
' * * See the NOTICE file distributed with this work for additional
' * * information regarding copyright ownership.
' * * 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.
' * *
' * * SPDX-License-Identifier: Apache-2.0
' * *****************************************************************************
'
Namespace org.deeplearning4j.text.movingwindow
'JAVA TO VB CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
'ORIGINAL LINE: @Slf4j public class WindowConverter
Public Class WindowConverter
Private Sub New()
End Sub
''' <summary>
''' Converts a window (each word in the window)
'''
''' in to a vector.
'''
''' Keep in mind each window is a multi word context.
'''
''' From there, each word uses the passed in model
''' as a lookup table to get what vectors are relevant
''' to the passed in windows </summary>
''' <param name="window"> the window to take in. </param>
''' <param name="vec"> the model to use as a lookup table </param>
''' <returns> a concacneated 1 row array
''' containing all of the numbers for each word in the window </returns>
Public Shared Function asExampleArray(ByVal window As Window, ByVal vec As Word2Vec, ByVal normalize As Boolean) As INDArray
Dim length As Integer = vec.lookupTable().layerSize()
Dim words As IList(Of String) = window.getWords()
Dim windowSize As Integer = vec.getWindow()
Preconditions.checkState(words.Count = vec.getWindow())
Dim ret As INDArray = Nd4j.create(1, length * windowSize)
For i As Integer = 0 To words.Count - 1
Dim word As String = words(i)
Dim n As INDArray = If(normalize, vec.getWordVectorMatrixNormalized(word), vec.getWordVectorMatrix(word))
ret.put(New INDArrayIndex() {NDArrayIndex.interval(i * vec.lookupTable().layerSize(), i * vec.lookupTable().layerSize() + vec.lookupTable().layerSize())}, n)
Next i
Return ret
End Function
''' <summary>
''' Converts a window (each word in the window)
'''
''' in to a vector.
'''
''' Keep in mind each window is a multi word context.
'''
''' From there, each word uses the passed in model
''' as a lookup table to get what vectors are relevant
''' to the passed in windows </summary>
''' <param name="window"> the window to take in. </param>
''' <param name="vec"> the model to use as a lookup table </param>
''' <returns> a concatneated 1 row array
''' containing all of the numbers for each word in the window </returns>
Public Shared Function asExampleMatrix(ByVal window As Window, ByVal vec As Word2Vec) As INDArray
Dim data((window.getWords().Count) - 1) As INDArray
For i As Integer = 0 To data.Length - 1
data(i) = vec.getWordVectorMatrix(window.getWord(i))
' if there's null elements
If data(i) Is Nothing Then
data(i) = Nd4j.zeros(1, vec.LayerSize)
End If
Next i
Return Nd4j.hstack(data)
End Function
End Class
End Namespace |
Imports System
Imports System.Diagnostics
Imports System.Collections.Generic
Imports System.Reflection
Imports System.Text
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Input
Imports DevZest.Windows.Docking
Namespace DevZest.DockSample
''' <summary>
''' Interaction logic for MainPage.xaml
''' </summary>
Partial Class MainPage
Private Shared IsLayoutSavedPropertyKey As DependencyPropertyKey = DependencyProperty.RegisterReadOnly("IsLayoutSaved", GetType(System.Boolean), GetType(MainPage), New FrameworkPropertyMetadata(False))
Public Shared IsLayoutSavedProperty As DependencyProperty = IsLayoutSavedPropertyKey.DependencyProperty
Public Property IsLayoutSaved As Boolean
Get
Return CType(GetValue(IsLayoutSavedProperty), Boolean)
End Get
Set(value As Boolean)
SetValue(IsLayoutSavedPropertyKey, value)
End Set
End Property
Private _lastDocumentId As Integer
Public Sub New()
MyBase.New()
InitializeComponent()
Dim sb As StringBuilder = New StringBuilder
sb.AppendLine("***** Welcome to DevZest WPF docking! *****")
sb.AppendLine(String.Format("===== CLR Version: {0}, Loaded Assemblies:", Environment.Version))
For Each assembly As Assembly In AppDomain.CurrentDomain.GetAssemblies
sb.AppendLine(assembly.FullName)
Next
Output.AppendLog(sb.ToString)
End Sub
Private Sub NewDocument(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
_lastDocumentId = _lastDocumentId + 1
Dim document As Document = New Document(_lastDocumentId)
document.Show(dockControl)
End Sub
Private Sub CanExecuteCloseActiveDocument(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs)
e.CanExecute = (Not (DockControl.ActiveDocument) Is Nothing)
End Sub
Private Sub CloseActiveDocument(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
DockControl.ActiveDocument.PerformClose()
End Sub
Private Sub OnFocusedItemChanged(ByVal sender As Object, ByVal e As EventArgs)
Output.AppendLog(String.Format("FocusedItemChanged: FocusedItem={0}", GetString(DockControl.FocusedItem)))
End Sub
Private Sub OnActiveItemChanged(ByVal sender As Object, ByVal e As EventArgs)
Output.AppendLog(String.Format("ActiveItemChanged: ActiveItem={0}", GetString(DockControl.ActiveItem)))
End Sub
Private Sub OnActiveDocumentChanged(ByVal sender As Object, ByVal e As EventArgs)
Output.AppendLog(String.Format("ActiveDocumentChanged: ActiveDocument={0}", GetString(DockControl.ActiveDocument)))
End Sub
Private Sub OnDockItemStateChanging(ByVal sender As Object, ByVal e As DockItemStateEventArgs)
Output.AppendLog(String.Format("DockItemStateChanging: {0}", GetString(e)))
End Sub
Private Sub OnDockItemStateChanged(ByVal sender As Object, ByVal e As DockItemStateEventArgs)
Output.AppendLog(String.Format("DockItemStateChanged: {0}", GetString(e)))
End Sub
Private Overloads Function GetString(ByVal item As DockItem) As String
If (item Is Nothing) Then
Return "null"
Else
Return item.TabText
End If
End Function
Private Overloads Function GetString(ByVal e As DockItemStateEventArgs) As String
If (e.OldDockPosition = e.NewDockPosition) Then
Return String.Format("DockItem={0}, StateChangeMethod={1}, ShowMethod={2}", GetString(e.DockItem), e.StateChangeMethod, e.ShowMethod)
Else
Return String.Format("DockItem={0}, StateChangeMethod={1}, DockPosition={2}->{3}, ShowMethod={4}", GetString(e.DockItem), e.StateChangeMethod, e.OldDockPosition, e.NewDockPosition, e.ShowMethod)
End If
End Function
Private Function LoadDockItem(ByVal obj As Object) As DockItem
If Welcome.GetType.ToString.Equals(obj) Then
Return Me.welcome
ElseIf SavedLayout.GetType.ToString.Equals(obj) Then
Return Me.savedLayout
ElseIf Output.GetType.ToString.Equals(obj) Then
Return Me.output
ElseIf SolutionExplorer.GetType.ToString.Equals(obj) Then
Return Me.solutionExplorer
ElseIf PropertiesWindow.GetType.ToString.Equals(obj) Then
Return Me.propertiesWindow
Else
Return CType(obj, DockItem)
End If
End Function
Private Sub SaveLayout_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
SavedLayout.Save(DockControl)
IsLayoutSaved = True
End Sub
Private Sub LoadLayout_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
CloseAll()
savedLayout.Load(dockControl, AddressOf LoadDockItem)
End Sub
Private Sub CloseAll()
Dim i As Integer = (DockControl.DockItems.Count - 1)
Do While (i >= 0)
Dim item As DockItem
item = dockControl.DockItems(i)
item.Close()
i = (i - 1)
Loop
End Sub
Private Sub ChangeTheme(ByVal themeName As String)
If String.IsNullOrEmpty(themeName) Then
DockSample.Themes.Reset()
DevZest.Windows.Docking.Themes.Reset()
Else
DockSample.Themes.Load(themeName)
DevZest.Windows.Docking.Themes.Load(themeName)
End If
_defaultTheme.IsChecked = String.IsNullOrEmpty(themeName)
_expressionDark.IsChecked = (themeName = "ExpressionDark")
_vs2010.IsChecked = (themeName = "VS2010")
End Sub
Private Sub Theme_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
Dim menuItem As MenuItem = CType(sender, MenuItem)
Dim theme As String = CType(menuItem.CommandParameter, String)
ChangeTheme(theme)
End Sub
End Class
End Namespace |
'''<Summary>The SVGFECompositeElement interface corresponds to the <feComposite> element.</Summary>
<DynamicInterface(GetType(EcmaScriptObject))>
Public Interface [SVGFECompositeElement]
Inherits SVGElement, SVGFilterPrimitiveStandardAttributes
'''<Summary>An SVGAnimatedString corresponding to the in attribute of the given element.</Summary>
ReadOnly Property [in1] As SVGAnimatedString
'''<Summary>An SVGAnimatedEnumeration corresponding to the type attribute of the given element. It takes one of the SVG_FECOMPOSITE_OPERATOR_* constants defined on this interface.</Summary>
ReadOnly Property [type] As Dynamic
'''<Summary>An SVGAnimatedNumberList corresponding to the values attribute of the given element.</Summary>
ReadOnly Property [values] As SVGAnimatedNumberList
End Interface |
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
<TestClass()> Public Class StructuredPacketTests
<TestMethod()> Public Sub SP_CrcCheck()
Dim pkt As New StructuredPacket
Dim int1 As Integer = 10
Dim bytes As Byte() = {1, 2, 3, 4, 5}
pkt.Add("Bytes", bytes)
pkt.EnableCRC = True
Dim coded = pkt.ToBytePacket
coded.Bytes(coded.Bytes.Length - 1) = coded.Bytes(coded.Bytes.Length - 1) Xor 170
TestException(Sub()
Dim decoded As New StructuredPacket(coded)
End Sub, "CRC error must be found")
Assert.AreEqual(True, pkt.EnableCRC)
End Sub
<TestMethod()> Public Sub SP_CodeDecodeArrays()
Dim pkt As New StructuredPacket
Dim arr1 = {"Cat", "Dog"}
Dim arr2 = {"Cat", ""}
Dim arr3 = {""}
Dim arr4 As String() = {}
pkt.Add("Arr1", arr1)
pkt.Add("Arr2", arr2)
pkt.Add("Arr3", arr3)
pkt.Add("Arr4", arr4)
Dim coded = pkt.ToBytePacket
Dim decoded As New StructuredPacket(coded)
Assert.IsInstanceOfType(decoded.Parts("Arr1"), GetType(String()))
Assert.IsInstanceOfType(decoded.Parts("Arr2"), GetType(String()))
Assert.IsInstanceOfType(decoded.Parts("Arr3"), GetType(String()))
Assert.IsInstanceOfType(decoded.Parts("Arr4"), GetType(String()))
CompareArrays(Of String)(arr1, decoded.Parts("Arr1"))
CompareArrays(Of String)(arr2, decoded.Parts("Arr2"))
CompareArrays(Of String)(arr3, decoded.Parts("Arr3"))
CompareArrays(Of String)(arr4, decoded.Parts("Arr4"))
End Sub
<TestMethod()> Public Sub SP_CodeDecode()
Dim pkt As New StructuredPacket
Dim int1 As Integer = 10
Dim long1 As Long = -645645645645645747
Dim sng1 As Single = 55646.5
Dim dbl1 As Double = -55435646.5
Dim str1 As String = "CatsCatsCats" + vbCrLf + "rerwrwer"
Dim bool1 As Boolean = True
Dim datetime1 As DateTime = Now.ToLocalTime
Dim datetime2 As DateTime = Now.ToUniversalTime
Dim bytes = PrepareData(0.1)
pkt.ReplyToID = 53465465
pkt.Add("Int1", int1)
pkt.Add("Long1", long1)
pkt.Add("Sng1", sng1)
pkt.Add("Dbl1", dbl1)
pkt.Add("String1", str1)
pkt.Add("Bool1", bool1)
pkt.Add("Date1", datetime1)
pkt.Add("Date2", datetime2)
pkt.Add("Bytes", bytes)
pkt.AddressFrom = "Addr1"
pkt.AddressTo = "Addr2"
pkt.ServiceID = "ServiceId1"
pkt.EnableCRC = True
Dim coded = pkt.ToBytePacket
Dim decoded As New StructuredPacket(coded)
Assert.AreEqual(pkt.AddressFrom, decoded.AddressFrom)
Assert.AreEqual(pkt.AddressTo, decoded.AddressTo)
Assert.AreEqual(pkt.ServiceID, decoded.ServiceID)
Assert.AreEqual(decoded.Parts("Int1"), int1)
Assert.AreEqual(decoded.Parts("Long1"), long1)
Assert.AreEqual(decoded.Parts("Sng1"), sng1)
Assert.AreEqual(decoded.Parts("Dbl1"), dbl1)
Assert.AreEqual(decoded.Parts("String1"), str1)
Assert.AreEqual(decoded.Parts("Bool1"), bool1)
Assert.AreEqual(decoded.Parts("Date1"), datetime1)
Assert.AreEqual(decoded.Parts("Date2"), datetime2)
Assert.IsInstanceOfType(decoded.Parts("Int1"), GetType(Integer))
Assert.IsInstanceOfType(decoded.Parts("Long1"), GetType(Long))
Assert.IsInstanceOfType(decoded.Parts("Sng1"), GetType(Single))
Assert.IsInstanceOfType(decoded.Parts("Dbl1"), GetType(Double))
Assert.IsInstanceOfType(decoded.Parts("String1"), GetType(String))
Assert.IsInstanceOfType(decoded.Parts("Date1"), GetType(DateTime))
Assert.IsInstanceOfType(decoded.Parts("Bytes"), GetType(Byte()))
Assert.AreEqual(True, decoded.EnableCRC)
Assert.AreEqual(pkt.ReplyToID, decoded.ReplyToID)
Assert.AreEqual(pkt.MsgID, decoded.MsgID)
CompareArrays(Of Byte)(bytes, decoded.Parts("Bytes"))
' Assert.AreSame()
End Sub
<TestMethod()> Public Sub SP_CodeDecodeEmpty()
Dim pkt As New StructuredPacket
Dim coded = pkt.ToBytePacket
Dim decoded As New StructuredPacket(coded)
If decoded.Parts.Count <> 0 Then Throw New Exception
End Sub
<TestMethod()> Public Sub SP_Keys()
Dim pkt As New StructuredPacket
TestException(Sub()
pkt.Add("Key1", 1)
pkt.Add("Key1", 1)
End Sub, "Same keys must not be added")
TestException(Sub()
pkt.Add("", 1)
End Sub, "Empty keys must not be added")
TestException(Sub()
pkt.Add(Nothing, 1)
End Sub, "Null keys must not be added")
End Sub
End Class |
Imports HomeSeerAPI
Imports Scheduler
Imports System.Reflection
Imports System.Text
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters
Module Util
' interface status
' for InterfaceStatus function call
Public Const ERR_NONE = 0
Public Const ERR_SEND = 1
Public Const ERR_INIT = 2
Public hs As HomeSeerAPI.IHSApplication
Public callback As HomeSeerAPI.IAppCallbackAPI
Public mediacallback As HomeSeerAPI.IMediaAPI_HS
Public Const IFACE_NAME As String = "Sample Plugin"
Public Instance As String = "" ' set when SupportMultipleInstances is TRUE
Public gEXEPath As String = ""
Public gGlobalTempScaleF As Boolean = True
Public colTrigs_Sync As System.Collections.SortedList
Public colTrigs As System.Collections.SortedList
Public colActs_Sync As System.Collections.SortedList
Public colActs As System.Collections.SortedList
Private Demo_ARE As Threading.AutoResetEvent
Private Demo_Thread As Threading.Thread
Public Function StringIsNullOrEmpty(ByRef s As String) As Boolean
If String.IsNullOrEmpty(s) Then Return True
Return String.IsNullOrEmpty(s.Trim)
End Function
Friend Sub Demo_Start()
Dim StartIt As Boolean = False
If Demo_ARE Is Nothing Then
Demo_ARE = New Threading.AutoResetEvent(False)
End If
If Demo_Thread Is Nothing Then
StartIt = True
ElseIf Not Demo_Thread.IsAlive Then
StartIt = True
End If
If Not StartIt Then Exit Sub
Demo_Thread = New Threading.Thread(AddressOf Demo_Proc)
Demo_Thread.Name = "Sample Plug-In Number Generator for Trigger Demonstration"
Demo_Thread.Priority = Threading.ThreadPriority.BelowNormal
Demo_Thread.Start()
End Sub
Friend Function GetDecimals(ByVal D As Double) As Integer
Dim s As String = ""
Dim c(0) As Char
c(0) = "0" ' Trailing zeros to be removed.
D = Math.Abs(D) - Math.Abs(Int(D)) ' Remove the whole number so the result always starts with "0." which is a known quantity.
s = D.ToString("F30")
s = s.TrimEnd(c)
Return s.Length - 2 ' Minus 2 because that is the length of "0."
End Function
Friend RNum As New Random(2000)
Friend Function Demo_Generate_Weight() As Double
Dim Mult As Integer
Dim W As Double
' The sole purpose of this procedure is to generate random weights
' for the purpose of testing the triggers and actions in this plug-in.
Try
Do
Mult = RNum.Next(3)
Loop Until Mult > 0
W = (RNum.NextDouble * 2001) * Mult ' Generates a random weight between 0 and 6003 lbs.
Catch ex As Exception
Log(IFACE_NAME & " Error: Exception in demo number generation for Trigger 1: " & ex.Message, LogType.LOG_TYPE_WARNING)
End Try
Return W
End Function
Friend Class Volt_Demo
Public Sub New(ByVal Euro As Boolean)
MyBase.New()
mvarVoltTypeEuro = Euro
End Sub
Private mvarVoltTypeEuro As Boolean
Private mvarVoltage As Double
Private mvarAverageVoltage As Double
Private mvarSumVoltage As Double
Private mvarStart As Date = Date.MinValue
Private mvarCount As Integer
Public ReadOnly Property Voltage As Double
Get
Return mvarVoltage
End Get
End Property
Public ReadOnly Property AverageVoltage As Double
Get
Return mvarAverageVoltage
End Get
End Property
Public ReadOnly Property AverageSince As Date
Get
Return mvarStart
End Get
End Property
Public ReadOnly Property AverageCount As Integer
Get
Return mvarCount
End Get
End Property
Friend Sub ResetAverage()
mvarSumVoltage = 0
mvarAverageVoltage = 0
mvarCount = 0
End Sub
Friend RNum As New Random(IIf(mvarVoltTypeEuro, 220, 110))
Friend Sub Demo_Generate_Value()
' The sole purpose of this procedure is to generate random voltages for
' purposes of testing the triggers and actions in this plug-in.
Try
If HSPI.bShutDown Then Exit Sub
' Initialize time if it has not been done.
If mvarStart = Date.MinValue Then
mvarStart = Now
End If
mvarCount += 1
If mvarVoltTypeEuro Then
Do
mvarVoltage = (RNum.NextDouble * 240) + RNum.Next(20)
Loop While mvarVoltage < 205
Log("Voltage (European) = " & mvarVoltage.ToString, LogType.LOG_TYPE_INFO)
Else
Do
mvarVoltage = (RNum.NextDouble * 120) + RNum.Next(10)
Loop While mvarVoltage < 100
Log("Voltage (North American) = " & mvarVoltage.ToString, LogType.LOG_TYPE_INFO)
End If
mvarSumVoltage += mvarVoltage
mvarAverageVoltage = mvarSumVoltage / mvarCount
If Double.MaxValue - mvarSumVoltage <= 300 Then
mvarStart = Now
mvarSumVoltage = mvarVoltage
mvarCount = 1
End If
Catch ex As Exception
Log(IFACE_NAME & " Error: Exception in Value generation for Trigger 2: " & ex.Message, LogType.LOG_TYPE_WARNING)
End Try
End Sub
End Class
Friend Volt As Volt_Demo = Nothing
Friend VoltEuro As Volt_Demo = Nothing
Friend Sub Demo_Proc()
Dim obj As Object = Nothing
Dim Trig1 As MyTrigger1Ton = Nothing
Dim Trig2 As MyTrigger2Shoe = Nothing
Dim RND As New Random(1000)
Dim T As Integer
Dim Weight As Double
Dim WeightEven As Double
Try
Do
If HSPI.bShutDown Then Exit Do
If colTrigs Is Nothing Then
Demo_ARE.WaitOne(10000)
If HSPI.bShutDown Then Exit Do
Continue Do
End If
If colTrigs.Count < 1 Then
Demo_ARE.WaitOne(10000)
If HSPI.bShutDown Then Exit Do
Continue Do
End If
T = RND.Next(10000, 30000)
If HSPI.bShutDown Then Exit Do
Demo_ARE.WaitOne(T)
If HSPI.bShutDown Then Exit Do
Weight = Demo_Generate_Weight()
Dim i As Integer
i = Convert.ToInt32(Weight / 2000)
WeightEven = i * 2000
Log("----------------------------------------------------------------", LogType.LOG_TYPE_INFO)
Log("Weight = " & Weight.ToString & ", Even = " & WeightEven.ToString, LogType.LOG_TYPE_INFO)
Dim TrigsToCheck() As IAllRemoteAPI.strTrigActInfo = Nothing
Dim TC As IAllRemoteAPI.strTrigActInfo = Nothing
Dim Trig As strTrigger
' We have generated a new Weight, so let's see if we need to trigger events.
Try
' Step 1: Ask HomeSeer for any triggers that are for this plug-in and are Type 1
TrigsToCheck = Nothing
TrigsToCheck = callback.TriggerMatches(IFACE_NAME, 1, -1)
Catch ex As Exception
End Try
' Step 2: If triggers were returned, we need to check them against our trigger value.
If TrigsToCheck IsNot Nothing AndAlso TrigsToCheck.Count > 0 Then
For Each TC In TrigsToCheck
If TC.DataIn IsNot Nothing AndAlso TC.DataIn.Length > 10 Then
Trig = TriggerFromData(TC.DataIn)
Else
Trig = TriggerFromInfo(TC)
End If
If Not Trig.Result Then Continue For
If Trig.TrigObj Is Nothing Then Continue For
If Trig.WhichTrigger <> eTriggerType.OneTon Then Continue For
Try
Trig1 = CType(Trig.TrigObj, MyTrigger1Ton)
Catch ex As Exception
Trig1 = Nothing
End Try
If Trig1 Is Nothing Then Continue For
If Trig1.EvenTon Then
Log("Checking Weight Trigger (Even), " & WeightEven.ToString & " against trigger of " & Trig1.TriggerWeight.ToString, LogType.LOG_TYPE_INFO)
If WeightEven > Trig1.TriggerWeight Then
Log("Weight trigger is TRUE - calling FIRE! for event ID " & TC.evRef.ToString, LogType.LOG_TYPE_WARNING)
' Step 3: If a trigger matches, call FIRE!
callback.TriggerFire(IFACE_NAME, TC)
End If
Else
Log("Checking Weight Trigger, " & Weight.ToString & " against trigger of " & Trig1.TriggerWeight.ToString, LogType.LOG_TYPE_INFO)
If Weight > Trig1.TriggerWeight Then
Log("Weight trigger is TRUE - calling FIRE! for event ID " & TC.evRef.ToString, LogType.LOG_TYPE_WARNING)
callback.TriggerFire(IFACE_NAME, TC)
' Step 3: If a trigger matches, call FIRE!
End If
End If
Next
End If
If Volt Is Nothing Then Volt = New Volt_Demo(False)
If VoltEuro Is Nothing Then VoltEuro = New Volt_Demo(True)
Volt.Demo_Generate_Value()
VoltEuro.Demo_Generate_Value()
' We have generated a new Voltage, so let's see if we need to trigger events.
Try
' Step 1: Ask HomeSeer for any triggers that are for this plug-in and are Type 2, SubType 1
TrigsToCheck = Nothing
TrigsToCheck = callback.TriggerMatches(IFACE_NAME, 2, 1)
Catch ex As Exception
End Try
' Step 2: If triggers were returned, we need to check them against our trigger value.
If TrigsToCheck IsNot Nothing AndAlso TrigsToCheck.Count > 0 Then
For Each TC In TrigsToCheck
If TC.DataIn IsNot Nothing AndAlso TC.DataIn.Length > 10 Then
Trig = TriggerFromData(TC.DataIn)
Else
Trig = TriggerFromInfo(TC)
End If
If Not Trig.Result Then Continue For
If Trig.TrigObj Is Nothing Then Continue For
If Trig.WhichTrigger <> eTriggerType.TwoVolts Then Continue For
Try
Trig2 = CType(Trig.TrigObj, MyTrigger2Shoe)
Catch ex As Exception
Trig2 = Nothing
End Try
If Trig2 Is Nothing Then Continue For
If Trig2.SubTrigger2 Then Continue For ' Only checking SubType 1 right now.
If Trig2.EuroVoltage Then
Log("Checking Voltage Trigger: " & Math.Round(VoltEuro.Voltage, GetDecimals(Trig2.TriggerValue)).ToString & " vs Trigger Value " & Trig2.TriggerValue.ToString, LogType.LOG_TYPE_INFO)
If Math.Round(VoltEuro.Voltage, GetDecimals(Trig2.TriggerValue)) = Trig2.TriggerValue Then
' Step 3: If a trigger matches, call FIRE!
Log("Voltage trigger is TRUE - calling FIRE! for event ID " & TC.evRef.ToString, LogType.LOG_TYPE_WARNING)
callback.TriggerFire(IFACE_NAME, TC)
End If
Else
Log("Checking Voltage Trigger: " & Math.Round(Volt.Voltage, GetDecimals(Trig2.TriggerValue)).ToString & " vs Trigger Value " & Trig2.TriggerValue.ToString, LogType.LOG_TYPE_INFO)
If Math.Round(Volt.Voltage, GetDecimals(Trig2.TriggerValue)) = Trig2.TriggerValue Then
' Step 3: If a trigger matches, call FIRE!
Log("Voltage trigger is TRUE - calling FIRE! for event ID " & TC.evRef.ToString, LogType.LOG_TYPE_WARNING)
callback.TriggerFire(IFACE_NAME, TC)
End If
End If
Next
End If
' We have generated a new Voltage, so let's see if we need to trigger events.
Try
' Step 1: Ask HomeSeer for any triggers that are for this plug-in and are Type 2, SubType 2
' (We did Type 2 SubType 1 up above)
TrigsToCheck = Nothing
TrigsToCheck = callback.TriggerMatches(IFACE_NAME, 2, 2)
Catch ex As Exception
End Try
' Step 2: If triggers were returned, we need to check them against our trigger value.
If TrigsToCheck IsNot Nothing AndAlso TrigsToCheck.Count > 0 Then
For Each TC In TrigsToCheck
If TC.DataIn IsNot Nothing AndAlso TC.DataIn.Length > 10 Then
Trig = TriggerFromData(TC.DataIn)
Else
Trig = TriggerFromInfo(TC)
End If
If Not Trig.Result Then Continue For
If Trig.TrigObj Is Nothing Then Continue For
If Trig.WhichTrigger <> eTriggerType.TwoVolts Then Continue For
Try
Trig2 = CType(Trig.TrigObj, MyTrigger2Shoe)
Catch ex As Exception
Trig2 = Nothing
End Try
If Trig2 Is Nothing Then Continue For
If Not Trig2.SubTrigger2 Then Continue For ' Only checking SubType 2 right now.
If Trig2.EuroVoltage Then
Log("Checking Avg Voltage Trigger: " & Math.Round(VoltEuro.AverageVoltage, GetDecimals(Trig2.TriggerValue)).ToString & " vs Trigger Value " & Trig2.TriggerValue.ToString, LogType.LOG_TYPE_INFO)
If Math.Round(VoltEuro.AverageVoltage, GetDecimals(Trig2.TriggerValue)) = Trig2.TriggerValue Then
' Step 3: If a trigger matches, call FIRE!
Log("Average Voltage trigger is TRUE - calling FIRE! for event ID " & TC.evRef.ToString, LogType.LOG_TYPE_WARNING)
callback.TriggerFire(IFACE_NAME, TC)
End If
Else
Log("Checking Avg Voltage Trigger: " & Math.Round(Volt.AverageVoltage, GetDecimals(Trig2.TriggerValue)).ToString & " vs Trigger Value " & Trig2.TriggerValue.ToString, LogType.LOG_TYPE_INFO)
If Math.Round(Volt.AverageVoltage, GetDecimals(Trig2.TriggerValue)) = Trig2.TriggerValue Then
' Step 3: If a trigger matches, call FIRE!
Log("Average Voltage trigger is TRUE - calling FIRE! for event ID " & TC.evRef.ToString, LogType.LOG_TYPE_WARNING)
callback.TriggerFire(IFACE_NAME, TC)
End If
End If
Next
End If
Loop
Catch ex As Exception
End Try
End Sub
Enum LogType
LOG_TYPE_INFO = 0
LOG_TYPE_ERROR = 1
LOG_TYPE_WARNING = 2
End Enum
Public Sub Log(ByVal msg As String, ByVal logType As LogType)
Try
If msg Is Nothing Then msg = ""
If Not [Enum].IsDefined(GetType(LogType), logType) Then
logType = Util.LogType.LOG_TYPE_ERROR
End If
Console.WriteLine(msg)
Select Case logType
Case logType.LOG_TYPE_ERROR
hs.WriteLog(IFACE_NAME & " Error", msg)
Case logType.LOG_TYPE_WARNING
hs.WriteLog(IFACE_NAME & " Warning", msg)
Case logType.LOG_TYPE_INFO
hs.WriteLog(IFACE_NAME, msg)
End Select
Catch ex As Exception
Console.WriteLine("Exception in LOG of " & IFACE_NAME & ": " & ex.Message)
End Try
End Sub
Friend Enum eTriggerType
OneTon = 1
TwoVolts = 2
Unknown = 0
End Enum
Friend Enum eActionType
Unknown = 0
Weight = 1
Voltage = 2
End Enum
Friend Structure strTrigger
Public WhichTrigger As eTriggerType
Public TrigObj As Object
Public Result As Boolean
End Structure
Friend Structure strAction
Public WhichAction As eActionType
Public ActObj As Object
Public Result As Boolean
End Structure
Friend Function TriggerFromData(ByRef Data As Byte()) As strTrigger
Dim ST As New strTrigger
ST.WhichTrigger = eTriggerType.Unknown
ST.Result = False
If Data Is Nothing Then Return ST
If Data.Length < 1 Then Return ST
Dim bRes As Boolean = False
Dim Trig1 As New MyTrigger1Ton
Dim Trig2 As New MyTrigger2Shoe
Try
bRes = DeSerializeObject(Data, Trig1)
Catch ex As Exception
bRes = False
End Try
If bRes And Trig1 IsNot Nothing Then
ST.WhichTrigger = eTriggerType.OneTon
ST.TrigObj = Trig1
ST.Result = True
Return ST
End If
Try
bRes = DeSerializeObject(Data, Trig2)
Catch ex As Exception
bRes = False
End Try
If bRes And Trig2 IsNot Nothing Then
ST.WhichTrigger = eTriggerType.TwoVolts
ST.TrigObj = Trig2
ST.Result = True
Return ST
End If
ST.WhichTrigger = eTriggerType.Unknown
ST.TrigObj = Nothing
ST.Result = False
Return ST
End Function
Friend Function ActionFromData(ByRef Data As Byte()) As strAction
Dim ST As New strAction
ST.WhichAction = eActionType.Unknown
ST.Result = False
If Data Is Nothing Then Return ST
If Data.Length < 1 Then Return ST
Dim bRes As Boolean = False
Dim Act1 As New MyAction1EvenTon
Dim Act2 As New MyAction2Euro
Try
bRes = DeSerializeObject(Data, Act1)
Catch ex As Exception
bRes = False
End Try
If bRes And Act1 IsNot Nothing Then
ST.WhichAction = eActionType.Weight
ST.ActObj = Act1
ST.Result = True
Return ST
End If
Try
bRes = DeSerializeObject(Data, Act2)
Catch ex As Exception
bRes = False
End Try
If bRes And Act2 IsNot Nothing Then
ST.WhichAction = eActionType.Voltage
ST.ActObj = Act2
ST.Result = True
Return ST
End If
ST.WhichAction = eActionType.Unknown
ST.ActObj = Nothing
ST.Result = False
Return ST
End Function
Sub Add_Update_Trigger(ByVal Trig As Object)
If Trig Is Nothing Then Exit Sub
Dim sKey As String = ""
If TypeOf Trig Is MyTrigger1Ton Then
Dim Trig1 As MyTrigger1Ton = Nothing
Try
Trig1 = CType(Trig, MyTrigger1Ton)
Catch ex As Exception
Trig1 = Nothing
End Try
If Trig1 IsNot Nothing Then
If Trig1.TriggerUID < 1 Then Exit Sub
sKey = "K" & Trig1.TriggerUID.ToString
If colTrigs.ContainsKey(sKey) Then
SyncLock colTrigs.SyncRoot
colTrigs.Remove(sKey)
End SyncLock
End If
colTrigs.Add(sKey, Trig1)
End If
ElseIf TypeOf Trig Is MyTrigger2Shoe Then
Dim Trig2 As MyTrigger2Shoe = Nothing
Try
Trig2 = CType(Trig, MyTrigger2Shoe)
Catch ex As Exception
Trig2 = Nothing
End Try
If Trig2 IsNot Nothing Then
If Trig2.TriggerUID < 1 Then Exit Sub
sKey = "K" & Trig2.TriggerUID.ToString
If colTrigs.ContainsKey(sKey) Then
SyncLock colTrigs.SyncRoot
colTrigs.Remove(sKey)
End SyncLock
End If
colTrigs.Add(sKey, Trig2)
End If
End If
End Sub
Sub Add_Update_Action(ByVal Act As Object)
If Act Is Nothing Then Exit Sub
Dim sKey As String = ""
If TypeOf Act Is MyAction1EvenTon Then
Dim Act1 As MyAction1EvenTon = Nothing
Try
Act1 = CType(Act, MyAction1EvenTon)
Catch ex As Exception
Act1 = Nothing
End Try
If Act1 IsNot Nothing Then
If Act1.ActionUID < 1 Then Exit Sub
sKey = "K" & Act1.ActionUID.ToString
If colActs.ContainsKey(sKey) Then
SyncLock colActs.SyncRoot
colActs.Remove(sKey)
End SyncLock
End If
colActs.Add(sKey, Act1)
End If
ElseIf TypeOf Act Is MyAction2Euro Then
Dim Act2 As MyAction2Euro = Nothing
Try
Act2 = CType(Act, MyAction2Euro)
Catch ex As Exception
Act2 = Nothing
End Try
If Act2 IsNot Nothing Then
If Act2.ActionUID < 1 Then Exit Sub
sKey = "K" & Act2.ActionUID.ToString
If colActs.ContainsKey(sKey) Then
SyncLock colActs.SyncRoot
colActs.Remove(sKey)
End SyncLock
End If
colActs.Add(sKey, Act2)
End If
End If
End Sub
Public MyDevice As Integer = -1
Public MyTempDevice As Integer = -1
Friend Sub Find_Create_Devices()
Dim col As New Collections.Generic.List(Of Scheduler.Classes.DeviceClass)
Dim dv As Scheduler.Classes.DeviceClass
Dim Found As Boolean = False
Try
Dim EN As Scheduler.Classes.clsDeviceEnumeration
EN = hs.GetDeviceEnumerator
If EN Is Nothing Then Throw New Exception(IFACE_NAME & " failed to get a device enumerator from HomeSeer.")
Do
dv = EN.GetNext
If dv Is Nothing Then Continue Do
If dv.Interface(Nothing) IsNot Nothing Then
If dv.Interface(Nothing).Trim = IFACE_NAME Then
col.Add(dv)
End If
End If
Loop Until EN.Finished
Catch ex As Exception
hs.WriteLog(IFACE_NAME & " Error", "Exception in Find_Create_Devices/Enumerator: " & ex.Message)
End Try
Try
Dim DT As DeviceTypeInfo = Nothing
If col IsNot Nothing AndAlso col.Count > 0 Then
For Each dv In col
If dv Is Nothing Then Continue For
If dv.Interface(hs) <> IFACE_NAME Then Continue For
DT = dv.DeviceType_Get(hs)
If DT IsNot Nothing Then
If DT.Device_API = DeviceTypeInfo.eDeviceAPI.Thermostat AndAlso DT.Device_Type = DeviceTypeInfo.eDeviceType_Thermostat.Temperature Then
' this is our temp device
Found = True
MyTempDevice = dv.Ref(Nothing)
hs.SetDeviceValueByRef(dv.Ref(Nothing), 72, False)
End If
If DT.Device_API = DeviceTypeInfo.eDeviceAPI.Thermostat AndAlso DT.Device_Type = DeviceTypeInfo.eDeviceType_Thermostat.Setpoint Then
Found = True
If DT.Device_SubType = DeviceTypeInfo.eDeviceSubType_Setpoint.Heating_1 Then
hs.SetDeviceValueByRef(dv.Ref(Nothing), 68, False)
End If
End If
If DT.Device_API = DeviceTypeInfo.eDeviceAPI.Thermostat AndAlso DT.Device_Type = DeviceTypeInfo.eDeviceType_Thermostat.Setpoint Then
Found = True
If DT.Device_SubType = DeviceTypeInfo.eDeviceSubType_Setpoint.Cooling_1 Then
hs.SetDeviceValueByRef(dv.Ref(Nothing), 75, False)
End If
End If
If DT.Device_API = DeviceTypeInfo.eDeviceAPI.Plug_In AndAlso DT.Device_Type = 69 Then
Found = True
MyDevice = dv.Ref(Nothing)
' Now (mostly for demonstration purposes) - work with the PlugExtraData object.
Dim EDO As HomeSeerAPI.clsPlugExtraData = Nothing
EDO = dv.PlugExtraData_Get(Nothing)
If EDO IsNot Nothing Then
Dim obj As Object = Nothing
obj = EDO.GetNamed("My Special Object")
If obj IsNot Nothing Then
Log("Plug-In Extra Data Object Retrieved = " & obj.ToString, LogType.LOG_TYPE_INFO)
End If
obj = EDO.GetNamed("My Count")
Dim MC As Integer = 1
If obj Is Nothing Then
If Not EDO.AddNamed("My Count", MC) Then
Log("Error adding named data object to plug-in sample device!", LogType.LOG_TYPE_ERROR)
Exit For
End If
dv.PlugExtraData_Set(hs) = EDO
hs.SaveEventsDevices()
Else
Try
MC = Convert.ToInt32(obj)
Catch ex As Exception
MC = -1
End Try
If MC < 0 Then Exit For
Log("Retrieved count from plug-in sample device is: " & MC.ToString, LogType.LOG_TYPE_INFO)
MC += 1
' Now put it back - need to remove the old one first.
EDO.RemoveNamed("My Count")
EDO.AddNamed("My Count", MC)
dv.PlugExtraData_Set(hs) = EDO
hs.SaveEventsDevices()
End If
End If
End If
End If
Next
End If
Catch ex As Exception
hs.WriteLog(IFACE_NAME & " Error", "Exception in Find_Create_Devices/Find: " & ex.Message)
End Try
Try
If Not Found Then
Dim ref As Integer
Dim GPair As VGPair = Nothing
ref = hs.NewDeviceRef("Sample Plugin Device with buttons and slider")
If ref > 0 Then
MyDevice = ref
dv = hs.GetDeviceByRef(ref)
Dim disp(1) As String
disp(0) = "This is a test of the"
disp(1) = "Emergency Broadcast Display Data system"
dv.AdditionalDisplayData(hs) = disp
dv.Address(hs) = "HOME"
dv.Code(hs) = "A1" ' set a code if needed, but not required
'dv.Can_Dim(hs) = True
dv.Device_Type_String(hs) = "My Sample Device"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Plug_In
DT.Device_Type = 69 ' our own device type
dv.DeviceType_Set(hs) = DT
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Last_Change(hs) = #5/21/1929 11:00:00 AM#
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim EDO As New HomeSeerAPI.clsPlugExtraData
dv.PlugExtraData_Set(hs) = EDO
' Now just for grins, let's modify it.
Dim HW As String = "Hello World"
If EDO.GetNamed("My Special Object") IsNot Nothing Then
EDO.RemoveNamed("My Special Object")
End If
EDO.AddNamed("My Special Object", HW)
' Need to re-save it.
dv.PlugExtraData_Set(hs) = EDO
' add an ON button and value
Dim Pair As VSPair
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 0
Pair.Status = "Off"
Pair.Render = Enums.CAPIControlType.Button
Pair.Render_Location.Row = 1
Pair.Render_Location.Column = 1
Pair.ControlUse = ePairControlUse._Off ' set this for UI apps like HSTouch so they know this is for OFF
hs.DeviceVSP_AddPair(ref, Pair)
GPair = New VGPair
GPair.PairType = VSVGPairType.SingleValue
GPair.Set_Value = 0
GPair.Graphic = "/images/HomeSeer/status/off.gif"
dv.ImageLarge(hs) = "/images/browser.png"
hs.DeviceVGP_AddPair(ref, GPair)
' add DIM values
Pair = New VSPair(ePairStatusControl.Both)
Pair.PairType = VSVGPairType.Range
Pair.ControlUse = ePairControlUse._Dim ' set this for UI apps like HSTouch so they know this is for lighting control dimming
Pair.RangeStart = 1
Pair.RangeEnd = 99
Pair.RangeStatusPrefix = "Dim "
Pair.RangeStatusSuffix = "%"
Pair.Render = Enums.CAPIControlType.ValuesRangeSlider
Pair.Render_Location.Row = 2
Pair.Render_Location.Column = 1
Pair.Render_Location.ColumnSpan = 3
hs.DeviceVSP_AddPair(ref, Pair)
' add graphic pairs for the dim levels
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 1
GPair.RangeEnd = 5.99999999
GPair.Graphic = "/images/HomeSeer/status/dim-00.gif"
hs.DeviceVGP_AddPair(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 6
GPair.RangeEnd = 15.99999999
GPair.Graphic = "/images/HomeSeer/status/dim-10.gif"
hs.DeviceVGP_AddPair(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 16
GPair.RangeEnd = 25.99999999
GPair.Graphic = "/images/HomeSeer/status/dim-20.gif"
hs.DeviceVGP_AddPair(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 26
GPair.RangeEnd = 35.99999999
GPair.Graphic = "/images/HomeSeer/status/dim-30.gif"
hs.DeviceVGP_AddPair(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 36
GPair.RangeEnd = 45.99999999
GPair.Graphic = "/images/HomeSeer/status/dim-40.gif"
hs.DeviceVGP_AddPair(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 46
GPair.RangeEnd = 55.99999999
GPair.Graphic = "/images/HomeSeer/status/dim-50.gif"
hs.DeviceVGP_AddPair(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 56
GPair.RangeEnd = 65.99999999
GPair.Graphic = "/images/HomeSeer/status/dim-60.gif"
hs.DeviceVGP_AddPair(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 66
GPair.RangeEnd = 75.99999999
GPair.Graphic = "/images/HomeSeer/status/dim-70.gif"
hs.DeviceVGP_AddPair(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 76
GPair.RangeEnd = 85.99999999
GPair.Graphic = "/images/HomeSeer/status/dim-80.gif"
hs.DeviceVGP_AddPair(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 86
GPair.RangeEnd = 95.99999999
GPair.Graphic = "/images/HomeSeer/status/dim-90.gif"
hs.DeviceVGP_AddPair(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 96
GPair.RangeEnd = 98.99999999
GPair.Graphic = "/images/HomeSeer/status/on.gif"
hs.DeviceVGP_AddPair(ref, GPair)
' add an OFF button and value
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 100
Pair.Status = "On"
Pair.ControlUse = ePairControlUse._On ' set this for UI apps like HSTouch so they know this is for lighting control ON
Pair.Render = Enums.CAPIControlType.Button
Pair.Render_Location.Row = 1
Pair.Render_Location.Column = 2
hs.DeviceVSP_AddPair(ref, Pair)
GPair = New VGPair
GPair.PairType = VSVGPairType.SingleValue
GPair.Set_Value = 100
GPair.Graphic = "/images/HomeSeer/status/on.gif"
hs.DeviceVGP_AddPair(ref, GPair)
' add an last level button and value
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 255
Pair.Status = "On Last Level"
Pair.Render = Enums.CAPIControlType.Button
Pair.Render_Location.Row = 1
Pair.Render_Location.Column = 3
hs.DeviceVSP_AddPair(ref, Pair)
' add a button that executes a special command but does not actually set any device value, here we will speak something
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Control) ' set the type to CONTROL only so that this value will never be displayed as a status
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 1000 ' we use a value that is not used as a status, this value will be handled in SetIOMult, see that function for the handling
Pair.Status = "Speak Hello"
Pair.Render = Enums.CAPIControlType.Button
Pair.Render_Location.Row = 1
Pair.Render_Location.Column = 3
hs.DeviceVSP_AddPair(ref, Pair)
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.MISC_Set(hs, Enums.dvMISC.NO_LOG)
'dv.MISC_Set(hs, Enums.dvMISC.STATUS_ONLY) ' set this for a status only device, no controls, and do not include the DeviceVSP calls above
Dim PED As clsPlugExtraData = dv.PlugExtraData_Get(hs)
If PED Is Nothing Then PED = New clsPlugExtraData
PED.AddNamed("Test", New Boolean)
PED.AddNamed("Device", dv)
dv.PlugExtraData_Set(hs) = PED
dv.Status_Support(hs) = True
dv.UserNote(hs) = "This is my user note - how do you like it? This device is version " & dv.Version.ToString
'hs.SetDeviceString(ref, "Not Set", False) ' this will override the name/value pairs
End If
ref = hs.NewDeviceRef("Sample Plugin Device with list values")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
'dv.Can_Dim(hs) = True
dv.Device_Type_String(hs) = "My Sample Device"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Plug_In
DT.Device_Type = 70
dv.DeviceType_Set(hs) = DT
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Last_Change(hs) = #5/21/1929 11:00:00 AM#
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim Pair As VSPair
' add list values, will appear as drop list control
Pair = New VSPair(ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Render = Enums.CAPIControlType.Values
Pair.Value = 1
Pair.Status = "1"
hs.DeviceVSP_AddPair(ref, Pair)
Pair = New VSPair(ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Render = Enums.CAPIControlType.Values
Pair.Value = 2
Pair.Status = "2"
hs.DeviceVSP_AddPair(ref, Pair)
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.MISC_Set(hs, Enums.dvMISC.NO_LOG)
'dv.MISC_Set(hs, Enums.dvMISC.STATUS_ONLY) ' set this for a status only device, no controls, and do not include the DeviceVSP calls above
dv.Status_Support(hs) = True
End If
ref = hs.NewDeviceRef("Sample Plugin Device with radio type control")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
'dv.Can_Dim(hs) = True
dv.Device_Type_String(hs) = "My Sample Device"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Plug_In
DT.Device_Type = 71
dv.DeviceType_Set(hs) = DT
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Last_Change(hs) = #5/21/1929 11:00:00 AM#
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim Pair As VSPair
' add values, will appear as a radio control and only allow one option to be selected at a time
Pair = New VSPair(ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Render = Enums.CAPIControlType.Radio_Option
Pair.Value = 1
Pair.Status = "Value 1"
hs.DeviceVSP_AddPair(ref, Pair)
Pair.Value = 2
Pair.Status = "Value 2"
hs.DeviceVSP_AddPair(ref, Pair)
Pair.Value = 3
Pair.Status = "Value 3"
hs.DeviceVSP_AddPair(ref, Pair)
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.MISC_Set(hs, Enums.dvMISC.NO_LOG)
'dv.MISC_Set(hs, Enums.dvMISC.STATUS_ONLY) ' set this for a status only device, no controls, and do not include the DeviceVSP calls above
dv.Status_Support(hs) = True
End If
ref = hs.NewDeviceRef("Sample Plugin Device with list text single selection")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
'dv.Can_Dim(hs) = True
dv.Device_Type_String(hs) = "My Sample Device"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Plug_In
DT.Device_Type = 72
dv.DeviceType_Set(hs) = DT
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Last_Change(hs) = #5/21/1929 11:00:00 AM#
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim Pair As VSPair
' add list values, will appear as drop list control
Pair = New VSPair(ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Render = Enums.CAPIControlType.Single_Text_from_List
Pair.Value = 1
Pair.Status = "String 1"
hs.DeviceVSP_AddPair(ref, Pair)
Pair = New VSPair(ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Render = Enums.CAPIControlType.Single_Text_from_List
Pair.Value = 2
Pair.Status = "String 2"
hs.DeviceVSP_AddPair(ref, Pair)
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.MISC_Set(hs, Enums.dvMISC.NO_LOG)
'dv.MISC_Set(hs, Enums.dvMISC.STATUS_ONLY) ' set this for a status only device, no controls, and do not include the DeviceVSP calls above
dv.Status_Support(hs) = True
End If
ref = hs.NewDeviceRef("Sample Plugin Device with list text multiple selection")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
'dv.Can_Dim(hs) = True
dv.Device_Type_String(hs) = "My Sample Device"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Plug_In
DT.Device_Type = 73
dv.DeviceType_Set(hs) = DT
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Last_Change(hs) = #5/21/1929 11:00:00 AM#
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim Pair As VSPair
' add list values, will appear as drop list control
Pair = New VSPair(ePairStatusControl.Control)
Pair.PairType = VSVGPairType.SingleValue
Pair.Render = Enums.CAPIControlType.List_Text_from_List
Pair.StringListAdd = "String 1"
Pair.StringListAdd = "String 2"
hs.DeviceVSP_AddPair(ref, Pair)
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.MISC_Set(hs, Enums.dvMISC.NO_LOG)
'dv.MISC_Set(hs, Enums.dvMISC.STATUS_ONLY) ' set this for a status only device, no controls, and do not include the DeviceVSP calls above
dv.Status_Support(hs) = True
End If
ref = hs.NewDeviceRef("Sample Plugin Device with text box text")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
'dv.Can_Dim(hs) = True
dv.Device_Type_String(hs) = "Sample Device with textbox input"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Plug_In
DT.Device_Type = 74
dv.DeviceType_Set(hs) = DT
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Last_Change(hs) = #5/21/1929 11:00:00 AM#
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim Pair As VSPair
' add text value it will appear in an editable text box
Pair = New VSPair(ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Render = Enums.CAPIControlType.TextBox_String
Pair.Value = 0
Pair.Status = "Default Text"
hs.DeviceVSP_AddPair(ref, Pair)
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.MISC_Set(hs, Enums.dvMISC.NO_LOG)
'dv.MISC_Set(hs, Enums.dvMISC.STATUS_ONLY) ' set this for a status only device, no controls, and do not include the DeviceVSP calls above
dv.Status_Support(hs) = True
End If
ref = hs.NewDeviceRef("Sample Plugin Device with text box number")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
'dv.Can_Dim(hs) = True
dv.Device_Type_String(hs) = "Sample Device with textbox input"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Plug_In
DT.Device_Type = 75
dv.DeviceType_Set(hs) = DT
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Last_Change(hs) = #5/21/1929 11:00:00 AM#
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim Pair As VSPair
' add text value it will appear in an editable text box
Pair = New VSPair(ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Render = Enums.CAPIControlType.TextBox_Number
Pair.Value = 0
Pair.Status = "Default Number"
Pair.Value = 0
hs.DeviceVSP_AddPair(ref, Pair)
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.MISC_Set(hs, Enums.dvMISC.NO_LOG)
'dv.MISC_Set(hs, Enums.dvMISC.STATUS_ONLY) ' set this for a status only device, no controls, and do not include the DeviceVSP calls above
dv.Status_Support(hs) = True
End If
' this demonstrates some controls that are displayed in a pop-up dialog on the device utility page
' this device is also set so the values/graphics pairs cannot be edited and no graphics displays for the status
ref = hs.NewDeviceRef("Sample Plugin Device with pop-up control")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
'dv.Can_Dim(hs) = True
dv.Device_Type_String(hs) = "My Sample Device"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Plug_In
DT.Device_Type = 76
dv.DeviceType_Set(hs) = DT
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Last_Change(hs) = #5/21/1929 11:00:00 AM#
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim Pair As VSPair
' add an OFF button and value
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 0
Pair.Status = "Off"
Pair.Render = Enums.CAPIControlType.Button
hs.DeviceVSP_AddPair(ref, Pair)
' add an ON button and value
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 100
Pair.Status = "On"
Pair.Render = Enums.CAPIControlType.Button
hs.DeviceVSP_AddPair(ref, Pair)
' add DIM values
Pair = New VSPair(ePairStatusControl.Both)
Pair.PairType = VSVGPairType.Range
Pair.RangeStart = 1
Pair.RangeEnd = 99
Pair.RangeStatusPrefix = "Dim "
Pair.RangeStatusSuffix = "%"
Pair.Render = Enums.CAPIControlType.ValuesRangeSlider
hs.DeviceVSP_AddPair(ref, Pair)
dv.MISC_Set(hs, Enums.dvMISC.CONTROL_POPUP) ' cause control to be displayed in a pop-up dialog
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.MISC_Set(hs, Enums.dvMISC.NO_LOG)
dv.Status_Support(hs) = True
End If
' this is a device that pop-ups and uses row/column attributes to position the controls on the form
ref = hs.NewDeviceRef("Sample Plugin Device with pop-up control row/column")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
dv.Device_Type_String(hs) = "My Sample Device"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Plug_In
DT.Device_Type = 77
dv.DeviceType_Set(hs) = DT
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Last_Change(hs) = #5/21/1929 11:00:00 AM#
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
' add an array of buttons formatted like a number pad
Dim Pair As VSPair
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 1
Pair.Status = "1"
Pair.Render = Enums.CAPIControlType.Button
Pair.Render_Location.Column = 1
Pair.Render_Location.Row = 1
hs.DeviceVSP_AddPair(ref, Pair)
Pair.Value = 2 : Pair.Status = "2" : Pair.Render_Location.Column = 2 : Pair.Render_Location.Row = 1 : hs.DeviceVSP_AddPair(ref, Pair)
Pair.Value = 3 : Pair.Status = "3" : Pair.Render_Location.Column = 3 : Pair.Render_Location.Row = 1 : hs.DeviceVSP_AddPair(ref, Pair)
Pair.Value = 4 : Pair.Status = "4" : Pair.Render_Location.Column = 1 : Pair.Render_Location.Row = 2 : hs.DeviceVSP_AddPair(ref, Pair)
Pair.Value = 5 : Pair.Status = "5" : Pair.Render_Location.Column = 2 : Pair.Render_Location.Row = 2 : hs.DeviceVSP_AddPair(ref, Pair)
Pair.Value = 6 : Pair.Status = "6" : Pair.Render_Location.Column = 3 : Pair.Render_Location.Row = 2 : hs.DeviceVSP_AddPair(ref, Pair)
Pair.Value = 7 : Pair.Status = "7" : Pair.Render_Location.Column = 1 : Pair.Render_Location.Row = 3 : hs.DeviceVSP_AddPair(ref, Pair)
Pair.Value = 8 : Pair.Status = "8" : Pair.Render_Location.Column = 2 : Pair.Render_Location.Row = 3 : hs.DeviceVSP_AddPair(ref, Pair)
Pair.Value = 9 : Pair.Status = "9" : Pair.Render_Location.Column = 3 : Pair.Render_Location.Row = 3 : hs.DeviceVSP_AddPair(ref, Pair)
Pair.Value = 10 : Pair.Status = "*" : Pair.Render_Location.Column = 1 : Pair.Render_Location.Row = 4 : hs.DeviceVSP_AddPair(ref, Pair)
Pair.Value = 0 : Pair.Status = "0" : Pair.Render_Location.Column = 2 : Pair.Render_Location.Row = 4 : hs.DeviceVSP_AddPair(ref, Pair)
Pair.Value = 11 : Pair.Status = "#" : Pair.Render_Location.Column = 3 : Pair.Render_Location.Row = 4 : hs.DeviceVSP_AddPair(ref, Pair)
Pair.Value = 12 : Pair.Status = "Clear" : Pair.Render_Location.Column = 1 : Pair.Render_Location.Row = 5 : Pair.Render_Location.ColumnSpan = 3 : hs.DeviceVSP_AddPair(ref, Pair)
dv.MISC_Set(hs, Enums.dvMISC.CONTROL_POPUP) ' cause control to be displayed in a pop-up dialog
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.MISC_Set(hs, Enums.dvMISC.NO_LOG)
dv.Status_Support(hs) = True
End If
' this device is created so that no graphics are displayed and the value/graphics pairs cannot be edited
ref = hs.NewDeviceRef("Sample Plugin Device no graphics")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
'dv.Can_Dim(hs) = True
dv.Device_Type_String(hs) = "My Sample Device"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Plug_In
DT.Device_Type = 76
dv.DeviceType_Set(hs) = DT
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Last_Change(hs) = #5/21/1929 11:00:00 AM#
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
dv.MISC_Set(hs, Enums.dvMISC.NO_GRAPHICS_DISPLAY) ' causes no graphics to display and value/graphics pairs cannot be edited
dv.MISC_Set(hs, Enums.dvMISC.CONTROL_POPUP) ' cause control to be displayed in a pop-up dialog
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.MISC_Set(hs, Enums.dvMISC.NO_LOG)
dv.Status_Support(hs) = True
End If
ref = hs.NewDeviceRef("Sample Plugin Device with color control")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
'dv.Can_Dim(hs) = True
dv.Device_Type_String(hs) = "My Sample Device"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Plug_In
DT.Device_Type = 76
dv.DeviceType_Set(hs) = DT
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Last_Change(hs) = #5/21/1929 11:00:00 AM#
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim Pair As VSPair
Pair = New VSPair(ePairStatusControl.Both)
Pair.PairType = VSVGPairType.Range
Pair.RangeStart = 1
Pair.RangeEnd = 99
Pair.RangeStatusPrefix = ""
Pair.RangeStatusSuffix = ""
Pair.Render = Enums.CAPIControlType.Color_Picker
hs.DeviceVSP_AddPair(ref, Pair)
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.Status_Support(hs) = True
End If
' build a thermostat device group,all of the following thermostat devices are grouped under this root device
gGlobalTempScaleF = Convert.ToBoolean(hs.GetINISetting("Settings", "gGlobalTempScaleF", "True").Trim) ' get the F or C setting from HS setup
Dim therm_root_dv As Scheduler.Classes.DeviceClass = Nothing
ref = hs.NewDeviceRef("Sample Plugin Thermostat Root Device")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
therm_root_dv = dv
dv.Address(hs) = "HOME"
dv.Device_Type_String(hs) = "Z-Wave Thermostat" ' this device type is set up in the default HSTouch projects so we set it here so the default project displays
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Thermostat
DT.Device_Type = DeviceTypeInfo.eDeviceType_Thermostat.Root
DT.Device_SubType = 0
DT.Device_SubType_Description = ""
dv.DeviceType_Set(hs) = DT
dv.MISC_Set(hs, Enums.dvMISC.STATUS_ONLY)
dv.Relationship(hs) = Enums.eRelationship.Parent_Root
hs.SaveEventsDevices()
End If
ref = hs.NewDeviceRef("Sample Plugin Thermostat Fan Device")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
dv.Device_Type_String(hs) = "Thermostat Fan"
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Thermostat
DT.Device_Type = DeviceTypeInfo.eDeviceType_Thermostat.Fan_Mode_Set
DT.Device_SubType = 0
DT.Device_SubType_Description = ""
dv.DeviceType_Set(hs) = DT
dv.Relationship(hs) = Enums.eRelationship.Child
If therm_root_dv IsNot Nothing Then
therm_root_dv.AssociatedDevice_Add(hs, ref)
End If
dv.AssociatedDevice_Add(hs, therm_root_dv.Ref(hs))
Dim Pair As VSPair
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 0
Pair.Status = "Auto"
Pair.Render = Enums.CAPIControlType.Button
Default_VS_Pairs_AddUpdateUtil(ref, Pair)
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 1
Pair.Status = "On"
Pair.Render = Enums.CAPIControlType.Button
Default_VS_Pairs_AddUpdateUtil(ref, Pair)
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.Status_Support(hs) = True
hs.SaveEventsDevices()
End If
ref = hs.NewDeviceRef("Sample Plugin Thermostat Mode Device")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
dv.Device_Type_String(hs) = "Thermostat Mode"
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Thermostat
DT.Device_Type = DeviceTypeInfo.eDeviceType_Thermostat.Operating_Mode
DT.Device_SubType = 0
DT.Device_SubType_Description = ""
dv.DeviceType_Set(hs) = DT
dv.Relationship(hs) = Enums.eRelationship.Child
If therm_root_dv IsNot Nothing Then
therm_root_dv.AssociatedDevice_Add(hs, ref)
End If
dv.AssociatedDevice_Add(hs, therm_root_dv.Ref(hs))
Dim Pair As VSPair
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 0
Pair.Status = "Off"
Pair.Render = Enums.CAPIControlType.Button
Default_VS_Pairs_AddUpdateUtil(ref, Pair)
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 1
Pair.Status = "Heat"
Pair.Render = Enums.CAPIControlType.Button
Default_VS_Pairs_AddUpdateUtil(ref, Pair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.SingleValue
GPair.Set_Value = 1
GPair.Graphic = "/images/HomeSeer/status/Heat.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 2
Pair.Status = "Cool"
Pair.Render = Enums.CAPIControlType.Button
Default_VS_Pairs_AddUpdateUtil(ref, Pair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.SingleValue
GPair.Set_Value = 2
GPair.Graphic = "/images/HomeSeer/status/Cool.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 3
Pair.Status = "Auto"
Pair.Render = Enums.CAPIControlType.Button
Default_VS_Pairs_AddUpdateUtil(ref, Pair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.SingleValue
GPair.Set_Value = 3
GPair.Graphic = "/images/HomeSeer/status/Auto.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.Status_Support(hs) = True
hs.SaveEventsDevices()
End If
ref = hs.NewDeviceRef("Sample Plugin Thermostat Heat Setpoint")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
dv.Device_Type_String(hs) = "Thermostat Heat Setpoint"
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Thermostat
DT.Device_Type = DeviceTypeInfo.eDeviceType_Thermostat.Setpoint
DT.Device_SubType = DeviceTypeInfo.eDeviceSubType_Setpoint.Heating_1
DT.Device_SubType_Description = ""
dv.DeviceType_Set(hs) = DT
dv.Relationship(hs) = Enums.eRelationship.Child
If therm_root_dv IsNot Nothing Then
therm_root_dv.AssociatedDevice_Add(hs, ref)
End If
dv.AssociatedDevice_Add(hs, therm_root_dv.Ref(hs))
Dim Pair As VSPair
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Status)
Pair.PairType = VSVGPairType.Range
Pair.RangeStart = -2147483648
Pair.RangeEnd = 2147483647
Pair.RangeStatusPrefix = ""
Pair.RangeStatusSuffix = " " & VSPair.ScaleReplace
Pair.IncludeValues = True
Pair.ValueOffset = 0
Pair.RangeStatusDecimals = 0
Pair.HasScale = True
Default_VS_Pairs_AddUpdateUtil(ref, Pair)
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Control)
Pair.PairType = VSVGPairType.Range
' 39F = 4C
' 50F = 10C
' 90F = 32C
If gGlobalTempScaleF Then
Pair.RangeStart = 50
Pair.RangeEnd = 90
Else
Pair.RangeStart = 10
Pair.RangeEnd = 32
End If
Pair.RangeStatusPrefix = ""
Pair.RangeStatusSuffix = " " & VSPair.ScaleReplace
Pair.IncludeValues = True
Pair.ValueOffset = 0
Pair.RangeStatusDecimals = 0
Pair.HasScale = True
Pair.Render = Enums.CAPIControlType.TextBox_Number
Default_VS_Pairs_AddUpdateUtil(ref, Pair)
' The scale does not matter because the global temperature scale setting
' will override and cause the temperature to always display in the user's
' selected scale, so use that in setting up the ranges.
'If dv.ZWData.Sensor_Scale = 1 Then ' Fahrenheit
If gGlobalTempScaleF Then
' Set up the ranges for Fahrenheit
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = -50
GPair.RangeEnd = 5
GPair.Graphic = "/images/HomeSeer/status/Thermometer-00.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 5.00000001
GPair.RangeEnd = 15.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-10.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 16
GPair.RangeEnd = 25.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-20.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 26
GPair.RangeEnd = 35.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-30.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 36
GPair.RangeEnd = 45.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-40.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 46
GPair.RangeEnd = 55.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-50.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 56
GPair.RangeEnd = 65.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-60.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 66
GPair.RangeEnd = 75.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-70.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 76
GPair.RangeEnd = 85.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-80.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 86
GPair.RangeEnd = 95.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-90.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 96
GPair.RangeEnd = 104.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-100.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 105
GPair.RangeEnd = 150.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-110.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
Else
' Celsius
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = -45
GPair.RangeEnd = -15
GPair.Graphic = "/images/HomeSeer/status/Thermometer-00.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = -14.999999
GPair.RangeEnd = -9.44
GPair.Graphic = "/images/HomeSeer/status/Thermometer-10.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = -9.43999999
GPair.RangeEnd = -3.88
GPair.Graphic = "/images/HomeSeer/status/Thermometer-20.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = -3.8799999
GPair.RangeEnd = 1.66
GPair.Graphic = "/images/HomeSeer/status/Thermometer-30.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 1.67
GPair.RangeEnd = 7.22
GPair.Graphic = "/images/HomeSeer/status/Thermometer-40.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 7.23
GPair.RangeEnd = 12.77
GPair.Graphic = "/images/HomeSeer/status/Thermometer-50.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 12.78
GPair.RangeEnd = 18.33
GPair.Graphic = "/images/HomeSeer/status/Thermometer-60.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 18.34
GPair.RangeEnd = 23.88
GPair.Graphic = "/images/HomeSeer/status/Thermometer-70.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 23.89
GPair.RangeEnd = 29.44
GPair.Graphic = "/images/HomeSeer/status/Thermometer-80.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 29.45
GPair.RangeEnd = 35
GPair.Graphic = "/images/HomeSeer/status/Thermometer-90.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 35.0000001
GPair.RangeEnd = 40
GPair.Graphic = "/images/HomeSeer/status/Thermometer-100.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 40.0000001
GPair.RangeEnd = 75
GPair.Graphic = "/images/HomeSeer/status/Thermometer-110.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
End If
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.Status_Support(hs) = True
hs.SaveEventsDevices()
End If
ref = hs.NewDeviceRef("Sample Plugin Thermostat Cool Setpoint")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
dv.Device_Type_String(hs) = "Thermostat Cool Setpoint"
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Thermostat
DT.Device_Type = DeviceTypeInfo.eDeviceType_Thermostat.Setpoint
DT.Device_SubType = DeviceTypeInfo.eDeviceSubType_Setpoint.Cooling_1
DT.Device_SubType_Description = ""
dv.DeviceType_Set(hs) = DT
dv.Relationship(hs) = Enums.eRelationship.Child
If therm_root_dv IsNot Nothing Then
therm_root_dv.AssociatedDevice_Add(hs, ref)
End If
dv.AssociatedDevice_Add(hs, therm_root_dv.Ref(hs))
Dim Pair As VSPair
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Status)
Pair.PairType = VSVGPairType.Range
Pair.RangeStart = -2147483648
Pair.RangeEnd = 2147483647
Pair.RangeStatusPrefix = ""
Pair.RangeStatusSuffix = " " & VSPair.ScaleReplace
Pair.IncludeValues = True
Pair.ValueOffset = 0
Pair.RangeStatusDecimals = 0
Pair.HasScale = True
Default_VS_Pairs_AddUpdateUtil(ref, Pair)
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Control)
Pair.PairType = VSVGPairType.Range
' 39F = 4C
' 50F = 10C
' 90F = 32C
If gGlobalTempScaleF Then
Pair.RangeStart = 50
Pair.RangeEnd = 90
Else
Pair.RangeStart = 10
Pair.RangeEnd = 32
End If
Pair.RangeStatusPrefix = ""
Pair.RangeStatusSuffix = " " & VSPair.ScaleReplace
Pair.IncludeValues = True
Pair.ValueOffset = 0
Pair.RangeStatusDecimals = 0
Pair.HasScale = True
Pair.Render = Enums.CAPIControlType.TextBox_Number
Default_VS_Pairs_AddUpdateUtil(ref, Pair)
' The scale does not matter because the global temperature scale setting
' will override and cause the temperature to always display in the user's
' selected scale, so use that in setting up the ranges.
'If dv.ZWData.Sensor_Scale = 1 Then ' Fahrenheit
If gGlobalTempScaleF Then
' Set up the ranges for Fahrenheit
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = -50
GPair.RangeEnd = 5
GPair.Graphic = "/images/HomeSeer/status/Thermometer-00.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 5.00000001
GPair.RangeEnd = 15.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-10.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 16
GPair.RangeEnd = 25.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-20.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 26
GPair.RangeEnd = 35.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-30.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 36
GPair.RangeEnd = 45.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-40.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 46
GPair.RangeEnd = 55.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-50.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 56
GPair.RangeEnd = 65.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-60.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 66
GPair.RangeEnd = 75.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-70.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 76
GPair.RangeEnd = 85.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-80.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 86
GPair.RangeEnd = 95.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-90.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 96
GPair.RangeEnd = 104.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-100.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 105
GPair.RangeEnd = 150.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-110.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
Else
' Celsius
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = -45
GPair.RangeEnd = -15
GPair.Graphic = "/images/HomeSeer/status/Thermometer-00.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = -14.999999
GPair.RangeEnd = -9.44
GPair.Graphic = "/images/HomeSeer/status/Thermometer-10.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = -9.43999999
GPair.RangeEnd = -3.88
GPair.Graphic = "/images/HomeSeer/status/Thermometer-20.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = -3.8799999
GPair.RangeEnd = 1.66
GPair.Graphic = "/images/HomeSeer/status/Thermometer-30.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 1.67
GPair.RangeEnd = 7.22
GPair.Graphic = "/images/HomeSeer/status/Thermometer-40.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 7.23
GPair.RangeEnd = 12.77
GPair.Graphic = "/images/HomeSeer/status/Thermometer-50.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 12.78
GPair.RangeEnd = 18.33
GPair.Graphic = "/images/HomeSeer/status/Thermometer-60.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 18.34
GPair.RangeEnd = 23.88
GPair.Graphic = "/images/HomeSeer/status/Thermometer-70.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 23.89
GPair.RangeEnd = 29.44
GPair.Graphic = "/images/HomeSeer/status/Thermometer-80.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 29.45
GPair.RangeEnd = 35
GPair.Graphic = "/images/HomeSeer/status/Thermometer-90.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 35.0000001
GPair.RangeEnd = 40
GPair.Graphic = "/images/HomeSeer/status/Thermometer-100.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 40.0000001
GPair.RangeEnd = 75
GPair.Graphic = "/images/HomeSeer/status/Thermometer-110.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
End If
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.Status_Support(hs) = True
hs.SaveEventsDevices()
End If
ref = hs.NewDeviceRef("Sample Plugin Thermostat Temp")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
dv.Device_Type_String(hs) = "Thermostat Temp"
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Thermostat
DT.Device_Type = DeviceTypeInfo.eDeviceType_Thermostat.Temperature
DT.Device_SubType = 1 ' temp
DT.Device_SubType_Description = ""
dv.DeviceType_Set(hs) = DT
dv.Relationship(hs) = Enums.eRelationship.Child
If therm_root_dv IsNot Nothing Then
therm_root_dv.AssociatedDevice_Add(hs, ref)
End If
dv.AssociatedDevice_Add(hs, therm_root_dv.Ref(hs))
Dim Pair As VSPair
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Status)
Pair.PairType = VSVGPairType.Range
Pair.RangeStart = -2147483648
Pair.RangeEnd = 2147483647
Pair.RangeStatusPrefix = ""
Pair.RangeStatusSuffix = " " & VSPair.ScaleReplace
Pair.IncludeValues = True
Pair.ValueOffset = 0
Pair.HasScale = True
Pair.RangeStatusDecimals = 0
Default_VS_Pairs_AddUpdateUtil(ref, Pair)
If gGlobalTempScaleF Then
' Set up the ranges for Fahrenheit
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = -50
GPair.RangeEnd = 5
GPair.Graphic = "/images/HomeSeer/status/Thermometer-00.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 5.00000001
GPair.RangeEnd = 15.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-10.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 16
GPair.RangeEnd = 25.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-20.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 26
GPair.RangeEnd = 35.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-30.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 36
GPair.RangeEnd = 45.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-40.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 46
GPair.RangeEnd = 55.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-50.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 56
GPair.RangeEnd = 65.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-60.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 66
GPair.RangeEnd = 75.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-70.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 76
GPair.RangeEnd = 85.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-80.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 86
GPair.RangeEnd = 95.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-90.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 96
GPair.RangeEnd = 104.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-100.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 105
GPair.RangeEnd = 150.99999999
GPair.Graphic = "/images/HomeSeer/status/Thermometer-110.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
Else
' Celsius
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = -45
GPair.RangeEnd = -15
GPair.Graphic = "/images/HomeSeer/status/Thermometer-00.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = -14.999999
GPair.RangeEnd = -9.44
GPair.Graphic = "/images/HomeSeer/status/Thermometer-10.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = -9.43999999
GPair.RangeEnd = -3.88
GPair.Graphic = "/images/HomeSeer/status/Thermometer-20.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = -3.8799999
GPair.RangeEnd = 1.66
GPair.Graphic = "/images/HomeSeer/status/Thermometer-30.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 1.67
GPair.RangeEnd = 7.22
GPair.Graphic = "/images/HomeSeer/status/Thermometer-40.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 7.23
GPair.RangeEnd = 12.77
GPair.Graphic = "/images/HomeSeer/status/Thermometer-50.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 12.78
GPair.RangeEnd = 18.33
GPair.Graphic = "/images/HomeSeer/status/Thermometer-60.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 18.34
GPair.RangeEnd = 23.88
GPair.Graphic = "/images/HomeSeer/status/Thermometer-70.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 23.89
GPair.RangeEnd = 29.44
GPair.Graphic = "/images/HomeSeer/status/Thermometer-80.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 29.45
GPair.RangeEnd = 35
GPair.Graphic = "/images/HomeSeer/status/Thermometer-90.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 35.0000001
GPair.RangeEnd = 40
GPair.Graphic = "/images/HomeSeer/status/Thermometer-100.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
GPair = New VGPair()
GPair.PairType = VSVGPairType.Range
GPair.RangeStart = 40.0000001
GPair.RangeEnd = 75
GPair.Graphic = "/images/HomeSeer/status/Thermometer-110.png"
Default_VG_Pairs_AddUpdateUtil(ref, GPair)
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.Status_Support(hs) = True
hs.SaveEventsDevices()
End If
End If
ref = hs.NewDeviceRef("Sample Plugin Thermostat Fan State")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
dv.Device_Type_String(hs) = "Thermostat Fan State"
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Thermostat
DT.Device_Type = DeviceTypeInfo.eDeviceType_Thermostat.Fan_Status
DT.Device_SubType = 0
DT.Device_SubType_Description = ""
dv.DeviceType_Set(hs) = DT
dv.Relationship(hs) = Enums.eRelationship.Child
If therm_root_dv IsNot Nothing Then
therm_root_dv.AssociatedDevice_Add(hs, ref)
End If
dv.AssociatedDevice_Add(hs, therm_root_dv.Ref(hs))
Dim Pair As VSPair
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Status)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 0
Pair.Status = "Off"
Default_VS_Pairs_AddUpdateUtil(ref, Pair)
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Status)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 1
Pair.Status = "On"
Default_VS_Pairs_AddUpdateUtil(ref, Pair)
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.Status_Support(hs) = True
hs.SaveEventsDevices()
End If
ref = hs.NewDeviceRef("Sample Plugin Thermostat Mode Status")
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
dv.Device_Type_String(hs) = "Thermostat Mode Status"
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Thermostat
DT.Device_Type = DeviceTypeInfo.eDeviceType_Thermostat.Operating_State
DT.Device_SubType = 0
DT.Device_SubType_Description = ""
dv.DeviceType_Set(hs) = DT
dv.Relationship(hs) = Enums.eRelationship.Child
If therm_root_dv IsNot Nothing Then
therm_root_dv.AssociatedDevice_Add(hs, ref)
End If
dv.AssociatedDevice_Add(hs, therm_root_dv.Ref(hs))
Dim Pair As VSPair
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Status)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 0
Pair.Status = "Idle"
Default_VS_Pairs_AddUpdateUtil(ref, Pair)
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Status)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 1
Pair.Status = "Heating"
Default_VS_Pairs_AddUpdateUtil(ref, Pair)
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Status)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 2
Pair.Status = "Cooling"
Default_VS_Pairs_AddUpdateUtil(ref, Pair)
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.Status_Support(hs) = True
hs.SaveEventsDevices()
End If
End If
Catch ex As Exception
hs.WriteLog(IFACE_NAME & " Error", "Exception in Find_Create_Devices/Create: " & ex.Message)
End Try
End Sub
Private Sub Default_VG_Pairs_AddUpdateUtil(ByVal dvRef As Integer, ByRef Pair As VGPair)
If Pair Is Nothing Then Exit Sub
If dvRef < 1 Then Exit Sub
If Not hs.DeviceExistsRef(dvRef) Then Exit Sub
Dim Existing As VGPair = Nothing
' The purpose of this procedure is to add the protected, default VS/VG pairs WITHOUT overwriting any user added
' pairs unless absolutely necessary (because they conflict).
Try
Existing = hs.DeviceVGP_Get(dvRef, Pair.Value) 'VGPairs.GetPairByValue(Pair.Value)
If Existing IsNot Nothing Then
hs.DeviceVGP_Clear(dvRef, Pair.Value)
hs.DeviceVGP_AddPair(dvRef, Pair)
Else
' There is not a pair existing, so just add it.
hs.DeviceVGP_AddPair(dvRef, Pair)
End If
Catch ex As Exception
End Try
End Sub
Private Sub Default_VS_Pairs_AddUpdateUtil(ByVal dvRef As Integer, ByRef Pair As VSPair)
If Pair Is Nothing Then Exit Sub
If dvRef < 1 Then Exit Sub
If Not hs.DeviceExistsRef(dvRef) Then Exit Sub
Dim Existing As VSPair = Nothing
' The purpose of this procedure is to add the protected, default VS/VG pairs WITHOUT overwriting any user added
' pairs unless absolutely necessary (because they conflict).
Try
Existing = hs.DeviceVSP_Get(dvRef, Pair.Value, Pair.ControlStatus) 'VSPairs.GetPairByValue(Pair.Value, Pair.ControlStatus)
If Existing IsNot Nothing Then
' This is unprotected, so it is a user's value/status pair.
If Existing.ControlStatus = HomeSeerAPI.ePairStatusControl.Both And Pair.ControlStatus <> HomeSeerAPI.ePairStatusControl.Both Then
' The existing one is for BOTH, so try changing it to the opposite of what we are adding and then add it.
If Pair.ControlStatus = HomeSeerAPI.ePairStatusControl.Status Then
If Not hs.DeviceVSP_ChangePair(dvRef, Existing, HomeSeerAPI.ePairStatusControl.Control) Then
hs.DeviceVSP_ClearBoth(dvRef, Pair.Value)
hs.DeviceVSP_AddPair(dvRef, Pair)
Else
hs.DeviceVSP_AddPair(dvRef, Pair)
End If
Else
If Not hs.DeviceVSP_ChangePair(dvRef, Existing, HomeSeerAPI.ePairStatusControl.Status) Then
hs.DeviceVSP_ClearBoth(dvRef, Pair.Value)
hs.DeviceVSP_AddPair(dvRef, Pair)
Else
hs.DeviceVSP_AddPair(dvRef, Pair)
End If
End If
ElseIf Existing.ControlStatus = HomeSeerAPI.ePairStatusControl.Control Then
' There is an existing one that is STATUS or CONTROL - remove it if ours is protected.
hs.DeviceVSP_ClearControl(dvRef, Pair.Value)
hs.DeviceVSP_AddPair(dvRef, Pair)
ElseIf Existing.ControlStatus = HomeSeerAPI.ePairStatusControl.Status Then
' There is an existing one that is STATUS or CONTROL - remove it if ours is protected.
hs.DeviceVSP_ClearStatus(dvRef, Pair.Value)
hs.DeviceVSP_AddPair(dvRef, Pair)
End If
Else
' There is not a pair existing, so just add it.
hs.DeviceVSP_AddPair(dvRef, Pair)
End If
Catch ex As Exception
End Try
End Sub
Private Sub CreateOneDevice(dev_name As String)
Dim ref As Integer
Dim dv As Scheduler.Classes.DeviceClass
ref = hs.NewDeviceRef(dev_name)
Console.WriteLine("Creating device named: " & dev_name)
If ref > 0 Then
dv = hs.GetDeviceByRef(ref)
dv.Address(hs) = "HOME"
'dv.Can_Dim(hs) = True
dv.Device_Type_String(hs) = "My Sample Device"
Dim DT As New DeviceTypeInfo
DT.Device_API = DeviceTypeInfo.eDeviceAPI.Plug_In
DT.Device_Type = 69
dv.DeviceType_Set(hs) = DT
dv.Interface(hs) = IFACE_NAME
dv.InterfaceInstance(hs) = ""
dv.Last_Change(hs) = #5/21/1929 11:00:00 AM#
dv.Location(hs) = IFACE_NAME
dv.Location2(hs) = "Sample Devices"
' add an ON button and value
Dim Pair As VSPair
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 100
Pair.Status = "On"
Pair.Render = Enums.CAPIControlType.Button
hs.DeviceVSP_AddPair(ref, Pair)
' add an OFF button and value
Pair = New VSPair(HomeSeerAPI.ePairStatusControl.Both)
Pair.PairType = VSVGPairType.SingleValue
Pair.Value = 0
Pair.Status = "Off"
Pair.Render = Enums.CAPIControlType.Button
hs.DeviceVSP_AddPair(ref, Pair)
' add DIM values
Pair = New VSPair(ePairStatusControl.Both)
Pair.PairType = VSVGPairType.Range
Pair.RangeStart = 1
Pair.RangeEnd = 99
Pair.RangeStatusPrefix = "Dim "
Pair.RangeStatusSuffix = "%"
Pair.Render = Enums.CAPIControlType.ValuesRangeSlider
hs.DeviceVSP_AddPair(ref, Pair)
'dv.MISC_Set(hs, Enums.dvMISC.CONTROL_POPUP) ' cause control to be displayed in a pop-up dialog
dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES)
dv.MISC_Set(hs, Enums.dvMISC.NO_LOG)
dv.Status_Support(hs) = True
End If
End Sub
Friend Function TriggerFromInfo(ByVal TrigInfo As HomeSeerAPI.IPlugInAPI.strTrigActInfo) As strTrigger
Dim sKey As String = ""
sKey = "K" & TrigInfo.UID.ToString
If colTrigs IsNot Nothing Then
If colTrigs.ContainsKey(sKey) Then
Dim obj As Object = Nothing
obj = colTrigs.Item(sKey)
If obj IsNot Nothing Then
Dim Ret As strTrigger
Ret.Result = False
If TypeOf obj Is MyTrigger1Ton Then
Ret.WhichTrigger = eTriggerType.OneTon
Ret.TrigObj = obj
Ret.Result = True
Return Ret
ElseIf TypeOf obj Is MyTrigger2Shoe Then
Ret.WhichTrigger = eTriggerType.TwoVolts
Ret.TrigObj = obj
Ret.Result = True
Return Ret
End If
End If
End If
End If
Dim Bad As strTrigger
Bad.WhichTrigger = eTriggerType.Unknown
Bad.Result = False
Bad.TrigObj = Nothing
Return Bad
End Function
Friend Function ActionFromInfo(ByVal ActInfo As HomeSeerAPI.IPlugInAPI.strTrigActInfo) As strAction
Dim sKey As String = ""
sKey = "K" & ActInfo.UID.ToString
If colActs IsNot Nothing Then
If colActs.ContainsKey(sKey) Then
Dim obj As Object = Nothing
obj = colActs.Item(sKey)
If obj IsNot Nothing Then
Dim Ret As strAction
Ret.Result = False
If TypeOf obj Is MyAction1EvenTon Then
Ret.WhichAction = eActionType.Weight
Ret.ActObj = obj
Ret.Result = True
Return Ret
ElseIf TypeOf obj Is MyAction2Euro Then
Ret.WhichAction = eActionType.Voltage
Ret.ActObj = obj
Ret.Result = True
Return Ret
End If
End If
End If
End If
Dim Bad As strAction
Bad.WhichAction = eActionType.Unknown
Bad.Result = False
Bad.ActObj = Nothing
Return Bad
End Function
Friend Function SerializeObject(ByRef ObjIn As Object, ByRef bteOut() As Byte) As Boolean
If ObjIn Is Nothing Then Return False
Dim str As New MemoryStream
Dim sf As New Binary.BinaryFormatter
Try
sf.Serialize(str, ObjIn)
ReDim bteOut(Convert.ToInt32(str.Length - 1))
bteOut = str.ToArray
Return True
Catch ex As Exception
Log(IFACE_NAME & " Error: Serializing object " & ObjIn.ToString & " :" & ex.Message, LogType.LOG_TYPE_ERROR)
Return False
End Try
End Function
Friend Function SerializeObject(ByRef ObjIn As Object, ByRef HexOut As String) As Boolean
If ObjIn Is Nothing Then Return False
Dim str As New MemoryStream
Dim sf As New Binary.BinaryFormatter
Dim bteOut() As Byte
Try
sf.Serialize(str, ObjIn)
ReDim bteOut(Convert.ToInt32(str.Length - 1))
bteOut = str.ToArray
HexOut = ""
For i As Integer = 0 To bteOut.Length - 1
HexOut &= bteOut(i).ToString("x2").ToUpper
Next
Return True
Catch ex As Exception
Log(IFACE_NAME & " Error: Serializing (Hex) object " & ObjIn.ToString & " :" & ex.Message, LogType.LOG_TYPE_ERROR)
Return False
End Try
End Function
Public Function DeSerializeObject(ByRef bteIn() As Byte, ByRef ObjOut As Object) As Boolean
' Almost immediately there is a test to see if ObjOut is NOTHING. The reason for this
' when the ObjOut is suppose to be where the deserialized object is stored, is that
' I could find no way to test to see if the deserialized object and the variable to
' hold it was of the same type. If you try to get the type of a null object, you get
' only a null reference exception! If I do not test the object type beforehand and
' there is a difference, then the InvalidCastException is thrown back in the CALLING
' procedure, not here, because the cast is made when the ByRef object is cast when this
' procedure returns, not earlier. In order to prevent a cast exception in the calling
' procedure that may or may not be handled, I made it so that you have to at least
' provide an initialized ObjOut when you call this - ObjOut is set to nothing after it
' is typed.
If bteIn Is Nothing Then Return False
If bteIn.Length < 1 Then Return False
If ObjOut Is Nothing Then Return False
Dim str As MemoryStream
Dim sf As New Binary.BinaryFormatter
Dim ObjTest As Object
Dim TType As System.Type
Dim OType As System.Type
Try
OType = ObjOut.GetType
ObjOut = Nothing
str = New MemoryStream(bteIn)
ObjTest = sf.Deserialize(str)
If ObjTest Is Nothing Then Return False
TType = ObjTest.GetType
If Not TType.Equals(OType) Then Return False
ObjOut = ObjTest
If ObjOut Is Nothing Then Return False
Return True
Catch exIC As InvalidCastException
Return False
Catch ex As Exception
Log(IFACE_NAME & " Error: DeSerializing object: " & ex.Message, LogType.LOG_TYPE_ERROR)
Return False
End Try
End Function
Public Function DeSerializeObject(ByRef HexIn As String, ByRef ObjOut As Object) As Boolean
' Almost immediately there is a test to see if ObjOut is NOTHING. The reason for this
' when the ObjOut is suppose to be where the deserialized object is stored, is that
' I could find no way to test to see if the deserialized object and the variable to
' hold it was of the same type. If you try to get the type of a null object, you get
' only a null reference exception! If I do not test the object type beforehand and
' there is a difference, then the InvalidCastException is thrown back in the CALLING
' procedure, not here, because the cast is made when the ByRef object is cast when this
' procedure returns, not earlier. In order to prevent a cast exception in the calling
' procedure that may or may not be handled, I made it so that you have to at least
' provide an initialized ObjOut when you call this - ObjOut is set to nothing after it
' is typed.
If HexIn Is Nothing Then Return False
If String.IsNullOrEmpty(HexIn.Trim) Then Return False
If ObjOut Is Nothing Then Return False
Dim str As MemoryStream
Dim sf As New Binary.BinaryFormatter
Dim ObjTest As Object
Dim TType As System.Type
Dim OType As System.Type
Dim bteIn() As Byte
Dim HowMany As Integer
Try
HowMany = Convert.ToInt32((HexIn.Length / 2) - 1)
ReDim bteIn(HowMany)
For i As Integer = 0 To HowMany
'bteIn(i) = CByte("&H" & HexIn.Substring(i * 2, 2))
bteIn(i) = Byte.Parse(HexIn.Substring(i * 2, 2), Globalization.NumberStyles.HexNumber)
Next
OType = ObjOut.GetType
ObjOut = Nothing
str = New MemoryStream(bteIn)
ObjTest = sf.Deserialize(str)
If ObjTest Is Nothing Then Return False
TType = ObjTest.GetType
If Not TType.Equals(OType) Then Return False
ObjOut = ObjTest
If ObjOut Is Nothing Then Return False
Return True
Catch exIC As InvalidCastException
Return False
Catch ex As Exception
Log(IFACE_NAME & " Error: DeSerializing object: " & ex.Message, LogType.LOG_TYPE_ERROR)
Return False
End Try
End Function
End Module
|
Imports System
Imports System.IO
Imports System.Collections.Generic
Imports Mal
Imports MalVal = Mal.types.MalVal
Imports MalInt = Mal.types.MalInt
Imports MalSymbol = Mal.types.MalSymbol
Imports MalList = Mal.types.MalList
Imports MalVector = Mal.types.MalVector
Imports MalHashMap = Mal.types.MalHashMap
Imports MalFunc = Mal.types.MalFunc
Imports MalEnv = Mal.env.Env
Namespace Mal
Class step5_tco
' read
Shared Function READ(str As String) As MalVal
Return reader.read_str(str)
End Function
' eval
Shared Function eval_ast(ast As MalVal, env As MalEnv) As MalVal
If TypeOf ast Is MalSymbol Then
return env.do_get(DirectCast(ast, MalSymbol))
Else If TypeOf ast Is MalList Then
Dim old_lst As MalList = DirectCast(ast, MalList)
Dim new_lst As MalList
If ast.list_Q() Then
new_lst = New MalList
Else
new_lst = DirectCast(New MalVector, MalList)
End If
Dim mv As MalVal
For Each mv in old_lst.getValue()
new_lst.conj_BANG(EVAL(mv, env))
Next
return new_lst
Else If TypeOf ast Is MalHashMap Then
Dim new_dict As New Dictionary(Of String, MalVal)
Dim entry As KeyValuePair(Of String, MalVal)
For Each entry in DirectCast(ast,MalHashMap).getValue()
new_dict.Add(entry.Key, EVAL(DirectCast(entry.Value,MalVal), env))
Next
return New MalHashMap(new_dict)
Else
return ast
End If
return ast
End Function
' TODO: move to types.vb when it is ported
Class FClosure
Public ast As MalVal
Public params As MalList
Public env As MalEnv
Function fn(args as MalList) As MalVal
return EVAL(ast, new MalEnv(env, params, args))
End Function
End Class
Shared Function EVAL(orig_ast As MalVal, env As MalEnv) As MalVal
Do
'Console.WriteLine("EVAL: {0}", printer._pr_str(orig_ast, true))
If not orig_ast.list_Q() Then
return eval_ast(orig_ast, env)
End If
' apply list
Dim ast As MalList = DirectCast(orig_ast, MalList)
If ast.size() = 0 Then
return ast
End If
Dim a0 As MalVal = ast(0)
Dim a0sym As String
If TypeOf a0 is MalSymbol Then
a0sym = DirectCast(a0,MalSymbol).getName()
Else
a0sym = "__<*fn*>__"
End If
Select a0sym
Case "def!"
Dim a1 As MalVal = ast(1)
Dim a2 As MalVal = ast(2)
Dim res As MalVal = EVAL(a2, env)
env.do_set(DirectCast(a1,MalSymbol), res)
return res
Case "let*"
Dim a1 As MalVal = ast(1)
Dim a2 As MalVal = ast(2)
Dim key As MalSymbol
Dim val as MalVal
Dim let_env As new MalEnv(env)
For i As Integer = 0 To (DirectCast(a1,MalList)).size()-1 Step 2
key = DirectCast(DirectCast(a1,MalList)(i),MalSymbol)
val = DirectCast(a1,MalList)(i+1)
let_env.do_set(key, EVAL(val, let_env))
Next
orig_ast = a2
env = let_env
Case "do"
eval_ast(ast.slice(1, ast.size()-1), env)
orig_ast = ast(ast.size()-1)
Case "if"
Dim a1 As MalVal = ast(1)
Dim cond As MalVal = EVAL(a1, env)
If cond Is Mal.types.Nil or cond Is Mal.types.MalFalse Then
' eval false slot form
If ast.size() > 3 Then
orig_ast = ast(3)
Else
return Mal.types.Nil
End If
Else
' eval true slot form
orig_ast = ast(2)
End If
Case "fn*"
Dim fc As New FClosure()
fc.ast = ast(2)
fc.params = DirectCast(ast(1),MalLIst)
fc.env = env
Dim f As Func(Of MalList, MalVal) = AddressOf fc.fn
Dim mf As new MalFunc(ast(2), env,
DirectCast(ast(1),MalList), f)
return DirectCast(mf,MalVal)
Case Else
Dim el As MalList = DirectCast(eval_ast(ast, env), MalList)
Dim f As MalFunc = DirectCast(el(0), MalFunc)
Dim fnast As MalVal = f.getAst()
If not fnast Is Nothing
orig_ast = fnast
env = f.genEnv(el.rest())
Else
Return f.apply(el.rest())
End If
End Select
Loop While True
End Function
' print
Shared Function PRINT(exp As MalVal) As String
return printer._pr_str(exp, TRUE)
End Function
' repl
Shared repl_env As MalEnv
Shared Function REP(str As String) As String
Return PRINT(EVAL(READ(str), repl_env))
End Function
Shared Function Main As Integer
Dim args As String() = Environment.GetCommandLineArgs()
repl_env = New MalEnv(Nothing)
' core.vb: defined using VB.NET
For Each entry As KeyValuePair(Of String,MalVal) In core.ns()
repl_env.do_set(new MalSymbol(entry.Key), entry.Value)
Next
' core.mal: defined using the language itself
REP("(def! not (fn* (a) (if a false true)))")
If args.Length > 1 AndAlso args(1) = "--raw" Then
Mal.readline.SetMode(Mal.readline.Modes.Raw)
End If
' repl loop
Dim line As String
Do
Try
line = Mal.readline.Readline("user> ")
If line is Nothing Then
Exit Do
End If
If line = "" Then
Continue Do
End If
Catch e As IOException
Console.WriteLine("IOException: " & e.Message)
End Try
Try
Console.WriteLine(REP(line))
Catch e as Exception
Console.WriteLine("Error: " & e.Message)
Console.WriteLine(e.StackTrace)
Continue Do
End Try
Loop While True
End function
End Class
End Namespace
|
' Copyright (C) 2010-2012 Thies Gerken
' This file is part of Fractals.
' Fractals is free software: you can redistribute it and/or modify
' it under the terms of the GNU General Public License as published by
' the Free Software Foundation, either version 3 of the License, or
' (at your option) any later version.
' Fractals is distributed in the hope that it will be useful,
' but WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
' GNU General Public License for more details.
' You should have received a copy of the GNU General Public License
' along with Fractals. If not, see <http://www.gnu.org/licenses/>.
Imports System.Windows
Imports System.ComponentModel
Imports Fractals.Mathematics
Public Class ComplexNumberSelector
Implements INotifyPropertyChanged
Private _realPart As Double
Private _imaginaryPart As Double
Public Property RealPart As Double
Get
Return _realPart
End Get
Set(ByVal value As Double)
_realPart = value
OnPropertyChanged("RealPart")
End Set
End Property
Public Property ImaginaryPart As Double
Get
Return _imaginaryPart
End Get
Set(ByVal value As Double)
_imaginaryPart = value
OnPropertyChanged("ImaginaryPart")
End Set
End Property
Public ReadOnly Property Result As ComplexNumber
Get
Return New ComplexNumber(RealPart, ImaginaryPart)
End Get
End Property
Private Sub DeleteButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles DeleteButton.Click
OnRemoveButtonPressed()
End Sub
Public Event RemoveButtonPressed(ByVal sender As Object, ByVal e As EventArgs)
Private Sub OnRemoveButtonPressed()
RaiseEvent RemoveButtonPressed(Me, New EventArgs)
End Sub
Private Shadows Sub OnPropertyChanged(ByVal propertyName As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
Public Event PropertyChanged(ByVal sender As Object, ByVal e As PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
Private Sub ComplexNumberSelector_Initialized(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Initialized
Me.DataContext = Me
End Sub
End Class
|
Public Class AboutBox
Public Sub SetTheme(Theme As Theme)
Me.Background = Theme.contentBackground
Me.Foreground = Theme.contentForeground
End Sub
Private Sub Lb_OpenSource_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles Lb_OpenSource.MouseDown
Process.Start("https://github.com/MarchStudio/OGFrp")
End Sub
End Class
|
Public Class InstrCurve
Inherits InstrBase
Private dc As New DrawCurve()
''' <summary>
''' Draws curve using outline and fill.
''' </summary>
''' <param name="DrawCrv"></param>
''' <remarks></remarks>
Sub New(ByVal DrawCrv As DrawCurve)
MyBase.InstructionType = "Draw"
dc = DrawCrv.Duplicate
End Sub
Property DrawCurve As DrawCurve
Set(value As DrawCurve)
dc = value.Duplicate
End Set
Get
Return dc
End Get
End Property
End Class
|
Imports Newtonsoft.Json.Linq
Imports System.IO
Module mdlModList
Dim ood As Integer = 0
Public Sub loadModJson(ByVal cListView As ListView)
Dim json As String = readHttpFile(My.Resources.mod_url & "/" & My.Resources.mod_patchlist)
Dim ser As JObject = JObject.Parse(json)
Dim mod_files As JArray = ser("mod_files")
frmMain.chkListMod.Checked = False
WriteLog("iModMan:loadModJson", ErrorType.trace, "Parsing mods data")
For Each item As JObject In mod_files
WriteLog("iModMan:loadModJson", ErrorType.trace, item.SelectToken("name").ToString())
Dim f As clsFFile = New clsFFile(
item.SelectToken("name").ToString(),
item.SelectToken("path").ToString(),
item.SelectToken("version").ToString(),
item.SelectToken("url").ToString(),
item.SelectToken("desc").ToString(),
item.SelectToken("hash").ToString())
Dim status As Integer = checkModVersion(f.getPath(), f.getVersion())
Dim val As ListViewItem = New ListViewItem()
val.SubItems.Add(f.getName())
val.SubItems.Add(f.getVersion())
val.SubItems.Add(getModVersionDetails(status))
val.SubItems.Add(f.getDesc())
If (status = 1) Then
val.Checked = True
val.ForeColor = Color.Red
ood = ood + 1
End If
If (status = 2) Then val.ForeColor = Color.Green
If (status = 4) Then val.ForeColor = Color.Red
val.Tag = f
cListView.Items.Add(val)
Next
If (ood > 0) Then
frmMain.lblNumberUpdates.Text = ood & " buah pembaruan tersedia."
Else
frmMain.lblNumberUpdates.Text = "Semua mod telah diperbarui."
End If
WriteLog("iModMan:loadModJson", ErrorType.trace, "OK")
cListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
End Sub
Private Function checkModVersion(ByVal sFileName As String, ByVal version As String)
Dim filePath As String
Dim local As String
Dim server As String = version
filePath = Path.Combine(Application.StartupPath, sFileName)
' Cek filenya apakah ada di local
If (File.Exists(filePath)) Then
If (FileLen(filePath) > 0) Then ' pastikan filenya berisi bukan file dummy
Dim elem As String() = sFileName.Split(New Char() {"_"c}) ' Split nama filenya
local = elem(elem.Count - 1).Replace(".pak", "").Replace(".", "")
server = version.Replace(".", "")
If (server > local) Then
Return 1 ' Mod ada update
Else
Return 2 ' ' Mod sudah terbaru
End If
Else
Return 4 ' Ukuran file mod 0KB
End If
Else
Return 3 ' Mod tidak ada/tidak diinstall
End If
' Ada error
Return -1
End Function
Private Function getModVersionDetails(ByVal i As Integer)
If (i = 1) Then
Return "Pembaruan tersedia"
ElseIf (i = 2) Then
Return "Diperbarui!"
ElseIf (i = 3) Then
Return "Tidak dipasang"
ElseIf (i = 4) Then
Return "File rusak!"
Else
Return "Ada kesalahan!"
End If
End Function
End Module
|
' 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 System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Binder used to bind statements inside With blocks.
''' </summary>
Friend NotInheritable Class WithBlockBinder
Inherits BlockBaseBinder
''' <summary> Reference to a With statement syntax this binder is created for </summary>
Private ReadOnly _withBlockSyntax As WithBlockSyntax
''' <summary> Reference to an expression from With statement </summary>
Private ReadOnly Property Expression As ExpressionSyntax
Get
Return Me._withBlockSyntax.WithStatement.Expression
End Get
End Property
''' <summary>
''' Holds information needed by With block to properly bind
''' references to With block expression placeholder
''' </summary>
Private _withBlockInfo As WithBlockInfo = Nothing
Friend ReadOnly Property Info As WithBlockInfo
Get
Return _withBlockInfo
End Get
End Property
''' <summary>
''' True if there were references to the With statement expression
''' placeholder which prevent ByRef local from being used
''' </summary>
Friend ReadOnly Property ExpressionIsAccessedFromNestedLambda As Boolean
Get
Debug.Assert(Me._withBlockInfo IsNot Nothing)
Return Me._withBlockInfo.ExpressionIsAccessedFromNestedLambda
End Get
End Property
''' <summary>
''' With statement expression placeholder is a bound node being used in initial binding
''' to represent with statement expression. In lowering it is to be replaced with
''' the lowered expression which will actually be emitted.
''' </summary>
Friend ReadOnly Property ExpressionPlaceholder As BoundValuePlaceholderBase
Get
Debug.Assert(Me._withBlockInfo IsNot Nothing)
Return Me._withBlockInfo.ExpressionPlaceholder
End Get
End Property
''' <summary>
''' A draft version of initializers which will be used in this With statement.
''' Initializers are expressions which are used to capture expression in the current
''' With statement; they can be empty in some cases like if the expression is a local
''' variable of value type.
'''
''' Note, the initializers returned by this property are 'draft' because they are
''' generated based on initial bound tree, the real initializers will be generated
''' in lowering based on lowered expression form.
''' </summary>
Friend ReadOnly Property DraftInitializers As ImmutableArray(Of BoundExpression)
Get
Debug.Assert(Me._withBlockInfo IsNot Nothing)
Return Me._withBlockInfo.DraftInitializers
End Get
End Property
''' <summary>
''' A draft version of placeholder substitute which will be used in this With statement.
'''
''' Note, the placeholder substitute returned by this property is 'draft' because it is
''' generated based on initial bound tree, the real substitute will be generated in lowering
''' based on lowered expression form.
''' </summary>
Friend ReadOnly Property DraftPlaceholderSubstitute As BoundExpression
Get
Debug.Assert(Me._withBlockInfo IsNot Nothing)
Return Me._withBlockInfo.DraftSubstitute
End Get
End Property
''' <summary> Holds information needed by With block to properly bind
''' references to With block expression, placeholder, etc... </summary>
Friend Class WithBlockInfo
Public Sub New(originalExpression As BoundExpression,
expressionPlaceholder As BoundValuePlaceholderBase,
draftSubstitute As BoundExpression,
draftInitializers As ImmutableArray(Of BoundExpression),
diagnostics As DiagnosticBag)
Debug.Assert(originalExpression IsNot Nothing)
Debug.Assert(expressionPlaceholder IsNot Nothing AndAlso (expressionPlaceholder.Kind = BoundKind.WithLValueExpressionPlaceholder OrElse expressionPlaceholder.Kind = BoundKind.WithRValueExpressionPlaceholder))
Debug.Assert(draftSubstitute IsNot Nothing)
Debug.Assert(Not draftInitializers.IsDefault)
Debug.Assert(diagnostics IsNot Nothing)
Me.OriginalExpression = originalExpression
Me.ExpressionPlaceholder = expressionPlaceholder
Me.DraftSubstitute = draftSubstitute
Me.DraftInitializers = draftInitializers
Me.Diagnostics = diagnostics
End Sub
''' <summary> Original bound expression from With statement </summary>
Public ReadOnly OriginalExpression As BoundExpression
''' <summary> Bound placeholder expression if used, otherwise Nothing </summary>
Public ReadOnly ExpressionPlaceholder As BoundValuePlaceholderBase
''' <summary> Diagnostics produced while binding the expression </summary>
Public ReadOnly Diagnostics As DiagnosticBag
''' <summary>
''' Draft initializers for With statement, is based on initial binding tree
''' and is only to be used for warnings generation as well as for flow analysis
''' and semantic API; real initializers will be re-calculated in lowering
''' </summary>
Public ReadOnly DraftInitializers As ImmutableArray(Of BoundExpression)
''' <summary>
''' Draft substitute for With expression placeholder, is based on initial
''' binding tree and is only to be used for warnings generation as well as
''' for flow analysis and semantic API; real substitute will be re-calculated
''' in lowering
''' </summary>
Public ReadOnly DraftSubstitute As BoundExpression
Public ReadOnly Property ExpressionIsAccessedFromNestedLambda As Boolean
Get
Return Me._exprAccessedFromNestedLambda = ThreeState.True
End Get
End Property
Public Sub RegisterAccessFromNestedLambda()
If Me._exprAccessedFromNestedLambda <> ThreeState.True Then
Dim oldValue = Interlocked.CompareExchange(Me._exprAccessedFromNestedLambda, ThreeState.True, ThreeState.Unknown)
Debug.Assert(oldValue = ThreeState.Unknown OrElse oldValue = ThreeState.True)
End If
End Sub
Private _exprAccessedFromNestedLambda As Integer = ThreeState.Unknown
''' <summary>
''' If With statement expression is being used from nested lambda there are some restrictions
''' to the usage of Me reference in this expression. As these restrictions are only to be checked
''' in few scenarios, this flag is being calculated lazily.
''' </summary>
Public Function ExpressionHasByRefMeReference(recursionDepth As Integer) As Boolean
If Me._exprHasByRefMeReference = ThreeState.Unknown Then
' Analyze the expression which will be used instead of placeholder
Dim value As Boolean = ValueTypedMeReferenceFinder.HasByRefMeReference(Me.DraftSubstitute, recursionDepth)
Dim newValue As Integer = If(value, ThreeState.True, ThreeState.False)
Dim oldValue = Interlocked.CompareExchange(Me._exprHasByRefMeReference, newValue, ThreeState.Unknown)
Debug.Assert(newValue = oldValue OrElse oldValue = ThreeState.Unknown)
End If
Debug.Assert(Me._exprHasByRefMeReference <> ThreeState.Unknown)
Return Me._exprHasByRefMeReference = ThreeState.True
End Function
Private _exprHasByRefMeReference As Integer = ThreeState.Unknown
End Class
''' <summary> Create a new instance of With statement binder for a statement syntax provided </summary>
Public Sub New(enclosing As Binder, syntax As WithBlockSyntax)
MyBase.New(enclosing)
Debug.Assert(syntax IsNot Nothing)
Debug.Assert(syntax.WithStatement IsNot Nothing)
Debug.Assert(syntax.WithStatement.Expression IsNot Nothing)
Me._withBlockSyntax = syntax
End Sub
#Region "Implementation"
Friend Overrides Function GetWithStatementPlaceholderSubstitute(placeholder As BoundValuePlaceholderBase) As BoundExpression
Me.EnsureExpressionAndPlaceholder()
If placeholder Is Me.ExpressionPlaceholder Then
Return Me.DraftPlaceholderSubstitute
End If
Return MyBase.GetWithStatementPlaceholderSubstitute(placeholder)
End Function
Private Sub EnsureExpressionAndPlaceholder()
If Me._withBlockInfo Is Nothing Then
' Because we cannot guarantee that diagnostics will be freed we
' don't allocate this diagnostics bag from a pool
Dim diagnostics As New DiagnosticBag()
' Bind the expression as a value
Dim boundExpression As BoundExpression = Me.ContainingBinder.BindValue(Me.Expression, diagnostics)
' NOTE: If the expression is not an l-value we should make an r-value of it
If Not boundExpression.IsLValue Then
boundExpression = Me.MakeRValue(boundExpression, diagnostics)
End If
' Prepare draft substitute/initializers for expression placeholder;
' note that those substitute/initializers will be based on initial bound
' form of the original expression captured without using ByRef locals
Dim result As WithExpressionRewriter.Result =
(New WithExpressionRewriter(Me._withBlockSyntax.WithStatement)).AnalyzeWithExpression(Me.ContainingMember, boundExpression,
doNotUseByRefLocal:=True,
binder:=Me.ContainingBinder,
preserveIdentityOfLValues:=True)
' Create a placeholder if needed
Dim placeholder As BoundValuePlaceholderBase = Nothing
If boundExpression.IsLValue OrElse boundExpression.IsMeReference Then
placeholder = New BoundWithLValueExpressionPlaceholder(Me.Expression, boundExpression.Type)
Else
placeholder = New BoundWithRValueExpressionPlaceholder(Me.Expression, boundExpression.Type)
End If
placeholder.SetWasCompilerGenerated()
' It is assumed that the binding result in case of race should still be the same in all racing threads,
' so if the following call fails we can just drop the bound node and diagnostics on the floor
Interlocked.CompareExchange(Me._withBlockInfo,
New WithBlockInfo(boundExpression, placeholder,
result.Expression, result.Initializers, diagnostics),
Nothing)
End If
Debug.Assert(Me._withBlockInfo IsNot Nothing)
End Sub
''' <summary>
''' A bound tree walker which search for a bound Me and MyClass references of value type.
''' Is being only used for calculating the value of 'ExpressionHasByRefMeReference'
''' </summary>
Private Class ValueTypedMeReferenceFinder
Inherits BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
Private Sub New(recursionDepth As Integer)
MyBase.New(recursionDepth)
End Sub
Private _found As Boolean = False
Public Shared Function HasByRefMeReference(expression As BoundExpression, recursionDepth As Integer) As Boolean
Dim walker As New ValueTypedMeReferenceFinder(recursionDepth)
walker.Visit(expression)
Return walker._found
End Function
Public Overrides Function Visit(node As BoundNode) As BoundNode
If Not _found Then
Return MyBase.Visit(node)
End If
Return Nothing
End Function
Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode
Dim type As TypeSymbol = node.Type
Debug.Assert(Not type.IsTypeParameter)
Debug.Assert(type.IsValueType)
Me._found = True
Return Nothing
End Function
Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode
Dim type As TypeSymbol = node.Type
Debug.Assert(Not type.IsTypeParameter)
Debug.Assert(type.IsValueType)
Me._found = True
Return Nothing
End Function
End Class
#End Region
#Region "With block binding"
Protected Overrides Function CreateBoundWithBlock(node As WithBlockSyntax, boundBlockBinder As Binder, diagnostics As DiagnosticBag) As BoundStatement
Debug.Assert(node Is Me._withBlockSyntax)
' Bind With statement expression
Me.EnsureExpressionAndPlaceholder()
' We need to take care of possible diagnostics that might be produced
' by EnsureExpressionAndPlaceholder call, note that this call might have
' been before in which case the diagnostics were stored in '_withBlockInfo'
' See also comment in PrepareBindingOfOmittedLeft(...)
diagnostics.AddRange(Me._withBlockInfo.Diagnostics)
Return New BoundWithStatement(node,
Me._withBlockInfo.OriginalExpression,
boundBlockBinder.BindBlock(node, node.Statements, diagnostics),
Me)
End Function
#End Region
#Region "Other Overrides"
''' <summary> Asserts that the node is NOT from With statement expression </summary>
<Conditional("DEBUG")>
Private Sub AssertExpressionIsNotFromStatementExpression(node As SyntaxNode)
While node IsNot Nothing
Debug.Assert(node IsNot Me.Expression)
node = node.Parent
End While
End Sub
#If DEBUG Then
Public Overrides Function BindStatement(node As StatementSyntax, diagnostics As DiagnosticBag) As BoundStatement
AssertExpressionIsNotFromStatementExpression(node)
Return MyBase.BindStatement(node, diagnostics)
End Function
Public Overrides Function GetBinder(node As SyntaxNode) As Binder
AssertExpressionIsNotFromStatementExpression(node)
Return MyBase.GetBinder(node)
End Function
#End If
Private Sub PrepareBindingOfOmittedLeft(node As VisualBasicSyntaxNode, diagnostics As DiagnosticBag, accessingBinder As Binder)
AssertExpressionIsNotFromStatementExpression(node)
Debug.Assert((node.Kind = SyntaxKind.SimpleMemberAccessExpression) OrElse
(node.Kind = SyntaxKind.DictionaryAccessExpression) OrElse
(node.Kind = SyntaxKind.XmlAttributeAccessExpression) OrElse
(node.Kind = SyntaxKind.XmlElementAccessExpression) OrElse
(node.Kind = SyntaxKind.XmlDescendantAccessExpression) OrElse
(node.Kind = SyntaxKind.ConditionalAccessExpression))
Me.EnsureExpressionAndPlaceholder()
' NOTE: In case the call above produced diagnostics they were stored in
' '_withBlockInfo' and will be reported in later call to CreateBoundWithBlock(...)
Dim info As WithBlockInfo = Me._withBlockInfo
If Me.ContainingMember IsNot accessingBinder.ContainingMember Then
' The expression placeholder from With statement may be captured
info.RegisterAccessFromNestedLambda()
End If
End Sub
Protected Friend Overrides Function TryBindOmittedLeftForMemberAccess(node As MemberAccessExpressionSyntax,
diagnostics As DiagnosticBag,
accessingBinder As Binder,
<Out> ByRef wholeMemberAccessExpressionBound As Boolean) As BoundExpression
PrepareBindingOfOmittedLeft(node, diagnostics, accessingBinder)
wholeMemberAccessExpressionBound = False
Return Me._withBlockInfo.ExpressionPlaceholder
End Function
Protected Overrides Function TryBindOmittedLeftForDictionaryAccess(node As MemberAccessExpressionSyntax,
accessingBinder As Binder,
diagnostics As DiagnosticBag) As BoundExpression
PrepareBindingOfOmittedLeft(node, diagnostics, accessingBinder)
Return Me._withBlockInfo.ExpressionPlaceholder
End Function
Protected Overrides Function TryBindOmittedLeftForConditionalAccess(node As ConditionalAccessExpressionSyntax, accessingBinder As Binder, diagnostics As DiagnosticBag) As BoundExpression
PrepareBindingOfOmittedLeft(node, diagnostics, accessingBinder)
Return Me._withBlockInfo.ExpressionPlaceholder
End Function
Protected Friend Overrides Function TryBindOmittedLeftForXmlMemberAccess(node As XmlMemberAccessExpressionSyntax,
diagnostics As DiagnosticBag,
accessingBinder As Binder) As BoundExpression
PrepareBindingOfOmittedLeft(node, diagnostics, accessingBinder)
Return Me._withBlockInfo.ExpressionPlaceholder
End Function
Friend Overrides ReadOnly Property Locals As ImmutableArray(Of LocalSymbol)
Get
Return ImmutableArray(Of LocalSymbol).Empty
End Get
End Property
#End Region
End Class
End Namespace
|
Imports System.Threading.Tasks
Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.Owin
Partial Public Class AddPhoneNumber
Inherits System.Web.UI.Page
Protected Sub PhoneNumber_Click(sender As Object, e As EventArgs)
Dim manager = Context.GetOwinContext().GetUserManager(Of ApplicationUserManager)()
Dim code = manager.GenerateChangePhoneNumberToken(User.Identity.GetUserId(), PhoneNumber.Text)
If manager.SmsService IsNot Nothing Then
Dim message = New IdentityMessage() With {
.Destination = PhoneNumber.Text,
.Body = "Su código de seguridad es " & Convert.ToString(code)
}
manager.SmsService.Send(message)
End If
Response.Redirect("/Account/VerifyPhoneNumber?PhoneNumber=" & HttpUtility.UrlEncode(PhoneNumber.Text))
End Sub
End Class
|
Public Class TextHelpForm
Property Find As String
Public Sub New(text As String, find As String)
InitializeComponent()
rtb.Text = text
rtb.BackColor = Color.Black
rtb.ForeColor = Color.White
rtb.ReadOnly = True
Me.Find = find
ScaleClientSize(45, 30)
End Sub
Private Sub TextHelpForm_Shown(sender As Object, e As EventArgs) Handles Me.Shown
rtb.Find(Find)
rtb.ScrollToCaret()
End Sub
End Class |
Option Strict Off
Option Explicit On
Imports System.Xml
Imports System.Collections
Imports System.Web.Configuration
Imports System.Data.SqlClient
Imports System.Web.HttpUtility
Imports VB = Microsoft.VisualBasic
Imports System.IO
Imports Eonic.Tools.Xml
Imports Eonic.Tools.Xml.XmlNodeState
Imports System
Imports System.Reflection
Imports Eonic.Providers.Membership.EonicProvider
Partial Public Class Web
Public Class Cart
#Region "Declarations"
Public moCartConfig As System.Collections.Specialized.NameValueCollection = WebConfigurationManager.GetWebApplicationSection("eonic/cart")
Public moConfig As System.Collections.Specialized.NameValueCollection
Private moServer As System.Web.HttpServerUtility
Public moPageXml As XmlDocument
Public Shadows mcModuleName As String = "Eonic.Cart"
'Session EonicWeb Details
Public mcEwDataConn As String
Public mcEwSiteDomain As String
Public mbEwMembership As Boolean
Public oShippingOptions As XmlElement
' MEMB - notes beginning with MEMB relate to changes to the cart to incorporate logging in members and adding their addresses to contact fields in the billing/delivery forms
' Cart Status Ref
' 1 new cart
' 2 entered address
' 3 abbandoned
' 4 pass to payment
' 5 Transaction Failed
' 6 Payment Successful
' 7 Order Cancelled / Payment Refunded
' 8 Failed and Checked
' 9 Order Shipped
' 10 Part Payment (e.g. depsoit) Received
' 11 Settlement initiated?
' 12 Awaiting Payment
Public mcSiteURL As String ' Site Identifier, used for User Cookie Name
Public mcCartURL As String ' Site Identifier, used for User Cookie Name
Public mnCartId As Integer ' Unique Id refering to this session cart
Public mcSessionId As String ' Session ID - Unique for each client browser
Private mcRefSessionId As String ' Referrer Site Session ID - The session ID from the referrer site, if passed.
Public mnEwUserId As Integer ' User Id for Membership integration
Public mmcOrderType As String ' The order type associated with the current cart
Public mcItemOrderType As String ' The order type associated with the current page (if provided)
Public moCartXml As XmlElement
Public mnGiftListId As Integer = -1 ' If the current user is buying from a giftlist
Public mcNotesXForm As String ' Location of Notes xform prior to billing details
Public mnTaxRate As Double ' Add Tax to Cart Rate
Public mcTermsAndConditions As String = ""
Public mcMerchantEmail As String
Public mcMerchantEmailTemplatePath As String
Public mbStockControl As Boolean = False ' Stock Control
Public mcDeposit As String ' Deposits are Available
Public mcDepositAmount As String ' Deposit Amount
Private cOrderNoPrefix As String
Public mcCurrency As String = ""
Public mcCurrencySymbol As String = ""
Public mcVoucherNumber As String = ""
Public mcVoucherValue As String = ""
Public mcVoucherExpires As String = ""
Private promocodeFromExternalRef As String = ""
Public mcPersistCart As String = ""
Public mcPagePath As String
Public mnPaymentId As Integer = 0 ' to be populated by payment prvoider to pass to subscriptions
Public bFullCartOption As Boolean
Public mbAddItemWithNoPrice As Boolean ' Switch to allow enquiries of items with no price
' Address Mods
Public mcBillingAddressXform As String = "" ' Location of bespoke Billing Address
Public mcDeliveryAddressXform As String = "" ' Location of bespoke Delivery Address
Public mcPriorityCountries As String ' List of countires to appear at the top of dropdowns
Public mbNoDeliveryAddress As Boolean = False ' Option to turn off the need for a delivery address
Public mcReturnPage As String ' page to return to with continue Shopping
Public mcCartCmd As String = "" ' Action String for ewCart main function, ewcartPlugin()
' Can be: <case sensitive>
' Billing
' Delivery
' Cart
' Add
' Remove
' ShowInvoice
' MakePayment
' Failed Payment
' Quit
Public mcCartCmdAlt As String = "" 'alternative if we call apply again
Public mnProcessId As Short = 0 ' State of Cart:
' 0: Empty / New Cart
' 1: Shopping / Items in Cart
' 2: Billing Address is Complete
' 3: Billing & Delivery Addressi are Complete
' 4: Order Confirmed / Ready to make payment
' 5: Transaction Complete
' 6: Tender Cancelled
Public mnProcessError As Short ' General Process Error has been encountered:
' 1: Cookies are disabled or undetectable
' 2: The current item's order type does not match the cart's order type
' 100+: Payment gateway errors
' 1000+: Bespoke errors - can be defined in the xsl
Public mcPaymentMethod As String = "" ' Payment Method:
' SecPay
' ProTx
' Secure Email
' MetaCharge
' WorldPay
' Cheque
Public mcPaymentProfile As String = ""
' Behaviour mods
Private mbRedirectSecure As Boolean = False
Private mbDisplayPrice As Boolean = True
Public mcSubmitText As String
Public moDBHelper As dbHelper
Public mcOrderType As String
Public cOrderReference As String
Public mbVatAtUnit As Boolean = False
Public mbVatOnLine As Boolean = False
Public mbRoundup As Boolean = False
Public mbDiscountsOn As Boolean = False
Public mbOveridePrice As Boolean = False
Public mcPriceModOrder As String = ""
Public mcUnitModOrder As String = ""
Public mcReEstablishSession As String
Public mcCurrencyRef As String
Public mcCurrencyCode As String
Public mnShippingRootId As Integer
'Public mcCurrencySymbol As String
Public moDiscount As Discount
Public moSubscription As Subscriptions
Protected moPay As PaymentProviders
Public mbQuitOnShowInvoice As Boolean = True
Enum cartError
OutOfStock = 2
ProductQuantityOverLimit = 201
ProductQuantityUnderLimit = 202
ProductQuantityNotInBulk = 203
End Enum
Enum cartProcess
Empty = 0
Items = 1
Billing = 2
Delivery = 3
Confirmed = 4
PassForPayment = 5
Complete = 6
Refunded = 7
Failed = 8
Shipped = 9
DepositPaid = 10
Abandoned = 11
Deleted = 12
AwaitingPayment = 13
SettlementInitiated = 14
SkipAddress = 15
End Enum
#End Region
#Region "Properties"
Public Overridable Property OrderNoPrefix() As String
Get
If cOrderNoPrefix = "" Then
cOrderNoPrefix = moCartConfig("OrderNoPrefix")
End If
Return cOrderNoPrefix
End Get
Set(ByVal value As String)
cOrderNoPrefix = value
End Set
End Property
#End Region
#Region "Classes"
Class FormResult
Public Name As String
Public Value As String
Sub New(ByVal cName As String, ByVal cValue As String)
PerfMon.Log("Cart", "New")
Name = cName
Value = cValue
End Sub
End Class
Class Order
Private OrderElmt As XmlElement
Protected Friend myWeb As Web
Public moConfig As System.Collections.Specialized.NameValueCollection
Private moServer As System.Web.HttpServerUtility
Dim nFirstPayment As Double
Dim nRepeatPayment As Double
Dim sRepeatInterval As String
Dim nRepeatLength As Integer
Dim bDelayStart As Boolean
Dim dStartDate As Date
Dim sPaymentMethod As String
Dim sTransactionRef As String
Dim sDescription As String
Dim sGivenName As String
Dim sBillingAddress1 As String
Dim sBillingAddress2 As String
Dim sBillingTown As String
Dim sBillingCounty As String
Dim sBillingPostcode As String
Dim sEmail As String
Public moPageXml As XmlDocument
Sub New(ByRef aWeb As Eonic.Web)
PerfMon.Log("Order", "New")
myWeb = aWeb
moConfig = myWeb.moConfig
moPageXml = myWeb.moPageXml
moServer = aWeb.moCtx.Server
OrderElmt = moPageXml.CreateElement("Order")
End Sub
ReadOnly Property xml As XmlElement
Get
Return OrderElmt
End Get
End Property
Property PaymentMethod As String
Get
Return sPaymentMethod
End Get
Set(ByVal Value As String)
sPaymentMethod = Value
OrderElmt.SetAttribute("paymentMethod", Value)
End Set
End Property
Property firstPayment As Double
Get
Return nFirstPayment
End Get
Set(ByVal Value As Double)
nFirstPayment = Value
OrderElmt.SetAttribute("total", Value)
End Set
End Property
Property repeatPayment As Double
Get
Return nRepeatPayment
End Get
Set(ByVal Value As Double)
nRepeatPayment = Value
OrderElmt.SetAttribute("repeatPrice", Value)
End Set
End Property
Property repeatInterval As String
Get
Return sRepeatInterval
End Get
Set(ByVal Value As String)
sRepeatInterval = Value
OrderElmt.SetAttribute("repeatInterval", Value)
End Set
End Property
Property repeatLength As Integer
Get
Return nRepeatLength
End Get
Set(ByVal Value As Integer)
nRepeatLength = Value
OrderElmt.SetAttribute("repeatLength", Value)
End Set
End Property
Property delayStart As Boolean
Get
Return bDelayStart
End Get
Set(ByVal Value As Boolean)
bDelayStart = Value
If Value Then
OrderElmt.SetAttribute("delayStart", "true")
Else
OrderElmt.SetAttribute("delayStart", "false")
End If
End Set
End Property
Property startDate As Date
Get
Return dStartDate
End Get
Set(ByVal Value As Date)
dStartDate = Value
OrderElmt.SetAttribute("startDate", xmlDate(dStartDate))
End Set
End Property
Property TransactionRef As String
Get
Return sTransactionRef
End Get
Set(ByVal Value As String)
sTransactionRef = Value
OrderElmt.SetAttribute("transactionRef", sTransactionRef)
End Set
End Property
Property description As String
Get
Return sDescription
End Get
Set(ByVal Value As String)
sDescription = Value
Dim descElmt As XmlElement = moPageXml.CreateElement("Description")
descElmt.InnerText = sDescription
OrderElmt.AppendChild(descElmt)
End Set
End Property
Sub SetAddress(ByVal GivenName As String, ByVal Email As String, ByVal Company As String, ByVal Street As String, ByVal City As String, ByVal State As String, ByVal PostalCode As String, ByVal Country As String)
Dim addElmt As XmlElement = moPageXml.CreateElement("Contact")
addElmt.SetAttribute("type", "Billing Address")
xmlTools.addElement(addElmt, "GivenName", GivenName)
xmlTools.addElement(addElmt, "Email", Email)
xmlTools.addElement(addElmt, "Company", Company)
xmlTools.addElement(addElmt, "Street", Street)
xmlTools.addElement(addElmt, "City", City)
xmlTools.addElement(addElmt, "State", State)
xmlTools.addElement(addElmt, "PostalCode", PostalCode)
xmlTools.addElement(addElmt, "Country", Country)
OrderElmt.AppendChild(addElmt)
End Sub
End Class
#End Region
Private Function getProcessName(ByVal cp As cartProcess) As String
Select Case cp
Case cartProcess.Abandoned
Return "Abandoned"
Case cartProcess.AwaitingPayment
Return "Awaiting Payment"
Case cartProcess.SkipAddress
Return "SkipAddress"
Case cartProcess.Billing
Return "Billing"
Case cartProcess.Complete
Return "Complete"
Case cartProcess.Confirmed
Return "Confirmed"
Case cartProcess.Deleted
Return "Deleted"
Case cartProcess.Delivery
Return "Delivery"
Case cartProcess.DepositPaid
Return "Deposit Paid"
Case cartProcess.Empty
Return "Empty"
Case cartProcess.Failed
Return "Failed"
Case cartProcess.PassForPayment
Return "Pass For Payment"
Case cartProcess.Refunded
Return "Refunded"
Case cartProcess.Shipped
Return "Shipped"
Case Else
Return "Unknown Process ID"
End Select
End Function
Protected Friend myWeb As Web
Public Sub New(ByRef aWeb As Eonic.Web)
PerfMon.Log("Cart", "New")
Dim cProcessInfo As String = ""
Try
myWeb = aWeb
moConfig = myWeb.moConfig
moPageXml = myWeb.moPageXml
moDBHelper = myWeb.moDbHelper
InitializeVariables()
moServer = aWeb.moCtx.Server
Catch ex As Exception
returnException(mcModuleName, "Close", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Sub InitializeVariables()
PerfMon.Log("Cart", "InitializeVariables")
'Author: Trevor Spink
'Copyright: Eonic Ltd 2006
'Date: 2006-10-04
' called at the beginning, whenever ewCart is run
' sets the global variables and initialises the current cart
Dim sSql As String = ""
Dim oDr As SqlDataReader
Dim cartXmlFromDatabase As String = ""
mcOrderType = "Order"
cOrderReference = ""
mcModuleName = "Eonic.Cart"
Dim cProcessInfo As String = "" = "initialise variables"
Try
If Not moCartConfig Is Nothing Then
If myWeb.mnUserId > 0 And myWeb.moConfig("SecureMembershipAddress") <> "" Then
mcSiteURL = myWeb.moConfig("SecureMembershipAddress") & moConfig("ProjectPath") & "/"
mcCartURL = myWeb.moConfig("SecureMembershipAddress") & moConfig("ProjectPath") & "/"
Else
mcSiteURL = moCartConfig("SiteURL")
mcCartURL = moCartConfig("SecureURL")
End If
moDiscount = New Discount(Me)
mcPagePath = myWeb.mcPagePath
If mcPagePath = "" Then
If mcCartURL.EndsWith("/") Then
mcPagePath = mcCartURL & "?"
Else
mcPagePath = mcCartURL & "/?"
End If
Else
mcPagePath = mcCartURL & mcPagePath & "?"
End If
If moConfig("Membership") = "on" Then mbEwMembership = True
mnTaxRate = moCartConfig("TaxRate")
mcMerchantEmail = moCartConfig("MerchantEmail")
mcTermsAndConditions = moCartConfig("TermsAndConditions")
'mcOrderNoPrefix = moCartConfig("OrderNoPrefix")
mcCurrencySymbol = moCartConfig("CurrencySymbol")
mcCurrency = moCartConfig("Currency")
If mcCurrency = "" Then mcCurrency = "GBP"
Dim moPaymentCfg As XmlNode
'change currency based on language selection
If myWeb.gcLang <> "" Then
Dim moLangCfg As XmlNode = WebConfigurationManager.GetWebApplicationSection("eonic/languages")
If Not moLangCfg Is Nothing Then
Dim thisLangNode As XmlElement = moLangCfg.SelectSingleNode("Language[@code='" & myWeb.gcLang & "']")
If Not thisLangNode Is Nothing Then
mcCurrency = thisLangNode.GetAttribute("currency")
moPaymentCfg = WebConfigurationManager.GetWebApplicationSection("eonic/payment")
Dim thisCurrencyNode As XmlElement = moPaymentCfg.SelectSingleNode("currencies/Currency[@ref='" & mcCurrency & "']")
mcCurrencySymbol = thisCurrencyNode.GetAttribute("symbol")
End If
End If
End If
'change currency if default user currency is set
If myWeb.mnUserId > 0 Then
Dim userxml As XmlElement = myWeb.moPageXml.SelectSingleNode("/Page/User")
If userxml Is Nothing Then
userxml = myWeb.GetUserXML(myWeb.mnUserId)
End If
If userxml.GetAttribute("defaultCurrency") <> "" Then
mcCurrency = userxml.GetAttribute("defaultCurrency")
moPaymentCfg = WebConfigurationManager.GetWebApplicationSection("eonic/payment")
Dim thisCurrencyNode As XmlElement = moPaymentCfg.SelectSingleNode("currencies/Currency[@ref='" & mcCurrency & "']")
mcCurrencySymbol = thisCurrencyNode.GetAttribute("symbol")
End If
End If
moPaymentCfg = Nothing
'reset the currency on discounts
moDiscount.mcCurrency = mcCurrency
If moCartConfig("StockControl") = "on" Then mbStockControl = True
If moCartConfig("DisplayPrice") = "off" Then mbDisplayPrice = False
mcDeposit = LCase(moCartConfig("Deposit"))
mcDepositAmount = moCartConfig("DepositAmount")
mcNotesXForm = moCartConfig("NotesXForm")
mcBillingAddressXform = moCartConfig("BillingAddressXForm")
mcDeliveryAddressXform = moCartConfig("DeliveryAddressXForm")
If moCartConfig("NoDeliveryAddress") = "on" Then mbNoDeliveryAddress = True
mcMerchantEmailTemplatePath = moCartConfig("MerchantEmailTemplatePath")
mcPriorityCountries = moCartConfig("PriorityCountries")
mcPersistCart = moCartConfig("PersistCart") 'might need to add checks for missing key
If mcPriorityCountries Is Nothing Or mcPriorityCountries = "" Then
mcPriorityCountries = "United Kingdom,United States"
End If
If myWeb.moSession("nTaxRate") Is Nothing Then
mnTaxRate = CDbl("0" & myWeb.moSession("nTaxRate"))
End If
If myWeb.moRequest.Form("url") <> "" Then
myWeb.moSession("returnPage") = myWeb.moRequest.Form("url")
End If
If myWeb.moRequest.QueryString("url") <> "" Then
myWeb.moSession("returnPage") = myWeb.moRequest.QueryString("url")
End If
mcReturnPage = myWeb.moSession("returnPage")
If Not myWeb.moSession("nEwUserId") Is Nothing Then
mnEwUserId = CInt("0" & myWeb.moSession("nEwUserId"))
Else
mnEwUserId = 0
End If
If myWeb.mnUserId > 0 And mnEwUserId = 0 Then mnEwUserId = myWeb.mnUserId
'MEMB - eEDIT
If myWeb.goApp("bFullCartOption") = True Then
bFullCartOption = True
Else
bFullCartOption = False
End If
If myWeb.moSession("CartId") Is Nothing Then
mnCartId = 0
Else
If Not (IsNumeric(myWeb.moSession("CartId"))) Or myWeb.moSession("CartId") <= 0 Then
mnCartId = 0
Else
mnCartId = CInt(myWeb.moSession("CartId"))
End If
End If
If Not (myWeb.moRequest("refSessionId") Is Nothing) Then
mcSessionId = myWeb.moRequest("refSessionId")
myWeb.moSession.Add("refSessionId", mcSessionId)
ElseIf Not (myWeb.moSession("refSessionId") Is Nothing) Then
mcSessionId = myWeb.moSession("refSessionId")
Else
mcSessionId = myWeb.moSession.SessionID
End If
If IsNumeric(myWeb.moRequest.QueryString("cartErr")) Then mnProcessError = CInt(myWeb.moRequest.QueryString("cartErr"))
mcCartCmd = myWeb.moRequest.QueryString("cartCmd")
If mcCartCmd = "" Then
mcCartCmd = myWeb.moRequest.Form("cartCmd")
End If
mcPaymentMethod = myWeb.moSession("mcPaymentMethod")
mmcOrderType = myWeb.moSession("mmcOrderType")
mcItemOrderType = myWeb.moRequest.Form("ordertype")
' MsgBox "Item: " & mcItemOrderType & vbCrLf & "Order: " & mmcOrderType
' set global variable for submit button
mcSubmitText = myWeb.moRequest("submit")
If mnCartId > 0 Then
' cart exists
'turn off page caching
myWeb.bPageCache = False
If mcPersistCart = "on" Then
writeSessionCookie() 'write the cookie to persist the cart
End If
If mcReEstablishSession <> "" Then
sSql = "select * from tblCartOrder where not(nCartStatus IN (6,9,13,14)) and nCartOrderKey = " & mnCartId
Else
sSql = "select * from tblCartOrder where (nCartStatus < 7 or nCartStatus IN (10,14)) and nCartOrderKey = " & mnCartId & " and not(cCartSessionId like 'OLD_%')"
End If
oDr = moDBHelper.getDataReader(sSql)
If oDr.HasRows Then
While oDr.Read
mnGiftListId = oDr("nGiftListId")
mnTaxRate = CDbl("0" & oDr("nTaxRate"))
mnProcessId = CLng("0" & oDr("nCartStatus"))
cartXmlFromDatabase = oDr("cCartXml").ToString
' Check for deposit and earlier stages
If mcDeposit = "on" Then
If Not (IsDBNull((oDr("nAmountReceived")))) Then
If oDr("nAmountReceived") > 0 And mnProcessId < cartProcess.Confirmed Then
mnProcessId = cartProcess.SettlementInitiated
moDBHelper.ExeProcessSql("update tblCartOrder set nCartStatus = '" & mnProcessId & "' where nCartOrderKey = " & mnCartId)
End If
End If
End If
End While
Else
' Cart no longer exists - a quit command has probably been issued. Clear the session
mnCartId = 0
mnProcessId = 0
mcCartCmd = ""
End If
oDr.Close()
If mnCartId = 0 Then
EndSession()
End If
Else
'-- Cart doesn't exist --
'check if we need to persist the cart
Dim cSessionFromSessionCookie As String = ""
If mcPersistCart = "on" Then
Dim cSessionCookieName As String = "ewSession" & myWeb.mnUserId.ToString
If myWeb.moRequest.Cookies(cSessionCookieName) Is Nothing Then
writeSessionCookie()
Else
Try
'get session ID from cookie IF session ID and current user if match
'Dim cSessionCookieContents As String = myWeb.moRequest.Cookies("ewSession" & myWeb.mnUserId.ToString).Value
Dim cSessionFromCookie As String = myWeb.moRequest.Cookies(cSessionCookieName).Value
'Dim nCartIdCheck As Integer = moDBHelper.ExeProcessSqlScalar("SELECT COUNT(nCartOrderKey) FROM tblCartOrder WHERE nCartUserDirId = " & cUserIdFromCookie.ToString & " AND cCartSessionId = '" & cSessionFromCookie & "'")
If cSessionFromCookie <> "" Then
cSessionFromSessionCookie = cSessionFromCookie
End If
If mcReEstablishSession <> "" Then
cSessionFromSessionCookie = mcReEstablishSession
End If
Catch ex As Exception
cProcessInfo = ex.Message
End Try
End If
End If
' check if the cart can be found in the database, although only run this check if we
' know that we've visited the cart
' Also check out if this is coming from a Worldpay callback.
' Also check we need to udpate the session from the cookie
If Not (myWeb.moRequest("refSessionId") Is Nothing) _
Or Not (myWeb.moRequest("transStatus") Is Nothing) _
Or Not (myWeb.moRequest("ewSettlement") Is Nothing) _
Or (cSessionFromSessionCookie <> "") Then
If Not (myWeb.moRequest("transStatus") Is Nothing) Then
'add in check for session cookie
sSql = "select * from tblCartOrder o inner join tblAudit a on a.nAuditKey=o.nAuditId where o.cCartSchemaName='Order' and o.nCartOrderKey=" & myWeb.moRequest("cartId") & " and DATEDIFF(hh,a.dInsertDate,GETDATE())<24"
mcPaymentMethod = "WorldPay"
ElseIf Not (myWeb.moRequest("ewSettlement") Is Nothing) Then
' Go get the cart, restore settings
sSql = "select * from tblCartOrder where cCartSchemaName='Order' and cSettlementID='" & myWeb.moRequest("ewSettlement") & "'"
Else
'get session id from ewSession cookie
If cSessionFromSessionCookie <> "" Then ' myWeb.mnUserId > 0 And
mcSessionId = cSessionFromSessionCookie
cSessionFromSessionCookie = ""
End If
sSql = "select * from tblCartOrder o inner join tblAudit a on a.nAuditKey=o.nAuditId where o.cCartSchemaName='Order' and o.cCartSessionId = '" & SqlFmt(mcSessionId) & "'"
End If
PerfMon.Log("Cart", "InitializeVariables - check for cart start")
oDr = moDBHelper.getDataReader(sSql)
PerfMon.Log("Cart", "InitializeVariables - check for cart end")
If oDr.HasRows Then
While oDr.Read
mnGiftListId = oDr("nGiftListId")
mnCartId = oDr("nCartOrderKey") ' get cart id
mnProcessId = oDr("nCartStatus") ' get cart status
mnTaxRate = oDr("nTaxRate")
If Not (myWeb.moRequest("ewSettlement") Is Nothing) Or Not (myWeb.moRequest("ewsettlement") Is Nothing) Then
' Set to a holding state that indicates that the settlement has been initiated
mnProcessId = cartProcess.SettlementInitiated
' If a cart has been found, we need to update the session ID in it.
If oDr("cCartSessionId") <> mcSessionId Then
moDBHelper.ExeProcessSql("update tblCartOrder set cCartSessionId = '" & mcSessionId & "' where nCartOrderKey = " & mnCartId)
End If
' Reactivate the order in the database
moDBHelper.ExeProcessSql("update tblCartOrder set nCartStatus = '" & mnProcessId & "' where nCartOrderKey = " & mnCartId)
End If
If mnProcessId > 5 And mnProcessId <> cartProcess.SettlementInitiated Then
' Cart has passed a status of "Succeeded" - we can't do anything to this cart. Clear the session.
EndSession()
mnCartId = 0
mnProcessId = 0
mcCartCmd = ""
End If
mcCurrencyRef = oDr("cCurrency")
cartXmlFromDatabase = oDr("cCartXml").ToString
End While
oDr.Close()
End If
End If
End If
' Load the cart xml from the database for passing on transitory variables.
If mnCartId > 0 AndAlso Not String.IsNullOrEmpty(cartXmlFromDatabase) Then
' This is used to load in variables from the xml that is saved to the database.
' Much more for transitory data that may need to be stored across sessions - e.g. from site to secure site.
Dim cartXmlFromLoad As XmlElement = Nothing
cartXmlFromLoad = myWeb.moPageXml.CreateElement("Load")
cartXmlFromLoad.InnerXml = cartXmlFromDatabase
If Not cartXmlFromLoad.SelectSingleNode("Order") Is Nothing Then
cartXmlFromLoad = cartXmlFromLoad.SelectSingleNode("Order")
If Not String.IsNullOrEmpty(cartXmlFromLoad.GetAttribute("promocodeFromExternalRef")) Then
promocodeFromExternalRef = cartXmlFromLoad.GetAttribute("promocodeFromExternalRef")
End If
End If
cartXmlFromLoad = Nothing
End If
' Check for promo code from request object
If myWeb.moRequest("promocode") <> "" AndAlso myWeb.moSession IsNot Nothing Then
' This has been requested - update Session
myWeb.moSession("promocode") = myWeb.moRequest("promocode").ToString
Me.promocodeFromExternalRef = myWeb.moRequest("promocode").ToString
ElseIf myWeb.moSession IsNot Nothing AndAlso myWeb.moSession("promocode") <> "" Then
' Set the value from the session.
Me.promocodeFromExternalRef = myWeb.moSession("promocode").ToString
End If
mbVatAtUnit = IIf(LCase(moCartConfig("VatAtUnit")) = "yes" Or LCase(moCartConfig("VatAtUnit")) = "on", True, False)
mbVatOnLine = IIf(LCase(moCartConfig("VatOnLine")) = "yes" Or LCase(moCartConfig("VatOnLine")) = "on", True, False)
mbRoundup = IIf(LCase(moCartConfig("Roundup")) = "yes" Or LCase(moCartConfig("Roundup")) = "on", True, False)
mbDiscountsOn = IIf(LCase(moCartConfig("Discounts")) = "yes" Or LCase(moCartConfig("Discounts")) = "on", True, False)
mbOveridePrice = IIf(LCase(moCartConfig("OveridePrice")) = "yes" Or LCase(moCartConfig("OveridePrice")) = "on", True, False)
If mcCurrencyRef = "" Then mcCurrencyRef = myWeb.moSession("cCurrency")
If mcCurrencyRef = "" Or mcCurrencyRef Is Nothing Then mcCurrencyRef = moCartConfig("currencyRef") 'Setting Deprecated
If mcCurrencyRef = "" Or mcCurrencyRef Is Nothing Then mcCurrencyRef = moCartConfig("DefaultCurrencyOveride")
GetCurrencyDefinition()
'try grabbing a userid if we dont have one but have a cart
If myWeb.mnUserId = 0 And mnCartId > 0 Then
sSql = "SELECT nCartUserDirId FROM tblCartOrder WHERE nCartOrderKey = " & mnCartId
Dim cRes As String = moDBHelper.ExeProcessSqlScalar(sSql)
If IsNumeric(cRes) AndAlso cRes > 0 Then
myWeb.mnUserId = CInt(cRes)
mnEwUserId = myWeb.mnUserId
myWeb.moSession("nUserId") = cRes
Dim cRequestPage As String = myWeb.moRequest("pgid")
If IsNumeric(cRequestPage) AndAlso cRequestPage > 0 Then
myWeb.mnPageId = myWeb.moRequest("pgid")
End If
End If
End If
' Behavioural Tweaks
If mnProcessId = cartProcess.SettlementInitiated Then
mbRedirectSecure = True
End If
If moConfig("Subscriptions") = "on" Then
moSubscription = New Subscriptions(Me)
End If
'If Not moDiscount Is Nothing Then
' moDiscount.bHasPromotionalDiscounts = myWeb.moSession("bHasPromotionalDiscounts")
'End If
End If
Catch ex As Exception
returnException(mcModuleName, "InitializeVariables", ex, "", cProcessInfo, gbDebug)
'close()
Finally
oDr = Nothing
End Try
End Sub
Public Sub writeSessionCookie()
'writes the session cookie to persist the cart
If mcPersistCart = "on" Then
'make or update the session cookie
Dim cookieEwSession As System.Web.HttpCookie = New System.Web.HttpCookie("ewSession" & myWeb.mnUserId.ToString)
cookieEwSession.Value = mcSessionId.ToString
cookieEwSession.Expires = DateAdd(DateInterval.Month, 1, Date.Now)
myWeb.moResponse.Cookies.Add(cookieEwSession)
End If
End Sub
Private Sub clearSessionCookie()
Dim cSessionCookieName As String = "ewSession" & myWeb.mnUserId.ToString
If (Not myWeb.moResponse.Cookies(cSessionCookieName) Is Nothing) Then
'clear ewSession cookie so cart doesn't get persisted
'we don't need to check for mcPersistCart = "on"
Dim cookieEwSession As New System.Web.HttpCookie(cSessionCookieName)
cookieEwSession.Expires = Now.AddDays(-1)
myWeb.moResponse.Cookies.Add(cookieEwSession)
cookieEwSession.Expires = DateAdd(DateInterval.Month, 1, Date.Now)
End If
End Sub
Public Shadows Sub close()
PerfMon.Log("Cart", "close")
Dim cProcessInfo As String = ""
Try
PersistVariables()
Catch ex As Exception
returnException(mcModuleName, "Close", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Overridable Sub PersistVariables()
PerfMon.Log("Cart", "PersistVariables")
'Author: Trevor Spink
'Copyright: Eonic Ltd 2003
'Date: 2003-02-01
'called at the end of the main procedure (ewCartPlugin())
'holds variable values after cart module ends for use next time it starts
'they are stored in either a session attribute or in the database
Dim sSql As String
Dim cProcessInfo As String = ""
Try
cProcessInfo = "set session variables" ' persist global sProcessInfo
If Not myWeb.moSession Is Nothing Then
If myWeb.moSession("CartId") Is Nothing Then
myWeb.moSession.Add("CartId", CStr(mnCartId))
Else
myWeb.moSession("CartId") = CStr(mnCartId)
End If
' oResponse.Cookies(mcSiteURL & "CartId").Domain = mcSiteURL
' oSession("nCartOrderId") = mnCartId ' session attribute holds Cart ID
End If
If mnCartId > 0 Then
' Only update the process if less than 6 we don't ever want to change the status of a completed order other than within the admin system. Boo Yah!
Dim currentStatus As Integer = moDBHelper.ExeProcessSqlScalar("select nCartStatus from tblCartOrder where nCartOrderKey = " & mnCartId)
If currentStatus < 6 Then
' If we have a cart, update its status in the db
If mnProcessId <> currentStatus Then
sSql = "update tblCartOrder set nCartStatus = " & mnProcessId & ", nGiftListId = " & mnGiftListId & ", nCartUserDirId = " & myWeb.mnUserId & " where nCartOrderKey = " & mnCartId
Else
sSql = "update tblCartOrder set nGiftListId = " & mnGiftListId & ", nCartUserDirId = " & myWeb.mnUserId & " where nCartOrderKey = " & mnCartId
End If
moDBHelper.ExeProcessSql(sSql)
End If
End If
If Not myWeb.moSession Is Nothing Then
myWeb.moSession("nProcessId") = mnProcessId ' persist global mnProcessId
myWeb.moSession("mcPaymentMethod") = mcPaymentMethod
myWeb.moSession("mmcOrderType") = mmcOrderType
myWeb.moSession("nTaxRate") = mnTaxRate
If Not moDiscount Is Nothing Then
myWeb.moSession("bHasPromotionalDiscounts") = moDiscount.bHasPromotionalDiscounts
End If
End If
Catch ex As Exception
returnException(mcModuleName, "PersistVariables", ex, "", cProcessInfo, gbDebug)
'close()
End Try
End Sub
Overridable Sub checkButtons()
PerfMon.Log("Cart", "checkButtons")
Dim cProcessInfo As String = ""
Try
'if we have set mcCartCmdAlt then that overides the button.
If mcCartCmdAlt <> "" Then
mcCartCmd = mcCartCmdAlt
Exit Sub
End If
If ButtonSubmitted(myWeb.moRequest, "cartAdd") Then
mcCartCmd = "Add"
End If
If ButtonSubmitted(myWeb.moRequest, "cartDetail") Then
mcCartCmd = "Cart"
End If
If ButtonSubmitted(myWeb.moRequest, "cartProceed") Then
mcCartCmd = "RedirectSecure"
End If
If ButtonSubmitted(myWeb.moRequest, "cartNotes") Then
mcCartCmd = "Notes"
End If
If ButtonSubmitted(myWeb.moRequest, "cartUpdate") Then
mcCartCmd = "Update"
End If
If ButtonSubmitted(myWeb.moRequest, "cartLogon") Then
mcCartCmd = "Logon"
End If
If ButtonSubmitted(myWeb.moRequest, "cartRegister") Then
mcCartCmd = "Logon"
End If
If ButtonSubmitted(myWeb.moRequest, "cartQuit") Then
mcCartCmd = "Quit"
End If
'Continue shopping
If ButtonSubmitted(myWeb.moRequest, "cartBrief") Then
mcCartCmd = "Brief"
End If
' Pick Address Buttions
If ButtonSubmitted(myWeb.moRequest, "cartBillAddress") Or ButtonSubmitted(myWeb.moRequest, "cartBillcontact") Or ButtonSubmitted(myWeb.moRequest, "cartBilladdNewAddress") Or ButtonSubmitted(myWeb.moRequest, "cartBilleditAddress") Then
mcCartCmd = "Billing"
End If
If ButtonSubmitted(myWeb.moRequest, "cartDelAddress") Or ButtonSubmitted(myWeb.moRequest, "cartDelcontact") Or ButtonSubmitted(myWeb.moRequest, "cartDeladdNewAddress") Or ButtonSubmitted(myWeb.moRequest, "cartDeleditAddress") Then
mcCartCmd = "Delivery"
End If
'legacy button handling looking at button values rather than names, should not be required soon
'Select Case mcSubmitText
' Case "Goto Checkout", "Go To Checkout"
' updateCart("RedirectSecure")
' mcCartCmd = "RedirectSecure"
' Case "Edit Billing Details", "Proceed without Logon"
' mcCartCmd = "Billing"
' Case "Edit Delivery Details"
' mcCartCmd = "Delivery"
' Case "Confirm Order", "Proceed with Order", "Proceed"
' updateCart("ChoosePaymentShippingOption")
' Case "Update Cart", "Update Order"
' updateCart("Cart")
' Case "Empty Cart", "Empty Order"
' mcCartCmd = "Quit"
' Case "Make Secure Payment"
' updateCart(mcCartCmd)
' Case "Continue Shopping"
' mcCartCmd = "BackToSite"
'End Select
Catch ex As Exception
returnException(mcModuleName, "checkButtons", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Function CreateCartElement(oCartXML As XmlDocument)
Dim oContentElmt As XmlElement
Dim oElmt As XmlElement
Try
oContentElmt = oCartXML.CreateElement("Cart")
oContentElmt.SetAttribute("type", "order")
oContentElmt.SetAttribute("currency", mcCurrency)
oContentElmt.SetAttribute("currencySymbol", mcCurrencySymbol)
If Not mbDisplayPrice Then oContentElmt.SetAttribute("displayPrice", mbDisplayPrice.ToString)
oElmt = oCartXML.CreateElement("Order")
oContentElmt.AppendChild(oElmt)
moCartXml = oContentElmt
Return oContentElmt
Catch ex As Exception
returnException(mcModuleName, "apply", ex, "", "CreateCartElement", gbDebug)
Return Nothing
End Try
End Function
Public Overridable Sub apply()
PerfMon.Log("Cart", "apply")
' this function is the main function.
Dim oCartXML As XmlDocument = moPageXml
Dim oContentElmt As XmlElement
Dim oElmt As XmlElement
'Dim oPickContactXForm As xForm
Dim cProcessInfo As String = ""
Dim bRedirect As Boolean
Dim cRepeatPaymentError As String = ""
Try
' myWeb.moDbHelper.logActivity(Eonic.Web.dbHelper.ActivityType.Alert, 0, 0, 0, "Start1 CALLBACK : " & mnProcessId & mcCartCmd)
oContentElmt = CreateCartElement(oCartXML)
oElmt = oContentElmt.FirstChild
' if the cartCmd is not on a link but on a button
' we need to set the cartCmd dependant upon the button name
'TS for OpenQuote allow cart step to be set before checking against button allows apply to be called again
If mcCartCmd = "" Then
End If
checkButtons()
' Cart Command overrides
If mbRedirectSecure Or mnProcessId = cartProcess.SettlementInitiated Then
mcCartCmd = "RedirectSecure"
End If
' Secure Trading CallBack override
If mcCartCmd <> "" Then
If mcCartCmd.StartsWith("SecureTradingReturn") Then mcCartCmd = "SubmitPaymentDetails"
End If
If Not (mnCartId > 0) Then
' Cart doesn't exist - if the process flow has a valid command (except add or quit), then this is an error
Select Case mcCartCmd
Case "Cart"
mcCartCmd = "CartEmpty"
Case "Logon", "Remove", "Notes", "Billing", "Delivery", "ChoosePaymentShippingOption", "Confirm", "EnterPaymentDetails", "SubmitPaymentDetails", "SubmitPaymentDetails", "ShowInvoice", "ShowCallBackInvoice"
mcCartCmd = "CookiesDisabled"
Case "Error"
mcCartCmd = "Error"
End Select
End If
'Cart Process
processFlow:
' myWeb.moDbHelper.logActivity(Eonic.Web.dbHelper.ActivityType.Alert, 0, 0, 0, "Start2 CALLBACK : " & mnProcessId & mcCartCmd)
' user can't change things if we are to show the invoice
If mnProcessId = Cart.cartProcess.Complete And mcCartCmd <> "Quit" And mcCartCmd <> "ShowCallBackInvoice" Then mcCartCmd = "ShowInvoice"
cProcessInfo &= IIf(mcCartCmd = "", "", ", ") & mcCartCmd
If mcCartCmd <> "" Then
'ensure the client is not able to hit the back button and go back to the page without refreshing.
'This should resolve some rare random errors in the cart process.
myWeb.mbSetNoBrowserCache = True
End If
Select Case mcCartCmd
Case "Update"
mcCartCmd = updateCart("Currency")
GoTo processFlow
Case "Remove" ' take away an item and set the command to display the cart
If RemoveItem() > 0 Then
mcCartCmd = "Currency"
Else
' RemoveItem has removed the last item in the cart - quit the cart.
mcCartCmd = "Quit"
End If
GoTo processFlow
Case "Add" ' add an item to the cart, if its a new cart we must initialise it and change its status
Dim qtyAdded As Long = 0
Dim oItem1 As Object
Dim nQuantity As Long
'Check we are adding a quantity (we need to catch any adds that don't have a specified quantity and create empty carts)
For Each oItem1 In myWeb.moRequest.Form 'Loop for getting products/quants
If InStr(oItem1, "qty_") = 1 Then 'check for getting productID and quantity (since there will only be one of these per item submitted)
If IsNumeric(myWeb.moRequest.Form.Get(oItem1)) Then
nQuantity = myWeb.moRequest.Form.Get(oItem1)
End If
'replacementName
If nQuantity > 0 Then
qtyAdded = qtyAdded + nQuantity
End If 'end check for previously added
End If 'end check for item/quant
Next 'End Loop for getting products/quants
If mnCartId < 1 And qtyAdded > 0 Then
CreateNewCart(oElmt)
If mcItemOrderType <> "" Then
mmcOrderType = mcItemOrderType
Else
mmcOrderType = ""
End If
mnProcessId = 1
End If
If qtyAdded > 0 And mnCartId > 0 Then
If Not AddItems() Then
mnProcessError = 2 ' Error: The current item's order type does not match the cart's order type
mcCartCmd = "Error"
GoTo processFlow
Else
'Case for if a items have been added from a giftlist
If Not myWeb.moRequest("giftlistId") Is Nothing Then
AddDeliveryFromGiftList(myWeb.moRequest("giftlistId"))
End If
mcCartCmd = "Currency"
GoTo processFlow
End If
End If
If qtyAdded > 0 And mnCartId = 0 Then
mnProcessError = 1 ' Error: Cookies Disabled
mcCartCmd = "Error"
GoTo processFlow
End If
'here is where we should check cart for subscriptions
Case "Currency"
If SelectCurrency() Then
If mcCartCmd = "Cart" Then
AddBehaviour()
End If
GoTo processFlow
End If
Case "Quit"
' action depends on whether order is complete or not
If mnProcessId = 6 Or mnProcessId = 10 Then
' QuitCart()
EndSession()
mcCartCmd = ""
mnCartId = 0
mnProcessId = 0
Else
clearSessionCookie()
QuitCart()
EndSession()
mnProcessId = 0
If bFullCartOption = True Then
GetCart(oElmt)
Else
GetCartSummary(oElmt)
End If
mnCartId = 0
End If
'return to site
bRedirect = True
'hack for assure so we can choose not to redirect on quit
If myWeb.moRequest("redirect") <> "false" Then
If mcReturnPage Is Nothing Then mcReturnPage = ""
If Not myWeb.moRequest("redirect") Is Nothing Then
If myWeb.moRequest("redirect").StartsWith("/") Then mcReturnPage = myWeb.moRequest("redirect")
End If
myWeb.msRedirectOnEnd = mcSiteURL & mcReturnPage & IIf((mcSiteURL & mcReturnPage).Contains("?"), "&", "?") & "cartCmd=finish"
'myWeb.moResponse.Redirect(mcSiteURL & mcReturnPage & IIf((mcSiteURL & mcReturnPage).Contains("?"), "&", "?") & "cartCmd=finish")
End If
Case "Error"
GetCart(oElmt)
Case "Cart" 'Choose Shipping Costs
If mnProcessId > 3 Then
' when everything is ready we can show the invoice screen
mcCartCmd = "Confirm"
GoTo processFlow ' execute next step (make the payment)
End If
' info to display the cart
GetCart(oElmt)
Case "Discounts"
mcCartCmd = discountsProcess(oElmt)
If mcCartCmd <> "Discounts" Then
GoTo processflow
End If
Case "RedirectSecure"
Dim cRedirectCommand As String
' Set a Session variable flag to
myWeb.moSession.Add("CartIsOn", "true")
bRedirect = True
If myWeb.moRequest("ewSettlement") Is Nothing Then
cRedirectCommand = "Logon"
Else
cRedirectCommand = "ChoosePaymentShippingOption"
End If
' If a settlement has been initiated, then update the process
If mnProcessId = cartProcess.SettlementInitiated Then
mnProcessId = cartProcess.PassForPayment
moDBHelper.ExeProcessSql("update tblCartOrder set nCartStatus = '" & mnProcessId & "' where nCartOrderKey = " & mnCartId)
End If
' pickup any google tracking code.
Dim item As Object
Dim cGoogleTrackingCode As String = ""
For Each item In myWeb.moRequest.QueryString
' form needs to have this <form method="post" action="http://www.thissite.com" id="cart" onsubmit="pageTracker._linkByPost(this)">
' the action URL is important
' each querystring item in the google tracking code start with __utm
If InStr(CStr(item), "__utm") = 1 Then
cGoogleTrackingCode = cGoogleTrackingCode & "&" & CStr(item) & "=" & myWeb.moRequest.QueryString(CStr(item))
End If
Next item
myWeb.msRedirectOnEnd = mcPagePath & "cartCmd=" & cRedirectCommand & "&refSessionId=" & mcSessionId & cGoogleTrackingCode
' myWeb.moResponse.Redirect(mcPagePath & "cartCmd=" & cRedirectCommand & "&refSessionId=" & mcSessionId & cGoogleTrackingCode)
Case "Logon", "LogonSubs" ' offer the user the ability to logon / register
If mbEwMembership = True And (moCartConfig("SkipLogon") <> "on" Or mcCartCmd = "LogonSubs") Then
'logon xform !!! We disable this because it is being brought in allready by .Web
If myWeb.mnUserId = 0 Then
'addtional string for membership to check
myWeb.moSession("cLogonCmd") = "cartCmd=Logon"
'registration xform
Dim oMembershipProv As New Providers.Membership.BaseProvider(myWeb, myWeb.moConfig("MembershipProvider"))
Dim oRegXform As AdminXForms = oMembershipProv.AdminXforms
oRegXform.open(moPageXml)
oRegXform.xFrmEditDirectoryItem(myWeb.mnUserId, "User", CInt("0" & moCartConfig("DefaultSubscriptionGroupId")), "CartRegistration")
If oRegXform.valid Then
Dim sReturn As String = moDBHelper.validateUser(myWeb.moRequest("cDirName"), myWeb.moRequest("cDirPassword"))
If IsNumeric(sReturn) Then
myWeb.mnUserId = CLng(sReturn)
Dim oUserElmt As XmlElement = moDBHelper.GetUserXML(myWeb.mnUserId)
moPageXml.DocumentElement.AppendChild(oUserElmt)
myWeb.moSession("nUserId") = myWeb.mnUserId
mcCartCmd = "Notes"
GoTo processFlow
Else
oRegXform.addNote(oRegXform.moXformElmt.FirstChild, xForm.noteTypes.Alert, sReturn)
moPageXml.SelectSingleNode("/Page/Contents").AppendChild(oRegXform.moXformElmt)
End If
Else
moPageXml.SelectSingleNode("/Page/Contents").AppendChild(oRegXform.moXformElmt)
GetCart(oElmt)
End If
oRegXform = Nothing
Else
mcCartCmd = "Notes"
GoTo processFlow
End If
Else
mcCartCmd = "Notes"
GoTo processFlow
End If
Case "Notes"
mcCartCmd = notesProcess(oElmt)
If mcCartCmd <> "Notes" Then
GoTo processflow
End If
Case "SkipAddress" 'Check if order has Billing Address
If usePreviousAddress(oElmt) = False Then
mcCartCmd = "Billing"
End If
If mcCartCmd <> "SkipAddress" Then
GoTo processFlow
End If
Case "Billing" 'Check if order has Billing Address
addressSubProcess(oElmt, "Billing Address")
GetCart(oElmt)
If mcCartCmd <> "Billing" Then
GoTo processflow
End If
Case "Delivery" 'Check if order needs a Delivery Address
addressSubProcess(oElmt, "Delivery Address")
GetCart(oElmt)
If mcCartCmd <> "Delivery" Then
GoTo processflow
End If
Case "ChoosePaymentShippingOption", "Confirm" ' and confirm terms and conditions
mnProcessId = 4
GetCart(oElmt)
If mcCartCmd = "ChoosePaymentShippingOption" Then
If Not oContentElmt Is Nothing Then
AddToLists("Quote", oContentElmt)
End If
End If
Dim oOptionXform As xForm = optionsXform(oElmt)
If Not oOptionXform.valid Then
Dim oContentsElmt As XmlElement = moPageXml.SelectSingleNode("/Page/Contents")
If oContentsElmt Is Nothing Then
oContentsElmt = moPageXml.CreateElement("Contents")
If moPageXml.DocumentElement Is Nothing Then
Err.Raise(1004, "addressSubProcess", " PAGE IS NOT CREATED")
Else
moPageXml.DocumentElement.AppendChild(oContentsElmt)
End If
End If
oContentsElmt.AppendChild(oOptionXform.moXformElmt)
'moPageXml.SelectSingleNode("/Page/Contents").AppendChild(oOptionXform.moXformElmt)
If Not cRepeatPaymentError = "" Then
oOptionXform.addNote(oOptionXform.moXformElmt.SelectSingleNode("group"), xForm.noteTypes.Alert, cRepeatPaymentError, True)
End If
Else
mnProcessId = 5
mcCartCmd = "EnterPaymentDetails"
' execute next step unless form filled out wrong / not in db
GoTo processFlow
End If
Case "Redirect3ds"
Dim oEwProv As Eonic.Web.Cart.PaymentProviders = New PaymentProviders(myWeb)
Dim Redirect3dsXform As xForm = New xForm
Redirect3dsXform = oEwProv.GetRedirect3dsForm(myWeb)
moPageXml.SelectSingleNode("/Page/Contents").AppendChild(Redirect3dsXform.moXformElmt)
myWeb.moResponseType = pageResponseType.iframe
Case "EnterPaymentDetails", "SubmitPaymentDetails" 'confirm order and submit for payment
mnProcessId = 5
If oElmt.FirstChild Is Nothing Then
GetCart(oElmt)
End If
' Add the date and reference to the cart
addDateAndRef(oElmt)
If mcPaymentMethod = "No Charge" Then
mcCartCmd = "ShowInvoice"
mnProcessId = Cart.cartProcess.Complete
GoTo processFlow
End If
Dim oPayProv As New Providers.Payment.BaseProvider(myWeb, mcPaymentMethod)
Dim ccPaymentXform As xForm = New xForm
ccPaymentXform = oPayProv.Activities.GetPaymentForm(myWeb, Me, oElmt)
If InStr(mcPaymentMethod, "Repeat_") > 0 Then
If ccPaymentXform.valid = True Then
mcCartCmd = "ShowInvoice"
GoTo processFlow
ElseIf ccPaymentXform.isSubmitted Then
If ccPaymentXform.getSubmitted = "Cancel" Then
mcCartCmd = "ChoosePaymentShippingOption"
GoTo processFlow
Else
'invalid redisplay form
End If
End If
End If
' Don't show the payment screen if the stock levels are incorrect
If Not (oElmt.SelectSingleNode("error/msg") Is Nothing) Then
'oElmt.SelectSingleNode("error").PrependChild(oElmt.OwnerDocument.CreateElement("msg"))
'oElmt.SelectSingleNode("error").FirstChild.InnerXml = "<strong>PAYMENT CANNOT PROCEED UNTIL QUANTITIES ARE ADJUSTED</strong>"
ElseIf ccPaymentXform.valid = True Then
mcCartCmd = "ShowInvoice"
'Move this from "ShowInvoice" to prevent URL requests from confirming successful payment
If (mnProcessId <> Cart.cartProcess.DepositPaid And mnProcessId <> Cart.cartProcess.AwaitingPayment) Then
mnProcessId = Cart.cartProcess.Complete
End If
'remove the existing cart to force an update.
Dim oNodeCart As XmlNode
For Each oNodeCart In oElmt.SelectNodes("*")
oElmt.RemoveChild(oNodeCart)
Next
'oEwProv = Nothing
GoTo processFlow
Else
moPageXml.SelectSingleNode("/Page/Contents").AppendChild(ccPaymentXform.moXformElmt)
End If
'oEwProv = Nothing
Case "ShowInvoice", "ShowCallBackInvoice" 'Payment confirmed / show invoice
If mnProcessId <> Cart.cartProcess.Complete And mnProcessId <> Cart.cartProcess.AwaitingPayment Then
'check we are allready complete otherwise we will risk confirming sale just on URL request.
'myWeb.moDbHelper.logActivity(Eonic.Web.dbHelper.ActivityType.Alert, 0, 0, 0, "FAILED CALLBACK : " & mnProcessId)
mcCartCmd = "ChoosePaymentShippingOption"
GoTo processFlow
Else
PersistVariables()
If oElmt.FirstChild Is Nothing Then
GetCart(oElmt)
End If
If moCartConfig("StockControl") = "on" Then
UpdateStockLevels(oElmt)
End If
UpdateGiftListLevels()
addDateAndRef(oElmt)
If myWeb.mnUserId > 0 Then
Dim userXml As XmlElement = myWeb.moDbHelper.GetUserXML(myWeb.mnUserId, False)
If userXml IsNot Nothing Then
Dim cartElement As XmlElement = oContentElmt.SelectSingleNode("Cart")
If cartElement IsNot Nothing Then
cartElement.AppendChild(cartElement.OwnerDocument.ImportNode(userXml, True))
End If
End If
End If
purchaseActions(oContentElmt)
AddToLists("Invoice", oContentElmt)
If myWeb.mnUserId > 0 Then
If Not moSubscription Is Nothing Then
moSubscription.AddUserSubscriptions(Me.mnCartId, myWeb.mnUserId, mnPaymentId)
End If
End If
emailReceipts(oContentElmt)
moDiscount.DisablePromotionalDiscounts()
If mbQuitOnShowInvoice Then
EndSession()
End If
End If
Case "CookiesDisabled" ' Cookies have been disabled or are undetectable
mnProcessError = 1
GetCart(oElmt)
Case "CartEmpty" ' Cookies have been disabled or are undetectable
mnProcessError = -1
GetCart(oElmt)
Case "BackToSite"
bRedirect = True
myWeb.moResponse.Redirect(mcSiteURL & mcReturnPage, False)
myWeb.moCtx.ApplicationInstance.CompleteRequest()
Case "List"
Dim nI As Integer = 0
If Not myWeb.moRequest.Item("OrderID") = "" Then nI = myWeb.moRequest.Item("OrderID")
GetCartSummary(oElmt)
ListOrders(nI)
Case "MakeCurrent"
Dim nI As Integer = 0
If Not myWeb.moRequest.Item("OrderID") = "" Then nI = myWeb.moRequest.Item("OrderID")
If Not nI = 0 Then MakeCurrent(nI)
mcCartCmd = "Cart"
GoTo processFlow
Case "Delete"
Dim nI As Integer = 0
If Not myWeb.moRequest.Item("OrderID") = "" Then nI = myWeb.moRequest.Item("OrderID")
If Not nI = 0 Then DeleteCart(nI)
mcCartCmd = "List"
GoTo processFlow
Case "Brief"
'Continue shopping
'go to the cart url
Dim cPage As String = myWeb.moRequest("pgid")
If cPage = "" Or cPage Is Nothing Then cPage = moPageXml.DocumentElement.GetAttribute("id")
cPage = "?pgid=" & cPage
myWeb.moResponse.Redirect(mcSiteURL & cPage, False)
myWeb.moCtx.ApplicationInstance.CompleteRequest()
Case "NoteToAddress"
'do nothing this is a placeholder for openquote
GetCart(oElmt)
Case Else ' Show Cart Summary
mcCartCmd = ""
If bFullCartOption = True Then
GetCart(oElmt)
Else
GetCartSummary(oElmt)
End If
End Select
PersistVariables() ' store data for next time this function runs
If Not (oElmt Is Nothing) Then
oElmt.SetAttribute("cmd", mcCartCmd)
oElmt.SetAttribute("sessionId", CStr(mcSessionId))
oElmt.SetAttribute("siteUrl", mcSiteURL)
oElmt.SetAttribute("cartUrl", mcCartURL)
End If
AddCartToPage(moPageXml, oContentElmt)
Exit Sub
Catch ex As Exception
If bRedirect = True And ex.GetType() Is GetType(System.Threading.ThreadAbortException) Then
'mbRedirect = True
'do nothing
Else
returnException(mcModuleName, "apply", ex, "", cProcessInfo, gbDebug)
End If
End Try
End Sub
Sub AddCartToPage(moPageXml As XmlDocument, oContentElmt As XmlElement)
Dim cProcessInfo As String = ""
Try
oContentElmt.SetAttribute("currencyRef", mcCurrencyRef)
oContentElmt.SetAttribute("currency", mcCurrency)
oContentElmt.SetAttribute("currencySymbol", mcCurrencySymbol)
oContentElmt.SetAttribute("Process", mnProcessId)
'remove any existing Cart
If Not moPageXml.DocumentElement.SelectSingleNode("Cart") Is Nothing Then
moPageXml.DocumentElement.RemoveChild(moPageXml.DocumentElement.SelectSingleNode("Cart"))
End If
moPageXml.DocumentElement.AppendChild(oContentElmt)
Catch ex As Exception
returnException(mcModuleName, "AddCartElement", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Overridable Sub AddBehaviour()
Dim cProcessInfo As String = ""
Try
Select Case LCase(moCartConfig("AddBehaviour"))
Case "discounts"
mcCartCmd = "Discounts"
Case "notes"
mcCartCmd = "RedirectSecure"
Case "brief"
mcCartCmd = "Brief"
Case Else
'do nothing
End Select
Catch ex As Exception
returnException(mcModuleName, "AddBehavior", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Overridable Function GetPaymentProvider() As PaymentProviders
Dim oEwProv As PaymentProviders = New PaymentProviders(myWeb)
Return oEwProv
End Function
Overridable Sub emailReceipts(ByRef oCartElmt As XmlElement)
PerfMon.Log("Cart", "emailReceipts")
Dim sMessageResponse As String
Dim cProcessInfo As String = ""
Try
If LCase(moCartConfig("EmailReceipts")) <> "off" Then
' Default subject line
Dim cSubject As String = moCartConfig("OrderEmailSubject")
If String.IsNullOrEmpty(cSubject) Then cSubject = "Website Order"
Dim CustomerEmailTemplatePath As String = IIf(moCartConfig("CustomerEmailTemplatePath") <> "", moCartConfig("CustomerEmailTemplatePath"), "/xsl/Cart/mailOrderCustomer.xsl")
Dim MerchantEmailTemplatePath As String = IIf(moCartConfig("MerchantEmailTemplatePath") <> "", moCartConfig("MerchantEmailTemplatePath"), "/xsl/Cart/mailOrderMerchant.xsl")
'send to customer
sMessageResponse = emailCart(oCartElmt, CustomerEmailTemplatePath, moCartConfig("MerchantName"), moCartConfig("MerchantEmail"), (oCartElmt.FirstChild.SelectSingleNode("Contact[@type='Billing Address']/Email").InnerText), cSubject)
'Send to merchant
sMessageResponse = emailCart(oCartElmt, MerchantEmailTemplatePath, (oCartElmt.FirstChild.SelectSingleNode("Contact[@type='Billing Address']/GivenName").InnerText), (oCartElmt.FirstChild.SelectSingleNode("Contact[@type='Billing Address']/Email").InnerText), moCartConfig("MerchantEmail"), cSubject)
Dim oElmtEmail As XmlElement
oElmtEmail = moPageXml.CreateElement("Reciept")
oCartElmt.AppendChild(oElmtEmail)
oElmtEmail.InnerText = sMessageResponse
If sMessageResponse = "Message Sent" Then
oElmtEmail.SetAttribute("status", "sent")
Else
oElmtEmail.SetAttribute("status", "failed")
End If
End If
Catch ex As Exception
returnException(mcModuleName, "emailReceipts", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Overridable Sub purchaseActions(ByRef oCartElmt As XmlElement)
PerfMon.Log("Cart", "purchaseActions")
' Dim sMessageResponse As String
Dim cProcessInfo As String = ""
Dim ocNode As XmlElement
Try
For Each ocNode In oCartElmt.SelectNodes("descendant-or-self::Order/Item/productDetail[@purchaseAction!='']")
Dim classPath As String = ocNode.GetAttribute("purchaseAction")
Dim assemblyName As String = ocNode.GetAttribute("assembly")
Dim providerName As String = ocNode.GetAttribute("providerName")
Dim assemblyType As String = ocNode.GetAttribute("assemblyType")
Dim methodName As String = Right(classPath, Len(classPath) - classPath.LastIndexOf(".") - 1)
classPath = Left(classPath, classPath.LastIndexOf("."))
If classPath <> "" Then
Try
Dim calledType As Type
If assemblyName <> "" Then
classPath = classPath & ", " & assemblyName
End If
'Dim oModules As New Eonic.Web.Membership.Modules
If providerName <> "" Then
'case for external Providers
Dim moPrvConfig As Eonic.ProviderSectionHandler = WebConfigurationManager.GetWebApplicationSection("eonic/messagingProviders")
Dim assemblyInstance As [Assembly] = [Assembly].Load(moPrvConfig.Providers(providerName).Type)
calledType = assemblyInstance.GetType(classPath, True)
ElseIf assemblyType <> "" Then
'case for external DLL's
Dim assemblyInstance As [Assembly] = [Assembly].Load(assemblyType)
calledType = assemblyInstance.GetType(classPath, True)
Else
'case for methods within EonicWeb Core DLL
calledType = System.Type.GetType(classPath, True)
End If
Dim o As Object = Activator.CreateInstance(calledType)
Dim args(1) As Object
args(0) = Me.myWeb
args(1) = ocNode
calledType.InvokeMember(methodName, BindingFlags.InvokeMethod, Nothing, o, args)
'Error Handling ?
'Object Clearup ?
Catch ex As Exception
' OnComponentError(Me, New Eonic.Tools.Errors.ErrorEventArgs(mcModuleName, "ContentActions", ex, sProcessInfo))
cProcessInfo = classPath & "." & methodName & " not found"
ocNode.InnerXml = "<Content type=""error""><div>" & cProcessInfo & "</div></Content>"
End Try
End If
Next
Catch ex As Exception
returnException(mcModuleName, "purchaseActions", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
''' <summary>
''' This provides the ability to add customers to makreting lists if they reach a particular stage within a shopping cart.
''' Only works if 3rd party messaging provider enabled.
''' </summary>
''' <param name="StepName"></param>
''' <param name="oCartElmt"></param>
Overridable Sub AddToLists(StepName As String, ByRef oCartElmt As XmlElement, Optional Name As String = "", Optional Email As String = "", Optional valDict As System.Collections.Generic.Dictionary(Of String, String) = Nothing)
PerfMon.Log("Cart", "AddToLists")
' Dim sMessageResponse As String
Dim cProcessInfo As String = ""
Try
Dim moMailConfig As System.Collections.Specialized.NameValueCollection = WebConfigurationManager.GetWebApplicationSection("eonic/mailinglist")
If Not moMailConfig Is Nothing Then
Dim sMessagingProvider As String = ""
If Not moMailConfig Is Nothing Then
sMessagingProvider = moMailConfig("MessagingProvider")
End If
If sMessagingProvider <> "" Or (moMailConfig("InvoiceList") <> "" And moMailConfig("QuoteList") <> "") Then
Dim oMessaging As New Eonic.Providers.Messaging.BaseProvider(myWeb, sMessagingProvider)
If Email = "" Then Email = oCartElmt.FirstChild.SelectSingleNode("Contact[@type='Billing Address']/Email").InnerText
If Name = "" Then Name = oCartElmt.FirstChild.SelectSingleNode("Contact[@type='Billing Address']/GivenName").InnerText
If valDict Is Nothing Then valDict = New System.Collections.Generic.Dictionary(Of String, String)
For Each Attribute As XmlAttribute In oCartElmt.Attributes
If Not "errorMsg,hideDeliveryAddress,orderType,statusId,complete".Contains(Attribute.Name) Then
valDict.Add(Attribute.Name, Attribute.Value)
End If
Next
Dim ListId As String = ""
Select Case StepName
Case "Invoice"
ListId = moMailConfig("InvoiceList")
If moMailConfig("QuoteList") <> "" Then
oMessaging.Activities.RemoveFromList(moMailConfig("QuoteList"), Email)
End If
Case "Quote"
If moMailConfig("QuoteList") <> "" Then
oMessaging.Activities.RemoveFromList(moMailConfig("QuoteList"), Email)
End If
ListId = moMailConfig("QuoteList")
End Select
If ListId <> "" Then
oMessaging.Activities.addToList(ListId, Name, Email, valDict)
End If
End If
End If
Catch ex As Exception
returnException(mcModuleName, "purchaseActions", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Private Sub RemoveDeliveryOption(ByVal nOrderId As Integer)
Try
Dim cSQL As String = "UPDATE tblCartOrder SET nShippingMethodId = 0, cShippingDesc = NULL, nShippingCost = 0 WHERE nCartOrderKey = " & nOrderId
myWeb.moDbHelper.ExeProcessSqlorIgnore(cSQL)
Catch ex As Exception
returnException(mcModuleName, "RemoveDeliveryOption", ex, "", "", gbDebug)
End Try
End Sub
'Sub GetCartSummary(ByRef oCartElmt As XmlElement, Optional ByVal nSelCartId As Integer = 0)
' PerfMon.Log("Cart", "GetCartSummary")
' ' Sets content for the XML to be displayed in the small summary plugin attached
' ' to the current content page
' Dim oDs As DataSet
' Dim sSql As String
' Dim cNotes As String
' Dim total As Double
' Dim quant As Integer
' Dim weight As Integer
' Dim nCheckPrice As Double
' Dim oRow As DataRow
' 'We need to read this value from somewhere so we can change where vat is added
' 'Currently defaulted to per line
' 'If true will be added to the unit
' Dim nUnitVat As Decimal = 0
' Dim nLineVat As Decimal = 0
' Dim nCartIdUse As Integer
' If nSelCartId > 0 Then nCartIdUse = nSelCartId Else nCartIdUse = mnCartId
' Dim cProcessInfo As String = ""
' oCartElmt.SetAttribute("vatRate", moCartConfig("TaxRate"))
' Try
' If Not moSubscription Is Nothing Then moSubscription.CheckCartForSubscriptions(nCartIdUse, myWeb.mnUserId)
' If Not (nCartIdUse > 0) Then ' no shopping
' oCartElmt.SetAttribute("status", "Empty") ' set CartXML attributes
' oCartElmt.SetAttribute("itemCount", "0") ' to nothing
' oCartElmt.SetAttribute("vatRate", moCartConfig("TaxRate"))
' oCartElmt.SetAttribute("total", "0.00") ' for nothing
' Else
' ' otherwise
' ' and the address details we have obtained
' ' (if any)
' 'Add Totals
' quant = 0 ' get number of items & sum of collective prices (ie. cart total) from db
' total = 0.0#
' weight = 0.0#
' sSql = "select i.nCartItemKey as id, i.nItemId as contentId, i.cItemRef as ref, i.cItemURL as url, i.cItemName as Name, i.cItemUnit as unit, i.nPrice as price, i.nTaxRate as taxRate, i.nQuantity as quantity, i.nShpCat as shippingLevel, i.nDiscountValue as discount,i.nWeight as weight, p.cContentXmlDetail as productDetail, i.nItemOptGrpIdx, i.nItemOptIdx, i.nParentId, p.cContentSchemaName AS contentType from tblCartItem i left join tblContent p on i.nItemId = p.nContentKey where nCartOrderId=" & nCartIdUse
' ':TODO we only want to check prices on current orders not history
' oDs = moDBHelper.getDataSetForUpdate(sSql, "Item", "Cart")
' '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
' oDs.Relations.Add("Rel1", oDs.Tables("Item").Columns("id"), oDs.Tables("Item").Columns("nParentId"), False)
' oDs.Relations("Rel1").Nested = True
' '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
' For Each oRow In oDs.Tables("Item").Rows
' If moDBHelper.DBN2int(oRow("nParentId")) = 0 Then
' Dim oOpRow As DataRow
' Dim nOpPrices As Decimal = 0
' If Not IsDBNull(oRow("productDetail")) Then
' ' Go get the lowest price based on user and group
' nCheckPrice = getProductPricesByXml(oRow("productDetail"), oRow("unit") & "", oRow("quantity"))
' If Not moSubscription Is Nothing And oRow("contentType") = "Subscription" Then nCheckPrice = moSubscription.CartSubscriptionPrice(oRow("contentId"), myWeb.mnUserId)
' If nCheckPrice > 0 And nCheckPrice <> oRow("price") Then
' ' If price is lower, then update the item price field
' oRow.BeginEdit()
' oRow("price") = nCheckPrice
' oRow.EndEdit()
' End If
' '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
' For Each oOpRow In oRow.GetChildRows("Rel1")
' 'need an option check price bit here
' Dim nNPrice As Decimal = getOptionPricesByXml(oRow("productDetail"), oRow("nItemOptGrpIdx"), oRow("nItemOptIdx"))
' If nNPrice > 0 And nNPrice <> oOpRow("price") Then
' nOpPrices += nNPrice
' oOpRow.BeginEdit()
' oOpRow("price") = nNPrice
' oOpRow.EndEdit()
' Else
' nOpPrices += oOpRow("price")
' End If
' Next
' 'oRow.BeginEdit()
' 'oRow("price") = nOpPrices
' 'oRow.EndEdit()
' '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
' End If
' ' Apply stock control
' If mbStockControl Then CheckStock(oCartElmt, oRow("productDetail"), oRow("quantity"))
' ' Apply quantity control
' CheckQuantities(oCartElmt, oRow("productDetail"), oRow("quantity"))
' weight = weight + (oRow("weight") * oRow("quantity"))
' quant = quant + oRow("quantity")
' If moCartConfig("DiscountDirection") = "up" Then
' total = total + (oRow("quantity") * (oRow("price") + nOpPrices)) + CDec("0" & oRow("discount"))
' Else
' total = total + (oRow("quantity") * (oRow("price") + nOpPrices)) - CDec("0" & oRow("discount"))
' End If
' 'Round( Price * Vat ) * Quantity
' nUnitVat += RoundUp(((oRow("price") + nOpPrices)) - CDec("0" & oRow("discount")) * (mnTaxRate / 100)) * oRow("quantity")
' 'Round( ( Price * Quantity )* VAT )
' nLineVat += RoundUp((((oRow("price") + nOpPrices) - CDec("0" & oRow("discount"))) * oRow("quantity")) * (mnTaxRate / 100))
' End If
' Dim cUpdtSQL As String = "UPDATE tblCartItem SET nPrice = " & oRow("price") & " WHERE nCartItemKey = " & oRow("id")
' moDBHelper.exeProcessSQLScalar(cUpdtSQL)
' Next
' ' Quantity based error messaging
' Dim oError As XmlElement = oCartElmt.SelectSingleNode("error")
' If Not (oError Is Nothing) Then
' Dim oMsg As XmlElement
' oMsg = oCartElmt.OwnerDocument.CreateElement("msg")
' oMsg.SetAttribute("type", "zz_footer") ' Forces it to the bottom of the message block
' oMsg.InnerText = "Please adjust the quantities you require, or call for assistance."
' oError.AppendChild(oMsg)
' End If
' 'moDBHelper.updateDataset(oDs, "Item", True)
' sSql = "select cClientNotes from tblCartOrder where nCartOrderKey=" & nCartIdUse
' Dim oNotes As XmlElement = oCartElmt.OwnerDocument.CreateElement("Notes")
' oNotes.InnerXml = moDBHelper.exeProcessSQLScalar(sSql)
' total -= moDiscount.CheckDiscounts(oDs, oCartElmt, False, oNotes)
' oCartElmt.SetAttribute("status", "Active")
' oCartElmt.SetAttribute("itemCount", quant)
' oCartElmt.SetAttribute("vatRate", moCartConfig("TaxRate"))
' oCartElmt.SetAttribute("total", total)
' oCartElmt.SetAttribute("weight", weight)
' oCartElmt.SetAttribute("orderType", mmcOrderType & "")
' 'Adding notes to cart summary
' sSql = "Select cClientNotes from tblCartOrder where nCartOrderKey = " & nCartIdUse
' cNotes = moDBHelper.DBN2Str(moDBHelper.exeProcessSQLScalar(sSql), False, False)
' sSql = "Select nCartStatus from tblCartOrder where nCartOrderKey = " & nCartIdUse
' If moDBHelper.DBN2Str(moDBHelper.exeProcessSQLScalar(sSql), False, False) = 6 Then
' oCartElmt.SetAttribute("complete", "true")
' Else
' oCartElmt.SetAttribute("complete", "true")
' End If
' Dim oElmt As XmlElement
' If Not (cNotes = "") Then
' oElmt = moPageXml.CreateElement("Notes")
' oElmt.InnerXml = cNotes
' oCartElmt.AppendChild(oElmt.FirstChild())
' End If
' End If
' Catch ex As Exception
' returnException(mcModuleName, "GetCartSummary", ex, "", cProcessInfo, gbDebug)
' End Try
'End Sub
'Public Sub GetCartSummary(ByRef oCartElmt As XmlElement, Optional ByVal nSelCartId As Integer = 0)
' 'made same as get cart
' PerfMon.Log("Cart", "GetCartSummary")
' ' Content for the XML that will display all the information stored for the Cart
' ' This is a list of cart items (and quantity, price ...), totals,
' ' billing & delivery addressi and delivery method.
' Dim oDs As DataSet
' Dim sSql As String
' Dim oRow As DataRow
' Dim oElmt As XmlElement
' Dim oElmt2 As XmlElement
' Dim oXml As XmlDataDocument
' Dim quant As Integer
' Dim weight As Double
' Dim total As Double
' Dim vatAmt As Double
' Dim shipCost As Double
' Dim nCheckPrice As Double
' 'We need to read this value from somewhere so we can change where vat is added
' 'Currently defaulted to per line
' 'If true will be added to the unit
' Dim nUnitVat As Decimal = 0
' Dim nLineVat As Decimal = 0
' Dim cProcessInfo As String = ""
' Dim cOptionGroupName As String = ""
' Dim nCartIdUse As Integer
' If nSelCartId > 0 Then nCartIdUse = nSelCartId Else nCartIdUse = mnCartId
' Try
' If Not moSubscription Is Nothing Then moSubscription.CheckCartForSubscriptions(nCartIdUse, myWeb.mnUserId)
' If Not (nCartIdUse > 0) Then ' no shopping
' oCartElmt.SetAttribute("status", "Empty") ' set CartXML attributes
' oCartElmt.SetAttribute("itemCount", "0") ' to nothing
' oCartElmt.SetAttribute("vatRate", moCartConfig("TaxRate"))
' oCartElmt.SetAttribute("total", "0.00") ' for nothing
' Else
' ' otherwise
' ' and the address details we have obtained
' ' (if any)
' 'Add Totals
' quant = 0 ' get number of items & sum of collective prices (ie. cart total) from db
' total = 0.0#
' weight = 0.0#
' sSql = "select i.nCartItemKey as id, i.nItemId as contentId, i.cItemRef as ref, i.cItemURL as url, i.cItemName as Name, i.cItemUnit as unit, i.nPrice as price, i.nTaxRate as taxRate, i.nQuantity as quantity, i.nShpCat as shippingLevel, i.nDiscountValue as discount,i.nWeight as weight, p.cContentXmlDetail as productDetail, i.nItemOptGrpIdx, i.nItemOptIdx, i.nParentId, p.cContentSchemaName AS contentType, dbo.fxn_getContentParents(i.nItemId) as parId from tblCartItem i left join tblContent p on i.nItemId = p.nContentKey where nCartOrderId=" & nCartIdUse
' oDs = moDBHelper.getDataSetForUpdate(sSql, "Item", "Cart")
' 'add relationship for options
' oDs.Relations.Add("Rel1", oDs.Tables("Item").Columns("id"), oDs.Tables("Item").Columns("nParentId"), False)
' oDs.Relations("Rel1").Nested = True
' '
' For Each oRow In oDs.Tables("Item").Rows
' If moDBHelper.DBN2int(oRow("nParentId")) = 0 Then
' ' Go get the lowest price based on user and group
' If Not IsDBNull(oRow("productDetail")) Then
' nCheckPrice = getProductPricesByXml(oRow("productDetail"), oRow("unit") & "", oRow("quantity"))
' If Not moSubscription Is Nothing And oRow("contentType") = "Subscription" Then nCheckPrice = moSubscription.CartSubscriptionPrice(oRow("contentId"), myWeb.mnUserId)
' End If
' If nCheckPrice > 0 And nCheckPrice <> oRow("price") Then
' ' If price is lower, then update the item price field
' 'oRow.BeginEdit()
' oRow("price") = nCheckPrice
' 'oRow.EndEdit()
' End If
' 'option prices
' Dim oOpRow As DataRow
' Dim nOpPrices As Decimal = 0
' For Each oOpRow In oRow.GetChildRows("Rel1")
' Dim nNPrice As Decimal = getOptionPricesByXml(oRow("productDetail"), oRow("nItemOptGrpIdx"), oRow("nItemOptIdx"))
' If nNPrice > 0 And nNPrice <> oOpRow("price") Then
' nOpPrices += nNPrice
' 'oOpRow.BeginEdit()
' oOpRow("price") = nNPrice
' 'oOpRow.EndEdit()
' Else
' nOpPrices += oOpRow("price")
' End If
' Next
' ' Apply stock control
' If mbStockControl Then CheckStock(oCartElmt, oRow("productDetail"), oRow("quantity"))
' ' Apply quantity control
' CheckQuantities(oCartElmt, oRow("productDetail"), oRow("quantity"))
' weight = weight + (oRow("weight") * oRow("quantity"))
' quant = quant + oRow("quantity")
' total = total + (oRow("quantity") * (oRow("price") + nOpPrices))
' 'Round( Price * Vat ) * Quantity
' ' nUnitVat += Round((oRow("price") + nOpPrices) * (mnTaxRate / 100), , , mbRoundup) * oRow("quantity")
' 'Round( ( Price * Quantity )* VAT )
' ' nLineVat += Round((((oRow("price") + nOpPrices)) * oRow("quantity")) * (mnTaxRate / 100), , , mbRoundup)
' End If
' 'Dim ix As Integer
' 'Dim xstr As String
' 'For ix = 0 To oRow.Table.Columns.Count - 1
' ' xstr &= oRow.Table.Columns(ix).ColumnName & "="
' ' xstr &= oRow(ix) & ", "
' 'Next
' Dim cUpdtSQL As String = "UPDATE tblCartItem SET nPrice = " & oRow("price") & " WHERE nCartItemKey = " & oRow("id")
' moDBHelper.exeProcessSQLScalar(cUpdtSQL)
' Next
' ' Quantity based error messaging
' Dim oError As XmlElement = oCartElmt.SelectSingleNode("error")
' If Not (oError Is Nothing) Then
' Dim oMsg As XmlElement
' oMsg = oCartElmt.OwnerDocument.CreateElement("msg")
' oMsg.SetAttribute("type", "zz_footer") ' Forces it to the bottom of the message block
' oMsg.InnerText = "Please adjust the quantities you require, or call for assistance."
' oError.AppendChild(oMsg)
' End If
' 'moDBHelper.updateDataset(oDs, "Item", True)
' ' add to Cart XML
' sSql = "Select nCartStatus from tblCartOrder where nCartOrderKey = " & mnCartId
' Dim nStatusId As Long = moDBHelper.DBN2Str(moDBHelper.exeProcessSQLScalar(sSql), False, False)
' oCartElmt.SetAttribute("statusId", nStatusId)
' oCartElmt.SetAttribute("status", Me.getProcessName(nStatusId))
' oCartElmt.SetAttribute("itemCount", quant)
' oCartElmt.SetAttribute("weight", weight)
' oCartElmt.SetAttribute("orderType", mmcOrderType & "")
' If nStatusId = 6 Then
' oCartElmt.SetAttribute("complete", "true")
' Else
' oCartElmt.SetAttribute("complete", "true")
' End If
' 'Add the addresses to the dataset
' If nCartIdUse > 0 Then
' sSql = "select cContactType as type, cContactName as GivenName, cContactCompany as Company, cContactAddress as Street, cContactCity as City, cContactState as State, cContactZip as PostalCode, cContactCountry as Country, cContactTel as Telephone, cContactFax as Fax, cContactEmail as Email, cContactXml as Details from tblCartContact where nContactCartId=" & nCartIdUse
' moDBHelper.addTableToDataSet(oDs, sSql, "Contact")
' End If
' 'Add Items - note - do this AFTER we've updated the prices!
' If oDs.Tables("Item").Rows.Count > 0 Then
' 'cart items
' oDs.Tables(0).Columns(0).ColumnMapping = Data.MappingType.Attribute
' oDs.Tables(0).Columns(1).ColumnMapping = Data.MappingType.Attribute
' oDs.Tables(0).Columns(2).ColumnMapping = Data.MappingType.Attribute
' oDs.Tables(0).Columns(3).ColumnMapping = Data.MappingType.Attribute
' oDs.Tables(0).Columns(5).ColumnMapping = Data.MappingType.Attribute
' oDs.Tables(0).Columns(6).ColumnMapping = Data.MappingType.Attribute
' oDs.Tables(0).Columns(7).ColumnMapping = Data.MappingType.Attribute
' oDs.Tables(0).Columns(8).ColumnMapping = Data.MappingType.Attribute
' oDs.Tables(0).Columns(9).ColumnMapping = Data.MappingType.Attribute
' oDs.Tables(0).Columns(10).ColumnMapping = Data.MappingType.Attribute
' oDs.Tables(0).Columns(11).ColumnMapping = Data.MappingType.Attribute
' oDs.Tables(0).Columns("parId").ColumnMapping = Data.MappingType.Attribute
' 'cart contacts
' oDs.Tables("Contact").Columns(0).ColumnMapping = Data.MappingType.Attribute
' oXml = New XmlDataDocument(oDs)
' oDs.EnforceConstraints = False
' 'Convert the detail to xml
' For Each oElmt In oXml.SelectNodes("/Cart/Item/productDetail | /Cart/Contact/Detail | /Cart/Contact/Details")
' oElmt.InnerXml = oElmt.InnerText
' If Not oElmt.SelectSingleNode("Content") Is Nothing Then
' oElmt.InnerXml = oElmt.SelectSingleNode("Content").InnerXml
' End If
' Next
' 'get the option xml
' For Each oElmt In oXml.SelectNodes("/Cart/Item/Item/productDetail")
' oElmt.InnerXml = oElmt.InnerText
' Dim nGroupIndex As String = oElmt.ParentNode.SelectSingleNode("nItemOptGrpIdx").InnerText
' Dim nOptionIndex As String = oElmt.ParentNode.SelectSingleNode("nItemOptIdx").InnerText
' cOptionGroupName = ""
' If Not oElmt.SelectSingleNode("Content/Options/OptGroup[" & nGroupIndex & "]/@name") Is Nothing Then
' cOptionGroupName = oElmt.SelectSingleNode("Content/Options/OptGroup[" & nGroupIndex & "]/@name").InnerText
' End If
' If nOptionIndex >= 0 Then
' oElmt2 = oElmt.SelectSingleNode("Content/Options/OptGroup[" & nGroupIndex & "]/option[" & nOptionIndex & "]")
' If cOptionGroupName <> "" Then oElmt2.SetAttribute("groupName", cOptionGroupName)
' oElmt.ParentNode.InnerXml = oElmt2.OuterXml
' Else
' 'case for text option
' oElmt2 = oElmt.SelectSingleNode("Content/Options/OptGroup[" & nGroupIndex & "]/option[1]")
' If cOptionGroupName <> "" Then oElmt2.SetAttribute("groupName", cOptionGroupName)
' oElmt2.SetAttribute("name", oElmt.ParentNode.SelectSingleNode("Name").InnerText)
' oElmt.ParentNode.InnerXml = oElmt2.OuterXml
' End If
' Next
' oElmt = moPageXml.CreateElement("Cart")
' ' Note: Preserve the original elements in oCartElmt
' 'oCartElmt.InnerXml = oCartElmt.InnerXml + oXml.FirstChild.InnerXml
' End If
' myWeb.CheckMultiParents(oCartElmt)
' sSql = "select cClientNotes from tblCartOrder where nCartOrderKey=" & nCartIdUse
' Dim oNotes As XmlElement = oCartElmt.OwnerDocument.CreateElement("Notes")
' oNotes.InnerXml = moDBHelper.exeProcessSQLScalar(sSql)
' total -= moDiscount.CheckDiscounts(oDs, oCartElmt, True, oNotes)
' oXml = Nothing
' oDs = Nothing
' If mbNoDeliveryAddress Then oCartElmt.SetAttribute("hideDeliveryAddress", "true")
' If mnGiftListId > 0 Then oCartElmt.SetAttribute("giftListId", mnGiftListId)
' sSql = "select * from tblCartOrder where nCartOrderKey=" & nCartIdUse
' oDs = moDBHelper.getDataSet(sSql, "Order", "Cart")
' For Each oRow In oDs.Tables("Order").Rows
' shipCost = CDbl("0" & oRow("nShippingCost"))
' oCartElmt.SetAttribute("shippingType", oRow("nShippingMethodId") & "")
' oCartElmt.SetAttribute("shippingCost", shipCost & "")
' oCartElmt.SetAttribute("shippingDesc", oRow("cShippingDesc") & "")
' If oRow("nShippingMethodId") > 0 Then
' getShippingDetailXml(oCartElmt, oRow("nShippingMethodId"))
' End If
' If mnTaxRate > 0 Then
' 'we calculate vat at the end after we have applied discounts etc
' For Each oElmt In oXml.SelectNodes("/Cart/Item")
' Dim nOpPrices As Long = 0
' 'get the prices of options to calculate vat
' For Each oElmt2 In oXml.SelectNodes("/Item")
' nOpPrices += oElmt2.GetAttribute("price")
' Next
' If mbVatAtUnit Then
' 'Round( Price * Vat ) * Quantity
' nLineVat = Round((oElmt.GetAttribute("price") + nOpPrices) * (mnTaxRate / 100), , , mbRoundup) * oElmt.GetAttribute("quantity"))
' Else
' 'Round( ( Price * Quantity )* VAT )
' nLineVat = Round((((oRow("price") + nOpPrices)) * oRow("quantity")) * (mnTaxRate / 100), , , mbRoundup)
' End If
' ' oElmt.SetAttribute("itemTax", nLineVat)
' vatAmt += nLineVat
' Next
' vatAmt = Round((shipCost) * (mnTaxRate / 100), , , mbRoundup) + vatAmt
' oCartElmt.SetAttribute("totalNet", FormatNumber(total + shipCost, 2, TriState.True, TriState.False, TriState.False))
' oCartElmt.SetAttribute("vatRate", mnTaxRate)
' oCartElmt.SetAttribute("shippingType", oRow("nShippingMethodId") & "")
' oCartElmt.SetAttribute("shippingCost", FormatNumber(shipCost, 2, TriState.True, TriState.False, TriState.False))
' oCartElmt.SetAttribute("vatAmt", FormatNumber(vatAmt, 2, TriState.True, TriState.False, TriState.False))
' oCartElmt.SetAttribute("total", FormatNumber(total + shipCost + vatAmt, 2, TriState.True, TriState.False, TriState.False))
' Else
' oCartElmt.SetAttribute("totalNet", FormatNumber(total + shipCost, 2, TriState.True, TriState.False, TriState.False))
' oCartElmt.SetAttribute("vatRate", 0.0#)
' oCartElmt.SetAttribute("shippingType", oRow("nShippingMethodId") & "")
' oCartElmt.SetAttribute("shippingCost", FormatNumber(shipCost, 2, TriState.True, TriState.False, TriState.False))
' oCartElmt.SetAttribute("vatAmt", 0.0#)
' oCartElmt.SetAttribute("total", FormatNumber(total + shipCost, 2, TriState.True, TriState.False, TriState.False))
' End If
' Next
' End If
' Catch ex As Exception
' returnException(mcModuleName, "GetCartSummary", ex, "", cProcessInfo, gbDebug)
' End Try
'End Sub
''' <summary>
''' This does the same as get cart without the item information, so we call get cart and delete any items we find
''' </summary>
''' <param name="oCartElmt"></param>
''' <param name="nSelCartId"></param>
''' <remarks></remarks>
Sub GetCartSummary(ByRef oCartElmt As XmlElement, Optional ByVal nSelCartId As Integer = 0)
PerfMon.Log("Cart", "GetCartSummary")
' Sets content for the XML to be displayed in the small summary plugin attached
' to the current content page
Dim oElmt As XmlElement
Dim nCartIdUse As Integer
If nSelCartId > 0 Then
nCartIdUse = nSelCartId
Else
nCartIdUse = mnCartId
End If
Dim cProcessInfo As String = "CartId=" & nCartIdUse
Try
GetCart(oCartElmt, nCartIdUse)
'remove all the items
For Each oElmt In oCartElmt.SelectNodes("/Cart/Order/Item")
oElmt.ParentNode.RemoveChild(oElmt)
Next
Catch ex As Exception
returnException(mcModuleName, "GetCartSummary", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Sub GetCart()
GetCart(moCartXml.FirstChild)
End Sub
Public Sub GetCart(ByRef oCartElmt As XmlElement, Optional ByVal nSelCartId As Integer = 0)
oCartElmt.InnerXml = ""
PerfMon.Log("Cart", "GetCart")
' Content for the XML that will display all the information stored for the Cart
' This is a list of cart items (and quantity, price ...), totals,
' billing & delivery addressi and delivery method.
Dim oDs As DataSet
Dim oDs2 As DataSet
Dim sSql As String
Dim oRow As DataRow
Dim oRow2 As DataRow
Dim oElmt As XmlElement
Dim oElmt2 As XmlElement
Dim oXml As XmlDocument
Dim quant As Long
Dim weight As Double
Dim total As Double
Dim vatAmt As Double
Dim shipCost As Double
Dim nCheckPrice As Double
Dim oCheckPrice As XmlElement
'We need to read this value from somewhere so we can change where vat is added
'Currently defaulted to per line
'If true will be added to the unit
Dim nLineVat As Decimal = 0
Dim bCheckSubscriptions = False
Dim cOptionGroupName As String = ""
Dim nCartIdUse As Integer
If nSelCartId > 0 Then
nCartIdUse = nSelCartId
Else
nCartIdUse = mnCartId
End If
Dim oldCartId As Long = mnCartId
Dim cProcessInfo As String = "CartId=" & nCartIdUse
'For related products
Dim oItemList As New Hashtable ' for related Products
If moCartConfig("RelatedProductsInCart") = "on" Then
End If
Try
If Not moSubscription Is Nothing And nCartIdUse <> 0 Then
bCheckSubscriptions = moSubscription.CheckCartForSubscriptions(nCartIdUse, myWeb.mnUserId)
If moCartConfig("subCheck") = "always" Then
bCheckSubscriptions = True
End If
End If
If Not (nCartIdUse > 0) Then ' no shopping
oCartElmt.SetAttribute("status", "Empty") ' set CartXML attributes
oCartElmt.SetAttribute("itemCount", "0") ' to nothing
oCartElmt.SetAttribute("vatRate", moCartConfig("TaxRate"))
oCartElmt.SetAttribute("total", "0.00") ' for nothing
Else
' otherwise
oCartElmt.SetAttribute("cartId", mnCartId)
oCartElmt.SetAttribute("session", mcSessionId)
' Check tax rate
UpdateTaxRate()
' and the address details we have obtained
' (if any)
'Add Totals
quant = 0 ' get number of items & sum of collective prices (ie. cart total) from db
total = 0.0#
weight = 0.0#
' Process promo code from external refs.
If myWeb.moSession("promocode") <> "" Or myWeb.moRequest("promocode") <> "" Then
If myWeb.moRequest("promocode") <> "" Then
promocodeFromExternalRef = myWeb.moRequest("promocode").ToString
ElseIf myWeb.moSession("promocode") <> "" Then
promocodeFromExternalRef = myWeb.moSession("promocode").ToString
End If
myWeb.moSession("promocode") = ""
End If
If Not String.IsNullOrEmpty(promocodeFromExternalRef) Then
oCartElmt.SetAttribute("promocodeFromExternalRef", promocodeFromExternalRef)
End If
If moDBHelper.checkTableColumnExists("tblCartItem", "xItemXml") Then
sSql = "select i.nCartItemKey as id, i.nItemId as contentId, i.cItemRef as ref, i.cItemURL as url, i.cItemName as Name, i.cItemUnit as unit, i.nPrice as price, i.nTaxRate as taxRate, i.nQuantity as quantity, i.nShpCat as shippingLevel, i.nDiscountValue as discount,i.nWeight as weight, i.xItemXml as productDetail, i.nItemOptGrpIdx, i.nItemOptIdx, i.nParentId, i.xItemXml.value('Content[1]/@type','nvarchar(50)') AS contentType, dbo.fxn_getContentParents(i.nItemId) as parId from tblCartItem i left join tblContent p on i.nItemId = p.nContentKey where nCartOrderId=" & nCartIdUse
Else
sSql = "select i.nCartItemKey as id, i.nItemId as contentId, i.cItemRef as ref, i.cItemURL as url, i.cItemName as Name, i.cItemUnit as unit, i.nPrice as price, i.nTaxRate as taxRate, i.nQuantity as quantity, i.nShpCat as shippingLevel, i.nDiscountValue as discount,i.nWeight as weight, p.cContentXmlDetail as productDetail, i.nItemOptGrpIdx, i.nItemOptIdx, i.nParentId, p.cContentSchemaName AS contentType, dbo.fxn_getContentParents(i.nItemId) as parId from tblCartItem i left join tblContent p on i.nItemId = p.nContentKey where nCartOrderId=" & nCartIdUse
End If
oDs = moDBHelper.getDataSetForUpdate(sSql, "Item", "Cart")
'add relationship for options
oDs.Relations.Add("Rel1", oDs.Tables("Item").Columns("id"), oDs.Tables("Item").Columns("nParentId"), False)
oDs.Relations("Rel1").Nested = True
'
For Each oRow In oDs.Tables("Item").Rows
Dim Discount As Double = 0
If Not oItemList.ContainsValue(oRow("contentId")) Then
oItemList.Add(oItemList.Count, oRow("contentId"))
End If
If moDBHelper.DBN2int(oRow("nParentId")) = 0 Then
Dim nTaxRate As Long = 0
Dim bOverridePrice As Boolean = False
If Not mbOveridePrice Then ' for openquote
' Go get the lowest price based on user and group
If Not IsDBNull(oRow("productDetail")) Then
Dim oProd As XmlElement = moPageXml.CreateElement("product")
oProd.InnerXml = oRow("productDetail")
If oProd.SelectSingleNode("Content[@overridePrice='True']") Is Nothing Then
oCheckPrice = getContentPricesNode(oProd, oRow("unit") & "", oRow("quantity"))
cProcessInfo = "Error getting price for unit:" & oRow("unit") & " and Quantity:" & oRow("quantity") & " and Currency " & mcCurrencyRef & " Check that a price is available for this quantity and a group for this current user."
If Not oCheckPrice Is Nothing Then
nCheckPrice = oCheckPrice.InnerText
nTaxRate = getProductTaxRate(oCheckPrice)
End If
'nCheckPrice = getProductPricesByXml(oRow("productDetail"), oRow("unit") & "", oRow("quantity"))
If Not moSubscription Is Nothing And CStr(oRow("contentType") & "") = "Subscription" Then
Dim revisedPrice As Double
If oRow("contentId") > 0 Then
revisedPrice = moSubscription.CartSubscriptionPrice(oRow("contentId"), myWeb.mnUserId)
Else
oCheckPrice = getContentPricesNode(oProd, oRow("unit") & "", oRow("quantity"), "SubscriptionPrices")
nCheckPrice = oCheckPrice.InnerText
nTaxRate = getProductTaxRate(oCheckPrice)
End If
If revisedPrice < nCheckPrice Then
'nCheckPrice = revisedPrice
Discount = nCheckPrice - revisedPrice
nCheckPrice = revisedPrice
End If
End If
Else
bOverridePrice = True
End If
End If
If Not bOverridePrice Then
If nCheckPrice > 0 And nCheckPrice <> oRow("price") Then
' If price is lower, then update the item price field
'oRow.BeginEdit()
oRow("price") = nCheckPrice
'oRow("taxRate") = nTaxRate
'oRow.EndEdit()
End If
If oRow("taxRate") <> nTaxRate Then
oRow("taxRate") = nTaxRate
End If
End If
End If
'option prices
Dim oOpRow As DataRow
Dim nOpPrices As Decimal = 0
For Each oOpRow In oRow.GetChildRows("Rel1")
If Not mbOveridePrice Then ' for openquote
Dim nNPrice As Decimal = getOptionPricesByXml(oRow("productDetail"), oRow("nItemOptGrpIdx"), oRow("nItemOptIdx"))
If nNPrice > 0 And nNPrice <> oOpRow("price") Then
nOpPrices += nNPrice
'oOpRow.BeginEdit()
oOpRow("price") = nNPrice
'oOpRow.EndEdit()
Else
nOpPrices += oOpRow("price")
End If
End If
Next
' Apply stock control
If mbStockControl Then CheckStock(oCartElmt, oRow("productDetail"), oRow("quantity"))
' Apply quantity control
If Not IsDBNull(oRow("productDetail")) Then
'not sure why the product has no detail but if it not we skip this, suspect it was old test data that raised this issue.
CheckQuantities(oCartElmt, oRow("productDetail") & "", CLng(oRow("quantity")))
End If
weight = weight + (oRow("weight") * oRow("quantity"))
quant = quant + oRow("quantity")
total = total + (oRow("quantity") * Round(oRow("price") + nOpPrices, , , mbRoundup))
'we do this later after we have applied discounts
'Round( Price * Vat ) * Quantity
' nUnitVat += Round((oRow("price") + nOpPrices) * (mnTaxRate / 100), , , mbRoundup) * oRow("quantity")
'Round( ( Price * Quantity )* VAT )
' nLineVat += Round((((oRow("price") + nOpPrices)) * oRow("quantity")) * (mnTaxRate / 100), , , mbRoundup)
End If
'Dim ix As Integer
'Dim xstr As String
'For ix = 0 To oRow.Table.Columns.Count - 1
' xstr &= oRow.Table.Columns(ix).ColumnName & "="
' xstr &= oRow(ix) & ", "
'Next
Dim discountSQL As String = ""
If Discount <> 0 Then
' discountSQL = ", nDiscountValue = " & Discount & " "
End If
Dim cUpdtSQL As String = "UPDATE tblCartItem Set nPrice = " & oRow("price") & discountSQL & " WHERE nCartItemKey = " & oRow("id")
moDBHelper.ExeProcessSqlScalar(cUpdtSQL)
Next
' Quantity based error messaging
Dim oError As XmlElement = oCartElmt.SelectSingleNode("Error")
If Not (oError Is Nothing) Then
Dim oMsg As XmlElement
oMsg = oCartElmt.OwnerDocument.CreateElement("msg")
oMsg.SetAttribute("type", "zz_footer") ' Forces it to the bottom of the message block
oMsg.InnerText = "<span Class=""term3081"">Please adjust the quantities you require, Or Call For assistance.</span>"
oError.AppendChild(oMsg)
End If
'moDBHelper.updateDataset(oDs, "Item", True)
' add to Cart XML
sSql = "Select nCartStatus from tblCartOrder where nCartOrderKey = " & nCartIdUse
Dim nStatusId As Long = moDBHelper.DBN2Str(moDBHelper.ExeProcessSqlScalar(sSql), False, False)
oCartElmt.SetAttribute("statusId", nStatusId)
oCartElmt.SetAttribute("status", Me.getProcessName(nStatusId))
oCartElmt.SetAttribute("itemCount", quant)
oCartElmt.SetAttribute("weight", weight)
oCartElmt.SetAttribute("orderType", mmcOrderType & "")
If nStatusId = 6 Then
oCartElmt.SetAttribute("complete", "True")
Else
oCartElmt.SetAttribute("complete", "True")
End If
'Add the addresses to the dataset
If nCartIdUse > 0 Then
sSql = "Select cContactType As type, cContactName As GivenName, cContactCompany As Company, cContactAddress As Street, cContactCity As City, cContactState As State, cContactZip As PostalCode, cContactCountry As Country, cContactTel As Telephone, cContactFax As Fax, cContactEmail As Email, cContactXml As Details from tblCartContact where nContactCartId=" & nCartIdUse
moDBHelper.addTableToDataSet(oDs, sSql, "Contact")
End If
'Add Items - note - do this AFTER we've updated the prices!
If oDs.Tables("Item").Rows.Count > 0 Then
'cart items
oDs.Tables(0).Columns(0).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(1).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(2).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(3).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(5).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(6).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(7).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(8).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(9).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(10).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(11).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns("parId").ColumnMapping = Data.MappingType.Attribute
'cart contacts
oDs.Tables("Contact").Columns(0).ColumnMapping = Data.MappingType.Attribute
oXml = New XmlDocument
oXml.LoadXml(oDs.GetXml)
oDs.EnforceConstraints = False
'Convert the detail to xml
For Each oElmt In oXml.SelectNodes("/Cart/Item/productDetail | /Cart/Contact/Detail | /Cart/Contact/Details")
oElmt.InnerXml = oElmt.InnerText
If Not oElmt.SelectSingleNode("Content") Is Nothing Then
Dim oAtt As XmlAttribute
For Each oAtt In oElmt.SelectSingleNode("Content").Attributes
oElmt.SetAttribute(oAtt.Name, oAtt.Value)
Next
oElmt.InnerXml = oElmt.SelectSingleNode("Content").InnerXml
End If
Next
For Each oElmt In oXml.SelectNodes("/Cart/Contact/Email")
If moDBHelper.CheckOptOut(oElmt.InnerText) Then
oElmt.SetAttribute("optOut", "True")
End If
Next
'get the option xml
For Each oElmt In oXml.SelectNodes("/Cart/Item/Item/productDetail")
oElmt.InnerXml = oElmt.InnerText
Dim nGroupIndex As String = oElmt.ParentNode.SelectSingleNode("nItemOptGrpIdx").InnerText
Dim nOptionIndex As String = oElmt.ParentNode.SelectSingleNode("nItemOptIdx").InnerText
cOptionGroupName = ""
If Not oElmt.SelectSingleNode("Content/Options/OptGroup[" & nGroupIndex & "]/@name") Is Nothing Then
cOptionGroupName = oElmt.SelectSingleNode("Content/Options/OptGroup[" & nGroupIndex & "]/@name").InnerText
End If
If nOptionIndex >= 0 Then
oElmt2 = oElmt.SelectSingleNode("Content/Options/OptGroup[" & nGroupIndex & "]/Option[" & nOptionIndex & "]")
If Not oElmt2 Is Nothing Then
If cOptionGroupName <> "" Then oElmt2.SetAttribute("groupName", cOptionGroupName)
oElmt.ParentNode.InnerXml = oElmt2.OuterXml
End If
Else
'case for text option
oElmt2 = oElmt.SelectSingleNode("Content/Options/OptGroup[" & nGroupIndex & "]/Option[1]")
If Not oElmt2 Is Nothing Then
If cOptionGroupName <> "" Then oElmt2.SetAttribute("groupName", cOptionGroupName)
If Not oElmt.ParentNode.SelectSingleNode("Name") Is Nothing Then
oElmt2.SetAttribute("name", oElmt.ParentNode.SelectSingleNode("Name").InnerText)
Else
oElmt2.SetAttribute("name", "Name Not defined")
End If
oElmt.ParentNode.InnerXml = oElmt2.OuterXml
End If
End If
Next
oElmt = moPageXml.CreateElement("Cart")
' Note: Preserve the original elements in oCartElmt
oCartElmt.InnerXml = oCartElmt.InnerXml + oXml.FirstChild.InnerXml
End If
myWeb.CheckMultiParents(oCartElmt)
sSql = "Select cClientNotes from tblCartOrder where nCartOrderKey=" & nCartIdUse
Dim oNotes As XmlElement = oCartElmt.OwnerDocument.CreateElement("Notes")
Dim notes As String = CStr("" & moDBHelper.ExeProcessSqlScalar(sSql))
oNotes.InnerXml = notes
total -= moDiscount.CheckDiscounts(oDs, oCartElmt, True, oNotes)
oXml = Nothing
oDs = Nothing
If mbNoDeliveryAddress Then oCartElmt.SetAttribute("hideDeliveryAddress", "True")
If mnGiftListId > 0 Then oCartElmt.SetAttribute("giftListId", mnGiftListId)
sSql = "Select * from tblCartOrder where nCartOrderKey=" & nCartIdUse
oDs = moDBHelper.GetDataSet(sSql, "Order", "Cart")
For Each oRow In oDs.Tables("Order").Rows
shipCost = CDbl("0" & oRow("nShippingCost"))
oCartElmt.SetAttribute("shippingType", oRow("nShippingMethodId") & "")
oCartElmt.SetAttribute("shippingCost", shipCost & "")
oCartElmt.SetAttribute("shippingDesc", oRow("cShippingDesc") & "")
If oRow("nShippingMethodId") = 0 And oRow("nCartStatus") < 4 Then
shipCost = -1
'Default Shipping Country.
Dim cDestinationCountry As String = moCartConfig("DefaultCountry")
If cDestinationCountry <> "" Then
'Go and collect the valid shipping options available for this order
Dim oDsShipOptions As DataSet = getValidShippingOptionsDS(cDestinationCountry, total, quant, weight)
Dim oRowSO As DataRow
For Each oRowSO In oDsShipOptions.Tables(0).Rows
Dim bCollection As Boolean = False
If Not IsDBNull(oRowSO("bCollection")) Then
bCollection = oRowSO("bCollection")
End If
If (shipCost = -1 Or CDbl("0" & oRowSO("nShipOptCost")) < shipCost) And bCollection = False Then
shipCost = CDbl("0" & oRowSO("nShipOptCost"))
oCartElmt.SetAttribute("shippingDefaultDestination", moCartConfig("DefaultCountry"))
oCartElmt.SetAttribute("shippingType", oRowSO("nShipOptKey") & "")
oCartElmt.SetAttribute("shippingCost", shipCost & "")
oCartElmt.SetAttribute("shippingDesc", oRowSO("cShipOptName") & "")
oCartElmt.SetAttribute("shippingCarrier", oRowSO("cShipOptCarrier") & "")
End If
Next
End If
If shipCost = -1 Then shipCost = 0
End If
If oCartElmt.GetAttribute("shippingType") > 0 Then
getShippingDetailXml(oCartElmt, oCartElmt.GetAttribute("shippingType"))
End If
vatAmt = updateTotals(oCartElmt, total, shipCost, oCartElmt.GetAttribute("shippingType"))
' Check if the cart needs to be adjusted for deposits or settlements
If mcDeposit = "On" Then
Dim nTotalAmount As Double = total + shipCost + vatAmt
Dim nPayable As Double = 0.0#
' First check if an inital deposit has been paid
' We are still in a payment type of deposit if:
' 1. No amount has been received
' OR 2. An amount has been received but the cart is still in a status of 10
If IsDBNull(oRow("nAmountReceived")) Then
' No deposit has been paid yet - let's set the deposit value, if it has been specified
If mcDepositAmount <> "" Then
If Right(mcDepositAmount, 1) = "%" Then
If IsNumeric(Left(mcDepositAmount, Len(mcDepositAmount) - 1)) Then
nPayable = (nTotalAmount) * CDbl(Left(mcDepositAmount, Len(mcDepositAmount) - 1)) / 100
End If
Else
If IsNumeric(mcDepositAmount) Then nPayable = CDbl(mcDepositAmount)
End If
If nPayable > nTotalAmount Then nPayable = nTotalAmount
' Set the Payable Amount
If nPayable > 0 Then
oCartElmt.SetAttribute("payableAmount", FormatNumber(nPayable, 2, Microsoft.VisualBasic.TriState.True, Microsoft.VisualBasic.TriState.False, Microsoft.VisualBasic.TriState.False))
oCartElmt.SetAttribute("paymentMade", "0")
End If
End If
Else
' A deposit has been paid - should I check if it's the same as the total amount?
If IsNumeric(oRow("nAmountReceived")) Then
nPayable = nTotalAmount - CDbl(oRow("nAmountReceived"))
If nPayable > 0 Then
oCartElmt.SetAttribute("payableAmount", FormatNumber(nPayable, 2, Microsoft.VisualBasic.TriState.True, Microsoft.VisualBasic.TriState.False, Microsoft.VisualBasic.TriState.False))
End If
oCartElmt.SetAttribute("paymentMade", FormatNumber(CDbl(oRow("nLastPaymentMade")), 2, Microsoft.VisualBasic.TriState.True, Microsoft.VisualBasic.TriState.False, Microsoft.VisualBasic.TriState.False))
End If
End If
' Set the payableType
If IsDBNull(oRow("nAmountReceived")) Or nStatusId = 10 Then
oCartElmt.SetAttribute("payableType", "deposit")
Else
oCartElmt.SetAttribute("payableType", "settlement")
End If
If nPayable = 0 Then
oCartElmt.SetAttribute("ReadOnly", "On")
End If
End If
'Add Any Client Notes
If Not (IsDBNull(oRow("cClientNotes")) Or oRow("cClientNotes") & "" = "") Then
oElmt = moPageXml.CreateElement("Notes")
oElmt.InnerXml = oRow("cClientNotes")
If oElmt.FirstChild.Name = "Notes" Then
oCartElmt.AppendChild(oElmt.SelectSingleNode("Notes"))
Else
oCartElmt.AppendChild(oElmt)
End If
End If
'Add the payment details if we have them
If oRow("nPayMthdId") > 0 Then
sSql = "Select * from tblCartPaymentMethod where nPayMthdKey=" & oRow("nPayMthdId")
oDs2 = moDBHelper.GetDataSet(sSql, "Payment", "Cart")
oElmt = moPageXml.CreateElement("PaymentDetails")
For Each oRow2 In oDs2.Tables("Payment").Rows
oElmt.InnerXml = oRow2("cPayMthdDetailXml")
oElmt.SetAttribute("provider", oRow2("cPayMthdProviderName"))
oElmt.SetAttribute("ref", oRow2("cPayMthdProviderRef"))
oElmt.SetAttribute("acct", oRow2("cPayMthdAcctName"))
Next
oCartElmt.AppendChild(oElmt)
End If
'Add Delivery Details
If nStatusId = 9 Then
sSql = "Select * from tblCartOrderDelivery where nOrderId=" & nCartIdUse
oDs2 = moDBHelper.GetDataSet(sSql, "Delivery", "Details")
For Each oRow2 In oDs2.Tables("Delivery").Rows
oElmt = moPageXml.CreateElement("DeliveryDetails")
oElmt.SetAttribute("carrierName", oRow2("cCarrierName"))
oElmt.SetAttribute("ref", oRow2("cCarrierRef"))
oElmt.SetAttribute("notes", oRow2("cCarrierNotes"))
oElmt.SetAttribute("deliveryDate", xmlDate(oRow2("dExpectedDeliveryDate")))
oElmt.SetAttribute("collectionDate", xmlDate(oRow2("dCollectionDate")))
oCartElmt.AppendChild(oElmt)
Next
oldCartId = nCartIdUse
End If
Next
End If
' Check for any process reported errors
If Not IsDBNull(mnProcessError) Then oCartElmt.SetAttribute("errorMsg", mnProcessError)
'Save the data
If bCheckSubscriptions Then
moSubscription.UpdateSubscriptionsTotals(oCartElmt)
End If
mnCartId = oldCartId
SaveCartXML(oCartElmt)
'mnCartId = nCartIdUse
If moCartConfig("RelatedProductsInCart") = "On" Then
Dim oRelatedElmt As XmlElement = oCartElmt.OwnerDocument.CreateElement("RelatedItems")
For i As Integer = 0 To oItemList.Count - 1
myWeb.moDbHelper.addRelatedContent(oRelatedElmt, oItemList(i), False)
Next
For Each oRelElmt As XmlElement In oRelatedElmt.SelectNodes("Content")
If oItemList.ContainsValue(oRelElmt.GetAttribute("id")) Then
oRelElmt.ParentNode.RemoveChild(oRelElmt)
End If
Next
If Not oRelatedElmt.InnerXml = "" Then oCartElmt.AppendChild(oRelatedElmt)
End If
Catch ex As Exception
returnException(mcModuleName, "GetCart", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Function updateTotals(ByRef oCartElmt As XmlElement, ByVal total As Double, ByVal shipCost As Double, ByVal ShipMethodId As String) As Double
Dim cProcessInfo As String = ""
Dim oElmt As XmlElement
Dim oElmt2 As XmlElement
Dim vatAmt As Double = 0
Dim nLineVat As Double
Try
If mnTaxRate > 0 Then
'we calculate vat at the end after we have applied discounts etc
For Each oElmt In oCartElmt.SelectNodes("/Order/Item")
Dim nOpPrices As Long = 0
'get the prices of options to calculate vat
' AG - I think this is a mistake: For Each oElmt2 In oCartElmt.SelectNodes("/Item")
For Each oElmt2 In oElmt.SelectNodes("Item")
nOpPrices += oElmt2.GetAttribute("price")
Next
Dim nItemDiscount As Double = 0
Dim nLineTaxRate As Double = mnTaxRate
If mbVatOnLine Then
nLineTaxRate = oElmt.GetAttribute("taxRate")
End If
'NB 14th Jan 2010 This doesn't work
' It generates a figure that matches oElement.GetAttribute("price") so vat is always 0
' even if one of the items is being paid for
' to test, 1 high qualifyer, 2 low (so only 1 free)
If Not oElmt.SelectSingleNode("DiscountItem[@nDiscountCat='4']") Is Nothing Then
Dim oDiscItem As XmlElement = oElmt.SelectSingleNode("DiscountItem")
If Not oElmt.SelectSingleNode("Discount[@nDiscountCat='4' and @bDiscountIsPercent='1' and number(@nDiscountValue)=100]") Is Nothing Then
'checks for a 100% off discount
nLineVat = Round((oElmt.GetAttribute("price") - nItemDiscount + nOpPrices) * (nLineTaxRate / 100), , , mbRoundup) * oDiscItem.GetAttribute("Units")
Else
'nLineVat = Round((oElmt.GetAttribute("price") - nItemDiscount + nOpPrices) * (mnTaxRate / 100), , , mbRoundup) * oDiscItem.GetAttribute("Units")
nLineVat = Round((oDiscItem.GetAttribute("Total")) * (nLineTaxRate / 100), , , mbRoundup)
'nLineVat = 5000
End If
'
'NB 15th Jan: What is this use of this line? It's logic makes one of the multipliers 0 thus destroying VAT?
'Replaced with basic unit VAT change, charge per unit but reduce number of units to only those being paid for
'nItemDiscount = oDiscItem.GetAttribute("TotalSaving") / (oDiscItem.GetAttribute("Units") - oDiscItem.GetAttribute("oldUnits")) * -1
Else
'NB: 15-01-2010 Moved into Else so Buy X Get Y Free do not use this, as they can get 0
If mbVatAtUnit Then
'Round( Price * Vat ) * Quantity
nLineVat = Round((oElmt.GetAttribute("price") - nItemDiscount + nOpPrices) * (nLineTaxRate / 100), , , mbRoundup) * oElmt.GetAttribute("quantity")
Else
'Round( ( Price * Quantity )* VAT )
nLineVat = Round((((oElmt.GetAttribute("price") - nItemDiscount + nOpPrices)) * oElmt.GetAttribute("quantity")) * (nLineTaxRate / 100), , , mbRoundup)
End If
End If
oElmt.SetAttribute("itemTax", nLineVat)
vatAmt += nLineVat
Next
If Not LCase(moCartConfig("DontTaxShipping")) = "on" Then
vatAmt = Round((shipCost) * (mnTaxRate / 100), , , mbRoundup) + Round(vatAmt, , , mbRoundup)
End If
oCartElmt.SetAttribute("totalNet", FormatNumber(total + shipCost, 2, Microsoft.VisualBasic.TriState.True, Microsoft.VisualBasic.TriState.False, Microsoft.VisualBasic.TriState.False))
oCartElmt.SetAttribute("vatRate", mnTaxRate)
oCartElmt.SetAttribute("shippingType", ShipMethodId & "")
oCartElmt.SetAttribute("shippingCost", FormatNumber(shipCost, 2, Microsoft.VisualBasic.TriState.True, Microsoft.VisualBasic.TriState.False, Microsoft.VisualBasic.TriState.False))
oCartElmt.SetAttribute("vatAmt", FormatNumber(vatAmt, 2, Microsoft.VisualBasic.TriState.True, Microsoft.VisualBasic.TriState.False, Microsoft.VisualBasic.TriState.False))
oCartElmt.SetAttribute("total", FormatNumber(total + shipCost + vatAmt, 2, Microsoft.VisualBasic.TriState.True, Microsoft.VisualBasic.TriState.False, Microsoft.VisualBasic.TriState.False))
Else
oCartElmt.SetAttribute("totalNet", FormatNumber(total + shipCost, 2, Microsoft.VisualBasic.TriState.True, Microsoft.VisualBasic.TriState.False, Microsoft.VisualBasic.TriState.False))
oCartElmt.SetAttribute("vatRate", 0.0#)
oCartElmt.SetAttribute("shippingType", ShipMethodId & "")
oCartElmt.SetAttribute("shippingCost", FormatNumber(shipCost, 2, Microsoft.VisualBasic.TriState.True, Microsoft.VisualBasic.TriState.False, Microsoft.VisualBasic.TriState.False))
oCartElmt.SetAttribute("vatAmt", 0.0#)
oCartElmt.SetAttribute("total", FormatNumber(total + shipCost, 2, Microsoft.VisualBasic.TriState.True, Microsoft.VisualBasic.TriState.False, Microsoft.VisualBasic.TriState.False))
End If
Return vatAmt
Catch ex As Exception
returnException(mcModuleName, "updateTotals", ex, "", cProcessInfo, gbDebug)
End Try
End Function
Sub getShippingDetailXml(ByRef oCartXml As XmlElement, ByVal nShippingId As Long)
PerfMon.Log("Cart", "getShippingDetailXml")
Dim cProcessInfo As String = ""
Dim oDs As DataSet
Dim sSql As String = "select cShipOptName as Name, cShipOptCarrier as Carrier, cShipOptTime as DeliveryTime from tblCartShippingMethods where nShipOptKey=" & nShippingId
Dim oXml As XmlDataDocument
Dim oShippingXml As XmlElement
Try
oDs = moDBHelper.GetDataSet(sSql, "Shipping", "Cart")
oXml = New XmlDataDocument(oDs)
oDs.EnforceConstraints = False
oShippingXml = moPageXml.CreateElement("Cart")
oShippingXml.InnerXml = oXml.InnerXml
oCartXml.AppendChild(oShippingXml.FirstChild.FirstChild)
Catch ex As Exception
returnException(mcModuleName, "getShippingDetailXml", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Function getProductPricesByXml(ByVal cXml As String, ByVal cUnit As String, ByVal nQuantity As Long, Optional ByVal PriceType As String = "Prices") As Double
PerfMon.Log("Cart", "getProductPricesByXml")
Dim cGroupXPath As String = ""
Dim oProd As XmlElement = moPageXml.CreateElement("product")
Try
oProd.InnerXml = cXml
Dim oThePrice As XmlElement = getContentPricesNode(oProd, cUnit, nQuantity, PriceType)
Dim nPrice As Double = 0.0#
If IsNumeric(oThePrice.InnerText) Then
nPrice = CDbl(oThePrice.InnerText)
End If
Return nPrice
Catch ex As Exception
returnException(mcModuleName, "getProductPricesByXml", ex, "", "", gbDebug)
End Try
End Function
Function getProductTaxRate(ByVal priceXml As XmlElement) As Double
PerfMon.Log("Cart", "getProductVatRate")
Dim cGroupXPath As String = ""
Dim oProd As XmlNode = moPageXml.CreateNode(XmlNodeType.Document, "", "product")
Try
Dim vatCode As String = ""
If mbVatOnLine Then
Select Case priceXml.GetAttribute("taxCode")
Case "0"
Return 0
Case LCase("s")
Return mnTaxRate
Case Else
Return mnTaxRate
End Select
Else
Return 0
End If
Catch ex As Exception
returnException(mcModuleName, "getProductTaxRate", ex, "", "", gbDebug)
Return Nothing
End Try
End Function
Function getContentPricesNode(ByVal oContentXml As XmlElement, ByVal cUnit As String, ByVal nQuantity As Long, Optional ByVal PriceType As String = "Prices") As XmlElement
PerfMon.Log("Cart", "getContentPricesNode")
Dim cGroupXPath As String = ""
Dim oDefaultPrice As XmlNode
Try
' Get the Default Price - note if it does not exist, then this is menaingless.
oDefaultPrice = oContentXml.SelectSingleNode("Content/" & PriceType & "/Price[@default='true']")
'here we are checking if the price is the correct currency
'then if we are logged in we will also check if it belongs to
'one of the user's groups, just looking for
Dim cGroups As String = getGroupsByName()
If cGroups = "" Then cGroups &= "default,all" Else cGroups &= ",default,all"
cGroups = " and ( contains(@validGroup,""" & Replace(cGroups, ",", """) or contains(@validGroup,""")
cGroups &= """) or not(@validGroup) or @validGroup="""")"
If cUnit <> "" Then
cGroups = cGroups & "and (@unit=""" & cUnit & """)"
End If
' cGroups = ""
'Dim cxpath As String = "Content/Prices/Price[(@currency='" & mcCurrency & "') " & cGroups & " ][1]"
'Fix for content items that are not Content/Content done for legacy sites such as insure your move 09/06/2015
Dim xPathStart As String = "Content/"
If oContentXml.FirstChild.Name <> "Content" Then
xPathStart = ""
End If
Dim cxpath As String = xPathStart & PriceType & "/Price[(@currency=""" & mcCurrency & """) " & cGroups & " and node()!=""""]" 'need to loop through all just in case we have splits'handled later on though
Dim oThePrice As XmlElement = oDefaultPrice
Dim oPNode As XmlElement
Dim nPrice As Double = 0.0#
For Each oPNode In oContentXml.SelectNodes(cxpath)
'need to deal with "in-product" price splits
Dim bHasSplits As Boolean = False
Dim bValidSplit As Boolean = False
If oPNode.HasAttribute("min") Or oPNode.HasAttribute("max") Then
If oPNode.GetAttribute("min") <> "" And oPNode.GetAttribute("max") <> "" Then
bHasSplits = True
'has a split
Dim nThisMin As Integer = IIf(oPNode.GetAttribute("min") = "", 1, oPNode.GetAttribute("min"))
Dim nThisMax As Integer = IIf(oPNode.GetAttribute("max") = "", 0, oPNode.GetAttribute("max"))
If (nThisMin <= nQuantity) And (nThisMax >= nQuantity Or nThisMax = 0) Then
'now we know it is a valid split
bValidSplit = True
End If
End If
End If
If Not oThePrice Is Nothing Then
If IsNumeric(oThePrice.InnerText) Then
'this selects the cheapest price for this user assuming not free
If IsNumeric(oPNode.InnerText) Then
If CDbl(oPNode.InnerText) < CDbl(oThePrice.InnerText) And CLng(oPNode.InnerText) <> 0 Then
oThePrice = oPNode
End If
End If
Else
oThePrice = oPNode
End If
Else
oThePrice = oPNode
End If
'if there are splits and this is a valid split then we want to exit
If bHasSplits And bValidSplit Then Exit For
'If Not bHasSplits Then Exit For 'we only need the first one if we dont have splits
Next
Return oThePrice
Catch ex As Exception
returnException(mcModuleName, "getContentPricesNode", ex, "", "", gbDebug)
Return Nothing
End Try
End Function
Function getOptionPricesByXml(ByVal cXml As String, ByVal nGroupIndex As Integer, ByVal nOptionIndex As Integer) As Double
PerfMon.Log("Cart", "getOptionPricesByXml")
Dim cGroupXPath As String = ""
Dim oProd As XmlNode = moPageXml.CreateNode(XmlNodeType.Document, "", "product")
Dim oDefaultPrice As XmlNode
Try
' Load product xml
oProd.InnerXml = cXml
' Get the Default Price - note if it does not exist, then this is menaingless.
oDefaultPrice = oProd.SelectSingleNode("Content/Options/OptGroup[" & nGroupIndex & "]/option[" & nOptionIndex & "]/Prices/Price[@default='true']")
'here we are checking if the price is the correct currency
'then if we are logged in we will also check if it belongs to
'one of the user's groups, just looking for
Dim cGroups As String = getGroupsByName()
If cGroups = "" Then cGroups &= "default,all" Else cGroups &= ",default,all"
cGroups = " and ( contains(@validGroup,""" & Replace(cGroups, ",", """) or contains(@validGroup,""")
cGroups &= """) or not(@validGroup) or @validGroup="""")"
Dim cxpath As String = "Content/Options/OptGroup[" & nGroupIndex & "]/option[" & nOptionIndex & "]/Prices/Price[(@currency=""" & mcCurrency & """) " & cGroups & " ]"
Dim oThePrice As XmlElement = oDefaultPrice
Dim oPNode As XmlElement
Dim nPrice As Double = 0.0#
For Each oPNode In oProd.SelectNodes(cxpath)
'If Not oThePrice Is Nothing Then
' If CDbl(oPNode.InnerText) < CDbl(oThePrice.InnerText) Then
' oThePrice = oPNode
' nPrice = CDbl(oThePrice.InnerText)
' End If
'Else
' oThePrice = oPNode
' nPrice = CDbl(oThePrice.InnerText)
'End If
If Not oThePrice Is Nothing Then
If IsNumeric(oThePrice.InnerText) Then
If CDbl(oPNode.InnerText) < CDbl(oThePrice.InnerText) Then
oThePrice = oPNode
nPrice = CDbl(oThePrice.InnerText)
End If
Else
oThePrice = oPNode
nPrice = CDbl(oThePrice.InnerText)
End If
Else
oThePrice = oPNode
If IsNumeric(oThePrice.InnerText) Then
nPrice = CDbl(oThePrice.InnerText)
End If
End If
Next
Return nPrice
Catch ex As Exception
returnException(mcModuleName, "getOptionPricesByXml", ex, "", "", gbDebug)
End Try
End Function
Private Sub CheckQuantities(ByRef oCartElmt As XmlElement, ByVal cProdXml As String, ByVal cItemQuantity As String)
PerfMon.Log("Cart", "CheckQuantities")
' Check each product against max and mins
Try
Dim oErrorMsg As String = ""
Dim oError As XmlElement
Dim oMsg As XmlElement
Dim oProd As XmlNode = moPageXml.CreateNode(XmlNodeType.Document, "", "product")
' Load product xml
oProd.InnerXml = cProdXml
' Set the error node
oError = oCartElmt.SelectSingleNode("error")
If IsNumeric(cItemQuantity) Then
'Check minimum value
If CLng(cItemQuantity) < CLng(getNodeValueByType(oProd, "//Quantities/Minimum", dataType.TypeNumber, 0)) Then
' Minimum has not been matched
' Check for existence of error node
If oError Is Nothing Then
oError = oCartElmt.OwnerDocument.CreateElement("error")
oCartElmt.AppendChild(oError)
End If
' Check for existence of msg node for min
If oError.SelectSingleNode("msg[@type='quantity_min']") Is Nothing Then
oMsg = addElement(oError, "msg", "You have not requested enough of one or more products", True)
oMsg.SetAttribute("type", "quantity_min")
End If
' Add product specific msg
oMsg = addElement(oError, "msg", "<strong>" & getNodeValueByType(oProd, "/Content/Name", dataType.TypeString, "A product below ") & "</strong> requires a quantity equal to or above <em>" & getNodeValueByType(oProd, "//Quantities/Minimum", dataType.TypeNumber, "an undetermined value (please call for assistance).") & "</em>", True)
oMsg.SetAttribute("type", "quantity_min_detail")
End If
'Check maximum value
If CLng(cItemQuantity) > CLng(getNodeValueByType(oProd, "//Quantities/Maximum", dataType.TypeNumber, Integer.MaxValue)) Then
' Maximum has not been matched
' Check for existence of error node
If oError Is Nothing Then
oError = oCartElmt.OwnerDocument.CreateElement("error")
oCartElmt.AppendChild(oError)
End If
' Check for existence of msg node for min
If oError.SelectSingleNode("msg[@type='quantity_max']") Is Nothing Then
oMsg = addElement(oError, "msg", "You have requested too much of one or more products")
oMsg.SetAttribute("type", "quantity_max")
End If
' Add product specific msg
oMsg = addElement(oError, "msg", "<strong>" & getNodeValueByType(oProd, "/Content/Name", dataType.TypeString, "A product below ") & "</strong> requires a quantity equal to or below <em>" & getNodeValueByType(oProd, "//Quantities/Maximum", dataType.TypeNumber, "an undetermined value (please call for assistance).") & "</em>", True)
oMsg.SetAttribute("type", "quantity_max_detail")
End If
'Check bulkunit value
Dim cBulkUnit As Integer = getNodeValueByType(oProd, "//Quantities/BulkUnit", dataType.TypeNumber, 0)
If (CLng(cItemQuantity) Mod CLng(getNodeValueByType(oProd, "//Quantities/BulkUnit", dataType.TypeNumber, 1))) <> 0 Then
' Bulk Unit has not been matched
' Check for existence of error node
If oError Is Nothing Then
oError = oCartElmt.OwnerDocument.CreateElement("error")
oCartElmt.AppendChild(oError)
End If
' Check for existence of msg node for min
If oError.SelectSingleNode("msg[@type='quantity_mod']") Is Nothing Then
oMsg = addElement(oError, "msg", "One or more products below can only be bought in certain quantities.")
oMsg.SetAttribute("type", "quantity_mod")
End If
' Add product specific msg
oMsg = addElement(oError, "msg", "<strong>" & getNodeValueByType(oProd, "/Content/Name", dataType.TypeString, "A product below ") & "</strong> can only be bought in lots of <em>" & getNodeValueByType(oProd, "//Quantities/BulkUnit", dataType.TypeNumber, "an undetermined value (please call for assistance).") & "</em>", True)
oMsg.SetAttribute("type", "quantity_mod_detail")
End If
End If
Catch ex As Exception
returnException(mcModuleName, "CheckQuantities", ex, "", "", gbDebug)
End Try
End Sub
Private Sub CheckStock(ByRef oCartElmt As XmlElement, ByVal cProdXml As String, ByVal cItemQuantity As String)
PerfMon.Log("Cart", "CheckStock")
Dim oProd As XmlNode = moPageXml.CreateNode(XmlNodeType.Document, "", "product")
Dim oStock As XmlNode
Dim oError As XmlElement
Dim oMsg As XmlElement
Dim cProcessInfo As String = ""
Try
' Load product xml
oProd.InnerXml = cProdXml
' Locate the Stock Node
oStock = oProd.SelectSingleNode("//Stock")
' Ignore empty nodes
If Not (oStock Is Nothing) Then
' Ignore non-numeric nodes
If IsNumeric(oStock.InnerText) Then
' If the requested quantity is greater than the stock level, add a warning to the cart - only check tihs on an active cart.
If CLng(cItemQuantity) > CLng(oStock.InnerText) And mnProcessId < 6 Then
If oCartElmt.SelectSingleNode("error") Is Nothing Then oCartElmt.AppendChild(oCartElmt.OwnerDocument.CreateElement("error"))
oError = oCartElmt.SelectSingleNode("error")
oMsg = addElement(oError, "msg", "<span class=""term3080"">You have requested more items than are currently <em>in stock</em> for <strong class=""product-name"">" & oProd.SelectSingleNode("//Name").InnerText & "</strong> (only <span class=""quantity-available"">" & oStock.InnerText & "</span> available).</span><br/>", True)
oMsg.SetAttribute("type", "stock")
End If
End If
End If
Catch ex As Exception
returnException(mcModuleName, "CheckStock", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Sub UpdateStockLevels(ByRef oCartElmt As XmlElement)
PerfMon.Log("Cart", "UpdateStockLevels")
Dim sSql As String
Dim oDs As DataSet
Dim oRow As DataRow
Dim oProd As XmlNode = moPageXml.CreateNode(XmlNodeType.Document, "", "product")
Dim oItem As XmlElement
Dim oStock As XmlNode
Dim nStockLevel As Integer
Dim cProcessInfo As String = ""
Try
For Each oItem In oCartElmt.SelectNodes("Item")
If oItem.GetAttribute("contentId") <> "" Then
sSql = "select * from tblContent where nContentKey=" & oItem.GetAttribute("contentId")
oDs = moDBHelper.getDataSetForUpdate(sSql, "Item", "Cart")
For Each oRow In oDs.Tables("Item").Rows
oProd.InnerXml = oRow("cContentXmlDetail")
oStock = oProd.SelectSingleNode("//Stock")
' Ignore empty nodes
If Not (oStock Is Nothing) Then
' Ignore non-numeric nodes
If IsNumeric(oStock.InnerText) Then
nStockLevel = CInt(oStock.InnerText) - CInt(oItem.GetAttribute("quantity"))
' Remember to delete the XmlCache
moDBHelper.DeleteXMLCache()
' Update stock level
If nStockLevel < 0 Then nStockLevel = 0
oStock.InnerText = nStockLevel
oRow("cContentXmlDetail") = oProd.InnerXml
End If
End If
'For Brief
oProd.InnerXml = oRow("cContentXmlBrief")
oStock = oProd.SelectSingleNode("//Stock")
' Ignore empty nodes
If Not (oStock Is Nothing) Then
' Ignore non-numeric nodes
If IsNumeric(oStock.InnerText) Then
oStock.InnerText = nStockLevel
oRow("cContentXmlBrief") = oProd.InnerXml
End If
End If
Next
moDBHelper.updateDataset(oDs, "Item")
End If
Next
Catch ex As Exception
returnException(mcModuleName, "UpdateStockLevels", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Sub UpdateGiftListLevels()
PerfMon.Log("Cart", "UpdateGiftListLevels")
Dim sSql As String
Dim cProcessInfo As String = ""
Try
If mnGiftListId > 0 Then
' The SQL statement JOINS items in the current cart to items in giftlist (by matching ID_OPTION1_OPTION2), and updates the quantity in giftlist accordingly.
' CONVERT is needed to create concat the unique identifier.
sSql = "update g " _
& "set g.nQuantity=(g.nQuantity - o.nQuantity) " _
& "from tblCartItem o inner join tblCartItem g " _
& "on (convert(nvarchar,o.nItemId) + '_' + convert(nvarchar,o.cItemOption1) + '_' + convert(nvarchar,o.cItemOption2)) = (convert(nvarchar,g.nItemId) + '_' + convert(nvarchar,g.cItemOption1) + '_' + convert(nvarchar,g.cItemOption2)) " _
& "where o.nCartOrderId = " & mnCartId & " and g.nCartOrderId = " & mnGiftListId
moDBHelper.ExeProcessSql(sSql)
End If
Catch ex As Exception
returnException(mcModuleName, "UpdateGiftListLevels", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
'deprecated for the single call function above.
Public Sub UpdateGiftListLevels_Old()
PerfMon.Log("Cart", "UpdateGiftListLevels_Old")
Dim sSql As String
Dim oDs As DataSet
Dim oRow As DataRow
Dim oDr2 As SqlDataReader
Dim nNewQty As Decimal
Dim cProcessInfo As String = ""
Try
If mnGiftListId > 0 Then
sSql = "select * from tblCartItem where nCartOrderId=" & mnCartId
oDs = moDBHelper.GetDataSet(sSql, "tblCartItem")
For Each oRow In oDs.Tables("tblCartItem").Rows
nNewQty = oRow.Item("nQuantity")
sSql = "select * from tblCartItem where nCartOrderId=" & mnGiftListId & " and nItemId =" & oRow("nItemId").ToString() & " and cItemOption1='" & SqlFmt(oRow("cItemOption1").ToString()) & "' and cItemOption2='" & SqlFmt(oRow("cItemOption2").ToString()) & "'"
oDr2 = moDBHelper.getDataReader(sSql)
While (oDr2.Read())
nNewQty = oDr2.Item("nQuantity") - oRow.Item("nQuantity")
End While
sSql = "Update tblCartItem set nQuantity = " & nNewQty.ToString() & " where nCartOrderId=" & mnGiftListId & " and nItemId =" & oRow("nItemId").ToString() & " and cItemOption1='" & SqlFmt(oRow("cItemOption1").ToString()) & "' and cItemOption2='" & SqlFmt(oRow("cItemOption2").ToString()) & "'"
moDBHelper.ExeProcessSql(sSql)
oDr2.Close()
Next
End If
Catch ex As Exception
returnException(mcModuleName, "UpdateGiftListLevels", ex, "", cProcessInfo, gbDebug)
Finally
oDr2 = Nothing
oDs = Nothing
End Try
End Sub
Public Function getGroupsByName() As String
PerfMon.Log("Cart", "getGroupsByName")
'!!!!!!!!!!!!!! Should this be in Membership Object???
Dim cReturn As String
Dim oDs As DataSet
Dim oDr As DataRow
Dim cProcessInfo As String = ""
Try
' Get groups from user ID return A comma separated string?
oDs = moDBHelper.GetDataSet("select * from tblDirectory g inner join tblDirectoryRelation r on g.nDirKey = r.nDirParentId where r.nDirChildId = " & mnEwUserId, "Groups")
cReturn = ""
If oDs.Tables("Groups").Rows.Count > 0 Then
For Each oDr In oDs.Tables("Groups").Rows
cReturn = cReturn & "," & oDr.Item("cDirName")
Next
cReturn = Mid(cReturn, 2)
End If
Return cReturn
Catch ex As Exception
returnException(mcModuleName, "getGroupsByName", ex, "", cProcessInfo, gbDebug)
Return Nothing
End Try
End Function
Public Overridable Sub addressSubProcess(ByRef oCartElmt As XmlElement, ByVal cAddressType As String)
Dim oContactXform As xForm
Dim submitPrefix As String = "cartBill"
Dim cProcessInfo As String = submitPrefix
Try
If cAddressType.Contains("Delivery") Then submitPrefix = "cartDel"
If mbEwMembership = True And myWeb.mnUserId <> 0 And submitPrefix <> "cartDel" Then
'we now only need this on delivery.
oContactXform = pickContactXform(cAddressType, submitPrefix, , mcCartCmd)
GetCart(oCartElmt)
Else
oContactXform = contactXform(cAddressType, , , mcCartCmd)
GetCart(oCartElmt)
End If
If oContactXform.valid = False Then
'show the form
Dim oContentElmt As XmlElement = moPageXml.SelectSingleNode("/Page/Contents")
If oContentElmt Is Nothing Then
oContentElmt = moPageXml.CreateElement("Contents")
If moPageXml.DocumentElement Is Nothing Then
Err.Raise(1004, "addressSubProcess", " PAGE IS NOT CREATED")
Else
moPageXml.DocumentElement.AppendChild(oContentElmt)
End If
End If
oContentElmt.AppendChild(oContactXform.moXformElmt)
Else
If Not cAddressType.Contains("Delivery") Then
' Valid Form, let's adjust the Vat rate
' AJG By default the tax rate is picked up from the billing address, unless otherwise specified.
'
If moCartConfig("TaxFromDeliveryAddress") <> "on" Or (myWeb.moRequest("cIsDelivery") = "True" And moCartConfig("TaxFromDeliveryAddress") = "on") Then
If Not oContactXform.Instance.SelectSingleNode("Contact[@type='Billing Address']") Is Nothing Then
UpdateTaxRate(oCartElmt.SelectSingleNode("Contact[@type='Billing Address']/Country").InnerText)
End If
End If
'to allow for single form with multiple addresses.
If moCartConfig("TaxFromDeliveryAddress") = "on" And Not (oCartElmt.SelectSingleNode("Contact[@type='Delivery Address']") Is Nothing) Then
UpdateTaxRate(oCartElmt.SelectSingleNode("Contact[@type='Delivery Address']/Country").InnerText)
End If
' Skip Delivery if:
' - Deliver to this address is selected
' - mbNoDeliveryAddress is True
' - the order is part of a giftlist (the delivery address is pre-determined)
' - we have submitted the delivery address allready
If myWeb.moRequest("cIsDelivery") = "True" _
Or mbNoDeliveryAddress _
Or mnGiftListId > 0 _
Or Not (oContactXform.Instance.SelectSingleNode("tblCartContact[cContactType/node()='Delivery Address']") Is Nothing) _
Or oContactXform.moXformElmt.GetAttribute("cartCmd") = "ChoosePaymentShippingOption" _
Then
mcCartCmd = "ChoosePaymentShippingOption"
mnProcessId = 3
Else
'If mbEwMembership = True And myWeb.mnUserId <> 0 Then
' 'all handled in pick form
'Else
Dim BillingAddressID As Long = setCurrentBillingAddress(myWeb.mnUserId, 0)
If myWeb.moRequest(submitPrefix & "editAddress" & BillingAddressID) <> "" Then
'we are editing an address form the pick address form so lets go back.
mcCartCmd = "Billing"
mnProcessId = 2
Else
mcCartCmd = "Delivery"
End If
'End If
' billing address is saved, so up cart status if needed
'If mnProcessId < 2 Then mnProcessId = 2
'If mnProcessId > 2 Then
' mcCartCmd = "ChoosePaymentShippingOption"
' mnProcessId = 3
'End If
End If
If myWeb.mnUserId > 0 Then
setCurrentBillingAddress(myWeb.mnUserId, 0)
End If
Else 'Case for Delivery
' AJG If specified, the tax rate can be picked up from the delivery address
If moCartConfig("TaxFromDeliveryAddress") = "on" Then
UpdateTaxRate(oCartElmt.SelectSingleNode("Contact[@type='Delivery Address']/Country").InnerText)
End If
'TS if we don't have a billing address we need one
Dim oDs2 As DataSet
oDs2 = moDBHelper.GetDataSet("select * from tblCartContact where nContactCartId = " & CStr(Me.mnCartId) & " and cContactType = 'Billing Address'", "tblCartContact")
If oDs2.Tables("tblCartContact").Rows.Count > 0 Then
mcCartCmd = "ChoosePaymentShippingOption"
mnProcessId = 3
Else
If myWeb.mnUserId > 0 Then
Dim BillingAddressID As Long = setCurrentBillingAddress(myWeb.mnUserId, 0)
If BillingAddressID > 0 Then
'set the billing address
Dim sSql As String = "Select nContactKey from tblCartContact where cContactType = 'Delivery Address' and nContactCartid=" & mnCartId
Dim DeliveryAddressID As String = moDBHelper.ExeProcessSqlScalar(sSql)
useSavedAddressesOnCart(BillingAddressID, DeliveryAddressID)
mcCartCmd = "ChoosePaymentShippingOption"
mnProcessId = 3
Else
mcCartCmd = "Billing"
mnProcessId = 2
End If
Else
mcCartCmd = "Billing"
mnProcessId = 2
End If
End If
End If
'save address against the user
If mbEwMembership = True And myWeb.mnUserId > 0 And oContactXform.valid Then
If Not oContactXform.moXformElmt.GetAttribute("persistAddress") = "false" Then
cProcessInfo = "UpdateExistingUserAddress for : " & myWeb.mnUserId
UpdateExistingUserAddress(oContactXform)
End If
End If
End If
oContactXform = Nothing
Catch ex As Exception
returnException(mcModuleName, "addressSubProcess", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Overridable Function usePreviousAddress(ByRef oCartElmt As XmlElement) As Boolean
Dim cProcessInfo As String
Dim sSql As String
Dim billingAddId As Long = 0
Dim deliveryAddId As Long = 0
Dim oDs As DataSet
Dim odr As DataRow
Try
If mbEwMembership = True And myWeb.mnUserId <> 0 Then
If LCase(moCartConfig("UsePreviousAddress")) = "on" Then
sSql = "select nContactKey, cContactType, nAuditKey from tblCartContact inner join tblAudit a on nAuditId = a.nAuditKey where nContactCartId = 0 and nContactDirId =" & CStr(myWeb.mnUserId)
oDs = moDBHelper.GetDataSet(sSql, "tblCartContact")
For Each odr In oDs.Tables("tblCartContact").Rows
If odr("cContactType") = "Billing Address" Then
billingAddId = odr("nContactKey")
End If
If LCase(moCartConfig("NoDeliveryAddress")) = "on" Then
deliveryAddId = billingAddId
Else
If odr("cContactType") = "Delivery Address" Then
deliveryAddId = odr("nContactKey")
End If
End If
Next
If deliveryAddId <> 0 And billingAddId <> 0 Then
useSavedAddressesOnCart(billingAddId, deliveryAddId)
'skip
mcCartCmd = "ChoosePaymentShippingOption"
Return True
Else
'we don't have the addresses we need so we need to go to address step anyhow
Return False
End If
Else
'Use previous address functionality turned off
Return False
End If
Else
'User not logged on or membership is off
Return False
End If
Catch ex As Exception
returnException(mcModuleName, "addressSubProcess", ex, "", cProcessInfo, gbDebug)
Return False
End Try
End Function
Public Overridable Function contactXform(ByVal cAddressType As String, Optional ByVal cSubmitName As String = "submit", Optional ByVal cCmdType As String = "cartCmd", Optional ByVal cCmdAction As String = "") As xForm
Return contactXform(cAddressType, cSubmitName, cCmdType, cCmdAction, False)
End Function
Public Overridable Function contactXform(ByVal cAddressType As String, ByVal cSubmitName As String, ByVal cCmdType As String, ByVal cCmdAction As String, ByVal bDontPopulate As Boolean, Optional ContactId As Long = 0, Optional cmd2 As String = "") As xForm
PerfMon.Log("Cart", "contactXform")
Dim oXform As xForm = New xForm
Dim oGrpElmt As XmlElement
Dim oDs As DataSet
Dim oDr As DataRow
Dim oElmt As XmlElement
Dim cWhere As String
Dim cProcessInfo As String = ""
Dim cXformLocation As String = ""
Dim bIsBespokeXform As Boolean = False
Dim bGetInstance As Boolean
Dim sSql As String
Try
' Build the xform
oXform.moPageXML = moPageXml
oXform.NewFrm(cAddressType)
' Check for bespoke xform
Select Case cAddressType
Case "Billing Address" : cXformLocation = mcBillingAddressXform
Case "Delivery Address" : cXformLocation = mcDeliveryAddressXform
End Select
' Test that a bespoke form exists and is a valid filename
bIsBespokeXform = System.IO.File.Exists(myWeb.goServer.MapPath(cXformLocation)) And LCase(Right(cXformLocation, 4)) = ".xml"
' :::::::::::::::::::::::::::::::::::::::::::::::
' :::: CONTACT XFORM :: GROUP and BIND BUILD ::::
' :::::::::::::::::::::::::::::::::::::::::::::::
If bIsBespokeXform Then
' Load the bespoke form
oXform.load(cXformLocation)
'select the first group element for adding delivery checkbox
oGrpElmt = oXform.moXformElmt.SelectSingleNode("group[1]")
If ContactId > 0 Then
bGetInstance = True
End If
Else
'Build the xform because file not specified
bGetInstance = True
oXform.addGroup(oXform.moXformElmt, "address", , cAddressType)
oGrpElmt = oXform.moXformElmt.LastChild
oXform.addInput(oGrpElmt, cCmdType, True, cCmdType, "hidden")
oXform.addBind(cCmdType, cCmdType)
oXform.addInput(oGrpElmt, "cContactType", True, "Type", "hidden")
oXform.addBind("cContactType", "tblCartContact/cContactType")
oXform.addInput(oGrpElmt, "cContactName", True, "Name", "textbox required")
oXform.addBind("cContactName", "tblCartContact/cContactName", "true()", "string")
oXform.addInput(oGrpElmt, "cContactCompany", True, "Company", "textbox")
oXform.addBind("cContactCompany", "tblCartContact/cContactCompany", "false()")
oXform.addInput(oGrpElmt, "cContactAddress", True, "Address", "textbox required")
oXform.addBind("cContactAddress", "tblCartContact/cContactAddress", "true()", "string")
oXform.addInput(oGrpElmt, "cContactCity", True, "City", "textbox required")
oXform.addBind("cContactCity", "tblCartContact/cContactCity", "true()")
oXform.addInput(oGrpElmt, "cContactState", True, "County/State", "textbox")
oXform.addBind("cContactState", "tblCartContact/cContactState")
oXform.addInput(oGrpElmt, "cContactZip", True, "Postcode/Zip", "textbox required")
oXform.addBind("cContactZip", "tblCartContact/cContactZip", "true()", "string")
oXform.addSelect1(oGrpElmt, "cContactCountry", True, "Country", "dropdown required")
oXform.addBind("cContactCountry", "tblCartContact/cContactCountry", "true()", "string")
oXform.addInput(oGrpElmt, "cContactTel", True, "Tel", "textbox")
oXform.addBind("cContactTel", "tblCartContact/cContactTel")
oXform.addInput(oGrpElmt, "cContactFax", True, "Fax", "textbox")
oXform.addBind("cContactFax", "tblCartContact/cContactFax")
' Only show email address for Billing
If cAddressType = "Billing Address" Or mnGiftListId > 0 Then
oXform.addInput(oGrpElmt, "cContactEmail", True, "Email", "textbox required")
oXform.addBind("cContactEmail", "tblCartContact/cContactEmail", "true()", "email")
End If
If myWeb.moConfig("cssFramework") = "bs3" Then
oXform.addSubmit(oGrpElmt, "Submit" & Replace(cAddressType, " ", ""), "Submit")
Else
oXform.addSubmit(oGrpElmt, "Submit" & Replace(cAddressType, " ", ""), "Submit", cSubmitName & Replace(cAddressType, " ", ""))
End If
oXform.submission("Submit" & Replace(cAddressType, " ", ""), IIf(cCmdAction = "", "", "?" & cCmdType & "=" & cCmdAction), "POST", "return form_check(this);")
End If
' Add the countries list to the form
For Each oElmt In oXform.moXformElmt.SelectNodes("descendant-or-self::select1[contains(@class, 'country') or @bind='cContactCountry']")
Dim cThisAddressType As String
If oElmt.ParentNode.SelectSingleNode("input[@bind='cContactType' or @bind='cDelContactType']/value") Is Nothing Then
cThisAddressType = cAddressType
Else
cThisAddressType = oElmt.ParentNode.SelectSingleNode("input[@bind='cContactType' or @bind='cDelContactType']/value").InnerText
End If
If LCase(moCartConfig("NoDeliveryAddress")) = "on" Then
cThisAddressType = "Delivery Address"
End If
populateCountriesDropDown(oXform, oElmt, cThisAddressType)
Next
' Add the Delivery Checkbox if needed
If cAddressType = "Billing Address" And mnProcessId < 2 And (Not (mbNoDeliveryAddress)) And Not (mnGiftListId > 0) Then
' this can be optionally turned off in the xform, by the absence of cIsDelivery in the instance.
If oXform.Instance.SelectSingleNode("tblCartContact[@type='Delivery Address']") Is Nothing And oXform.Instance.SelectSingleNode("//bDisallowDeliveryCheckbox") Is Nothing Then
' shoppers have the option to send to same address as the billing with a checkbox
oXform.addSelect(oGrpElmt, "cIsDelivery", True, "Deliver to This Address", "checkbox", xForm.ApperanceTypes.Minimal)
oXform.addOption((oGrpElmt.LastChild), "", "True")
oXform.addBind("cIsDelivery", "tblCartContact/cIsDelivery")
End If
End If
If moDBHelper.checkTableColumnExists("tblCartShippingMethods", "bCollection") Then
'Add Collection options
Dim oIsDeliverySelect As XmlElement = oXform.moXformElmt.SelectSingleNode("descendant-or-self::select[@bind='cIsDelivery']")
If Not oIsDeliverySelect Is Nothing Then
'Create duplicate select as select1
Dim newElmt As XmlElement = moPageXml.CreateElement("select1")
Dim oAtt As XmlAttribute
For Each oAtt In oIsDeliverySelect.Attributes
newElmt.SetAttribute(oAtt.Name, oAtt.Value)
Next
Dim oNode As XmlNode
For Each oNode In oIsDeliverySelect.ChildNodes
newElmt.AppendChild(oNode.CloneNode(True))
Next
Dim delBillingElmt As XmlElement = oXform.addOption(newElmt, "Deliver to Billing Address", "false")
Dim bCollection As Boolean = False
'Get the collection delivery options
Dim oDrCollectionOptions As SqlDataReader = moDBHelper.getDataReader("select * from tblCartShippingMethods where bCollection = 1")
Do While oDrCollectionOptions.Read()
Dim OptLabel As String = "<span class=""opt-name"">" & oDrCollectionOptions.Item("cShipOptName").ToString() & "</span>"
OptLabel = OptLabel & "<span class=""opt-carrier"">" & oDrCollectionOptions.Item("cShipOptCarrier").ToString() & "</span>"
oXform.addOption(newElmt, OptLabel, oDrCollectionOptions.Item("nShipOptKey").ToString(), True)
bCollection = True
Loop
'Only change this if collection shipping options exist.
If bCollection Then
oIsDeliverySelect.ParentNode.ReplaceChild(newElmt, oIsDeliverySelect)
Else
'this was all for nuffin
newElmt = Nothing
End If
End If
End If
If cmd2 <> "" Then
oXform.addInput(oGrpElmt, cmd2, True, cmd2, "hidden")
oXform.addBind(cmd2, "cmd2")
End If
' :::::::::::::::::::::::::::::::::::::::::::::::
' :::: CONTACT XFORM :: CREATE/LOAD INSTANCE ::::
' :::::::::::::::::::::::::::::::::::::::::::::::
' When there is no match this will get the default instance based on the table schema.
' This will override any form that we have loaded in, so we need to put exceptions in.
If bGetInstance Then
oXform.Instance.InnerXml = moDBHelper.getObjectInstance(dbHelper.objectTypes.CartContact, ContactId)
If ContactId > 0 Then
bDontPopulate = True
End If
End If
'if the instance is empty fill these values
Dim bAddIds As Boolean = False
'catch for sites where nContactKey is not specified.
If oXform.Instance.SelectSingleNode("*/nContactKey") Is Nothing Then
bAddIds = True
Else
If oXform.Instance.SelectSingleNode("*/nContactKey").InnerText = "" Then
bAddIds = True
End If
End If
If bAddIds Then
For Each oElmt In oXform.Instance.SelectNodes("*/nContactDirId")
oElmt.InnerText = myWeb.mnUserId
Next
For Each oElmt In oXform.Instance.SelectNodes("*/nContactCartId")
oElmt.InnerText = mnCartId
Next
For Each oElmt In oXform.Instance.SelectNodes("*/cContactType")
If oElmt.InnerText = "" Then oElmt.InnerText = cAddressType
Next
End If
'make sure we don't show a random address.
If mnCartId = 0 Then bDontPopulate = True
If bDontPopulate = False Then
'if we have addresses in the cart insert them
sSql = "select nContactKey, cContactType from tblCartContact where nContactCartId = " & CStr(mnCartId)
oDs = moDBHelper.GetDataSet(sSql, "tblCartContact")
For Each oDr In oDs.Tables("tblCartContact").Rows
Dim tempInstance As XmlElement = moPageXml.CreateElement("TempInstance")
tempInstance.InnerXml = moDBHelper.getObjectInstance(dbHelper.objectTypes.CartContact, oDr("nContactKey"))
Dim instanceAdd As XmlElement = oXform.Instance.SelectSingleNode("tblCartContact[cContactType/node()='" & oDr("cContactType") & "']")
If Not instanceAdd Is Nothing Then
instanceAdd.ParentNode.ReplaceChild(tempInstance.FirstChild, instanceAdd)
instanceAdd = oXform.Instance.SelectSingleNode("tblCartContact[cContactType/node()='" & oDr("cContactType") & "']")
If Not instanceAdd Is Nothing Then
instanceAdd.SetAttribute("type", oDr("cContactType"))
End If
End If
Next
oDs = Nothing
'set the isDelivery Value
'remember the delivery address setting.
Dim delivElmt As XmlElement = oXform.Instance.SelectSingleNode("tblCartContact[cContactType/node()='Delivery Address']")
If Not delivElmt Is Nothing Then
If myWeb.moSession("isDelivery") = "" Then
delivElmt.SetAttribute("isDelivery", "false")
Else
delivElmt.SetAttribute("isDelivery", myWeb.moSession("isDelivery"))
End If
End If
End If
'Dim bGetInstance As Boolean = True
'If bIsBespokeXform Then
' ' There is a bespoke form, let's check for the presence of an item in the contact table
' Dim oCartContactInDB As Object = moDBHelper.GetDataValue("SELECT COUNT(*) As FoundCount FROM tblCartContact " & ssql)
' If Not (oCartContactInDB > 0) Then bGetInstance = False ' No Item so do not get the instance
'End If
' If membership is on and the user is logged on, we need to check if this is an existing address in the user's list of addresses
If mbEwMembership = True And myWeb.mnUserId > 0 Then
' If we are using the Pick Address list to EDIT an address, there will be a hidden control of userAddId
If myWeb.moRequest("userAddId") <> "" Then
oXform.Instance.AppendChild(oXform.moPageXML.CreateElement("nUserAddressId"))
oXform.Instance.LastChild.InnerText = myWeb.moRequest("userAddId")
oXform.Instance.AppendChild(oXform.moPageXML.CreateElement("nUserAddressType"))
oXform.Instance.LastChild.InnerText = myWeb.moRequest("userAddType")
Else
' Holy large where statement, Batman! But how on earth else do we tell is a cart address is the same as a user address?
Dim value As String
Dim contact As XmlElement = oXform.Instance.SelectSingleNode("tblCartContact")
cWhere = ""
If NodeState(contact, "cContactName", , , , , , value) <> NotInstantiated Then cWhere &= " and cContactName='" & SqlFmt(value) & "' "
If NodeState(contact, "cContactCompany", , , , , , value) <> NotInstantiated Then cWhere &= " and cContactCompany='" & SqlFmt(value) & "' "
If NodeState(contact, "cContactAddress", , , , , , value) <> NotInstantiated Then cWhere &= " and cContactAddress='" & SqlFmt(value) & "' "
If NodeState(contact, "cContactCity", , , , , , value) <> NotInstantiated Then cWhere &= " and cContactCity='" & SqlFmt(value) & "' "
If NodeState(contact, "cContactState", , , , , , value) <> NotInstantiated Then cWhere &= " and cContactState='" & SqlFmt(value) & "' "
If NodeState(contact, "cContactZip", , , , , , value) <> NotInstantiated Then cWhere &= " and cContactZip='" & SqlFmt(value) & "' "
If NodeState(contact, "cContactCountry", , , , , , value) <> NotInstantiated Then cWhere &= " and cContactCountry='" & SqlFmt(value) & "' "
'cWhere = " and cContactName='" & SqlFmt(oXform.Instance.SelectSingleNode("tblCartContact/cContactName").InnerText) & "' " & _
' "and cContactCompany='" & SqlFmt(oXform.Instance.SelectSingleNode("tblCartContact/cContactCompany").InnerText) & "' " & _
' "and cContactAddress='" & SqlFmt(oXform.Instance.SelectSingleNode("tblCartContact/cContactAddress").InnerText) & "' " & _
' "and cContactCity='" & SqlFmt(oXform.Instance.SelectSingleNode("tblCartContact/cContactCity").InnerText) & "' " & _
' "and cContactState='" & SqlFmt(oXform.Instance.SelectSingleNode("tblCartContact/cContactState").InnerText) & "' " & _
' "and cContactZip='" & SqlFmt(oXform.Instance.SelectSingleNode("tblCartContact/cContactZip").InnerText) & "' " & _
' "and cContactCountry='" & SqlFmt(oXform.Instance.SelectSingleNode("tblCartContact/cContactCountry").InnerText) & "' "
oDs = moDBHelper.GetDataSet("select * from tblCartContact where nContactDirId = " & CStr(myWeb.mnUserId) & cWhere, "tblCartContact")
If oDs.Tables("tblCartContact").Rows.Count > 0 Then
oXform.Instance.AppendChild(oXform.moPageXML.CreateElement("nUserAddressId"))
oXform.Instance.LastChild.InnerText = oDs.Tables("tblCartContact").Rows(0).Item("nContactKey")
oXform.Instance.AppendChild(oXform.moPageXML.CreateElement("nUserAddressType"))
oXform.Instance.LastChild.InnerText = oDs.Tables("tblCartContact").Rows(0).Item("cContactType")
End If
End If
End If
'add some proceedual fields to instance
oElmt = oXform.moPageXML.CreateElement(cCmdType)
oXform.Instance.AppendChild(oElmt)
oElmt = oXform.moPageXML.CreateElement("cIsDelivery")
oXform.Instance.AppendChild(oElmt)
If cmd2 <> "" Then
oElmt = oXform.moPageXML.CreateElement("cmd2")
oElmt.InnerText = "True"
oXform.Instance.AppendChild(oElmt)
End If
' If oXform.isSubmitted And cAddressType = myWeb.moRequest.Form("cContactType") Then
If oXform.isSubmitted Then
oXform.updateInstanceFromRequest()
oXform.validate()
myWeb.moSession("isDelivery") = myWeb.moRequest("isDelivery")
'Catch for space as country
If Not myWeb.moRequest("cContactCountry") = Nothing Then
If myWeb.moRequest("cContactCountry").Trim = "" Then
oXform.valid = False
oXform.addNote("cContactCountry", xForm.noteTypes.Alert, "Please select a country", True)
End If
End If
If oXform.valid Then
'the form is valid so update it - add a check for timed out session (mnCartId = 0)
If ContactId > 0 Then
'ID is specified so we simply update ignore relation to the cart
moDBHelper.setObjectInstance(Web.dbHelper.objectTypes.CartContact, oXform.Instance, ContactId)
Else
If mnCartId > 0 Then
'test if we have a address of this type against the order..!
'ssql = "Select nContactKey from tblCartContact where cContactType = '" & cAddressType & "' and nContactCartid=" & mnCartId
'Dim sContactKey1 As String = moDBHelper.ExeProcessSqlScalar(ssql)
'moDBHelper.setObjectInstance(Web.dbHelper.objectTypes.CartContact, oXform.Instance, sContactKey1)
'Step through for multiple addresses
Dim bSavedDelivery As Boolean = False
'check for collection options
If IsNumeric(myWeb.moRequest("cIsDelivery")) Then
'Save the delivery method allready
Dim cSqlUpdate As String = ""
Dim oDrCollectionOptions2 As SqlDataReader = moDBHelper.getDataReader("select * from tblCartShippingMethods where nShipOptKey = " & myWeb.moRequest("cIsDelivery"))
Do While oDrCollectionOptions2.Read()
Dim cShippingDesc As String = oDrCollectionOptions2.Item("cShipOptName").ToString() & "-" &
oDrCollectionOptions2.Item("cShipOptCarrier").ToString() & "</span>"
Dim nShippingCost As Double = CDbl("0" & oDrCollectionOptions2.Item("nShipOptCost"))
cSqlUpdate = "UPDATE tblCartOrder SET cShippingDesc='" & SqlFmt(cShippingDesc) & "', nShippingCost=" & SqlFmt(nShippingCost) & ", nShippingMethodId = " & myWeb.moRequest("cIsDelivery") & " WHERE nCartOrderKey=" & mnCartId
Loop
moDBHelper.ExeProcessSql(cSqlUpdate)
bSavedDelivery = True
Else
'If it exists and we are here means we may have changed the Delivery address
'country
RemoveDeliveryOption(mnCartId)
End If
For Each oElmt In oXform.Instance.SelectNodes("tblCartContact")
Dim cThisAddressType As String = oElmt.SelectSingleNode("cContactType").InnerText
sSql = "Select nContactKey from tblCartContact where cContactType = '" & cThisAddressType & "' and nContactCartid=" & mnCartId
Dim sContactKey1 As String = moDBHelper.ExeProcessSqlScalar(sSql)
Dim saveInstance As XmlElement = moPageXml.CreateElement("instance")
saveInstance.AppendChild(oElmt.Clone)
moDBHelper.setObjectInstance(Web.dbHelper.objectTypes.CartContact, saveInstance, sContactKey1)
If cThisAddressType = "Delivery Address" Then bSavedDelivery = True
Next
'if the option save Delivery is true then
If bSavedDelivery = False Then
If myWeb.moRequest("cIsDelivery") = "True" Or (mbNoDeliveryAddress And cAddressType = "Billing Address") Then
If myWeb.moRequest("cIsDelivery") = "True" And mnShippingRootId > 0 Then
'mnShippingRootId
'check if the submitted country matches one in the delivery list
Dim oCheckElmt As XmlElement = moPageXml.CreateElement("ValidCountries")
ListShippingLocations(oCheckElmt)
Dim cCountry As String = oXform.Instance.SelectSingleNode("tblCartContact/cContactCountry").InnerText
If oCheckElmt.SelectSingleNode("descendant-or-self::TreeItem[@Name='" & cCountry & "' or @name='" & cCountry & "' or @nameShort='" & cCountry & "']") Is Nothing Then
oXform.valid = False
oXform.addNote("cContactCountry", xForm.noteTypes.Alert, "Cannot Deliver to this country. please select another.", True)
End If
End If
If oXform.valid Then
sSql = "Select nContactKey from tblCartContact where cContactType = 'Delivery Address' and nContactCartid=" & mnCartId
Dim sContactKey2 As String = moDBHelper.ExeProcessSqlScalar(sSql)
oXform.Instance.SelectSingleNode("tblCartContact/cContactType").InnerText = "Delivery Address"
moDBHelper.setObjectInstance(Web.dbHelper.objectTypes.CartContact, oXform.Instance, sContactKey2)
'going to set it back to a billing address
oXform.Instance.SelectSingleNode("tblCartContact/cContactType").InnerText = "Billing Address"
End If
End If
End If
If Not oXform.Instance.SelectSingleNode("tblCartContact/cContactEmail[@optOut='true']") Is Nothing Then
moDBHelper.AddInvalidEmail(oXform.Instance.SelectSingleNode("tblCartContact/cContactEmail[@optOut='true']").InnerText)
End If
Else
' Throw an error to indicate that the user has timed out
mnProcessError = 4
End If
End If
End If
End If
oXform.addValues()
Return oXform
Catch ex As Exception
returnException(mcModuleName, "contactXform", ex, "", cProcessInfo, gbDebug)
Return Nothing
End Try
End Function
Public Overridable Function pickContactXform(ByVal cAddressType As String, Optional ByVal submitPrefix As String = "", Optional ByVal cCmdType As String = "cartCmd", Optional ByVal cCmdAction As String = "") As xForm
PerfMon.Log("Cart", "pickContactXform")
Dim oXform As xForm = New xForm
Dim oReturnForm As xForm
Dim oGrpElmt As XmlElement
Dim oDs As DataSet
Dim oDs2 As DataSet
Dim oDr As DataRow
Dim cSql As String = ""
'Dim sAddressHtml As String
Dim cProcessInfo As String = ""
Dim contactId As Long = 0
Dim billingAddId As Long = 0
Dim oContactXform As xForm = Nothing
Dim bDontPopulate As Boolean = False
Dim bBillingSet As Boolean = False
Dim newSubmitPrefix As String = submitPrefix
Dim newAddressType As String = cAddressType
Dim contactFormCmd2 As String = ""
Try
' Get any existing addresses for user
' Changed this so it gets any
'Check if updated primiary billing address, (TS added order by reverse order added)
cSql = "select * from tblCartContact where nContactDirId = " & CStr(myWeb.mnUserId) & " and nContactCartId = 0 order by cContactType ASC, nContactKey DESC"
oDs = moDBHelper.GetDataSet(cSql, "tblCartContact")
For Each oDr In oDs.Tables("tblCartContact").Rows
If billingAddId = 0 Then billingAddId = oDr.Item("nContactKey")
If myWeb.moRequest("cartDeleditAddress" & oDr.Item("nContactKey")) <> "" Then
submitPrefix = "cartDel"
cAddressType = "Delivery Address"
newSubmitPrefix = "cartDel"
newAddressType = "Delivery Address"
'ensure we hit this next time through...
cCmdAction = "Delivery"
contactFormCmd2 = "cartDeleditAddress" & oDr.Item("nContactKey")
ElseIf myWeb.moRequest(submitPrefix & "addDelivery" & oDr.Item("nContactKey")) <> "" Then
bDontPopulate = True
newSubmitPrefix = "cartDel"
newAddressType = "Delivery Address"
cCmdAction = "Delivery"
ElseIf myWeb.moRequest(submitPrefix & "editAddress" & oDr.Item("nContactKey")) <> "" Then
If Not billingAddId = oDr.Item("nContactKey") Then
newSubmitPrefix = "cartDel"
newAddressType = "Delivery Address"
Else
'we are editing a billing address and want to ensure we dont get a double form.
If mcBillingAddressXform.Contains("BillingAndDeliveryAddress.xml") Then
mcBillingAddressXform = mcBillingAddressXform.Replace("BillingAndDeliveryAddress.xml", "BillingAddress.xml")
End If
'ensure we hit this next time through...
cCmdAction = "Billing"
contactFormCmd2 = submitPrefix & "editAddress" & oDr.Item("nContactKey")
bDontPopulate = True
'we specifiy a contactID to ensure we don't update the cart addresses just the ones on file.
contactId = oDr.Item("nContactKey")
End If
ElseIf myWeb.moRequest(submitPrefix & "useBilling" & oDr.Item("nContactKey")) <> "" Then
contactId = setCurrentBillingAddress(myWeb.mnUserId, oDr.Item("nContactKey"))
bBillingSet = True
End If
Next
If myWeb.moRequest(submitPrefix & "addNewAddress") <> "" Then
contactId = 0
bDontPopulate = True
End If
oContactXform = contactXform(newAddressType, newSubmitPrefix & "Address", cCmdType, cCmdAction, bDontPopulate, contactId, contactFormCmd2)
'Build the xform
oXform.moPageXML = moPageXml
oXform.NewFrm(cAddressType)
oXform.valid = False
' oReturnForm is going to be the form returned at the end of the function.
oReturnForm = oXform
If Not bBillingSet Then
contactId = setCurrentBillingAddress(myWeb.mnUserId, 0)
Else
cSql = "select * from tblCartContact where nContactDirId = " & CStr(myWeb.mnUserId) & " and nContactCartId = 0 order by cContactType ASC"
oDs = moDBHelper.GetDataSet(cSql, "tblCartContact")
End If
If oDs.Tables("tblCartContact").Rows.Count > 0 Then
' Create the instance
oXform.Instance.AppendChild(oXform.moPageXML.CreateElement("cContactId"))
' Add a value if an address has been selected
oDs2 = moDBHelper.GetDataSet("select * from tblCartContact where nContactCartId = " & CStr(Me.mnCartId) & " and cContactType = '" & cAddressType & "'", "tblCartContact")
If oDs2.Tables("tblCartContact").Rows.Count > 0 Then
oXform.Instance.SelectSingleNode("cContactId").InnerText = oDs2.Tables("tblCartContact").Rows(0).Item("nContactKey")
End If
oXform.Instance.AppendChild(oXform.moPageXML.CreateElement("cIsDelivery"))
oXform.submission("contact", mcPagePath & cCmdType & "=" & cCmdAction, "POST", )
oGrpElmt = oXform.addGroup(oXform.moXformElmt, "address", , "")
oXform.addInput(oGrpElmt, "addType", False, "", "hidden")
oGrpElmt.LastChild.AppendChild(oGrpElmt.OwnerDocument.CreateElement("value"))
oGrpElmt.LastChild.FirstChild.InnerText = cAddressType
'oXform.addSelect1(oGrpElmt, "cContactId", True, "Select", "multiline", xForm.ApperanceTypes.Full)
'oXform.addBind("cContactId", "cContactId")
'Add Collection Options
If moDBHelper.checkTableColumnExists("tblCartShippingMethods", "bCollection") Then
'Add Collection options
'Get the collection delivery options
Dim oDrCollectionOptions As SqlDataReader = moDBHelper.getDataReader("select * from tblCartShippingMethods where bCollection = 1")
If oDrCollectionOptions.HasRows Then
Dim oCollectionGrp As XmlElement
oCollectionGrp = oXform.addGroup(oGrpElmt, "CollectionOptions", "collection-options", "")
Do While oDrCollectionOptions.Read()
Dim OptLabel As String = oDrCollectionOptions.Item("cShipOptName").ToString() & " - " & oDrCollectionOptions.Item("cShipOptCarrier").ToString()
oXform.addSubmit(oCollectionGrp, "collect", OptLabel, "CollectionID_" & oDrCollectionOptions.Item("nShipOptKey").ToString(), "collect btn-success principle", "fa-truck")
Loop
End If
End If
For Each oDr In oDs.Tables("tblCartContact").Rows
Dim oAddressGrp As XmlElement
oAddressGrp = oXform.addGroup(oGrpElmt, "addressGrp-" & oDr.Item("nContactKey"), "addressGrp", "")
oXform.addDiv(oAddressGrp, moDBHelper.getObjectInstance(dbHelper.objectTypes.CartContact, oDr.Item("nContactKey")), "pickAddress")
If billingAddId <> oDr.Item("nContactKey") Then
oXform.addSubmit(oAddressGrp, "editAddress", "Edit", "cartDeleditAddress" & oDr.Item("nContactKey"), "edit", "fa-pencil")
oXform.addSubmit(oAddressGrp, "removeAddress", "Del", submitPrefix & "deleteAddress" & oDr.Item("nContactKey"), "delete", "fa-trash-o")
Else
oXform.addSubmit(oAddressGrp, "editAddress", "Edit", submitPrefix & "editAddress" & oDr.Item("nContactKey"), "edit", "fa-pencil")
' oXform.addSubmit(oAddressGrp, "removeAddress", "Delete", submitPrefix & "deleteAddress" & oDr.Item("nContactKey"), "delete")
End If
If oDr.Item("cContactType") <> "Billing Address" Then
oXform.addSubmit(oAddressGrp, oDr.Item("nContactKey"), "Use as Billing", submitPrefix & "useBilling" & oDr.Item("nContactKey"), "setAsBilling")
Else
If LCase(moCartConfig("NoDeliveryAddress")) = "on" Then
oXform.addSubmit(oAddressGrp, "addNewAddress", "Add New Address", submitPrefix & "addNewAddress", "addnew", "fa-plus")
Else
oXform.addSubmit(oAddressGrp, "addNewAddress", "Add New Billing Address", submitPrefix & "addNewAddress", "addnew", "fa-plus")
End If
If Not (LCase(moCartConfig("NoDeliveryAddress"))) = "on" Then
oXform.addSubmit(oGrpElmt, oDr.Item("nContactKey"), "New Delivery Address", submitPrefix & "addDelivery" & oDr.Item("nContactKey"), "setAsBilling btn-success principle", "fa-plus")
End If
End If
If LCase(moCartConfig("NoDeliveryAddress")) = "on" Then
oXform.addSubmit(oAddressGrp, oDr.Item("nContactKey"), "Use This Address", submitPrefix & "contact" & oDr.Item("nContactKey"))
Else
oXform.addSubmit(oAddressGrp, oDr.Item("nContactKey"), "Deliver To This Address", submitPrefix & "contact" & oDr.Item("nContactKey"))
End If
Next
' Check if the form has been submitted
If oXform.isSubmitted Then
oXform.updateInstanceFromRequest()
Dim forCollection As Boolean = False
If moDBHelper.checkTableColumnExists("tblCartShippingMethods", "bCollection") Then
Dim bCollectionSelected = False
Dim oDrCollectionOptions As SqlDataReader = moDBHelper.getDataReader("select * from tblCartShippingMethods where bCollection = 1")
If oDrCollectionOptions.HasRows Then
Do While oDrCollectionOptions.Read()
If myWeb.moRequest("CollectionID_" & oDrCollectionOptions.Item("nShipOptKey")) <> "" Then
bCollectionSelected = True
'Set the shipping option
Dim cShippingDesc As String = oDrCollectionOptions.Item("cShipOptName").ToString() & "-" &
oDrCollectionOptions.Item("cShipOptCarrier").ToString()
Dim nShippingCost As Double = CDbl("0" & oDrCollectionOptions.Item("nShipOptCost"))
Dim cSqlUpdate As String
cSqlUpdate = "UPDATE tblCartOrder SET cShippingDesc='" & SqlFmt(cShippingDesc) & "', nShippingCost=" & SqlFmt(nShippingCost) & ", nShippingMethodId = " & oDrCollectionOptions.Item("nShipOptKey") & " WHERE nCartOrderKey=" & mnCartId
moDBHelper.ExeProcessSql(cSqlUpdate)
forCollection = True
oXform.valid = True
oContactXform.valid = True
mbNoDeliveryAddress = True
Dim NewInstance As XmlElement = moPageXml.CreateElement("instance")
Dim delXform As xForm = contactXform("Delivery Address")
NewInstance.InnerXml = delXform.Instance.SelectSingleNode("tblCartContact").OuterXml
'dissassciate from user so not shown again
NewInstance.SelectSingleNode("tblCartContact/nContactDirId").InnerText = ""
NewInstance.SelectSingleNode("tblCartContact/cContactName").InnerText = oDrCollectionOptions.Item("cShipOptName").ToString()
NewInstance.SelectSingleNode("tblCartContact/cContactCompany").InnerText = oDrCollectionOptions.Item("cShipOptCarrier").ToString()
NewInstance.SelectSingleNode("tblCartContact/cContactCountry").InnerText = moCartConfig("DefaultDeliveryCountry")
Dim collectionContactID As String
collectionContactID = moDBHelper.setObjectInstance(dbHelper.objectTypes.CartContact, NewInstance)
useSavedAddressesOnCart(billingAddId, CInt(collectionContactID))
Return oReturnForm
End If
Loop
If bCollectionSelected = False Then
RemoveDeliveryOption(mnCartId)
End If
End If
End If
For Each oDr In oDs.Tables("tblCartContact").Rows
If myWeb.moRequest(submitPrefix & "contact" & oDr.Item("nContactKey")) <> "" Then
contactId = oDr.Item("nContactKey")
'Save Behaviour
oXform.valid = True
ElseIf myWeb.moRequest(submitPrefix & "addDelivery" & oDr.Item("nContactKey")) <> "" Then
contactId = oDr.Item("nContactKey")
oXform.valid = False
oContactXform.valid = False
ElseIf myWeb.moRequest(submitPrefix & "editAddress" & oDr.Item("nContactKey")) <> "" Then
contactId = oDr.Item("nContactKey")
'edit Behavior
ElseIf myWeb.moRequest(submitPrefix & "deleteAddress" & oDr.Item("nContactKey")) <> "" Then
contactId = oDr.Item("nContactKey")
'delete Behavior
moDBHelper.DeleteObject(dbHelper.objectTypes.CartContact, contactId)
'remove from form
oXform.moXformElmt.SelectSingleNode("descendant-or-self::group[@ref='addressGrp-" & contactId & "']").ParentNode.RemoveChild(oXform.moXformElmt.SelectSingleNode("descendant-or-self::group[@ref='addressGrp-" & contactId & "']"))
oXform.valid = False
ElseIf myWeb.moRequest(submitPrefix & "useBilling" & oDr.Item("nContactKey")) <> "" Then
'we have handled this at the top
oXform.valid = False
End If
Next
' Check if the contactID is populated
If contactId = 0 Then
oXform.addNote("address", xForm.noteTypes.Alert, "You must select an address from the list")
Else
' Get the selected address
Dim oMatches() As DataRow = oDs.Tables("tblCartContact").Select("nContactKey = " & contactId)
If Not oMatches Is Nothing Then
Dim oMR As DataRow = oMatches(0)
If Not bDontPopulate Then
' Update the contactXform with the address
oContactXform.Instance.SelectSingleNode("tblCartContact/cContactType").InnerText = newAddressType
oContactXform.Instance.SelectSingleNode("tblCartContact/cContactName").InnerText = oMR.Item("cContactName") & ""
oContactXform.Instance.SelectSingleNode("tblCartContact/cContactCompany").InnerText = oMR.Item("cContactCompany") & ""
oContactXform.Instance.SelectSingleNode("tblCartContact/cContactAddress").InnerText = oMR.Item("cContactAddress") & ""
oContactXform.Instance.SelectSingleNode("tblCartContact/cContactCity").InnerText = oMR.Item("cContactCity") & ""
oContactXform.Instance.SelectSingleNode("tblCartContact/cContactState").InnerText = oMR.Item("cContactState") & ""
oContactXform.Instance.SelectSingleNode("tblCartContact/cContactZip").InnerText = oMR.Item("cContactZip") & ""
oContactXform.Instance.SelectSingleNode("tblCartContact/cContactCountry").InnerText = oMR.Item("cContactCountry") & ""
oContactXform.Instance.SelectSingleNode("tblCartContact/cContactTel").InnerText = oMR.Item("cContactTel") & ""
oContactXform.Instance.SelectSingleNode("tblCartContact/cContactFax").InnerText = oMR.Item("cContactFax") & ""
oContactXform.Instance.SelectSingleNode("tblCartContact/cContactEmail").InnerText = oMR.Item("cContactEmail") & ""
oContactXform.Instance.SelectSingleNode("cIsDelivery").InnerText = oXform.Instance.SelectSingleNode("cIsDelivery").InnerText
oContactXform.resetXFormUI()
oContactXform.addValues()
' Add hidden values for the parent address
If myWeb.moRequest(submitPrefix & "editAddress" & contactId) <> "" Then
oGrpElmt = oContactXform.moXformElmt.SelectSingleNode("group")
oContactXform.addInput(oGrpElmt, "userAddId", False, "", "hidden")
oGrpElmt.LastChild.AppendChild(oGrpElmt.OwnerDocument.CreateElement("value"))
oGrpElmt.LastChild.FirstChild.InnerText = contactId 'oMR.Item("nContactKey")
oContactXform.addInput(oGrpElmt, "userAddType", False, "", "hidden")
oGrpElmt.LastChild.AppendChild(oGrpElmt.OwnerDocument.CreateElement("value"))
oGrpElmt.LastChild.FirstChild.InnerText = newAddressType 'oMR.Item("cContactType")
End If
End If
End If
End If
End If
oXform.addValues()
End If
If oContactXform.valid = False And oXform.valid = False Then
'both forms are invalid so we need to output one of the forms.
If myWeb.moRequest(submitPrefix & "editAddress" & contactId) <> "" Or myWeb.moRequest(submitPrefix & "addDelivery" & contactId) <> "" Or oContactXform.isSubmitted Then
'we are editing an address so show the contactXform or a contactXform has been submitted to
oReturnForm = oContactXform
Else
' We need to show the pick list if and only if :
' 1. It has addresses in it
' 2. There is no request to Add
If oXform.moXformElmt.SelectSingleNode("/model/instance").HasChildNodes() And Not (myWeb.moRequest(submitPrefix & "addNewAddress") <> "") Then
oReturnForm = oXform
Else
' Add address needs to clear out the existing xForm
If myWeb.moRequest(submitPrefix & "addNewAddress") <> "" Then
oContactXform.resetXFormUI()
oContactXform.addValues()
End If
oReturnForm = oContactXform
End If
End If
Else
' If pick address has been submitted, then we have a contactXform that has not been submitted, and therefore not saved. Let's save it.
If myWeb.moRequest(submitPrefix & "contact" & contactId) <> "" Then
useSavedAddressesOnCart(billingAddId, contactId)
'skip delivery
oContactXform.moXformElmt.SetAttribute("cartCmd", "ChoosePaymentShippingOption")
End If
If myWeb.moRequest(submitPrefix & "addDelivery" & contactId) <> "" Then
useSavedAddressesOnCart(billingAddId, 0)
'remove the deliver from the instance if it is there
Dim oNode As XmlNode
For Each oNode In oContactXform.Instance.SelectNodes("tblCartContact[cContactType='Delivery Address']")
oNode.ParentNode.RemoveChild(oNode)
Next
End If
If oContactXform.valid = False Then
oContactXform.valid = True
oContactXform.moXformElmt.SetAttribute("persistAddress", "false")
End If
If myWeb.moRequest(submitPrefix & "editAddress" & billingAddId) <> "" And oContactXform.valid Then
'We have edited a billing address and need to output the pickForm
oReturnForm = oXform
Else
'pass through the xform to make transparent
oReturnForm = oContactXform
End If
End If
'TS not sure if required after rewrite, think it is deleting addresses unessesarily.
'If Not (oReturnForm Is Nothing) AndAlso oReturnForm.valid AndAlso oReturnForm.isSubmitted Then
' ' There seems to be an issue with duplicate addresses being submitted by type against an order.
' ' This script finds the duplciates and nullifies them (i.e. sets their cartid to be 0).
' cSql = "UPDATE tblCartContact SET nContactCartId = 0 " _
' & "FROM (SELECT nContactCartId id, cContactType type, MAX(nContactKey) As latest FROM dbo.tblCartContact WHERE nContactCartId <> 0 GROUP BY nContactCartId, cContactType HAVING COUNT(*) >1) dup " _
' & "INNER JOIN tblCartContact c ON c.nContactCartId = dup.id AND c.cContactType = dup.type AND c.nContactKey <> dup.latest"
' cProcessInfo = "Clear Duplicate Addresses: " & cSql
' moDBHelper.ExeProcessSql(cSql)
'End If
Return oReturnForm
Catch ex As Exception
returnException(mcModuleName, "pickContactXform", ex, "", cProcessInfo, gbDebug)
Return Nothing
End Try
End Function
''' <summary>
''' Each user need only have a single active billing address
''' </summary>
''' <param name="UserId"></param>
''' <param name="ContactId"></param>
''' <returns>If Contact ID = 0 then uses last updated</returns>
''' <remarks></remarks>
Public Function setCurrentBillingAddress(ByVal UserId As Long, ByVal ContactId As Long) As Long
Dim cProcessInfo As String = ""
Dim cSql As String
Dim oDS As DataSet
Dim oDr As DataRow
Try
If myWeb.mnUserId > 0 Then
If ContactId <> 0 Then
moDBHelper.updateInstanceField(dbHelper.objectTypes.CartContact, ContactId, "cContactType", "Billing Address")
End If
'Check for othersss
cSql = "select c.* from tblCartContact c inner JOIN tblAudit a on a.nAuditKey = c.nAuditId where nContactDirId = " & CStr(myWeb.mnUserId) & " and nContactCartId = 0 and cContactType='Billing Address' order by a.dUpdateDate DESC"
oDS = moDBHelper.GetDataSet(cSql, "tblCartContact")
For Each oDr In oDS.Tables("tblCartContact").Rows
If ContactId = "0" Then
'gets the top one
ContactId = oDr("nContactKey")
End If
If oDr("nContactKey") <> ContactId Then
moDBHelper.ExeProcessSql("update tblCartContact set cContactType='Previous Billing Address' where nContactKey=" & oDr("nContactKey"))
End If
Next
Return ContactId
Else
Return 0
End If
Catch ex As Exception
returnException(mcModuleName, "setCurrentBillingAddress", ex, "", cProcessInfo, gbDebug)
Return Nothing
End Try
End Function
Public Sub useSavedAddressesOnCart(ByVal billingId As Long, ByVal deliveryId As Long)
Dim cProcessInfo As String = ""
Dim oDs As DataSet
Dim odr As DataRow
Try
'get id's of addresses allready assoicated with this cart they are being replaced
Dim sSql As String
sSql = "select nContactKey, cContactType, nAuditKey from tblCartContact inner join tblAudit a on nAuditId = a.nAuditKey where nContactCartId = " & CStr(mnCartId)
oDs = moDBHelper.GetDataSet(sSql, "tblCartContact")
Dim savedBillingId As String = ""
Dim savedDeliveryId As String = ""
Dim savedBillingAuditId As String = ""
Dim savedDeliveryAuditId As String = ""
For Each odr In oDs.Tables("tblCartContact").Rows
If odr("cContactType") = "Billing Address" Then
If savedBillingId <> "" Then
'delete any duplicates
moDBHelper.DeleteObject(dbHelper.objectTypes.CartContact, odr("nContactKey"))
Else
savedBillingId = odr("nContactKey")
savedBillingAuditId = odr("nAuditKey")
End If
End If
If odr("cContactType") = "Delivery Address" Then
If savedDeliveryId <> "" Then
'delete any duplicates
moDBHelper.DeleteObject(dbHelper.objectTypes.CartContact, odr("nContactKey"))
Else
savedDeliveryId = odr("nContactKey")
savedDeliveryAuditId = odr("nAuditKey")
End If
End If
Next
oDs = Nothing
'this should update the billing address
Dim billInstance As XmlElement = myWeb.moPageXml.CreateElement("Instance")
billInstance.InnerXml = moDBHelper.getObjectInstance(dbHelper.objectTypes.CartContact, billingId)
billInstance.SelectSingleNode("*/nContactKey").InnerText = savedBillingId
billInstance.SelectSingleNode("*/nContactCartId").InnerText = mnCartId
billInstance.SelectSingleNode("*/cContactType").InnerText = "Billing Address"
billInstance.SelectSingleNode("*/nAuditId").InnerText = savedBillingAuditId
billInstance.SelectSingleNode("*/nAuditKey").InnerText = savedBillingAuditId
moDBHelper.setObjectInstance(Web.dbHelper.objectTypes.CartContact, billInstance)
'now get the submitted delivery id instance
If Not deliveryId = 0 Then
Dim delInstance As XmlElement = myWeb.moPageXml.CreateElement("Instance")
delInstance.InnerXml = moDBHelper.getObjectInstance(dbHelper.objectTypes.CartContact, deliveryId)
delInstance.SelectSingleNode("*/nContactKey").InnerText = savedDeliveryId
delInstance.SelectSingleNode("*/nContactCartId").InnerText = mnCartId
delInstance.SelectSingleNode("*/cContactType").InnerText = "Delivery Address"
delInstance.SelectSingleNode("*/nAuditId").InnerText = savedDeliveryAuditId
delInstance.SelectSingleNode("*/nAuditKey").InnerText = savedDeliveryAuditId
moDBHelper.setObjectInstance(Web.dbHelper.objectTypes.CartContact, delInstance)
End If
'here we should update the current instance so we can calculate the shipping later
Catch ex As Exception
returnException(mcModuleName, "useAddressesOnCart", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Protected Sub UpdateExistingUserAddress(ByRef oContactXform As xForm)
PerfMon.Log("Cart", "UpdateExistingUserAddress")
' Check if it exists - if it does then update the nContactKey node
Dim oTempCXform As New xForm
Dim cProcessInfo As String = ""
Dim sSql As String
Dim nCount As Long
Dim oAddElmt As XmlElement
Dim oElmt As XmlElement
Dim oElmt2 As XmlElement
Try
For Each oAddElmt In oContactXform.Instance.SelectNodes("tblCartContact")
If oAddElmt.GetAttribute("saveToUser") <> "false" Then
'does this address allready exist?
sSql = "select count(nContactKey) from tblCartContact where nContactDirId = " & myWeb.mnUserId & " and nContactCartId = 0 " & _
" and cContactName = '" & SqlFmt(oAddElmt.SelectSingleNode("cContactName").InnerText) & "'" & _
" and cContactCompany = '" & SqlFmt(oAddElmt.SelectSingleNode("cContactCompany").InnerText) & "'" & _
" and cContactAddress = '" & SqlFmt(oAddElmt.SelectSingleNode("cContactAddress").InnerText) & "'" & _
" and cContactCity = '" & SqlFmt(oAddElmt.SelectSingleNode("cContactCity").InnerText) & "'" & _
" and cContactState = '" & SqlFmt(oAddElmt.SelectSingleNode("cContactState").InnerText) & "'" & _
" and cContactZip = '" & SqlFmt(oAddElmt.SelectSingleNode("cContactZip").InnerText) & "'" & _
" and cContactCountry = '" & SqlFmt(oAddElmt.SelectSingleNode("cContactCountry").InnerText) & "'" & _
" and cContactTel = '" & SqlFmt(oAddElmt.SelectSingleNode("cContactTel").InnerText) & "'" & _
" and cContactFax = '" & SqlFmt(oAddElmt.SelectSingleNode("cContactFax").InnerText) & "'" & _
" and cContactEmail = '" & SqlFmt(oAddElmt.SelectSingleNode("cContactEmail").InnerText) & "'" & _
" and cContactXml = '" & SqlFmt(oAddElmt.SelectSingleNode("cContactXml").InnerXml) & "'"
nCount = moDBHelper.ExeProcessSqlScalar(sSql)
If nCount = 0 Then
oTempCXform.NewFrm("tblCartContact")
oTempCXform.Instance.InnerXml = oAddElmt.OuterXml
Dim tempInstance As XmlElement = moPageXml.CreateElement("instance")
Dim ContactType As String = oTempCXform.Instance.SelectSingleNode("tblCartContact/cContactType").InnerText
' Update/add the address to the table
' make sure we are inserting by reseting the key
If myWeb.moRequest("userAddId") <> "" And ContactType = myWeb.moRequest("userAddType") Then
'get the id we are updating
Dim updateId As Long = myWeb.moRequest("userAddId")
oTempCXform.Instance.SelectSingleNode("tblCartContact/nContactKey").InnerText = updateId
'We need to populate the auditId feilds
tempInstance.InnerXml = moDBHelper.getObjectInstance(dbHelper.objectTypes.CartContact, updateId)
'update with the fields specified
For Each oElmt In oTempCXform.Instance.SelectNodes("tblCartContact/*[node()!='']")
If Not (oElmt.Name = "nAuditId" Or oElmt.Name = "nAuditKey") Then
oElmt2 = tempInstance.SelectSingleNode("tblCartContact/" & oElmt.Name)
oElmt2.InnerXml = oElmt.InnerXml
End If
Next
oTempCXform.Instance = tempInstance
Else
oTempCXform.Instance.SelectSingleNode("tblCartContact/nContactKey").InnerText = "0"
oTempCXform.Instance.SelectSingleNode("tblCartContact/nAuditId").InnerText = ""
oTempCXform.Instance.SelectSingleNode("tblCartContact/nAuditKey").InnerText = ""
End If
'separate from cart
oTempCXform.Instance.SelectSingleNode("tblCartContact/nContactCartId").InnerText = "0"
'link to user
oTempCXform.Instance.SelectSingleNode("tblCartContact/nContactDirId").InnerText = myWeb.mnUserId
moDBHelper.setObjectInstance(Web.dbHelper.objectTypes.CartContact, oTempCXform.Instance)
End If
End If
Next
setCurrentBillingAddress(myWeb.mnUserId, 0)
Catch ex As Exception
returnException(mcModuleName, "UpdateExistingUserAddress", ex, "", cProcessInfo, gbDebug)
Finally
oTempCXform = Nothing
End Try
End Sub
Public Overridable Function discountsProcess(ByVal oElmt As XmlElement) As String
Dim sCartCmd As String = mcCartCmd
Dim cProcessInfo As String = ""
Dim bAlwaysAskForDiscountCode As Boolean = IIf(LCase(moCartConfig("AlwaysAskForDiscountCode")) = "on", True, False)
Try
myWeb.moSession("cLogonCmd") = ""
GetCart(oElmt)
If moDiscount.bHasPromotionalDiscounts Or bAlwaysAskForDiscountCode Then
Dim oDiscountsXform As xForm = discountsXform("discountsForm", "?pgid=" & myWeb.mnPageId & "&cartCmd=Discounts")
If oDiscountsXform.valid = False Then
moPageXml.SelectSingleNode("/Page/Contents").AppendChild(oDiscountsXform.moXformElmt)
Else
oElmt.RemoveAll()
sCartCmd = "RedirectSecure"
End If
Else
oElmt.RemoveAll()
sCartCmd = "RedirectSecure"
End If
'if this returns Notes then we display for otherwise we goto processflow
Return sCartCmd
Catch ex As Exception
returnException(mcModuleName, "discountsProcess", ex, "", cProcessInfo, gbDebug)
Return ""
End Try
End Function
Public Overridable Function discountsXform(Optional ByVal formName As String = "notesForm", Optional ByVal action As String = "?cartCmd=Discounts") As xForm
PerfMon.Log("Cart", "notesXform")
' this function is called for the collection from a form and addition to the database
' of address information.
Dim oDs As DataSet
Dim oRow As DataRow
Dim sSql As String
Dim oFormGrp As XmlElement
Dim sXmlContent As String
Dim promocodeElement As XmlElement = Nothing
Dim usedPromocodeFromExternalRef As Boolean = False
Dim cProcessInfo As String = ""
Try
'Get notes XML
Dim oXform As xForm = New xForm
oXform.moPageXML = moPageXml
'oXform.NewFrm(formName)
Dim cDiscountsXform As String = moCartConfig("DiscountsXform")
If cDiscountsXform <> "" Then
If Not oXform.load(cDiscountsXform) Then
oXform.NewFrm(formName)
oFormGrp = oXform.addGroup(oXform.moXformElmt, "discounts", , "Missing File: " & mcNotesXForm)
Else
'add missing submission or submit buttons
If oXform.moXformElmt.SelectSingleNode("model/submission") Is Nothing Then
'If oXform.moXformElmt.SelectSingleNode("model/instance/submission") Is Nothing Then
oXform.submission(formName, action, "POST", "return form_check(this);")
End If
If oXform.moXformElmt.SelectSingleNode("descendant-or-self::submit") Is Nothing Then
oXform.addSubmit(oXform.moXformElmt, "Submit", "Continue")
End If
Dim oSubmit As XmlElement = oXform.moXformElmt.SelectSingleNode("descendant-or-self::submit")
If Not oSubmit Is Nothing Then
oFormGrp = oSubmit.ParentNode
Else
oFormGrp = oXform.addGroup(oXform.moXformElmt, "Promo", , "Enter Promotional Code")
End If
If oXform.Instance.SelectSingleNode("descendant-or-self::PromotionalCode") Is Nothing Then
If oXform.Instance.FirstChild.SelectSingleNode("Notes") Is Nothing Then
oXform.Instance.FirstChild.AppendChild(oXform.Instance.OwnerDocument.CreateElement("Notes"))
End If
promocodeElement = oXform.Instance.FirstChild.AppendChild(oXform.Instance.OwnerDocument.CreateElement("PromotionalCode"))
oXform.addInput(oFormGrp, "Notes/PromotionalCode", False, "Promotional Code", "")
End If
End If
Else
oXform.NewFrm(formName)
oXform.submission(formName, action, "POST", "return form_check(this);")
oXform.Instance.InnerXml = "<Notes/>"
oFormGrp = oXform.addGroup(oXform.moXformElmt, "notes", , "")
If oXform.Instance.FirstChild.SelectSingleNode("Notes") Is Nothing Then
oXform.Instance.FirstChild.AppendChild(oXform.Instance.OwnerDocument.CreateElement("Notes"))
End If
promocodeElement = oXform.Instance.FirstChild.AppendChild(oXform.Instance.OwnerDocument.CreateElement("PromotionalCode"))
oXform.addInput(oFormGrp, "Notes/PromotionalCode", False, "Promotional Code", "")
oXform.addSubmit(oFormGrp, "Submit", "Continue")
End If
'Open database for reading and writing
' External promo code checks
If promocodeElement IsNot Nothing And Not String.IsNullOrEmpty(Me.promocodeFromExternalRef) Then
usedPromocodeFromExternalRef = True
End If
sSql = "select * from tblCartOrder where nCartOrderKey=" & mnCartId
oDs = moDBHelper.getDataSetForUpdate(sSql, "Order", "Cart")
For Each oRow In oDs.Tables("Order").Rows
'load existing notes from Cart
sXmlContent = oRow("cClientNotes") & ""
If sXmlContent <> "" Then
oXform.Instance.InnerXml = sXmlContent
End If
'If this xform is being submitted
Dim isSubmitted As Boolean = oXform.isSubmitted
If isSubmitted Or myWeb.moRequest("Submit") = "Continue" _
Or myWeb.moRequest("Submit") = "Search" Then
oXform.updateInstanceFromRequest()
oXform.validate()
If oXform.valid = True Then
oRow("cClientNotes") = oXform.Instance.InnerXml
mcCartCmd = "RedirectSecure"
End If
ElseIf Not isSubmitted And usedPromocodeFromExternalRef Then
' If an external promo code is in the system then save it, even before it has been submitted
promocodeElement = oXform.Instance.SelectSingleNode("//PromotionalCode")
If promocodeElement IsNot Nothing Then
promocodeElement.InnerText = Me.promocodeFromExternalRef
oRow("cClientNotes") = oXform.Instance.InnerXml
' Promo code is officially in the process, so we can ditch any transitory variables.
Me.promocodeFromExternalRef = ""
End If
End If
Next
moDBHelper.updateDataset(oDs, "Order", True)
oDs.Clear()
oDs = Nothing
oXform.addValues()
Return oXform
Catch ex As Exception
returnException(mcModuleName, "notesXform", ex, "", cProcessInfo, gbDebug)
Return Nothing
End Try
End Function
Public Overridable Function notesProcess(ByVal oElmt As XmlElement) As String
Dim sCartCmd As String = mcCartCmd
Dim cProcessInfo As String = ""
Try
'should never get this far for subscriptions unless logged on.
If Not moSubscription Is Nothing Then
If Not moSubscription.CheckCartForSubscriptions(mnCartId, myWeb.mnUserId) Then
If myWeb.mnUserId = 0 Then
sCartCmd = "LogonSubs"
End If
End If
End If
myWeb.moSession("cLogonCmd") = ""
GetCart(oElmt)
If mcNotesXForm <> "" Then
Dim oNotesXform As xForm = notesXform("notesForm", mcPagePath & "cartCmd=Notes", oElmt)
If oNotesXform.valid = False Then
moPageXml.SelectSingleNode("/Page/Contents").AppendChild(oNotesXform.moXformElmt)
Else
oElmt.RemoveAll()
sCartCmd = "SkipAddress"
End If
Else
oElmt.RemoveAll()
sCartCmd = "SkipAddress"
End If
'if this returns Notes then we display for otherwise we goto processflow
Return sCartCmd
Catch ex As Exception
returnException(mcModuleName, "notesProcess", ex, "", cProcessInfo, gbDebug)
Return ""
End Try
End Function
Public Overridable Function notesXform(Optional ByVal formName As String = "notesForm", Optional ByVal action As String = "?cartCmd=Notes", Optional oCart As XmlElement = Nothing) As xForm
PerfMon.Log("Cart", "notesXform")
' this function is called for the collection from a form and addition to the database
' of address information.
Dim oDs As DataSet
Dim oRow As DataRow
Dim sSql As String
Dim oFormGrp As XmlElement
Dim sXmlContent As String
Dim promocodeElement As XmlElement = Nothing
Dim cProcessInfo As String = ""
Try
'Get notes XML
Dim oXform As xForm = New xForm
oXform.moPageXML = moPageXml
'
Select Case LCase(mcNotesXForm)
Case "default"
oXform.NewFrm(formName)
oXform.submission(formName, action, "POST", "return form_check(this);")
oXform.Instance.InnerXml = "<Notes/>"
oFormGrp = oXform.addGroup(oXform.moXformElmt, "notes", , "Please enter any comments on your order here")
oXform.addTextArea(oFormGrp, "Notes/Notes", False, "Notes", "")
If moDiscount.bHasPromotionalDiscounts Then
'If oXform.Instance.FirstChild.SelectSingleNode("Notes") Is Nothing Then
If Eonic.Tools.Xml.firstElement(oXform.Instance).SelectSingleNode("Notes") Is Nothing Then
'oXform.Instance.FirstChild.AppendChild(oXform.Instance.OwnerDocument.CreateElement("Notes"))
'Eonic.Tools.Xml.firstElement(oXform.Instance).AppendChild(oXform.Instance.OwnerDocument.CreateElement("Notes"))
Eonic.Tools.Xml.firstElement(oXform.moXformElmt.SelectSingleNode("descendant-or-self::instance")).AppendChild(oXform.Instance.OwnerDocument.CreateElement("Notes"))
End If
'oXform.Instance.FirstChild.AppendChild(oXform.Instance.OwnerDocument.CreateElement("PromotionalCode"))
'Eonic.Tools.Xml.firstElement(oXform.Instance).AppendChild(oXform.Instance.OwnerDocument.CreateElement("PromotionalCode"))
promocodeElement = Eonic.Tools.Xml.firstElement(oXform.moXformElmt.SelectSingleNode("descendant-or-self::instance")).AppendChild(oXform.Instance.OwnerDocument.CreateElement("PromotionalCode"))
oXform.addInput(oFormGrp, "Notes/PromotionalCode", False, "Promotional Code", "")
End If
oXform.addSubmit(oFormGrp, "Submit", "Continue")
Case "productspecific"
Dim oOrderLine As XmlElement
Dim oMasterFormXml As XmlElement = Nothing
For Each oOrderLine In oCart.SelectNodes("Item")
'get any Xform related to cart items
Dim contentId As Long = oOrderLine.GetAttribute("contentId")
sSql = "select nContentKey from tblContent c inner join tblContentRelation cr on cr.nContentChildId = c.nContentKey where c.cContentSchemaName = 'xform' and cr.nContentParentId = " & contentId
Dim FormId As Long = myWeb.moDbHelper.GetDataValue(sSql)
If Not FormId = Nothing Then
Dim oFormXml As XmlElement = moPageXml.CreateElement("NewXform")
oFormXml.InnerXml = myWeb.moDbHelper.getContentBrief(FormId)
If oMasterFormXml Is Nothing Then
'Duplication the items for each qty in cart
Dim n As Integer = 1
Dim oItem As XmlElement = oFormXml.SelectSingleNode("descendant-or-self::Item")
oItem.SetAttribute("name", oOrderLine.SelectSingleNode("Name").InnerText)
oItem.SetAttribute("stockCode", oOrderLine.SelectSingleNode("productDetail/StockCode").InnerText)
oItem.SetAttribute("number", n)
Dim i As Integer
For i = 2 To oOrderLine.GetAttribute("quantity")
n = n + 1
Dim newItem As XmlElement = oItem.CloneNode(True)
newItem.SetAttribute("number", n)
oItem.ParentNode.InsertAfter(newItem, oItem.ParentNode.LastChild)
Next
oMasterFormXml = oFormXml
Else
'behaviour for appending additioanl product forms
Dim n As Integer = 1
Dim oItem As XmlElement = oFormXml.SelectSingleNode("descendant-or-self::Item")
oItem.SetAttribute("name", oOrderLine.SelectSingleNode("Name").InnerText)
oItem.SetAttribute("stockCode", oOrderLine.SelectSingleNode("productDetail/StockCode").InnerText)
oItem.SetAttribute("number", n)
Dim i As Integer
For i = 1 To oOrderLine.GetAttribute("quantity")
Dim newItem As XmlElement = oItem.CloneNode(True)
newItem.SetAttribute("number", n)
n = n + 1
Dim AddAfterNode As XmlElement = oMasterFormXml.SelectSingleNode("Content/model/instance/Notes/Item[last()]")
AddAfterNode.ParentNode.InsertAfter(newItem, AddAfterNode)
Next
End If
End If
Next
'Load with repeats.
If Not oMasterFormXml Is Nothing Then
oXform.load(oMasterFormXml.SelectSingleNode("descendant-or-self::Content"), True)
End If
If moDiscount.bHasPromotionalDiscounts Then
Dim oNotesRoot As XmlElement = oXform.Instance.SelectSingleNode("Notes")
If oNotesRoot.SelectSingleNode("PromotionalCode") Is Nothing Then
promocodeElement = oNotesRoot.AppendChild(oMasterFormXml.OwnerDocument.CreateElement("PromotionalCode"))
End If
oFormGrp = oXform.moXformElmt.SelectSingleNode("descendant-or-self::group[1]")
oXform.addInput(oFormGrp, "Notes/PromotionalCode", False, "Promotional Code", "")
End If
If Not oXform.moXformElmt Is Nothing Then
'add missing submission or submit buttons
If oXform.moXformElmt.SelectSingleNode("model/submission") Is Nothing Then
'If oXform.moXformElmt.SelectSingleNode("model/instance/submission") Is Nothing Then
oXform.submission(formName, action, "POST", "return form_check(this);")
End If
If oXform.moXformElmt.SelectSingleNode("descendant-or-self::submit") Is Nothing Then
oXform.addSubmit(oXform.moXformElmt, "Submit", "Continue")
End If
oXform.moXformElmt.SetAttribute("type", "xform")
oXform.moXformElmt.SetAttribute("name", "notesForm")
Else
oXform.NewFrm(formName)
oFormGrp = oXform.addGroup(oXform.moXformElmt, "notes", , "Missing File: Product has no form request ")
'force to true so we move on.
oXform.valid = True
End If
Case Else
If Not oXform.load(mcNotesXForm) Then
oXform.NewFrm(formName)
oFormGrp = oXform.addGroup(oXform.moXformElmt, "notes", , "Missing File: " & mcNotesXForm)
Else
'add missing submission or submit buttons
If oXform.moXformElmt.SelectSingleNode("model/submission") Is Nothing Then
'If oXform.moXformElmt.SelectSingleNode("model/instance/submission") Is Nothing Then
oXform.submission(formName, action, "POST", "return form_check(this);")
End If
If oXform.moXformElmt.SelectSingleNode("descendant-or-self::submit") Is Nothing Then
oXform.addSubmit(oXform.moXformElmt, "Submit", "Continue")
End If
If moDiscount.bHasPromotionalDiscounts Then
Dim oSubmit As XmlElement = oXform.moXformElmt.SelectSingleNode("descendant-or-self::submit")
If Not oSubmit Is Nothing Then
oFormGrp = oSubmit.ParentNode
Else
oFormGrp = oXform.addGroup(oXform.moXformElmt, "Promo", , "Enter Promotional Code")
End If
If oXform.Instance.SelectSingleNode("descendant-or-self::PromotionalCode") Is Nothing Then
'If oXform.Instance.FirstChild.SelectSingleNode("Notes") Is Nothing Then
If Eonic.Tools.Xml.firstElement(oXform.Instance).SelectSingleNode("Notes") Is Nothing Then
'ocNode.AppendChild(moPageXml.ImportNode(Eonic.Tools.Xml.firstElement(newXml.DocumentElement), True))
'oXform.Instance.FirstChild.AppendChild(oXform.Instance.OwnerDocument.CreateElement("Notes"))
'Eonic.Tools.Xml.firstElement(oXform.Instance).AppendChild(oXform.Instance.OwnerDocument.CreateElement("Notes"))
Eonic.Tools.Xml.firstElement(oXform.moXformElmt.SelectSingleNode("descendant-or-self::instance")).AppendChild(oXform.Instance.OwnerDocument.CreateElement("Notes"))
End If
'oXform.Instance.FirstChild.AppendChild(oXform.Instance.OwnerDocument.CreateElement("PromotionalCode"))
'Eonic.Tools.Xml.firstElement(oXform.Instance).AppendChild(oXform.Instance.OwnerDocument.CreateElement("PromotionalCode"))
promocodeElement = Eonic.Tools.Xml.firstElement(oXform.moXformElmt.SelectSingleNode("descendant-or-self::instance")).AppendChild(oXform.Instance.OwnerDocument.CreateElement("PromotionalCode"))
oXform.addInput(oFormGrp, "Notes/PromotionalCode", False, "Promotional Code", "")
End If
End If
End If
End Select
' External promo code checks
If promocodeElement IsNot Nothing And Not String.IsNullOrEmpty(Me.promocodeFromExternalRef) Then
promocodeElement.InnerText = Me.promocodeFromExternalRef
' Promo code is officially in the process, so we can ditch any transitory variables.
Me.promocodeFromExternalRef = ""
End If
'Open database for reading and writing
sSql = "select * from tblCartOrder where nCartOrderKey=" & mnCartId
oDs = moDBHelper.getDataSetForUpdate(sSql, "Order", "Cart")
For Each oRow In oDs.Tables("Order").Rows
'load existing notes from Cart
sXmlContent = oRow("cClientNotes") & ""
If sXmlContent <> "" Then
Dim savedInstance As XmlElement = moPageXml.CreateElement("instance")
moPageXml.PreserveWhitespace = False
savedInstance.InnerXml = sXmlContent
If oXform.Instance.SelectNodes("*/*").Count > savedInstance.SelectNodes("*/*").Count Then
' we have a greater amount of childnodes we need to merge....
Dim oStepElmt As XmlElement
Dim oStepElmtCount As Integer = 0
'step through each child element and replace where attributes match, leaving final
For Each oStepElmt In oXform.Instance.SelectNodes("*/*")
Dim attXpath As String = oStepElmt.Name
Dim attElmt As XmlAttribute
Dim bfirst As Boolean = True
For Each attElmt In oStepElmt.Attributes
If bfirst Then attXpath = attXpath & "["
If Not bfirst Then attXpath = attXpath & " and "
attXpath = attXpath + "@" & attElmt.Name & "='" & attElmt.Value & "'"
bfirst = False
Next
If Not bfirst Then attXpath = attXpath & "]"
If Not savedInstance.SelectSingleNode("*/" & attXpath) Is Nothing Then
oStepElmt.ParentNode.ReplaceChild(savedInstance.SelectSingleNode("*/" & attXpath).CloneNode(True), oStepElmt)
End If
oStepElmtCount = oStepElmtCount + 1
Next
Else
oXform.Instance.InnerXml = sXmlContent
End If
End If
'If this xform is being submitted
If oXform.isSubmitted Or myWeb.moRequest("Submit") = "Continue" Or myWeb.moRequest("Submit") = "Search" Then
oXform.updateInstanceFromRequest()
oXform.validate()
If oXform.valid = True Then
oRow("cClientNotes") = oXform.Instance.InnerXml
'if we are useing the notes as a search facility for products
If myWeb.moRequest("Submit") = "Search" Then
mcCartCmd = "Search"
Else
mcCartCmd = "SkipAddress"
End If
End If
End If
Next
moDBHelper.updateDataset(oDs, "Order", True)
oDs.Clear()
oDs = Nothing
oXform.addValues()
notesXform = oXform
Catch ex As Exception
returnException(mcModuleName, "notesXform", ex, "", cProcessInfo, gbDebug)
Return Nothing
End Try
End Function
Public Overridable Function optionsXform(ByRef cartElmt As XmlElement) As xForm
PerfMon.Log("Cart", "optionsXform")
Dim ods As DataSet
Dim ods2 As DataSet
Dim oRow As DataRow
Dim sSql As String
Dim sSql2 As String
Dim oGrpElmt As XmlElement
Dim nQuantity As Short
Dim nAmount As Double
Dim nWeight As Double
Dim cDestinationCountry As String
Dim nShippingCost As Double
Dim cShippingDesc As String = ""
Dim cHidden As String = ""
Dim bHideDelivery As Boolean = False
Dim bHidePayment As Boolean = False
Dim bFirstRow As Boolean = True
' Dim oElmt As XmlElement
Dim sProcessInfo As String = ""
Dim bForceValidation As Boolean = False
Dim bAdjustTitle As Boolean = True
'Dim cFormURL As String
'Dim cExternalGateway As String
'Dim cBillingAddress As String
'Dim cPaymentResponse As String
Dim cProcessInfo As String = ""
Dim bAddTerms As Boolean = False
Dim oPay As PaymentProviders
Dim bDeny As Boolean = False
Dim AllowedPaymentMethods As New Collections.Specialized.StringCollection
If moPay Is Nothing Then
oPay = New PaymentProviders(myWeb)
Else
oPay = moPay
End If
oPay.mcCurrency = mcCurrency
Dim cDenyFilter As String = ""
Try
If moDBHelper.checkTableColumnExists("tblCartShippingPermission", "nPermLevel") Then
bDeny = True
cDenyFilter = " and nPermLevel <> 0"
End If
If moCartConfig("TermsContentId") = "" And moCartConfig("TermsAndConditions") = "" Then bAddTerms = False
nQuantity = CInt("0" & cartElmt.GetAttribute("itemCount"))
nAmount = CDbl("0" & cartElmt.GetAttribute("totalNet")) - CDbl("0" & cartElmt.GetAttribute("shippingCost"))
nWeight = CDbl("0" & cartElmt.GetAttribute("weight"))
Dim nRepeatAmount As Double = CDbl("0" & cartElmt.GetAttribute("repeatPrice"))
Dim nShippingMethodId As Integer = CDbl("0" & cartElmt.GetAttribute("shippingType"))
If cartElmt.SelectSingleNode("Contact[@type='Delivery Address']/Country") Is Nothing Then
sProcessInfo = "Destination Country not specified in Delivery Address"
cDestinationCountry = ""
Dim sTarget As String = ""
Dim oAddressElmt As XmlElement
For Each oAddressElmt In cartElmt.SelectSingleNode("Contact[@type='Delivery Address']/*")
If sTarget <> "" Then sTarget = sTarget & ", "
sTarget = sTarget & oAddressElmt.InnerText
Next
Err.Raise(1004, "getParentCountries", sTarget & " Destination Country not specified in Delivery Address.")
Else
cDestinationCountry = cartElmt.SelectSingleNode("Contact[@type='Delivery Address']/Country").InnerText
End If
'Go and collect the valid shipping options available for this order
ods = getValidShippingOptionsDS(cDestinationCountry, nAmount, nQuantity, nWeight)
Dim oOptXform As New xForm
oOptXform.moPageXML = moPageXml
If Not oOptXform.load("/xforms/Cart/Options.xml") Then
oOptXform.NewFrm("optionsForm")
oOptXform.Instance.InnerXml = "<nShipOptKey/><cPaymentMethod/><terms/><confirmterms>No</confirmterms><tblCartOrder><cShippingDesc/></tblCartOrder>"
If Not (moCartConfig("TermsContentId") = "" And moCartConfig("TermsAndConditions") = "") Then
bAddTerms = True
End If
Else
bAdjustTitle = False
bForceValidation = True
If Not (moCartConfig("TermsContentId") = "" And moCartConfig("TermsAndConditions") = "") Then
bAddTerms = True
End If
End If
' If there is already a submit item in the form, then maintain the event node
' Would rather that this whole form obeyed xform validation, but hey-ho. Ali
Dim cEvent As String = ""
Dim oSub As XmlElement = oOptXform.model.SelectSingleNode("submission")
If oSub Is Nothing Then
cEvent = "return form_check(this);"
Else
cEvent = oSub.GetAttribute("event")
'now remove the origional submit node coz we are going to add another. TS.
oSub.ParentNode.RemoveChild(oSub)
End If
oOptXform.submission("optionsForm", mcPagePath & "cartCmd=ChoosePaymentShippingOption", "POST", cEvent)
Dim cUserGroups As String = ""
Dim rowCount As Long = ods.Tables("Option").Rows.Count
If bDeny Then
'remove denied delivery methods
If myWeb.mnUserId > 0 Then
Dim grpElmt As XmlElement
For Each grpElmt In moPageXml.SelectNodes("/Page/User/Group[@isMember='yes']")
cUserGroups = cUserGroups & grpElmt.GetAttribute("id") & ","
Next
cUserGroups = cUserGroups & gnAuthUsers
Else
cUserGroups = gnNonAuthUsers
End If
For Each oRow In ods.Tables("Option").Rows
Dim denyCount As Integer = 0
If bDeny Then
Dim permSQL As String
'check option is not denied
If Not cUserGroups = "" Then
permSQL = "select count(*) from tblCartShippingPermission where nPermLevel = 0 and nDirId IN (" & cUserGroups & ") and nShippingMethodId = " & oRow("nShipOptKey")
denyCount = moDBHelper.ExeProcessSqlScalar(permSQL)
End If
End If
If denyCount > 0 Then
oRow.Delete()
rowCount = rowCount - 1
End If
Next
End If
If rowCount = 0 Then
oOptXform.addGroup(oOptXform.moXformElmt, "options")
cartElmt.SetAttribute("errorMsg", 3)
Else
' Build the Payment Options
'if the root group element exists i.e. we have loaded a form in.
oGrpElmt = oOptXform.moXformElmt.SelectSingleNode("group")
If oGrpElmt Is Nothing Then
oGrpElmt = oOptXform.addGroup(oOptXform.moXformElmt, "options", "", "Select Delivery Option")
End If
' Even if there is only 1 option we still want to display it, if it is a non-zero value - the visitor should know the description of their delivery option
If ods.Tables("Option").Rows.Count = 1 Then
For Each oRow In ods.Tables("Option").Rows
If IsDBNull(oRow("nShippingTotal")) Then
cHidden = " hidden"
bHideDelivery = True
ElseIf oRow("nShippingTotal") = 0 Then
cHidden = " hidden"
bHideDelivery = True
Else
nShippingCost = oRow("nShippingTotal")
nShippingCost = CDbl(FormatNumber(nShippingCost, 2, Microsoft.VisualBasic.TriState.True, Microsoft.VisualBasic.TriState.False, Microsoft.VisualBasic.TriState.False))
oOptXform.addInput(oGrpElmt, "nShipOptKey", False, oRow("cShipOptName") & "-" & oRow("cShipOptCarrier"), "hidden")
oOptXform.Instance.SelectSingleNode("nShipOptKey").InnerText = oRow("nShipOptKey")
oOptXform.addInput(oGrpElmt, "tblCartOrder/cShippingDesc", False, "Shipping Method", "readonly")
Dim DescElement As XmlElement = oOptXform.Instance.SelectSingleNode("tblCartOrder/cShippingDesc")
DescElement.InnerText = oRow("cShipOptName") & "-" & oRow("cShipOptCarrier") & ": " & mcCurrencySymbol & FormatNumber(nShippingCost, 2)
DescElement.SetAttribute("name", oRow("cShipOptName"))
DescElement.SetAttribute("carrier", oRow("cShipOptCarrier"))
DescElement.SetAttribute("cost", FormatNumber(nShippingCost, 2))
End If
Next
Else
oOptXform.addSelect1(oGrpElmt, "nShipOptKey", False, "Delivery Method", "radios multiline", xForm.ApperanceTypes.Full)
bFirstRow = True
Dim nLastID As Integer = 0
' If selected shipping method is still in those available (because we now )
If nShippingMethodId <> 0 Then
Dim bIsAvail As Boolean = False
For Each oRow In ods.Tables("Option").Rows
If Not oRow.RowState = DataRowState.Deleted Then
If nShippingMethodId = oRow("nShipOptKey") Then
bIsAvail = True
End If
End If
Next
'If not then strip it out.
If bIsAvail = False Then
nShippingMethodId = 0
cartElmt.SetAttribute("shippingType", "0")
cartElmt.SetAttribute("shippingCost", "")
cartElmt.SetAttribute("shippingDesc", "")
Dim cSqlUpdate As String = "UPDATE tblCartOrder SET cShippingDesc= null, nShippingCost=null, nShippingMethodId = 0 WHERE nCartOrderKey=" & mnCartId
moDBHelper.ExeProcessSql(cSqlUpdate)
End If
End If
'If shipping option selected is collection don't change
Dim bCollectionSelected As Boolean = False
For Each oRow In ods.Tables("Option").Rows
If Not oRow.RowState = DataRowState.Deleted Then
If Not IsDBNull(oRow("bCollection")) Then
If oRow("nShipOptKey") = nShippingMethodId And oRow("bCollection") = True Then
bCollectionSelected = True
End If
End If
End If
Next
For Each oRow In ods.Tables("Option").Rows
If Not oRow.RowState = DataRowState.Deleted Then
If (Not oRow("nShipOptKey") = nLastID) Then
If bCollectionSelected Then
'if collection allready selected... Show only this option
If nShippingMethodId = oRow("nShipOptKey") Then
oOptXform.Instance.SelectSingleNode("nShipOptKey").InnerText = CStr(oRow("nShipOptKey"))
nShippingCost = CDbl("0" & oRow("nShippingTotal"))
nShippingCost = CDbl(FormatNumber(nShippingCost, 2, Microsoft.VisualBasic.TriState.True, Microsoft.VisualBasic.TriState.False, Microsoft.VisualBasic.TriState.False))
Dim optElmt As XmlElement = oOptXform.addOption((oGrpElmt.LastChild), oRow("cShipOptName") & "-" & oRow("cShipOptCarrier") & ": " & mcCurrencySymbol & FormatNumber(nShippingCost, 2), oRow("nShipOptKey"))
Dim optLabel As XmlElement = optElmt.SelectSingleNode("label")
optLabel.SetAttribute("name", oRow("cShipOptName"))
optLabel.SetAttribute("carrier", oRow("cShipOptCarrier"))
optLabel.SetAttribute("cost", FormatNumber(nShippingCost, 2))
End If
Else
Dim bShowMethod As Boolean = True
'Don't show if a collection method
If moDBHelper.checkTableColumnExists("tblCartShippingMethods", "bCollection") Then
If Not IsDBNull(oRow("bCollection")) Then
If oRow("bCollection") = True Then
bShowMethod = False
End If
End If
End If
If bShowMethod Then
If bFirstRow Then oOptXform.Instance.SelectSingleNode("nShipOptKey").InnerText = CStr(oRow("nShipOptKey"))
nShippingCost = CDbl("0" & oRow("nShippingTotal"))
nShippingCost = CDbl(FormatNumber(nShippingCost, 2, Microsoft.VisualBasic.TriState.True, Microsoft.VisualBasic.TriState.False, Microsoft.VisualBasic.TriState.False))
Dim optElmt As XmlElement = oOptXform.addOption((oGrpElmt.LastChild), oRow("cShipOptName") & "-" & oRow("cShipOptCarrier") & ": " & mcCurrencySymbol & FormatNumber(nShippingCost, 2), oRow("nShipOptKey"))
Dim optLabel As XmlElement = optElmt.SelectSingleNode("label")
optLabel.SetAttribute("name", oRow("cShipOptName"))
optLabel.SetAttribute("carrier", oRow("cShipOptCarrier"))
optLabel.SetAttribute("cost", FormatNumber(nShippingCost, 2))
bFirstRow = False
nLastID = oRow("nShipOptKey")
End If
End If
End If
End If
Next
End If
ods = Nothing
' Allow to Select Multiple Payment Methods or just one
Dim oPaymentCfg As XmlNode
oPaymentCfg = WebConfigurationManager.GetWebApplicationSection("eonic/payment")
'more than one..
bFirstRow = True
If Not oPaymentCfg Is Nothing Then
If nAmount = 0 And nRepeatAmount = 0 Then
oOptXform.Instance.SelectSingleNode("cPaymentMethod").InnerText = "No Charge"
Dim oSelectElmt As XmlElement = oOptXform.addSelect1(oGrpElmt, "cPaymentMethod", False, "Payment Method", "radios multiline", xForm.ApperanceTypes.Full)
oOptXform.addOption(oSelectElmt, "No Charge", "No Charge")
bHidePayment = False
AllowedPaymentMethods.Add("No Charge")
ElseIf oPaymentCfg.SelectNodes("provider").Count > 1 Then
Dim oSelectElmt As XmlElement
oSelectElmt = oOptXform.moXformElmt.SelectSingleNode("descendant-or-self::select1[@ref='cPaymentMethod']")
If oSelectElmt Is Nothing Then
oSelectElmt = oOptXform.addSelect1(oGrpElmt, "cPaymentMethod", False, "Payment Method", "radios multiline", xForm.ApperanceTypes.Full)
End If
Dim nOptCount As Integer = oPay.getPaymentMethods(oOptXform, oSelectElmt, nAmount, mcPaymentMethod)
'Code Moved to Get PaymentMethods
If nOptCount = 0 Then
oOptXform.valid = False
oOptXform.addNote(oGrpElmt, xForm.noteTypes.Alert, "There is no method of payment available for your account - please contact the site administrator.")
ElseIf nOptCount = 1 Then
'hide the options
oSelectElmt.SetAttribute("class", "hidden")
End If
'step throught the payment methods to set as allowed.
Dim oOptElmt As XmlElement
For Each oOptElmt In oSelectElmt.SelectNodes("item")
AllowedPaymentMethods.Add(oOptElmt.SelectSingleNode("value").InnerText)
Next
ElseIf oPaymentCfg.SelectNodes("provider").Count = 1 Then
'or just one
If oPay.HasRepeatPayments Then
Dim oSelectElmt As XmlElement = oOptXform.addSelect1(oGrpElmt, "cPaymentMethod", False, "Payment Method", "radios multiline", xForm.ApperanceTypes.Full)
oPay.ReturnRepeatPayments(oPaymentCfg.SelectSingleNode("provider/@name").InnerText, oOptXform, oSelectElmt)
oOptXform.addOption(oSelectElmt, oPaymentCfg.SelectSingleNode("provider/description").Attributes("value").Value, oPaymentCfg.SelectSingleNode("provider").Attributes("name").Value)
bHidePayment = False
AllowedPaymentMethods.Add(oPaymentCfg.SelectSingleNode("provider/@name").InnerText)
Else
bHidePayment = True
oOptXform.addInput(oGrpElmt, "cPaymentMethod", False, oPaymentCfg.SelectSingleNode("provider/@name").InnerText, "hidden")
oOptXform.Instance.SelectSingleNode("cPaymentMethod").InnerText = oPaymentCfg.SelectSingleNode("provider/@name").InnerText
AllowedPaymentMethods.Add(oPaymentCfg.SelectSingleNode("provider/@name").InnerText)
End If
'bHidePayment = True
'oOptXform.addInput(oGrpElmt, "cPaymentMethod", False, oPaymentCfg.SelectSingleNode("provider/@name").InnerText, "hidden")
'oOptXform.instance.SelectSingleNode("cPaymentMethod").InnerText = oPaymentCfg.SelectSingleNode("provider/@name").InnerText
'Dim oSelectElmt As XmlElement = oOptXform.addSelect1(oGrpElmt, "cPaymentMethod", False, "Payment Method", "radios multiline", xForm.ApperanceTypes.Full)
'oPay.ReturnRepeatPayments(oPaymentCfg.SelectSingleNode("provider/@name").InnerText, oOptXform, oSelectElmt)
Else
oOptXform.valid = False
oOptXform.addNote(oGrpElmt, xForm.noteTypes.Alert, "There is no method of payment setup on this site - please contact the site administrator.")
End If
Else
oOptXform.valid = False
oOptXform.addNote(oGrpElmt, xForm.noteTypes.Alert, "There is no method of payment setup on this site - please contact the site administrator.")
End If
Dim cTermsTitle As String = "Terms and Conditions"
' Adjust the group title
If bAdjustTitle Then
Dim cGroupTitle As String = "Select Delivery and Payment Option"
If bHideDelivery And bHidePayment Then cGroupTitle = "Terms and Conditions"
If bHideDelivery And Not (bHidePayment) Then cGroupTitle = "Select Payment Option"
If Not (bHideDelivery) And bHidePayment Then cGroupTitle = "Select Delivery Option"
oGrpElmt.SelectSingleNode("label").InnerText = cGroupTitle
' Just so we don't show the terms and conditions title twice
If cGroupTitle = "Terms and Conditions" Then
cTermsTitle = ""
End If
End If
If bAddTerms Then
If oGrpElmt.SelectSingleNode("*[@ref='terms']") Is Nothing Then
oOptXform.addTextArea(oGrpElmt, "terms", False, cTermsTitle, "readonly terms-and-condiditons")
End If
If oGrpElmt.SelectSingleNode("*[@ref='confirmterms']") Is Nothing Then
oOptXform.addSelect(oGrpElmt, "confirmterms", False, " ", "", xForm.ApperanceTypes.Full)
oOptXform.addOption(oGrpElmt.LastChild, "I agree to the Terms and Conditions", "Agree")
End If
If CInt("0" & moCartConfig("TermsContentId")) > 0 Then
Dim termsElmt As New XmlDocument
termsElmt.LoadXml(moDBHelper.getContentBrief(moCartConfig("TermsContentId")))
mcTermsAndConditions = termsElmt.DocumentElement.InnerXml
Else
mcTermsAndConditions = moCartConfig("TermsAndConditions")
End If
If mcTermsAndConditions Is Nothing Then mcTermsAndConditions = ""
oOptXform.Instance.SelectSingleNode("terms").InnerXml = mcTermsAndConditions
End If
oOptXform.addSubmit(oGrpElmt, "optionsForm", "Make Secure Payment")
End If
oOptXform.valid = False
If AllowedPaymentMethods.Contains(myWeb.moRequest("cPaymentMethod")) Then ' equates to is submitted
If myWeb.moRequest("confirmterms") = "Agree" Or Not bAddTerms Then
'Save Submissions
If mcPaymentMethod = "" Then
mcPaymentMethod = myWeb.moRequest("cPaymentMethod")
End If
'if we have a profile split it out, allows for more than one set of settings for each payment method, only done for SecPay right now.
If InStr(mcPaymentMethod, "-") Then
Dim aPayMth() As String = Split(mcPaymentMethod, "-")
mcPaymentMethod = aPayMth(0)
mcPaymentProfile = aPayMth(1)
End If
sSql2 = "select * from tblCartOrder where nCartOrderKey = " & mnCartId
ods2 = moDBHelper.GetDataSet(sSql2, "Order", "Cart")
Dim oRow2 As DataRow, cSqlUpdate As String
For Each oRow2 In ods2.Tables("Order").Rows
Dim nShipOptKey As Long
If Not myWeb.moRequest("nShipOptKey") Is Nothing Then
oRow2("nShippingMethodId") = myWeb.moRequest("nShipOptKey")
End If
nShipOptKey = oRow2("nShippingMethodId")
sSql = "select * from tblCartShippingMethods "
sSql = sSql & " where nShipOptKey = " & nShipOptKey
ods = moDBHelper.GetDataSet(sSql, "Order", "Cart")
For Each oRow In ods.Tables("Order").Rows
cShippingDesc = oRow("cShipOptName") & "-" & oRow("cShipOptCarrier")
nShippingCost = oRow("nShipOptCost")
cSqlUpdate = "UPDATE tblCartOrder SET cShippingDesc='" & SqlFmt(cShippingDesc) & "', nShippingCost=" & SqlFmt(nShippingCost) & ", nShippingMethodId = " & nShipOptKey & " WHERE nCartOrderKey=" & mnCartId
moDBHelper.ExeProcessSql(cSqlUpdate)
Next
' update the cart xml
updateTotals(cartElmt, nAmount, nShippingCost, nShipOptKey)
ods2 = Nothing
If bForceValidation Then
oOptXform.updateInstanceFromRequest()
oOptXform.validate()
Else
oOptXform.valid = True
End If
Next
Else
oOptXform.addNote("confirmterms", xForm.noteTypes.Alert, "You must agree to the terms and conditions to proceed")
End If
End If
If oOptXform.valid Then
'If we have any order notes we save them
If Not oOptXform.Instance.SelectSingleNode("Notes") Is Nothing Then
'Open database for reading and writing
sSql = "select * from tblCartOrder where nCartOrderKey=" & mnCartId
ods = moDBHelper.getDataSetForUpdate(sSql, "Order", "Cart")
For Each oRow In ods.Tables("Order").Rows
oRow("cClientNotes") = oOptXform.Instance.SelectSingleNode("Notes").OuterXml
moDBHelper.updateDataset(ods, "Order", True)
Next
ods.Clear()
ods = Nothing
End If
End If
oOptXform.addValues()
Return oOptXform
Catch ex As Exception
returnException(mcModuleName, "optionsXform", ex, "", cProcessInfo, gbDebug)
Return Nothing
End Try
End Function
Public Function getParentCountries(ByRef sTarget As String, ByRef nIndex As Integer) As String
PerfMon.Log("Cart", "getParentCountries")
Dim oDr As SqlDataReader
Dim sSql As String
Dim oLocations As Hashtable
Dim nTargetId As Integer
Dim sCountryList As String
Dim nLocKey As Integer
Dim cProcessInfo As String = ""
Try
' First let's go and get a list of all the countries and their parent id's
sSql = "SELECT * FROM tblCartShippingLocations ORDER BY nLocationParId"
oDr = moDBHelper.getDataReader(sSql)
sCountryList = ""
nTargetId = -1
If oDr.HasRows Then
oLocations = New Hashtable
While oDr.Read
Dim arrLoc(3) As String
arrLoc(0) = oDr("nLocationParId") & ""
If IsDBNull(oDr("nLocationTaxRate")) Or Not (IsNumeric(oDr("nLocationTaxRate"))) Then
arrLoc(2) = 0
Else
arrLoc(2) = oDr("nLocationTaxRate")
End If
If IsDBNull(oDr("cLocationNameShort")) Or IsNothing(oDr("cLocationNameShort")) Then
arrLoc(1) = oDr("cLocationNameFull")
Else
arrLoc(1) = oDr("cLocationNameShort")
End If
nLocKey = CInt(oDr("nLocationKey"))
oLocations(nLocKey) = arrLoc
arrLoc = Nothing
If IIf(IsDBNull(oDr("cLocationNameShort")), "", oDr("cLocationNameShort")) = Trim(sTarget) _
Or IIf(IsDBNull(oDr("cLocationNameFull")), "", oDr("cLocationNameFull")) = Trim(sTarget) Then
nTargetId = oDr("nLocationKey")
End If
End While
' Iterate through the country list
If nTargetId <> -1 Then
' Get country names
sCountryList = iterateCountryList(oLocations, nTargetId, nIndex)
sCountryList = "(" & Right(sCountryList, Len(sCountryList) - 1) & ")"
End If
oLocations = Nothing
End If
oDr.Close()
oDr = Nothing
If sCountryList = "" Then
Err.Raise(1004, "getParentCountries", sTarget & " cannot be found as a delivery location, please add via the admin system.")
End If
Return sCountryList
Catch ex As Exception
returnException(mcModuleName, "getParentCountries", ex, "", cProcessInfo, gbDebug)
Return Nothing
End Try
End Function
Private Function iterateCountryList(ByRef oDict As Hashtable, ByRef nParent As Integer, ByRef nIndex As Integer) As String
PerfMon.Log("Cart", "iterateCountryList")
Dim arrTmp As Object
Dim sListReturn As String
Dim cProcessInfo As String = ""
Try
sListReturn = ""
If oDict.ContainsKey(nParent) Then
arrTmp = oDict.Item(nParent)
sListReturn = ",'" & SqlFmt(arrTmp(nIndex)) & "'" ' Adding this line here allows the top root location to be added
If Not (IsDBNull(arrTmp(0)) Or arrTmp(0) = "") Then ' You're not at the root - arrTmp(0) is the parent of the location
If arrTmp(0) <> nParent Then ' guard against recursive loops
sListReturn = sListReturn & iterateCountryList(oDict, arrTmp(0), nIndex)
End If
End If
End If
iterateCountryList = sListReturn
Catch ex As Exception
returnException(mcModuleName, "iterateCountryList", ex, "", cProcessInfo, gbDebug)
Return Nothing
End Try
End Function
Public Sub addDateAndRef(ByRef oCartElmt As XmlElement, Optional invoiceDate As DateTime = Nothing)
PerfMon.Log("Cart", "addDateAndRef")
' adds current date and an invoice reference number to the cart object.
' so the cart now contains all details needed for an invoice
Dim cProcessInfo As String = ""
Try
If invoiceDate = Nothing Then invoiceDate = Now()
oCartElmt.SetAttribute("InvoiceDate", niceDate(invoiceDate))
oCartElmt.SetAttribute("InvoiceRef", OrderNoPrefix & CStr(mnCartId))
If mcVoucherNumber <> "" Then
oCartElmt.SetAttribute("payableType", "Voucher")
oCartElmt.SetAttribute("voucherNumber", mcVoucherNumber)
oCartElmt.SetAttribute("voucherValue", mcVoucherValue)
oCartElmt.SetAttribute("voucherExpires", mcVoucherExpires)
End If
Catch ex As Exception
returnException(mcModuleName, "addDateAndRef", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Function CreateNewCart(ByRef oCartElmt As XmlElement, Optional ByVal cCartSchemaName As String = "Order") As Long
PerfMon.Log("Cart", "CreateNewCart")
' user has started shopping so we need to initialise the cart and add it to the db
Dim cProcessInfo As String = ""
Dim oInstance As XmlDataDocument = New XmlDataDocument
Dim oElmt As XmlElement
Try
'stop carts being added by robots
If Not myWeb.moSession("previousPage") = "" Then
oInstance.AppendChild(oInstance.CreateElement("instance"))
oElmt = addNewTextNode("tblCartOrder", oInstance.DocumentElement)
'addNewTextNode("nCartOrderKey", oElmt)
addNewTextNode("cCurrency", oElmt, mcCurrencyRef)
addNewTextNode("cCartSiteRef", oElmt, moCartConfig("OrderNoPrefix"))
addNewTextNode("cCartForiegnRef", oElmt)
addNewTextNode("nCartStatus", oElmt, "1")
addNewTextNode("cCartSchemaName", oElmt, mcOrderType) '-----BJR----cCartSchemaName)
addNewTextNode("cCartSessionId", oElmt, mcSessionId)
' MEMB - add userid to oRs if we are logged on
If mnEwUserId > 0 Then
addNewTextNode("nCartUserDirId", oElmt, CStr(mnEwUserId))
Else
addNewTextNode("nCartUserDirId", oElmt, "0")
End If
addNewTextNode("nPayMthdId", oElmt, "0")
addNewTextNode("cPaymentRef", oElmt)
addNewTextNode("cCartXml", oElmt)
addNewTextNode("nShippingMethodId", oElmt, "0")
addNewTextNode("cShippingDesc", oElmt, moCartConfig("DefaultShippingDesc"))
addNewTextNode("nShippingCost", oElmt, CLng(moCartConfig("DefaultShippingCost") & "0"))
addNewTextNode("cClientNotes", oElmt, cOrderReference) '----BJR
addNewTextNode("cSellerNotes", oElmt, "referer:" & myWeb.moSession("previousPage") & "/n")
If Not (moPageXml.SelectSingleNode("/Page/Request/GoogleCampaign") Is Nothing) Then
addElement(oElmt, "cCampaignCode", moPageXml.SelectSingleNode("/Page/Request/GoogleCampaign").OuterXml, True)
End If
addNewTextNode("nTaxRate", oElmt, CStr(mnTaxRate))
addNewTextNode("nGiftListId", oElmt, "0")
addNewTextNode("nAuditId", oElmt)
mnCartId = moDBHelper.setObjectInstance(Web.dbHelper.objectTypes.CartOrder, oInstance.DocumentElement)
Return mnCartId
Else
mnCartId = 0
Return mnCartId
End If
Catch ex As Exception
returnException(mcModuleName, "CreateNewCart", ex, "", cProcessInfo, gbDebug)
End Try
End Function
Public Function SetPaymentMethod(ByVal nPayMthdId As Long)
Dim sSql As String = ""
Dim oDs As DataSet
Dim oRow As DataRow
Dim cProcessInfo As String
Try
If mnCartId > 0 Then
'Update Seller Notes:
sSql = "select * from tblCartOrder where nCartOrderKey = " & mnCartId
oDs = myWeb.moDbHelper.getDataSetForUpdate(sSql, "Order", "Cart")
For Each oRow In oDs.Tables("Order").Rows
oRow("nPayMthdId") = nPayMthdId
Next
myWeb.moDbHelper.updateDataset(oDs, "Order")
End If
Catch ex As Exception
returnException(mcModuleName, "AddPaymentMethod", ex, "", cProcessInfo, gbDebug)
End Try
End Function
Public Sub SetClientNotes(ByVal Notes As String)
Dim sSql As String = ""
Dim oDs As DataSet
Dim oRow As DataRow
Dim cProcessInfo As String
Try
If mnCartId > 0 Then
'Update Seller Notes:
sSql = "select * from tblCartOrder where nCartOrderKey = " & mnCartId
oDs = myWeb.moDbHelper.getDataSetForUpdate(sSql, "Order", "Cart")
For Each oRow In oDs.Tables("Order").Rows
oRow("cClientNotes") = Notes
Next
myWeb.moDbHelper.updateDataset(oDs, "Order")
End If
Catch ex As Exception
returnException(mcModuleName, "UpdateSellerNotes", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Function AddItem(ByVal nProductId As Long, ByVal nQuantity As Long, ByVal oProdOptions As Array, Optional ByVal cProductText As String = "", Optional ByVal nPrice As Double = 0, Optional ProductXml As String = "") As Boolean
PerfMon.Log("Cart", "AddItem")
Dim cSQL As String = "Select * From tblCartItem WHERE nCartOrderID = " & mnCartId & " AND nItemID =" & nProductId
Dim oDS As New DataSet
Dim oDR1 As DataRow 'Parent Rows
Dim oDr2 As DataRow 'Child Rows
Dim nItemID As Integer = 0 'ID of the cart item record
Dim nCountExOptions As Integer 'number of matching options in the old cart item
Dim cProcessInfo As String = ""
Dim NoOptions As Integer 'the number of options for the item
Dim oProdXml As New XmlDocument
Dim strPrice1 As String
Dim nTaxRate As Long = 0
Dim i As Integer
Try
oDS = moDBHelper.getDataSetForUpdate(cSQL, "CartItems", "Cart")
oDS.EnforceConstraints = False
'create relationship
oDS.Relations.Add("Rel1", oDS.Tables("CartItems").Columns("nCartItemKey"), oDS.Tables("CartItems").Columns("nParentId"), False)
oDS.Relations("Rel1").Nested = True
'loop through the parent rows to check the product
If oDS.Tables("CartItems").Rows.Count > 0 Then
For Each oDR1 In oDS.Tables("CartItems").Rows
If moDBHelper.DBN2int(oDR1.Item("nParentId")) = 0 And oDR1.Item("nItemId") = nProductId Then '(oDR1.Item("nParentId") = 0 Or IsDBNull(oDR1.Item("nParentId"))) And oDR1.Item("nItemId") = nProductId Then
nCountExOptions = 0
NoOptions = 0
'loop through the children(options) and count how many are the same
For Each oDr2 In oDR1.GetChildRows("Rel1")
For i = 0 To UBound(oProdOptions) - 1
If UBound(oProdOptions(i)) < 1 Then
'Case for text option with no index
If oProdOptions(i)(0) = CStr(oDr2.Item("nItemOptGrpIdx")) Then nCountExOptions += 1
Else
If oProdOptions(i)(0) = oDr2.Item("nItemOptGrpIdx") And oProdOptions(i)(1) = oDr2.Item("nItemOptIdx") Then nCountExOptions += 1
End If
Next
NoOptions += 1
Next
If Not oProdOptions Is Nothing Then
'if they are all the same then we have the correct record so it is an update
If ((nCountExOptions) = UBound(oProdOptions)) And ((NoOptions) = UBound(oProdOptions)) Then
nItemID = oDR1.Item("NCartItemKey") 'ok, got the bugger
Exit For 'exit the loop other wise we might go through some other ones
End If
Else
If NoOptions = 0 Then nItemID = oDR1.Item("NCartItemKey")
End If
End If
Next
End If
If nItemID = 0 Then
'New
Dim oElmt As XmlElement
Dim oPrice As XmlElement = Nothing
Dim nWeight As Long = 0
Dim oItemInstance As XmlDataDocument = New XmlDataDocument
oItemInstance.AppendChild(oItemInstance.CreateElement("instance"))
oElmt = addNewTextNode("tblCartItem", oItemInstance.DocumentElement)
addNewTextNode("nCartOrderId", oElmt, CStr(mnCartId))
addNewTextNode("nItemId", oElmt, nProductId)
addNewTextNode("cItemURL", oElmt, myWeb.GetContentUrl(nProductId)) 'Erm?
If ProductXml <> "" Then
oProdXml.InnerXml = ProductXml
Else
If nProductId > 0 Then
oProdXml.InnerXml = moDBHelper.ExeProcessSqlScalar("Select cContentXmlDetail FROM tblContent WHERE nContentKey = " & nProductId)
If Not oProdXml.SelectSingleNode("/Content/StockCode") Is Nothing Then addNewTextNode("cItemRef", oElmt, oProdXml.SelectSingleNode("/Content/StockCode").InnerText) '@ Where do we get this from?
If cProductText = "" Then
cProductText = oProdXml.SelectSingleNode("/Content/*[1]").InnerText
End If
oPrice = getContentPricesNode(oProdXml.DocumentElement, myWeb.moRequest("unit"), nQuantity)
If Not oProdXml.SelectSingleNode("/Content[@overridePrice='True']") Is Nothing Then
mbOveridePrice = True
End If
'lets add the discount to the cart if supplied
If Not oProdXml.SelectSingleNode("/Content/Prices/Discount[@currency='" & mcCurrency & "']") Is Nothing Then
Dim strDiscount1 As String = oProdXml.SelectSingleNode(
"/Content/Prices/Discount[@currency='" & mcCurrency & "']"
).InnerText
addNewTextNode("nDiscountValue", oElmt, IIf(IsNumeric(strDiscount1), strDiscount1, 0))
End If
If Not oProdXml.SelectSingleNode("/Content/ShippingWeight") Is Nothing Then
nWeight = CDbl("0" & oProdXml.SelectSingleNode("/Content/ShippingWeight").InnerText)
End If
End If
End If
addNewTextNode("cItemName", oElmt, cProductText)
addNewTextNode("nItemOptGrpIdx", oElmt, 0) 'Dont Need
addNewTextNode("nItemOptIdx", oElmt, 0) 'Dont Need
If myWeb.moRequest("unit") <> "" Then
addNewTextNode("cItemUnit", oElmt, myWeb.moRequest("unit"))
End If
If Not oPrice Is Nothing Then
strPrice1 = oPrice.InnerText
nTaxRate = getProductTaxRate(oPrice)
Else
strPrice1 = CStr(nPrice)
End If
If mbOveridePrice Then
If myWeb.moRequest("price_" & nProductId) > 0 Then
strPrice1 = myWeb.moRequest("price_" & nProductId)
End If
End If
addNewTextNode("nPrice", oElmt, IIf(IsNumeric(strPrice1), strPrice1, 0))
addNewTextNode("nShpCat", oElmt, -1) '@ Where do we get this from?
addNewTextNode("nTaxRate", oElmt, nTaxRate)
addNewTextNode("nQuantity", oElmt, nQuantity)
addNewTextNode("nWeight", oElmt, nWeight)
addNewTextNode("nParentId", oElmt, 0)
addNewTextNode("nParentId", oElmt, 0)
Dim ProductXmlElmt As XmlElement = addNewTextNode("xItemXml", oElmt, "")
ProductXmlElmt.InnerXml = oProdXml.DocumentElement.OuterXml
nItemID = moDBHelper.setObjectInstance(Web.dbHelper.objectTypes.CartItem, oItemInstance.DocumentElement)
'Options
If Not oProdOptions Is Nothing Then
For i = 0 To UBound(oProdOptions)
If Not oProdOptions(i) Is Nothing And nQuantity > 0 Then
'Add Options
oItemInstance = New XmlDataDocument
oItemInstance.AppendChild(oItemInstance.CreateElement("instance"))
oElmt = addNewTextNode("tblCartItem", oItemInstance.DocumentElement)
addNewTextNode("nCartOrderId", oElmt, CStr(mnCartId))
Dim cStockCode As String = ""
Dim cOptName As String = ""
Dim bTextOption As Boolean = False
If UBound(oProdOptions(i)) < 1 Then
'This option dosen't have an index value
'Save the submitted value against stock code.
cStockCode = Me.myWeb.moRequest.Form("opt_" & nProductId & "_" & (i + 1))
cOptName = cStockCode
bTextOption = True
Else
If IsNumeric(oProdOptions(i)(0)) And IsNumeric(oProdOptions(i)(1)) Then
'add the stock code from the option
If Not oProdXml.SelectSingleNode("/Content/Options/OptGroup[" & oProdOptions(i)(0) & "]/option[" & oProdOptions(i)(1) & "]/StockCode") Is Nothing Then
cStockCode = oProdXml.SelectSingleNode("/Content/Options/OptGroup[" & oProdOptions(i)(0) & "]/option[" & oProdOptions(i)(1) & "]/StockCode").InnerText
ElseIf Not oProdXml.SelectSingleNode("/Content/Options/OptGroup[" & oProdOptions(i)(0) & "]/option[" & oProdOptions(i)(1) & "]/code") Is Nothing Then
cStockCode = oProdXml.SelectSingleNode("/Content/Options/OptGroup[" & oProdOptions(i)(0) & "]/option[" & oProdOptions(i)(1) & "]/code").InnerText
ElseIf Not oProdXml.SelectSingleNode("/Content/Options/OptGroup[" & oProdOptions(i)(0) & "]/option[" & oProdOptions(i)(1) & "]/name") Is Nothing Then
cStockCode = oProdXml.SelectSingleNode("/Content/Options/OptGroup[" & oProdOptions(i)(0) & "]/option[" & oProdOptions(i)(1) & "]/name").InnerText
End If
'add the name from the option
If Not oProdXml.SelectSingleNode("/Content/Options/OptGroup[" & oProdOptions(i)(0) & "]" & "/option[" & oProdOptions(i)(1) & "]/Name") Is Nothing Then
cOptName = oProdXml.SelectSingleNode("/Content/Options/OptGroup[" & oProdOptions(i)(0) & "]" & "/option[" & oProdOptions(i)(1) & "]/Name").InnerText
ElseIf Not oProdXml.SelectSingleNode("/Content/Options/OptGroup[" & oProdOptions(i)(0) & "]" & "/option[" & oProdOptions(i)(1) & "]/name") Is Nothing Then
cOptName = oProdXml.SelectSingleNode("/Content/Options/OptGroup[" & oProdOptions(i)(0) & "]" & "/option[" & oProdOptions(i)(1) & "]/name").InnerText
ElseIf Not oProdXml.SelectSingleNode("/Content/Options/OptGroup[" & oProdOptions(i)(0) & "]" & "/option[" & oProdOptions(i)(1) & "]/@name") Is Nothing Then
cOptName = oProdXml.SelectSingleNode("/Content/Options/OptGroup[" & oProdOptions(i)(0) & "]" & "/option[" & oProdOptions(i)(1) & "]/@name").InnerText
End If
Else
cStockCode = ""
cOptName = "Invalid Option"
End If
End If
addNewTextNode("cItemRef", oElmt, cStockCode)
addNewTextNode("nItemId", oElmt, nProductId)
addNewTextNode("cItemURL", oElmt, myWeb.mcOriginalURL) 'Erm?
addNewTextNode("cItemName", oElmt, cOptName)
If bTextOption Then
'save the option index as -1 for text option
addNewTextNode("nItemOptGrpIdx", oElmt, (i + 1))
addNewTextNode("nItemOptIdx", oElmt, -1)
'No price variation for text options
addNewTextNode("nPrice", oElmt, "0")
Else
addNewTextNode("nItemOptGrpIdx", oElmt, oProdOptions(i)(0))
addNewTextNode("nItemOptIdx", oElmt, oProdOptions(i)(1))
Dim oPriceElmt As XmlElement = oProdXml.SelectSingleNode(
"/Content/Options/OptGroup[" & oProdOptions(i)(0) & "]" &
"/option[" & oProdOptions(i)(1) & "]/Prices/Price[@currency='" & mcCurrency & "']"
)
Dim strPrice2 As String = 0
If Not oPriceElmt Is Nothing Then strPrice2 = oPriceElmt.InnerText
addNewTextNode("nPrice", oElmt, IIf(IsNumeric(strPrice2), strPrice2, 0))
End If
addNewTextNode("nShpCat", oElmt, -1)
addNewTextNode("nTaxRate", oElmt, 0)
addNewTextNode("nQuantity", oElmt, 1)
addNewTextNode("nWeight", oElmt, 0)
addNewTextNode("nParentId", oElmt, nItemID)
moDBHelper.setObjectInstance(Web.dbHelper.objectTypes.CartItem, oItemInstance.DocumentElement)
End If
Next
End If
Else
'Existing
oDS.Relations.Clear()
If nQuantity <= 0 Then
moDBHelper.DeleteObject(Web.dbHelper.objectTypes.CartItem, nItemID, False)
Else
For Each oDR1 In oDS.Tables("CartItems").Rows
If oDR1.Item("nCartItemKey") = nItemID Then
oDR1.BeginEdit()
oDR1("nQuantity") += nQuantity
oDR1.EndEdit()
Exit For
End If
Next
End If
moDBHelper.updateDataset(oDS, "CartItems")
End If
Return True
Catch ex As Exception
returnException(mcModuleName, "addItem", ex, "", cProcessInfo, gbDebug)
End Try
End Function
Public Overridable Function AddItems() As Boolean
PerfMon.Log("Cart", "AddItems")
'this function checks for an identical item in the database.
' If there is, the quantity is increased accordingly.
' If not, a new item is added to the table
Dim cProcessInfo As String = "Checking Submitted Products and Options"
Dim oItem1 As Object 'Object for product keys/quantittie
Dim oItem2 As Object 'Object for options
Dim strAddedProducts As String = "Start:" 'string of products added
Dim oOptions(1) As Array 'an array of option arrays (2 dimensional array)
Dim nCurOptNo As Integer = 0
Dim oCurOpt() As String 'CurrentOption bieng evaluated
Dim nProductKey As Long
Dim nQuantity As Long
Dim nI As Integer
Dim cReplacementName As String = ""
'test string
'qty_233=1 opt_233_1=1_2,1_3 opt_233_2=1_5
Dim cSql As String
Dim oDs As DataSet
Dim oRow As DataRow
Dim qtyAdded As Integer = 0
Try
If LCase(moCartConfig("ClearOnAdd")) = "on" Then
cSql = "select nCartItemKey from tblCartItem where nCartOrderId = " & mnCartId
oDs = moDBHelper.GetDataSet(cSql, "Item")
If oDs.Tables("Item").Rows.Count > 0 Then
For Each oRow In oDs.Tables("Item").Rows
moDBHelper.DeleteObject(dbHelper.objectTypes.CartItem, oRow("nCartItemKey"))
Next
End If
End If
If LCase(mmcOrderType) = LCase(mcItemOrderType) Then ' test for order?
For Each oItem1 In myWeb.moRequest.Form 'Loop for getting products/quants
'set defaults
nProductKey = 0
nQuantity = 0
oOptions = Nothing
cReplacementName = ""
'begin
If InStr(oItem1, "qty_") = 1 Then 'check for getting productID and quantity (since there will only be one of these per item submitted)
nProductKey = CLng(Replace(oItem1, "qty_", "")) 'Product key
cProcessInfo = oItem1.ToString & " = " & myWeb.moRequest.Form.Get(oItem1)
If IsNumeric(myWeb.moRequest.Form.Get(oItem1)) Then
nQuantity = myWeb.moRequest.Form.Get(oItem1)
End If
'replacementName
If nQuantity > 0 Then
qtyAdded = qtyAdded + nQuantity
If Not InStr(strAddedProducts, "'" & nProductKey & "'") > 0 Then ' double check we havent added this product (dont really need but good just in case)
For Each oItem2 In myWeb.moRequest.Form 'loop through again checking for options
If oItem2 = "replacementName_" & nProductKey Then cReplacementName = myWeb.moRequest.Form.Get(oItem2)
If InStr(oItem2, "_") > 0 Then
If Split(oItem2, "_")(0) & "_" & Split(oItem2, "_")(1) = "opt_" & nProductKey Then 'check it is an option
oCurOpt = Split(myWeb.moRequest.Form.Get(oItem2), ",") 'get array of option in "1_2" format
For nI = 0 To UBound(oCurOpt) 'loop through current options to split into another array
ReDim Preserve oOptions(nCurOptNo + 1) 'redim the array to new length while preserving the current data
oOptions(nCurOptNo) = Split(oCurOpt(nI), "_") 'split out the arrays of options
nCurOptNo += 1 'update number of options
Next
End If 'end option check
End If
Next 'end option loop
'Add Item
AddItem(nProductKey, nQuantity, oOptions, cReplacementName)
'Add Item to "Done" List
strAddedProducts &= "'" & nProductKey & "',"
End If
End If 'end check for previously added
End If 'end check for item/quant
Next 'End Loop for getting products/quants
If qtyAdded > 0 Then
AddItems = True
Else
AddItems = False
End If
Else
AddItems = False
End If
Catch ex As Exception
returnException(mcModuleName, "addItems", ex, "", cProcessInfo, gbDebug)
Return False
End Try
End Function
Public Function RemoveItem(Optional ByVal nItemId As Long = 0, Optional ByVal nContentId As Long = 0) As Integer
PerfMon.Log("Cart", "RemoveItem")
' deletes record from item table in db
Dim oDr As SqlDataReader
Dim sSql As String
Dim oDs As DataSet
Dim oRow As DataRow
Dim cProcessInfo As String = ""
Dim itemCount As Long
If IsNumeric(myWeb.moRequest("id")) Then nItemId = myWeb.moRequest("id")
Try
'If myWeb.moRequest("id") <> "" Then
If nContentId = 0 Then
sSql = "select nCartItemKey from tblCartItem where (nCartItemKey = " & nItemId & " Or nParentId = " & nItemId & ") and nCartOrderId = " & mnCartId
Else
sSql = "select nCartItemKey from tblCartItem where nItemId = " & nContentId & " and nCartOrderId = " & mnCartId
End If
oDs = moDBHelper.GetDataSet(sSql, "Item")
If oDs.Tables("Item").Rows.Count > 0 Then
For Each oRow In oDs.Tables("Item").Rows
moDBHelper.DeleteObject(dbHelper.objectTypes.CartItem, oRow("nCartItemKey"))
Next
End If
' REturn the cart order item count
sSql = "select count(*) As ItemCount from tblCartItem where nCartOrderId = " & mnCartId
oDr = moDBHelper.getDataReader(sSql)
If oDr.HasRows Then
While oDr.Read
itemCount = CInt(oDr("ItemCount"))
End While
End If
oDr.Close()
oDr = Nothing
Return itemCount
Catch ex As Exception
returnException(mcModuleName, "removeItem", ex, "", cProcessInfo, gbDebug)
End Try
End Function
Public Function UpdateItem(Optional ByVal nItemId As Long = 0, Optional ByVal nContentId As Long = 0, Optional ByVal qty As Long = 1) As Integer
PerfMon.Log("Cart", "RemoveItem")
' deletes record from item table in db
Dim oDr As SqlDataReader
Dim sSql As String
Dim oDs As DataSet
Dim oRow As DataRow
Dim cProcessInfo As String = ""
Dim itemCount As Long
Try
If LCase(moCartConfig("ClearOnAdd")) = "on" Then
Dim cSql As String = "select nCartItemKey from tblCartItem where nCartOrderId = " & mnCartId
oDs = moDBHelper.GetDataSet(cSql, "Item")
If oDs.Tables("Item").Rows.Count > 0 Then
For Each oRow In oDs.Tables("Item").Rows
moDBHelper.DeleteObject(dbHelper.objectTypes.CartItem, oRow("nCartItemKey"))
Next
End If
End If
'If myWeb.moRequest("id") <> "" Then
If qty > 0 Then
'sSql = "delete from tblCartItem where nCartItemKey = " & myWeb.moRequest("id") & "and nCartOrderId = " & mnCartId
If nContentId = 0 Then
sSql = "select * from tblCartItem where (nCartItemKey = " & nItemId & " Or nParentId = " & nItemId & ") and nCartOrderId = " & mnCartId
Else
sSql = "select * from tblCartItem where nItemId = " & nContentId & " and nCartOrderId = " & mnCartId
End If
oDs = moDBHelper.getDataSetForUpdate(sSql, "Item")
If oDs.Tables("Item").Rows.Count > 0 Then
For Each oRow In oDs.Tables("Item").Rows
oRow("nQuantity") = qty
Next
Else
AddItem(nContentId, qty, Nothing)
End If
moDBHelper.updateDataset(oDs, "Item")
oDs = Nothing
Else
RemoveItem(nItemId, nContentId)
End If
' REturn the cart order item count
sSql = "select count(*) As ItemCount from tblCartItem where nCartOrderId = " & mnCartId
oDr = moDBHelper.getDataReader(sSql)
If oDr.HasRows Then
While oDr.Read
itemCount = CInt(oDr("ItemCount"))
End While
End If
oDr.Close()
oDr = Nothing
Return itemCount
Catch ex As Exception
returnException(mcModuleName, "removeItem", ex, "", cProcessInfo, gbDebug)
End Try
End Function
''' <summary>
''' Empties all items in a shopping cart.
''' </summary>
''' <remarks></remarks>
Public Sub EmptyCart()
PerfMon.Log("Cart", "EmptyCart")
Dim oDr As SqlDataReader
Dim sSql As String
Dim cProcessInfo As String = ""
Try
' Return the cart order item count
sSql = "select nCartItemKey from tblCartItem where nCartOrderId = " & mnCartId
oDr = moDBHelper.getDataReader(sSql)
If oDr.HasRows Then
While oDr.Read
moDBHelper.DeleteObject(dbHelper.objectTypes.CartItem, oDr("nCartItemKey"))
End While
End If
oDr.Close()
oDr = Nothing
Catch ex As Exception
returnException(mcModuleName, "EmptyCart", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Sub UpdateCartDeposit(ByRef oRoot As XmlElement, ByVal nPaymentAmount As Double, ByVal cPaymentType As String)
PerfMon.Log("Cart", "UpdateCartDeposit")
Dim oDr As SqlDataReader
Dim sSql As String
Dim nAmountReceived As Double = 0.0#
Dim cUniqueLink As String = ""
Dim cProcessInfo As String = ""
Try
' If the cPaymentType is deposit then we need to make a link, otherwise we need to get the paymentReceived details.
If cPaymentType = "deposit" Then
' Get the unique link from the cart
cUniqueLink = ", cSettlementID='" & oRoot.GetAttribute("settlementID") & "' "
Else
' Get the amount received so far
sSql = "select * from tblCartOrder where nCartOrderKey = " & mnCartId
oDr = moDBHelper.getDataReader(sSql)
If oDr.HasRows Then
While oDr.Read
nAmountReceived = CDbl(oDr("nAmountReceived"))
cUniqueLink = ", cSettlementID='OLD_" & oDr("cSettlementID") & "' "
End While
End If
oDr.Close()
End If
nAmountReceived = nAmountReceived + nPaymentAmount
sSql = "update tblCartOrder set nAmountReceived = " & nAmountReceived & ", nLastPaymentMade= " & nPaymentAmount & cUniqueLink & " where nCartOrderKey = " & mnCartId
moDBHelper.ExeProcessSql(sSql)
Catch ex As Exception
returnException(mcModuleName, "QuitCart", ex, "", cProcessInfo, gbDebug)
Finally
oDr = Nothing
End Try
End Sub
Public Sub QuitCart()
PerfMon.Log("Cart", "QuitCart")
' set the cart status to 7
Dim sSql As String
Dim cProcessInfo As String = ""
Try
' Old delete calls - DON't DELETE THE CART, Simply set the status to abandoned.
' sSql = "delete from tblCartItem where nCartOrderId = " & mnCartId
' oDb.exeProcessSQL sSql, mcEwDataConn
' sSql = "delete from tblCartOrder where nCartOrderKey =" & mnCartId
' oDb.exeProcessSQL sSql, mcEwDataConn
sSql = "update tblCartOrder set nCartStatus = 11 where(nCartOrderKey = " & mnCartId & ")"
moDBHelper.ExeProcessSql(sSql)
Catch ex As Exception
returnException(mcModuleName, "QuitCart", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Overridable Sub EndSession()
PerfMon.Log("Cart", "EndSession")
Dim sProcessInfo As String = ""
Dim sSql As String
Dim cProcessInfo As String = ""
Try
clearSessionCookie()
sSql = "update tblCartOrder set cCartSessionId = 'OLD_' + cCartSessionId where(nCartOrderKey = " & mnCartId & ")"
moDBHelper.ExeProcessSql(sSql)
mmcOrderType = ""
mnCartId = 0
myWeb.moSession("CartId") = Nothing
Catch ex As Exception
returnException(mcModuleName, "EndSession", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Function updateCart(ByRef cSuccessfulCartCmd As String) As Object
PerfMon.Log("Cart", "updateCart")
' user can decide to change the quantity of identical items or change the shipping options
' changes to the database are made in this function
Dim oDs As DataSet
Dim oRow As DataRow
Dim sSql As String
Dim nItemCount As Integer
Dim cProcessInfo As String = ""
Try
'Go through the items associated with the order
sSql = "select * from tblCartItem where nCartOrderId = " & mnCartId
cProcessInfo = sSql
oDs = moDBHelper.getDataSetForUpdate(sSql, "Item", "Cart")
'@@@@@@@@@@@@@@@@@@@@@@@@@@@@
oDs.Relations.Add("Rel1", oDs.Tables("Item").Columns("nCartItemKey"), oDs.Tables("Item").Columns("nParentId"), False)
oDs.Relations("Rel1").Nested = True
'@@@@@@@@@@@@@@@@@@@@@@@@@@@@
nItemCount = 0 ' nItemCount - keeps a running total (accounting for deletions)
Dim bNullParentId As Boolean = False
For Each oRow In oDs.Tables("Item").Rows
If Not oRow.RowState = DataRowState.Deleted Then
bNullParentId = False
If oRow("nParentId") Is DBNull.Value Then
bNullParentId = True
ElseIf oRow("nParentId") = 0 Then
bNullParentId = True
End If
If bNullParentId Then ' for options
nItemCount = nItemCount + 1
' First check if the quantity is numeric (if not ignore it)
If IsNumeric(myWeb.moRequest("itemId-" & oRow("nCartItemKey"))) Then
' It's numeric - let's see if it's positive (i.e. update it, if not delete it)
If CInt(myWeb.moRequest("itemId-" & oRow("nCartItemKey"))) > 0 Then
oRow("nQuantity") = myWeb.moRequest("itemId-" & oRow("nCartItemKey"))
Else
'delete options first
Dim oCRows() As DataRow = oRow.GetChildRows("Rel1")
Dim nDels As Integer
For nDels = 0 To UBound(oCRows)
oCRows(nDels).Delete()
Next
'end delete options
oRow.Delete()
nItemCount = nItemCount - 1
End If
End If
End If 'for options
End If
Next
moDBHelper.updateDataset(oDs, "Item")
' If itemCount is 0 or less Then quit the cart, otherwise update the cart
If nItemCount > 0 Then
'Get the Cart Order
sSql = "select * from tblCartOrder where nCartOrderKey=" & mnCartId
cProcessInfo = sSql
oDs = moDBHelper.getDataSetForUpdate(sSql, "Order", "Cart")
For Each oRow In oDs.Tables("Order").Rows
oRow.BeginEdit()
'update the "cart last update" date
moDBHelper.setObjectInstance(Web.dbHelper.objectTypes.Audit, , oRow("nAuditId"))
'Update the Client notes, only if no separate form
If mcNotesXForm = "" And Not myWeb.moRequest("cClientNotes") = "" Then
oRow("cClientNotes") = myWeb.moRequest("cClientNotes")
End If
oRow("nCartStatus") = mnProcessId
'------------BJR-------------------
oRow("cCartSchemaName") = mcOrderType
'oRow("cClientNotes") = cOrderReference
'----------------------------------
If Not CStr(oRow("cSellerNotes")).Contains("Referrer: " & myWeb.Referrer) And Not myWeb.Referrer = "" Then
oRow("cSellerNotes") &= "/n" & "Referrer: " & myWeb.Referrer & "/n"
End If
oRow.EndEdit()
Next
moDBHelper.updateDataset(oDs, "Order")
' Set the successful Cart Cmd
mcCartCmd = cSuccessfulCartCmd
Return cSuccessfulCartCmd
Else
mnProcessId = 0
mcCartCmd = "Quit"
'Return Nothing
Return mcCartCmd
End If
Catch ex As Exception
returnException(mcModuleName, "UpdateCart", ex, "", cProcessInfo, gbDebug)
Return Nothing
End Try
End Function
Public Sub ListOrders(ByRef oContentsXML As XmlElement, ByVal ProcessId As cartProcess)
PerfMon.Log("Cart", "ListOrders")
Dim oRoot As XmlElement
Dim oElmt As XmlElement
Dim sSql As String
Dim oDs As DataSet
Dim cProcessInfo As String = ""
Try
oRoot = moPageXml.CreateElement("Content")
oRoot.SetAttribute("type", "listTree")
oRoot.SetAttribute("template", "default")
oRoot.SetAttribute("name", "Orders - " & ProcessId.GetType.ToString)
sSql = "SELECT nCartOrderKey as id, c.cContactName as name, c.cContactEmail as email, a.dUpdateDate from tblCartOrder inner join tblAudit a on nAuditId = a.nAuditKey left outer join tblCartContact c on (nCartOrderKey = c.nContactCartId and cContactType = 'Billing Address') where nCartStatus = " & ProcessId
oDs = moDBHelper.GetDataSet(sSql, "Order", "List")
If oDs.Tables(0).Rows.Count > 0 Then
oDs.Tables(0).Columns(0).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(1).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(2).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(3).ColumnMapping = Data.MappingType.Attribute
'load existing data into the instance
oElmt = moPageXml.CreateElement("List")
oElmt.InnerXml = oDs.GetXml
oContentsXML.AppendChild(oElmt)
End If
Catch ex As Exception
returnException(mcModuleName, "ListShippingLocations", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Sub ListShippingLocations(ByRef oContentsXML As XmlElement, Optional ByVal OptId As Long = 0)
PerfMon.Log("Cart", "ListShippingLocations")
Dim oRoot As XmlElement
Dim oElmt As XmlElement
Dim sSql As String
Dim oDs As DataSet
Dim cProcessInfo As String = ""
Try
oRoot = moPageXml.CreateElement("Content")
oRoot.SetAttribute("type", "listTree")
oRoot.SetAttribute("template", "default")
If OptId <> 0 Then
oRoot.SetAttribute("name", "Shipping Locations Form")
sSql = "SELECT nLocationKey as id, nLocationType as type, nLocationParId as parid, cLocationNameFull as Name, cLocationNameShort as nameShort, (SELECT COUNT(*) from tblCartShippingRelations r where r.nShpLocId = n.nLocationKey and r.nShpOptId = " & OptId & ") As selected from tblCartShippingLocations n "
Else
oRoot.SetAttribute("name", "Shipping Locations")
sSql = "SELECT nLocationKey as id, nLocationType as type, nLocationParId as parid, cLocationNameFull as Name, cLocationNameShort as nameShort, (SELECT COUNT(*) from tblCartShippingRelations r where r.nShpLocId = n.nLocationKey) As nOptCount from tblCartShippingLocations n "
End If
' NOTE : This SQL is NOT the same as the equivalent function in the EonicWeb component.
' It adds a count of shipping option relations for each location
oDs = moDBHelper.GetDataSet(sSql, "TreeItem", "Tree")
oDs.Relations.Add("rel01", oDs.Tables(0).Columns("id"), oDs.Tables(0).Columns("parId"), False)
oDs.Relations("rel01").Nested = True
If oDs.Tables(0).Rows.Count > 0 Then
oDs.Tables(0).Columns(0).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(1).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(2).ColumnMapping = Data.MappingType.Hidden
oDs.Tables(0).Columns(3).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(4).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(5).ColumnMapping = Data.MappingType.Attribute
'load existing data into the instance
oElmt = moPageXml.CreateElement("Tree")
oElmt.InnerXml = oDs.GetXml
Dim oCheckElmt As XmlElement = Nothing
oCheckElmt = oElmt.SelectSingleNode("descendant-or-self::TreeItem[@id='" & mnShippingRootId & "']")
If Not oCheckElmt Is Nothing Then oElmt = oCheckElmt
oContentsXML.AppendChild(oElmt)
End If
Catch ex As Exception
returnException(mcModuleName, "ListShippingLocations", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Sub ListDeliveryMethods(ByRef oContentsXML As XmlElement)
PerfMon.Log("Cart", "ListDeliveryMethods")
Dim oElmt As XmlElement
Dim sSql As String
Dim oDs As DataSet
Dim cProcessInfo As String = ""
Try
sSql = "select a.nStatus as status, nShipOptKey as id, cShipOptName as name, cShipOptCarrier as carrier, a.dPublishDate as startDate, a.dExpireDate as endDate, tblCartShippingMethods.cCurrency from tblCartShippingMethods left join tblAudit a on a.nAuditKey = nAuditId order by nDisplayPriority"
oDs = moDBHelper.GetDataSet(sSql, "ListItem", "List")
If oDs.Tables(0).Rows.Count > 0 Then
oDs.Tables(0).Columns(0).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(1).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(2).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(3).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(4).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(5).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(6).ColumnMapping = Data.MappingType.Attribute
'load existing data into the instance
oElmt = moPageXml.CreateElement("List")
oElmt.InnerXml = oDs.GetXml
oContentsXML.AppendChild(oElmt.FirstChild)
End If
Catch ex As Exception
returnException(mcModuleName, "ListDeliveryMethods", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Sub ListCarriers(ByRef oContentsXML As XmlElement)
PerfMon.Log("Cart", "ListDeliveryMethods")
Dim oElmt As XmlElement
Dim sSql As String
Dim oDs As DataSet
Dim cProcessInfo As String = ""
Try
sSql = "select a.nStatus as status, nCarrierKey as id, cCarrierName as name, cCarrierTrackingInstructions as info, a.dPublishDate as startDate, a.dExpireDate as endDate from tblCartCarrier left join tblAudit a on a.nAuditKey = nAuditId"
oDs = moDBHelper.GetDataSet(sSql, "Carrier", "Carriers")
If oDs.Tables(0).Rows.Count > 0 Then
oDs.Tables(0).Columns(0).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(1).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(4).ColumnMapping = Data.MappingType.Attribute
oDs.Tables(0).Columns(5).ColumnMapping = Data.MappingType.Attribute
'load existing data into the instance
oElmt = moPageXml.CreateElement("Carriers")
oElmt.InnerXml = oDs.GetXml
oContentsXML.AppendChild(oElmt.FirstChild)
End If
Catch ex As Exception
returnException(mcModuleName, "ListCarriers", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Sub ListPaymentProviders(ByRef oContentsXML As XmlElement)
PerfMon.Log("Cart", "ListPaymentProviders")
Dim oElmt As XmlElement
Dim oElmt2 As XmlElement
Dim cProcessInfo As String = ""
Dim oPaymentCfg As XmlNode
Dim Folder As String = "/ewcommon/xforms/PaymentProvider/"
Dim fi As FileInfo
Dim ProviderName As String
Try
oPaymentCfg = WebConfigurationManager.GetWebApplicationSection("eonic/payment")
oElmt = moPageXml.CreateElement("List")
Dim dir As New DirectoryInfo(moServer.MapPath(Folder))
Dim files As FileInfo() = dir.GetFiles()
For Each fi In files
If fi.Extension = ".xml" Then
ProviderName = Replace(fi.Name, fi.Extension, "")
oElmt2 = addNewTextNode("Provider", oElmt, Replace(ProviderName, "-", " "))
If Not oPaymentCfg.SelectSingleNode("/payment/provider[@name='" & Replace(ProviderName, "-", "") & "']") Is Nothing Then
oElmt2.SetAttribute("active", "true")
End If
End If
Next
oContentsXML.AppendChild(oElmt)
Catch ex As Exception
returnException(mcModuleName, "ListPaymentProviders", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Private Sub AddDeliveryFromGiftList(ByVal nGiftListId As String)
PerfMon.Log("Cart", "AddDeliveryFromGiftList")
Dim oDs As DataSet
Dim oXml As XmlDocument = New XmlDocument
Dim cProcessInfo As String = ""
Try
'does the order allready contain a delivery address?
oDs = moDBHelper.GetDataSet("select * from tblCartContact where cContactType='Delivery Address' and nContactParentId > 0 and nContactParentId=" & mnCartId.ToString & " and nContactParentType=1", "tblCartContact")
If oDs.Tables("tblCartContact").Rows.Count = 0 Then
oDs.Dispose()
oDs = Nothing
oDs = moDBHelper.GetDataSet("select * from tblCartContact where cContactType='Delivery Address' and nContactParentId > 0 and nContactParentId=" & nGiftListId & " and nContactParentType=1", "tblCartContact")
If oDs.Tables("tblCartContact").Rows.Count = 1 Then
oXml.LoadXml(oDs.GetXml)
oXml.SelectSingleNode("NewDataSet/tblCartContact/nContactKey").InnerText = "-1"
' oXml.SelectSingleNode("NewDataSet/tblCartContact/nContactParentType").InnerText = "1"
oXml.SelectSingleNode("NewDataSet/tblCartContact/nContactParentId").InnerText = mnCartId.ToString
moDBHelper.saveInstance(oXml.DocumentElement, "tblCartContact", "nContactKey")
End If
End If
'OK now add the GiftList Id to the cart
mnGiftListId = nGiftListId
oDs.Dispose()
oDs = Nothing
oXml = Nothing
Catch ex As Exception
returnException(mcModuleName, "AddDeliveryFromGiftList", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
''' <summary>
''' Calculates and updates the tax rate.
''' </summary>
''' <param name="cContactCountry">Optional: The name of the current current to work out the tax rate for. If empty, then the default tax rate is assumed.</param>
''' <remarks>If customer is logged on user and they are in a specified group, then void their tax rate</remarks>
Public Sub UpdateTaxRate(Optional ByRef cContactCountry As String = "")
PerfMon.Log("Cart", "UpdateTaxRate")
Dim sCountryList As String
Dim aVatRates() As String
Dim cVatRate As String
Dim cVatExclusionGroup As String
Dim nUpdateTaxRate As Double
Dim nCurrentTaxRate As Double
Dim bAllZero As Boolean
Dim sSql As String
Dim cProcessInfo As String = ""
Try
' Store the current tax rate for comparison later
nCurrentTaxRate = mnTaxRate
nUpdateTaxRate = nCurrentTaxRate
cVatExclusionGroup = "" & moCartConfig("TaxRateExclusionGroupId")
' First check if the user is in a tax exclusion group
If IsNumeric(cVatExclusionGroup) _
AndAlso CInt(cVatExclusionGroup) > 0 _
AndAlso Tools.Xml.NodeState(myWeb.moPageXml.DocumentElement, "/Page/User/*[@id='" & cVatExclusionGroup & "']") Then
cProcessInfo = "User is in Tax Rate exclusion group"
nUpdateTaxRate = 0
ElseIf cContactCountry <> "" Then
' First get an iterative list of the location and its parents tax rates
sCountryList = getParentCountries(cContactCountry, 2)
cProcessInfo = "Get tax for:" & cContactCountry
If sCountryList = "" Then
bAllZero = True
Else
sCountryList = Mid(sCountryList, 3, Len(sCountryList) - 4)
aVatRates = Split(sCountryList, "','")
Array.Reverse(aVatRates)
' go backwards through the list, and use the last non-zero tax rate
bAllZero = True
For Each cVatRate In aVatRates
If CDbl(cVatRate) > 0 Then
nUpdateTaxRate = CDbl(cVatRate)
bAllZero = False
End If
Next
End If
' If all the countries are 0 then we need to set the tax rate accordingly
If bAllZero Then nUpdateTaxRate = 0
End If
If nUpdateTaxRate <> nCurrentTaxRate Then
' return the (amended) rate to the mnTaxRate global variable.
mnTaxRate = nUpdateTaxRate
' update the cart order table with the new tax rate
sSql = "update tblCartOrder set nTaxRate = " & mnTaxRate & " where nCartOrderKey=" & mnCartId
moDBHelper.ExeProcessSql(sSql)
End If
PerfMon.Log("Cart", "UpdateTaxEnd")
Catch ex As Exception
returnException(mcModuleName, "UpdateTaxRate", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Sub populateCountriesDropDown(ByRef oXform As xForm, ByRef oCountriesDropDown As XmlElement, Optional ByVal cAddressType As String = "", Optional IDValues As Boolean = False)
PerfMon.Log("Cart", "populateCountriesDropDown")
Dim sSql As String
Dim oDr As SqlDataReader
Dim oLoctree As XmlElement
Dim oLocation As XmlElement
Dim arrPreLocs() As String = Split(mcPriorityCountries, ",")
Dim arrIdx As Integer
Dim bPreSelect As Boolean
Dim cProcessInfo As String = "" = oCountriesDropDown.OuterXml
Try
Select Case cAddressType
Case "Delivery Address"
' Delivery countries are restricted
' Go and build a tree of all locations - this will allow us to detect whether or not a country is in iteself or in a zone that has a Shipping Option
oLoctree = moPageXml.CreateElement("Contents")
ListShippingLocations(oLoctree, False)
' Add any priority countries
For arrIdx = 0 To UBound(arrPreLocs)
oLocation = oLoctree.SelectSingleNode("//TreeItem[@nameShort='" & arrPreLocs(arrIdx) & "']/ancestor-or-self::*[@nOptCount!='0']")
If Not (oLocation Is Nothing) Then
oXform.addOption((oCountriesDropDown), Trim(CStr(arrPreLocs(arrIdx))), Trim(CStr(arrPreLocs(arrIdx))))
bPreSelect = True
End If
Next
If bPreSelect Then
oXform.addOption((oCountriesDropDown), "--------", " ")
End If
' Now let's go and get a list of all the COUNTRIES sorted ALPHABETICALLY
sSql = "SELECT DISTINCT cLocationNameShort FROM tblCartShippingLocations WHERE nLocationType = 2 ORDER BY cLocationNameShort"
oDr = moDBHelper.getDataReader(sSql)
While oDr.Read()
'Let's find the country node
' XPath says "Get the context node for the location I'm looking at. Does it or its ancestors have an OptCount > 0?
If Not (oLoctree.SelectSingleNode("//TreeItem[@nameShort=""" & oDr("cLocationNameShort") & """]/ancestor-or-self::*[@nOptCount!='0']") Is Nothing) Then
oXform.addOption((oCountriesDropDown), oDr("cLocationNameShort"), oDr("cLocationNameShort"))
End If
End While
oLoctree = Nothing
oLocation = Nothing
oDr.Close()
oDr = Nothing
Case Else
' Not restricted by delivery address - add all countries.
For arrIdx = 0 To UBound(arrPreLocs)
oXform.addOption((oCountriesDropDown), Trim(CStr(arrPreLocs(arrIdx))), Trim(CStr(arrPreLocs(arrIdx))))
bPreSelect = True
Next
If bPreSelect Then
oXform.addOption((oCountriesDropDown), "--------", " ")
End If
If IDValues Then
sSql = "SELECT DISTINCT cLocationNameShort as name, nLocationKey as value FROM tblCartShippingLocations WHERE nLocationType = 2 ORDER BY cLocationNameShort"
Else
sSql = "SELECT DISTINCT cLocationNameShort as name, cLocationNameShort as value FROM tblCartShippingLocations WHERE nLocationType = 2 ORDER BY cLocationNameShort"
End If
oDr = moDBHelper.getDataReader(sSql)
oXform.addOptionsFromSqlDataReader(oCountriesDropDown, oDr)
'this closes the oDr too
End Select
Catch ex As Exception
returnException(mcModuleName, "populateCountriesDropDown", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Function emailCart(ByRef oCartXML As XmlElement, ByVal xsltPath As String, ByVal fromName As String, ByVal fromEmail As String, ByVal recipientEmail As String, ByVal SubjectLine As String, Optional ByVal bEncrypt As Boolean = False) As Object
PerfMon.Log("Cart", "emailCart")
Dim oXml As XmlDocument = New XmlDocument
Dim cProcessInfo As String = "emailCart"
Try
'check file path
Dim ofs As New Eonic.fsHelper()
oXml.LoadXml(oCartXML.OuterXml)
xsltPath = ofs.checkCommonFilePath(moConfig("ProjectPath") & xsltPath)
oCartXML.SetAttribute("lang", myWeb.mcPageLanguage)
Dim oMsg As Messaging = New Messaging
cProcessInfo = oMsg.emailer(oCartXML, xsltPath, fromName, fromEmail, recipientEmail, SubjectLine, "Message Sent", "Message Failed")
oMsg = Nothing
Return cProcessInfo
Catch ex As Exception
returnException(mcModuleName, "emailCart", ex, "", cProcessInfo, gbDebug)
Return Nothing
End Try
End Function
Public Sub DoNotesItem(ByVal cAction As String)
PerfMon.Log("Cart", "DoNotesItem")
Dim sSql As String
Dim cNotes As String ' xml string value, gets reused
Dim oNoteElmt As XmlElement
Dim oNoteXML As New XmlDocument
Dim oItem As Object
Dim oAttribs(0) As FormResult
Dim nQuantity As Integer = -1 'making it this number so we know
Dim cProcessInfo As String = "DoNotesLine"
Dim i As Integer
Dim cxPath As String = ""
Dim oTmpElements As XmlElement
Dim tmpDoc As New XmlDocument
Try
'if there is no active cart object (or quote) we need to make one
If mnCartId = 0 Then
Dim otmpcart As New Cart(myWeb)
mnCartId = otmpcart.CreateNewCart(Nothing)
End If
'now we need to get the notes from the cart
sSql = "Select cClientNotes from tblCartOrder where nCartOrderKey = " & mnCartId
cNotes = moDBHelper.DBN2Str(moDBHelper.ExeProcessSqlScalar(sSql), False, False)
'Check if it is empty
If cNotes = "" Then
'we get the empty notes schema from the notes xForm instance.
Dim oXform As xForm = New xForm
oXform.moPageXML = moPageXml
oXform.NewFrm("notesForm")
If oXform.load(mcNotesXForm) Then
oNoteXML.LoadXml(oXform.Instance.InnerXml)
Else
'no notes xform is spcificed so create new notes node
oNoteElmt = oNoteXML.CreateElement("Notes")
oNoteXML.AppendChild(oNoteElmt)
oNoteElmt = oNoteXML.CreateElement("Notes")
oNoteXML.SelectSingleNode("Notes").AppendChild(oNoteElmt)
End If
oXform = Nothing
Else
oNoteXML.InnerXml = cNotes
End If
cNotes = ""
'now to get on and create our nodes
For Each oItem In myWeb.moRequest.Form
If oItem = "node" Then
'this is the basic node text
cNotes = myWeb.moRequest.Form.Get(oItem)
Else
'this is the rest of the submitted form data
'going to be saved as attributes
ReDim Preserve oAttribs(UBound(oAttribs) + 1)
oAttribs(UBound(oAttribs) - 1) = New FormResult(oItem, myWeb.moRequest.Form.Get(oItem))
End If
Next
'creating a temporary xml document so we can turn the notes string
'into actual xml
tmpDoc.InnerXml = cNotes
oNoteElmt = Nothing
'now we can create an actual node in the main document with the right name
oNoteElmt = oNoteXML.CreateElement(tmpDoc.ChildNodes(0).Name)
'give it the same xml
oNoteElmt.InnerXml = tmpDoc.ChildNodes(0).InnerXml
'set the attributes
'and create an xpath excluding the quantity field to see if we have an identical node
Dim cIncludeList As String = myWeb.moRequest.Form("InputList")
For i = 0 To UBound(oAttribs) - 1
If cIncludeList.Contains(oAttribs(i).Name) Or cIncludeList = "" Then
oNoteElmt.SetAttribute(oAttribs(i).Name, oAttribs(i).Value)
If Not oAttribs(i).Name = "qty" Then
If Not cxPath = "" Then cxPath &= " and "
cxPath &= "@" & oAttribs(i).Name & "='" & oAttribs(i).Value & "'"
Else
nQuantity = oAttribs(i).Value
End If
End If
Next
'If Not oAttribs(i).Name = "cartCmd" And Not oAttribs(i).Name = "quoteCmd" Then
'finish of the xpath
cxPath = "Notes/" & oNoteElmt.Name & "[" & cxPath & "]"
'"addNoteLine", "removeNoteLine", "updateNoteLine"
'loop through any basic matchest to see if it exisists already
For Each oTmpElements In oNoteXML.SelectNodes("descendant-or-self::" & cxPath)
'we have a basic top level match
'does it match at a lower level
If oTmpElements.InnerXml = oNoteElmt.InnerXml Then
'ok, it matches, do we add to the quantity or remove it
If cAction = "removeNoteLine" Then
'its a remove
'check this
oNoteXML.SelectSingleNode("Notes").RemoveChild(oTmpElements)
'skip the addition of a notes item
GoTo SaveNotes
ElseIf cAction = "updateNoteLine" Then
'an update
oTmpElements.SetAttribute("qty", nQuantity)
' Complete Bodge for keysource
Dim cVAs As String = myWeb.moRequest.Form("VA")
If cVAs Is Nothing Or cVAs = "" Then cVAs = myWeb.moRequest.Form("Custom_VARating")
Dim nTotalVA As Integer = 0
If IsNumeric(cVAs) Then
nTotalVA = CDec(oTmpElements.GetAttribute("qty")) * CDec(cVAs)
If nTotalVA > 0 Then oTmpElements.SetAttribute("TotalVA", nTotalVA)
End If
GoTo SaveNotes
ElseIf Not nQuantity = -1 Then
'its an Add
oTmpElements.SetAttribute("qty", CInt(oTmpElements.GetAttribute("qty")) + nQuantity)
' Complete Bodge for keysource
Dim cVAs As String = myWeb.moRequest.Form("VA")
If cVAs Is Nothing Or cVAs = "" Then cVAs = myWeb.moRequest.Form("Custom_VARating")
Dim nTotalVA As Integer = 0
If IsNumeric(cVAs) Then
nTotalVA = CDec(oTmpElements.GetAttribute("qty")) * CDec(cVAs)
If nTotalVA > 0 Then oTmpElements.SetAttribute("TotalVA", nTotalVA)
End If
'skip the addition of a notes item
GoTo SaveNotes
Else
'dont do anything, there is no quantity involved so we just add the item anyway
End If
'there should only be one exact match so no need to go through the rest
Exit For
End If
Next
' Complete Bodge for keysource
Dim cVAsN As String = myWeb.moRequest.Form("VA")
If cVAsN Is Nothing Or cVAsN = "" Then cVAsN = myWeb.moRequest.Form("Custom_VARating")
Dim nTotalVAN As Integer = 0
If IsNumeric(cVAsN) Then
nTotalVAN = nQuantity * CDec(cVAsN)
If nTotalVAN > 0 Then oNoteElmt.SetAttribute("TotalVA", nTotalVAN)
End If
'we only actually hit this if there is no exact match
oNoteXML.DocumentElement.InsertAfter(oNoteElmt, oNoteXML.DocumentElement.LastChild)
SaveNotes: ' this is so we can skip the appending of new node
'now we just need to update the cart notes and the other
'procedures will do the rest
sSql = "UPDATE tblCartOrder SET cClientNotes = '" & oNoteXML.OuterXml & "' WHERE (nCartOrderKey = " & mnCartId & ")"
moDBHelper.ExeProcessSql(sSql)
Catch ex As Exception
returnException(mcModuleName, "addItems", ex, "", cProcessInfo, gbDebug)
End Try
End Sub
Public Sub ListOrders(Optional ByVal nOrderID As Integer = 0, Optional ByVal bListAllQuotes As Boolean = False, Optional ByVal ProcessId As Integer = 0, Optional ByRef oPageDetail As XmlElement = Nothing, Optional ByVal bForceRefresh As Boolean = False, Optional nUserId As Long = 0)
PerfMon.Log("Cart", "ListOrders")
If myWeb.mnUserId = 0 Then Exit Sub ' if not logged in, dont bother
'For listing a users previous orders/quotes
Dim oDs As New DataSet
Dim cSQL As String
Dim cWhereSQL As String = ""
' Paging variables
Dim nStart As Integer = 0
Dim nRows As Integer = 100
Dim nCurrentRow As Integer = 0
Dim moPaymentCfg = WebConfigurationManager.GetWebApplicationSection("eonic/payment")
Try
' Set the paging variables, if provided.
If Not (myWeb.moRequest("startPos") Is Nothing) AndAlso IsNumeric(myWeb.moRequest("startPos")) Then nStart = CInt(myWeb.moRequest("startPos"))
If Not (myWeb.moRequest("rows") Is Nothing) AndAlso IsNumeric(myWeb.moRequest("rows")) Then nRows = CInt(myWeb.moRequest("rows"))
If nStart < 0 Then nStart = 0
If nRows < 1 Then nRows = 100
If Not nUserId = 0 Then
cWhereSQL = " WHERE nCartUserDirId = " & nUserId & IIf(nOrderID > 0, " AND nCartOrderKey = " & nOrderID, "") & " AND cCartSchemaName = '" & mcOrderType & "'"
ElseIf Not myWeb.mbAdminMode Then
cWhereSQL = " WHERE nCartUserDirId = " & myWeb.mnUserId & IIf(nOrderID > 0, " AND nCartOrderKey = " & nOrderID, "") & " AND cCartSchemaName = '" & mcOrderType & "'"
Else
cWhereSQL = " WHERE " & IIf(nOrderID > 0, " nCartOrderKey = " & nOrderID & " AND ", "") & " cCartSchemaName = '" & mcOrderType & "' "
'if nCartStatus = " & ProcessId
If Not ProcessId = 0 Then
cWhereSQL &= " and nCartStatus = " & ProcessId
End If
End If
' Quick call to get the total number of records
cSQL = "SELECT COUNT(*) As Count FROM tblCartOrder " & cWhereSQL
Dim nTotal As Long = moDBHelper.GetDataValue(cSQL, , , 0)
If nTotal > 0 Then
' Initial paging option is limit the the rows returned
cSQL = "SELECT TOP " & (nStart + nRows) & " * FROM tblCartOrder "
cSQL &= cWhereSQL & " ORDER BY nCartOrderKey Desc"
oDs = moDBHelper.GetDataSet(cSQL, mcOrderType, mcOrderType & "List")
Dim oDR As DataRow
If oDs.Tables.Count > 0 Then
Dim oContentDetails As XmlElement
'Get the content Detail element
If oPageDetail Is Nothing Then
oContentDetails = moPageXml.SelectSingleNode("Page/ContentDetail")
If oContentDetails Is Nothing Then
oContentDetails = moPageXml.CreateElement("ContentDetail")
If Not moPageXml.InnerXml = "" Then
moPageXml.FirstChild.AppendChild(oContentDetails)
Else
oPageDetail.AppendChild(oContentDetails)
End If
End If
Else
oContentDetails = oPageDetail
End If
oContentDetails.SetAttribute("start", nStart)
oContentDetails.SetAttribute("total", nTotal)
Dim bSingleRecord As Boolean = False
If oDs.Tables(mcOrderType).Rows.Count = 1 Then bSingleRecord = True
'go through each cart
For Each oDR In oDs.Tables(mcOrderType).Rows
' Only add the relevant rows (page selected)
nCurrentRow += 1
If nCurrentRow > nStart Then
Dim oContent As XmlElement = moPageXml.CreateElement("Content")
oContent.SetAttribute("type", mcOrderType)
oContent.SetAttribute("id", oDR("nCartOrderKey"))
oContent.SetAttribute("statusId", oDR("nCartStatus"))
'Get Date
cSQL = "Select dInsertDate from tblAudit where nAuditKey =" & oDR("nAuditId")
Dim oDRe As SqlDataReader = moDBHelper.getDataReader(cSQL)
Do While oDRe.Read
oContent.SetAttribute("created", xmlDateTime(oDRe.GetValue(0)))
Loop
oDRe.Close()
'Get stored CartXML
If (Not oDR("cCartXML") = "") And bForceRefresh = False Then
oContent.InnerXml = oDR("cCartXML")
Else
Dim oCartListElmt As XmlElement = moPageXml.CreateElement("Order")
Me.GetCart(oCartListElmt, oDR("nCartOrderKey"))
oContent.InnerXml = oCartListElmt.OuterXml
End If
Dim orderNode As XmlElement = oContent.FirstChild
'Add values not stored in cartXml
orderNode.SetAttribute("statusId", oDR("nCartStatus"))
If oDR("cCurrency") Is Nothing Or oDR("cCurrency") = "" Then
oContent.SetAttribute("currency", mcCurrency)
oContent.SetAttribute("currencySymbol", mcCurrencySymbol)
Else
oContent.SetAttribute("currency", oDR("cCurrency"))
Dim thisCurrencyNode As XmlElement = moPaymentCfg.SelectSingleNode("currencies/Currency[@ref='" & oDR("cCurrency") & "']")
If Not thisCurrencyNode Is Nothing Then
oContent.SetAttribute("currencySymbol", thisCurrencyNode.GetAttribute("symbol"))
Else
oContent.SetAttribute("currencySymbol", mcCurrencySymbol)
End If
End If
oContent.SetAttribute("type", LCase(mcOrderType))
'oContent.SetAttribute("currency", mcCurrency)
'oContent.SetAttribute("currencySymbol", mcCurrencySymbol)
If oDR("nCartUserDirId") <> 0 Then
oContent.SetAttribute("userId", oDR("nCartUserDirId"))
End If
'TS: Removed because it gives a massive overhead when Listing loads of orders.
If bSingleRecord Then
If myWeb.mbAdminMode And CInt("0" & oDR("nCartUserDirId")) > 0 Then
oContent.AppendChild(moDBHelper.GetUserXML(CInt(oDR("nCartUserDirId")), False))
End If
addNewTextNode("Notes", oContent.FirstChild, oDR("cClientNotes"))
Dim aSellerNotes As String() = Split(oDR("cSellerNotes"), "/n")
Dim cSellerNotesHtml As String = "<ul>"
For snCount As Integer = 0 To UBound(aSellerNotes)
cSellerNotesHtml = cSellerNotesHtml + "<li>" + Eonic.Tools.Xml.convertEntitiesToCodes(aSellerNotes(snCount)) + "</li>"
Next
Dim sellerNode As XmlElement = addNewTextNode("SellerNotes", oContent.FirstChild, "")
sellerNode.InnerXml = cSellerNotesHtml + "</ul>"
'Add the Delivery Details
'Add Delivery Details
If oDR("nCartStatus") = 9 Then
Dim sSql As String = "Select * from tblCartOrderDelivery where nOrderId=" & oDR("nCartOrderKey")
Dim oDs2 As DataSet = moDBHelper.GetDataSet(sSql, "Delivery", "Details")
For Each oRow2 As DataRow In oDs2.Tables("Delivery").Rows
Dim oElmt As XmlElement = moPageXml.CreateElement("DeliveryDetails")
oElmt.SetAttribute("carrierName", oRow2("cCarrierName"))
oElmt.SetAttribute("ref", oRow2("cCarrierRef"))
oElmt.SetAttribute("notes", oRow2("cCarrierNotes"))
oElmt.SetAttribute("deliveryDate", xmlDate(oRow2("dExpectedDeliveryDate")))
oElmt.SetAttribute("collectionDate", xmlDate(oRow2("dCollectionDate")))
oContent.AppendChild(oElmt)
Next
End If
End If
Dim oTestNode As XmlElement = oContentDetails.SelectSingleNode("Content[@id=" & oContent.GetAttribute("id") & " and @type='" & LCase(mcOrderType) & "']")
If mcOrderType = "Cart" Or mcOrderType = "Order" Then
'If (Not oContent.FirstChild.Attributes("itemCount").Value = 0) And oTestNode Is Nothing Then
oContentDetails.AppendChild(oContent)
'End If
Else
If oTestNode Is Nothing Then
If bListAllQuotes Then
oContentDetails.AppendChild(oContent)
Else
' If (Not oContent.FirstChild.Attributes("itemCount").Value = 0) Then
oContentDetails.AppendChild(oContent)
' End If
End If
End If
End If
'If (Not oContent.FirstChild.Attributes("itemCount").Value = 0) And oTestNode Is Nothing Then
' oContentDetails.AppendChild(oContent)
'End If
End If
Next
End If
End If
Catch ex As Exception
returnException(mcModuleName, "ListOrders", ex, "", "", gbDebug)
End Try
End Sub
Public Overridable Sub MakeCurrent(ByVal nOrderID As Integer)
PerfMon.Log("Cart", "MakeCurrent")
'procedure to make a selected historical
'order or quote into the currently active one
Dim oDS As New DataSet
Dim otmpcart As Cart = Nothing
Try
If myWeb.mnUserId = 0 Then Exit Sub
If Not moDBHelper.ExeProcessSqlScalar("Select nCartUserDirId FROM tblCartOrder WHERE nCartOrderKey = " & nOrderID) = mnEwUserId Then
Exit Sub 'else we carry on
End If
If mnCartId = 0 Then
'create a new cart
otmpcart = New Cart(myWeb)
otmpcart.CreateNewCart(Nothing)
mnCartId = otmpcart.mnCartId
End If
'now add the details to it
oDS = moDBHelper.GetDataSet("Select * From tblCartItem WHERE nCartOrderID = " & nOrderID, "CartItems")
Dim oDR1 As DataRow
Dim oDR2 As DataRow
Dim nParentID As Integer
Dim sSQL As String
moDBHelper.ReturnNullsEmpty(oDS)
For Each oDR1 In oDS.Tables("CartItems").Rows
If oDR1("nParentId") = 0 Then
sSQL = "INSERT INTO tblCartItem (nCartOrderId, nItemId, nParentId, cItemRef, cItemURL, " & _
"cItemName, nItemOptGrpIdx, nItemOptIdx, nPrice, nShpCat, nDiscountCat, nDiscountValue, " & _
"nTaxRate, nQuantity, nWeight, nAuditId) VALUES ("
sSQL &= mnCartId & ","
sSQL &= IIf(IsDBNull(oDR1("nItemId")), "Null", oDR1("nItemId")) & ","
sSQL &= IIf(IsDBNull(oDR1("nParentId")), "Null", oDR1("nParentId")) & ","
sSQL &= IIf(IsDBNull(oDR1("cItemRef")), "Null", "'" & oDR1("cItemRef")) & "',"
sSQL &= IIf(IsDBNull(oDR1("cItemURL")), "Null", "'" & oDR1("cItemURL")) & "',"
sSQL &= IIf(IsDBNull(oDR1("cItemName")), "Null", "'" & oDR1("cItemName")) & "',"
sSQL &= IIf(IsDBNull(oDR1("nItemOptGrpIdx")), "Null", oDR1("nItemOptGrpIdx")) & ","
sSQL &= IIf(IsDBNull(oDR1("nItemOptIdx")), "Null", oDR1("nItemOptIdx")) & ","
sSQL &= IIf(IsDBNull(oDR1("nPrice")), "Null", oDR1("nPrice")) & ","
sSQL &= IIf(IsDBNull(oDR1("nShpCat")), "Null", oDR1("nShpCat")) & ","
sSQL &= IIf(IsDBNull(oDR1("nDiscountCat")), "Null", oDR1("nDiscountCat")) & ","
sSQL &= IIf(IsDBNull(oDR1("nDiscountValue")), "Null", oDR1("nDiscountValue")) & ","
sSQL &= IIf(IsDBNull(oDR1("nTaxRate")), "Null", oDR1("nTaxRate")) & ","
sSQL &= IIf(IsDBNull(oDR1("nQuantity")), "Null", oDR1("nQuantity")) & ","
sSQL &= IIf(IsDBNull(oDR1("nWeight")), "Null", oDR1("nWeight")) & ","
sSQL &= moDBHelper.getAuditId() & ")"
nParentID = moDBHelper.GetIdInsertSql(sSQL)
'now for any children
For Each oDR2 In oDS.Tables("CartItems").Rows
If oDR2("nParentId") = oDR1("nCartItemKey") Then
sSQL = "INSERT INTO tblCartItem (nCartOrderId, nItemId, nParentId, cItemRef, cItemURL, " & _
"cItemName, nItemOptGrpIdx, nItemOptIdx, nPrice, nShpCat, nDiscountCat, nDiscountValue, " & _
"nTaxRate, nQuantity, nWeight, nAuditId) VALUES ("
sSQL &= mnCartId & ","
sSQL &= IIf(IsDBNull(oDR2("nItemId")), "Null", oDR2("nItemId")) & ","
sSQL &= nParentID & ","
sSQL &= IIf(IsDBNull(oDR2("cItemRef")), "Null", "'" & oDR2("cItemRef")) & "',"
sSQL &= IIf(IsDBNull(oDR2("cItemURL")), "Null", "'" & oDR2("cItemURL")) & "',"
sSQL &= IIf(IsDBNull(oDR2("cItemName")), "Null", "'" & oDR2("cItemName")) & "',"
sSQL &= IIf(IsDBNull(oDR2("nItemOptGrpIdx")), "Null", oDR2("nItemOptGrpIdx")) & ","
sSQL &= IIf(IsDBNull(oDR2("nItemOptIdx")), "Null", oDR2("nItemOptIdx")) & ","
sSQL &= IIf(IsDBNull(oDR2("nPrice")), "Null", oDR2("nPrice")) & ","
sSQL &= IIf(IsDBNull(oDR2("nShpCat")), "Null", oDR2("nShpCat")) & ","
sSQL &= IIf(IsDBNull(oDR2("nDiscountCat")), "Null", oDR2("nDiscountCat")) & ","
sSQL &= IIf(IsDBNull(oDR2("nDiscountValue")), "Null", oDR2("nDiscountValue")) & ","
sSQL &= IIf(IsDBNull(oDR2("nTaxRate")), "Null", oDR2("nTaxRate")) & ","
sSQL &= IIf(IsDBNull(oDR2("nQuantity")), "Null", oDR2("nQuantity")) & ","
sSQL &= IIf(IsDBNull(oDR2("nWeight")), "Null", oDR2("nWeight")) & ","
sSQL &= moDBHelper.getAuditId() & ")"
moDBHelper.GetIdInsertSql(sSQL)
'now for any children
End If
Next
End If
Next
If Not otmpcart Is Nothing Then
otmpcart.mnProcessId = 1
otmpcart.mcCartCmd = "Cart"
otmpcart.apply()
End If
'now we need to redirect somewhere?
'bRedirect = True
myWeb.moResponse.Redirect("?cartCmd=Cart", False)
myWeb.moCtx.ApplicationInstance.CompleteRequest()
Catch ex As Exception
returnException(mcModuleName, "MakeCurrent", ex, "", "", gbDebug)
End Try
End Sub
Public Function DeleteCart(ByVal nOrderID As Integer) As Boolean
PerfMon.Log("Cart", "DeleteCart")
If myWeb.mnUserId = 0 Then Exit Function
If nOrderID <= 0 Then Exit Function
Try
clearSessionCookie()
Dim cSQL As String = "Select nCartStatus, nCartUserDirId from tblCartOrder WHERE nCartOrderKey=" & nOrderID
Dim oDR As SqlDataReader = moDBHelper.getDataReader(cSQL)
Dim nStat As Integer
Dim nOwner As Integer
Do While oDR.Read
nStat = oDR.GetValue(0)
nOwner = oDR.GetValue(1)
Loop
oDR.Close()
'If (nOwner = myWeb.mnUserId And (nStat = 7 Or nStat < 4)) Then moDBHelper.DeleteObject(dbHelper.objectTypes.CartOrder, nOrderID)
If nOwner = myWeb.mnUserId Then
moDBHelper.DeleteObject(dbHelper.objectTypes.CartOrder, nOrderID)
Return True
Else
Return False
End If
Catch ex As Exception
returnException(mcModuleName, "Delete Cart", ex, "", "", gbDebug)
End Try
End Function
Public Sub SaveCartXML(ByVal cartXML As XmlElement)
PerfMon.Log("Cart", "SaveCartXML")
Try
If mnCartId > 0 Then
Dim sSQL As String = "Update tblCartOrder SET cCartXML ='" & SqlFmt(cartXML.OuterXml.ToString) & "' WHERE nCartOrderKey = " & mnCartId
moDBHelper.ExeProcessSql(sSQL)
End If
Catch ex As Exception
returnException(mcModuleName, "SaveCartXML", ex, "", "", gbDebug)
End Try
End Sub
''' <summary>
''' Select currency deals with the workflow around choosing a currency when an item is added to the cart.
''' </summary>
''' <returns></returns>
Public Function SelectCurrency() As Boolean
If Not PerfMon Is Nothing Then PerfMon.Log("Cart", "SelectCurrency")
Dim cProcessInfo As String = ""
Try
cProcessInfo = "checking of Override"
'if we are not looking to switch the currency then
'we just check if there are any available
Dim cOverrideCur As String
cOverrideCur = myWeb.moRequest("Currency")
If Not cOverrideCur Is Nothing And Not cOverrideCur = "" Then
cProcessInfo = "Using Override"
mcCurrencyRef = cOverrideCur
GetCurrencyDefinition()
myWeb.moSession("bCurrencySelected") = True
If mnProcessId >= 1 Then
If mnShippingRootId > 0 Then
mnProcessId = 2
mcCartCmd = "Delivery"
Else
mcCartCmd = "Cart"
End If
Else
mcCartCmd = ""
End If
Return True
Else
cProcessInfo = "Check to see if already used"
If myWeb.moSession("bCurrencySelected") = True Then
If mcCartCmd = "Currency" Then
mcCartCmd = "Cart"
Else
mcCartCmd = mcCartCmd
End If
Return True
End If
End If
cProcessInfo = "Getting Currencies"
Dim moPaymentCfg As XmlNode
moPaymentCfg = WebConfigurationManager.GetWebApplicationSection("eonic/payment")
If moPaymentCfg Is Nothing Then
cProcessInfo = "eonic/payment Config node is missing"
mcCartCmd = "Cart"
Return True
End If
'check we have differenct currencies
If moPaymentCfg.SelectSingleNode("currencies/Currency") Is Nothing Then
' mcCartCmd = "Cart"
myWeb.moSession("bCurrencySelected") = True
Return True
Else
Dim oCurrencies As XmlNodeList = moPaymentCfg.SelectNodes("currencies/Currency")
If oCurrencies.Count = 1 Then
Dim oCurrency As XmlElement = oCurrencies(0)
myWeb.moSession("cCurrency") = oCurrency.GetAttribute("ref")
'here we need to re-get the cart stuff in the new currency
GetCurrencyDefinition()
' mcCartCmd = "Cart"
myWeb.moSession("bCurrencySelected") = True
Return True
End If
oCurrencies = Nothing
'If multiple currencies then we need to pick
End If
'If Not bOverride And Not mcCurrencyRef = "" Then Return True
If mcCartCmd = "Currency" Then
'And mcCurrencyRef = "" Then Return True
'get and load the currency selector xform
cProcessInfo = "Supplying and Checking Form"
Dim oCForm As New xForm(myWeb)
oCForm.NewFrm()
oCForm.load("/ewcommon/xforms/cart/CurrencySelector.xml")
Dim oInputElmt As XmlElement = oCForm.moXformElmt.SelectSingleNode("group/group/group/select1[@bind='cRef']")
Dim oCur As XmlElement = oCForm.Instance.SelectSingleNode("Currency/ref")
oCur.InnerText = mcCurrency
Dim oCurrencyElmt As XmlElement
For Each oCurrencyElmt In moPaymentCfg.SelectNodes("currencies/Currency")
'going to need to do something about languages
Dim oOptionElmt As XmlElement
oOptionElmt = oCForm.addOption(oInputElmt, oCurrencyElmt.SelectSingleNode("name").InnerText, oCurrencyElmt.GetAttribute("ref"))
oCForm.addNote(oOptionElmt, xForm.noteTypes.Hint, oCurrencyElmt.SelectSingleNode("description").InnerText)
Next
If oCForm.isSubmitted Then
oCForm.updateInstanceFromRequest()
oCForm.addValues()
oCForm.validate()
If oCForm.valid Then
mcCurrencyRef = oCForm.Instance.SelectSingleNode("Currency/ref").InnerText
myWeb.moSession("cCurrency") = mcCurrencyRef
'here we need to re-get the cart stuff in the new currency
GetCurrencyDefinition()
myWeb.moSession("bCurrencySelected") = True
mcCartCmd = "Cart"
Return True
End If
End If
oCForm.addValues()
If Not moPageXml.SelectSingleNode("/Page/Contents") Is Nothing Then
moPageXml.SelectSingleNode("/Page/Contents").AppendChild(moPageXml.ImportNode(oCForm.moXformElmt.CloneNode(True), True))
End If
mcCartCmd = "Currency"
Return False
End If
Catch ex As Exception
returnException(mcModuleName, "SelectCurrency", ex, "", cProcessInfo, gbDebug)
End Try
End Function
''' <summary>
''' takes the mcCurrencyRef and sets the currency for the current order
''' </summary>
Public Sub GetCurrencyDefinition()
If Not PerfMon Is Nothing Then PerfMon.Log("Cart", "GetCurrencyDefinition")
Dim cProcessInfo As String = ""
Try
If Not mcCurrencyRef = "" And Not mcCurrencyRef Is Nothing Then
Dim moPaymentCfg As XmlNode
moPaymentCfg = WebConfigurationManager.GetWebApplicationSection("eonic/payment")
Dim oCurrency As XmlElement = moPaymentCfg.SelectSingleNode("currencies/Currency[@ref='" & mcCurrencyRef & "']")
If oCurrency Is Nothing Then Exit Sub
mcCurrencySymbol = oCurrency.GetAttribute("symbol")
mcCurrencyCode = oCurrency.GetAttribute("code")
mnShippingRootId = -1
If IsNumeric(oCurrency.GetAttribute("ShippingRootId")) Then
mnShippingRootId = CInt(oCurrency.GetAttribute("ShippingRootId"))
End If
mcCurrency = mcCurrencyCode
myWeb.moSession("cCurrency") = mcCurrencyRef
myWeb.moSession("mcCurrency") = mcCurrency
'now update the cart database row
Dim sSQL As String = "UPDATE tblCartOrder SET cCurrency = '" & mcCurrency & "' WHERE nCartOrderKey = " & mnCartId
myWeb.moDbHelper.ExeProcessSqlScalar(sSQL)
End If
Catch ex As Exception
returnException(mcModuleName, "GetCurrencyDefinition", ex, , cProcessInfo, gbDebug)
End Try
End Sub
Public Function CartOverview() As XmlElement
Try
Dim oRptElmt As XmlElement = myWeb.moPageXml.CreateElement("CartOverview")
Return oRptElmt
Catch ex As Exception
returnException(mcModuleName, "CartOverview", ex, , "", gbDebug)
Return Nothing
End Try
End Function
Public Function CartReportsDownload(ByVal dBegin As Date, ByVal dEnd As Date, ByVal cCurrencySymbol As String, ByVal cOrderType As String, ByVal nOrderStage As Integer, Optional ByVal updateDatesWithStartAndEndTimes As Boolean = True) As XmlElement
Try
Dim cSQL As String = "exec "
Dim cCustomParam As String = ""
Dim cReportType As String = "CartDownload"
Dim oElmt As XmlElement
' Set the times for each date
If updateDatesWithStartAndEndTimes Then
dBegin = dBegin.Date
dEnd = dEnd.Date.AddHours(23).AddMinutes(59).AddSeconds(59)
End If
cSQL &= moDBHelper.getDBObjectNameWithBespokeCheck("spOrderDownload") & " "
cSQL &= Eonic.Tools.Database.SqlDate(dBegin, True) & ","
cSQL &= Eonic.Tools.Database.SqlDate(dEnd, True) & ","
cSQL &= "'" & cOrderType & "',"
cSQL &= nOrderStage
Dim oDS As DataSet = myWeb.moDbHelper.GetDataSet(cSQL, "Item", "Report")
If oDS.Tables("Item").Columns.Contains("cCartXML") Then
oDS.Tables("Item").Columns("cCartXML").ColumnMapping = MappingType.Element
End If
Dim oRptElmt As XmlElement = myWeb.moPageXml.CreateElement("Content")
oRptElmt.SetAttribute("type", "Report")
oRptElmt.SetAttribute("name", "CartDownloads")
'NB editing this line to add in &'s
oRptElmt.InnerXml = oDS.GetXml
For Each oElmt In oRptElmt.SelectNodes("Report/Item/cCartXml")
oElmt.InnerXml = oElmt.InnerText
Next
'oRptElmt.InnerXml = Replace(Replace(Replace(Replace(oDS.GetXml, "&", "&"), ">", ">"), "<", "<"), " xmlns=""""", "")
'oRptElmt.InnerXml = Replace(Replace(Replace(oDS.GetXml, ">", ">"), "<", "<"), " xmlns=""""", "")
Dim oReturnElmt As XmlElement = oRptElmt.FirstChild
oReturnElmt.SetAttribute("cReportType", cReportType)
oReturnElmt.SetAttribute("dBegin", dBegin)
oReturnElmt.SetAttribute("dEnd", dEnd)
oReturnElmt.SetAttribute("cCurrencySymbol", cCurrencySymbol)
oReturnElmt.SetAttribute("cOrderType", cOrderType)
oReturnElmt.SetAttribute("nOrderStage", nOrderStage)
Return oRptElmt
Catch ex As Exception
returnException(mcModuleName, "CartReports", ex, , "", gbDebug)
Return Nothing
End Try
End Function
Public Function CartReports(ByVal dBegin As Date, ByVal dEnd As Date, Optional ByVal bSplit As Integer = 0, Optional ByVal cProductType As String = "", Optional ByVal nProductId As Integer = 0, Optional ByVal cCurrencySymbol As String = "", Optional ByVal nOrderStatus1 As Integer = 6, Optional ByVal nOrderStatus2 As Integer = 9, Optional ByVal cOrderType As String = "ORDER") As XmlElement
Try
Dim cSQL As String = "exec "
Dim cCustomParam As String = ""
Dim cReportType As String = ""
If nProductId > 0 Then
'Low Level
cSQL &= "spCartActivityLowLevel"
cCustomParam = nProductId
cReportType = "Item Totals"
ElseIf Not cProductType = "" Then
'Med Level
cSQL &= "spCartActivityMedLevel"
cCustomParam = "'" & cProductType & "'"
cReportType = "Type Totals"
Else
'HighLevel
cSQL &= "spCartActivityTopLevel"
cCustomParam = bSplit
cReportType = "All Totals"
End If
cSQL &= Eonic.Tools.Database.SqlDate(dBegin) & ","
cSQL &= Eonic.Tools.Database.SqlDate(dEnd) & ","
cSQL &= cCustomParam & ","
cSQL &= "'" & cCurrencySymbol & "',"
cSQL &= nOrderStatus1 & ","
cSQL &= nOrderStatus2 & ","
cSQL &= "'" & cOrderType & "'"
Dim oDS As DataSet = myWeb.moDbHelper.GetDataSet(cSQL, "Item", "Report")
If oDS.Tables("Item").Columns.Contains("cCartXML") Then
oDS.Tables("Item").Columns("cCartXML").ColumnMapping = MappingType.Element
End If
Dim oRptElmt As XmlElement = myWeb.moPageXml.CreateElement("Content")
oRptElmt.SetAttribute("type", "Report")
oRptElmt.SetAttribute("name", "Cart Activity")
oRptElmt.InnerXml = Replace(Replace(oDS.GetXml, ">", ">"), "<", "<")
Dim oReturnElmt As XmlElement = oRptElmt.FirstChild
oReturnElmt.SetAttribute("cReportType", cReportType)
oReturnElmt.SetAttribute("dBegin", dBegin)
oReturnElmt.SetAttribute("dEnd", dEnd)
oReturnElmt.SetAttribute("bSplit", IIf(bSplit, 1, 0))
oReturnElmt.SetAttribute("cProductType", cProductType)
oReturnElmt.SetAttribute("nProductId", nProductId)
oReturnElmt.SetAttribute("cCurrencySymbol", cCurrencySymbol)
oReturnElmt.SetAttribute("nOrderStatus1", nOrderStatus1)
oReturnElmt.SetAttribute("nOrderStatus2", nOrderStatus2)
oReturnElmt.SetAttribute("cOrderType", cOrderType)
Return oRptElmt
Catch ex As Exception
returnException(mcModuleName, "CartReports", ex, , "", gbDebug)
Return Nothing
End Try
End Function
Public Function CartReportsDrilldown(Optional ByVal cGrouping As String = "Page", Optional ByVal nYear As Integer = 0, Optional ByVal nMonth As Integer = 0, Optional ByVal nDay As Integer = 0, Optional ByVal cCurrencySymbol As String = "", Optional ByVal nOrderStatus1 As Integer = 6, Optional ByVal nOrderStatus2 As Integer = 9, Optional ByVal cOrderType As String = "ORDER") As XmlElement
Try
Dim cSQL As String = "exec spCartActivityGroupsPages "
Dim bPage As Boolean = False
Dim cReportType As String = ""
cSQL &= "'" & cGrouping & "',"
cSQL &= nYear & ","
cSQL &= nMonth & ","
cSQL &= nDay & ","
cSQL &= "'" & cCurrencySymbol & "',"
cSQL &= nOrderStatus1 & ","
cSQL &= nOrderStatus2 & ","
cSQL &= "'" & cOrderType & "'"
Dim oDS As DataSet = myWeb.moDbHelper.GetDataSet(cSQL, "Item", "Report")
'For Grouped by page is going to be bloody hard
If oDS.Tables("Item").Columns.Contains("nStructId") Then
bPage = True
cSQL = "EXEC getContentStructure @userId=" & myWeb.mnUserId & ", @bAdminMode=1, @dateNow=" & Eonic.Tools.Database.SqlDate(Now) & ", @authUsersGrp = " & gnAuthUsers
myWeb.moDbHelper.addTableToDataSet(oDS, cSQL, "MenuItem")
'oDS.Tables("MenuItem").Columns.Add(New DataColumn("PageQuantity", GetType(Double)))
'oDS.Tables("MenuItem").Columns.Add(New DataColumn("PageCost", GetType(Double)))
'oDS.Tables("MenuItem").Columns.Add(New DataColumn("DecendantQuantity", GetType(Double)))
'oDS.Tables("MenuItem").Columns.Add(New DataColumn("DecendantCost", GetType(Double)))
For Each oDC As DataColumn In oDS.Tables("MenuItem").Columns
Dim cValid As String = "id,parid,name" ',PageQuantity,PageCost,DecendantQuantity,DecendantCost"
If Not cValid.Contains(oDC.ColumnName) Then
oDC.ColumnMapping = MappingType.Hidden
Else
oDC.ColumnMapping = MappingType.Attribute
End If
Next
For Each oDC As DataColumn In oDS.Tables("Item").Columns
oDC.ColumnMapping = MappingType.Attribute
Next
oDS.Relations.Add("Rel01", oDS.Tables("MenuItem").Columns("id"), oDS.Tables("MenuItem").Columns("parId"), False)
oDS.Relations("Rel01").Nested = True
oDS.Relations.Add(New DataRelation("Rel02", oDS.Tables("MenuItem").Columns("id"), oDS.Tables("Item").Columns("nStructId"), False))
oDS.Relations("Rel02").Nested = True
End If
Dim oRptElmt As XmlElement = myWeb.moPageXml.CreateElement("Content")
oRptElmt.SetAttribute("type", "Report")
oRptElmt.SetAttribute("name", "Cart Activity")
oRptElmt.InnerXml = oDS.GetXml
Dim oReturnElmt As XmlElement = oRptElmt.FirstChild
oReturnElmt.SetAttribute("cReportType", cReportType)
oReturnElmt.SetAttribute("nYear", nYear)
oReturnElmt.SetAttribute("nMonth", nMonth)
oReturnElmt.SetAttribute("nDay", nDay)
oReturnElmt.SetAttribute("cGrouping", cGrouping)
oReturnElmt.SetAttribute("cCurrencySymbol", cCurrencySymbol)
oReturnElmt.SetAttribute("nOrderStatus1", nOrderStatus1)
oReturnElmt.SetAttribute("nOrderStatus2", nOrderStatus2)
oReturnElmt.SetAttribute("cOrderType", cOrderType)
If bPage Then
'Page Totals
For Each oElmt As XmlElement In oReturnElmt.SelectNodes("descendant-or-self::MenuItem")
Dim nQ As Integer = 0
Dim nC As Double = 0
For Each oItemElmt As XmlElement In oElmt.SelectNodes("Item")
nQ += oItemElmt.GetAttribute("nQuantity")
nC += oItemElmt.GetAttribute("nLinePrice")
Next
oElmt.SetAttribute("PageQuantity", nQ)
oElmt.SetAttribute("PageCost", nC)
Next
'loop through each node and then each item and see how many of each
'item it has and its decendants
For Each oElmt As XmlElement In oReturnElmt.SelectNodes("descendant-or-self::MenuItem")
Dim oHN As New Hashtable 'Number found
Dim oHQ As New Hashtable 'Quantity
Dim oHC As New Hashtable 'Cost
For Each oItem As XmlElement In oElmt.SelectNodes("descendant-or-self::Item")
Dim cKey As String = "I" & oItem.GetAttribute("nCartItemKey")
If Not oHN.ContainsKey(cKey) Then
oHN.Add(cKey, 1)
oHQ.Add(cKey, oItem.GetAttribute("nQuantity"))
oHC.Add(cKey, oItem.GetAttribute("nLinePrice"))
Else
oHN(cKey) += 1
End If
Next
Dim nQ As Integer = 0
Dim nC As Double = 0
For Each ci As String In oHN.Keys
nQ += oHQ.Item(ci)
nC += oHC.Item(ci)
Next
oElmt.SetAttribute("PageAndDescendantQuantity", nQ)
oElmt.SetAttribute("PageAndDescendantCost", nC)
Next
End If
If bPage And gnTopLevel > 0 Then
Dim oElmt As XmlElement = oRptElmt.SelectSingleNode("descendant-or-self::MenuItem[@id=" & gnTopLevel & "]")
If Not oElmt Is Nothing Then
oRptElmt.FirstChild.InnerXml = oElmt.OuterXml
Else
oRptElmt.FirstChild.InnerXml = ""
End If
End If
Return oRptElmt
Catch ex As Exception
returnException(mcModuleName, "CartReports", ex, , "", gbDebug)
Return Nothing
End Try
End Function
Public Function CartReportsPeriod(Optional ByVal cGroup As String = "Month", Optional ByVal nYear As Integer = 0, Optional ByVal nMonth As Integer = 0, Optional ByVal nWeek As Integer = 0, Optional ByVal cCurrencySymbol As String = "", Optional ByVal nOrderStatus1 As Integer = 6, Optional ByVal nOrderStatus2 As Integer = 9, Optional ByVal cOrderType As String = "ORDER") As XmlElement
Try
Dim cSQL As String = "exec spCartActivityPagesPeriod "
Dim bPage As Boolean = False
Dim cReportType As String = ""
If nYear = 0 Then nYear = Now.Year
cSQL &= "@Group='" & cGroup & "'"
cSQL &= ",@nYear=" & nYear
cSQL &= ",@nMonth=" & nMonth
cSQL &= ",@nWeek=" & nWeek
cSQL &= ",@cCurrencySymbol='" & cCurrencySymbol & "'"
cSQL &= ",@nOrderStatus1=" & nOrderStatus1
cSQL &= ",@nOrderStatus2=" & nOrderStatus2
cSQL &= ",@cOrderType='" & cOrderType & "'"
Dim oDS As DataSet = myWeb.moDbHelper.GetDataSet(cSQL, "Item", "Report")
'For Grouped by page is going to be bloody hard
Dim oRptElmt As XmlElement = myWeb.moPageXml.CreateElement("Content")
oRptElmt.SetAttribute("type", "Report")
oRptElmt.SetAttribute("name", "Cart Activity")
oRptElmt.InnerXml = oDS.GetXml
Dim oReturnElmt As XmlElement = oRptElmt.FirstChild
oReturnElmt.SetAttribute("cReportType", cReportType)
oReturnElmt.SetAttribute("nYear", nYear)
oReturnElmt.SetAttribute("nMonth", nMonth)
oReturnElmt.SetAttribute("nWeek", nWeek)
oReturnElmt.SetAttribute("cGroup", cGroup)
oReturnElmt.SetAttribute("cCurrencySymbol", cCurrencySymbol)
oReturnElmt.SetAttribute("nOrderStatus1", nOrderStatus1)
oReturnElmt.SetAttribute("nOrderStatus2", nOrderStatus2)
oReturnElmt.SetAttribute("cOrderType", cOrderType)
Return oRptElmt
Catch ex As Exception
returnException(mcModuleName, "CartReports", ex, , "", gbDebug)
Return Nothing
End Try
End Function
Public Sub AddShippingCosts(ByRef xmlProduct As XmlElement, ByVal nPrice As String, ByVal nWeight As String)
Try
Dim nQuantity As Long = 1
xmlProduct.SetAttribute("test1", "1")
Dim xmlShippingOptions As XmlElement = makeShippingOptionsXML()
''step through oShipping Options and add to oElmt those options
''that are valid for our price and weight.
Dim xmlShippingOptionsValid As XmlElement = moPageXml.CreateElement("ShippingOptions")
Dim strXpath As New Text.StringBuilder
strXpath.Append("Method[ ")
strXpath.Append("(WeightMin=0 or WeightMin<=" & nWeight.ToString & ") ")
strXpath.Append(" and ")
strXpath.Append("(WeightMax=0 or WeightMax>=" & nWeight.ToString & ") ")
strXpath.Append(" and ")
strXpath.Append("(PriceMin=0 or PriceMin<=" & nPrice.ToString & ") ")
strXpath.Append(" and ")
strXpath.Append("(PriceMax=0 or PriceMax>=" & nPrice.ToString & ") ")
strXpath.Append(" ]")
'add filtered list to xmlShippingOptionsValid
Dim xmlMethod As XmlElement
For Each xmlMethod In xmlShippingOptions.SelectNodes(strXpath.ToString)
'add to
xmlShippingOptionsValid.AppendChild(xmlMethod.CloneNode(True))
Next
'itterate though xmlShippingOptionsValid and get cheapest for each Location
Dim cShippingLocation As String = ""
Dim cShippingLocationPrev As String = ""
For Each xmlMethod In xmlShippingOptionsValid.SelectNodes("Method")
Try
cShippingLocation = xmlMethod.SelectSingleNode("Location").InnerText
If cShippingLocationPrev <> "" And cShippingLocationPrev = cShippingLocation Then
xmlShippingOptionsValid.RemoveChild(xmlMethod)
End If
cShippingLocationPrev = cShippingLocation 'set cShippingLocationPrev for next loop
Catch ex As Exception
xmlMethod = xmlMethod
xmlProduct = xmlProduct
returnException(mcModuleName, "AddShippingCosts", ex, , "", gbDebug)
End Try
Next
'add to product XML
xmlProduct.AppendChild(xmlShippingOptionsValid.CloneNode(True))
Catch ex As Exception
returnException(mcModuleName, "AddShippingCosts", ex, , "", gbDebug)
End Try
End Sub
Private Function getValidShippingOptionsDS(cDestinationCountry As String, nAmount As Long, nQuantity As Long, nWeight As Long) As DataSet
Try
Dim sSql As String
Dim sCountryList As String = getParentCountries(cDestinationCountry, 1)
sSql = "select opt.*, dbo.fxn_shippingTotal(opt.nShipOptKey," & nAmount & "," & nQuantity & "," & nWeight & ") as nShippingTotal from tblCartShippingLocations Loc "
sSql = sSql & "Inner Join tblCartShippingRelations rel ON Loc.nLocationKey = rel.nShpLocId "
sSql = sSql & "Inner Join tblCartShippingMethods opt ON rel.nShpOptId = opt.nShipOptKey "
sSql &= "INNER JOIN tblAudit ON opt.nAuditId = tblAudit.nAuditKey"
sSql = sSql & " WHERE (nShipOptQuantMin <= 0 or nShipOptQuantMin <= " & nQuantity & ") and (nShipOptQuantMax <= 0 or nShipOptQuantMax >= " & nQuantity & ") and "
sSql = sSql & "(nShipOptPriceMin <= 0 or nShipOptPriceMin <= " & nAmount & ") and (nShipOptPriceMax <= 0 or nShipOptPriceMax >= " & nAmount & ") and "
sSql = sSql & "(nShipOptWeightMin <= 0 or nShipOptWeightMin <= " & nWeight & ") and (nShipOptWeightMax <= 0 or nShipOptWeightMax >= " & nWeight & ") "
sSql &= " and ((opt.cCurrency Is Null) or (opt.cCurrency = '') or (opt.cCurrency = '" & mcCurrency & "'))"
If myWeb.mnUserId > 0 Then
' if user in group then return it
sSql &= " and ((SELECT COUNT(perm.nCartShippingPermissionKey) from tblCartShippingPermission perm" &
" Inner join tblDirectoryRelation PermGroup ON perm.nDirId = PermGroup.nDirParentId" &
" where perm.nShippingMethodId = opt.nShipOptKey and PermGroup.nDirChildId = " & myWeb.mnUserId & " and perm.nPermLevel = 1) > 0"
sSql &= " and not((SELECT COUNT(perm.nCartShippingPermissionKey) from tblCartShippingPermission perm" &
" Inner join tblDirectoryRelation PermGroup ON perm.nDirId = PermGroup.nDirParentId" &
" where perm.nShippingMethodId = opt.nShipOptKey and PermGroup.nDirChildId = " & myWeb.mnUserId & " and perm.nPermLevel = 0) > 0)"
'method allowed for authenticated
sSql &= " or (SELECT COUNT(perm.nCartShippingPermissionKey) from tblCartShippingPermission perm" &
" where perm.nShippingMethodId = opt.nShipOptKey and perm.nDirId = " & gnAuthUsers & " and perm.nPermLevel = 1) > 0"
' if no group exists return it.
sSql &= " or (SELECT COUNT(*) from tblCartShippingPermission perm where opt.nShipOptKey = perm.nShippingMethodId and perm.nPermLevel = 1) = 0)"
Else
Dim nonAuthID As Long = gnNonAuthUsers
Dim AuthID As Long = gnAuthUsers
'method allowed for non-authenticated
sSql &= " and ((SELECT COUNT(perm.nCartShippingPermissionKey) from tblCartShippingPermission perm" &
" where perm.nShippingMethodId = opt.nShipOptKey and perm.nDirId = " & gnNonAuthUsers & " and perm.nPermLevel = 1) > 0"
' method has no group
sSql &= " or (SELECT COUNT(*) from tblCartShippingPermission perm where opt.nShipOptKey = perm.nShippingMethodId and perm.nPermLevel = 1) = 0)"
End If
' Restrict the shipping options by looking at the delivery country currently selected.
' Of course, if we are hiding the delivery address then this can be ignored.
If sCountryList <> "" Then
sSql = sSql & " and ((loc.cLocationNameShort IN " & sCountryList & ") or (loc.cLocationNameFull IN " & sCountryList & ")) "
End If
'Active methods
sSql &= " AND (tblAudit.nStatus >0)"
sSql &= " AND ((tblAudit.dPublishDate = 0) or (tblAudit.dPublishDate Is Null) or (tblAudit.dPublishDate <= " & Eonic.Tools.Database.SqlDate(Now) & "))"
sSql &= " AND ((tblAudit.dExpireDate = 0) or (tblAudit.dExpireDate Is Null) or (tblAudit.dExpireDate >= " & Eonic.Tools.Database.SqlDate(Now) & "))"
'Build Form
'Go and collect the valid shipping options available for this order
Return moDBHelper.GetDataSet(sSql & " order by opt.nDisplayPriority, nShippingTotal", "Option", "Shipping")
Catch ex As Exception
returnException(mcModuleName, "getValidShippingOptionsDS", ex, , "", gbDebug)
End Try
End Function
Private Function makeShippingOptionsXML() As XmlElement
Try
If oShippingOptions Is Nothing Then
Dim xmlTemp As XmlElement
'create XML of all possible shipping methods and add it to the page XML
oShippingOptions = moPageXml.CreateElement("oShippingOptions")
'get all the shipping options for a given shipping weight and price
Dim strSql As New Text.StringBuilder
strSql.Append("SELECT opt.cShipOptCarrier as Carrier, opt.cShipOptTime AS ShippingTime, ")
strSql.Append("opt.nShipOptCost AS Cost, ")
strSql.Append("tblCartShippingLocations.cLocationNameShort as Location, tblCartShippingLocations.cLocationISOa2 as LocationISOa2, ")
strSql.Append("opt.nShipOptWeightMin AS WeightMin, opt.nShipOptWeightMax AS WeightMax, ")
strSql.Append("opt.nShipOptPriceMin AS PriceMin, opt.nShipOptPriceMax AS PriceMax, ")
strSql.Append("opt.nShipOptQuantMin AS QuantMin, opt.nShipOptQuantMax AS QuantMax, ")
strSql.Append("tblCartShippingLocations.nLocationType, tblCartShippingLocations.cLocationNameFull ")
strSql.Append("FROM tblCartShippingLocations ")
strSql.Append("INNER JOIN tblCartShippingRelations ON tblCartShippingLocations.nLocationKey = tblCartShippingRelations.nShpLocId ")
strSql.Append("RIGHT OUTER JOIN tblCartShippingMethods AS opt ")
strSql.Append("INNER JOIN tblAudit ON opt.nAuditId = tblAudit.nAuditKey ON tblCartShippingRelations.nShpOptId = opt.nShipOptKey ")
strSql.Append("WHERE (tblAudit.nStatus > 0) ")
strSql.Append("AND (tblAudit.dPublishDate = 0 OR tblAudit.dPublishDate IS NULL OR tblAudit.dPublishDate <= " & Eonic.Tools.Database.SqlDate(Now) & ") ")
strSql.Append("AND (tblAudit.dExpireDate = 0 OR tblAudit.dExpireDate IS NULL OR tblAudit.dExpireDate >= " & Eonic.Tools.Database.SqlDate(Now) & ") ")
strSql.Append("AND (tblCartShippingLocations.cLocationNameShort IS NOT NULL) ")
strSql.Append("ORDER BY tblCartShippingLocations.cLocationNameShort, opt.nShipOptCost ")
Dim oDs As DataSet = moDBHelper.GetDataSet(strSql.ToString, "Method", "ShippingMethods", )
oShippingOptions.InnerXml = oDs.GetXml()
'move all the shipping methods up a level
For Each xmlTemp In oShippingOptions.SelectNodes("ShippingMethods/Method")
oShippingOptions.AppendChild(xmlTemp)
Next
For Each xmlTemp In oShippingOptions.SelectNodes("ShippingMethods")
oShippingOptions.RemoveChild(xmlTemp)
Next
End If
Return oShippingOptions
Catch ex As Exception
returnException(mcModuleName, "makeShippingOptionsXML", ex, , "", gbDebug)
End Try
End Function
End Class
End Class
|
Imports JM.LinqFaster
Imports StaxRip.UI
Public Class SourceFilesForm
Inherits DialogBase
#Region " Designer "
Protected Overloads Overrides Sub Dispose(disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
Private components As System.ComponentModel.IContainer
Friend WithEvents lb As ListBoxEx
Friend WithEvents bnDown As ButtonEx
Friend WithEvents bnUp As ButtonEx
Friend WithEvents bnRemove As ButtonEx
Friend WithEvents bnAdd As ButtonEx
Friend WithEvents bnCancel As StaxRip.UI.ButtonEx
Friend WithEvents tlpMain As TableLayoutPanel
Friend WithEvents pnLB As Panel
Friend WithEvents bnOK As StaxRip.UI.ButtonEx
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Me.lb = New StaxRip.UI.ListBoxEx()
Me.bnDown = New StaxRip.UI.ButtonEx()
Me.bnRemove = New StaxRip.UI.ButtonEx()
Me.bnUp = New StaxRip.UI.ButtonEx()
Me.bnAdd = New StaxRip.UI.ButtonEx()
Me.bnCancel = New StaxRip.UI.ButtonEx()
Me.bnOK = New StaxRip.UI.ButtonEx()
Me.tlpMain = New System.Windows.Forms.TableLayoutPanel()
Me.pnLB = New System.Windows.Forms.Panel()
Me.tlpMain.SuspendLayout()
Me.pnLB.SuspendLayout()
Me.SuspendLayout()
'
'lb
'
Me.lb.AllowDrop = True
Me.lb.Dock = System.Windows.Forms.DockStyle.Fill
Me.lb.DownButton = Me.bnDown
Me.lb.FormattingEnabled = True
Me.lb.HorizontalScrollbar = True
Me.lb.IntegralHeight = False
Me.lb.ItemHeight = 48
Me.lb.Location = New System.Drawing.Point(0, 0)
Me.lb.Name = "lb"
Me.lb.RemoveButton = Me.bnRemove
Me.lb.Size = New System.Drawing.Size(717, 600)
Me.lb.TabIndex = 2
Me.lb.UpButton = Me.bnUp
'
'bnDown
'
Me.bnDown.Anchor = System.Windows.Forms.AnchorStyles.Top
Me.bnDown.Location = New System.Drawing.Point(749, 370)
Me.bnDown.Margin = New System.Windows.Forms.Padding(8)
Me.bnDown.Size = New System.Drawing.Size(250, 80)
Me.bnDown.Text = " &Down"
'
'bnRemove
'
Me.bnRemove.Location = New System.Drawing.Point(749, 112)
Me.bnRemove.Margin = New System.Windows.Forms.Padding(8)
Me.bnRemove.Size = New System.Drawing.Size(250, 80)
Me.bnRemove.Text = " &Remove"
'
'bnUp
'
Me.bnUp.Anchor = System.Windows.Forms.AnchorStyles.Bottom
Me.bnUp.Location = New System.Drawing.Point(749, 274)
Me.bnUp.Margin = New System.Windows.Forms.Padding(8)
Me.bnUp.Size = New System.Drawing.Size(250, 80)
Me.bnUp.Text = "&Up"
'
'bnAdd
'
Me.bnAdd.Location = New System.Drawing.Point(749, 16)
Me.bnAdd.Margin = New System.Windows.Forms.Padding(8)
Me.bnAdd.Size = New System.Drawing.Size(250, 80)
Me.bnAdd.Text = "&Add..."
'
'bnCancel
'
Me.bnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.bnCancel.Location = New System.Drawing.Point(749, 632)
Me.bnCancel.Margin = New System.Windows.Forms.Padding(8)
Me.bnCancel.Size = New System.Drawing.Size(250, 80)
Me.bnCancel.Text = "Cancel"
'
'bnOK
'
Me.bnOK.DialogResult = System.Windows.Forms.DialogResult.OK
Me.bnOK.Location = New System.Drawing.Point(483, 632)
Me.bnOK.Margin = New System.Windows.Forms.Padding(8)
Me.bnOK.Size = New System.Drawing.Size(250, 80)
Me.bnOK.Text = "OK"
'
'tlpMain
'
Me.tlpMain.ColumnCount = 3
Me.tlpMain.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.tlpMain.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle())
Me.tlpMain.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle())
Me.tlpMain.Controls.Add(Me.bnRemove, 2, 1)
Me.tlpMain.Controls.Add(Me.bnAdd, 2, 0)
Me.tlpMain.Controls.Add(Me.bnCancel, 2, 7)
Me.tlpMain.Controls.Add(Me.bnOK, 1, 7)
Me.tlpMain.Controls.Add(Me.bnUp, 2, 3)
Me.tlpMain.Controls.Add(Me.bnDown, 2, 4)
Me.tlpMain.Controls.Add(Me.pnLB, 0, 0)
Me.tlpMain.Dock = System.Windows.Forms.DockStyle.Fill
Me.tlpMain.Location = New System.Drawing.Point(0, 0)
Me.tlpMain.Name = "tlpMain"
Me.tlpMain.Padding = New System.Windows.Forms.Padding(8)
Me.tlpMain.RowCount = 8
Me.tlpMain.RowStyles.Add(New System.Windows.Forms.RowStyle())
Me.tlpMain.RowStyles.Add(New System.Windows.Forms.RowStyle())
Me.tlpMain.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50.0!))
Me.tlpMain.RowStyles.Add(New System.Windows.Forms.RowStyle())
Me.tlpMain.RowStyles.Add(New System.Windows.Forms.RowStyle())
Me.tlpMain.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50.0!))
Me.tlpMain.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 100.0!))
Me.tlpMain.RowStyles.Add(New System.Windows.Forms.RowStyle())
Me.tlpMain.Size = New System.Drawing.Size(1015, 729)
Me.tlpMain.TabIndex = 7
'
'pnLB
'
Me.pnLB.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.tlpMain.SetColumnSpan(Me.pnLB, 2)
Me.pnLB.Controls.Add(Me.lb)
Me.pnLB.Location = New System.Drawing.Point(16, 16)
Me.pnLB.Margin = New System.Windows.Forms.Padding(8)
Me.pnLB.Name = "pnLB"
Me.tlpMain.SetRowSpan(Me.pnLB, 7)
Me.pnLB.Size = New System.Drawing.Size(717, 600)
Me.pnLB.TabIndex = 9
'
'SourceFilesForm
'
Me.AcceptButton = Me.bnOK
Me.AutoScaleDimensions = New System.Drawing.SizeF(288.0!, 288.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi
Me.CancelButton = Me.bnCancel
Me.ClientSize = New System.Drawing.Size(1015, 729)
Me.Controls.Add(Me.tlpMain)
Me.HelpButton = False
Me.KeyPreview = True
Me.Margin = New System.Windows.Forms.Padding(13, 14, 13, 14)
Me.Name = "SourceFilesForm"
Me.Text = "Source Files"
Me.tlpMain.ResumeLayout(False)
Me.pnLB.ResumeLayout(False)
Me.ResumeLayout(False)
End Sub
#End Region
Property IsMerge As Boolean
Sub New()
MyBase.New()
InitializeComponent()
ScaleClientSize(36, 22, FontHeight)
MinimumSize = New Size(Width \ 2, CInt(Height * 0.6))
bnUp.Image = ImageHelp.GetImageC(Symbol.Up)
bnDown.Image = ImageHelp.GetImageC(Symbol.Down)
bnAdd.Image = ImageHelp.GetImageC(Symbol.Add)
bnRemove.Image = ImageHelp.GetImageC(Symbol.Remove)
For Each bn In {bnAdd, bnRemove, bnUp, bnDown}
bn.TextImageRelation = TextImageRelation.Overlay
bn.ImageAlign = ContentAlignment.MiddleLeft
Dim pad = bn.Padding
pad.Left = FontHeight \ 10
pad.Right = pad.Left
bn.Padding = pad
Next
ActiveControl = bnOK
End Sub
Sub ShowOpenFileDialog()
Using dialog As New OpenFileDialog
dialog.Multiselect = True
dialog.Filter = FileTypes.GetFilter(FileTypes.Video)
dialog.SetInitDir(s.LastSourceDir)
If dialog.ShowDialog() = DialogResult.OK Then
s.LastSourceDir = dialog.FileName.Dir
lb.Items.AddRange(dialog.FileNames.Sort)
lb.SelectedIndex = lb.Items.Count - 1
End If
End Using
End Sub
Sub bnAdd_Click() Handles bnAdd.Click
If IsMerge Then
ShowOpenFileDialog()
Exit Sub
End If
Using td As New TaskDialog(Of String)
td.AddCommand("Add files", "files")
td.AddCommand("Add folder", "folder")
Select Case td.Show
Case "files"
ShowOpenFileDialog()
Case "folder"
Using dialog As New FolderBrowserDialog
If dialog.ShowDialog = DialogResult.OK Then
Dim subfolders = Directory.GetDirectories(dialog.SelectedPath)
Dim opt = SearchOption.TopDirectoryOnly
If Directory.GetDirectories(dialog.SelectedPath).Length > 0 Then
If MsgQuestion("Include sub folders?", TaskDialogButtons.YesNo) = DialogResult.Yes Then
opt = SearchOption.AllDirectories
End If
End If
lb.Items.AddRange(Directory.GetFiles(dialog.SelectedPath, "*.*", opt).WhereF(Function(val) FileTypes.Video.ContainsString(val.Ext)))
lb.SelectedIndex = lb.Items.Count - 1
End If
End Using
End Select
End Using
End Sub
Protected Overrides Sub OnFormClosing(args As FormClosingEventArgs)
MyBase.OnFormClosing(args)
If DialogResult = DialogResult.OK Then
Dim files = GetFiles()
If Not g.VerifySource(GetFiles) Then
args.Cancel = True
End If
End If
End Sub
Function GetFiles() As IEnumerable(Of String)
Return lb.Items.OfType(Of String)
End Function
Sub lb_DragDrop(sender As Object, e As DragEventArgs) Handles lb.DragDrop
Dim items = TryCast(e.Data.GetData(DataFormats.FileDrop), String())
If Not items.NothingOrEmpty Then
Array.Sort(items)
lb.Items.AddRange(items.WhereF(Function(val) File.Exists(val)))
End If
End Sub
Sub lb_DragEnter(sender As Object, e As DragEventArgs) Handles lb.DragEnter
e.Effect = DragDropEffects.Copy
End Sub
End Class
|
'*******************************************************************************************'
' '
' Download Free Evaluation Version From: https://bytescout.com/download/web-installer '
' '
' Also available as Web API! Free Trial Sign Up: https://secure.bytescout.com/users/sign_up '
' '
' Copyright © 2017-2018 ByteScout Inc. All rights reserved. '
' http://www.bytescout.com '
' '
'*******************************************************************************************'
Imports System
Imports System.IO
Imports System.Management
Imports System.Windows.Forms
Imports System.ServiceProcess
Public Partial Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub btnInstallService_Click(sender As Object, e As EventArgs)
Try
' Install the service
ServiceInstaller.Install("Service1", "Service1", Path.GetFullPath("WindowsService1.exe"))
' Set the service option "Allow desktop interaction".
Dim co As New ConnectionOptions()
co.Impersonation = ImpersonationLevel.Impersonate
Dim mgmtScope As New ManagementScope("root\CIMV2", co)
mgmtScope.Connect()
Dim wmiService As New ManagementObject("Win32_Service.Name='Service1'")
Dim InParam As ManagementBaseObject = wmiService.GetMethodParameters("Change")
InParam("DesktopInteract") = True
Dim OutParam As ManagementBaseObject = wmiService.InvokeMethod("Change", InParam, Nothing)
' Start the service
ServiceInstaller.StartService("Service1")
Catch exception As Exception
MessageBox.Show(exception.Message)
End Try
End Sub
Private Sub btnUninstallService_Click(sender As Object, e As EventArgs)
Try
ServiceInstaller.Uninstall("Service1")
Catch exception As Exception
MessageBox.Show(exception.Message)
End Try
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs)
Me.Close()
End Sub
End Class
|
' 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.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class WellKnownTypeValidationTests
Inherits BasicTestBase
<Fact>
<WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")>
Public Sub NonPublicSpecialType()
Dim source = <![CDATA[
Namespace System
Public Class [Object]
Public Sub New()
End Sub
End Class
Friend Class [String]
End Class
Public Class ValueType
End Class
Public Structure Void
End Structure
End Namespace
]]>.Value.Replace(vbLf, vbCrLf).Trim
Dim validate As Action(Of VisualBasicCompilation) =
Sub(comp)
Dim special = comp.GetSpecialType(SpecialType.System_String)
Assert.Equal(TypeKind.Error, special.TypeKind)
Assert.Equal(SpecialType.System_String, special.SpecialType)
Assert.Equal(Accessibility.Public, special.DeclaredAccessibility)
Dim lookup = comp.GetTypeByMetadataName("System.String")
Assert.Equal(TypeKind.Class, lookup.TypeKind)
Assert.Equal(SpecialType.None, lookup.SpecialType)
Assert.Equal(Accessibility.Internal, lookup.DeclaredAccessibility)
End Sub
ValidateSourceAndMetadata(source, validate)
End Sub
<Fact>
<WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")>
Public Sub NonPublicSpecialTypeMember()
Dim sourceTemplate = <![CDATA[
Namespace System
Public Class [Object]
Public Sub New()
End Sub
{0} Overridable Function ToString() As [String]
Return Nothing
End Function
End Class
{0} Class [String]
Public Shared Function Concat(s1 As [String], s2 As [String]) As [String]
Return Nothing
End Function
End Class
Public Class ValueType
End Class
Public Structure Void
End Structure
End Namespace
]]>.Value.Replace(vbLf, vbCrLf).Trim
Dim validatePresent As Action(Of VisualBasicCompilation) =
Sub(comp)
Assert.NotNull(comp.GetSpecialTypeMember(SpecialMember.System_Object__ToString))
Assert.NotNull(comp.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringString))
comp.GetDiagnostics()
End Sub
Dim validateMissing As Action(Of VisualBasicCompilation) =
Sub(comp)
Assert.Null(comp.GetSpecialTypeMember(SpecialMember.System_Object__ToString))
Assert.Null(comp.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringString))
comp.GetDiagnostics()
End Sub
ValidateSourceAndMetadata(String.Format(sourceTemplate, "Public"), validatePresent)
ValidateSourceAndMetadata(String.Format(sourceTemplate, "Friend"), validateMissing)
End Sub
' Document the fact that we don't reject type parameters with constraints (yet?).
<Fact>
<WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")>
Public Sub GenericConstraintsOnSpecialType()
Dim source = <![CDATA[
Namespace System
Public Class [Object]
Public Sub New()
End Sub
End Class
Public Structure Nullable(Of T As New)
End Structure
Public Class ValueType
End Class
Public Structure Void
End Structure
End Namespace
]]>.Value.Replace(vbLf, vbCrLf).Trim
Dim validate As Action(Of VisualBasicCompilation) =
Sub(comp)
Dim special = comp.GetSpecialType(SpecialType.System_Nullable_T)
Assert.Equal(TypeKind.Structure, special.TypeKind)
Assert.Equal(SpecialType.System_Nullable_T, special.SpecialType)
Dim lookup = comp.GetTypeByMetadataName("System.Nullable`1")
Assert.Equal(TypeKind.Structure, lookup.TypeKind)
Assert.Equal(SpecialType.System_Nullable_T, lookup.SpecialType)
End Sub
ValidateSourceAndMetadata(source, validate)
End Sub
' No special type members have type parameters that could (incorrectly) be constrained.
<Fact>
<WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")>
Public Sub NonPublicWellKnownType()
Dim source = <![CDATA[
Namespace System
Public Class [Object]
Public Sub New()
End Sub
End Class
Friend Class Type
End Class
Public Class ValueType
End Class
Public Structure Void
End Structure
End Namespace
]]>.Value.Replace(vbLf, vbCrLf).Trim
Dim validate As Action(Of VisualBasicCompilation) =
Sub(comp)
Dim wellKnown = comp.GetWellKnownType(WellKnownType.System_Type)
If wellKnown.DeclaringCompilation Is comp Then
Assert.Equal(TypeKind.Class, wellKnown.TypeKind)
Assert.Equal(Accessibility.Internal, wellKnown.DeclaredAccessibility)
Else
Assert.Equal(TypeKind.Error, wellKnown.TypeKind)
Assert.Equal(Accessibility.Public, wellKnown.DeclaredAccessibility)
End If
Dim lookup = comp.GetTypeByMetadataName("System.Type")
Assert.Equal(TypeKind.Class, lookup.TypeKind)
Assert.Equal(Accessibility.Internal, lookup.DeclaredAccessibility)
End Sub
ValidateSourceAndMetadata(source, validate)
End Sub
<Fact>
<WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")>
Public Sub NonPublicWellKnownType_Nested()
Dim sourceTemplate = <![CDATA[
Namespace System.Diagnostics
{0} Class DebuggableAttribute
{1} Enum DebuggingModes
Mode
End Enum
End Class
End Namespace
Namespace System
Public Class [Object]
Public Sub New()
End Sub
End Class
Public Class ValueType
End Class
Public Class [Enum]
End Class
Public Structure Void
End Structure
Public Structure [Int32]
End Structure
End Namespace
]]>.Value.Replace(vbLf, vbCrLf).Trim
Dim validate As Action(Of VisualBasicCompilation) =
Sub(comp)
Dim wellKnown = comp.GetWellKnownType(WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes)
Assert.Equal(If(wellKnown.DeclaringCompilation Is comp, TypeKind.Enum, TypeKind.Error), wellKnown.TypeKind)
Dim lookup = comp.GetTypeByMetadataName("System.Diagnostics.DebuggableAttribute+DebuggingModes")
Assert.Equal(TypeKind.Enum, lookup.TypeKind)
End Sub
ValidateSourceAndMetadata(String.Format(sourceTemplate, "Public", "Friend"), validate)
ValidateSourceAndMetadata(String.Format(sourceTemplate, "Friend", "Public"), validate)
End Sub
<Fact>
<WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")>
Public Sub NonPublicWellKnownTypeMember()
Dim sourceTemplate = <![CDATA[
Namespace System
Public Class [Object]
Public Sub New()
End Sub
End Class
Public Class [String]
End Class
{0} Class Type
Public Shared ReadOnly Missing As [Object]
End Class
Public Class FlagsAttribute
{0} Sub New()
End Sub
End Class
Public Class ValueType
End Class
Public Structure Void
End Structure
End Namespace
]]>.Value.Replace(vbLf, vbCrLf).Trim
Dim validatePresent As Action(Of VisualBasicCompilation) =
Sub(comp)
Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Type__Missing))
Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_FlagsAttribute__ctor))
comp.GetDiagnostics()
End Sub
Dim validateMissing As Action(Of VisualBasicCompilation) =
Sub(comp)
If comp.Assembly.CorLibrary Is comp.Assembly Then
Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Type__Missing))
Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_FlagsAttribute__ctor))
Else
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_Type__Missing))
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_FlagsAttribute__ctor))
End If
comp.GetDiagnostics()
End Sub
ValidateSourceAndMetadata(String.Format(sourceTemplate, "Public"), validatePresent)
ValidateSourceAndMetadata(String.Format(sourceTemplate, "Friend"), validateMissing)
End Sub
' Document the fact that we don't reject type parameters with constraints (yet?).
<Fact>
<WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")>
Public Sub GenericConstraintsOnWellKnownType()
Dim source = <![CDATA[
Namespace System
Public Class [Object]
Public Sub New()
End Sub
End Class
Public Class ValueType
End Class
Public Structure Void
End Structure
End Namespace
Namespace System.Threading.Tasks
Public Class Task(Of T As New)
End Class
End Namespace
]]>.Value.Replace(vbLf, vbCrLf).Trim
Dim validate As Action(Of VisualBasicCompilation) =
Sub(comp)
Dim wellKnown = comp.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T)
Assert.Equal(TypeKind.Class, wellKnown.TypeKind)
Dim lookup = comp.GetTypeByMetadataName("System.Threading.Tasks.Task`1")
Assert.Equal(TypeKind.Class, lookup.TypeKind)
End Sub
ValidateSourceAndMetadata(source, validate)
End Sub
' Document the fact that we don't reject type parameters with constraints (yet?).
<Fact>
<WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")>
Public Sub GenericConstraintsOnWellKnownTypeMember()
Dim sourceTemplate = <![CDATA[
Namespace System
Public Class [Object]
Public Sub New()
End Sub
End Class
Public Class Activator
Public Shared Function CreateInstance(Of T{0})() As T
Throw New Exception()
End Function
End Class
Public Class Exception
Public Sub New()
End Sub
End Class
Public Class ValueType
End Class
Public Structure Void
End Structure
End Namespace
]]>.Value.Replace(vbLf, vbCrLf).Trim
Dim validate As Action(Of VisualBasicCompilation) =
Sub(comp)
Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Activator__CreateInstance_T))
comp.GetDiagnostics()
End Sub
ValidateSourceAndMetadata(String.Format(sourceTemplate, ""), validate)
ValidateSourceAndMetadata(String.Format(sourceTemplate, " As New"), validate)
End Sub
Private Shared Sub ValidateSourceAndMetadata(source As String, validate As Action(Of VisualBasicCompilation))
Dim comp1 = CreateCompilationWithoutReferences(WrapInCompilationXml(source))
validate(comp1)
Dim reference = comp1.EmitToImageReference()
Dim comp2 = CreateCompilationWithReferences(<compilation/>, {reference})
validate(comp2)
End Sub
Private Shared Function WrapInCompilationXml(source As String) As XElement
Return <compilation>
<file name="a.vb">
<%= source %>
</file>
</compilation>
End Function
<Fact>
<WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")>
Public Sub PublicVersusInternalWellKnownType()
Dim corlibSource =
<compilation>
<file name="a.vb">
Namespace System
Public Class [Object]
Public Sub New()
End Sub
End Class
Public Class [String]
End Class
Public Class Attribute
End Class
Public Class ValueType
End Class
Public Structure Void
End Structure
End Namespace
Namespace System.Runtime.CompilerServices
Public Class InternalsVisibleToAttribute : Inherits System.Attribute
Public Sub New(s As [String])
End Sub
End Class
End Namespace
</file>
</compilation>
If True Then
Dim libSourceTemplate = <![CDATA[
Namespace System
{0} Class Type
End Class
End Namespace
]]>.Value.Replace(vbLf, vbCrLf).Trim
Dim corlibRef = CreateCompilationWithoutReferences(corlibSource).EmitToImageReference()
Dim publicLibRef = CreateCompilationWithReferences(WrapInCompilationXml(String.Format(libSourceTemplate, "Public")), {corlibRef}).EmitToImageReference()
Dim internalLibRef = CreateCompilationWithReferences(WrapInCompilationXml(String.Format(libSourceTemplate, "Friend")), {corlibRef}).EmitToImageReference()
Dim comp = CreateCompilationWithReferences({}, {corlibRef, publicLibRef, internalLibRef}, assemblyName:="Test")
Dim wellKnown = comp.GetWellKnownType(WellKnownType.System_Type)
Assert.NotNull(wellKnown)
Assert.Equal(TypeKind.Class, wellKnown.TypeKind)
Assert.Equal(Accessibility.Public, wellKnown.DeclaredAccessibility)
Dim Lookup = comp.GetTypeByMetadataName("System.Type")
Assert.Null(Lookup) ' Ambiguous
End If
If True Then
Dim libSourceTemplate = <![CDATA[
<Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Test")>
Namespace System
{0} Class Type
End Class
End Namespace
]]>.Value.Replace(vbLf, vbCrLf).Trim
Dim corlibRef = CreateCompilationWithoutReferences(corlibSource).EmitToImageReference()
Dim publicLibRef = CreateCompilationWithReferences(WrapInCompilationXml(String.Format(libSourceTemplate, "Public")), {corlibRef}).EmitToImageReference()
Dim internalLibRef = CreateCompilationWithReferences(WrapInCompilationXml(String.Format(libSourceTemplate, "Friend")), {corlibRef}).EmitToImageReference()
Dim comp = CreateCompilationWithReferences({}, {corlibRef, publicLibRef, internalLibRef}, assemblyName:="Test")
Dim wellKnown = comp.GetWellKnownType(WellKnownType.System_Type)
Assert.NotNull(wellKnown)
Assert.Equal(TypeKind.Error, wellKnown.TypeKind)
Dim Lookup = comp.GetTypeByMetadataName("System.Type")
Assert.Null(Lookup) ' Ambiguous
End If
End Sub
<Fact>
<WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")>
Public Sub AllSpecialTypes()
Dim comp = CreateCompilationWithReferences((<compilation/>), {MscorlibRef_v4_0_30316_17626})
For special As SpecialType = CType(SpecialType.None + 1, SpecialType) To SpecialType.Count
Dim symbol = comp.GetSpecialType(special)
Assert.NotNull(symbol)
Assert.NotEqual(SymbolKind.ErrorType, symbol.Kind)
Next
End Sub
<Fact>
<WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")>
Public Sub AllSpecialTypeMembers()
Dim comp = CreateCompilationWithReferences((<compilation/>), {MscorlibRef_v4_0_30316_17626})
For Each special As SpecialMember In [Enum].GetValues(GetType(SpecialMember))
Select Case special
Case SpecialMember.System_IntPtr__op_Explicit_ToPointer,
SpecialMember.System_IntPtr__op_Explicit_FromPointer,
SpecialMember.System_UIntPtr__op_Explicit_ToPointer,
SpecialMember.System_UIntPtr__op_Explicit_FromPointer
' VB doesn't have pointer types.
Continue For
Case SpecialMember.Count
' Not a real value.
Continue For
End Select
Dim symbol = comp.GetSpecialTypeMember(special)
Assert.NotNull(symbol)
Next
End Sub
<Fact>
<WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")>
Public Sub AllWellKnownTypes()
Dim refs As MetadataReference() =
{
MscorlibRef_v4_0_30316_17626,
SystemRef_v4_0_30319_17929,
SystemCoreRef_v4_0_30319_17929,
CSharpRef,
SystemXmlRef,
SystemXmlLinqRef,
SystemWindowsFormsRef,
ValueTupleRef
}.Concat(WinRtRefs).ToArray()
Dim lastType = CType(WellKnownType.NextAvailable - 1, WellKnownType)
Dim comp = CreateCompilationWithReferences((<compilation/>), refs.Concat(MsvbRef_v4_0_30319_17929).ToArray())
For wkt = WellKnownType.First To lastType
Select Case wkt
Case WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators
' Only present when embedding VB Core.
Continue For
Case WellKnownType.System_FormattableString,
WellKnownType.System_Runtime_CompilerServices_FormattableStringFactory,
WellKnownType.System_Span_T,
WellKnownType.System_ReadOnlySpan_T
' Not available on all platforms.
Continue For
Case WellKnownType.ExtSentinel
' Not a real type
Continue For
Case WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation,
WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute,
WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute
' Not always available.
Continue For
End Select
Dim symbol = comp.GetWellKnownType(wkt)
Assert.NotNull(symbol)
Assert.NotEqual(SymbolKind.ErrorType, symbol.Kind)
Next
comp = CreateCompilationWithReferences(<compilation/>, refs, TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True))
For wkt = WellKnownType.First To lastType
Select Case wkt
Case WellKnownType.Microsoft_VisualBasic_CallType,
WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators,
WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding,
WellKnownType.Microsoft_VisualBasic_CompilerServices_LikeOperator,
WellKnownType.Microsoft_VisualBasic_CompilerServices_StringType,
WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned,
WellKnownType.Microsoft_VisualBasic_CompareMethod,
WellKnownType.Microsoft_VisualBasic_ErrObject,
WellKnownType.Microsoft_VisualBasic_FileSystem,
WellKnownType.Microsoft_VisualBasic_ApplicationServices_ApplicationBase,
WellKnownType.Microsoft_VisualBasic_ApplicationServices_WindowsFormsApplicationBase,
WellKnownType.Microsoft_VisualBasic_Information,
WellKnownType.Microsoft_VisualBasic_Interaction
' Not embedded, so not available.
Continue For
Case WellKnownType.System_FormattableString,
WellKnownType.System_Runtime_CompilerServices_FormattableStringFactory,
WellKnownType.System_Span_T,
WellKnownType.System_ReadOnlySpan_T
' Not available on all platforms.
Continue For
Case WellKnownType.ExtSentinel
' Not a real type
Continue For
Case WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation,
WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute,
WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute
' Not always available.
Continue For
End Select
Dim symbol = comp.GetWellKnownType(wkt)
Assert.NotNull(symbol)
Assert.NotEqual(SymbolKind.ErrorType, symbol.Kind)
Next
End Sub
<Fact>
<WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")>
Public Sub AllWellKnownTypeMembers()
Dim refs As MetadataReference() =
{
MscorlibRef_v4_0_30316_17626,
SystemRef_v4_0_30319_17929,
SystemCoreRef_v4_0_30319_17929,
CSharpRef,
SystemXmlRef,
SystemXmlLinqRef,
SystemWindowsFormsRef,
ValueTupleRef
}.Concat(WinRtRefs).ToArray()
Dim comp = CreateCompilationWithReferences((<compilation/>), refs.Concat(MsvbRef_v4_0_30319_17929).ToArray())
For Each wkm As WellKnownMember In [Enum].GetValues(GetType(WellKnownMember))
Select Case wkm
Case WellKnownMember.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean
' Only present when embedding VB Core.
Continue For
Case WellKnownMember.Count
' Not a real value.
Continue For
Case WellKnownMember.System_Array__Empty,
WellKnownMember.System_Span_T__ctor,
WellKnownMember.System_Span_T__get_Item,
WellKnownMember.System_Span_T__get_Length,
WellKnownMember.System_ReadOnlySpan_T__get_Item,
WellKnownMember.System_ReadOnlySpan_T__get_Length
' Not available yet, but will be in upcoming release.
Continue For
Case WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile,
WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles,
WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor,
WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor
' Not always available.
Continue For
End Select
Dim symbol = comp.GetWellKnownTypeMember(wkm)
Assert.NotNull(symbol)
Next
comp = CreateCompilationWithReferences(<compilation/>, refs, TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True))
For Each wkm As WellKnownMember In [Enum].GetValues(GetType(WellKnownMember))
Select Case wkm
Case WellKnownMember.Count
' Not a real value.
Continue For
Case WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ChangeType,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__CreateProjectError,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__EndApp,
WellKnownMember.Microsoft_VisualBasic_Strings__AscCharInt32,
WellKnownMember.Microsoft_VisualBasic_Strings__AscStringInt32,
WellKnownMember.Microsoft_VisualBasic_Strings__ChrInt32Char
' Even though the containing type is embedded, the specific member is not.
Continue For
Case WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__PlusObjectObject,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__NegateObjectObject,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__NotObjectObject,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectEqualObjectObjectBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectNotEqualObjectObjectBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessObjectObjectBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessEqualObjectObjectBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterEqualObjectObjectBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterObjectObjectBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectEqualObjectObjectBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectNotEqualObjectObjectBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessObjectObjectBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessEqualObjectObjectBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterEqualObjectObjectBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterObjectObjectBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateCall,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateGet,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSet,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSetComplex,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexGet,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSet,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSetComplex,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_StringType__MidStmtStr,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeStringStringStringCompareMethod,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeObjectObjectObjectCompareMethod,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__CallByName,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__IsNumeric,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__SystemTypeName,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__TypeName,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__VbTypeName,
WellKnownMember.Microsoft_VisualBasic_Information__IsNumeric,
WellKnownMember.Microsoft_VisualBasic_Information__SystemTypeName,
WellKnownMember.Microsoft_VisualBasic_Information__TypeName,
WellKnownMember.Microsoft_VisualBasic_Information__VbTypeName,
WellKnownMember.Microsoft_VisualBasic_Interaction__CallByName
' The type is not embedded, so the member is not available.
Continue For
Case WellKnownMember.System_Array__Empty,
WellKnownMember.System_Span_T__ctor,
WellKnownMember.System_Span_T__get_Item,
WellKnownMember.System_Span_T__get_Length,
WellKnownMember.System_ReadOnlySpan_T__get_Item,
WellKnownMember.System_ReadOnlySpan_T__get_Length
' Not available yet, but will be in upcoming release.
Continue For
Case WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile,
WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles,
WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor,
WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor
' Not always available.
Continue For
End Select
Dim symbol = comp.GetWellKnownTypeMember(wkm)
Assert.NotNull(symbol)
Next
End Sub
End Class
End Namespace
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class frmFaqAnswerView
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Dim DataGridViewCellStyle1 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle()
Dim DataGridViewCellStyle2 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle()
Dim DataGridViewCellStyle3 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle()
Dim DataGridViewCellStyle4 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle()
Dim DataGridViewCellStyle5 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmFaqAnswerView))
Me.lblTitle = New System.Windows.Forms.Label()
Me.dgv = New System.Windows.Forms.DataGridView()
CType(Me.dgv, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'lblTitle
'
Me.lblTitle.AutoSize = True
Me.lblTitle.Font = New System.Drawing.Font("Microsoft Sans Serif", 14.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.lblTitle.ForeColor = System.Drawing.Color.Lime
Me.lblTitle.Location = New System.Drawing.Point(149, 9)
Me.lblTitle.Name = "lblTitle"
Me.lblTitle.Size = New System.Drawing.Size(45, 24)
Me.lblTitle.TabIndex = 1
Me.lblTitle.Text = "Title"
'
'dgv
'
DataGridViewCellStyle1.BackColor = System.Drawing.Color.Black
DataGridViewCellStyle1.ForeColor = System.Drawing.Color.Lime
DataGridViewCellStyle1.SelectionBackColor = System.Drawing.Color.Gray
DataGridViewCellStyle1.SelectionForeColor = System.Drawing.Color.FromArgb(CType(CType(128, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(128, Byte), Integer))
Me.dgv.AlternatingRowsDefaultCellStyle = DataGridViewCellStyle1
Me.dgv.BackgroundColor = System.Drawing.Color.Black
DataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft
DataGridViewCellStyle2.BackColor = System.Drawing.Color.Black
DataGridViewCellStyle2.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
DataGridViewCellStyle2.ForeColor = System.Drawing.Color.Lime
DataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight
DataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText
DataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.[True]
Me.dgv.ColumnHeadersDefaultCellStyle = DataGridViewCellStyle2
Me.dgv.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
DataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft
DataGridViewCellStyle3.BackColor = System.Drawing.Color.Black
DataGridViewCellStyle3.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
DataGridViewCellStyle3.ForeColor = System.Drawing.Color.Lime
DataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight
DataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText
DataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.[False]
Me.dgv.DefaultCellStyle = DataGridViewCellStyle3
Me.dgv.EnableHeadersVisualStyles = False
Me.dgv.GridColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer))
Me.dgv.Location = New System.Drawing.Point(12, 61)
Me.dgv.Name = "dgv"
DataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft
DataGridViewCellStyle4.BackColor = System.Drawing.Color.Black
DataGridViewCellStyle4.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
DataGridViewCellStyle4.ForeColor = System.Drawing.Color.Lime
DataGridViewCellStyle4.SelectionBackColor = System.Drawing.SystemColors.Highlight
DataGridViewCellStyle4.SelectionForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(0, Byte), Integer))
DataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.[True]
Me.dgv.RowHeadersDefaultCellStyle = DataGridViewCellStyle4
DataGridViewCellStyle5.BackColor = System.Drawing.Color.Black
DataGridViewCellStyle5.ForeColor = System.Drawing.Color.Lime
Me.dgv.RowsDefaultCellStyle = DataGridViewCellStyle5
Me.dgv.Size = New System.Drawing.Size(1260, 726)
Me.dgv.TabIndex = 2
'
'frmFaqAnswerView
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.Color.Black
Me.ClientSize = New System.Drawing.Size(1298, 799)
Me.Controls.Add(Me.dgv)
Me.Controls.Add(Me.lblTitle)
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.KeyPreview = True
Me.Name = "frmFaqAnswerView"
Me.Text = "FAQ - Answers"
CType(Me.dgv, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents lblTitle As System.Windows.Forms.Label
Friend WithEvents dgv As System.Windows.Forms.DataGridView
End Class
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.