text stringlengths 43 2.01M |
|---|
'Program: Lab #7
'Programmer: Jim Galioto
'Date: 4/3/19
'Description: Calculate sales price using the BookSale class.
' Instantiate TheBookSale as a new object of the BookSale class.
Public Class SalesForm
' Declare the new object.
Dim TheBookSale As New BookSale
Dim TheBookSale2 As New BookSale
Private Sub CalculateSaleToolStripMenuItem_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles CalculateSaleToolStripMenuItem.Click
Try
' Calculate the extended price for the sale.
TheBookSale = New BookSale(TitleTextBox.Text,
Integer.Parse(QuantityTextBox.Text),
Decimal.Parse(PriceTextBox.Text))
'output the resule
ExtendedPriceTextBox.Text = TheBookSale.ExtendedPrice.ToString("c")
Catch ex As FormatException
'bad quantity
Catch ex1 As ArgumentOutOfRangeException
'catch errors thrown by class
MessageBox.Show(ex1.Message)
End Try
End Sub
Private Sub ClearToolStripMenuItem_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ClearToolStripMenuItem.Click
' Clear the screen controls.
QuantityTextBox.Clear()
PriceTextBox.Clear()
ExtendedPriceTextBox.Clear()
With TitleTextBox
.Clear()
.Focus()
End With
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
' Exit the program.
Me.Close()
End Sub
Private Sub SummaryToolStripMenuItem_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles SummaryToolStripMenuItem.Click
' Display the sales summary information.
Dim MessageString As String
MessageString = "Sales Count: " & BookSale.SalesCount.ToString & vbCrLf
MessageString &= "Sales Total: " & BookSale.SalesTotal.ToString("c")
MessageBox.Show(MessageString)
End Sub
Private Sub TitleTextBox_TextChanged(sender As Object, e As EventArgs) Handles TitleTextBox.TextChanged
End Sub
Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
'AboutBox1.Show() 'modeless
AboutBox1.ShowDialog() 'modally
End Sub
End Class
|
Imports AutoMapper
Imports UGPP.CobrosCoactivo.Datos
Imports UGPP.CobrosCoactivo.Entidades
Public Class ObservacionesCNCGralBLL
''' <summary>
''' Objeto para llamar métodos de consulta a la base de datos
''' </summary>
''' <returns></returns>
Private Property _ObservacionesCNCGralDAl As ObservacionesCNCGralDAL
Private Property _AuditEntity As Entidades.LogAuditoria
Public Sub New()
_ObservacionesCNCGralDAl = New ObservacionesCNCGralDAL()
End Sub
''' <param name="auditData"></param>
Public Sub New(ByVal auditData As Entidades.LogAuditoria)
_AuditEntity = auditData
_ObservacionesCNCGralDAl = New ObservacionesCNCGralDAL(_AuditEntity)
End Sub
Public Function ConvertirEntidadObservacionesCNC(ByVal prmObjModuloObservacionesCNCDatos As Datos.OBSERVACIONES_CUMPLE_NOCUMPLE) As Entidades.ObservacionesCNC
Dim Observaciones As Entidades.ObservacionesCNC
Dim config As New MapperConfiguration(Function(cfg)
Return cfg.CreateMap(Of Entidades.ObservacionesCNC, Datos.OBSERVACIONES_CUMPLE_NOCUMPLE)()
End Function)
Dim IMapper = config.CreateMapper()
Observaciones = IMapper.Map(Of Datos.OBSERVACIONES_CUMPLE_NOCUMPLE, Entidades.ObservacionesCNC)(prmObjModuloObservacionesCNCDatos)
Return Observaciones
End Function
''' <summary>
''' Obtiene las tipificaciones de cumple no cumple estudio de titulos
''' </summary>
''' <returns>Lista de objetos del tipo Entidades.ESTADO_OPERATIVO</returns>
Public Function obtenerObservacionesCNCGral(ByVal IdUnico As Int64) As List(Of Entidades.ObservacionesCNC)
Dim ObservacionesCNC = _ObservacionesCNCGralDAl.obtenerObservacionCNC(IdUnico)
Dim Observaciones As List(Of Entidades.ObservacionesCNC) = New List(Of Entidades.ObservacionesCNC)
For Each ObservacionesL As Datos.OBSERVACIONES_CUMPLE_NOCUMPLE In ObservacionesCNC
Observaciones.Add(ConvertirEntidadObservacionesCNC(ObservacionesL))
Next
Return Observaciones
End Function
End Class
|
Public Class Form1
' Data protocol setup.
' ----------------------------------------------------------------------------
' COM status indicator
Dim com_status As Integer = 0
' COM status constants
Const DISCONNECTED = 0
Const OPEN = 1
Const CONNECTED = 2
' COM timeout counter, interval is 50ms.
Dim com_timeout As Integer = 5
Const TIMEOUT = 5
' reserved start byte
Const START = &HFF
Const ESC = &HFE
' global RX variables
Const RX_LEN As Integer = 56
Const TX_LEN As Integer = 9
Dim rx_buffer(RX_LEN) As Byte
Dim rx_i As Integer = RX_LEN
' Data packets are validated by 8-bit CRC.
' CRC seed value
Const CRC_SEED = &H18
' CRC-8 Look-up Table
Dim CRC8LUT() As Byte = { _
&H0, &H18, &H30, &H28, &H60, &H78, &H50, &H48, &HC0, &HD8, &HF0, &HE8, &HA0, &HB8, &H90, &H88, _
&H98, &H80, &HA8, &HB0, &HF8, &HE0, &HC8, &HD0, &H58, &H40, &H68, &H70, &H38, &H20, &H8, &H10, _
&H28, &H30, &H18, &H0, &H48, &H50, &H78, &H60, &HE8, &HF0, &HD8, &HC0, &H88, &H90, &HB8, &HA0, _
&HB0, &HA8, &H80, &H98, &HD0, &HC8, &HE0, &HF8, &H70, &H68, &H40, &H58, &H10, &H8, &H20, &H38, _
&H50, &H48, &H60, &H78, &H30, &H28, &H0, &H18, &H90, &H88, &HA0, &HB8, &HF0, &HE8, &HC0, &HD8, _
&HC8, &HD0, &HF8, &HE0, &HA8, &HB0, &H98, &H80, &H8, &H10, &H38, &H20, &H68, &H70, &H58, &H40, _
&H78, &H60, &H48, &H50, &H18, &H0, &H28, &H30, &HB8, &HA0, &H88, &H90, &HD8, &HC0, &HE8, &HF0, _
&HE0, &HF8, &HD0, &HC8, &H80, &H98, &HB0, &HA8, &H20, &H38, &H10, &H8, &H40, &H58, &H70, &H68, _
&HA0, &HB8, &H90, &H88, &HC0, &HD8, &HF0, &HE8, &H60, &H78, &H50, &H48, &H0, &H18, &H30, &H28, _
&H38, &H20, &H8, &H10, &H58, &H40, &H68, &H70, &HF8, &HE0, &HC8, &HD0, &H98, &H80, &HA8, &HB0, _
&H88, &H90, &HB8, &HA0, &HE8, &HF0, &HD8, &HC0, &H48, &H50, &H78, &H60, &H28, &H30, &H18, &H0, _
&H10, &H8, &H20, &H38, &H70, &H68, &H40, &H58, &HD0, &HC8, &HE0, &HF8, &HB0, &HA8, &H80, &H98, _
&HF0, &HE8, &HC0, &HD8, &H90, &H88, &HA0, &HB8, &H30, &H28, &H0, &H18, &H50, &H48, &H60, &H78, _
&H68, &H70, &H58, &H40, &H8, &H10, &H38, &H20, &HA8, &HB0, &H98, &H80, &HC8, &HD0, &HF8, &HE0, _
&HD8, &HC0, &HE8, &HF0, &HB8, &HA0, &H88, &H90, &H18, &H0, &H28, &H30, &H78, &H60, &H48, &H50, _
&H40, &H58, &H70, &H68, &H20, &H38, &H10, &H8, &H80, &H98, &HB0, &HA8, &HE0, &HF8, &HD0, &HC8 _
}
' ----------------------------------------------------------------------------
' State variables as received.
' These are defined the same here as on the STM32F103.
Dim ia_int As Long
Dim ib_int As Long
Dim ic_int As Long
Dim idc_int As Integer
Dim Iqf As Single
Dim Idf As Single
Dim vdc_int As Integer
Dim rpmt_echo As Integer
Dim mag As Byte
Dim phase As Byte
Dim hallstate As Byte
Dim fluxstate As Byte
Dim v_idx_int_h As Integer
Dim v_idx_int_f As Integer
Dim speed_h As Integer
Dim speed_f As Integer
Dim faultstate As Integer
Dim debug_int As Integer
' State variable scaling constants.
' These should also be consistent with the STM32 program.
Const KRPM As Single = 133929 ' (3/25/2012)
Const KSPEED As Single = 2462 ' not right
Const KMAG As Single = 0.392 ' [%/lsb]
Const KPHASE As Single = 1.412 ' [deg/lsb]
Const A_MIN As Integer = 540 ' [lsb]
Const A_ZERO As Integer = 1200 ' [lsb]
Const A_MAX As Integer = 2610 ' [lsb]
' State variables as displayed / logged.
' These are scaled to be in physical units.
Dim v_dc_log As Single = 0.0 ' [V]
Dim i_dc_log As Single = 0.0 ' [A]
Dim i_a_log As Single = 0.0 ' [A]
Dim i_b_log As Single = 0.0 ' [A]
Dim i_c_log As Single = 0.0 ' [A]
Dim hallstate_log As Single = 0.0 ' [ABC]
Dim speed_log_h As Single = 0.0 ' [rpm]
Dim speed_log_f As Single = 0.0 ' [rpm]
Dim rpmt_log As Single = 0.0 ' [rpm]
Dim b_log As Single = 0.0 ' [%]
Dim mag_log As Single = 0.0 ' [%]
Dim phase_log As Single = 0.0 ' [deg]
Dim Iq_log As Single = 0.0 ' [A]
Dim Id_log As Single = 0.0 ' [A]
' Derived variables as displayed. They are not logged.
' These are scaled to be in physical units.
Dim time As System.DateTime ' time stamp of current packet
Dim prev_time As System.DateTime ' time stamp of previous packet
Dim dcpower As Single = 0.0 ' [W]
Dim dcenergy As Single = 0.0 ' [Wh]
Dim i_b As Single = 0.0 ' [A]
Dim groundspeed As Single = 0.0 ' [mph]
' Variables to transmit.
Dim accelt As Integer = 0
Dim phaset As Integer = 0
Dim rpmt As Integer = 0
' Data logging.
Dim path As String ' data recording path
Dim datafile As System.IO.StreamWriter ' data recording file class
Dim starttime As Date ' recording start time
' Data plotting.
Dim dataidx As Integer
Dim plotdata1(0 To 1023) As Single
Dim plotdata2(0 To 1023) As Single
Dim plotstep1 As Single
Dim plotstep2 As Single
Dim data1 As Integer
Dim data2 As Integer
Const DATAI As Integer = 1
Const DATAV As Integer = 2
Const DATAP As Integer = 3
Const DATAMAG As Integer = 4
Const DATAPHASE As Integer = 5
Const DATAIQ As Integer = 6
Const DATAID As Integer = 7
Const DATAIA As Integer = 8
Const DATAIB As Integer = 9
Const DATAIC As Integer = 10
Const DATAHALL As Integer = 11
Const DATAACCEL As Integer = 12
Const DATARPM As Integer = 13
Const DATASPEED As Integer = 14
Const DATARPMF As Integer = 15
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' stop yelling at me, I don't even have a multi-threading processor
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False
' initialize to COM1
cmbCOM_DropDown(Nothing, Nothing)
cmbCOM.SelectedItem = "COM1"
reset_globals()
End Sub
Private Sub reset_globals()
' Initialize or reset global variables.
rx_i = RX_LEN + 1
' Reset state variables.
ia_int = 0
ib_int = 0
ic_int = 0
idc_int = 0
Iqf = 0.0
Idf = 0.0
vdc_int = 0
rpmt_echo = 0
mag = 0
phase = 0
hallstate = 0
fluxstate = 0
v_idx_int_h = 0
v_idx_int_f = 0
speed_h = 0
speed_f = 0
faultstate = 0
convert_variables()
time = System.DateTime.Now
prev_time = System.DateTime.Now
data1 = DATARPM
plotstep1 = 100
lblData1.Text = "Armature Current [100A/div]"
data2 = DATAIQ
plotstep2 = 1000
lblData2.Text = "Tachometer [1000rpm/div]"
End Sub
Private Sub convert_variables()
' Convert state variables as received to physical units.
' State variables as logged.
v_dc_log = vdc_int / 1000.0
i_dc_log = idc_int / 1000.0
i_a_log = ia_int / 1000.0
i_b_log = ib_int / 1000.0
i_c_log = ic_int / 1000.0
hallstate_log = fluxstate
speed_log_h = KRPM * speed_h / &HFFFF
speed_log_f = KRPM * speed_f / &HFFFF
rpmt_log = rpmt_echo
mag_log = mag * KMAG
phase_log = phase * KPHASE
Iq_log = Iqf / 1000.0
Id_log = Idf / 1000.0
' Derived variables as displayed.
prev_time = time
time = System.DateTime.Now
dcpower = v_dc_log * i_dc_log
dcenergy = dcpower * (time - prev_time).TotalHours
i_b = -(i_a_log + i_c_log)
groundspeed = KSPEED * speed_h / &HFFFF
End Sub
Private Sub cmbCOM_DropDown(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbCOM.DropDown
' Refresh the available port list.
Dim PortList As Array
Dim i As Integer
For i = 0 To cmbCOM.Items.Count - 1
cmbCOM.Items.RemoveAt(0)
Next
PortList = System.IO.Ports.SerialPort.GetPortNames()
For Each PortString As String In PortList
cmbCOM.Items.Insert(0, PortString)
Next
End Sub
Private Sub btnCOM_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCOM.Click
' Toggle connection on or off.
Try
If serCOM.IsOpen() Then
serCOM.Close()
' enddata()
End If
If com_status = OPEN Or com_status = CONNECTED Then
tmrTX.Enabled = False
com_status = DISCONNECTED
btnCOM.Text = "Connect"
end_data()
reset_globals()
Else
serCOM.PortName = cmbCOM.SelectedItem
serCOM.Open()
'serCOM.DtrEnable = False
'serCOM.DtrEnable = True
com_status = OPEN
com_timeout = 0
btnCOM.Text = "Disconnect"
start_data()
tmrTX.Enabled = True
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub start_data()
' Begin recording to file. (Data is written every time a full packet is processed.)
path = "scooterdata.txt"
If System.IO.File.Exists(path) Then
System.IO.File.Delete(path)
End If
datafile = System.IO.File.CreateText(path)
starttime = System.DateTime.Now
datafile.Write("Pneu Scooter Data Log: " + System.DateTime.Now.ToString)
datafile.WriteLine()
datafile.Write("Time [s], ")
datafile.Write("DC Voltage [V], ")
datafile.Write("DC Current [A], ")
datafile.Write("Phase A Current [A], ")
datafile.Write("Phase B Current [A], ")
datafile.Write("Phase C Current [A], ")
datafile.Write("Sensor State [ABC], ")
datafile.Write("Flux State [ABC], ")
datafile.Write("Sensor Speed [rpm], ")
datafile.Write("Flux Speed [rpm], ")
datafile.Write("Accel Command [%], ")
datafile.Write("Brake Command [%], ")
datafile.Write("PWM Magnitude [%], ")
datafile.Write("PWM Phase [deg], ")
datafile.Write("Q-Axis Current [A], ")
datafile.Write("D-Axis Current [A], ")
datafile.Write("Sensor V-Index [16-bit], ")
datafile.Write("Flux V-Index [16-bit], ")
datafile.Write("Fault State, ")
datafile.Write("Debug Integer")
datafile.WriteLine()
End Sub
Private Sub write_data()
datafile.Write(Format((time - starttime).TotalSeconds, "0.00") + ", ")
datafile.Write(Format(v_dc_log, "0.00") + ", ")
datafile.Write(Format(i_dc_log, "0.00") + ", ")
datafile.Write(Format(i_a_log, "0.00") + ", ")
datafile.Write(Format(i_b_log, "0.00") + ", ")
datafile.Write(Format(i_c_log, "0.00") + ", ")
datafile.Write(Format(hallstate, "0") + ", ")
datafile.Write(Format(fluxstate, "0") + ", ")
datafile.Write(Format(speed_log_h, "0") + ", ")
datafile.Write(Format(speed_log_f, "0") + ", ")
datafile.Write(Format(rpmt_log, "0") + ", ")
datafile.Write(Format(b_log, "0.0") + ", ")
datafile.Write(Format(mag_log, "0.0") + ", ")
datafile.Write(Format(phase_log, "0.0") + ", ")
datafile.Write(Format(Iq_log, "0.00") + ", ")
datafile.Write(Format(Id_log, "0.00") + ", ")
datafile.Write(Format(v_idx_int_h, "0") + ", ")
datafile.Write(Format(v_idx_int_f, "0") + ", ")
datafile.Write(Format(faultstate, "0") + ", ")
datafile.Write(Format(debug_int, "0"))
datafile.WriteLine()
End Sub
Private Sub end_data()
Try
datafile.Close()
datafile.Dispose()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub serCOM_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles serCOM.DataReceived
' handles incoming data
Dim rx_data(4096) As Byte
Dim rx_size As Integer = 0
Dim i As Integer = 0
rx_size = serCOM.BytesToRead
serCOM.Read(rx_data, 0, rx_size)
For i = 0 To rx_size - 1
If rx_data(i) = START Then
' If any byte in the rx_data stream is START (&HFF)...
' ... start a new packet in rx_buffer.
rx_buffer(0) = START
rx_i = 1
ElseIf rx_i <= RX_LEN - 1 Then
' If the byte was not START and the packet is not yet full...
' ... add the byte to the packet and increment the index.
rx_buffer(rx_i) = rx_data(i)
rx_i = rx_i + 1
End If
If rx_i = RX_LEN Then
' If the packet is full, process it with rx().
rx()
End If
Next
End Sub
Private Sub rx()
' Attempt to process a received data packet.
Dim rflags As Byte = 0
Dim i, j As Integer
Dim rx_crc As Byte
' replace escaped characters
For j = 0 To 6
rflags = rx_buffer(50 + j)
For i = 0 To 6
If (rflags And (2 ^ i)) <> 0 Then ' rflags & (0x01 << i)
rx_buffer(7 * j + i + 1) = START
End If
Next
Next
' compute CRC
rx_crc = CRC_SEED
For i = 1 To 48
rx_crc = CRC8LUT(rx_buffer(i) Xor rx_crc)
Next
If rx_buffer(49) = rx_crc Then
' reset COM timeout
com_timeout = 0
com_status = CONNECTED
' parse state variables
ia_int = rx_buffer(1) * 2 ^ 24 + rx_buffer(2) * 2 ^ 16 + rx_buffer(3) * 2 ^ 8 + rx_buffer(4) - 100000
ib_int = rx_buffer(5) * 2 ^ 24 + rx_buffer(6) * 2 ^ 16 + rx_buffer(7) * 2 ^ 8 + rx_buffer(8) - 100000
ic_int = rx_buffer(9) * 2 ^ 24 + rx_buffer(10) * 2 ^ 16 + rx_buffer(11) * 2 ^ 8 + rx_buffer(12) - 100000
idc_int = rx_buffer(13) * 2 ^ 24 + rx_buffer(14) * 2 ^ 16 + rx_buffer(15) * 2 ^ 8 + rx_buffer(16) - 100000
Iqf = rx_buffer(17) * 2 ^ 24 + rx_buffer(18) * 2 ^ 16 + rx_buffer(19) * 2 ^ 8 + rx_buffer(20) - 100000.0
Idf = rx_buffer(21) * 2 ^ 24 + rx_buffer(22) * 2 ^ 16 + rx_buffer(23) * 2 ^ 8 + rx_buffer(24) - 100000.0
vdc_int = rx_buffer(25) * 2 ^ 24 + rx_buffer(26) * 2 ^ 16 + rx_buffer(27) * 2 ^ 8 + rx_buffer(28)
rpmt_echo = rx_buffer(29) * 2 ^ 8 + rx_buffer(30)
mag = rx_buffer(31)
phase = rx_buffer(32)
hallstate = (Int(rx_buffer(33) / 2 ^ 3)) And &H7
fluxstate = rx_buffer(33) And &H7
v_idx_int_h = rx_buffer(34) * 2 ^ 8 + rx_buffer(35)
v_idx_int_f = rx_buffer(36) * 2 ^ 8 + rx_buffer(37)
speed_h = rx_buffer(38) * 2 ^ 8 + rx_buffer(39)
speed_f = rx_buffer(40) * 2 ^ 8 + rx_buffer(41)
faultstate = rx_buffer(42)
debug_int = rx_buffer(43) * 2 ^ 24 + rx_buffer(44) * 2 ^ 16 + rx_buffer(45) * 2 ^ 8 + rx_buffer(46) - 100000
' calculated state variables in normal units
convert_variables()
' write data
If Not datafile Is Nothing Then
write_data()
End If
End If
rx_i = RX_LEN
End Sub
Private Sub cleardata1()
Dim n As Integer
For n = 0 To 1023
plotdata1(n) = 0
Next
End Sub
Private Sub cleardata2()
Dim n As Integer
For n = 0 To 1023
plotdata2(n) = 0
Next
End Sub
Private Sub trmPaint_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles trmPaint.Tick
Dim backbuffer = New Bitmap(picPlot.Width, picPlot.Height)
Dim buffergfx = Graphics.FromImage(backbuffer)
Dim plot As Graphics
Dim x1, y1, x2, y2 As Single
' timeout handler
If com_timeout < TIMEOUT Then
com_timeout = com_timeout + 1
ElseIf com_status = CONNECTED Then
com_status = OPEN
End If
' COM status indicator
Select Case com_status
Case DISCONNECTED : cmbCOM.BackColor = Color.DarkBlue : Exit Select
Case OPEN : cmbCOM.BackColor = Color.Blue : Exit Select
Case CONNECTED : cmbCOM.BackColor = Color.DeepSkyBlue : Exit Select
End Select
' Fill labels.
lblTime.Text = Format((System.DateTime.Now - starttime).TotalSeconds, "0.0")
lblV.Text = Format(v_dc_log, "0.00")
lblI.Text = Format(i_dc_log, "0.00")
lblIa.Text = Format(i_a_log, "0.00")
lblIc.Text = Format(i_c_log, "0.00")
lblHall.Text = Format(hallstate, "0")
lblRPM.Text = Format(speed_log_h, "0")
lblRPMf.Text = Format(speed_log_f, "0")
lblAccel.Text = Format(rpmt_log, "0")
lblMag.Text = Format(mag_log, "0.0")
lblPhase.Text = Format(phase_log, "0.0")
lblIq.Text = Format(Iq_log, "0.00")
lblId.Text = Format(Id_log, "0.00")
lblP.Text = Format(dcpower, "0")
lblE.Text = Format(dcenergy, "0.00")
lblIb.Text = Format(i_b_log, "0.00")
lblSpeed.Text = (Format(groundspeed, "0.0"))
' Fill the data circular buffer based on plot selections.
dataidx = (dataidx + 1) Mod 1024
Select Case data1
Case DATAI
plotdata1(dataidx) = i_dc_log
Exit Select
Case DATAV
plotdata1(dataidx) = v_dc_log
Exit Select
Case DATAP
plotdata1(dataidx) = dcpower
Exit Select
Case DATAMAG
plotdata1(dataidx) = mag_log
Exit Select
Case DATAPHASE
plotdata1(dataidx) = phase_log
Exit Select
Case DATAIQ
plotdata1(dataidx) = Iq_log
Exit Select
Case DATAID
plotdata1(dataidx) = Id_log
Exit Select
Case DATAIA
plotdata1(dataidx) = i_a_log
Exit Select
Case DATAIB
plotdata1(dataidx) = i_b
Exit Select
Case DATAIC
plotdata1(dataidx) = i_c_log
Exit Select
Case DATAHALL
plotdata1(dataidx) = hallstate_log
Exit Select
Case DATAACCEL
plotdata1(dataidx) = rpmt_log
Exit Select
Case DATARPM
plotdata1(dataidx) = speed_log_h
Exit Select
Case DATASPEED
plotdata1(dataidx) = groundspeed
Exit Select
Case DATARPMF
plotdata1(dataidx) = speed_log_f
Exit Select
End Select
Select Case data2
Case DATAI
plotdata2(dataidx) = i_dc_log
Exit Select
Case DATAV
plotdata2(dataidx) = v_dc_log
Exit Select
Case DATAP
plotdata2(dataidx) = dcpower
Exit Select
Case DATAMAG
plotdata2(dataidx) = mag_log
Exit Select
Case DATAPHASE
plotdata2(dataidx) = phase_log
Exit Select
Case DATAIQ
plotdata2(dataidx) = Iq_log
Exit Select
Case DATAID
plotdata2(dataidx) = Id_log
Exit Select
Case DATAIA
plotdata2(dataidx) = i_a_log
Exit Select
Case DATAIB
plotdata2(dataidx) = i_b
Exit Select
Case DATAIC
plotdata2(dataidx) = i_c_log
Exit Select
Case DATAHALL
plotdata2(dataidx) = hallstate_log
Exit Select
Case DATAACCEL
plotdata2(dataidx) = rpmt_log
Exit Select
Case DATARPM
plotdata2(dataidx) = speed_log_h
Exit Select
Case DATASPEED
plotdata2(dataidx) = groundspeed
Exit Select
Case DATARPMF
plotdata2(dataidx) = speed_log_f
Exit Select
End Select
' Do the plotting on a back-buffer.
buffergfx.FillRectangle(Brushes.DimGray, 0, 0, picPlot.Width, picPlot.Height)
For n = 1 To 20
x1 = 0
x2 = picPlot.Width
y1 = picPlot.Height * n / 20
y2 = y1
buffergfx.DrawLine(Pens.Gray, x1, y1, x2, y2)
Next
x1 = 0
x2 = picPlot.Width
y1 = picPlot.Height * 1 / 2 + 1
y2 = y1
buffergfx.DrawLine(Pens.Gray, x1, y1, x2, y2)
x1 = 0
x2 = picPlot.Width
y1 = picPlot.Height * 1 / 2 - 1
y2 = y1
buffergfx.DrawLine(Pens.Gray, x1, y1, x2, y2)
For n = 1 To picPlot.Width
x1 = n
y1 = (picPlot.Height / 2) - plotdata1((1024 + dataidx - picPlot.Width + n) Mod 1024) * picPlot.Height / (20 * plotstep1)
x2 = 2
y2 = 2
buffergfx.DrawEllipse(Pens.Yellow, x1, y1, x2, y2)
Next
For n = 1 To picPlot.Width
x1 = n
y1 = (picPlot.Height / 2) - plotdata2((1024 + dataidx - picPlot.Width + n) Mod 1024) * picPlot.Height / (20 * plotstep2)
x2 = 2
y2 = 2
buffergfx.DrawEllipse(Pens.Cyan, x1, y1, x2, y2)
Next
' Plot in the foreground.
plot = picPlot.CreateGraphics()
plot.DrawImage(backbuffer, 0, 0)
plot.Dispose()
buffergfx.Dispose()
backbuffer.Dispose()
Me.Text = faultstate
End Sub
Private Sub lblAccel_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lblAccel.MouseClick
If e.Button = Windows.Forms.MouseButtons.Left Then
cleardata1()
data1 = DATAACCEL
plotstep1 = 20
lblData1.Text = "Acceleration Command [20%/div]"
ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
cleardata2()
data2 = DATAACCEL
plotstep2 = 20
lblData2.Text = "Acceleration Command [20%/div]"
End If
End Sub
Private Sub lblRPM_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lblRPM.MouseClick
If e.Button = Windows.Forms.MouseButtons.Left Then
cleardata1()
data1 = DATARPM
plotstep1 = 200
lblData1.Text = "RPM (Hall Sensors) [200rpm/div]"
ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
cleardata2()
data2 = DATARPM
plotstep2 = 200
lblData2.Text = "RPM (Hall Sensors) [200rpm/div]"
End If
End Sub
Private Sub lblRPMf_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lblRPMf.MouseClick
If e.Button = Windows.Forms.MouseButtons.Left Then
cleardata1()
data1 = DATARPMF
plotstep1 = 1000
lblData1.Text = "RPM (Flux Estimator) [1000rpm/div]"
ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
cleardata2()
data2 = DATARPMF
plotstep2 = 1000
lblData2.Text = "RPM (Flux Estimator) [1000rpm/div]"
End If
End Sub
Private Sub lblSpeed_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lblSpeed.MouseClick
If e.Button = Windows.Forms.MouseButtons.Left Then
cleardata1()
data1 = DATASPEED
plotstep1 = 5
lblData1.Text = "Ground Speed [5km/h/div]"
ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
cleardata2()
data2 = DATASPEED
plotstep2 = 5
lblData2.Text = "Ground Speed [5km/h/div]"
End If
End Sub
Private Sub lblHall_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lblHall.MouseClick
If e.Button = Windows.Forms.MouseButtons.Left Then
cleardata1()
data1 = DATAHALL
plotstep1 = 1
lblData1.Text = "Sensor State [1ABC/div]"
ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
cleardata2()
data2 = DATAHALL
plotstep2 = 1
lblData2.Text = "Sensor State [1ABC/div]"
End If
End Sub
Private Sub lblIc_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lblIc.MouseClick
If e.Button = Windows.Forms.MouseButtons.Left Then
cleardata1()
data1 = DATAIC
plotstep1 = 5
lblData1.Text = "Phase C Current [5A/div]"
ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
cleardata2()
data2 = DATAIC
plotstep2 = 5
lblData2.Text = "Phase C Current [5A/div]"
End If
End Sub
Private Sub lblIb_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lblIb.MouseClick
If e.Button = Windows.Forms.MouseButtons.Left Then
cleardata1()
data1 = DATAIB
plotstep1 = 5
lblData1.Text = "Phase B Current [5A/div]"
ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
cleardata2()
data2 = DATAIB
plotstep2 = 5
lblData2.Text = "Phase B Current [5A/div]"
End If
End Sub
Private Sub lblIa_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lblIa.MouseClick
If e.Button = Windows.Forms.MouseButtons.Left Then
cleardata1()
data1 = DATAIA
plotstep1 = 5
lblData1.Text = "Phase A Current [5A/div]"
ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
cleardata2()
data2 = DATAIA
plotstep2 = 5
lblData2.Text = "Phase A Current [5A/div]"
End If
End Sub
Private Sub lblId_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lblId.MouseClick
If e.Button = Windows.Forms.MouseButtons.Left Then
cleardata1()
data1 = DATAID
plotstep1 = 5
lblData1.Text = "D-Axis Current [5A/div]"
ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
cleardata2()
data2 = DATAID
plotstep2 = 5
lblData2.Text = "D-Axis Current [5A/div]"
End If
End Sub
Private Sub lblIq_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lblIq.MouseClick
If e.Button = Windows.Forms.MouseButtons.Left Then
cleardata1()
data1 = DATAIQ
plotstep1 = 5
lblData1.Text = "Q-Axis Current [5A/div]"
ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
cleardata2()
data2 = DATAIQ
plotstep2 = 5
lblData2.Text = "Q-Axis Current [5A/div]"
End If
End Sub
Private Sub lblPhase_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lblPhase.MouseClick
If e.Button = Windows.Forms.MouseButtons.Left Then
cleardata1()
data1 = DATAPHASE
plotstep1 = 10
lblData1.Text = "PWM Phase [10deg/div]"
ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
cleardata2()
data2 = DATAPHASE
plotstep2 = 10
lblData2.Text = "PWM Phase [10deg/div]"
End If
End Sub
Private Sub lblMag_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lblMag.MouseClick
If e.Button = Windows.Forms.MouseButtons.Left Then
cleardata1()
data1 = DATAMAG
plotstep1 = 20
lblData1.Text = "PWM Magnitude [20%/div]"
ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
cleardata2()
data2 = DATAMAG
plotstep2 = 20
lblData2.Text = "PWM Magnitude [20%/div]"
End If
End Sub
Private Sub lblP_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lblP.MouseClick
If e.Button = Windows.Forms.MouseButtons.Left Then
cleardata1()
data1 = DATAP
plotstep1 = 100
lblData1.Text = "DC Power [100W/div]"
ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
cleardata2()
data2 = DATAP
plotstep2 = 100
lblData2.Text = "DC Power [100W/div]"
End If
End Sub
Private Sub lblI_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lblI.MouseClick
If e.Button = Windows.Forms.MouseButtons.Left Then
cleardata1()
data1 = DATAI
plotstep1 = 5
lblData1.Text = "DC Current [5A/div]"
ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
cleardata2()
data2 = DATAI
plotstep2 = 5
lblData2.Text = "DC Current [5A/div]"
End If
End Sub
Private Sub lblV_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lblV.MouseClick
If e.Button = Windows.Forms.MouseButtons.Left Then
cleardata1()
data1 = DATAV
plotstep1 = 5
lblData1.Text = "DC Voltage [5V/div]"
ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
cleardata2()
data2 = DATAV
plotstep2 = 5
lblData2.Text = "DC Voltage [5V/div]"
End If
End Sub
Private Sub trkAccel_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles trkAccel.Scroll
lblAccelt.Text = trkAccel.Value
accelt = trkAccel.Value
End Sub
Private Sub trkPhase_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles trkPhase.Scroll
lblPhaset.Text = trkPhase.Value
phaset = trkPhase.Value
End Sub
Private Sub tmrTX_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrTX.Tick
Dim tx_buffer(0 To TX_LEN - 1) As Byte
Dim i, j As Integer
Dim rflags As Byte
Dim tx_crc As Byte = CRC_SEED
tx_buffer(0) = START
tx_buffer(1) = Int(rpmt / 2 ^ 8) And &HFF
tx_buffer(2) = rpmt And &HFF
tx_buffer(3) = Int(phaset / 2 ^ 8) And &HFF
tx_buffer(4) = phaset And &HFF
tx_buffer(5) = 0
tx_buffer(6) = 0
' Calculate a CRC on bytes 1-146 and put it in byte 147
For i = 1 To 6
tx_crc = CRC8LUT(tx_buffer(i) Xor tx_crc)
Next
tx_buffer(7) = tx_crc
' Check for restricted character (START, &HFF) in bytes 1-147.
' Escape and flag these bytes using 21 groups of 7 flag bits.
For j = 0 To 0
rflags = &H0
For i = 0 To 6
If tx_buffer(7 * j + i + 1) = START Then
tx_buffer(7 * j + i + 1) = ESC
rflags = rflags Or (&H1 * 2 ^ i)
End If
Next
tx_buffer(8 + j) = rflags
Next
If chkTX.Checked = True Then
Try
serCOM.Write(tx_buffer, 0, TX_LEN)
Catch Ex As Exception
MsgBox(Ex.Message)
End Try
End If
End Sub
Private Sub btnRPM_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRPM.Click
If (IsNumeric(txtRPM.Text)) Then
If ((Val(txtRPM.Text) >= 0) And (Val(txtRPM.Text) <= 5000)) Then
rpmt = Int(Val(txtRPM.Text))
trkRPM.Value = rpmt
End If
End If
End Sub
Private Sub trkRPM_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles trkRPM.Scroll
txtRPM.Text = trkRPM.Value
End Sub
End Class
|
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Data
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Imaging
Imports System.Windows.Navigation
Imports devDept.Eyeshot.Entities
Imports devDept.Geometry
Namespace WpfApplication1
''' <summary>
''' Interaction logic for MainWindow.xaml
''' </summary>
Partial Public Class MainWindow
Public Sub New()
InitializeComponent()
'model1.Unlock("") ' For more details see 'Product Activation' topic in the documentation.
End Sub
Protected Overrides Sub OnContentRendered(e As EventArgs)
'#Region "Frame drawing"
Dim jointsLabel As String= "Joints"
Dim barsLabel As String= "Bars"
model1.Layers.Add("Joints", System.Drawing.Color.Red)
model1.Layers.Add("Bars", System.Drawing.Color.DimGray)
model1.Entities.Add(New Joint(-40, -20, 0, 2.5, 2), jointsLabel)
model1.Entities.Add(New Joint(-40, +20, 0, 2.5, 2), jointsLabel)
model1.Entities.Add(New Joint(+40, -20, 0, 2.5, 2), jointsLabel)
model1.Entities.Add(New Joint(+40, +20, 0, 2.5, 2), jointsLabel)
model1.Entities.Add(New Bar(-40, -20, 0, +40, -20, 0, 1, 8), barsLabel)
model1.Entities.Add(New Bar(-40, +20, 0, +40, +20, 0, 1, 8), barsLabel)
model1.Entities.Add(New Joint(+40, 0, 40, 2.5, 2), jointsLabel)
model1.Entities.Add(New Joint(-40, 0, 40, 2.5, 2), jointsLabel)
model1.Entities.Add(New Bar(-40, 0, 40, +40, 0, 40, 1, 8), barsLabel)
model1.Entities.Add(New Bar(-40, -20, 0, -40, +20, 0, 1, 8), barsLabel)
model1.Entities.Add(New Bar(-40, -20, 0, -40, 0, 40, 1, 8), barsLabel)
model1.Entities.Add(New Bar(-40, +20, 0, -40, 0, 40, 1, 8), barsLabel)
model1.Entities.Add(New Bar(+40, -20, 0, +40, +20, 0, 1, 8), barsLabel)
model1.Entities.Add(New Bar(+40, -20, 0, +40, 0, 40, 1, 8), barsLabel)
model1.Entities.Add(New Bar(+40, +20, 0, +40, 0, 40, 1, 8), barsLabel)
model1.Entities.Add(New Bar(-40, -20, 0, +40, +20, 0, 1, 8), barsLabel)
model1.Entities.Add(New Bar(+40, -20, 0, +120, -20, 0, 1, 8), barsLabel)
model1.Entities.Add(New Bar(+40, +20, 0, +120, +20, 0, 1, 8), barsLabel)
model1.Entities.Add(New Bar(+40, 0, 40, +120, +20, 0, 1, 8), barsLabel)
model1.Entities.Add(New Bar(+40, 0, 40, +120, -20, 0, 1, 8), barsLabel)
model1.Entities.Add(New Bar(+120, +20, 0, +120, -20, 0, 1, 8), barsLabel)
model1.Entities.Add(New Bar(+40, +20, 0, +120, -20, 0, 1, 8), barsLabel)
model1.Entities.Add(New Joint(120, -20, 0, 2.5, 2), jointsLabel)
model1.Entities.Add(New Joint(120, +20, 0, 2.5, 2), jointsLabel)
'#End Region
' adds cable layer and entities
model1.LineTypes.Add("Dash", New Single() {2, -1})
Dim cableLayer As String = "Cable"
model1.Layers.Add(cableLayer, System.Drawing.Color.Teal, "Dash")
Dim xz As New Plane(New Point3D(110, 0, -10), Vector3D.AxisX, Vector3D.AxisZ)
Dim l1 As New Line(-60, 0, -10, 120, 0, -10)
Dim a1 As New Arc(xz, New Point3D(120, 0, -15), 5, 0, Math.PI / 2)
Dim l2 As New Line(125, 0, -15, 125, 0, -50)
model1.Entities.AddRange(New Entity() {l1, a1, l2}, cableLayer)
' adds pulley layer and entities
Dim pulleyLayer As String = "Pulley"
model1.Layers.Add(pulleyLayer, System.Drawing.Color.Magenta)
Dim c1 As New Circle(xz, New Point3D(120, 0, -15), 5)
Dim c2 As New Circle(xz, New Point3D(120, 0, -15), 7)
Dim c3 As New Circle(xz, New Point3D(120, 0, -15), 2)
model1.Entities.AddRange(New Entity() {c1, c2, c3}, pulleyLayer)
' axes on default layer with their own line style
Dim l3 As New Line(110, 0, -15, 130, 0, -15)
model1.LineTypes.Add("DashDot", New Single() {5, -1.5F, 0.25F, -1.5F})
l3.LineTypeMethod = colorMethodType.byEntity
l3.LineTypeName = "DashDot"
Dim l4 As New Line(120, 0, -5, 120, 0, -25)
l4.LineTypeMethod = colorMethodType.byEntity
l4.LineTypeName = "DashDot"
model1.Entities.Add(l3)
model1.Entities.Add(l4)
model1.ZoomFit()
model1.Invalidate()
MyBase.OnContentRendered(e)
End Sub
End Class
End Namespace
|
Imports System.Collections.ObjectModel
Imports System.IO
Imports System.Text.RegularExpressions
Imports BVSoftware.Bvc5.Core
Namespace FeedEngine.Sitemaps
Public Class GoogleSitemap
Inherits BaseSitemapXmlFeed
Private Const COMPONENTID As String = "33775C61-7388-4b28-8BB2-F3D866E21A7C"
Private _IncludeProductImages As Boolean
#Region " Default Properties "
Protected Overrides ReadOnly Property DEFAULT_FEEDNAME() As String
Get
Return "Google Sitemap"
End Get
End Property
Protected Overrides ReadOnly Property DEFAULT_FILENAME() As String
Get
Return "sitemap.xml"
End Get
End Property
Protected Overrides ReadOnly Property DEFAULT_FILEPATH() As String
Get
Return String.Empty
End Get
End Property
Protected Overridable ReadOnly Property DEFAULT_INCLUDEPRODUCTIMAGES() As Boolean
Get
Return False
End Get
End Property
#End Region
#Region " Properties "
Public Overridable Property IncludeProductImages() As Boolean
Get
Return Me._IncludeProductImages
End Get
Set(ByVal value As Boolean)
Me._IncludeProductImages = value
End Set
End Property
#End Region
Sub New()
MyBase.New(COMPONENTID)
Me.SettingsManager = New Datalayer.ComponentSettingsManager(COMPONENTID)
Dim setting As String = String.Empty
setting = Me.SettingsManager.GetSetting("IncludeProductImages")
Me._IncludeProductImages = If(Not String.IsNullOrEmpty(setting), System.Convert.ToBoolean(setting), Me.DEFAULT_INCLUDEPRODUCTIMAGES)
End Sub
Public Overrides Sub SaveSettings()
MyBase.SaveSettings()
Me.SettingsManager.SaveSetting("IncludeProductImages", Me.IncludeProductImages.ToString(), "Develisys", "Product Feed", Me.FeedName)
End Sub
Public Overrides Function GenerateFeedAndUpload() As Boolean
GenerateFeed()
If Me.PingSearchEngines Then
PingAllSearchEngines()
End If
Return UploadFile()
End Function
Protected Overrides Sub WriteRootStartElement()
xw.WriteStartDocument()
xw.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9")
If Me.IncludeProductImages Then
xw.WriteAttributeString("xmlns", "image", Nothing, "http://www.google.com/schemas/sitemap-image/1.1")
End If
xw.WriteComment(" Generated by BV Commerce 2013 - http://www.bvcommerce.com/ ")
End Sub
Protected Overrides Sub WriteProductPage(ByRef p As Catalog.Product)
xw.WriteStartElement("url")
xw.WriteElementString("loc", Me.CreateProductUrl(p))
xw.WriteElementString("lastmod", p.LastUpdated.ToString(Me.DateFormat))
xw.WriteElementString("changefreq", Me.DefaultChangeFreq)
xw.WriteElementString("priority", Me.DefaultPriority)
' Product images
If Me.IncludeProductImages Then
Dim mediumImage As New Catalog.ProductImage()
mediumImage.Bvin = p.Bvin ' fake the bvin to pass data checks in CreateProductAdditionalImageUrl method
mediumImage.FileName = p.ImageFileMedium
mediumImage.ProductId = p.Bvin
Dim productImages As Collection(Of Catalog.ProductImage) = Catalog.ProductImage.FindByProductId(p.Bvin)
productImages.Insert(0, mediumImage)
For Each pi As Catalog.ProductImage In Catalog.ProductImage.FindByProductId(p.Bvin)
Dim imageUrl As String = Me.CreateProductAdditionalImageUrl(pi)
Dim title As String = Me.CleanXmlText(If(String.IsNullOrEmpty(pi.AlternateText), p.ProductName, pi.AlternateText))
Dim caption As String = Me.CleanXmlText(pi.Caption)
If Not String.IsNullOrEmpty(imageUrl) Then
xw.WriteStartElement("image", "image", Nothing)
xw.WriteStartElement("image", "loc", Nothing)
xw.WriteString(imageUrl)
xw.WriteEndElement()
If Not String.IsNullOrEmpty(title) Then
xw.WriteStartElement("image", "title", Nothing)
xw.WriteString(title)
xw.WriteEndElement()
End If
If Not String.IsNullOrEmpty(caption) Then
xw.WriteStartElement("image", "caption", Nothing)
xw.WriteString(caption)
xw.WriteEndElement()
End If
xw.WriteEndElement() '/image:image
End If
Next
End If
xw.WriteEndElement() '/url
End Sub
End Class
End Namespace |
Imports LibreriaLogica
Public Class DatosUser
Private tupla As DataRow
''' <summary>
''' Constructor específico encargado de inicializar la instancia de la clase y tomar como parámetro una tupla conteniendo los datos del vehículo a mostrar los detalles.
''' </summary>
''' <param name="fila">Tupla conteniendo todos los datos del vehículo en cuestión.</param>
Public Sub New(fila As DataRow)
InitializeComponent()
tupla = fila
OpcGraficas()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btn_delete.Click
End Sub
Private Sub btn_edit_Click(sender As Object, e As EventArgs) Handles btn_edit.Click
End Sub
'username 0, contraseña 1, NOMBRe 2, apellido 3
Private Sub traducirControles()
If Settings.GetSingleton.LangCFG = Settings.LangEnum.EN_UK Then
''traduce al ingles
' lbl_apellido.Text = My.Resources.EN_UK.DatosUser_lblApellido
' lbl_movil.Text = My.Resources.EN_UK.DatosUser_lbl
ElseIf Settings.GetSingleton.LangCFG = Settings.LangEnum.ES_LA Then
''traduce al español
Else
''traduce al portugues
End If
End Sub
Private Sub OpcGraficas()
Me.BackColor = propiedadesVentanas.GetSingleton.ColorFondo
lbl_apellido.ForeColor = propiedadesVentanas.GetSingleton.ColorForeLabels
lbl_movil.ForeColor = propiedadesVentanas.GetSingleton.ColorForeLabels
lbl_newpass.ForeColor = propiedadesVentanas.GetSingleton.ColorForeLabels
lbl_nombre.ForeColor = propiedadesVentanas.GetSingleton.ColorForeLabels
lbl_telfijo.ForeColor = propiedadesVentanas.GetSingleton.ColorForeLabels
btn_edit.ForeColor = propiedadesVentanas.GetSingleton.ColorForeBotones
btn_edit.BackColor = propiedadesVentanas.GetSingleton.ColorBackBotones
btn_save.ForeColor = propiedadesVentanas.GetSingleton.ColorForeBotones
btn_save.BackColor = propiedadesVentanas.GetSingleton.ColorBackBotones
btn_delete.BackColor = propiedadesVentanas.GetSingleton.ColorBackBotones
btn_delete.ForeColor = propiedadesVentanas.GetSingleton.ColorForeBotones
End Sub
Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_save.Click
End Sub
End Class |
Public Class Easter
'*****************
'* GetEasterDate *
'*****************
'
' Returns the EventDate of the next Easter
'
<AllowAnonymous>
Public Shared Function GetEasterDate() As DateTime
Dim eventYear As Integer = Date.UtcNow.Year
Dim h As Integer = (24 + 19 * (eventYear Mod 19)) Mod 30
Dim i As Integer = CInt(h - h / 28)
Dim j As Integer = CInt((eventYear + eventYear / 4 + i - 13) Mod 7)
Dim l As Integer = i - j
Dim eventMonth As Integer = CInt(3 + ((i - j) + 40) / 44)
Dim eventDay As Integer = CInt(l + 28 - 31 * (eventMonth / 4))
Dim eventDate As Date = Date.Parse(eventYear.ToString + "-" +
eventMonth.ToString + "-" +
eventDay.ToString +
"T00:00:00").ToUniversalTime
If eventDate < Date.UtcNow Then
eventYear = Date.UtcNow.Year + 1
h = (24 + 19 * (eventYear Mod 19)) Mod 30
i = CInt(h - h / 28)
j = CInt((eventYear + eventYear / 4 + i - 13) Mod 7)
l = i - j
eventMonth = CInt(3 + ((i - j) + 40) / 44)
eventDay = CInt(l + 28 - 31 * (eventMonth / 4))
eventDate = Date.Parse(eventYear.ToString + "-" +
eventMonth.ToString + "-" +
eventDay.ToString +
"T00:00:00").ToUniversalTime
End If
Return eventDate
End Function
End Class |
option explicit
sub main() ' {
dim rng as range
set rng = range(cells(1,1), cells(1,3))
rng.numberFormat = "@"
rng = array("01", "+2", "1E4")
dim cel as range
for each cel in rng
cel.errors(xlNumberAsText).ignore = true
next cel
end sub ' }
|
Option Compare Binary
Option Explicit On
Option Infer Off
Option Strict On
Imports Watermark_Lead.Common
Imports Watermark_Lead.WebUI
Imports Watermark_Lead.Utils
Imports Watermark_Lead.DAL
Public Class LostStatusControl
Inherits BaseControl
Public Event ClosePopup As EventHandler
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack = True Then
Return
End If
txtStatusDateWatermarkExtender.WatermarkText = WebUIConstants.Watermark_Date
txtStatusDate.Attributes.Add("readonly", "readonly")
SetDropDownLists()
End Sub
Public Sub StartForm(ByVal LeadID As Integer)
Try
LoadData(LeadID)
LostStatusControlModalPopupExtender.Show()
Catch ex As Exception
TempLogManager.GetInstance().LogException(0, ex)
End Try
End Sub
#Region "ClickEvents"
Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCancel.Click
LostStatusControlModalPopupExtender.Hide()
End Sub
Protected Sub ddlCompetition_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlCompetition.SelectedIndexChanged
Dim thisCompetitionD As Integer = CInt(CType(sender, DropDownList).SelectedValue)
If thisCompetitionD = 127 Then
txtCompetitionOther.Enabled = True
txtCompetitionOther.CssClass = "reqdfield"
'txtCompetitionOtherRequiredFieldValidator.Enabled = True
Else
txtCompetitionOther.Enabled = False
txtCompetitionOther.CssClass = "optfield"
'txtCompetitionOtherRequiredFieldValidator.Enabled = False
End If
LostStatusControlModalPanel.Update()
End Sub
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
Try
Me.Page_DAO.BeginTransaction()
Dim thisLeadID As Long = CLng(hfLeadID.Value)
Dim newStatus As Status = New Status With {
.LeadID = thisLeadID,
.StatusDate = CDate(txtStatusDate.Text),
.Competition = CLng(ddlCompetition.SelectedValue),
.CompetitionOther = txtCompetitionOther.Text,
.Notes = txtNotes.Text,
.InsertUserID = CLng(Session(SystemConstants.SESSION_USERID)),
.StatusID = 30
}
newStatus.insertRecord(Me.Page_DAO)
Session(SystemConstants.SESSION_DISPLAYSTATUSID) = newStatus.ID
Me.Page_DAO.CommitTransaction()
Catch ex As Exception
Me.Page_DAO.RollbackTransaction()
TempLogManager.GetInstance().LogException(0, ex)
End Try
LostStatusControlModalPopupExtender.Hide()
Me.OnClosePopup(New EventArgs())
End Sub
#End Region 'Click Events
#Region "Setup Methods"
Private Sub LoadData(ByVal leadID As Integer)
hfLeadID.Value = leadID.ToString()
txtStatusDate.Text = Today().ToString()
txtCompetitionOther.Text = ""
SetDropDownValue(ddlCompetition, "0")
txtNotes.Text = ""
End Sub
Private Sub SetDropDownLists()
LoadDDValueAndDesc(ddlCompetition, ReferenceCode.GetActiveRefCodeForRefType(13, Me.Page_DAO), "ID", "Description", "Description", True)
End Sub
#End Region
#Region "Custom Event Methods"
'=======================================================================
'=== Custom Events ======================================================
'=======================================================================
Protected Overridable Sub OnClosePopup(In__EventArgs As EventArgs)
RaiseEvent ClosePopup(Me, In__EventArgs)
End Sub
#End Region 'Custom Events
End Class |
Option Strict On 'プロジェクトのプロパティでも設定可能
Public Class cDataArrivalSubDBIO
Private pConn As OleDb.OleDbConnection
Private pCommand As OleDb.OleDbCommand
Private pDataReader As OleDb.OleDbDataReader
Private pMessageBox As cMessageLib.fMessage
Sub New(ByRef iConn As OleDb.OleDbConnection, ByRef iCommand As OleDb.OleDbCommand, ByRef iDataReader As OleDb.OleDbDataReader)
pConn = iConn
pCommand = iCommand
pDataReader = iDataReader
End Sub
'----------------------------------------------------------------------
' 機能:注文情報テーブルから該当注文コード・注文明細コードのデータを取得する関数
' 引数:Byref DataTable型オブジェクト(取得された取引レコード値を設定)
' 戻値:True --> レコードの取得成功
' False --> 取得するレコードなし
'----------------------------------------------------------------------
Public Function getArrivalSubData(ByRef parArrivalSubData() As cStructureLib.sArrivalSubData, _
ByVal KeyArrivalCode As String, _
ByRef Tran As System.Data.OleDb.OleDbTransaction) As Long
Dim i As Integer
Try
Const strSelectArrival As String = _
"SELECT * FROM 入庫情報明細データ WHERE 発注コード = @OrderCode"
'コマンドオブジェクトの生成
pCommand = pConn.CreateCommand()
pCommand.Transaction = Tran
'SQL文の設定
pCommand.CommandText = strSelectArrival
'***********************
' パラメータの設定
'***********************
'2020,1,14 A.Komita Nothing判定時のelseを追加 From
'取引コード
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@OrderCode", OleDb.OleDbType.Char, 13))
If KeyArrivalCode <> Nothing Then
pCommand.Parameters("@OrderCode").Value = KeyArrivalCode
Else
pCommand.Parameters("@OrderCode").Value = ""
End If
'2020,1,14 A.Komita 追加 To
pDataReader = pCommand.ExecuteReader()
i = 0
While pDataReader.Read()
ReDim Preserve parArrivalSubData(i)
'発注コード
parArrivalSubData(i).sOrderCode = pDataReader("発注コード").ToString
'発注明細コード
If IsDBNull(pDataReader("発注明細コード")) = True Then
parArrivalSubData(i).sOrderDetailNo = 0
Else
parArrivalSubData(i).sOrderDetailNo = CInt(pDataReader("発注明細コード"))
End If
'入庫番号
If IsDBNull(pDataReader("入庫番号")) = True Then
parArrivalSubData(i).sArrivalNo = 0
Else
parArrivalSubData(i).sArrivalNo = CInt(pDataReader("入庫番号"))
End If
'JANコード
parArrivalSubData(i).sJANCode = pDataReader("JANコード").ToString
'商品コード
parArrivalSubData(i).sProductCode = pDataReader("商品コード").ToString
'商品名称
parArrivalSubData(i).sProductName = pDataReader("商品名称").ToString
'オプション1
parArrivalSubData(i).sOption1 = pDataReader("オプション1").ToString
'オプション2
parArrivalSubData(i).sOption2 = pDataReader("オプション2").ToString
'オプション3
parArrivalSubData(i).sOption3 = pDataReader("オプション3").ToString
'オプション4
parArrivalSubData(i).sOption4 = pDataReader("オプション4").ToString
'オプション5
parArrivalSubData(i).sOption5 = pDataReader("オプション5").ToString
'定価
If IsDBNull(pDataReader("定価")) = True Then
parArrivalSubData(i).sListPrice = 0
Else
parArrivalSubData(i).sListPrice = CLng(pDataReader("定価"))
End If
'仕入単価
If IsDBNull(pDataReader("仕入単価")) = True Then
parArrivalSubData(i).sCostPrice = 0
Else
parArrivalSubData(i).sCostPrice = CLng(pDataReader("仕入単価"))
End If
'入庫商品単価
If IsDBNull(pDataReader("入庫商品単価")) = True Then
parArrivalSubData(i).sUnitPrice = 0
Else
parArrivalSubData(i).sUnitPrice = CLng(pDataReader("入庫商品単価"))
End If
'入庫数量
If IsDBNull(pDataReader("入庫数量")) = True Then
parArrivalSubData(i).sCount = 0
Else
parArrivalSubData(i).sCount = CInt(pDataReader("入庫数量"))
End If
'入庫税抜金額
If IsDBNull(pDataReader("入庫税抜金額")) = True Then
parArrivalSubData(i).sNoTaxPrice = 0
Else
parArrivalSubData(i).sNoTaxPrice = CLng(pDataReader("入庫税抜金額"))
End If
'入庫消費税額
If IsDBNull(pDataReader("入庫消費税額")) = True Then
parArrivalSubData(i).sTaxPrice = 0
Else
parArrivalSubData(i).sTaxPrice = CLng(pDataReader("入庫消費税額"))
End If
'入庫税込金額
If IsDBNull(pDataReader("入庫税込金額")) = True Then
parArrivalSubData(i).sPrice = 0
Else
parArrivalSubData(i).sPrice = CLng(pDataReader("入庫税込金額"))
End If
'納入残数
If IsDBNull(pDataReader("納入残数")) = True Then
parArrivalSubData(i).sArrivalStiffness = 0
Else
parArrivalSubData(i).sArrivalStiffness = CLng(pDataReader("納入残数"))
End If
'登録日
parArrivalSubData(i).sCreateDate = pDataReader("登録日").ToString
'登録時間
parArrivalSubData(i).ScreateTime = pDataReader("登録時間").ToString
'最終更新日
parArrivalSubData(i).sUpdateDate = pDataReader("最終更新日").ToString
'最終更新時間
parArrivalSubData(i).sUpdateTime = pDataReader("最終更新時間").ToString
i = i + 1
End While
getArrivalSubData = i
Catch oExcept As Exception
'例外が発生した時の処理
pMessageBox = New cMessageLib.fMessage(1, "システムエラー(cArrivalDataSubDBIO.getArrivalSubData)", Nothing, Nothing, oExcept.ToString)
pMessageBox.ShowDialog()
pMessageBox.Dispose()
pMessageBox = Nothing
Environment.Exit(1)
Finally
If IsNothing(pDataReader) = False Then
pDataReader.Close()
End If
End Try
End Function
'----------------------------------------------------------------------
' 機能:注文情報テーブルから該当注文コード・注文明細コードの入庫残数を取得
' 引数:Byref DataTable型オブジェクト(取得された取引レコード値を設定)
' 戻値:True --> レコードの取得成功
' False --> 取得するレコードなし
'----------------------------------------------------------------------
Public Function getSitffnessCount(ByRef parArrivalSubData() As cStructureLib.sArrivalSubData, _
ByVal KeyOrderCode As String, _
ByVal KeyOrderSubCode As Integer, _
ByRef Tran As System.Data.OleDb.OleDbTransaction) As Integer
Dim i As Integer
Dim strSelectArrival As String
Try
strSelectArrival = "SELECT " & _
"入庫情報明細データ.発注コード, " & _
"入庫情報明細データ.発注明細コード, " & _
"入庫情報明細データ.商品コード, " & _
"Min(入庫情報明細データ.納入残数) AS 納入残数 " & _
"FROM(入庫情報明細データ) " & _
"GROUP BY " & _
"入庫情報明細データ.発注コード, " & _
"入庫情報明細データ.発注明細コード, " & _
"入庫情報明細データ.商品コード " & _
"HAVING (((入庫情報明細データ.発注コード)= """ & KeyOrderCode & """) " & _
"AND ((入庫情報明細データ.発注明細コード)= " & KeyOrderSubCode & "))"
'コマンドオブジェクトの生成
pCommand = pConn.CreateCommand()
pCommand.Transaction = Tran
'SQL文の設定
pCommand.CommandText = strSelectArrival
pDataReader = pCommand.ExecuteReader()
i = 0
If pDataReader.Read() Then
ReDim Preserve parArrivalSubData(i)
'発注コード
parArrivalSubData(i).sOrderCode = pDataReader("発注コード").ToString
'発注明細コード
If IsDBNull(pDataReader("発注明細コード")) = True Then
parArrivalSubData(i).sOrderDetailNo = 0
Else
parArrivalSubData(i).sOrderDetailNo = CInt(pDataReader("発注明細コード"))
End If
'商品コード
parArrivalSubData(i).sProductCode = pDataReader("商品コード").ToString
'納入残数
parArrivalSubData(i).sArrivalStiffness = CInt(pDataReader("納入残数"))
getSitffnessCount = CInt(pDataReader("納入残数"))
Else
getSitffnessCount = -1
End If
Catch oExcept As Exception
'例外が発生した時の処理
pMessageBox = New cMessageLib.fMessage(1, "システムエラー(cArrivalDataSubDBIO.getSitffnessCount)", Nothing, Nothing, oExcept.ToString)
pMessageBox.ShowDialog()
pMessageBox.Dispose()
pMessageBox = Nothing
Environment.Exit(1)
Finally
If IsNothing(pDataReader) = False Then
pDataReader.Close()
End If
End Try
End Function
'----------------------------------------------------------------------
' 機能:注文情報テーブルから該当注文コード・注文明細コードの入庫残数を取得
' 引数:Byref DataTable型オブジェクト(取得された取引レコード値を設定)
' 戻値:True --> レコードの取得成功
' False --> 取得するレコードなし
'----------------------------------------------------------------------
Public Function getLastArrivalSubData(ByRef parArrivalSubData() As cStructureLib.sArrivalSubData, _
ByVal KeyOrderCode As String, _
ByVal KeyOrderSubCode As Integer, _
ByVal KeyProductCode As String, _
ByRef Tran As System.Data.OleDb.OleDbTransaction) As Integer
Dim strSelectArrival As String
Dim i As Integer
Dim pc As Integer
Dim scnt As Integer
Dim mpc As Integer
Try
strSelectArrival = "SELECT * FROM 入庫情報明細データ "
'コマンドオブジェクトの生成
pCommand = pConn.CreateCommand()
pCommand.Transaction = Tran
'パラメータ数のカウント
pc = 0
mpc = 0
If KeyOrderCode <> Nothing Then
mpc = 1
pc = pc Or mpc
End If
If KeyOrderSubCode <> Nothing Then
mpc = 2
pc = pc Or mpc
End If
If KeyProductCode <> Nothing Then
mpc = 4
pc = pc Or mpc
End If
'パラメータ指定がある場合
If (mpc And pc) > 0 Then
i = 1
scnt = 0
While i <= mpc
Select Case i And pc
Case 1
If scnt > 0 Then
strSelectArrival = strSelectArrival & "AND "
Else
strSelectArrival = strSelectArrival & "WHERE "
End If
strSelectArrival = strSelectArrival & "発注コード= """ & KeyOrderCode & """ "
scnt = scnt + 1
Case 2
If scnt > 0 Then
strSelectArrival = strSelectArrival & "AND "
Else
strSelectArrival = strSelectArrival & "WHERE "
End If
strSelectArrival = strSelectArrival & "発注明細コード= " & KeyOrderSubCode & " "
scnt = scnt + 1
Case 4
If scnt > 0 Then
strSelectArrival = strSelectArrival & "AND "
Else
strSelectArrival = strSelectArrival & "WHERE "
End If
strSelectArrival = strSelectArrival & "商品コード= """ & KeyProductCode & """ "
scnt = scnt + 1
End Select
i = i * 2
End While
End If
strSelectArrival = strSelectArrival & "ORDER BY 入庫番号 DESC "
'SQL文の設定
pCommand.CommandText = strSelectArrival
pDataReader = pCommand.ExecuteReader()
i = 0
If pDataReader.Read() Then
ReDim Preserve parArrivalSubData(i)
'発注コード
parArrivalSubData(i).sOrderCode = pDataReader("発注コード").ToString
'発注明細コード
If IsDBNull(pDataReader("発注明細コード")) = True Then
parArrivalSubData(i).sOrderDetailNo = 0
Else
parArrivalSubData(i).sOrderDetailNo = CInt(pDataReader("発注明細コード"))
End If
'入庫番号
If IsDBNull(pDataReader("入庫番号")) = True Then
parArrivalSubData(i).sArrivalNo = 0
Else
parArrivalSubData(i).sArrivalNo = CInt(pDataReader("入庫番号"))
End If
'JANコード
parArrivalSubData(i).sJANCode = pDataReader("JANコード").ToString
'商品コード
parArrivalSubData(i).sProductCode = pDataReader("商品コード").ToString
'商品名称
parArrivalSubData(i).sProductName = pDataReader("商品名称").ToString
'オプション1
parArrivalSubData(i).sOption1 = pDataReader("オプション1").ToString
'オプション2
parArrivalSubData(i).sOption2 = pDataReader("オプション2").ToString
'オプション3
parArrivalSubData(i).sOption3 = pDataReader("オプション3").ToString
'オプション4
parArrivalSubData(i).sOption4 = pDataReader("オプション4").ToString
'オプション5
parArrivalSubData(i).sOption5 = pDataReader("オプション5").ToString
'定価
If IsDBNull(pDataReader("定価")) = True Then
parArrivalSubData(i).sListPrice = 0
Else
parArrivalSubData(i).sListPrice = CLng(pDataReader("定価"))
End If
'仕入単価
If IsDBNull(pDataReader("仕入単価")) = True Then
parArrivalSubData(i).sCostPrice = 0
Else
parArrivalSubData(i).sCostPrice = CLng(pDataReader("仕入単価"))
End If
'入庫商品単価
If IsDBNull(pDataReader("入庫商品単価")) = True Then
parArrivalSubData(i).sUnitPrice = 0
Else
parArrivalSubData(i).sUnitPrice = CLng(pDataReader("入庫商品単価"))
End If
'入庫数量
If IsDBNull(pDataReader("入庫数量")) = True Then
parArrivalSubData(i).sCount = 0
Else
parArrivalSubData(i).sCount = CInt(pDataReader("入庫数量"))
End If
'入庫税抜金額
If IsDBNull(pDataReader("入庫税抜金額")) = True Then
parArrivalSubData(i).sNoTaxPrice = 0
Else
parArrivalSubData(i).sNoTaxPrice = CLng(pDataReader("入庫税抜金額"))
End If
'入庫消費税額
If IsDBNull(pDataReader("入庫消費税額")) = True Then
parArrivalSubData(i).sTaxPrice = 0
Else
parArrivalSubData(i).sTaxPrice = CLng(pDataReader("入庫消費税額"))
End If
'入庫税込金額
If IsDBNull(pDataReader("入庫税込金額")) = True Then
parArrivalSubData(i).sPrice = 0
Else
parArrivalSubData(i).sPrice = CLng(pDataReader("入庫税込金額"))
End If
'納入残数
If IsDBNull(pDataReader("納入残数")) = True Then
parArrivalSubData(i).sArrivalStiffness = 0
Else
parArrivalSubData(i).sArrivalStiffness = CLng(pDataReader("納入残数"))
End If
'登録日
parArrivalSubData(i).sCreateDate = pDataReader("登録日").ToString
'登録時間
parArrivalSubData(i).ScreateTime = pDataReader("登録時間").ToString
'最終更新日
parArrivalSubData(i).sUpdateDate = pDataReader("最終更新日").ToString
'最終更新時間
parArrivalSubData(i).sUpdateTime = pDataReader("最終更新時間").ToString
getLastArrivalSubData = CInt(pDataReader("納入残数"))
Else
getLastArrivalSubData = -1
End If
Catch oExcept As Exception
'例外が発生した時の処理
pMessageBox = New cMessageLib.fMessage(1, "システムエラー(cArrivalDataSubDBIO.getLastArrivalSubData)", Nothing, Nothing, oExcept.ToString)
pMessageBox.ShowDialog()
pMessageBox.Dispose()
pMessageBox = Nothing
Environment.Exit(1)
Finally
If IsNothing(pDataReader) = False Then
pDataReader.Close()
End If
End Try
End Function
'----------------------------------------------------------------------
' 機能:注文情報明細テーブルに1レコードを登録するメソッド
' 引数:in cSubArrivalオブジェクト
' 戻値:True --> 登録成功. False --> 登録失敗
'----------------------------------------------------------------------
Public Function insertArrivalSubData(ByVal parArrivalSubData As cStructureLib.sArrivalSubData, ByRef Tran As System.Data.OleDb.OleDbTransaction) As Boolean
Dim strInsertArrival As String
Try
'SQL文の設定
strInsertArrival = "INSERT INTO 入庫情報明細データ (" &
"発注コード, " &
"発注明細コード, " &
"入庫番号, " &
"JANコード, " &
"商品コード, " &
"商品名称, " &
"オプション1, " &
"オプション2, " &
"オプション3, " &
"オプション4, " &
"オプション5, " &
"定価, " &
"仕入単価, " &
"入庫商品単価, " &
"入庫数量, " &
"入庫税抜金額, " &
"入庫消費税額, " &
"入庫軽減税額, " &
"入庫税込金額, " &
"納入残数, " &
"登録日, " &
"登録時間, " &
"最終更新日, " &
"最終更新時間 " &
") VALUES (" &
"@OrderCode, " &
"@OrderDetailNo, " &
"@ArrivalNo, " &
"@JANCode, " &
"@ProductCode, " &
"@ProductName, " &
"@Option1, " &
"@Option2, " &
"@Option3, " &
"@Option4, " &
"@Option5, " &
"@ListPrice, " &
"@CostPrice, " &
"@UnitPrice, " &
"@Count, " &
"@NoTaxPrice, " &
"@TaxPrice, " &
"@ReducedTaxRate, " &
"@Price, " &
"@ArrivalStiffness, " &
"@CreateDate, " &
"@createTime, " &
"@UpdateDate, " &
"@UpdateTime " &
")"
pCommand = pConn.CreateCommand
pCommand.Transaction = Tran
pCommand.CommandText = strInsertArrival
'***********************
' パラメータの設定
'***********************
'発注コード
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@OrderCode", OleDb.OleDbType.Char, 13))
pCommand.Parameters("@OrderCode").Value = parArrivalSubData.sOrderCode
'発注明細コード
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@OrderDetailNo", OleDb.OleDbType.Numeric, 2))
pCommand.Parameters("@OrderDetailNo").Value = parArrivalSubData.sOrderDetailNo
'入庫番号
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@ArrivalNo", OleDb.OleDbType.Numeric, 2))
pCommand.Parameters("@ArrivalNo").Value = parArrivalSubData.sArrivalNo
'JANコード
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@JANCode", OleDb.OleDbType.Char, 13))
pCommand.Parameters("@JANCode").Value = parArrivalSubData.sJANCode
'商品コード
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@ProductCode", OleDb.OleDbType.Char, 8))
pCommand.Parameters("@ProductCode").Value = parArrivalSubData.sProductCode
'商品名称
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@ProductName", OleDb.OleDbType.Char, 100))
pCommand.Parameters("@ProductName").Value = parArrivalSubData.sProductName
'オプション1
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@Option1", OleDb.OleDbType.Char, 20))
pCommand.Parameters("@Option1").Value = parArrivalSubData.sOption1
'オプション2
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@Option2", OleDb.OleDbType.Char, 20))
pCommand.Parameters("@Option2").Value = parArrivalSubData.sOption2
'オプション3
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@Option3", OleDb.OleDbType.Char, 20))
pCommand.Parameters("@Option3").Value = parArrivalSubData.sOption3
'オプション4
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@Option4", OleDb.OleDbType.Char, 20))
pCommand.Parameters("@Option4").Value = parArrivalSubData.sOption4
'オプション5
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@Option5", OleDb.OleDbType.Char, 20))
pCommand.Parameters("@Option5").Value = parArrivalSubData.sOption5
'定価
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@ListPrice", OleDb.OleDbType.Numeric, 6))
pCommand.Parameters("@ListPrice").Value = parArrivalSubData.sListPrice
'仕入単価
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@CostPrice", OleDb.OleDbType.Numeric, 6))
pCommand.Parameters("@CostPrice").Value = parArrivalSubData.sCostPrice
'入庫商品単価
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@UnitPrice", OleDb.OleDbType.Numeric, 6))
pCommand.Parameters("@UnitPrice").Value = parArrivalSubData.sUnitPrice
'入庫数量
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@Count", OleDb.OleDbType.Numeric, 3))
pCommand.Parameters("@Count").Value = parArrivalSubData.sCount
'入庫税抜金額
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@NoTaxPrice", OleDb.OleDbType.Numeric, 6))
pCommand.Parameters("@NoTaxPrice").Value = parArrivalSubData.sNoTaxPrice
'入庫消費税額
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@TaxPrice", OleDb.OleDbType.Numeric, 6))
pCommand.Parameters("@TaxPrice").Value = parArrivalSubData.sTaxPrice
'2019,11,15 A.Komita 追加 From
'入庫軽減税額
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@ReducedTaxRate", OleDb.OleDbType.Numeric, 6))
pCommand.Parameters("@ReducedTaxRate").Value = parArrivalSubData.sReducedTaxRate
'2019,11,15 A.Komita 追加 To
'入庫税込金額
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@Price", OleDb.OleDbType.Numeric, 6))
pCommand.Parameters("@Price").Value = parArrivalSubData.sPrice
'納入残数
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@ArrivalStiffness", OleDb.OleDbType.Numeric, 6))
pCommand.Parameters("@ArrivalStiffness").Value = parArrivalSubData.sArrivalStiffness
'登録日
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@CreateDate", OleDb.OleDbType.Char, 10))
pCommand.Parameters("@CreateDate").Value = String.Format("{0:yyyy/MM/dd}", Now)
'登録時間
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@CreateTime", OleDb.OleDbType.Char, 8))
pCommand.Parameters("@CreateTime").Value = String.Format("{0:HH:mm:ss}", Now)
'最終更新日
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@UpdateDate", OleDb.OleDbType.Char, 10))
pCommand.Parameters("@UpdateDate").Value = String.Format("{0:yyyy/MM/dd}", Now)
'最終更新時間
pCommand.Parameters.Add _
(New OleDb.OleDbParameter("@UpdateTime", OleDb.OleDbType.Char, 8))
pCommand.Parameters("@UpdateTime").Value = String.Format("{0:HH:mm:ss}", Now)
'注文情報明細データ挿入処理実行
pCommand.ExecuteNonQuery()
insertArrivalSubData = True
Catch oExcept As Exception
'例外が発生した時の処理
pMessageBox = New cMessageLib.fMessage(1, "システムエラー(cArrivalDataSubDBIO.insertArrivalSubData)", Nothing, Nothing, oExcept.ToString)
pMessageBox.ShowDialog()
pMessageBox.Dispose()
pMessageBox = Nothing
Environment.Exit(1)
Finally
If IsNothing(pDataReader) = False Then
pDataReader.Close()
End If
End Try
End Function
'----------------------------------------------------
'2015/07/07
'及川和彦
'商品コードで絞込
'FROM
'----------------------------------------------------
Public Function getArrivalSubProduct(ByVal KeyProductCode As String, ByRef Tran As System.Data.OleDb.OleDbTransaction) As Long
Dim strSelect As String
Try
strSelect = ""
strSelect = "SELECT COUNT(*) AS CNT FROM 入庫情報明細データ WHERE 商品コード = """ & KeyProductCode & """"
'コマンドオブジェクトの生成
pCommand = pConn.CreateCommand()
pCommand.Transaction = Tran
'SQL文の設定
pCommand.CommandText = strSelect
pDataReader = pCommand.ExecuteReader()
pDataReader.Read()
getArrivalSubProduct = CLng(pDataReader("CNT"))
Catch oExcept As Exception
'例外が発生した時の処理
pMessageBox = New cMessageLib.fMessage(1, "システムエラー(cArrivalDataSubDBIO.getArrivalSubData)", Nothing, Nothing, oExcept.ToString)
pMessageBox.ShowDialog()
pMessageBox.Dispose()
pMessageBox = Nothing
Environment.Exit(1)
Finally
If IsNothing(pDataReader) = False Then
pDataReader.Close()
End If
End Try
End Function
'----------------------------------------------------
'HERE
'----------------------------------------------------
End Class
|
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Data
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Imaging
Imports System.Windows.Navigation
Imports devDept.Eyeshot
Imports devDept.Eyeshot.Entities
Imports devDept.Eyeshot.Labels
Imports devDept.Graphics
Imports devDept.Geometry
''' <summary>
''' Interaction logic for MainWindow.xaml
''' </summary>
Partial Public Class MainWindow
Public Sub New()
InitializeComponent()
'model1.Unlock("") ' For more details see 'Product Activation' topic in the documentation.
End Sub
Protected Overrides Sub OnContentRendered(e As EventArgs)
model1.GetGrid().AutoSize = True
model1.GetGrid().[Step] = 5
' for correct volume calculation, during modeling it is useful to have this = true
model1.ShowNormals = False
Dim tol As Double = 0.25
Dim holeDia As Double = 10
Dim thickness As Double = 5
Dim hole As ICurve = New Circle(40, 20, 0, holeDia)
hole.Reverse()
' Bottom face
' to see the model at this point UNComment
' the two lines just after this code block
Dim baseProfile As New CompositeCurve(New Line(0, 0, 40, 0), New Arc(New Point3D(40, 20, 0), 20, 6 * Math.PI / 4, 2 * Math.PI), New Line(60, 20, 60, 40), New Line(60, 40, 0, 40), New Line(0, 40, 0, 0))
Dim faceRegion As Region = new Region(baseProfile, hole)
Dim part1 As Mesh = faceRegion.ConvertToMesh(tol)
part1.FlipNormal()
'model1.Entities.Add(part1);
'return;
' Extrudes of some profile entities
' to see the model at this point UNComment
' the two lines just after this code block
Dim face As Mesh
For i As Integer = 1 To 2
face = baseProfile.CurveList(i).ExtrudeAsMesh(0, 0, thickness, tol, Mesh.natureType.Smooth)
part1.MergeWith(face)
Next
face = hole.ExtrudeAsMesh(New Vector3D(0, 0, thickness), tol, Mesh.natureType.Smooth)
part1.MergeWith(face)
'model1.Entities.Add(part1);
'return;
' Top face
' to see the model at this point UNComment
' the two lines just after this code block
baseProfile = New CompositeCurve(New Line(thickness, 0, 40, 0), New Arc(New Point3D(40, 20, 0), 20, 6 * Math.PI / 4, 2 * Math.PI), New Line(60, 20, 60, 40), New Line(60, 40, thickness, 40), New Line(thickness, 40, thickness, 0))
faceRegion = new Region(baseProfile, hole)
face = faceRegion.ConvertToMesh(tol)
' Translates it to Z = 10
face.Translate(0, 0, thickness)
part1.MergeWith(face)
'model1.Entities.Add(part1);
'return;
' Top vertical profile
' to see the model at this point UNComment
' the two lines just after this code block
Dim pl As New LinearPath(4)
pl.Vertices(0) = New Point3D(thickness, 0, thickness)
pl.Vertices(1) = New Point3D(thickness, 0, 30)
pl.Vertices(2) = New Point3D(0, 0, 30)
pl.Vertices(3) = New Point3D(0, 0, 0)
face = pl.ExtrudeAsMesh(0, 40, 0, tol, Mesh.natureType.Smooth)
face.FlipNormal()
part1.MergeWith(face)
'model1.Entities.Add(part1);
'return;
' Front 'L' shaped face
' to see the model at this point UNComment
' the two lines just after this code block
Dim frontProfile As Point3D() = New Point3D(6) {}
frontProfile(0) = Point3D.Origin
frontProfile(1) = New Point3D(40, 0, 0)
frontProfile(2) = New Point3D(40, 0, thickness)
frontProfile(3) = New Point3D(thickness, 0, thickness)
frontProfile(4) = New Point3D(thickness, 0, 30)
frontProfile(5) = New Point3D(0, 0, 30)
frontProfile(6) = Point3D.Origin
' This profile is in the wrong direction, we use true as last parameter
face = Mesh.CreatePlanar(frontProfile, Mesh.natureType.Smooth)
' makes a deep copy of this face
Dim rearFace As Mesh = DirectCast(face.Clone(), Mesh)
part1.MergeWith(face)
' model1.Entities.Add(part1);
' return;
' Rear 'L' shaped face
' to see the model at this point UNComment
' the two lines just after this code block
' Translates it to Y = 40
rearFace.Translate(0, 40, 0)
' Stretches it
For i As Integer = 0 To rearFace.Vertices.Length - 1
If rearFace.Vertices(i).X > 10 Then
rearFace.Vertices(i).X = 60
End If
Next
rearFace.FlipNormal()
part1.MergeWith(rearFace)
'model1.Entities.Add(part1);
'return;
' Set the normal averaging and edge style mode
part1.NormalAveragingMode = Mesh.normalAveragingType.AveragedByAngle
part1.EdgeStyle = Mesh.edgeStyleType.Sharp
model1.Layers.Add("Brakets", System.Drawing.Color.Crimson)
' Adds the mesh to the model1
model1.Entities.Add(part1, "Brakets")
Dim mp As New VolumeProperties(part1.Vertices, part1.Triangles)
' Adds the volume label
model1.Labels.Add(New LeaderAndText(60, 40, thickness, "Volume = " + mp.Volume.ToString("f3") & " cubic " & model1.Units, New System.Drawing.Font("Tahoma", 8.25F), System.Drawing.Color.Black, New Vector2D(0, 50)))
' fits the model in the model1
model1.ZoomFit()
' refresh the viewport
model1.Invalidate()
MyBase.OnContentRendered(e)
End Sub
End Class
|
Namespace Analysis
Public Partial Class Result
#Region " Public Constants "
Public Const NAME_DELINEATOR As String = "//"
#End Region
#Region " Public Properties "
Public ReadOnly Property Names As String()
Get
If String.IsNullOrEmpty(Name) Then
Return New String() {}
Else
Return Name.Split(New String() {NAME_DELINEATOR}, System.StringSplitOptions.RemoveEmptyEntries)
End If
End Get
End Property
Public ReadOnly Property Display_Name As System.String
Get
Return Name.Replace(NAME_DELINEATOR, " ")
End Get
End Property
Public ReadOnly Property Average_Edge_Count As System.Double
Get
If Edges Is Nothing OrElse Edges.Count = 0 Then
Return 0
Else
Dim ret_Val As Double
For i As Integer = 0 To Edges.Count - 1
ret_Val += Edges(i).Count
Next
Return ret_Val / Edges.Count
End If
End Get
End Property
#End Region
End Class
End Namespace |
Imports System.Data
Imports System.Data.SqlClient
Public Class frmInventarioXLocal
Private Sub frmInventarioXLocal_Load(sender As Object, e As EventArgs) Handles MyBase.Load
llenarComboLocales()
End Sub
Sub llenarComboLocales()
'Permite conexion a base de datos'
Dim sqlad As SqlDataAdapter
'Resultado de lo que se trae de la tabla'
Dim dt As DataTable
'Crea instancia de la variable'
sqlCon = New SqlConnection(conn)
Using (sqlCon)
Dim sqlComm As New SqlCommand()
'se hace la referencia a la conexión con la bd'
sqlComm.Connection = sqlCon
'se indica el nombre del stored procedure y el tipo'
sqlComm.CommandText = "sp_SeleccionarLocales" '
'Tipo de comando'
sqlComm.CommandType = CommandType.StoredProcedure
sqlad = New SqlDataAdapter(sqlComm)
dt = New DataTable("Datos")
'Llena el data table con la informacion que captura el sql adapter con el sp'
sqlad.Fill(dt)
Me.LocalCbx.DataSource = dt
'DisplayMember: Lo que se va a mostrar al usuario'
Me.LocalCbx.DisplayMember = "Nombre"
'ValueMember: Codigo que va enrrolado'
Me.LocalCbx.ValueMember = "LocalID"
Me.LocalCbx.SelectedIndex = -1
End Using
End Sub
Private Sub Local_btn_Click(sender As Object, e As EventArgs) Handles Local_btn.Click
If (LocalCbx.Text <> "") Then
'Crea instancia de la variable'
sqlCon = New SqlConnection(conn)
sqlCon.Open()
Dim cmd As New SqlCommand("sp_SeleccionarInventarioXLocal", sqlCon)
'Tipo de comando'
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@LocalID", LocalCbx.SelectedValue)
'Resultado de lo que se trae de la tabla'
Dim dt As DataTable = New DataTable()
'Llena el data table con la informacion que captura el sql adapter con el sp'
dt.Load(cmd.ExecuteReader())
Me.ProductosXLocal_dt.DataSource = dt
sqlCon.Close()
End If
End Sub
End Class |
'
' Copyright (c) Clevergy
'
' The SOFTWARE, as well as the related copyrights and intellectual property rights, are the exclusive property of Clevergy srl.
' Licensee acquires no title, right or interest in the SOFTWARE other than the license rights granted herein.
'
' conceived and developed by Marco Fagnano (D.R.T.C.)
' il software è ricorsivo, nel tempo rigenera se stesso.
'
Imports System
Imports System.Collections.Generic
Imports SF.DAL
Imports System.IO
Namespace SF.BLL
Public Class EO_Str_AlarmCodes
#Region "constructor"
Public Sub New()
Me.New(0, 0)
End Sub
Public Sub New(m_AlarmCode As Integer, m_MessageId As Integer)
AlarmCode = m_AlarmCode
MessageId = m_MessageId
End Sub
#End Region
#Region "methods"
Public Shared Function Add(AlarmCode As Integer, MessageId As Integer) As Boolean
If AlarmCode <= 0 Then Return False
If MessageId <= 0 Then Return False
Return DataAccessHelper.GetDataAccess.EO_Str_AlarmCodes_Add(AlarmCode, MessageId)
End Function
Public Shared Function Del(AlarmCode As Integer, MessageId As Integer) As Boolean
If AlarmCode <= 0 Then Return False
If MessageId <= 0 Then Return False
Return DataAccessHelper.GetDataAccess.EO_Str_AlarmCodes_Del(AlarmCode, MessageId)
End Function
Public Shared Function Read(AlarmCode As Integer, MessageId As Integer) As EO_Str_AlarmCodes
If AlarmCode <= 0 Then Return Nothing
If MessageId <= 0 Then Return Nothing
Return DataAccessHelper.GetDataAccess.EO_Str_AlarmCodes_Read(AlarmCode, MessageId)
End Function
Public Shared Function ReadByAlarmCode(AlarmCode As Integer) As EO_Str_AlarmCodes
If AlarmCode <= 0 Then Return Nothing
Return DataAccessHelper.GetDataAccess.EO_Str_AlarmCodes_ReadByAlarmCode(AlarmCode)
End Function
#End Region
#Region "public properties"
Public Property AlarmCode As Integer
Public Property MessageId As Integer
#End Region
End Class
End Namespace
|
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports Ctx = Basics._01_04_Operatoren
<TestClass()> Public Class _01_04_Operatoren
Public Sub _01_04_Operatoren_LogikopsTest()
Assert.IsTrue(Ctx.Logische_Operatoren_in_Aussagen())
End Sub
<TestMethod> _
Public Sub Kombinierte_Operatoren()
Dim zaehler As Integer
' Ausführliche (klassische) Form des hochzählens
zaehler = zaehler + 1
Debug.Assert(zaehler = 1)
' Vereinfachte (moderne Form) des Hochzählens
zaehler += 1
Debug.Assert(zaehler = 2)
' Kombinierte Operatoren kann man auch mit -, *, / bilden
zaehler -= 2 ' <=> zaehler = zaehler - 2
Debug.Assert(zaehler = 0)
zaehler = 100
zaehler *= 2 ' <=> zaehler = zaehler * 2
Debug.Assert(zaehler = 200)
zaehler /= 2 ' <=> zaehler = zaehler / 2
Debug.Assert(zaehler = 100)
End Sub
<TestMethod> _
Public Sub _01_04_Operatoren_FestkommaoperatorenTest()
' Einfache Festkommaoperationen
Dim A, B, C As Integer
A = 100
B = 99
C = A + B
C = A - B
C = B * 100 + 33
C = (B * 100 + 33) / 100
C = (B * 100 + 33) \ 100
C = 13 Mod 3
Assert.IsTrue(Ctx.Gepruefte_Festkommaoperatoren())
Assert.IsTrue(Ctx.Ungepruefte_Festkommaoperatoren())
' Bsp.: Preise durch Festkommawerte darstellen, indem 2 stellen Fest für die
' Cents definiert sind
Dim preis1 As Integer = 9950
' Entspricht 99,50 €
Dim preis2 As Integer = 38560
' Entspricht 385,60 €
Dim Gesamtpreis As Integer = preis1 + preis2
' Für die Ausgabe sollten die Vor und Nachkommastellen Isoliert werden, um sie
' getrennt auszugeben
' a / b ergibt als Ergebnis einen Double- Wert
' a \ b ergibt als Ergebnis einen Integer- Wert
Dim GesamtpreisEuro As Integer = Gesamtpreis \ 100
Dim GesamtpreisCent As Integer = Gesamtpreis - GesamtpreisEuro * 100
Assert.AreEqual(485, GesamtpreisEuro)
Assert.AreEqual(10, GesamtpreisCent)
' Vereinfachen der Festkommarechnung für Preise mittels Hilfsfunktionen
Dim preis3 As Integer = Ctx.Preis(99, 50)
Dim preis4 As Integer = Ctx.Preis(385, 60)
Dim Gesamtpreis2 As Integer = preis3 + preis4
Assert.AreEqual(485, Ctx.PreisEuroAnteil(Gesamtpreis2))
Assert.AreEqual(10, Ctx.PreisCentAnteil(Gesamtpreis2))
End Sub
<TestMethod> _
Public Sub _01_04_Operatoren_GleitkommaoperatorenTest()
Dim dPReis1 As Double = 99.5
Dim dPreis2 As Double = 385.6
Dim dGesamt As Double = dPReis1 + dPreis2
Assert.AreEqual("485,10", dGesamt.ToString("N2"))
' Jedoch können in Gleitkommarechnungen Rundungsfehler erbarmungslos zuschlagen
'float EntfernungRaketeVonErde = (float)19999998.0; // f;
Dim EntfernungRaketeVonErde As Single = 19999998.0F
For i As Integer = 1 To 10
EntfernungRaketeVonErde += 1.0F
Next
Assert.AreEqual(Math.Round(20000000.0, 7), Math.Round(EntfernungRaketeVonErde, 7))
' Rechnen mit großen Messwerten (Sternenmassen)
Dim MasseSonneKg As Double = 1.989E+30
Dim MasseBeteigeuzeKg As Double = 1.531E+31
Dim MasseRiegelKg As Double = 3.88E+31
Dim MasseCanisMajorisKg As Double = 5.967E+31
Dim Verhältnis As Double = MasseCanisMajorisKg / MasseSonneKg
End Sub
<TestMethod> _
Public Sub Zeichenkettenoperatoren()
Dim txt, frag1, frag2 As String
' Zeichkettenverkettung mit +
frag1 = "Hallo"
frag2 = "Welt"
txt = frag1 + " " + frag2
' Probleme, wenn nummerische Werte an Zeichenkette angehangen werden sollen
Try
txt = 99 + " Euro"
Catch ex As Exception
Debug.WriteLine("Ausnahme beim Verketten mit +" + ex.ToString())
End Try
Try
txt = "SFr " + 99
Catch ex As Exception
Debug.WriteLine("Ausnahme beim Verketten mit +" + ex.ToString())
End Try
' Lösung: & anstatt +: Alles, was rechts von & steht, wird automat. mittels ToString() in eine Zeichenkette gewandelt
txt = 99 & " Euro"
txt = "SFr " & 99
End Sub
<TestMethod> _
Public Sub _01_04_Operatoren_BitopsTest()
Dim dz As String = Ctx.In_Dualzahl_konvertieren_mit_Bitops(8)
Assert.AreEqual(dz, "OOOOOOOOOOOOOOOOOOOOOOOOOOOOLOOO")
dz = Ctx.In_Dualzahl_konvertieren_mit_Bitops(&HFFFFFFFFUI)
Assert.AreEqual(dz, "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL")
dz = Ctx.In_Dualzahl_konvertieren_mit_Bitops(12345)
Trace.WriteLine(Convert.ToString("12345 in Dual = ") & dz)
End Sub
End Class |
Imports System.IO
Imports System.Xml.Linq
Public Class frmRevisiones
Public ID_Paciente As Integer
Private context As CMLinqDataContext
Public Revision As COMPARATIVA
Private Sub frmRevisiones_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
CtrlImageWithStickers1.tsOpciones.Visible = False
CargaDatos()
AplicaPermisos()
'ActualizarFechaNac()
End Sub
#Region "Private Sub AplicaPermisos()"
Private Sub AplicaPermisos()
tstRevisiones.Enabled = (Globales.Usuario.Permisos(RoleManager.Items.Pacientes_Revisiones_Comparativas) > RoleManager.TipoPermisos.Lectura)
'tstRevisiones.ReadOnly = (Globales.Usuario.Permisos(RoleManager.Items.Pacientes_Revisiones_Comparativas) > 2)
tstRevisiones.Enabled = (Globales.Usuario.Permisos(RoleManager.Items.Pacientes_Revisiones_Comparativas) > 3)
tst_RevisionComparada_ADD.Enabled = (Globales.Usuario.Permisos(RoleManager.Items.Pacientes_Revisiones_Comparativas) > 2)
tst_RevisionComparada_Editar.Enabled = (Globales.Usuario.Permisos(RoleManager.Items.Pacientes_Revisiones_Comparativas) > 2)
tst_RevisionComparada_Eliminar.Enabled = (Globales.Usuario.Permisos(RoleManager.Items.Pacientes_Revisiones_Comparativas) > 3)
dtp_revDetFecha.Enabled = (Globales.Usuario.Permisos(RoleManager.Items.Pacientes_Revisiones_Comparativas) > 2)
tb_revDetDescripcion.Enabled = (Globales.Usuario.Permisos(RoleManager.Items.Pacientes_Revisiones_Comparativas) > 2)
'bt_revDetDescripcion.Enabled = (Globales.Usuario.Permisos(RoleManager.Items.Pacientes_Revisiones_Comparativas) > 2)
tb_revNotas.Enabled = (Globales.Usuario.Permisos(RoleManager.Items.Pacientes_Revisiones_Comparativas) > 2)
'dtg_revSeguimientos.Enabled = (Globales.Usuario.Permisos(RoleManager.Items.Pacientes_Revisiones_Comparativas) > 2)
'dtg_revResultados.Enabled = (Globales.Usuario.Permisos(RoleManager.Items.Pacientes_Revisiones_Comparativas) > 2)
End Sub
#End Region
Public Sub CargaDatos()
Grid_Comparativas.DataSource = Nothing
grid_Revisiones.DataSource = Nothing
'Grid_Tratamientos.DataSource = Nothing
GridEX_Resultados.DataSource = Nothing
context = New CMLinqDataContext()
COMPARATIVABindingSource.DataSource = (From c As COMPARATIVA In context.COMPARATIVAs Where c.REFPACIENTE = ID_Paciente Select c).ToList()
Grid_Comparativas.DataSource = COMPARATIVABindingSource
End Sub
#Region "Private Sub CargaDetalles()"
Private Sub CargaDetalles()
If Grid_Comparativas.CurrentRow Is Nothing Then
Return
End If
Revision = Grid_Comparativas.CurrentRow.DataRow
grid_Revisiones.DataSource = LCOMPARATIVAsBindingSource
'Grid_Tratamientos.DataSource = LCOMPARATIVASTRATAMIENTOsBindingSource
GridEX_Resultados.DataSource = DATOSCOMPARATIVAsBindingSource
CtrlImageWithStickers1.Clear()
'Cargar todos los tratamientos de todas las revisiones de esta comparativa
Dim tratamientos As List(Of LCOMPARATIVAS_TRATAMIENTO) = (From t As LCOMPARATIVAS_TRATAMIENTO In context.LCOMPARATIVAS_TRATAMIENTOs _
Where t.LCOMPARATIVA.REFCOMPARATIVA = Revision.CODIGO _
Select t).ToList()
For Each t As LCOMPARATIVAS_TRATAMIENTO In tratamientos
If Not t.Layout Is Nothing Then
CtrlImageWithStickers1.AddPointer(t)
End If
Next
If Not grid_Revisiones.CurrentRow Is Nothing Then
Dim lcomparativa As LCOMPARATIVA = grid_Revisiones.CurrentRow.DataRow
CtrlImageWithStickers1.ResaltaStickersWithParentID(lcomparativa.ID)
End If
'If Not Revision.IMAGEN Is Nothing Then
' Dim ms As New MemoryStream(Revision.IMAGEN.ToArray())
' CtrlImageWithStickers1.BackIMAGE = Image.FromStream(ms)
'Else
' CtrlImageWithStickers1.BackIMAGE = Nothing
'End If
End Sub
#End Region
Private Sub Grid_Comparativas_SelectionChanged(sender As System.Object, e As System.EventArgs) Handles Grid_Comparativas.SelectionChanged
tst_RevisionComparada_Editar.Enabled = Grid_Comparativas.SelectedItems.Count > 0
tst_RevisionComparada_Eliminar.Enabled = Grid_Comparativas.SelectedItems.Count > 0
tstDuplicarRevision.Enabled = Grid_Comparativas.SelectedItems.Count > 0
tstConsultarGrafica.Enabled = Grid_Comparativas.SelectedItems.Count > 0
CargaDetalles()
End Sub
Private Sub grid_Revisiones_SelectionChanged(sender As System.Object, e As System.EventArgs) Handles grid_Revisiones.SelectionChanged
If Not grid_Revisiones.CurrentRow Is Nothing Then
Dim lcomparativa As LCOMPARATIVA = grid_Revisiones.CurrentRow.DataRow
If (Not lcomparativa.MODELOSCOMPARATIVA.IMAGEN Is Nothing) Then
Dim ms As New MemoryStream(lcomparativa.MODELOSCOMPARATIVA.IMAGEN.ToArray())
CtrlImageWithStickers1.BackIMAGE = Image.FromStream(ms)
Else
CtrlImageWithStickers1.BackIMAGE = Nothing
End If
CtrlImageWithStickers1.ResaltaStickersWithParentID(lcomparativa.ID)
End If
End Sub
#Region "Private Sub GridEX1_FormattingRow(sender As System.Object, e As Janus.Windows.GridEX.RowLoadEventArgs) Handles GridEX_Resultados.FormattingRow"
Private Sub GridEX1_FormattingRow(sender As System.Object, e As Janus.Windows.GridEX.RowLoadEventArgs) Handles GridEX_Resultados.FormattingRow
Dim dato As DATOSCOMPARATIVA = e.Row.DataRow
Dim valor As Object = Globales.ValorModelo(dato)
If IsNumeric(valor) Then
e.Row.Cells("ColumnValue").Text = CType(valor, Double).ToString("N3")
Else
e.Row.Cells("ColumnValue").Text = valor
End If
End Sub
#End Region
Private Sub tst_RevisionComparada_ADD_Click(sender As System.Object, e As System.EventArgs) Handles tst_RevisionComparada_ADD.Click
Dim frm As New frmRevComparativa_Editar()
frm.ID_Paciente = ID_Paciente
frm.CODIGO = "-1"
If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then
Globales.AuditoriaInfo.Registra(Globales.AuditoriaInfo.Accion.Insertar,
RoleManager.Items.Pacientes_Revisiones_Comparativas, "Revision Comparativa",
frm.Revision.CODIGO,
String.Format("Paciente: [{0}] {1} Fecha: {2} ",
frm.Revision.PACIENTE.CPACIENTE,
frm.Revision.PACIENTE.NombreCompleto,
frm.Revision.FECHA))
CargaDatos()
Else
'Aqui hay que borrar la comparativa
BorrarComparativa(frm.CODIGO)
End If
End Sub
Private Sub BorrarComparativa(ByVal codigo As String)
Try
Dim context As New CMLinqDataContext
Dim comp As COMPARATIVA = (From c As COMPARATIVA In context.COMPARATIVAs Where c.CODIGO = codigo Select c).SingleOrDefault()
If Not comp Is Nothing Then
For Each linea As LCOMPARATIVA In comp.LCOMPARATIVAs
'Borrar los datos por lineas
context.DATOSCOMPARATIVAs.DeleteAllOnSubmit(linea.DATOSCOMPARATIVAs)
context.SubmitChanges()
context.LCOMPARATIVAS_TRATAMIENTOs.DeleteAllOnSubmit(linea.LCOMPARATIVAS_TRATAMIENTOs)
context.SubmitChanges()
Next
'Borrar los seguimientos
context.LCOMPARATIVAs.DeleteAllOnSubmit(comp.LCOMPARATIVAs)
context.SubmitChanges()
context.COMPARATIVAs.DeleteOnSubmit(comp)
context.SubmitChanges()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub tstDuplicarRevision_Click(sender As System.Object, e As System.EventArgs) Handles tstDuplicarRevision.Click
Dim comparativaOriginal As COMPARATIVA = COMPARATIVABindingSource.Current
If comparativaOriginal Is Nothing Then
Return
End If
'Duplicar la comparativa
Dim nuevaComparativa As COMPARATIVA = New COMPARATIVA()
If comparativaOriginal.REFPACIENTE.HasValue Then
nuevaComparativa.REFPACIENTE = comparativaOriginal.REFPACIENTE
End If
If Not comparativaOriginal.DESCRIPCION Is Nothing Then
nuevaComparativa.DESCRIPCION = comparativaOriginal.DESCRIPCION
End If
If comparativaOriginal.FECHA.HasValue Then
nuevaComparativa.FECHA = comparativaOriginal.FECHA
End If
If Not comparativaOriginal.NOTAS Is Nothing Then
nuevaComparativa.NOTAS = nuevaComparativa.NOTAS
End If
If Not comparativaOriginal.REFMODELOCOMPARATIVA Is Nothing Then
nuevaComparativa.REFMODELOCOMPARATIVA = comparativaOriginal.REFMODELOCOMPARATIVA
End If
nuevaComparativa.IMAGEN = comparativaOriginal.IMAGEN
nuevaComparativa.FECHATERMINADA = comparativaOriginal.FECHATERMINADA
context.COMPARATIVAs.InsertOnSubmit(nuevaComparativa)
context.SubmitChanges()
Globales.AuditoriaInfo.Registra(Globales.AuditoriaInfo.Accion.Insertar,
RoleManager.Items.Pacientes_Revisiones_Comparativas, "Revision Comparativa Duplicada",
nuevaComparativa.CODIGO,
String.Format("Duplicada rev [{3}]->[{4}]: [{0}] Paciente: [{1}] Fecha: {2} ",
nuevaComparativa.PACIENTE.CPACIENTE,
nuevaComparativa.PACIENTE.NombreCompleto,
nuevaComparativa.FECHA,
comparativaOriginal.CODIGO,
nuevaComparativa.CODIGO
))
'Ahora replicar las lineascomparativas
For Each lineaOriginal As LCOMPARATIVA In comparativaOriginal.LCOMPARATIVAs
Dim nuevaLinea As New LCOMPARATIVA()
nuevaLinea.REFCOMPARATIVA = nuevaComparativa.CODIGO
If lineaOriginal.FECHA.HasValue Then
nuevaLinea.FECHA = lineaOriginal.FECHA
End If
If lineaOriginal.HORA.HasValue Then
nuevaLinea.HORA = lineaOriginal.HORA
End If
If Not lineaOriginal.REFMODELOCOMPARATIVA Is Nothing Then
nuevaLinea.REFMODELOCOMPARATIVA = lineaOriginal.REFMODELOCOMPARATIVA
End If
If Not lineaOriginal.DESCRIPCION Is Nothing Then
nuevaLinea.DESCRIPCION = lineaOriginal.DESCRIPCION
End If
If Not lineaOriginal.NOTAS Is Nothing Then
nuevaLinea.NOTAS = lineaOriginal.NOTAS
End If
context.LCOMPARATIVAs.InsertOnSubmit(nuevaLinea)
context.SubmitChanges()
'Ahora los datos de la comparativa
For Each datoOriginal As DATOSCOMPARATIVA In lineaOriginal.DATOSCOMPARATIVAs
Dim datoNuevo As New DATOSCOMPARATIVA()
datoNuevo.REFLCOMPARATIVA = nuevaLinea.ID
If datoOriginal.DFLOAT.HasValue Then
datoNuevo.DFLOAT = datoOriginal.DFLOAT
End If
If Not datoOriginal.DBOOLEAN Is Nothing Then
datoNuevo.DBOOLEAN = datoOriginal.DBOOLEAN
End If
If Not datoOriginal.DVARCHAR Is Nothing Then
datoNuevo.DVARCHAR = datoOriginal.DVARCHAR
End If
If Not datoOriginal.DXML Is Nothing Then
datoNuevo.DXML = datoOriginal.DXML
End If
datoNuevo.REFMODELODATO = datoOriginal.REFMODELODATO
context.DATOSCOMPARATIVAs.InsertOnSubmit(datoNuevo)
context.SubmitChanges()
Next
'Clonar los tratamientos
For Each ori_trat As LCOMPARATIVAS_TRATAMIENTO In lineaOriginal.LCOMPARATIVAS_TRATAMIENTOs
Dim nuevoTrat As New LCOMPARATIVAS_TRATAMIENTO
nuevoTrat.Comentarios = ori_trat.Comentarios
nuevoTrat.Fecha = ori_trat.Fecha
nuevoTrat.ID_LCOMPARATIVA = nuevaLinea.ID
nuevoTrat.REFCONCEPTOFRA = ori_trat.REFCONCEPTOFRA
nuevoTrat.Tratamiento = ori_trat.Tratamiento
nuevoTrat.Unidad = ori_trat.Unidad
nuevoTrat.Valor_Unidad = ori_trat.Valor_Unidad
nuevoTrat.Layout = ori_trat.Layout
context.LCOMPARATIVAS_TRATAMIENTOs.InsertOnSubmit(nuevoTrat)
context.SubmitChanges()
Next
Next
CargaDatos()
End Sub
Private Sub tst_RevisionComparada_Editar_Click(sender As System.Object, e As System.EventArgs) Handles tst_RevisionComparada_Editar.Click
If Grid_Comparativas.SelectedItems.Count > 0 Then
If Not COMPARATIVABindingSource.Current Is Nothing Then
Dim _Cod As String = COMPARATIVABindingSource.Current.CODIGO
'Dim frm As frmRevisionComparativa_ADD2 = New frmRevisionComparativa_ADD2(Me.CMDataSet, fId)
'frm.Codigo = dtg_revComparativas.SelectedRows(0).Cells(CODIGODREVISIONdatagridColumn.Name).Value
Dim frm As New frmRevComparativa_Editar()
frm.ID_Paciente = ID_Paciente
frm.CODIGO = _Cod
'Globales.AuditoriaInfo.Registra(Globales.AuditoriaInfo.Accion.Abrir,
' RoleManager.Items.Pacientes_Revisiones_Comparativas, "Revision Comparativa",
' frm.Revision.CODIGO,
' String.Format("Paciente: [{0}] {1} Fecha: {2}",
' frm.Revision.PACIENTE.CPACIENTE,
' frm.Revision.PACIENTE.NombreCompleto,
' frm.Revision.FECHA))
If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then
CargaDatos()
End If
End If
End If
End Sub
Private Sub tst_RevisionComparada_Eliminar_Click(sender As System.Object, e As System.EventArgs) Handles tst_RevisionComparada_Eliminar.Click
If Grid_Comparativas.SelectedItems.Count > 0 Then
If Not COMPARATIVABindingSource.Current Is Nothing Then
If MessageBox.Show("¿Está seguro que desea eliminar la Revisión y sus datos asociados?", "Confirmación", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
Dim comparativa As COMPARATIVA = COMPARATIVABindingSource.Current
BorrarComparativa(comparativa.CODIGO)
Globales.AuditoriaInfo.Registra(Globales.AuditoriaInfo.Accion.Borrar,
RoleManager.Items.Pacientes_Revisiones_Comparativas, "Revision Comparativa",
comparativa.CODIGO,
String.Format("Paciente: [{0}] {1} Fecha: {2}",
comparativa.PACIENTE.CPACIENTE,
comparativa.PACIENTE.NombreCompleto,
comparativa.FECHA))
CargaDatos()
End If
End If
End If
End Sub
Private Sub tstConsultarGrafica_Click(sender As System.Object, e As System.EventArgs) Handles tstConsultarGrafica.Click
If Grid_Comparativas.SelectedItems.Count > 0 Then
If Not COMPARATIVABindingSource.Current Is Nothing Then
Dim comparativa As COMPARATIVA = COMPARATIVABindingSource.Current
Globales.AuditoriaInfo.Registra(Globales.AuditoriaInfo.Accion.Abrir,
RoleManager.Items.Pacientes_Revisiones_Comparativas, "Gráfico Revision Comparativa",
comparativa.CODIGO,
String.Format("Paciente: [{0}] {1} Fecha: {2} ",
comparativa.PACIENTE.CPACIENTE,
comparativa.PACIENTE.NombreCompleto,
comparativa.FECHA))
Dim _grafico As form_grafica_rev_comp = New form_grafica_rev_comp(comparativa.CODIGO, comparativa.PACIENTE.NombreCompleto)
_grafico.ShowInTaskbar = False
_grafico.ShowDialog()
End If
End If
End Sub
Private Sub Grid_Comparativas_RowDoubleClick(sender As System.Object, e As Janus.Windows.GridEX.RowActionEventArgs) Handles Grid_Comparativas.RowDoubleClick
tst_RevisionComparada_Editar_Click(Nothing, Nothing)
End Sub
End Class |
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.mzData.mzWebCache
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Ms1.Annotations
Imports BioNovoGene.BioDeep.Chemoinformatics.Formula
Imports Microsoft.VisualBasic.ComponentModel.Collection.Generic
Imports Microsoft.VisualBasic.Data.IO
Namespace PoolData
''' <summary>
''' metadata of the spectrum object
''' </summary>
Public Class Metadata : Implements INamedValue
Implements IReadOnlyId, ICompoundNameProvider, IExactMassProvider, IFormulaProvider
Public Property guid As String Implements INamedValue.Key
Public Property mz As Double
Public Property rt As Double
Public Property intensity As Double
Public Property source_file As String
''' <summary>
''' the spectrum data is store in mzpack <see cref="ScanMs2"/> format
''' </summary>
''' <returns></returns>
Public Property block As BufferRegion
''' <summary>
''' blood, urine, etc
''' </summary>
''' <returns></returns>
Public Property sample_source As String
''' <summary>
'''
''' </summary>
''' <returns></returns>
Public Property organism As String
Public Property instrument As String = "Thermo Scientific Q Exactive"
Public Property name As String Implements ICompoundNameProvider.CommonName
Public Property biodeep_id As String Implements IReadOnlyId.Identity
Public Property formula As String Implements IFormulaProvider.Formula
Public Property adducts As String
Public Property project As String
Private ReadOnly Property ExactMass As Double Implements IExactMassProvider.ExactMass
Get
Return FormulaScanner.EvaluateExactMass(formula)
End Get
End Property
Public Overrides Function ToString() As String
Return $"[{guid}] {name}"
End Function
End Class
End Namespace |
Imports System.Data.OleDb
Imports Powertrain_Task_Manager.Common
Imports Powertrain_Task_Manager.Models
Namespace Repositories
Public Class AreaStructureRepository
Dim DbSqlHelper As SqlHelper
Public Sub New(ByVal dbSqlHelper As SqlHelper)
Me.DbSqlHelper = dbSqlHelper
End Sub
Public Function GetAreaStructureDataTable(ByVal strAreaMemberName As String) As DataTable
Dim query As String = "SELECT * FROM Area_Structures WHERE MemberName = @MemberName"
Dim dt As DataTable = New DataTable
Dim params = New List(Of OleDbParameter)()
params.Add(New OleDbParameter("@AreaXrefName", strAreaMemberName))
Try
dt = DbSqlHelper.ExcuteDataTable(CommandType.Text, query, params)
Catch ex As Exception
Log_Anything("GetAreaStructureDataTable - " & GetExceptionInfo(ex))
End Try
Return dt
End Function
Public Function GetAreaStructureDataTable() As DataTable
Dim query As String = "SELECT * FROM Area_Structures"
Dim dt As DataTable = New DataTable
Try
dt = DbSqlHelper.ExcuteDataSet(query).Tables(0)
Catch ex As Exception
Log_Anything("GetAreaStructureDataTable - " & GetExceptionInfo(ex))
End Try
Return dt
End Function
Public Function GetListAreaStructure(ByVal dt As DataTable) As List(Of AreaStructure)
Dim listAreaStructure As List(Of AreaStructure) = New List(Of AreaStructure)
For i = 0 To dt.Rows.Count - 1
Dim areastructure As AreaStructure = New AreaStructure
Areastructure.Id = Integer.Parse(dt.Rows(i)("ID").ToString)
areastructure.Parent = dt.Rows(i)("Parent").ToString
Areastructure.MemberName = dt.Rows(i)("MemberName").ToString
Areastructure.MemberType = dt.Rows(i)("MemberType").ToString
Areastructure.MemberOrder = dt.Rows(i)("MemberOrder").ToString
Areastructure.MemberDescription1 = dt.Rows(i)("MemberDescription_1").ToString
Areastructure.MemberDescription2 = dt.Rows(i)("MemberDescription_2").ToString
Areastructure.MemberDescription3 = dt.Rows(i)("MemberDescription_3").ToString
Areastructure.MemberValues = dt.Rows(i)("MemberValues").ToString
Areastructure.TaskXrefName = dt.Rows(i)("TaskXrefName").ToString
Areastructure.Visible = Integer.Parse(IIf(dt.Rows(i)("Visible").ToString = "", 0, dt.Rows(i)("Visible").ToString))
Areastructure.Global1 = Integer.Parse(IIf(dt.Rows(i)("Global").ToString = "", 0, dt.Rows(i)("Global").ToString))
Areastructure.Base = Integer.Parse(IIf(dt.Rows(i)("BASE").ToString = "", 0, dt.Rows(i)("BASE").ToString))
Areastructure.MaxLength = Integer.Parse(IIf(dt.Rows(i)("MaxLength").ToString = "", 0, dt.Rows(i)("MaxLength").ToString))
Areastructure.MinValue = Integer.Parse(IIf(dt.Rows(i)("MinValue").ToString = "", 0, dt.Rows(i)("MinValue").ToString))
Areastructure.MaxValue = Integer.Parse(IIf(dt.Rows(i)("MaxValue").ToString = "", 0, dt.Rows(i)("MaxValue").ToString))
areastructure.ExclusionString = dt.Rows(i)("ExclusionString").ToString
areastructure.MemberAffiliation = dt.Rows(i)("MemberAffiliation").ToString
Areastructure.Version = dt.Rows(i)("Version").ToString
listAreaStructure.Add(Areastructure)
Next
Return listAreaStructure
End Function
End Class
End Namespace
|
Option Explicit On
Public Class CuentaCorriente
Shared Sub Delete(id As Integer)
MPP.CuentaCorriente.Delete(id)
End Sub
Shared Function GetAll() As List(Of BE.CuentaCorriente)
Return MPP.CuentaCorriente.GetAll()
End Function
Shared Function GetById(id As Integer) As BE.CuentaCorriente
Return MPP.CuentaCorriente.GetById(id)
End Function
Shared Sub Add(ByRef obj As BE.CuentaCorriente)
MPP.CuentaCorriente.Add(obj)
End Sub
Shared Sub Update(ByRef obj As BE.CuentaCorriente)
MPP.CuentaCorriente.Update(obj)
End Sub
End Class ' CuentaCorriente
|
Public Class MeteorWarning
Implements Entity
Private Ticks As Double = 0
Public Sub New(x As Double, y As Double)
InitializeComponent()
SetValue(Panel.ZIndexProperty, WARNING_LAYER)
RenderTransform = New TranslateTransform(x, y)
End Sub
Public Function Tick(maze As Maze) As Entity.State Implements Entity.Tick
If Ticks Mod 5 = 0 Then
If Visibility = Visibility.Visible Then
Visibility = Visibility.Collapsed
Else
Visibility = Visibility.Visible
End If
End If
If Ticks = 20 Then
Return Entity.State.Done
End If
Ticks += 1
Return Entity.State.Active
End Function
End Class
|
Imports System.Data.SqlClient
Public Class DAO_Telefone
Private Conexao As SqlConnection
Private Transacao As SqlTransaction
Public Sub New(ByVal conexao As SqlConnection)
Me.Conexao = conexao
End Sub
Public Sub New(ByVal conexao As SqlConnection, ByVal Transacao As SqlTransaction)
Me.Conexao = conexao
Me.Transacao = Transacao
End Sub
Public Function Delete(ByVal Obj_Telefone As ClassTelefone) As Integer
'Dim Telefones As New List(Of ClassTelefone)
Dim Comando As New SqlCommand
Comando.Connection = Conexao
Comando.CommandType = CommandType.Text
If Transacao IsNot Nothing Then
Comando.Transaction = Transacao
End If
Comando.CommandText = ("delete from Telefone where Codigo_Telefone = @Codigo_Telefone")
Comando.Parameters.AddWithValue("@Codigo_Telefone", Obj_Telefone.Codigo_Telefone)
Dim Exe As Integer = Comando.ExecuteNonQuery
Return Exe
End Function
Public Function Insert(ByVal Obj_Telefone As ClassTelefone) As Integer
Dim Comando As New SqlCommand
Comando.Connection = Conexao
Comando.CommandType = CommandType.Text
If Transacao IsNot Nothing Then
Comando.Transaction = Transacao
End If
Comando.CommandText = "insert into Telefone (Numero,Matricula_Aluno,Codigo_TipoTelefone) values (@Numero,@Matricula_Aluno,@Codigo_TipoTelefone)"
Comando.Parameters.AddWithValue("@Numero", BbUtil.GetNull(Obj_Telefone.Numero))
Comando.Parameters.AddWithValue("@Matricula_Aluno", Obj_Telefone.Matricula_Aluno)
Comando.Parameters.AddWithValue("@Codigo_TipoTelefone", Obj_Telefone.Tipo_Telefone)
Return Comando.ExecuteNonQuery()
End Function
Public Function ListAll_By_MatriculaAluno(ByVal Matricula_Aluno As Integer) As List(Of ClassTelefone)
Dim Telefones As New List(Of ClassTelefone)
Dim Comando As New SqlCommand
Comando.Connection = Conexao
Comando.CommandType = CommandType.Text
If Transacao IsNot Nothing Then
Comando.Transaction = Transacao
End If
Comando.CommandText = ("select * from Telefone where Matricula_Aluno = @Matricula_Aluno")
Comando.Parameters.AddWithValue("@Matricula_Aluno", Matricula_Aluno)
If Transacao IsNot Nothing Then
Comando.Transaction = Transacao
End If
Dim Cursor As SqlDataReader = Comando.ExecuteReader
While Cursor.Read
Dim Obj_Telefone As New ClassTelefone
Obj_Telefone.Codigo_Telefone = Cursor("Codigo_Telefone")
Obj_Telefone.Numero = Cursor("Numero")
Obj_Telefone.Matricula_Aluno = Cursor("Matricula_Aluno")
Obj_Telefone.Tipo_Telefone = Cursor("Codigo_TipoTelefone")
Telefones.Add(Obj_Telefone)
End While
If Cursor IsNot Nothing AndAlso Not Cursor.IsClosed Then
Cursor.Close()
End If
Return Telefones
End Function
Public Function ListAll() As List(Of ClassTelefone)
Dim Cidades As New List(Of ClassTelefone)
Dim Comando As New SqlCommand
Comando.Connection = Conexao
Comando.CommandType = CommandType.Text
If Transacao IsNot Nothing Then
Comando.Transaction = Transacao
End If
Comando.CommandText = ("select * from Telefone")
If Transacao IsNot Nothing Then
Comando.Transaction = Transacao
End If
Dim Cursor As SqlDataReader = Comando.ExecuteReader
While Cursor.Read
Dim Obj_Telefone As New ClassTelefone
Obj_Telefone.Codigo_Telefone = Cursor("Codigo_Telefone")
Obj_Telefone.Numero = Cursor("Numero")
Obj_Telefone.Matricula_Aluno = Cursor("Matricula_Aluno")
Obj_Telefone.Tipo_Telefone = Cursor("Codigo_TipoTelefone")
Cidades.Add(Obj_Telefone)
End While
If Cursor IsNot Nothing AndAlso Not Cursor.IsClosed Then
Cursor.Close()
End If
Return Cidades
End Function
Public Function GetById(ByVal codigo As Integer) As ClassTelefone
Dim Comando As New SqlCommand
Comando.Connection = Conexao
Comando.CommandType = CommandType.Text
If Transacao IsNot Nothing Then
Comando.Transaction = Transacao
End If
Comando.CommandText = ("select * from Telefone where Codigo_Telefone = @Codigo_Telefone")
Comando.Parameters.AddWithValue("@Codigo_Telefone", codigo)
Dim Obj_Telefone As ClassTelefone = Nothing
Dim Cursor As SqlDataReader = Comando.ExecuteReader
If Cursor.Read Then
Obj_Telefone = New ClassTelefone
Obj_Telefone.Codigo_Telefone = Cursor("Codigo_Telefone")
Obj_Telefone.Numero = BbUtil.SetNull(Cursor("Numero"))
Obj_Telefone.Matricula_Aluno = Cursor("Matricula_Aluno")
Obj_Telefone.Tipo_Telefone = Cursor("Codigo_TipoTelefone")
End If
If Cursor IsNot Nothing AndAlso Not Cursor.IsClosed Then
Cursor.Close()
End If
Return Obj_Telefone
End Function
Public Function Atualizar(ByVal Obj_Telefone As ClassTelefone) As Integer
Dim Comando As New SqlCommand
Comando.Connection = Conexao
Comando.CommandType = CommandType.Text
If Transacao IsNot Nothing Then
Comando.Transaction = Transacao
End If
Comando.CommandText = ("update Telefone set Numero = @Numero, Matricula_Aluno = @Matricula_Aluno, Codigo_TipoTelefone = @Codigo_TipoTelefone where Codigo_Telefone = @Codigo_Telefone")
Comando.Parameters.AddWithValue("@Codigo_Telefone", Obj_Telefone.Codigo_Telefone)
Comando.Parameters.AddWithValue("@Numero", Obj_Telefone.Numero)
Comando.Parameters.AddWithValue("@Matricula_Aluno", Obj_Telefone.Matricula_Aluno)
Comando.Parameters.AddWithValue("@Codigo_TipoTelefone", Obj_Telefone.Tipo_Telefone)
Dim Exe As Integer = Comando.ExecuteNonQuery
Return Exe
End Function
End Class
|
' NX 3.0.0.10
' Journal created by geolekas on Tue Mar 09 13:43:02 2004 Eastern Standard Time
Option Strict Off
Imports System
Imports System.IO
Imports NXOpen
Imports NXOpen.Drawings
Imports NXOpen.Annotations
' ----------------------------------------------
' This automation journal imports a symbol that represents a simple
' 3 line title block. It then adds in headers for the three lines (Part Name,
' Author, and Date). And then it addes in the values for thost lines.
' While this is a simplistic title block, the goal is to show the process
' of how to automatically generate a title block.
'
'
' The title block's text is associative; it will stay with the title block if
' if it is moved around.
' ----------------------------------------------
Module NXJournal
Sub Main
Dim theSession As Session = Session.GetSession()
Dim theUI As UI = UI.GetUI()
Dim PartNameString(0) As String
Dim AuthorString(0) As String
Dim DateString(0) As String
Dim TimeNote As DateTime
' ----------------------------------------------
' Have the time field go to the local system time
' ----------------------------------------------
TimeNote = System.DateTime.Now()
DateString = TimeNote.GetDateTimeFormats()
Dim integer1 As Integer
' ----------------------------------------------
' Alter these strings here to change values
' of strings
' ----------------------------------------------
Dim query_data As Form1 = new Form1()
if query_data.ShowDialog() <> query_data.DialogResult.OK then exit sub
PartNameString(0) = query_data.GetPartName()
AuthorString(0) = query_data.GetAuthorName()
' ----------------------------------------------
' Menu: Insert->Annotation...
' ----------------------------------------------
Dim session_UndoMarkId1 As Session.UndoMarkId
session_UndoMarkId1 = theSession.SetUndoMark(Session.MarkVisibility.Invisible, "Create Annotation")
Dim letteringPreferences1 As LetteringPreferences
letteringPreferences1 = theSession.Parts.Work.Annotations.Preferences.GetLetteringPreferences()
' ----------------------------------------------
' For this example, we need the set the lettering preferences so the
' Text will align correctly in the title block
' ----------------------------------------------
Dim Annotations_Lettering1 As Annotations.Lettering
Annotations_Lettering1.size = 0.125
Annotations_Lettering1.CharacterSpaceFactor = 1
Annotations_Lettering1.AspectRatio = 1
Annotations_Lettering1.LineSpaceFactor = 1
Annotations_Lettering1.cfw.color = 2
Annotations_Lettering1.cfw.font = 1
Annotations_Lettering1.cfw.width = Annotations.LineWidth.Thin
letteringPreferences1.SetGeneralText(Annotations_Lettering1)
theSession.Parts.Work.Annotations.Preferences.SetLetteringPreferences(letteringPreferences1)
Dim userSymbolPreferences1 As UserSymbolPreferences
userSymbolPreferences1 = theSession.Parts.Work.Annotations.NewUserSymbolPreferences(UserSymbolPreferences.SizeType.ScaleAspectRatio, 1, 1)
' ----------------------------------------------
' We need to load in the custom sybmol of the simple title block that has three lines
' ----------------------------------------------
Dim name As String
name = theSession.Parts.Work.FullPath
theSession.Parts.Work.Annotations.CurrentSbfFile = Path.Combine(Path.GetDirectoryName(name), "special.sbf")
Dim double1 As Double
Dim double2 As Double
Dim symbolFont1 As SymbolFont
symbolFont1 = theSession.Parts.Work.Annotations.LoadSymbolFontFromSbfFile("TITLE4 ", double1, double2)
' ----------------------------------------------
' This creates adds the in the title block
' ----------------------------------------------
Dim stringArray1(0) As String
stringArray1(0) = "<%TITLE4>"
Dim point3d1 As Point3d = New Point3d(12.9219405594406, 2.3166958041958, 0)
Dim note1 As Note
note1 = theSession.Parts.Work.Annotations.CreateNote(stringArray1, point3d1, AxisOrientation.Horizontal, letteringPreferences1, userSymbolPreferences1)
theSession.SetUndoMarkVisibility(session_UndoMarkId1, "Create Annotation", Session.MarkVisibility.Visible)
' ----------------------------------------------
' This adds in the note for the Part Name title entry
'
' We set up an association, to the title block note, so
' when the title block is moved the text will travel with it
' ----------------------------------------------
stringArray1(0) = "<C3.250>Part Name<C>"
point3d1 = New Point3d(0, 0, 0)
Dim note3 As Note
note3 = theSession.Parts.Work.Annotations.CreateNote(stringArray1, point3d1, AxisOrientation.Horizontal, letteringPreferences1, userSymbolPreferences1)
' ----------------------------------------------
' Menu: Edit->Placement->Origin Tool
' ----------------------------------------------
theSession.SetUndoMarkVisibility(session_UndoMarkId1, "Create Annotation", Session.MarkVisibility.Visible)
Dim annotation_AssociativeOriginData2 As Annotation.AssociativeOriginData
annotation_AssociativeOriginData2.OriginType = Annotations.AssociativeOriginType.OffsetFromText
annotation_AssociativeOriginData2.View = Nothing
annotation_AssociativeOriginData2.ViewOfGeometry = Nothing
annotation_AssociativeOriginData2.PointOnGeometry = Nothing
annotation_AssociativeOriginData2.VertAnnotation = Nothing
annotation_AssociativeOriginData2.VertAlignmentPosition = Annotations.AlignmentPosition.TopLeft
annotation_AssociativeOriginData2.HorizAnnotation = Nothing
annotation_AssociativeOriginData2.HorizAlignmentPosition = Annotations.AlignmentPosition.TopLeft
annotation_AssociativeOriginData2.AlignedAnnotation = Nothing
annotation_AssociativeOriginData2.DimensionLine = 0
annotation_AssociativeOriginData2.AssociatedView = Nothing
annotation_AssociativeOriginData2.AssociatedPoint = Nothing
annotation_AssociativeOriginData2.OffsetAnnotation = note1
annotation_AssociativeOriginData2.OffsetAlignmentPosition = Annotations.AlignmentPosition.MidCenter
annotation_AssociativeOriginData2.XOffsetFactor = -70
annotation_AssociativeOriginData2.YOffsetFactor = 8
Dim point3d6 As Point3d = New Point3d(2.54694055944056, 3.3166958041958, 0)
note3.SetAssociativeOrigin(annotation_AssociativeOriginData2, point3d6)
integer1 = theSession.UpdateManager.DoUpdate(session_UndoMarkId1)
session_UndoMarkId1 = theSession.SetUndoMark(Session.MarkVisibility.Invisible, "Create Annotation")
' ----------------------------------------------
' This adds in the note for the Author title entry
'
' We set up an association, to the title block note, so
' when the title block is moved the text will travel with it
' ----------------------------------------------
stringArray1(0) = "<C3.250>Author<C>"
point3d1 = New Point3d(0, 0, 0)
Dim note4 As Note
note4 = theSession.Parts.Work.Annotations.CreateNote(stringArray1, point3d1, AxisOrientation.Horizontal, letteringPreferences1, userSymbolPreferences1)
' ----------------------------------------------
' Menu: Edit->Placement->Origin Tool
' ----------------------------------------------
theSession.SetUndoMarkVisibility(session_UndoMarkId1, "Create Annotation", Session.MarkVisibility.Visible)
Dim annotation_AssociativeOriginData3 As Annotation.AssociativeOriginData
annotation_AssociativeOriginData3.OriginType = Annotations.AssociativeOriginType.OffsetFromText
annotation_AssociativeOriginData3.View = Nothing
annotation_AssociativeOriginData3.ViewOfGeometry = Nothing
annotation_AssociativeOriginData3.PointOnGeometry = Nothing
annotation_AssociativeOriginData3.VertAnnotation = Nothing
annotation_AssociativeOriginData3.VertAlignmentPosition = Annotations.AlignmentPosition.TopLeft
annotation_AssociativeOriginData3.HorizAnnotation = Nothing
annotation_AssociativeOriginData3.HorizAlignmentPosition = Annotations.AlignmentPosition.TopLeft
annotation_AssociativeOriginData3.AlignedAnnotation = Nothing
annotation_AssociativeOriginData3.DimensionLine = 0
annotation_AssociativeOriginData3.AssociatedView = Nothing
annotation_AssociativeOriginData3.AssociatedPoint = Nothing
annotation_AssociativeOriginData3.OffsetAnnotation = note1
annotation_AssociativeOriginData3.OffsetAlignmentPosition = Annotations.AlignmentPosition.MidCenter
annotation_AssociativeOriginData3.XOffsetFactor = -70
annotation_AssociativeOriginData3.YOffsetFactor = 1
Dim point3d8 As Point3d = New Point3d(1.92194055944056, 2.4416958041958, 0)
note4.SetAssociativeOrigin(annotation_AssociativeOriginData3, point3d8)
integer1 = theSession.UpdateManager.DoUpdate(session_UndoMarkId1)
session_UndoMarkId1 = theSession.SetUndoMark(Session.MarkVisibility.Invisible, "Create Annotation")
' ----------------------------------------------
' This adds in the note for the Date title entry
'
' We set up an association, to the title block note, so
' when the title block is moved the text will travel with it
' ----------------------------------------------
stringArray1(0) = "<C3.250>Revision Date<C>"
point3d1 = New Point3d(0, 0, 0)
Dim note8 As Note
note8 = theSession.Parts.Work.Annotations.CreateNote(stringArray1, point3d1, AxisOrientation.Horizontal, letteringPreferences1, userSymbolPreferences1)
' ----------------------------------------------
' Menu: Edit->Placement->Origin Tool
' ----------------------------------------------
theSession.SetUndoMarkVisibility(session_UndoMarkId1, "Create Annotation", Session.MarkVisibility.Visible)
Dim annotation_AssociativeOriginData5 As Annotation.AssociativeOriginData
annotation_AssociativeOriginData5.OriginType = Annotations.AssociativeOriginType.OffsetFromText
annotation_AssociativeOriginData5.View = Nothing
annotation_AssociativeOriginData5.ViewOfGeometry = Nothing
annotation_AssociativeOriginData5.PointOnGeometry = Nothing
annotation_AssociativeOriginData5.VertAnnotation = Nothing
annotation_AssociativeOriginData5.VertAlignmentPosition = Annotations.AlignmentPosition.TopLeft
annotation_AssociativeOriginData5.HorizAnnotation = Nothing
annotation_AssociativeOriginData5.HorizAlignmentPosition = Annotations.AlignmentPosition.TopLeft
annotation_AssociativeOriginData5.AlignedAnnotation = Nothing
annotation_AssociativeOriginData5.DimensionLine = 0
annotation_AssociativeOriginData5.AssociatedView = Nothing
annotation_AssociativeOriginData5.AssociatedPoint = Nothing
annotation_AssociativeOriginData5.OffsetAnnotation = note1
annotation_AssociativeOriginData5.OffsetAlignmentPosition = Annotations.AlignmentPosition.MidCenter
annotation_AssociativeOriginData5.XOffsetFactor = -70
annotation_AssociativeOriginData5.YOffsetFactor = -7
Dim point3d14 As Point3d = New Point3d(3.42194055944056, 1.4416958041958, 0)
note8.SetAssociativeOrigin(annotation_AssociativeOriginData5, point3d14)
integer1 = theSession.UpdateManager.DoUpdate(session_UndoMarkId1)
session_UndoMarkId1 = theSession.SetUndoMark(Session.MarkVisibility.Invisible, "Create Annotation")
session_UndoMarkId1 = theSession.SetUndoMark(Session.MarkVisibility.Invisible, "Create Annotation")
' ----------------------------------------------
' This adds in the note for the Part name
'
' We set up an association, to the title block note, so
' when the title block is moved the text will travel with it
' ----------------------------------------------
stringArray1(0) = "<C3.250>" + PartNameString(0) + "<C>"
point3d1 = New Point3d(0, 0, 0)
Dim note9 As Note
note9 = theSession.Parts.Work.Annotations.CreateNote(stringArray1, point3d1, AxisOrientation.Horizontal, letteringPreferences1, userSymbolPreferences1)
' ----------------------------------------------
' Menu: Edit->Placement->Origin Tool
' ----------------------------------------------
theSession.SetUndoMarkVisibility(session_UndoMarkId1, "Create Annotation", Session.MarkVisibility.Visible)
Dim annotation_AssociativeOriginData11 As Annotation.AssociativeOriginData
annotation_AssociativeOriginData11.OriginType = Annotations.AssociativeOriginType.OffsetFromText
annotation_AssociativeOriginData11.View = Nothing
annotation_AssociativeOriginData11.ViewOfGeometry = Nothing
annotation_AssociativeOriginData11.PointOnGeometry = Nothing
annotation_AssociativeOriginData11.VertAnnotation = Nothing
annotation_AssociativeOriginData11.VertAlignmentPosition = Annotations.AlignmentPosition.TopLeft
annotation_AssociativeOriginData11.HorizAnnotation = Nothing
annotation_AssociativeOriginData11.HorizAlignmentPosition = Annotations.AlignmentPosition.TopLeft
annotation_AssociativeOriginData11.AlignedAnnotation = Nothing
annotation_AssociativeOriginData11.DimensionLine = 0
annotation_AssociativeOriginData11.AssociatedView = Nothing
annotation_AssociativeOriginData11.AssociatedPoint = Nothing
annotation_AssociativeOriginData11.OffsetAnnotation = note1
annotation_AssociativeOriginData11.OffsetAlignmentPosition = Annotations.AlignmentPosition.MidCenter
annotation_AssociativeOriginData11.XOffsetFactor = 40
annotation_AssociativeOriginData11.YOffsetFactor = 8
Dim point3d2 As Point3d = New Point3d(33.1533828382838, 3.8529702970297, 0)
note9.SetAssociativeOrigin(annotation_AssociativeOriginData11, point3d2)
integer1 = theSession.UpdateManager.DoUpdate(session_UndoMarkId1)
session_UndoMarkId1 = theSession.SetUndoMark(Session.MarkVisibility.Invisible, "Create Annotation")
' ----------------------------------------------
' This adds in the note for the Author name
'
' We set up an association, to the title block note, so
' when the title block is moved the text will travel with it
' ----------------------------------------------
stringArray1(0) = "<C3.250>" + AuthorString(0) + "<C>"
point3d1 = New Point3d(0, 0, 0)
Dim note10 As Note
note10 = theSession.Parts.Work.Annotations.CreateNote(stringArray1, point3d1, AxisOrientation.Horizontal, letteringPreferences1, userSymbolPreferences1)
' ----------------------------------------------
' Menu: Edit->Placement->Origin Tool
' ----------------------------------------------
theSession.SetUndoMarkVisibility(session_UndoMarkId1, "Create Annotation", Session.MarkVisibility.Visible)
Dim annotation_AssociativeOriginData12 As Annotation.AssociativeOriginData
annotation_AssociativeOriginData12.OriginType = Annotations.AssociativeOriginType.OffsetFromText
annotation_AssociativeOriginData12.View = Nothing
annotation_AssociativeOriginData12.ViewOfGeometry = Nothing
annotation_AssociativeOriginData12.PointOnGeometry = Nothing
annotation_AssociativeOriginData12.VertAnnotation = Nothing
annotation_AssociativeOriginData12.VertAlignmentPosition = Annotations.AlignmentPosition.TopLeft
annotation_AssociativeOriginData12.HorizAnnotation = Nothing
annotation_AssociativeOriginData12.HorizAlignmentPosition = Annotations.AlignmentPosition.TopLeft
annotation_AssociativeOriginData12.AlignedAnnotation = Nothing
annotation_AssociativeOriginData12.DimensionLine = 0
annotation_AssociativeOriginData12.AssociatedView = Nothing
annotation_AssociativeOriginData12.AssociatedPoint = Nothing
annotation_AssociativeOriginData12.OffsetAnnotation = note1
annotation_AssociativeOriginData12.OffsetAlignmentPosition = Annotations.AlignmentPosition.MidCenter
annotation_AssociativeOriginData12.XOffsetFactor = 40
annotation_AssociativeOriginData12.YOffsetFactor = 1
Dim point3d4 As Point3d = New Point3d(33.1533828382838, 2.9779702970297, 0)
note10.SetAssociativeOrigin(annotation_AssociativeOriginData12, point3d4)
integer1 = theSession.UpdateManager.DoUpdate(session_UndoMarkId1)
session_UndoMarkId1 = theSession.SetUndoMark(Session.MarkVisibility.Invisible, "Create Annotation")
' ----------------------------------------------
' This adds in the note for the Date name
'
' We set up an association, to the title block note, so
' when the title block is moved the text will travel with it
' ----------------------------------------------
stringArray1(0) = "<C3.250>" + DateString(0) + "<C>"
point3d1 = New Point3d(0, 0, 0)
Dim note11 As Note
note11 = theSession.Parts.Work.Annotations.CreateNote(stringArray1, point3d1, AxisOrientation.Horizontal, letteringPreferences1, userSymbolPreferences1)
Dim annotation_AssociativeOriginData13 As Annotation.AssociativeOriginData
annotation_AssociativeOriginData13.OriginType = Annotations.AssociativeOriginType.OffsetFromText
annotation_AssociativeOriginData13.View = Nothing
annotation_AssociativeOriginData13.ViewOfGeometry = Nothing
annotation_AssociativeOriginData13.PointOnGeometry = Nothing
annotation_AssociativeOriginData13.VertAnnotation = Nothing
annotation_AssociativeOriginData13.VertAlignmentPosition = Annotations.AlignmentPosition.TopLeft
annotation_AssociativeOriginData13.HorizAnnotation = Nothing
annotation_AssociativeOriginData13.HorizAlignmentPosition = Annotations.AlignmentPosition.TopLeft
annotation_AssociativeOriginData13.AlignedAnnotation = Nothing
annotation_AssociativeOriginData13.DimensionLine = 0
annotation_AssociativeOriginData13.AssociatedView = Nothing
annotation_AssociativeOriginData13.AssociatedPoint = Nothing
annotation_AssociativeOriginData13.OffsetAnnotation = note1
annotation_AssociativeOriginData13.OffsetAlignmentPosition = Annotations.AlignmentPosition.MidCenter
annotation_AssociativeOriginData13.XOffsetFactor = 40
annotation_AssociativeOriginData13.YOffsetFactor = -7
point3d1 = New Point3d(33.1533828382838, 1.9779702970297, 0)
note11.SetAssociativeOrigin(annotation_AssociativeOriginData13, point3d1)
integer1 = theSession.UpdateManager.DoUpdate(session_UndoMarkId1)
session_UndoMarkId1 = theSession.SetUndoMark(Session.MarkVisibility.Invisible, "Create Annotation")
' ----------------------------------------------
' Menu: Edit->Placement->Origin Tool
' ----------------------------------------------
theSession.SetUndoMarkVisibility(session_UndoMarkId1, "Create Annotation", Session.MarkVisibility.Visible)
letteringPreferences1.Dispose()
userSymbolPreferences1.Dispose()
' ----------------------------------------------
' Menu: Tools->Journal->Stop
' ----------------------------------------------
query_data.dispose()
End Sub
' ----------------------------------------------
' The following code for the form was generated
' using Microsoft Visual Studio .Net
' ----------------------------------------------
Public Class Form1
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
End Sub
'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents m_partNameTextBox As System.Windows.Forms.TextBox
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents Button1 As System.Windows.Forms.Button
Friend WithEvents m_authorNameTextBox As System.Windows.Forms.TextBox
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.Label1 = New System.Windows.Forms.Label
Me.m_partNameTextBox = New System.Windows.Forms.TextBox
Me.Label2 = New System.Windows.Forms.Label
Me.m_authorNameTextBox = New System.Windows.Forms.TextBox
Me.Button1 = New System.Windows.Forms.Button
Me.SuspendLayout()
'
'Label1
'
Me.Label1.Location = New System.Drawing.Point(16, 24)
Me.Label1.Name = "Label1"
Me.Label1.TabIndex = 0
Me.Label1.Text = "Part name"
'
'm_partNameTextBox
'
Me.m_partNameTextBox.Location = New System.Drawing.Point(16, 56)
Me.m_partNameTextBox.Name = "m_partNameTextBox"
Me.m_partNameTextBox.Size = New System.Drawing.Size(232, 20)
Me.m_partNameTextBox.TabIndex = 1
Me.m_partNameTextBox.Text = ""
Me.m_partNameTextBox.MaxLength = 30
'
'Label2
'
Me.Label2.Location = New System.Drawing.Point(16, 96)
Me.Label2.Name = "Label2"
Me.Label2.TabIndex = 2
Me.Label2.Text = "Author name"
'
'm_authorNameTextBox
'
Me.m_authorNameTextBox.Location = New System.Drawing.Point(16, 128)
Me.m_authorNameTextBox.Name = "m_authorNameTextBox"
Me.m_authorNameTextBox.Size = New System.Drawing.Size(232, 20)
Me.m_authorNameTextBox.TabIndex = 3
Me.m_authorNameTextBox.Text = ""
Me.m_authorNameTextBox.MaxLength = 30
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(112, 168)
Me.Button1.Name = "Button1"
Me.Button1.TabIndex = 4
Me.Button1.Text = "Ok"
Me.Button1.DialogResult = DialogResult.OK
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(292, 205)
Me.Controls.Add(Me.Button1)
Me.Controls.Add(Me.m_authorNameTextBox)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.m_partNameTextBox)
Me.Controls.Add(Me.Label1)
Me.Name = "GenerateTitleBlock"
Me.Text = "GenerateTitleBlock"
Me.ResumeLayout(False)
End Sub
#End Region
Public Function GetPartName() As String
Return Me.m_partNameTextBox.Text()
End Function
Public Function GetAuthorName() As String
Return Me.m_authorNameTextBox.Text()
End Function
End Class
End Module
|
Public Class Form1
Private _clubs() As String
Private _table()() As Byte
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
_clubs = {"แมนยู", "ลิเวอร์พูล", "อาร์เซนอล", "เชลซี", "แมนซิตี้", "สเปอร์"}
_table = New Byte(_clubs.Length - 1)() {}
' _tables(i)() = {แข่ง, ชนะ, เสมอ, แพ้, คะแนน}
'-- เริ่มแรกในข้อมูลทุกอย่างของทุกสโมสรเป็น 0 ทั้งหมด
For i = 0 To _clubs.Length - 1
_table(i) = {0, 0, 0, 0, 0}
Next
'-- เพิ่มรายชื่อสโมสรลงใน ComboBox ทั้งสองอัน
ComboHome.Items.AddRange(_clubs)
ComboAway.Items.AddRange(_clubs)
ComboHome.SelectedIndex = 0
ComboAway.SelectedIndex = 1
UpdateTable()
End Sub
Private Sub UpdateTable()
'-- Clear ข้อมูลเดิมในตาราง เพื่อให้เรียงลำดับใหม่ได้
DataGridView1.Rows.Clear()
DataGridView1.Rows.Add(_clubs.Length - 1) '-- เพิ่มแถวเท่ากับจำนวนสโมสร (มีแถวเดิมอยู่แล้ว 1)
'-- อ่านข้อมูลจากอาร์เรย์มาเติมลงใน DataGridView
For i = 0 To _clubs.Length - 1
DataGridView1.Rows(i).Cells(1).Value = _clubs(i) '-- ชื่อสโมสร
'-- ข้อมูลการแข่งขันเติมลงในคอลัมน์ที่ 3 เป็นต้นไป
For j = 0 To _table(i).Length - 1
DataGridView1.Rows(i).Cells(j + 2).Value = _table(i)(j)
Next
Next
'-- เรียงลำดับตามคะแนน (คอลัมน์ที่ 7)
DataGridView1.Sort(DataGridView1.Columns(6), System.ComponentModel.ListSortDirection.Descending)
'-- เติมเลขลำดับลงในคอลัมน์แรก
For i = 0 To DataGridView1.RowCount - 1
DataGridView1.Rows(i).Cells(0).Value = (i + 1)
Next
End Sub
Private Sub ButtonUpdate_Click(sender As Object, e As EventArgs) Handles ButtonUpdate.Click
If ComboHome.SelectedIndex = ComboAway.SelectedIndex Then
MessageBox.Show("ทีมเหย้าและเยือนต้องไม่ใช่ทีมเดียวกัน")
Exit Sub
End If
'-- เนื่องจากรายการใน ComboBox สร้างจากอาร์เรย์
'-- ดังนั้นลำดับรายการที่เลือกใน ComboBox จะตรงกับลำดับในอาร์เรย์ด้วย
Dim h As Byte = ComboHome.SelectedIndex '-- ทีมเจ้าบ้านที่เลือก
Dim home_goal As Byte = TextHomeGoal.Text '-- ประตูที่ทีมเจ้าบ้านทำได้
Dim away_goal As Byte = TextAwayGoal.Text '-- ทีมเยือนที่เลือก
Dim a As Byte = ComboAway.SelectedIndex '-- ประตูที่ทีมเยือนทำได้
' _tables(i)(?) = {แข่ง, ชนะ, เสมอ, แพ้, คะแนน}
'-- เพิ่มจำนวนแข่งขันไปอีก 1 นัดให้กับทั้ง 2 ทีม
_table(h)(0) += 1
_table(a)(0) += 1
If home_goal > away_goal Then '-- ถ้าเจ้าบ้าน ชนะ ทีมเยือน
_table(h)(1) += 1 '-- เพิ่มจำนวนครั้งที่เจ้าบ้านชนะไปอีก 1
_table(h)(4) += 3 '-- เพิ่มคะแนนให้ทีมเจ้าบ้านอีก 3
_table(a)(3) += 1 '-- เพิ่มจำนวนที่แพ้ให้ทีมเยือนอีก 1
ElseIf home_goal = away_goal Then '-- ถ้าเจ้าบ้าน เสมอ ทีมเยือน
_table(h)(2) += 1 '-- เพิ่มจำนวนที่เสมอให้ทีมเจ้าบ้านไปอีก 1
_table(h)(4) += 1 '-- เพิ่มคะแนนให้ทีมเจ้าบ้านไปอีก 1
_table(a)(2) += 1 '-- เพิ่มจำนวนเสมอให้ทีมเยือนไปอีก 1
_table(a)(4) += 1 '-- เพิ่มคะแนนให้ทีมเยือนไปอีก 1
ElseIf home_goal < away_goal Then '-- ถ้าเจ้าบ้าน แพ้ ทีมเยือน
_table(h)(3) += 1 '-- เพิ่มจำนวนครั้งที่ทีมเจ้าบ้านแพ้ไปอีก 1
_table(a)(1) += 1 '-- เพิ่มจำนวนที่ทีมเยือนชนะไปอีก 1
_table(a)(4) += 3 '-- เพิ่มคะแนนให้ทีมเยือนไปอีก 3
End If
UpdateTable()
End Sub
End Class
|
'+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
'* Copyright (C) 2013-2016 NamCore Studio <https://github.com/megasus/Namcore-Studio>
'*
'* This program 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.
'*
'* This program is distributed in the hope that it will be useful, but WITHOUT
'* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
'* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
'* more details.
'*
'* You should have received a copy of the GNU General Public License along
'* with this program. If not, see <http://www.gnu.org/licenses/>.
'*
'* Developed by Alcanmage/megasus
'*
'* //FileInfo//
'* /Filename: Date2Timestamp
'* /Description: Extension to convert a date to timestamp and vv
'+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Imports System.Runtime.CompilerServices
Namespace Framework.Extension.Special
Module Date2Timestamp
''' <summary>
''' timestamp converter
''' </summary>
<Extension>
Public Function ToDate(ByRef stamp As Integer) As DateTime
Try
Dim span As TimeSpan
Dim startdate = #1/1/1970#
If Stamp = 0 Then Return startdate
span = New TimeSpan(0, 0, Stamp)
Return startdate.Add(span)
Catch ex As Exception
Return DateTime.Today
End Try
End Function
<Extension>
Public Function ToTimeStamp(ByRef dt As DateTime) As Integer
Try
Dim startdate = #1/1/1970#
Dim spanne As TimeSpan
spanne = dt.Subtract(startdate)
Return CType(Math.Abs(spanne.TotalSeconds()), Integer)
Catch ex As Exception
Return 0
End Try
End Function
End Module
End Namespace |
Imports System.IO
Public Class Util
Public Shared Function ReadFileAsBase64(ByVal fileName As String) As String
Dim ruta As String = Path.Combine(Environment.CurrentDirectory, "..", "..", "Files", fileName)
Using ms As MemoryStream = New MemoryStream()
Using fileStream As FileStream = New FileStream(ruta, FileMode.Open)
ms.SetLength(fileStream.Length)
fileStream.Read(ms.GetBuffer(), 0, CInt(fileStream.Length))
End Using
Return Convert.ToBase64String(ms.ToArray())
End Using
End Function
Public Shared Function ReadFileAsArray(ByVal fileName As String) As Byte()
Dim ruta As String = Path.Combine(Environment.CurrentDirectory, "..", "..", "Files", fileName)
Using ms As MemoryStream = New MemoryStream()
Using fileStream As FileStream = New FileStream(ruta, FileMode.Open)
ms.SetLength(fileStream.Length)
fileStream.Read(ms.GetBuffer(), 0, CInt(fileStream.Length))
End Using
Return ms.ToArray()
End Using
End Function
End Class |
'===============================================================================
' EntitySpaces Studio by EntitySpaces, LLC
' Persistence Layer and Business Objects for Microsoft .NET
' EntitySpaces(TM) is a legal trademark of EntitySpaces, LLC
' http://www.entityspaces.net
'===============================================================================
' EntitySpaces Version : 2012.1.0930.0
' EntitySpaces Driver : SQL
' Date Generated : 9/23/2012 6:16:22 PM
'===============================================================================
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Text
Imports System.Linq
Imports System.Data
Imports System.ComponentModel
Imports System.Xml.Serialization
Imports System.Runtime.Serialization
Imports EntitySpaces.Core
Imports EntitySpaces.Interfaces
Imports EntitySpaces.DynamicQuery
Namespace BusinessObjects
' <summary>
' Encapsulates the 'Products' table
' </summary>
<System.Diagnostics.DebuggerDisplay("Data = {Debug}")> _
<Serializable> _
<DataContract> _
<KnownType(GetType(Products))> _
<XmlType("Products")> _
Partial Public Class Products
Inherits esProducts
<DebuggerBrowsable(DebuggerBrowsableState.RootHidden Or DebuggerBrowsableState.Never)> _
Protected Overrides ReadOnly Property Debug() As esEntityDebuggerView()
Get
Return MyBase.Debug
End Get
End Property
Public Overrides Function CreateInstance() as esEntity
Return New Products()
End Function
#Region "Static Quick Access Methods"
Public Shared Sub Delete(ByVal productID As System.Int32)
Dim obj As New Products()
obj.ProductID = productID
obj.AcceptChanges()
obj.MarkAsDeleted()
obj.Save()
End Sub
Public Shared Sub Delete(ByVal productID As System.Int32, ByVal sqlAccessType As esSqlAccessType)
Dim obj As New Products()
obj.ProductID = productID
obj.AcceptChanges()
obj.MarkAsDeleted()
obj.Save(sqlAccessType)
End Sub
#End Region
End Class
<DebuggerDisplay("Count = {Count}")> _
<Serializable> _
<CollectionDataContract> _
<XmlType("ProductsCollection")> _
Partial Public Class ProductsCollection
Inherits esProductsCollection
Implements IEnumerable(Of Products)
Public Function FindByPrimaryKey(ByVal productID As System.Int32) As Products
Return MyBase.SingleOrDefault(Function(e) e.ProductID.HasValue AndAlso e.ProductID.Value = productID)
End Function
#Region "WCF Service Class"
<DataContract> _
<KnownType(GetType(Products))> _
Public Class ProductsCollectionWCFPacket
Inherits esCollectionWCFPacket(Of ProductsCollection)
Public Shared Widening Operator CType(packet As ProductsCollectionWCFPacket) As ProductsCollection
Return packet.Collection
End Operator
Public Shared Widening Operator CType(collection As ProductsCollection) As ProductsCollectionWCFPacket
Return New ProductsCollectionWCFPacket() With {.Collection = collection}
End Operator
End Class
#End Region
End Class
<DebuggerDisplay("Query = {Parse()}")> _
<Serializable> _
Partial Public Class ProductsQuery
Inherits esProductsQuery
Public Sub New(ByVal joinAlias As String)
Me.es.JoinAlias = joinAlias
End Sub
Protected Overrides Function GetQueryName() As String
Return "ProductsQuery"
End Function
#Region "Explicit Casts"
Public Shared Narrowing Operator CType(ByVal query As ProductsQuery) As String
Return ProductsQuery.SerializeHelper.ToXml(query)
End Operator
Public Shared Narrowing Operator CType(ByVal query As String) As ProductsQuery
Return DirectCast(ProductsQuery.SerializeHelper.FromXml(query, GetType(ProductsQuery)), ProductsQuery)
End Operator
#End Region
End Class
<DataContract> _
<Serializable()> _
MustInherit Public Partial Class esProducts
Inherits esEntity
Implements INotifyPropertyChanged
Public Sub New()
End Sub
#Region "LoadByPrimaryKey"
Public Overridable Function LoadByPrimaryKey(ByVal productID As System.Int32) As Boolean
If Me.es.Connection.SqlAccessType = esSqlAccessType.DynamicSQL
Return LoadByPrimaryKeyDynamic(productID)
Else
Return LoadByPrimaryKeyStoredProcedure(productID)
End If
End Function
Public Overridable Function LoadByPrimaryKey(ByVal sqlAccessType As esSqlAccessType, ByVal productID As System.Int32) As Boolean
If sqlAccessType = esSqlAccessType.DynamicSQL
Return LoadByPrimaryKeyDynamic(productID)
Else
Return LoadByPrimaryKeyStoredProcedure(productID)
End If
End Function
Private Function LoadByPrimaryKeyDynamic(ByVal productID As System.Int32) As Boolean
Dim query As New ProductsQuery()
query.Where(query.ProductID = productID)
Return Me.Load(query)
End Function
Private Function LoadByPrimaryKeyStoredProcedure(ByVal productID As System.Int32) As Boolean
Dim parms As esParameters = New esParameters()
parms.Add("ProductID", productID)
Return MyBase.Load(esQueryType.StoredProcedure, Me.es.spLoadByPrimaryKey, parms)
End Function
#End Region
#Region "Properties"
' <summary>
' Maps to Products.ProductID
' </summary>
<DataMember(EmitDefaultValue:=False)> _
Public Overridable Property ProductID As Nullable(Of System.Int32)
Get
Return MyBase.GetSystemInt32(ProductsMetadata.ColumnNames.ProductID)
End Get
Set(ByVal value As Nullable(Of System.Int32))
If MyBase.SetSystemInt32(ProductsMetadata.ColumnNames.ProductID, value) Then
OnPropertyChanged(ProductsMetadata.PropertyNames.ProductID)
End If
End Set
End Property
' <summary>
' Maps to Products.ProductName
' </summary>
<DataMember(EmitDefaultValue:=False)> _
Public Overridable Property ProductName As System.String
Get
Return MyBase.GetSystemString(ProductsMetadata.ColumnNames.ProductName)
End Get
Set(ByVal value As System.String)
If MyBase.SetSystemString(ProductsMetadata.ColumnNames.ProductName, value) Then
OnPropertyChanged(ProductsMetadata.PropertyNames.ProductName)
End If
End Set
End Property
' <summary>
' Maps to Products.SupplierID
' </summary>
<DataMember(EmitDefaultValue:=False)> _
Public Overridable Property SupplierID As Nullable(Of System.Int32)
Get
Return MyBase.GetSystemInt32(ProductsMetadata.ColumnNames.SupplierID)
End Get
Set(ByVal value As Nullable(Of System.Int32))
If MyBase.SetSystemInt32(ProductsMetadata.ColumnNames.SupplierID, value) Then
OnPropertyChanged(ProductsMetadata.PropertyNames.SupplierID)
End If
End Set
End Property
' <summary>
' Maps to Products.CategoryID
' </summary>
<DataMember(EmitDefaultValue:=False)> _
Public Overridable Property CategoryID As Nullable(Of System.Int32)
Get
Return MyBase.GetSystemInt32(ProductsMetadata.ColumnNames.CategoryID)
End Get
Set(ByVal value As Nullable(Of System.Int32))
If MyBase.SetSystemInt32(ProductsMetadata.ColumnNames.CategoryID, value) Then
Me._UpToCategoriesByCategoryID = Nothing
Me.OnPropertyChanged("UpToCategoriesByCategoryID")
OnPropertyChanged(ProductsMetadata.PropertyNames.CategoryID)
End If
End Set
End Property
' <summary>
' Maps to Products.QuantityPerUnit
' </summary>
<DataMember(EmitDefaultValue:=False)> _
Public Overridable Property QuantityPerUnit As System.String
Get
Return MyBase.GetSystemString(ProductsMetadata.ColumnNames.QuantityPerUnit)
End Get
Set(ByVal value As System.String)
If MyBase.SetSystemString(ProductsMetadata.ColumnNames.QuantityPerUnit, value) Then
OnPropertyChanged(ProductsMetadata.PropertyNames.QuantityPerUnit)
End If
End Set
End Property
' <summary>
' Maps to Products.UnitPrice
' </summary>
<DataMember(EmitDefaultValue:=False)> _
Public Overridable Property UnitPrice As Nullable(Of System.Decimal)
Get
Return MyBase.GetSystemDecimal(ProductsMetadata.ColumnNames.UnitPrice)
End Get
Set(ByVal value As Nullable(Of System.Decimal))
If MyBase.SetSystemDecimal(ProductsMetadata.ColumnNames.UnitPrice, value) Then
OnPropertyChanged(ProductsMetadata.PropertyNames.UnitPrice)
End If
End Set
End Property
' <summary>
' Maps to Products.UnitsInStock
' </summary>
<DataMember(EmitDefaultValue:=False)> _
Public Overridable Property UnitsInStock As Nullable(Of System.Int16)
Get
Return MyBase.GetSystemInt16(ProductsMetadata.ColumnNames.UnitsInStock)
End Get
Set(ByVal value As Nullable(Of System.Int16))
If MyBase.SetSystemInt16(ProductsMetadata.ColumnNames.UnitsInStock, value) Then
OnPropertyChanged(ProductsMetadata.PropertyNames.UnitsInStock)
End If
End Set
End Property
' <summary>
' Maps to Products.UnitsOnOrder
' </summary>
<DataMember(EmitDefaultValue:=False)> _
Public Overridable Property UnitsOnOrder As Nullable(Of System.Int16)
Get
Return MyBase.GetSystemInt16(ProductsMetadata.ColumnNames.UnitsOnOrder)
End Get
Set(ByVal value As Nullable(Of System.Int16))
If MyBase.SetSystemInt16(ProductsMetadata.ColumnNames.UnitsOnOrder, value) Then
OnPropertyChanged(ProductsMetadata.PropertyNames.UnitsOnOrder)
End If
End Set
End Property
' <summary>
' Maps to Products.ReorderLevel
' </summary>
<DataMember(EmitDefaultValue:=False)> _
Public Overridable Property ReorderLevel As Nullable(Of System.Int16)
Get
Return MyBase.GetSystemInt16(ProductsMetadata.ColumnNames.ReorderLevel)
End Get
Set(ByVal value As Nullable(Of System.Int16))
If MyBase.SetSystemInt16(ProductsMetadata.ColumnNames.ReorderLevel, value) Then
OnPropertyChanged(ProductsMetadata.PropertyNames.ReorderLevel)
End If
End Set
End Property
' <summary>
' Maps to Products.Discontinued
' </summary>
<DataMember(EmitDefaultValue:=False)> _
Public Overridable Property Discontinued As Nullable(Of System.Boolean)
Get
Return MyBase.GetSystemBoolean(ProductsMetadata.ColumnNames.Discontinued)
End Get
Set(ByVal value As Nullable(Of System.Boolean))
If MyBase.SetSystemBoolean(ProductsMetadata.ColumnNames.Discontinued, value) Then
OnPropertyChanged(ProductsMetadata.PropertyNames.Discontinued)
End If
End Set
End Property
<CLSCompliant(false)> _
Dim Friend Protected _UpToCategoriesByCategoryID As Categories
#End Region
#Region ".str() Properties"
Public Overrides Sub SetProperties(values as IDictionary)
Dim propertyName As String
For Each propertyName In values.Keys
Me.SetProperty(propertyName, values(propertyName))
Next
End Sub
Public Overrides Sub SetProperty(name as string, value as object)
Dim col As esColumnMetadata = Me.Meta.Columns.FindByPropertyName(name)
If Not col Is Nothing Then
If value Is Nothing OrElse value.GetType().ToString() = "System.String" Then
' Use the strongly typed property
Select Case name
Case "ProductID"
Me.str().ProductID = CType(value, string)
Case "ProductName"
Me.str().ProductName = CType(value, string)
Case "SupplierID"
Me.str().SupplierID = CType(value, string)
Case "CategoryID"
Me.str().CategoryID = CType(value, string)
Case "QuantityPerUnit"
Me.str().QuantityPerUnit = CType(value, string)
Case "UnitPrice"
Me.str().UnitPrice = CType(value, string)
Case "UnitsInStock"
Me.str().UnitsInStock = CType(value, string)
Case "UnitsOnOrder"
Me.str().UnitsOnOrder = CType(value, string)
Case "ReorderLevel"
Me.str().ReorderLevel = CType(value, string)
Case "Discontinued"
Me.str().Discontinued = CType(value, string)
End Select
Else
Select Case name
Case "ProductID"
If value Is Nothing Or value.GetType().ToString() = "System.Int32" Then
Me.ProductID = CType(value, Nullable(Of System.Int32))
OnPropertyChanged(ProductsMetadata.PropertyNames.ProductID)
End If
Case "SupplierID"
If value Is Nothing Or value.GetType().ToString() = "System.Int32" Then
Me.SupplierID = CType(value, Nullable(Of System.Int32))
OnPropertyChanged(ProductsMetadata.PropertyNames.SupplierID)
End If
Case "CategoryID"
If value Is Nothing Or value.GetType().ToString() = "System.Int32" Then
Me.CategoryID = CType(value, Nullable(Of System.Int32))
OnPropertyChanged(ProductsMetadata.PropertyNames.CategoryID)
End If
Case "UnitPrice"
If value Is Nothing Or value.GetType().ToString() = "System.Decimal" Then
Me.UnitPrice = CType(value, Nullable(Of System.Decimal))
OnPropertyChanged(ProductsMetadata.PropertyNames.UnitPrice)
End If
Case "UnitsInStock"
If value Is Nothing Or value.GetType().ToString() = "System.Int16" Then
Me.UnitsInStock = CType(value, Nullable(Of System.Int16))
OnPropertyChanged(ProductsMetadata.PropertyNames.UnitsInStock)
End If
Case "UnitsOnOrder"
If value Is Nothing Or value.GetType().ToString() = "System.Int16" Then
Me.UnitsOnOrder = CType(value, Nullable(Of System.Int16))
OnPropertyChanged(ProductsMetadata.PropertyNames.UnitsOnOrder)
End If
Case "ReorderLevel"
If value Is Nothing Or value.GetType().ToString() = "System.Int16" Then
Me.ReorderLevel = CType(value, Nullable(Of System.Int16))
OnPropertyChanged(ProductsMetadata.PropertyNames.ReorderLevel)
End If
Case "Discontinued"
If value Is Nothing Or value.GetType().ToString() = "System.Boolean" Then
Me.Discontinued = CType(value, Nullable(Of System.Boolean))
OnPropertyChanged(ProductsMetadata.PropertyNames.Discontinued)
End If
Case Else
End Select
End If
Else If Me.ContainsColumn(name) Then
Me.SetColumn(name, value)
Else
throw New Exception("SetProperty Error: '" + name + "' not found")
End If
End Sub
Public Function str() As esStrings
If _esstrings Is Nothing Then
_esstrings = New esStrings(Me)
End If
Return _esstrings
End Function
NotInheritable Public Class esStrings
Public Sub New(ByVal entity As esProducts)
Me.entity = entity
End Sub
Public Property ProductID As System.String
Get
Dim data_ As Nullable(Of System.Int32) = entity.ProductID
If Not data_.HasValue Then
Return String.Empty
Else
Return Convert.ToString(data_)
End If
End Get
Set(ByVal Value as System.String)
If String.IsNullOrEmpty(value) Then
entity.ProductID = Nothing
Else
entity.ProductID = Convert.ToInt32(Value)
End If
End Set
End Property
Public Property ProductName As System.String
Get
Dim data_ As System.String = entity.ProductName
if data_ Is Nothing Then
Return String.Empty
Else
Return Convert.ToString(data_)
End If
End Get
Set(ByVal Value as System.String)
If String.IsNullOrEmpty(value) Then
entity.ProductName = Nothing
Else
entity.ProductName = Convert.ToString(Value)
End If
End Set
End Property
Public Property SupplierID As System.String
Get
Dim data_ As Nullable(Of System.Int32) = entity.SupplierID
If Not data_.HasValue Then
Return String.Empty
Else
Return Convert.ToString(data_)
End If
End Get
Set(ByVal Value as System.String)
If String.IsNullOrEmpty(value) Then
entity.SupplierID = Nothing
Else
entity.SupplierID = Convert.ToInt32(Value)
End If
End Set
End Property
Public Property CategoryID As System.String
Get
Dim data_ As Nullable(Of System.Int32) = entity.CategoryID
If Not data_.HasValue Then
Return String.Empty
Else
Return Convert.ToString(data_)
End If
End Get
Set(ByVal Value as System.String)
If String.IsNullOrEmpty(value) Then
entity.CategoryID = Nothing
Else
entity.CategoryID = Convert.ToInt32(Value)
End If
End Set
End Property
Public Property QuantityPerUnit As System.String
Get
Dim data_ As System.String = entity.QuantityPerUnit
if data_ Is Nothing Then
Return String.Empty
Else
Return Convert.ToString(data_)
End If
End Get
Set(ByVal Value as System.String)
If String.IsNullOrEmpty(value) Then
entity.QuantityPerUnit = Nothing
Else
entity.QuantityPerUnit = Convert.ToString(Value)
End If
End Set
End Property
Public Property UnitPrice As System.String
Get
Dim data_ As Nullable(Of System.Decimal) = entity.UnitPrice
If Not data_.HasValue Then
Return String.Empty
Else
Return Convert.ToString(data_)
End If
End Get
Set(ByVal Value as System.String)
If String.IsNullOrEmpty(value) Then
entity.UnitPrice = Nothing
Else
entity.UnitPrice = Convert.ToDecimal(Value)
End If
End Set
End Property
Public Property UnitsInStock As System.String
Get
Dim data_ As Nullable(Of System.Int16) = entity.UnitsInStock
If Not data_.HasValue Then
Return String.Empty
Else
Return Convert.ToString(data_)
End If
End Get
Set(ByVal Value as System.String)
If String.IsNullOrEmpty(value) Then
entity.UnitsInStock = Nothing
Else
entity.UnitsInStock = Convert.ToInt16(Value)
End If
End Set
End Property
Public Property UnitsOnOrder As System.String
Get
Dim data_ As Nullable(Of System.Int16) = entity.UnitsOnOrder
If Not data_.HasValue Then
Return String.Empty
Else
Return Convert.ToString(data_)
End If
End Get
Set(ByVal Value as System.String)
If String.IsNullOrEmpty(value) Then
entity.UnitsOnOrder = Nothing
Else
entity.UnitsOnOrder = Convert.ToInt16(Value)
End If
End Set
End Property
Public Property ReorderLevel As System.String
Get
Dim data_ As Nullable(Of System.Int16) = entity.ReorderLevel
If Not data_.HasValue Then
Return String.Empty
Else
Return Convert.ToString(data_)
End If
End Get
Set(ByVal Value as System.String)
If String.IsNullOrEmpty(value) Then
entity.ReorderLevel = Nothing
Else
entity.ReorderLevel = Convert.ToInt16(Value)
End If
End Set
End Property
Public Property Discontinued As System.String
Get
Dim data_ As Nullable(Of System.Boolean) = entity.Discontinued
If Not data_.HasValue Then
Return String.Empty
Else
Return Convert.ToString(data_)
End If
End Get
Set(ByVal Value as System.String)
If String.IsNullOrEmpty(value) Then
entity.Discontinued = Nothing
Else
entity.Discontinued = Convert.ToBoolean(Value)
End If
End Set
End Property
Private entity As esProducts
End Class
<NonSerialized> _
<IgnoreDataMember> _
Private _esstrings As esStrings
#End Region
#Region "Housekeeping methods"
Protected Overloads Overrides ReadOnly Property Meta() As IMetadata
Get
Return ProductsMetadata.Meta()
End Get
End Property
#End Region
#Region "Query Logic"
Public ReadOnly Property Query() As ProductsQuery
Get
If Me.m_query Is Nothing Then
Me.m_query = New ProductsQuery()
InitQuery(Me.m_query)
End If
Return Me.m_query
End Get
End Property
Public Overloads Function Load(ByVal query As ProductsQuery) As Boolean
Me.m_query = query
InitQuery(Me.m_query)
Return Me.Query.Load()
End Function
Protected Sub InitQuery(ByVal query As ProductsQuery)
query.OnLoadDelegate = AddressOf OnQueryLoaded
If Not query.es2.HasConnection Then
query.es2.Connection = DirectCast(Me, IEntity).Connection
End If
End Sub
#End Region
<IgnoreDataMember> _
Private m_query As ProductsQuery
End Class
<Serializable()> _
MustInherit Public Partial Class esProductsCollection
Inherits esEntityCollection(Of Products)
#Region "Housekeeping methods"
Protected Overloads Overrides ReadOnly Property Meta() As IMetadata
Get
Return ProductsMetadata.Meta()
End Get
End Property
Protected Overloads Overrides Function GetCollectionName() As String
Return "ProductsCollection"
End Function
#End Region
#Region "Query Logic"
<BrowsableAttribute(False)> _
Public ReadOnly Property Query() As ProductsQuery
Get
If Me.m_query Is Nothing Then
Me.m_query = New ProductsQuery()
InitQuery(Me.m_query)
End If
Return Me.m_query
End Get
End Property
Public Overloads Function Load(ByVal query As ProductsQuery) As Boolean
Me.m_query = query
InitQuery(Me.m_query)
Return Query.Load()
End Function
Protected Overloads Overrides Function GetDynamicQuery() As esDynamicQuery
If Me.m_query Is Nothing Then
Me.m_query = New ProductsQuery()
Me.InitQuery(m_query)
End If
Return Me.m_query
End Function
Protected Sub InitQuery(ByVal query As ProductsQuery)
query.OnLoadDelegate = AddressOf OnQueryLoaded
If Not query.es2.HasConnection Then
query.es2.Connection = DirectCast(Me, IEntityCollection).Connection
End If
End Sub
Protected Overloads Overrides Sub HookupQuery(ByVal query As esDynamicQuery)
Me.InitQuery(DirectCast(query, ProductsQuery))
End Sub
#End Region
Private m_query As ProductsQuery
End Class
<Serializable> _
MustInherit Public Partial Class esProductsQuery
Inherits esDynamicQuery
Protected ReadOnly Overrides Property Meta() As IMetadata
Get
Return ProductsMetadata.Meta()
End Get
End Property
#Region "QueryItemFromName"
Protected Overrides Function QueryItemFromName(ByVal name As String) As esQueryItem
Select Case name
Case "ProductID"
Return Me.ProductID
Case "ProductName"
Return Me.ProductName
Case "SupplierID"
Return Me.SupplierID
Case "CategoryID"
Return Me.CategoryID
Case "QuantityPerUnit"
Return Me.QuantityPerUnit
Case "UnitPrice"
Return Me.UnitPrice
Case "UnitsInStock"
Return Me.UnitsInStock
Case "UnitsOnOrder"
Return Me.UnitsOnOrder
Case "ReorderLevel"
Return Me.ReorderLevel
Case "Discontinued"
Return Me.Discontinued
Case Else
Return Nothing
End Select
End Function
#End Region
#Region "esQueryItems"
Public ReadOnly Property ProductID As esQueryItem
Get
Return New esQueryItem(Me, ProductsMetadata.ColumnNames.ProductID, esSystemType.Int32)
End Get
End Property
Public ReadOnly Property ProductName As esQueryItem
Get
Return New esQueryItem(Me, ProductsMetadata.ColumnNames.ProductName, esSystemType.String)
End Get
End Property
Public ReadOnly Property SupplierID As esQueryItem
Get
Return New esQueryItem(Me, ProductsMetadata.ColumnNames.SupplierID, esSystemType.Int32)
End Get
End Property
Public ReadOnly Property CategoryID As esQueryItem
Get
Return New esQueryItem(Me, ProductsMetadata.ColumnNames.CategoryID, esSystemType.Int32)
End Get
End Property
Public ReadOnly Property QuantityPerUnit As esQueryItem
Get
Return New esQueryItem(Me, ProductsMetadata.ColumnNames.QuantityPerUnit, esSystemType.String)
End Get
End Property
Public ReadOnly Property UnitPrice As esQueryItem
Get
Return New esQueryItem(Me, ProductsMetadata.ColumnNames.UnitPrice, esSystemType.Decimal)
End Get
End Property
Public ReadOnly Property UnitsInStock As esQueryItem
Get
Return New esQueryItem(Me, ProductsMetadata.ColumnNames.UnitsInStock, esSystemType.Int16)
End Get
End Property
Public ReadOnly Property UnitsOnOrder As esQueryItem
Get
Return New esQueryItem(Me, ProductsMetadata.ColumnNames.UnitsOnOrder, esSystemType.Int16)
End Get
End Property
Public ReadOnly Property ReorderLevel As esQueryItem
Get
Return New esQueryItem(Me, ProductsMetadata.ColumnNames.ReorderLevel, esSystemType.Int16)
End Get
End Property
Public ReadOnly Property Discontinued As esQueryItem
Get
Return New esQueryItem(Me, ProductsMetadata.ColumnNames.Discontinued, esSystemType.Boolean)
End Get
End Property
#End Region
End Class
Partial Public Class Products
Inherits esProducts
#Region "UpToCategoriesByCategoryID - Many To One"
''' <summary>
''' Many to One
''' Foreign Key Name - FK_Products_Categories
''' </summary>
<XmlIgnore()> _
Public Property UpToCategoriesByCategoryID As Categories
Get
If Me.es.IsLazyLoadDisabled Then return Nothing
If Me._UpToCategoriesByCategoryID Is Nothing _
AndAlso Not CategoryID.Equals(Nothing) Then
Me._UpToCategoriesByCategoryID = New Categories()
Me._UpToCategoriesByCategoryID.es.Connection.Name = Me.es.Connection.Name
Me.SetPreSave("UpToCategoriesByCategoryID", Me._UpToCategoriesByCategoryID)
Me._UpToCategoriesByCategoryID.Query.Where(Me._UpToCategoriesByCategoryID.Query.CategoryID = Me.CategoryID)
Me._UpToCategoriesByCategoryID.Query.Load()
End If
Return Me._UpToCategoriesByCategoryID
End Get
Set(ByVal value As Categories)
Me.RemovePreSave("UpToCategoriesByCategoryID")
Dim changed as Boolean = Me._UpToCategoriesByCategoryID IsNot value
If value Is Nothing Then
Me.CategoryID = Nothing
Me._UpToCategoriesByCategoryID = Nothing
Else
Me.CategoryID = value.CategoryID
Me._UpToCategoriesByCategoryID = value
Me.SetPreSave("UpToCategoriesByCategoryID", Me._UpToCategoriesByCategoryID)
End If
If changed Then
Me.OnPropertyChanged("UpToCategoriesByCategoryID")
End If
End Set
End Property
#End Region
''' <summary>
''' Used internally for retrieving AutoIncrementing keys
''' during hierarchical PreSave.
''' </summary>
Protected Overrides Sub ApplyPreSaveKeys()
If Not Me.es.IsDeleted And Not Me._UpToCategoriesByCategoryID Is Nothing Then
Me.CategoryID = Me._UpToCategoriesByCategoryID.CategoryID
End If
End Sub
End Class
<Serializable> _
Partial Public Class ProductsMetadata
Inherits esMetadata
Implements IMetadata
#Region "Protected Constructor"
Protected Sub New()
m_columns = New esColumnMetadataCollection()
Dim c as esColumnMetadata
c = New esColumnMetadata(ProductsMetadata.ColumnNames.ProductID, 0, GetType(System.Int32), esSystemType.Int32)
c.PropertyName = ProductsMetadata.PropertyNames.ProductID
c.IsInPrimaryKey = True
c.IsAutoIncrement = True
c.NumericPrecision = 10
m_columns.Add(c)
c = New esColumnMetadata(ProductsMetadata.ColumnNames.ProductName, 1, GetType(System.String), esSystemType.String)
c.PropertyName = ProductsMetadata.PropertyNames.ProductName
c.CharacterMaxLength = 40
m_columns.Add(c)
c = New esColumnMetadata(ProductsMetadata.ColumnNames.SupplierID, 2, GetType(System.Int32), esSystemType.Int32)
c.PropertyName = ProductsMetadata.PropertyNames.SupplierID
c.NumericPrecision = 10
c.IsNullable = True
m_columns.Add(c)
c = New esColumnMetadata(ProductsMetadata.ColumnNames.CategoryID, 3, GetType(System.Int32), esSystemType.Int32)
c.PropertyName = ProductsMetadata.PropertyNames.CategoryID
c.NumericPrecision = 10
c.IsNullable = True
m_columns.Add(c)
c = New esColumnMetadata(ProductsMetadata.ColumnNames.QuantityPerUnit, 4, GetType(System.String), esSystemType.String)
c.PropertyName = ProductsMetadata.PropertyNames.QuantityPerUnit
c.CharacterMaxLength = 20
c.IsNullable = True
m_columns.Add(c)
c = New esColumnMetadata(ProductsMetadata.ColumnNames.UnitPrice, 5, GetType(System.Decimal), esSystemType.Decimal)
c.PropertyName = ProductsMetadata.PropertyNames.UnitPrice
c.NumericPrecision = 19
c.HasDefault = True
c.Default = "(0)"
c.IsNullable = True
m_columns.Add(c)
c = New esColumnMetadata(ProductsMetadata.ColumnNames.UnitsInStock, 6, GetType(System.Int16), esSystemType.Int16)
c.PropertyName = ProductsMetadata.PropertyNames.UnitsInStock
c.NumericPrecision = 5
c.HasDefault = True
c.Default = "(0)"
c.IsNullable = True
m_columns.Add(c)
c = New esColumnMetadata(ProductsMetadata.ColumnNames.UnitsOnOrder, 7, GetType(System.Int16), esSystemType.Int16)
c.PropertyName = ProductsMetadata.PropertyNames.UnitsOnOrder
c.NumericPrecision = 5
c.HasDefault = True
c.Default = "(0)"
c.IsNullable = True
m_columns.Add(c)
c = New esColumnMetadata(ProductsMetadata.ColumnNames.ReorderLevel, 8, GetType(System.Int16), esSystemType.Int16)
c.PropertyName = ProductsMetadata.PropertyNames.ReorderLevel
c.NumericPrecision = 5
c.HasDefault = True
c.Default = "(0)"
c.IsNullable = True
m_columns.Add(c)
c = New esColumnMetadata(ProductsMetadata.ColumnNames.Discontinued, 9, GetType(System.Boolean), esSystemType.Boolean)
c.PropertyName = ProductsMetadata.PropertyNames.Discontinued
c.HasDefault = True
c.Default = "(0)"
m_columns.Add(c)
End Sub
#End Region
Shared Public Function Meta() As ProductsMetadata
Return _meta
End Function
Public ReadOnly Property DataID() As System.Guid Implements IMetadata.DataID
Get
Return MyBase.m_dataID
End Get
End Property
Public ReadOnly Property MultiProviderMode() As Boolean Implements IMetadata.MultiProviderMode
Get
Return false
End Get
End Property
Public ReadOnly Property Columns() As esColumnMetadataCollection Implements IMetadata.Columns
Get
Return MyBase.m_columns
End Get
End Property
#Region "ColumnNames"
Public Class ColumnNames
Public Const ProductID As String = "ProductID"
Public Const ProductName As String = "ProductName"
Public Const SupplierID As String = "SupplierID"
Public Const CategoryID As String = "CategoryID"
Public Const QuantityPerUnit As String = "QuantityPerUnit"
Public Const UnitPrice As String = "UnitPrice"
Public Const UnitsInStock As String = "UnitsInStock"
Public Const UnitsOnOrder As String = "UnitsOnOrder"
Public Const ReorderLevel As String = "ReorderLevel"
Public Const Discontinued As String = "Discontinued"
End Class
#End Region
#Region "PropertyNames"
Public Class PropertyNames
Public Const ProductID As String = "ProductID"
Public Const ProductName As String = "ProductName"
Public Const SupplierID As String = "SupplierID"
Public Const CategoryID As String = "CategoryID"
Public Const QuantityPerUnit As String = "QuantityPerUnit"
Public Const UnitPrice As String = "UnitPrice"
Public Const UnitsInStock As String = "UnitsInStock"
Public Const UnitsOnOrder As String = "UnitsOnOrder"
Public Const ReorderLevel As String = "ReorderLevel"
Public Const Discontinued As String = "Discontinued"
End Class
#End Region
Public Function GetProviderMetadata(ByVal mapName As String) As esProviderSpecificMetadata _
Implements IMetadata.GetProviderMetadata
Dim mapMethod As MapToMeta = mapDelegates(mapName)
If (Not mapMethod = Nothing) Then
Return mapMethod(mapName)
Else
Return Nothing
End If
End Function
#Region "MAP esDefault"
Private Shared Function RegisterDelegateesDefault() As Integer
' This is only executed once per the life of the application
SyncLock GetType(ProductsMetadata)
If ProductsMetadata.mapDelegates Is Nothing Then
ProductsMetadata.mapDelegates = New Dictionary(Of String, MapToMeta)
End If
If ProductsMetadata._meta Is Nothing Then
ProductsMetadata._meta = New ProductsMetadata()
End If
Dim mapMethod As New MapToMeta(AddressOf _meta.esDefault)
mapDelegates.Add("esDefault", mapMethod)
mapMethod("esDefault")
Return 0
End SyncLock
End Function
Private Function esDefault(ByVal mapName As String) As esProviderSpecificMetadata
If (Not m_providerMetadataMaps.ContainsKey(mapName)) Then
Dim meta As esProviderSpecificMetadata = New esProviderSpecificMetadata()
meta.AddTypeMap("ProductID", new esTypeMap("int", "System.Int32"))
meta.AddTypeMap("ProductName", new esTypeMap("nvarchar", "System.String"))
meta.AddTypeMap("SupplierID", new esTypeMap("int", "System.Int32"))
meta.AddTypeMap("CategoryID", new esTypeMap("int", "System.Int32"))
meta.AddTypeMap("QuantityPerUnit", new esTypeMap("nvarchar", "System.String"))
meta.AddTypeMap("UnitPrice", new esTypeMap("money", "System.Decimal"))
meta.AddTypeMap("UnitsInStock", new esTypeMap("smallint", "System.Int16"))
meta.AddTypeMap("UnitsOnOrder", new esTypeMap("smallint", "System.Int16"))
meta.AddTypeMap("ReorderLevel", new esTypeMap("smallint", "System.Int16"))
meta.AddTypeMap("Discontinued", new esTypeMap("bit", "System.Boolean"))
meta.Source = "Products"
meta.Destination = "Products"
meta.spInsert = "proc_ProductsInsert"
meta.spUpdate = "proc_ProductsUpdate"
meta.spDelete = "proc_ProductsDelete"
meta.spLoadAll = "proc_ProductsLoadAll"
meta.spLoadByPrimaryKey = "proc_ProductsLoadByPrimaryKey"
Me.m_providerMetadataMaps.Add("esDefault", meta)
End If
Return Me.m_providerMetadataMaps("esDefault")
End Function
#End Region
Private Shared _meta As ProductsMetadata
Protected Shared mapDelegates As Dictionary(Of String, MapToMeta)
Private Shared _esDefault As Integer = RegisterDelegateesDefault()
End Class
End Namespace
|
Imports Microsoft.VisualBasic.Language
''' <summary>
''' Chemical Abstracts Service Number of a specific metabolite
''' </summary>
Public Class CASNumber
''' <summary>
''' CAS号(第一、二部分数字)的最后一位乘以1,最后第二位乘以2,往前依此类推,
''' 然后再把所有的乘积相加,和除以10,余数就是第三部分的校验码。举例来说,
''' 水(H2O)的CAS编号前两部分是7732-18,则其校验码
''' ( 8×1 + 1×2 + 2×3 + 3×4 + 7×5 + 7×6 ) /10 = 105/10 = 10余5,
''' 所以水的CAS号为7732-18-5。
''' </summary>
''' <param name="cas"></param>
''' <returns></returns>
''' <remarks>
''' 第一部分有2到7位数字,第二部分有2位数字,第三部分有1位数字作为校验码
''' </remarks>
Public Shared Function Verify(cas As String) As Boolean
If cas.StringEmpty Then
Return False
End If
Dim tokens As String() = cas.Split("-"c)
If Not tokens.Any(Function(si) si.IsInteger) Then
Return False
End If
Dim n As Long = 0
Dim i As i32 = 1
For Each ni As Char In tokens.Take(2).JoinBy("").Reverse
n += Integer.Parse(CStr(ni)) * (++i)
Next
Dim code As Integer = n Mod 10
Dim code2 As Integer = Integer.Parse(tokens(2))
Return code = code2
End Function
End Class
|
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports Client.Chat
Imports Client.Chat.Definitions
Namespace World.Network
Public Partial Class WorldSocket
<PacketHandler(WorldCommand.SMSG_MESSAGECHAT)> _
Private Sub HandleMessageChat(packet As InPacket)
Dim type = CType(packet.ReadByte(), ChatMessageType)
Dim lang = CType(packet.ReadInt32(), Language)
Dim guid = packet.ReadUInt64()
Dim unkInt = packet.ReadInt32()
Select Case type
Case ChatMessageType.Say, ChatMessageType.Yell, ChatMessageType.Party, ChatMessageType.PartyLeader, ChatMessageType.Raid, ChatMessageType.RaidLeader, _
ChatMessageType.RaidWarning, ChatMessageType.Guild, ChatMessageType.Officer, ChatMessageType.Emote, ChatMessageType.TextEmote, ChatMessageType.Whisper, _
ChatMessageType.WhisperInform, ChatMessageType.System, ChatMessageType.Channel, ChatMessageType.Battleground, ChatMessageType.BattlegroundNeutral, ChatMessageType.BattlegroundAlliance, _
ChatMessageType.BattlegroundHorde, ChatMessageType.BattlegroundLeader, ChatMessageType.Achievement, ChatMessageType.GuildAchievement
If True Then
Dim channel As New ChatChannel()
channel.Type = type
If type = ChatMessageType.Channel Then
channel.ChannelName = packet.ReadCString()
End If
Dim sender = packet.ReadUInt64()
Dim message As New ChatMessage()
Dim textLen = packet.ReadInt32()
message.Message = packet.ReadCString()
message.Language = lang
message.ChatTag = CType(packet.ReadByte(), ChatTag)
message.Sender = channel
'! If we know the name of the sender GUID, use it
'! For system messages sender GUID is 0, don't need to do anything fancy
Dim senderName As String = Nothing
If type = ChatMessageType.System OrElse Game.World.PlayerNameLookup.TryGetValue(sender, senderName) Then
message.Sender.Sender = senderName
Game.UI.PresentChatMessage(message)
Return
End If
'! If not we place the message in the queue,
'! .. either existent
Dim messageQueue As Queue(Of ChatMessage) = Nothing
If Game.World.QueuedChatMessages.TryGetValue(sender, messageQueue) Then
messageQueue.Enqueue(message)
Else
'! or non existent
messageQueue = New Queue(Of ChatMessage)()
messageQueue.Enqueue(message)
Game.World.QueuedChatMessages.Add(sender, messageQueue)
End If
'! Furthermore we send CMSG_NAME_QUERY to the server to retrieve the name of the sender
Dim response As New OutPacket(WorldCommand.CMSG_NAME_QUERY)
response.Write(sender)
Game.SendPacket(response)
'! Enqueued chat will be printed when we receive SMSG_NAME_QUERY_RESPONSE
Exit Select
End If
Case Else
Return
End Select
End Sub
<PacketHandler(WorldCommand.SMSG_CHAT_PLAYER_NOT_FOUND)> _
Private Sub HandleChatPlayerNotFound(packet As InPacket)
Game.UI.LogLine([String].Format("Player {0} not found!", packet.ReadCString()))
End Sub
End Class
End Namespace
|
Public Class clsFunctions
Property DefaultButtonBackColour As String = "#0D3D57"
Property DefaultButtonTextColour As String = "#FFFFFF"
Property FunctionButtons As IEnumerable(Of clsTillFunctionButton)
End Class
|
Imports System.Xml
Imports System.IO
Imports PolyMon.Status
'This monitor will test for the existence of files
'matching a specific pattern in a specified location
'OK, Fail, Warn is based on the age of the oldest file
'and/or the number of files matching the pattern in the
'specified directory.
'This monitor type can be useful for monitoring a file based queue system
'where you would want to make sure no files older than a certain age exist
'or making sure that the queues are not getting backup up beyond a certain number of files
'This monitor generates a single counter indicating the number of files matching the pattern
'in the specified directory.
'The XML definition for this monitor's settings is specified as follows:
'<FileMonitor>
' <DirPath>c:\</DirPath>
' <FilePattern>*.xml</FilePattern>
' <WarnCount Enabled="1">50</WarnCount>
' <MaxCount Enabled="1">100</MaxCount>
' <MaxAge Enabled="1" AgeType="seconds|minutes|hours|days" DateType="created|modified|accessed" FileType="oldest|newest">1800</MaxAge>
' <EnableCounters>1</EnableCounters>
'</FileMonitor>
'
'Notes:
'MaxAge is specified in seconds.
'If enabled, WarnCount specifies a threshold value at or above which a Warn alert will be generated.
'If enabled, MaxCount specifies a threshold value at or above which a Fail alert willbe generated.
'If EnableCounters is set to 1, any counters defined by this monitor will be logged to the database.
'Enhancements contributed by Rod Sawers: 10/25/2006
'Rod's Notes:
'FilePattern was not being used - now added to GetFiles() call
'When checking the oldest file in the folder (e.g. a queue), fail on first old file found.
'When checking the newest file in the folder (e.g. a logfile), check all files to find the newest; then check the timestamp.
Namespace Monitors
Public Class FileMonitor
Inherits PolyMon.Monitors.MonitorExecutor
'Need to implement the New method since a constructor is required
Public Sub New(ByVal MonitorID As Integer)
MyBase.New(MonitorID)
End Sub
'Need to implement the MonitorTest function
'This is the function that performs the monitoring and sets any warn/fail/ok statuses as well as any counters
Protected Overrides Function MonitorTest(ByRef StatusMessage As String, ByRef Counters As CounterList) As MonitorExecutor.MonitorStatus
'Initialize
Dim myStatus As MonitorStatus = MonitorExecutor.MonitorStatus.Fail
Counters.Clear()
StatusMessage = "Monitor not run."
Try
'Read in monitor/threshold definitions
Dim DirPath As String
Dim FilePattern As String
Dim WarnCountEnabled As Boolean
Dim WarnCountThreshold As Integer
Dim MaxCountEnabled As Boolean
Dim MaxCountThreshold As Integer
Dim MaxAgeEnabled As Boolean
Dim MaxAgeThreshold As Integer
Dim EnableCounters As Boolean
Dim MaxAgeAgeType As String
Dim MaxAgeDateType As String
Dim MaxAgeFileType As String
Dim RootNode As XmlNode = Me.MonitorXML.DocumentElement
DirPath = ReadXMLNodeValue(RootNode.SelectSingleNode("DirPath"))
FilePattern = ReadXMLNodeValue(RootNode.SelectSingleNode("FilePattern"))
MaxCountEnabled = CBool(ReadXMLAttributeValue(RootNode.SelectSingleNode("MaxCount").Attributes("Enabled")))
If MaxCountEnabled Then
MaxCountThreshold = CInt(ReadXMLNodeValue(RootNode.SelectSingleNode("MaxCount")))
End If
WarnCountEnabled = CBool(ReadXMLAttributeValue(RootNode.SelectSingleNode("WarnCount").Attributes("Enabled")))
If WarnCountEnabled Then
WarnCountThreshold = CInt(ReadXMLNodeValue(RootNode.SelectSingleNode("WarnCount")))
End If
MaxAgeEnabled = CBool(ReadXMLAttributeValue(RootNode.SelectSingleNode("MaxAge").Attributes("Enabled")))
If MaxAgeEnabled Then
MaxAgeThreshold = CInt(ReadXMLNodeValue(RootNode.SelectSingleNode("MaxAge")))
End If
EnableCounters = CBool(ReadXMLNodeValue(RootNode.SelectSingleNode("EnableCounters")))
Try
MaxAgeAgeType = ReadXMLAttributeValue(RootNode.SelectSingleNode("MaxAge").Attributes("AgeType")).ToLower
Catch ex As Exception
MaxAgeAgeType = ""
End Try
If MaxAgeAgeType = "" Then MaxAgeAgeType = "seconds"
' Convert the threshold to seconds.
Select Case MaxAgeAgeType
Case "minutes"
MaxAgeThreshold *= 60
Case "hours"
MaxAgeThreshold *= 60 * 60
Case "days"
MaxAgeThreshold *= 60 * 60 * 24
End Select
Try
MaxAgeDateType = ReadXMLAttributeValue(RootNode.SelectSingleNode("MaxAge").Attributes("DateType")).ToLower
Catch ex As Exception
MaxAgeDateType = ""
End Try
If MaxAgeDateType = "" Then MaxAgeDateType = "created"
Try
MaxAgeFileType = ReadXMLAttributeValue(RootNode.SelectSingleNode("MaxAge").Attributes("FileType")).ToLower
Catch ex As Exception
MaxAgeFileType = ""
End Try
If MaxAgeDateType = "" Then MaxAgeDateType = "oldest"
'Run Monitor Test/Counters
Dim FileDir As DirectoryInfo
FileDir = New DirectoryInfo(DirPath)
Dim myFiles() As FileInfo = FileDir.GetFiles(FilePattern)
Dim FileCount As Integer = myFiles.GetLength(0)
If EnableCounters Then
Counters.Add(New Counter("File Count", FileCount))
End If
Dim IsOK As Boolean = True
If MaxAgeEnabled AndAlso FileCount > 0 Then
Dim myFile As FileInfo
Dim checkTime As DateTime
Dim newestTime As DateTime = DateTime.MinValue
Dim newestFile As FileInfo = Nothing
IsOK = True
For Each myFile In myFiles
Select Case MaxAgeDateType
Case "modified"
checkTime = myFile.LastWriteTime
Case "accessed"
checkTime = myFile.LastAccessTime
Case Else
checkTime = myFile.CreationTime
End Select
' Store the timestamp of the newest file in the folder.
If checkTime > newestTime Then
newestTime = checkTime
newestFile = myFile
End If
' Checking 'oldest' file - we can stop as soon as we find any older file.
If MaxAgeFileType = "oldest" Then
If checkTime <= DateAdd(DateInterval.Second, -MaxAgeThreshold, Now()) Then
StatusMessage = FormatStatusMessage(checkTime, MaxAgeDateType, MaxAgeAgeType)
myStatus = MonitorExecutor.MonitorStatus.Fail
IsOK = False
Exit For 'No need to keep checking
End If
End If
Next
' Checking 'newest' file - we need to process all files in the folder.
If MaxAgeFileType = "newest" Then
If newestTime <= DateAdd(DateInterval.Second, -MaxAgeThreshold, Now()) Then
StatusMessage = FormatStatusMessage(newestTime, MaxAgeDateType, MaxAgeAgeType) & _
vbCrLf & newestFile.FullName
myStatus = MonitorExecutor.MonitorStatus.Fail
IsOK = False
End If
End If
myFile = Nothing
End If
If IsOK Then 'keep checking for FileCounts (if enabled)
Dim IsWarn As Boolean = False
Dim IsMax As Boolean = False
If WarnCountEnabled AndAlso (FileCount > WarnCountThreshold) Then IsWarn = True
If MaxCountEnabled AndAlso (FileCount > MaxCountThreshold) Then IsMax = True
If IsMax Then
'Max threshold reached...
myStatus = MonitorExecutor.MonitorStatus.Fail
StatusMessage = "Maximum File Count exceeded: Total Count=" & CStr(FileCount)
ElseIf IsWarn Then
myStatus = MonitorExecutor.MonitorStatus.Warn
StatusMessage = "Warning File Count exceeded: Total Count=" & CStr(FileCount)
Else
myStatus = MonitorExecutor.MonitorStatus.OK
StatusMessage = "OK. Total Count=" & CStr(FileCount)
End If
End If
myFiles = Nothing
Catch ex As Exception
myStatus = MonitorExecutor.MonitorStatus.Fail
StatusMessage = "Monitor Exception: " & vbCrLf & ex.Message
End Try
Return myStatus
End Function
Private Function ReadXMLNodeValue(ByVal myXMLNode As XmlNode) As String
If myXMLNode Is Nothing Then
Return Nothing
Else
If myXMLNode Is Nothing OrElse myXMLNode.InnerXml = Nothing Then
Return Nothing
Else
Return myXMLNode.InnerXml.Trim()
End If
End If
End Function
Private Function ReadXMLAttributeValue(ByVal myXMLAttribute As XmlAttribute) As String
If myXMLAttribute Is Nothing Then
Return Nothing
Else
If myXMLAttribute.Value Is Nothing OrElse myXMLAttribute.Value.Trim() = "" Then
Return Nothing
Else
Return myXMLAttribute.Value.Trim()
End If
End If
End Function
Private Function FormatStatusMessage(ByVal checkTime As DateTime, ByVal dateType As String, ByVal ageType As String) As String
Dim checkAge As Double
Select Case ageType
Case "minutes"
checkAge = Now.Subtract(checkTime).TotalMinutes
Case "hours"
checkAge = Now.Subtract(checkTime).TotalHours
Case "days"
checkAge = Now.Subtract(checkTime).TotalDays
Case Else
checkAge = Now.Subtract(checkTime).TotalSeconds
End Select
Return String.Format("File found with a {0} timestamp of: {1:MM/dd/yyyy hh:mm:ss tt} ({2:F} {3} ago)", dateType, checkTime, checkAge, ageType)
End Function
End Class
End Namespace |
'
' Copyright (c) Clevergy
'
' The SOFTWARE, as well as the related copyrights and intellectual property rights, are the exclusive property of Clevergy srl.
' Licensee acquires no title, right or interest in the SOFTWARE other than the license rights granted herein.
'
' conceived and developed by Marco Fagnano (D.R.T.C.)
' il software è ricorsivo, nel tempo rigenera se stesso.
'
Imports System
Imports System.Collections.Generic
Imports SF.DAL
Imports System.IO
Imports Microsoft.AspNet.SignalR
Namespace SF.BLL
Public Class SolarSystem
#Region "constructor"
Public Sub New()
Me.New(0, String.Empty, 0, 0, 0, 0, String.Empty, String.Empty, String.Empty, FormatDateTime("01/01/1900", DateFormat.GeneralDate), 0, 0)
End Sub
Public Sub New(m_hsId As Integer, _
m_IdImpianto As String, _
m_NominalCapacity As Decimal, _
m_Panels As Integer, _
m_Stringboxes As Integer, _
m_Inverters As Integer, _
m_PowerSupplyType As String, _
m_LineType As String, _
m_marcamodello As String, _
m_installationDate As Date, _
m_Latitude As Decimal, _
m_Longitude As Decimal)
hsId = m_hsId
IdImpianto = m_IdImpianto
NominalCapacity = m_NominalCapacity
Panels = m_Panels
Stringboxes = m_Stringboxes
Inverters = m_Inverters
PowerSupplyType = m_PowerSupplyType
LineType = m_LineType
marcamodello = m_marcamodello
installationDate = m_installationDate
Latitude = m_Latitude
Longitude = m_Longitude
End Sub
#End Region
#Region "methods"
Public Shared Function Add(hsId As Integer, _
IdImpianto As String, _
NominalCapacity As Decimal, _
Panels As Integer, _
Stringboxes As Integer, _
Inverters As Integer, _
PowerSupplyType As String, _
LineType As String, _
marcamodello As String, _
installationDate As Date, _
UserName As String) As Boolean
Dim retVal As Boolean = False
retVal = DataAccessHelper.GetDataAccess.SolarSystem_Add(hsId, _
IdImpianto, _
NominalCapacity, _
Panels, _
Stringboxes, _
Inverters, _
PowerSupplyType, _
LineType, _
marcamodello, _
installationDate, _
UserName)
If retVal = True Then
Dim m_clientsHub = GlobalHost.ConnectionManager.GetHubContext(Of SF.clientsHub)()
m_clientsHub.Clients.Group(IdImpianto).received_SolarSystem_Add(hsId)
m_clientsHub = Nothing
End If
Return retVal
End Function
Public Shared Function Del(hsId As Integer) As Boolean
If hsId <= 0 Then
Return False
End If
Dim IdImpianto As String = String.Empty
Dim _s As SF.BLL.SolarSystem = DataAccessHelper.GetDataAccess.SolarSystem_Read(hsId)
If Not _s Is Nothing Then
IdImpianto = _s.IdImpianto
_s = Nothing
End If
Dim retVal As Boolean = False
retVal = DataAccessHelper.GetDataAccess.SolarSystem_Del(hsId)
If retVal = True Then
If Not String.IsNullOrEmpty(IdImpianto) Then
Dim m_clientsHub = GlobalHost.ConnectionManager.GetHubContext(Of SF.clientsHub)()
m_clientsHub.Clients.Group(IdImpianto).received_SolarSystem_Del(hsId)
m_clientsHub = Nothing
End If
End If
Return retVal
End Function
Public Shared Function List(IdImpianto As String) As List(Of SolarSystem)
If String.IsNullOrEmpty(IdImpianto) Then
Return Nothing
End If
Return DataAccessHelper.GetDataAccess.SolarSystem_List(IdImpianto)
End Function
Public Shared Function ListAll() As List(Of SolarSystem)
Return DataAccessHelper.GetDataAccess.SolarSystem_ListAll()
End Function
Public Shared Function Read(hsId As Integer) As SolarSystem
If hsId <= 0 Then
Return Nothing
End If
Return DataAccessHelper.GetDataAccess.SolarSystem_Read(hsId)
End Function
Public Shared Function Update(hsId As Integer, _
IdImpianto As String, _
NominalCapacity As Decimal, _
Panels As Integer, _
Stringboxes As Integer, _
Inverters As Integer, _
PowerSupplyType As String, _
LineType As String, _
marcamodello As String, _
installationDate As Date, _
UserName As String) As Boolean
If hsId <= 0 Then
Return False
End If
Dim retVal As Boolean = False
Dim _obj As SF.BLL.SolarSystem = SF.BLL.SolarSystem.Read(hsId)
If _obj Is Nothing Then
retVal = DataAccessHelper.GetDataAccess.SolarSystem_Add(hsId, IdImpianto, NominalCapacity, Panels, Stringboxes, Inverters, PowerSupplyType, LineType, marcamodello, installationDate, UserName)
Else
_obj = Nothing
retVal = DataAccessHelper.GetDataAccess.SolarSystem_Update(hsId, IdImpianto, NominalCapacity, Panels, Stringboxes, Inverters, PowerSupplyType, LineType, marcamodello, installationDate, UserName)
End If
If retVal = True Then
Dim m_clientsHub = GlobalHost.ConnectionManager.GetHubContext(Of SF.clientsHub)()
m_clientsHub.Clients.Group(IdImpianto).received_SolarSystem_Udate(hsId)
m_clientsHub = Nothing
End If
Return retVal
End Function
Public Shared Function setGeoLocation(hsId As Integer, Latitude As Decimal, Longitude As Decimal)
If hsId <= 0 Then Return False
Return DataAccessHelper.GetDataAccess.SolarSystem_setGeoLocation(hsId, Latitude, Longitude)
End Function
Public Shared Function setInvPVpowerErrCounter(hsId As Integer, InvPVpowerErrCounter As Integer) As Boolean
If hsId <= 0 Then Return False
Return DataAccessHelper.GetDataAccess.SolarSystem_setInvPVpowerErrCounter(hsId, InvPVpowerErrCounter)
End Function
Public Shared Function getInvPVpowerErrCounter(hsId As Integer) As Integer
If hsId <= 0 Then Return False
Return DataAccessHelper.GetDataAccess.SolarSystem_getInvPVpowerErrCounter(hsId)
End Function
#End Region
#Region "public properties"
Public Property hsId As Integer
Public Property IdImpianto As String
Public Property NominalCapacity As Decimal
Public Property Panels As Integer
Public Property Stringboxes As Integer
Public Property Inverters As Integer
Public Property PowerSupplyType As String
Public Property LineType As String
Public Property marcamodello As String
Public Property installationDate As Date
Public Property Latitude As Decimal
Public Property Longitude As Decimal
#End Region
End Class
End Namespace
|
' NOTA: puede usar el comando "Cambiar nombre" del menú contextual para cambiar el nombre de clase "Service1" en el código, en svc y en el archivo de configuración.
' NOTA: para iniciar el Cliente de prueba WCF para probar este servicio, seleccione Service1.svc o Service1.svc.vb en el Explorador de soluciones e inicie la depuración.
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.ServiceModel.Web
Imports System.Text
Public Class ServiceMotivoDevolucionBodega
Implements IServiceMotivoDevolucionBodega
Public Function ActualizarDatos(ByVal pObjMD As clsBeMotivo_devolucion, ByVal pListObjMDB As List(Of clsBeMotivo_devolucion_bodega)) As Boolean Implements IServiceMotivoDevolucionBodega.ActualizaDatos
Dim lConnection As New SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings("CST"))
Dim lTransaction As SqlClient.SqlTransaction = Nothing
Dim ObjMD As New clsLnMotivo_devolucion()
Dim ObjMDB As New clsLnMotivo_devolucion_bodega()
Try
lConnection.Open()
lTransaction = lConnection.BeginTransaction()
ObjMD.Actualizar(pObjMD, lConnection, lTransaction)
Dim lMax As Integer = clsLnMotivo_devolucion_bodega.MaxID()
For Each Obj As clsBeMotivo_devolucion_bodega In pListObjMDB
If Obj.IdMotivoDevolucionBodega = 0 Then
lMax += 1
Obj.IdMotivoDevolucionBodega = lMax
ObjMDB.Insertar(Obj, lConnection, lTransaction)
Else
ObjMDB.Actualizar(Obj, lConnection, lTransaction)
End If
Next
lTransaction.Commit()
lConnection.Close()
Return True
Catch ex As Exception
lTransaction.Rollback()
lConnection.Close()
Throw ex
End Try
End Function
Public Function GetAllByMotivoDevolucion(ByVal pIdMotivoDevolucion As Integer) As List(Of clsBeMotivo_devolucion_bodega) Implements IServiceMotivoDevolucionBodega.GetAllByMotivoDevolucion
Try
Dim List As New List(Of clsBeMotivo_devolucion_bodega)
List = clsLnMotivo_devolucion_bodega.GetAllByMotivoDevolucion(pIdMotivoDevolucion)
Return List.ToList()
Catch ex As Exception
Throw ex
End Try
End Function
End Class
|
Imports System.Xml.Serialization
Namespace Entities
Public Class ValidationRuleSetting
<XmlAttribute()> _
Public Property Id() As String
<XmlText()> _
Public Property Description() As String
<XmlAttribute()> _
Public Property IsEnabled() As Boolean
'<XmlAttribute()> _
'Public Property IsConfigurable() As Boolean
Public Const KEY = "Id"
End Class
End Namespace |
Public Class Form2
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
End Sub
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Function Collision(p As PictureBox, t As String, Optional ByRef other As Object = vbNull)
Dim col As Boolean
For Each c In Controls
Dim obj As Control
obj = c
If obj.Visible AndAlso p.Bounds.IntersectsWith(obj.Bounds) And obj.Name.ToUpper.Contains(t.ToUpper) Then
col = True
other = obj
End If
Next
Return col
End Function
Function IsClear(p As PictureBox, distx As Integer, disty As Integer, t As String) As Boolean
Dim b As Boolean
p.Location += New Point(distx, disty)
b = Not Collision(p, t)
p.Location -= New Point(distx, disty)
Return b
End Function
Sub MoveTo(p As PictureBox, distx As Integer, disty As Integer)
If IsClear(p, distx, disty, "WALL") Then
p.Location += New Point(distx, disty)
End If
End Sub
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
Select Case e.KeyCode
Case Keys.R
crash.Image.RotateFlip(RotateFlipType.Rotate90FlipX)
Me.Refresh()
Case Keys.Up
MoveTo(crash, 0, -40)
Case Keys.Down
MoveTo(crash, 0, 40)
Case Keys.Left
MoveTo(crash, -40, 0)
Case Keys.Right
MoveTo(crash, 40, 0)
Case Keys.Space
End Select
End Sub
End Class |
#Region "Microsoft.VisualBasic::904b341c3a1551df1c36aae0458346fa, mzkit\src\visualize\plot\ChromatogramPlot\TICplot.vb"
' Author:
'
' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.)
'
' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD.
'
'
' MIT License
'
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
' /********************************************************************************/
' Summaries:
' Code Statistics:
' Total Lines: 336
' Code Lines: 274
' Comment Lines: 10
' Blank Lines: 52
' File Size: 13.24 KB
' Class TICplot
'
' Constructor: (+1 Overloads) Sub New
'
' Function: colorProvider, GetLabels, newPen
'
' Sub: DrawLabels, DrawTICLegends, PlotInternal, RunPlot
'
' /********************************************************************************/
#End Region
Imports System.Drawing
Imports System.Runtime.CompilerServices
Imports BioNovoGene.Analytical.MassSpectrometry.Math
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Chromatogram
Imports Microsoft.VisualBasic.ComponentModel.Algorithm.base
Imports Microsoft.VisualBasic.ComponentModel.DataSourceModel
Imports Microsoft.VisualBasic.ComponentModel.DataStructures
Imports Microsoft.VisualBasic.Data.ChartPlots.Graphic
Imports Microsoft.VisualBasic.Data.ChartPlots.Graphic.Axis
Imports Microsoft.VisualBasic.Data.ChartPlots.Graphic.Canvas
Imports Microsoft.VisualBasic.Data.ChartPlots.Graphic.Legend
Imports Microsoft.VisualBasic.Imaging
Imports Microsoft.VisualBasic.Imaging.d3js
Imports Microsoft.VisualBasic.Imaging.d3js.Layout
Imports Microsoft.VisualBasic.Imaging.Drawing2D
Imports Microsoft.VisualBasic.Imaging.Drawing2D.Colors
Imports Microsoft.VisualBasic.Language
Imports Microsoft.VisualBasic.Linq
Imports Microsoft.VisualBasic.Math
Imports Microsoft.VisualBasic.Math.Interpolation
Imports Microsoft.VisualBasic.MIME.Html.CSS
Public Class TICplot : Inherits Plot
ReadOnly ionData As NamedCollection(Of ChromatogramTick)()
ReadOnly timeRange As Double() = Nothing
ReadOnly intensityMax As Double = 0
ReadOnly isXIC As Boolean
ReadOnly fillCurve As Boolean
ReadOnly fillAlpha As Integer
ReadOnly labelLayoutTicks As Integer = 100
ReadOnly deln As Integer = 10
ReadOnly bspline As Single = 0!
''' <summary>
''' 当两个滑窗点的时间距离过长的时候,就不进行连接线的绘制操作了
''' (插入两个零值的点)
''' </summary>
ReadOnly leapTimeWinSize As Double = 30
Public Sub New(ionData As NamedCollection(Of ChromatogramTick)(),
timeRange As Double(),
intensityMax As Double,
isXIC As Boolean,
fillCurve As Boolean,
fillAlpha As Integer,
labelLayoutTicks As Integer,
deln As Integer,
bspline As Single,
theme As Theme)
MyBase.New(theme)
Me.isXIC = isXIC
Me.intensityMax = intensityMax
Me.ionData = ionData
Me.fillCurve = fillCurve
Me.fillAlpha = fillAlpha
Me.labelLayoutTicks = labelLayoutTicks
Me.deln = deln
Me.bspline = bspline
If timeRange Is Nothing Then
Me.timeRange = {}
Else
Me.timeRange = timeRange
End If
End Sub
Private Function newPen(c As Color) As Pen
Dim style As Stroke = Stroke.TryParse(theme.lineStroke)
style.fill = c.ARGBExpression
Return style.GDIObject
End Function
Private Function colorProvider() As LoopArray(Of Pen)
If ionData.Length = 1 Then
Return {newPen(theme.colorSet.TranslateColor(False) Or Color.DeepSkyBlue.AsDefault)}
Else
Return Designer _
.GetColors(theme.colorSet) _
.Select(AddressOf newPen) _
.ToArray
End If
End Function
<MethodImpl(MethodImplOptions.AggressiveInlining)>
Protected Overrides Sub PlotInternal(ByRef g As IGraphics, canvas As GraphicsRegion)
Call RunPlot(g, canvas, Nothing, Nothing)
End Sub
Friend Sub RunPlot(ByRef g As IGraphics, canvas As GraphicsRegion, ByRef labels As Label(), ByRef legends As LegendObject())
Dim colors As LoopArray(Of Pen) = colorProvider()
Dim XTicks As Double() = ionData _
.Select(Function(ion)
Return ion.value.TimeArray
End Function) _
.IteratesALL _
.JoinIterates(timeRange) _
.AsVector _
.Range _
.CreateAxisTicks ' time
Dim YTicks = ionData _
.Select(Function(ion)
Return ion.value.IntensityArray
End Function) _
.IteratesALL _
.JoinIterates({intensityMax}) _
.AsVector _
.Range _
.CreateAxisTicks ' intensity
' make bugs fixed of all intensity value is zero
If YTicks.Length = 0 Then
YTicks = {0, 100}
End If
Dim rect As Rectangle = canvas.PlotRegion
Dim X = d3js.scale.linear.domain(values:=XTicks).range(integers:={rect.Left, rect.Right})
Dim Y = d3js.scale.linear.domain(values:=YTicks).range(integers:={rect.Top, rect.Bottom})
Dim scaler As New DataScaler With {
.AxisTicks = (XTicks, YTicks),
.region = rect,
.X = X,
.Y = Y
}
If theme.drawAxis Then
Call g.DrawAxis(
canvas, scaler, showGrid:=theme.drawGrid,
xlabel:=Me.xlabel,
ylabel:=Me.ylabel,
htmlLabel:=False,
XtickFormat:=If(isXIC, "F2", "F0"),
YtickFormat:="G2",
labelFont:=theme.axisLabelCSS,
tickFontStyle:=theme.axisTickCSS,
gridFill:=theme.gridFill,
xlayout:=theme.xAxisLayout,
ylayout:=theme.yAxisLayout,
axisStroke:=theme.axisStroke
)
End If
Dim peakTimes As New List(Of NamedValue(Of ChromatogramTick))
Dim fillColor As Brush
Dim legendList As New List(Of LegendObject)
For i As Integer = 0 To ionData.Length - 1
Dim curvePen As Pen = colors.Next
Dim line = ionData(i)
Dim chromatogram = line.value
If chromatogram.IsNullOrEmpty Then
Call $"ion not found in raw file: '{line.name}'".Warning
Continue For
ElseIf bspline > 0 Then
Dim raw As PointF() = chromatogram.Select(Function(t) New PointF(t.Time, t.Intensity)).ToArray
Dim interpolate = B_Spline.BSpline(raw, bspline, 10).ToArray
chromatogram = interpolate _
.Select(Function(pi)
Return New ChromatogramTick With {
.Time = pi.X,
.Intensity = pi.Y
}
End Function) _
.ToArray
End If
legendList += New LegendObject With {
.title = line.name,
.color = curvePen.Color.ToHtmlColor,
.fontstyle = theme.legendLabelCSS,
.style = LegendStyles.Rectangle
}
If theme.drawLabels Then
Dim data As New MzGroup With {.mz = 0, .XIC = chromatogram}
Dim peaks = data.GetPeakGroups(New Double() {5, 60}).ToArray
peakTimes += From ROI As PeakFeature
In peaks
Select New NamedValue(Of ChromatogramTick) With {
.Name = ROI.rt.ToString("F1"),
.Value = New ChromatogramTick With {.Intensity = ROI.maxInto, .Time = ROI.rt}
}
End If
Dim bottom% = canvas.Bottom - 6
Dim viz = g
Dim polygon As New List(Of PointF)
Dim draw = Sub(t1 As ChromatogramTick, t2 As ChromatogramTick)
Dim A = scaler.Translate(t1.Time, t1.Intensity)
Dim B = scaler.Translate(t2.Time, t2.Intensity)
Call viz.DrawLine(curvePen, A, B)
If polygon = 0 Then
polygon.Add(New PointF(A.X, bottom))
polygon.Add(A)
End If
polygon.Add(B)
End Sub
For Each signal As SlideWindow(Of ChromatogramTick) In chromatogram.SlideWindows(winSize:=2)
Dim dt As Double = signal.Last.Time - signal.First.Time
If dt > leapTimeWinSize Then
' add zero point
If dt > leapTimeWinSize Then
dt = leapTimeWinSize / 2
Else
dt = dt / 2
End If
Dim i1 As New ChromatogramTick With {.Time = signal.First.Time + dt, .Intensity = 0}
Dim i2 As New ChromatogramTick With {.Time = signal.Last.Time - dt, .Intensity = 0}
Call draw(signal.First, i1)
polygon.Add(New PointF(polygon.Last.X, bottom))
If fillCurve Then
fillColor = New SolidBrush(Color.FromArgb(fillAlpha, curvePen.Color))
g.FillPolygon(fillColor, polygon)
End If
polygon.Clear()
Call draw(i2, signal.Last)
Else
Call draw(signal.First, signal.Last)
End If
Next
polygon.Add(New PointF(polygon.Last.X, bottom))
If fillCurve Then
fillColor = New SolidBrush(Color.FromArgb(fillAlpha, curvePen.Color))
g.FillPolygon(fillColor, polygon)
End If
Next
legends = legendList
labels = GetLabels(g, scaler, peakTimes).ToArray
If theme.drawLabels Then Call DrawLabels(g, rect, labels, theme, labelLayoutTicks)
If theme.drawLegend Then Call DrawTICLegends(g, canvas, legends, deln, outside:=False)
End Sub
Private Iterator Function GetLabels(g As IGraphics, scaler As DataScaler, peakTimes As IEnumerable(Of NamedValue(Of ChromatogramTick))) As IEnumerable(Of Label)
Dim labelFont As Font = CSSFont.TryParse(theme.tagCSS).GDIObject(g.Dpi)
For Each ion As NamedValue(Of ChromatogramTick) In peakTimes
Dim labelSize As SizeF = g.MeasureString(ion.Name, labelFont)
Dim location As PointF = scaler.Translate(ion.Value)
location = New PointF With {
.X = location.X - labelSize.Width / 2,
.Y = location.Y - labelSize.Height * 1.0125
}
Yield New Label With {
.height = labelSize.Height,
.width = labelSize.Width,
.text = ion.Name,
.X = location.X,
.Y = location.Y
}
Next
End Function
Friend Shared Sub DrawLabels(g As IGraphics, rect As Rectangle, labels As Label(), theme As Theme, labelLayoutTicks As Integer)
Dim labelFont As Font = CSSFont.TryParse(theme.tagCSS).GDIObject(g.Dpi)
Dim labelConnector As Pen = Stroke.TryParse(theme.tagLinkStroke)
Dim anchors As Anchor() = labels.GetLabelAnchors(r:=3)
If labelLayoutTicks > 0 Then
Call d3js.labeler(maxAngle:=5, maxMove:=300, w_lab2:=100, w_lab_anc:=100) _
.Labels(labels) _
.Anchors(anchors) _
.Width(rect.Width) _
.Height(rect.Height) _
.Start(showProgress:=False, nsweeps:=labelLayoutTicks)
End If
Dim labelBrush As Brush = theme.tagColor.GetBrush
For Each i As SeqValue(Of Label) In labels.SeqIterator
If labelLayoutTicks > 0 Then
Call g.DrawLine(labelConnector, i.value.GetTextAnchor(anchors(i)), anchors(i))
End If
Call g.DrawString(i.value.text, labelFont, labelBrush, i.value)
Next
End Sub
Friend Shared Sub DrawTICLegends(g As IGraphics, canvas As GraphicsRegion, legends As LegendObject(), deln As Integer, outside As Boolean)
' 如果离子数量非常多的话,则会显示不完
' 这时候每20个换一列
Dim cols = legends.Length / deln
If cols > Fix(cols) Then
' 有余数,说明还有剩下的,增加一列
cols += 1
End If
' 计算在右上角的位置
Dim maxSize As SizeF = legends.MaxLegendSize(g)
Dim top = canvas.PlotRegion.Top + maxSize.Height + 5
Dim maxLen = maxSize.Width
Dim legendShapeWidth% = 70
Dim left As Double
If outside Then
left = canvas.PlotRegion.Right + g.MeasureString("A", legends(Scan0).GetFont(g.Dpi)).Width
Else
left = canvas.PlotRegion.Right - (maxLen + legendShapeWidth) * cols
End If
Dim position As New Point With {
.X = left,
.Y = top
}
For Each block As LegendObject() In legends.Split(deln)
g.DrawLegends(position, block, $"{legendShapeWidth},10", d:=0)
position = New Point With {
.X = position.X + maxLen + legendShapeWidth,
.Y = position.Y
}
Next
End Sub
End Class
|
Imports Talent.Common.DataObjects.TableObjects
Namespace DataObjects
''' <summary>
''' Class provides the functionality to access Delivery tables objects
''' </summary>
<Serializable()> _
Public Class Delivery
#Region "Class Level Fields"
''' <summary>
''' DESettings Instance
''' </summary>
Private _settings As New DESettings
Private _tblCarrier As tbl_carrier
Private _tblDeliveryUnavailableDates As tbl_delivery_unavailable_dates
#End Region
#Region "Constructors"
Sub New()
End Sub
''' <summary>
''' Initializes a new instance of the <see cref="Delivery" /> class.
''' </summary>
''' <param name="settings">DESettings Instance</param>
Sub New(ByVal settings As DESettings)
_settings = settings
End Sub
#End Region
#Region "Properties"
''' <summary>
''' Create and Gets the tbl_carrier instance with DESettings
''' </summary>
''' <value></value>
Public ReadOnly Property TblCarrier() As tbl_carrier
Get
If (_tblCarrier Is Nothing) Then
_tblCarrier = New tbl_carrier(_settings)
End If
Return _tblCarrier
End Get
End Property
''' <summary>
''' Create and Gets the tbl_delivery_unavailable_dates instance with DESettings
''' </summary>
''' <value></value>
Public ReadOnly Property TblDeliveryUnavailableDates() As tbl_delivery_unavailable_dates
Get
If (_tblDeliveryUnavailableDates Is Nothing) Then
_tblDeliveryUnavailableDates = New tbl_delivery_unavailable_dates(_settings)
End If
Return _tblDeliveryUnavailableDates
End Get
End Property
#End Region
End Class
End Namespace |
Public Enum internalEnum
PROGRAM_ERROR
LOGIN
HANDSHAKE_STATE
HANDSHAKE_LOG ' especially used in ptp
VERSION 'version code
GENERIC_MESSAGE
End Enum
|
Option Explicit On
Option Strict On
' // *** Includes *** //
' // General
Imports System.Text
' // *** Class Definition *** //
Public Class WebsiteImage
#Region "WebsiteImage - Data Members"
Protected m_intImageID As Integer
#End Region
#Region "WebsiteImage - Constructors"
Public Sub New()
End Sub
Public Sub New(
ByVal intImageID As Integer
)
Me.m_intImageID = intImageID
End Sub
#End Region
#Region "WebsiteImage - Properties"
Public ReadOnly Property ImageID As Integer
Get
Return (Me.m_intImageID)
End Get
End Property
#End Region
#Region "WebsiteImage - Methods"
#End Region
#Region "WebsiteImage - Methods - Helpers"
#End Region
End Class
|
Public Class Route
Private isle1 As Isle
Private isle2 As Isle
Private Quality As Integer
Public Sub New(ByVal i1 As Isle, ByVal i2 As Isle, ByVal aQuality As Integer)
isle1 = i1
isle2 = i2
Quality = aQuality
End Sub
Public Shared Operator =(ByVal r1 As Route, ByVal r2 As Route)
If r1.isle1 <> r2.isle1 AndAlso r1.isle1 <> r2.isle2 Then Return False
If r1.isle2 <> r2.isle1 AndAlso r1.isle2 <> r2.isle2 Then Return False
Return True
End Operator
Public Shared Operator <>(ByVal r1 As Route, ByVal r2 As Route)
If r1 = r2 Then Return False Else Return True
End Operator
Public Shared Operator -(ByVal route As Route, ByVal isle As Isle) As Isle
If route.isle1 = isle Then Return route.isle2
If route.isle2 = isle Then Return route.isle1
Return Nothing
End Operator
Public Shared Operator >(ByVal i As Integer, ByVal route As Route) As Boolean
If i > route.Quality Then Return True Else Return False
End Operator
Public Shared Operator <(ByVal i As Integer, ByVal route As Route) As Boolean
If i < route.Quality Then Return True Else Return False
End Operator
Public Shared Operator +(ByVal route As Route, ByVal i As Integer) As Route
Return New Route(route.isle1, route.isle2, route.Quality + i)
End Operator
Public Function Contains(ByVal isle As Isle) As Boolean
If isle1 = isle OrElse isle2 = isle Then Return True
Return False
End Function
Public Function GetDistance() As Double
Dim modifier As Double
Select Case Quality
Case 0 : modifier = 2
Case 1 : modifier = 1.75
Case 2 : modifier = 1.5
Case 3 : modifier = 1.25
Case 4 : modifier = 1
Case 5 : modifier = 0.75
Case Else : Throw New Exception("Route quality out of range")
End Select
'pythogoras theorem
Dim dx As Integer = Math.Abs(isle1.X - isle2.X)
Dim dy As Integer = Math.Abs(isle1.Y - isle2.Y)
Dim c As Double = Math.Sqrt((dx * dx) + (dy * dy))
Dim total As Double = Math.Round(c * modifier, 2)
Return total
End Function
Public Overrides Function ToString() As String
Return isle1.Name & " - " & isle2.Name
End Function
End Class
|
Public Class pendientesEn
Private id As Integer
Private codigo As String
Private descripcion As String
Private valorUn As Integer
Public Property idPrendiente()
Get
Return Me.id
End Get
Set(ByVal value)
id = value
End Set
End Property
Public Property codigoPendiente()
Get
Return Me.codigo
End Get
Set(ByVal value)
codigo = value
End Set
End Property
Public Property descripcionPendiente()
Get
Return Me.descripcion
End Get
Set(ByVal value)
descripcion = value
End Set
End Property
Public Property valorUnitarioPrendiente()
Get
Return Me.valorUn
End Get
Set(ByVal value)
valorUn = CInt(value)
End Set
End Property
End Class
|
Namespace Classes
Public Class Suppliers
Public Property SupplierIdentifier() As Integer
Public Property CompanyName() As String
Public Property ContactName() As String
End Class
End Namespace
|
Namespace WorkingWithResourceAssignments
Public Class GenerateResourceAssignmentTimephasedData
Public Shared Sub Run()
' The path to the documents directory.
Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName)
' ExStart:GenerateResourceAssignmentTimephasedData
' Create project instance
Dim project1 As New Project(dataDir + "ResourceAssignmentTimephasedData.mpp")
' Get the first task of the Project
Dim task As Task = project1.RootTask.Children.GetById(1)
' Get the First Resource Assignment of the Project
Dim firstRA As ResourceAssignment = project1.ResourceAssignments.ToList()(0)
' Flat contour is default contour
Console.WriteLine("Flat contour")
Dim td As TimephasedData
Dim tdList = task.GetTimephasedData(project1.Get(Prj.StartDate), project1.Get(Prj.FinishDate))
For Each td In tdList
Console.WriteLine(td.Start.ToShortDateString() + " " + td.Value)
Next
' Change contour
firstRA.Set(Asn.WorkContour, WorkContourType.Turtle)
Console.WriteLine("Turtle contour")
tdList = task.GetTimephasedData(project1.Get(Prj.StartDate), project1.Get(Prj.FinishDate))
For Each td In tdList
Console.WriteLine(td.Start.ToShortDateString() + " " + td.Value)
Next
' Change contour
firstRA.Set(Asn.WorkContour, WorkContourType.BackLoaded)
Console.WriteLine("BackLoaded contour")
tdList = task.GetTimephasedData(project1.Get(Prj.StartDate), project1.Get(Prj.FinishDate))
For Each td In tdList
Console.WriteLine(td.Start.ToShortDateString() + " " + td.Value)
Next
' Change contour
firstRA.Set(Asn.WorkContour, WorkContourType.FrontLoaded)
Console.WriteLine("FrontLoaded contour")
tdList = task.GetTimephasedData(project1.Get(Prj.StartDate), project1.Get(Prj.FinishDate))
For Each td In tdList
Console.WriteLine(td.Start.ToShortDateString() + " " + td.Value)
Next
' Change contour
firstRA.Set(Asn.WorkContour, WorkContourType.Bell)
Console.WriteLine("Bell contour")
tdList = task.GetTimephasedData(project1.Get(Prj.StartDate), project1.Get(Prj.FinishDate))
For Each td In tdList
Console.WriteLine(td.Start.ToShortDateString() + " " + td.Value)
Next
' Change contour
firstRA.Set(Asn.WorkContour, WorkContourType.EarlyPeak)
Console.WriteLine("EarlyPeak contour")
tdList = task.GetTimephasedData(project1.Get(Prj.StartDate), project1.Get(Prj.FinishDate))
For Each td In tdList
Console.WriteLine(td.Start.ToShortDateString() + " " + td.Value)
Next
' Change contour
firstRA.Set(Asn.WorkContour, WorkContourType.LatePeak)
Console.WriteLine("LatePeak contour")
tdList = task.GetTimephasedData(project1.Get(Prj.StartDate), project1.Get(Prj.FinishDate))
For Each td In tdList
Console.WriteLine(td.Start.ToShortDateString() + " " + td.Value)
Next
' Change contour
firstRA.Set(Asn.WorkContour, WorkContourType.DoublePeak)
Console.WriteLine("DoublePeak contour")
tdList = task.GetTimephasedData(project1.Get(Prj.StartDate), project1.Get(Prj.FinishDate))
For Each td In tdList
Console.WriteLine(td.Start.ToShortDateString() + " " + td.Value)
Next
' ExEnd:GenerateResourceAssignmentTimephasedData
End Sub
End Class
End Namespace |
Imports System.Threading
'''-----------------------------------------------------------------------------
''' Project : DOTUCPEMI
''' Class : SMSClient
'''
'''-----------------------------------------------------------------------------
''' <summary>To simply thins use this class to easyly send and recieve SMS messages</summary>
''' <remarks></remarks>
''' <history>
''' [bofh] 06-02-2003 Created
''' </history>
'''-----------------------------------------------------------------------------
Public Class SMSClient
'''-----------------------------------------------------------------------------
''' <summary>This event triggers when these debug information. use when looking for errors</summary>
''' <param name="msg">debug messages</param>
''' <remarks></remarks>
'''-----------------------------------------------------------------------------
Public Event onDebug(ByVal msg As String)
'''-----------------------------------------------------------------------------
''' <summary>most SMSC dont allow continually connections, and will disconnect
''' clients after 5-10 minuts. this options lets SMSClient handle this for you
''' by automatily reconnect if we have been disconnected.
''' this value will be automatily set to false if we get an authentication error </summary>
'''-----------------------------------------------------------------------------
Public autoReconnect As Boolean = True
Private priv_username As String = ""
Private priv_password As String = ""
Private pre_SMSC_Host As String = ""
Private priv_SMSC_port As Integer = 0
'''-----------------------------------------------------------------------------
''' <summary>This event fires if we get disconnected from the SMSC</summary>
''' <remarks></remarks>
'''-----------------------------------------------------------------------------
Public Event onDisconnect()
'''-----------------------------------------------------------------------------
''' <summary>This event fires when we have successfully connected to the SMSC</summary>
''' <remarks></remarks>
'''-----------------------------------------------------------------------------
Public Event onConnect()
'''-----------------------------------------------------------------------------
''' <summary>This event fires, if SMSC accepts login our login credentials</summary>
''' <remarks></remarks>
'''-----------------------------------------------------------------------------
Public Event login_success()
'''-----------------------------------------------------------------------------
''' <summary>This event fires if we gets rejected with our credentials</summary>
''' <param name="reason"></param>
''' <remarks></remarks>
'''-----------------------------------------------------------------------------
Public Event login_failed(ByVal reason As String)
Public Event msg_recv(ByVal packet As UCPPacket)
''' <summary>This event fires, if SMSC accepts login our login credentials</summary>
''' <remarks></remarks>
'''-----------------------------------------------------------------------------
Public Event send_keep_alive()
'''-----------------------------------------------------------------------------
''' <summary>Have we ben authenticatede by the SMSC successfully ?</summary>
''' <value></value>
''' <remarks>ignore this, if your account/smsc does not need to be authenticated</remarks>
''' <history>
''' [bofh] 06-02-2003 Created
''' </history>
'''-----------------------------------------------------------------------------
Public ReadOnly Property isAuthenticated() As Boolean
Get
Return authenticated
End Get
End Property
Private WithEvents ClientSocket As UCPSocket
Private WithEvents ClientListener As UCPListener
Private authenticated As Boolean = False
'''-----------------------------------------------------------------------------
''' <summary>Are we connected to the SMSC. Dont use externally </summary>
''' <value></value>
''' <remarks>this property automaticly resumes connection with SMSC if
''' you have set autoReconnect to True ( its the default )</remarks>
''' <history>
''' [bofh] 06-02-2003 Created
''' </history>
'''-----------------------------------------------------------------------------
Public ReadOnly Property connected() As Boolean
Get
If Not ClientSocket.connected And autoReconnect Then
Reconnect(pre_SMSC_Host, priv_SMSC_port)
'ClientSocket.disconnect()
If priv_username <> "" And priv_password <> "" Then
login(priv_username, priv_password)
RaiseEvent onDebug("disconnected, so reconningting, with login")
Else
RaiseEvent onDebug("disconnected, so reconningting")
End If
End If
Return ClientSocket.connected
End Get
End Property
'''-----------------------------------------------------------------------------
''' <summary>converts and ip and port, to something the smsc understands</summary>
''' <param name="Ip">the ip address</param>
''' <param name="port">the port</param>
''' <returns>an encoded string of ip and port</returns>
''' <remarks></remarks>
''' <history>
''' [bofh] 09-02-2004 Created
''' </history>
'''-----------------------------------------------------------------------------
Public Function encodeIpAndPort(ByVal Ip As String, ByVal port As Integer) As String
Return encodeIpPort(Ip, port)
End Function
'''-----------------------------------------------------------------------------
''' <summary>Takes an SMSC formatet ip and port, and converts it to and easy
''' readeble ip address and port</summary>
''' <param name="IpAndPort">SMSC port and ip</param>
''' <param name="ip">extractet ip address</param>
''' <param name="port">extractet port</param>
''' <remarks>return "" in ip and 0 in port, if input was not valid</remarks>
''' <history>
''' [bofh] 09-02-2004 Created
''' </history>
'''-----------------------------------------------------------------------------
Public Sub decodeIpAndPort(ByVal IpAndPort As String, ByRef ip As String, ByRef port As Integer)
decodeIpPort(IpAndPort, ip, port)
End Sub
'''-----------------------------------------------------------------------------
''' <summary>Reconnects to SMSC</summary>
''' <param name="SMSC_Host"></param>
''' <param name="SMSC_port"></param>
''' <remarks></remarks>
''' <history>
''' [bofh] 06-02-2003 Created
''' </history>
'''-----------------------------------------------------------------------------
Public Sub Reconnect(ByVal SMSC_Host As String, ByVal SMSC_port As Integer)
' Added by Patrick, to disconnect first before connecting again 2016-09-21
ClientSocket.disconnect()
ClientSocket.connect(SMSC_Host, SMSC_port)
End Sub
'''-----------------------------------------------------------------------------
''' <summary>Send login informations to SMSC</summary>
''' <param name="username">your account ID</param>
''' <param name="password">your password</param>
''' <remarks>if login fails, autoReconnect will be set to False</remarks>
''' <history>
''' [bofh] 06-02-2003 Created
''' </history>
'''-----------------------------------------------------------------------------
Public Sub login(ByVal username As String, ByVal password As String)
If ClientSocket.connected Then
priv_username = username
priv_password = password
If Not connected Then Exit Sub
Dim login_p As New UCPPacket
login_p.CreateLoginPacket(username, password)
ClientSocket.SendData(login_p.createpacket)
Else
RaiseEvent login_failed("Not connected")
End If
End Sub
'''-----------------------------------------------------------------------------
''' <summary>If you have public IP, you can make the SMSC send receipts and SMS
''' messages to your maskine. Use bind to make this class pickup the messages
''' from the smsc, and then you can react on those</summary>
''' <param name="LocalIP">sms clients internal IP or fqdn</param>
''' <param name="localport">port to listen on</param>
''' <remarks>This ip should be the maskines IP. if the IP is on an rfc1918 net
''' make sure you pat or nat the extern ip and port to this. then use
''' encodeIpAndPort to construct the ip and port smses should be sendt too</remarks>
''' <history>
''' [bofh] 09-02-2004 Created
''' </history>
'''-----------------------------------------------------------------------------
Public Sub bind(ByVal LocalIP As String, ByVal localport As Integer)
If ClientListener Is Nothing Then
ClientListener = New UCPListener
AddHandler ClientListener.Packet_recieved, AddressOf Packet_recieved
AddHandler ClientListener.onDebug, AddressOf listener_onDebug
End If
ClientListener.bind(LocalIP, localport)
End Sub
'''-----------------------------------------------------------------------------
''' <summary>Creates an new instans of the SMS client and connects to the SMSC</summary>
''' <param name="SMSC_Host">host or IP of SMSC</param>
''' <param name="SMSC_port">port number on SMSC</param>
''' <remarks></remarks>
''' <history>
''' [bofh] 06-02-2003 Created
''' </history>
'''-----------------------------------------------------------------------------
Sub New(ByVal SMSC_Host As String, ByVal SMSC_port As Integer)
pre_SMSC_Host = SMSC_Host
priv_SMSC_port = SMSC_port
TransActionNumber = Int(98 * Rnd() + 1)
ClientSocket = New UCPSocket
AddHandler ClientSocket.Packet_recieved, AddressOf Packet_recieved
AddHandler ClientSocket.onDebug, AddressOf socket_onDebug
AddHandler ClientSocket.onConnect, AddressOf socket_onConnect
AddHandler ClientSocket.onDisconnect, AddressOf socket_onDisconnect
ClientSocket.connect(SMSC_Host, SMSC_port)
End Sub
'''-----------------------------------------------------------------------------
''' <summary>Creates an new instans of the SMS client and connects to the SMSC
''' and sends authentication packets ( logs on )</summary>
''' <param name="SMSC_Host">host or IP of SMSC</param>
''' <param name="SMSC_port">port number on SMSC</param>
''' <param name="username">user account ID</param>
''' <param name="password">user account password</param>
''' <remarks></remarks>
''' <history>
''' [bofh] 06-02-2003 Created
''' </history>
'''-----------------------------------------------------------------------------
Sub New(ByVal SMSC_Host As String, ByVal SMSC_port As Integer, ByVal username As String, ByVal password As String)
pre_SMSC_Host = SMSC_Host
priv_SMSC_port = SMSC_port
TransActionNumber = Int(98 * Rnd() + 1)
ClientSocket = New UCPSocket
ClientSocket.connect(SMSC_Host, SMSC_port)
AddHandler ClientSocket.Packet_recieved, AddressOf Packet_recieved
AddHandler ClientSocket.onDebug, AddressOf socket_onDebug
AddHandler ClientSocket.onConnect, AddressOf socket_onConnect
AddHandler ClientSocket.onDisconnect, AddressOf socket_onDisconnect
ClientListener = New UCPListener
End Sub
Private Sub Packet_recieved(ByVal packet As UCPPacket)
If packet.Operation = enumOT.Session_management_operation Then
If packet.success() Then
authenticated = True
RaiseEvent login_success()
Else
authenticated = False
autoReconnect = False
RaiseEvent login_failed("{" & packet.last_errorcode.ToString & "} " & packet.error_message)
ClientSocket.disconnect()
End If
ElseIf Not packet.success And packet.is_Operation_or_Request = enumOR.Request Then
If packet.last_errorcode = Error_code.Authentication_failure Then
authenticated = False
autoReconnect = False
ClientSocket.disconnect()
End If
RaiseEvent onDebug("Packet_recieved: Error: {" & packet.last_errorcode.ToString & "} " & packet.error_message)
Else
If packet.is_Operation_or_Request = enumOR.Operation Then
' We need to respond to this packets.
If packet.Message <> "" Then
packet.acknowledgement(True, "")
ClientSocket.SendData(packet.createpacket)
'sendKeepAlive()
Else
'2015/02/04 Patrick: To reply success even blank messages
'packet.acknowledgement(False, "Not understood", Error_code.Message_type_not_supported_by_system)
packet.acknowledgement(True, "")
ClientSocket.SendData(packet.createpacket)
'sendKeepAlive()
End If
Else
' SMSC is just telling us something ( went right )
End If
If packet.Message <> "" Then
RaiseEvent onDebug("Packet_recieved: " & packet.Originator & "->" & packet.receiver & ": " & packet.Message)
RaiseEvent msg_recv(packet)
Else
RaiseEvent onDebug("Packet_recieved: " & packet.createpacket)
End If
End If
End Sub
Private Sub socket_onDebug(ByVal msg As String)
RaiseEvent onDebug("UCPSocket." & msg)
End Sub
Private Sub listener_onDebug(ByVal msg As String)
RaiseEvent onDebug("UCPListener." & msg)
End Sub
Private Sub socket_onConnect()
authenticated = False
RaiseEvent onConnect()
End Sub
Private Sub socket_onDisconnect()
authenticated = False
RaiseEvent onDisconnect()
End Sub
'''-----------------------------------------------------------------------------
''' <summary>a VERY simple way of sending sms messages via UCP</summary>
''' <param name="from">who is SMS from</param>
''' <param name="sto">who is SMS to</param>
''' <param name="msg">The alpha numeric messages</param>
''' <returns>false if messages could not be sendt</returns>
''' <remarks>by this function return true does not mean that the sms actually was sendt.
''' you need to use notifications requests for this</remarks>
''' <history>
''' [bofh] 06-02-2003 Created
''' </history>
'''-----------------------------------------------------------------------------
Public Function SendSimpleSMS(ByVal from As String, ByVal sto As String, ByVal msg As String) As Boolean
If Not connected Then : Return False : Exit Function : End If
Dim sms_p As New UCPPacket
sms_p.CreateSimpleSMSpacket(from, sto, msg)
ClientSocket.SendData(sms_p.createpacket)
Return True
End Function
'''-----------------------------------------------------------------------------
''' <summary>send a normal and simple sms messages</summary>
''' <param name="Public"></param>
''' <param name="from">who is SMS from</param>
''' <param name="sto">who is SMS to</param>
''' <param name="msg">The alpha numeric messages</param>
''' <returns>false if messages could not be sendt</returns>
''' <remarks>by this function return true does not mean that the sms actually was sendt.
''' you need to use notifications requests for this</remarks>
''' <history>
''' [bofh] 06-02-2003 Created
''' </history>
'''-----------------------------------------------------------------------------
Public Function SubmitSMS(ByVal from As String, ByVal sto As String, _
ByVal msg As String, ByVal charge As String, ByVal page As String, ByVal keywordID As String) As Boolean
If Not connected Then : Return False : Exit Function : End If
Dim sms_p As New UCPPacket
sms_p.Create_Submit_AlphaNum_SMS(from, sto, msg, charge, page, keywordID)
Return ClientSocket.SendData(sms_p.createpacket)
'Return True
End Function
Public t = ""
'Added by Patrick 2016-10-13
'Keep alive function
Public Sub StartKeepAlive()
'If Not connected Then : Return False : Exit Sub : End If
'Dim sms_p As New UCPPacket
'Return ClientSocket.SendData(sms_p.createpacket)
'sendKeepAlive()
'Do While connected
' 'If Not connected Then : Exit Sub : End If
' Threading.Thread.Sleep(10000)
' RaiseEvent send_keep_alive()
' Dim p As New UCPPacket("02/00035/O/31/2488/0139/A0")
' ClientSocket.SendData(p.createpacket)
' 'sendKeepAlive()
' BackgroundWorker1.RunWorkerAsync()
'Loop
t = New Thread(AddressOf Me.BackgroundProcess)
t.Priority = ThreadPriority.BelowNormal ' This will push the subroutine even further into the background
t.Start()
End Sub
Private Sub BackgroundProcess()
Do While connected
If Not connected Then : Exit Sub : End If
'Threading.Thread.Sleep(60000)
Threading.Thread.Sleep(30000)
RaiseEvent send_keep_alive()
'Dim p As New UCPPacket("02/00035/O/31/2488/0139/A0")
'ClientSocket.SendData(p.createpacket)z
Dim sms_p As New UCPPacket
sms_p.CreateKeepAlivePacket()
ClientSocket.SendData(sms_p.createpacket)
Loop
End Sub
'Public Sub sendKeepAlive()
' If Not connected Then : Exit Sub : End If
' Threading.Thread.Sleep(10000)
' RaiseEvent send_keep_alive()
' Dim p As New UCPPacket("02/00035/O/31/2488/0139/A0")
' ClientSocket.SendData(p.createpacket)
' StartKeepAlive()
'End Sub
'''-----------------------------------------------------------------------------
''' <summary>
'''
''' </summary>
''' <param name="Public"></param>
''' <param name="from">who is SMS from</param>
''' <param name="sto">who is SMS to</param>
''' <param name="msg">The alpha numeric messages</param>
''' <param name="notificationAddr">mobil number, or ipaddress and port to send notifications too</param>
''' <param name="notify_over_ip">is the notification adddress and internet addresse. Use false for mobil numbers.</param>
''' <returns>false if messages could not be sendt</returns>
''' <remarks>by this function return true does not mean that the sms actually was sendt.
''' you need to use notifications requests for this</remarks>
''' <history>
''' [bofh] 06-02-2003 Created
''' </history>
'''-----------------------------------------------------------------------------
'Public Function SubmitSMS(ByVal from As String, ByVal sto As String, _
'ByVal msg As String, _
' ByVal charge As String, ByVal notificationAddr As String, Optional ByVal notify_over_ip As Boolean = False) As Boolean
'If Not connected Then : Return False : Exit Function : End If
' Dim sms_p As New UCPPacket
'Dim notifcationtype As Notification_Type
'notifcationtype.Delivery_Notification = True
'notifcationtype.Non_delivery_notification = True
'If notify_over_ip Then
'sms_p.Create_Submit_AlphaNum_SMS(from, sto, msg, charge, True, notificationAddr, notifcationtype, Notification_PID.PC_appl_over_TCP_IP)
'Else
'sms_p.Create_Submit_AlphaNum_SMS(from, sto, msg, charge, True, notificationAddr, notifcationtype, Notification_PID.Mobile_Station)
'End If
'ClientSocket.SendData(sms_p.createpacket)
'Return True
'End Function
Public Sub test()
Dim p As New UCPPacket("70/00019/R/60/A//74")
Dim s As String = p.createpacket
End Sub
'''-----------------------------------------------------------------------------
''' <summary>To proberly close down listner, call this function before disposing object</summary>
''' <remarks></remarks>
''' <history>
''' [bofh] 06-02-2003 Created
''' </history>
'''-----------------------------------------------------------------------------
Public Sub destroy()
If Not ClientListener Is Nothing Then ClientListener.StopListener = True
End Sub
End Class
|
Public Class RotatePosModeCfg
Public Property RDelayTime As Double
Get
Return CDbl(txtRDelayTime.Text)
End Get
Set(value As Double)
txtRDelayTime.Text = value.ToString
End Set
End Property
Public Property RTacc As Double
Get
Return CDbl(txtRAccTime.Text)
End Get
Set(value As Double)
txtRAccTime.Text = value.ToString
End Set
End Property
Public Property RTdec As Double
Get
Return CDbl(txtRDecTime.Text)
End Get
Set(value As Double)
txtRDecTime.Text = value.ToString
End Set
End Property
Public Property RStrVel As Double
Get
Return 0
End Get
Set(value As Double)
End Set
End Property
Public Property RMaxVel As Double
Get
Return CDbl(txtRMaxSpeed.Text)
End Get
Set(value As Double)
txtRMaxSpeed.Text = value.ToString
End Set
End Property
Public Property RDist As Double
Get
Return CDbl(txtRDist.Text)
End Get
Set(value As Double)
txtRDist.Text = value.ToString
End Set
End Property
Public Property RCurSpeed As Double
Get
Return CDbl(txtRCurSpeed.Text)
End Get
Set(value As Double)
txtRCurSpeed.Text = value.ToString
End Set
End Property
Public Property IsRotatePosMode As Boolean
Get
Return chkRMode.Checked
End Get
Set(value As Boolean)
chkRMode.Checked = value
End Set
End Property
End Class
|
Imports TvDatabase
Namespace Settings
Public Class mySettings
Private Shared _layer As New TvBusinessLayer
#Region "Properties"
Private Shared m_dlgMessage As String = "Niveau ?!"
Public Shared Property dlgMessage As String
Get
Return m_dlgMessage
End Get
Set(ByVal value As String)
m_dlgMessage = value
End Set
End Property
Private Shared m_dlgMessageShow As Boolean = True
Public Shared Property dlgMessageShow As Boolean
Get
Return m_dlgMessageShow
End Get
Set(ByVal value As Boolean)
m_dlgMessageShow = value
End Set
End Property
Private Shared m_delay As Integer = 20
Public Shared Property delay As Integer
Get
Return m_delay
End Get
Set(ByVal value As Integer)
m_delay = value
End Set
End Property
Private Shared m_BtnDeactivate As String = "ACTION_REMOTE_BLUE_BUTTON"
Public Shared Property BtnDeactivate As String
Get
Return m_BtnDeactivate
End Get
Set(ByVal value As String)
m_BtnDeactivate = value
End Set
End Property
Private Shared m_BtnAdd As String = "ACTION_REMOTE_RED_BUTTON"
Public Shared Property BtnAdd As String
Get
Return m_BtnAdd
End Get
Set(ByVal value As String)
m_BtnAdd = value
End Set
End Property
Private Shared m_debug As Boolean = False
Public Shared Property debug As Boolean
Get
Return m_debug
End Get
Set(ByVal value As Boolean)
m_debug = value
End Set
End Property
#End Region
#Region "Functions"
Public Shared Sub Load(Optional ByVal log As Boolean = True)
If log = True Then
MyLog.Info("")
MyLog.Info("-------------Load Settings---------------------")
End If
Dim _localPrefix As String = "myTvNiveauChecker."
Dim clstype As Type = GetType(mySettings)
Dim clsProperties As System.Reflection.PropertyInfo() = clstype.GetProperties()
Dim _maxlenghtLog As Integer = clsProperties.Max(Function(x) x.Name.Length)
For Each prop As System.Reflection.PropertyInfo In clsProperties.OrderBy(Function(x) x.Name)
Dim _value As String = _layer.GetSetting(_localPrefix & prop.Name, prop.GetValue(clstype, Nothing).ToString).Value
Select Case prop.PropertyType.Name
Case GetType(String).Name
prop.SetValue(clstype, CType(_value, String), Nothing)
Case GetType(Integer).Name
prop.SetValue(clstype, CType(_value, Integer), Nothing)
Case GetType(Boolean).Name
prop.SetValue(clstype, CType(_value, Boolean), Nothing)
Case GetType(Date).Name
prop.SetValue(clstype, CType(_value, Date), Nothing)
End Select
If log = True Then
MyLog.Debug("mySettings: {0}: {1}", _localPrefix & prop.Name, Space((_maxlenghtLog + 5) - prop.Name.Length) & prop.GetValue(clstype, Nothing).ToString)
End If
Next
If log = True Then
MyLog.Debug("-------------------------------------------------------")
End If
End Sub
Public Shared Sub Save()
Dim _localPrefix As String = "myTvNiveauChecker."
Dim clstype As Type = GetType(mySettings)
Dim clsProperties As System.Reflection.PropertyInfo() = clstype.GetProperties()
For Each prop As System.Reflection.PropertyInfo In clsProperties
Select Case prop.Name
Case Is = "pluginEnabledServer"
Exit Select
Case Else
Dim _setting As Setting = _layer.GetSetting(_localPrefix & prop.Name, prop.GetValue(clstype, Nothing).ToString)
_setting.Value = prop.GetValue(clstype, Nothing).ToString
_setting.Persist()
End Select
Next
End Sub
#End Region
End Class
End Namespace |
Imports Microsoft.VisualBasic
Public Class ClCreditLog_app
Public Property LogID As Integer
Public Property Deleted As Boolean
Public Property CreditReceiptNo As String
Public Property WithdrawReceiptNo As String
Public Property ContactID As Integer
Public Property Action As String
Public Property ReceiptNo As String
Public Property InitialCredit As Double
Public Property Amount As Double
Public Property Term As String
Public Property Notes As String
Public Property CreatedDate As Date
Public Property CreatedBy As String
Public Property RunOut As Boolean
End Class
|
Namespace DBFXClient
Public Class DBFXTrades
Inherits EventArgs
Private tOrderID As String
Private tCurrency As String
Private tTime As String
Private tAccountID As String
Private tOfferID As String
Private tBuySell As Boolean
Private tLot As Integer
Private tSide As String
Private tStatus As String
Private tRate As Double
Public Sub New(ByVal OrderID As String, ByVal OfferID As String, ByVal Lot As Integer, ByVal currency As String, ByVal BuySell As String, ByVal Time As String, ByVal Side As Integer, ByVal AccountID As String, ByVal Rate As Double, ByVal Status As String)
tLot = Lot
tTime = Time
tSide = Side
tRate = Rate
tStatus = Status
tOrderID = OrderID
tOfferID = OfferID
If BuySell = "B" Then
tBuySell = True
Else
tBuySell = False
End If
tCurrency = currency
tAccountID = AccountID
End Sub
Public ReadOnly Property OrderID() As String
Get
Return tOrderID
End Get
End Property
Public ReadOnly Property Quantity() As Integer
Get
Return tLot
End Get
End Property
Public ReadOnly Property Currency() As String
Get
Return tCurrency
End Get
End Property
Public ReadOnly Property TimeStamp() As String
Get
Return tTime
End Get
End Property
Public ReadOnly Property SenderID() As String
Get
Return tAccountID
End Get
End Property
Public ReadOnly Property Symbol() As String
Get
Return tCurrency
End Get
End Property
Public ReadOnly Property Side() As Integer
Get
Return tSide
End Get
End Property
Public ReadOnly Property TradeType() As Integer
Get
Return tSide
End Get
End Property
Public ReadOnly Property Status() As String
Get
Return tStatus
End Get
End Property
Public ReadOnly Property Rate() As Double
Get
Return tRate
End Get
End Property
End Class
End Namespace
|
Imports Ladle.Module.XPO
''' <summary>
''' Used to display a Sales_QuoteDetail object in a listview control
''' </summary>
''' <remarks></remarks>
Public Class QuoteDetailItem
''' <summary>
''' The object to display
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property Detail As Sales_QuoteDetail
''' <summary>
''' Default constructor
''' </summary>
''' <remarks></remarks>
Public Sub New()
End Sub
''' <summary>
''' Default constructor
''' </summary>
''' <param name="sd"></param>
''' <remarks></remarks>
Public Sub New(sd As Sales_QuoteDetail)
Detail = sd
End Sub
End Class
|
Imports AutoMapper
Imports UGPP.CobrosCoactivo.Datos
Public Class TipificacionCNCBLL
''' <summary>
''' Objeto para llamar métodos de consulta a la base de datos
''' </summary>
''' <returns></returns>
Private Property _TipificacionDAL As TipificacionCNCDAL
Private Property _AuditEntity As Entidades.LogAuditoria
Public Sub New()
_TipificacionDAL = New TipificacionCNCDAL()
End Sub
Public Sub New(ByVal auditData As Entidades.LogAuditoria)
_AuditEntity = auditData
_TipificacionDAL = New TipificacionCNCDAL(_AuditEntity)
End Sub
''' <summary>
''' Convierte un objeto del tipo Datos.TIPIFICACION_CUMPLE_NOCUMPLE a Entidades.TipificacionCNC
''' </summary>
''' <param name="prmObjModuloTipificacionCNCDatos">Objeto de tipo Datos.TIPIFICACION_CUMPLE_NOCUMPLE</param>
''' <returns>Objeto de tipo Entidades.TipificacionCNC</returns>
Public Function ConvertirEntidadTipificacionCNC(ByVal prmObjModuloTipificacionCNCDatos As Datos.TIPIFICACION_CUMPLE_NOCUMPLE) As Entidades.TipificacionCNC
Dim estadoOperativo As Entidades.TipificacionCNC
Dim config As New MapperConfiguration(Function(cfg)
Return cfg.CreateMap(Of Entidades.TipificacionCNC, Datos.TIPIFICACION_CUMPLE_NOCUMPLE)()
End Function)
Dim IMapper = config.CreateMapper()
estadoOperativo = IMapper.Map(Of Datos.TIPIFICACION_CUMPLE_NOCUMPLE, Entidades.TipificacionCNC)(prmObjModuloTipificacionCNCDatos)
Return estadoOperativo
End Function
''' <summary>
''' Obtiene las tipificaciones de cumple no cumple estudio de titulos
''' </summary>
''' <returns>Lista de objetos del tipo Entidades.ESTADO_OPERATIVO</returns>
Public Function obtenerTipificacionCNC() As List(Of Entidades.TipificacionCNC)
Dim tipificacionCNC = _TipificacionDAL.obtenerTipificacionCNC()
Dim tipificaciones As New List(Of Entidades.TipificacionCNC)
For Each tipificacion As Datos.TIPIFICACION_CUMPLE_NOCUMPLE In tipificacionCNC
tipificaciones.Add(ConvertirEntidadTipificacionCNC(tipificacion))
Next
Return tipificaciones
End Function
End Class
|
Imports System.ComponentModel
Imports System.Drawing
''' <summary>
''' Okno upozorňující na vzniklou chybu
''' </summary>
Public Class ErrorDialog
Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
''' <summary>
''' Jméno chybujícího procesu
''' </summary>
Public Property ProcessName As String
''' <summary>
''' Návratový kód procesu
''' </summary>
Public Property ResponseCode As Integer
''' <summary>
''' Vzniklé chyby
''' </summary>
Public Property Errors As New List(Of ProcessError)
''' <summary>
''' Obrázek Procesu
''' </summary>
Public Property Image As ImageSource
Private _restartprocess As Action
''' <summary>
''' Akce, která se zavolá, když uživatel vyžádá restart chybujícího serveru
''' </summary>
''' <returns></returns>
Public Property RestartProcess As Action
Get
Return _restartprocess
End Get
Set(value As Action)
' Nastaví hodnotu
_restartprocess = value
' Aktualizuje data-binding
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("DisplayRestartProcess"))
End Set
End Property
''' <summary>
''' Nastavuje zdali se zobrazí tlačítko pro zobrazení procesu
''' </summary>
Public ReadOnly Property DisplayRestartProcess As Visibility
Get
If RestartProcess IsNot Nothing Then
Return Visibility.Visible
Else
Return Visibility.Hidden
End If
End Get
End Property
''' <summary>
''' Incializuje nové okno
''' </summary>
''' <param name="processName">jméno havarovaného procesu</param>
''' <param name="process">havarovaný proces (může být Nothing)</param>
''' <param name="errors">seznam navrácených chyb</param>
''' <param name="image">ikona serveru</param>
Public Sub New(processName As String, process As Process, errors As List(Of String), image As ImageSource)
' příprava data-binding
Me.DataContext = Me
' inicializace
Me.Image = image
Me.ProcessName = processName
' Zpracování návratového kódu
If process IsNot Nothing Then
ResponseCode = process.ExitCode
Else
ResponseCode = 0
End If
' zpracování grafické reprezentace chyb
For Each e As String In errors
Me.Errors.Add(New ProcessError(e))
Next
' incializace GUI
InitializeComponent()
' Načtení ikony okna (chybový červený křížek; systémová ikona)
Dim ico = Interop.Imaging.CreateBitmapSourceFromHBitmap(
SystemIcons.Error.ToBitmap().GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions())
' vložení systémové ikony do GUI
ErrorImage.Source = ico
' titulek okna
Me.Title = "Chyba " & processName
End Sub
''' <summary>
''' Inicializuje nové okno, chyby rozparsuje ze System.String
''' </summary>
''' <param name="processName">jméno havarovaného programu</param>
''' <param name="process">hovarovaný proces</param>
''' <param name="output">výstup havarovaného procesu</param>
''' <param name="image">ikona serveru</param>
Public Sub New(processName As String, process As Process, output As String, image As ImageSource)
Me.New(
processName,
process,
output.Split(New String() {vbCr, vbLf}, StringSplitOptions.RemoveEmptyEntries).ToList(),
image)
End Sub
''' <summary>
''' Obsluha události načtení formuláře, pokud neobsahuje žádné chyby okamžitě jej zavře.
''' </summary>
''' <param name="sender">Reserved</param>
''' <param name="e">Reserved</param>
Private Sub ErrorDialog_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
If Me.Errors.Count = 0 Then
Me.Close()
End If
End Sub
''' <summary>
''' Oblusha události kliknutí na tlačítko Google, otevře webový prohlížeč s hledáním chyby na http://google.com
''' </summary>
''' <param name="sender">zdroj události</param>
''' <param name="e">Reserved</param>
Private Sub Google_Click(sender As Object, e As RoutedEventArgs)
' příprava URL dotazu
Dim query As String = sender.Tag
query = query.Replace(Xampp.Config.path, "")
query = query.Replace(Xampp.Config.path.Replace("\", "/"), "")
Dim url = String.Format("http://google.com/#q={0}", query)
' zavolání otevření odkazu (systém vybere výchozí prohlížeč)
Process.Start(url)
End Sub
''' <summary>
''' Obsluha kliknutí potvrzovacího tlačítka
''' </summary>
''' <param name="sender">Reserved</param>
''' <param name="e">Reserved</param>
Private Sub OK_Click(sender As Object, e As RoutedEventArgs)
Me.Close()
End Sub
''' <summary>
''' Vyvolá restart procesu
''' </summary>
''' <param name="sender">Reserved</param>
''' <param name="e">Reserved</param>
Private Sub RestartProcess_Click(sender As Object, e As RoutedEventArgs)
' vyvolá restart
Me.RestartProcess.Invoke()
' zavře okno
Me.Close()
End Sub
End Class
|
''' <summary>
''' Class with static methods for validating input for the StudData Database
''' </summary>
''' <remarks></remarks>
Public Class DatabaseValidation
''' <summary>
''' Validates a Student Number
''' </summary>
''' <param name="text"></param>
''' <param name="errors"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function StudentNumber(text As String, Optional ByRef errors As String = Nothing) As Boolean
' Constants
' Length of a student number
Const STUDENT_NUMBER_LENGTH As Integer = 5
' Whether Valid Or Not
Dim valid As Boolean = True
' Variables
' Current Student Number
Dim outputStudentNumber As Integer
' Trim Before Checks
text = text.Trim()
' Check that entry is long enough to be a full student number
If text.Length = STUDENT_NUMBER_LENGTH Then
' Try to get the student number
If Integer.TryParse(text, outputStudentNumber) Then
Else ' Failed Parsing Number
' Display Error Status
errors = "Student Number Must be Numeric"
' Not Valid
valid = False
End If
Else ' Entry Not Long Enough
' Display Error Status
errors = "Student Number Must be " & STUDENT_NUMBER_LENGTH & " Long"
' Not Valid
valid = False
End If
' Return Whether Valid Student Number
Return valid
End Function
''' <summary>
''' Validates a Student Name
''' </summary>
''' <param name="text"></param>
''' <param name="errors"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function StudentName(text As String, Optional ByRef errors As String = Nothing) As Boolean
' Constants
' Min Length of a student name
Const STUDENT_NAME_MINIMUM_LENGTH As Integer = 4
' Max Length of a student name
Const STUDENT_NAME_MAXIMUM_LENGTH As Integer = 50
' Whether Valid Or Not
Dim valid As Boolean = True
' Check length of name
If text.Length < STUDENT_NAME_MINIMUM_LENGTH Then
' Invalid Name
valid = False
' Specify Error
errors = "The student's name must be at least " & STUDENT_NAME_MINIMUM_LENGTH & " character long."
ElseIf text.Length > STUDENT_NAME_MAXIMUM_LENGTH Then
' Invalid Name
valid = False
' Specify Error
errors = "The student's name must be " & STUDENT_NAME_MAXIMUM_LENGTH & " character long or less."
End If
' Return Whether Valid Student Name
Return valid
End Function
''' <summary>
''' Validates a Phone Number
''' </summary>
''' <param name="text"></param>
''' <param name="errors"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function PhoneNumber(text As String, Optional ByRef errors As String = Nothing) As Boolean
' Constants
' Length of a student number
Const PHONE_NUMBER_MINIMUM_LENGTH As Integer = 10
' Whether Valid Or Not
Dim valid As Boolean = True
' Check length of number, numeric & if there is a decimal
If text.Length < PHONE_NUMBER_MINIMUM_LENGTH Then
' Invalid Name
valid = False
' Specify Error
errors = "The phone number must be at least " & PHONE_NUMBER_MINIMUM_LENGTH & " digits long."
ElseIf IsNumeric(text) And (Not text.IndexOf(".") = -1) Then
' Invalid Name
valid = False
' Specify Error
errors = "The phone number cannot contain decimals."
End If
' Return Whether Valid Phone Number
Return valid
End Function
''' <summary>
''' Validates an Enroll Date
''' </summary>
''' <param name="text"></param>
''' <param name="errors"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function EnrollDate(text As String, Optional ByRef errors As String = Nothing) As Boolean
' Whether Valid Or Not
Dim valid As Boolean = True
' Check if Date
If Not IsDate(text) Then
' Invalid Name
valid = False
' Specify Error
errors = "The enroll date must be a valid date."
End If
' Return Whether Valid Date
Return valid
End Function
''' <summary>
''' Validates a Student Loan
''' </summary>
''' <param name="text"></param>
''' <param name="errors"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function StudentLoan(text As String, Optional ByRef errors As String = Nothing) As Boolean
' Whether Valid Or Not
Dim valid As Boolean = True
' Check Loan
If Not IsNumeric(text) Then
' Invalid Name
valid = False
' Specify Error
errors = "The student loan must be a number."
End If
' Return Whether Valid Student Loan
Return valid
End Function
''' <summary>
''' Validates a Major
''' </summary>
''' <param name="text"></param>
''' <param name="errors"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function Major(text As String, Optional ByRef errors As String = Nothing) As Boolean
' Whether Valid Or Not
Dim valid As Boolean = True
' Check for either CPA or CST
If Not (text.Equals("CPA") Or text.Equals("CST")) Then
' Invalid Name
valid = False
' Specify Error
errors = "The major must be one of CPA or CST"
End If
' Return Whether Valid Major
Return valid
End Function
End Class
|
Imports DSharpPlus
Imports DSharpPlus.CommandsNext
Imports DSharpPlus.CommandsNext.Attributes
Imports DSharpPlus.Entities
Imports Raymond.Generators
Imports Raymond.Generators.MarkovChain
Namespace Commands.Modules
<Group("markov")>
<Description("Contains subcommands relating to the markov generator. See help for each subcommand.")>
<RequireUserPermissions(Permissions.ManageGuild)>
Public Class MarkovModule
Inherits BaseCommandModule
Private _generator As MarkovGenerator
Public Sub New(generators As IEnumerable(Of IGenerator))
Dim gen = generators.First(Function(g) TypeOf g Is MarkovGenerator)
_generator = CType(gen, MarkovGenerator)
End Sub
<Command("train")>
<Description("Retrieves the last 500 messages from the specified text channels and trains the markov generator using the content of those messages." + vbCrLf +
"Ignores blacklisted channels and messages from bots.")>
Public Async Function TrainCommand(ctx As CommandContext, ParamArray channels As DiscordChannel()) As Task
channels = channels.Where(Function(c) c.Type = ChannelType.Text).ToArray
If Not channels.Any Then
Await ctx.RespondAsync("You must specify at least one text channel.")
Return
End If
For Each channel In channels
For Each message In Await channel.GetMessagesAsync(500)
_generator.TrainMarkov(ctx.Guild, message)
Next
Next
Await ctx.Message.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":ok_hand:"))
End Function
<Command("reset")>
<Description("Deletes the markov chain for this server then reinitializes it using 20 messages from each non-blacklisted text channel.")>
Public Async Function ResetCommand(ctx As CommandContext) As Task
Dim loading = DiscordEmoji.FromGuildEmote(ctx.Client, 534230967574069249)
Dim okay = DiscordEmoji.FromName(ctx.Client, ":ok_hand:")
Await ctx.Message.CreateReactionAsync(loading)
Await _generator.ReinitializeMarkovAsync(ctx.Guild)
Await ctx.Message.CreateReactionAsync(okay)
Await ctx.Message.DeleteOwnReactionAsync(loading)
End Function
<Command("generate")>
<Description("Creates a 'sentence' using the markov chain for your server. This can be used to get an idea of what Raymond " +
"would say when the markov generator is enabled so you can retrain it if desired.")>
Public Async Function GenerateCommand(ctx As CommandContext) As Task
Dim sentence = _generator.CreateSentence(ctx.Guild).Sentence
Await ctx.RespondAsync(Formatter.BlockCode(sentence))
End Function
End Class
End Namespace |
Public Class frmPrintPreview
Private _message As MessageBoxUser = New MessageBoxUser()
Public PrintPreviewData As DataGridView
Public Sub New()
MyBase.New()
InitializeComponent()
PrintPreviewData = Me.GetPrintPreviewData()
End Sub
Private Function GetPrintPreviewData() As DataGridView
Try
Dim personal As PersonInformationBAL = New PersonInformationBAL()
Dim data As DataTable = personal.LoadAllInformation()
dgvPrintPrview.DataSource = Nothing
dgvPrintPrview.DataSource = data
dgvPrintPrview.Columns("Person No").Width = 60
dgvPrintPrview.Columns("Person No").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
dgvPrintPrview.Columns("First Name").Width = 80
dgvPrintPrview.Columns("Last Name").Width = 80
dgvPrintPrview.Columns("Sex").Width = 45
dgvPrintPrview.Columns("DOB").Width = 55
dgvPrintPrview.Columns("DOB").DefaultCellStyle.Format = "yyyy/MM/dd"
dgvPrintPrview.Columns("DOB").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
dgvPrintPrview.Columns("Height").Width = 45
dgvPrintPrview.Columns("Weight").Width = 45
dgvPrintPrview.Columns("Eyes").Width = 60
dgvPrintPrview.Columns("Hair").Width = 60
dgvPrintPrview.Columns("Address").Width = 100
dgvPrintPrview.Columns("POB").Width = 40
dgvPrintPrview.Columns("Phone").Width = 60
dgvPrintPrview.Columns("FPS").Width = 50
dgvPrintPrview.Columns("Comments").Width = 70
dgvPrintPrview.Columns("Phone").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
dgvPrintPrview.Columns("Weight").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
dgvPrintPrview.Columns("Height").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
dgvPrintPrview.Columns("Create Date").Visible = False
dgvPrintPrview.Height = 26
If dgvPrintPrview.Rows.Count > 0 Then
dgvPrintPrview.Height = (dgvPrintPrview.RowCount * 22) + 26
End If
Catch ex As Exception
_message.ShowMessageBox(ex.Message, "Error", 1, 4)
End Try
Return dgvPrintPrview
End Function
End Class |
Imports ESRI.ArcGIS.Framework
Imports ESRI.ArcGIS.ArcMapUI
Imports ESRI.ArcGIS.esriSystem
Imports ESRI.ArcGIS.Carto
Imports ESRI.ArcGIS.Display
Imports ESRI.ArcGIS.Geometry
Imports ESRI.ArcGIS.EditorExt
Imports ESRI.ArcGIS.Geodatabase
Imports ESRI.ArcGIS.GeoDatabaseUI
Imports ESRI.ArcGIS.DataSourcesRaster
Imports System.IO
'''<summary>
''' Commande qui permet d'afficher les valeurs des pixels et leurs formes selon un nombre minimum et maximum de pixels à afficher en X et Y
''' pour tous les RasterLayer présents et visibles dans la fenêtre d'affichage active.
'''</summary>
'''
'''<remarks>
''' Ce traitement est utilisable en mode interactif à l'aide de ses interfaces graphiques et doit être
''' utilisé dans ArcMap (ArcGisESRI).
'''</remarks>
Public Class cmdAfficherValeurPixel
Inherits ESRI.ArcGIS.Desktop.AddIns.Button
'Déclarer les variables de travail
Dim gpApp As IApplication = Nothing 'Interface ESRI contenant l'application ArcMap
Dim gpMxDoc As IMxDocument = Nothing 'Interface ESRI contenant un document ArcMap
Public Sub New()
'Définir les variables de travail
Try
'Par défaut la commande est inactive
Enabled = False
'Vérifier si l'application est définie
If Not Hook Is Nothing Then
'Définir l'application
gpApp = CType(Hook, IApplication)
'Vérifier si l'application est ArcMap
If TypeOf Hook Is IMxApplication Then
'Définir le document
gpMxDoc = CType(gpApp.Document, IMxDocument)
End If
End If
Catch erreur As Exception
'Message d'erreur
MsgBox("--Message: " & erreur.Message & vbCrLf & "--Source: " & erreur.Source & vbCrLf & "--StackTrace: " & erreur.StackTrace & vbCrLf)
Finally
'Vider la mémoire
End Try
End Sub
Protected Overrides Sub OnClick()
'Déclarer les variables de travail
Dim pMouseCursor As IMouseCursor = Nothing 'Interface qui permet de changer le curseur de la souris.
Dim pDocument As IDocument = Nothing 'Interface utilisé pour extraire la barre de statut.
Dim oMapLayer As clsGererMapLayer = Nothing 'Objet utilisé pour extraire les RasterLayer visibles.
Dim pRasterLayerColl As Collection = Nothing 'Contient la collection des RasterLayer visibles.
Dim pRasterLayer As IRasterLayer = Nothing 'Contient un RasterLayer.
Dim oPixel2Polygon As clsPixel2Polygon = Nothing 'Objet utilisé pour afficher les valeurs de pixels et leurs formes.
Dim nNbPixelX As Integer = 36 'Contient le nombre de pixel à afficher en X.
Dim nNbPixelY As Integer = 36 'Contient le nombre de pixel à afficher en Y.
Try
'Changer le curseur en Sablier pour montrer qu'une tâche est en cours
pMouseCursor = New MouseCursorClass
pMouseCursor.SetCursor(2)
'Interface pour définir le document afin d'extraire le StatusBar
pDocument = CType(gpMxDoc, IDocument)
'Définir le nonbre de pixel selon la forme de la fenêtre active
If gpMxDoc.ActiveView.Extent.Width > gpMxDoc.ActiveView.Extent.Height Then
nNbPixelY = CInt(gpMxDoc.ActiveView.Extent.Height / (gpMxDoc.ActiveView.Extent.Width / nNbPixelX))
Else
nNbPixelX = CInt(gpMxDoc.ActiveView.Extent.Width / (gpMxDoc.ActiveView.Extent.Height / nNbPixelY))
End If
'Définir l'objet utilisé pour extraire la collection des RasterLayers visibles
oMapLayer = New clsGererMapLayer(gpMxDoc.FocusMap)
'Extraire la collection des RasterLayers visibles
pRasterLayerColl = oMapLayer.RasterLayerCollection
'Traiter tous les RasterLayer
For i = 1 To pRasterLayerColl.Count
'Définir le RasterLayer
pRasterLayer = CType(pRasterLayerColl.Item(i), IRasterLayer)
'Définir un nouvel objet pour traiter l'affichage des pixels de l'image matricielle
oPixel2Polygon = New clsPixel2Polygon(pRasterLayer)
'Affichage des valeurs de pixels et leurs formes selon un nombre minimum et maximum de pixel par ligne et colonne
oPixel2Polygon.AfficherValeurPixel(gpMxDoc.ActiveView, pDocument.Parent.StatusBar, nNbPixelX, nNbPixelY)
Next
Catch erreur As Exception
'Message d'erreur
MsgBox("--Message: " & erreur.Message & vbCrLf & "--Source: " & erreur.Source & vbCrLf & "--StackTrace: " & erreur.StackTrace & vbCrLf)
Finally
'Vider la mémoire
pMouseCursor = Nothing
pDocument = Nothing
oMapLayer = Nothing
pRasterLayerColl = Nothing
pRasterLayer = Nothing
oPixel2Polygon = Nothing
End Try
End Sub
Protected Overrides Sub OnUpdate()
'Vérifier si aucun Layer n'est présent
If gpMxDoc.FocusMap.LayerCount = 0 Then
Enabled = False
Else
Enabled = True
End If
End Sub
End Class
|
Imports System.Windows.Forms
Public Class Options
Dim initialized = False
Dim m_queryLanguage As Boolean = QueryLanguage.OriginalLanguage
Dim m_testSetPhrases As Boolean = False
Dim m_saveWindowPosition As Boolean = False
Dim m_useCards As Boolean
Dim m_CardsInitialInterval As Integer
Dim oldValue As Integer = 1
' Lokalisierung
Public Overrides Sub LocalizationChanged()
End Sub
Private Sub OK(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdOK.Click
Me.DialogResult = System.Windows.Forms.DialogResult.OK
QueryLanguage = IIf(chkTestTargetLanguage.Checked, QueryLanguage.TargetLanguage, QueryLanguage.OriginalLanguage)
TestSetPhrases = chkTestSetPhrases.Checked
SaveWindowPosition = chkSaveWindowPosition.Checked
UseCards = chkUseCards.Checked
CardsInitialInterval = updownCardsInitialInterval.Value
Me.Close()
End Sub
Private Sub Cancel(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCancel.Click
Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.Close()
End Sub
Private Sub Options_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Select Case QueryLanguage
Case QueryLanguage.TargetLanguage
chkTestTargetLanguage.Checked = True
Case QueryLanguage.OriginalLanguage
chkTestTargetLanguage.Checked = False
Case Else
Throw New ArgumentException("Unsupported direction " & QueryLanguage)
End Select
chkTestSetPhrases.Checked = TestSetPhrases
chkSaveWindowPosition.Checked = SaveWindowPosition
chkUseCards.Checked = UseCards
updownCardsInitialInterval.Value = CardsInitialInterval
oldValue = CardsInitialInterval
initialized = True
End Sub
' Eigenschaften für die Objekte
Public Property QueryLanguage() As QueryLanguage
Get
Return m_queryLanguage
End Get
Set(ByVal value As QueryLanguage)
m_queryLanguage = value
End Set
End Property
Public Property TestSetPhrases() As Boolean
Get
Return m_testSetPhrases
End Get
Set(ByVal value As Boolean)
m_testSetPhrases = value
End Set
End Property
Public Property SaveWindowPosition() As Boolean
Get
Return m_saveWindowPosition
End Get
Set(ByVal value As Boolean)
m_saveWindowPosition = value
End Set
End Property
Public Property UseCards() As Boolean
Get
Return m_useCards
End Get
Set(ByVal value As Boolean)
m_useCards = value
End Set
End Property
Public Property CardsInitialInterval() As Integer
Get
Return m_CardsInitialInterval
End Get
Set(ByVal value As Integer)
m_CardsInitialInterval = value
End Set
End Property
Private Sub cardsInitialInterval_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles updownCardsInitialInterval.ValueChanged
If Not initialized Then Exit Sub
Dim newValue As Integer
If updownCardsInitialInterval.Value > oldValue Then newValue = oldValue * 2 Else newValue = oldValue / 2
If newValue < updownCardsInitialInterval.Minimum Then newValue = updownCardsInitialInterval.Minimum
If newValue > updownCardsInitialInterval.Maximum Then newValue = updownCardsInitialInterval.Maximum
updownCardsInitialInterval.Value = newValue
oldValue = newValue
End Sub
Private Sub cmdCopyCards_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCopyCards.Click
Dim db As IDataBaseOperation = New SQLiteDataBaseOperation()
db.Open(DBPath)
Dim man As New xlsManagement(db)
man.CopyGobalCardsToGroups()
End Sub
End Class |
Module Module1
Sub Main()
End Sub
#Region "MAP"
''' <summary>
''' Generates a map of rooms and corridors
''' </summary>
''' <returns>A two-dimensional integer array</returns>
''' <remarks>1 = wall, 0 = explorable spacec</remarks>
Private Function MapBaseGenerateDungeon() As Integer(,)
Dim ReturnValue(,) As Integer
Dim mb As New MapBuilder(300, 300)
With mb
.CorridorSpace = 10
.Corridor_Min = 3
.Corridor_Max = 10
.Corridor_MaxTurns = 1
.BreakOut = 1000
.BuildProb = 50
.CorridorDistance = 2
.RoomDistance = 5
.Room_Min = New Drawing.Size(3, 3)
.Room_Max = New Drawing.Size(10, 6)
.MaxRooms = 25
End With
log("building map")
Dim MapBuilt As Boolean = False
For x = 1 To 10
If mb.Build_ConnectedStartRooms Then
MapBuilt = True
Exit For
End If
Next
If MapBuilt Then
ReturnValue = mb.map
Else
ReturnValue = Nothing
End If
Return ReturnValue
End Function
''' <summary>
''' Generates a map of caves
''' </summary>
''' <returns>A two-dimensional integer array</returns>
''' <remarks>1 = wall, 0 = explorable spacec</remarks>
Private Function MapBaseGenerateCaves() As Integer(,)
'' TODO: implement Andrew's cave code
Return Nothing
End Function
#End Region
#Region "UTILITY"
Private Sub log(message As String)
Debug.WriteLine(message)
End Sub
#End Region
End Module
|
Imports System.Windows.Forms
Module Composite
Sub Main()
' create some arbitrary heirarchy of containers
Dim objRoot As New Container("Root")
Dim objChild1 As New Container("Child1")
Dim objGrandChild1 As New Container("Grandchild1")
Dim objChild2 As New Leaf("Child2")
objRoot.Add(objChild1)
objRoot.Add(objChild2)
objRoot.Add(New Container("Child3"))
objChild1.Add(objGrandChild1)
objGrandChild1.Add(New Leaf("GreatGrandchild1"))
objGrandChild1.Add(New Leaf("GreatGrandchild2"))
' output the contents of the root (including all subcontainers)
objRoot.PrintSelfAndContents()
MessageBox.Show("Click OK to end")
End Sub
Public Interface Node
Function GetName() As String
Sub PrintSelfAndContents()
End Interface
Public Class Container : Implements Node
Private m_Name As String
Private m_Nodes As New ArrayList()
Sub New(ByVal Name As String)
m_Name = "Container_" & Name
End Sub
Sub Add(ByRef Item As Node)
m_Nodes.Add(Item)
End Sub
Function GetName() As String Implements Node.GetName
Return m_Name
End Function
Sub PrintSelfAndContents() Implements Node.PrintSelfAndContents
Console.WriteLine(m_Name)
Dim tmpNode As Node
For Each tmpNode In m_Nodes
tmpNode.PrintSelfAndContents()
Next
End Sub
End Class
Public Class Leaf : Implements Node
Private m_Name As String
Sub New(ByVal Name As String)
m_Name = "Leaf_" & Name
End Sub
Function GetName() As String Implements Node.GetName
Return m_Name
End Function
Sub PrintSelfAndContents() Implements Node.PrintSelfAndContents
Console.WriteLine(m_Name)
End Sub
End Class
End Module
|
Option Explicit On
Option Strict On
' // *** Includes *** //
' // General
Imports System.Text
' // *** Class Definition *** //
Public Class CtlAccountNav : Inherits IWDEControl
#Region "CtlAccountNav.UserControl - Event Handlers"
Protected Sub Control_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub Control_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
Dim objUser As IWDEUser = IWDEUser.Current
Me.IWDEPage.BuildQueryString(Me)
Me.ShowLinks()
Me.SelectAndDisableTabs()
End Sub
#End Region
#Region "CtlAccountNav - Properties"
Protected ReadOnly Property IWDEAccountPage As IWDEAccountPage
Get
Dim objResult As IWDEAccountPage = Nothing
If (TypeOf Me.IWDEPage Is IWDEAccountPage) Then
objResult = DirectCast(Me.IWDEPage, IWDEAccountPage)
End If
Return (objResult)
End Get
End Property
#End Region
#Region "CtlAccountNav - Methods - Helpers"
Protected Sub ShowLinks()
Me.ShowAdminPanel(True)
Me.ShowUserPermissions(Me.IWDEAccountPage IsNot Nothing AndAlso Me.IWDEAccountPage.AccountID > 0)
Me.ShowEditPermissions(Me.IWDEPage.WebsiteID > 0)
End Sub
Protected Sub ShowAdminPanel(
ByVal blnEnable As Boolean
)
Me.lnkAdminPanel.Enabled = blnEnable
If (blnEnable) Then
Me.lnkAdminPanel.NavigateUrl = "/Account/AdminPanel.aspx"
End If
End Sub
Protected Sub ShowUserPermissions(
ByVal blnEnable As Boolean
)
Me.lnkUserPermissions.Enabled = blnEnable
If (blnEnable) Then
Me.lnkUserPermissions.NavigateUrl = "/Account/UserPermissions.aspx" & Me.QueryString
End If
End Sub
Protected Sub ShowEditPermissions(
ByVal blnEnable As Boolean
)
Me.lnkEditPermissions.Enabled = blnEnable
If (blnEnable) Then
Me.lnkEditPermissions.NavigateUrl = "/Account/EditPermissions.aspx" & Me.QueryString
End If
End Sub
Protected Sub SelectAndDisableTabs()
Dim sbCommand As New StringBuilder
Dim strPage As String = String.Empty
Dim strLinks(2) As String
Dim links(2) As HyperLink
strLinks(0) = "lnkAdminPanel"
strLinks(1) = "lnkUserPermissions"
strLinks(2) = "lnkEditPermissions"
links(0) = Me.lnkAdminPanel
links(1) = Me.lnkUserPermissions
links(2) = Me.lnkEditPermissions
' Add css class for disabled tabs
For i As Integer = 0 To links.Length - 1
If Not links(i).Enabled Then
sbCommand.AppendLine("$('#" & strLinks(i) & "').parent().addClass('ui-state-disabled');")
End If
Next
Select Case Me.Page.ToString
Case "ASP.adminpanel_aspx"
strPage = "lnkAdminPanel"
Case "ASP.userpermissions_aspx"
strPage = "lnkUserPermissions"
Case "ASP.editpermissions_aspx"
strPage = "lnkEditPermissions"
End Select
' Add css class for selected tab
sbCommand.AppendLine("$('#" & strPage & "').parent().addClass('ui-tabs-selected ui-state-active');")
' Register script
Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "SelectAndDisableTabs", sbCommand.ToString, True)
End Sub
#End Region
End Class |
Imports IronPython.Hosting
Imports Microsoft.Scripting.Hosting
Imports Powertrain_Task_Manager.Constants
Imports Powertrain_Task_Manager.Models
Namespace Controllers
Public Class PythonController
''' <summary>
''' Get python file object without connection
''' </summary>
''' <returns></returns>
Public Shared Function GetPythonFileObj() As Object
Dim fath = Form2Constant.LogixService
Dim pyruntime As ScriptRuntime = Python.CreateRuntime()
Dim fileObj As Object = pyruntime.UseFile(fath)
Return fileObj
End Function
''' <summary>
''' Get python file object with connection
''' </summary>
''' <param name="plcAddressConfig"></param>
''' <returns></returns>
Public Shared Function GetPythonFileObj(ByVal plcAddressConfig As PlcAddressConfiguration) As Object
Dim fileObj = GetPythonFileObj()
GenerateConnectionInPython(fileObj, plcAddressConfig)
Return fileObj
End Function
''' <summary>
''' Generate the connection in python through plc address and slot
''' </summary>
''' <param name="fileObj"></param>
''' <param name="plcAddressConfig"></param>
Public Shared Sub GenerateConnectionInPython(ByRef fileObj As Object, ByVal plcAddressConfig As PlcAddressConfiguration)
Dim strIpAddress = plcAddressConfig.IpAddress
Dim strPlcSlot = plcAddressConfig.Slot.ToString()
fileObj.set_comn_tag(strIpAddress, strPlcSlot)
End Sub
Public Shared Sub DownloadTag(ByRef fileObj As Object, ByVal tagName As String, ByVal tagValue As String)
fileObj.write_tag(tagName, tagValue)
End Sub
Public Shared Function UploadTag(ByRef fileObj As Object, ByVal tagName As String) As String
Return fileObj.ex_read(tagName)
End Function
End Class
End Namespace
|
Imports System
Imports System.Globalization
Imports System.Windows.Data
Imports DevExpress.DevAV
Namespace DevExpress.DevAV
Public Class PictureConverter
Implements IValueConverter
Private Function IValueConverter_Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As CultureInfo) As Object Implements IValueConverter.Convert
Dim picture As Picture = TryCast(value, Picture)
Return If(picture Is Nothing, Nothing, picture.Data)
End Function
Private Function IValueConverter_ConvertBack(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
Dim data() As Byte = TryCast(value, Byte())
Return If(data Is Nothing, Nothing, New Picture() With {.Data = data})
End Function
End Class
End Namespace
|
Imports BVSoftware.Bvc5.Core
Imports System.Collections.ObjectModel
Partial Class BVAdmin_Controls_UserPicker
Inherits System.Web.UI.UserControl
Private _tabIndex As Integer = -1
Public Property UserName() As String
Get
Return Me.UserNameField.Text
End Get
Set(ByVal value As String)
Me.UserNameField.Text = value
End Set
End Property
Dim _messageBox As IMessageBox = Nothing
Public Property MessageBox() As IMessageBox
Get
Return _messageBox
End Get
Set(ByVal value As IMessageBox)
_messageBox = value
End Set
End Property
Public Property TabIndex() As Integer
Get
Return _tabIndex
End Get
Set(ByVal value As Integer)
_tabIndex = value
End Set
End Property
Public Event UserSelected(ByVal args As Controls.UserSelectedEventArgs)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If _tabIndex <> -1 Then
FilterField.TabIndex = _tabIndex
btnGoUserSearch.TabIndex = _tabIndex + 1
btnBrowserUserCancel.TabIndex = _tabIndex + 2
NewUserNameField.TabIndex = _tabIndex + 3
NewUserEmailField.TabIndex = _tabIndex + 4
NewUserFirstNameField.TabIndex = _tabIndex + 5
NewUserLastNameField.TabIndex = _tabIndex + 6
btnNewUserCancel.TabIndex = _tabIndex + 7
btnNewUserSave.TabIndex = _tabIndex + 8
End If
End Sub
Protected Sub btnBrowseUsers_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnBrowseUsers.Click
MessageBox.ClearMessage()
Me.pnlNewUser.Visible = False
If pnlUserBrowser.Visible = True Then
pnlUserBrowser.Visible = False
Else
Me.pnlUserBrowser.Visible = True
LoadUsers()
End If
End Sub
Protected Sub btnBrowserUserCancel_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnBrowserUserCancel.Click
MessageBox.ClearMessage()
Me.pnlUserBrowser.Visible = False
End Sub
Protected Sub btnNewUserCancel_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnNewUserCancel.Click
MessageBox.ClearMessage()
Me.pnlNewUser.Visible = False
End Sub
Protected Sub btnNewUser_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnNewUser.Click
MessageBox.ClearMessage()
Me.pnlUserBrowser.Visible = False
If Me.pnlNewUser.Visible = True Then
Me.pnlNewUser.Visible = False
Else
Me.pnlNewUser.Visible = True
End If
End Sub
Protected Sub btnGoUserSearch_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnGoUserSearch.Click
MessageBox.ClearMessage()
LoadUsers()
Me.FilterField.Focus()
End Sub
Private Sub LoadUsers()
Dim users As Collection(Of Membership.UserAccount)
users = Membership.UserAccount.FindAllWithFilter(Me.FilterField.Text.Trim)
Me.GridView1.DataSource = users
Me.GridView1.DataBind()
End Sub
Protected Sub btnNewUserSave_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnNewUserSave.Click
MessageBox.ClearMessage()
Dim u As New Membership.UserAccount
u.UserName = Me.NewUserNameField.Text.Trim
u.Email = Me.NewUserEmailField.Text.Trim
u.FirstName = Me.NewUserFirstNameField.Text.Trim
u.LastName = Me.NewUserLastNameField.Text.Trim
u.Password = Membership.UserAccount.GeneratePassword(12)
u.PasswordFormat = WebAppSettings.PasswordDefaultEncryption
Dim createResult As New Membership.CreateUserStatus
If Membership.UserAccount.Insert(u, createResult) = True Then
Me.UserNameField.Text = u.UserName
ValidateUser()
Me.pnlNewUser.Visible = False
Else
Select Case createResult
Case Membership.CreateUserStatus.DuplicateUsername
MessageBox.ShowWarning("The username " & Me.NewUserNameField.Text.Trim & " already exists. Please select another username.")
Case Membership.CreateUserStatus.InvalidPassword
MessageBox.ShowWarning("Unable to create this account. Invalid Password")
Case Else
MessageBox.ShowWarning("Unable to create this account. Unknown Error.")
End Select
End If
End Sub
Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing
MessageBox.ClearMessage()
Dim bvin As String = CStr(GridView1.DataKeys(e.NewEditIndex).Value)
Dim u As Membership.UserAccount = Membership.UserAccount.FindByBvin(bvin)
Me.UserNameField.Text = u.UserName
ValidateUser()
Me.pnlUserBrowser.Visible = False
End Sub
Protected Sub btnValidateUser_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnValidateUser.Click
MessageBox.ClearMessage()
ValidateUser()
End Sub
Private Sub ValidateUser()
Dim u As Membership.UserAccount = Membership.UserAccount.FindByUserName(Me.UserNameField.Text.Trim)
If u IsNot Nothing Then
If u.Bvin <> String.Empty Then
Dim args As New Controls.UserSelectedEventArgs()
args.UserAccount = u
RaiseEvent UserSelected(args)
Else
MessageBox.ShowWarning("User account " & Me.UserNameField.Text.Trim & " wasn't found. Please try again or create a new account.")
End If
End If
End Sub
End Class
|
Imports System
Imports System.ComponentModel.DataAnnotations
Imports System.ServiceModel.DomainServices.Client.ApplicationServices
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Data
Imports System.Windows.Input
Imports Silverlight_RiaServices.Controls
Namespace LoginUI
''' <summary>
''' Form that presents the login fields and handles the login process.
''' </summary>
Partial Public Class LoginForm
Inherits StackPanel
Private parentWindow As LoginRegistrationWindow
Private loginInfo As New LoginInfo()
''' <summary>
''' Creates a new <see cref="LoginForm"/> instance.
''' </summary>
Public Sub New()
InitializeComponent()
' Set the DataContext of this control to the
' LoginInfo instance to allow for easy binding
Me.DataContext = loginInfo
End Sub
''' <summary>
''' Sets the parent window for the current <see cref="LoginForm"/>.
''' </summary>
''' <param name="window">The window to use as the parent.</param>
Public Sub SetParentWindow(ByVal window As LoginRegistrationWindow)
Me.parentWindow = window
End Sub
''' <summary>
''' Handles <see cref="DataForm.AutoGeneratingField"/> to provide the PasswordAccessor.
''' </summary>
Private Sub LoginForm_AutoGeneratingField(ByVal sender As Object, ByVal e As DataFormAutoGeneratingFieldEventArgs)
If e.PropertyName = "Password" Then
Dim passwordBox As PasswordBox = DirectCast(e.Field.Content, PasswordBox)
loginInfo.PasswordAccessor = Function() passwordBox.Password
End If
End Sub
''' <summary>
''' Submits the <see cref="LoginOperation"/> to the server
''' </summary>
Private Sub LoginButton_Click(ByVal sender As Object, ByVal e As EventArgs)
' We need to force validation since we are not using the standard OK
' button from the DataForm. Without ensuring the form is valid, we
' would get an exception invoking the operation if the entity is invalid.
If Me.loginForm.ValidateItem() Then
loginInfo.CurrentLoginOperation = WebContext.Current.Authentication.Login(loginInfo.ToLoginParameters(), AddressOf Me.LoginOperation_Completed, Nothing)
parentWindow.AddPendingOperation(loginInfo.CurrentLoginOperation)
End If
End Sub
''' <summary>
''' Completion handler for a <see cref="LoginOperation"/>. If operation succeeds,
''' it closes the window. If it has an error, we show an <see cref="ErrorWindow"/>
''' and mark the error as handled. If it was not canceled, but login failed, it must
''' have been because credentials were incorrect so we add a validation error to
''' to notify the user.
''' </summary>
Private Sub LoginOperation_Completed(ByVal loginOperation As LoginOperation)
If loginOperation.LoginSuccess Then
parentWindow.Close()
ElseIf loginOperation.HasError Then
ErrorWindow.CreateNew(loginOperation.Error)
loginOperation.MarkErrorAsHandled()
ElseIf Not loginOperation.IsCanceled Then
loginInfo.ValidationErrors.Add(New ValidationResult(ErrorResources.ErrorBadUserNameOrPassword, New String() {"UserName", "Password"}))
End If
End Sub
''' <summary>
''' Switches to the registration form.
''' </summary>
Private Sub RegisterNow_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
parentWindow.NavigateToRegistration()
End Sub
''' <summary>
''' If a login operation is in progress and is cancellable, cancel it.
''' Otherwise, close the window.
''' </summary>
Private Sub CancelButton_Click(ByVal sender As Object, ByVal e As EventArgs)
If (Not IsNothing(loginInfo.CurrentLoginOperation)) AndAlso loginInfo.CurrentLoginOperation.CanCancel Then
loginInfo.CurrentLoginOperation.Cancel()
Else
parentWindow.Close()
End If
End Sub
''' <summary>
''' Maps Esc to the cancel button and Enter to the OK button.
''' </summary>
Private Sub LoginForm_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
If e.Key = Key.Escape Then
Me.CancelButton_Click(sender, e)
ElseIf e.Key = Key.Enter AndAlso Me.loginButton.IsEnabled Then
Me.LoginButton_Click(sender, e)
End If
End Sub
End Class
End Namespace |
Public Class OrdemFabricação
Dim Ação As New TrfGerais()
Dim Exclusão As Boolean = False
Private Operation As Byte
Const INS As Byte = 0
Const UPD As Byte = 1
Const DEL As Byte = 2
Private Sub Fechar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Fechar.Click
Me.Close()
Me.Dispose()
End Sub
Private Sub Novo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Novo.Click
Ação.LimpaTextBox(Me)
Ação.Desbloquear_Controle(Me, True)
Me.MyLista.Items.Clear()
Me.NumeroOF.Text = "0000"
Me.NumeroOF.Focus()
Operation = INS
End Sub
Private Sub Editar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Editar.Click
If Me.NumeroOF.Text = "" Then
MsgBox("Não existe Ordem de Fabricação para ser editado.", 64, TituloMsgbox)
Exit Sub
End If
Operation = UPD
Ação.Desbloquear_Controle(Me, True)
Me.NumeroOF.Focus()
End Sub
Private Sub Salvar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Salvar.Click
'Area destinada para as validacoes
If Me.NumeroOF.Text = "" Then
MsgBox("O Código da Ordem de Fabricação não foi informado, favor verificar.", 64, TituloMsgbox)
Me.NumeroOF.Focus()
Exit Sub
ElseIf Me.NumeroPedido.Text = "" Then
Me.NumeroPedido.Text = 0
ElseIf Me.DataEmissão.Text = "" Then
MsgBox("A Data de emissão da ordem de favricação não foi informado, favor verificar.", 64, TituloMsgbox)
Me.DataEmissão.Focus()
Exit Sub
ElseIf Me.AutorizadoPor.Text = "" Then
MsgBox("A Ordem de Fabricação tem que ser autorizado por alguem responsavel da Lista, favor verificar.", 64, TituloMsgbox)
Me.AutorizadoPor.Focus()
Exit Sub
End If
'Fim da Area destinada para as validacoes
Dim CNN As New OleDb.OleDbConnection(New Conectar().ConectarBD(LocalBD & Nome_BD))
If Operation = INS Then
CNN.Open()
UltimoReg()
Dim Sql As String = "INSERT INTO OrdemFabricação (NumeroOf, NumeroPedido, NomeCliente, DataEmissão, DataEntrega, AutorizadoPor, Confirmada, Empresa) VALUES (@1, @2, @3, @4, @5, @6, @7, @8)"
Dim cmd As New OleDb.OleDbCommand(Sql, CNN)
cmd.Parameters.Add(New OleDb.OleDbParameter("@1", Nz(Me.NumeroOF.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@2", Nz(Me.NumeroPedido.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@3", Nz(Me.NomeCliente.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@4", Nz(Me.DataEmissão.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@5", Nz(Me.DataEntrega.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@6", Nz(Me.AutorizadoPor.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@7", "N"))
cmd.Parameters.Add(New OleDb.OleDbParameter("@8", CodEmpresa))
Try
cmd.ExecuteNonQuery()
CriaLog(UserAtivo, "OrdemFabricacao", "Adicionou: a Ordem " & Me.NumeroOF.Text & " para o Cliente " & Me.NomeCliente.Text)
MsgBox("Registro adicionado com sucesso", 64, TituloMsgbox)
Operation = UPD
Catch ex As Exception
MsgBox(ex.Message, 64, TituloMsgbox)
End Try
Ação.Desbloquear_Controle(Me, False)
CNN.Close()
ElseIf Operation = UPD Then
CNN.Open()
Dim Sql As String = "Update OrdemFabricação set NumeroPedido = @2, NomeCliente = @3, DataEmissão = @4, DataEntrega = @5, AutorizadoPor = @6, Confirmada = @7, Empresa = @8 Where NumeroOF = " & Me.NumeroOF.Text
Dim cmd As New OleDb.OleDbCommand(Sql, CNN)
cmd.Parameters.Add(New OleDb.OleDbParameter("@2", Nz(Me.NumeroPedido.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@3", Nz(Me.NomeCliente.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@4", Nz(Me.DataEmissão.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@5", Nz(Me.DataEntrega.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@6", Nz(Me.AutorizadoPor.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@7", "N"))
cmd.Parameters.Add(New OleDb.OleDbParameter("@8", CodEmpresa))
Try
cmd.ExecuteNonQuery()
CriaLog(UserAtivo, "OrdemFabricacao", "Editou: a Ordem " & Me.NumeroOF.Text & " para o Cliente " & Me.NomeCliente.Text)
MsgBox("Registro Atualizado com sucesso", 64, TituloMsgbox)
Catch x As Exception
MsgBox(x.Message)
Exit Sub
End Try
Ação.Desbloquear_Controle(Me, False)
CNN.Close()
End If
End Sub
Public Sub UltimoReg()
'Inserir ultimo registro
Dim Cnn As New OleDb.OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0; Data Source=" & LocalBD & Nome_BD)
Dim Cmd As New OleDb.OleDbCommand()
Dim DataReader As OleDb.OleDbDataReader
Dim Ult As Integer
With Cmd
.Connection = Cnn
.CommandTimeout = 0
.CommandText = "Select max(NumeroOF) from OrdemFabricação"
.CommandType = CommandType.Text
End With
Try
Cnn.Open()
DataReader = Cmd.ExecuteReader
While DataReader.Read
If Not IsDBNull(DataReader.Item(0)) Then
'Achou o iten procurado o iten as caixas serão preenchida
Ult = DataReader.Item(0)
End If
End While
DataReader.Close()
Catch Merror As System.Exception
MsgBox(Merror.ToString)
If ConnectionState.Open Then
Cnn.Close()
Exit Sub
End If
End Try
Cnn.Close()
Me.NumeroOF.Text = Ult + 1
Me.NumeroPedido.Focus()
'fim inserir ultimo registro
End Sub
Private Sub Localizar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Localizar.Click
RetornoProcura = ""
ChamaTelaProcura("Nº Ordem", "Cliente", "", "OrdemFabricação", "NumeroOF", "NomeCliente", "", True)
Me.NumeroOF.Text = RetornoProcura
If Me.NumeroOF.Text <> "" Then
LocalizaDados()
Me.NumeroPedido.Focus()
End If
End Sub
Public Sub LocalizaDados()
If Me.NumeroOF.Text = "" Then
Exit Sub
End If
Dim CNN As New OleDb.OleDbConnection(New Conectar().ConectarBD(LocalBD & Nome_BD))
CNN.Open()
Dim Sql As String = "Select * from OrdemFabricação where NumeroOF = " & Me.NumeroOF.Text
Dim CMD As New OleDb.OleDbCommand(Sql, CNN)
Dim DR As OleDb.OleDbDataReader
DR = CMD.ExecuteReader
DR.Read()
If DR.HasRows Then
Me.NumeroOF.Text = DR.Item("NumeroOF") & ""
Me.NumeroPedido.Text = DR.Item("NumeroPedido") & ""
Me.NomeCliente.Text = DR.Item("NomeCliente") & ""
Me.DataEmissão.Text = DR.Item("DataEmissão") & ""
Me.DataEntrega.Text = DR.Item("DataEntrega") & ""
Me.AutorizadoPor.Text = DR.Item("AutorizadoPor") & ""
Me.Confirmada.Text = DR.Item("Confirmada") & ""
DR.Close()
EncheListaItens()
Ação.Desbloquear_Controle(Me, True)
Operation = UPD
Else
MsgBox("Ordem de Fabricação não cadastrado, Verifique.", 64, TituloMsgbox)
DR.Close()
Me.NumeroOF.Text = "0000"
Me.NumeroOF.Focus()
Operation = INS
Exit Sub
End If
End Sub
Private Sub OrdemFabricação_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.F11 Then
Fechar_Click(sender, e)
End If
If e.KeyCode = Keys.F10 Then
Salvar_Click(sender, e)
End If
If e.KeyCode = Keys.F9 Then
Novo_Click(sender, e)
End If
If e.KeyCode = Keys.F8 Then
Editar_Click(sender, e)
End If
If e.KeyCode = Keys.F4 Then
Localizar_Click(sender, e)
End If
If e.KeyCode = Keys.F6 Then
If F6 = False Then
MsgBox("Este Usuário não tem permissão para recurso adicionais, consulte o Administrador.", 64, TituloMsgbox)
Exit Sub
Else
MsgBox("Este Usuário tem permissão para recurso adicionais, recurso Liberado", 64, TituloMsgbox)
Exclusão = True
End If
End If
If e.KeyCode = Keys.F2 Then
'colocar aqui recurso para excluir o item
MsgBox("O Recurso de Exclusão não esta disponivel nesta versão")
Exit Sub
End If
End Sub
Private Sub NumeroOF_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles NumeroOF.Leave
If Me.NumeroOF.Text = "0000" Then
Exit Sub
Else
LocalizaDados()
End If
End Sub
Private Sub OrdemFabricação_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Ação.Desbloquear_Controle(Me, False)
End Sub
Public Sub EncheListaItens()
If Me.NumeroOF.Text = "" Then Exit Sub
MyLista.Items.Clear()
Dim Cnn As New OleDb.OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0; Data Source=" & LocalBD & Nome_BD)
Dim Cmd As New OleDb.OleDbCommand()
Dim DataReader As OleDb.OleDbDataReader
Cnn.Open()
With Cmd
.Connection = Cnn
.CommandTimeout = 0
.CommandText = "SELECT OrdemFabricaçãoItens.*, OrdemFabricaçãoItens.NumeroOF, Produtos.Descrição FROM Produtos INNER JOIN OrdemFabricaçãoItens ON Produtos.CodigoProduto = OrdemFabricaçãoItens.Produto WHERE OrdemFabricaçãoItens.NumeroOF = " & Me.NumeroOF.Text
.CommandType = CommandType.Text
End With
Try
DataReader = Cmd.ExecuteReader
Dim Zebrar As Boolean = True
Dim AProduzir As Double = 0
While DataReader.Read
If Not IsDBNull(DataReader.Item("Produto")) Then
Dim AA As String = DataReader.Item("Produto")
Dim item1 As New ListViewItem(AA, 0)
item1.SubItems.Add(DataReader.Item("Descrição") & "")
item1.SubItems.Add(FormatNumber(DataReader.Item("Qtd"), 2))
item1.SubItems.Add(FormatNumber(DataReader.Item("Produzido"), 2))
AProduzir = CDbl(DataReader.Item("Qtd")) - CDbl(DataReader.Item("Produzido"))
item1.SubItems.Add(FormatNumber(AProduzir, 2))
item1.SubItems.Add(DataReader.Item("OrdemFabricaçãoItens.NumeroOF") & "")
MyLista.Items.AddRange(New ListViewItem() {item1})
If Zebrar = True Then
MyLista.Items.Item(MyLista.Items.Count() - 1).BackColor = Color.White
Zebrar = False
Else
MyLista.Items.Item(MyLista.Items.Count() - 1).BackColor = Color.MistyRose
Zebrar = True
End If
End If
End While
DataReader.Close()
Cnn.Close()
Catch Merror As System.Exception
MsgBox(Merror.ToString)
If ConnectionState.Open Then
Cnn.Close()
Exit Sub
End If
End Try
End Sub
Private Sub MyLista_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyLista.DoubleClick
If Me.NumeroOF.Text = "" Then
MsgBox("O usuário deve selecionar primeiro uma Ordem de Fabricação para editar os seus itens.", 64, TituloMsgbox)
Exit Sub
End If
Dim I As Integer = 0
RetornoProcura = ""
For I = 0 To MyLista.Items.Count - 1
If MyLista.Items(I).Selected = True Then RetornoProcura = (MyLista.Items(I).Text.Substring(0))
Next
If RetornoProcura = "" Then
Exit Sub
Else
My.Forms.OrdemFabricaçãoItens.ShowDialog()
End If
End Sub
Private Sub LançarItensNaOFToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LançarItensNaOFToolStripMenuItem.Click
If Me.NumeroOF.Text = "" Then
MsgBox("O usuário deve selecionar uma orderm de fabricação antes de lançar os itens.", 64, TituloMsgbox)
Exit Sub
End If
If Operation = INS Then
MsgBox("O usuário deve salvar a ordem de fabricação antes de adicionar os itens.", 64, TituloMsgbox)
Else
RetornoProcura = ""
My.Forms.OrdemFabricaçãoItens.ShowDialog()
End If
End Sub
Private Sub ImportarItensDoPedidoToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImportarItensDoPedidoToolStripMenuItem.Click
If Me.NumeroOF.Text = "" Then
MsgBox("O usuário deve selecionar uma orderm de fabricação antes de lançar os itens.", 64, TituloMsgbox)
Exit Sub
End If
If Me.NumeroPedido.Text = "" Then
MsgBox("Esta Ordem de Fabricação não foi informado um numero de Pedido, verifique.", 64, TituloMsgbox)
Exit Sub
End If
If Operation = INS Then
MsgBox("O usuário deve salvar a ordem de fabricação antes de adicionar os itens.", 64, TituloMsgbox)
Exit Sub
End If
Dim CNN As New OleDb.OleDbConnection(New Conectar().ConectarBD(LocalBD & Nome_BD))
CNN.Open()
Dim Sql As String = "Select * from Pedido where PedidoSequencia = " & Me.NumeroPedido.Text
Dim CMD As New OleDb.OleDbCommand(Sql, CNN)
Dim DR As OleDb.OleDbDataReader
DR = CMD.ExecuteReader
DR.Read()
If DR.HasRows Then
DR.Close()
ImportaItens()
EncheListaItens()
Else
MsgBox("Pedido não encontrado, Verifique.", 64, TituloMsgbox)
DR.Close()
Exit Sub
End If
End Sub
Public Sub ImportaItens()
Dim CNN As New OleDb.OleDbConnection(New Conectar().ConectarBD(LocalBD & Nome_BD))
CNN.Open()
Dim Sql As String = "INSERT INTO OrdemFabricaçãoItens ( NumeroOF, Produto, Qtd, Produzido ) SELECT " & Me.NumeroOF.Text & " AS [OF], ItensPedido.CodigoProduto, Sum(ItensPedido.Qtd) AS SomaDeQtd, 0 AS Zero FROM(ItensPedido) GROUP BY ItensPedido.PedidoSequencia, " & Me.NumeroOF.Text & ", ItensPedido.CodigoProduto, 0 HAVING (((ItensPedido.PedidoSequencia)=" & Me.NumeroPedido.Text & "));"
Dim CMD As New OleDb.OleDbCommand(Sql, CNN)
Try
If MsgBox("Deseja realmente importar os dados do pedido.", 36, TituloMsgbox) = 6 Then
CMD.ExecuteNonQuery()
CriaLog(UserAtivo, "OrdemFabricacao", "Importacao: dos Itens do Pedido " & Me.NumeroPedido.Text)
CNN.Close()
End If
CNN.Close()
Catch ex As Exception
MsgBox("Erro na importação dos Itens, verifique.", 64, TituloMsgbox)
CNN.Close()
Exit Sub
End Try
End Sub
Private Sub ExcluirItenSelecionadoToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcluirItenSelecionadoToolStripMenuItem.Click
If Me.Confirmada.Text = "S" Then
MsgBox("Esta ordem de Fabricação já foi confirmada e impressa, não pode ser alterada.", 64, TituloMsgbox)
Exit Sub
Else
Dim I As Integer = 0
RetornoProcura = ""
For I = 0 To MyLista.Items.Count - 1
If MyLista.Items(I).Selected = True Then RetornoProcura = (MyLista.Items(I).Text.Substring(0))
Next
If RetornoProcura = "" Then
Exit Sub
Else
Dim CNN As New OleDb.OleDbConnection(New Conectar().ConectarBD(LocalBD & Nome_BD))
CNN.Open()
Dim Sql As String = "Delete * from OrdemFabricaçãoItens Where NumeroOF = " & Me.NumeroOF.Text & " and Produto = " & RetornoProcura
Dim cmd As New OleDb.OleDbCommand(Sql, CNN)
Try
cmd.ExecuteNonQuery()
CriaLog(UserAtivo, "OrdemFabricacao", "Excluiu: da Ordem o Produto " & RetornoProcura)
CNN.Close()
EncheListaItens()
Catch ex As Exception
MsgBox(ex.Message, 64, TituloMsgbox)
End Try
End If
End If
End Sub
Private Sub ImprimirOFToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImprimirOFToolStripMenuItem.Click
If Me.Confirmada.Text <> "S" Then
MsgBox("Para Imprimir a Ordem de Fabricação o usuário deve primeiro confirmar.", 64, TituloMsgbox)
Exit Sub
End If
RelatorioCarregar = "RelOrdemFabricação"
My.Forms.VisualizadorRelatorio.ShowDialog()
End Sub
Private Sub ConfirmarOFToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConfirmarOFToolStripMenuItem.Click
'Area destinada para as validacoes
If Me.NumeroOF.Text = "" Then
MsgBox("O Código da Ordem de Fabricação não foi informado, favor verificar.", 64, TituloMsgbox)
Me.NumeroOF.Focus()
Exit Sub
ElseIf Me.NumeroPedido.Text = "" Then
Me.NumeroPedido.Text = 0
ElseIf Me.DataEmissão.Text = "" Then
MsgBox("A Data de emissão da ordem de favricação não foi informado, favor verificar.", 64, TituloMsgbox)
Me.DataEmissão.Focus()
Exit Sub
ElseIf Me.AutorizadoPor.Text = "" Then
MsgBox("A Ordem de Fabricação tem que ser autorizado por alguem responsavel da Lista, favor verificar.", 64, TituloMsgbox)
Me.AutorizadoPor.Focus()
Exit Sub
End If
'Fim da Area destinada para as validacoes
Dim CNN As New OleDb.OleDbConnection(New Conectar().ConectarBD(LocalBD & Nome_BD))
CNN.Open()
Dim Sql As String = "Update OrdemFabricação set NumeroPedido = @2, NomeCliente = @3, DataEmissão = @4, DataEntrega = @5, AutorizadoPor = @6, Confirmada = @7, Empresa = @8 Where NumeroOF = " & Me.NumeroOF.Text
Dim cmd As New OleDb.OleDbCommand(Sql, CNN)
cmd.Parameters.Add(New OleDb.OleDbParameter("@2", Nz(Me.NumeroPedido.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@3", Nz(Me.NomeCliente.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@4", Nz(Me.DataEmissão.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@5", Nz(Me.DataEntrega.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@6", Nz(Me.AutorizadoPor.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@7", "S"))
cmd.Parameters.Add(New OleDb.OleDbParameter("@8", CodEmpresa))
Try
cmd.ExecuteNonQuery()
Me.Confirmada.Text = "S"
MsgBox("Odem de Fabricação Atualizado e Confirmada com sucesso", 64, TituloMsgbox)
CNN.Close()
Catch x As Exception
MsgBox(x.Message)
Exit Sub
End Try
Ação.Desbloquear_Controle(Me, False)
CNN.Close()
End Sub
End Class |
'---------------------------------------------
' LineArcCombo.vb (c) 2002 by Charles Petzold
'---------------------------------------------
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Class LineArcCombo
Inherits PrintableForm
Shared Shadows Sub Main()
Application.Run(New LineArcCombo())
End Sub
Sub New()
Text = "Line & Arc Combo"
End Sub
Protected Overrides Sub DoPage(ByVal grfx As Graphics, _
ByVal clr As Color, ByVal cx As Integer, ByVal cy As Integer)
Dim pn As New Pen(clr, 25)
grfx.DrawLine(pn, 25, 100, 125, 100)
grfx.DrawArc(pn, 125, 50, 100, 100, -180, 180)
grfx.DrawLine(pn, 225, 100, 325, 100)
End Sub
End Class
|
' Project: Bonus Point Tracker
' Programmer: Arthur Buckowitz
' Date: June 7, 2012
' Description: Calculate the amount of bonus points earned based on user input of total books read, summary displays
' average books read for all readers entered.
Public Class frmBPTracker
Const int10Points As Integer = 10
Const int15Points As Integer = 15
Const int20Points As Integer = 20
Dim intTotalBooksRead As Integer
Dim intTotalReaders As Integer
Dim ResultDialogColor As Color
Dim ResultDialogFont As Font
Private Sub PointsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PointsToolStripMenuItem.Click
' Retrieves information from PointsEarned function and displays bonus points in textbox.
If txtboxName.Text = "" Or txtboxBooksRead.Text = "" Then
MessageBox.Show("Please enter name and books read to display earned points.", "Input Error", MessageBoxButtons.OK)
Else
txtboxBooksRead.Text = Math.Floor(Decimal.Parse(txtboxBooksRead.Text))
txtboxBonusPoints.Text = PointsEarned(Integer.Parse(txtboxBooksRead.Text))
intTotalReaders += 1
intTotalBooksRead = intTotalBooksRead + txtboxBooksRead.Text
End If
End Sub
Private Function PointsEarned(ByVal num1 As Integer) As Integer
' Calculates amount of points earned based on how many books were read, returns total.
Dim int1To3Books As Integer
Dim int4To6Books As Integer
Dim int7PlusBooks As Integer
Dim intPointOutput
If num1 <= 3 And Not 0 Then
int1To3Books = num1 * int10Points
End If
If num1 >= 4 And num1 <= 6 Then
int4To6Books = (num1 - 3) * int15Points + 30
End If
If num1 >= 7 Then
int7PlusBooks = (num1 - 6) * int20Points + 75
End If
intPointOutput = int1To3Books + int4To6Books + int7PlusBooks
Return intPointOutput.ToString
End Function
Private Sub SummaryToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SummaryToolStripMenuItem.Click
' Retrieves AvgBooksRead function and displays in messagebox.
If intTotalBooksRead = 0 Then
MessageBox.Show("Summary cannot be displayed without first entering amount of books read.", "Input Error", MessageBoxButtons.OK)
Else
MessageBox.Show("Average Amount of Books Read: " & AvgBooksRead(), "Summary", MessageBoxButtons.OK)
End If
End Sub
Private Function AvgBooksRead() As Integer
' Calculates average amount of books read for all readers and return total.
Dim intAverage As Integer
intAverage = intTotalBooksRead / intTotalReaders
Return intAverage.ToString
End Function
Private Sub ClearToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ClearToolStripMenuItem.Click
' Clears fields of the form and places focus on name textbox.
txtboxName.Text = ""
txtboxBooksRead.Text = ""
txtboxBonusPoints.Text = ""
txtboxName.Focus()
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
' Exits the program
Application.Exit()
End Sub
Private Sub FontToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FontToolStripMenuItem.Click
' Changes the font of the bonus points textbox.
FontDialog1.ShowDialog()
ResultDialogFont = FontDialog1.Font
txtboxBonusPoints.Font = ResultDialogFont
End Sub
Private Sub ColorToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ColorToolStripMenuItem.Click
' Changes the color of the bonus points textbox forecolor.
ColorDialog1.ShowDialog()
ResultDialogColor = ColorDialog1.Color
txtboxBonusPoints.ForeColor = ResultDialogColor
End Sub
Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
' Displays information about the program and programmer.
MessageBox.Show("Bonus Point Tracker v1.3" & Environment.NewLine & "Programmer: Arthur Buckowitz", "About", MessageBoxButtons.OK)
End Sub
Private Sub txtboxName_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtboxName.TextChanged
' Validates user input in name textbox.
If IsNumeric(txtboxName.Text) Then
MessageBox.Show("Numbers cannot be entered for name, please revise.", "Input Error", MessageBoxButtons.OK)
txtboxName.Text = ""
End If
End Sub
Private Sub txtboxBooksRead_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtboxBooksRead.TextChanged
' Validates user input in the books read textbox.
If Not IsNumeric(txtboxBooksRead.Text) And txtboxBooksRead.Text <> "" Then
MessageBox.Show("Letters and symbols may not be entered for " & Environment.NewLine & "amount of books read, please revise.", "Input Error", MessageBoxButtons.OK)
txtboxBooksRead.Text = ""
End If
End Sub
End Class
|
Imports System.IO.Compression
Imports System.IO
Public Class Meta
Private _InFileInfo As IO.FileInfo
Friend Property InFileInfo As IO.FileInfo
Get
Return _InFileInfo
End Get
Private Set(value As IO.FileInfo)
_InFileInfo = value
End Set
End Property
Private _OutFileInfo As IO.FileInfo
Friend Property OutFileInfo As IO.FileInfo
Get
Return _OutFileInfo
End Get
Private Set(value As IO.FileInfo)
_OutFileInfo = value
End Set
End Property
Private _FileName As String
Friend Property FileName As String
Get
Return _FileName
End Get
Private Set(value As String)
_FileName = value
End Set
End Property
Friend ReadOnly Property CompressionMode As CompressionMode
Get
If InFileInfo.Extension.ToUpper = CompressionExtension.ToUpper Then
Return Compression.CompressionMode.Decompress
Else
Return Compression.CompressionMode.Compress
End If
End Get
End Property
Sub New(m_FileName As String)
Try
If IO.File.Exists(m_FileName) = False Then Throw New Exception("File Not found " & m_FileName)
FileName = m_FileName
InFileInfo = New FileInfo(FileName)
Catch ex As Exception
Throw
End Try
End Sub
Friend ReadOnly Property CompressionExtension As String
Get
Return ".gz"
End Get
End Property
Friend Function DoWork() As Boolean
Try
If CompressionMode = Compression.CompressionMode.Compress Then
Return Compress()
Else
Return Decompress()
End If
Return True
Catch ex As Exception
Throw
End Try
End Function
Private Function Compress() As Boolean
Dim MyDestinationFile As String = InFileInfo.FullName & CompressionExtension
Try
Using inFile As FileStream = InFileInfo.OpenRead
Using outFile As FileStream = File.Create(MyDestinationFile)
Using GZipStream As GZipStream = New GZipStream(outFile, CompressionMode.Compress)
inFile.CopyTo(GZipStream)
End Using
End Using
End Using
Return True
Catch ex As Exception
Throw
Finally
If IO.File.Exists(MyDestinationFile) Then
OutFileInfo = New FileInfo(MyDestinationFile)
Else
OutFileInfo = Nothing
End If
End Try
End Function
Private Function Decompress() As Boolean
Dim MyDestinationFile As String = InFileInfo.FullName.Replace(CompressionExtension, "")
Try
Using inFile As FileStream = InFileInfo.OpenRead()
Using outFile As FileStream = File.Create(MyDestinationFile)
Using GZipStream As GZipStream = New GZipStream(inFile, CompressionMode.Decompress)
GZipStream.CopyTo(outFile)
End Using
End Using
End Using
Return True
Catch ex As Exception
Throw
Finally
If IO.File.Exists(MyDestinationFile) Then
OutFileInfo = New FileInfo(MyDestinationFile)
Else
OutFileInfo = Nothing
End If
End Try
End Function
End Class
|
Imports System.Text.RegularExpressions
Public Class Kiemtra
Public Function KiemtraSdt(ByVal sdt As String) As Boolean
Dim rgx As New Regex("^-*[0-9,\.?\-?\(?\)?\ ]+$")
'
If sdt.Length < 9 Or sdt.Length > 11 Then
Return False
Else Return rgx.IsMatch(sdt)
End If
End Function
Public Function KiemtraNgaysinh(ByVal ngsinh As Date) As Boolean
'trong do tuoi tu 18-70
Dim tuoi As Integer = 0
Dim kq As Boolean = False
'ko quá hôm nay
Dim nam As Integer
nam = DateAndTime.Now.Year
tuoi = DateAndTime.Now.Year - ngsinh.Year
If (ngsinh.Year < nam) Then
If tuoi > 17 And tuoi < 71 Then
kq = True
End If
End If
Return kq
End Function
Public Function KiemtraNgayNhapXuat(ByVal _date As Date) As Boolean
'ko quá hôm nay
Dim ngay, thang, nam As Integer
Dim kq As Boolean = False
ngay = DateAndTime.Now.Day
thang = DateAndTime.Now.Month
nam = DateAndTime.Now.Year
If (_date.Year < nam) Then
kq = True
ElseIf (_date.Year = nam) Then
If _date.Month < thang Then
kq = True
ElseIf _date.Month = thang Then
If _date.Day <= ngay Then
kq = True
End If
End If
End If
Return kq
End Function
Public Function CheckMail(ByVal emailAddress As String) As Boolean
If emailAddress.Length = 0 Then
Return False
End If
If emailAddress.IndexOf("@") > -1 Then
If (emailAddress.IndexOf(".", emailAddress.IndexOf("@")) > emailAddress.IndexOf("@")) AndAlso emailAddress.Split(".").Length > 0 AndAlso emailAddress.Split(".")(1) <> "" Then
Return True
End If
End If
Return False
End Function
End Class
|
Public Enum ContentManagerType
NotSet = 0
Image = 1
Audio = 2
Video = 3
GeneralFile = 4
End Enum
Public Enum ManagerViewMode
allVersions = 1
defaultVersions = 2
End Enum
Public Enum Enums
success = 0
fail = 1
missingParameters = 2
parameterInvalid = 3
conflict = 4
notFound = 5
End Enum
Public Enum GamePeriodStatus
Queued = 0
Progress = 1
Ended = 2
End Enum
Public Enum ProgressStatusEnum
notStarted = 0
inProgress = 1
completed = 2
End Enum
Public Enum CashflowType
revenue = 0
cost = 1
End Enum
Public Enum PaymentType
oneTime = 0
weeklyRecursive = 1
monthlyRecursive = 2
yearlyRecursive = 3
End Enum
Public Enum PaymentTargetType
asset = 0
liability = 1
equity = 2
End Enum
Public Enum BusinessAspect
marketing = 0
rnd = 1
production = 2
End Enum
Public Enum IdType
revenueAndCost = 1
End Enum |
Imports System.Math
Public Class RndNormGen
Private GNAC As GaussNumArrayClass
Private SampleS
Private Grnd As Random
Public Sub New(Mean As Double, StdDev As Double, SampleSize As Integer)
SampleS = SampleSize
GNAC = New GaussNumArrayClass()
GNAC.GaussNumDist(Mean, StdDev, SampleSize)
Grnd = New Random()
End Sub
Public Function GetRnd() As Double
Return GNAC.GaussNumArray(Grnd.Next(1, SampleS))
End Function
Private Class GaussNumArrayClass
Public GaussNumArray() As Double
Friend intICell As Long
Public Sub GaussNumDist(ByVal Mean As Double, ByVal StdDev As Double, ByVal SampleSize As Integer)
intICell = 1 'Loop variable
ReDim GaussNumArray(SampleSize)
Do While (intICell < (SampleSize + 1))
Call NumDist(Mean, StdDev)
Loop
End Sub
Sub NumDist(ByVal meanin As Double, ByVal sdin As Double)
'---------------------------------------------------------------------------------
'Converts uniform random numbers over the region 0 to 1 into Gaussian distributed
'random numbers using Box-Muller algorithm.
'Adapted from Numerical Recipes in C
'---------------------------------------------------------------------------------
'Defining variables
Dim dblR1 As Double
Dim dblR2 As Double
Dim circ As Double
Dim trans As Double
Dim dblY1 As Double
Dim dblY2 As Double
Dim Pi As Double
Pi = 4 * Atan(1)
'Get two random numbers
dblR1 = (2 * UniformRandomNumber()) - 1
dblR2 = (2 * UniformRandomNumber()) - 1
circ = (dblR1 ^ 2) + (dblR2 ^ 2) 'Radius of circle
If circ >= 1 Then 'If outside unit circle, then reject number
Call NumDist(meanin, sdin)
Exit Sub
End If
'Transform to Gaussian
trans = Sqrt(-2 * Log(circ) / circ)
dblY1 = (trans * dblR1 * sdin) + meanin
dblY2 = (trans * dblR2 * sdin) + meanin
GaussNumArray(intICell) = dblY1 'First number
'Increase intICell for next random number
intICell = (intICell + 1)
GaussNumArray(intICell) = dblY2 'Second number
'Increase intICell again ready for next call of ConvertNumberDistribution
intICell = (intICell + 1)
End Sub
Friend Function UniformRandomNumber() As Double
'-----------------------------------------------------------------------------------
'Outputs random numbers with a period of > 2x10^18 in the range 0 to 1 (exclusive)
'Implements a L'Ecuyer generator with Bays-Durham shuffle
'Adapted from Numerical Recipes in C
'-----------------------------------------------------------------------------------
'Defining constants
Const IM1 As Double = 2147483563
Const IM2 As Double = 2147483399
Const AM As Double = (1.0# / IM1)
Const IMM1 As Double = (IM1 - 1.0#)
Const IA1 As Double = 40014
Const IA2 As Double = 40692
Const IQ1 As Double = 53668
Const IQ2 As Double = 52774
Const IR1 As Double = 12211
Const IR2 As Double = 3791
Const NTAB As Double = 32
Const NDIV As Double = (1.0# + IM1 / NTAB)
Const ESP As Double = 0.00000012
Const RNMX As Double = (1.0# - ESP)
Dim iCell As Integer
Dim idum As Double
Dim j As Integer
Dim k As Long
Dim temp As Double
Static idum2 As Long
Static iy As Long
Static iv(NTAB) As Long
idum2 = 123456789
iy = 0
'Seed value required is a negative integer (idum)
Randomize()
idum = (-Rnd() * 1000)
'For loop to generate a sequence of random numbers based on idum
For iCell = 1 To 10
'Initialize generator
If (idum <= 0) Then
'Prevent idum = 0
If (-(idum) < 1) Then
idum = 1
Else
idum = -(idum)
End If
idum2 = idum
For j = (NTAB + 7) To 0
k = ((idum) / IQ1)
idum = ((IA1 * (idum - (k * IQ1))) - (k * IR1))
If (idum < 0) Then
idum = (idum + IM1)
End If
If (j < NTAB) Then
iv(j) = idum
End If
Next j
iy = iv(0)
End If
'Start here when not initializing
k = (idum / IQ1)
idum = ((IA1 * (idum - (k * IQ1))) - (k * IR1))
If (idum < 0) Then
idum = (idum + IM1)
End If
k = (idum2 / IQ2)
idum2 = ((IA2 * (idum2 - (k * IQ2))) - (k * IR2))
If (idum2 < 0) Then
idum2 = idum2 + IM2
End If
j = (iy / NDIV)
iy = (iv(j) - idum2)
iv(j) = idum
If (iy < 1) Then
iy = (iy + IMM1)
End If
temp = AM * iy
If (temp <= RNMX) Then
'Return the value of the random number
UniformRandomNumber = temp
End If
Next iCell
End Function
End Class
End Class
|
Imports Inventor
Public Class clsColorChange
'*************************************************************
' The declarations and functions below need to be copied into
' a class module whose name is "clsColorChange". The name
' can be changed but you'll need to change the declaration in
' the calling function "ChangeAppearanceMiniToolbarSample" to use the new name.
Private WithEvents m_MiniToolbar As MiniToolbar
Private WithEvents m_Colors As MiniToolbarComboBox
Private WithEvents m_Filter As MiniToolbarDropdown
Private WithEvents m_Preview As MiniToolbarCheckBox
Private m_PreviewColor As MiniToolbarCheckBox
Private WithEvents oInteractionEvents As InteractionEvents
Private WithEvents m_SelectEvents As SelectEvents
Private m_ChangeColorTransaction As Transaction
Private m_Doc As PartDocument
Private m_DefaultColor As Asset
Private bIsinteractionStarted As Boolean
Private bNeedTransaction As Boolean
Private bStop As Boolean
Private ThisApplication As Inventor.Application
Public Sub Init(oDoc As PartDocument)
m_Doc = oDoc
m_DefaultColor = m_Doc.ActiveAppearance
ThisApplication = oDoc.PrintManager.Application
' Create interaction events
oInteractionEvents = ThisApplication.CommandManager.CreateInteractionEvents
'oInteractionEvents.InteractionDisabled = False
m_SelectEvents = oInteractionEvents.SelectEvents
'm_SelectEvents.ClearSelectionFilter
'm_SelectEvents.SingleSelectEnabled = False
'm_SelectEvents.Enabled = True
' Create mini-tool bar for changing appearance
m_MiniToolbar = oInteractionEvents.CreateMiniToolbar
Call InitiateMiniToolbar()
bStop = False
m_ChangeColorTransaction = ThisApplication.TransactionManager.StartTransaction(m_Doc, "Change Appearance")
Do
ThisApplication.UserInterfaceManager.DoEvents
Loop Until bStop
End Sub
Private Sub InitiateMiniToolbar()
m_MiniToolbar.ShowOK = True
m_MiniToolbar.ShowApply = True
m_MiniToolbar.ShowCancel = True
Dim oControls As MiniToolbarControls
oControls = m_MiniToolbar.Controls
oControls.Item("MTB_Options").Visible = False
m_Filter = m_MiniToolbar.Controls.AddDropdown("Filter", False, True, True, False)
Call m_Filter.AddItem("Part", "Part", "Filter_Part", False, False)
Call m_Filter.AddItem("Feature", "Feature", "Filter_Feature", False, False)
Call m_Filter.AddItem("Face", "Face", "Filter_Face", False, False)
m_Colors = oControls.AddComboBox("Colors", True, True, 50)
Call m_Colors.AddItem("Default", "Use default color", "Default", False)
Call m_Colors.AddItem("Red", "Red", "Red", False)
Call m_Colors.AddItem("Orange", "Orange", "Orange", False)
Call m_Colors.AddItem("Yellow", "Yellow", "Yellow", False)
Call m_Colors.AddItem("Green", "Green", "Green", False)
Call m_Colors.AddItem("Blue", "Blue", "Blue", False)
Call m_Colors.AddItem("Indigo", "Indigo", "Indigo", False)
Call m_Colors.AddItem("Purple", "Purple", "Purple", False)
oControls.AddNewLine
' Specify if preview the color when hover a color item
m_PreviewColor = m_MiniToolbar.Controls.AddCheckBox("PreviewColor", "Hover color preview", "Whether preview color when hover on it", True)
' Position the mini-tool bar to the top-left.
Dim oPosition As Point2d
oPosition = ThisApplication.TransientGeometry.CreatePoint2d(0, 0)
m_MiniToolbar.Visible = True
m_MiniToolbar.Position = oPosition
End Sub
Private Sub m_Colors_OnItemHoverStart(ByVal ListItem As MiniToolbarListItem)
' Preview the color when hover on it.
If m_PreviewColor.Checked Then
Call ChangeColor(ListItem.Text)
End If
End Sub
Private Sub m_Colors_OnSelect(ByVal ListItem As MiniToolbarListItem)
' Check if the selected color is already used for the part/objects
If m_Filter.SelectedItem.Text = "Part" Then
If m_Doc.ActiveAppearance.Name = ListItem.Text Then
bNeedTransaction = False
Else
bNeedTransaction = True
End If
Else
bNeedTransaction = True
End If
Call ChangeColor(ListItem.Text)
End Sub
' Change filter for assigning color
Private Sub m_Filter_OnSelect(ByVal ListItem As MiniToolbarListItem)
If ThisApplication.TransactionManager.CurrentTransaction.DisplayName = "Change Appearance" Then
ThisApplication.TransactionManager.CurrentTransaction.Abort
End If
m_ChangeColorTransaction = ThisApplication.TransactionManager.StartTransaction(m_Doc, "Change Appearance")
Select Case ListItem.Text
Case "Part"
m_Doc.SelectSet.Clear
m_SelectEvents.ResetSelections
m_SelectEvents.ClearSelectionFilter
m_SelectEvents.AddSelectionFilter(SelectionFilterEnum.kPartDefaultFilter)
oInteractionEvents.SetCursor(CursorTypeEnum.kCursorTypeDefault)
Case "Feature"
m_Doc.SelectSet.Clear
m_SelectEvents.ResetSelections
m_SelectEvents.ClearSelectionFilter
m_SelectEvents.AddSelectionFilter(SelectionFilterEnum.kPartFeatureFilter)
If Not bIsinteractionStarted Then
oInteractionEvents.Start
bIsinteractionStarted = True
End If
Case "Face"
m_Doc.SelectSet.Clear
m_SelectEvents.ResetSelections
m_SelectEvents.ClearSelectionFilter
m_SelectEvents.AddSelectionFilter(SelectionFilterEnum.kPartFaceFilter)
If Not bIsinteractionStarted Then
oInteractionEvents.Start
bIsinteractionStarted = True
End If
End Select
m_Doc.Views(1).Update
Call ChangeColor(ListItem.Text)
End Sub
Private Sub m_MiniToolbar_OnApply()
If (m_Filter.SelectedItem.Text = "Feature" Or m_Filter.SelectedItem.Text = "Face") And (m_SelectEvents.SelectedEntities.Count = 0) Then
m_ChangeColorTransaction.Abort
m_Doc.Views(1).Update
m_ChangeColorTransaction = ThisApplication.TransactionManager.StartTransaction(m_Doc, "Change Appearance")
Exit Sub
Else
If bNeedTransaction Then ' Change color style
Call ChangeColor(m_Colors.SelectedItem.Text)
m_ChangeColorTransaction.End
Else ' If no change to the color style
m_ChangeColorTransaction.Abort
End If
' Clear current selection for Feature and Face filter.
If (m_Filter.SelectedItem.Text = "Feature" Or m_Filter.SelectedItem.Text = "Face") Then
m_Doc.SelectSet.Clear
m_SelectEvents.ResetSelections
End If
End If
m_ChangeColorTransaction = ThisApplication.TransactionManager.StartTransaction(m_Doc, "Change Appearance")
End Sub
Private Sub m_MiniToolbar_OnCancel()
bStop = True
If ThisApplication.TransactionManager.CurrentTransaction Is m_ChangeColorTransaction Then
m_ChangeColorTransaction.Abort
End If
m_SelectEvents.AddSelectionFilter(SelectionFilterEnum.kPartDefaultFilter)
If bIsinteractionStarted Then oInteractionEvents.Stop
m_Doc.Views(1).Update
End Sub
Private Sub m_MiniToolbar_OnOK()
bStop = True
If bNeedTransaction Then ' Change color
Call ChangeColor(m_Colors.SelectedItem.Text)
m_ChangeColorTransaction.End
Else ' If no change to the color style
m_ChangeColorTransaction.Abort
End If
End Sub
Private Sub oInteractionEvents_OnTerminate()
If ThisApplication.TransactionManager.CurrentTransaction Is m_ChangeColorTransaction Then
m_ChangeColorTransaction.Abort
End If
If bIsinteractionStarted Then
oInteractionEvents.Stop
End If
m_Doc.Views(1).Update
End Sub
Private Sub ChangeColor(sColor As String)
Debug.Print("Passed in:" & sColor)
If m_Filter.SelectedItem.Text = "Part" Then
Select Case sColor
Case "Default"
m_Doc.ActiveAppearance = m_DefaultColor
Case "Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Purple"
m_Doc.ActiveAppearance = m_Doc.AppearanceAssets.Item(sColor)
End Select
ElseIf m_Filter.SelectedItem.Text = "Feature" Then
If m_SelectEvents.SelectedEntities.Count Then
Dim oFeature As PartFeature, oSelectedObj As Object
For Each oSelectedObj In m_SelectEvents.SelectedEntities
If InStr(1, TypeName(oSelectedObj), "Feature") Then
oFeature = oSelectedObj
Select Case sColor 'm_Colors.SelectedItem.Text
Case "Default"
oFeature.Appearance = m_DefaultColor
Case "Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Purple"
oFeature.Appearance = m_Doc.AppearanceAssets.Item(sColor)
End Select
End If
Next
End If
ElseIf m_Filter.SelectedItem.Text = "Face" Then
If m_SelectEvents.SelectedEntities.Count Then
Dim oFace As Face
For Each oSelectedObj In m_SelectEvents.SelectedEntities
If InStr(1, TypeName(oSelectedObj), "Face") Then
oFace = oSelectedObj
Select Case sColor
Case "Default"
oFace.Appearance = m_DefaultColor
Case "Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Purple"
oFace.Appearance = m_Doc.AppearanceAssets.Item(sColor)
End Select
End If
Next
End If
End If
End Sub
End Class
|
'Project: Quiz 3 Question 27
'Programmer: Arthur Buckowitz
'Date: June 26, 2012
'Description: When form loads, 100 random numbers are generated between 1 and 1000, the numbers are stored in an array.
' When button is pressed, the smallest, largest, and average of all the numbers in the array are displayed in labels.
Public Class Form1
Dim Number(99) As Integer
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
'generates and stores 100 random numbers between 1 and 1000 to an array.
Dim rnd As New Random
Dim ArrayIndex As Integer = 0
Do Until ArrayIndex = 100
Number(ArrayIndex) = rnd.Next(1, 1000)
ArrayIndex += 1
Loop
End Sub
Private Sub btnShownumbers_Click(sender As System.Object, e As System.EventArgs) Handles btnShowNumbers.Click
'performs loop to establish the smallest, largest, and average of all numbers in the array, displays numbers to labels.
Dim Smallest As Integer
Dim Largest As Integer
Dim Sum As Integer
Dim Average As Integer
For i As Integer = 0 To 99
If Number(i) <= 499 And Smallest = 0 Then
Smallest = Number(i)
ElseIf Number(i) >= 500 And Largest = 0 Then
Largest = Number(i)
ElseIf Number(i) > Largest Then
Largest = Number(i)
ElseIf Number(i) < Smallest Then
Smallest = Number(i)
End If
Sum = Sum + Number(i)
Next
Average = (CInt(Sum / 100))
lblSmallest.Text = Smallest.ToString
lblLargest.Text = Largest.ToString
lblAverage.Text = Average.ToString
End Sub
End Class
|
Imports System
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Linq
Imports System.Text
Imports System.Xml.Linq
Namespace ChartsDemo
Public Class AgePopulation
Private name_Renamed As String
Private age_Renamed As String
Private sex_Renamed As String
Private population_Renamed As Double
Public ReadOnly Property Name() As String
Get
Return name_Renamed
End Get
End Property
Public ReadOnly Property Age() As String
Get
Return age_Renamed
End Get
End Property
Public ReadOnly Property Sex() As String
Get
Return sex_Renamed
End Get
End Property
Public ReadOnly Property SexAgeKey() As String
Get
Return sex_Renamed.ToString() & ": " & age_Renamed
End Get
End Property
Public ReadOnly Property CountryAgeKey() As String
Get
Return name_Renamed & ": " & age_Renamed
End Get
End Property
Public ReadOnly Property CountrySexKey() As String
Get
Return name_Renamed & ": " & sex_Renamed.ToString()
End Get
End Property
Public ReadOnly Property Population() As Double
Get
Return population_Renamed
End Get
End Property
Public Sub New(ByVal name As String, ByVal age As String, ByVal gender As String, ByVal population As Double)
Me.name_Renamed = name
Me.age_Renamed = age
Me.sex_Renamed = gender
Me.population_Renamed = population
End Sub
End Class
End Namespace
|
Public Class Form2
Private WithEvents o_MonSI As SI
' mémorisation des mat oblig et des textbox
Private o_MatieresObligatoires As Matieres
Private o_Lestxtb As List(Of TextBox)
Private Sub chkResultats_CheckedChanged(sender As Object, e As EventArgs) Handles chkResultats.CheckedChanged
pnlResultats.Visible = chkResultats.Checked
btnEnreg.Enabled = False
End Sub
Public Sub New()
' Cet appel est requis par le concepteur.
InitializeComponent()
' Ajoutez une initialisation quelconque après l'appel InitializeComponent().
o_MonSI = SI.DonneMoisLeSI()
' instancier les mémos
o_MatieresObligatoires = New Matieres
o_Lestxtb = New List(Of TextBox)
End Sub
''' <summary>
''' Permet de remplir le panel des résultats
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Private Function RemplirLesResultatsDynamiquement()
Dim letop As Integer = 10
Dim leLeft As Integer = 15
For Each MAT As Matiere In o_MonSI.Matieres
If Not MAT.Facultatif Then
Dim labCode As Label = New Label
Dim labLibelle As Label = New Label
Dim txtNote As TextBox = New TextBox
Dim labNote As Label = New Label
labCode.Text = MAT.Code
labCode.Top = letop
labCode.Left = leLeft
labLibelle.Text = MAT.Intitule
labLibelle.Top = letop
labLibelle.Left = labCode.Width + leLeft
labLibelle.Width = 300
txtNote.Top = letop
txtNote.Left = labLibelle.Right + 15
txtNote.Width = 35
txtNote.MaxLength = 2
o_Lestxtb.Add(txtNote)
o_MatieresObligatoires.Add(MAT)
labNote.Text = "/20"
labNote.Left = txtNote.Right + leLeft
labNote.Top = letop
letop += labCode.Height + 10
If Not pnlResultats.Controls.Contains(labCode) Then
pnlResultats.Controls.Add(labCode)
pnlResultats.Controls.Add(labLibelle)
pnlResultats.Controls.Add(txtNote)
pnlResultats.Controls.Add(labNote)
End If
Else
If Not cbxEpreuveFacultative.Items.Contains(MAT) Then
cbxEpreuveFacultative.Items.Add(MAT)
End If
End If
Next
Debug.WriteLine("Affichage des matieres")
End Function
''' <summary>
''' Permet de créer les labels et TextBox correspondant à la matière falcultative sélectionnée
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub cbxEpreuveFacultative_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxEpreuveFacultative.SelectedIndexChanged
Dim labCode2 As Label = New Label
Dim labLibelle2 As Label = New Label
Dim txtNote2 As TextBox = New TextBox
Dim labNote2 As Label = New Label
Dim MAT2 As Matiere = cbxEpreuveFacultative.SelectedItem
Dim letop As Integer = 10
Dim leLeft As Integer = 15
labCode2.Text = MAT2.Code
labCode2.Top = cbxEpreuveFacultative.Bottom + letop
labCode2.Left = leLeft
labLibelle2.Text = MAT2.Intitule
labLibelle2.Top = cbxEpreuveFacultative.Bottom + letop
labLibelle2.Left = labCode2.Width + leLeft
labLibelle2.Width = 300
txtNote2.Top = cbxEpreuveFacultative.Bottom + letop
txtNote2.Left = labLibelle2.Right + 15
txtNote2.Width = 35
labNote2.Text = "/20"
labNote2.Left = txtNote2.Right + leLeft
labNote2.Top = cbxEpreuveFacultative.Bottom + letop
pnlResultats2.Controls.Add(labCode2)
pnlResultats2.Controls.Add(labLibelle2)
pnlResultats2.Controls.Add(txtNote2)
pnlResultats2.Controls.Add(labNote2)
End Sub
''' <summary>
''' Permet d'annuler la modification ou l'ajout d'un étudiant
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub btnAbondon_Click(sender As Object, e As EventArgs) Handles btnAbondon.Click
Me.Close()
End Sub
''' <summary>
''' Permet d'enregister les modifications ou d'enregistrer un nouvel élève
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub btnEnreg_Click(sender As Object, e As EventArgs) Handles btnEnreg.Click
If tbId.Text <> "" And tbNom.Text <> "" And tbPrénom.Text <> "" Then
End If
End Sub
''' <summary>
''' exécuté quandle form est chargé
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles Me.Load
RemplirLesResultatsDynamiquement()
End Sub
End Class |
Public Class frmRegistration
#Region "Properties"
'Allows this form to reference and return to parent form
Private Overloads Property ParentForm() As Form
#End Region
#Region "Methods"
'?Overload Show() method to include parent argument?
Public Overloads Sub Show(parent As Form)
ParentForm = parent
MyBase.Show()
End Sub
#End Region
#Region "Event Handlers"
'Handles btnSubmit Click
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
'Validate inputs and add new user to DB
Dim users As New MyMoviesDBDataSetTableAdapters.UserTableAdapter()
Dim tblUser As New MyMoviesDBDataSet.UserDataTable()
users.Fill(tblUser)
Dim user As String = If(CheckForSQL(txtUsername.Text), "ERROR USER ATTEMPTED SQL INJECTION", txtUsername.Text)
Dim pwd As String = txtPassword.Text
If user.Equals("ERROR USER ATTEMPTED SQL INJECTION") Then
MessageBox.Show("SQL Injection Attempt Detected.", "Error: Closing Application", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error)
Application.Exit()
End If
Dim checkUser As DataRow
checkUser = tblUser.Select(String.Format("Username = '{0}'", user.ToUpper)).FirstOrDefault()
If checkUser Is Nothing AndAlso txtUsername.TextLength >= 5 AndAlso txtPassword.TextLength >= 5 Then
'This block can be used to selectively validate inserted fields
Dim customer As New MyMoviesDBDataSetTableAdapters.CustomerTableAdapter()
Dim firstName As String = txtFirstName.Text
Dim lastName As String = txtLastName.Text
Dim phone As String = txtPhone.Text
Dim email As String = txtEmail.Text
Dim address As String = txtAddress.Text
Dim city As String = txtCity.Text
Dim zip As String = txtZip.Text
Dim DOB As Date
Date.TryParse(txtDOB.Text, DOB)
Dim expiration As Date
Date.TryParse(txtExpiration.Text, expiration)
Dim CC As String = txtCreditCard.Text
Dim state As String = cboState.Text
Dim CreateTime As Date = DateTime.Now
customer.Insert(firstName, lastName, DOB, phone, email, address, city, state, zip, CC, expiration, CreateTime)
Dim tblCustomer As New MyMoviesDBDataSet.CustomerDataTable()
customer.Fill(tblCustomer)
Dim row As DataRow = (From r As DataRow In tblCustomer.Rows Where r(12).ToString().Equals(CreateTime.ToString()) Select r).Single()
users.Insert(txtUsername.Text.ToUpper, txtPassword.Text, CType(row, MyMoviesDBDataSet.CustomerRow).CustomerID)
UserID = CType(row, MyMoviesDBDataSet.CustomerRow).CustomerID
MessageBox.Show("User Added!")
'shows parent
If (ParentForm.Name = "frmStart") Then
Start.Show()
Else
PlaceOrder.Show()
End If
'closes this form
Close()
Else
MessageBox.Show("Username already taken or shorter than minimum length (5 characters).")
End If
End Sub
'Handles btnCancel Click
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
'Return to frmStart if that was previous form, otherwise
'display frmPlaceOrder
If (ParentForm.Name = "frmStart") Then
Start.Show()
Else
PlaceOrder.Show()
End If
'Hides this form
Hide()
End Sub
Private Sub frmRegistration_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
'Toggles all forms to / from fullscreen when F11 is pressed
If (e.KeyCode = Keys.F11) Then
ResizeAllForms()
End If
End Sub
Private Sub frmRegistration_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MyMoviesDBDataSet.State' table. You can move, or remove it, as needed.
Me.StateTableAdapter.Fill(Me.MyMoviesDBDataSet.State)
txtPassword.UseSystemPasswordChar = True
End Sub
#End Region
End Class |
Imports System.Data.SqlClient
Public Class DepartamentoDAO
Inherits DBConnection
Public Function Registrar(ByVal departamento As Departamento) As Boolean
Dim command As New SqlCommand("RegistrarDepartamento", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.AddWithValue("@Nom_Dpto", departamento.Nombre)
connection.Open()
command.ExecuteNonQuery()
connection.Close()
Return True
End Function
Public Function Editar(ByVal departamento As Departamento) As Boolean
Dim command As New SqlCommand("EditarDepartamento", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.AddWithValue("@ID_Dpto", departamento.ID)
command.Parameters.AddWithValue("@Nom_Dpto", departamento.Nombre)
connection.Open()
command.ExecuteNonQuery()
connection.Close()
Return True
End Function
Public Function Desactivar(ByVal idDpto As Integer) As Boolean
Dim command As New SqlCommand("DesactivarDepartamento", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.AddWithValue("@ID_Dpto", idDpto)
connection.Open()
command.ExecuteNonQuery()
connection.Close()
Return True
End Function
Public Function VerDepartamentos() As List(Of Departamento)
Dim command As New SqlCommand("VerDepartamentos", connection)
command.CommandType = CommandType.StoredProcedure
Dim departamentos As New List(Of Departamento)
connection.Open()
Dim reader As SqlDataReader
reader = command.ExecuteReader()
While (reader.Read())
Dim departamento As New Departamento With {
.ID = reader.GetInt32(0),
.Nombre = reader.GetString(1),
.Activo = reader.GetBoolean(2)
}
departamentos.Add(departamento)
End While
reader.Close()
connection.Close()
Return departamentos
End Function
Public Function ObtenerDepartamento(ByVal idDepartamento As Integer) As Departamento
Dim departamento As New Departamento
Dim command As New SqlCommand("VerDepartamentos", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.AddWithValue("@ID_Dpto", idDepartamento)
connection.Open()
Dim reader As SqlDataReader
reader = command.ExecuteReader()
If (reader.Read()) Then
departamento.ID = reader.GetInt32(0)
departamento.Nombre = reader.GetString(1)
departamento.Activo = reader.GetBoolean(2)
End If
reader.Close()
connection.Close()
Return departamento
End Function
Public Function VerDepartamentosEmpresa(ByVal idEmpresa As String) As List(Of Departamento)
Dim command As New SqlCommand("VerDepartamentos", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.AddWithValue("@ID_Empresa", idEmpresa)
Dim departamentos As New List(Of Departamento)
connection.Open()
Dim reader As SqlDataReader
reader = command.ExecuteReader()
While (reader.Read())
Dim departamento As New Departamento With {
.ID = reader.GetInt32(0),
.Nombre = reader.GetString(1),
.Activo = reader.GetBoolean(2)
}
departamentos.Add(departamento)
End While
reader.Close()
connection.Close()
Return departamentos
End Function
Public Function AsignarGerente(ByVal idEmpresa As String, ByVal idDpto As Integer, ByVal idGerente As Integer, ByVal bono As Double, ByVal bonoPorcent As Double) As Boolean
Dim command As New SqlCommand("AsignarGerenteDpto", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.AddWithValue("@ID_Empresa", idEmpresa)
command.Parameters.AddWithValue("@ID_Dpto", idDpto)
command.Parameters.AddWithValue("@ID_Gerente", idGerente)
command.Parameters.AddWithValue("@Cant_Bono", bono)
command.Parameters.AddWithValue("@Porcent_Bono", bonoPorcent)
connection.Open()
command.ExecuteNonQuery()
connection.Close()
Return True
End Function
Public Function AgregarPuesto(ByVal idDpto As Integer, ByVal idPuesto As Integer, ByVal porcentajeSueldo As Double) As Boolean
Dim command As New SqlCommand("AgregarPuestoDpto", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.AddWithValue("@ID_Dpto", idDpto)
command.Parameters.AddWithValue("@ID_Puesto", idPuesto)
command.Parameters.AddWithValue("@Porcent_Sueldo", porcentajeSueldo)
command.Parameters.AddWithValue("@Mode", 1)
connection.Open()
Command.ExecuteNonQuery()
connection.Close()
Return True
End Function
Public Function EditarPorcentSueldoPuesto(ByVal idDpto As Integer, ByVal idPuesto As Integer, ByVal porcentajeSueldo As Double) As Boolean
Dim command As New SqlCommand("AgregarPuestoDpto", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.AddWithValue("@ID_Dpto", idDpto)
command.Parameters.AddWithValue("@ID_Puesto", idPuesto)
command.Parameters.AddWithValue("@Porcent_Sueldo", porcentajeSueldo)
command.Parameters.AddWithValue("@Mode", 2)
connection.Open()
command.ExecuteNonQuery()
connection.Close()
Return True
End Function
End Class
|
Public Class Votante
Inherits Persona
Private _cedula As String
Public Property Cedula() As String
Get
Return _cedula
End Get
Set(ByVal value As String)
_cedula = value
End Set
End Property
Public Sub New(nombre As String, apellido As String, edad As Integer, cedula As String, rol As String)
Me.Nombre = nombre
Me.Apellido = apellido
Me.Edad = edad
Me.Cedula = cedula
Me.Rol = rol
End Sub
Public Overrides Function ToString() As String
Return "nombre: " & Me.Nombre & " apellido: " & Me.Apellido & " edad: " & Me.Edad & " cedula: " & Me.Cedula
End Function
End Class
|
Imports MC_FRAMEWORK
Imports MCRA_DATA
Imports DevExpress.XtraEditors
Public Class BaseDatosDetails
Dim BaseDatosBE As New BaseDatoBE
Public Sub New()
' This call is required by the designer.
InitializeComponent()
'Se inicializa los controles
Me.Text = "MANTENIMIENTO DE BASE DE DATOS"
Me.FormBorderStyle = Windows.Forms.FormBorderStyle.Sizable
Me.StartPosition = FormStartPosition.CenterScreen
Me.KeyPreview = True
Me.txtIDBaseDatos.Enabled = False
Me.txtNombre.Properties.MaxLength = 100
Me.txtCadenaConexion.Properties.MaxLength = 250
'Se inicializa los controles
ControlesDevExpress.InitRibbonControl(RibbonControl)
End Sub
Private Sub BaseDatosDetails_Load(sender As Object, e As EventArgs) Handles Me.Load
If BaseDatosDAO.IDBaseDatos = 0 Then
txtIDBaseDatos.Text = 0
Else
'Se carga la entidad
BaseDatosBE = BaseDatosDAO.GetByID(BaseDatosDAO.IDBaseDatos)
With BaseDatosBE
txtIDBaseDatos.Text = .IDBaseDatos
txtNombre.Text = .Nombre
txtCadenaConexion.Text = .CadenaConexion
End With
End If
End Sub
Private Sub BaseDatosDetails_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.Escape Then
Me.Close()
End If
End Sub
Private Sub btnGuardar_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnGuardar.ItemClick, btnGuardarCerrar.ItemClick
Try
If Validar() Then
'Se guarda el registro
BaseDatosDAO.Save(BaseDatosBE)
'Se recupera el ID autogenerado
txtIDBaseDatos.Text = BaseDatosDAO.IDBaseDatos
'Si el boton es Guardar y Cerrar, entonces se cierra el formulario
If e.Item.Caption = "Guardar y Cerrar" Then
Me.Close()
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub btnProbarConexion_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnProbarConexion.ItemClick
Dim cnx As New System.Data.SqlClient.SqlConnection
Try
If Validar() Then
cnx.ConnectionString = BaseDatosBE.CadenaConexion
cnx.Open()
MessageBox.Show("La conexión fue exitosa.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
If cnx.State = ConnectionState.Open Then
cnx.Close()
End If
End Try
End Sub
Private Sub btnCerrar_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnCerrar.ItemClick
Me.Close()
End Sub
Private Sub Control_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles txtNombre.Validating, txtCadenaConexion.Validating
With CType(sender, TextEdit)
If .Text = "" Then
.ErrorIconAlignment = ErrorIconAlignment.MiddleRight
.ErrorText = "El campo es obligatorio"
End If
End With
End Sub
Private Function Validar() As Boolean
Dim Result As Boolean = False
'Si no existe mensajes de error, entonces los controles estan validados
If String.IsNullOrEmpty(txtNombre.ErrorText) AndAlso String.IsNullOrEmpty(txtCadenaConexion.ErrorText) Then
'Se carga la entidad
With BaseDatosBE
.IDBaseDatos = txtIDBaseDatos.Text
.Nombre = txtNombre.Text.ToString.Trim
.CadenaConexion = txtCadenaConexion.Text.ToString.Trim
.IDUsuario = 1
.FechaRegistro = DateTime.Now
End With
Result = True
Else
MessageBox.Show("Es necesario ingresar los valores requeridos, antes de guardar el registro.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Return Result
End Function
End Class |
Option Explicit On
Option Strict On
' // *** Includes *** //
' // CoreFlow
Imports CFT.Web.Controls
' // General
Imports System.Text
' // *** Class Definition *** //
' NOTE: This is not promoted to CFT.Web.Controls because it would not be able to inherit the base "CoreControl" class that each project defines
' TODO: Solve this problem (or find a workaround) to allow promotion
Public MustInherit Class UpdateControl(Of typeSettings As {New}) : Inherits IWDEControl
#Region "UpdateControl - Data Members"
Protected m_strSessionKey As String
Protected m_objSettings As typeSettings
#End Region
#Region "UpdateControl - Constructors"
Protected Sub New()
Me.New(String.Empty)
End Sub
Protected Sub New(ByRef objSettings As typeSettings)
Me.New(String.Empty)
End Sub
Protected Sub New(ByVal strSessionKey As String)
Me.New(New typeSettings(), strSessionKey)
End Sub
Protected Sub New( _
ByRef objSettings As typeSettings, _
ByVal strSessionKey As String _
)
MyBase.New()
Me.m_strSessionKey = strSessionKey
Me.m_objSettings = objSettings
End Sub
#End Region
#Region "UpdateControl - Events"
' SaveSettings
Public Event SaveSettings As EventHandler
Protected Sub RaiseSaveSettingsEvent()
Me.RaiseSaveSettingsEvent(Me, Nothing)
End Sub
Protected Sub RaiseSaveSettingsEvent(ByVal sender As Object, ByVal e As System.EventArgs)
RaiseEvent SaveSettings(sender, e)
End Sub
' LoadSettings
Public Event LoadSettings As EventHandler
Protected Sub RaiseLoadSettingsEvent()
Me.RaiseLoadSettingsEvent(Me, Nothing)
End Sub
Protected Sub RaiseLoadSettingsEvent(ByVal sender As Object, ByVal e As System.EventArgs)
RaiseEvent LoadSettings(sender, e)
End Sub
#End Region
#Region "UpdateControl - Properties"
Public MustOverride Property Settings As typeSettings
#End Region
#Region "UpdateControl - Methods"
Public MustOverride Sub RefreshControl(ByRef objSettings As typeSettings)
Public MustOverride Function UpdateSettings() As typeSettings
#End Region
#Region "UpdateControl - Methods - Helpers"
Protected MustOverride Sub ClearControl()
#End Region
End Class
|
Imports System.ComponentModel
Imports FrontWork
Public Class PagerView
Implements IView
Private _currentPage as Integer = 1
Private _totalPage as Integer = 1
Private _pageSize as Integer = 50
Private _mode As String = "default"
''' <summary>
''' 总页码,从1开始
''' </summary>
''' <returns>总页码</returns>
<Description("总页码(从1开始)"), Category("FrontWork"), Browsable(False), DesignerSerializationVisibility(False)>
Public Property TotalPage as Integer
Get
Return Me._totalPage
End Get
Set(value as Integer)
If value < 1 Then throw new FrontWorkException("TotalPage must be greater than 1")
If value < Me.CurrentPage Then
throw new FrontWorkException($"TotalPage:{value} cannot be less than CurrentPage:{Me.CurrentPage}")
End If
Me._totalPage = value
Me.TextBoxTotalPage.Text = CStr(value)
End Set
End Property
''' <summary>
''' 当前页码,从1开始
''' </summary>
''' <returns>当前页码</returns>
<Description("当前页(从1开始)"), Category("FrontWork"), Browsable(False), DesignerSerializationVisibility(False)>
Public Property CurrentPage as Integer
Get
Return Me._currentPage
End Get
Set(value as Integer)
If value < 1 Then throw new FrontWorkException("Page must be greater than 1")
If value > Me.TotalPage Then
throw new FrontWorkException($"CurrentPage:{value} exceeded TotalPage:{Me.TotalPage}")
End If
Me._currentPage = value
Me.TextBoxCurrentPage.Text = CStr(value)
Dim eventArgs As New PageChangedEventArgs(value)
RaiseEvent OnCurrentPageChanged(Me, eventArgs)
End Set
End Property
''' <summary>
''' 每页大小,默认50行
''' </summary>
''' <returns></returns>
<Description("每页大小"), Category("FrontWork")>
Public Property PageSize as Integer
Get
Return Me._pageSize
End Get
Set(value as Integer)
If value <= 0 Then
throw new FrontWorkException($"PageSize:{value} must be positive!")
End If
Me._pageSize = value
End Set
End Property
''' <summary>
''' 当前模式
''' </summary>
''' <returns></returns>
<Description("当前配置模式"), Category("FrontWork")>
Public Property Mode As String
Get
Return Me._mode
End Get
Set(value As String)
Me._mode = value
End Set
End Property
''' <summary>
''' 当前页码改变事件(可能由于用户点击下一页,或者程序改变CurrentPage触发)
''' </summary>
Public Event OnCurrentPageChanged As EventHandler(Of PageChangedEventArgs)
Private Sub TableLayoutPanel1_Paint(sender As Object, e As PaintEventArgs) Handles TableLayoutPanel1.Paint
End Sub
Private Sub TextBoxCurrentPage_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBoxCurrentPage.KeyPress
If e.KeyChar = vbBack Then Return
If Not Char.IsNumber(e.KeyChar) Then
e.Handled = True
End If
End Sub
Private Sub ButtonGo_Click(sender As Object, e As EventArgs) Handles ButtonGo.Click
If Not (Me.CurrentPage >= 1 And Me.CurrentPage <= Me.TotalPage) Then
MessageBox.Show($"请输入{1}到{Me.TotalPage}之间的页码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
RaiseEvent OnCurrentPageChanged(Me, New PageChangedEventArgs(Me.CurrentPage))
End Sub
Private Sub TextBoxCurrentPage_TextChanged(sender As Object, e As EventArgs) Handles TextBoxCurrentPage.TextChanged
If String.IsNullOrEmpty(Me.TextBoxCurrentPage.Text) Then
Me._currentPage = -1
Return
End If
Me._currentPage = CInt(Me.TextBoxCurrentPage.Text)
End Sub
Private Sub ButtonNextPage_Click(sender As Object, e As EventArgs) Handles ButtonNextPage.Click
If Me.CurrentPage = -1 Then
Me.CurrentPage = 1
Return
End If
If Me.CurrentPage >= Me.TotalPage Then Return
Me.CurrentPage += 1
End Sub
Private Sub ButtonEndPage_Click(sender As Object, e As EventArgs) Handles ButtonEndPage.Click
If Me.CurrentPage = Me.TotalPage Then Return
Me.CurrentPage = Me.TotalPage
End Sub
Private Sub ButtonPreviousPage_Click(sender As Object, e As EventArgs) Handles ButtonPreviousPage.Click
If Me.CurrentPage = -1 Then
Me.CurrentPage = 1
Return
End If
If Me.CurrentPage <= 1 Then Return
Me.CurrentPage -= 1
End Sub
Private Sub ButtonStartPage_Click(sender As Object, e As EventArgs) Handles ButtonStartPage.Click
If Me.CurrentPage = 1 Then Return
Me.CurrentPage = 1
End Sub
End Class
|
Imports System
Imports Microsoft.VisualBasic
Imports ChartDirector
Public Class icondonut
Implements DemoModule
'Name of demo module
Public Function getName() As String Implements DemoModule.getName
Return "Icon Donut Chart"
End Function
'Number of charts produced in this demo module
Public Function getNoOfCharts() As Integer Implements DemoModule.getNoOfCharts
Return 1
End Function
'Main code for creating chart.
'Note: the argument chartIndex is unused because this demo only has 1 chart.
Public Sub createChart(viewer As WinChartViewer, chartIndex As Integer) _
Implements DemoModule.createChart
' The data for the pie chart
Dim data() As Double = {72, 18, 15, 12}
' The depths for the sectors
Dim depths() As Double = {30, 20, 10, 10}
' The labels for the pie chart
Dim labels() As String = {"Sunny", "Cloudy", "Rainy", "Snowy"}
' The icons for the sectors
Dim icons() As String = {"sun.png", "cloud.png", "rain.png", "snowy.png"}
' Create a PieChart object of size 400 x 300 pixels
Dim c As PieChart = New PieChart(400, 300)
' Use the semi-transparent palette for this chart
c.setColors(Chart.transparentPalette)
' Set the background to metallic light blue (CCFFFF), with a black border and 1 pixel 3D
' border effect,
c.setBackground(Chart.metalColor(&Hccccff), &H000000, 1)
' Set donut center at (200, 175), and outer/inner radii as 100/50 pixels
c.setDonutSize(200, 175, 100, 50)
' Add a title box using 15pt Times Bold Italic font and metallic blue (8888FF) background
' color
c.addTitle("Weather Profile in Wonderland", "Times New Roman Bold Italic", 15 _
).setBackground(Chart.metalColor(&H8888ff))
' Set the pie data and the pie labels
c.setData(data, labels)
' Add icons to the chart as a custom field
c.addExtraField(icons)
' Configure the sector labels using CDML to include the icon images
c.setLabelFormat( _
"<*block,valign=absmiddle*><*img={field0}*> <*block*>{label}<*br*>{percent}%<*/*><*/*>")
' Draw the pie in 3D with variable 3D depths
c.set3D2(depths)
' Set the start angle to 225 degrees may improve layout when the depths of the sector are
' sorted in descending order, because it ensures the tallest sector is at the back.
c.setStartAngle(225)
' Output the chart
viewer.Chart = c
'include tool tip for the chart
viewer.ImageMap = c.getHTMLImageMap("clickable", "", _
"title='{label}: {value} days ({percent}%)'")
End Sub
End Class
|
Option Explicit On
Option Strict On
' // *** Includes *** //
' // General
Imports System.Text
' // *** Class Definition *** //
Public Class SkinAsset
#Region "SkinAsset - Data Members"
' Instance Members
Protected m_intAssetID As Integer
Protected m_intSkinID As Integer
Protected m_intWebsiteID As Integer
' Direct data
Protected m_strName As String
Protected m_strFilename As String
Protected m_strExportPath As String
Protected m_strFileSystemPath As String
#End Region
#Region "SkinAsset - Constructors"
Public Sub New()
End Sub
Public Sub New(
ByVal intAssetID As Integer,
ByVal intSkinID As Integer,
ByVal intWebsiteID As Integer,
ByVal strName As String,
ByVal strFilename As String,
ByVal strExportPath As String,
ByVal strFileSystemPath As String
)
Me.m_intAssetID = intAssetID
Me.m_intSkinID = intSkinID
Me.m_intWebsiteID = intWebsiteID
Me.m_strName = strName
Me.m_strFilename = strFilename
Me.m_strExportPath = strExportPath
Me.m_strFileSystemPath = strFileSystemPath
End Sub
#End Region
#Region "SkinAsset - Properties"
Public ReadOnly Property AssetID As Integer
Get
Return (Me.m_intAssetID)
End Get
End Property
Public ReadOnly Property SkinID As Integer
Get
Return (Me.m_intSkinID)
End Get
End Property
Public Property Name As String
Get
Return (Me.m_strName)
End Get
Set(ByVal strValue As String)
Me.m_strName = strValue
End Set
End Property
Public Property Filename As String
Get
Return (Me.m_strFilename)
End Get
Set(ByVal strValue As String)
Me.m_strFilename = strValue
End Set
End Property
Public Property ExportPath As String
Get
Return (Me.m_strExportPath)
End Get
Set(ByVal strValue As String)
Me.m_strExportPath = strValue
End Set
End Property
Public Property FileSystemPath As String
Get
Return (Me.m_strFileSystemPath)
End Get
Set(ByVal strValue As String)
Me.m_strFileSystemPath = strValue
End Set
End Property
#End Region
#Region "SkinAsset - Methods"
#End Region
#Region "SkinAsset - Methods - Helpers"
#End Region
End Class
|
<Authorize(Roles:="ViewOnly")>
Public Class ReportsController
Inherits Controller
<AllowAnonymous>
Function Index() As ActionResult
Return RedirectToAction("WorkCompleted")
End Function
Function WorkCompleted(Optional ByVal CustomerID As Integer = 0, Optional ByVal CrewID As Integer = 0, Optional ByVal StartDate? As Date = Nothing, Optional ByVal EndDate? As Date = Nothing, Optional ByVal SetDefault As Boolean = True) As ActionResult
Dim myWork As List(Of tWork)
Dim myCustomers As List(Of tCustomer)
Dim myCrews As List(Of tCrew)
If SetDefault = True Then
If StartDate.HasValue = False Then
StartDate = CDate(Now.AddMonths(-1).Month & "/01/" & Now.AddMonths(-1).Year)
End If
If EndDate.HasValue = False Then EndDate = StartDate.Value.AddMonths(1).AddDays(-1)
End If
myWork = JobSite.Work.listWork(CustomerID, CrewID, StartDate, EndDate, User.RestrictedCrewIDs)
myCustomers = JobSite.Customer.listCustomers()
myCrews = JobSite.Crew.listCrew()
ViewData("CustomerID") = CustomerID
ViewData("CrewID") = CrewID
ViewData("StartDate") = StartDate
ViewData("EndDate") = EndDate
ViewData("SetDefault") = SetDefault
ViewData("Customers") = myCustomers
ViewData("Crews") = myCrews
Return View(myWork)
End Function
<HttpPost>
<AllowAnonymous>
Function FilterWorkCompleted(ByVal CustomerID As Integer, ByVal CrewID As Integer, ByVal StartDate As String, ByVal EndDate As String, ByVal SetDefault As Boolean) As ActionResult
Return RedirectToAction("WorkCompleted", New With {.CustomerID = CustomerID, .CrewID = CrewID, .StartDate = StartDate, .EndDate = EndDate, .SetDefault = SetDefault})
End Function
End Class
|
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
<TestClass()> Public Class FuncCallTest
<TestMethod()> Public Sub Primitive_call()
Assert.AreEqual(
"""fox""",
Intrigue.Interpreter.DoEval(
Util.NewString(
<![CDATA[
define a " fox "
call a "Trim"
]]>)).ToString)
End Sub
End Class
|
Namespace SomeERP
Public Class DataContext
Private _Customers As CustomerDataManager
Public ReadOnly Property Customers As CustomerDataManager
Get
If (_Customers Is Nothing) Then
_Customers = New CustomerDataManager
End If
Return _Customers
End Get
End Property
End Class
End Namespace
|
'Employee bonus application
'Hong Cui 2/16/2014
Option Strict On 'all data conversion will be performed explicitly
Public Class Form1
Private Sub SubmitButton_Click(sender As Object, e As EventArgs) Handles SubmitButton.Click
'declare all input and output data
Dim name As String = ""
Dim salary As Decimal = 0D
Dim year As Integer = 0
Dim bonus As Decimal = 0D
'call GetInoputs to get all input data and return these data
GetInputs(name, salary, year)
'call CalculateBonus function calculate and return bonus
bonus = CalculateBonus(salary, year)
'call DisplayResults method to display the output data
DisplayResults(name, salary, year, bonus)
'show controls of output view
ResultListBox.Visible = True
BackButton.Visible = True
'Hide submit button
SubmitButton.Visible = False
End Sub
Private Sub BackButton_Click(sender As Object, e As EventArgs) Handles BackButton.Click
'hide controls of output view
ResultListBox.Visible = False
BackButton.Visible = False
'show Submit button
SubmitButton.Visible = True
'clear the previous input data
NameTextBox.Text = ""
SalaryTextBox.Text = ""
YearTextBox.Text = ""
End Sub
'method to get all input data and return to the caller
'3 input data will be returned, so this could not be a function since function only returns 1 data
'sub does not have Return statement, so 3 ByRef parameters (memory locations) are needed
'input data will be saved in passed memory locations directly
Sub GetInputs(ByRef name As String, ByRef sal As Decimal, ByRef year As Integer)
name = NameTextBox.Text
sal = Convert.ToDecimal(Val(SalaryTextBox.Text))
year = Convert.ToInt32(Val(YearTextBox.Text))
End Sub
'function to calculate and return bonus
Function CalculateBonus(sal As Decimal, year As Integer) As Decimal
Dim bonus As Decimal
If sal < 50000 Then
If year >= 10 Then
bonus = Convert.ToDecimal(sal * 0.05)
Else
bonus = Convert.ToDecimal(sal * 0.03)
End If
Else
bonus = 0D
End If
Return bonus
End Function
'method to display output ionformation
'Only the copies of employee's data are needed, so ByVal (can be skipped) parameters are passed
Sub DisplayResults(name As String, sal As Decimal, year As Integer, bonus As Decimal)
ResultListBox.Items.Clear() 'clear the previous outputs
ResultListBox.Items.Add("Name: " & name)
ResultListBox.Items.Add(String.Format("Salary: {0:c2}", sal))
ResultListBox.Items.Add("Year: " & year)
ResultListBox.Items.Add(String.Format("Bonus: {0:c2}", bonus))
End Sub
End Class
|
Imports Microsoft.Xna.Framework.Content
Imports Microsoft.Xna.Framework.Graphics
Public Class Fonts
Public Class ChakraPetch
Public Shared Normal As SpriteFont ' Loaded at program start
''' <summary>
''' Font Size: 32
''' </summary>
Public Shared Large As SpriteFont ' Loaded at program start
''' <summary>
''' Font Size: 90
''' </summary>
Public Shared ExtraLarge As SpriteFont
End Class
Public Shared Sub LoadContent(content As ContentManager)
ChakraPetch.ExtraLarge = content.Load(Of SpriteFont)("Fonts/ChakraPetch/ChakraPetch-ExtraLarge")
End Sub
End Class
|
Imports DevExpress.Xpo
Imports DevExpress.Data.Filtering
Imports DevExpress.Persistent.Base
''' <summary>
'''
''' </summary>
''' <remarks></remarks>
<Persistent("Sales.PurchaseHeader"), DefaultClassOptions()>
Public Class Sales_PurchaseHeader
Inherits Base_DocumentHeader
''' <summary>
'''
''' </summary>
''' <param name="session"></param>
''' <remarks></remarks>
Public Sub New(ByVal session As Session)
MyBase.New(session)
End Sub
''' <summary>
'''
''' </summary>
''' <remarks></remarks>
Public Overrides Sub AfterConstruction()
MyBase.AfterConstruction()
ShipToAddress = Session.FindObject(Of TPF_Address)(CriteriaOperator.Parse("ShipToName=?", "TRAVIS PATTERN"))
DocType = DocumentType.PurchaseOrder
DocNumber = String.Format("{0}{1:yyMMddHHmmss}", Branch.Abreviation, DateTime.Now)
End Sub
Private _supplier As TPF_Vendor
Private _shipToAddress As TPF_Address
Private _remarks As String
Private _contact As String
Private _verifiedBy As TPF_Employee
Private _verifiedAt As DateTime
''' <summary>
''' The detail items associated with this purchase order
''' </summary>
Public ReadOnly Property PurchaseOrderDetails As XPCollection(Of Sales_PurchaseDetail)
Get
Return New XPCollection(Of Sales_PurchaseDetail)(Session, Detail)
End Get
End Property
''' <summary>
''' Add Vendor Object after creating view.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
<Association("Vendor-PurchaseOrder")>
Public Property Supplier As TPF_Vendor
Get
Return _supplier
End Get
Set(ByVal Value As TPF_Vendor)
SetPropertyValue("Supplier", _supplier, Value)
End Set
End Property
''' <summary>
'''
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public ReadOnly Property BillToAddress As SYSPRO_ApSupplierAddr
Get
' If bill to address is not available default to TPF. BV 10/30/2014
If IsNothing(Organization) AndAlso Not (IsLoading) Then
Return Session.FindObject(Of SYSPRO_ApSupplierAddr)(CriteriaOperator.Parse("Supplier = '0441640'"))
ElseIf Supplier IsNot Nothing Then
Return Session.FindObject(Of SYSPRO_ApSupplierAddr)(CriteriaOperator.Parse(String.Format("Supplier = '{0}'", Supplier.Supplier.Supplier))) 'Supplier.Supplier.Supplier)))
End If
Return Nothing
End Get
End Property
''' <summary>
'''
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property Contact As String
Get
Return _contact
End Get
Set(ByVal Value As String)
SetPropertyValue("Contact", _contact, Value)
End Set
End Property
''' <summary>
'''
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
<Size(SizeAttribute.Unlimited)>
Public Property Remarks As String
Get
Return _remarks
End Get
Set(ByVal Value As String)
SetPropertyValue("Remarks", _remarks, Value)
End Set
End Property
''' <summary>
'''
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property ShipToAddress As TPF_Address
Get
Return _shipToAddress
End Get
Set(ByVal Value As TPF_Address)
SetPropertyValue("ShipToAddress", _shipToAddress, Value)
End Set
End Property
''' <summary>
''' Set to true if all ordered items/quantities on this PO have been received by the purchaser
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public ReadOnly Property Received As Boolean
Get
Return PurchaseOrderDetails.Where(Function(x) x.Received = False).Count() = 0
End Get
End Property
''' <summary>
''' The employee who verified that this PO was received
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property VerifiedBy As TPF_Employee
Get
Return _verifiedBy
End Get
Set(ByVal Value As TPF_Employee)
SetPropertyValue("VerifiedBy", _verifiedBy, Value)
End Set
End Property
''' <summary>
''' The date/time that this PO was verified to have been received
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property VerifiedAt As DateTime
Get
Return _verifiedAt
End Get
Set(ByVal Value As DateTime)
SetPropertyValue("VerifiedAt", _verifiedAt, Value)
End Set
End Property
''' <summary>
'''
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public ReadOnly Property CombinedAddress As String
Get
If BillToAddress IsNot Nothing Then
Return String.Format("{0} {1} {2} {3} {4} {5}", BillToAddress.SupAddr1, BillToAddress.SupAddr2, BillToAddress.SupAddr3,
BillToAddress.SupAddr4, BillToAddress.SupAddr5, BillToAddress.SupPostalCode)
End If
Return ""
End Get
End Property
End Class
|
Public Class DBO_GestionesPendientes
inherits BasesParaCompatibilidad.DataBussines
Private m_Id As BasesParaCompatibilidad.DataBussinesParameter
Private m_Descripcion As BasesParaCompatibilidad.DataBussinesParameter
Private m_Fecha As BasesParaCompatibilidad.DataBussinesParameter
Private m_PersonaContactada As BasesParaCompatibilidad.DataBussinesParameter
Private m_MedioContacto As BasesParaCompatibilidad.DataBussinesParameter
Private m_PendienteID As BasesParaCompatibilidad.DataBussinesParameter
Public Sub New()
MyBase.New()
m_Id = New BasesParaCompatibilidad.DataBussinesParameter("@GestionPendienteID","GestionPendienteID")
m_Descripcion= New BasesParaCompatibilidad.DataBussinesParameter("@Descripcion","Descripcion")
m_Fecha= New BasesParaCompatibilidad.DataBussinesParameter("@Fecha","Fecha")
m_PersonaContactada= New BasesParaCompatibilidad.DataBussinesParameter("@PersonaContactada","PersonaContactada")
m_MedioContacto= New BasesParaCompatibilidad.DataBussinesParameter("@MedioContacto","MedioContacto")
m_PendienteID= New BasesParaCompatibilidad.DataBussinesParameter("@PendienteID","PendienteID")
MyBase.primaryKey = m_Id
aņadirParametros()
End Sub
Public Property ID() As Int32
Get
if m_id.value is convert.dbnull then
Return 0
End if
Return ctype(m_id.value,int32)
End Get
Set(ByVal value As Int32)
Me.primaryKey.value = value
m_id.value = value
End Set
End Property
Public Property Descripcion() As String
Get
if m_Descripcion.value is convert.dbnull then
Return string.empty
End if
Return ctype(m_Descripcion.value,string)
End Get
Set(ByVal value As String)
m_Descripcion.value = value
End Set
End Property
Public Property Fecha() As Date
Get
If m_Fecha.value Is Convert.DBNull Then
Return Today.Date
End If
Return CType(m_Fecha.value, Date)
End Get
Set(ByVal value As Date)
m_Fecha.value = value
End Set
End Property
Public Property PersonaContactada() As String
Get
if m_PersonaContactada.value is convert.dbnull then
Return string.empty
End if
Return ctype(m_PersonaContactada.value,string)
End Get
Set(ByVal value As String)
m_PersonaContactada.value = value
End Set
End Property
Public Property MedioContacto() As String
Get
if m_MedioContacto.value is convert.dbnull then
Return string.empty
End if
Return ctype(m_MedioContacto.value,string)
End Get
Set(ByVal value As String)
m_MedioContacto.value = value
End Set
End Property
Public Property PendienteID() As Int32
Get
if m_PendienteID.value is convert.dbnull then
Return 0
End if
Return ctype(m_PendienteID.value,int32)
End Get
Set(ByVal value As Int32)
m_PendienteID.value = value
End Set
End Property
Private Sub aņadirParametros()
MyBase.atributos.Add(m_Id, m_Id.sqlName)
MyBase.atributos.Add(m_Descripcion, m_Descripcion.sqlName)
MyBase.atributos.Add(m_Fecha, m_Fecha.sqlName)
MyBase.atributos.Add(m_PersonaContactada, m_PersonaContactada.sqlName)
MyBase.atributos.Add(m_MedioContacto, m_MedioContacto.sqlName)
MyBase.atributos.Add(m_PendienteID, m_PendienteID.sqlName)
End Sub
End Class
|
'------------------------------------------------------
' InstantiateHelloWorld.vb (c) 2002 by Charles Petzold
'------------------------------------------------------
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Module InstantiateHelloWorld
Sub Main()
Dim frm As New HelloWorld()
frm.Text = "Instantiate " & frm.Text
AddHandler frm.Paint, AddressOf MyPaintHandler
Application.Run(frm)
End Sub
Sub MyPaintHandler(ByVal obj As Object, ByVal pea As PaintEventArgs)
Dim frm As Form = DirectCast(obj, Form)
Dim grfx As Graphics = pea.Graphics
grfx.DrawString("Hello from InstantiateHelloWorld!", _
frm.Font, Brushes.Black, 0, 100)
End Sub
End Module
|
#Region "Copyright (C) 2005-2011 Team MediaPortal"
' Copyright (C) 2005-2011 Team MediaPortal
' http://www.team-mediaportal.com
'
' MediaPortal 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 2 of the License, or
' (at your option) any later version.
'
' MediaPortal 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 MediaPortal. If not, see <http://www.gnu.org/licenses/>.
#End Region
Imports System
Imports System.Collections.Generic
Imports Gentle.Framework
Namespace TvDatabase
''' <summary>
''' Instances of this class represent the properties and methods of a row in the table <b>TvMovieSeriesMapping</b>.
''' </summary>
<TableName("TvMovieSeriesMapping")> _
Public Class TvMovieSeriesMapping
Inherits Persistent
#Region "Members"
Private m_isChanged As Boolean
<TableColumn("idSeries", NotNull:=True), PrimaryKey(AutoGenerated:=False)> _
Private m_idSeries As Integer
<TableColumn("disabled", NotNull:=True)> _
Private m_disabled As Boolean
<TableColumn("TvSeriesTitle", NotNull:=True)> _
Private m_TvSeriesTitle As String
<TableColumn("EpgTitle", NotNull:=True)> _
Private m_EpgTitle As String
<TableColumn("minSeasonNum", NotNull:=True)> _
Private m_minSeasonNum As Integer
#End Region
#Region "Constructors"
''' <summary>
''' Create an object from an existing row of data. This will be used by Gentle to
''' construct objects from retrieved rows.
''' </summary>
Public Sub New(ByVal idSeries As Integer)
Me.m_idSeries = idSeries
End Sub
#End Region
#Region "Public Properties"
''' <summary>
''' Indicates whether the entity is changed and requires saving or not.
''' </summary>
Public ReadOnly Property IsChanged() As Boolean
Get
Return m_isChanged
End Get
End Property
''' <summary>
''' Property relating to database column idSeries
''' </summary>
Public Property idSeries() As Integer
Get
Return m_idSeries
End Get
Set(ByVal value As Integer)
m_isChanged = m_isChanged Or m_idSeries <> value
m_idSeries = value
End Set
End Property
Public Property disabled() As Boolean
Get
Return m_disabled
End Get
Set(ByVal value As Boolean)
m_isChanged = m_isChanged Or m_disabled <> value
m_disabled = value
End Set
End Property
Public Property TvSeriesTitle() As String
Get
Return m_TvSeriesTitle
End Get
Set(ByVal value As String)
m_isChanged = m_isChanged Or m_TvSeriesTitle <> value
m_TvSeriesTitle = value
End Set
End Property
Public Property EpgTitle() As String
Get
Return m_EpgTitle
End Get
Set(ByVal value As String)
m_isChanged = m_isChanged Or m_EpgTitle <> value
m_EpgTitle = value
End Set
End Property
Public Property minSeasonNum() As String
Get
Return m_minSeasonNum
End Get
Set(ByVal value As String)
m_isChanged = m_isChanged Or m_minSeasonNum <> value
m_minSeasonNum = value
End Set
End Property
#End Region
#Region "Storage and Retrieval"
''' <summary>
''' Static method to retrieve all instances that are stored in the database in one call
''' </summary>
Public Shared Function ListAll() As IList(Of TvMovieSeriesMapping)
Return Gentle.Framework.Broker.RetrieveList(Of TvMovieSeriesMapping)()
End Function
''' <summary>
''' Retrieves an entity given it's id.
''' </summary>
Public Overloads Shared Function Retrieve(ByVal idSeries As Integer) As TvMovieSeriesMapping
Dim key As New Key(GetType(TvMovieSeriesMapping), True, "idSeries", idSeries)
Return Gentle.Framework.Broker.RetrieveInstance(Of TvMovieSeriesMapping)(key)
End Function
''' <summary>
''' Retrieves an entity given it's id, using Gentle.Framework.Key class.
''' This allows retrieval based on multi-column keys.
''' </summary>
Public Overloads Shared Function Retrieve(ByVal key As Key) As TvMovieSeriesMapping
Return Gentle.Framework.Broker.RetrieveInstance(Of TvMovieSeriesMapping)(key)
End Function
''' <summary>
''' Persists the entity if it was never persisted or was changed.
''' </summary>
Public Overrides Sub Persist()
If IsChanged OrElse Not IsPersisted Then
Try
MyBase.Persist()
Catch ex As Exception
MyLog.Error("Exception in TvMovieSeriesMapping.Persist() with Message {0}", ex.Message)
Return
End Try
m_isChanged = False
End If
End Sub
#End Region
#Region "Relations"
''' <summary>
''' alle TvMovieProgram laden (Episoden im EPG)
''' </summary>
<CLSCompliant(False)> _
Public Function ReferencedTvMovieProgramList() As IList(Of TVMovieProgram)
Dim key As New Key(GetType(TVMovieProgram), True, "idSeries", idSeries)
Return Gentle.Framework.Broker.RetrieveList(Of TVMovieProgram)(key)
End Function
#End Region
Public Sub Delete()
Dim list As IList(Of TvMovieSeriesMapping) = ListAll()
For Each map As TvMovieSeriesMapping In list
map.Remove()
Next
'Remove()
End Sub
End Class
End Namespace
|
Enum motorAddress
MsX = 0 ' MsX,FA,X¶b,R0-0-0
MsY = 1 ' MsY,FA,Y¶b,R0-0-1
MsZ = 2 ' MsZ,FA,Z¶b,R0-0-2
MpUV = 3 ' MpUV,FA,UV¥ú±½´y,R0-0-3
End Enum
|
Public Class employee
Private firstnamevalue As String
Private lastniamevalue As String
Private Shared countvalue As Integer
Public Sub New(ByVal first As String, ByVal last As String)
firstnamevalue = first
lastniamevalue = last
countvalue += 1
End Sub
Public ReadOnly Property firstname() As String
Get
Return firstnamevalue
End Get
End Property
Public ReadOnly Property lastname() As String
Get
Return lastniamevalue
End Get
End Property
Public Shared ReadOnly Property count() As Integer
Get
Return countvalue
End Get
End Property
End Class
|
Option Explicit On
Option Strict On
'BakeryItem.vb
'Created By: Anmar Khazal 2013-12-04
Public Class BakeryItem
Private m_name As String
Private m_price As Double
Public Sub New(name As String, price As Double)
m_name = name
m_price = price
End Sub
Public Property Name() As String
Get
Return m_name
End Get
Set(ByVal value As String)
If Not String.IsNullOrEmpty(value) Then
m_name = value
End If
End Set
End Property
Public Property Price() As Double
Get
Return m_price
End Get
Set(ByVal value As Double)
m_price = value
End Set
End Property
''' <summary>
''' Checks if item of producttype is a cake or cookie
''' </summary>
''' <param name="item"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function IsItemCake(item As ProductType) As Boolean
If item.Equals(ProductType.Cookies) Then
Return False
Else
Return True
End If
End Function
''' <summary>
''' This function deletes the "_"s from products names
''' </summary>
''' <returns>The product string without "_" char</returns>
''' <remarks></remarks>
Public Function GetProductString(item As ProductType) As String
Dim strOut As String = item.ToString().Replace("_", " ").Trim()
Return strOut
End Function
''' <summary>
''' This function deletes the "_"s from all products names
''' </summary>
''' <returns>The products strings without "_" chars</returns>
''' <remarks></remarks>
Public Function GetProductStrings() As String()
Dim strOut As New List(Of String)
Dim items As Array
items = System.Enum.GetValues(GetType(ProductType))
For Each item As ProductType In items
strOut.Add(GetProductString(item))
Next
Dim productStrings As String() = strOut.ToArray()
Return productStrings
End Function
Public Overrides Function ToString() As String
Dim strOut As String = String.Format("Name: {0} {2}Price: {1} kr", Name, Price, Environment.NewLine)
Return strOut
End Function
End Class
|
Imports System.Runtime.CompilerServices
Imports System.Data.Objects.DataClasses
Namespace Extension
Public Module EDMXExtension
<Extension()> _
Public Function LazyLoad(Of T As {Class, IEntityWithRelationships})(ByVal collection As EntityCollection(Of T)) As EntityCollection(Of T)
If Not collection.IsLoaded Then
collection.Load()
End If
Return collection
End Function
<Extension()> _
Public Sub LazyLoad(Of T As {Class, IEntityWithRelationships})(ByVal reference As EntityReference(Of T))
If Not reference.IsLoaded Then
reference.Load()
End If
End Sub
End Module
End Namespace |
Imports System.Runtime.Serialization
Namespace Route4MeSDK.DataTypes
<DataContract> _
Public NotInheritable Class Links
<DataMember(Name:="route")> _
Public Property Route As String
<DataMember(Name:="view")> _
Public Property View As String
<DataMember(Name:="optimization_problem_id")> _
Public Property OptimizationProblemId As String
End Class
End Namespace
|
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.Caching
Imports System.Xml.Linq
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object,
ByVal e As EventArgs)
Dim cache As ObjectCache = MemoryCache.Default
Dim usernameFromXml As String =
TryCast(cache("userFromXml"), String)
If usernameFromXml Is Nothing Then
Dim userFilePath As New List(Of String)()
userFilePath.Add("C:\Username.xml")
Dim policy As New CacheItemPolicy()
policy.ChangeMonitors.Add(New HostFileChangeMonitor(userFilePath))
Dim xdoc As XDocument =
XDocument.Load("C:\Username.xml")
Dim query = From u In xdoc.Elements("usernames")
Select u.Value
usernameFromXml = query.First().ToString()
cache.Set("userFromXml", usernameFromXml, policy)
End If
Label1.Text = usernameFromXml
End Sub
End Class
|
Imports StudentSection.DomainClasses
Namespace DataLayer
Public Class DraftRepository
Implements IDraftRepository
Protected oContext As BaseContext
#Region "Constructors"
Public Sub New()
Dim uow As New UnitOfWorkStudentSection()
oContext = uow.Context
End Sub
Public Sub New(uow As UnitOfWorkStudentSection)
oContext = uow.Context
End Sub
#End Region
Public Sub Add(oEntity As DraftPick) Implements IEntityRepository(Of DraftPick).Add
oContext.DraftPicks.Add(oEntity)
End Sub
Public Sub Remove(oEntity As DraftPick) Implements IEntityRepository(Of DraftPick).Remove
oContext.DraftPicks.Find(oEntity.DraftPickId)
oContext.DraftPicks.Remove(oEntity)
End Sub
Public Function All() As IQueryable(Of DraftPick) Implements IEntityRepository(Of DraftPick).All
Return oContext.DraftPicks
End Function
Public Function Find(predicate As Expressions.Expression(Of Func(Of DraftPick, Boolean))) As IQueryable(Of DraftPick) Implements IEntityRepository(Of DraftPick).Find
Return oContext.DraftPicks.Where(predicate)
End Function
Public Function FindById(Id As Integer) As DraftPick Implements IEntityRepository(Of DraftPick).FindById
Return oContext.DraftPicks.Single(Function(t) t.DraftPickId = Id)
End Function
Public Function GetLastDraftPick(leagueId As Integer, year As Integer) As DraftPick Implements IDraftRepository.GetLastDraftPick
Dim maxPick = oContext.DraftPicks.Where(Function(d) d.Team.LeagueId = leagueId And d.Year = year) _
.Select(Function(d) d.PickNumberOverall).DefaultIfEmpty().Max()
Dim lastPick As DraftPick = (From d In oContext.DraftPicks
Where d.Team.LeagueId = leagueId And d.Year = year And d.PickNumberOverall = maxPick).SingleOrDefault()
Return lastPick
End Function
Public Function GetNextAvailableDraftPick(leagueId As Integer, year As Integer) As DraftPick Implements IDraftRepository.GetNextAvailableDraftPick
Dim minPick = oContext.DraftPicks.Where(Function(d) d.Team.LeagueId = leagueId And d.Year = year And d.AthleteId.Equals(Nothing)) _
.Select(Function(d) d.PickNumberOverall).DefaultIfEmpty().Min()
Dim lastPick As DraftPick = (From d In oContext.DraftPicks
Where d.Team.LeagueId = leagueId And d.Year = year And d.PickNumberOverall = minPick).SingleOrDefault()
Return lastPick
End Function
Public Function GetLastDraftRound(leagueId As Integer, year As Integer) As List(Of DraftPick) Implements IDraftRepository.GetLastDraftRound
Dim maxRound = oContext.DraftPicks.Where(Function(d) d.Team.LeagueId = leagueId And d.Year = year) _
.Select(Function(d) d.Round).DefaultIfEmpty().Max()
Dim lastRound = oContext.DraftPicks.Where(Function(d) d.Round = maxRound And d.Team.LeagueId = leagueId And d.Year = year).OrderBy(Function(x) x.PickNumberOverall)
Return lastRound.ToList()
End Function
Public Function GetDraftResults(leagueId As Integer, year As Integer) As IQueryable(Of DraftPick) Implements IDraftRepository.GetDraftResults
Dim draftResults = From d In oContext.DraftPicks
Where d.Team.LeagueId = leagueId And d.Year = year
Order By d.PickNumberOverall
Return draftResults
End Function
Public Function GetDraftResultsForTeam(teamId As Integer, year As Integer) As ICollection(Of DraftPick) Implements IDraftRepository.GetDraftResultsForTeam
Dim draftResults = From d In oContext.DraftPicks
Where d.Team.TeamId = teamId And d.Year = year
Order By d.PickNumberOverall
Return draftResults.ToList()
End Function
Public Function DraftPicksCountForTeamIncludeLocal(teamId As Integer, year As Integer) As Integer Implements IDraftRepository.DraftPicksCountForTeamIncludeLocal
Dim draftResults = From d In oContext.DraftPicks
Where d.Team.TeamId = teamId And d.Year = year
Order By d.PickNumberOverall
Dim localResults = From d In oContext.DraftPicks.Local
Where d.Team.TeamId = teamId And d.Year = year
Order By d.PickNumberOverall
Dim totalAthletes As Integer = localResults.Union(draftResults).Distinct.Count()
Return totalAthletes
End Function
End Class
End Namespace
|
Imports System.ComponentModel
Public Class PlcConfigurator
#Region "Common properites"
<Category("#Common properties"), Browsable(True)>
<Description("The IP address of the PLC endpoint")>
Public Property IpAddress() As String
<Category("#Common properties"), Browsable(True)>
<Description("The name of the PLC")>
Public Property Name() As String
<Category("#Common properties"), Browsable(True)>
<Description("The maximum number of threads for PLC thread pool")>
Public Property MaxThreads() As Int16
<Category("#Common properties"), Browsable(True)>
<Description("The brand of the PLC: Siemens or Omron")>
Public Property PlcBrand() As Plc.PlcBrand
#End Region
#Region "Siemens properties"
<Category("#Siemens properties"), Browsable(True)>
<Description("The Rack number, usually 0")>
Public Property RackNum() As Int16
<Category("#Siemens properties"), Browsable(True)>
<Description("The Slot number, usually 1")>
Public Property SlotNum() As Int16
#End Region
#Region "Omron properties"
#End Region
End Class
|
Namespace Global.Sorting
Public Module SortingAlgorithms
Public Sub BubbleSort(ByRef arr As Integer())
If (arr.Length = 1) Then Return
Dim n As Integer = arr.Length
For i As Integer = 0 To n - 2
Dim swapped As Boolean = False
For j = 0 To n - 2
If (arr(j) > arr(j + 1)) Then
Dim v As Integer = arr(j)
arr(j) = arr(j + 1)
arr(j + 1) = v
swapped = True
End If
Next
If Not swapped Then
Exit For
End If
Next
End Sub
Public Sub InsertionSort(ByRef arr As Integer())
For i As Integer = 1 To arr.Length - 1
Dim j As Integer = i
While j > 0 AndAlso arr(j - 1) > arr(j)
Dim v As Integer = arr(j)
arr(j) = arr(j - 1)
arr(j - 1) = v
j -= 1
End While
Next
End Sub
Public Sub SelectionSort(ByRef arr As Integer())
Dim len As Integer = arr.Length
For i As Integer = 0 To len - 2 '' < len - 1, in C#.
Dim min = i
For j As Integer = i + 1 To len - 1
If (arr(j) < arr(min)) Then
min = j
End If
Next
If (min <> i) Then
Dim value As Integer = arr(i)
arr(i) = arr(min)
arr(min) = value
End If
Next
End Sub
Public Sub Quicksort(ByRef arr As Integer())
Quicksort(arr, 0, arr.Length - 1)
End Sub
Private Sub Quicksort(ByRef arr As Integer(),
ByVal lower As Integer,
ByVal upper As Integer)
If (lower < upper) Then
Dim p As Integer = Partition(arr, lower, upper)
Quicksort(arr, lower, p - 1)
Quicksort(arr, p + 1, upper)
End If
End Sub
Private Function Partition(ByRef arr As Integer(),
ByVal lower As Integer,
ByVal upper As Integer) As Integer
Dim pivot As Integer = arr(upper)
Dim i = lower - 1
For j As Integer = lower To upper - 1
If (arr(j) < pivot) Then
i += 1
Dim value As Integer = arr(i)
arr(i) = arr(j)
arr(j) = value
End If
Next
Dim swap As Integer = arr(i + 1)
arr(i + 1) = arr(upper)
arr(upper) = swap
Return i + 1
End Function
End Module
End Namespace
|
Namespace Dominios
Public Class CategoriasTorneo
Private _categoria As String
Private _cuposDisponibles As Integer
Private _precioInscripcion As Decimal
Public Property Categoria As String
Get
Return _categoria
End Get
Set(value As String)
_categoria = value
End Set
End Property
Public Property CuposDisponibles As Integer
Get
Return _cuposDisponibles
End Get
Set(value As Integer)
_cuposDisponibles = value
End Set
End Property
Public Property PrecioInscripcion As Decimal
Get
Return _precioInscripcion
End Get
Set(value As Decimal)
_precioInscripcion = value
End Set
End Property
End Class
End Namespace
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.