text stringlengths 43 2.01M |
|---|
Module RichTextBoxExModule
' see if keystrokes are given for special characters
Public Sub CheckForSpecialCharacters(tb As TextBox, e As KeyEventArgs)
Dim InsertionText As String = ""
If Not e.Control Then
Exit Sub ' [Ctrl] not pressed
End If
' else check key combination
Select Case e.KeyCode
Case Keys.OemMinus, Keys.Subtract
' hyphens/dashes
If e.Alt Then
' em dash ("—")
' -- [Ctrl] + [Alt] + [-]
InsertionText = "—"
Else
' optional hyphen (display only when breaking line)
' -- [Ctrl] + [-]
InsertionText = ChrW(173)
End If
Case Keys.Oemtilde
' left quotes
If e.Shift Then
' left double-quote
' -- [Ctrl] + [Shift] + [~]
InsertionText = ChrW(8220)
Else
' left single-quote
' -- [Ctrl] + [`]
InsertionText = ChrW(8216)
End If
Case Keys.OemQuotes
' right quotes
If e.Shift Then
' right double-quote
' -- [Ctrl] + [Shift] + ["]
InsertionText = ChrW(8221)
Else
' right single-quote
' -- [Ctrl] + [']
InsertionText = ChrW(8217)
End If
Case Keys.C
' copyright ("©")
' -- [Ctrl] + [Alt] + [C]
If e.Alt Then
InsertionText = "©"
End If
Case Keys.R
' registered trademark ("®")
' -- [Ctrl] + [Alt] + [RC]
If e.Alt Then
InsertionText = "®"
End If
Case Keys.T
' trademark ("™")
' -- [Ctrl] + [Alt] + [T]
If e.Alt Then
InsertionText = "™"
End If
End Select
' insert special character if one was given
If Not String.IsNullOrEmpty(InsertionText) Then
tb.SelectedText = InsertionText : e.SuppressKeyPress = True
End If
End Sub
End Module
|
Imports System.Runtime.InteropServices
Module GUIEffect
Structure MARGINS
Public Left, Right, Top, Bottom As Integer
End Structure
<DllImport("dwmapi.dll", PreserveSig:=True)>
Private Function DwmSetWindowAttribute(hwnd As IntPtr, attr As Integer, ByRef attrValue As Integer, attrSize As Integer) As Integer
End Function
<DllImport("dwmapi.dll")>
Private Function DwmExtendFrameIntoClientArea(hWnd As IntPtr, ByRef pMarInset As MARGINS) As Integer
End Function
Public Function CreateDropShadow(form As Form) As Boolean
Try
Dim val As Integer = 2
Dim ret1 As Integer = DwmSetWindowAttribute(form.Handle, 2, val, 4)
If ret1 = 0 Then
Dim m As MARGINS = New MARGINS() With {
.Left = 1,
.Right = 1,
.Top = 1,
.Bottom = 1
}
Dim ret2 As Integer = DwmExtendFrameIntoClientArea(form.Handle, m)
Return ret2 = 0
Else
Return False
End If
Catch ex As Exception
'dwmapi.dll 없음
Return False
End Try
End Function
End Module
|
Module modCTUN_Checks_v3_1
Public Sub CTUN_Checks_v3_1()
'This part only check the correct data structure of the data line
'and prepares the variables ready for the MainAnalysis which
'is called directly after by this code.
' THIS CODE MUST ONLY BE CALLED AFTER THE DATA LINE HAS BEEN VALIDATED AS THE CORRECT TYPE !!!
If ReadFileResilienceCheck(9) = True Then
'FMT, 4, 25, CTUN, hcefchhhh, ThrIn,SonAlt,BarAlt,WPAlt,DesSonAlt,AngBst,CRate,ThrOut,DCRate
Log_CTUN_ThrIn = Val(DataArray(1))
Log_CTUN_SonAlt = Val(DataArray(2))
Log_CTUN_BarAlt = Val(DataArray(3))
Log_CTUN_WPAlt = Val(DataArray(4))
Log_CTUN_DesSonAlt = Val(DataArray(5))
Log_CTUN_AngBst = Val(DataArray(6))
Log_CTUN_CRate = Val(DataArray(7))
Log_CTUN_ThrOut = Val(DataArray(8))
Log_CTUN_DCRate = Val(DataArray(9))
Call CTUN_MainAnalysis()
End If
End Sub
End Module
|
Imports DevExpress.DemoData.Models
Imports System
Imports System.Collections.Generic
Imports System.Linq
Namespace GridDemo
Public NotInheritable Class GroupIntervalData
Private Sub New()
End Sub
Public Shared rnd As New Random()
Public Shared ReadOnly Property Invoices() As List(Of Invoice)
Get
Dim invoices_Renamed = NWindContext.Create().Invoices.ToList()
For Each invoice In invoices_Renamed
invoice.OrderDate = GetDate(True)
Next invoice
Return invoices_Renamed
End Get
End Property
Public Shared ReadOnly Property Products() As List(Of ProductInfo)
Get
Const rowCount As Integer = 1000
Dim products_Renamed = NWindContext.Create().Products.ToList()
Dim shuffledProducts = New List(Of ProductInfo)()
For i As Integer = 0 To rowCount - 1
Dim product As Product = products_Renamed(rnd.Next(products_Renamed.Count - 1))
shuffledProducts.Add(New ProductInfo() With {.ProductName = product.ProductName, .UnitPrice = product.UnitPrice, .Count = GetCount(), .OrderDate = GetDate(False)})
Next i
Return shuffledProducts
End Get
End Property
Private Shared Function GetDate(ByVal range As Boolean) As Date
Dim result As Date = Date.Now
Dim r As Integer = rnd.Next(20)
If range Then
If r > 1 Then
result = result.AddDays(rnd.Next(80) - 40)
End If
If r > 18 Then
result = result.AddMonths(rnd.Next(18))
End If
Else
result = result.AddDays(rnd.Next(r * 30) - r * 15)
End If
Return result
End Function
Private Shared Function GetCount() As Decimal
Return rnd.Next(50) + 10
End Function
End Class
Public Class ProductInfo
Public Property ProductName() As String
Public Property UnitPrice() As Decimal?
Public Property Count() As Decimal
Public Property OrderDate() As Date
End Class
End Namespace
|
Option Strict On
Public Class Car
'Variable Declarations
Private Shared countNum As Integer 'Stores the total number of entries. Shared
Private identificationNum As Integer = 0 'Store the id number of the car
Private make As String = String.Empty 'Stores the make of the car
Private model As String = String.Empty 'Stores the model of the car
Private price As Double = 0.0 'Stores the price of the car
Private year As Integer = 0 'Stores the year of that model car
Private newStatus As Boolean = False 'Stores whether the car is new or not
'''<summary>
'''Default Constructor - Creates a new Car Object
'''</summary>
Public Sub New()
countNum += 1
identificationNum = countNum
End Sub
''' <summary>
''' Parameterized Constructor - Creates a new Car Object
''' </summary>
''' <param name="newMake"></param>
''' <param name="newModel"></param>
''' <param name="newYear"></param>
''' <param name="newPrice"></param>
''' <param name="statusUpdate"></param>
Public Sub New(newMake As String, newModel As String, newYear As Integer, newPrice As Double, statusUpdate As Boolean)
Me.New()
make = newMake
model = newModel
year = newYear
price = newPrice
newStatus = statusUpdate
End Sub
''' <summary>
''' Gets the number of entries
''' </summary>
''' <returns>Integer</returns>
Public ReadOnly Property GetCount() As Integer
Get
Return countNum
End Get
End Property
''' <summary>
''' Gets the ID number of the vehicle
''' </summary>
''' <returns>Integer</returns>
Public ReadOnly Property GetIdNumber() As Integer
Get
Return identificationNum
End Get
End Property
''' <summary>
''' Gets or Sets the the make of the vehicle
''' </summary>
''' <returns>String</returns>
Public Property MakeStatus() As String
Get
Return make
End Get
Set(value As String)
make = value
End Set
End Property
''' <summary>
''' Gets or Sets the model of the vehicle
''' </summary>
''' <returns>String</returns>
Public Property ModelStatus() As String
Get
Return model
End Get
Set(value As String)
model = value
End Set
End Property
''' <summary>
''' Gets or Sets the price of the vehicle
''' </summary>
''' <returns>Double</returns>
Public Property PriceStatus() As Double
Get
Return price
End Get
Set(value As Double)
price = value
End Set
End Property
''' <summary>
''' Gets or Sets the year of the car
''' </summary>
''' <returns>Integer</returns>
Public Property YearStatus() As Integer
Get
Return year
End Get
Set(value As Integer)
year = value
End Set
End Property
''' <summary>
''' Gets or Sets whether the car is new or not
''' </summary>
''' <returns>Boolean</returns>
Public Property QualityStatus() As Boolean
Get
Return newStatus
End Get
Set(value As Boolean)
newStatus = value
End Set
End Property
''' <summary>
''' Returns a string representation of the car object
''' </summary>
''' <returns>String</returns>
Public Function GetCarData() As String
Dim output = (make.ToString & " " & model.ToString & " " & year.ToString & " " & price.ToString & " " & newStatus.ToString)
Return output
End Function
End Class
|
<TestClass()> Public Class 必須文字列クラステスト
'テスト用パラメーター
Private Const m_テスト値1 As String = "日本"
Private Const m_テスト値2 As String = " 今日の天気は "
<TestMethod()> <TestCategory("基本テスト")> Public Sub 必須文字列クラス基本テスト()
'必須文字列クラスを生成する時は、値となる文字列を設定する。
Dim 必須の文字列1 As New SampleApplication.PrimitiveObject.必須文字列(m_テスト値1)
'値プロパティは読み取り専用である。
Assert.AreEqual(m_テスト値1, 必須の文字列1.値)
'必須文字列は、先頭と末尾のスペースを許容する。
Dim 必須文字列2 As New SampleApplication.PrimitiveObject.必須文字列(m_テスト値2)
Assert.AreEqual(m_テスト値2, 必須文字列2.値)
End Sub
<TestMethod()> <TestCategory("例外テスト")> <ExpectedException(GetType(Exception))> Public Sub 必須文字列クラス例外処理1()
'インスタンスの生成時にセットする文字列が文字列0ならば例外を発生する。
Dim 必須の文字列 As New SampleApplication.PrimitiveObject.必須文字列(String.Empty)
End Sub
<TestMethod()> <TestCategory("例外テスト")> <ExpectedException(GetType(Exception))> Public Sub 必須文字列クラス例外処理2()
'インスタンスの生成時にセットする文字列がスペースのみならば例外を発生する。
Dim 必須の文字列 As New SampleApplication.PrimitiveObject.必須文字列(" ")
End Sub
End Class
|
Imports System.IO
Public Class frmMain
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 btnBrowse As System.Windows.Forms.Button
Friend WithEvents txtPath As System.Windows.Forms.TextBox
Friend WithEvents lblSelectedDirectory As System.Windows.Forms.Label
Friend WithEvents lstFinal As System.Windows.Forms.ListBox
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents txtStartFilenameWith As System.Windows.Forms.TextBox
Friend WithEvents btnRename As System.Windows.Forms.Button
Friend WithEvents fbd1 As System.Windows.Forms.FolderBrowserDialog
Friend WithEvents btnExit As System.Windows.Forms.Button
Friend WithEvents lstInitial As System.Windows.Forms.ListBox
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents Label3 As System.Windows.Forms.Label
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.btnBrowse = New System.Windows.Forms.Button
Me.txtPath = New System.Windows.Forms.TextBox
Me.lblSelectedDirectory = New System.Windows.Forms.Label
Me.lstInitial = New System.Windows.Forms.ListBox
Me.lstFinal = New System.Windows.Forms.ListBox
Me.Label1 = New System.Windows.Forms.Label
Me.txtStartFilenameWith = New System.Windows.Forms.TextBox
Me.btnRename = New System.Windows.Forms.Button
Me.fbd1 = New System.Windows.Forms.FolderBrowserDialog
Me.btnExit = New System.Windows.Forms.Button
Me.Label2 = New System.Windows.Forms.Label
Me.Label3 = New System.Windows.Forms.Label
Me.SuspendLayout()
'
'btnBrowse
'
Me.btnBrowse.BackColor = System.Drawing.Color.DarkSalmon
Me.btnBrowse.Location = New System.Drawing.Point(647, 16)
Me.btnBrowse.Name = "btnBrowse"
Me.btnBrowse.TabIndex = 0
Me.btnBrowse.Text = "Browse"
'
'txtPath
'
Me.txtPath.Location = New System.Drawing.Point(215, 16)
Me.txtPath.Name = "txtPath"
Me.txtPath.Size = New System.Drawing.Size(424, 20)
Me.txtPath.TabIndex = 1
Me.txtPath.Text = ""
'
'lblSelectedDirectory
'
Me.lblSelectedDirectory.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.lblSelectedDirectory.Location = New System.Drawing.Point(103, 16)
Me.lblSelectedDirectory.Name = "lblSelectedDirectory"
Me.lblSelectedDirectory.Size = New System.Drawing.Size(104, 23)
Me.lblSelectedDirectory.TabIndex = 2
Me.lblSelectedDirectory.Text = "Selected Directory"
Me.lblSelectedDirectory.TextAlign = System.Drawing.ContentAlignment.MiddleRight
'
'lstInitial
'
Me.lstInitial.BackColor = System.Drawing.Color.FromArgb(CType(192, Byte), CType(255, Byte), CType(192, Byte))
Me.lstInitial.Location = New System.Drawing.Point(12, 168)
Me.lstInitial.Name = "lstInitial"
Me.lstInitial.Size = New System.Drawing.Size(360, 342)
Me.lstInitial.TabIndex = 3
'
'lstFinal
'
Me.lstFinal.BackColor = System.Drawing.Color.FromArgb(CType(255, Byte), CType(192, Byte), CType(192, Byte))
Me.lstFinal.Location = New System.Drawing.Point(444, 168)
Me.lstFinal.Name = "lstFinal"
Me.lstFinal.Size = New System.Drawing.Size(360, 342)
Me.lstFinal.TabIndex = 4
'
'Label1
'
Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label1.Location = New System.Drawing.Point(32, 48)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(168, 23)
Me.Label1.TabIndex = 5
Me.Label1.Text = "Start Renamed Filename With"
Me.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight
'
'txtStartFilenameWith
'
Me.txtStartFilenameWith.Location = New System.Drawing.Point(215, 48)
Me.txtStartFilenameWith.Name = "txtStartFilenameWith"
Me.txtStartFilenameWith.Size = New System.Drawing.Size(424, 20)
Me.txtStartFilenameWith.TabIndex = 6
Me.txtStartFilenameWith.Text = ""
'
'btnRename
'
Me.btnRename.BackColor = System.Drawing.Color.DarkSalmon
Me.btnRename.Location = New System.Drawing.Point(380, 304)
Me.btnRename.Name = "btnRename"
Me.btnRename.Size = New System.Drawing.Size(56, 23)
Me.btnRename.TabIndex = 7
Me.btnRename.Text = "Rename"
'
'fbd1
'
Me.fbd1.Description = "Folder Browse Dialog"
'
'btnExit
'
Me.btnExit.BackColor = System.Drawing.Color.DarkSalmon
Me.btnExit.Location = New System.Drawing.Point(647, 48)
Me.btnExit.Name = "btnExit"
Me.btnExit.TabIndex = 8
Me.btnExit.Text = "Exit"
'
'Label2
'
Me.Label2.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label2.Location = New System.Drawing.Point(16, 136)
Me.Label2.Name = "Label2"
Me.Label2.TabIndex = 9
Me.Label2.Text = "Initial File List"
Me.Label2.TextAlign = System.Drawing.ContentAlignment.BottomLeft
'
'Label3
'
Me.Label3.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label3.Location = New System.Drawing.Point(448, 136)
Me.Label3.Name = "Label3"
Me.Label3.TabIndex = 10
Me.Label3.Text = "Renamed File List"
Me.Label3.TextAlign = System.Drawing.ContentAlignment.BottomLeft
'
'frmMain
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(816, 533)
Me.Controls.Add(Me.Label3)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.btnExit)
Me.Controls.Add(Me.btnRename)
Me.Controls.Add(Me.txtStartFilenameWith)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.lstFinal)
Me.Controls.Add(Me.lstInitial)
Me.Controls.Add(Me.lblSelectedDirectory)
Me.Controls.Add(Me.txtPath)
Me.Controls.Add(Me.btnBrowse)
Me.Name = "frmMain"
Me.Text = "DigiOz Mass File Renamer Version 1.0"
Me.ResumeLayout(False)
End Sub
#End Region
Dim listfiles As Directory
Dim files As Array
Dim file As String
Dim fileShort As String
Dim i As Integer = 1
Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
fbd1.ShowDialog()
txtPath.Text = fbd1.SelectedPath.ToString()
files = listfiles.GetFiles(fbd1.SelectedPath.ToString())
For Each file In files
fileShort = Replace(file, txtPath.Text & "\", "")
lstInitial.Items.Add(fileShort)
Next
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnRename_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRename.Click
If lstInitial.Items.Count <= 0 Then
MessageBox.Show("There are no files in your initial file list!")
Exit Sub
End If
If txtStartFilenameWith.Text = "" Then
MessageBox.Show("Please Enter a phrase to start the new filename with")
Exit Sub
End If
For Each file In files
listfiles.Move(file, txtPath.Text & "\" & txtStartFilenameWith.Text & "_" & i & ".jpg")
i = i + 1
Next
End Sub
End Class
|
Imports cv = OpenCvSharp
Imports System.Runtime.InteropServices
Imports CS_Classes
' https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_surf_intro/py_surf_intro.html
Public Class Surf_Basics_CS : Implements IDisposable
Dim radio As New OptionsRadioButtons
Dim sliders As New OptionsSliders
Dim CS_SurfBasics As New CS_SurfBasics
Public Sub New(ocvb As AlgorithmData)
radio.Setup(ocvb, 2)
radio.check(0).Text = "Use BF Matcher"
radio.check(1).Text = "Use Flann Matcher"
radio.check(0).Checked = True
If ocvb.parms.ShowOptions Then radio.Show()
sliders.setupTrackBar1(ocvb, "Hessian threshold", 1, 5000, 2000)
If ocvb.parms.ShowOptions Then sliders.Show()
ocvb.desc = "Compare 2 images to get a homography. We will use left and right infrared images."
ocvb.label1 = "BF Matcher output"
End Sub
Public Sub Run(ocvb As AlgorithmData)
Dim dst As New cv.Mat(ocvb.leftView.Rows, ocvb.leftView.Cols * 2, cv.MatType.CV_8UC3)
CS_SurfBasics.Run(ocvb.leftView, ocvb.rightView, dst, sliders.TrackBar1.Value, radio.check(0).Checked)
dst(New cv.Rect(0, 0, ocvb.result1.Width, ocvb.result1.Height)).CopyTo(ocvb.result1)
dst(New cv.Rect(ocvb.result1.Width, 0, ocvb.result1.Width, ocvb.result1.Height)).CopyTo(ocvb.result2)
ocvb.label1 = If(radio.check(0).Checked, "BF Matcher output", "Flann Matcher output")
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
sliders.Dispose()
radio.Dispose()
End Sub
End Class
|
Imports RTIS.CommonVB
Public Class clsPurchaseOrderInfo
Private pPurchaseOrder As dmPurchaseOrder
Private pPOItemInfos As colPOItemInfos
Private pPOItem As dmPurchaseOrderItem
Private pStockItem As dmStockItem
Private pBuyerName As String
Private pSupplierContactName As String
Private pTotalNetValueInfo As Decimal
Private pSalesOrderPhaseItemInfos As colSalesOrderPhaseItemInfos
Private pTotalVatValue As Decimal
Private pTotalRetentionValue As Decimal
Private pTotalValue As Decimal
Public Sub New()
pPurchaseOrder = New dmPurchaseOrder
pPOItem = New dmPurchaseOrderItem
pPOItemInfos = New colPOItemInfos
pSalesOrderPhaseItemInfos = New colSalesOrderPhaseItemInfos
End Sub
Public Property BuyerName As String
Get
Return pBuyerName
End Get
Set(value As String)
pBuyerName = value
End Set
End Property
Public ReadOnly Property PurchaseOrderItem As dmPurchaseOrderItem
Get
Return pPOItem
End Get
End Property
Public ReadOnly Property PaymentMethod As Int32
Get
Return pPurchaseOrder.PaymentMethod
End Get
End Property
Public ReadOnly Property PaymentMethodDes As String
Get
Return clsEnumsConstants.GetEnumDescription(GetType(ePaymentMethod), CType(pPurchaseOrder.PaymentMethod, ePaymentMethod))
End Get
End Property
Public ReadOnly Property PurchaseOrderItemID As Int32
Get
Return pPOItem.PurchaseOrderItemID
End Get
End Property
Public Property PurchaseOrder As dmPurchaseOrder
Get
Return pPurchaseOrder
End Get
Set(value As dmPurchaseOrder)
pPurchaseOrder = value
End Set
End Property
Public ReadOnly Property FileName As String
Get
Return pPurchaseOrder.FileName
End Get
End Property
Public Property POItemInfos As colPOItemInfos
Get
Return pPOItemInfos
End Get
Set(value As colPOItemInfos)
pPOItemInfos = value
End Set
End Property
Public ReadOnly Property PurchaseOrderID() As Int32
Get
Return pPurchaseOrder.PurchaseOrderID
End Get
End Property
Public ReadOnly Property AccoutingCategoryID() As Int32
Get
Return pPurchaseOrder.AccoutingCategoryID
End Get
End Property
Public ReadOnly Property POStage As Integer
Get
Return pPurchaseOrder.POStage
End Get
End Property
Public ReadOnly Property POStageDesc As String
Get
If POStage > 0 Then
Return clsEnumsConstants.GetEnumDescription(GetType(ePOStage), CType(pPurchaseOrder.POStage, ePOStage))
Else
Return AccoutingCategoryDesc
End If
End Get
End Property
Public ReadOnly Property ExchangeRateValue() As Decimal
Get
Return pPurchaseOrder.ExchangeRateValue
End Get
End Property
Public ReadOnly Property MaterialRequirementTypeID() As Int32
Get
Return pPurchaseOrder.MaterialRequirementTypeID
End Get
End Property
Public ReadOnly Property MaterialRequirementTypeWorkOrderID() As Int32
Get
Return pPurchaseOrder.MaterialRequirementTypeWorkOrderID
End Get
End Property
Public ReadOnly Property DefaultCurrency() As Int32
Get
Return pPurchaseOrder.DefaultCurrency
End Get
End Property
Public ReadOnly Property CategoryDesc As String
Get
Return clsEnumsConstants.GetEnumDescription(GetType(ePurchaseCategories), CType(pPurchaseOrder.Category, ePurchaseCategories))
End Get
End Property
Public ReadOnly Property PurchaseStateDes As String
Get
Return clsEnumsConstants.GetEnumDescription(GetType(ePurchaseOrderDueDateStatus), CType(pPurchaseOrder.Status, ePurchaseOrderDueDateStatus))
End Get
End Property
Public ReadOnly Property TotalReceivedAmountCordobas As Decimal
Get
Dim mRetVal As Decimal = 0
Select Case DefaultCurrency
Case eCurrency.Cordobas
mRetVal = pTotalNetValueInfo
Case eCurrency.Dollar
If ExchangeRateValue > 0 Then
mRetVal = pTotalNetValueInfo * ExchangeRateValue
Else
mRetVal = 0
End If
End Select
Return mRetVal
End Get
End Property
Public ReadOnly Property TotalReceivedAmountUSD As Decimal
Get
Dim mRetVal As Decimal = 0
Select Case DefaultCurrency
Case eCurrency.Dollar
mRetVal = pTotalNetValueInfo
Case eCurrency.Cordobas
If ExchangeRateValue > 0 Then
mRetVal = pTotalNetValueInfo / ExchangeRateValue
Else
mRetVal = 0
End If
End Select
Return Math.Round(mRetVal, 2, MidpointRounding.AwayFromZero)
End Get
End Property
Public ReadOnly Property CarriageUSD As Decimal
Get
Dim mRetVal As Decimal = 0
Select Case DefaultCurrency
Case eCurrency.Dollar
mRetVal = Carriage
Case eCurrency.Cordobas
If ExchangeRateValue > 0 Then
mRetVal = Carriage / ExchangeRateValue
Else
mRetVal = 0
End If
End Select
Return mRetVal
End Get
End Property
Public ReadOnly Property CarriageCordobas As Decimal
Get
Dim mRetVal As Decimal = 0
Select Case DefaultCurrency
Case eCurrency.Cordobas
mRetVal = Carriage
Case eCurrency.Dollar
If ExchangeRateValue > 0 Then
mRetVal = Carriage * ExchangeRateValue
Else
mRetVal = 0
End If
End Select
Return mRetVal
End Get
End Property
Public Property SalesOrderPhaseItemInfos As colSalesOrderPhaseItemInfos
Get
Return pSalesOrderPhaseItemInfos
End Get
Set(value As colSalesOrderPhaseItemInfos)
pSalesOrderPhaseItemInfos = value
End Set
End Property
Public ReadOnly Property DefaultCurrencyDesc() As String
Get
Return clsEnumsConstants.GetEnumDescription(GetType(eCurrency), CType(pPurchaseOrder.DefaultCurrency, eCurrency))
End Get
End Property
Public ReadOnly Property RefMatType() As String
Get
Return pPurchaseOrder.RefMatType
End Get
End Property
Public ReadOnly Property PONum() As String
Get
Return pPurchaseOrder.PONum
End Get
End Property
Public ReadOnly Property SupplierContactTel() As String
Get
Return pPurchaseOrder.SupplierContactTel
End Get
End Property
Public ReadOnly Property Category() As Byte
Get
Return pPurchaseOrder.Category
End Get
End Property
Public ReadOnly Property SubmissionDate() As DateTime
Get
Return pPurchaseOrder.SubmissionDate
End Get
End Property
Public ReadOnly Property SubmissionDateWC() As DateTime
Get
Return RTIS.CommonVB.libDateTime.MondayOfWeek(pPurchaseOrder.SubmissionDate)
End Get
End Property
Public ReadOnly Property SubmissionDateMC As Date
Get
Return New Date(Year(pPurchaseOrder.SubmissionDate), Month(pPurchaseOrder.SubmissionDate), 1)
End Get
End Property
Public ReadOnly Property Status() As Byte
Get
Return pPurchaseOrder.Status
End Get
End Property
Public ReadOnly Property DelStatus() As Byte
Get
Return pPurchaseOrder.DelStatus
End Get
End Property
Public ReadOnly Property Instructions() As String
Get
Return pPurchaseOrder.Instructions
End Get
End Property
Public ReadOnly Property Comments() As String
Get
Return pPurchaseOrder.Comments
End Get
End Property
Public ReadOnly Property BuyerID() As Byte
Get
Return pPurchaseOrder.BuyerID
End Get
End Property
Public ReadOnly Property AcknowledgementNo() As String
Get
Return pPurchaseOrder.AcknowledgementNo
End Get
End Property
Public ReadOnly Property OrderType() As Byte
Get
Return pPurchaseOrder.OrderType
End Get
End Property
Public ReadOnly Property Carriage() As Double
Get
Return pPurchaseOrder.Carriage
End Get
End Property
Public ReadOnly Property VatRate() As Decimal
Get
Return pPurchaseOrder.VatRate
End Get
End Property
Public Property RequiredDate() As DateTime
Get
Return pPurchaseOrder.RequiredDate
End Get
Set(value As DateTime)
pPurchaseOrder.RequiredDate = value
End Set
End Property
Public ReadOnly Property PurchaseCategory() As Byte
Get
Return pPurchaseOrder.PurchaseCategory
End Get
End Property
Public ReadOnly Property CoCOrder() As Boolean
Get
Return pPurchaseOrder.CoCOrder
End Get
End Property
Public ReadOnly Property CoCType() As Byte
Get
Return pPurchaseOrder.CoCType
End Get
End Property
Public ReadOnly Property PriceGross() As Decimal
Get
Return pPurchaseOrder.PriceGross
End Get
End Property
Public ReadOnly Property TotalPrice() As Decimal
Get
Return pPurchaseOrder.TotalPrice
End Get
End Property
Public ReadOnly Property PaymentStatus As Integer
Get
Return pPurchaseOrder.PaymentStatus
End Get
End Property
Public ReadOnly Property DeliveryAddress As String
Get
Return pPurchaseOrder.DeliveryAddress.FullAddress(vbCrLf)
End Get
End Property
Public ReadOnly Property BankName() As String
Get
Return pPurchaseOrder.Supplier.BankName
End Get
End Property
Public ReadOnly Property isBigTaxPayer() As Boolean
Get
Return pPurchaseOrder.Supplier.isBigTaxPayer
End Get
End Property
Public ReadOnly Property CompanyName() As String
Get
Return pPurchaseOrder.Supplier.CompanyName
End Get
End Property
Public ReadOnly Property TotalVAT As Decimal
Get
Dim mRetVal As Decimal
For Each mPOItemInfo As clsPOItemInfo In pPOItemInfos
mRetVal += mPOItemInfo.VATAmount
Next
mRetVal += pPurchaseOrder.CarriageVAT()
Return mRetVal
End Get
End Property
Public ReadOnly Property TotalRetention As Decimal
Get
Dim mRetVal As Decimal
For Each mPOItemInfo As clsPOItemInfo In pPOItemInfos
mRetVal += (mPOItemInfo.Qty * mPOItemInfo.UnitPrice) * PurchaseOrder.RetentionPercentage
Next
Return mRetVal
End Get
End Property
Public Property TotalVatValueReport As Decimal
Get
Return pTotalVatValue
End Get
Set(value As Decimal)
pTotalVatValue = value
End Set
End Property
Public ReadOnly Property TotalVatValueReportUSD As Decimal
Get
Dim mRetVal As Decimal = 0
Select Case DefaultCurrency
Case eCurrency.Dollar
mRetVal = TotalVatValueReport
Case eCurrency.Cordobas
If ExchangeRateValue > 0 Then
mRetVal = TotalVatValueReport / ExchangeRateValue
Else
mRetVal = 0
End If
End Select
Return Math.Round(mRetVal, 2, MidpointRounding.AwayFromZero)
End Get
End Property
Public Property TotalRetentionValueReport As Decimal
Get
Return pTotalRetentionValue
End Get
Set(value As Decimal)
pTotalRetentionValue = value
End Set
End Property
Public ReadOnly Property TotalValueReport As Decimal
Get
Dim mRetVal As Decimal = 0
mRetVal = TotalReceivedAmountUSD - TotalRetentionValueReportUSD + TotalVatValueReportUSD + CarriageUSD
Return Math.Round(mRetVal, 2, MidpointRounding.AwayFromZero)
End Get
End Property
Public ReadOnly Property TotalRetentionValueReportUSD As Decimal
Get
Dim mRetVal As Decimal = 0
Select Case DefaultCurrency
Case eCurrency.Dollar
mRetVal = TotalRetentionValueReport
Case eCurrency.Cordobas
If ExchangeRateValue > 0 Then
mRetVal = TotalRetentionValueReport / ExchangeRateValue
Else
mRetVal = 0
End If
End Select
Return Math.Round(mRetVal, 2, MidpointRounding.AwayFromZero)
End Get
End Property
Public ReadOnly Property TotalRetentionCordobas As Decimal
Get
Dim mRetVal As Decimal = 0
Select Case DefaultCurrency
Case eCurrency.Cordobas
mRetVal = TotalRetention
Case eCurrency.Dollar
If ExchangeRateValue > 0 Then
mRetVal = TotalRetention * ExchangeRateValue
Else
mRetVal = 0
End If
End Select
Return mRetVal
End Get
End Property
Public ReadOnly Property TotalRetentionUSD As Decimal
Get
Dim mRetVal As Decimal = 0
Select Case DefaultCurrency
Case eCurrency.Dollar
mRetVal = TotalRetention
Case eCurrency.Cordobas
If ExchangeRateValue > 0 Then
mRetVal = TotalRetention / ExchangeRateValue
Else
mRetVal = 0
End If
End Select
Return mRetVal
End Get
End Property
Public ReadOnly Property TotalVATCordobas As Decimal
Get
Dim mRetVal As Decimal = 0
Select Case DefaultCurrency
Case eCurrency.Cordobas
mRetVal = TotalVAT
Case eCurrency.Dollar
If ExchangeRateValue > 0 Then
mRetVal = TotalVAT * ExchangeRateValue
Else
mRetVal = 0
End If
End Select
Return mRetVal
End Get
End Property
Public ReadOnly Property TotalVATUSD As Decimal
Get
Dim mRetVal As Decimal = 0
Select Case DefaultCurrency
Case eCurrency.Dollar
mRetVal = TotalVAT
Case eCurrency.Cordobas
If ExchangeRateValue > 0 Then
mRetVal = TotalVAT / ExchangeRateValue
Else
mRetVal = 0
End If
End Select
Return mRetVal
End Get
End Property
Public ReadOnly Property TotalNetValue As Decimal
Get
Dim mRetVal As Decimal
For Each mPOItemInfo As clsPOItemInfo In pPOItemInfos
mRetVal += Math.Round(mPOItemInfo.Price, 2, MidpointRounding.AwayFromZero)
Next
'mRetVal += pPurchaseOrder.Carriage
Return mRetVal
End Get
End Property
Public ReadOnly Property RetentionPercentage As Decimal
Get
Return pPurchaseOrder.RetentionPercentage
End Get
End Property
Public ReadOnly Property TotalGrossValueGUI As Decimal
Get
Dim mRetVal As Decimal
For Each mPOItemInfo As clsPOItemInfo In pPOItemInfos
mRetVal += mPOItemInfo.GrossPrice '* (1 - RetentionPercentage)
Next
mRetVal = mRetVal - TotalRetention
Return mRetVal
End Get
End Property
Public ReadOnly Property TotalGrossValue As Decimal
Get
Dim mRetVal As Decimal
For Each mPOItemInfo As clsPOItemInfo In pPOItemInfos
mRetVal += mPOItemInfo.GrossPrice
Next
mRetVal += (pPurchaseOrder.Carriage + pPurchaseOrder.CarriageVAT)
Return mRetVal
End Get
End Property
Public ReadOnly Property TotalGrossValueUSD As Decimal
Get
Dim mRetVal As Decimal = 0
Select Case DefaultCurrency
Case eCurrency.Dollar
mRetVal = TotalGrossValueGUI
Case eCurrency.Cordobas
If ExchangeRateValue > 0 Then
mRetVal = TotalGrossValueGUI / ExchangeRateValue
Else
mRetVal = 0
End If
End Select
Return mRetVal
End Get
End Property
Public ReadOnly Property TotalGrossValueCordobas As Decimal
Get
Dim mRetVal As Decimal = 0
Select Case DefaultCurrency
Case eCurrency.Cordobas
mRetVal = TotalGrossValueGUI
Case eCurrency.Dollar
If ExchangeRateValue > 0 Then
mRetVal = TotalGrossValueGUI * ExchangeRateValue
Else
mRetVal = 0
End If
End Select
Return mRetVal
End Get
End Property
Public ReadOnly Property AnyCoC As Boolean
Get
Dim mRetVal As Boolean = False
For Each mPOItem As dmPurchaseOrderItem In pPurchaseOrder.PurchaseOrderItems
If mPOItem.CoCType <> eCOCType.None And mPOItem.CoCType <> eCOCType.Uncertified Then
mRetVal = True
Exit For
End If
Next
Return mRetVal
End Get
End Property
Public Property TotalNetValueInfo As Decimal
Get
Return pTotalNetValueInfo
End Get
Set(value As Decimal)
pTotalNetValueInfo = value
End Set
End Property
Public ReadOnly Property AccoutingCategoryDesc As String
Get
Dim mRetVal As String = ""
mRetVal = AppRTISGlobal.GetInstance.RefLists.RefListVI(appRefLists.AccoutingCategory).DisplayValueString(AccoutingCategoryID)
Return mRetVal
End Get
End Property
Public ReadOnly Property PaymentDate As Date
Get
Return pPurchaseOrder.PaymentDate
End Get
End Property
Public ReadOnly Property ProjectName As String
Get
Dim mRetVal As String = ""
Dim mSalesOrderPhaseItemInfo As clsSalesOrderPhaseItemInfo
For Each mPOA As dmPurchaseOrderAllocation In PurchaseOrder.PurchaseOrderAllocations
mSalesOrderPhaseItemInfo = pSalesOrderPhaseItemInfos.ItemFromKey(mPOA.SalesorderPhaseItemID)
If mSalesOrderPhaseItemInfo IsNot Nothing Then
If mSalesOrderPhaseItemInfo.ProjectName <> "" Then
mRetVal &= mSalesOrderPhaseItemInfo.ProjectName & " /"
Else
mRetVal = AccoutingCategoryDesc
End If
End If
Next
If mRetVal.Length > 0 Then
If mRetVal.Substring(mRetVal.Length - 1) = "/" Then
mRetVal = mRetVal.Remove(mRetVal.Length - 1)
End If
Else
mRetVal = AccoutingCategoryDesc
End If
Return mRetVal
End Get
End Property
Public ReadOnly Property ValuationMode As Int32
Get
Return pPurchaseOrder.ValuationMode
End Get
End Property
End Class
Public Class colPurchaseOrderInfos : Inherits List(Of clsPurchaseOrderInfo)
Public Function GetLivePOCountByCategory(ByVal vCategory As Integer) As Integer
End Function
End Class
Public Class clsPOItemInfo
Private pPOItem As dmPurchaseOrderItem
Private pStockItem As dmStockItem
Private pPOItemAllocations As colPurchaseOrderItemAllocations
Public Sub New(ByRef rPOItem As dmPurchaseOrderItem, ByRef rStockItem As dmStockItem)
pPOItem = rPOItem
pStockItem = rStockItem
pPOItemAllocations = rPOItem.PurchaseOrderItemAllocations
End Sub
Public ReadOnly Property PurchaseRefCodes As String
Get
Dim mRetVal As String = ""
mRetVal = pPOItem.PartNo
If pPOItem.SupplierCode <> "" Then
If mRetVal <> "" Then mRetVal &= " / "
mRetVal = mRetVal & pPOItem.SupplierCode
End If
Return mRetVal
End Get
End Property
Public Property PurchaseOrderItemAllocations As colPurchaseOrderItemAllocations
Get
Return pPOItemAllocations
End Get
Set(value As colPurchaseOrderItemAllocations)
pPOItemAllocations = value
End Set
End Property
Public Property StockCode As String
Get
Dim mRetVal As String
Dim mSI As dmStockItem
mSI = AppRTISGlobal.GetInstance.StockItemRegistry.GetStockItemFromID(pPOItem.StockItemID)
If mSI IsNot Nothing Then
mRetVal = mSI.StockCode
Else
mRetVal = ""
End If
Return mRetVal
End Get
Set(value As String)
pPOItem.StockCode = value
End Set
End Property
Public ReadOnly Property Qty As Decimal
Get
Return pPOItem.QtyRequired
End Get
End Property
Public ReadOnly Property SupplierCode As String
Get
Return pPOItem.SupplierCode
End Get
End Property
Public ReadOnly Property Description As String
Get
Return pPOItem.Description
End Get
End Property
Public ReadOnly Property UnitPrice As Decimal
Get
Return pPOItem.UnitPrice
End Get
End Property
Public ReadOnly Property Density As Decimal
Get
Return pPOItem.Density
End Get
End Property
Public ReadOnly Property CoCType As String
Get
Return RTIS.CommonVB.clsEnumsConstants.GetEnumDescription(GetType(eCOCType), CType(pPOItem.CoCType, eCOCType))
End Get
End Property
Public ReadOnly Property UoM As Integer
Get
Return pPOItem.UoM
End Get
End Property
Public ReadOnly Property UoMDesc As String
Get
Return RTIS.CommonVB.clsEnumsConstants.GetEnumDescription(GetType(eUoM), CType(pPOItem.UoM, eUoM))
End Get
End Property
Public ReadOnly Property Price As Decimal
Get
Return pPOItem.NetAmount
End Get
End Property
Public ReadOnly Property VATAmount As Decimal
Get
Return pPOItem.VATAmount
End Get
End Property
Public ReadOnly Property RetentionValue As Decimal
Get
Return pPOItem.RetentionValue
End Get
End Property
Public ReadOnly Property GrossPrice As Decimal
Get
Return pPOItem.GrossAmount
End Get
End Property
Public ReadOnly Property AllocationItemRefSummary As String
Get
Dim mRetVal As String = ""
For Each mPOIA As dmPurchaseOrderItemAllocation In pPOItem.PurchaseOrderItemAllocations
If mRetVal = "" Then mRetVal &= vbCrLf
mRetVal &= mPOIA.ItemRef & " / " & mPOIA.Quantity.ToString("N2") & vbCrLf
Next
Return Description & vbCrLf & mRetVal
End Get
End Property
Public ReadOnly Property DisplayReportPOIDesc As String
Get
Dim mRetVal As String
mRetVal = String.Format("{0} {1} de {2}", clsSMSharedFuncs.FractStrFromDec(Qty), UoMDesc, Description)
Return mRetVal
End Get
End Property
Public ReadOnly Property PurchaseOrderItemID As Integer
Get
Return pPOItem.PurchaseOrderID
End Get
End Property
End Class
Public Class colPOItemInfos : Inherits List(Of clsPOItemInfo)
Public Function GetItemFromKey(ByVal vPurchaseOrderItemID As Integer) As clsPOItemInfo
Dim mRetVal As clsPOItemInfo = Nothing
For Each mItem In Me
If mItem.PurchaseOrderItemID = vPurchaseOrderItemID Then
mRetVal = mItem
Exit For
End If
Next
Return mRetVal
End Function
End Class
|
Imports System.Windows.Forms
Imports System.Timers
Imports MediaPortal.Configuration
Imports MediaPortal.Dialogs
Imports MediaPortal.Player
Imports MediaPortal.GUI.Library
Imports TvControl
Imports TvDatabase
Imports myTvNiveauChecker.MediaPortal.TvDatabase
Imports myTvNiveauChecker.Settings
Imports myTvNiveauChecker.Language
Imports System.Reflection
<PluginIcons("myTvNiveauChecker.Config.png", "myTvNiveauChecker.Config_disable.png")> _
Public Class myTvNiveauChecker
Implements IPlugin
Implements ISetupForm
#Region "Members"
Private _idCurrentProgram As Integer = 0
Private _CurrentEndTime As Date
Private _CurrentProgram As Program
Private _deactivated As Boolean = False
Private _stateTimer As System.Timers.Timer
Private _CheckTimer As System.Timers.Timer
Private _CountDownTimer As System.Timers.Timer
Private _CountDown As Integer
Public Enum Match
exact = 0
contains = 1
End Enum
#End Region
#Region "iSetupFormImplementation"
Public Function Author() As String Implements ISetupForm.Author
Return "Scrounger"
End Function
Public Function CanEnable() As Boolean Implements ISetupForm.CanEnable
Return True
End Function
Public Function DefaultEnabled() As Boolean Implements ISetupForm.DefaultEnabled
Return True
End Function
Public Function Description() As String Implements ISetupForm.Description
Return "myTvNiveauChecker Version: " & Assembly.GetExecutingAssembly().GetName().Version.ToString
End Function
Public Function GetHome(ByRef strButtonText As String, ByRef strButtonImage As String, ByRef strButtonImageFocus As String, ByRef strPictureImage As String) As Boolean Implements ISetupForm.GetHome
strButtonText = "myTvNiveauChecker"
strButtonImage = String.Empty
strButtonImageFocus = String.Empty
strPictureImage = "Config.png"
End Function
Public Function GetWindowId() As Integer Implements ISetupForm.GetWindowId
Return 15498
End Function
Public Function HasSetup() As Boolean Implements ISetupForm.HasSetup
Return True
End Function
Public Function PluginName() As String Implements ISetupForm.PluginName
Return "myTvNiveauChecker"
End Function
Public Sub ShowPlugin() Implements ISetupForm.ShowPlugin
Dim setup As New setup
setup.Show()
End Sub
Public Sub Start() Implements IPlugin.Start
MyLog.BackupLogFiles()
MyLog.Info("")
MyLog.Info("----------------myTvNiveauChecker started------------------")
Translator.TranslateSkin()
GUIPropertyManager.SetProperty("#myTvNiveauChecker.active", False)
GUIPropertyManager.SetProperty("#myTvNiveauChecker.CountDown", 0)
'Event Handler (channel change, tv started)
AddHandler g_Player.TVChannelChanged, New g_Player.TVChannelChangeHandler(AddressOf Event_TvChannelChange)
AddHandler g_Player.PlayBackStarted, New g_Player.StartedHandler(AddressOf Event_TvStarted)
'Event Handler key press
AddHandler GUIWindowManager.OnNewAction, AddressOf Event_GuiAction
'AddHandler GUIWindowManager.OnNewAction, New GUIWindowManager.PostRenderActionHandler(AddressOf Event_Action)
MyLog.Info("handler for g_player tv events registered")
End Sub
Public Sub [Stop]() Implements IPlugin.Stop
MyLog.Info("myTvNiveauChecker stopped")
End Sub
#End Region
#Region "Gui Events"
Sub Event_TvStarted(ByVal type As g_Player.MediaType, ByVal filename As String)
If g_Player.IsTV = True And g_Player.IsTVRecording = False Then
mySettings.Load(True)
CheckTvDatabaseTable()
MyLog.Info("Version: " & Assembly.GetExecutingAssembly().GetName().Version.ToString)
_deactivated = False
_idCurrentProgram = 0
TvEventTimer(True)
End If
End Sub
Private _ChannelChangeCounter As Integer = 1
Private Sub Event_TvChannelChange()
If _ChannelChangeCounter = 1 Then
'GUIPropertyManager.SetProperty("#myTvNiveauChecker.active", False)
_ChannelChangeCounter = 2
Else
_ChannelChangeCounter = 1
If g_Player.IsTV = True And g_Player.IsTVRecording = False Then
Try
CheckTimer(False)
Catch ex As Exception
End Try
getCurrentProgram()
End If
End If
End Sub
Private Sub Event_GuiAction(ByVal action As Global.MediaPortal.GUI.Library.Action)
'myTvNiveauChecker aktivieren / deaktivieren, by user key press (key defined in setup)
'nur aktiv in TvHomeServer & Fullscreen (window ids 1/ 602)
If GUIWindowManager.ActiveWindow = 1 Or GUIWindowManager.ActiveWindow = 602 Then
If g_Player.IsTV = True And g_Player.IsTVRecording = False Then
'Window spezifische tasten abfangen um prop zu reseten (sonst wird das erst nach kanal wechsel ausgeführt)
If GUIWindowManager.ActiveWindow = 1 Then
Select Case action.wID
Case Is = action.ActionType.ACTION_PAGE_UP
GUIPropertyManager.SetProperty("#myTvNiveauChecker.active", False)
Case Is = action.ActionType.ACTION_PAGE_DOWN
GUIPropertyManager.SetProperty("#myTvNiveauChecker.active", False)
Case Is = action.ActionType.ACTION_STOP
GUIPropertyManager.SetProperty("#myTvNiveauChecker.active", False)
TvEventTimer(False)
End Select
End If
If GUIWindowManager.ActiveWindow = 602 Then
Select Case action.wID
Case Is = action.ActionType.ACTION_STOP
GUIPropertyManager.SetProperty("#myTvNiveauChecker.active", False)
TvEventTimer(False)
Case Is = action.ActionType.ACTION_NEXT_CHANNEL
GUIPropertyManager.SetProperty("#myTvNiveauChecker.active", False)
Case Is = action.ActionType.ACTION_PREV_CHANNEL
GUIPropertyManager.SetProperty("#myTvNiveauChecker.active", False)
End Select
End If
'myTvNiveauChecker actions
Select Case action.wID
Case CType([Enum].Parse(GetType(Action.ActionType), mySettings.BtnDeactivate), Action.ActionType)
If _deactivated = False Then
_deactivated = True
MyLog.Info("myTvNiveauChecker deactivated")
Try
CheckTimer(False)
Catch ex As Exception
End Try
MP_Notify(Translation.deactivated)
Else
_deactivated = False
MyLog.Info("myTvNiveauChecker activated")
CheckTimer(True)
MP_Notify(Translation.activated)
End If
Case CType([Enum].Parse(GetType(Action.ActionType), mySettings.BtnAdd), Action.ActionType)
Try
Dim _test As myTNC = myTNC.Retrieve(_CurrentProgram.Title)
MP_Notify(Translation.stilladded)
Catch ex As Exception
'Dialog fragen ob zur db hinzufügen
Dim dlgContext As GUIDialogPlayStop = CType(GUIWindowManager.GetWindow(CType(GUIWindow.Window.WINDOW_DIALOG_PLAY_STOP, Integer)), GUIDialogPlayStop)
dlgContext.Reset()
'ContextMenu Layout
dlgContext.SetHeading("myTvNiveauChecker")
dlgContext.SetLine(1, _CurrentProgram.Title)
dlgContext.SetLine(2, Translation.addtoBlacklist)
dlgContext.SetDefaultToStop(False)
dlgContext.DoModal(GUIWindowManager.ActiveWindow)
If dlgContext.IsStopConfirmed = True Then
Dim _add As New myTNC(_CurrentProgram.Title)
_add.matchRule = myTvNiveauChecker.Match.exact.ToString
_add.Persist()
MyLog.Info("added {0} to blacklist", _CurrentProgram.Title)
CheckTimer(True)
End If
End Try
End Select
End If
End If
End Sub
#End Region
Private Sub getCurrentProgram()
Dim _userList As New List(Of IUser)
Dim _cards = TvDatabase.Card.ListAll()
For Each _card In _cards
_userList.AddRange(RemoteControl.Instance.GetUsersForCard(_card.IdCard))
Next
If Not _userList.Count = 0 Then
For Each user In _userList
If user.Name.ToLower = My.Computer.Name.ToLower Then
'Program laden
Dim _channel = Channel.Retrieve(user.IdChannel)
Try
Dim _program = _channel.GetProgramAt(Now)
If Not _program.IdProgram = _idCurrentProgram Then
_idCurrentProgram = _program.IdProgram
_CurrentEndTime = _program.EndTime
MyLog.Info("current program: {0} ({1})", _program.Title, _channel.DisplayName)
_CurrentProgram = _program
CheckTimer(True)
End If
Exit For
Catch ex As Exception
MyLog.Warn("current program has no epg data! - {0}", _channel.DisplayName)
End Try
End If
Next
End If
End Sub
Private Sub TvEventTimer(ByVal startNow As Boolean)
'timer der prüft ob sich das Progran geändert hat, also wechsel des Program auf gleichem Sender
If startNow Then
If _stateTimer Is Nothing Then
MyLog.Info("TvEvent timer started...")
getCurrentProgram()
_stateTimer = New System.Timers.Timer()
AddHandler _stateTimer.Elapsed, New ElapsedEventHandler(AddressOf programChanged)
_stateTimer.Interval = 1000
_stateTimer.AutoReset = True
GC.KeepAlive(_stateTimer)
End If
_stateTimer.Start()
_stateTimer.Enabled = True
Else
_idCurrentProgram = 0
_CurrentProgram = Nothing
Try
CheckTimer(False)
Catch ex As Exception
End Try
_stateTimer.Enabled = False
_stateTimer.[Stop]()
'Event Handler key press
'RemoveHandler GUIWindowManager.OnNewAction, AddressOf Event_GuiAction
_stateTimer = Nothing
MyLog.Info("TvEvent timer stopped")
MyLog.Info("-------------------------------------------------------")
End If
End Sub
Private Sub programChanged()
If g_Player.IsTV = True And g_Player.IsTVRecording = False Then
If _idCurrentProgram > 0 And Now > _CurrentEndTime Then
getCurrentProgram()
End If
Else
'Falls Player nicht mehr TV, dann alle timer beenden
TvEventTimer(False)
End If
End Sub
Private Sub CheckTimer(ByVal startNow As Boolean)
'CountDown Timer, wird nur gestartet wenn program blacklisted ist!
If startNow And _deactivated = False Then
'wenn in myTNC gefunden, dann Countdown starten
Dim _myTncList As List(Of myTNC) = myTNC.ListAll
If _myTncList.FindAll(Function(x) InStr(_CurrentProgram.Title, x.name) > 0).Count > 0 Then
Dim _match As myTNC = _myTncList.Find(Function(x) InStr(_CurrentProgram.Title, x.name) > 0)
Select Case _match.matchRule
Case Is = myTvNiveauChecker.Match.contains.ToString
blacklisted()
Case Is = myTvNiveauChecker.Match.exact.ToString
If _CurrentProgram.Title = _match.name Then
blacklisted()
Else
MyLog.Info("{0}: clear (rule: {1})", _CurrentProgram.Title, _match.matchRule)
GUIPropertyManager.SetProperty("#myTvNiveauChecker.active", False)
End If
End Select
Else
MyLog.Info("{0}: clear ;)", _CurrentProgram.Title)
GUIPropertyManager.SetProperty("#myTvNiveauChecker.active", False)
End If
Else
_CheckTimer.Enabled = False
_CheckTimer.[Stop]()
_CountDownTimer.Enabled = False
_CountDownTimer.[Stop]()
_CountDown = 0
GUIPropertyManager.SetProperty("#myTvNiveauChecker.active", False)
MyLog.Debug("myTvNiveauChecker CheckTimer stopped!")
End If
End Sub
Private Sub blacklisted()
MyLog.Warn("{0}: blacklisted!", _CurrentProgram.Title)
MyLog.Debug("myTvNiveauChecker CheckTimer started!")
'skin properties ausgeben
GUIPropertyManager.SetProperty("#myTvNiveauChecker.active", True)
_CountDown = mySettings.delay - 2
If _CountDownTimer Is Nothing Then
_CountDownTimer = New System.Timers.Timer()
AddHandler _CountDownTimer.Elapsed, New ElapsedEventHandler(AddressOf countDownPropertiy)
_CountDownTimer.Interval = 1000
_CountDownTimer.AutoReset = True
GC.KeepAlive(_CountDownTimer)
End If
If _CheckTimer Is Nothing Then
_CheckTimer = New System.Timers.Timer()
AddHandler _CheckTimer.Elapsed, New ElapsedEventHandler(AddressOf StopPlayer)
_CheckTimer.Interval = mySettings.delay * 1000
_CheckTimer.AutoReset = True
GC.KeepAlive(_CheckTimer)
End If
MyLog.Debug("myTvNiveauChecker Countdown started ...")
_CheckTimer.Start()
_CheckTimer.Enabled = True
_CountDownTimer.Start()
_CountDownTimer.Enabled = True
End Sub
Private Sub countDownPropertiy()
GUIPropertyManager.SetProperty("#myTvNiveauChecker.CountDown", _CountDown)
_CountDown = _CountDown - 1
End Sub
Private Sub StopPlayer()
CheckTimer(False)
If mySettings.dlgMessageShow = True Then
MP_Notify(mySettings.dlgMessage)
End If
'Action Stop an MP schicken
Dim action__1 As New Action(Action.ActionType.ACTION_STOP, 0, 0)
GUIGraphicsContext.OnAction(action__1)
GUIGraphicsContext.OnAction(action__1)
MyLog.Info("Tv stopped!")
End Sub
Public Shared Sub CheckTvDatabaseTable()
If Gentle.Framework.Broker.ProviderName = "MySQL" Then
'MySQL
Try
Gentle.Framework.Broker.Execute("CREATE TABLE mptvdb.myTNC ( `Name` varchar(255) NOT NULL, `matchRule` varchar(45), PRIMARY KEY (`Name`))")
MyLog.Info("myTNC table created")
Catch ex As Exception
MyLog.Warn(ex.Message)
End Try
Else
'MSSQL
Try
Gentle.Framework.Broker.Execute("CREATE TABLE [mptvdb].[dbo].[myTNC] ( Name varchar(255) NOT NULL, matchingRule varchar(45), PRIMARY KEY (Name))")
MyLog.Info("myTNC table created")
Catch ex As Exception
MyLog.Warn(ex.Message)
End Try
End If
End Sub
Friend Shared Sub MP_Notify(ByVal message As String)
Try
Dim dlgContext As GUIDialogNotify = CType(GUIWindowManager.GetWindow(CType(GUIWindow.Window.WINDOW_DIALOG_NOTIFY, Integer)), GUIDialogNotify)
dlgContext.Reset()
dlgContext.SetHeading("myTvNiveauChecker")
dlgContext.SetImage(Config.GetFile(Config.Dir.Skin, GUIGraphicsContext.SkinName & "\Media\" & "icon_myTvNiveauChecker.png"))
dlgContext.SetText(message)
dlgContext.TimeOut = 5
dlgContext.DoModal(GUIWindowManager.ActiveWindow)
dlgContext.Dispose()
dlgContext.AllocResources()
Catch ex As Exception
MyLog.Error("[Helper]: [Notify]: exception err: {0} stack: {1}", ex.Message, ex.StackTrace)
End Try
End Sub
End Class
|
Imports System.Xml
Imports System.IO
Imports System.Xml.Serialization
Public Class InstrumentXMLSerializationForm
Sub New()
' This call is required by the designer.
InitializeComponent()
LoadForm()
' Add any initialization after the InitializeComponent() call.
End Sub
Private Sub InstrumentXMLSerializationForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Public ExpandStart, ExpandEnd, GroupStart, GroupEnd As Long()
Private Sub LoadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadButton.Click
SumdataGridView.Rows.Clear()
LoadForm()
End Sub
Private Sub AutoFillButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AutoFillButton.Click
DefaultValues()
End Sub
''' <summary>
''' Saves the called Object(AnyObject) into xml file.
''' </summary>
''' <remarks>This can be used in the XMLSerializationForm</remarks>
Public Sub DefaultValues()
RichTextBox1.Text = "This Feature is coming soon!"
End Sub
''' <summary>
''' Save the datagridview format form data to xml file. Later xml file
''' will be deserialized in to an object
''' </summary>
''' <remarks></remarks>
Public Sub SaveForm()
Dim RowCount As Integer = 0
Dim FileDir As String = Directory.GetCurrentDirectory() & "\EquipmentConfig\"
Dim fileNames = My.Computer.FileSystem.GetFiles(
FileDir, FileIO.SearchOption.SearchTopLevelOnly, "*.xml")
Dim InstrInfo As New InstrumentDetails
For Each Row As Object In SumdataGridView.Rows
InstrInfo = New InstrumentDetails 'Clear InstrInfo for every Instrument/Test Address write
Dim fileName As String = "InstrCount" & Row.Cells.Item(2).Value & " " & Row.Cells.Item(0).Value & " Com.SiLabs.Timing.Instrument." & Row.Cells.Item(1).Value & ".xml"
Dim FilePath As String = FileDir & fileName
If Row.Cells.Item(3).Value = "" Then 'ComType
Row.Cells.Item(3).Selected = True
SumdataGridView.Select()
RichTextBox1.Text = "Save Failed, Enter the data in the selected Cell to continue!"
Exit Sub
End If
InstrInfo.ComType = Row.Cells.Item(3).Value
If Row.Cells.Item(4).Value = "" Then 'Address
Row.Cells.Item(4).Selected = True
SumdataGridView.Select()
RichTextBox1.Text = "Save Failed, Enter the data in the selected Cell to continue!"
Exit Sub
End If
InstrInfo.Address = Row.Cells.Item(4).Value
'Serialize object to a text file.
Dim objStreamWriter As New StreamWriter(FilePath)
Dim x As New XmlSerializer(InstrInfo.GetType)
x.Serialize(objStreamWriter, InstrInfo)
objStreamWriter.Close()
Next
End Sub
Class InstrumentDetails
Public ComType As String = "0"
Public Address As String = ""
End Class
''' <summary>
''' Load the xml of an object converted using xml serialization
''' into Datagridview. Includes interactive control such as expand and collapse,
''' Color the cell for easy view.
''' </summary>
''' <remarks></remarks>
Public Sub LoadForm()
Dim EnableForm As Boolean = False
Dim RowCount As Integer = 0
Dim FileDir As String = Directory.GetCurrentDirectory() & "\EquipmentConfig\"
Dim temp
Dim fileNames = My.Computer.FileSystem.GetFiles(
FileDir, FileIO.SearchOption.SearchTopLevelOnly, "*.xml")
Dim InstrInfo As New InstrumentDetails
For Each fileName As String In fileNames
Dim objStreamReader As New StreamReader(fileName)
Dim serializedSettings As New XmlSerializer(InstrInfo.GetType) 'open deserializer
InstrInfo = Nothing
InstrInfo = CType(serializedSettings.Deserialize(objStreamReader), InstrumentDetails) 'deserialize
objStreamReader.Close() 'close settings file
Dim FileStr As String = Path.GetFileName(fileName)
temp = Split(FileStr, " ")
SumdataGridView.Rows.Add(1)
RowCount = RowCount + 1
SumdataGridView.Rows.Item(RowCount - 1).Cells.Item(0).Value = temp(1).ToString
temp(2) = Replace(temp(2).ToString, "Com.SiLabs.Timing.Instrument.", "")
temp(2) = Replace(temp(2).ToString, ".xml", "")
SumdataGridView.Rows.Item(RowCount - 1).Cells.Item(1).Value = temp(2).ToString
SumdataGridView.Rows.Item(RowCount - 1).Cells.Item(2).Value = Replace(temp(0).ToString, "InstrCount", "")
Select Case InstrInfo.ComType
Case "GPIB"
SumdataGridView.Rows.Item(RowCount - 1).Cells.Item(3).Value = "GPIB"
Case "USB"
SumdataGridView.Rows.Item(RowCount - 1).Cells.Item(3).Value = "USB"
Case "RS232"
SumdataGridView.Rows.Item(RowCount - 1).Cells.Item(3).Value = "RS232"
Case "USBX"
SumdataGridView.Rows.Item(RowCount - 1).Cells.Item(3).Value = "USBX"
Case "LAN"
SumdataGridView.Rows.Item(RowCount - 1).Cells.Item(3).Value = "LAN"
End Select
SumdataGridView.Rows.Item(RowCount - 1).Cells.Item(4).Value = InstrInfo.Address
If InstrInfo.Address = "" Or InstrInfo.ComType = "" Then EnableForm = True
Next
'Check it is called from Main.UpdateTestSelect()
Dim stackInfo As String = Environment.StackTrace.ToString()
temp = Split(stackInfo, vbCrLf)
Dim InstrName As String = ""
InstrName = temp(4).ToString
'If called from UpdateTestSelect then try to close
If EnableForm = False And InStr(InstrName, "UpdateTestSelect") > 0 Then Me.Close()
End Sub
Private Sub DefaultButton_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles AutoFillButton.MouseEnter
RichTextBox1.Text = "To get default values, enter the Values inside the class initialization"
End Sub
Private Sub LoadButton_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles LoadButton.MouseEnter
RichTextBox1.Text = "Load your own xml file"
End Sub
Private Sub ContinueButton_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs)
RichTextBox1.Text = "Saves the data to default XML and continues"
End Sub
Private Sub ExitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitButton.Click
File.Create(System.IO.Path.GetTempPath & "terminate.txt").Dispose()
Me.Close()
End Sub
Private Sub ExitButton_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles ExitButton.MouseEnter
RichTextBox1.Text = "Exit the Program"
End Sub
Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click
SaveForm()
End Sub
Private Sub SaveButton_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles SaveButton.MouseEnter
RichTextBox1.Text = "Saves the data to default XML"
End Sub
End Class |
Imports DevExpress.Xpf.Core
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Media
Namespace RibbonDemo
Public Class ThemedContentControl
Inherits ContentControl
#Region "static"
Public Shared ReadOnly IsHoverStateProperty As DependencyProperty = DependencyProperty.Register("IsHoverState", GetType(Boolean), GetType(ThemedContentControl), New PropertyMetadata(False, New PropertyChangedCallback(AddressOf OnHoverStatePropertyChanged)))
Public Shared ReadOnly LightThemeNormalForegroundProperty As DependencyProperty = DependencyProperty.Register("LightThemeNormalForeground", GetType(Brush), GetType(ThemedContentControl), New PropertyMetadata(Nothing))
Public Shared ReadOnly DarkThemeNormalForegroundProperty As DependencyProperty = DependencyProperty.Register("DarkThemeNormalForeground", GetType(Brush), GetType(ThemedContentControl), New PropertyMetadata(Nothing))
Public Shared ReadOnly LightThemeHoverForegroundProperty As DependencyProperty = DependencyProperty.Register("LightThemeHoverForeground", GetType(Brush), GetType(ThemedContentControl), New PropertyMetadata(Nothing))
Public Shared ReadOnly DarkThemeHoverForegroundProperty As DependencyProperty = DependencyProperty.Register("DarkThemeHoverForeground", GetType(Brush), GetType(ThemedContentControl), New PropertyMetadata(Nothing))
Protected Shared Sub OnHoverStatePropertyChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
CType(d, ThemedContentControl).UpdateForeground()
End Sub
#End Region
#Region "dep props"
Public Property IsHoverState() As Boolean
Get
Return DirectCast(GetValue(IsHoverStateProperty), Boolean)
End Get
Set(ByVal value As Boolean)
SetValue(IsHoverStateProperty, value)
End Set
End Property
Public Property LightThemeNormalForeground() As Brush
Get
Return DirectCast(GetValue(LightThemeNormalForegroundProperty), Brush)
End Get
Set(ByVal value As Brush)
SetValue(LightThemeNormalForegroundProperty, value)
End Set
End Property
Public Property DarkThemeNormalForeground() As Brush
Get
Return DirectCast(GetValue(DarkThemeNormalForegroundProperty), Brush)
End Get
Set(ByVal value As Brush)
SetValue(DarkThemeNormalForegroundProperty, value)
End Set
End Property
Public Property LightThemeHoverForeground() As Brush
Get
Return DirectCast(GetValue(LightThemeHoverForegroundProperty), Brush)
End Get
Set(ByVal value As Brush)
SetValue(LightThemeHoverForegroundProperty, value)
End Set
End Property
Public Property DarkThemeHoverForeground() As Brush
Get
Return DirectCast(GetValue(DarkThemeHoverForegroundProperty), Brush)
End Get
Set(ByVal value As Brush)
SetValue(DarkThemeHoverForegroundProperty, value)
End Set
End Property
#End Region
#Region "props "
Private ReadOnly Property IsDarkTheme() As Boolean
Get
Return ApplicationThemeHelper.ApplicationThemeName = Theme.MetropolisDarkName OrElse ApplicationThemeHelper.ApplicationThemeName = Theme.TouchlineDarkName OrElse ApplicationThemeHelper.ApplicationThemeName = Theme.Office2016DarkGraySEName
End Get
End Property
#End Region
Public Sub New()
DefaultStyleKey = GetType(ThemedContentControl)
AddHandler Loaded, AddressOf OnLoaded
End Sub
Private Sub OnLoaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
UpdateForeground()
End Sub
Private Sub UpdateForeground()
If IsHoverState Then
Foreground = If(IsDarkTheme, DarkThemeHoverForeground, LightThemeHoverForeground)
Else
Foreground = If(IsDarkTheme, DarkThemeNormalForeground, LightThemeNormalForeground)
End If
End Sub
End Class
End Namespace
|
#Region "License"
' The MIT License (MIT)
'
' Copyright (c) 2017 Richard L King (TradeWright Software Systems)
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
#End Region
Imports OrderUtils27
Public Module Orders
#Region "Interfaces"
#End Region
#Region "Events"
#End Region
#Region "Enums"
#End Region
#Region "Types"
#End Region
#Region "Constants"
Private Const ModuleName As String = "Orders"
#End Region
#Region "Member variables"
#End Region
#Region "Constructors"
#End Region
#Region "XXXX Interface Members"
#End Region
#Region "XXXX Event Handlers"
#End Region
#Region "Properties"
Public ReadOnly Property AccountBalance() As Double
Get
' dummy value at present, awaiting development of an Account Service Provider
AccountBalance = 10000
End Get
End Property
Public ReadOnly Property ActiveBuySize() As Integer
Get
ActiveBuySize = getDefaultOrderContext(True, False).ActiveSize
End Get
End Property
Public ReadOnly Property ActiveSellSize() As Integer
Get
ActiveSellSize = getDefaultOrderContext(False, False).ActiveSize
End Get
End Property
Public ReadOnly Property ActiveSimulatedBuySize() As Integer
Get
ActiveSimulatedBuySize = getDefaultOrderContext(True, True).ActiveSize
End Get
End Property
Public ReadOnly Property ActiveSimulatedSellSize() As Integer
Get
ActiveSimulatedSellSize = getDefaultOrderContext(False, True).ActiveSize
End Get
End Property
Public ReadOnly Property ActiveSize(OrderContext As OrderContext) As Integer
Get
ActiveSize = OrderContext.OrderContext.ActiveSize
End Get
End Property
Public ReadOnly Property AveragePrice(Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing) As Double
Get
AveragePrice = getBracketOrder(BracketOrder).EntryOrder.AveragePrice
End Get
End Property
Public ReadOnly Property EntryPrice(Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing) As Double
Get
EntryPrice = getBracketOrder(BracketOrder).EntryOrder.LimitPrice
End Get
End Property
Public ReadOnly Property EntryOffset(Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing) As Integer
Get
EntryOffset = getBracketOrder(BracketOrder).EntryOrder.Offset
End Get
End Property
Public ReadOnly Property EntryTriggerPrice(Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing) As Double
Get
EntryTriggerPrice = getBracketOrder(BracketOrder).EntryOrder.TriggerPrice
End Get
End Property
Public ReadOnly Property IsBuy(Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing) As Boolean
Get
IsBuy = getBracketOrder(BracketOrder).LongPosition
End Get
End Property
Public ReadOnly Property IsCompleted(Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing) As Boolean
Get
IsCompleted = (getBracketOrder(BracketOrder).State = BracketOrderStates.BracketOrderStateClosed)
End Get
End Property
Public ReadOnly Property IsSell(Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing) As Boolean
Get
IsSell = Not getBracketOrder(BracketOrder).LongPosition
End Get
End Property
Public ReadOnly Property PendingBuySize() As Integer
Get
PendingBuySize = getDefaultOrderContext(True, False).PendingSize
End Get
End Property
Public ReadOnly Property PendingSellSize() As Integer
Get
PendingSellSize = getDefaultOrderContext(False, False).PendingSize
End Get
End Property
Public ReadOnly Property PendingSimulatedBuySize() As Integer
Get
PendingSimulatedBuySize = getDefaultOrderContext(True, True).PendingSize
End Get
End Property
Public ReadOnly Property PendingSimulatedSellSize() As Integer
Get
PendingSimulatedSellSize = getDefaultOrderContext(False, True).PendingSize
End Get
End Property
Public ReadOnly Property PendingSize(OrderContext As OrderContext) As Integer
Get
PendingSize = OrderContext.OrderContext.PendingSize
End Get
End Property
Public ReadOnly Property PrimaryBracketOrder() As AutoTradingEnvironment.BracketOrder
Get
PrimaryBracketOrder = CurrentResourceContext.PrimaryBracketOrder
End Get
End Property
Public ReadOnly Property QuantityFilled(Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing) As Integer
Get
QuantityFilled = getBracketOrder(BracketOrder).EntryOrder.QuantityFilled
End Get
End Property
Public ReadOnly Property Size(OrderContext As OrderContext) As Integer
Get
Size = OrderContext.OrderContext.Size
End Get
End Property
Public ReadOnly Property StopLossPrice(Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing) As Double
Get
StopLossPrice = getBracketOrder(BracketOrder).StopLossOrder.LimitPrice
End Get
End Property
Public ReadOnly Property StopLossOffset(Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing) As Integer
Get
StopLossOffset = getBracketOrder(BracketOrder).StopLossOrder.Offset
End Get
End Property
Public ReadOnly Property StopLossTriggerPrice(Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing) As Double
Get
StopLossTriggerPrice = getBracketOrder(BracketOrder).StopLossOrder.TriggerPrice
End Get
End Property
Public ReadOnly Property TargetPrice(Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing) As Double
Get
TargetPrice = getBracketOrder(BracketOrder).TargetOrder.LimitPrice
End Get
End Property
Public ReadOnly Property TargetOffset(Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing) As Integer
Get
TargetOffset = getBracketOrder(BracketOrder).TargetOrder.Offset
End Get
End Property
Public ReadOnly Property TargetTriggerPrice(Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing) As Double
Get
TargetTriggerPrice = getBracketOrder(BracketOrder).TargetOrder.TriggerPrice
End Get
End Property
Public ReadOnly Property TotalPendingPositionSize() As Integer
Get
TotalPendingPositionSize = CurrentTradingContext.PositionManager.PendingPositionSize
End Get
End Property
Public ReadOnly Property TotalPositionSize() As Integer
Get
TotalPositionSize = CurrentTradingContext.PositionManager.PositionSize
End Get
End Property
Public ReadOnly Property TotalSimulatedPendingPositionSize() As Integer
Get
TotalSimulatedPendingPositionSize = CurrentTradingContext.PositionManagerSimulated.PendingPositionSize
End Get
End Property
Public ReadOnly Property TotalSimulatedPositionSize() As Integer
Get
TotalSimulatedPositionSize = CurrentTradingContext.PositionManagerSimulated.PositionSize
End Get
End Property
#End Region
#Region "Methods"
Public Sub AdjustStop(StopTriggerPrice As Double, Optional Quantity As Integer = -1, Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing)
getBracketOrder(BracketOrder).AdjustStop(StopTriggerPrice, Quantity)
End Sub
Public Function Buy(Number As Integer,
EntryOrder As OrderSpecifier,
Optional StopLossOrder As OrderSpecifier = Nothing,
Optional TargetOrder As OrderSpecifier = Nothing,
Optional CancelPrice As Double = 0,
Optional CancelAfter As Integer = 0,
Optional NotifyCompletion As Boolean = False,
Optional OrderContext As OrderContext = Nothing) As AutoTradingEnvironment.BracketOrder
Buy = buyOrSell(True, OrderContext, False, Number, EntryOrder, StopLossOrder, TargetOrder, CancelPrice, CancelAfter, NotifyCompletion)
End Function
Public Function BuySimulated(Number As Integer,
EntryOrder As OrderSpecifier,
Optional StopLossOrder As OrderSpecifier = Nothing,
Optional TargetOrder As OrderSpecifier = Nothing,
Optional CancelPrice As Double = 0,
Optional CancelAfter As Integer = 0,
Optional NotifyCompletion As Boolean = False,
Optional OrderContext As OrderContext = Nothing) As AutoTradingEnvironment.BracketOrder
BuySimulated = buyOrSell(True, OrderContext, True, Number, EntryOrder, StopLossOrder, TargetOrder, CancelPrice, CancelAfter, NotifyCompletion)
End Function
Public Sub CancelBracketOrder(Optional EvenIfFilled As Boolean = False, Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing)
getBracketOrder(BracketOrder).Cancel(EvenIfFilled)
End Sub
Public Function CanTrade(Optional OrderContext As OrderContext = Nothing) As Boolean
If OrderContext Is Nothing Then
CanTrade = canTradeContext(Nothing, True, False) And canTradeContext(Nothing, False, False)
Else
' note the value of pIsBuy in this call is irrelevant
CanTrade = canTradeContext(OrderContext, False, False)
End If
End Function
Public Function CanTradeSimulated(Optional OrderContext As OrderContext = Nothing) As Boolean
If OrderContext Is Nothing Then
CanTradeSimulated = canTradeContext(Nothing, True, True) And canTradeContext(Nothing, False, True)
Else
' note the value of pIsBuy in this call is irrelevant
CanTradeSimulated = canTradeContext(OrderContext, False, True)
End If
End Function
Public Sub ClearPrimaryBracketOrder()
CurrentResourceContext.ClearPrimaryBracketOrder()
End Sub
Public Sub CloseAllPositions()
CurrentTradingContext.PositionManager.ClosePositions()
End Sub
Public Sub CloseAllSimulatedPositions()
CurrentTradingContext.PositionManagerSimulated.ClosePositions()
End Sub
Public Sub AllowUnprotectedPositions()
Assert(Not CurrentInitialisationContext Is Nothing, "Method can only be called during strategy initialisation")
CurrentInitialisationContext.AllowUnprotectedPositions = True
For Each oc As OrderUtils27.OrderContext In CurrentInitialisationContext.PositionManager.OrderContexts
oc.PreventUnprotectedPositions = False
Next oc
End Sub
Public Function Sell(Number As Integer,
EntryOrder As OrderSpecifier,
Optional StopLossOrder As OrderSpecifier = Nothing,
Optional TargetOrder As OrderSpecifier = Nothing,
Optional CancelPrice As Double = 0,
Optional CancelAfter As Integer = 0,
Optional NotifyCompletion As Boolean = False,
Optional OrderContext As OrderContext = Nothing) As AutoTradingEnvironment.BracketOrder
Sell = buyOrSell(False, OrderContext, False, Number, EntryOrder, StopLossOrder, TargetOrder, CancelPrice, CancelAfter, NotifyCompletion)
End Function
Public Function SellSimulated(Number As Integer,
EntryOrder As OrderSpecifier,
Optional StopLossOrder As OrderSpecifier = Nothing,
Optional TargetOrder As OrderSpecifier = Nothing,
Optional CancelPrice As Double = 0,
Optional CancelAfter As Integer = 0,
Optional NotifyCompletion As Boolean = False,
Optional OrderContext As OrderContext = Nothing) As AutoTradingEnvironment.BracketOrder
SellSimulated = buyOrSell(False, OrderContext, True, Number, EntryOrder, StopLossOrder, TargetOrder, CancelPrice, CancelAfter, NotifyCompletion)
End Function
Public Sub SetEntryReason(Reason As String, Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing)
getBracketOrder(BracketOrder).EntryReason = Reason
End Sub
Public Sub SetNewEntryPrice(Price As Double, Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing)
getBracketOrder(BracketOrder).SetNewEntryPrice(Price)
End Sub
Public Sub SetNewEntryTriggerPrice(Price As Double, Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing)
getBracketOrder(BracketOrder).SetNewEntryTriggerPrice(Price)
End Sub
Public Sub SetNewQuantity(Quantity As Integer, Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing)
getBracketOrder(BracketOrder).SetNewQuantity(Quantity)
End Sub
Public Sub SetNewStopLossOffset(Offset As Integer, Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing)
getBracketOrder(BracketOrder).SetNewStopLossOffset(Offset)
End Sub
Public Sub SetNewStopLossPrice(Price As Double, Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing)
getBracketOrder(BracketOrder).SetNewStopLossPrice(Price)
End Sub
Public Sub SetNewStopLossTriggerPrice(Price As Double, Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing)
getBracketOrder(BracketOrder).SetNewStopLossTriggerPrice(Price)
End Sub
Public Sub SetNewTargetOffset(Offset As Integer, Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing)
getBracketOrder(BracketOrder).SetNewTargetOffset(Offset)
End Sub
Public Sub SetNewTargetPrice(Price As Double, Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing)
getBracketOrder(BracketOrder).SetNewTargetPrice(Price)
End Sub
Public Sub SetNewTargetTriggerPrice(Price As Double, Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing)
getBracketOrder(BracketOrder).SetNewTargetTriggerPrice(Price)
End Sub
Public Sub SetPrimaryBracketOrder(BracketOrder As AutoTradingEnvironment.BracketOrder)
CurrentResourceContext.SetPrimaryBracketOrder(BracketOrder)
End Sub
Public Sub SetStopReason(Reason As String, Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing)
getBracketOrder(BracketOrder).StopReason = Reason
End Sub
Public Sub SetTargetReason(Reason As String, Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing)
getBracketOrder(BracketOrder).TargetReason = Reason
End Sub
Public Sub Update(Optional BracketOrder As AutoTradingEnvironment.BracketOrder = Nothing)
getBracketOrder(BracketOrder).Update()
End Sub
#End Region
#Region "Helper Functions"
Private Function buyOrSell(pIsBuy As Boolean,
pOrderContext As OrderContext,
pIsSimulated As Boolean,
pNumber As Integer,
pEntryOrder As OrderSpecifier,
pStopLossOrder As OrderSpecifier,
pTargetOrder As OrderSpecifier,
pCancelPrice As Double,
pCancelAfter As Integer,
pNotifyCompletion As Boolean) As AutoTradingEnvironment.BracketOrder
Assert(Not CurrentTradingContext Is Nothing, "Method can only be called during strategy execution")
AssertArgument(pNumber > 0, "Number must be greater than 0")
AssertArgument(Not pEntryOrder Is Nothing, "pEntryOrder must be supplied")
If pStopLossOrder Is Nothing Then pStopLossOrder = DeclareStopLossOrder(StopLossOrderType.None)
If pTargetOrder Is Nothing Then pTargetOrder = DeclareTargetOrder(TargetOrderType.None)
Dim lOrderContext As OrderUtils27.OrderContext
If pOrderContext Is Nothing Then
lOrderContext = getDefaultOrderContext(pIsBuy, pIsSimulated)
Else
lOrderContext = pOrderContext.OrderContext
Assert(lOrderContext.IsSimulated = pIsSimulated, "Order context has incorrect simulated property")
End If
validateOrderSpecifier(pEntryOrder, OrderRole.Entry)
validateOrderSpecifier(pStopLossOrder, OrderRole.StopLoss)
validateOrderSpecifier(pTargetOrder, OrderRole.Target)
Dim lBracketOrder As _IBracketOrder
If pIsBuy Then
lBracketOrder = doBuy(lOrderContext, pNumber, pEntryOrder, pStopLossOrder, pTargetOrder, pCancelPrice, pCancelAfter)
Else
lBracketOrder = doSell(lOrderContext, pNumber, pEntryOrder, pStopLossOrder, pTargetOrder, pCancelPrice, pCancelAfter)
End If
buyOrSell = New AutoTradingEnvironment.BracketOrder(lBracketOrder)
CurrentStrategyRunner.MapCOMBracketOrderToBracketOrder(lBracketOrder, buyOrSell)
requestNotification(lBracketOrder, pNotifyCompletion)
createAttachedStrategies(lBracketOrder)
End Function
Private Function canTradeContext(pOrderContext As OrderContext, pIsBuy As Boolean, pIsSimulated As Boolean) As Boolean
Dim lOrderContext As OrderUtils27.OrderContext
If pOrderContext Is Nothing Then
lOrderContext = getDefaultOrderContext(pIsBuy, pIsSimulated)
Else
lOrderContext = pOrderContext.OrderContext
Assert(lOrderContext.IsSimulated = pIsSimulated, "Order context has incorrect simulated property")
End If
canTradeContext = lOrderContext.IsReady
End Function
Private Sub createAttachedStrategies(pBracketOrder As _IBracketOrder)
Dim lFactory As IPositionManagementStrategyFactory
If TypeOf CurrentStrategy Is IStrategy Then
For Each lFactory In CurrentStrategyRunner.PositionManagementStrategyFactories
CurrentTradingContext.ApplyPositionManagementStrategy(pBracketOrder, lFactory.CreateStrategy(CurrentTradingContext), New ResourceContext(CurrentStrategyRunner.GetPositionManagementStrategyResourceContext(lFactory)))
Next lFactory
End If
End Sub
Private Function doBuy(pOrderContext As OrderUtils27.OrderContext,
pNumber As Integer,
pEntryOrderSpec As OrderSpecifier,
pStopLossOrderSpec As OrderSpecifier,
pTargetOrderSpec As OrderSpecifier,
pCancelPrice As Double,
pCancelAfter As Integer) As _IBracketOrder
Dim entryType = CType(pEntryOrderSpec.OrderType, BracketEntryTypes)
Dim entryTIF = CType(pEntryOrderSpec.TIF, OrderTIFs)
Dim stopLossType = CType(pStopLossOrderSpec.OrderType, BracketStopLossTypes)
Dim stopLossTIF = CType(pStopLossOrderSpec.TIF, OrderTIFs)
Dim targetType = CType(pTargetOrderSpec.OrderType, BracketTargetTypes)
Dim targetTIF = CType(pTargetOrderSpec.TIF, OrderTIFs)
Return pOrderContext.Buy(pNumber,
entryType,
pEntryOrderSpec.Price,
pEntryOrderSpec.Offset,
pEntryOrderSpec.TriggerPrice,
stopLossType,
pStopLossOrderSpec.TriggerPrice,
pStopLossOrderSpec.Offset,
pStopLossOrderSpec.Price,
targetType,
pTargetOrderSpec.Price,
pTargetOrderSpec.Offset,
pTargetOrderSpec.TriggerPrice,
entryTIF,
stopLossTIF,
targetTIF,
pCancelPrice,
pCancelAfter)
End Function
Private Function doSell(pOrderContext As OrderUtils27.OrderContext,
pNumber As Integer,
pEntryOrderSpec As OrderSpecifier,
pStopLossOrderSpec As OrderSpecifier,
pTargetOrderSpec As OrderSpecifier,
pCancelPrice As Double,
pCancelAfter As Integer) As _IBracketOrder
Dim entryType = CType(pEntryOrderSpec.OrderType, BracketEntryTypes)
Dim entryTIF = CType(pEntryOrderSpec.TIF, OrderTIFs)
Dim stopLossType = CType(pStopLossOrderSpec.OrderType, BracketStopLossTypes)
Dim stopLossTIF = CType(pStopLossOrderSpec.TIF, OrderTIFs)
Dim targetType = CType(pTargetOrderSpec.OrderType, BracketTargetTypes)
Dim targetTIF = CType(pTargetOrderSpec.TIF, OrderTIFs)
Return pOrderContext.Sell(pNumber,
entryType,
pEntryOrderSpec.Price,
pEntryOrderSpec.Offset,
pEntryOrderSpec.TriggerPrice,
stopLossType,
pStopLossOrderSpec.TriggerPrice,
pStopLossOrderSpec.Offset,
pStopLossOrderSpec.Price,
targetType,
pTargetOrderSpec.Price,
pTargetOrderSpec.Offset,
pTargetOrderSpec.TriggerPrice,
entryTIF,
stopLossTIF,
targetTIF,
pCancelPrice,
pCancelAfter)
End Function
Private Function getBracketOrder(pBracketOrder As AutoTradingEnvironment.BracketOrder) As _IBracketOrder
If pBracketOrder Is Nothing Then pBracketOrder = CurrentResourceContext.PrimaryBracketOrder
Dim lObj = pBracketOrder.BracketOrder
Return DirectCast(lObj, _IBracketOrder)
End Function
Private Function getDefaultOrderContext(pIsBuy As Boolean, pIsSimulated As Boolean) As OrderUtils27.OrderContext
Dim lOrderContext As OrderUtils27.OrderContext
If pIsBuy Then
If pIsSimulated Then
lOrderContext = CurrentTradingContext.DefaultBuyOrderContextSimulated
Else
lOrderContext = CurrentTradingContext.DefaultBuyOrderContext
End If
Else
If pIsSimulated Then
lOrderContext = CurrentTradingContext.DefaultSellOrderContextSimulated
Else
lOrderContext = CurrentTradingContext.DefaultSellOrderContext
End If
End If
getDefaultOrderContext = lOrderContext
End Function
Private Sub requestNotification(pBracketOrder As _IBracketOrder, pNotifyCompletion As Boolean)
If pNotifyCompletion Then CurrentStrategyRunner.RequestBracketOrderNotification(pBracketOrder, CurrentStrategy, CurrentResourceContext)
End Sub
Private Sub validateOrderSpecifier(pOrderSpec As OrderSpecifier, pRole As OrderRole)
AssertArgument(pOrderSpec.OrderRole = pRole, "Order specifier not correct role (entry, stop-loss or target)")
End Sub
#End Region
End Module |
' This example shows how new documents can be added.
'
' Documentation: https://docs.basex.org/wiki/Clients
'
' (C) BaseX Team 2005-23, BSD License
Imports System
Imports System.IO
Module CreateExample
Sub Main()
Try
' create session
Dim session As New Session("localhost", 1984, "admin", "admin")
' create empty database
session.Execute("create db database")
Console.WriteLine(session.Info)
' define InputStream
Dim ms As New MemoryStream(System.Text.Encoding.UTF8.GetBytes("<xml>Hello World!</xml>"))
' add document
session.Add("world/World.xml", ms)
Console.WriteLine(session.Info)
' define InputStream
Dim ms As New MemoryStream(System.Text.Encoding.UTF8.GetBytes("<xml>Hello Universe!</xml>"))
' add document
session.Add("Universe.xml", ms)
Console.WriteLine(session.Info)
' run query on database
Console.WriteLine(session.Execute("xquery /"))
' drop database
session.Execute("drop db database")
' close session
session.Close()
Catch e As IOException
' print exception
Console.WriteLine(e.Message)
End Try
End Sub
End Module |
Imports System.Runtime.InteropServices
Imports System.Drawing.Drawing2D
Public Class frmVLCDrawing
#Region "Properties"
Private _DrawSubtitles As Boolean = False 'Temporary property
Public Property DrawSubtitles As Boolean
Get
Return _DrawSubtitles
End Get
Set(value As Boolean)
_DrawSubtitles = value
Invalidate()
End Set
End Property
Private _DrawNotification As Boolean = False
Public Property DrawNotification As Boolean
Get
Return _DrawNotification
End Get
Set(value As Boolean)
_DrawNotification = value
Invalidate()
End Set
End Property
Private _DrawExitButton As Boolean = False
Public Property DrawExitButton As Boolean
Get
Return _DrawExitButton
End Get
Set(value As Boolean)
_DrawExitButton = value
If value Then
tmrExitButtonTimeOut.Stop()
tmrExitButtonTimeOut.Start()
Else
tmrExitButtonTimeOut.Stop()
End If
Invalidate()
End Set
End Property
Private _DrawVideoStateButton As PlayPauseBufferButtonStyles = PlayPauseBufferButtonStyles.Play
Public Property DrawVideoStateButton As PlayPauseBufferButtonStyles
Get
Return _DrawVideoStateButton
End Get
Set(value As PlayPauseBufferButtonStyles)
_DrawVideoStateButton = value
Invalidate()
End Set
End Property
Enum PlayPauseBufferButtonStyles
Play = 0
Pause = 1
Buffering = 2
End Enum
Private _BufferingValue As Integer = 0
Public Property BufferingValue As Integer
Get
Return _BufferingValue
End Get
Set(value As Integer)
If value <> _BufferingValue Then
_BufferingValue = value
Invalidate()
End If
End Set
End Property
Private _SubtitleText As String = String.Empty
Public Property SubtitleText As String
Get
Return _SubtitleText
End Get
Set(value As String)
_SubtitleText = value
End Set
End Property
#End Region
#Region "Private Fields"
Private WithEvents tmrExitButtonTimeOut As New Timer With {.Enabled = False, .Interval = 3000}
#End Region
Public Event CrossClicked()
Protected Overrides Sub OnShown(e As EventArgs)
AddHandler frmMain.Move, Sub()
MakeFormFitOnVLCPlayer()
End Sub
AddHandler frmMain.Resize, Sub()
MakeFormFitOnVLCPlayer()
End Sub
AddHandler frmMain.pnl_VideoPlayback.Resize, Sub()
MakeFormFitOnVLCPlayer()
End Sub
AddHandler frmMain.pnl_VideoPlayback.Move, Sub()
MakeFormFitOnVLCPlayer()
End Sub
MakeFormFitOnVLCPlayer()
MyBase.OnShown(e)
End Sub
Private _ResetDrawing As Boolean = False
Public Sub ResetDrawing()
_SubtitleText = String.Empty
_DrawExitButton = False
_DrawSubtitles = False
_DrawNotification = False
_DrawVideoStateButton = PlayPauseBufferButtonStyles.Play
PaintHook()
End Sub
Public NotificationText As String = String.Empty
Public Sub PaintHook()
Using B As New Bitmap(Width, Height)
Using G As Graphics = Graphics.FromImage(B)
If _DrawSubtitles Then
DrawSubtitleToSubtitlesForm(G, B, _SubtitleText, Settings.Data.SubFont, Settings.Data.SubColor)
End If
If _DrawExitButton Then
DrawExitButtonToVideo(G, B)
End If
If _DrawNotification AndAlso _DrawVideoStateButton <> PlayPauseBufferButtonStyles.Buffering Then
PaintNotification(G, B, Bounds.Size, NotificationText)
End If
Select Case _DrawVideoStateButton
Case PlayPauseBufferButtonStyles.Pause
PaintPauseButton(G, B, Bounds.Size)
Case PlayPauseBufferButtonStyles.Buffering
PaintBufferingProgressBar(G, B, Bounds.Size)
Case PlayPauseBufferButtonStyles.Play
End Select
UpdateLayeredForm(B)
End Using
End Using
End Sub
#Region "Form Location"
Private Sub MakeFormFitOnVLCPlayer()
Size = frmMain.pnl_VideoPlayback.Size
Location = frmMain.PointToScreen(frmMain.pnl_VideoPlayback.Location)
End Sub
#End Region
#Region "Subtitle Drawing"
Private Sub DrawSubtitleToSubtitlesForm(G As Graphics, B As Bitmap, SubtitleText As String, TextFont As Font, TextColor As Color, Optional ByVal ShadowColor As Color = Nothing)
Try
If ShadowColor = Nothing Then ShadowColor = Color.Black
Dim TextBounds As Rectangle = Rectangle.Round(B.GetBounds(GraphicsUnit.Pixel))
TextBounds = New Rectangle(TextBounds.X + 10, TextBounds.Y + 5, TextBounds.Width - 20, TextBounds.Height - 35)
Using SF As New StringFormat With {.Alignment = StringAlignment.Center, .LineAlignment = StringAlignment.Far}
Dim originalSize As SizeF = New SizeF(849, 527)
TextFont = AppropriateFont(G, originalSize, ClientRectangle.Size, TextFont) 'Autoscale font
If SubtitleText.Contains("<i>") AndAlso SubtitleText.Contains("</i>") Then
SubtitleText = SubtitleText.Replace("<i>", String.Empty).Replace("</i>", String.Empty)
TextFont = New Font(TextFont.FontFamily.Name, TextFont.Size, FontStyle.Italic)
End If
G.DrawString(SubtitleText, TextFont, New SolidBrush(ShadowColor), TextBounds, SF)
G.DrawString(SubtitleText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(TextBounds.X + 1, TextBounds.Y + 0), TextBounds.Size), SF)
G.DrawString(SubtitleText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(TextBounds.X + 0, TextBounds.Y + 1), TextBounds.Size), SF)
G.DrawString(SubtitleText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(TextBounds.X + 1, TextBounds.Y + 1), TextBounds.Size), SF)
G.DrawString(SubtitleText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(TextBounds.X + 1, TextBounds.Y + 2), TextBounds.Size), SF)
G.DrawString(SubtitleText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(TextBounds.X + 2, TextBounds.Y + 1), TextBounds.Size), SF)
G.DrawString(SubtitleText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(TextBounds.X + 0, TextBounds.Y + 2), TextBounds.Size), SF)
G.DrawString(SubtitleText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(TextBounds.X + 1, TextBounds.Y + 2), TextBounds.Size), SF)
G.DrawString(SubtitleText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(TextBounds.X + 2, TextBounds.Y + 2), TextBounds.Size), SF)
G.DrawString(SubtitleText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(TextBounds.X + 2, TextBounds.Y + 0), TextBounds.Size), SF)
G.DrawString(SubtitleText, TextFont, New SolidBrush(TextColor), New Rectangle(New Point(TextBounds.X + 1, TextBounds.Y + 1), TextBounds.Size), SF)
TextBounds = Nothing
TextFont.Dispose()
End Using
Catch ex As Exception
End Try
End Sub
Private _oldfont As Font = Settings.Data.SubFont
Private Function AppropriateFont(g As Graphics, defaultSize As SizeF, changedSize As SizeF, f As Font) As Font
Dim wRatio As Single = changedSize.Width / defaultSize.Width
Dim hRatio As Single = changedSize.Height / defaultSize.Height
Dim ratio As Single = If((hRatio < wRatio), hRatio, wRatio)
Dim newSize As Single = f.Size * ratio
If newSize = _oldfont.Size Then
Return f
Else
Return New Font(f.FontFamily.Name, newSize, f.Style)
End If
End Function
#End Region
#Region "Cross Drawing"
Private Sub DrawExitButtonToVideo(G As Graphics, B As Bitmap)
If _DrawExitButton AndAlso Not frmHint.Visible Then
If frmMain.FullscreenModeToolStripMenuItem.Checked OrElse frmMain.PictureInPictureToolStripMenuItem.Checked Then
Using crossFont As New Font("Marlett", 16.0F)
Dim R As New Rectangle(New Point(Width - 29, 6), New Size(30, 24))
G.DrawString("r", crossFont, Brushes.White, R) 'Draw a cross
End Using
End If
End If
End Sub
Protected Overrides Sub OnMouseClick(e As MouseEventArgs)
If IsMouseOverCross(e.Location) Then RaiseEvent CrossClicked()
MyBase.OnMouseClick(e)
End Sub
Public Function IsMouseOverCross(mouseLoc As Point) As Boolean
Dim R As New Rectangle(PointToScreen(New Point(Width - 29, 6)), New Size(30, 24))
mouseLoc = PointToScreen(mouseLoc)
If R.Contains(mouseLoc) Then
Return True
Else
Return False
End If
End Function
Private oldMouseLoc As Point = Point.Empty
Public Function IsMouseOverVLC() As Boolean
Dim R As Rectangle = frmMain.Bounds
Dim pcin As New CURSORINFO() With {.cbSize = Marshal.SizeOf(pcin)}
If GetCursorInfo(pcin) Then
Dim mouseLocation As Point = New Point(pcin.ptScreenPos.x, pcin.ptScreenPos.y)
If R.Contains(New Point(pcin.ptScreenPos.x, pcin.ptScreenPos.y)) AndAlso mouseLocation <> oldMouseLoc Then
' Debug.WriteLine("Old:{0} - Current:{1}", oldMouseLoc, mouseLocation)
oldMouseLoc = mouseLocation
Return True
Else
Return False
End If
Else
Return False
End If
End Function
Private Sub tmrExitButtonTimeOut_Tick(sender As Object, e As EventArgs) Handles tmrExitButtonTimeOut.Tick
_DrawExitButton = False
End Sub
#End Region
#Region "Video State Drawing"
Private Sub PaintPlayButton(G As Graphics, B As Bitmap, size As Size)
Dim buttonBounds As New Rectangle(Width / 2 - (size.Width / 2), Height / 2 - (size.Height / 2), size.Width, size.Height)
Dim p1 = New Point(((buttonBounds.Width / 5) * 2) + buttonBounds.X, (buttonBounds.Height / 4) + buttonBounds.Y)
Dim p2 = New Point(((buttonBounds.Width / 5) * 2) + buttonBounds.X, (buttonBounds.Height - (buttonBounds.Height / 4) - 2) + buttonBounds.Y)
Dim p3 = New Point(((buttonBounds.Width / 9) * 6) + buttonBounds.X, ((buttonBounds.Height - 1) / 2) + buttonBounds.Y)
Dim p = {p1, p2, p3}
G.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
G.FillPolygon(Brushes.White, p)
End Sub
Private Sub PaintPauseButton(G As Graphics, B As Bitmap, size As Size)
G.SmoothingMode = Drawing2D.SmoothingMode.None
size = GetProportionalSize(size)
Dim buttonBounds As New Rectangle(Width / 2 - (size.Width / 2), Height / 2 - (size.Height / 2), size.Width, size.Height)
Dim R1 As New Rectangle(((buttonBounds.Width / 7) * 2) + buttonBounds.X, (buttonBounds.Height / 4) + buttonBounds.Y, buttonBounds.Width / 7, (buttonBounds.Height) - 2 * (buttonBounds.Height / 4))
G.FillRectangle(Brushes.White, R1)
Dim R2 As New Rectangle((buttonBounds.Width - ((buttonBounds.Width / 7) * 3)) + buttonBounds.X, (buttonBounds.Height / 4) + buttonBounds.Y, buttonBounds.Width / 7, (buttonBounds.Height) - 2 * (buttonBounds.Height / 4))
G.FillRectangle(Brushes.White, R2)
G.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
End Sub
Dim _Maximum As Integer = 100
Dim Thickness As Single = 3
Dim oldValue As Integer = -1
Private Sub PaintBufferingProgressBar(G As Graphics, B As Bitmap, size As Size)
If _BufferingValue <= _Maximum AndAlso _BufferingValue > 0 Then
size = GetRadialBarProportionalSize(size)
Dim buttonBounds As New Rectangle((Me.Width / 2) - (size.Width / 2), (Me.Height / 2) - (size.Height / 2), size.Width, size.Height)
Dim SF As New StringFormat() With {.Alignment = StringAlignment.Center, .LineAlignment = StringAlignment.Center, .Trimming = StringTrimming.EllipsisCharacter}
Dim BufferingText As String = String.Format("Buffering: {0}%", CInt((100 / _Maximum) * _BufferingValue))
Dim TextFont As New Font("Segoe UI Light", 15)
Dim ShadowColor As Color = Color.Black
Dim Width As Integer = buttonBounds.Width
Dim Height As Integer = buttonBounds.Height
'Enable anti-aliasing to prevent rough edges
G.SmoothingMode = SmoothingMode.HighQuality
'Draw progress
Using P As New Pen(Brushes.White, Thickness)
P.StartCap = LineCap.Round : P.EndCap = LineCap.Round
Try
G.DrawArc(P, CInt(buttonBounds.X + (Thickness / 2)), CInt(buttonBounds.Y + (Thickness / 2)), Width - Thickness - 1, Height - Thickness - 1, -90, CInt((360 / _Maximum) * _BufferingValue))
Catch ex As Exception
End Try
End Using
'Draw progress string
Dim S As SizeF = G.MeasureString(BufferingText, TextFont, buttonBounds.Width)
'Draw round rectangle behind the text
Dim centreRectangle As New Rectangle(buttonBounds.X + (buttonBounds.Width / 2) - ((S.Width + 9) / 2), buttonBounds.Y + (buttonBounds.Height / 2) - ((S.Height + 3) / 2), S.Width + 9, S.Height + 4)
G.FillPath(New SolidBrush(Color.FromArgb(13, 250, 250, 250)), CreateRound(centreRectangle, 5))
G.DrawString(BufferingText, TextFont, New SolidBrush(ShadowColor), buttonBounds, SF)
G.DrawString(BufferingText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 1, buttonBounds.Y + 0), buttonBounds.Size), SF)
G.DrawString(BufferingText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 0, buttonBounds.Y + 1), buttonBounds.Size), SF)
G.DrawString(BufferingText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 1, buttonBounds.Y + 1), buttonBounds.Size), SF)
G.DrawString(BufferingText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 1, buttonBounds.Y + 2), buttonBounds.Size), SF)
G.DrawString(BufferingText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 2, buttonBounds.Y + 1), buttonBounds.Size), SF)
G.DrawString(BufferingText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 0, buttonBounds.Y + 2), buttonBounds.Size), SF)
G.DrawString(BufferingText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 1, buttonBounds.Y + 2), buttonBounds.Size), SF)
G.DrawString(BufferingText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 2, buttonBounds.Y + 2), buttonBounds.Size), SF)
G.DrawString(BufferingText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 2, buttonBounds.Y + 0), buttonBounds.Size), SF)
G.DrawString(BufferingText, TextFont, New SolidBrush(Color.White), New Rectangle(New Point(buttonBounds.X + 1, buttonBounds.Y + 1), buttonBounds.Size), SF)
'oldValue = _BufferingValue
End If
End Sub
Private Sub PaintNotification(G As Graphics, B As Bitmap, size As Size, Text As String)
size = GetRadialBarProportionalSize(size)
Dim buttonBounds As New Rectangle((Me.Width / 2) - (size.Width / 2), (Me.Height / 2) - (size.Height / 2), size.Width, size.Height)
Dim SF As New StringFormat() With {.Alignment = StringAlignment.Center, .LineAlignment = StringAlignment.Center, .Trimming = StringTrimming.EllipsisCharacter}
Dim ErrorText As String = Text
Dim TextFont As New Font("Segoe UI Light", 15)
Dim ShadowColor As Color = Color.Black
Dim Width As Integer = buttonBounds.Width
Dim Height As Integer = buttonBounds.Height
'Enable anti-aliasing to prevent rough edges
G.SmoothingMode = SmoothingMode.HighQuality
'Draw progress string
Dim S As SizeF = G.MeasureString(ErrorText, TextFont, buttonBounds.Width)
'Draw round rectangle behind the text
Dim centreRectangle As New Rectangle(buttonBounds.X + (buttonBounds.Width / 2) - ((S.Width + 9) / 2), buttonBounds.Y + (buttonBounds.Height / 2) - ((S.Height + 3) / 2), S.Width + 9, S.Height + 4)
G.FillPath(New SolidBrush(Color.FromArgb(13, 250, 250, 250)), CreateRound(centreRectangle, 5))
G.DrawString(ErrorText, TextFont, New SolidBrush(ShadowColor), buttonBounds, SF)
G.DrawString(ErrorText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 1, buttonBounds.Y + 0), buttonBounds.Size), SF)
G.DrawString(ErrorText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 0, buttonBounds.Y + 1), buttonBounds.Size), SF)
G.DrawString(ErrorText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 1, buttonBounds.Y + 1), buttonBounds.Size), SF)
G.DrawString(ErrorText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 1, buttonBounds.Y + 2), buttonBounds.Size), SF)
G.DrawString(ErrorText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 2, buttonBounds.Y + 1), buttonBounds.Size), SF)
G.DrawString(ErrorText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 0, buttonBounds.Y + 2), buttonBounds.Size), SF)
G.DrawString(ErrorText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 1, buttonBounds.Y + 2), buttonBounds.Size), SF)
G.DrawString(ErrorText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 2, buttonBounds.Y + 2), buttonBounds.Size), SF)
G.DrawString(ErrorText, TextFont, New SolidBrush(ShadowColor), New Rectangle(New Point(buttonBounds.X + 2, buttonBounds.Y + 0), buttonBounds.Size), SF)
G.DrawString(ErrorText, TextFont, New SolidBrush(Color.White), New Rectangle(New Point(buttonBounds.X + 1, buttonBounds.Y + 1), buttonBounds.Size), SF)
End Sub
#End Region
#Region "Helper Methods"
Private CreateRoundPath As GraphicsPath
Private CreateCreateRoundangle As Rectangle
Function CreateRound(ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal slope As Integer) As GraphicsPath
CreateCreateRoundangle = New Rectangle(x, y, width, height)
Return CreateRound(CreateCreateRoundangle, slope)
End Function
Function CreateRound(ByVal r As Rectangle, ByVal slope As Integer) As GraphicsPath
CreateRoundPath = New GraphicsPath(FillMode.Winding)
slope = slope * 4
CreateRoundPath.AddArc(r.X, r.Y, slope, slope, 180.0F, 90.0F)
CreateRoundPath.AddArc(r.Right - slope, r.Y, slope, slope, 270.0F, 90.0F)
CreateRoundPath.AddArc(r.Right - slope, r.Bottom - slope, slope, slope, 0.0F, 90.0F)
CreateRoundPath.AddArc(r.X, r.Bottom - slope, slope, slope, 90.0F, 90.0F)
CreateRoundPath.CloseFigure()
Return CreateRoundPath
End Function
Private Function GetRadialBarProportionalSize(size As Size) As Size
size = New Size(size.Width * 0.45, size.Height * 0.45)
Dim originalSize As Size = New Size(250, 250)
Dim wRatio As Single = size.Width / originalSize.Width
Dim hRatio As Single = size.Height / originalSize.Height
Dim ratio As Single = If((hRatio < wRatio), hRatio, wRatio)
Dim newSize As Size = New Size(originalSize.Width * ratio, originalSize.Height * ratio)
Return newSize
End Function
Private Function GetProportionalSize(size As Size) As Size
size = New Size(size.Width * 0.6, size.Height * 0.6)
Dim originalSize As Size = New Size(250, 250)
Dim wRatio As Single = size.Width / originalSize.Width
Dim hRatio As Single = size.Height / originalSize.Height
Dim ratio As Single = If((hRatio < wRatio), hRatio, wRatio)
Dim newSize As Size = New Size(originalSize.Width * ratio, originalSize.Height * ratio)
Return newSize
End Function
#End Region
Private Sub DrawLoadingNyanToVideo(G As Graphics, B As Bitmap)
Dim rectangle As New Rectangle(Width / 2 - (Size.Width / 2), Height / 2 - (Size.Height / 2), Size.Width, Size.Height)
G.DrawImage(My.Resources.tumblr_mjphnqLpNy1s5jjtzo1_400, rectangle)
End Sub
End Class |
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
Partial Public NotInheritable Class Route4MeExamples
''' <summary>
''' The example refers to the process of creating an optimization
''' with 10 stops And single-driver option.
''' </summary>
Public Sub SingleDriverRoute10Stops()
' Create the manager with the api key
Dim route4Me As New Route4MeManager(ActualApiKey)
#Region "Prepare the addresses"
'indicate that this is a departure stop
'single depot routes can only have one departure depot
'required coordinates for every departure and stop on the route
'the expected time on site, in seconds. this value is incorporated into the optimization engine
'it also adjusts the estimated and dynamic eta's for a route
'input as many custom fields as needed, custom data is passed through to mobile devices and to the manifest
Dim addresses As Address() = New Address() {New Address() With {
.AddressString = "151 Arbor Way Milledgeville GA 31061",
.IsDepot = True,
.Latitude = 33.132675170898,
.Longitude = -83.244743347168,
.Time = 0,
.CustomFields = New Dictionary(Of String, String)() From {
{"color", "red"},
{"size", "huge"}
}
}, New Address() With {
.AddressString = "230 Arbor Way Milledgeville GA 31061",
.Latitude = 33.129695892334,
.Longitude = -83.24577331543,
.Time = 0
}, New Address() With {
.AddressString = "148 Bass Rd NE Milledgeville GA 31061",
.Latitude = 33.143497,
.Longitude = -83.224487,
.Time = 0
}, New Address() With {
.AddressString = "117 Bill Johnson Rd NE Milledgeville GA 31061",
.Latitude = 33.141784667969,
.Longitude = -83.237518310547,
.Time = 0
}, New Address() With {
.AddressString = "119 Bill Johnson Rd NE Milledgeville GA 31061",
.Latitude = 33.141086578369,
.Longitude = -83.238258361816,
.Time = 0
}, New Address() With {
.AddressString = "131 Bill Johnson Rd NE Milledgeville GA 31061",
.Latitude = 33.142036437988,
.Longitude = -83.238845825195,
.Time = 0
}, New Address() With {
.AddressString = "138 Bill Johnson Rd NE Milledgeville GA 31061",
.Latitude = 33.14307,
.Longitude = -83.239334,
.Time = 0
}, New Address() With {
.AddressString = "139 Bill Johnson Rd NE Milledgeville GA 31061",
.Latitude = 33.142734527588,
.Longitude = -83.237442016602,
.Time = 0
}, New Address() With {
.AddressString = "145 Bill Johnson Rd NE Milledgeville GA 31061",
.Latitude = 33.143871307373,
.Longitude = -83.237342834473,
.Time = 0
}, New Address() With {
.AddressString = "221 Blake Cir Milledgeville GA 31061",
.Latitude = 33.081462860107,
.Longitude = -83.208511352539,
.Time = 0
}}
#End Region
' Set parameters
Dim parameters = New RouteParameters() With {
.AlgorithmType = AlgorithmType.TSP,
.RouteName = "Single Driver Route 10 Stops",
.RouteDate = R4MeUtils.ConvertToUnixTimestamp(DateTime.UtcNow.Date.AddDays(1)),
.RouteTime = 60 * 60 * 7,
.Optimize = Optimize.Distance.GetEnumDescription(),
.DistanceUnit = DistanceUnit.MI.GetEnumDescription(),
.DeviceType = DeviceType.Web.GetEnumDescription()
}
Dim optimizationParameters = New OptimizationParameters() With {
.Addresses = addresses,
.Parameters = parameters
}
' Run the query
Dim errorString As String = Nothing
Dim dataObject As DataObject = route4Me.RunOptimization(optimizationParameters, errorString)
OptimizationsToRemove = New List(Of String)() From {
If(dataObject?.OptimizationProblemId, Nothing)
}
PrintExampleOptimizationResult(dataObject, errorString)
RemoveTestOptimizations()
End Sub
End Class
End Namespace
|
Namespace Infrastructure
Module Ini
Private Declare Function GetPrivateProfileString Lib "Kernel32.Dll" Alias "GetPrivateProfileStringA" _
(ByVal sSection As String,
ByVal sKey As String,
ByVal sDefa As String,
ByVal sRetStr As String,
ByVal iSize As Integer,
ByVal sIniFile As String
) As Integer
Public Function GetValue(ByVal sSection As String, ByVal sKey As String, ByVal sDefault As String, ByVal sIni As String) As String
Dim sb As String = Space(500)
Dim iI As Integer
iI = GetPrivateProfileString(sSection, sKey, sDefault, sb, sb.Length, sIni)
Return Left(sb, iI)
End Function
End Module
End Namespace |
''''
'''Lance Brown
'''Test1
'''6/8/20
'''
' --------------------------------------------------------------------------------
' Options
' --------------------------------------------------------------------------------
Option Strict On
Public Class frmMain
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim strSelect As String = ""
Dim cmdSelect As OleDb.OleDbCommand
Dim drSourceTable As OleDb.OleDbDataReader
Dim dt As DataTable = New DataTable
For Each ctrl As Control In Controls
If TypeOf ctrl Is TextBox Then
ctrl.Text = String.Empty
End If
If TypeOf ctrl Is ComboBox Then
Dim box As ComboBox = CType(ctrl, ComboBox)
If box.Tag Is "input" Then
box.SelectedIndex = -1
End If
End If
Next
If OpenDatabaseConnectionSQLServer() = False Then
MessageBox.Show(Me, "Database connection error." & vbNewLine &
"The application will now close.",
Me.Text + " Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
strSelect = "SELECT intCustomerID, strLastName FROM TCustomers"
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
dt.Load(drSourceTable)
cboCustomers.ValueMember = "intCustomerID"
cboCustomers.DisplayMember = "strLastName"
cboCustomers.DataSource = dt
If cboCustomers.Items.Count > 0 Then cboCustomers.SelectedIndex = 0
drSourceTable.Close()
CloseDatabaseConnection()
Catch excError As Exception
MessageBox.Show(excError.Message)
End Try
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Close()
End Sub
Private Sub btnView_Click(sender As Object, e As EventArgs) Handles btnView.Click
Dim strSelect As String = ""
Dim strName As String = ""
Dim cmdSelect As OleDb.OleDbCommand
Dim drSourceTable As OleDb.OleDbDataReader
Dim dt As DataTable = New DataTable
If OpenDatabaseConnectionSQLServer() = False Then
MessageBox.Show(Me, "Database connection error." & vbNewLine &
"The application will now close.",
Me.Text + " Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
strSelect = "SELECT strFirstName, strLastName, strAddress, strCity, strState, strZip, strLoyaltyCard FROM TCustomers Where intCustomerID = " & cboCustomers.SelectedValue.ToString
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
dt.Load(drSourceTable)
txtFirst.Text = dt.Rows(0).Item(0).ToString
txtLast.Text = dt.Rows(0).Item(1).ToString
txtAddress.Text = dt.Rows(0).Item(2).ToString
txtCity.Text = dt.Rows(0).Item(3).ToString
txtState.Text = dt.Rows(0).Item(4).ToString
txtZip.Text = dt.Rows(0).Item(5).ToString
txtLoyalty.Text = dt.Rows(0).Item(6).ToString
CloseDatabaseConnection()
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim strSelect As String = ""
Dim strFirstName As String = ""
Dim strLastName As String = ""
Dim strAddress As String = ""
Dim strCity As String = ""
Dim strState As String = ""
Dim strZip As String = ""
Dim strLoyalty As String = ""
Dim intRowsAffected As Integer
Dim cmdUpdate As OleDb.OleDbCommand
If Validation() = True Then
If OpenDatabaseConnectionSQLServer() = False Then
MessageBox.Show(Me, "Database connection error." & vbNewLine &
"The application will now close.",
Me.Text + " Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
If Validation() = True Then
strFirstName = txtFirst.Text
strLastName = txtLast.Text
strAddress = txtAddress.Text
strCity = txtCity.Text
strState = txtState.Text
strZip = txtZip.Text
strLoyalty = txtLoyalty.Text
strSelect = "Update TCustomers Set strFirstName = '" & strFirstName & "', " & "strLastName = '" & strLastName &
"', " & "strStreetAddress = '" & strAddress & "', " & "strCity = '" & strCity & "', " &
"strState = '" & strState & "', " & "strZip = '" & strZip & "', " & "strLoyaltyNumber = '" & strLoyalty & "' " & "Where intCustomerID = " & cboCustomers.SelectedValue.ToString
MessageBox.Show(strSelect)
cmdUpdate = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
intRowsAffected = cmdUpdate.ExecuteNonQuery()
If intRowsAffected = 1 Then
MessageBox.Show("Update successful")
Else
MessageBox.Show("Update failed")
End If
CloseDatabaseConnection()
frmMain_Load(sender, e)
End If
End If
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim strDelete As String = ""
Dim strSelect As String = String.Empty
Dim strName As String = ""
Dim intRowsAffected As Integer
Dim cmdDelete As OleDb.OleDbCommand
Dim dt As DataTable = New DataTable
Dim result As DialogResult
If OpenDatabaseConnectionSQLServer() = False Then
MessageBox.Show("Database connection error." & vbNewLine &
"The application will now close.",
Text + " Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Close()
End If
result = MessageBox.Show("Are you sure you want to Delete Customer: Last Name-" & cboCustomers.Text & "?", "Confirm Deletion", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
Select Case result
Case DialogResult.Cancel
MessageBox.Show("Action Canceled")
Case DialogResult.No
MessageBox.Show("Action Canceled")
Case DialogResult.Yes
strDelete = "Delete FROM TCustomers Where intCustomerID = " & cboCustomers.SelectedValue.ToString
cmdDelete = New OleDb.OleDbCommand(strDelete, m_conAdministrator)
intRowsAffected = cmdDelete.ExecuteNonQuery()
If intRowsAffected > 0 Then
MessageBox.Show("Delete successful")
End If
End Select
CloseDatabaseConnection()
frmMain_Load(sender, e)
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim AddCustomer As New frmAddCustomer
AddCustomer.ShowDialog()
frmMain_Load(sender, e)
End Sub
Public Function Validation() As Boolean
For Each ctrl As Control In Controls
If TypeOf ctrl Is TextBox Then
ctrl.BackColor = Color.White
If ctrl.Text = String.Empty Then
ctrl.BackColor = Color.HotPink
ctrl.Focus()
Return False
End If
End If
Next
Return True
End Function
End Class
|
''' <summary>
''' A page that allows a user to edit or delete an address within his online resume
''' </summary>
''' <remarks>
''' Completed: 08/23/2007
''' Author: Bill Hedge
''' Modifications: None
''' </remarks>
Public Class EditAddress
Inherits System.Web.UI.Page
#Region "Private Members"
Private _ID As Long = 0
#End Region
#Region "Protected Sub-Routines"
Protected Sub Page_Load(ByVal s As Object, ByVal E As EventArgs)
If User.Identity.IsAuthenticated Then
Master.WebLoginID = CType(User.Identity.Name, Long)
Master.PageTitleText = "Edit Address"
End If
lblReturnUrl.Text = "detail.aspx"
Try
_ID = CType(Request.QueryString("id"), Long)
Catch ex As Exception
_ID = 0
End Try
If _ID > 0 Then
Dim add As New BridgesInterface.ResumeAddressRecord(System.Configuration.ConfigurationManager.AppSettings("DBCnn"))
Dim wbl As New BridgesInterface.WebLoginRecord(add.ConnectionString)
wbl.Load(Master.WebLoginID)
add.Load(_ID)
If add.ResumeID = CType(wbl.Login, Long) Then
If Not IsPostBack Then
LoadResumeAddress()
End If
Else
divForm.Visible = False
Response.Redirect(lblReturnUrl.Text, True)
End If
Else
divForm.Visible = False
Response.Redirect(lblReturnUrl.Text, True)
End If
End Sub
#End Region
#Region "Private Sub-Routines"
Private Sub LoadResumeAddress()
Dim rad As New BridgesInterface.ResumeAddressRecord(System.Configuration.ConfigurationManager.AppSettings("DBCnn"))
rad.Load(_ID)
addAddress.AddressTypeID = rad.AddressTypeID
addAddress.Street = rad.Street
addAddress.Extended = rad.Extended
addAddress.City = rad.City
addAddress.StateID = rad.StateID
addAddress.Zip = rad.ZipCode
End Sub
Private Sub SaveResumeAddress()
Dim rad As New BridgesInterface.ResumeAddressRecord(System.Configuration.ConfigurationManager.AppSettings("DBCnn"))
Dim strChangeLog As String = ""
rad.Load(_ID)
rad.Street = addAddress.Street
rad.Extended = addAddress.Extended
rad.City = addAddress.City
rad.StateID = addAddress.StateID
rad.ZipCode = addAddress.Zip
rad.AddressTypeID = addAddress.AddressTypeID
rad.Active = Not chkRemove.Checked
rad.Save(strChangeLog)
Dim act As New BridgesInterface.ActionRecord(System.Configuration.ConfigurationManager.AppSettings("DBCnn"))
act.Add(Master.UserID, "web", "web", "web", "web", 24, rad.ResumeAddressID, strChangeLog)
End Sub
#End Region
#Region "Private Functions"
Private Function IsAddressComplete() As Boolean
Dim blnReturn As Boolean = True
Dim zip As New BridgesInterface.ZipCodeRecord(System.Configuration.ConfigurationManager.AppSettings("DBCnn"))
Dim strErrors As String = ""
If addAddress.AddressTypeID <= 0 Then
blnReturn = False
strErrors &= "<li>Address Type is Required</li>"
End If
If addAddress.Street.Trim.Length = 0 Then
blnReturn = False
strErrors &= "<li>Street is Required</li>"
End If
If addAddress.City.Trim.Length = 0 Then
blnReturn = False
strErrors &= "<li>City is Required</li>"
End If
If addAddress.StateID <= 0 Then
blnReturn = False
strErrors &= "<li>State is Required</li>"
End If
If addAddress.Zip.Trim.Length = 0 Then
blnReturn = False
strErrors &= "<li>Zip Code is Required</li>"
Else
zip.Load(addAddress.Zip.Trim)
If zip.ZipCodeID <= 0 Then
blnReturn = False
strErrors &= "<li>Zip Code is Invalid</li>"
End If
End If
divError.InnerHtml = "<ul>" & strErrors & "</ul>"
Return blnReturn
End Function
#End Region
#Region "Event Handlers"
Protected Sub btnCancel_Click(ByVal S As Object, ByVal E As EventArgs)
Response.Redirect(lblReturnUrl.Text, True)
End Sub
Protected Sub btnSubmit_Click(ByVal S As Object, ByVal E As EventArgs)
If IsAddressComplete() Then
divError.Visible = False
SaveResumeAddress()
Response.Redirect(lblReturnUrl.Text, True)
Else
divError.Visible = True
End If
End Sub
#End Region
End Class |
Option Strict On
Imports System.IO
Public Class frmTextEditor
Private Sub OpenToolStripMenuItem_Click_1(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
Dim OpenFileDialog1 = New OpenFileDialog()
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
Try
Me.Text = "Title"
Dim Reader As New StreamReader(OpenFileDialog1.FileName)
txtText.Text = Reader.ReadToEnd
Reader.Close()
Catch ex As Exception
Throw New ApplicationException(ex.ToString)
End Try
End If
End Sub
Private Sub mnuSaveAs_Click(sender As Object, e As EventArgs) Handles mnuSaveAs.Click
Dim SaveFileDialog1 = New SaveFileDialog
SaveFileDialog1.Filter = "TXT Files (*.txt)|.txt"
If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
My.Computer.FileSystem.WriteAllText(txtText.Text, SaveFileDialog1.FileName, False)
End If
End Sub
Private Sub mnuClose_Click(sender As Object, e As EventArgs) Handles mnuClose.Click
Application.Exit()
End Sub
Private Sub mnuSave_Click(sender As Object, e As EventArgs) Handles mnuSave.Click
Dim OpenFileDialog1 = New OpenFileDialog()
Dim Save As New SaveFileDialog
Dim myWriter As System.IO.StreamWriter
Save.Filter = "Text (*.txt)|*.txt|HTML (*.html*)|*.html|PHP (*.php*)|*.php*|All Files (*.*)|*>*"
Save.CheckPathExists = True
Save.Title = "Save File"
Save.ShowDialog(Me)
Try
myWriter = System.IO.File.AppendText(Save.FileName)
myWriter.Write(txtText.Text)
myWriter.Flush()
myWriter.Close()
Catch ex As Exception
Throw ex
End Try
'* The line of code below wasnt working im my code dont really know why
''My.Computer.FileSystem.WriteAllText(OpenFileDialog1.FileName, txtText.Text, False)
End Sub
Private Sub mnuCopy_Click(sender As Object, e As EventArgs) Handles mnuCopy.Click
txtText.Copy()
End Sub
Private Sub mnuCut_Click(sender As Object, e As EventArgs) Handles mnuCut.Click
txtText.Cut()
End Sub
Private Sub mnuPaste_Click(sender As Object, e As EventArgs) Handles mnuPaste.Click
txtText.Paste()
End Sub
Private Sub mnuNew_Click(sender As Object, e As EventArgs) Handles mnuNew.Click
txtText.Clear()
End Sub
End Class
|
'Thief Fan Mission Manager is released under the GPL 3.0 license.
'The licence text can be viewed in the gpl-3.0.txt file or at
'http://www.gnu.org/licenses/gpl.html
Imports System.Windows.Forms
Imports System.Data
Imports System.IO
Imports Thief_Fan_Mission_Manager.MyAppSettings
Public Class dlgSetup
Private Const DefaultMissionTitleRegex As String = ""
Private Const DefaultAuthorNameRegex As String = ""
Private Const DefaultTextFileExtensions As String = "txt,htm,html,glml,wri,rtf"
Private Sub dlgSetup_Load(sender As Object, e As EventArgs) Handles Me.Load
lvGameExe.ListViewItemSorter = New ListViewColumnSorter With {.Order = SortOrder.Ascending, .SortColumn = 0}
lvInstallPath.ListViewItemSorter = New ListViewColumnSorter With {.Order = SortOrder.Ascending, .SortColumn = 0}
LoadSettings()
End Sub
Private Sub btnAddDir_Click(sender As Object, e As EventArgs) Handles btnAddDir.Click
With New FolderBrowserDialog
.Description = "Select Fan Mission Folder"
If Not .ShowDialog = Windows.Forms.DialogResult.OK Then Exit Sub
If Not lstFMDirs.Items.Contains(.SelectedPath) Then lstFMDirs.Items.Add(.SelectedPath)
End With
End Sub
Private Sub btnMultiAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnMultiAdd.Click
With New dlgMultiFolderSelect(My.Application.Info.DirectoryPath)
If .ShowDialog <> Windows.Forms.DialogResult.OK Then Exit Sub
For Each s As String In .SelectedFolders
If Not lstFMDirs.Items.Contains(s) Then lstFMDirs.Items.Add(s)
Next
End With
End Sub
Private Sub btnRemoveDir_Click(sender As Object, e As EventArgs) Handles btnRemoveDir.Click
If lstFMDirs.SelectedItems.Count = 0 Then Exit Sub
lstFMDirs.Items.RemoveAt(lstFMDirs.SelectedIndex)
End Sub
Private Sub btnLocateGameExe_Click(sender As Object, e As EventArgs) Handles btnSS2.Click, btnSS2D.Click, btnT1.Click, btnT1D.Click, btnT2.Click, btnT2D.Click, btnT3.Click, btnDM.Click
Dim exePath As String = ""
Dim installPath As String = ""
With New OpenFileDialog
.Filter = "Executables|*.exe"
Select Case sender.text
Case "SS2"
.Title = "Select executable to launch for System Shock 2 Missions."
Case "SS2D"
.Title = "Select executable to launch for System Shock 2 Dromed Only Missions."
Case "T1"
.Title = "Select executable to launch for Thief 1/Gold Missions."
Case "T1D"
.Title = "Select executable to launch for Thief 1/Gold Dromed Only Missions."
Case "T2"
.Title = "Select executable to launch for Thief 2 Missions."
Case "T2D"
.Title = "Select executable to launch for Thief 2 Dromed Only Missions."
Case "T3"
.Title = "Select executable to launch for Thief 3 Missions."
Case "DM"
.Title = "Select executable to launch for Dark Mod Missions."
End Select
If Not .ShowDialog = Windows.Forms.DialogResult.OK Then Exit Sub
exePath = .FileName
End With
Select Case sender.text
Case "SS2", "T1", "T2"
installPath = ReadCamModIni(exePath)
Case "T3"
installPath = ReadSneakyOptions(exePath)
Case "TDM"
End Select
AddItemToListView(lvGameExe, sender.text.ToString, exePath)
If installPath <> "" Then AddItemToListView(lvInstallPath, sender.text.ToString, installPath)
End Sub
Private Sub AddItemToListView(ByRef lv As ListView, ByVal key As String, ByVal value As String)
For i As Integer = lv.Items.Count - 1 To 0 Step -1
If lv.Items.Item(i).Text = key Then lv.Items.RemoveAt(i)
Next
Dim itm As New ListViewItem(key)
Select Case key
Case "DM" : itm.ImageIndex = 0
Case "SS2", "SS2D" : itm.ImageIndex = 1
Case "T1", "T1D" : itm.ImageIndex = 2
Case "T2", "T2D" : itm.ImageIndex = 3
Case "T3" : itm.ImageIndex = 4
End Select
itm.SubItems.Add(value)
lv.Items.Add(itm)
For Each ch As ColumnHeader In lv.Columns
ch.Width = -2
Next
lv.Sort()
End Sub
Private Sub btnLocateInstallFolder_Click(sender As Object, e As EventArgs) Handles btnSS2InstallLocation.Click, btnSS2DInstallLocation.Click, btnT1InstallLocation.Click, btnT1DInstallLocation.Click, btnT2InstallLocation.Click, btnT2DInstallLocation.Click, btnT3InstallLocation.Click, btnDMInstallLocation.Click
With New FolderBrowserDialog
Select Case sender.text
Case "SS2"
.Description = "Select install location for System Shock 2 Missions."
Case "SS2D"
.Description = "Select install location for System Shock 2 Dromed Only Missions."
Case "T1"
.Description = "Select install location for Thief 1/Gold Missions."
Case "T1D"
.Description = "Select install location for Thief 1/Gold Dromed Only Missions."
Case "T2"
.Description = "Select install location for Thief 2 Missions."
Case "T2D"
.Description = "Select install location for Thief 2 Dromed Only Missions."
Case "T3"
.Description = "Select install location for Thief 3 Missions."
Case "DM"
.Description = "Select install location for Dark Mod Missions."
End Select
If Not .ShowDialog = Windows.Forms.DialogResult.OK Then Exit Sub
AddItemToListView(lvInstallPath, sender.text.ToString, .SelectedPath)
End With
End Sub
Private Sub btnClearAllSettings_Click(sender As Object, e As EventArgs) Handles btnClearAllSettings.Click
If MsgBox("Are you sure?", MsgBoxStyle.OkCancel, "Clear all settings") = MsgBoxResult.Cancel Then Exit Sub
ClearControl(Me)
End Sub
Private Sub ClearControl(ByVal ctl As Control)
If ctl.HasChildren Then
For Each c As Control In ctl.Controls
ClearControl(c)
Next
Else
If ctl.GetType.ToString.Contains("ListView") Then DirectCast(ctl, ListView).Items.Clear()
If ctl.GetType.ToString.Contains("ListBox") Then DirectCast(ctl, ListBox).Items.Clear()
If ctl.GetType.ToString.Contains("TextBox") Then DirectCast(ctl, TextBox).Clear()
End If
txtAuthorNameRegex.Text = DefaultAuthorNameRegex
txtMissionTitleRegex.Text = DefaultMissionTitleRegex
txtTextFileExtensions.Text = DefaultTextFileExtensions
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim ht As New Hashtable
For Each lvi As ListViewItem In lvGameExe.Items
ht.Add(lvi.Text, lvi.SubItems(1).Text)
Next
MySettings.hashtblSetting("GameExes") = ht
ht = New Hashtable
For Each lvi As ListViewItem In lvInstallPath.Items
ht.Add(lvi.Text, lvi.SubItems(1).Text)
Next
MySettings.hashtblSetting("InstallPath") = ht
Dim al As New ArrayList
For Each itm As String In lstFMDirs.Items
al.Add(itm)
Next
MySettings.arylstSetting("FMDirs") = al
'MySettings.strSetting("TextFileExts") = txtFileExts.Text
MySettings.arylstSetting("TextFileExts") = New ArrayList(txtTextFileExtensions.Text.ToLower.Split(","))
MySettings.strSetting("AuthorNameRegex") = txtAuthorNameRegex.Text
MySettings.strSetting("MissionTitleRegex") = txtMissionTitleRegex.Text
MySettings.Save()
Me.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Close()
End Sub
Private Sub LoadSettings()
Dim ht As Hashtable = MySettings.hashtblSetting("GameExes")
If ht IsNot Nothing Then
For Each key As String In ht.Keys
AddItemToListView(lvGameExe, key, ht.Item(key))
Next
End If
ht = MySettings.hashtblSetting("InstallPath")
If ht IsNot Nothing Then
For Each key As String In ht.Keys
AddItemToListView(lvInstallPath, key, ht.Item(key))
Next
End If
Dim al As ArrayList = MySettings.arylstSetting("FMDirs")
For Each s As String In al
lstFMDirs.Items.Add(s)
Next
'If mySettings.strSetting("TextFileExts") <> "" Then txtFileExts.Text = mySettings.strSetting("TextFileExts")
al = MySettings.arylstSetting("TextFileExts")
If al IsNot Nothing Then txtTextFileExtensions.Text = String.Join(",", al.ToArray(GetType(String)))
If txtTextFileExtensions.Text = "" Then txtTextFileExtensions.Text = DefaultTextFileExtensions
txtAuthorNameRegex.Text = MySettings.strSetting("AuthorNameRegex")
If txtAuthorNameRegex.Text = "" Then txtAuthorNameRegex.Text = DefaultAuthorNameRegex
txtMissionTitleRegex.Text = MySettings.strSetting("MissionTitleRegex")
If txtMissionTitleRegex.Text = "" Then txtMissionTitleRegex.Text = DefaultMissionTitleRegex
End Sub
Private Sub btnRemoveGameExe_Click(sender As Object, e As EventArgs) Handles btnRemoveGameExe.Click
If lvGameExe.SelectedItems.Count = 1 Then
lvGameExe.Items.RemoveAt(lvGameExe.SelectedItems(0).Index)
End If
End Sub
Private Sub btnDeleteInstallLocation_Click(sender As Object, e As EventArgs) Handles btnDeleteInstallLocation.Click
If lvInstallPath.SelectedItems.Count = 1 Then
lvInstallPath.Items.RemoveAt(lvInstallPath.SelectedItems(0).Index)
End If
End Sub
End Class
|
Module Module1
Sub Main()
Dim choice As String
Dim choosing As Boolean
choosing = True
Do While choosing = True
Console.Write("Which Challenge: ")
choice = Console.ReadLine()
If choice = "" Then choosing = False
If choice = "1" Then Challenge1()
If choice = "2" Then Challenge2()
If choice = "3" Then challenge3()
If choice = "4" Then Challenge4()
If choice = "5" Then Challenge5()
If choice = "6" Then Challenge6()
If choice = "7" Then challenge7()
Loop
End Sub
Sub Challenge1()
Dim input As Integer
Dim choosing As Boolean
choosing = True
Console.WriteLine("1. Play Game ")
Console.WriteLine("2. Instructions ")
Console.WriteLine("3. Quit")
Do While choosing = True
Console.Write("Choose: ")
input = Console.ReadLine()
If input = 1 Or input = 2 Or input = 3 Then
choosing = False
Else
Console.WriteLine("That is not a valid input ")
End If
Loop
Console.WriteLine("Valid option chosen ")
Console.ReadLine()
End Sub
Sub Challenge2()
Dim current, target, year As Integer
Console.Write("What is your current ballence: ")
current = Console.ReadLine()
Console.Write("What is your target ballence: ")
target = Console.ReadLine()
year = 0
Do While current < target
current = current * 1.04
year = year + 1
Console.WriteLine("Year " & year & ", £" & current)
Loop
End Sub
Sub challenge3()
Dim rN, guess As Integer
Dim playing As Boolean
Randomize()
rN = Rnd() * 100
playing = True
Do While playing = True
Console.Write("Guess: ")
guess = Console.ReadLine()
If guess = rN Then
Console.WriteLine("That's the correct number!! ")
playing = False
ElseIf guess < rN Then
Console.WriteLine("That's too low ")
ElseIf guess > rN Then
Console.WriteLine("That's too high ")
End If
Loop
End Sub
Sub Challenge4()
Dim gamertag As String
Dim choosing As Boolean
Console.WriteLine("Gamertag must not be longer than 15 characters")
choosing = True
Do While choosing = True
Console.Write("Gamertag: ")
gamertag = Console.ReadLine()
If gamertag.Length() > 15 Then Console.WriteLine("That is too long")
If gamertag.Length() < 16 Then choosing = False
Loop
Console.Write("Valid tag entered ")
End Sub
Sub Challenge5()
Dim userChoice As String
Dim rN, compScore, userScore As Integer
Dim playing As Boolean
Randomize()
playing = True
compScore = 0
userScore = 0
Do While playing = True
Console.Write("Rock, Paper, or Scissors: ")
userChoice = UCase(Left(Console.ReadLine(), 1))
rN = Rnd() * 3
'rock = 0, paper = 1, scissors = 2
If userChoice = "R" And rN = 2 Then
Console.WriteLine("You win")
userScore = userScore + 1
ElseIf userChoice = "P" And rN = 0 Then
Console.WriteLine("You win")
userScore = userScore + 1
ElseIf userChoice = "S" And rN = 2 Then
Console.WriteLine("You win")
userScore = userScore + 1
ElseIf userChoice = "R" And rN = 1 Then
Console.WriteLine("You loose")
compScore = compScore + 1
ElseIf userChoice = "P" And rN = 2 Then
Console.WriteLine("You loose")
compScore = compScore + 1
ElseIf userChoice = "S" And rN = 0 Then
Console.WriteLine("You loose")
compScore = compScore + 1
Else
Console.WriteLine("It was a tie")
End If
If userScore = 10 Then
Console.WriteLine("You win!!")
playing = False
ElseIf compScore = 10 Then
Console.WriteLine("You loose :(")
playing = False
End If
Console.WriteLine("Your score: " & userScore & " Computer score: " & compScore)
Loop
Console.Read()
End Sub
Sub Challenge6()
Dim number As String
Dim addition, four As Integer
Dim checking As Boolean
Console.Write("Number: ")
number = Console.ReadLine()
checking = True
four = 0
Do While checking = True
Dim unit(number.Length() - 1)
Dim newNumber(number.Length() - 1)
addition = 0
For i = 0 To number.Length() - 1
unit(i) = CInt(Mid(number, i + 1, 1))
newNumber(i) = unit(i) * unit(i)
Next
For i = 0 To newNumber.Count() - 1
addition = addition + newNumber(i)
Next
Console.WriteLine(addition)
If addition = 1 Then
checking = False
Console.WriteLine("That is a happy number")
ElseIf addition = 4 Then
If four = 0 Then
four = 1
Else
checking = False
Console.WriteLine("That is not a happpy number")
End If
End If
number = CStr(addition)
Loop
Console.Read()
End Sub
Sub challenge7()
Dim rank, xp, newxp, xpRequired As Integer
Dim ranks(4) As String
ranks(0) = "Private"
ranks(1) = "Corporal"
ranks(2) = "Seargent"
ranks(3) = "Staff Seargent"
ranks(4) = "Warrent Officer"
rank = 1
xp = 0
xpRequired = 100
Do While rank < 5
Console.WriteLine("You are rank: " & ranks(rank - 1))
Console.Write("XP gained: ")
newxp = Console.ReadLine()
xp = xp + newxp
If xp > xpRequired - 1 Then
xp = xp - xpRequired
xpRequired = (xpRequired * 2) + 100
rank = rank + 1
End If
Loop
Console.Read()
End Sub
End Module
|
Namespace Core
Public Partial Class Instance
#Region " Public Shared Methods "
Public Shared Function Create_Instance( _
ByVal _db As System.Data.IDbConnection, _
ByVal _option As [Option] _
) As Instance
' -- Create New Instance --
Dim new_Instance As New Instance()
new_Instance.Option = _option.Id
new_Instance.Code = Exercise.Generate_Code(_db, ObjectType.Instance)
If Not Instance.All.Set(_db, new_Instance) Then _
Return Nothing
'' -------------------------
Return new_Instance
End Function
#End Region
End Class
End Namespace |
Public Class MainForm
Private Sub Btn_Exit_Click(sender As Object, e As EventArgs) Handles Btn_Exit.Click
' Close this form
Me.Close()
End Sub
Private Sub btn_Reset_Click(sender As Object, e As EventArgs) Handles btn_Reset.Click
' Clear this Form of all data
For Each c In gb_Registation.Controls
'Check to see if control is a text box
If TypeOf c Is TextBox Then
'Clear the text
DirectCast(c, TextBox).Text = String.Empty
End If
Next
'Clear Total TextBox
tb_Total.Text = String.Empty
' Reset All Labels to Default ForeColor
SetLabelTextToDefaultColor()
End Sub
Private Sub btn_SelectConference_Click(sender As Object, e As EventArgs) Handles btn_SelectConference.Click
' Create an Instance of the Conference Option Form
Dim frmConfOptions As New ConfOptionsForm
If Not CheckTextBoxes() Then
' Display Conference Option Form in modal
frmConfOptions.ShowDialog()
' Dispose of Conferene Form
frmConfOptions.Dispose()
' Show Confernce Total on Main Form
tb_Total.Text = intTotalRegistrationFee.ToString("c")
End If
End Sub
' Check for Empty TextBoxes and throw an Error Message
' Returns false if no empty Text Boxes Found or True if empty TExt Boxes Found
Private Function CheckTextBoxes() As Boolean
' Flag if an Empty Text Box is found
Dim emptyTextBoxFound As Boolean = False
' Variable for label Name
Dim labelName As String
' Reset all Labels to Default ForeColor
SetLabelTextToDefaultColor()
' Check All Controls on
For Each c In gb_Registation.Controls
' Check to see if control is a Text Box
If TypeOf c Is TextBox Then
' Check to see if Text Box is Null or WhiteSpaces
If String.IsNullOrWhiteSpace(DirectCast(c, TextBox).Text) Then
' Set Flag to True
emptyTextBoxFound = True
' Retrieve the unique substring of Textbox Name ie tb_Unique
' retrieves the Unique and appends it to labelName
labelName = "lbl_" + DirectCast(c, TextBox).Name.Substring(3)
' Find the Label for Empty Text Box
For Each l In gb_Registation.Controls
' Check to see if control is a Label
If TypeOf l Is Label Then
' Check to see if Label is for Text Box
If DirectCast(l, Label).Name = labelName Then
' Change Text Color to Red
DirectCast(l, Label).ForeColor = Color.Red
' Leave Label For Loop
Exit For
End If
End If
Next
End If
End If
Next
'Check to see if Flag is true
If emptyTextBoxFound Then
' Display an Error Message
MessageBox.Show("All Fields must be filled", "Entry Error")
'Set Focus to First Field
tb_Name.Focus()
End If
Return emptyTextBoxFound
End Function
Private Sub SetLabelTextToDefaultColor()
' Find All Label in Form
For Each l In gb_Registation.Controls
If TypeOf l Is Label Then
' Set Text Color to Default
DirectCast(l, Label).ForeColor = Label.DefaultForeColor
End If
Next
End Sub
End Class
|
Imports Microsoft.VisualBasic
<Serializable()> _
Public Class ShoppingCart
Private PID As String
Private CompanyProductName As String
Private Number As Integer
Private Price As Decimal
Private DateAdded As DateTime
Public Property ProductID() As String
Get
Return PID
End Get
Set(ByVal value As String)
PID = value
End Set
End Property
Public Property ProductName() As String
Get
Return CompanyProductName
End Get
Set(ByVal value As String)
CompanyProductName = value
End Set
End Property
Public Property NumberSelected() As Integer
Get
Return Number
End Get
Set(ByVal value As Integer)
Number = value
End Set
End Property
Public Property ItemPrice() As Decimal
Get
Return Price
End Get
Set(ByVal value As Decimal)
Price = value
End Set
End Property
Public Property DateItemAdded() As DateTime
Get
Return DateAdded
End Get
Set(ByVal value As DateTime)
DateAdded = value
End Set
End Property
End Class
|
'==============================================================================
'Project: Lab 2
'Title: Yahtzee
'File Name: Yahtzee.sln, .exe
'Date Completed: 12/2/2018
'
'Author: Van Quach, Margaret Alcock, Dylan E Parker, Tyler R Little
'Course: CS 115, Section C
'
'Description: This program is a dice game called Yahtzee. There are five
' dice that can be rolled to get different combinations.
' Then, the user can pick which type of combination they want
' to score by choosing the program's buttons.
'
' The user can choose how many players they want to play by
' typing the number of player in the input box appearing at
' the beginning of the game. Then, the user can type the name
' of each player in the input box.
'
' There are 13 rounds in the game. There are labels near the
' top right corner of the game indicating how many rounds
' are left.
'
' Each turn starts with a roll of all five dice. Then the
' player decices how many of the dice to roll again, if any.
' The player has up to three rolls of the dice including the
' first roll. The player can decide to roll up to five dice
' for any of the rolls. The player can roll by clicking the
' Roll button and can change which dice are being held from
' roll to roll by clicking the check boxes under every dice.
' However, after the third roll of every round, the player
' must pick a combination to be scored even if this choice
' yields a zero score on that combination.
'
' Below the bottm of the game is the label showing name and
' total score of each player.
'
' There are the tool tip that can help the player to know
' the function of each button.
'
' At the bottom of the game, there is a status bar indicating
' the player's turn.
'
' At the top of the game, there is the menu bar containing
' some functions such as saving, loading, starting a new game,
' terminating the game, showing recent high scores. There is
' a How to play menu showing the game's rules and a About
' menu giving the information about the people who made the
' program.
'==============================================================================
'Known Bugs:
'==============================================================================
Option Explicit On
Option Strict On
Imports System.IO
'------------------------------------------------------------------------------
'Description: Declaring class variables and arrays.
'------------------------------------------------------------------------------
Public Class Yahtzee
Dim cshtDiceVal(4) As Short
Dim cchkHold(4) As CheckBox
Dim cpicDie(4) As PictureBox
Dim clblAces(5) As Label
Dim clblTwos(5) As Label
Dim clblThrees(5) As Label
Dim clblFours(5) As Label
Dim clblFives(5) As Label
Dim clblSixes(5) As Label
Dim clblTotalScore(5) As Label
Dim clblBonus(5) As Label
Dim clblTotalOfUpperSection(5) As Label
Dim clbl3OfAKind(5) As Label
Dim clbl4OfAKind(5) As Label
Dim clblFullHouse(5) As Label
Dim clblSmallStraight(5) As Label
Dim clblLargeStraight(5) As Label
Dim clblYahtzee(5) As Label
Dim clblChance(5) As Label
Dim clblYahtzeeBonus(5) As Label
Dim clblTotalOfLowerSection(5) As Label
Dim clblTotal(5) As Label
Dim cshtPlayerScores(5, 18) As Short '2d array to hold all player scores
Dim cstrPlayerNames(5) As String
Dim cblnYahtzee(5) As Boolean
Dim cshtNumPlayers As Short
Dim clblPlayersU(5) As Label
Dim clblPlayersL(5) As Label
Dim clblPlayersT(5) As Label
Dim cshtCurrentPlayer As Short 'for tracking/iterating current player
Dim cshtRolls As Short 'tracks which dice roll the player is on
Dim cshtTurn As Short 'tracks current turn
'--------------------------------------------------------------------------
'Description: Set up check boxes, picture boxes and player scores arrays
' for dice.
'--------------------------------------------------------------------------
Private Sub Yahtzee_Load(sender As Object,
e As EventArgs) Handles MyBase.Load
'set up check boxes and picture boxes arrays for dice.
Dim i As Short
Dim j As Short
cshtNumPlayers = 6
Randomize()
'set up arrays for check boxes and picture boxes
For i = 0 To 4
cchkHold(i) = New CheckBox
Me.Controls.Add(cchkHold(i))
cchkHold(i).Width = 75
cchkHold(i).Height = 25
cchkHold(i).Top = 120
cchkHold(i).Left = i * cchkHold(i).Width + 375
cchkHold(i).Text = "Hold"
cpicDie(i) = New PictureBox
Me.Controls.Add(cpicDie(i))
cpicDie(i).Width = 75
cpicDie(i).Height = cpicDie(i).Width
cpicDie(i).Top = 45
cpicDie(i).Left = i * cpicDie(i).Width + 375
cpicDie(i).BackgroundImage = Image.FromFile("..\Images\redDie0.png")
cpicDie(i).BackgroundImageLayout = ImageLayout.Zoom
Next i
'set up arrays for player scores
For j = 0 To 5
clblPlayersU(j) = New Label
Me.Controls.Add(clblPlayersU(j))
clblPlayersU(j).Width = 75
clblPlayersU(j).Height = 25
clblPlayersU(j).Top = 171
clblPlayersU(j).Left = j * clblPlayersU(j).Width + 120 + j * 6
clblPlayersU(j).BackColor = Color.Pink
clblPlayersU(j).Text = ""
clblPlayersL(j) = New Label
Me.Controls.Add(clblPlayersL(j))
clblPlayersL(j).Width = 75
clblPlayersL(j).Height = 25
clblPlayersL(j).Top = 171
clblPlayersL(j).Left = j * clblPlayersL(j).Width + 758 + j * 6
clblPlayersL(j).BackColor = Color.Pink
clblPlayersL(j).Text = ""
clblPlayersT(j) = New Label
Me.Controls.Add(clblPlayersT(j))
clblPlayersT(j).Width = 75
clblPlayersT(j).Height = 35
clblPlayersT(j).Top = 556
clblPlayersT(j).Left = j * clblPlayersT(j).Width + 26 + j * 135
clblPlayersT(j).BackColor = Color.Pink
clblPlayersT(j).Text = ""
clblAces(j) = New Label
grpUpperSection.Controls.Add(clblAces(j))
clblAces(j).Width = 75
clblAces(j).Height = 25
clblAces(j).Top = 22
clblAces(j).Left = j * clblAces(j).Width + 107 + j * 6
clblAces(j).BackColor = Color.Pink
clblAces(j).Text = ""
clblTwos(j) = New Label
grpUpperSection.Controls.Add(clblTwos(j))
clblTwos(j).Width = 75
clblTwos(j).Height = 25
clblTwos(j).Top = 51
clblTwos(j).Left = j * clblTwos(j).Width + 107 + j * 6
clblTwos(j).BackColor = Color.Pink
clblTwos(j).Text = ""
clblThrees(j) = New Label
grpUpperSection.Controls.Add(clblThrees(j))
clblThrees(j).Width = 75
clblThrees(j).Height = 25
clblThrees(j).Top = 80
clblThrees(j).Left = j * clblThrees(j).Width + 107 + j * 6
clblThrees(j).BackColor = Color.Pink
clblThrees(j).Text = ""
clblFours(j) = New Label
grpUpperSection.Controls.Add(clblFours(j))
clblFours(j).Width = 75
clblFours(j).Height = 25
clblFours(j).Top = 109
clblFours(j).Left = j * clblFours(j).Width + 107 + j * 6
clblFours(j).BackColor = Color.Pink
clblFours(j).Text = ""
clblFives(j) = New Label
grpUpperSection.Controls.Add(clblFives(j))
clblFives(j).Width = 75
clblFives(j).Height = 25
clblFives(j).Top = 138
clblFives(j).Left = j * clblFives(j).Width + 107 + j * 6
clblFives(j).BackColor = Color.Pink
clblFives(j).Text = ""
clblSixes(j) = New Label
grpUpperSection.Controls.Add(clblSixes(j))
clblSixes(j).Width = 75
clblSixes(j).Height = 25
clblSixes(j).Top = 167
clblSixes(j).Left = j * clblSixes(j).Width + 107 + j * 6
clblSixes(j).BackColor = Color.Pink
clblSixes(j).Text = ""
clblTotalScore(j) = New Label
grpUpperSection.Controls.Add(clblTotalScore(j))
clblTotalScore(j).Width = 75
clblTotalScore(j).Height = 25
clblTotalScore(j).Top = 195
clblTotalScore(j).Left = j * clblTotalScore(j).Width + 107 + j * 6
clblTotalScore(j).BackColor = Color.Pink
clblTotalScore(j).Text = ""
clblBonus(j) = New Label
grpUpperSection.Controls.Add(clblBonus(j))
clblBonus(j).Width = 75
clblBonus(j).Height = 25
clblBonus(j).Top = 233
clblBonus(j).Left = j * clblBonus(j).Width + 107 + j * 6
clblBonus(j).BackColor = Color.Pink
clblBonus(j).Text = ""
clblTotalOfUpperSection(j) = New Label
grpUpperSection.Controls.Add(clblTotalOfUpperSection(j))
clblTotalOfUpperSection(j).Width = 75
clblTotalOfUpperSection(j).Height = 25
clblTotalOfUpperSection(j).Top = 289
clblTotalOfUpperSection(j).Left = j *
clblTotalOfUpperSection(j).Width + 107 + j * 6
clblTotalOfUpperSection(j).BackColor = Color.Pink
clblTotalOfUpperSection(j).Text = ""
clbl3OfAKind(j) = New Label
grpLowerSection.Controls.Add(clbl3OfAKind(j))
clbl3OfAKind(j).Width = 75
clbl3OfAKind(j).Height = 25
clbl3OfAKind(j).Top = 22
clbl3OfAKind(j).Left = j * clbl3OfAKind(j).Width + 120 + j * 6
clbl3OfAKind(j).BackColor = Color.Pink
clbl3OfAKind(j).Text = ""
clbl4OfAKind(j) = New Label
grpLowerSection.Controls.Add(clbl4OfAKind(j))
clbl4OfAKind(j).Width = 75
clbl4OfAKind(j).Height = 25
clbl4OfAKind(j).Top = 51
clbl4OfAKind(j).Left = j * clbl4OfAKind(j).Width + 120 + j * 6
clbl4OfAKind(j).BackColor = Color.Pink
clbl4OfAKind(j).Text = ""
clblFullHouse(j) = New Label
grpLowerSection.Controls.Add(clblFullHouse(j))
clblFullHouse(j).Width = 75
clblFullHouse(j).Height = 25
clblFullHouse(j).Top = 80
clblFullHouse(j).Left = j * clblFullHouse(j).Width + 120 + j * 6
clblFullHouse(j).BackColor = Color.Pink
clblFullHouse(j).Text = ""
clblSmallStraight(j) = New Label
grpLowerSection.Controls.Add(clblSmallStraight(j))
clblSmallStraight(j).Width = 75
clblSmallStraight(j).Height = 25
clblSmallStraight(j).Top = 109
clblSmallStraight(j).Left = j * clblSmallStraight(j).Width + 120 + j * 6
clblSmallStraight(j).BackColor = Color.Pink
clblSmallStraight(j).Text = ""
clblLargeStraight(j) = New Label
grpLowerSection.Controls.Add(clblLargeStraight(j))
clblLargeStraight(j).Width = 75
clblLargeStraight(j).Height = 25
clblLargeStraight(j).Top = 138
clblLargeStraight(j).Left = j * clblLargeStraight(j).Width + 120 + j * 6
clblLargeStraight(j).BackColor = Color.Pink
clblLargeStraight(j).Text = ""
clblYahtzee(j) = New Label
grpLowerSection.Controls.Add(clblYahtzee(j))
clblYahtzee(j).Width = 75
clblYahtzee(j).Height = 25
clblYahtzee(j).Top = 167
clblYahtzee(j).Left = j * clblYahtzee(j).Width + 120 + j * 6
clblYahtzee(j).BackColor = Color.Pink
clblYahtzee(j).Text = ""
clblChance(j) = New Label
grpLowerSection.Controls.Add(clblChance(j))
clblChance(j).Width = 75
clblChance(j).Height = 25
clblChance(j).Top = 196
clblChance(j).Left = j * clblChance(j).Width + 120 + j * 6
clblChance(j).BackColor = Color.Pink
clblChance(j).Text = ""
clblYahtzeeBonus(j) = New Label
grpLowerSection.Controls.Add(clblYahtzeeBonus(j))
clblYahtzeeBonus(j).Width = 75
clblYahtzeeBonus(j).Height = 25
clblYahtzeeBonus(j).Top = 233
clblYahtzeeBonus(j).Left = j * clblYahtzeeBonus(j).Width + 120 + j * 6
clblYahtzeeBonus(j).BackColor = Color.Pink
clblYahtzeeBonus(j).Text = ""
clblTotalOfLowerSection(j) = New Label
grpLowerSection.Controls.Add(clblTotalOfLowerSection(j))
clblTotalOfLowerSection(j).Width = 75
clblTotalOfLowerSection(j).Height = 25
clblTotalOfLowerSection(j).Top = 288
clblTotalOfLowerSection(j).Left = j * clblTotalOfLowerSection(j).Width + 120 + j * 6
clblTotalOfLowerSection(j).BackColor = Color.Pink
clblTotalOfLowerSection(j).Text = ""
clblTotal(j) = New Label
Me.Controls.Add(clblTotal(j))
clblTotal(j).Width = 75
clblTotal(j).Height = 35
clblTotal(j).Top = 556
clblTotal(j).Left = j * clblTotalOfLowerSection(j).Width + 124 + j * 135
clblTotal(j).BackColor = Color.White
clblTotal(j).Text = ""
Next j
Call sNewGame()
'Call sScratch()
End Sub
'--------------------------------------------------------------------------
'Description: Exits the game from the menu item "Exit".
'--------------------------------------------------------------------------
Private Sub mnuExit_Click(sender As Object,
e As EventArgs) Handles mnuExit.Click
Me.Close()
End Sub
'--------------------------------------------------------------------------
'Description: Asks if the user want to start a new game. If yes, calls
' sNewGame.
'
'Calls: sNewGame.
'--------------------------------------------------------------------------
Private Sub mnuNewGame_Click(sender As Object,
e As EventArgs) Handles mnuNewGame.Click
'Are you sure you want to reset the game?
Dim result = MessageBox.Show("Are you sure you want to start a new game?",
"New Game", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
Call sNewGame()
End If
End Sub
'--------------------------------------------------------------------------
'Description: Loads the previous game for the player to continue playing.
'
'Called by: mnuLoadGame_Click.
'--------------------------------------------------------------------------
Private Sub sLoadGame()
Dim i As Integer
For i = 0 To cshtNumPlayers - CShort(1)
FileOpen(2, "..\Data\" & (i + CShort(1)).ToString & ".txt", OpenMode.Input)
clblAces(i).Text = LineInput(2)
'cshtPlayerLineScore(0) = CShort(clblAces(i).Text)
clblTwos(i).Text = LineInput(2)
clblThrees(i).Text = LineInput(2)
clblFours(i).Text = LineInput(2)
clblFives(i).Text = LineInput(2)
clblSixes(i).Text = LineInput(2)
clblTotalScore(i).Text = LineInput(2)
clblBonus(i).Text = LineInput(2)
clblTotalOfUpperSection(i).Text = LineInput(2)
clbl3OfAKind(i).Text = LineInput(2)
clbl4OfAKind(i).Text = LineInput(2)
clblFullHouse(i).Text = LineInput(2)
clblSmallStraight(i).Text = LineInput(2)
clblLargeStraight(i).Text = LineInput(2)
clblYahtzee(i).Text = LineInput(2)
clblChance(i).Text = LineInput(2)
clblYahtzeeBonus(i).Text = LineInput(2)
clblTotalOfLowerSection(i).Text = LineInput(2)
clblPlayersL(i).Text = LineInput(2)
clblPlayersU(i).Text = LineInput(2)
clblPlayersT(i).Text = LineInput(2)
clblTotal(i).Text = LineInput(2)
Next i
FileClose(2)
End Sub
'--------------------------------------------------------------------------
'Description: Checking if the user wants to start a new game or to continue
' their game.
'--------------------------------------------------------------------------
Private Sub sScratch()
Dim strTemp As String
Dim strTempo As String
strTemp = CStr(MessageBox.Show("Do you want to start a new game?",
"New Game", MessageBoxButtons.YesNo))
If strTemp = CStr(DialogResult.Yes) Then
Call sNewGame()
Else
strTempo = CStr(MessageBox.Show("Do you want continue your game?",
"Load Game", MessageBoxButtons.YesNo))
If strTempo = CStr(DialogResult.Yes) Then
Call sLoadGame()
End If
End If
End Sub
'--------------------------------------------------------------------------
'Description: Clears all the labels of the game to start a new game.
'--------------------------------------------------------------------------
Private Sub sNewGame()
Dim i As Short
Dim j As Short
Dim strTemp As String
Call sResetTheDie()
lblRoundsLeft.Text = "13"
lblCurrentPlayer.Text = cstrPlayerNames(cshtCurrentPlayer) & "'s Turn"
For i = 0 To cshtNumPlayers - CShort(1)
For j = 0 To 18
cshtPlayerScores(i, j) = 0
Next j
clblAces(i).Text = ""
clblTwos(i).Text = ""
clblThrees(i).Text = ""
clblFours(i).Text = ""
clblFives(i).Text = ""
clblSixes(i).Text = ""
clblTotalScore(i).Text = ""
clblBonus(i).Text = ""
clblTotalOfUpperSection(i).Text = ""
clbl3OfAKind(i).Text = ""
clbl4OfAKind(i).Text = ""
clblFullHouse(i).Text = ""
clblSmallStraight(i).Text = ""
clblLargeStraight(i).Text = ""
clblYahtzee(i).Text = ""
clblChance(i).Text = ""
clblYahtzeeBonus(i).Text = ""
clblTotal(i).Text = ""
clblPlayersL(i).Text = ""
clblPlayersT(i).Text = ""
clblPlayersU(i).Text = ""
Next i
cshtCurrentPlayer = 0
'ask for number of players and assign to cshtNumPlayers
Try
strTemp = InputBox("Please enter the number of players (1-6):")
cshtNumPlayers = CShort(strTemp)
If cshtNumPlayers > 6 Then
MessageBox.Show("The maximum number of players is 6.")
cshtNumPlayers = 6
ElseIf cshtNumPlayers < 1 Then
MessageBox.Show("The minimum number of players is 1.")
cshtNumPlayers = 1
End If
Catch
MessageBox.Show("You must enter a numeric value")
End Try
'Ask for names and assign to string array
For i = 1 To cshtNumPlayers
strTemp = InputBox("Please enter the name of player " &
i.ToString & ":")
cstrPlayerNames(i - 1) = strTemp
clblPlayersU(i - 1).Text = strTemp
clblPlayersL(i - 1).Text = strTemp
clblPlayersT(i - 1).Text = strTemp
Next i
If cshtNumPlayers = 1 Then
grpUpperSection.Width = 95 + cshtNumPlayers * 93
grpLowerSection.Width = 100 + cshtNumPlayers * 100
clblPlayersL(1).Visible = False
clblPlayersL(2).Visible = False
clblPlayersL(3).Visible = False
clblPlayersL(4).Visible = False
clblPlayersL(5).Visible = False
clblPlayersU(1).Visible = False
clblPlayersU(2).Visible = False
clblPlayersU(3).Visible = False
clblPlayersU(4).Visible = False
clblPlayersU(5).Visible = False
clblPlayersT(1).Visible = False
clblPlayersT(2).Visible = False
clblPlayersT(3).Visible = False
clblPlayersT(4).Visible = False
clblPlayersT(5).Visible = False
clblTotal(1).Visible = False
clblTotal(2).Visible = False
clblTotal(3).Visible = False
clblTotal(4).Visible = False
clblTotal(5).Visible = False
grpUpperSection.Left = 150
grpLowerSection.Left = 450
clblPlayersU(0).Left = grpUpperSection.Left + btnAces.Width + 15
clblPlayersL(0).Left = grpLowerSection.Left + btn3OfAKind.Width + 15
clblPlayersT(0).Left = grpUpperSection.Left + btnAces.Width * 2
clblTotal(0).Left = clblPlayersT(0).Left + clblPlayersT(0).Width + 10
For i = 0 To 4
cpicDie(i).Left = i * cpicDie(i).Width + 100
cchkHold(i).Left = i * cchkHold(i).Width + 100
Next
btnRoll.Left = 475
lblRounds.Left = btnRoll.Left + lblRounds.Width + 10
lblRoundsLeft.Left = lblRounds.Left
Me.Width = lblRounds.Left + lblRounds.Width + 110
End If
If cshtNumPlayers = 2 Then
grpUpperSection.Width = 95 + cshtNumPlayers * 87
grpLowerSection.Width = 100 + cshtNumPlayers * 90
clblPlayersL(2).Visible = False
clblPlayersL(3).Visible = False
clblPlayersL(4).Visible = False
clblPlayersL(5).Visible = False
clblPlayersU(2).Visible = False
clblPlayersU(3).Visible = False
clblPlayersU(4).Visible = False
clblPlayersU(5).Visible = False
clblPlayersT(2).Visible = False
clblPlayersT(3).Visible = False
clblPlayersT(4).Visible = False
clblPlayersT(5).Visible = False
clblTotal(2).Visible = False
clblTotal(3).Visible = False
clblTotal(4).Visible = False
clblTotal(5).Visible = False
grpUpperSection.Left = 100
grpLowerSection.Left = 500
clblPlayersU(0).Left = grpUpperSection.Left + btnAces.Width + 20
clblPlayersU(1).Left = clblPlayersU(0).Left + clblPlayersU(0).Width + 5
clblPlayersL(0).Left = grpLowerSection.Left + btn3OfAKind.Width + 20
clblPlayersL(1).Left = clblPlayersL(0).Left + clblPlayersL(0).Width + 5
clblPlayersT(0).Left = grpUpperSection.Left + btnAces.Width * 2
clblTotal(0).Left = clblPlayersT(0).Left + clblPlayersT(0).Width + 10
clblPlayersT(1).Left = clblTotal(0).Left + clblTotal(0).Width + 20
clblTotal(1).Left = clblPlayersT(1).Left + clblPlayersT(1).Width + 20
For i = 0 To 4
cpicDie(i).Left = i * cpicDie(i).Width + 100
cchkHold(i).Left = i * cchkHold(i).Width + 100
Next
btnRoll.Left = 500
lblRounds.Left = btnRoll.Left + lblRounds.Width + 10
lblRoundsLeft.Left = lblRounds.Left
Me.Width = lblRounds.Left + lblRounds.Width + 200
End If
If cshtNumPlayers = 3 Then
grpUpperSection.Width = 95 + cshtNumPlayers * 85
grpLowerSection.Width = 100 + cshtNumPlayers * 87
clblPlayersL(3).Visible = False
clblPlayersL(4).Visible = False
clblPlayersL(5).Visible = False
clblPlayersU(3).Visible = False
clblPlayersU(4).Visible = False
clblPlayersU(5).Visible = False
clblPlayersT(3).Visible = False
clblPlayersT(4).Visible = False
clblPlayersT(5).Visible = False
clblTotal(3).Visible = False
clblTotal(4).Visible = False
clblTotal(5).Visible = False
grpUpperSection.Left = 75
grpLowerSection.Left = 525
clblPlayersU(0).Left = grpUpperSection.Left + btnAces.Width + 20
clblPlayersU(1).Left = clblPlayersU(0).Left + clblPlayersU(0).Width + 7
clblPlayersU(2).Left = clblPlayersU(1).Left + clblPlayersU(1).Width + 7
clblPlayersL(0).Left = grpLowerSection.Left + btn3OfAKind.Width + 20
clblPlayersL(1).Left = clblPlayersL(0).Left + clblPlayersL(0).Width + 5
clblPlayersL(2).Left = clblPlayersL(1).Left + clblPlayersL(1).Width + 5
clblPlayersT(0).Left = grpUpperSection.Left + btnAces.Width * 2
clblTotal(0).Left = clblPlayersT(0).Left + clblPlayersT(0).Width + 10
clblPlayersT(1).Left = clblTotal(0).Left + clblTotal(0).Width + 20
clblTotal(1).Left = clblPlayersT(1).Left + clblPlayersT(1).Width + 20
clblPlayersT(2).Left = clblTotal(1).Left + clblTotal(1).Width + 20
clblTotal(2).Left = clblPlayersT(2).Left + clblPlayersT(2).Width + 20
For i = 0 To 4
cpicDie(i).Left = i * cpicDie(i).Width + 135
cchkHold(i).Left = i * cchkHold(i).Width + 135
Next
btnRoll.Left = 525
lblRounds.Left = btnRoll.Left + lblRounds.Width + 10
lblRoundsLeft.Left = lblRounds.Left
Me.Width = lblRounds.Left + lblRounds.Width + 240
End If
If cshtNumPlayers = 4 Then
grpUpperSection.Width = 95 + cshtNumPlayers * 84
grpLowerSection.Width = 100 + cshtNumPlayers * 86
clblPlayersL(4).Visible = False
clblPlayersL(5).Visible = False
clblPlayersU(4).Visible = False
clblPlayersU(5).Visible = False
clblPlayersT(4).Visible = False
clblPlayersT(5).Visible = False
clblTotal(4).Visible = False
clblTotal(5).Visible = False
grpUpperSection.Left = 50
grpLowerSection.Left = 525
clblPlayersU(0).Left = grpUpperSection.Left + btnAces.Width + 20
clblPlayersU(1).Left = clblPlayersU(0).Left + clblPlayersU(0).Width + 5
clblPlayersU(2).Left = clblPlayersU(1).Left + clblPlayersU(1).Width + 5
clblPlayersU(3).Left = clblPlayersU(2).Left + clblPlayersU(2).Width + 8
clblPlayersL(0).Left = grpLowerSection.Left + btn3OfAKind.Width + 20
clblPlayersL(1).Left = clblPlayersL(0).Left + clblPlayersL(0).Width + 5
clblPlayersL(2).Left = clblPlayersL(1).Left + clblPlayersL(1).Width + 5
clblPlayersL(3).Left = clblPlayersL(2).Left + clblPlayersL(2).Width + 9
clblPlayersT(0).Left = grpUpperSection.Left + btnAces.Width
clblTotal(0).Left = clblPlayersT(0).Left + clblPlayersT(0).Width + 10
clblPlayersT(1).Left = clblTotal(0).Left + clblTotal(0).Width + 20
clblTotal(1).Left = clblPlayersT(1).Left + clblPlayersT(1).Width + 20
clblPlayersT(2).Left = clblTotal(1).Left + clblTotal(1).Width + 20
clblTotal(2).Left = clblPlayersT(2).Left + clblPlayersT(2).Width + 20
clblPlayersT(3).Left = clblTotal(2).Left + clblTotal(2).Width + 21
clblTotal(3).Left = clblPlayersT(3).Left + clblPlayersT(3).Width + 21
For i = 0 To 4
cpicDie(i).Left = i * cpicDie(i).Width + 150
cchkHold(i).Left = i * cchkHold(i).Width + 150
Next
btnRoll.Left = 550
lblRounds.Left = btnRoll.Left + lblRounds.Width + 10
lblRoundsLeft.Left = lblRounds.Left
Me.Width = lblRounds.Left + lblRounds.Width + 275
End If
If cshtNumPlayers = 5 Then
grpUpperSection.Width = 95 + cshtNumPlayers * 83
grpLowerSection.Width = 100 + cshtNumPlayers * 85
clblPlayersL(5).Visible = False
clblPlayersU(5).Visible = False
clblPlayersT(5).Visible = False
clblTotal(5).Visible = False
grpUpperSection.Left = 25
grpLowerSection.Left = 600
clblPlayersU(0).Left = grpUpperSection.Left + btnAces.Width + 20
clblPlayersU(1).Left = clblPlayersU(0).Left + clblPlayersU(0).Width + 5
clblPlayersU(2).Left = clblPlayersU(1).Left + clblPlayersU(1).Width + 5
clblPlayersU(3).Left = clblPlayersU(2).Left + clblPlayersU(2).Width + 8
clblPlayersU(4).Left = clblPlayersU(3).Left + clblPlayersU(3).Width + 9
clblPlayersL(0).Left = grpLowerSection.Left + btn3OfAKind.Width + 20
clblPlayersL(1).Left = clblPlayersL(0).Left + clblPlayersL(0).Width + 5
clblPlayersL(2).Left = clblPlayersL(1).Left + clblPlayersL(1).Width + 5
clblPlayersL(3).Left = clblPlayersL(2).Left + clblPlayersL(2).Width + 8
clblPlayersL(4).Left = clblPlayersL(3).Left + clblPlayersL(3).Width + 9
clblPlayersT(0).Left = grpUpperSection.Left + btnAces.Width
clblTotal(0).Left = clblPlayersT(0).Left + clblPlayersT(0).Width + 10
clblPlayersT(1).Left = clblTotal(0).Left + clblTotal(0).Width + 20
clblTotal(1).Left = clblPlayersT(1).Left + clblPlayersT(1).Width + 20
clblPlayersT(2).Left = clblTotal(1).Left + clblTotal(1).Width + 20
clblTotal(2).Left = clblPlayersT(2).Left + clblPlayersT(2).Width + 20
clblPlayersT(3).Left = clblTotal(2).Left + clblTotal(2).Width + 21
clblTotal(3).Left = clblPlayersT(3).Left + clblPlayersT(3).Width + 21
clblPlayersT(4).Left = clblTotal(3).Left + clblTotal(3).Width + 22
clblTotal(4).Left = clblPlayersT(4).Left + clblPlayersT(4).Width + 22
For i = 0 To 4
cpicDie(i).Left = i * cpicDie(i).Width + 225
cchkHold(i).Left = i * cchkHold(i).Width + 225
Next
btnRoll.Left = 625
lblRounds.Left = btnRoll.Left + lblRounds.Width + 10
lblRoundsLeft.Left = lblRounds.Left
Me.Width = lblRounds.Left + lblRounds.Width * 3 + 140
End If
End Sub
'--------------------------------------------------------------------------
'Description: Checks an array of values for a how many of a particular
' number.
'
'Called by: btnAces_Click, btnTwos_Click, btnThrees_Click, btnFours_Click,
' btnFives_Click, btnSixes_Click.
'--------------------------------------------------------------------------
Private Function fHowMany(ByVal shtNumber As Short,
ByVal cshtDiceVal() As Short) As Short
Dim shtQty As Short
Dim i As Short
For i = 0 To 4
If cshtDiceVal(i) = shtNumber Then
shtQty += CShort(1)
End If
Next i
Return shtQty
End Function
'--------------------------------------------------------------------------
'Description: This sub checks if the number of rounds have been reached,
' and if so, it will determine which player has the highest
' score, congratulate them in a popup, then save high scores.
'
'Called by: btnAces_Click, btnTwos_Click, btnThrees_Click, btnFours_Click,
' btnFives_Click, btnSixes_Click, btn3OfAKind_Click,
' btn4OfAKind_Click, btnFullHouse_Click, btnSmallStraight_Click,
' btnLargeStraight_Click, btnChance_Click.
'--------------------------------------------------------------------------
Private Sub sEndGame()
Dim shtHighScore As Short
Dim strWinner As String
Dim i As Short
If cshtCurrentPlayer + 1 = cshtNumPlayers Then
cshtTurn += CShort(1)
lblRoundsLeft.Text = CStr(13 - cshtTurn)
If cshtTurn = 13 Then
shtHighScore = cshtPlayerScores(0, 18)
strWinner = cstrPlayerNames(0)
For i = 1 To cshtCurrentPlayer
If cshtPlayerScores(i, 18) > shtHighScore Then
shtHighScore = cshtPlayerScores(i, 18)
strWinner = cstrPlayerNames(i)
End If
Next i
MessageBox.Show("Congratulations, " & strWinner & "!" &
Chr(13) & "You have the highest score!")
'then save player name and score to high scores file
End If
End If
End Sub
'--------------------------------------------------------------------------
'Description: Increments the current player, and resets to 0 if reaching
' maximum.
'
'Called by: sEndofTurn, btnYahtzee_Click, btnYahtzeeBonus_Click.
'--------------------------------------------------------------------------
Private Sub sNextTurn()
cshtCurrentPlayer += CShort(1)
If cshtCurrentPlayer = cshtNumPlayers Then
cshtCurrentPlayer = 0
End If
lblCurrentPlayer.Text = cstrPlayerNames(cshtCurrentPlayer) & "'s Turn"
End Sub
'--------------------------------------------------------------------------
'Description: Generates random dice roll of each dice that doesn't have a
' checked "Hold".
'
'Called by: btnRoll_Click.
'--------------------------------------------------------------------------
Private Sub sRollEm()
Dim i As Integer
For i = 0 To 4
If cchkHold(i).Checked = False Then
cshtDiceVal(i) = CShort(Int(Rnd() * 6 + 1))
cpicDie(i).BackgroundImage = Image.FromFile("..\Images\redDie" _
& cshtDiceVal(i).ToString & ".png")
End If
Next i
End Sub
'--------------------------------------------------------------------------
'Description: This reduces lines of code by making one call for four.
'
'Calls: sTotalUp, sEndGame, sNextTurn, sResetTheDice.
'
'Called by: btnAces_Click, btnTwos_Click, btnThrees_Click, btnFours_Click,
' btnFives_Click, btnSixes_Click, btn3OfAKind_Click,
' btn4OfAKind_Click, btnFullHouse_Click, btnSmallStraight_Click,
' btnLargeSTraight_Click, btnChance_Click.
'--------------------------------------------------------------------------
Private Sub sEndofTurn()
Call sTotalUp()
Call sEndGame()
Call sNextTurn()
Call sResetTheDie()
End Sub
'--------------------------------------------------------------------------
'Description: Checks how many times the dice have been rolled and
' increments. This sub will not execute function if the dice
' have been rolled 3 times.
'
'Call: sRollEm
'--------------------------------------------------------------------------
Private Sub btnRoll_Click(sender As Object,
e As EventArgs) Handles btnRoll.Click
If cshtRolls < 3 Then
Call sRollEm()
cshtRolls += CShort(1)
End If
End Sub
'--------------------------------------------------------------------------
'Description: Calculates the total and then assigns to the right labels. If
' the total of upper section is bigger than 62, the players
' will get a 35 bonus point.
'
'Called by: sEndofTurn.
'--------------------------------------------------------------------------
Private Sub sTotalUp()
Dim i As Short
Dim j As Short
Dim shtBonusCheck As Short
cshtPlayerScores(cshtCurrentPlayer, 17) = 0 'Fix score totalling bug
For i = 0 To 5
shtBonusCheck += cshtPlayerScores(cshtCurrentPlayer, i)
Next
cshtPlayerScores(cshtCurrentPlayer, 6) = shtBonusCheck
clblTotalScore(cshtCurrentPlayer).Text = shtBonusCheck.ToString
If shtBonusCheck > 62 Then
cshtPlayerScores(cshtCurrentPlayer, 7) = 35
clblBonus(cshtCurrentPlayer).Text = "35"
End If
cshtPlayerScores(cshtCurrentPlayer, 8) =
cshtPlayerScores(cshtCurrentPlayer, 7) +
cshtPlayerScores(cshtCurrentPlayer, 6)
clblTotalOfUpperSection(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 8).ToString
For j = 9 To 16
cshtPlayerScores(cshtCurrentPlayer, 17) +=
cshtPlayerScores(cshtCurrentPlayer, j)
Next j
clblTotalOfLowerSection(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 17).ToString()
cshtPlayerScores(cshtCurrentPlayer, 18) =
cshtPlayerScores(cshtCurrentPlayer, 8) +
cshtPlayerScores(cshtCurrentPlayer, 17)
clblTotal(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 18).ToString
End Sub
'--------------------------------------------------------------------------
'Description: A function to get the total value of all dice.
'
'Called by: btn3OfAKind_Click, btn4OfAKind_Click, btnChance_Click.
'--------------------------------------------------------------------------
Private Function fDiceTotal() As Short
Dim i As Short
Dim shtTotal As Short
For i = 0 To 4
shtTotal += cshtDiceVal(i)
Next i
Return shtTotal
End Function
'--------------------------------------------------------------------------
'Description: Resets all the dice to prepare for new roll.
'
'Called by: sEndofTurn.
'--------------------------------------------------------------------------
Private Sub sResetTheDie()
Dim i As Short
For i = 0 To 4
cpicDie(i).BackgroundImage = Image.FromFile("..\Images\redDie0.png")
cpicDie(i).BackgroundImageLayout = ImageLayout.Zoom
cchkHold(i).Checked = False
Next i
cshtRolls = 0
End Sub
'--------------------------------------------------------------------------
'Description: After verifying if the Aces have not been scored, this sub
' will check how many Aces there are in the dice value array
' and assign that number to the 0 element of the scores array
' and display it on clblAces(cshtCurrentPlayer), then update
' the score, check if the game ends and if not, calculate the
' turn and reset the dice.
'
'Calls: sEndofTurn.
'--------------------------------------------------------------------------
Private Sub btnAces_Click(sender As Object,
e As EventArgs) Handles btnAces.Click
If clblAces(cshtCurrentPlayer).Text = "" Then
cshtPlayerScores(cshtCurrentPlayer, 0) = fHowMany(1, cshtDiceVal)
clblAces(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 0).ToString
Call sEndofTurn()
End If
End Sub
'--------------------------------------------------------------------------
'Description: After verifying if the Twos have not been scored, this sub
' will check how many Twos there are in the dice value array
' and assign that number to the 1 element of the scores array
' and display it on clblTwos(cshtCurrentPlayer), then update
' the score, check if the game ends and if not, calculate the
' turn and reset the dice.
'
'Calls: sEndofTurn.
'--------------------------------------------------------------------------
Private Sub btnTwos_Click(sender As Object,
e As EventArgs) Handles btnTwos.Click
If clblTwos(cshtCurrentPlayer).Text = "" Then
cshtPlayerScores(cshtCurrentPlayer, 1) =
CShort(fHowMany(2, cshtDiceVal) * 2)
clblTwos(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 1).ToString
Call sEndofTurn()
End If
End Sub
'--------------------------------------------------------------------------
'Description: After verifying if the Threes have not been scored, this sub
' will check how many Threes there are in the dice value array
' and assign that number to the 2 element of the scores array
' and display it on clblThrees(cshtCurrentPlayer), then update
' the score, check if the game ends and if not, calculate the
' turn and reset the dice.
'
'Calls: sEndofTurn.
'--------------------------------------------------------------------------
Private Sub btnThrees_Click(sender As Object,
e As EventArgs) Handles btnThrees.Click
If clblThrees(cshtCurrentPlayer).Text = "" Then
cshtPlayerScores(cshtCurrentPlayer, 2) =
CShort(fHowMany(3, cshtDiceVal) * 3)
clblThrees(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 2).ToString
Call sEndofTurn()
End If
End Sub
'--------------------------------------------------------------------------
'Description: After verifying if the Fours have not been scored, this sub
' will check how many Fours there are in the dice value array
' and assign that number to the 3 element of the scores array
' and display it on clblFours(cshtCurrentPlayer), then update
' the score, check if the game ends and if not, calculate the
' turn and reset the dice.
'
'Calls: sEndofTurn.
'--------------------------------------------------------------------------
Private Sub btnFours_Click(sender As Object,
e As EventArgs) Handles btnFours.Click
If clblFours(cshtCurrentPlayer).Text = "" Then
cshtPlayerScores(cshtCurrentPlayer, 3) =
CShort(fHowMany(4, cshtDiceVal) * 4)
clblFours(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 3).ToString
Call sEndofTurn()
End If
End Sub
'--------------------------------------------------------------------------
'Description: After verifying if the Fives have not been scored, this sub
' will check how many Fives there are in the dice value array
' and assign that number to the 4 element of the scores array
' and display it on clblFives(cshtCurrentPlayer), then update
' the score, check if the game ends and if not, calculate the
' turn and reset the dice.
'
'Calls: sEndofTurn.
'--------------------------------------------------------------------------
Private Sub btnFives_Click(sender As Object,
e As EventArgs) Handles btnFives.Click
If clblFives(cshtCurrentPlayer).Text = "" Then
cshtPlayerScores(cshtCurrentPlayer, 4) =
CShort(fHowMany(5, cshtDiceVal) * 5)
clblFives(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 4).ToString
Call sEndofTurn()
End If
End Sub
'--------------------------------------------------------------------------
'Description: After verifying if the Sixes have not been scored, this sub
' will check how many Sixes there are in the dice value array
' and assign that number to the 5 element of the scores array
' and display it on clblSixes(cshtCurrentPlayer), then update
' the score, check if the game ends and if not, calculate the
' turn and reset the dice.
'
'Calls: sEndofTurn.
'--------------------------------------------------------------------------
Private Sub btnSixes_Click(sender As Object,
e As EventArgs) Handles btnSixes.Click
If clblSixes(cshtCurrentPlayer).Text = "" Then
cshtPlayerScores(cshtCurrentPlayer, 5) =
CShort(fHowMany(6, cshtDiceVal) * 6)
clblSixes(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 5).ToString
Call sEndofTurn()
End If
End Sub
'--------------------------------------------------------------------------
'Description: This sub checks how many of the dice of a particular value
' there are and then return a boolean value.
'
'Called by: btn3OfAKind_Click, btn4OfAKind_Click, btnFullHouse_Click,
' btnYahtzee_Click, btnYahtzeeBonus_Click.
'--------------------------------------------------------------------------
Private Function fTargetAmt(ByVal shtNum As Short) As Boolean
Dim blnTarget As Boolean
Dim i As Short
Dim sht1 As Short
Dim sht2 As Short
Dim sht3 As Short
Dim sht4 As Short
Dim sht5 As Short
Dim sht6 As Short
sht1 = fHowMany(1, cshtDiceVal)
sht2 = fHowMany(2, cshtDiceVal)
sht3 = fHowMany(3, cshtDiceVal)
sht4 = fHowMany(4, cshtDiceVal)
sht5 = fHowMany(5, cshtDiceVal)
sht6 = fHowMany(6, cshtDiceVal)
For i = 0 To 5
If sht1 = shtNum Or sht2 = shtNum Or sht3 = shtNum Or
sht4 = shtNum Or sht5 = shtNum Or sht6 = shtNum Then
blnTarget = True
End If
Next i
Return blnTarget
End Function
'--------------------------------------------------------------------------
'Description: After verifying if 3 of a kind has not been score, this sub
' checks if there are three of a kind of dice present, then
' scores it.
'
'Calls: fTargetAmt, sEndofTurn.
'--------------------------------------------------------------------------
Private Sub btn3OfAKind_Click(sender As Object,
e As EventArgs) Handles btn3OfAKind.Click
If clbl3OfAKind(cshtCurrentPlayer).Text = "" Then
If fTargetAmt(3) Or fTargetAmt(4) Or fTargetAmt(5) Then
cshtPlayerScores(cshtCurrentPlayer, 9) = fDiceTotal()
clbl3OfAKind(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 9).ToString
Else
cshtPlayerScores(cshtCurrentPlayer, 9) = 0
clbl3OfAKind(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 9).ToString
End If
Call sEndofTurn()
End If
End Sub
'--------------------------------------------------------------------------
'Description: After veryfying if 4 of a kind has not been scored, it checks
' if there are four of a kind of dice present, then scores it.
'
'Calls: fTargetAmt, sEndofTurn.
'--------------------------------------------------------------------------
Private Sub btn4OfAKind_Click(sender As Object,
e As EventArgs) Handles btn4OfAKind.Click
If clbl4OfAKind(cshtCurrentPlayer).Text = "" Then
If fTargetAmt(4) Or fTargetAmt(5) Then
cshtPlayerScores(cshtCurrentPlayer, 10) = fDiceTotal()
clbl4OfAKind(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 10).ToString
Else
cshtPlayerScores(cshtCurrentPlayer, 10) = 0
clbl4OfAKind(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 10).ToString
End If
Call sEndofTurn()
End If
End Sub
'--------------------------------------------------------------------------
'Description: After verifying if Yahtzee have not been scored, this sub
' checks if there are five of a kind dice present, there
' scores 50. If not, the player scores 0.
'
'Calls: fTargetAmt, sTotalUp, sResetTheDice, sEndofTurn.
'--------------------------------------------------------------------------
Private Sub btnYahtzee_Click(sender As Object,
e As EventArgs) Handles btnYahtzee.Click
If clblYahtzee(cshtCurrentPlayer).Text = "" Then
If fTargetAmt(5) Then
cshtPlayerScores(cshtCurrentPlayer, 14) = 50
clblYahtzee(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 14).ToString
Call sTotalUp()
Call sResetTheDie()
Else
cshtPlayerScores(cshtCurrentPlayer, 14) = 0
clblYahtzee(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 14).ToString
Call sEndofTurn()
End If
cblnYahtzee(cshtCurrentPlayer) = True
End If
End Sub
'--------------------------------------------------------------------------
'Description: After verifying if Full House has not been scored, it checks
' if there are 2 of a kind and 3 of a kind and then scores it.
' If not, the player will get 0 point.
'
'Calls: fTargetAmt, sEndofTurn
'--------------------------------------------------------------------------
Private Sub btnFullHouse_Click(sender As Object,
e As EventArgs) Handles btnFullHouse.Click
If clblFullHouse(cshtCurrentPlayer).Text = "" Then
If fTargetAmt(2) And fTargetAmt(3) Then
cshtPlayerScores(cshtCurrentPlayer, 11) = 25
clblFullHouse(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 11).ToString
Else
cshtPlayerScores(cshtCurrentPlayer, 11) = 0
clblFullHouse(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 11).ToString
End If
Call sEndofTurn()
End If
End Sub
'--------------------------------------------------------------------------
'Description: After verifying if Small Straight has not been scored, it
' checks if there are four dice in a row and then score it. If
' not, the player will get 0 point.
'
'Calls: fHowMany, sEndofTurn.
'--------------------------------------------------------------------------
Private Sub btnSmallStraight_Click(sender As Object,
e As EventArgs) Handles btnSmallStraight.Click
If clblSmallStraight(cshtCurrentPlayer).Text = "" Then
Dim sht1 As Short
Dim sht2 As Short
Dim sht3 As Short
Dim sht4 As Short
Dim sht5 As Short
Dim sht6 As Short
sht1 = fHowMany(1, cshtDiceVal)
sht2 = fHowMany(2, cshtDiceVal)
sht3 = fHowMany(3, cshtDiceVal)
sht4 = fHowMany(4, cshtDiceVal)
sht5 = fHowMany(5, cshtDiceVal)
sht6 = fHowMany(6, cshtDiceVal)
If sht1 >= 1 And sht2 >= 1 And sht3 >= 1 And sht4 >= 1 Then
cshtPlayerScores(cshtCurrentPlayer, 12) = 30
clblSmallStraight(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 12).ToString
ElseIf sht2 >= 1 And sht3 >= 1 And sht4 >= 1 And sht5 >= 1 Then
cshtPlayerScores(cshtCurrentPlayer, 12) = 30
clblSmallStraight(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 12).ToString
ElseIf sht3 >= 1 And sht4 >= 1 And sht5 >= 1 And sht6 >= 1 Then
cshtPlayerScores(cshtCurrentPlayer, 12) = 30
clblSmallStraight(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 12).ToString
Else
cshtPlayerScores(cshtCurrentPlayer, 12) = 0
clblSmallStraight(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 12).ToString
End If
Call sEndofTurn()
End If
End Sub
'--------------------------------------------------------------------------
'Description: After verifying if Large Straight has not been scored, it
' checks if there are 5 dice in a row and then scores it. If
' not, the player will get 0 point.
'
'Calls: fHowMany, sEndofTurn.
'--------------------------------------------------------------------------
Private Sub btnLargeStraight_Click(sender As Object,
e As EventArgs) Handles btnLargeStraight.Click
If clblLargeStraight(cshtCurrentPlayer).Text = "" Then
Dim sht1 As Short
Dim sht2 As Short
Dim sht3 As Short
Dim sht4 As Short
Dim sht5 As Short
Dim sht6 As Short
sht1 = fHowMany(1, cshtDiceVal)
sht2 = fHowMany(2, cshtDiceVal)
sht3 = fHowMany(3, cshtDiceVal)
sht4 = fHowMany(4, cshtDiceVal)
sht5 = fHowMany(5, cshtDiceVal)
sht6 = fHowMany(6, cshtDiceVal)
If sht1 = 1 And sht2 = 1 And sht3 = 1 And sht4 = 1 And sht5 = 1 Then
cshtPlayerScores(cshtCurrentPlayer, 13) = 40
clblLargeStraight(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 13).ToString
ElseIf sht2 = 1 And sht3 = 1 And sht4 = 1 And sht5 = 1 And sht6 = 1 Then
cshtPlayerScores(cshtCurrentPlayer, 13) = 40
clblLargeStraight(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 13).ToString
Else
cshtPlayerScores(cshtCurrentPlayer, 13) = 0
clblLargeStraight(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 13).ToString
End If
Call sEndofTurn()
End If
End Sub
'--------------------------------------------------------------------------
'Description: After verifying if Chance has not been scored, this sub
' calculates the total value of all dice and then score it.
'
'Calls: fDiceTotal, sEndofTurn.
'--------------------------------------------------------------------------
Private Sub btnChance_Click(sender As Object,
e As EventArgs) Handles btnChance.Click
If clblChance(cshtCurrentPlayer).Text = "" Then
Dim i As Short
For i = 0 To 5
cshtPlayerScores(cshtCurrentPlayer, 15) = fDiceTotal()
clblChance(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 15).ToString
Next
Call sEndofTurn()
End If
End Sub
'--------------------------------------------------------------------------
'Description: After verifying if the player has scored Yahtzee and if there
' are 5 dice in a row, the player will get 50 points.
'
'Calls: fHowMany, sTotalUp, sResetTheDice
'--------------------------------------------------------------------------
Private Sub btnYahtzeeBonus_Click(sender As Object,
e As EventArgs) Handles btnYahtzeeBonus.Click
If cblnYahtzee(cshtCurrentPlayer) = True And fTargetAmt(5) Then
cshtPlayerScores(cshtCurrentPlayer, 16) += CShort(50)
clblYahtzeeBonus(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 16).ToString
Call sTotalUp()
Call sResetTheDie()
Else
cshtPlayerScores(cshtCurrentPlayer, 16) = 0
clblYahtzeeBonus(cshtCurrentPlayer).Text =
cshtPlayerScores(cshtCurrentPlayer, 16).ToString
End If
End Sub
'--------------------------------------------------------------------------
'Description: Saves the program.
'--------------------------------------------------------------------------
Private Sub mnuSaveGame_Click(sender As Object,
e As EventArgs) Handles mnuSaveGame.Click
Dim i As Short
FileOpen(1, "..\Data\ygs.txt", OpenMode.Output)
WriteLine(1, cshtNumPlayers)
For i = 0 To cshtNumPlayers - CShort(1)
'FileOpen(1, "..\Data\" & (i + CShort(1)).ToString & ".txt", OpenMode.Output)
WriteLine(1, clblAces(i).Text)
WriteLine(1, clblTwos(i).Text)
WriteLine(1, clblThrees(i).Text)
WriteLine(1, clblFours(i).Text)
WriteLine(1, clblFives(i).Text)
WriteLine(1, clblSixes(i).Text)
WriteLine(1, clblTotalScore(i).Text)
WriteLine(1, clblBonus(i).Text)
WriteLine(1, clblTotalOfUpperSection(i).Text)
WriteLine(1, clbl3OfAKind(i).Text)
WriteLine(1, clbl4OfAKind(i).Text)
WriteLine(1, clblFullHouse(i).Text)
WriteLine(1, clblSmallStraight(i).Text)
WriteLine(1, clblLargeStraight(i).Text)
WriteLine(1, clblYahtzee(i).Text)
WriteLine(1, clblChance(i).Text)
WriteLine(1, clblYahtzeeBonus(i).Text)
WriteLine(1, clblTotalOfLowerSection(i).Text)
WriteLine(1, clblPlayersL(i).Text)
WriteLine(1, clblPlayersU(i).Text)
WriteLine(1, clblPlayersT(i).Text)
WriteLine(1, clblTotal(i).Text)
Next i
FileClose(1)
End Sub
'--------------------------------------------------------------------------
'Description: Loads the game for the player to continue their game.
'
'Calls: sLoadGame.
'--------------------------------------------------------------------------
Private Sub mnuLoadGame_Click(sender As Object,
e As EventArgs) Handles mnuLoadGame.Click
Call sLoadGame()
End Sub
'----------------------------------------------------------------------
'Description: Shows the information of the people who made the program.
'----------------------------------------------------------------------
Private Sub mnuAbout_Click(sender As Object,
e As EventArgs) Handles mnuAbout.Click
MessageBox.Show("Yahtzee designed and written by:" & Chr(13) &
"Team Jingle Bells" & Chr(13) & Chr(13) & "Margaret
Alcock" & Chr(13) & "Van Quach" & Chr(13) & "Dylan
Parker" & Chr(13) & "Tyler Little" & Chr(13) & Chr(13) &
"CS 115, Section C" & Chr(13) & "Fall 2018")
End Sub
'--------------------------------------------------------------------------
'Description: Shows the rules of the program.
'--------------------------------------------------------------------------
Private Sub mnuHowToPlay_Click(sender As Object,
e As EventArgs) Handles mnuHowToPlay.Click
lblRules.Text = ""
grpHowTo.Visible = True
FileOpen(47, "..\Images\howtoplay.Txt", OpenMode.Input)
Dim strTemp As String
Do Until EOF(47) = True
strTemp = LineInput(47) & Chr(13)
lblRules.Text &= strTemp
Loop
FileClose(47)
End Sub
'--------------------------------------------------------------------------
'Description: Close grpHowTo.
'--------------------------------------------------------------------------
Private Sub btnClose_Click(sender As Object,
e As EventArgs) Handles btnClose.Click
grpHowTo.Visible = False
End Sub
End Class
|
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' Filename: GeoFunction.vb
' Project: jaktools
' Version: 0.2
' Author: Simone Giacomoni (jaksg82@yahoo.it)
' http://www.vivoscuola.it/us/simone.giacomoni/devtools/index.html
'
' Description: the function to convert the coordinates between various crs
'
' Public Functions: EN2LL(ByVal Ellipsoid As Ellipsoid, ByVal Projection As ProjectionParam, ByVal Point As Point3D) As Point3D
' LL2EN(ByVal Ellipsoid As Ellipsoid, ByVal Projection As ProjectionParam, ByVal Point As Point3D) As Point3D
' LL2XYZ(ByVal Ellipsoid As Ellipsoid, ByVal Point As Point3D) As Point3D
' XYZ2LL(ByVal Ellipsoid As Ellipsoid, ByVal Point As Point3D) As Point3D
' XYZ2XYZ(ByVal Conversion As ConversionParameters, ByVal Point As Point3D, ByVal ToWgs84 As Boolean) As Point3D
' EllDistance(ByVal Ellipsoid As Ellipsoid, ByVal Point1 As Point3D, ByVal Point2 As Point3D, Optional ByRef Alpha1 As Double = 0.0, Optional ByRef Alpha2 As Double = 0.0) As Double
'
' Private Functions: UTM(ByVal Ellipsoid As Ellipsoid, ByVal Projection As ProjectionParam, ByVal Point As Point3D, ByVal IsInverse As Boolean) As Point3D
' TMerc(ByVal Ellipsoid As Ellipsoid, ByVal Projection As ProjectionParam, ByVal Point As Point3D, ByVal IsInverse As Boolean) As Point3D
' Merc(ByVal Ellipsoid As Ellipsoid, ByVal Projection As ProjectionParam, ByVal Point As Point3D, ByVal IsInverse As Boolean) As Point3D
' LCC1(ByVal Ellipsoid As Ellipsoid, ByVal Projection As ProjectionParam, ByVal Point As Point3D, ByVal IsInverse As Boolean) As Point3D
' LCC2(ByVal Ellipsoid As Ellipsoid, ByVal Projection As ProjectionParam, ByVal Point As Point3D, ByVal IsInverse As Boolean) As Point3D
'
' Copyright @2013, Simone Giacomoni
'
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Imports System.Math
Public Module GeoFunction
Public Function EN2LL(ByVal Ellipsoid As Ellipsoid, ByVal Projection As Projection, ByVal Point As Point3D) As Point3D
Select Case Projection.Method
Case "UTM"
EN2LL = UTM(Ellipsoid, Projection, Point, True)
Case "TMerc"
EN2LL = TMerc(Ellipsoid, Projection, Point, True)
Case "Merc"
EN2LL = Merc(Ellipsoid, Projection, Point, True)
Case "LCC1"
EN2LL = LCC1(Ellipsoid, Projection, Point, True)
Case "LCC2"
EN2LL = LCC2(Ellipsoid, Projection, Point, True)
Case Else
EN2LL = Point
End Select
End Function
Public Function LL2EN(ByVal Ellipsoid As Ellipsoid, ByVal Projection As Projection, ByVal Point As Point3D) As Point3D
Select Case Projection.Method
Case "UTM"
LL2EN = UTM(Ellipsoid, Projection, Point, False)
Case "TMerc"
LL2EN = TMerc(Ellipsoid, Projection, Point, False)
Case "Merc"
LL2EN = Merc(Ellipsoid, Projection, Point, False)
Case "LCC1"
LL2EN = LCC1(Ellipsoid, Projection, Point, False)
Case "LCC2"
LL2EN = LCC2(Ellipsoid, Projection, Point, False)
Case Else
LL2EN = Point
End Select
End Function
Public Function LL2XYZ(ByVal Ellipsoid As Ellipsoid, ByVal Point As Point3D) As Point3D
'Complete the definition of the ellipsoid
Dim f As Double = Ellipsoid.InvFlattening ^ -1
If Ellipsoid.InvFlattening = 0 Then f = 1
Dim a As Double = Ellipsoid.SemiMayorAxis
Dim e As Double = Sqrt((2 * f) - (f ^ 2))
'Calculate the prime vertical radious of curvature at given latitude
Dim v As Double = a / Sqrt(1 - e ^ 2 * (Sin(Point.Y) ^ 2))
'Calculate the results
LL2XYZ.X = (v + Point.Z) * Cos(Point.Y) * Cos(Point.X)
LL2XYZ.Y = (v + Point.Z) * Cos(Point.Y) * Sin(Point.X)
LL2XYZ.Z = ((1 - e ^ 2) * v + Point.Z) * Sin(Point.Y)
End Function
Public Function XYZ2LL(ByVal Ellipsoid As Ellipsoid, ByVal Point As Point3D) As Point3D
'Complete the definition of the ellipsoid
Dim f As Double = Ellipsoid.InvFlattening ^ -1
Dim a As Double = Ellipsoid.SemiMayorAxis
Dim b As Double = (1 - f) * a
Dim e As Double = Sqrt((2 * f) - (f ^ 2))
Dim eps, p, q, v As Double
'Calculate the latitude
eps = e ^ 2 / (1 - e ^ 2)
p = (Point.X ^ 2 + Point.Y ^ 2) ^ 0.5
q = Atan((Point.Z * a) / (p * b))
XYZ2LL.Y = Atan((Point.Z + eps * b * Sin(q) ^ 3) / (p - e ^ 2 * a * Cos(q) ^ 3))
'Calculate the elevetion
v = a / (1 - e ^ 2 * (Sin(XYZ2LL.Y) ^ 2)) ^ 0.5
XYZ2LL.Z = (p / Cos(XYZ2LL.Y)) - v
'Calculate the longitude
XYZ2LL.X = Atan(Point.Y / Point.X)
End Function
Public Function XYZ2XYZ(ByVal Conversion As DatumShift, ByVal Point As Point3D, ByVal ToWgs84 As Boolean) As Point3D
Dim dX, dY, dZ, Rx, Ry, Rz, M As Double
Dim Xs, Ys, Zs, Xr, Yr, Zr, Xp, Yp, Zp As Double
Xs = Point.X
Ys = Point.Y
Zs = Point.Z
If ToWgs84 Then
M = 1 + (Conversion.ScaleFactorPPM * 10 ^ -6)
dX = Conversion.DeltaX
dY = Conversion.DeltaY
dZ = Conversion.DeltaZ
Rx = Conversion.RotationXrad
Ry = Conversion.RotationYrad
Rz = Conversion.RotationZrad
Xp = Conversion.RotationPointX
Yp = Conversion.RotationPointY
Zp = Conversion.RotationPointZ
Else
M = 1 + (-Conversion.ScaleFactorPPM * 10 ^ -6)
dX = -Conversion.DeltaX
dY = -Conversion.DeltaY
dZ = -Conversion.DeltaZ
Rx = -Conversion.RotationXrad
Ry = -Conversion.RotationYrad
Rz = -Conversion.RotationZrad
Xp = Conversion.RotationPointX
Yp = Conversion.RotationPointY
Zp = Conversion.RotationPointZ
End If
Select Case UCase(Left(Conversion.Method, 1))
Case "G"
XYZ2XYZ.X = Xs + dX
XYZ2XYZ.Y = Ys + dY
XYZ2XYZ.Z = Zs + dZ
Case "P"
XYZ2XYZ.X = M * ((1 * Xs) + (-Rz * Ys) + (Ry * Zs)) + dX
XYZ2XYZ.Y = M * ((Rz * Xs) + (1 * Ys) + (-Rx * Zs)) + dY
XYZ2XYZ.Z = M * ((-Ry * Xs) + (Rx * Ys) + (1 * Zs)) + dZ
Case "C"
XYZ2XYZ.X = M * ((1 * Xs) + (Rz * Ys) + (-Ry * Zs)) + dX
XYZ2XYZ.Y = M * ((-Rz * Xs) + (1 * Ys) + (Rx * Zs)) + dY
XYZ2XYZ.Z = M * ((Ry * Xs) + (-Rx * Ys) + (1 * Zs)) + dZ
Case "M"
Xr = Xs - Xp
Yr = Ys - Yp
Zr = Zs - Zp
XYZ2XYZ.X = M * ((1 * Xr) + (Rz * Yr) + (-Ry * Zr)) + dX + Xp
XYZ2XYZ.Y = M * ((-Rz * Xr) + (1 * Yr) + (Rx * Zr)) + dY + Yp
XYZ2XYZ.Z = M * ((Ry * Xr) + (-Rx * Yr) + (1 * Zr)) + dZ + Zp
Case Else
XYZ2XYZ.X = 0
XYZ2XYZ.Y = 0
XYZ2XYZ.Z = 0
End Select
End Function
Public Function EllDistance(ByVal Ellipsoid As Ellipsoid, ByVal Point1 As Point3D, ByVal Point2 As Point3D, _
Optional ByRef Alpha1 As Double = 0.0, Optional ByRef Alpha2 As Double = 0.0) As Double
Dim a, b, f, lat1, lat2, U1, U2, L, L1, L2, Alpha, S, sinSigma, cosSigma, Sigma, lambda As Double
Dim sinAlpha, cos2Alpha, cos2sigma, C, lambdaPrev, Usquare, Aa, Bb, k1, DeltaSigma As Double
Dim maxIter As Integer = 100000
Dim Iter As Integer = 0
If Point1.X = Point2.X And Point1.Y = Point2.Y Then
Return 0
Else
a = Ellipsoid.SemiMayorAxis
f = 1 / Ellipsoid.InvFlattening
b = (1 - f) * a
lat1 = Point1.Y
lat2 = Point2.Y
U1 = Atan((1 - f) * Tan(lat1))
U2 = Atan((1 - f) * Tan(lat2))
L1 = Point1.X
L2 = Point2.X
L = L2 - L1
lambda = L
If lat1 = 0 And lat2 = 0 Then
'Geodesic runs along equator
S = a * lambda
If L1 > L2 Then
Alpha1 = DegRad(270)
Alpha2 = Alpha1
Else
Alpha1 = DegRad(90)
Alpha2 = Alpha1
End If
Else
Do
sinSigma = Sqrt((Cos(U2) * Sin(lambda)) ^ 2 + (Cos(U1) * Sin(U2) - Sin(U1) * Cos(U2) * Cos(lambda)) ^ 2)
cosSigma = Sin(U1) * Sin(U2) + Cos(U1) * Cos(U2) * Cos(lambda)
Sigma = Atan2(sinSigma, cosSigma)
sinAlpha = (Cos(U1) * Cos(U2) * Sin(lambda)) / Sin(Sigma)
cos2Alpha = 1 - sinAlpha ^ 2
cos2sigma = Cos(Sigma) - ((2 * Sin(U1) * Sin(U2)) / cos2Alpha)
C = (f / 16) * cos2Alpha * (4 + f * (4 - 3 * cos2Alpha))
lambdaPrev = lambda
lambda = L + (1 - C) * f * sinAlpha * (Sigma + C * Sin(Sigma) * (cos2sigma + C * Cos(Sigma) * (-1 + 2 * cos2sigma ^ 2)))
Iter = Iter + 1
Loop Until Abs(lambda - lambdaPrev) < 0.0000000001 Or Iter = maxIter
Alpha = ASin(sinAlpha)
Usquare = Cos(Alpha) ^ 2 * ((a ^ 2 - b ^ 2) / b ^ 2)
k1 = (Sqrt(1 + Usquare) - 1) / (Sqrt(1 + Usquare) + 1)
Aa = (1 + 0.25 * k1 ^ 2) / (1 - k1)
Bb = k1 * (1 - 3 / 8 * k1 ^ 2)
DeltaSigma = Bb * sinSigma * (cos2sigma + 0.25 * Bb * (cosSigma * (-1 + 2 * cos2sigma ^ 2) - (1 / 6) * Bb * cos2sigma * (-3 + 4 * sinSigma ^ 2) * (-3 + 4 * cosSigma ^ 2)))
S = b * Aa * (Sigma - DeltaSigma)
'Alpha1 = Atan((Cos(U2) * Sin(lambda)) / (Cos(U1) * Sin(U2) - Sin(U1) * Cos(U2) * Cos(lambda)))
'Alpha2 = Atan((Cos(U1) * Sin(lambda)) / (-Sin(U1) * Cos(U2) + Cos(U1) * Sin(U2) * Cos(lambda)))
Dim Alp1 As Double = Atan2(Cos(U2) * Sin(lambda), (Cos(U1) * Sin(U2) - Sin(U1) * Cos(U2) * Cos(lambda)))
Dim Alp2 As Double = Atan2(Cos(U1) * Sin(lambda), (-Sin(U1) * Cos(U2) + Cos(U1) * Sin(U2) * Cos(lambda)))
Alpha1 = Alp1
Alpha2 = Alp2
If Double.IsNaN(S) Then S = 0
End If
Return S
End If
End Function
Private Function UTM(ByVal Ellipsoid As Ellipsoid, ByVal Projection As Projection, ByVal Point As Point3D, _
ByVal IsInverse As Boolean) As Point3D
Dim f As Double
If Ellipsoid.InvFlattening = 0 Then
f = 1
Else
f = 1 / Ellipsoid.InvFlattening
End If
Dim a As Double = Ellipsoid.SemiMayorAxis
Dim b As Double = (1 - f) * a
Dim e As Double = Sqrt(2 * f - f ^ 2)
Dim secEcc As Double = Sqrt(e ^ 2 / (1 - e ^ 2))
Dim lat0, lon0, E0, N0, latf, Ef, Nf, lonf, Mo, k0 As Double
k0 = 0.9996
lon0 = Point.X
lat0 = Point.Y
E0 = Point.X
N0 = Point.Y
lonf = DegRad((Projection.UTMzone - 1) * 6 - 180 + 3)
Ef = 500000
If Projection.IsNorthHemisphere Then
'North
latf = 0
Nf = 0
Else
latf = 0
Nf = 10000000
End If
'Projection costant
Dim h1, h2, h3, h4, h1i, h2i, h3i, h4i As Double
Dim BI, n, Qo, Q, Qi, Qii, Beta, BetaO, Betai As Double
Dim Eta0, Eta1, Eta2, Eta3, Eta4, Eta As Double
Dim Eta0i, Eta1i, Eta2i, Eta3i, Eta4i, Etai As Double
Dim xiO, xiO0, xiO1, xiO2, xiO3, xiO4 As Double
Dim xi0, xi1, xi2, xi3, xi4, xi As Double
Dim xi0i, xi1i, xi2i, xi3i, xi4i, xii As Double
n = f / (2 - f)
BI = (a / (1 + n)) * (1 + n ^ 2 / 4 + n ^ 4 / 64)
h1 = n / 2 - (2 / 3) * n ^ 2 + (5 / 16) * n ^ 3 + (41 / 180) * n ^ 4
h2 = (13 / 48) * n ^ 2 - (3 / 5) * n ^ 3 + (557 / 1440) * n ^ 4
h3 = (61 / 240) * n ^ 3 - (103 / 140) * n ^ 4
h4 = (49561 / 161280) * n ^ 4
h1i = n / 2 - (2 / 3) * n ^ 2 + (37 / 96) * n ^ 3 - (1 / 360) * n ^ 4
h2i = (1 / 48) * n ^ 2 + (1 / 15) * n ^ 3 - (437 / 1440) * n ^ 4
h3i = (17 / 480) * n ^ 3 - (37 / 840) * n ^ 4
h4i = (4397 / 161280) * n ^ 4
If latf = 0 Then
Mo = 0
ElseIf latf = (PI / 2) Then
Mo = BI * (PI / 2)
ElseIf latf = -(PI / 2) Then
Mo = BI * -(PI / 2)
Else
Qo = ASinH(Tan(latf)) - (e * ATanH(e * Sin(latf)))
BetaO = Atan(SinH(Qo))
xiO0 = ASin(Sin(BetaO))
xiO1 = h1 * Sin(2 * xiO0)
xiO2 = h2 * Sin(4 * xiO0)
xiO3 = h3 * Sin(6 * xiO0)
xiO4 = h4 * Sin(8 * xiO0)
xiO = xiO0 + xiO1 + xiO2 + xiO3 + xiO4
Mo = BI * xiO
End If
If IsInverse Then
'From EN to LL
Etai = (E0 - Ef) / (BI * k0)
xii = ((N0 - Nf) + k0 * Mo) / (BI * k0)
xi1i = h1i * Sin(2 * xii) * CosH(2 * Etai)
xi2i = h2i * Sin(4 * xii) * CosH(4 * Etai)
xi3i = h3i * Sin(6 * xii) * CosH(6 * Etai)
xi4i = h4i * Sin(8 * xii) * CosH(8 * Etai)
xi0i = xii - (xi1i + xi2i + xi3i + xi4i)
Eta1i = h1i * Cos(2 * xii) * SinH(2 * Etai)
Eta2i = h2i * Cos(4 * xii) * SinH(4 * Etai)
Eta3i = h3i * Cos(6 * xii) * SinH(6 * Etai)
Eta4i = h4i * Cos(8 * xii) * SinH(8 * Etai)
Eta0i = Etai - (Eta1i + Eta2i + Eta3i + Eta4i)
Betai = ASin(Sin(xi0i) / CosH(Eta0i))
Qi = ASinH(Tan(Betai))
Qii = Qi + (e * ATanH(e * TanH(Qi)))
For i = 0 To 100
Qii = Qi + (e * ATanH(e * TanH(Qii)))
Next
'return the results
UTM.X = lonf + ASin(TanH(Eta0i) / Cos(Betai))
UTM.Y = Atan(SinH(Qii))
UTM.Z = Point.Z
Else
'From LL to EN
Q = ASinH(Tan(lat0)) - (e * ATanH(e * Sin(lat0)))
Beta = Atan(SinH(Q))
Eta0 = ATanH(Cos(Beta) * Sin(lon0 - lonf))
xi0 = ASin(Sin(Beta) * CosH(Eta0))
xi1 = h1 * Sin(2 * xi0) * CosH(2 * Eta0)
xi2 = h2 * Sin(4 * xi0) * CosH(4 * Eta0)
xi3 = h3 * Sin(6 * xi0) * CosH(6 * Eta0)
xi4 = h4 * Sin(8 * xi0) * CosH(8 * Eta0)
xi = xi0 + xi1 + xi2 + xi3 + xi4
Eta1 = h1 * Cos(2 * xi0) * SinH(2 * Eta0)
Eta2 = h2 * Cos(4 * xi0) * SinH(4 * Eta0)
Eta3 = h3 * Cos(6 * xi0) * SinH(6 * Eta0)
Eta4 = h4 * Cos(8 * xi0) * SinH(8 * Eta0)
Eta = Eta0 + Eta1 + Eta2 + Eta3 + Eta4
'return the results
UTM.X = Ef + k0 * BI * Eta
UTM.Y = Nf + k0 * (BI * xi - Mo)
UTM.Z = Point.Z
End If
End Function
Private Function TMerc(ByVal Ellipsoid As Ellipsoid, ByVal Projection As Projection, ByVal Point As Point3D, _
ByVal IsInverse As Boolean) As Point3D
Dim f As Double
If Ellipsoid.InvFlattening = 0 Then
f = 1
Else
f = 1 / Ellipsoid.InvFlattening
End If
Dim a As Double = Ellipsoid.SemiMayorAxis
Dim b As Double = (1 - f) * a
Dim e As Double = Sqrt(2 * f - f ^ 2)
Dim lat0, lon0, E0, N0, latf, Ef, Nf, lonf, Mo, k0 As Double
lon0 = Point.X
lat0 = Point.Y
E0 = Point.X
N0 = Point.Y
lonf = Projection.LongOrigin
latf = Projection.LatOrigin
Ef = Projection.FalseEasting
Nf = Projection.FalseNorthing
k0 = Projection.OriginScale
'Projection costant
Dim h1, h2, h3, h4, h1i, h2i, h3i, h4i As Double
Dim BI, n, Qo, Q, Qi, Qii, Beta, BetaO, Betai As Double
Dim Eta0, Eta1, Eta2, Eta3, Eta4, Eta As Double
Dim Eta0i, Eta1i, Eta2i, Eta3i, Eta4i, Etai As Double
Dim xiO, xiO0, xiO1, xiO2, xiO3, xiO4 As Double
Dim xi0, xi1, xi2, xi3, xi4, xi As Double
Dim xi0i, xi1i, xi2i, xi3i, xi4i, xii As Double
n = f / (2 - f)
BI = (a / (1 + n)) * (1 + n ^ 2 / 4 + n ^ 4 / 64)
h1 = n / 2 - (2 / 3) * n ^ 2 + (5 / 16) * n ^ 3 + (41 / 180) * n ^ 4
h2 = (13 / 48) * n ^ 2 - (3 / 5) * n ^ 3 + (557 / 1440) * n ^ 4
h3 = (61 / 240) * n ^ 3 - (103 / 140) * n ^ 4
h4 = (49561 / 161280) * n ^ 4
h1i = n / 2 - (2 / 3) * n ^ 2 + (37 / 96) * n ^ 3 - (1 / 360) * n ^ 4
h2i = (1 / 48) * n ^ 2 + (1 / 15) * n ^ 3 - (437 / 1440) * n ^ 4
h3i = (17 / 480) * n ^ 3 - (37 / 840) * n ^ 4
h4i = (4397 / 161280) * n ^ 4
If latf = 0 Then
Mo = 0
ElseIf latf = (PI / 2) Then
Mo = BI * (PI / 2)
ElseIf latf = -(PI / 2) Then
Mo = BI * -(PI / 2)
Else
Qo = ASinH(Tan(latf)) - (e * ATanH(e * Sin(latf)))
BetaO = Atan(SinH(Qo))
xiO0 = ASin(Sin(BetaO))
xiO1 = h1 * Sin(2 * xiO0)
xiO2 = h2 * Sin(4 * xiO0)
xiO3 = h3 * Sin(6 * xiO0)
xiO4 = h4 * Sin(8 * xiO0)
xiO = xiO0 + xiO1 + xiO2 + xiO3 + xiO4
Mo = BI * xiO
End If
If IsInverse Then
'From EN to LL
Etai = (E0 - Ef) / (BI * k0)
xii = ((N0 - Nf) + k0 * Mo) / (BI * k0)
xi1i = h1i * Sin(2 * xii) * CosH(2 * Etai)
xi2i = h2i * Sin(4 * xii) * CosH(4 * Etai)
xi3i = h3i * Sin(6 * xii) * CosH(6 * Etai)
xi4i = h4i * Sin(8 * xii) * CosH(8 * Etai)
xi0i = xii - (xi1i + xi2i + xi3i + xi4i)
Eta1i = h1i * Cos(2 * xii) * SinH(2 * Etai)
Eta2i = h2i * Cos(4 * xii) * SinH(4 * Etai)
Eta3i = h3i * Cos(6 * xii) * SinH(6 * Etai)
Eta4i = h4i * Cos(8 * xii) * SinH(8 * Etai)
Eta0i = Etai - (Eta1i + Eta2i + Eta3i + Eta4i)
Betai = ASin(Sin(xi0i) / CosH(Eta0i))
Qi = ASinH(Tan(Betai))
Qii = Qi + (e * ATanH(e * TanH(Qi)))
For i = 0 To 100
Qii = Qi + (e * ATanH(e * TanH(Qii)))
Next
'return the results
TMerc.X = lonf + ASin(TanH(Eta0i) / Cos(Betai))
TMerc.Y = Atan(SinH(Qii))
TMerc.Z = Point.Z
Else
'From LL to EN
Q = ASinH(Tan(lat0)) - (e * ATanH(e * Sin(lat0)))
Beta = Atan(SinH(Q))
Eta0 = ATanH(Cos(Beta) * Sin(lon0 - lonf))
xi0 = ASin(Sin(Beta) * CosH(Eta0))
xi1 = h1 * Sin(2 * xi0) * CosH(2 * Eta0)
xi2 = h2 * Sin(4 * xi0) * CosH(4 * Eta0)
xi3 = h3 * Sin(6 * xi0) * CosH(6 * Eta0)
xi4 = h4 * Sin(8 * xi0) * CosH(8 * Eta0)
xi = xi0 + xi1 + xi2 + xi3 + xi4
Eta1 = h1 * Cos(2 * xi0) * SinH(2 * Eta0)
Eta2 = h2 * Cos(4 * xi0) * SinH(4 * Eta0)
Eta3 = h3 * Cos(6 * xi0) * SinH(6 * Eta0)
Eta4 = h4 * Cos(8 * xi0) * SinH(8 * Eta0)
Eta = Eta0 + Eta1 + Eta2 + Eta3 + Eta4
'return the results
TMerc.X = Ef + k0 * BI * Eta
TMerc.Y = Nf + k0 * (BI * xi - Mo)
TMerc.Z = Point.Z
End If
End Function
'Forward and inverse projection formula for Mercator (EPSG Variant A)
Private Function Merc(ByVal Ellipsoid As Ellipsoid, ByVal Projection As Projection, ByVal Point As Point3D, _
ByVal IsInverse As Boolean) As Point3D
Dim f, a, b, e As Double
f = 1 / Ellipsoid.InvFlattening
a = Ellipsoid.SemiMayorAxis
b = (1 - f) * a
e = Sqrt(2 * f - f ^ 2)
Dim lat0, lon0, E0, N0, latf, Ef, Nf, lonf, k0 As Double
lon0 = Point.X
lat0 = Point.Y
E0 = Point.X
N0 = Point.Y
lonf = Projection.LongOrigin
latf = 0
Ef = Projection.FalseEasting
Nf = Projection.FalseNorthing
k0 = Projection.OriginScale
'Projection costant
Dim X, t As Double
Dim A1, A2, A3, A4 As Double
A1 = (e ^ 2 / 2) + (5 * e ^ 4 / 24) + (e ^ 6 / 12) + (13 * e ^ 8 / 360)
A2 = (7 * e ^ 4 / 48) + (29 * e ^ 6 / 240) + (811 * e ^ 8 / 11520)
A3 = (7 * e ^ 6 / 120) + (81 * e ^ 8 / 1120)
A4 = (4279 * e ^ 8 / 161280)
If IsInverse Then
'From EN to LL
t = Math.E ^ ((Nf - N0) / (a * k0))
X = PI / 2 - 2 * Atan(t)
Merc.Y = X + A1 * Sin(2 * X) + A2 * Sin(4 * X) + A3 * Sin(6 * X) + A4 * Sin(8 * X)
Merc.X = ((E0 - Ef) / a * k0) + lonf
Merc.Z = Point.Z
Else
'From LL to EN
Merc.X = Ef + a * k0 * (lon0 - lonf)
Merc.Y = Nf + a * k0 * Log(Tan(PI / 4 + lat0 / 2) * ((1 - e * Sin(lat0)) / (1 + e * Sin(lat0))) * (e / 2))
Merc.Z = Point.Z
End If
End Function
'Forward and inverse projection formula for Lambert Conic Conformal with 1 standard parallel
Private Function LCC1(ByVal Ellipsoid As Ellipsoid, ByVal Projection As Projection, ByVal Point As Point3D, _
ByVal IsInverse As Boolean) As Point3D
Dim f As Double
If Ellipsoid.InvFlattening = 0 Then
f = 1
Else
f = 1 / Ellipsoid.InvFlattening
End If
Dim a As Double = Ellipsoid.SemiMayorAxis
Dim b As Double = (1 - f) * a
Dim e As Double = Sqrt(2 * f - f ^ 2)
Dim secEcc As Double = Sqrt(e ^ 2 / (1 - e ^ 2))
Dim lat0, latf, Ef, Nf, lon0, lonf, k0 As Double
lon0 = Point.X
lat0 = Point.Y
latf = Projection.LatOrigin
lonf = Projection.LongOrigin
Ef = Projection.FalseEasting
Nf = Projection.FalseNorthing
k0 = Projection.OriginScale
Dim theta, thetai, Mo, Tf, T0, Ff, Rf, R0, Ti, Ri, n As Double
If IsInverse Then
'From EN to LL
Mo = Cos(latf) / Sqrt(1 - e ^ 2 * Sin(latf) ^ 2)
Tf = Tan(PI / 4 - latf / 2) / ((1 - e * Sin(latf)) / (1 + e * Sin(latf))) ^ (e / 2)
n = Sin(latf)
Ff = Mo / (n * Tf ^ n)
Rf = a * f * Tf ^ n
If n > 0 Then
Ri = Abs(((lon0 - Ef) ^ 2 + (Rf - (lat0 - Nf)) ^ 2) ^ 0.5)
Else
Ri = -Abs(((lon0 - Ef) ^ 2 + (Rf - (lat0 - Nf)) ^ 2) ^ 0.5)
End If
Ti = (Ri / (a * k0 * Ff)) ^ (1 / n)
Dim tmplat As Double = PI / 2 - 2 * Atan(Ti)
For i = 0 To 100
tmplat = PI / 2 - 2 * Atan(Ti * ((1 - e * Sin(tmplat)) / (1 + e * Sin(tmplat))) ^ (e / 2))
Next
thetai = Atan((lon0 - Ef) / (Rf - (lat0 - Nf)))
'Return the results
LCC1.X = thetai / n + lonf
LCC1.Y = tmplat
LCC1.Z = Point.Z
Else
'From LL to EN
Mo = Cos(latf) / Sqrt(1 - e ^ 2 * Sin(latf) ^ 2)
T0 = Tan(PI / 4 - lat0 / 2) / ((1 - e * Sin(lat0)) / (1 + e * Sin(lat0))) ^ (e / 2)
Tf = Tan(PI / 4 - latf / 2) / ((1 - e * Sin(latf)) / (1 + e * Sin(latf))) ^ (e / 2)
n = Sin(latf)
Ff = Mo / (n * Tf ^ n)
Rf = a * Ff * Tf ^ n * k0
R0 = a * Ff * T0 ^ n * k0
theta = n * (lon0 - lonf)
'Return the results
LCC1.X = Ef + R0 * Sin(theta)
LCC1.Y = Nf + Rf - R0 * Cos(theta)
LCC1.Z = Point.Z
End If
End Function
'Forward and inverse projection formula for Lambert Conic Conformal with 2 standard parallels
Private Function LCC2(ByVal Ellipsoid As Ellipsoid, ByVal Projection As Projection, ByVal Point As Point3D, _
ByVal IsInverse As Boolean) As Point3D
Dim Flattening As Double
If Ellipsoid.InvFlattening = 0 Then
Flattening = 1
Else
Flattening = 1 / Ellipsoid.InvFlattening
End If
Dim a As Double = Ellipsoid.SemiMayorAxis
Dim b As Double = (1 - Flattening) * a
Dim e As Double = Sqrt(2 * Flattening - Flattening ^ 2)
Dim secEcc As Double = Sqrt(e ^ 2 / (1 - e ^ 2))
Dim lat0, lat1, lat2, latf, Ef, Nf, lon0, lonf As Double
Dim theta, Rf, m1, m2, t0, t1, t2, tf, n, F, r, Ri As Double
lon0 = Point.X
lat0 = Point.Y
lat1 = Projection.FirstParallel
lat2 = Projection.SecondParallel
latf = Projection.LatOrigin
lonf = Projection.LongOrigin
Ef = Projection.FalseEasting
Nf = Projection.FalseNorthing
If IsInverse Then
'From EN to LL
m1 = Cos(lat1) / Sqrt(1 - e ^ 2 * Sin(lat1) ^ 2)
m2 = Cos(lat2) / Sqrt(1 - e ^ 2 * Sin(lat2) ^ 2)
t1 = Tan(PI / 4 - lat1 / 2) / ((1 - e * Sin(lat1)) / (1 + e * Sin(lat1))) ^ (e / 2)
t2 = Tan(PI / 4 - lat2 / 2) / ((1 - e * Sin(lat2)) / (1 + e * Sin(lat2))) ^ (e / 2)
tf = Tan(PI / 4 - latf / 2) / ((1 - e * Sin(latf)) / (1 + e * Sin(latf))) ^ (e / 2)
n = (Log(m1) - Log(m2)) / (Log(t1) - Log(t2))
F = m1 / (n * t1 ^ n)
Rf = a * F * tf ^ n
If n > 0 Then
Ri = Abs(((lon0 - Ef) ^ 2 + (Rf - (lat0 - Nf)) ^ 2) ^ 0.5)
Else
Ri = -Abs(((lon0 - Ef) ^ 2 + (Rf - (lat0 - Nf)) ^ 2) ^ 0.5)
End If
t0 = (Ri / (a * F)) ^ (1 / n)
Dim tmplat As Double = PI / 2 - 2 * Atan(t0)
For i = 0 To 100
tmplat = PI / 2 - 2 * Atan(t0 * ((1 - e * Sin(tmplat)) / (1 + e * Sin(tmplat))) ^ (e / 2))
Next
Dim thetainv As Double = Atan((lon0 - Ef) / (Rf - (lat0 - Nf)))
'Return the results
LCC2.X = thetainv / n + lonf
LCC2.Y = tmplat
LCC2.Z = Point.Z
Else
'From LL to EN
m1 = Cos(lat1) / Sqrt(1 - e ^ 2 * Sin(lat1) ^ 2)
m2 = Cos(lat2) / Sqrt(1 - e ^ 2 * Sin(lat2) ^ 2)
t0 = Tan(PI / 4 - lat0 / 2) / ((1 - e * Sin(lat0)) / (1 + e * Sin(lat0))) ^ (e / 2)
t1 = Tan(PI / 4 - lat1 / 2) / ((1 - e * Sin(lat1)) / (1 + e * Sin(lat1))) ^ (e / 2)
t2 = Tan(PI / 4 - lat2 / 2) / ((1 - e * Sin(lat2)) / (1 + e * Sin(lat2))) ^ (e / 2)
tf = Tan(PI / 4 - latf / 2) / ((1 - e * Sin(latf)) / (1 + e * Sin(latf))) ^ (e / 2)
n = (Log(m1) - Log(m2)) / (Log(t1) - Log(t2))
F = m1 / (n * t1 ^ n)
r = a * F * t0 ^ n
theta = n * (lon0 - lonf)
Rf = a * F * tf ^ n
'Return the results
LCC2.X = Ef + r * Sin(theta)
LCC2.Y = Nf + Rf - r * Cos(theta)
LCC2.Z = Point.Z
End If
End Function
End Module
|
Public Class Cls_XML
''' <summary>
''' อ่าน ค่า XML
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function ReadXml(ByVal path As String) As String
Dim StrData As String
Dim objXMLDoc As New System.Xml.XmlDocument()
objXMLDoc.Load(path) 'xml data I need to send
StrData = objXMLDoc.OuterXml
Return StrData
End Function
Public doc As New System.Xml.XmlDocument
''' <summary>
''' แปลงค่า Content XML
''' </summary>
''' <param name="content"></param>
''' <remarks></remarks>
Public Sub ReadData(ByVal content As String)
Dim xmltxt As String = ""
Dim xmlStream As New System.IO.MemoryStream()
' Dim doc As New System.Xml.XmlDocument
doc.LoadXml(content)
'Dim item_P_ID As String = ""
'item_P_ID = Get_Value_Node(doc, "Txt_Remark")
'Label1.Text = item_P_ID
'xmltxt = GetValue_XML(doc, "Information")
End Sub
''' <summary>
''' ดึงค่า Value จาก XML ออกมาตัวเดียว
''' </summary>
''' <param name="TagName">ชื่อ XML</param>
''' <returns></returns>
''' <remarks></remarks>
Public Function Get_Value_XML(ByVal TagName As String) As String
Dim value As String = ""
Dim item_Node As System.Xml.XmlNodeList = doc.GetElementsByTagName(TagName)
For Each item As System.Xml.XmlElement In item_Node
value = item.InnerText
Next
Return value
End Function
''' <summary>
''' ดึงค่า XML ใน Tag ทั้งหมด
''' </summary>
''' <param name="Element">Tag XML</param>
''' <returns></returns>
''' <remarks></remarks>
Public Function Get_ListValue_XML(ByVal Element As String) As String
Dim items As System.Xml.XmlNodeList = doc.GetElementsByTagName(Element)
Dim temp As String = ""
Dim name As String = ""
For Each item As System.Xml.XmlElement In items
For i As Integer = 0 To item.ChildNodes.Count - 1
If temp = "" Then
temp = item.ChildNodes(i).InnerText
Else
temp = temp & "^" & item.ChildNodes(i).InnerText
End If
Next
Next
Return temp
End Function
End Class
|
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports MB.TheBeerHouse.DAL
Namespace MB.TheBeerHouse.BLL.Articles
Public Class Category
Inherits BaseArticle
' ==========
' Private Variables
' ==========
Private _title As String = ""
Private _importance As Integer = 0
Private _description As String = ""
Private _imageUrl As String = ""
Private _allArticles As List(Of Article) = Nothing
Private _publishedArticles As List(Of Article) = Nothing
' ==========
' Properties
' ==========
Public Property Title() As String
Get
Return _title
End Get
Set(ByVal value As String)
_title = value
End Set
End Property
Public Property Importance() As Integer
Get
Return _importance
End Get
Set(ByVal value As Integer)
_importance = value
End Set
End Property
Public Property Description() As String
Get
Return _description
End Get
Set(ByVal value As String)
_description = value
End Set
End Property
Public Property ImageUrl() As String
Get
Return _imageUrl
End Get
Set(ByVal value As String)
_imageUrl = value
End Set
End Property
Public ReadOnly Property AllArticles() As List(Of Article)
Get
If IsNothing(_allArticles) Then
_allArticles = Article.GetArticles(Me.ID, 0, BizObject.MAXROWS)
End If
Return _allArticles
End Get
End Property
Public ReadOnly Property PublishedArticles() As List(Of Article)
Get
If IsNothing(_publishedArticles) Then
_publishedArticles = Article.GetArticles(True, Me.ID, 0, BizObject.MAXROWS)
End If
Return _publishedArticles
End Get
End Property
' ===========
' Constructor
' ===========
Public Sub New(ByVal id As Integer, ByVal addedDate As DateTime, ByVal addedBy As String, ByVal title As String, ByVal importance As Integer, ByVal description As String, ByVal imageUrl As String)
Me.ID = id
Me.AddedDate = addedDate
Me.AddedBy = addedBy
Me.Title = title
Me.Importance = importance
Me.Description = description
Me.ImageUrl = imageUrl
End Sub
' ==========
' Methods
' ==========
Public Function Delete() As Boolean
Dim success As Boolean = Category.DeleteCategory(Me.ID)
If success Then
Me.ID = 0
End If
Return success
End Function
Public Function Update() As Boolean
Return Category.UpdateCategory(Me.ID, Me.Title, Me.Importance, Me.Description, Me.ImageUrl)
End Function
' ==========
' Shared methods
' ==========
' Returns a collection with all the categories
Public Shared Function GetCategories() As List(Of Category)
Dim categories As List(Of Category) = Nothing
Dim key As String = "Articles_Categories"
If BaseArticle.Settings.EnableCaching AndAlso Not IsNothing(BizObject.Cache(key)) Then
categories = CType(BizObject.Cache(key), List(Of Category))
Else
Dim recordset As List(Of CategoryDetails) = SiteProvider.Articles.GetCategories
categories = GetCategoryListFromCategoryDetailsList(recordset)
BaseArticle.CacheData(key, categories)
End If
Return categories
End Function
' Returns a Category object with the specified ID
Public Shared Function GetCategoryByID(ByVal categoryID As Integer) As Category
Dim m_category As Category = Nothing
Dim key As String = "Articles_Category_" + categoryID.ToString()
If BaseArticle.Settings.EnableCaching AndAlso Not IsNothing(BizObject.Cache(key)) Then
m_category = CType(BizObject.Cache(key), Category)
Else
m_category = GetCategoryFromCategoryDetails( _
SiteProvider.Articles.GetCategoryByID(categoryID))
BaseArticle.CacheData(key, m_category)
End If
Return m_category
End Function
' Updates an existing category
Public Shared Function UpdateCategory( _
ByVal id As Integer, ByVal title As String, ByVal importance As Integer, _
ByVal description As String, ByVal imageUrl As String) _
As Boolean
Dim record As New CategoryDetails( _
id, DateTime.Now, "", title, importance, description, imageUrl)
Dim ret As Boolean = SiteProvider.Articles.UpdateCategory(record)
BizObject.PurgeCacheItems("articles_categor")
Return ret
End Function
' Deletes an existing category
Public Shared Function DeleteCategory(ByVal id As Integer) As Boolean
Dim ret As Boolean = SiteProvider.Articles.DeleteCategory(id)
Dim ev As New RecordDeletedEvent("category", id, Nothing)
ev.Raise()
BizObject.PurgeCacheItems("articles_categor")
Return ret
End Function
' Creates a new category
Public Shared Function InsertCategory( _
ByVal title As String, ByVal importance As Integer, _
ByVal description As String, ByVal imageUrl As String) _
As Integer
Dim record As New CategoryDetails( _
0, DateTime.Now, BizObject.CurrentUserName, title, importance, description, imageUrl)
Dim ret As Integer = SiteProvider.Articles.InsertCategory(record)
BizObject.PurgeCacheItems("articles_categor")
Return ret
End Function
' Returns a Category object filled with the data taken from the input CategoryDetails
Public Shared Function GetCategoryFromCategoryDetails(ByVal record As CategoryDetails) As Category
If IsNothing(record) Then
Return Nothing
Else
Return New Category(record.ID, record.AddedDate, record.AddedBy, _
record.Title, record.Importance, record.Description, record.ImageURL)
End If
End Function
' Returns a list of Category objects filled with the data taken from the input list of CategoryDetails
Public Shared Function GetCategoryListFromCategoryDetailsList( _
ByVal recordset As List(Of CategoryDetails)) _
As List(Of Category)
Dim categories As New List(Of Category)
For Each record As CategoryDetails In recordset
categories.Add(GetCategoryFromCategoryDetails(record))
Next
Return categories
End Function
End Class
End Namespace
|
Public Class Consumer
Public Id As String
Private SourceLog As Log
Private Offset As Long
Public Sub New(id As String, sourceLog As Log)
Me.Id = id
Me.SourceLog = sourceLog
End Sub
Public Async Function ExecuteAsync() As Task
Dim command As Command
Dim message As String
Me.Offset = Await Log.GetConsumerOffset(Me.Id)
For i As Long = Me.Offset + 1L To Me.SourceLog.LogOffset
message = Me.SourceLog.GetMessage(i)
command = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Command)(message)
Await Me.ExecuteCommand(command)
Await Log.SetConsumerOffset(Me.Id, i)
Next
End Function
Private Function ExecuteCommand(command As Command) As Task
Select Case command.CommandType
Case Command.CommandTypeE.SendElectronicMailing
Return ExecuteElectronicMailingAsync(command)
End Select
Return Task.CompletedTask
End Function
Private Async Function ExecuteElectronicMailingAsync(command As Command) As Task
Dim emailing As ElectronicMailing
emailing = Newtonsoft.Json.JsonConvert.DeserializeObject(Of ElectronicMailing)(command.State.ToString)
Await emailing.InitializeAsync
Await emailing.ExecuteAsync
End Function
End Class
|
Public Class GpsSource
Implements IGpsSource
Private _port As New IO.Ports.SerialPort
Private _thread As New Threading.Thread(AddressOf ReadThread)
Public Event GpsUpdate(data As GpsData, raw As String) Implements IGpsSource.GpsUpdate
Private Sub ReadThread()
Do
Try
If _port.IsOpen Then
Dim line = _port.ReadLine()
If line.StartsWith("$GPRMC,") Then
Dim data = NmeaTools.DecodeGprmc(line)
RaiseEvent GpsUpdate(data, line)
End If
End If
Catch ex As Exception
End Try
Threading.Thread.Sleep(1)
Loop
End Sub
Public Sub New()
_thread.IsBackground = True
_thread.Start()
End Sub
Public Sub Open() Implements IGpsSource.Open
_port.BaudRate = 115200
_port.PortName = IO.Ports.SerialPort.GetPortNames(0)
_port.Open()
End Sub
End Class
|
Option Strict Off
Option Explicit On
Friend Class threeDGrapher
' this class is responsible for maintaining a
' 3d graph. It needs to keep track of the current
' viewing angles. An object calls the draw object
' method to draw a particular object. Note that
' the object (i.e. a line) to be drawn should give
' this method the object as viewed at 0 degrees vert.
' and 0 degrees horizontal. Use the line class.
Private refX As Integer ' tells us the reference point from
Private refY As Integer ' which everything is drawn
Private theGraph As System.Windows.Forms.PictureBox
Private vertAngle As Short
Private horAngle As Short
Private myScale As Double
Private mvarPyramid As PltPyramid
Public Property Pyramid() As PltPyramid
Get
If mvarPyramid Is Nothing Then
mvarPyramid = New PltPyramid
End If
Pyramid = mvarPyramid
End Get
Set(ByVal Value As PltPyramid)
mvarPyramid = Value
End Set
End Property
'UPGRADE_NOTE: Class_Terminate was upgraded to Class_Terminate_Renamed. Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"'
Private Sub Class_Terminate_Renamed()
'UPGRADE_NOTE: Object mvarPyramid may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
mvarPyramid = Nothing
End Sub
Protected Overrides Sub Finalize()
Class_Terminate_Renamed()
MyBase.Finalize()
End Sub
' this method simply tells this class what surface to
' draw on
Public Sub setDrawSurface(ByRef surface As System.Windows.Forms.PictureBox, ByRef X As Double, ByRef Y As Double, ByRef Incremental As Boolean)
theGraph = surface
'Dim x As Double
'Dim y As Double
If X = 0# And Y = 0# Then
X = VB6.PixelsToTwipsX(theGraph.Width)
Y = VB6.PixelsToTwipsY(theGraph.Height)
X = X / 2
Y = Y / 2
refX = X
refY = Y / 2
ElseIf Not Incremental Then
refX = X
refY = Y
Else
refX = refX + X
refY = refY + Y
End If
End Sub
' This method draws a line. It needs to take into
' acct the viewing angles and all that good stuff
Public Sub drawTheLine(ByVal aline As threeDLine, Optional ByRef scaleIt As Boolean = False)
' need to draw a line given the current view
'UPGRADE_NOTE: IsMissing() was changed to IsNothing(). Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="8AE1CB93-37AB-439A-A4FF-BE3B6760BB23"'
If IsNothing(scaleIt) Then
scaleIt = True
End If
Dim xt1 As Double
Dim xt2 As Double
Dim yt1 As Double
Dim yt2 As Double
Dim zt1 As Double
Dim zt2 As Double
Dim x1 As Double
Dim x2 As Double
Dim y1 As Double
Dim y2 As Double
Dim aColor As Integer
Dim lineLength As Double
aline.getCoords(xt1, yt1, zt1, xt2, yt2, zt2)
aColor = aline.getColor
'' test added
'yt1 = -yt1
'yt2 = -yt2
' end test added
' calculate along the "3d x axis first"
Dim vRads As Double
Dim hRads As Double
vRads = vertAngle * 3.1415927 / 180
hRads = horAngle * 3.1415927 / 180
' we solve for the 3d x coordinates of the start
' and finish point for the line.
x1 = xt1 * System.Math.Cos(hRads)
y1 = xt1 * System.Math.Sin(vRads) * System.Math.Sin(hRads) ' - Cos(hRads)
x2 = xt2 * System.Math.Cos(hRads)
y2 = xt2 * System.Math.Sin(vRads) * System.Math.Sin(hRads) ' - Cos(hRads)
' we have translated the x coords of the 3d graph
' onto the 2d graph. Now we need to account for
' the y coord. This will add on to X1 and X2
' x0 and y0 are just intermediate numbers, they will
' need to be added to X1, Y1, X2, and Y2. Just for
' cleanliness
Dim X0 As Double
Dim Y0 As Double
X0 = yt1 * System.Math.Sin(hRads)
x1 = X0 + x1
X0 = yt2 * System.Math.Sin(hRads)
x2 = X0 + x2
Y0 = yt1 * System.Math.Sin(vRads) * System.Math.Cos(hRads)
y1 = y1 - Y0
Y0 = yt2 * System.Math.Sin(vRads) * System.Math.Cos(hRads)
y2 = y2 - Y0
' we now need to account for the z axis. This is
' pretty simply as the z axis will never be tilted
' at an angle. It will always be straight up and
' down. Of course, you can view it from above and
' at various angles. So only affected coordinate
' will be the y coordinate
Y0 = zt1 * System.Math.Cos(vRads)
y1 = y1 - Y0
Y0 = zt2 * System.Math.Cos(vRads)
y2 = y2 - Y0
' scales the lines and actually draws the calculated
' line to the graph
Dim theScale As Double
'If scaleIt = True Then
' theScale = myScale
'Else
' theScale = 1
'endif
x1 = myScale * x1 + refX
y1 = myScale * y1 + refY
x2 = myScale * x2 + refX
y2 = myScale * y2 + refY
'UPGRADE_ISSUE: PictureBox method theGraph.Line was not upgraded. Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
'theGraph.Line (x1, y1) - (x2, y2), aColor
End Sub
'UPGRADE_NOTE: Class_Initialize was upgraded to Class_Initialize_Renamed. Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"'
Private Sub Class_Initialize_Renamed()
vertAngle = 0
horAngle = 0
myScale = 3
refX = 0
refY = 0
End Sub
Public Sub New()
MyBase.New()
Class_Initialize_Renamed()
End Sub
Public Sub newAngles(ByVal H As Short, ByVal V As Short)
horAngle = H
vertAngle = V
End Sub
Public Sub clearGraph()
'UPGRADE_ISSUE: PictureBox method theGraph.Cls was not upgraded. Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
theGraph.Cls()
End Sub
Public Function changeScale(ByVal changeInScale As Double) As Boolean
Dim newScale As Double
newScale = myScale * changeInScale
If (newScale <= 0) Or (newScale > 250) Then
changeScale = False
Else
myScale = newScale
changeScale = True
End If
End Function
Public Sub drawRect(ByVal aRect As threeDRect, Optional ByRef Filler As Boolean = False)
'UPGRADE_NOTE: IsMissing() was changed to IsNothing(). Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="8AE1CB93-37AB-439A-A4FF-BE3B6760BB23"'
If IsNothing(Filler) Then
Filler = False
End If
drawTheLine(aRect.Length1)
drawTheLine(aRect.Length2)
drawTheLine(aRect.Width1)
drawTheLine(aRect.Width2)
If Filler = True Then
fillRect(aRect)
End If
End Sub
Public Sub drawBox(ByVal aBox As PltBox3d)
drawRect(aBox.Bottom)
drawRect(aBox.side1)
drawRect(aBox.side2)
drawRect(aBox.Top)
drawTheLine(aBox.Line1)
drawTheLine(aBox.Line2)
drawTheLine(aBox.Line4)
drawTheLine(aBox.Line3)
End Sub
Public Sub drawOctagon(ByRef anOct As PltOctagon3d, Optional ByRef fillMe As Boolean = False)
Dim counter As Short
Dim Line1 As threeDLine
Dim Line2 As threeDLine
Dim Line3 As threeDLine
'UPGRADE_NOTE: IsMissing() was changed to IsNothing(). Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="8AE1CB93-37AB-439A-A4FF-BE3B6760BB23"'
If IsNothing(fillMe) Then
fillMe = False
End If
Dim oct2 As PltOctagon3d
Dim L As Double
If fillMe = True Then
oct2 = New PltOctagon3d
L = anOct.theLength
L = L - 10
Do While L > 0
oct2.createOctagon(L, (anOct.theHeight), (anOct.X), (anOct.Y), (anOct.z))
counter = 1
Do While counter <= 8
oct2.getLines(Line1, Line2, Line3, counter)
Line1.setColor(System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White))
Line2.setColor(System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White))
Line3.setColor(System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White))
drawTheLine(Line1)
drawTheLine(Line2)
drawTheLine(Line3)
counter = counter + 1
Loop
L = L - 10
Loop
End If
counter = 1
Do While counter <= 8
anOct.getLines(Line1, Line2, Line3, counter)
drawTheLine(Line1)
drawTheLine(Line2)
drawTheLine(Line3)
counter = counter + 1
Loop
End Sub
Public Function zoomPercent() As Double
zoomPercent = myScale / 2 * 100
End Function
' this method puts the dimensions of the graph it is
' drawing on into the arguments it is passed
Public Sub getPictureDim(ByRef width As Short, ByRef Length As Short)
Dim Height As Object
width = VB6.PixelsToTwipsX(theGraph.Width)
'UPGRADE_WARNING: Couldn't resolve default property of object Height. Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
Height = VB6.PixelsToTwipsY(theGraph.Height)
End Sub
Public Sub fillgraph()
Dim X As Short
X = 0
Do While X < VB6.PixelsToTwipsX(theGraph.Width)
'UPGRADE_ISSUE: PictureBox method theGraph.Line was not upgraded. Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
'theGraph.Line (X, 0) - (X, VB6.PixelsToTwipsY(theGraph.Height))
X = X + 1
' Debug.Print X
Loop
End Sub
Private Sub fillRect(ByRef aRect As threeDRect)
Dim X0 As Double
Dim Y0 As Double
Dim z0 As Double
Dim x1 As Double
Dim y1 As Double
Dim z1 As Double
Dim x2 As Double
Dim y2 As Double
Dim z2 As Double
Dim x3 As Double
Dim y3 As Double
Dim z3 As Double
aRect.Width1.getCoords(X0, Y0, z0, x1, y1, z1)
aRect.Width2.getCoords(x2, y2, z2, x3, y3, z3)
Dim newLine As threeDLine
newLine = New threeDLine
'x0 = x0 * myScale
'y0 = y0 * myScale
'z0 = z0 * myScale
'x1 = x1 * myScale
'y1 = y1 * myScale
'z1 = z1 * myScale
'x2 = x2 * myScale
'y2 = y2 * myScale
'z2 = z2 * myScale
'x3 = x3 * myScale
'y3 = y3 * myScale
'z3 = z3 * myScale
newLine.setColor(System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White))
Do While X0 < x2
X0 = X0 + 5
x1 = x1 + 5
newLine.setCoords(X0, Y0, z0, x1, y1, z1)
drawTheLine(newLine) ', False
Loop
End Sub
Private Sub fillOctagon(ByRef anOct As PltOctagon3d)
Dim Line1 As threeDLine
Dim Line2 As threeDLine
Dim Line3 As threeDLine
anOct.getLines(Line1, Line2, Line2, 1)
anOct.getLines(Line2, Line3, Line3, 2)
Dim X0 As Double
Dim Y0 As Double
Dim z0 As Double
Dim x1 As Double
Dim y1 As Double
Dim z1 As Double
Dim x2 As Double
Dim y2 As Double
Dim z2 As Double
Dim x3 As Double
Dim y3 As Double
Dim z3 As Double
Dim slope As Double
Dim deltaY As Double
Dim deltaX As Double
Dim newX As Double
Dim newY0 As Double
Dim newY1 As Double
deltaX = 1
anOct.getLines(Line3, Line1, Line3, 1)
anOct.getLines(Line3, Line2, Line3, 2)
Line1.getCoords(X0, Y0, z0, x1, y1, z1)
Line2.getCoords(x2, y2, z2, x3, y3, z3)
slope = System.Math.Abs((y3 - y2) / (x3 - x2))
deltaY = slope * deltaX
newX = X0 + deltaX
newY0 = Y0 - deltaY
newY1 = y1 + deltaY
Do While newX < x3
Line1.setCoords(newX, newY0, z0, newX, newY1, z1)
Line1.setColor(System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White))
drawTheLine(Line1)
newX = newX + deltaX
newY0 = newY0 - deltaY
newY1 = newY1 + deltaY
Loop
End Sub
End Class |
Public Class PopupHelper
Public Function ShowInputBox(ByVal strPrompt As String, Optional ByVal intTYpe As Int32 = 1, Optional ByVal strTitle As String = "", Optional ByVal StrDefault As String = "") As String
Dim oPopup As New ApplicationMessageBox
oPopup.Prompt = strPrompt
oPopup.Type = intTYpe
If strTitle <> "" Then
oPopup.Title = strTitle
End If
If intTYpe = 4 Then
'StrDefault Is Used For ComboBox Values
oPopup.Choices = StrDefault
Else
If StrDefault <> "" Then
oPopup.DefaultValue = StrDefault
End If
End If
oPopup.ShowDialog()
Return oPopup.DefaultValue
End Function
Public Function ShowMessageBox(ByVal strPrompt As String, Optional ByVal intTYpe As Int32 = 1, Optional ByVal strTitle As String = "") As String
Dim oPopup As New ApplicationMessageBox
oPopup.Prompt = strPrompt
oPopup.Type = intTYpe
If strTitle <> "" Then
oPopup.Title = strTitle
End If
oPopup.ShowDialog()
Return oPopup.DefaultValue
End Function
End Class
|
'
' Created by SharpDevelop.
' User: Admin
' Date: 02/01/2007
' Time: 23:16
'
' To change this template use Tools | Options | Coding | Edit Standard Headers.
'
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Namespace q
Public Class FrmConfirm
Inherits System.Windows.Forms.Form
Public LblText As System.Windows.Forms.Label
Public BtnOui As System.Windows.Forms.Button
Public BtnNon As System.Windows.Forms.Button
Public Sub New()
MyBase.New
'
' The Me.InitializeComponent call is required for Windows Forms designer support.
'
Me.InitializeComponent
'
' TODO : Add constructor code after InitializeComponents
'
End Sub
#Region " Windows Forms Designer generated code "
' This method is required for Windows Forms designer support.
' Do not change the method contents inside the source code editor. The Forms designer might
' not be able to load this method if it was changed manually.
Private Sub InitializeComponent()
Me.BtnNon = New System.Windows.Forms.Button
Me.BtnOui = New System.Windows.Forms.Button
Me.LblText = New System.Windows.Forms.Label
Me.SuspendLayout
'
'BtnNon
'
Me.BtnNon.DialogResult = System.Windows.Forms.DialogResult.No
Me.BtnNon.Font = New System.Drawing.Font("Tahoma", 15.75!, System.Drawing.FontStyle.Bold)
Me.BtnNon.Location = New System.Drawing.Point(232, 112)
Me.BtnNon.Name = "BtnNon"
Me.BtnNon.Size = New System.Drawing.Size(110, 42)
Me.BtnNon.TabIndex = 1
Me.BtnNon.Text = "Non"
AddHandler Me.BtnNon.Click, AddressOf Me.BtnNonClick
'
'BtnOui
'
Me.BtnOui.BackColor = System.Drawing.SystemColors.Control
Me.BtnOui.DialogResult = System.Windows.Forms.DialogResult.Yes
Me.BtnOui.Font = New System.Drawing.Font("Tahoma", 15.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0,Byte))
Me.BtnOui.ForeColor = System.Drawing.SystemColors.ControlText
Me.BtnOui.Location = New System.Drawing.Point(16, 112)
Me.BtnOui.Name = "BtnOui"
Me.BtnOui.Size = New System.Drawing.Size(110, 40)
Me.BtnOui.TabIndex = 0
Me.BtnOui.Text = "Oui"
'
'LblText
'
Me.LblText.Font = New System.Drawing.Font("Tahoma", 12!, System.Drawing.FontStyle.Bold)
Me.LblText.Location = New System.Drawing.Point(16, 16)
Me.LblText.Name = "LblText"
Me.LblText.Size = New System.Drawing.Size(328, 80)
Me.LblText.TabIndex = 2
Me.LblText.Text = "LblText"
Me.LblText.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
'
'FrmConfirm
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 14)
Me.ClientSize = New System.Drawing.Size(354, 167)
Me.ControlBox = false
Me.Controls.Add(Me.LblText)
Me.Controls.Add(Me.BtnNon)
Me.Controls.Add(Me.BtnOui)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
Me.Name = "FrmConfirm"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "FrmConfirm"
Me.TopMost = true
Me.ResumeLayout(false)
End Sub
#End Region
Private Sub BtnNonClick(sender As System.Object, e As System.EventArgs)
Me.close
End Sub
End Class
End Namespace
|
Public Class Comprobante
#Region "VARIABLES"
Private mensajesValue As New List(Of Mensaje)
Private claveAccesoValue As String = String.Empty
#End Region
#Region "PROPERTIES"
Public Property ClaveAcceso() As String
Get
Return claveAccesoValue
End Get
Set(ByVal value As String)
claveAccesoValue = value
End Set
End Property
Public Property Mensajes() As List(Of Mensaje)
Get
Return mensajesValue
End Get
Set(ByVal value As List(Of Mensaje))
mensajesValue = value
End Set
End Property
#End Region
End Class
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class FrmMaterialAndSubMaterial
Inherits DevExpress.XtraEditors.XtraForm
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(FrmMaterialAndSubMaterial))
Me.grpInput = New System.Windows.Forms.GroupBox()
Me.Label4 = New System.Windows.Forms.Label()
Me.txtMonthStd = New System.Windows.Forms.TextBox()
Me.lblNormWeek = New System.Windows.Forms.Label()
Me.txtWeekStd = New System.Windows.Forms.TextBox()
Me.lblSubPrc = New System.Windows.Forms.Label()
Me.lblAddDtbtQty = New System.Windows.Forms.Label()
Me.txtAddDtbtQty = New System.Windows.Forms.TextBox()
Me.lblStdDtbtQty = New System.Windows.Forms.Label()
Me.txtStdDtbtQty = New System.Windows.Forms.TextBox()
Me.lblMinQty = New System.Windows.Forms.Label()
Me.txtMinQty = New System.Windows.Forms.TextBox()
Me.lblUnit = New System.Windows.Forms.Label()
Me.txtUnit = New System.Windows.Forms.TextBox()
Me.lblVJName = New System.Windows.Forms.Label()
Me.txtJVName = New System.Windows.Forms.TextBox()
Me.lblJEName = New System.Windows.Forms.Label()
Me.txtJEName = New System.Windows.Forms.TextBox()
Me.lblJCode = New System.Windows.Forms.Label()
Me.txtJCode = New System.Windows.Forms.TextBox()
Me.cboSubPrc = New System.Windows.Forms.ComboBox()
Me.lblECode = New System.Windows.Forms.Label()
Me.txtECode = New System.Windows.Forms.TextBox()
Me.mnuDelete = New System.Windows.Forms.ToolStripButton()
Me.mnuExport = New System.Windows.Forms.ToolStripButton()
Me.tlsMenu = New System.Windows.Forms.ToolStrip()
Me.mnuNew = New System.Windows.Forms.ToolStripButton()
Me.mnuEdit = New System.Windows.Forms.ToolStripButton()
Me.mnuShowAll = New System.Windows.Forms.ToolStripButton()
Me.mnuSave = New System.Windows.Forms.ToolStripButton()
Me.ToolStripSeparator1 = New System.Windows.Forms.ToolStripSeparator()
Me.mnuImport = New System.Windows.Forms.ToolStripButton()
Me.mnuUpdateEmpID = New System.Windows.Forms.ToolStripButton()
Me.ToolStripSeparator2 = New System.Windows.Forms.ToolStripSeparator()
Me.grpGrid = New System.Windows.Forms.GroupBox()
Me.GridControl1 = New DevExpress.XtraGrid.GridControl()
Me.GridView1 = New DevExpress.XtraGrid.Views.Grid.GridView()
Me.Label1 = New System.Windows.Forms.Label()
Me.txtOldID = New System.Windows.Forms.TextBox()
Me.txtNewID = New System.Windows.Forms.TextBox()
Me.Label2 = New System.Windows.Forms.Label()
Me.Label3 = New System.Windows.Forms.Label()
Me.bttOK = New System.Windows.Forms.Button()
Me.DataGridViewTextBoxColumn3 = New System.Windows.Forms.DataGridViewTextBoxColumn()
Me.DataGridViewAutoFilterTextBoxColumn8 = New DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn()
Me.DataGridViewAutoFilterTextBoxColumn5 = New DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn()
Me.DataGridViewAutoFilterTextBoxColumn7 = New DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn()
Me.DataGridViewAutoFilterTextBoxColumn4 = New DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn()
Me.DataGridViewAutoFilterTextBoxColumn3 = New DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn()
Me.DataGridViewTextBoxColumn2 = New System.Windows.Forms.DataGridViewTextBoxColumn()
Me.DataGridViewAutoFilterTextBoxColumn2 = New DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn()
Me.DataGridViewAutoFilterTextBoxColumn6 = New DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn()
Me.DataGridViewAutoFilterTextBoxColumn1 = New DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn()
Me.DataGridViewTextBoxColumn4 = New System.Windows.Forms.DataGridViewTextBoxColumn()
Me.DataGridViewTextBoxColumn1 = New System.Windows.Forms.DataGridViewTextBoxColumn()
Me.DataGridViewAutoFilterTextBoxColumn9 = New DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn()
Me.CalendarColumn1 = New UtilityControl.CalendarColumn()
Me.grpInput.SuspendLayout()
Me.tlsMenu.SuspendLayout()
Me.grpGrid.SuspendLayout()
CType(Me.GridControl1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.GridView1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'grpInput
'
Me.grpInput.Controls.Add(Me.Label4)
Me.grpInput.Controls.Add(Me.txtMonthStd)
Me.grpInput.Controls.Add(Me.lblNormWeek)
Me.grpInput.Controls.Add(Me.txtWeekStd)
Me.grpInput.Controls.Add(Me.lblSubPrc)
Me.grpInput.Controls.Add(Me.lblAddDtbtQty)
Me.grpInput.Controls.Add(Me.txtAddDtbtQty)
Me.grpInput.Controls.Add(Me.lblStdDtbtQty)
Me.grpInput.Controls.Add(Me.txtStdDtbtQty)
Me.grpInput.Controls.Add(Me.lblMinQty)
Me.grpInput.Controls.Add(Me.txtMinQty)
Me.grpInput.Controls.Add(Me.lblUnit)
Me.grpInput.Controls.Add(Me.txtUnit)
Me.grpInput.Controls.Add(Me.lblVJName)
Me.grpInput.Controls.Add(Me.txtJVName)
Me.grpInput.Controls.Add(Me.lblJEName)
Me.grpInput.Controls.Add(Me.txtJEName)
Me.grpInput.Controls.Add(Me.lblJCode)
Me.grpInput.Controls.Add(Me.txtJCode)
Me.grpInput.Controls.Add(Me.cboSubPrc)
Me.grpInput.Controls.Add(Me.lblECode)
Me.grpInput.Controls.Add(Me.txtECode)
Me.grpInput.Dock = System.Windows.Forms.DockStyle.Top
Me.grpInput.Location = New System.Drawing.Point(0, 55)
Me.grpInput.Name = "grpInput"
Me.grpInput.Size = New System.Drawing.Size(992, 58)
Me.grpInput.TabIndex = 1
Me.grpInput.TabStop = False
'
'Label4
'
Me.Label4.AutoSize = True
Me.Label4.Location = New System.Drawing.Point(896, 13)
Me.Label4.Name = "Label4"
Me.Label4.Size = New System.Drawing.Size(55, 14)
Me.Label4.TabIndex = 12
Me.Label4.Text = "Month Std"
'
'txtMonthStd
'
Me.txtMonthStd.Location = New System.Drawing.Point(896, 27)
Me.txtMonthStd.Name = "txtMonthStd"
Me.txtMonthStd.Size = New System.Drawing.Size(63, 20)
Me.txtMonthStd.TabIndex = 10
'
'lblNormWeek
'
Me.lblNormWeek.AutoSize = True
Me.lblNormWeek.Location = New System.Drawing.Point(827, 13)
Me.lblNormWeek.Name = "lblNormWeek"
Me.lblNormWeek.Size = New System.Drawing.Size(53, 14)
Me.lblNormWeek.TabIndex = 10
Me.lblNormWeek.Text = "Week Std"
'
'txtWeekStd
'
Me.txtWeekStd.Location = New System.Drawing.Point(827, 27)
Me.txtWeekStd.Name = "txtWeekStd"
Me.txtWeekStd.Size = New System.Drawing.Size(63, 20)
Me.txtWeekStd.TabIndex = 9
'
'lblSubPrc
'
Me.lblSubPrc.AutoSize = True
Me.lblSubPrc.Location = New System.Drawing.Point(67, 13)
Me.lblSubPrc.Name = "lblSubPrc"
Me.lblSubPrc.Size = New System.Drawing.Size(69, 14)
Me.lblSubPrc.TabIndex = 1
Me.lblSubPrc.Text = "Sub Process"
'
'lblAddDtbtQty
'
Me.lblAddDtbtQty.AutoSize = True
Me.lblAddDtbtQty.Location = New System.Drawing.Point(762, 13)
Me.lblAddDtbtQty.Name = "lblAddDtbtQty"
Me.lblAddDtbtQty.Size = New System.Drawing.Size(63, 14)
Me.lblAddDtbtQty.TabIndex = 8
Me.lblAddDtbtQty.Text = "AddDtbtQty"
'
'txtAddDtbtQty
'
Me.txtAddDtbtQty.Location = New System.Drawing.Point(762, 27)
Me.txtAddDtbtQty.Name = "txtAddDtbtQty"
Me.txtAddDtbtQty.Size = New System.Drawing.Size(63, 20)
Me.txtAddDtbtQty.TabIndex = 8
'
'lblStdDtbtQty
'
Me.lblStdDtbtQty.AutoSize = True
Me.lblStdDtbtQty.Location = New System.Drawing.Point(704, 13)
Me.lblStdDtbtQty.Name = "lblStdDtbtQty"
Me.lblStdDtbtQty.Size = New System.Drawing.Size(59, 14)
Me.lblStdDtbtQty.TabIndex = 7
Me.lblStdDtbtQty.Text = "StdDtbtQty"
'
'txtStdDtbtQty
'
Me.txtStdDtbtQty.Location = New System.Drawing.Point(704, 27)
Me.txtStdDtbtQty.Name = "txtStdDtbtQty"
Me.txtStdDtbtQty.Size = New System.Drawing.Size(56, 20)
Me.txtStdDtbtQty.TabIndex = 7
'
'lblMinQty
'
Me.lblMinQty.AutoSize = True
Me.lblMinQty.Location = New System.Drawing.Point(659, 13)
Me.lblMinQty.Name = "lblMinQty"
Me.lblMinQty.Size = New System.Drawing.Size(43, 14)
Me.lblMinQty.TabIndex = 6
Me.lblMinQty.Text = "Min Qty"
'
'txtMinQty
'
Me.txtMinQty.Location = New System.Drawing.Point(659, 27)
Me.txtMinQty.Name = "txtMinQty"
Me.txtMinQty.Size = New System.Drawing.Size(43, 20)
Me.txtMinQty.TabIndex = 6
'
'lblUnit
'
Me.lblUnit.AutoSize = True
Me.lblUnit.Location = New System.Drawing.Point(621, 13)
Me.lblUnit.Name = "lblUnit"
Me.lblUnit.Size = New System.Drawing.Size(25, 14)
Me.lblUnit.TabIndex = 5
Me.lblUnit.Text = "Unit"
'
'txtUnit
'
Me.txtUnit.Location = New System.Drawing.Point(621, 27)
Me.txtUnit.Name = "txtUnit"
Me.txtUnit.Size = New System.Drawing.Size(36, 20)
Me.txtUnit.TabIndex = 5
'
'lblVJName
'
Me.lblVJName.AutoSize = True
Me.lblVJName.Location = New System.Drawing.Point(444, 13)
Me.lblVJName.Name = "lblVJName"
Me.lblVJName.Size = New System.Drawing.Size(94, 14)
Me.lblVJName.TabIndex = 4
Me.lblVJName.Text = "Vietnamese Name"
'
'txtJVName
'
Me.txtJVName.Location = New System.Drawing.Point(444, 27)
Me.txtJVName.Name = "txtJVName"
Me.txtJVName.Size = New System.Drawing.Size(175, 20)
Me.txtJVName.TabIndex = 4
'
'lblJEName
'
Me.lblJEName.AutoSize = True
Me.lblJEName.Location = New System.Drawing.Point(267, 13)
Me.lblJEName.Name = "lblJEName"
Me.lblJEName.Size = New System.Drawing.Size(71, 14)
Me.lblJEName.TabIndex = 3
Me.lblJEName.Text = "English Name"
'
'txtJEName
'
Me.txtJEName.Location = New System.Drawing.Point(267, 27)
Me.txtJEName.Name = "txtJEName"
Me.txtJEName.Size = New System.Drawing.Size(175, 20)
Me.txtJEName.TabIndex = 3
'
'lblJCode
'
Me.lblJCode.AutoSize = True
Me.lblJCode.Location = New System.Drawing.Point(203, 13)
Me.lblJCode.Name = "lblJCode"
Me.lblJCode.Size = New System.Drawing.Size(37, 14)
Me.lblJCode.TabIndex = 2
Me.lblJCode.Text = "JCode"
'
'txtJCode
'
Me.txtJCode.Location = New System.Drawing.Point(202, 27)
Me.txtJCode.MaxLength = 10
Me.txtJCode.Name = "txtJCode"
Me.txtJCode.Size = New System.Drawing.Size(62, 20)
Me.txtJCode.TabIndex = 2
'
'cboSubPrc
'
Me.cboSubPrc.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.cboSubPrc.DropDownWidth = 200
Me.cboSubPrc.FormattingEnabled = True
Me.cboSubPrc.Location = New System.Drawing.Point(67, 27)
Me.cboSubPrc.Name = "cboSubPrc"
Me.cboSubPrc.Size = New System.Drawing.Size(130, 22)
Me.cboSubPrc.TabIndex = 1
'
'lblECode
'
Me.lblECode.AutoSize = True
Me.lblECode.Location = New System.Drawing.Point(6, 13)
Me.lblECode.Name = "lblECode"
Me.lblECode.Size = New System.Drawing.Size(55, 14)
Me.lblECode.TabIndex = 0
Me.lblECode.Text = "Emp Code"
'
'txtECode
'
Me.txtECode.Location = New System.Drawing.Point(6, 27)
Me.txtECode.MaxLength = 5
Me.txtECode.Name = "txtECode"
Me.txtECode.Size = New System.Drawing.Size(56, 20)
Me.txtECode.TabIndex = 0
'
'mnuDelete
'
Me.mnuDelete.AutoSize = False
Me.mnuDelete.Image = CType(resources.GetObject("mnuDelete.Image"), System.Drawing.Image)
Me.mnuDelete.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None
Me.mnuDelete.ImageTransparentColor = System.Drawing.Color.Magenta
Me.mnuDelete.Name = "mnuDelete"
Me.mnuDelete.Size = New System.Drawing.Size(60, 50)
Me.mnuDelete.Text = "Delete"
Me.mnuDelete.TextDirection = System.Windows.Forms.ToolStripTextDirection.Horizontal
Me.mnuDelete.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
'
'mnuExport
'
Me.mnuExport.AutoSize = False
Me.mnuExport.Image = CType(resources.GetObject("mnuExport.Image"), System.Drawing.Image)
Me.mnuExport.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None
Me.mnuExport.ImageTransparentColor = System.Drawing.Color.Magenta
Me.mnuExport.Name = "mnuExport"
Me.mnuExport.Size = New System.Drawing.Size(60, 50)
Me.mnuExport.Text = "Export"
Me.mnuExport.TextDirection = System.Windows.Forms.ToolStripTextDirection.Horizontal
Me.mnuExport.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
'
'tlsMenu
'
Me.tlsMenu.AutoSize = False
Me.tlsMenu.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden
Me.tlsMenu.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.mnuNew, Me.mnuEdit, Me.mnuShowAll, Me.mnuSave, Me.mnuExport, Me.mnuDelete, Me.ToolStripSeparator1, Me.mnuImport, Me.mnuUpdateEmpID, Me.ToolStripSeparator2})
Me.tlsMenu.Location = New System.Drawing.Point(0, 0)
Me.tlsMenu.Name = "tlsMenu"
Me.tlsMenu.RenderMode = System.Windows.Forms.ToolStripRenderMode.System
Me.tlsMenu.Size = New System.Drawing.Size(992, 55)
Me.tlsMenu.TabIndex = 0
Me.tlsMenu.Text = "ToolStrip1"
'
'mnuNew
'
Me.mnuNew.AutoSize = False
Me.mnuNew.Image = CType(resources.GetObject("mnuNew.Image"), System.Drawing.Image)
Me.mnuNew.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None
Me.mnuNew.ImageTransparentColor = System.Drawing.Color.Magenta
Me.mnuNew.Name = "mnuNew"
Me.mnuNew.Size = New System.Drawing.Size(60, 50)
Me.mnuNew.Text = "New"
Me.mnuNew.TextDirection = System.Windows.Forms.ToolStripTextDirection.Horizontal
Me.mnuNew.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
'
'mnuEdit
'
Me.mnuEdit.AutoSize = False
Me.mnuEdit.Image = CType(resources.GetObject("mnuEdit.Image"), System.Drawing.Image)
Me.mnuEdit.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None
Me.mnuEdit.ImageTransparentColor = System.Drawing.Color.Magenta
Me.mnuEdit.Name = "mnuEdit"
Me.mnuEdit.Size = New System.Drawing.Size(60, 50)
Me.mnuEdit.Text = "Edit"
Me.mnuEdit.TextDirection = System.Windows.Forms.ToolStripTextDirection.Horizontal
Me.mnuEdit.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
'
'mnuShowAll
'
Me.mnuShowAll.AutoSize = False
Me.mnuShowAll.Image = CType(resources.GetObject("mnuShowAll.Image"), System.Drawing.Image)
Me.mnuShowAll.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None
Me.mnuShowAll.ImageTransparentColor = System.Drawing.Color.Magenta
Me.mnuShowAll.Name = "mnuShowAll"
Me.mnuShowAll.Size = New System.Drawing.Size(60, 50)
Me.mnuShowAll.Text = "Show all"
Me.mnuShowAll.TextDirection = System.Windows.Forms.ToolStripTextDirection.Horizontal
Me.mnuShowAll.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
'
'mnuSave
'
Me.mnuSave.AutoSize = False
Me.mnuSave.Image = CType(resources.GetObject("mnuSave.Image"), System.Drawing.Image)
Me.mnuSave.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None
Me.mnuSave.ImageTransparentColor = System.Drawing.Color.Magenta
Me.mnuSave.Name = "mnuSave"
Me.mnuSave.Size = New System.Drawing.Size(60, 50)
Me.mnuSave.Text = "Save"
Me.mnuSave.TextDirection = System.Windows.Forms.ToolStripTextDirection.Horizontal
Me.mnuSave.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
'
'ToolStripSeparator1
'
Me.ToolStripSeparator1.Name = "ToolStripSeparator1"
Me.ToolStripSeparator1.Size = New System.Drawing.Size(6, 55)
'
'mnuImport
'
Me.mnuImport.AutoSize = False
Me.mnuImport.Image = CType(resources.GetObject("mnuImport.Image"), System.Drawing.Image)
Me.mnuImport.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None
Me.mnuImport.ImageTransparentColor = System.Drawing.Color.Magenta
Me.mnuImport.Name = "mnuImport"
Me.mnuImport.Size = New System.Drawing.Size(60, 50)
Me.mnuImport.Text = "Import"
Me.mnuImport.TextDirection = System.Windows.Forms.ToolStripTextDirection.Horizontal
Me.mnuImport.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
Me.mnuImport.ToolTipText = "Import"
'
'mnuUpdateEmpID
'
Me.mnuUpdateEmpID.AutoSize = False
Me.mnuUpdateEmpID.Image = CType(resources.GetObject("mnuUpdateEmpID.Image"), System.Drawing.Image)
Me.mnuUpdateEmpID.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None
Me.mnuUpdateEmpID.ImageTransparentColor = System.Drawing.Color.Magenta
Me.mnuUpdateEmpID.Name = "mnuUpdateEmpID"
Me.mnuUpdateEmpID.Size = New System.Drawing.Size(80, 50)
Me.mnuUpdateEmpID.Text = "UpdateEmpID"
Me.mnuUpdateEmpID.TextDirection = System.Windows.Forms.ToolStripTextDirection.Horizontal
Me.mnuUpdateEmpID.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
'
'ToolStripSeparator2
'
Me.ToolStripSeparator2.Name = "ToolStripSeparator2"
Me.ToolStripSeparator2.Size = New System.Drawing.Size(6, 55)
'
'grpGrid
'
Me.grpGrid.Controls.Add(Me.GridControl1)
Me.grpGrid.Dock = System.Windows.Forms.DockStyle.Fill
Me.grpGrid.Location = New System.Drawing.Point(0, 113)
Me.grpGrid.Name = "grpGrid"
Me.grpGrid.Size = New System.Drawing.Size(992, 348)
Me.grpGrid.TabIndex = 2
Me.grpGrid.TabStop = False
'
'GridControl1
'
Me.GridControl1.Dock = System.Windows.Forms.DockStyle.Fill
Me.GridControl1.Location = New System.Drawing.Point(3, 16)
Me.GridControl1.MainView = Me.GridView1
Me.GridControl1.Name = "GridControl1"
Me.GridControl1.Size = New System.Drawing.Size(986, 329)
Me.GridControl1.TabIndex = 1
Me.GridControl1.ViewCollection.AddRange(New DevExpress.XtraGrid.Views.Base.BaseView() {Me.GridView1})
'
'GridView1
'
Me.GridView1.GridControl = Me.GridControl1
Me.GridView1.Name = "GridView1"
Me.GridView1.OptionsBehavior.Editable = False
Me.GridView1.OptionsFind.AlwaysVisible = True
Me.GridView1.OptionsSelection.MultiSelect = True
Me.GridView1.OptionsView.ColumnAutoWidth = False
Me.GridView1.OptionsView.ColumnHeaderAutoHeight = DevExpress.Utils.DefaultBoolean.[True]
Me.GridView1.OptionsView.ShowFooter = True
Me.GridView1.OptionsView.ShowGroupPanel = False
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(525, 9)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(48, 14)
Me.Label1.TabIndex = 4
Me.Label1.Text = "OldCode"
'
'txtOldID
'
Me.txtOldID.Location = New System.Drawing.Point(528, 24)
Me.txtOldID.MaxLength = 5
Me.txtOldID.Name = "txtOldID"
Me.txtOldID.ReadOnly = True
Me.txtOldID.Size = New System.Drawing.Size(56, 20)
Me.txtOldID.TabIndex = 3
'
'txtNewID
'
Me.txtNewID.Location = New System.Drawing.Point(633, 24)
Me.txtNewID.MaxLength = 5
Me.txtNewID.Name = "txtNewID"
Me.txtNewID.Size = New System.Drawing.Size(56, 20)
Me.txtNewID.TabIndex = 5
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.Location = New System.Drawing.Point(590, 27)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(37, 14)
Me.Label2.TabIndex = 6
Me.Label2.Text = "====>"
'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.Location = New System.Drawing.Point(634, 9)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(55, 14)
Me.Label3.TabIndex = 7
Me.Label3.Text = "NewCode"
'
'bttOK
'
Me.bttOK.Location = New System.Drawing.Point(707, 4)
Me.bttOK.Name = "bttOK"
Me.bttOK.Size = New System.Drawing.Size(96, 37)
Me.bttOK.TabIndex = 8
Me.bttOK.Text = "Chọn"
Me.bttOK.UseVisualStyleBackColor = True
'
'DataGridViewTextBoxColumn3
'
Me.DataGridViewTextBoxColumn3.DataPropertyName = "VenderName"
Me.DataGridViewTextBoxColumn3.HeaderText = "Vender Name"
Me.DataGridViewTextBoxColumn3.Name = "DataGridViewTextBoxColumn3"
Me.DataGridViewTextBoxColumn3.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
Me.DataGridViewTextBoxColumn3.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic
'
'DataGridViewAutoFilterTextBoxColumn8
'
Me.DataGridViewAutoFilterTextBoxColumn8.DataPropertyName = "Reason"
Me.DataGridViewAutoFilterTextBoxColumn8.HeaderText = "Reason"
Me.DataGridViewAutoFilterTextBoxColumn8.Name = "DataGridViewAutoFilterTextBoxColumn8"
Me.DataGridViewAutoFilterTextBoxColumn8.ReadOnly = True
'
'DataGridViewAutoFilterTextBoxColumn5
'
Me.DataGridViewAutoFilterTextBoxColumn5.DataPropertyName = "Unit"
Me.DataGridViewAutoFilterTextBoxColumn5.HeaderText = "Unit"
Me.DataGridViewAutoFilterTextBoxColumn5.Name = "DataGridViewAutoFilterTextBoxColumn5"
Me.DataGridViewAutoFilterTextBoxColumn5.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
Me.DataGridViewAutoFilterTextBoxColumn5.Visible = False
'
'DataGridViewAutoFilterTextBoxColumn7
'
Me.DataGridViewAutoFilterTextBoxColumn7.DataPropertyName = "OrderDate"
Me.DataGridViewAutoFilterTextBoxColumn7.HeaderText = "Order Date"
Me.DataGridViewAutoFilterTextBoxColumn7.Name = "DataGridViewAutoFilterTextBoxColumn7"
Me.DataGridViewAutoFilterTextBoxColumn7.ReadOnly = True
'
'DataGridViewAutoFilterTextBoxColumn4
'
Me.DataGridViewAutoFilterTextBoxColumn4.DataPropertyName = "Quantity"
Me.DataGridViewAutoFilterTextBoxColumn4.HeaderText = "Quantity"
Me.DataGridViewAutoFilterTextBoxColumn4.Name = "DataGridViewAutoFilterTextBoxColumn4"
Me.DataGridViewAutoFilterTextBoxColumn4.ReadOnly = True
Me.DataGridViewAutoFilterTextBoxColumn4.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
'
'DataGridViewAutoFilterTextBoxColumn3
'
Me.DataGridViewAutoFilterTextBoxColumn3.DataPropertyName = "Air"
Me.DataGridViewAutoFilterTextBoxColumn3.HeaderText = "Air"
Me.DataGridViewAutoFilterTextBoxColumn3.Name = "DataGridViewAutoFilterTextBoxColumn3"
Me.DataGridViewAutoFilterTextBoxColumn3.ReadOnly = True
Me.DataGridViewAutoFilterTextBoxColumn3.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
'
'DataGridViewTextBoxColumn2
'
Me.DataGridViewTextBoxColumn2.DataPropertyName = "DeliveryDate"
Me.DataGridViewTextBoxColumn2.HeaderText = "Delivery Date"
Me.DataGridViewTextBoxColumn2.Name = "DataGridViewTextBoxColumn2"
Me.DataGridViewTextBoxColumn2.ReadOnly = True
Me.DataGridViewTextBoxColumn2.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
Me.DataGridViewTextBoxColumn2.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic
'
'DataGridViewAutoFilterTextBoxColumn2
'
Me.DataGridViewAutoFilterTextBoxColumn2.DataPropertyName = "PackingUnit"
Me.DataGridViewAutoFilterTextBoxColumn2.HeaderText = "Packing Unit"
Me.DataGridViewAutoFilterTextBoxColumn2.Name = "DataGridViewAutoFilterTextBoxColumn2"
Me.DataGridViewAutoFilterTextBoxColumn2.ReadOnly = True
Me.DataGridViewAutoFilterTextBoxColumn2.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
Me.DataGridViewAutoFilterTextBoxColumn2.Visible = False
'
'DataGridViewAutoFilterTextBoxColumn6
'
Me.DataGridViewAutoFilterTextBoxColumn6.DataPropertyName = "FullName"
Me.DataGridViewAutoFilterTextBoxColumn6.HeaderText = "Employee"
Me.DataGridViewAutoFilterTextBoxColumn6.Name = "DataGridViewAutoFilterTextBoxColumn6"
Me.DataGridViewAutoFilterTextBoxColumn6.ReadOnly = True
Me.DataGridViewAutoFilterTextBoxColumn6.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
'
'DataGridViewAutoFilterTextBoxColumn1
'
Me.DataGridViewAutoFilterTextBoxColumn1.DataPropertyName = "JName"
Me.DataGridViewAutoFilterTextBoxColumn1.HeaderText = "JName"
Me.DataGridViewAutoFilterTextBoxColumn1.Name = "DataGridViewAutoFilterTextBoxColumn1"
Me.DataGridViewAutoFilterTextBoxColumn1.ReadOnly = True
Me.DataGridViewAutoFilterTextBoxColumn1.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
'
'DataGridViewTextBoxColumn4
'
Me.DataGridViewTextBoxColumn4.DataPropertyName = "ID"
Me.DataGridViewTextBoxColumn4.HeaderText = "GSR ID"
Me.DataGridViewTextBoxColumn4.Name = "DataGridViewTextBoxColumn4"
Me.DataGridViewTextBoxColumn4.ReadOnly = True
'
'DataGridViewTextBoxColumn1
'
Me.DataGridViewTextBoxColumn1.DataPropertyName = "JCode"
Me.DataGridViewTextBoxColumn1.HeaderText = "JCode"
Me.DataGridViewTextBoxColumn1.Name = "DataGridViewTextBoxColumn1"
Me.DataGridViewTextBoxColumn1.ReadOnly = True
Me.DataGridViewTextBoxColumn1.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
Me.DataGridViewTextBoxColumn1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic
'
'DataGridViewAutoFilterTextBoxColumn9
'
Me.DataGridViewAutoFilterTextBoxColumn9.DataPropertyName = "IsLock"
Me.DataGridViewAutoFilterTextBoxColumn9.HeaderText = "IsLock"
Me.DataGridViewAutoFilterTextBoxColumn9.Name = "DataGridViewAutoFilterTextBoxColumn9"
Me.DataGridViewAutoFilterTextBoxColumn9.ReadOnly = True
'
'CalendarColumn1
'
Me.CalendarColumn1.HeaderText = "Delivery Date"
Me.CalendarColumn1.Name = "CalendarColumn1"
Me.CalendarColumn1.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
Me.CalendarColumn1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic
'
'FrmMaterialAndSubMaterial
'
Me.Appearance.Options.UseFont = True
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 14.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(992, 461)
Me.Controls.Add(Me.bttOK)
Me.Controls.Add(Me.Label3)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.txtNewID)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.txtOldID)
Me.Controls.Add(Me.grpGrid)
Me.Controls.Add(Me.grpInput)
Me.Controls.Add(Me.tlsMenu)
Me.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.KeyPreview = True
Me.Name = "FrmMaterialAndSubMaterial"
Me.Tag = "021203"
Me.Text = "Material And Sub Material"
Me.grpInput.ResumeLayout(False)
Me.grpInput.PerformLayout()
Me.tlsMenu.ResumeLayout(False)
Me.tlsMenu.PerformLayout()
Me.grpGrid.ResumeLayout(False)
CType(Me.GridControl1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.GridView1, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents grpInput As System.Windows.Forms.GroupBox
Friend WithEvents lblECode As System.Windows.Forms.Label
Friend WithEvents txtECode As System.Windows.Forms.TextBox
Friend WithEvents mnuDelete As System.Windows.Forms.ToolStripButton
Friend WithEvents mnuExport As System.Windows.Forms.ToolStripButton
Friend WithEvents tlsMenu As System.Windows.Forms.ToolStrip
Friend WithEvents mnuShowAll As System.Windows.Forms.ToolStripButton
Friend WithEvents DataGridViewTextBoxColumn3 As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents DataGridViewAutoFilterTextBoxColumn8 As DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn
Friend WithEvents DataGridViewAutoFilterTextBoxColumn5 As DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn
Friend WithEvents DataGridViewAutoFilterTextBoxColumn7 As DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn
Friend WithEvents DataGridViewAutoFilterTextBoxColumn4 As DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn
Friend WithEvents DataGridViewAutoFilterTextBoxColumn3 As DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn
Friend WithEvents DataGridViewTextBoxColumn2 As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents DataGridViewAutoFilterTextBoxColumn2 As DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn
Friend WithEvents DataGridViewAutoFilterTextBoxColumn6 As DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn
Friend WithEvents DataGridViewAutoFilterTextBoxColumn1 As DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn
Friend WithEvents DataGridViewTextBoxColumn4 As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents DataGridViewTextBoxColumn1 As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents DataGridViewAutoFilterTextBoxColumn9 As DataGridViewAutoFilter.DataGridViewAutoFilterTextBoxColumn
Friend WithEvents grpGrid As System.Windows.Forms.GroupBox
Friend WithEvents CalendarColumn1 As UtilityControl.CalendarColumn
Friend WithEvents lblAddDtbtQty As System.Windows.Forms.Label
Friend WithEvents txtAddDtbtQty As System.Windows.Forms.TextBox
Friend WithEvents lblStdDtbtQty As System.Windows.Forms.Label
Friend WithEvents txtStdDtbtQty As System.Windows.Forms.TextBox
Friend WithEvents lblMinQty As System.Windows.Forms.Label
Friend WithEvents txtMinQty As System.Windows.Forms.TextBox
Friend WithEvents lblUnit As System.Windows.Forms.Label
Friend WithEvents txtUnit As System.Windows.Forms.TextBox
Friend WithEvents lblVJName As System.Windows.Forms.Label
Friend WithEvents txtJVName As System.Windows.Forms.TextBox
Friend WithEvents lblJEName As System.Windows.Forms.Label
Friend WithEvents txtJEName As System.Windows.Forms.TextBox
Friend WithEvents lblJCode As System.Windows.Forms.Label
Friend WithEvents txtJCode As System.Windows.Forms.TextBox
Friend WithEvents cboSubPrc As System.Windows.Forms.ComboBox
Friend WithEvents lblSubPrc As System.Windows.Forms.Label
Friend WithEvents mnuSave As System.Windows.Forms.ToolStripButton
Friend WithEvents mnuNew As System.Windows.Forms.ToolStripButton
Friend WithEvents mnuEdit As System.Windows.Forms.ToolStripButton
Friend WithEvents lblNormWeek As System.Windows.Forms.Label
Friend WithEvents txtWeekStd As System.Windows.Forms.TextBox
Friend WithEvents ToolStripSeparator1 As System.Windows.Forms.ToolStripSeparator
Friend WithEvents mnuUpdateEmpID As System.Windows.Forms.ToolStripButton
Friend WithEvents ToolStripSeparator2 As System.Windows.Forms.ToolStripSeparator
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents txtOldID As System.Windows.Forms.TextBox
Friend WithEvents txtNewID As System.Windows.Forms.TextBox
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents Label3 As System.Windows.Forms.Label
Friend WithEvents mnuImport As System.Windows.Forms.ToolStripButton
Friend WithEvents Label4 As System.Windows.Forms.Label
Friend WithEvents txtMonthStd As System.Windows.Forms.TextBox
Friend WithEvents bttOK As System.Windows.Forms.Button
Friend WithEvents GridControl1 As DevExpress.XtraGrid.GridControl
Friend WithEvents GridView1 As DevExpress.XtraGrid.Views.Grid.GridView
End Class
|
'------------------------------------------------------------
'- File Name : modMain.vb -
'- Part of Project: Assign9 -
'------------------------------------------------------------
'- Written By: Nathan Gaffney -
'- Written On: 5 Apr 2020 -
'------------------------------------------------------------
'- File Purpose: -
'- This file contains the main application driver, where the-
'- user can decide to use hard coded data or to use a file -
'- which supplies the data, -
'------------------------------------------------------------
'- Program Purpose: -
'- -
'- This program will create an excel file from either -
'- supplied data or hard-coded data, it will display this -
'- data to the user, and then it will perform basic stats -
'- on the data. -
'------------------------------------------------------------
'- Global Variable Dictionary (alphabetically): -
'- anExcel –the excel file to be created –
'- fileName – the file name to be loaded "ToyOrder.txt" –
'- mySalesForce – holds a list of employess and their sales –
'------------------------------------------------------------
Imports Microsoft.Office.Interop
Module modMain
Dim anExcel As Excel.Application
Dim mySalesForce As New List(Of clsSalesperson)
Dim fileName As String = "ToyOrder.txt"
'------------------------------------------------------------
'- Subprogram Name: Main -
'------------------------------------------------------------
'- Written By: Nathan Gaffney -
'- Written On: 6 Apr 2020 -
'------------------------------------------------------------
'- Subprogram Purpose: -
'- -
'- This subroutine calls the necessary functions to write -
'- an excel file and perform basic statistical analysis on -
'- the data either hard coded into the program or supplied -
'- by the user i the form of a file named ToyOrder.txt -
'------------------------------------------------------------
'- Parameter Dictionary (in parameter order): -
'- (None) -
'------------------------------------------------------------
'- Local Variable Dictionary (alphabetically): -
'- anExcel - the excel file -
'- strResponse – Users response to if they want to load file–
'------------------------------------------------------------
Sub Main()
Dim strResponse As String
Console.WriteLine("Loading Excel...")
anExcel = New Excel.Application()
Do
Console.Write("Would you like to load data from file? Y/N: ")
strResponse = Console.ReadKey().Key
Console.WriteLine()
Loop While strResponse <> ConsoleKey.Y And strResponse <> ConsoleKey.N ' And strResponse <> "N" And strResponse <> "n"
If strResponse = ConsoleKey.Y Then
Try
Console.WriteLine("Loading 'ToyOrder.txt'...")
readSalesInformation(fileName)
Catch ex As Exception
Console.WriteLine("Problem Opening File. Using hard coded data.")
createSalesForce()
End Try
Else
createSalesForce()
End If
anExcel.Workbooks.Add()
Console.WriteLine("Writting data to Excel...")
createHeader()
Dim intLastRow As Integer = createMainData()
createFormulaHeaders(intLastRow)
Console.WriteLine("Opening Excel...")
anExcel.Visible = True
Console.WriteLine("Press Any Key To Exit.")
Console.ReadKey()
anExcel.Quit()
anExcel = Nothing
End Sub
'------------------------------------------------------------
'- Subprogram Name: readSalesInformation -
'------------------------------------------------------------
'- Written By: Nathan Gaffney -
'- Written On: 6 Apr 2020 -
'------------------------------------------------------------
'- Subprogram Purpose: -
'- -
'- This subroutine creates the salesforce by reading from -
'- a file. -
'------------------------------------------------------------
'- Parameter Dictionary (in parameter order): -
'- fileName - Name of teh file to be read -
'------------------------------------------------------------
'- Local Variable Dictionary (alphabetically): -
'- fullPath - this will hold the full path to the file -
'- objMyStreamReader - holds the reader -
'- strLineContents - the contents of the line space delimited-
'- strContents - contents of the line as array -
'------------------------------------------------------------
Private Sub readSalesInformation(ByVal fileName)
Dim objMyStreamReader As System.IO.StreamReader
Dim strLineContents As String
'Create path string as shown by MSDN
Dim fullPath As String
'Combine as shown by MSDN
fullPath = My.Computer.FileSystem.CombinePath(My.Application.Info.DirectoryPath, fileName)
objMyStreamReader = System.IO.File.OpenText(fullPath)
While Not (objMyStreamReader.EndOfStream)
strLineContents = objMyStreamReader.ReadLine()
Debug.WriteLine("1")
Dim strContents() As String = Split(strLineContents, " ")
Debug.WriteLine(strContents)
'Create a salesperson with the inofrmation
mySalesForce.Add(New clsSalesperson(strContents(employee.strFirstName),
strContents(employee.strLastName),
strContents(employee.intOrderID),
strContents(employee.intID),
strContents(employee.sngGamesSales),
strContents(employee.intGamesQuantity),
strContents(employee.sngDollsSales),
strContents(employee.intDollsQuantity),
strContents(employee.sngBuildingSales),
strContents(employee.intBuildingQuantity),
strContents(employee.sngModelSales),
strContents(employee.intModelQuantity)))
End While
objMyStreamReader.Close()
Console.WriteLine("File loaded successfully.")
End Sub
'------------------------------------------------------------
'- Subprogram Name: createMainData -
'------------------------------------------------------------
'- Written By: Nathan Gaffney -
'- Written On: 6 Apr 2020 -
'------------------------------------------------------------
'- Subprogram Purpose: -
'- -
'- This subroutine creates a will write the data of -
'- sales force to the excel file. -
'------------------------------------------------------------
'- Parameter Dictionary (in parameter order): -
'- (None) -
'------------------------------------------------------------
'- Local Variable Dictionary (alphabetically): -
'- intCol - this will hold the column value -
'- intColumnOfdata1 - Where the first section of aggregate -
'- functions starts. -
'- intColumnOfData2 - the second batch of aggregate function-
'- intRow - this will hold the row value -
'------------------------------------------------------------
'------------------------------------------------------------
'- Returns: -
'- intRow – telling where the last row is -
'------------------------------------------------------------
Private Function createMainData()
Dim intRow = 1
Dim intCol = column.A
Dim intColumOfData1 As Integer
Dim intColumOfData2 As Integer
intRow += 1
For Each member In mySalesForce
With anExcel
.Cells(intRow, intCol) = member.getStrFirstName()
intCol += 1
.Cells(intRow, intCol) = member.getStrLastName()
intCol += 1
.Cells(intRow, intCol) = member.getIntOrderID()
intCol += 1
.Cells(intRow, intCol) = member.getIntID()
intCol += 1
intCol += 1
intColumOfData1 = intCol
.Cells(intRow, intCol) = member.getSngGamesSales()
intCol += 1
.Cells(intRow, intCol) = member.getSngDollsSales()
intCol += 1
.Cells(intRow, intCol) = member.getSngBuildingSales()
intCol += 1
.Cells(intRow, intCol) = member.getSngModelSales()
intCol += 1
.Cells(intRow, intCol) = "=sum(" & getColumnLetter(intColumOfData1) & intRow & ".." & getColumnLetter(intColumOfData1 + 3) & intRow & ")"
intCol += 1
.Cells(intRow, intCol) = "=min(" & getColumnLetter(intColumOfData1) & intRow & ".." & getColumnLetter(intColumOfData1 + 3) & intRow & ")"
intCol += 1
.Cells(intRow, intCol) = "=average(" & getColumnLetter(intColumOfData1) & intRow & ".." & getColumnLetter(intColumOfData1 + 3) & intRow & ")"
intCol += 1
.Cells(intRow, intCol) = "=max(" & getColumnLetter(intColumOfData1) & intRow & ".." & getColumnLetter(intColumOfData1 + 3) & intRow & ")"
intCol += 1
intCol += 1
intColumOfData2 = intCol
.Cells(intRow, intCol) = member.getIntGamesQuantity()
intCol += 1
.Cells(intRow, intCol) = member.getIntDollsQuantity()
intCol += 1
.Cells(intRow, intCol) = member.getIntBuildingQuantity()
intCol += 1
.Cells(intRow, intCol) = member.getIntModelQuantity()
intCol += 1
.Cells(intRow, intCol) = "=sum(" & getColumnLetter(intColumOfData2) & intRow & ".." & getColumnLetter(intColumOfData2 + 3) & intRow & ")"
intCol += 1
.Cells(intRow, intCol) = "=min(" & getColumnLetter(intColumOfData2) & intRow & ".." & getColumnLetter(intColumOfData2 + 3) & intRow & ")"
intCol += 1
.Cells(intRow, intCol) = "=average(" & getColumnLetter(intColumOfData2) & intRow & ".." & getColumnLetter(intColumOfData2 + 3) & intRow & ")"
intCol += 1
.Cells(intRow, intCol) = "=max(" & getColumnLetter(intColumOfData2) & intRow & ".." & getColumnLetter(intColumOfData2 + 3) & intRow & ")"
intCol += 1
intRow += 1
intCol = 1
End With
Next
Return intRow
End Function
'------------------------------------------------------------
'- Subprogram Name: createHeader -
'------------------------------------------------------------
'- Written By: Nathan Gaffney -
'- Written On: 5 Apr 2020 -
'------------------------------------------------------------
'- Subprogram Purpose: -
'- -
'- This subroutine creates a will write the headers -
'------------------------------------------------------------
'- Parameter Dictionary (in parameter order): -
'- (None) -
'------------------------------------------------------------
'- Local Variable Dictionary (alphabetically): -
'- intCol - this will hold the column value -
'- intRow - this will hold the row value -
'------------------------------------------------------------
Private Sub createHeader()
Dim intRow As Integer = 1
Dim intCol As Integer = 1
Dim strHeaders As New List(Of String)
strHeaders.Add("First Name")
strHeaders.Add("Last Name")
strHeaders.Add("Order ID")
strHeaders.Add("Employee ID")
strHeaders.Add(" ")
strHeaders.Add("Games Sales")
strHeaders.Add("Dolls Sales")
strHeaders.Add("Build Sales")
strHeaders.Add("Model Sales")
strHeaders.Add("Total Sale")
strHeaders.Add("Min Sales")
strHeaders.Add("Avg Sales")
strHeaders.Add("Max Sales")
strHeaders.Add(" ")
strHeaders.Add("Games Qty.")
strHeaders.Add("Dolls Qty.")
strHeaders.Add("Build Qty.")
strHeaders.Add("Model Qty.")
strHeaders.Add("Total Qty.")
strHeaders.Add("Max Qty.")
strHeaders.Add("Avg Qty.")
strHeaders.Add("Min Qty.")
For Each header In strHeaders
anExcel.Cells(intRow, intCol) = header.ToString
intCol += 1
Next
End Sub
'------------------------------------------------------------
'- Subprogram Name: createFormulaHeaders -
'------------------------------------------------------------
'- Written By: Nathan Gaffney -
'- Written On: 6 Apr 2020 -
'------------------------------------------------------------
'- Subprogram Purpose: -
'- -
'- This subroutine creates a will write the formulas needed -
'- to create the aggregrate functions on the columns -
'------------------------------------------------------------
'- Parameter Dictionary (in parameter order): -
'- (None) -
'------------------------------------------------------------
'- Local Variable Dictionary (alphabetically): -
'- intCol - this will hold the starting column the vertical -
'- headers will be placed -
'- intCounter - this has two functions, it is the column the-
'- data will be entered into and the control for the loop -
'- intLastRowOfData - this is the last row of data, before -
'- the single row gap. -
'------------------------------------------------------------
Private Sub createFormulaHeaders(ByVal intLastRow)
Dim intLastRowOfData As Integer = intLastRow
Dim intCol = column.E
Dim intColumn As Integer = column.F
'Increment intLastRow to create a "blank" row
intLastRow += 1
'Saves time retyping anExcel.Cells
With anExcel
'Create the header
.Cells(intLastRow, intCol) = "Total:"
'Loop through all remaining columns, except for column 14
'which is the empty column.
While intColumn <= column.V
If intColumn <> column.N Then
'Wirte the formula into the cell referencing the current
'column, 1 serves as the first row (should be 2 because of the header row)
'intLastRowOfData is the cell location where the function will stop
.Cells(intLastRow, intColumn) = "=sum(" & getColumnLetter(intColumn) & 1 & ".." & getColumnLetter(intColumn) & intLastRowOfData & ")"
End If
intColumn += 1
End While
'Reset target column to the column after header
intColumn = column.F
'Go down one row
intLastRow += 1
'Repeat above logic for each desired type of aggregate function
.Cells(intLastRow, intCol) = "Max:"
While intColumn <= column.V
If intColumn <> column.N Then
.Cells(intLastRow, intColumn) = "=max(" & getColumnLetter(intColumn) & 1 & ".." & getColumnLetter(intColumn) & intLastRowOfData & ")"
End If
intColumn += 1
End While
intColumn = column.F
intLastRow += 1
.Cells(intLastRow, intCol) = "Avg:"
While intColumn <= column.V
If intColumn <> column.N Then
.Cells(intLastRow, intColumn) = "=average(" & getColumnLetter(intColumn) & 1 & ".." & getColumnLetter(intColumn) & intLastRowOfData & ")"
End If
intColumn += 1
End While
intColumn = column.F
intLastRow += 1
.Cells(intLastRow, intCol) = "Min:"
While intColumn <= column.V
If intColumn <> column.N Then
.Cells(intLastRow, intColumn) = "=min(" & getColumnLetter(intColumn) & 1 & ".." & getColumnLetter(intColumn) & intLastRowOfData & ")"
End If
intColumn += 1
End While
End With
End Sub
'------------------------------------------------------------
'- Subprogram Name: createSalesForce -
'------------------------------------------------------------
'- Written By: Nathan Gaffney -
'- Written On: 5 Apr 2020 -
'------------------------------------------------------------
'- Subprogram Purpose: -
'- -
'- This subroutine creates a sales force, represented as a –
'- list of clsSalesPerson, the data for these people is -
'- hard-coded -
'------------------------------------------------------------
'- Parameter Dictionary (in parameter order): -
'- (None) -
'------------------------------------------------------------
'- Local Variable Dictionary (alphabetically): -
'- (None) -
'------------------------------------------------------------
Private Sub createSalesForce()
mySalesForce.Add(New clsSalesperson("Robert", "Phillips", 103, 1015, 115.54, 4, 108.15, 3, 102.15, 1, 107.19, 5))
mySalesForce.Add(New clsSalesperson("Susan", "Ricardo", 98, 1016, 174.15, 6, 132.14, 4, 181.54, 4, 185.67, 5))
mySalesForce.Add(New clsSalesperson("William", "Acerba", 203, 1017, 165.34, 4, 193.43, 2, 154.65, 3, 192.23, 4))
mySalesForce.Add(New clsSalesperson("Jill", "Quercas", 102, 1018, 186.85, 3, 196.65, 3, 324.44, 5, 175.34, 7))
mySalesForce.Add(New clsSalesperson("Anthony", "Stallman", 104, 1019, 175.54, 4, 283.43, 6, 293.23, 4, 192.54, 2))
mySalesForce.Add(New clsSalesperson("Scott", "Jarod", 36, 1020, 293.43, 5, 349.34, 3, 345.64, 3, 418.23, 2))
mySalesForce.Add(New clsSalesperson("Fred", "Nostrandt", 12, 1021, 482.23, 4, 384.23, 2, 384.45, 4, 934.53, 4))
mySalesForce.Add(New clsSalesperson("Leanne", "McCulloch", 215, 1022, 239.34, 2, 594.23, 4, 495.23, 5, 394.39, 9))
mySalesForce.Add(New clsSalesperson("Valina", "Farland", 220, 1023, 394.54, 5, 495.45, 4, 594.23, 9, 293.43, 4))
mySalesForce.Add(New clsSalesperson("Ashton", "Blasdell", 221, 1024, 473.99, 9, 293.98, 2, 485.38, 8, 384.95, 3))
mySalesForce.Add(New clsSalesperson("Cullen", "Italski", 123, 1025, 494.53, 5, 340.89, 2, 830.0, 8, 348.53, 9))
mySalesForce.Add(New clsSalesperson("Haleigh", "Turner", 144, 1026, 847.23, 9, 837.83, 4, 849.87, 7, 837.44, 8))
mySalesForce.Add(New clsSalesperson("John", "Egland", 212, 1027, 282.29, 8, 101.87, 2, 192.82, 7, 172.33, 2))
mySalesForce.Add(New clsSalesperson("Debbie", "Young", 133, 1028, 283.34, 8, 211.18, 2, 321.28, 2, 392.87, 7))
mySalesForce.Add(New clsSalesperson("Larry", "Hon", 135, 1029, 293.45, 8, 374.54, 8, 847.34, 7, 283.43, 8))
mySalesForce.Add(New clsSalesperson("Doug", "Ulysses", 132, 1030, 238.45, 2, 283.34, 2, 485.22, 2, 382.12, 8))
mySalesForce.Add(New clsSalesperson("Bea", "Conrad", 201, 1031, 283.43, 2, 234.45, 5, 583.45, 4, 734.73, 8))
mySalesForce.Add(New clsSalesperson("Ed", "Klute", 134, 1032, 293.43, 5, 837.45, 8, 934.98, 7, 938.28, 5))
mySalesForce.Add(New clsSalesperson("Brian", "Larton", 143, 1033, 193.45, 5, 985.34, 3, 349.59, 9, 934.34, 2))
mySalesForce.Add(New clsSalesperson("Cory", "Gerard", 200, 1034, 194.9, 9, 180.03, 4, 293.92, 3, 234.2, 9))
mySalesForce.Add(New clsSalesperson("Aubrey", "Vander", 185, 1035, 102.32, 4, 293.04, 3, 203.98, 2, 203.0, 4))
mySalesForce.Add(New clsSalesperson("Ted", "Xerxes", 181, 1036, 103.43, 2, 103.45, 2, 394.28, 4, 425.23, 6))
mySalesForce.Add(New clsSalesperson("DeAnn", "Davis", 202, 1037, 192.23, 3, 283.43, 3, 384.23, 2, 384.98, 8))
mySalesForce.Add(New clsSalesperson("Ron", "Zening", 76, 1038, 102.23, 3, 493.34, 3, 495.45, 4, 450.3, 9))
mySalesForce.Add(New clsSalesperson("Peggy", "Wallis", 199, 1039, 103.43, 3, 394.04, 9, 493.23, 2, 940.2, 2))
mySalesForce.Add(New clsSalesperson("Amy", "Oloff", 187, 1040, 102.3, 2, 184.03, 4, 103.45, 2, 394.34, 8))
End Sub
End Module
|
Imports System.IO
Public Class frmMain
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 btnBrowse As System.Windows.Forms.Button
Friend WithEvents txtPath As System.Windows.Forms.TextBox
Friend WithEvents lblSelectedDirectory As System.Windows.Forms.Label
Friend WithEvents lstFinal As System.Windows.Forms.ListBox
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents txtStartFilenameWith As System.Windows.Forms.TextBox
Friend WithEvents btnRename As System.Windows.Forms.Button
Friend WithEvents fbd1 As System.Windows.Forms.FolderBrowserDialog
Friend WithEvents btnExit As System.Windows.Forms.Button
Friend WithEvents lstInitial As System.Windows.Forms.ListBox
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents Label3 As System.Windows.Forms.Label
Friend WithEvents Label4 As System.Windows.Forms.Label
Friend WithEvents cmbPosition As System.Windows.Forms.ComboBox
Friend WithEvents Label5 As System.Windows.Forms.Label
Friend WithEvents cmbFilter As System.Windows.Forms.ComboBox
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(frmMain))
Me.btnBrowse = New System.Windows.Forms.Button
Me.txtPath = New System.Windows.Forms.TextBox
Me.lblSelectedDirectory = New System.Windows.Forms.Label
Me.lstInitial = New System.Windows.Forms.ListBox
Me.lstFinal = New System.Windows.Forms.ListBox
Me.Label1 = New System.Windows.Forms.Label
Me.txtStartFilenameWith = New System.Windows.Forms.TextBox
Me.btnRename = New System.Windows.Forms.Button
Me.fbd1 = New System.Windows.Forms.FolderBrowserDialog
Me.btnExit = New System.Windows.Forms.Button
Me.Label2 = New System.Windows.Forms.Label
Me.Label3 = New System.Windows.Forms.Label
Me.Label4 = New System.Windows.Forms.Label
Me.cmbPosition = New System.Windows.Forms.ComboBox
Me.Label5 = New System.Windows.Forms.Label
Me.cmbFilter = New System.Windows.Forms.ComboBox
Me.SuspendLayout()
'
'btnBrowse
'
Me.btnBrowse.BackColor = System.Drawing.Color.DarkSalmon
Me.btnBrowse.Location = New System.Drawing.Point(568, 16)
Me.btnBrowse.Name = "btnBrowse"
Me.btnBrowse.TabIndex = 0
Me.btnBrowse.Text = "Browse"
'
'txtPath
'
Me.txtPath.Location = New System.Drawing.Point(136, 16)
Me.txtPath.Name = "txtPath"
Me.txtPath.Size = New System.Drawing.Size(424, 20)
Me.txtPath.TabIndex = 1
Me.txtPath.Text = ""
'
'lblSelectedDirectory
'
Me.lblSelectedDirectory.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.lblSelectedDirectory.Location = New System.Drawing.Point(24, 16)
Me.lblSelectedDirectory.Name = "lblSelectedDirectory"
Me.lblSelectedDirectory.Size = New System.Drawing.Size(104, 23)
Me.lblSelectedDirectory.TabIndex = 2
Me.lblSelectedDirectory.Text = "Selected Directory"
Me.lblSelectedDirectory.TextAlign = System.Drawing.ContentAlignment.MiddleRight
'
'lstInitial
'
Me.lstInitial.BackColor = System.Drawing.Color.FromArgb(CType(192, Byte), CType(255, Byte), CType(192, Byte))
Me.lstInitial.HorizontalScrollbar = True
Me.lstInitial.Location = New System.Drawing.Point(24, 152)
Me.lstInitial.Name = "lstInitial"
Me.lstInitial.ScrollAlwaysVisible = True
Me.lstInitial.Size = New System.Drawing.Size(276, 342)
Me.lstInitial.TabIndex = 3
'
'lstFinal
'
Me.lstFinal.BackColor = System.Drawing.Color.FromArgb(CType(255, Byte), CType(192, Byte), CType(192, Byte))
Me.lstFinal.HorizontalScrollbar = True
Me.lstFinal.Location = New System.Drawing.Point(376, 152)
Me.lstFinal.Name = "lstFinal"
Me.lstFinal.ScrollAlwaysVisible = True
Me.lstFinal.Size = New System.Drawing.Size(276, 342)
Me.lstFinal.TabIndex = 4
'
'Label1
'
Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label1.Location = New System.Drawing.Point(32, 48)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(96, 23)
Me.Label1.TabIndex = 5
Me.Label1.Text = "Add To Filename"
Me.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight
'
'txtStartFilenameWith
'
Me.txtStartFilenameWith.Location = New System.Drawing.Point(136, 48)
Me.txtStartFilenameWith.Name = "txtStartFilenameWith"
Me.txtStartFilenameWith.Size = New System.Drawing.Size(177, 20)
Me.txtStartFilenameWith.TabIndex = 6
Me.txtStartFilenameWith.Text = ""
'
'btnRename
'
Me.btnRename.BackColor = System.Drawing.Color.DarkSalmon
Me.btnRename.Location = New System.Drawing.Point(312, 304)
Me.btnRename.Name = "btnRename"
Me.btnRename.Size = New System.Drawing.Size(56, 23)
Me.btnRename.TabIndex = 7
Me.btnRename.Text = "Rename"
'
'fbd1
'
Me.fbd1.Description = "Folder Browse Dialog"
'
'btnExit
'
Me.btnExit.BackColor = System.Drawing.Color.DarkSalmon
Me.btnExit.Location = New System.Drawing.Point(568, 48)
Me.btnExit.Name = "btnExit"
Me.btnExit.TabIndex = 8
Me.btnExit.Text = "Exit"
'
'Label2
'
Me.Label2.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label2.Location = New System.Drawing.Point(24, 120)
Me.Label2.Name = "Label2"
Me.Label2.TabIndex = 9
Me.Label2.Text = "Initial File List"
Me.Label2.TextAlign = System.Drawing.ContentAlignment.BottomLeft
'
'Label3
'
Me.Label3.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label3.Location = New System.Drawing.Point(376, 120)
Me.Label3.Name = "Label3"
Me.Label3.TabIndex = 10
Me.Label3.Text = "Renamed File List"
Me.Label3.TextAlign = System.Drawing.ContentAlignment.BottomLeft
'
'Label4
'
Me.Label4.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label4.Location = New System.Drawing.Point(312, 48)
Me.Label4.Name = "Label4"
Me.Label4.Size = New System.Drawing.Size(88, 23)
Me.Label4.TabIndex = 11
Me.Label4.Text = "Position In File"
Me.Label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight
'
'cmbPosition
'
Me.cmbPosition.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.cmbPosition.Items.AddRange(New Object() {"Beginning Of File Name", "End Of The File Name", "Numeric Increment"})
Me.cmbPosition.Location = New System.Drawing.Point(408, 48)
Me.cmbPosition.Name = "cmbPosition"
Me.cmbPosition.Size = New System.Drawing.Size(152, 21)
Me.cmbPosition.TabIndex = 12
'
'Label5
'
Me.Label5.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label5.Location = New System.Drawing.Point(24, 80)
Me.Label5.Name = "Label5"
Me.Label5.Size = New System.Drawing.Size(104, 23)
Me.Label5.TabIndex = 13
Me.Label5.Text = "Filter By File Type"
Me.Label5.TextAlign = System.Drawing.ContentAlignment.MiddleRight
'
'cmbFilter
'
Me.cmbFilter.Location = New System.Drawing.Point(136, 80)
Me.cmbFilter.Name = "cmbFilter"
Me.cmbFilter.Size = New System.Drawing.Size(176, 21)
Me.cmbFilter.TabIndex = 14
'
'frmMain
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(680, 525)
Me.Controls.Add(Me.cmbFilter)
Me.Controls.Add(Me.Label5)
Me.Controls.Add(Me.cmbPosition)
Me.Controls.Add(Me.Label4)
Me.Controls.Add(Me.Label3)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.btnExit)
Me.Controls.Add(Me.btnRename)
Me.Controls.Add(Me.txtStartFilenameWith)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.lstFinal)
Me.Controls.Add(Me.lstInitial)
Me.Controls.Add(Me.lblSelectedDirectory)
Me.Controls.Add(Me.txtPath)
Me.Controls.Add(Me.btnBrowse)
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.Name = "frmMain"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "DigiOz Mass File Renamer Version 1.0"
Me.ResumeLayout(False)
End Sub
#End Region
Dim listfiles As Directory
Dim files As Array
Dim file As String
Dim fileExtension As String
Dim fileShort As String
Dim fileShortRenamed As String
Dim i As Integer = 1
Function getFileExtension(ByVal f As String) As String
Dim nf As Array
Dim q As String
Dim countQ As Integer
nf = Split(f, ".")
countQ = nf.Length
'MessageBox.Show(nf(countQ - 1))
getFileExtension = nf(countQ - 1)
End Function
Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
Dim fileExtension As String
Dim uniqueExtensions As Array
Dim colExtensions As Collection
lstInitial.Items.Clear()
lstFinal.Items.Clear()
fbd1.ShowDialog()
txtPath.Text = fbd1.SelectedPath.ToString()
files = listfiles.GetFiles(fbd1.SelectedPath.ToString())
For Each file In files
fileShort = Replace(file, txtPath.Text & "\", "")
lstInitial.Items.Add(fileShort)
'getFileExtension(fileShort)
fileExtension = getFileExtension(fileShort)
cmbFilter.Items.Add(fileExtension)
Next
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnRename_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRename.Click
i = 1
Dim x As Integer
Dim iNumItems As Integer
If lstInitial.Items.Count <= 0 Then
MessageBox.Show("There are no files in your initial file list!")
Exit Sub
End If
If txtStartFilenameWith.Text = "" And cmbPosition.SelectedItem <> "Numeric Increment" Then
MessageBox.Show("Please Enter a phrase to use for file rename!")
Exit Sub
End If
iNumItems = lstInitial.Items.Count()
'For x = 0 To iNumItems - 1
'MessageBox.Show(lstInitial.Items.Item(x))
'Next x
'For Each file In files
For x = 0 To iNumItems - 1
If cmbPosition.SelectedItem = "Beginning Of File Name" Then
fileShortRenamed = txtPath.Text & "\" & txtStartFilenameWith.Text & "_" & i & "." & getFileExtension(lstInitial.Items.Item(x))
ElseIf cmbPosition.SelectedItem = "Numeric Increment" Then
fileShortRenamed = txtPath.Text & "\" & i & "." & getFileExtension(lstInitial.Items.Item(x))
Else
fileShortRenamed = txtPath.Text & "\" & i & "_" & txtStartFilenameWith.Text & "." & getFileExtension(lstInitial.Items.Item(x))
End If
listfiles.Move(txtPath.Text & "\" & lstInitial.Items.Item(x), fileShortRenamed)
i = i + 1
fileShortRenamed = Replace(fileShortRenamed, txtPath.Text & "\", "")
lstFinal.Items.Add(fileShortRenamed)
Next x
End Sub
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cmbPosition.SelectedItem = "Beginning Of File Name"
End Sub
End Class
|
Public Class vprofesores
Dim idprofesor As Integer
Dim nombre, apellido, domicilio, telefono As String
'seter y geteer
Public Property gidprofesor
Get
Return idprofesor
End Get
Set(value)
idprofesor = value
End Set
End Property
Public Property gnombre
Get
Return nombre
End Get
Set(value)
nombre = value
End Set
End Property
Public Property gapellido
Get
Return apellido
End Get
Set(value)
apellido = value
End Set
End Property
Public Property gdomicilio
Get
Return domicilio
End Get
Set(value)
domicilio = value
End Set
End Property
Public Property gtelefono
Get
Return telefono
End Get
Set(value)
telefono = value
End Set
End Property
'constructor
Public Sub New()
End Sub
Public Sub New(ByVal idprofesor As Integer, ByVal nombre As String, ByVal apellido As String, ByVal domicilio As String, ByVal telefono As String)
gidprofesor = idprofesor
gnombre = nombre
gapellido = apellido
gdomicilio = domicilio
gtelefono = telefono
End Sub
End Class
|
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=NameOf(HungarianNotationCodeFixProvider)), [Shared]>
Public Class HungarianNotationCodeFixProvider
Inherits CodeFixProvider
Private Const title As String = "Remove Hungarian Notation"
Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String)
Get
Return ImmutableArray.Create(HungarianNotationAnalyzer.DiagnosticId)
End Get
End Property
Public NotOverridable Overrides Function GetFixAllProvider() As FixAllProvider
Return WellKnownFixAllProviders.BatchFixer
End Function
Public NotOverridable Overrides Async Function RegisterCodeFixesAsync(context As CodeFixContext) As Task
Dim root = Await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(False)
Dim diagnostic = context.Diagnostics.First()
Dim diagnosticSpan = diagnostic.Location.SourceSpan
' Find the type statement identified by the diagnostic.
Dim declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType(Of LocalDeclarationStatementSyntax)().First()
' Register a code action that will invoke the fix.
context.RegisterCodeFix(
CodeAction.Create(
title:=title,
createChangedSolution:=Function(c) Fix(context.Document, declaration, c),
equivalenceKey:=title),
diagnostic)
End Function
Private Async Function Fix(document As Document, declaration As LocalDeclarationStatementSyntax, cancellationToken As CancellationToken) As Task(Of Solution)
Dim sm As SemanticModel = Nothing
document.TryGetSemanticModel(sm)
If (sm Is Nothing) Then Return Nothing
Dim result As Solution = document.Project.Solution
Dim delcarations As New SeparatedSyntaxList(Of VariableDeclaratorSyntax)
For Each declarator In declaration.Declarators
For Each name In declarator.Names
Dim varName As String = name.Identifier.Text
If Not (varName.Length > 1 AndAlso Char.IsLower(varName(0)) AndAlso Char.IsUpper(varName(1))) Then Continue For
Dim newName = varName.Substring(1)
newName = newName.Substring(0, 1).ToLower() & newName.Substring(1)
Dim nameInfo = sm.GetDeclaredSymbol(name, Nothing)
If sm.LookupSymbols(declaration.SpanStart, Nothing, newName, False).Any() Then Continue For
result = Await Renamer.RenameSymbolAsync(result, nameInfo, newName, Nothing, cancellationToken)
Next
Next
Return result
End Function
End Class |
'===============================================================================
' EntitySpaces 2010 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 : 2010.1.1011.0
' EntitySpaces Driver : SQL
' Date Generated : 10/9/2010 5:04:23 PM
'===============================================================================
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Imports System.Linq
Imports System.ServiceModel.DomainServices.Hosting
Imports System.ServiceModel.DomainServices.Server
Imports EntitySpaces.Core
Imports EntitySpaces.Interfaces
Imports EntitySpaces.DynamicQuery
Imports Silverlight_RiaServices.BusinessObjects
Namespace esDomainServices
' Add Custom Methods here, this file will not be ovewrriten
Partial Public Class esDomainService
''' <summary>
''' Give you a chance to handle any error during PersistChangeSet()
''' </summary>
''' <param name="ex">The Exception</param>
''' <returns>True if handle, otherwise the Exception is rethrown and bubbled up</returns>
Private Function HandleError(ByVal ex As Exception) As Boolean
Return False
End Function
<Query()> _
Public Function Employees_Prefetch() As EmployeesCollection
' Very simplistic prefetch ..
Dim coll As New EmployeesCollection()
coll.Query.Prefetch(Employees.Prefetch_OrdersCollectionByEmployeeID)
coll.Query.Prefetch(Employees.Prefetch_OrdersCollectionByEmployeeID, Orders.Prefetch_OrderDetailsCollectionByOrderID)
coll.Query.Load()
Return coll
End Function
<Query()> _
Public Function Employees_PrefetchSophisticated() As EmployeesCollection
' EmployeeID = "1"
Dim coll As New EmployeesCollection()
coll.Query.Where(coll.Query.EmployeeID = 1)
' Orders Query (nothing fancy, just ensure we're only getting Orders for EmployeeID = 1
Dim o As OrdersQuery = coll.Query.Prefetch(Of OrdersQuery)(Employees.Prefetch_OrdersCollectionByEmployeeID)
Dim e1 As EmployeesQuery = o.GetQuery(Of EmployeesQuery)()
o.Where(e1.EmployeeID = 1)
' OrderDetailsQuery (here we even limit the Select in addition to EmployeeID = 1) notice the "false"
Dim od As OrderDetailsQuery = coll.Query.Prefetch(Of OrderDetailsQuery)(False, Employees.Prefetch_OrdersCollectionByEmployeeID, Orders.Prefetch_OrderDetailsCollectionByOrderID)
Dim e2 As EmployeesQuery = od.GetQuery(Of EmployeesQuery)()
od.Where(e2.EmployeeID = 1)
od.[Select](od.OrderID, od.ProductID, od.UnitPrice)
coll.Query.Load()
Return coll
End Function
<Query()> _
Public Function Products_LoadWithExtraColumn() As ProductsCollection
Dim p As New ProductsQuery("p")
Dim s As New SuppliersQuery("s")
' Bring back the suppliers name for the Product from the Supplier table
p.[Select](p, s.CompanyName.[As]("SupplierName"))
p.InnerJoin(s).[On](p.SupplierID = s.SupplierID)
Dim coll As New ProductsCollection()
coll.Load(p)
Return coll
End Function
End Class
End Namespace
|
Imports System
Imports PermutationLibrary
Module PermutorShowcaseVB
Sub Main()
Dim PERMUTATION_SIZE As Integer = 1
Dim INPUT_VARARRAY() As Char = {"a", "b", "c", "d", "e"}
Dim ALLOW_DUPLICATES As Boolean = True
'SetInputAsAlphabet(INPUT_VARARRAY)
Dim permutor As New Permutor(Of Char)(PERMUTATION_SIZE, INPUT_VARARRAY, ALLOW_DUPLICATES)
'' LIST PERMUTING
'Console.WriteLine("LIST PERMUTING")
'Dim permutedList As List(Of Char()) = permutor.PermuteToList
'For Each permutation As String In permutedList
' Console.WriteLine(permutation)
'Next
'Console.WriteLine("Generated " & permutor.GetNoOfPermutations & " permutations.")
'' BASIC LIST PERMUTING
'Console.WriteLine("BASIC LIST PERMUTING")
'Dim basicPermutedList As List(Of Char()) = permutor.BasicPermuteToList
'For Each permutation As String In basicPermutedList
' Console.WriteLine(permutation)
'Next
'' STREAM PERMUTING
'Console.WriteLine("STREAM PERMUTING")
'Dim permutedStreamReceiver As Char()
'permutor.InitStreamPermutor()
'While permutor.IsStreamActive
' permutedStreamReceiver = permutor.GetPermutationFromStream
' Console.WriteLine(permutedStreamReceiver)
'End While
'Console.WriteLine("Generated " & permutor.GetNoOfPermutations & " permutations.")
'' RANDOM PERMUTING
'Console.WriteLine("RANDOM PERMUTING")
'SetInputAsAlphabet(INPUT_VARARRAY)
'permutor.Configure(40, INPUT_VARARRAY, True)
'Dim generator As New Random
'Dim randomPermuted As Char()
'For i As Integer = 1 To 9
' randomPermuted = permutor.GetRandomPermutation(generator)
' Console.WriteLine(i & ". " & randomPermuted)
'Next
'' DISPOSAL
'permutor.Dispose()
Console.ReadLine()
End Sub
Private Sub SetInputAsAlphabet(ByRef INPUT_VARARRAY As Char())
Dim alphabet As New List(Of Char)
For i As Integer = 0 To 25
alphabet.Add(Microsoft.VisualBasic.Chr(97 + i))
Next
INPUT_VARARRAY = alphabet.ToArray
End Sub
End Module
|
'---------------------------------------------------------------------------------------------------
' copyright file="CustomerOrder.vb" company="CitrusLime Ltd"
' Copyright (c) CitrusLime Ltd. All rights reserved.
' copyright
'---------------------------------------------------------------------------------------------------
'''-------------------------------------------------------------------------------------------------
''' <summary>A customer order.</summary>
'''-------------------------------------------------------------------------------------------------
Public Class CustomerOrder
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the UID.</summary>
''' <value>The UID.</value>
'''-------------------------------------------------------------------------------------------------
Public Property uid As Integer
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the client reference.</summary>
''' <value>The client reference.</value>
'''-------------------------------------------------------------------------------------------------
Public Property ClientRef As Integer
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets whether the order is closed.</summary>
''' <value>Whether the order is closed.</value>
'''-------------------------------------------------------------------------------------------------
Public Property Closed As Boolean
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the date created.</summary>
''' <value>The date created.</value>
'''-------------------------------------------------------------------------------------------------
Public Property DateCreated As DateTime
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the type of order.</summary>
''' <remarks>0: Not an Order, 2: Workorder, 3: Quote, 4: Backorder, 5: Layaway, 6: Workshop</remarks>
''' <value>The type of order.</value>
'''-------------------------------------------------------------------------------------------------
Public Property Type As Integer
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the comment.</summary>
''' <value>The comment.</value>
'''-------------------------------------------------------------------------------------------------
Public Property Comment As String
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the identifier of the customer.</summary>
''' <value>The identifier of the customer.</value>
'''-------------------------------------------------------------------------------------------------
Public Property CustomerID As Integer
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the identifier of the ship to address.</summary>
''' <value>The identifier of the ship to address.</value>
'''-------------------------------------------------------------------------------------------------
Public Property ShipToID As Integer
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the deposit.</summary>
''' <value>The deposit.</value>
'''-------------------------------------------------------------------------------------------------
Public Property Deposit As Decimal
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the tax.</summary>
''' <value>The tax.</value>
'''-------------------------------------------------------------------------------------------------
Public Property Tax As Decimal
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the total.</summary>
''' <value>The total.</value>
'''-------------------------------------------------------------------------------------------------
Public Property Total As Decimal
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the last updated date.</summary>
''' <value>The last updated date.</value>
'''-------------------------------------------------------------------------------------------------
Public Property LastUpdated As DateTime
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the due date.</summary>
''' <value>The due date.</value>
'''-------------------------------------------------------------------------------------------------
Public Property DueDate As DateTime
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets whether the order is taxable.</summary>
''' <value>Whether the order is taxable.</value>
'''-------------------------------------------------------------------------------------------------
Public Property Taxable As Boolean
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the identifier of the sales rep.</summary>
''' <value>The identifier of the sales rep.</value>
'''-------------------------------------------------------------------------------------------------
Public Property SalesRepID As Integer
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the reference number.</summary>
''' <value>The reference number.</value>
'''-------------------------------------------------------------------------------------------------
Public Property ReferenceNumber As String
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the shipping charge on the order.</summary>
''' <value>The shipping charge on the order.</value>
'''-------------------------------------------------------------------------------------------------
Public Property ShippingChargeOnOrder As Double
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the type of the channel.</summary>
''' <value>The type of the channel.</value>
'''-------------------------------------------------------------------------------------------------
Public Property ChannelType As Integer
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets whether the customer has checked in parts to fulfill the order.</summary>
''' <remarks>This is used for workshop orders.</remarks>
''' <value>Whether the customer has checked in parts.</value>
'''-------------------------------------------------------------------------------------------------
Public Property CheckedIn As Boolean
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the name of the customer.</summary>
''' <value>The name of the customer.</value>
'''-------------------------------------------------------------------------------------------------
Public Property CustomerName As String
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets or sets the order lines.</summary>
''' <value>The order lines.</value>
'''-------------------------------------------------------------------------------------------------
Public Property orderlines As OrderLine()
End Class |
Imports Microsoft.EntityFrameworkCore
Imports System.Collections.Generic
Public Class DoKUser
Public Property UserName As String
Public Property ScreenName As String
Public Property DateCreated As DateTime
End Class
Public Class DoKUserContext Inherits DbContext |
Imports System.ComponentModel.DataAnnotations
Imports System.ComponentModel.DataAnnotations.Schema
Namespace JhonyLopez.EmetraApp2017090.Model
Public Class Neighbor
#Region "Campos"
Private _NIT As String
Private _DPI As Integer
Private _FirstName As String
Private _LastName As String
Private _Adress As String
Private _Municipality As String
Private _PostalCode As Integer
Private _Telephone As Integer
#End Region
#Region "Llaves"
Public Overridable Property Vehicles() As ICollection(Of Vehicle)
#End Region
#Region "Propiedades"
<Key>
Public Property NIT As String
Get
Return _NIT
End Get
Set(value As String)
_NIT = value
End Set
End Property
Public Property DPI As Integer
Get
Return _DPI
End Get
Set(value As Integer)
_DPI = value
End Set
End Property
Public Property FirstName As String
Get
Return _FirstName
End Get
Set(value As String)
_FirstName = value
End Set
End Property
Public Property LastName As String
Get
Return _LastName
End Get
Set(value As String)
_LastName = value
End Set
End Property
Public Property Adress As String
Get
Return _Adress
End Get
Set(value As String)
_Adress = value
End Set
End Property
Public Property Municipality As String
Get
Return _Municipality
End Get
Set(value As String)
_Municipality = value
End Set
End Property
Public Property PostalCode As Integer
Get
Return _PostalCode
End Get
Set(value As Integer)
_PostalCode = value
End Set
End Property
Public Property Telephone As Integer
Get
Return _Telephone
End Get
Set(value As Integer)
_Telephone = value
End Set
End Property
#End Region
End Class
End Namespace
|
Imports System.Data.SqlClient
Namespace DataObjects.TableObjects
''' <summary>
''' Provides the functionality to manage data from the table tbl_forgotten_password based on business functionality
''' </summary>
<Serializable()> _
Public Class tbl_forgotten_password
Inherits DBObjectBase
#Region "Class Level Fields"
''' <summary>
''' Instance of DESettings
''' </summary>
Private _settings As New DESettings
''' <summary>
''' Class Name which is used in cache key construction
''' </summary>
Const CACHEKEY_CLASSNAME As String = "tbl_forgotten_password"
#End Region
#Region "Constructors"
Sub New()
End Sub
''' <summary>
''' Initializes a new instance of the <see cref="tbl_address" /> class.
''' </summary>
''' <param name="settings">The DESettings instance</param>
Sub New(ByVal settings As DESettings)
_settings = settings
End Sub
#End Region
#Region "Public Methods"
''' <summary>
''' Create a log for the specified functionality in table and returns log header id as reference and no of rows affected
''' </summary>
''' <param name="businessUnit">The businessUnit.</param>
''' <param name="partner">The partner.</param>
''' <param name="status">The status of the token</param>
''' <param name="customerNumber">The login id.</param>
''' <param name="email">The customer email address</param>
''' <param name="hashedToken">The hashed token that is sent to the customer</param>
''' <param name="validTime">The amount of time the token will be valid for, in minutes</param>
''' <returns>no of affected rows</returns>
Public Function Insert(ByVal businessUnit As String, ByVal partner As String, ByVal hashedToken As String, ByVal status As String, ByVal customerNumber As String, ByVal email As String, ByVal validTime As Integer) As Integer
Dim rowsAffected As Integer = 0
Dim talentSqlAccessDetail As New TalentDataAccess
Dim err As New ErrorObj
Try
'Construct The Call
talentSqlAccessDetail.Settings = _settings
talentSqlAccessDetail.Settings.Cacheing = False
talentSqlAccessDetail.Settings.CacheStringExtension = ""
talentSqlAccessDetail.CommandElements.CommandExecutionType = CommandExecution.ExecuteNonQuery
Dim sqlStatement As String = "INSERT INTO TBL_FORGOTTEN_PASSWORD (" & _
"BUSINESS_UNIT, PARTNER, HASHED_TOKEN, STATUS, CUSTOMER_NUMBER, EMAIL_ADDRESS, TIMESTAMP, EXPIRE_TIMESTAMP, LAST_UPDATED) " & _
"VALUES (@BUSINESS_UNIT, @PARTNER, @HASHED_TOKEN, @STATUS, @CUSTOMER, @EMAIL, GETDATE(), DATEADD(minute, @VALIDTIME, GETDATE()), GETDATE())"
talentSqlAccessDetail.CommandElements.CommandText = sqlStatement.ToString
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@BUSINESS_UNIT", businessUnit))
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@PARTNER", partner))
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@HASHED_TOKEN", hashedToken))
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@STATUS", status))
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@CUSTOMER", customerNumber))
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@EMAIL", email))
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@VALIDTIME", validTime, SqlDbType.Int))
'Execute
err = talentSqlAccessDetail.SQLAccess()
If (Not (err.HasError)) And (Not (talentSqlAccessDetail.ResultDataSet Is Nothing)) Then
rowsAffected = talentSqlAccessDetail.ResultDataSet.Tables(0).Rows(0)(0)
End If
talentSqlAccessDetail = Nothing
Catch ex As Exception
Throw ex
End Try
'Return results
Return rowsAffected
End Function
''' <summary>
''' Sets all of a customer's tokens to expired.
''' </summary>
''' <param name="customer">Customer number</param>
''' <param name="status">New status to set record to</param>
''' <param name="businessUnit">Optional business unit</param>
''' <param name="partner">Optional partner</param>
''' <remarks></remarks>
''' <returns>Number of affected rows</returns>
Public Function SetCustomerTokensAsUsed(ByVal customer As String, ByVal status As String, Optional ByVal businessUnit As String = "", Optional ByVal partner As String = "") As Integer
Dim rowsAffected As Integer = 0
Dim talentSqlAccessDetail As New TalentDataAccess
Dim err As New ErrorObj
Try
'Construct The Call
talentSqlAccessDetail.Settings = _settings
talentSqlAccessDetail.Settings.Cacheing = False
talentSqlAccessDetail.CommandElements.CommandExecutionType = CommandExecution.ExecuteNonQuery
Dim sqlStatement As String = "UPDATE tbl_forgotten_password SET EXPIRE_TIMESTAMP = GETDATE(), STATUS = @STATUS, LAST_UPDATED = GETDATE() WHERE CUSTOMER_NUMBER = @CUST"
talentSqlAccessDetail.CommandElements.CommandText = sqlStatement
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@CUST", customer))
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@STATUS", status))
If Not String.IsNullOrEmpty(businessUnit) Then
talentSqlAccessDetail.CommandElements.CommandText += " AND BUSINESS_UNIT = @businessUnit "
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@businessUnit", businessUnit))
End If
If Not String.IsNullOrEmpty(partner) Then
talentSqlAccessDetail.CommandElements.CommandText += " AND partner = @partner "
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@partner", partner))
End If
'Execute
err = talentSqlAccessDetail.SQLAccess()
If (Not (err.HasError)) And (Not (talentSqlAccessDetail.ResultDataSet Is Nothing)) Then
rowsAffected = talentSqlAccessDetail.ResultDataSet.Tables(0).Rows(0)(0)
End If
talentSqlAccessDetail = Nothing
Catch ex As Exception
Throw ex
End Try
'return results
Return rowsAffected
End Function
''' <summary>
''' Used to find a record by it's hashed token
''' </summary>
''' <param name="hashedToken">the token after being hashed using SHA512</param>
''' <param name="businessUnit">The business unit, optional</param>
''' <param name="partner">the partner, also optional</param>
''' <returns>A data table of the results</returns>
''' <remarks></remarks>
Public Function GetByHashedToken(ByVal hashedToken As String, Optional ByVal businessUnit As String = "", Optional ByVal partner As String = "") As DataTable
Dim outputDataTable As New DataTable
Dim talentSqlAccessDetail As New TalentDataAccess
Try
'Construct The Call
talentSqlAccessDetail.Settings = _settings
talentSqlAccessDetail.CommandElements.CommandExecutionType = CommandExecution.ExecuteDataSet
talentSqlAccessDetail.CommandElements.CommandText = "SELECT * FROM tbl_forgotten_password WHERE HASHED_TOKEN = @HASHED_TOKEN "
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@HASHED_TOKEN", hashedToken))
If Not String.IsNullOrEmpty(businessUnit) Then
talentSqlAccessDetail.CommandElements.CommandText += " AND BUSINESS_UNIT = @businessUnit "
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@businessUnit", businessUnit))
End If
If Not String.IsNullOrEmpty(partner) Then
talentSqlAccessDetail.CommandElements.CommandText += " AND partner = @partner "
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@partner", partner))
End If
'Execute
Dim err As New ErrorObj
err = talentSqlAccessDetail.SQLAccess()
If (Not (err.HasError)) And (Not (talentSqlAccessDetail.ResultDataSet Is Nothing)) Then
outputDataTable = talentSqlAccessDetail.ResultDataSet.Tables(0)
End If
Catch ex As Exception
Throw
Finally
talentSqlAccessDetail = Nothing
End Try
'Return the results
Return outputDataTable
End Function
''' <summary>
''' Lets you mark a token as used.
''' </summary>
''' <param name="hashedToken">the token after being hashed using SHA512</param>
''' <param name="businessUnit">Optional business unit</param>
''' <param name="partner">Optional partner</param>
''' <remarks>This will set the expiry to now. So once the record is used it will be deleted by TalentAdmin</remarks>
Public Function SetTokenAsUsed(ByVal hashedToken As String, Optional ByVal businessUnit As String = "", Optional ByVal partner As String = "") As Integer
Dim rowsAffected As Integer = 0
Dim talentSqlAccessDetail As New TalentDataAccess
Dim err As New ErrorObj
'Construct The Call
talentSqlAccessDetail.Settings = _settings
talentSqlAccessDetail.Settings.Cacheing = False
talentSqlAccessDetail.CommandElements.CommandExecutionType = CommandExecution.ExecuteNonQuery
talentSqlAccessDetail.CommandElements.CommandText = "UPDATE TBL_FORGOTTEN_PASSWORD SET EXPIRE_TIMESTAMP = GETDATE(), STATUS = 'EXPIRED', LAST_UPDATED = GETDATE() WHERE HASHED_TOKEN = @HASH"
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@HASH", hashedToken))
If Not String.IsNullOrEmpty(businessUnit) Then
talentSqlAccessDetail.CommandElements.CommandText += " AND BUSINESS_UNIT = @businessUnit "
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@businessUnit", businessUnit))
End If
If Not String.IsNullOrEmpty(partner) Then
talentSqlAccessDetail.CommandElements.CommandText += " AND PARTNER = @partner "
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@partner", partner))
End If
'Execute
err = talentSqlAccessDetail.SQLAccess()
If (Not (err.HasError)) And (Not (talentSqlAccessDetail.ResultDataSet Is Nothing)) Then
rowsAffected = talentSqlAccessDetail.ResultDataSet.Tables(0).Rows(0)(0)
End If
talentSqlAccessDetail = Nothing
Return rowsAffected
End Function
#End Region
End Class
End Namespace |
Imports System.Runtime.CompilerServices
Imports System.Data.Common
Public Module DbCommandExtensions
<Extension()>
Public Function AddParameter(Of T)(ByVal cmd As DbCommand, ByVal name As String, ByVal value As T) As DbCommand
cmd.AddParameter(name, value, DbTypeLookup.GetDbType(GetType(T)))
Return cmd
End Function
<Extension()>
Public Function AddParameter(ByVal cmd As DbCommand, ByVal name As String, ByVal value As Object, ByVal type As DbType) As DbCommand
Dim param = cmd.CreateParameter()
param.ParameterName = name
param.Value = If(value, DBNull.Value)
param.DbType = type
cmd.Parameters.Add(param)
Return cmd
End Function
<Extension()>
Public Function ExecuteScalar(Of T)(ByVal cmd As DbCommand) As T
Return DirectCast(cmd.ExecuteScalar(), T)
End Function
<Extension()>
Public Async Function ExecuteScalarAsync(Of T)(ByVal cmd As DbCommand) As Task(Of T)
Return DirectCast(Await cmd.ExecuteScalarAsync(), T)
End Function
End Module |
'Copyright 2014 Fariz Luqman
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
Module module_timekeeper
Public Function getTimeIn(ByVal pc As String) As String
Return System.Convert.ToDateTime(readClientConfig("clients", "timein", pc))
End Function
Public Function getTimeOut(ByVal pc As String) As String
Return System.Convert.ToDateTime(readClientConfig("clients", "timeout", pc))
End Function
Public Function getTotalTime(ByVal pc As String) As String
Dim TotalTime As TimeSpan
Dim TimeIn As DateTime
Dim TimeOut As DateTime
Dim hours As Integer
Dim minutes As Integer
Dim seconds As Integer
Dim formattedTotalTime As String
Dim accesslevel As Integer = Int(readClientConfig("clients", "accesslevel", pc))
If accesslevel = 1 Then
' counting backwards
TimeOut = System.Convert.ToDateTime(readClientConfig("clients", "timeout", pc))
TimeIn = System.Convert.ToDateTime(readClientConfig("clients", "timein", pc))
TotalTime = TimeOut - TimeIn
ElseIf accesslevel = 2 Then
' counting forward
TimeIn = System.Convert.ToDateTime(readClientConfig("clients", "timein", pc))
TotalTime = DateTime.Now - TimeIn
End If
hours = TotalTime.TotalHours
minutes = TotalTime.Minutes
seconds = TotalTime.Seconds
formattedTotalTime = Format(hours, "00") + " h " + Format(minutes, "00") + " m " + Format(seconds, "00") + " s "
Return formattedTotalTime
End Function
Public Function calculateTimeLeft(ByVal pc As String) As String
Dim d1 As DateTime = DateTime.Now
Dim d2 As DateTime = System.Convert.ToDateTime(readClientConfig("clients", "timeout", pc))
Dim difference As TimeSpan = d2 - d1
'round down total hours to integer'
Dim hours = Math.Floor(difference.TotalHours)
Dim minutes = Math.Abs(difference.Minutes)
Dim seconds = difference.Seconds
Dim timeleft As String = Format(hours, "00") + " h " + Format(minutes, "00") + " m " + Format(seconds, "00") + " s "
If Int(seconds) < 0 Then
timeleft = "00 h 00 m 00 s (Time Out)"
saveClientConfig("clients", "istimeout", 1, pc)
End If
Return timeleft
End Function
Public Function addtime(ByVal hours As Integer, ByVal minutes As Integer, ByVal prepaidmode As Integer, ByVal pc As String) As String
' this function will receive add-on hours & minutes, and then generate a new time out.
' usage: addtime(hours,minutes,prepaidmode,pc)
' prepaid mode 0 for unlock and 1 for expand time
Dim timeout As DateTime
Dim newtimeout As DateTime
If prepaidmode = 0 Then
' for unlock pc mode we calculate the time out by: adding Now + add-on time
timeout = Now.ToLocalTime
newtimeout = timeout.AddHours(hours)
newtimeout = newtimeout.AddMinutes(minutes)
ElseIf prepaidmode = 1 Then
' for expand time mode we calculate the time out by: adding old timeout + add-on time
timeout = DateTime.Parse(getTimeOut(pc))
newtimeout = timeout.AddHours(hours)
newtimeout = newtimeout.AddMinutes(minutes)
End If
Return newtimeout ' return the time
End Function
Public Function recordTime(ByVal hours As Integer, ByVal minutes As Integer, ByVal pc As String)
Dim newHours As Integer
Dim newMinutes As Integer
Dim accesslevel As Integer = Int(readClientConfig("clients", "accesslevel", pc))
If accesslevel = 0 Then
saveClientConfig("clients", "hours", 0, pc)
saveClientConfig("clients", "minutes", 0, pc)
End If
Dim oldHours As Integer = readClientConfig("clients", "hours", pc)
Dim oldMinutes As Integer = readClientConfig("clients", "minutes", pc)
newHours = oldHours + hours
newMinutes = oldMinutes + minutes
saveClientConfig("clients", "hours", newHours, pc)
saveClientConfig("clients", "minutes", newMinutes, pc)
Return 0
End Function
Public Function logout(ByVal pc As String)
saveClientConfig("clients", "accesslevel", 0, pc)
Return 0
End Function
Public Function open(ByVal pc As String)
saveClientConfig("clients", "accesslevel", 2, pc)
saveClientConfig("clients", "timein", Now, pc)
Return 0
End Function
End Module |
'**Update HelpBO** to include a list of AttachmentBO for the Templates property (we don't need to display the user name so just leave it blank instead of looking up from registration).
Public Class HelpBO
Public Property TOCID As Integer
Public Property ParentTOCID As Integer
Public Property ScreenTitle As String
Public Property NavigateUrl As String
Public Property Instructions As String
Public Property ScreenRules As ScreenRuleBO
Public Property Templates As List(Of AttachmentBO)
End Class
|
Public Class Form1
Dim WithEvents Grid As New ReverseGrid
Dim Turn As CellStatus = CellStatus.Black '今どっちの順番か
Dim PlayerColor As CellStatus = CellStatus.Black 'プレイヤーの色
Dim Computer As New CpuLevel3(Grid, CellStatus.White)
'■Start
''' <summary>ゲームを開始します。</summary>
''' <param name="PlayerColor">人間の石の色を指定します。</param>
''' <remarks>黒が先手になります。</remarks>
Private Sub Start(ByVal PlayerColor As CellStatus)
Grid.Initialize()
Me.PlayerColor = PlayerColor '人間の色
If PlayerColor = CellStatus.Black Then
Computer.Standard = CellStatus.White 'コンピュータの色は白
Else
Computer.Standard = CellStatus.Black 'コンピュータの色は黒
End If
'現在の黒と白の駒の数を表示する
lblBlackCount.Text = Grid.Count(CellStatus.Black)
lblWhiteCount.Text = Grid.Count(CellStatus.White)
'ChangeTurnを呼び出して黒の番を開始する。そのために仮に今は白の番であることにする。
Turn = CellStatus.White
ChangeTurn()
End Sub
Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
Grid.Draw(e.Graphics)
End Sub
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
'マウスの座標をPictureBox1のコントロール座標に変換する。
Dim Pos As Point = PictureBox1.PointToClient(Windows.Forms.Cursor.Position)
Dim ThisCell As Cell
ThisCell = Grid.CellFromPoint(Pos.X, Pos.Y)
If Grid.Put(Turn, ThisCell.Position.X, ThisCell.Position.Y) Then
ChangeTurn()
End If
End Sub
''' <summary>マウスの移動に伴ってセルにアクティブを示す枠を描画する</summary>
Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
Dim ThisCell As Cell
'マウスがある位置のセルを取得
ThisCell = Grid.CellFromPoint(e.X, e.Y)
If Not IsNothing(ThisCell) Then
'セルが取得できた場合は、セルにアクティブを示す枠を描画
ThisCell.Focus()
'現在の状態を描画(PictureBox1のPaintイベントを発生させる)
PictureBox1.Invalidate() '←実際の描画はすべてここで行う
End If
End Sub
'■ChangeTurn
''' <summary>ターン交代</summary>
Public Sub ChangeTurn()
'現在の状態を描画(PictureBox1のPaintイベントを発生させる)
PictureBox1.Invalidate()
'▼勝敗判定
If Grid.Count(CellStatus.Nothing) = 0 Then
'全セルへの配置が終了した場合は勝敗判定して終了
If Grid.Count(CellStatus.Black) > Grid.Count(CellStatus.White) Then
MsgBox("黒の勝ちです!")
ElseIf Grid.Count(CellStatus.Black) < Grid.Count(CellStatus.White) Then
MsgBox("白の勝ちです!")
Else
MsgBox("引き分けです!!")
End If
Return
ElseIf Grid.PuttableCount(CellStatus.Black) = 0 AndAlso Grid.PuttableCount(CellStatus.White) = 0 Then
'空いているセルがあるのに黒も白も置けない場合
If Grid.Count(CellStatus.Black) > Grid.Count(CellStatus.White) Then
MsgBox("黒の勝ちです!")
ElseIf Grid.Count(CellStatus.Black) < Grid.Count(CellStatus.White) Then
MsgBox("白の勝ちです!")
Else
MsgBox("引き分けです!!")
End If
Return
ElseIf Grid.Count(CellStatus.Black) = 0 Then
'すべての石が白になった場合(=黒の石が0個の場合)
MsgBox("白の勝ちです!")
Return
ElseIf Grid.Count(CellStatus.White) = 0 Then
'すべての石が黒になった場合(=白の石が0個の場合)
MsgBox("黒の勝ちです!")
Return
End If
'▼次のターンの決定
If Turn = CellStatus.Black Then
Turn = CellStatus.White
lblBlackTurn2.Visible = False
lblWhiteTurn.Visible = True
Else
Turn = CellStatus.Black
lblBlackTurn2.Visible = True
lblWhiteTurn.Visible = False
End If
'▼置ける場所があるか判定
If Grid.PuttableCount(Turn) = 0 Then
'置く場所がなければパスして次のターン
ChangeTurn()
End If
'▼人間かコンピュータかで処理を分岐
If Turn = PlayerColor Then
'人間の番ならば、PictureBoxを使用可能にする。
PictureBox1.Enabled = True
Else
'コンピュータの番ならば、PictureBoxを使用不可にする。
PictureBox1.Enabled = False
'ちょっと時間をおく
Application.DoEvents()
System.Threading.Thread.Sleep(500)
'コンピュータに石を置かせる。どのセルに置くかはコンピュータ(AI)が決定する。
Computer.PutStone()
ChangeTurn() 'プレイヤーの番へ
End If
End Sub
''' <summary>石を置いたときに発生するイベント</summary>
Private Sub Grid_PutNew(ByVal sender As Object, ByVal e As System.EventArgs) Handles Grid.PutNew
Call Grid_Reversed(sender, e)
End Sub
''' <summary>石がひっくり返されたときに発生するイベント</summary>
Private Sub Grid_Reversed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Grid.Reversed
'現在の状態を描画(PictureBox1のPaintイベントを発生させる)
PictureBox1.Invalidate()
'現在の黒と白の石の数を表示する
lblBlackCount.Text = Grid.Count(CellStatus.Black)
lblWhiteCount.Text = Grid.Count(CellStatus.White)
'ちょっと時間をおく
Application.DoEvents()
System.Threading.Thread.Sleep(500)
End Sub
Private Sub btnStartBlack_Click(sender As Object, e As EventArgs) Handles btnStartBlack.Click
Start(CellStatus.Black)
End Sub
Private Sub btnStartWhite_Click(sender As Object, e As EventArgs) Handles btnStartWhite.Click
Start(CellStatus.White)
End Sub
End Class
|
Imports BVSoftware.Bvc5.Core
Partial Class BVModules_Controls_ProductMainImage
Inherits System.Web.UI.UserControl
'Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'End Sub
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
If TypeOf Me.Page Is BaseStoreProductPage Then
Dim product As Catalog.Product = DirectCast(Me.Page, BaseStoreProductPage).LocalProduct
If product IsNot Nothing Then
' Image
Me.imgMain.ImageUrl = Me.Page.ResolveUrl(Utilities.ImageHelper.GetValidImage(product.ImageFileMedium, True))
Me.imgMain.AlternateText = HttpUtility.HtmlEncode(product.ImageFileMediumAlternateText)
Me.imgMain.Attributes.Add("itemprop", "image")
' New badge
If product.IsNew() AndAlso WebAppSettings.NewProductBadgeAllowed Then
BadgeImage.Visible = True
Else
BadgeImage.Visible = False
End If
End If
End If
' Force Image Size
ViewUtilities.ForceImageSize(imgMain, imgMain.ImageUrl, ViewUtilities.Sizes.Medium, Me.Page)
Dim id As String = Request.QueryString("ProductID")
Dim baseProd As Catalog.Product = Catalog.InternalProduct.FindByBvin(id)
If baseProd IsNot Nothing Then
If baseProd.AdditionalImages.Count > 0 Then
Me.AdditionalImagesLink.Visible = True
Me.AdditionalImagesLink.Style.Add("cursor", "pointer")
Me.AdditionalImagesLink.Attributes.Add("onclick", ViewUtilities.GetAdditionalImagesPopupJavascript(id, Me.Page))
End If
End If
End Sub
End Class
|
Public Class DBO_Articulos_ArticulosCertificadosTipos
Private m_Articulo_ArticuloCertificadoTipoID As Int32
Private m_ArticuloID As Nullable(Of Int32)
Private m_ArticuloCertificadoTipoID As Nullable(Of Int32)
Private m_Observaciones As String
Private m_FechaModificacion As date
Private m_UsuarioModificacion As Int32
Public Sub New()
End Sub
Public Property Articulo_ArticuloCertificadoTipoID() As Int32
Get
Return m_Articulo_ArticuloCertificadoTipoID
End Get
Set(ByVal value As Int32)
m_Articulo_ArticuloCertificadoTipoID = value
End Set
End Property
Public Property ArticuloID() As Nullable(Of Int32)
Get
Return m_ArticuloID
End Get
Set(ByVal value As Nullable(Of Int32))
m_ArticuloID = value
End Set
End Property
Public Property ArticuloCertificadoTipoID() As Nullable(Of Int32)
Get
Return m_ArticuloCertificadoTipoID
End Get
Set(ByVal value As Nullable(Of Int32))
m_ArticuloCertificadoTipoID = value
End Set
End Property
Public Property Observaciones() As String
Get
Return m_Observaciones
End Get
Set(ByVal value As String)
m_Observaciones = value
End Set
End Property
Public Property FechaModificacion() As Date
Get
Return m_FechaModificacion
End Get
Set(ByVal value As Date)
m_FechaModificacion = value
End Set
End Property
Public Property UsuarioModificacion() As Int32
Get
Return m_UsuarioModificacion
End Get
Set(ByVal value As Int32)
m_UsuarioModificacion = value
End Set
End Property
End Class
|
Imports System
Imports System.Collections.Generic
Partial Public Class HistoriqueMouvement
Public Property Id As Long
Public Property JournalCaisseId As Long
Public Property CollecteurId As Long
Public Property ClientId As Long
Public Property TraitementId As Long?
Public Property Latitude As String
Public Property Longitude As String
Public Property Montant As Decimal?
Public Property DateOperation As Date?
Public Property Pourcentage As Decimal?
Public Property MontantRetenu As Decimal?
Public Property PartBANK As Decimal?
Public Property PartCLIENT As Decimal?
Public Property EstTraiter As Integer = 0
Public Property DateTraitement As Date?
Public Property Etat As Boolean = False
Public Property Extourner As Boolean? = False
Public Property DateCreation As DateTime = Now
Public Property UserId As String
Public Overridable Property User As ApplicationUser
Public Overridable Property Client As Client
Public Overridable Property Collecteur As Collecteur
Public Overridable Property Traitement As Traitement
Public Overridable Property JournalCaisse As JournalCaisse
Public Property LibelleOperation As String
Public Overridable Property CompteurImpression As ICollection(Of CompteurImpression) = New HashSet(Of CompteurImpression)
'Public Property CoordoneeGeographiqueId As Long?
'Public Overridable Property CoordoneeGeographique As CoordonneeGeographique
End Class
|
Public class Cpu
Public Property Opcode as Byte
Public Property Id as String
Public Property State as CpuState
End Class |
Imports System.Net
Imports System.Net.Sockets
Imports System.Net.NetworkInformation
Imports System.Text
Imports System.ComponentModel
''' <summary>
''' The BarcodeReceiver receives barcodes from the scanner app
''' and raises an event when a barcode has been received.
''' </summary>
''' <remarks></remarks>
Public Class BarcodeReceiver
Private sck As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
Private bInputBuffer(1023) As Byte
Private epRemote As New IPEndPoint(IPAddress.Any, 0)
Private WithEvents bw As New BackgroundWorker
''' <summary>
''' This event is raised when a barcode has been received from the scanner app.
''' </summary>
''' <param name="Barcode"></param>
''' <remarks></remarks>
Public Event BarcodeReceived(Barcode As String)
''' <summary>
''' Binds an UDP socket to a free port, and starts the barcode receiver.
''' Use GetLocalPort() to get the local port of the UDP socket.
''' </summary>
''' <returns>True on success and false on failure.</returns>
''' <remarks></remarks>
Public Function Start() As Boolean
Try
' Bind the socket to a free udp port
sck.Bind(New IPEndPoint(IPAddress.Any, 0))
' Start receiving barcodes with a background worker
bw.RunWorkerAsync()
Catch ex As Exception
Return False
End Try
Return True
End Function
''' <summary>
''' Gets the local port of the UDP socket.
''' </summary>
''' <returns>An UDP port number as an Integer.</returns>
''' <remarks></remarks>
Public Function GetLocalPort() As Integer
Return CType(sck.LocalEndPoint, IPEndPoint).Port
End Function
''' <summary>
''' This method receives barcodes asynchronous.
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub bw_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bw.DoWork
Dim bBytesReceived As Integer = sck.ReceiveFrom(bInputBuffer, 0, bInputBuffer.Length, SocketFlags.None, epRemote)
Dim sReceivedString As String = Encoding.UTF8.GetString(bInputBuffer, 0, bBytesReceived)
If sReceivedString.StartsWith("WiFi Barcode Scanner Barcode") Then
Dim Parts() As String = sReceivedString.Split("|")
If Parts IsNot Nothing AndAlso Parts.Length >= 2 Then
e.Result = Parts
End If
End If
End Sub
''' <summary>
''' When a barcode has been received, this event is called.
''' This event is called on the main thread, so raising our own events here make them thread safe.
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub bw_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bw.RunWorkerCompleted
Dim Parts() As String = e.Result
'We are back on the main thread, so it is safe to fire the BarcodeReceived event here
RaiseEvent BarcodeReceived(Parts(1))
'Keep receiving those barcodes baby!
bw.RunWorkerAsync()
End Sub
End Class
|
Imports System.ComponentModel.DataAnnotations
Imports System.ComponentModel.DataAnnotations.Schema
<Table("Categorias")>
Public Class Categoria
Property CategoriaId As Int32
<Required>
Property CategoriaNombre As String
<Required>
Property EstaActiva As Boolean
'Navigation Property
Overridable Property Preguntas As ICollection(Of Pregunta)
End Class
|
Public Class Credit
'Parties privés
Private taux As Double = 0
Private dure As Double = 0
Private capitale As Double = 0
'------------------------
Private mensualite As Double = 0
Sub New()
End Sub
Sub New(ByVal monTaux As Double, ByVal maDure As Double, ByVal monCapitale As Double)
taux = monTaux
dure = maDure
capitale = monCapitale
End Sub
'Constructeur
Public Sub New(ByVal t As Double, ByVal d As Integer, ByVal c As Integer)
taux = t
dure = d
capitale = c
End Sub
'Méthode
Public ReadOnly Property mensualites() As Double
Get
' Math.Pow = puissance (^)
'Dim calcul As Double = capitale * ((taux / 100) / (1 - (Math.Pow(1 + taux, -dure))))
Dim calcul As Double = (capitale * (taux / 100)) / (1 - (Math.Pow(1 + (taux / 100), -dure)))
Return CType(calcul, Double)
End Get
End Property
Sub setEnregistreCredit(ByVal monCapitale As Double, ByVal monTaux As Double, ByVal maDuree As Double)
capitale = monCapitale
taux = monTaux
capitale = monCapitale
'mensualite = maMensualite
End Sub
Function getMonCapitale() As Double
Return (capitale)
End Function
Function getMonTaux() As Double
Return (taux)
End Function
Function getMaDuree() As Double
Return (dure)
End Function
End Class
|
Imports cv = OpenCvSharp
Imports System.Runtime.InteropServices
Module Salience_Exports
<DllImport(("CPP_Classes.dll"), CallingConvention:=CallingConvention.Cdecl)>
Public Function Salience_Open() As IntPtr
End Function
<DllImport(("CPP_Classes.dll"), CallingConvention:=CallingConvention.Cdecl)>
Public Function Salience_Run(classPtr As IntPtr, numScales As Int32, grayInput As IntPtr, rows As Int32, cols As Int32) As IntPtr
End Function
<DllImport(("CPP_Classes.dll"), CallingConvention:=CallingConvention.Cdecl)>
Public Sub Salience_Close(classPtr As IntPtr)
End Sub
End Module
Public Class Salience_Basics_CPP : Implements IDisposable
Dim sliders As OptionsSliders
Dim grayData() As Byte
Dim rows As Int32, cols As Int32, numScales As Int32
Dim salience As IntPtr
Public Sub New(ocvb As AlgorithmData)
sliders = New OptionsSliders
sliders.setupTrackBar1(ocvb, "Salience numScales", 1, 6, 1)
If ocvb.parms.ShowOptions Then sliders.Show()
ReDim grayData(ocvb.color.Total - 1)
rows = ocvb.color.Rows
cols = ocvb.color.Cols
salience = Salience_Open()
ocvb.desc = "Show results of Salience algorithm when using C++"
End Sub
Public Sub Run(ocvb As AlgorithmData)
Dim grayInput = ocvb.color.CvtColor(cv.ColorConversionCodes.BGR2GRAY)
Dim cols = ocvb.color.Width
Dim rows = ocvb.color.Height
Dim roi As New cv.Rect(0, 0, cols, rows)
If ocvb.drawRect.Width > 0 Then
cols = ocvb.drawRect.Width
rows = ocvb.drawRect.Height
roi = ocvb.drawRect
ocvb.color.CopyTo(ocvb.result1)
End If
Dim grayHandle = GCHandle.Alloc(grayData, GCHandleType.Pinned)
Dim gray As New cv.Mat(rows, cols, cv.MatType.CV_8U, grayData)
grayHandle.Free()
grayInput(roi).CopyTo(gray)
Dim imagePtr = Salience_Run(salience, sliders.TrackBar1.Value, gray.Data, roi.Height, roi.Width)
Dim dstData(roi.Width * roi.Height - 1) As Byte
Dim dst As New cv.Mat(rows, cols, cv.MatType.CV_8U, dstData)
Marshal.Copy(imagePtr, dstData, 0, roi.Height * roi.Width)
ocvb.color.CopyTo(ocvb.result1)
ocvb.result1(roi) = dst.CvtColor(cv.ColorConversionCodes.GRAY2BGR)
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Salience_Close(salience)
sliders.Dispose()
End Sub
End Class
Public Class Salience_Basics_MT : Implements IDisposable
Dim sliders As OptionsSliders
Dim grayData() As Byte
Public Sub New(ocvb As AlgorithmData)
sliders = New OptionsSliders
sliders.setupTrackBar1(ocvb, "Salience numScales", 1, 6, 1)
sliders.setupTrackBar2(ocvb, "Salience Number of Threads", 1, 100, 36)
If ocvb.parms.ShowOptions Then sliders.Show()
ReDim grayData(ocvb.color.Total - 1)
ocvb.desc = "Show results of multi-threaded Salience algorithm when using C++. NOTE: salience is relative."
End Sub
Public Sub Run(ocvb As AlgorithmData)
Dim numScales = sliders.TrackBar1.Value
Dim threads = sliders.TrackBar2.Value
Dim h = CInt(ocvb.color.Height / threads)
Dim grayHandle = GCHandle.Alloc(grayData, GCHandleType.Pinned)
Dim gray As New cv.Mat(ocvb.color.Rows, ocvb.color.Cols, cv.MatType.CV_8U, grayData)
Parallel.For(0, threads - 1,
Sub(i)
Dim roi = New cv.Rect(0, i * h, ocvb.color.Width, Math.Min(h, ocvb.color.Height - i * h))
If roi.Height <= 0 Then Exit Sub
Dim grayInput = ocvb.color(roi).CvtColor(cv.ColorConversionCodes.BGR2GRAY)
grayInput.CopyTo(gray(roi))
Dim salience = Salience_Open()
Dim imagePtr = Salience_Run(salience, numScales, gray(roi).Data, roi.Height, roi.Width)
Dim dstData(roi.Width * roi.Height - 1) As Byte
Dim dst As New cv.Mat(roi.Height, roi.Width, cv.MatType.CV_8U, dstData)
Marshal.Copy(imagePtr, dstData, 0, roi.Height * roi.Width)
ocvb.result1(roi) = dst.CvtColor(cv.ColorConversionCodes.GRAY2BGR)
Salience_Close(salience)
End Sub)
grayHandle.Free()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
sliders.Dispose()
End Sub
End Class
|
Option Explicit On
Imports System.Text
Imports System.Xml
Imports System.Net
Imports System.IO
Imports System.Security.Cryptography.HMACSHA256
Public Class cBufferAmazonCSV
Private Const PROGRAM_NAME As String = "Amazon"
Private Const COLUMN_CNT As Integer = 43
Private CHARSET As System.Text.Encoding = System.Text.Encoding.GetEncoding("utf-8")
Private accessKeyId As String
Private marketplaceId As String
Private signature As String
Private sellerId As String
Private secretKey As String
Private CSVsavePath As String
Private pSignature As String
Private oConn As OleDb.OleDbConnection
Private oCommand As OleDb.OleDbCommand
Private oDataReader As OleDb.OleDbDataReader
Private oTran As System.Data.OleDb.OleDbTransaction
Private oChannelCode As Integer
Public Sub New( _
ByRef iConn As OleDb.OleDbConnection, _
ByRef iCommand As OleDb.OleDbCommand, _
ByRef iDataReader As OleDb.OleDbDataReader, _
ByVal accessKeyId As String, _
ByVal marketplaceId As String, _
ByVal signature As String, _
ByVal sellerId As String, _
ByVal secretKey As String, _
ByVal CSVsavePath As String, _
ByVal iChannelCode As Integer, _
ByVal iTran As System.Data.OleDb.OleDbTransaction _
)
Me.accessKeyId = accessKeyId
Me.marketplaceId = marketplaceId
Me.signature = signature
Me.sellerId = sellerId
Me.secretKey = secretKey
Me.CSVsavePath = CSVsavePath
oConn = iConn
oCommand = iCommand
oDataReader = iDataReader
oChannelCode = iChannelCode
End Sub
Public Function DownLoad() As Long
Dim amazonReportId() As String
ReDim amazonReportId(0)
If ReportIdDownLoad(amazonReportId) Then
OrderDownLoad(amazonReportId)
End If
End Function
Public Function ReportIdDownLoad(ByRef amazonReportId() As String) As Long
Dim rtnStatus As Integer = 0
Dim l As New cLog(Application.StartupPath & "\Net\Log", PROGRAM_NAME)
Dim msg As String = ""
'Dim postListOrder As String
Dim i As Integer = 0
Dim j As Integer = 0
Dim k As Integer = 0
Dim m As Integer = 0
Dim n As Integer = 0
Dim o As Integer = 0
Dim p As Integer = 0
Dim q As Integer = 0
Dim r As Integer = 0
Dim recordOrderCnt As Integer = 0
Dim recordItemCnt As Integer = 0
Dim xmlStream As String
Dim csvListOrder As StreamWriter
Dim xmlDoc As XmlDocument
Dim xmlListElement As XmlElement
'Dim xListDoc As Object
'Dim httpObj As Object
Try
' Logファイルオープン
l.open()
ReportIdDownLoad = 0
'****************************************
' 受注データのレポートIDを取得
'****************************************
'' --------------------------------------------------------
'msg = "Amazon apiリクエストの生成(受注一覧)" : l.write(msg)
'' --------------------------------------------------------
'postListOrder = getAmazonReportList()
'' --------------------------------------------------------
'msg = "Amazon apiリクエストを送信(受注一覧)" : l.write(msg)
'' --------------------------------------------------------
'httpObj = CreateObject("Microsoft.XMLHTTP")
'httpObj.Open("POST", postListOrder, False)
'httpObj.send("")
'xListDoc = httpObj.ResponseXML
' --------------------------------------------------------
msg = "取得したXMLをCSVファイルに設定(受注一覧)" : l.write(msg)
' --------------------------------------------------------
' Stream取得
xmlStream = getAmazonReportList()
xmlDoc = New XmlDocument
xmlDoc.LoadXml(xmlStream)
xmlListElement = xmlDoc.DocumentElement
' 要素数を取得
recordOrderCnt = xmlListElement.FirstChild.ChildNodes.Count
If recordOrderCnt > 0 Then
' 取得Reportの件数分のレコード出力
For i = 2 To recordOrderCnt - 1
ReDim Preserve amazonReportId(i - 2)
'2016.05.31 K.Oikawa s
'ReportIdの取得処理が間違っていたためにエラーが発生していた
'amazonReportId(i - 2) = xmlListElement.FirstChild.ChildNodes(i).ChildNodes(0).InnerText
For j = 0 To xmlListElement.FirstChild.ChildNodes(i).ChildNodes.Count - 1
If xmlListElement.FirstChild.ChildNodes(i).ChildNodes(j).Name = "ReportId" Then
amazonReportId(i - 2) = xmlListElement.FirstChild.ChildNodes(i).ChildNodes(j).InnerText
End If
Next j
'2016.05.31 K.Oikawa e
Next i
End If
ReportIdDownLoad = recordOrderCnt - 2
Catch ex As Exception
l.write(msg)
l.write(ex)
'l.write("以下パスにXMLファイルを出力:" & vbCrLf & xmlDoc.InnerXml)
rtnStatus = -1
Finally
xmlDoc = Nothing
csvListOrder = Nothing
l.close()
l = Nothing
End Try
End Function
Public Function OrderDownLoad(ByVal amazonReportId() As String) As Long
Dim rtnStatus As Integer = 0
Dim l As New cLog(Application.StartupPath & "\Net\Log", PROGRAM_NAME)
Dim msg As String = ""
Dim i As Integer = 0
Dim j As Integer = 0
Dim k As Integer = 0
Dim csvListItem As StreamWriter
Dim xItemDoc As String
Dim csvData() As String
Dim csvDataTemp() As String
Dim csvDataPre() As String
Dim csvStr As String
'Dim ProductStr() As String
'Dim str As String
Dim pDownLoadColumn() As cStructureLib.sDownloadColumn
Dim pDownLoadColumnDBIO As New cMstDownloadColumnDBIO(oConn, oCommand, oDataReader)
'Dim pDownLoadCount As Integer
'Dim skuNo As Integer
'Dim ProductNameNo As Integer
'Dim quantityNo As Integer
'Dim ShippingPriceNo As Integer
'Dim itemPriceNo As Integer
'Dim ItemPromotionIdNo As Integer
'Dim ItemPromotionPriceNo As Integer
'Dim ShipPromotionIdNo As Integer
'Dim ShipPromotionPriceNo As Integer
'Dim PurchaseDateNo As Integer
Dim OrderCode As New Hashtable
Dim RecordNo As Integer
'Dim PromotionType As Integer
Dim pItemPromotion As New Hashtable
Dim pShipPromotion As New Hashtable
'Dim HeaderSize As Integer
Dim LastFlg As Boolean
Try
' Logファイルオープン
l.open()
'**********************************
' 受注データCSVの生成
'**********************************
csvListItem = New StreamWriter(CSVsavePath & "\Amazon_Order.csv", False, System.Text.Encoding.GetEncoding("shift_jis"))
ReDim csvData(0)
ReDim csvDataTemp(0)
ReDim csvDataPre(0)
csvStr = ""
LastFlg = False
' --------------------------------------------------------
msg = "Amazon apiリクエストの生成(受注明細)" : l.write(msg)
' --------------------------------------------------------
'ReDim pDownLoadColumn(0)
'pDownLoadCount = pDownLoadColumnDBIO.getDownloadColumn(pDownLoadColumn, oChannelCode, 2, "sku", oTran)
'skuNo = pDownLoadColumn(0).sDLColumnNo - 1
'pDownLoadCount = pDownLoadColumnDBIO.getDownloadColumn(pDownLoadColumn, oChannelCode, 2, "product-name", oTran)
'ProductNameNo = pDownLoadColumn(0).sDLColumnNo - 1
'pDownLoadCount = pDownLoadColumnDBIO.getDownloadColumn(pDownLoadColumn, oChannelCode, 2, "quantity-purchased", oTran)
'quantityNo = pDownLoadColumn(0).sDLColumnNo - 1
'pDownLoadCount = pDownLoadColumnDBIO.getDownloadColumn(pDownLoadColumn, oChannelCode, 2, "shipping-price", oTran)
'ShippingPriceNo = pDownLoadColumn(0).sDLColumnNo - 1
'pDownLoadCount = pDownLoadColumnDBIO.getDownloadColumn(pDownLoadColumn, oChannelCode, 2, "item-price", oTran)
'itemPriceNo = pDownLoadColumn(0).sDLColumnNo - 1
'pDownLoadCount = pDownLoadColumnDBIO.getDownloadColumn(pDownLoadColumn, oChannelCode, 2, "item-promotion-id", oTran)
'ItemPromotionIdNo = pDownLoadColumn(0).sDLColumnNo - 1
'pDownLoadCount = pDownLoadColumnDBIO.getDownloadColumn(pDownLoadColumn, oChannelCode, 2, "item-promotion-discount", oTran)
'ItemPromotionPriceNo = pDownLoadColumn(0).sDLColumnNo - 1
'pDownLoadCount = pDownLoadColumnDBIO.getDownloadColumn(pDownLoadColumn, oChannelCode, 2, "ship-promotion-id", oTran)
'ShipPromotionIdNo = pDownLoadColumn(0).sDLColumnNo - 1
'pDownLoadCount = pDownLoadColumnDBIO.getDownloadColumn(pDownLoadColumn, oChannelCode, 2, "ship-promotion-discount", oTran)
'ShipPromotionPriceNo = pDownLoadColumn(0).sDLColumnNo - 1
'pDownLoadCount = pDownLoadColumnDBIO.getDownloadColumn(pDownLoadColumn, oChannelCode, 1, "purchase-date", oTran)
'PurchaseDateNo = pDownLoadColumn(0).sDLColumnNo - 1
RecordNo = 0
'----------------------------
' i = レポート数分ループ
'----------------------------
For i = 0 To amazonReportId.Length - 1
If amazonReportId(i) <> "0" Then
ReDim pDownLoadColumn(0)
'Amazon受注レポートの受信
xItemDoc = getAmazonReport(amazonReportId(i))
' ------------------------------------------------------------------------------------
msg = "取得したフラット(TAB区切り)をCSVファイルに設定(受注情報)" : l.write(msg)
' ------------------------------------------------------------------------------------
' レコード分割
csvData = xItemDoc.Replace(vbLf, "").Split(vbCr)
ReDim csvDataPre(0)
'----------------------------
' j = レコード数分ループ
'----------------------------
For j = 0 To (csvData.Length - 1)
''プロモーションタイプの初期化
'PromotionType = 0
If csvData(j) <> "" Then '空レコードでなければ・・・
If i = 0 Or j > 0 Then
'項目毎に分割
csvDataTemp = csvData(j).Split(vbTab)
csvStr = """" & String.Join(""",""", csvDataTemp) & """"
csvListItem.Write(csvStr & vbCr + vbLf)
' 'レポート内の重複OrderNoの読み飛ばし
' If (OrderCode.ContainsKey(csvDataTemp(0)) = False) Or (csvDataPre(0) = csvDataTemp(0)) Then
' 'オーダーコードテーブルの作成
' If OrderCode.ContainsKey(csvDataTemp(0)) = False Then
' OrderCode.Add(csvDataTemp(0), csvDataTemp(0))
' End If
' Select Case RecordNo
' Case 0 '今回ダウンロードデータの先頭行(先頭レポートの先頭行の場合
' csvStr = """" & String.Join(""",""", csvDataTemp) & """"
' csvListItem.Write(csvStr & vbCr + vbLf)
' 'ヘッダー項目数の取得
' HeaderSize = csvDataTemp.Length
' ReDim Preserve csvDataPre(HeaderSize)
' Case Else
' Select Case j
' Case 0 '2レポート目移行のヘッダーレコードの場合 → 読み飛ばし
' Case Else
' If csvDataTemp(PurchaseDateNo) <> "" Then
' '当該レコードの確定
' csvStr = """" & String.Join(""",""", csvDataTemp) & """"
' csvListItem.Write(csvStr & vbCr + vbLf)
' Else
' If csvDataPre(0) = csvDataTemp(0) Then 'OrderIDが同一の場合
' If csvDataPre(1) = csvDataTemp(1) Then 'ItemIDが同一の場合
' '-------------------------------------------------------------
' ' 同一オーダー内の同一商品のプロモーションレコードの場合
' '-------------------------------------------------------------
' 'プロモーションタイプの判定
' '購入割引プロモーションの場合
' If csvDataTemp(ItemPromotionPriceNo) <> "0" Then
' PromotionType = 1
' End If
' '配送無料プロモーションの場合
' If csvDataTemp(ShipPromotionPriceNo) <> "0" Then
' PromotionType = 2
' End If
' '告知のみのプロモーションの場合
' If csvDataTemp(ItemPromotionPriceNo) = "0" And csvDataTemp(ShipPromotionPriceNo) = "0" Then
' PromotionType = 3
' End If
' Select Case PromotionType
' Case 1 '購入割引プロモーションの場合
' 'プロモーション名を商品名称に設定
' If csvDataTemp(ItemPromotionIdNo) <> "" Then
' ProductStr = csvDataTemp(ItemPromotionIdNo).Split(" ")
' str = ""
' For k = 0 To ProductStr.Length - 3
' If k > 0 Then
' str = str & " "
' End If
' str = str & ProductStr(k)
' Next
' csvDataTemp(ProductNameNo) = str
' End If
' csvDataTemp(itemPriceNo) = CLng(csvDataPre(ItemPromotionPriceNo)) + CLng(csvDataTemp(ItemPromotionPriceNo))
' csvDataTemp(quantityNo) = "1"
' 'If pItemPromotion.ContainsKey(csvDataTemp(ProductNameNo)) Then
' ' pItemPromotion(csvDataTemp(ProductNameNo)) = CType(csvDataTemp(ProductNameNo), Long) + CLng(csvDataTemp(ItemPromotionPriceNo))
' 'Else
' ' pItemPromotion.Add(csvDataTemp(ProductNameNo), CLng(csvDataTemp(ItemPromotionPriceNo)))
' 'End If
' Case 2 '配送無料プロモーションの場合
' 'shipプロモーション適用されている場合
' If csvDataTemp(ShipPromotionPriceNo) <> "0" And csvDataTemp(ShipPromotionPriceNo) <> "" Then
' 'プロモーション名を商品名称に設定
' If csvDataTemp(ShipPromotionIdNo) <> "" Then
' ProductStr = csvDataTemp(ShipPromotionIdNo).Split(" ")
' str = ""
' For k = 0 To ProductStr.Length - 3
' If k > 0 Then
' str = str & " "
' End If
' str = str & ProductStr(k)
' Next
' csvDataTemp(ProductNameNo) = str
' End If
' csvDataTemp(itemPriceNo) = CLng(csvDataPre(ShipPromotionPriceNo)) + CLng(csvDataTemp(ShipPromotionPriceNo))
' csvDataTemp(quantityNo) = "1"
' End If
' 'If pShipPromotion.ContainsKey(csvDataTemp(ProductNameNo)) Then
' ' pShipPromotion(csvDataTemp(ProductNameNo)) = CType(csvDataTemp(ProductNameNo), Long) + CLng(csvDataTemp(ShipPromotionPriceNo))
' 'Else
' ' pShipPromotion.Add(csvDataTemp(ProductNameNo), CLng(csvDataTemp(ShipPromotionPriceNo)))
' 'End If
' Case 3 '告知のみのプロモーションの場合
' End Select
' Else
' pItemPromotion.Clear()
' End If
' Else
' '--------------------------------------------
' ' オーダーが切替った場合
' '--------------------------------------------
' 'Preレコードの書出し
' csvStr = """" & String.Join(""",""", csvDataPre) & """"
' csvListItem.Write(csvStr & vbCr + vbLf)
' 'プロモーションレコードの生成
' For Each key As String In pShipPromotion.Keys
' csvDataPre(ProductNameNo) = key
' csvDataPre(itemPriceNo) = pShipPromotion(key)
' 'プロモーションレコードの書出し
' csvStr = """" & String.Join(""",""", csvDataPre) & """"
' csvListItem.Write(csvStr & vbCr + vbLf)
' Next
' 'プロモーションテーブルの初期化
' pShipPromotion.Clear()
' End If
' End If
' End Select
' End Select
' End If
' End If
' csvDataPre = csvDataTemp
' '複数レポートにおける連番の処理レコード番号をインクリメント
' RecordNo = RecordNo + 1
'Next j
''iTemプロモーションレコードの生成
'For Each key As String In pItemPromotion.Keys
' csvDataPre(ProductNameNo) = key
' csvDataPre(itemPriceNo) = pItemPromotion(key)
' 'プロモーションレコードの書出し
' csvStr = """" & String.Join(""",""", csvDataPre) & """"
' csvListItem.Write(csvStr & vbCr + vbLf)
'Next
''Shipプロモーションレコードの生成
'For Each key As String In pShipPromotion.Keys
' csvDataPre(ProductNameNo) = key
' csvDataPre(ShippingPriceNo) = pShipPromotion(key)
' 'プロモーションレコードの書出し
' csvStr = """" & String.Join(""",""", csvDataPre) & """"
' csvListItem.Write(csvStr & vbCr + vbLf)
'Next
End If
End If
Next j
'Amazonレポート受信済みの署名
xItemDoc = setAcknowledgements(amazonReportId(i))
End If
Next i
csvListItem.Close()
Catch ex As Exception
l.write(msg)
l.write(ex)
'l.write("以下パスにXMLファイルを出力:" & vbCrLf & xmlDoc.InnerXml)
rtnStatus = -1
Finally
csvListItem = Nothing
OrderCode = Nothing
l.close()
l = Nothing
End Try
End Function
'-------------------------------------------------------------------
' アマゾンへの受注一覧のリクエストパラメータ、署名を作成
'-------------------------------------------------------------------
Private Function getAmazonReportList() As String
'Dim dictRequest As New Dictionary(Of String, String)
'Dim lastDate As String
'Dim strNow As String
'Dim FromTime As String
'Dim pastTime As String
'Dim sortString As String
'Dim builder As New System.Text.StringBuilder()
'Dim qsBuilder As New System.Text.StringBuilder()
'Dim hashSignature As String
'Dim utcNowTime As Date
'' システム日時を標準時間で取得(システム日時だとAmazonからエラーが返されるため、ここで取得・変換する)
'utcNowTime = Now.ToUniversalTime
'' 当日日付を取得(ISO8601形式)
'strNow = Left(utcNowTime.ToString("o"), 23) & "Z"
'' 7日前日付を取得(ISO8601形式)
'FromTime = Left(utcNowTime.AddDays(-30).ToString("o"), 23) & "Z"
'Dim dt As New DateTime(2012, 5, 1, 0, 0, 0)
'''UTCに変換する
''Dim utcTime As DateTime = System.TimeZoneInfo.ConvertTimeToUtc(dt)
''FromTime = Left(utcTime.ToString("o"), 23) & "Z"
'' 2分前の時間を取得
'pastTime = Left(utcNowTime.AddDays(-2).ToString("o"), 23) & "Z"
'' 1週間前の日付を取得
'lastDate = Left(DateAdd("ww", -1, utcNowTime).ToString("s"), 23) & "Z"
''リクエストパラメータをハッシュテーブルに保存
'dictRequest("AWSAccessKeyId") = accessKeyId
'dictRequest("Version") = "2009-01-01"
'dictRequest("Merchant") = sellerId
'dictRequest("SignatureVersion") = "2"
'dictRequest("SignatureMethod") = "HmacSHA256"
'Dim dteNow As DateTime = DateTime.UtcNow
'Dim sTimeStamp As String = dteNow.ToString("yyyy-MM-ddTHH:mm:ssZ")
''タイムスタンプはGMT
'dictRequest("Timestamp") = sTimeStamp
''dictRequest("Timestamp") = "2014-08-25T06:37:10Z"
'dictRequest("Action") = "GetReportList"
'dictRequest("ReportTypeList.Type.1") = "_GET_FLAT_FILE_ORDERS_DATA_"
'Dim pc As New ParamComparer()
'Dim sortedHash As New SortedDictionary(Of String, String)(dictRequest, pc)
'Dim canonicalQS As String = ConstructCanonicalQueryString(sortedHash)
'builder.Append("POST").Append(vbLf). _
' Append(CStr("mws.amazonservices.jp").ToLower()).Append(vbLf). _
' Append("/").Append(vbLf). _
' Append(canonicalQS)
'Dim stringToSign As String = builder.ToString()
'Dim toSign As Byte() = System.Text.Encoding.UTF8.GetBytes(stringToSign)
'Dim secret As Byte()
'secret = System.Text.Encoding.UTF8.GetBytes(secretKey)
'Dim signer As System.Security.Cryptography.HMACSHA256
'signer = New System.Security.Cryptography.HMACSHA256(secret)
'Dim sigBytes As Byte() = signer.ComputeHash(toSign)
'Dim signature As String = PercentEncodeRfc3986(Convert.ToBase64String(sigBytes))
'' URLを生成
'qsBuilder.Append("https://"). _
' Append("mws.amazonservices.jp"). _
' Append("/?"). _
' Append(canonicalQS). _
' Append("&Signature=" & signature)
'makeAmazonReportList = qsBuilder.ToString()
Dim dictRequest As New Dictionary(Of String, String)
Dim wc As New System.Net.WebClient()
Dim strNow As String
Dim sortString As String
Dim stringToSign As String
Dim toSign As Byte()
Dim secret As Byte()
Dim sigBytes As Byte()
Dim pc As New ParamComparer()
Dim builder As New System.Text.StringBuilder()
Dim qsBuilder As New System.Text.StringBuilder()
Dim signer As System.Security.Cryptography.HMAC
Dim hashSignature As String
Dim utcNowTime As Date
' システム日時を標準時間で取得(システム日時だとAmazonからエラーが返されるため、ここで取得・変換する)
utcNowTime = Now.ToUniversalTime
' 当日日付を取得(ISO8601形式)
'strNow = Left(Now.ToUniversalTime.ToString("o"), 23) & "Z"
strNow = Left(utcNowTime.ToString("o"), 23) & "Z"
'リクエストパラメータをハッシュテーブルに保存
dictRequest("AWSAccessKeyId") = accessKeyId
dictRequest("Version") = "2009-01-01"
dictRequest("SignatureVersion") = "2"
dictRequest("SignatureMethod") = "HmacSHA256"
dictRequest("Timestamp") = strNow
dictRequest("MarketplaceId.Id") = marketplaceId
dictRequest("Merchant") = sellerId
dictRequest("Action") = "GetReportList"
dictRequest("ReportTypeList.Type.1") = "_GET_FLAT_FILE_ORDERS_DATA_"
Dim sortedHash As New SortedDictionary(Of String, String)(dictRequest, pc)
sortString = ConstructCanonicalQueryString(sortedHash)
' 署名にする文字列を作成
builder.Append("POST").Append(vbLf). _
Append(CStr("mws.amazonservices.jp").ToLower()).Append(vbLf). _
Append("/").Append(vbLf). _
Append(sortString)
stringToSign = builder.ToString()
' 署名対象文字列・秘密キーをバイト文字列に変換
toSign = System.Text.Encoding.UTF8.GetBytes(stringToSign)
secret = System.Text.Encoding.UTF8.GetBytes(signature)
' 署名を作成
signer = New System.Security.Cryptography.HMACSHA256(secret)
sigBytes = signer.ComputeHash(toSign)
hashSignature = Convert.ToBase64String(sigBytes)
' URLを生成
qsBuilder.Append("https://"). _
Append("mws.amazonservices.jp"). _
Append("/?"). _
Append(sortString). _
Append("&Signature=").Append(PercentEncodeRfc3986(hashSignature))
'文字コードを指定する()
wc.Encoding = System.Text.Encoding.GetEncoding("shift_jis")
'データを送信し、また受信する
getAmazonReportList = wc.UploadString(qsBuilder.ToString(), "")
wc.Dispose()
wc = Nothing
End Function
'-------------------------------------------------------------------
' アマゾンへの受注明細のリクエストパラメータ、署名を作成
'-------------------------------------------------------------------
Private Function getAmazonReport(ByVal pReportId As String) As String
Dim dictRequest As New Dictionary(Of String, String)
Dim wc As New System.Net.WebClient()
Dim strNow As String
Dim sortString As String
Dim stringToSign As String
Dim toSign As Byte()
Dim secret As Byte()
Dim sigBytes As Byte()
Dim pc As New ParamComparer()
Dim builder As New System.Text.StringBuilder()
Dim qsBuilder As New System.Text.StringBuilder()
Dim signer As System.Security.Cryptography.HMAC
Dim hashSignature As String
Dim utcNowTime As Date
' システム日時を標準時間で取得(システム日時だとAmazonからエラーが返されるため、ここで取得・変換する)
utcNowTime = Now.ToUniversalTime
' 当日日付を取得(ISO8601形式)
'strNow = Left(Now.ToUniversalTime.ToString("o"), 23) & "Z"
strNow = Left(utcNowTime.ToString("o"), 23) & "Z"
'リクエストパラメータをハッシュテーブルに保存
dictRequest("AWSAccessKeyId") = accessKeyId
dictRequest("Version") = "2009-01-01"
dictRequest("SignatureVersion") = "2"
dictRequest("SignatureMethod") = "HmacSHA256"
dictRequest("Timestamp") = strNow
dictRequest("Action") = "GetReport"
dictRequest("MarketplaceId.Id") = marketplaceId
dictRequest("Merchant") = sellerId
dictRequest("ReportId") = pReportId
Dim sortedHash As New SortedDictionary(Of String, String)(dictRequest, pc)
sortString = ConstructCanonicalQueryString(sortedHash)
' 署名にする文字列を作成
builder.Append("POST").Append(vbLf). _
Append(CStr("mws.amazonservices.jp").ToLower()).Append(vbLf). _
Append("/").Append(vbLf). _
Append(sortString)
stringToSign = builder.ToString()
' 署名対象文字列・秘密キーをバイト文字列に変換
toSign = System.Text.Encoding.UTF8.GetBytes(stringToSign)
secret = System.Text.Encoding.UTF8.GetBytes(signature)
' 署名を作成
signer = New System.Security.Cryptography.HMACSHA256(secret)
sigBytes = signer.ComputeHash(toSign)
hashSignature = Convert.ToBase64String(sigBytes)
' URLを生成
qsBuilder.Append("https://"). _
Append("mws.amazonservices.jp"). _
Append("/?"). _
Append(sortString). _
Append("&Signature=").Append(PercentEncodeRfc3986(hashSignature))
'文字コードを指定する()
wc.Encoding = System.Text.Encoding.GetEncoding("shift_jis")
'データを送信し、また受信する
getAmazonReport = wc.UploadString(qsBuilder.ToString(), "")
wc.Dispose()
wc = Nothing
End Function
'-------------------------------------------------------------------
' アマゾンへの受信済みレポートへの署名
'-------------------------------------------------------------------
Private Function setAcknowledgements(ByVal pReportId As String) As String
Dim dictRequest As New Dictionary(Of String, String)
Dim wc As New System.Net.WebClient()
Dim strNow As String
Dim sortString As String
Dim stringToSign As String
Dim toSign As Byte()
Dim secret As Byte()
Dim sigBytes As Byte()
Dim pc As New ParamComparer()
Dim builder As New System.Text.StringBuilder()
Dim qsBuilder As New System.Text.StringBuilder()
Dim signer As System.Security.Cryptography.HMAC
Dim hashSignature As String
Dim utcNowTime As Date
' システム日時を標準時間で取得(システム日時だとAmazonからエラーが返されるため、ここで取得・変換する)
utcNowTime = Now.ToUniversalTime
' 当日日付を取得(ISO8601形式)
'strNow = Left(Now.ToUniversalTime.ToString("o"), 23) & "Z"
strNow = Left(utcNowTime.ToString("o"), 23) & "Z"
'リクエストパラメータをハッシュテーブルに保存
dictRequest("AWSAccessKeyId") = accessKeyId
dictRequest("Version") = "2009-01-01"
dictRequest("SignatureVersion") = "2"
dictRequest("SignatureMethod") = "HmacSHA256"
dictRequest("Timestamp") = strNow
dictRequest("Action") = "UpdateReportAcknowledgements"
dictRequest("MarketplaceId.Id") = marketplaceId
dictRequest("Merchant") = sellerId
dictRequest("ReportIdList.Id.1") = pReportId
Dim sortedHash As New SortedDictionary(Of String, String)(dictRequest, pc)
sortString = ConstructCanonicalQueryString(sortedHash)
' 署名にする文字列を作成
builder.Append("POST").Append(vbLf). _
Append(CStr("mws.amazonservices.jp").ToLower()).Append(vbLf). _
Append("/").Append(vbLf). _
Append(sortString)
stringToSign = builder.ToString()
' 署名対象文字列・秘密キーをバイト文字列に変換
toSign = System.Text.Encoding.UTF8.GetBytes(stringToSign)
secret = System.Text.Encoding.UTF8.GetBytes(signature)
' 署名を作成
signer = New System.Security.Cryptography.HMACSHA256(secret)
sigBytes = signer.ComputeHash(toSign)
hashSignature = Convert.ToBase64String(sigBytes)
' URLを生成
qsBuilder.Append("https://"). _
Append("mws.amazonservices.jp"). _
Append("/?"). _
Append(sortString). _
Append("&Signature=").Append(PercentEncodeRfc3986(hashSignature))
'文字コードを指定する()
wc.Encoding = System.Text.Encoding.GetEncoding("shift_jis")
'データを送信し、また受信する
setAcknowledgements = wc.UploadString(qsBuilder.ToString(), "")
wc.Dispose()
wc = Nothing
End Function
Private Function PercentEncodeRfc3986(ByVal str As String) As String
str = System.Web.HttpUtility.UrlEncode(str, System.Text.Encoding.UTF8)
'str.Replace("'", "%27").Replace("(", "%28").Replace(")", "%29").Replace("*", "%2A").Replace("!", "%21").Replace("%7e", "~")
str = str.Replace("'", "%27"). _
Replace("(", "%28"). _
Replace(")", "%29"). _
Replace("*", "%2A"). _
Replace("!", "%21"). _
Replace("%7e", "~"). _
Replace("=", "%2F"). _
Replace("/", "%3D"). _
Replace("+", "%2B")
Dim sbuilder As New System.Text.StringBuilder(str)
For i As Integer = 0 To sbuilder.Length - 1
If sbuilder(i) = "%"c Then
'コメント化
'If [Char].IsDigit(sbuilder(i + 1)) AndAlso [Char].IsLetter(sbuilder(i + 2)) Then
sbuilder(i + 1) = [Char].ToUpper(sbuilder(i + 1)) '日本語対策で追加
sbuilder(i + 2) = [Char].ToUpper(sbuilder(i + 2))
'End If
End If
Next
Return sbuilder.ToString()
End Function
Private Function ConstructCanonicalQueryString(ByVal sortedParamMap As SortedDictionary(Of String, String)) As String
Dim builder As New System.Text.StringBuilder()
If sortedParamMap.Count = 0 Then
builder.Append("")
Return builder.ToString()
End If
For Each kvp As KeyValuePair(Of String, String) In sortedParamMap
builder.Append(PercentEncodeRfc3986(kvp.Key))
builder.Append("=")
builder.Append(PercentEncodeRfc3986(kvp.Value))
builder.Append("&")
Next
Dim canonicalString As String = builder.ToString()
canonicalString = canonicalString.Substring(0, canonicalString.Length - 1)
Return canonicalString
End Function
Class ParamComparer
Implements IComparer(Of String)
Public Function Compare(ByVal p1 As String, ByVal p2 As String) As Integer Implements IComparer(Of String).Compare
Return String.CompareOrdinal(p1, p2)
End Function
End Class
End Class
|
'Adam Boswell
'RCET 0265
'Asg 3-6
'Shipping Cost Calculator Program
'https://github.com/boswadam/AMB-VS-F19/tree/master/Assignments_3/Asg%203-6/Asg%203-6
Option Explicit On
Option Strict On
Public Class shippingCalc
Dim lbs As Double
Dim oz As Double
Dim shipCost As Double 'Dims all my variables
Const rate = 0.12 'sets the rate as a constant of .12
Dim ID As String
Dim errorMsg As String
Private Sub CalculateButton_Click(sender As Object, e As EventArgs) Handles CalculateButton.Click
errorMsg = "" 'sets error message as blank
Try
lbs = Double.Parse(lbTextBox.Text)
Catch ex As Exception
errorMsg = "Please enter the pounds of your package as a number"
lbTextBox.Select()
lbTextBox.Clear()
End Try
Try
oz = Double.Parse(ozTextBox.Text)
Catch ex As Exception
errorMsg = "Please enter the ounces of your package as a number"
ozTextBox.Select()
ozTextBox.Clear()
End Try
'Two try statements validate the data
If errorMsg <> "" Then
MessageBox.Show(errorMsg, "Invalid Entry") 'If the errorMsg isnt blank a message box will display the error
Else
shipCost = ((lbs * 16) + oz) * rate 'If errorMsg IS blank then math is performed
costTextBox.Text = shipCost.ToString("C") 'Cost is then displayed in dollars
End If
End Sub
Private Sub ClearButton_Click(sender As Object, e As EventArgs) Handles clearButton.Click
costTextBox.Clear()
ozTextBox.Clear()
lbTextBox.Clear() 'clears all data
lbTextBox.Select() 'puts the focus back on lbtextbox
End Sub
Private Sub ExitButton_Click(sender As Object, e As EventArgs) Handles exitButton.Click
Me.Close() 'closes the program when exit is clicked
End Sub
End Class
|
' In App.xaml:
' <Application.Resources>
' <vm:ViewModelLocator xmlns:vm="clr-namespace:WirePicking"
' x:Key="Locator" />
' </Application.Resources>
'
' In the View:
' DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}"
'
' You can also use Blend to do all this with the tool's support.
' See http://www.galasoft.ch/mvvm
Imports CommonServiceLocator
Imports GalaSoft.MvvmLight
Imports GalaSoft.MvvmLight.Ioc
Imports Microsoft.Practices.ServiceLocation
Namespace ViewModel
''' <summary>
''' This class contains static references to all the view models in the
''' application and provides an entry point for the bindings.
''' </summary>
Public Class ViewModelLocator
''' <summary>
''' Initializes a new instance of the ViewModelLocator class.
''' </summary>
Public Sub New()
ServiceLocator.SetLocatorProvider(Function() SimpleIoc.Default)
'if ViewModelBase.IsInDesignModeStatic then
' ' Create design time view services and models
' SimpleIoc.Default.Register(Of IDataService, DesignDataService)();
'else
' ' Create run time view services and models
' SimpleIoc.Default.Register(Of IDataService, DataService)();
'end if
SimpleIoc.Default.Register(Of MainViewModel)()
End Sub
Public ReadOnly Property Main As MainViewModel
Get
Return ServiceLocator.Current.GetInstance(Of MainViewModel)()
End Get
End Property
Public Shared Sub Cleanup()
' TODO: Clear the ViewModels
End Sub
End Class
End Namespace |
'Programmer: Samantha Naini
'Date: 3/15/2012
'Exercise: 4-4-22 pg.152
'Program Purpose: Create a program processing someone's major, year, and languages selected.
Option Strict On
Option Explicit On
Public Class frmQuestionnaire
Private Sub btnRecord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRecord.Click
Dim sentence As String = Nothing
If lstMajors.Text = Nothing Then
MessageBox.Show("No major was selected.", "4-4-22")
End If
If radFreshman.Checked = False And radSophmore.Checked = False And radJunior.Checked = False And radSenior.Checked = False Then
MessageBox.Show("No year was selected.", "4-4-22")
End If
If chkC.Checked Then
sentence = "C"
End If
If chkCobol.Checked Then
sentence &= "Cobol"
End If
If chkCPlus.Checked Then
sentence &= "C++"
End If
If chkCSharp.Checked Then
sentence &= "C#"
End If
If chkJava.Checked Then
sentence &= "Java"
End If
If chkVisBasic.Checked Then
sentence &= "Visual Basic"
End If
If sentence = Nothing Then
MessageBox.Show("No languages studied.", "4-4-22")
Else
MessageBox.Show("The following languages studied: " & sentence & ".", "4-4-22")
End If
End Sub
Private Sub btnEnd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnd.Click
If MsgBox("Do you really want to quit?", MsgBoxStyle.YesNoCancel, "Quit") = MsgBoxResult.Yes Then
MessageBox.Show("Have a nice day!", "Quit")
Me.Close()
End If
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
lstMajors.SelectedItem = Nothing
radFreshman.Checked = False
radSophmore.Checked = False
radJunior.Checked = False
radSenior.Checked = False
chkC.Checked = False
chkCobol.Checked = False
chkCPlus.Checked = False
chkCSharp.Checked = False
chkJava.Checked = False
chkVisBasic.Checked = False
End Sub
End Class
|
Imports System.IO
Imports System.Xml.Serialization
Namespace Settings
Public Class SettingsManager
Private Const _fileName As String = "CogentSettings.xml"
Private _path As String = ""
Public Sub New()
_path = FileIO.SpecialDirectories.AllUsersApplicationData + "\" + _fileName
End Sub
Public Sub Load(ByRef settings As Settings)
Try
If File.Exists(_path) Then
Dim reader As XmlSerializer = New XmlSerializer(GetType(Settings))
Dim file As StreamReader = New StreamReader(_path)
settings = CType(reader.Deserialize(file), Settings)
file.Close()
Else
settings = New Settings
End If
Catch ex As Exception
Logger.Logger.Instance.Log(GetType(SettingsManager).ToString + ".Load(): ", Logger.Logger.eStatus.Exception, ex)
End Try
End Sub
Public Sub Save(ByRef settings As Settings)
Try
Dim writer As XmlSerializer = New XmlSerializer(GetType(Settings))
Dim file As StreamWriter = New StreamWriter(_path)
writer.Serialize(file, settings)
file.Close()
Catch ex As Exception
Logger.Logger.Instance.Log(GetType(SettingsManager).ToString + ".Save(): ", Logger.Logger.eStatus.Exception, ex)
End Try
End Sub
End Class
End Namespace
|
Public Class clsValoresespecificaciones
#Region "Atributos"
Private ParametroID As Integer
Private EspecificacionID As Integer
Private LegislacionID As Integer
Private Nombre As String
Private Obligatoriedad As Boolean
Private Minimo As Double
Private Maximo As Double
Private Periodicidad As Double
Private UnidadMedida As String
Private MetodoAnalisisID As String
Private Desviacion_maximo As Double
Private Desviacion_minimo As Double
#End Region
#Region "Propiedades"
Public Property _ParametroID() As Integer
Get
Return ParametroID
End Get
Set(ByVal value As Integer)
ParametroID = value
End Set
End Property
Public Property _LegislacionID() As Integer
Get
Return LegislacionID
End Get
Set(ByVal value As Integer)
LegislacionID = value
End Set
End Property
Public Property _EspecificacionID() As Integer
Get
Return EspecificacionID
End Get
Set(ByVal value As Integer)
EspecificacionID = value
End Set
End Property
Public Property _DesviacionMaxima() As Double
Get
Return Desviacion_maximo
End Get
Set(ByVal value As Double)
Desviacion_maximo = value
End Set
End Property
Public Property _DesviacionMinima() As Double
Get
Return Desviacion_minimo
End Get
Set(ByVal value As Double)
Desviacion_minimo = value
End Set
End Property
Public Property _Obligatoriedad() As Boolean
Get
Return Obligatoriedad
End Get
Set(ByVal value As Boolean)
Obligatoriedad = value
End Set
End Property
Public Property _Minimo() As Double
Get
Return Minimo
End Get
Set(ByVal value As Double)
Minimo = value
End Set
End Property
Public Property _Maximo() As Double
Get
Return Maximo
End Get
Set(ByVal value As Double)
Maximo = value
End Set
End Property
Public Property _Periodicidad() As Double
Get
Return Periodicidad
End Get
Set(ByVal value As Double)
Periodicidad = value
End Set
End Property
Public Property _UnidadMedida() As String
Get
Return UnidadMedida
End Get
Set(ByVal value As String)
UnidadMedida = value
End Set
End Property
Public Property _MetodoAnalisisID() As Integer
Get
If MetodoAnalisisID = "null" Then
Return 0
Else
Return MetodoAnalisisID
End If
End Get
Set(ByVal value As Integer)
If value = 0 Then
MetodoAnalisisID = "null"
Else
MetodoAnalisisID = value
End If
End Set
End Property
#End Region
#Region "Metodos"
Public Function devolver(ByRef dtb As BasesParaCompatibilidad.DataBase) As DataTable
dtb.PrepararConsulta(" select ListaParametros.ParametroID, " & _
"ListaParametros.Nombre, " & _
"C1.Obligatoriedad, " & _
"isnull(C1.Minimo, legislacionProductos_listaParametros.minimo) as minimo, " & _
"isnull(C1.Maximo, legislacionProductos_listaParametros.maximo) as Maximo, " & _
"C1.Periodicidad, " & _
"UnidadesMedidas.Descripcion, " & _
"MetodosAnalisis.Descripcion AS MetodosAnalisis, " & _
"C1.desviacionMaximo, " & _
"C1.desviacionminimo, " & _
"legislacionProductos_listaParametros.maximo as maximoLegislacion, " & _
"legislacionProductos_listaParametros.minimo as minimoLegislacion " & _
" from MetodosAnalisis RIGHT JOIN (SELECT " & _
"ValoresEspecificaciones.ParametroID AS ParametroIDen, " & _
"ValoresEspecificaciones.Obligatoriedad, " & _
"ValoresEspecificaciones.Minimo, " & _
"ValoresEspecificaciones.Maximo, " & _
"ValoresEspecificaciones.Periodicidad, " & _
"ValoresEspecificaciones.MetodoAnalisisID, " & _
"ValoresEspecificaciones.desviacionMaximo, " & _
"ValoresEspecificaciones.desviacionMinimo " & _
"FROM " & _
"Especificaciones INNER JOIN ValoresEspecificaciones " & _
"ON Especificaciones.EspecificacionID = ValoresEspecificaciones.EspecificacionID " & _
"INNER JOIN ListaParametros AS ListaParametros_1 " & _
"ON ValoresEspecificaciones.ParametroID = ListaParametros_1.ParametroID " & _
"WHERE " & _
"(Especificaciones.EspecificacionID = " & EspecificacionID.ToString & ") " & _
") AS c1 " & _
"ON MetodosAnalisis.MetodoAnalisisID = c1.MetodoAnalisisID " & _
"RIGHT OUTER JOIN ListaParametros INNER JOIN UnidadesMedidas " & _
"ON ListaParametros.UnidadMedidaID = UnidadesMedidas.UnidadMedidaID " & _
"ON c1.ParametroIDen = ListaParametros.ParametroID " & _
"left join legislacionProductos_listaParametros " & _
"on ListaParametros.parametroId = legislacionProductos_listaParametros.Id_parametro " & _
"Where (id_legislacion = " & LegislacionID.ToString & "or id_legislacion is null)")
'"MetodosAnalisis RIGHT JOIN (SELECT ValoresEspecificaciones.ParametroID AS ParametroIDen, ValoresEspecificaciones.Obligatoriedad, ValoresEspecificaciones.Minimo, ValoresEspecificaciones.Maximo, ValoresEspecificaciones.Periodicidad, ValoresEspecificaciones.MetodoAnalisisID,ValoresEspecificaciones.desviacionMaximo, ValoresEspecificaciones.desviacionMinimo FROM Especificaciones INNER JOIN ValoresEspecificaciones ON Especificaciones.EspecificacionID = ValoresEspecificaciones.EspecificacionID INNER JOIN ListaParametros AS ListaParametros_1 ON ValoresEspecificaciones.ParametroID = ListaParametros_1.ParametroID WHERE (Especificaciones.EspecificacionID = " & EspecificacionID.ToString & ")) AS c1 ON MetodosAnalisis.MetodoAnalisisID = c1.MetodoAnalisisID RIGHT OUTER JOIN ListaParametros INNER JOIN UnidadesMedidas ON ListaParametros.UnidadMedidaID = UnidadesMedidas.UnidadMedidaID ON c1.ParametroIDen = ListaParametros.ParametroID")
Return dtb.Consultar
End Function
Public Function devolverPorEspecificacion(ByRef dtb As BasesParaCompatibilidad.DataBase) As DataTable
dtb.PrepararConsulta("select ListaParametros.ParametroID, ListaParametros.Nombre, t1.Minimo, t1.Maximo, t1.Obligatoriedad from ListaParametros left join (SELECT ValoresEspecificaciones.ParametroID, ValoresEspecificaciones.Obligatoriedad, ValoresEspecificaciones.Minimo, ValoresEspecificaciones.Maximo, ValoresEspecificaciones.MetodoAnalisisID FROM ListaParametros INNER JOIN ValoresEspecificaciones ON ListaParametros.ParametroID = ValoresEspecificaciones.ParametroID INNER JOIN Especificaciones ON ValoresEspecificaciones.EspecificacionID = Especificaciones.EspecificacionID WHERE (Especificaciones.EspecificacionID = " & EspecificacionID.ToString & ")) As t1 on ListaParametros.ParametroID = t1.ParametroID")
Return dtb.Consultar
End Function
Public Function existe(ByRef dtb As BasesParaCompatibilidad.DataBase) As Boolean
dtb.PrepararConsulta("select Count(*) from ValoresEspecificaciones where ParametroID = @par and EspecificacionID = @es")
dtb.AņadirParametroConsulta("@par", ParametroID)
dtb.AņadirParametroConsulta("@es", EspecificacionID)
Return CInt(dtb.Consultar().Rows(0).Item(0)) > 0
End Function
Public Function Modificar(ByRef dtb As BasesParaCompatibilidad.DataBase) As Boolean
dtb.PrepararConsulta("update ValoresEspecificaciones set " & _
"Obligatoriedad = '" & Obligatoriedad.ToString & _
"', Minimo = " & Minimo.ToString.Replace(","c, "."c) & _
", Maximo = " & Maximo.ToString.Replace(","c, "."c) & _
",Periodicidad = " & Convert.ToString(Periodicidad) & _
",desviacionMaximo = " & Desviacion_maximo.ToString.Replace(","c, "."c) & _
",desviacionMinimo = " & Desviacion_minimo.ToString.Replace(","c, "."c) & _
",MetodoAnalisisID=" & MetodoAnalisisID.ToString & _
" where ParametroID = " & ParametroID.ToString & " and EspecificacionID = " & EspecificacionID.ToString)
Return dtb.Execute
'Try
' Deprecated.ConsultaModificar("ValoresEspecificaciones", _
' "Obligatoriedad = '" & Obligatoriedad.ToString & _
' "', Minimo = " & Minimo.ToString.Replace(","c, "."c) & _
' ", Maximo = " & Maximo.ToString.Replace(","c, "."c) & _
' ",Periodicidad = " & Convert.ToString(Periodicidad) & _
' ",desviacionMaximo = " & Desviacion_maximo.ToString.Replace(","c, "."c) & _
' ",desviacionMinimo = " & Desviacion_minimo.ToString.Replace(","c, "."c) & _
' ",MetodoAnalisisID=" & MetodoAnalisisID.ToString, _
' "ParametroID = " & ParametroID.ToString & " and EspecificacionID = " & EspecificacionID.ToString)
' Return 1
'Catch ex As Exception
' MessageBox.Show(ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
' Return 0
'End Try
End Function
Public Function Insertar(ByRef dtb As BasesParaCompatibilidad.DataBase) As Boolean
dtb.PrepararConsulta("insert into ValoresEspecificaciones(ParametroID, EspecificacionID, Obligatoriedad, Minimo, Maximo, Periodicidad, MetodoAnalisisID, desviacionMaximo, desviacionMinimo) values(" & _
ParametroID.ToString & "," & EspecificacionID.ToString & ",'" & Obligatoriedad.ToString & "'," & _
Minimo.ToString.Replace(","c, "."c) & "," & Maximo.ToString.Replace(","c, "."c) & "," & _
Convert.ToString(Periodicidad) & "," & MetodoAnalisisID.ToString & "," & _
Desviacion_maximo.ToString.Replace(","c, "."c) & "," & Desviacion_minimo.ToString.Replace(","c, "."c) & ")")
Return dtb.Execute
'Try
' Deprecated.ConsultaInsertarConcampos("(ParametroID, EspecificacionID, Obligatoriedad, Minimo, Maximo, Periodicidad, MetodoAnalisisID, desviacionMaximo, desviacionMinimo, FechaModificacion, UsuarioModificacion)", _
' ParametroID.ToString & "," & EspecificacionID.ToString & ",'" & Obligatoriedad.ToString & "'," & _
' Minimo.ToString.Replace(","c, "."c) & "," & Maximo.ToString.Replace(","c, "."c) & "," & _
' Convert.ToString(Periodicidad) & "," & MetodoAnalisisID.ToString & "," & _
' Desviacion_maximo.ToString.Replace(","c, "."c) & "," & Desviacion_minimo.ToString.Replace(","c, "."c), _
' "ValoresEspecificaciones")
' Return 1
'Catch ex As Exception
' MessageBox.Show(ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
' Return 0
'End Try
End Function
Public Function Eliminar(ByRef dtb As BasesParaCompatibilidad.DataBase) As Boolean
dtb.PrepararConsulta("delete from ValoresEspecificaciones where ParametroID= @par and EspecificacionID= @esp")
dtb.AņadirParametroConsulta("@par", ParametroID)
dtb.AņadirParametroConsulta("@esp", EspecificacionID)
Return dtb.Execute
'Try
' BasesParaCompatibilidad.BD.ConsultaEliminar("ValoresEspecificaciones", "ParametroID = " & ParametroID.ToString & " and EspecificacionID = " & EspecificacionID.ToString)
' Return 1
'Catch ex As Exception
' MessageBox.Show(ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
' Return 0
'End Try
End Function
Public Function EliminarPorEspecificacion(ByRef dtb As BasesParaCompatibilidad.DataBase) As Boolean
dtb.PrepararConsulta("delete from ValoresEspecificaciones where EspecificacionID= @id")
dtb.AņadirParametroConsulta("@id", EspecificacionID)
Return dtb.Execute
'Try
' BasesParaCompatibilidad.BD.ConsultaEliminar("ValoresEspecificaciones", "EspecificacionID = " & EspecificacionID.ToString)
' Return 1
'Catch ex As Exception
' MessageBox.Show(ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
' Return 0
'End Try
End Function
#End Region
End Class
|
Imports CryptoNS = System.Security.Cryptography
Imports HashAlgo = System.Security.Cryptography.HashAlgorithm
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.IO
Namespace Crypto
Enum HashAlgorithm
SHA1
End Enum
Module HashHelper
Public Delegate Function HashFunction(data As Byte()()) As Byte()
Public HashFunctions As Dictionary(Of HashAlgorithm, HashFunction)
Public HashAlgorithms As Dictionary(Of HashAlgorithm, HashAlgo)
Sub New()
HashFunctions = New Dictionary(Of HashAlgorithm, HashFunction)()
HashFunctions(HashAlgorithm.SHA1) = AddressOf SHA1
End Sub
Private Function Combine(buffers As Byte()()) As Byte()
Dim length As Integer = 0
For Each buffer__1 As Byte() In buffers
length += buffer__1.Length
Next
Dim result As Byte() = New Byte(length - 1) {}
Dim position As Integer = 0
For Each buffer__1 As Byte() In buffers
Buffer.BlockCopy(buffer__1, 0, result, position, buffer__1.Length)
position += buffer__1.Length
Next
Return result
End Function
<System.Runtime.CompilerServices.Extension> _
Public Function Hash(algorithm As HashAlgorithm, ParamArray data As Byte()()) As Byte()
Return HashFunctions(algorithm)(data)
End Function
Private Function SHA1(ParamArray data As Byte()()) As Byte()
Using alg As System.Security.Cryptography.SHA1 = CryptoNS.SHA1.Create()
Return alg.ComputeHash(Combine(data))
End Using
End Function
End Module
End Namespace |
Imports CommonDemo.Helpers
Imports DevExpress.Mvvm.POCO
Imports DevExpress.Xpf.Core
Imports System
Imports System.Collections.ObjectModel
Imports System.ComponentModel
Imports System.Windows.Media
Namespace CommonDemo.TabControl.WebBrowser
Public Class WebBrowserMainViewModel
Public Overridable Property Tabs() As ObservableCollection(Of TabViewModel)
Public Overridable Property SpeedDials() As ObservableCollection(Of SpeedDialViewModel)
Public Shared Function Create() As WebBrowserMainViewModel
Return ViewModelSource.Create(Function() New WebBrowserMainViewModel())
End Function
Protected Sub New()
Tabs = New ObservableCollection(Of TabViewModel)()
Tabs.Add(TabViewModel.CreateNewTabViewModel())
SpeedDials = New ObservableCollection(Of SpeedDialViewModel)()
SpeedDials.Add(New SpeedDialViewModel(ImagesHelper.GetWebIcon("Microsoft.png"), New Uri("http://www.microsoft.com", UriKind.Absolute), "Microsoft"))
SpeedDials.Add(New SpeedDialViewModel(ImagesHelper.GetWebIcon("Google.png"), New Uri("http://www.google.com", UriKind.Absolute), "Google"))
SpeedDials.Add(New SpeedDialViewModel(ImagesHelper.GetWebIcon("Devexpress.png"), New Uri("http://www.devexpress.com", UriKind.Absolute), "DevExpress"))
SpeedDials.Add(New SpeedDialViewModel(ImagesHelper.GetWebIcon("VisualStudio.png"), New Uri("http://www.visualstudio.com", UriKind.Absolute), "Visual Studio"))
SpeedDials.Add(New SpeedDialViewModel(ImagesHelper.GetWebIcon("Stackoverflow.png"), New Uri("http://www.stackoverflow.com", UriKind.Absolute), "Stackoverflow"))
SpeedDials.Add(New SpeedDialViewModel(ImagesHelper.GetWebIcon("Facebook.png"), New Uri("http://www.facebook.com", UriKind.Absolute), "Facebook"))
SpeedDials.Add(New SpeedDialViewModel(ImagesHelper.GetWebIcon("Twitter.png"), New Uri("http://www.twitter.com", UriKind.Absolute), "Twitter"))
SpeedDials.Add(New SpeedDialViewModel(ImagesHelper.GetWebIcon("Youtube.png"), New Uri("http://www.youtube.com", UriKind.Absolute), "Youtube"))
SpeedDials.Add(New SpeedDialViewModel(ImagesHelper.GetWebIcon("Amazon.png"), New Uri("http://www.amazon.com", UriKind.Absolute), "Amazon"))
End Sub
Public Sub AddNewTab(ByVal e As TabControlTabAddingEventArgs)
e.Item = TabViewModel.CreateNewTabViewModel()
End Sub
End Class
Public Class TabViewModel
Public Overridable Property IsNewTab() As Boolean
Public Overridable Property Title() As String
Public Overridable Property Url() As Uri
Public Shared Function CreateNewTabViewModel() As TabViewModel
Return ViewModelSource.Create(Function() New TabViewModel())
End Function
Protected Sub New()
IsNewTab = True
Title = "Speed Dial"
End Sub
Public Sub LoadSpeedDial(ByVal speedDial As SpeedDialViewModel)
IsNewTab = False
Title = speedDial.Title
Url = speedDial.Url
End Sub
End Class
Public Class SpeedDialViewModel
Private privateIcon As ImageSource
Public Property Icon() As ImageSource
Get
Return privateIcon
End Get
Private Set(ByVal value As ImageSource)
privateIcon = value
End Set
End Property
Private privateUrl As Uri
Public Property Url() As Uri
Get
Return privateUrl
End Get
Private Set(ByVal value As Uri)
privateUrl = value
End Set
End Property
Private privateTitle As String
Public Property Title() As String
Get
Return privateTitle
End Get
Private Set(ByVal value As String)
privateTitle = value
End Set
End Property
Public Sub New(ByVal icon As ImageSource, ByVal url As Uri, ByVal title As String)
Me.Icon = icon
Me.Url = url
Me.Title = title
End Sub
End Class
End Namespace
|
Public Class frmMain
Sub DoRequest()
If InvokeRequired Then
Invoke(New MethodInvoker(AddressOf DoRequest))
Else
If (TextBox1.Text = Nothing) Then
DisplayMessage("Please input a Request URL.")
Exit Sub
End If
If Not (TextBox3.Text = Nothing) Then
HTTP.UserAgent = TextBox3.Text
End If
Dim Success As String = Nothing
If Not (TextBox5.Text = Nothing) Then
Success = TextBox5.Text
End If
If RadioButton1.Checked Then
HTTP.Method = "get"
Else
HTTP.Method = "post"
End If
HTTP.AllowAutoRedirect = CheckBox1.Checked
HTTP.KeepAlive = CheckBox2.Checked
Try
DisplayMessage("Alow Redirects: " & HTTP.AllowAutoRedirect)
DisplayMessage("Keep Alive: " & HTTP.KeepAlive)
DisplayMessage("UserAgent: " & HTTP.UserAgent)
DisplayMessage("Method: " & HTTP.Method)
DisplayMessage("Making Request...")
RichTextBox1.Text = HTTP.Request(TextBox1.Text, TextBox2.Text, TextBox4.Text, Success)
DisplayMessage("Request Complete.")
IO.File.WriteAllText(Application.StartupPath & "\Request.html", RichTextBox1.Text)
DisplayMessage("HTML saved to : " & Application.StartupPath & "\Request.html")
Catch ex As Exception
DisplayMessage("Error!")
DisplayMessage(ex.Message)
End Try
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim thrdRequest As New Threading.Thread(AddressOf DoRequest)
thrdRequest.IsBackground = True
thrdRequest.Start()
End Sub
Delegate Sub _DisplayMessage(ByVal Text As String)
Sub DisplayMessage(ByVal Text As String)
If InvokeRequired Then
Invoke(New _DisplayMessage(AddressOf DisplayMessage), Text)
Else
Dim L As New ListViewItem(Now.ToString("hh:mm:ss tt"))
L.SubItems.Add(Text)
ListView1.Items.Add(L)
End If
End Sub
End Class
Public Class HTTP
Public Shared Cookies As New Net.CookieContainer
#Region " UserAgent."
Private Shared _UserAgent As String = "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0" ' Default
Public Shared Property UserAgent() As String
Get
Return _UserAgent
End Get
Set(ByVal UserAgent_ As String)
_UserAgent = UserAgent_
End Set
End Property
#End Region
#Region " Method."
Private Shared _Method As String = "GET" ' Default
Public Shared Property Method() As String
Get
Return _Method
End Get
Set(ByVal Method_ As String)
_Method = Method_.ToUpper
End Set
End Property
#End Region
#Region " AllowAutoRedirect."
Private Shared _AllowAutoRedirect As Boolean = True ' Default
Public Shared Property AllowAutoRedirect() As Boolean
Get
Return _AllowAutoRedirect
End Get
Set(ByVal AllowAutoRedirect_ As Boolean)
_AllowAutoRedirect = AllowAutoRedirect_
End Set
End Property
#End Region
#Region " KeepAlive."
Private Shared _KeepAlive As Boolean = True ' Default
Public Shared Property KeepAlive() As Boolean
Get
Return _KeepAlive
End Get
Set(ByVal KeepAlive_ As Boolean)
_KeepAlive = KeepAlive_
End Set
End Property
#End Region
Public Shared Function Request(ByVal Host As String, Optional ByVal Referer As String = Nothing, Optional ByVal POSTData As String = Nothing, Optional ByVal SuccessString As String = Nothing) As String
Try
Dim Cookies_ As New Net.CookieContainer
Dim WebR As Net.HttpWebRequest = DirectCast(Net.WebRequest.Create(Host), Net.HttpWebRequest)
WebR.Method = _Method
WebR.CookieContainer = Cookies_
WebR.AllowAutoRedirect = _AllowAutoRedirect
WebR.KeepAlive = _KeepAlive
WebR.UserAgent = _UserAgent
WebR.ContentType = "application/x-www-form-urlencoded"
WebR.Referer = Referer
If (_Method = "POST") Then
Dim _PostData As Byte()
_PostData = System.Text.Encoding.Default.GetBytes(POSTData)
WebR.ContentLength = _PostData.Length
Dim StreamWriter As System.IO.Stream = WebR.GetRequestStream()
StreamWriter.Write(_PostData, 0, POSTData.Length)
StreamWriter.Dispose()
End If
Dim WebResponse As Net.HttpWebResponse = DirectCast(WebR.GetResponse, Net.HttpWebResponse)
Cookies_.Add(WebResponse.Cookies)
Cookies = Cookies_
Dim StreamReader As New System.IO.StreamReader(WebResponse.GetResponseStream)
Dim PageHTML As String = StreamReader.ReadToEnd()
If (SuccessString IsNot Nothing) Then
If PageHTML.Contains(SuccessString) Then
Return "Success!"
Else
Return "Failure!"
End If
Else
Return PageHTML
End If
Catch ex As Exception
Return ex.Message
End Try
End Function
End Class |
'======================================
' Copyright EntitySpaces, LLC 2005 - 2006
'======================================
Imports System.Data
Imports NUnit.Framework
'using Adapdev.UnitTest;
Imports System.Linq
Imports EntitySpaces.Interfaces
Imports EntitySpaces.DynamicQuery
Imports BusinessObjects
Namespace Tests.Base
<TestFixture> _
Public Class CollectionFixture
<Test> _
Public Sub CollectionFindByPrimaryKey()
Dim aggTest As New AggregateTest()
aggTest.Query.[Select]().Where(aggTest.Query.FirstName.Equal("Sarah"), aggTest.Query.LastName.Equal("Doe"))
Assert.IsTrue(aggTest.Query.Load())
Dim primaryKey As Integer = aggTest.Id.Value
Dim aggCloneColl As New AggregateTestCollection()
aggCloneColl.LoadAll()
Dim aggClone As AggregateTest = aggCloneColl.FindByPrimaryKey(primaryKey)
Assert.AreEqual("Doe", aggClone.str.LastName)
Assert.AreEqual("Sarah", aggClone.str.FirstName)
End Sub
<Test> _
Public Sub CollectionSort()
Dim aggTestColl As New AggregateTestCollection()
aggTestColl.LoadAll()
'aggTestColl.Filter = aggTestColl.AsQueryable().OrderBy(Function(s As ) s.Age)
aggTestColl.Filter = aggTestColl.AsQueryable().OrderBy(Function(s As AggregateTest) s.Age)
Dim oldAge As System.Nullable(Of Integer) = 0
For Each agg As AggregateTest In aggTestColl
If agg.Age.HasValue Then
Assert.IsTrue(CBool(oldAge <= agg.Age))
oldAge = agg.Age
End If
Next
aggTestColl.Filter = aggTestColl.AsQueryable().OrderByDescending(Function(s As AggregateTest) s.Age)
oldAge = 1000
For Each agg As AggregateTest In aggTestColl
If agg.Age.HasValue Then
Assert.IsTrue(CBool(oldAge >= agg.Age))
oldAge = agg.Age
End If
Next
aggTestColl.Filter = Nothing
Dim sorted As Boolean = True
oldAge = 0
For Each agg As AggregateTest In aggTestColl
If agg.Age.HasValue Then
If Not (oldAge <= agg.Age) Then
sorted = False
End If
oldAge = agg.Age
End If
Next
Assert.IsFalse(sorted)
End Sub
<Test> _
Public Sub CollectionSortDate()
Dim aggTestColl As New AggregateTestCollection()
aggTestColl.LoadAll()
aggTestColl.Filter = aggTestColl.AsQueryable().OrderBy(Function(s As AggregateTest) s.HireDate)
Dim oldDate As System.Nullable(Of DateTime) = Convert.ToDateTime("01/01/0001")
For Each agg As AggregateTest In aggTestColl
If agg.HireDate.HasValue Then
Assert.IsTrue(CBool(oldDate <= agg.HireDate))
oldDate = agg.HireDate
End If
Next
End Sub
<Test> _
Public Sub CollectionFilter()
Dim aggTestColl As New AggregateTestCollection()
aggTestColl.LoadAll()
Assert.AreEqual(30, aggTestColl.Count)
aggTestColl.Filter = aggTestColl.AsQueryable().Where(Function(f As AggregateTest) f.LastName = "Doe")
Assert.AreEqual(3, aggTestColl.Count)
For Each agg As AggregateTest In aggTestColl
Assert.AreEqual("Doe", agg.LastName)
Next
aggTestColl.Filter = Nothing
Assert.AreEqual(30, aggTestColl.Count)
aggTestColl.Filter = aggTestColl.AsQueryable().Where(Function(f As AggregateTest) f.LastName = "x")
Assert.AreEqual(0, aggTestColl.Count)
aggTestColl.Filter = Nothing
Assert.AreEqual(30, aggTestColl.Count)
End Sub
<Test> _
Public Sub CollectionFilterDate()
Dim aggTestColl As New AggregateTestCollection()
aggTestColl.LoadAll()
aggTestColl.Filter = aggTestColl.AsQueryable().OrderBy(Function(s As AggregateTest) s.Id)
Dim entity As AggregateTest = CType(aggTestColl(5), AggregateTest)
aggTestColl.Filter = aggTestColl.AsQueryable().Where(Function(f As AggregateTest) f.HireDate.HasValue AndAlso CBool(f.HireDate > entity.HireDate))
Assert.AreEqual(4, aggTestColl.Count)
aggTestColl.Filter = Nothing
Assert.AreEqual(30, aggTestColl.Count)
End Sub
'[Test]
'public void AssignPrimaryKeysTest()
'{
' AggregateTestCollection aggTestColl = new AggregateTestCollection();
' Assert.IsTrue(aggTestColl.LoadAll());
' Assert.AreEqual(1, aggTestColl.TestAssignPrimaryKeys());
' Assert.AreEqual(0, aggTestColl.TestRemovePrimaryKeys());
'}
<Test> _
Public Sub FilteredDeleteAll()
Dim aggTestColl As New AggregateTestCollection()
aggTestColl.LoadAll()
Assert.AreEqual(30, aggTestColl.Count)
aggTestColl.Filter = aggTestColl.AsQueryable().Where(Function(f As AggregateTest) f.LastName = "Doe")
Assert.AreEqual(3, aggTestColl.Count)
aggTestColl.MarkAllAsDeleted()
aggTestColl.Filter = Nothing
Assert.AreEqual(27, aggTestColl.Count)
End Sub
<Test> _
Public Sub TestForEach()
Dim aggTestColl As New AggregateTestCollection()
aggTestColl.LoadAll()
For Each entity As AggregateTest In aggTestColl
entity.LastName = "E_" & entity.LastName
Next
aggTestColl.Filter = aggTestColl.AsQueryable().Where(Function(f As AggregateTest) f.LastName.Contains("E_"))
Assert.AreEqual(30, aggTestColl.Count)
End Sub
<Test()> _
Public Sub TestCustomForEach()
AggregateTestCollection.CustomForEach()
End Sub
<Test()> _
Public Sub TestAttachDetachEntityModified()
Try
Using scope As New esTransactionScope()
Dim aggTestColl As New AggregateTestCollection()
Dim aggCloneColl As New AggregateTestCollection()
aggCloneColl.LoadAll()
For Each entity As AggregateTest In aggCloneColl
If entity.LastName = "Doe" Then
entity.MarkAllColumnsAsDirty(esDataRowState.Modified)
aggTestColl.AttachEntity(aggCloneColl.DetachEntity(entity))
Exit For
End If
Next
Assert.IsTrue(aggTestColl.IsDirty)
aggTestColl.Save()
Assert.IsFalse(aggTestColl.IsDirty, "Collection is still dirty")
aggTestColl.LoadAll()
Assert.AreEqual(30, aggTestColl.Count)
End Using
Finally
UnitTestBase.RefreshDatabase()
End Try
End Sub
<Test> _
Public Sub TestAttachDetachEntityAdded()
Try
Using scope As New esTransactionScope()
Dim aggTestColl As New AggregateTestCollection()
Dim aggCloneColl As New AggregateTestCollection()
aggCloneColl.LoadAll()
For Each entity As AggregateTest In aggCloneColl
If entity.LastName = "Doe" Then
entity.MarkAllColumnsAsDirty(esDataRowState.Added)
aggTestColl.AttachEntity(aggCloneColl.DetachEntity(entity))
Exit For
End If
Next
Assert.IsTrue(aggTestColl.IsDirty)
aggTestColl.Save()
Assert.IsFalse(aggTestColl.IsDirty, "Collection is still dirty")
aggTestColl.LoadAll()
Assert.AreEqual(31, aggTestColl.Count)
End Using
Finally
UnitTestBase.RefreshDatabase()
End Try
End Sub
<Test> _
Public Sub CombineCollections()
Dim coll As New OrderItemCollection()
coll.es.Connection.ConnectionString = UnitTestBase.GetFktString(coll.es.Connection)
coll.LoadAll()
Assert.AreEqual(15, coll.Count)
Dim coll2 As New OrderItemCollection()
coll2.es.Connection.ConnectionString = UnitTestBase.GetFktString(coll2.es.Connection)
coll2.LoadAll()
Assert.AreEqual(15, coll2.Count)
coll.Combine(coll2)
Assert.AreEqual(30, coll.Count)
End Sub
<Test> _
Public Sub CombineQueriedCollections()
Dim coll As New OrderItemCollection()
coll.es.Connection.ConnectionString = UnitTestBase.GetFktString(coll.es.Connection)
coll.Query.Where(coll.Query.ProductID = 1)
coll.Query.Load()
Assert.AreEqual(4, coll.Count)
Dim coll2 As New OrderItemCollection()
coll2.es.Connection.ConnectionString = UnitTestBase.GetFktString(coll2.es.Connection)
coll2.Query.Where(coll2.Query.ProductID = 2)
coll2.Query.Load()
Assert.AreEqual(3, coll2.Count)
coll.Combine(coll2)
Assert.AreEqual(7, coll.Count)
End Sub
<Test> _
Public Sub CombineJoinQueriedCollections()
Dim eq1 As New EmployeeQuery("e1")
Dim cq1 As New CustomerQuery("c1")
eq1.[Select](eq1, cq1.CustomerName)
eq1.InnerJoin(cq1).[On](eq1.EmployeeID = cq1.Manager)
eq1.Where(eq1.EmployeeID = 1)
Dim collection As New EmployeeCollection()
collection.es.Connection.ConnectionString = UnitTestBase.GetFktString(collection.es.Connection)
collection.Load(eq1)
Assert.AreEqual(35, collection.Count)
Dim eq2 As New EmployeeQuery("e2")
Dim cq2 As New CustomerQuery("c2")
eq2.[Select](eq2, cq2.CustomerName)
eq2.InnerJoin(cq2).[On](eq2.EmployeeID = cq2.Manager)
eq2.Where(eq2.EmployeeID = 2)
Dim collection2 As New EmployeeCollection()
collection2.es.Connection.ConnectionString = UnitTestBase.GetFktString(collection2.es.Connection)
collection2.Load(eq2)
Assert.AreEqual(12, collection2.Count)
collection.Combine(collection2)
Assert.AreEqual(47, collection.Count)
For Each emp As Employee In collection
Dim custName As String = CustomerMetadata.ColumnNames.CustomerName
Assert.IsTrue(emp.GetColumn(custName).ToString().Length > 0)
Next
End Sub
<Test> _
Public Sub CombineFilteredOriginal()
' Load a collection and apply a filter
Dim coll As New OrderItemCollection()
coll.es.Connection.ConnectionString = UnitTestBase.GetFktString(coll.es.Connection)
coll.LoadAll()
Assert.AreEqual(15, coll.Count)
'coll.Filter = coll.AsQueryable().Where(Function(f As OrderItem) f.ProductID = 1)
coll.Filter = coll.AsQueryable().Where(Function(f As OrderItem) CBool(f.ProductID = 1))
Assert.AreEqual(4, coll.Count)
' Load a second collection
Dim coll2 As New OrderItemCollection()
coll2.es.Connection.ConnectionString = UnitTestBase.GetFktString(coll2.es.Connection)
coll2.LoadAll()
Assert.AreEqual(15, coll2.Count)
' Combine the 15 rows from the second collection
' to the 15 rows from the first collection.
' Since the first collection still has a filter,
' only 8 rows are counted (4 from the first and 4 from the second).
coll.Combine(coll2)
Assert.AreEqual(8, coll.Count)
' Remove the filter to count all 30 rows.
coll.Filter = Nothing
Assert.AreEqual(30, coll.Count)
End Sub
<Test> _
Public Sub CombineFilteredCombine()
Dim coll As New OrderItemCollection()
coll.es.Connection.ConnectionString = UnitTestBase.GetFktString(coll.es.Connection)
coll.LoadAll()
Assert.AreEqual(15, coll.Count)
Dim coll2 As New OrderItemCollection()
coll2.es.Connection.ConnectionString = UnitTestBase.GetFktString(coll2.es.Connection)
coll2.LoadAll()
Assert.AreEqual(15, coll2.Count)
coll2.Filter = coll.AsQueryable().Where(Function(f As OrderItem) CBool(f.ProductID = 1))
Assert.AreEqual(4, coll2.Count)
coll.Combine(coll2)
Assert.AreEqual(19, coll.Count)
End Sub
<Test> _
Public Sub CombineFilteredOriginalAndCombine()
' Load a collection and apply a filter.
Dim coll As New OrderItemCollection()
coll.es.Connection.ConnectionString = UnitTestBase.GetFktString(coll.es.Connection)
coll.LoadAll()
Assert.AreEqual(15, coll.Count)
coll.Filter = coll.AsQueryable().Where(Function(f As OrderItem) CBool(f.ProductID = 1))
Assert.AreEqual(4, coll.Count)
' Load a second collection and apply a different filter.
Dim coll2 As New OrderItemCollection()
coll2.es.Connection.ConnectionString = UnitTestBase.GetFktString(coll2.es.Connection)
coll2.LoadAll()
Assert.AreEqual(15, coll2.Count)
coll2.Filter = coll2.AsQueryable().Where(Function(f As OrderItem) CBool(f.ProductID = 2))
Assert.AreEqual(3, coll2.Count)
' Add only the 3 filtered rows from coll2
' to all 15 rows in coll1.
' The filter for coll1 still applies.
' None of the items from coll2 appear,
' until the filter is removed from coll1.
coll.Combine(coll2)
Assert.AreEqual(4, coll.Count)
coll.Filter = Nothing
Assert.AreEqual(18, coll.Count)
End Sub
<Test> _
Public Sub CombineBuildOriginal()
' Start with an empty collection
Dim coll As New OrderItemCollection()
coll.es.Connection.ConnectionString = UnitTestBase.GetFktString(coll.es.Connection)
Assert.AreEqual(0, coll.Count)
Dim coll2 As New OrderItemCollection()
coll2.es.Connection.ConnectionString = UnitTestBase.GetFktString(coll2.es.Connection)
coll2.LoadAll()
Assert.AreEqual(15, coll2.Count)
coll2.Filter = coll2.AsQueryable().Where(Function(f As OrderItem) CBool(f.ProductID = 1))
Assert.AreEqual(4, coll2.Count)
' Add only the 4 filtered rows for coll2
coll.Combine(coll2)
Assert.AreEqual(4, coll.Count)
Dim coll3 As New OrderItemCollection()
coll3.es.Connection.ConnectionString = UnitTestBase.GetFktString(coll3.es.Connection)
coll3.LoadAll()
Assert.AreEqual(15, coll3.Count)
coll3.Filter = coll3.AsQueryable().Where(Function(f As OrderItem) CBool(f.ProductID = 2))
Assert.AreEqual(3, coll3.Count)
' Add only the 3 filtered rows for coll3
' coll1 now has all 7 rows
coll.Combine(coll3)
Assert.AreEqual(7, coll.Count)
End Sub
End Class
End Namespace
|
Public Class Customer
Public Sub New()
Me.New("", 0)
'Me.Name = ""
'Me.id = 0
'BirthDay = Nothing
End Sub
Public Sub New(Name As String, id As Integer)
Me.New(Name, id, Nothing)
'Me.Name = Name
'Me.id = id
'BirthDay = Nothing
End Sub
Public Sub New(Name As String, id As Integer, BirthDay As Date)
Me.Name = Name
Me.Id = id
Me.BirthDay = BirthDay
End Sub
' Campo, este forma parte de la implementación privada
Private _name As String
' Propiedad, forma parte de la interfaz pública
Public Property Name As String
' Metodo Getter es para obtener el valor
Get
Return _name
End Get
' Método Setter es para asignar el valor
Set(value As String)
' aqui se pueden hacer validaciones
_name = value.ToUpper()
End Set
End Property
Private _id As Integer
Public Property Id As Integer
Get
Return _id
End Get
Set(value As Integer)
_id = value
End Set
End Property
Private _birthDay As Date
Public Property BirthDay As Date
Get
Return _birthDay
End Get
Set(value As Date)
_birthDay = value
End Set
End Property
End Class
|
Imports System
Imports System.Threading
Imports System.Diagnostics
Imports System.Security.Principal
Namespace Security
Friend Class CustomPrincipal
Implements IPrincipal
Private m_User As IIdentity
Private m_OldPrincipal As IPrincipal
Private m_UserManager As IUserManager
Private m_ApplicationName As String
Private m_Roles As String()
Private Shared m_ThreadPolicySet As Boolean = False
Private Sub New(ByVal user As IIdentity, ByVal applicationName As String, ByVal userManager As IUserManager, ByVal cacheRoles As Boolean)
m_OldPrincipal = Thread.CurrentPrincipal
m_User = user
m_ApplicationName = applicationName
m_UserManager = userManager
If cacheRoles Then
m_Roles = m_UserManager.GetRoles(m_ApplicationName, m_User.Name)
End If
'Make this object the principal for this thread
Thread.CurrentPrincipal = Me
End Sub
Public Shared Sub Attach(ByVal user As IIdentity, ByVal applicationName As String, ByVal userManager As IUserManager)
Attach(user, applicationName, userManager, False)
End Sub
Public Shared Sub Attach(ByVal user As IIdentity, ByVal applicationName As String, ByVal userManager As IUserManager, ByVal cacheRoles As Boolean)
Debug.Assert(user.IsAuthenticated)
Dim _customPrincipal As IPrincipal = New CustomPrincipal(user, applicationName, userManager, cacheRoles)
'Make sure all future threads in this app domain use this principal
'but because default principal cannot be set twice:
If m_ThreadPolicySet = False Then
Dim currentDomain As AppDomain = AppDomain.CurrentDomain
currentDomain.SetThreadPrincipal(_customPrincipal)
m_ThreadPolicySet = True
End If
End Sub
Public Sub Detach()
Thread.CurrentPrincipal = m_OldPrincipal
End Sub
Public ReadOnly Property Identity() As IIdentity Implements IPrincipal.Identity
Get
Return m_User
End Get
End Property
Public Function IsInRole(ByVal role As String) As Boolean Implements IPrincipal.IsInRole
If Not m_Roles Is Nothing Then
For Each itm As String In m_Roles
If itm = role Then
Return True
End If
Next
Else
Return m_UserManager.IsInRole(m_ApplicationName, m_User.Name, role)
End If
End Function
End Class
End Namespace
|
Module modStructures
Public Structure MapRec
Dim Title As String
Dim BorderingMap() As Integer
Dim SizeX As Integer
Dim SizeY As Integer
Dim AttributesX As Integer
Dim AttributesY As Integer
Dim LayerCount As Byte
Dim Layers() As LayerRec
Dim Attributes(,) As AttributeRec
End Structure
Public Structure LayerRec
Dim LayerName As String
Dim UnderPlayer As Boolean
Dim Tiles(,) As TileRec
End Structure
Public Structure TileRec
Dim TileSetID As Integer
Dim TileSetX As Integer
Dim TileSetY As Integer
End Structure
Public Structure AttributeRec
Dim AttributeID As Byte
Dim Data1 As Integer
Dim Data2 As Integer
Dim Data3 As Integer
End Structure
End Module
|
Imports Microsoft.Xna.Framework
Imports Microsoft.Xna.Framework.Graphics
Imports Microsoft.Xna.Framework.Input
''' <summary>
''' Represents a complete dialog which is made up of one or multiple DialogueSegments
''' </summary>
Public Class Dialogue
''' <summary>
''' Array which cotains all DialogueSegments of this dialogue
''' </summary>
Public Segments As DialogueSegment()
''' <summary>
''' Texture of the speech box/bubble in which the dialogue text is displayed
''' </summary>
Public Shared SpeechBox As Texture2D
Dim KeyboardLastState As KeyboardState
Dim DisplayingTextLength As Single = 0.0F
Private _Active As Boolean = False
Public Property Active As Boolean
Get
Return _Active
End Get
Set(value As Boolean)
_Active = value
srcRect.Y = 0
End Set
End Property
Private _SegmentIndex As Integer = 0
Public Property SegmentIndex As Integer
Get
Return _SegmentIndex
End Get
Set(value As Integer)
_SegmentIndex = value
DisplayingTextLength = 0
End Set
End Property
Dim counter As Integer
Public Sub Update(gameTime As GameTime)
If Active Then
If KeyboardLastState.IsKeyDown(Keys.Space) AndAlso Keyboard.GetState.IsKeyUp(Keys.Space) Then
If SegmentIndex < Segments.Length - 1 Then
If Segments(SegmentIndex).DeactivateAfterSegment Then
Active = False
ScreenHandler.SelectedScreen.ToWorld.Player.IsInDialogue = False
End If
If Segments(SegmentIndex).ResetAfterSegment Then
' Reset to first segment
SegmentIndex = 0
Else
' Advance to next segment
SegmentIndex += 1
End If
Else
' End dialogue when last segment is reached
ScreenHandler.SelectedScreen.ToWorld.Player.IsInDialogue = False
Active = False
' Reset so dialogue starts at beginning if started again
SegmentIndex = 0
End If
End If
' Change srcRect to next frame of SpeechBox open animation
If srcRect.Y < 4000 AndAlso counter > 30 Then
srcRect.Y += 334
End If
End If
' Increment DisplayingTextLength to display letters of the text one by one
If DisplayingTextLength < Segments(SegmentIndex).Text.Length AndAlso srcRect.Y = 4000 Then
DisplayingTextLength += CSng(30.0F * gameTime.ElapsedGameTime.TotalSeconds)
End If
If counter > 30 Then
counter = 0
End If
counter += CInt(gameTime.ElapsedGameTime.TotalMilliseconds)
KeyboardLastState = Keyboard.GetState
End Sub
Dim srcRect As New Rectangle(0, 0, 3000, 800)
Public Sub Draw(sb As SpriteBatch)
If Active Then
sb.Draw(Segments(SegmentIndex).FaceSprite, New Rectangle(0, graphics.PreferredBackBufferHeight - 400, 330, 400), Color.White)
sb.Draw(SpeechBox, New Rectangle(300, graphics.PreferredBackBufferHeight - 250, graphics.PreferredBackBufferWidth - 500, 230), srcRect, Color.White)
If srcRect.Y = 4000 Then
'FontHand.DrawString(sb, New Vector2(450, graphics.PreferredBackBufferHeight - 220), Segments(SegmentIndex).Text.Substring(0, CInt(Math.Floor(DisplayingTextLength))), Color.White, 0.3)
' TODO: Change this to use the new font
End If
End If
End Sub
End Class
|
Imports System
Imports System.Collections.ObjectModel
Imports System.Linq
Imports System.Windows
Imports DevExpress.Mvvm
Imports DevExpress.Mvvm.DataAnnotations
Imports DevExpress.Mvvm.POCO
Namespace BarsDemo
Public Class MVVMBarViewModel
Public ReadOnly Property MessageBoxService() As IMessageBoxService
Get
Return Me.GetService(Of IMessageBoxService)()
End Get
End Property
Public Sub New()
Bars = New ObservableCollection(Of BarViewModel)()
SelectedText = String.Empty
Text = String.Empty
InitializeClipboardBar()
InitializeAdditionBar()
End Sub
Private Sub InitializeAdditionBar()
Dim addingBar As BarViewModel = ViewModelSource.Create(Function() New BarViewModel() With {.Name = "Addition"})
Bars.Add(addingBar)
Dim addGroupCommand = ViewModelSource.Create(Function() New GroupBarButtonInfo() With {.Caption = "Add", .LargeGlyph = DXImageHelper.GetDXImage("Add_32x32.png"), .SmallGlyph = DXImageHelper.GetDXImage("Add_16x16.png")})
Dim parentCommand = ViewModelSource.Create(Function() New ParentBarButtonInfo(Me, MyParentCommandType.CommandCreation) With {.Caption = "Add Command", .LargeGlyph = DXImageHelper.GetDXImage("Add_32x32.png"), .SmallGlyph = DXImageHelper.GetDXImage("Add_16x16.png")})
Dim parentBar = ViewModelSource.Create(Function() New ParentBarButtonInfo(Me, MyParentCommandType.BarCreation) With {.Caption = "Add Bar", .LargeGlyph = DXImageHelper.GetDXImage("Add_32x32.png"), .SmallGlyph = DXImageHelper.GetDXImage("Add_16x16.png")})
addGroupCommand.Commands.Add(parentCommand)
addGroupCommand.Commands.Add(parentBar)
addingBar.Commands.Add(addGroupCommand)
addingBar.Commands.Add(parentCommand)
addingBar.Commands.Add(parentBar)
End Sub
Private Sub InitializeClipboardBar()
Dim clipboardBar As BarViewModel = ViewModelSource.Create(Function() New BarViewModel() With {.Name = "Clipboard"})
Bars.Add(clipboardBar)
Dim cutCommand = ViewModelSource.Create(Function() New BarButtonInfo(AddressOf cutCommandExecuteFunc) With {.Caption = "Cut", .LargeGlyph = DXImageHelper.GetDXImage("Cut_32x32.png"), .SmallGlyph = DXImageHelper.GetDXImage("Cut_16x16.png")})
Dim copyCommand = ViewModelSource.Create(Function() New BarButtonInfo(AddressOf copyCommandExecuteFunc) With {.Caption = "Copy", .LargeGlyph = DXImageHelper.GetDXImage("Copy_32x32.png"), .SmallGlyph = DXImageHelper.GetDXImage("Copy_16x16.png")})
Dim pasteCommand = ViewModelSource.Create(Function() New BarButtonInfo(AddressOf pasteCommandExecuteFunc) With {.Caption = "Paste", .LargeGlyph = DXImageHelper.GetDXImage("Paste_32x32.png"), .SmallGlyph = DXImageHelper.GetDXImage("Paste_16x16.png")})
Dim selectCommand = ViewModelSource.Create(Function() New BarButtonInfo(AddressOf selectAllCommandExecuteFunc) With {.Caption = "Select All", .LargeGlyph = DXImageHelper.GetDXImage("SelectAll_32x32.png"), .SmallGlyph = DXImageHelper.GetDXImage("SelectAll_16x16.png")})
Dim blankCommand = ViewModelSource.Create(Function() New BarButtonInfo(AddressOf blankCommandExecuteFunc) With {.Caption = "Clear Page", .LargeGlyph = DXImageHelper.GetDXImage("New_32x32.png"), .SmallGlyph = DXImageHelper.GetDXImage("New_16x16.png")})
clipboardBar.Commands.Add(cutCommand)
clipboardBar.Commands.Add(copyCommand)
clipboardBar.Commands.Add(pasteCommand)
clipboardBar.Commands.Add(selectCommand)
clipboardBar.Commands.Add(blankCommand)
End Sub
Public Overridable Property Bars() As ObservableCollection(Of BarViewModel)
Public Overridable Property Text() As String
Public Overridable Property SelectedText() As String
Public Overridable Property SelectionStart() As Integer
Public Overridable Property SelectionLength() As Integer
#Region "CommandFuncs"
Public Sub cutCommandExecuteFunc()
OnCopyExecute()
SelectedText = String.Empty
End Sub
Public Sub copyCommandExecuteFunc()
OnCopyExecute()
End Sub
Public Sub pasteCommandExecuteFunc()
SelectedText = Clipboard.GetText()
SelectionStart += SelectionLength
SelectionLength = 0
End Sub
Public Sub selectAllCommandExecuteFunc()
SelectionStart = 0
SelectionLength = If(String.IsNullOrEmpty(Text), 0, Text.Count())
End Sub
Public Sub blankCommandExecuteFunc()
Text = String.Empty
End Sub
#End Region
Private Sub OnCopyExecute()
Clipboard.SetData(DataFormats.Text, DirectCast(SelectedText, Object))
End Sub
End Class
<POCOViewModel>
Public Class BarViewModel
Public Sub New()
Name = ""
Commands = New ObservableCollection(Of BarButtonInfo)()
End Sub
Public Overridable Property Name() As String
Public Overridable Property Commands() As ObservableCollection(Of BarButtonInfo)
End Class
End Namespace
|
'==========================================================================
'
' File: RLE.vb
' Location: Firefly.Compressing <Visual Basic .Net>
' Description: RLE算法类
' Version: 2010.06.23.
' Copyright(C) F.R.C.
'
'==========================================================================
Option Strict On
Imports System
Imports System.Math
Imports System.Collections.Generic
Namespace Compressing
''' <summary>
''' RLE算法类
''' 完成一个完整压缩的时间复杂度为O(n),空间复杂度为O(1)
''' </summary>
Public Class RLE
Private Data As Byte()
Private Offset As Integer
Private MinMatchLength As UInt16
Private MaxMatchLength As UInt16
Public Sub New(ByVal OriginalData As Byte(), ByVal MaxMatchLength As UInt16, Optional ByVal MinMatchLength As UInt16 = 1)
If OriginalData Is Nothing Then Throw New ArgumentNullException
If MinMatchLength <= 0 Then Throw New ArgumentOutOfRangeException
If MaxMatchLength < MinMatchLength Then Throw New ArgumentException
Data = OriginalData
Me.MinMatchLength = MinMatchLength
Me.MaxMatchLength = MaxMatchLength
Offset = 0
End Sub
''' <summary>原始数据</summary>
Public ReadOnly Property OriginalData() As Byte()
Get
Return Data
End Get
End Property
''' <summary>位置</summary>
Public ReadOnly Property Position() As Integer
Get
Return Offset
End Get
End Property
''' <summary>已重载。前进</summary>
Public Sub Proceed(ByVal n As Integer)
If n < 0 Then Throw New ArgumentOutOfRangeException
For i = 0 To n - 1
Proceed()
Next
End Sub
''' <summary>已重载。前进</summary>
Public Sub Proceed()
Offset += 1
End Sub
''' <summary>匹配</summary>
''' <remarks>无副作用</remarks>
Public Function Match() As RLEPointer
Dim d = Data(Offset)
Dim Max As UInt16 = CUShort(Min(MaxMatchLength, Data.Length - Offset))
Dim Count = Max
For l As UInt16 = 1 To Max - 1US
If Data(Offset + l) <> d Then
Count = l
Exit For
End If
Next
If Count < MinMatchLength Then Return Nothing
Return New RLEPointer(d, Count)
End Function
''' <summary>RLE匹配指针,表示一个RLE匹配</summary>
Public Class RLEPointer
Implements Pointer
''' <summary>重复值</summary>
Public ReadOnly Value As Byte
Private ReadOnly Count As UInt16
Public Sub New(ByVal Value As Byte, ByVal Count As UInt16)
Me.Value = Value
Me.Count = Count
End Sub
''' <summary>长度</summary>
Public ReadOnly Property Length() As Integer Implements Pointer.Length
Get
Return Count
End Get
End Property
End Class
End Class
End Namespace
|
Public Class AdHocSavedSearchBO
Public Property ReturnFields As List(Of AdHocQueryFieldBO)
Public Property SearchName As String
Public Property WhereClause As String
Public Property UserToken As String
End Class
|
Public Class ValeDesconto
Dim Ação As New TrfGerais
Private Operation As Byte
Const INS As Byte = 0
Const UPD As Byte = 1
Const DEL As Byte = 2
Private Sub ValeDesconto_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub SalvarBT_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SalvarBT.Click
'Area destinada para as validacoes
If Me.IdValeDesconto.Text = "" Then
MsgBox("O código do Vale desconto não foi informado, favor verificar.", 64, "Validação de Dados")
Me.IdValeDesconto.Focus()
Exit Sub
ElseIf Me.Cliente.Text = "" Then
MsgBox("O Cliente não foi informado, favor verificar.", 64, "Validação de Dados")
Me.Cliente.Focus()
Exit Sub
ElseIf Me.ValorVale.Text = "" Then
MsgBox("O Valor do Vale não foi informado, favor verificar.", 64, "Validação de Dados")
Me.ValorVale.Focus()
Exit Sub
ElseIf Me.DataLancamento.Text = "" Then
MsgBox("A data de Lançamento do vale não foi informado, favor verificar.", 64, "Validação de Dados")
Me.DataLancamento.Focus()
Exit Sub
ElseIf Me.DataValidade.Text = "" Then
MsgBox("A data de Validade do vale não foi informado, favor verificar.", 64, "Validação de Dados")
Me.DataValidade.Focus()
Exit Sub
ElseIf Me.MotivoVale.Text = "" Then
MsgBox("O motivo que foi dado o vale não foi informado, favor verificar.", 64, "Validação de Dados")
Me.MotivoVale.Focus()
Exit Sub
ElseIf Me.LoginAutorizou.Text = "" Then
MsgBox("O login de quem autorizou o vale não foi informado, favor verificar.", 64, "Validação de Dados")
Me.LoginAutorizou.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()
If Operation = INS Then
Dim Sql As String = "INSERT INTO ValeDesconto (IdValeDesconto, Cliente, NomeCliente, ValorVale, DataLancamento, DataValidade, MotivoVale, LoginAutorizou, Utilizado, Empresa) VALUES (@1, @2, @3, @4, @5, @6, @7, @8, @9, @10)"
Dim cmd As New OleDb.OleDbCommand(Sql, CNN)
cmd.Parameters.Add(New OleDb.OleDbParameter("@1", Nz(Me.IdValeDesconto.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@2", Nz(Me.Cliente.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@3", Nz(Me.NomeCliente.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@4", Nz(Me.ValorVale.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@5", Nz(Me.DataLancamento.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@6", Nz(Me.DataValidade.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@7", Nz(Me.MotivoVale.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@8", Nz(Me.MotivoVale.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@9", Me.Utilizado.Checked))
cmd.Parameters.Add(New OleDb.OleDbParameter("@10", CodEmpresa))
Try
cmd.ExecuteNonQuery()
MsgBox("Registro adicionado com sucesso", 64, "Validação de Dados")
Ação.Desbloquear_Controle(Me, False)
CNN.Close()
Catch ex As Exception
MsgBox(ex.Message, 64, "Validação de Dados")
End Try
Ação.Desbloquear_Controle(Me, False)
CNN.Close()
ElseIf Operation = UPD Then
Dim Sql As String = "Update ValeDesconto set IdValeDesconto = @1, Cliente = @2, NomeCliente = @3, ValorVale = @4, DataLancamento = @5, DataValidade = @6, MotivoVale = @7, LoginAutorizou = @8, Utilizado = @9, Empresa = @10 Where IdValeDesconto = '" & Me.IdValeDesconto.Text & "'"
Dim cmd As New OleDb.OleDbCommand(Sql, CNN)
cmd.Parameters.Add(New OleDb.OleDbParameter("@1", Nz(Me.IdValeDesconto.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@2", Nz(Me.Cliente.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@3", Nz(Me.NomeCliente.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@4", Nz(Me.ValorVale.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@5", Nz(Me.DataLancamento.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@6", Nz(Me.DataValidade.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@7", Nz(Me.MotivoVale.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@8", Nz(Me.MotivoVale.Text, 1)))
cmd.Parameters.Add(New OleDb.OleDbParameter("@9", Me.Utilizado.Checked))
cmd.Parameters.Add(New OleDb.OleDbParameter("@10", CodEmpresa))
Try
cmd.ExecuteNonQuery()
MsgBox("Registro Atualizado com sucesso", 64, "Validação de Dados")
Ação.Desbloquear_Controle(Me, False)
CNN.Close()
Catch x As Exception
MsgBox(x.Message)
Exit Sub
End Try
End If
End Sub
End Class |
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Namespace ChartsDemo
Public Class PricesModel
#Region "Data"
Private Const PointCount As Integer = 1500
Private Shared data_Renamed As List(Of PricesModel)
Public Shared ReadOnly Property Data() As List(Of PricesModel)
Get
If data_Renamed IsNot Nothing Then
Return data_Renamed
Else
data_Renamed = GetData()
Return data_Renamed
End If
End Get
End Property
Public Shared ReadOnly Property MinVisibleDate() As Date
Get
Return Data.First().ProductData(PointCount - 150).TradeDate
End Get
End Property
Private Shared Function GetData() As List(Of PricesModel)
Dim startDate = Date.Now.Subtract(TimeSpan.FromDays(PointCount))
Dim random = New Random()
Return Enumerable.Range(1, 3).Select(Function(x) New PricesModel With {.ProductName = "Product" & x, .ProductData = CreateProductData(startDate, random)}).ToList()
End Function
#End Region
#Region "Data Generator"
Private Shared Function CreateProductData(ByVal [date] As Date, ByVal random As Random) As List(Of PriceByDate)
Dim price = GenerateStartValue(random)
Dim productData_Renamed = New List(Of PriceByDate)()
For i As Integer = 0 To PointCount - 1
productData_Renamed.Add(New PriceByDate([date], price))
price += GenerateAddition(random)
[date] = [date].AddDays(1)
Next i
Return productData_Renamed
End Function
Private Shared Function GenerateAddition(ByVal random As Random) As Double
Dim factor As Double = random.NextDouble()
If factor = 1 Then
factor = 5
ElseIf factor = 0 Then
factor = -5
End If
Return (factor - 0.475) * 10
End Function
Private Shared Function GenerateStartValue(ByVal random As Random) As Double
Return random.NextDouble() * 100
End Function
#End Region
Private privateProductName As String
Public Property ProductName() As String
Get
Return privateProductName
End Get
Private Set(ByVal value As String)
privateProductName = value
End Set
End Property
Private privateProductData As List(Of PriceByDate)
Public Property ProductData() As List(Of PriceByDate)
Get
Return privateProductData
End Get
Private Set(ByVal value As List(Of PriceByDate))
privateProductData = value
End Set
End Property
End Class
Public Class PriceByDate
Private price_Renamed As Double
Private tradeDate_Renamed As Date
Public ReadOnly Property Price() As Double
Get
Return price_Renamed
End Get
End Property
Public ReadOnly Property TradeDate() As Date
Get
Return tradeDate_Renamed
End Get
End Property
Public Sub New(ByVal [date] As Date, ByVal price As Double)
Me.tradeDate_Renamed = [date]
Me.price_Renamed = price
End Sub
End Class
End Namespace
|
Imports Seagull.BarTender.Print
Imports Seagull.BarTender.Print.Database
Imports Seagull.BarTender.Print.Message
Imports System
Imports System.IO
Imports System.Data.SqlClient
Imports System.Data
Imports System.Text
Imports System.ComponentModel
Imports System.Runtime.InteropServices.Marshal
Imports System.Runtime.InteropServices
Imports System.Data.Common
Public Class ControlBarTender
Public format As LabelFormatDocument = Nothing ' The format that will be exported.
Private engine As Engine = Nothing ' The BarTender Print Engine.
Private previewPath As String '= "" ' The path to the folder where the previews will be exported.
Private dataPath As String '= "" ' The path to the folder where the text file data will be stored
Private currentPage As Integer = 1 ' The current page being viewed.
Private totalPages As Integer ' Number of pages.
Private messages As Messages
Private retcall As String ' String for returing the call if error occurs
Private Const appName As String = "Print Preview"
Private Const DatabaseConnectionNameInLabel As String = "LabelData"
Public Event PrintLabels(lblformat As LabelFormatDocument)
#Region " BarTender "
#Region " Methods "
Private Sub OpenBartenderFormat(op As OpenFileDialog)
' Close the previous format.
Try
If format IsNot Nothing Then
format.Close(SaveOptions.DoNotSaveChanges)
End If
Catch ex As Exception
End Try
' We need to delete the files associated with the last format.
Try
Dim files() As String = Directory.GetFiles(previewPath)
For Each filename As String In files
File.Delete(filename)
Next filename
Catch ex As Exception
End Try
' Put the UI back into a non-preview state.
DisablePreview()
' Open the format.
ExcelDataSet.BTLabelPathFileName = op.FileName
My.Settings.Label = op.FileName
My.Settings.Save()
My.Settings.Reload()
txtLabel.Text = op.FileName
If format IsNot Nothing Then
' Select the printer in use by the format.
cboPrinters.SelectedItem = format.PrintSetup.PrinterName
End If
Cursor.Current = Cursors.Default
cboPrinters.Enabled = True
End Sub
Private Sub CloseBartenderLabelFormat()
' Close the previous format.
Try
If format IsNot Nothing Then
format.Close(SaveOptions.DoNotSaveChanges)
End If
Catch ex As Exception
End Try
' We need to delete the files associated with the last format.
Dim files() As String = Directory.GetFiles(previewPath)
For Each filename As String In files
File.Delete(filename)
Next filename
' Put the UI back into a non-preview state.
DisablePreview()
picPreview.Visible = True
End Sub
Public Sub DisablePreview()
picPreview.ImageLocation = ""
'picPreview.Visible = False
btnPrev.Enabled = False
btnFirst.Enabled = False
lblNumPreviews.Visible = False
btnNext.Enabled = False
btnLast.Enabled = False
End Sub
Public Sub PreviewLabel(prntrName As String, fpreviewPath As String, fdataPath As String)
cboPrinters.Enabled = False
engine = MassarelliShippingLabels.engine
dataPath = fdataPath
previewPath = fpreviewPath
ExcelDataSet.PrinterName = prntrName
'Try
' engine = New Engine(True)
'Catch exception As PrintEngineException
' ' If the engine is unable to start, a PrintEngineException will be thrown.
' MessageBox.Show(Me, exception.Message, appName)
' 'Me.Close() ' Close this app. We cannot run without connection to an engine.
' Return
'End Try
Try
If format IsNot Nothing Then
format.Close(SaveOptions.DoNotSaveChanges)
End If
Catch ex As Exception
'If DirectCast(ex, Seagull.BarTender.Print.PrintEngineException).ErrorId = 2 Then
' MsgBox("You must load a Bartener Label before labels can be Previewed or Printed.", MsgBoxStyle.OkOnly, "Bartender Label not loaded.")
' Exit Sub
'End If
End Try
' We need to delete the files associated with the last format.
Dim files() As String = Directory.GetFiles(previewPath)
For Each filename As String In files
File.Delete(filename)
Next filename
' Put the UI back into a non-preview state.
DisablePreview()
Try
format = engine.Documents.Open(ExcelDataSet.BTLabelPathFileName)
CType(format.DatabaseConnections(DatabaseConnectionNameInLabel), TextFile).FileName = ExcelDataSet.LabelDataSourcePathFile
format.PrintSetup.PrinterName = ExcelDataSet.PrinterName
Catch ex As Exception
MsgBox(ex.Message)
End Try
' Set control states to show working. These will be reset when the work completes.
picUpdating.Visible = True
'dgvExcelPriceList.Visible = False
picPreview.Visible = True
Me.btnPrint.Enabled = True
' Have the background worker export the BarTender format.
'backgroundWorker.RunWorkerAsync(format)
PreviewAndPrintLabel()
End Sub
#Region " Background Worker "
Private Sub PreviewAndPrintLabel()
Dim oldFiles() As String = Directory.GetFiles(previewPath, "*.*")
For index As Integer = 0 To oldFiles.Length - 1
File.Delete(oldFiles(index))
Next index
Try
' Export the format's print previews.
format.ExportPrintPreviewToFile(previewPath, "PrintPreview%PageNumber%.jpg", ImageType.JPEG, _
Seagull.BarTender.Print.ColorDepth.ColorDepth24bit, _
New Resolution(picPreview.Width, picPreview.Height), _
System.Drawing.Color.White, OverwriteOptions.Overwrite, _
True, True, messages)
Dim files() As String = Directory.GetFiles(previewPath, "*.*")
totalPages = files.Length
Catch ex As Exception
End Try
' Report any messages.
If messages IsNot Nothing Then
If messages.Count > 5 Then
MessageBox.Show(Me, "There are more than 5 messages from the print preview. Only the first 5 will be displayed.", appName)
End If
Dim count As Integer = 0
For Each message As Seagull.BarTender.Print.Message In messages
MessageBox.Show(Me, message.Text, appName)
' if (++count >= 5)
count += 1
If count >= 5 Then
Exit For
End If
Next message
End If
picUpdating.Visible = False
'btnOpen.Enabled = True
'btnPreview.Enabled = True
cboPrinters.Enabled = True
' Only enable the preview if we actual got some pages.
If totalPages <> 0 Then
lblNumPreviews.Visible = True
currentPage = 1
ShowPreview()
End If
End Sub
Private Sub backgroundWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles backgroundWorker.DoWork
'Dim format As LabelFormatDocument = CType(e.Argument, LabelFormatDocument)
' Delete any existing files.
Dim oldFiles() As String = Directory.GetFiles(previewPath, "*.*")
For index As Integer = 0 To oldFiles.Length - 1
File.Delete(oldFiles(index))
Next index
Try
' Export the format's print previews.
format.ExportPrintPreviewToFile(previewPath, "PrintPreview%PageNumber%.jpg", ImageType.JPEG, _
Seagull.BarTender.Print.ColorDepth.ColorDepth24bit, _
New Resolution(picPreview.Width, picPreview.Height), _
System.Drawing.Color.White, OverwriteOptions.Overwrite, _
True, True, messages)
Dim files() As String = Directory.GetFiles(previewPath, "*.*")
totalPages = files.Length
Catch ex As Exception
End Try
End Sub
Private Sub backgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles backgroundWorker.RunWorkerCompleted
' Report any messages.
If messages IsNot Nothing Then
If messages.Count > 5 Then
MessageBox.Show(Me, "There are more than 5 messages from the print preview. Only the first 5 will be displayed.", appName)
End If
Dim count As Integer = 0
For Each message As Seagull.BarTender.Print.Message In messages
MessageBox.Show(Me, message.Text, appName)
' if (++count >= 5)
count += 1
If count >= 5 Then
Exit For
End If
Next message
End If
picUpdating.Visible = False
'btnOpen.Enabled = True
'btnPreview.Enabled = True
cboPrinters.Enabled = True
' Only enable the preview if we actual got some pages.
If totalPages <> 0 Then
lblNumPreviews.Visible = True
currentPage = 1
ShowPreview()
End If
End Sub
#End Region
Private Function CreateItemLabelsToPrintDataTable() As DataTable
'Create datatable
Dim oLabelData As New DataTable("LabelData")
If ExcelDataSet.ImportType = "SKU" Then
oLabelData.Columns.Add("Prnt", GetType(Boolean))
oLabelData.Columns.Add("SKU", GetType(String))
oLabelData.Columns.Add("Description", GetType(String))
oLabelData.Columns.Add("Retail", GetType(Decimal))
oLabelData.Columns.Add("MfgPart", GetType(String))
oLabelData.Columns.Add("MfgFinish", GetType(String))
oLabelData.Columns.Add("QtyOrd", GetType(Decimal))
ElseIf ExcelDataSet.ImportType = "UPC" Then
oLabelData.Columns.Add("Prnt", GetType(Boolean))
oLabelData.Columns.Add("SKU", GetType(String))
oLabelData.Columns.Add("Description", GetType(String))
oLabelData.Columns.Add("Retail", GetType(Decimal))
oLabelData.Columns.Add("MfgPart", GetType(String))
oLabelData.Columns.Add("MfgFinish", GetType(String))
oLabelData.Columns.Add("QtyOrd", GetType(Decimal))
oLabelData.Columns.Add("UPC", GetType(String))
End If
Return oLabelData
End Function
Public Sub PreviewEmptyLabel()
' Delete any existing files.
Dim oldFiles() As String = Directory.GetFiles(previewPath, "*.*")
For index As Integer = 0 To oldFiles.Length - 1
File.Delete(oldFiles(index))
Next index
' Export the format's print previews.
format.ExportPrintPreviewToFile(previewPath, "PrintPreview%PageNumber%.jpg", ImageType.JPEG, Seagull.BarTender.Print.ColorDepth.ColorDepth24bit, New Resolution(picPreview.Width, picPreview.Height), System.Drawing.Color.White, OverwriteOptions.Overwrite, True, True, messages)
Dim files() As String = Directory.GetFiles(previewPath, "*.*")
totalPages = files.Length
ShowPreview()
End Sub
''' <summary>
''' Show the preview of the current page.
''' </summary>
Private Sub ShowPreview()
' Our current preview number shouldn't be out of range,
' but we'll practice good programming by checking it.
If (currentPage < 1) OrElse (currentPage > totalPages) Then
currentPage = 1
End If
'previewPath = MassarelliShippingLabels.previewPath
' Update the page label and the preview Image.
lblNumPreviews.Text = String.Format("Page {0} of {1}", currentPage, totalPages)
Dim filename As String = String.Format("{0}\PrintPreview{1}.jpg", previewPath, currentPage)
picPreview.ImageLocation = filename
picPreview.Visible = True
' Enable or Disable controls as needed.
If currentPage = 1 Then
btnPrev.Enabled = False
btnFirst.Enabled = False
Else
btnPrev.Enabled = True
btnFirst.Enabled = True
End If
If currentPage = totalPages Then
btnNext.Enabled = False
btnLast.Enabled = False
Else
btnNext.Enabled = True
btnLast.Enabled = True
End If
'dgvExcelPriceList.Visible = False
picPreview.Visible = True
End Sub
#End Region
#End Region
Private Sub SetUpControls()
'List the Local Printers
Dim printers As New Printers()
For Each printer As Printer In printers
cboPrinters.Items.Add(printer.PrinterName)
Next printer
cboPrinters.Text = My.Settings.Printer
ExcelDataSet.PrinterName = My.Settings.Printer
With My.Settings
If .Printer = "" Then
.Printer = ExcelDataSet.PrinterName
End If
End With
Try
If My.Settings.Label > "" Then
ExcelDataSet.BTLabelPathFileName = My.Settings.Label
txtLabel.Text = My.Settings.Label
End If
Catch ex As Exception
txtLabel.Text = ""
ExcelDataSet.BTLabelPathFileName = ""
End Try
End Sub
Private Sub ControlBarTender_Load(sender As Object, e As System.EventArgs) Handles Me.Load
SetUpControls()
End Sub
Public Function WriteTextFile(ByVal arrItems(,) As String, previewPath As String, dataPath As String) As String
Dim RetMethod As String = "WriteTextFile"
Dim RetCall As String = ""
Dim i As Integer
Dim tmpFileName As String = "LabelData" & Now.ToString("MMddyyyyhhmmss")
IsLoading = False
previewPath = previewPath
dataPath = dataPath
tmpFileName = dataPath & "\" & tmpFileName & ".txt"
'Delete the temporary text file if it exists
Try
Kill(tmpFileName)
Catch ex As Exception
End Try
ExcelDataSet.LabelDataSourcePathFile = tmpFileName 'NOTE: Text file is not written until objWriter.CLOSE
Using objWriter As New StreamWriter(tmpFileName, True)
Try
For i = 0 To arrItems.GetUpperBound(0)
'If i = 99 Then
' MsgBox("STOP")
'End If
If ExcelDataSet.ImportType = "SKU" Then
RetCall = "objWriter.WriteLine" & arrItems(i, 0).ToString & "," & arrItems(i, 1).ToString & "," & arrItems(i, 2).ToString & "," & arrItems(i, 3).ToString & "," & arrItems(i, 4).ToString & "," & arrItems(i, 5).ToString
objWriter.WriteLine(arrItems(i, 0).ToString & "," & arrItems(i, 1).ToString & "," & arrItems(i, 2).ToString & "," & arrItems(i, 3).ToString & "," & arrItems(i, 4).ToString & "," & arrItems(i, 5).ToString)
ElseIf ExcelDataSet.ImportType = "UPC" Then
RetCall = "objWriter.WriteLine" & arrItems(i, 0).ToString & "," & arrItems(i, 1).ToString & "," & arrItems(i, 2).ToString & "," & arrItems(i, 3).ToString & "," & arrItems(i, 4).ToString & "," & arrItems(i, 5).ToString & "," & arrItems(i, 6).ToString
objWriter.WriteLine(arrItems(i, 0).ToString & "," & arrItems(i, 1).ToString & "," & arrItems(i, 2).ToString & "," & arrItems(i, 3).ToString & "," & arrItems(i, 4).ToString & "," & arrItems(i, 5).ToString & "," & arrItems(i, 6).ToString)
Else
RetCall = "objWriter.WriteLine" & arrItems(i, 0).ToString & "|" & arrItems(i, 1).ToString & "|" & arrItems(i, 2).ToString & "|" & arrItems(i, 3).ToString & "|" & arrItems(i, 4).ToString & "|" & arrItems(i, 5).ToString & "|" & arrItems(i, 6).ToString & "|" & arrItems(i, 7).ToString & "|" & arrItems(i, 8).ToString & "|" & arrItems(i, 9).ToString
objWriter.WriteLine(arrItems(i, 0).ToString & "|" & arrItems(i, 1).ToString & "|" & arrItems(i, 2).ToString & "|" & arrItems(i, 3).ToString & "|" & arrItems(i, 4).ToString & "|" & arrItems(i, 5).ToString & "|" & arrItems(i, 6).ToString & "|" & arrItems(i, 7).ToString & "|" & arrItems(i, 8).ToString & "|" & arrItems(i, 9).ToString)
'NOTE: Text file is not written until objWriter.CLOSE
End If
Next
Catch ex As Exception
MsgBox("Method: " & RetMethod & ", Call: " & RetCall, MsgBoxStyle.OkOnly, "Error")
MsgBox(ex.Message)
End Try
objWriter.Close()
End Using
Return tmpFileName
End Function
Private Sub btnNext_Click(sender As System.Object, e As System.EventArgs) Handles btnNext.Click
currentPage += 1
ShowPreview()
End Sub
Private Sub btnFirst_Click(sender As System.Object, e As System.EventArgs) Handles btnFirst.Click
currentPage = 1
ShowPreview()
End Sub
Private Sub btnPrev_Click(sender As System.Object, e As System.EventArgs) Handles btnPrev.Click
currentPage -= 1
ShowPreview()
End Sub
Private Sub btnLast_Click(sender As System.Object, e As System.EventArgs) Handles btnLast.Click
currentPage = totalPages
ShowPreview()
End Sub
Private Sub btnLoadBartenderLabel_Click(sender As System.Object, e As System.EventArgs) Handles btnLoadBartenderLabel.Click
Dim op As OpenFileDialog = DirectCast(Me.OpenFileDialogBartender, OpenFileDialog)
If op.ShowDialog() = Windows.Forms.DialogResult.Cancel Then
Exit Sub
Else
OpenBartenderFormat(op)
op.Dispose()
End If
My.Settings.Label = op.FileName
My.Settings.Save()
txtLabel.Text = My.Settings.Label
ExcelDataSet.BTLabelPathFileName = My.Settings.Label
If My.Settings.Label > "" AndAlso My.Settings.Printer > "" Then
EnableTextBox(MassarelliShippingLabels.tbOrderNo, True)
Else
EnableTextBox(MassarelliShippingLabels.tbOrderNo, True)
End If
End Sub
Private Sub txtLabel_MouseEnter(sender As Object, e As System.EventArgs) Handles txtLabel.MouseEnter
ToolTipLabelPrinter.SetToolTip(txtLabel, ExcelDataSet.BTLabelPathFileName)
End Sub
Private Sub btnPrint_Click(sender As Object, e As System.EventArgs) Handles btnPrint.Click
RaiseEvent PrintLabels(format)
End Sub
'Private Sub cboPrinters_DisplayMemberChanged(sender As Object, e As System.EventArgs) Handles cboPrinters.DisplayMemberChanged
'End Sub
Private Sub cboPrinters_SelectedValueChanged(sender As Object, e As System.EventArgs) Handles cboPrinters.SelectedValueChanged
My.Settings.Printer = cboPrinters.Text
My.Settings.Save()
ExcelDataSet.PrinterName = cboPrinters.Text
If My.Settings.Label > "" AndAlso My.Settings.Printer > "" Then
EnableTextBox(MassarelliShippingLabels.tbOrderNo, True)
Else
EnableTextBox(MassarelliShippingLabels.tbOrderNo, True)
End If
End Sub
Private Sub EnableTextBox(txt As RichTextBox, enableTxt As Boolean)
txt.Enabled = enableTxt
End Sub
'Private Sub txtLabel_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtLabel.TextChanged
' My.Settings.Label = cboPrinters.Text
' My.Settings.Save()
' ExcelDataSet.PrinterName = cboPrinters.Text
' If My.Settings.Label > "" AndAlso My.Settings.Printer > "" Then
' EnableTextBox(MassarelliShippingLabels.tbOrderNo, True)
' Else
' EnableTextBox(MassarelliShippingLabels.tbOrderNo, True)
' End If
'End Sub
End Class
|
Public Class ctrlHotSpot
Public ContainerClass As PointingSticker
Public Title As String
Public Brush As SolidBrush
Public Pen As Pen = Pens.Red
Public Event HotSpot_Updated(ByVal hotSpot As ctrlHotSpot)
Public Sub New()
' This call is required by the designer.
InitializeComponent()
Brush = New SolidBrush(Pen.Color)
End Sub
Protected Overrides Sub OnPaint(e As System.Windows.Forms.PaintEventArgs)
MyBase.OnPaint(e)
'e.Graphics.DrawEllipse(Pens.Red, 0, 0, Me.Width - 1, Me.Height - 1)
e.Graphics.FillEllipse(Brush, 0, 0, Me.Width - 1, Me.Height - 1)
End Sub
Public ReadOnly Property Vertix As Point
Get
Return New Point(Me.Left + Me.Width / 2, Me.Top + Me.Height / 2)
End Get
End Property
Private Sub ctrlHotSpot_LocationChanged(sender As System.Object, e As System.EventArgs) Handles MyBase.LocationChanged
RaiseEvent HotSpot_Updated(Me)
End Sub
Private Sub ctrlHotSpot_MouseEnter(sender As System.Object, e As System.EventArgs) Handles MyBase.MouseEnter
ContainerClass.ParentContainer.DisplayHint("Arrastre el punto para recolocarlo")
End Sub
Private Sub ctrlHotSpot_MouseLeave(sender As System.Object, e As System.EventArgs) Handles MyBase.MouseLeave
ContainerClass.ParentContainer.DisplayHint("")
End Sub
End Class
|
Imports System.Data.SqlClient
Public Class Embarques
Private idEmbarcador As Integer
Private idProducto As Integer
Private idVariedad As Integer
Private idEnvase As Integer
Private idTamano As Integer
Private idEtiqueta As Integer
Private fecha As Date
Private fecha2 As Date
Public Property EIdEmbarcador() As Integer
Get
Return Me.idEmbarcador
End Get
Set(value As Integer)
Me.idEmbarcador = value
End Set
End Property
Public Property EIdProducto() As Integer
Get
Return Me.idProducto
End Get
Set(value As Integer)
Me.idProducto = value
End Set
End Property
Public Property EIdVariedad() As Integer
Get
Return Me.idVariedad
End Get
Set(value As Integer)
Me.idVariedad = value
End Set
End Property
Public Property EIdEnvase() As Integer
Get
Return Me.idEnvase
End Get
Set(value As Integer)
Me.idEnvase = value
End Set
End Property
Public Property EIdTamano() As Integer
Get
Return Me.idTamano
End Get
Set(value As Integer)
Me.idTamano = value
End Set
End Property
Public Property EIdEtiqueta() As Integer
Get
Return Me.idEtiqueta
End Get
Set(value As Integer)
Me.idEtiqueta = value
End Set
End Property
Public Property EFecha() As String
Get
Return Me.fecha
End Get
Set(value As String)
Me.fecha = value
End Set
End Property
Public Property EFecha2() As String
Get
Return Me.fecha2
End Get
Set(value As String)
Me.fecha2 = value
End Set
End Property
Public Function ObtenerListadoReporteEmbarques(ByVal aplicaFecha As Boolean) As DataTable
Try
Dim datos As New DataTable
Dim comando As New SqlCommand()
comando.Connection = BaseDatos.conexionEmpaque
Dim condicion As String = String.Empty
Dim condicionFechaRango As String = String.Empty
Dim condicionTipoExportacion As String = String.Empty
Dim condicionTipoNacional As String = String.Empty
If (Me.EIdEmbarcador > 0) Then
condicion &= " AND E.IdEmbarcador=@idEmbarcador "
End If
If (aplicaFecha) Then
condicionFechaRango &= " AND Fecha BETWEEN @fecha AND @fecha2 "
End If
comando.CommandText = String.Format("SELECT E.Id, E.Fecha, CONVERT(VARCHAR(5), E.Hora, 108), CASE WHEN E.IdTipo=1 THEN 'Exportación' WHEN E.IdTipo=2 THEN 'Nacional' ELSE '' END, E.IdEmbarcador, E2.Nombre, E.IdCliente, C.Nombre, E.IdLineaTransporte, LT.Nombre, E.IdTrailer, T.Serie, E.IdCajaTrailer, CT.Serie, E.IdChofer, C2.Nombre, E.IdAduanaMex, AM.Nombre, E.IdAduanaUsa, AU.Nombre, E.IdDocumentador, D.Nombre, E.Temperatura, E.Termografo, E.PrecioFlete, E.Sello1, E.Sello2, E.Sello3, E.Sello4, E.Sello5, E.Sello6, E.Sello7, E.Sello8, E.Factura, E.GuiaCaades, E.Observaciones " & _
" FROM Embarques AS E " & _
" LEFT JOIN {0}Productores AS P ON E.IdProductor = P.Id " & _
" LEFT JOIN {0}Productores AS E2 ON E.IdEmbarcador = E2.Id " & _
" LEFT JOIN {0}Clientes AS C ON E.IdCliente = C.Id " & _
" LEFT JOIN {0}LineasTransportes AS LT ON E.IdLineaTransporte = LT.Id " & _
" LEFT JOIN {0}Trailers AS T ON E.IdLineaTransporte = T.IdLineaTransporte AND E.IdTrailer = T.Id " & _
" LEFT JOIN {0}CajasTrailers AS CT ON E.IdCajaTrailer = CT.Id " & _
" LEFT JOIN {0}Choferes AS C2 ON E.IdChofer = C2.Id " & _
" LEFT JOIN {0}AduanasMex AS AM ON E.IdAduanaMex = AM.Id " & _
" LEFT JOIN {0}AduanasUsa AS AU ON E.IdAduanaUsa = AU.Id " & _
" LEFT JOIN {0}Documentadores AS D ON E.IdDocumentador = D.Id " & _
" WHERE 0=0 {1}" & _
" ", EYELogicaReporteEmbarques.Programas.bdCatalogo & ".dbo." & EYELogicaReporteEmbarques.Programas.prefijoBaseDatosEmpaque, condicion & condicionFechaRango)
comando.Parameters.AddWithValue("@idEmbarcador", Me.EIdEmbarcador)
comando.Parameters.AddWithValue("@fecha", EYELogicaReporteEmbarques.Funciones.ValidarFechaAEstandar(Me.EFecha))
comando.Parameters.AddWithValue("@fecha2", EYELogicaReporteEmbarques.Funciones.ValidarFechaAEstandar(Me.EFecha2))
BaseDatos.conexionEmpaque.Open()
Dim dataReader As SqlDataReader
dataReader = comando.ExecuteReader()
datos.Load(dataReader)
BaseDatos.conexionEmpaque.Close()
Return datos
Catch ex As Exception
Throw ex
Finally
BaseDatos.conexionEmpaque.Close()
End Try
End Function
Public Function ObtenerListadoReporteEmbarquesDetallado(ByVal aplicaFecha As Boolean) As DataTable
Try
Dim datos As New DataTable
Dim comando As New SqlCommand()
comando.Connection = BaseDatos.conexionEmpaque
Dim condicion As String = String.Empty
Dim condicionFechaRango As String = String.Empty
Dim condicionTipoExportacion As String = String.Empty
Dim condicionTipoNacional As String = String.Empty
If (Me.EIdEmbarcador > 0) Then
condicion &= " AND E.IdEmbarcador=@idEmbarcador "
End If
If (Me.EIdProducto > 0) Then
condicion &= " AND T.IdProducto=@idProducto "
End If
If (Me.EIdVariedad > 0) Then
condicion &= " AND T.IdVariedad=@idVariedad "
End If
If (Me.EIdEnvase > 0) Then
condicion &= " AND T.IdEnvase=@idEnvase "
End If
If (Me.EIdTamano > 0) Then
condicion &= " AND T.IdTamano=@idTamano "
End If
If (Me.EIdEtiqueta > 0) Then
condicion &= " AND T.IdEtiqueta=@idEtiqueta "
End If
If (aplicaFecha) Then
condicionFechaRango &= " AND Fecha BETWEEN @fecha AND @fecha2 "
End If
comando.CommandText = String.Format("SELECT E.Id, E.Fecha, CONVERT(VARCHAR(5), E.Hora, 108), CASE WHEN E.IdTipo=1 THEN 'Exportación' WHEN E.IdTipo=2 THEN 'Nacional' ELSE '' END, E.IdEmbarcador, E2.Nombre, T.IdProducto, P2.Nombre, T.IdVariedad, V.Nombre, T.IdEnvase, E3.Nombre, T.IdTamano, T2.Nombre, T.IdEtiqueta, E4.Nombre, T.CantidadCajas, T.PesoCajas " & _
" FROM Embarques AS E " & _
" LEFT JOIN (SELECT IdEmbarque, IdTipoEmbarque, IdProducto, IdVariedad, IdEnvase, IdTamano, IdEtiqueta, ISNULL(SUM(CantidadCajas), 0) AS CantidadCajas, ISNULL(SUM(PesoTotalCajas), 0) AS PesoCajas FROM Tarimas GROUP BY IdEmbarque, IdTipoEmbarque, IdProducto, IdVariedad, IdEnvase, IdTamano, IdEtiqueta) AS T ON E.Id = T.IdEmbarque AND E.IdTipo = T.IdTipoEmbarque " & _
" LEFT JOIN {0}Productores AS E2 ON E.IdEmbarcador = E2.Id " & _
" LEFT JOIN {0}Productos AS P2 ON T.IdProducto = P2.Id " & _
" LEFT JOIN {0}Variedades AS V ON T.IdProducto = V.IdProducto AND T.IdVariedad = V.Id " & _
" LEFT JOIN {0}Envases AS E3 ON T.IdEnvase = E3.Id " & _
" LEFT JOIN {0}Tamanos AS T2 ON T.IdProducto = T2.IdProducto AND T.IdTamano = T2.Id " & _
" LEFT JOIN {0}Etiquetas AS E4 ON T.IdEtiqueta = E4.Id " & _
" WHERE 0=0 {1}" & _
" ", EYELogicaReporteEmbarques.Programas.bdCatalogo & ".dbo." & EYELogicaReporteEmbarques.Programas.prefijoBaseDatosEmpaque, condicion & condicionFechaRango)
comando.Parameters.AddWithValue("@idEmbarcador", Me.EIdEmbarcador)
comando.Parameters.AddWithValue("@idProducto", Me.EIdProducto)
comando.Parameters.AddWithValue("@idVariedad", Me.EIdVariedad)
comando.Parameters.AddWithValue("@idEnvase", Me.EIdEnvase)
comando.Parameters.AddWithValue("@idTamano", Me.EIdTamano)
comando.Parameters.AddWithValue("@idEtiqueta", Me.EIdEtiqueta)
comando.Parameters.AddWithValue("@fecha", EYELogicaReporteEmbarques.Funciones.ValidarFechaAEstandar(Me.EFecha))
comando.Parameters.AddWithValue("@fecha2", EYELogicaReporteEmbarques.Funciones.ValidarFechaAEstandar(Me.EFecha2))
BaseDatos.conexionEmpaque.Open()
Dim dataReader As SqlDataReader
dataReader = comando.ExecuteReader()
datos.Load(dataReader)
BaseDatos.conexionEmpaque.Close()
Return datos
Catch ex As Exception
Throw ex
Finally
BaseDatos.conexionEmpaque.Close()
End Try
End Function
End Class
|
Imports System.Runtime.CompilerServices
Imports System.Reflection
Imports LSW.Exceptions
Namespace Extension
Public Module DataSetLinqHelper
<Extension()> _
Public Function CopyToDataTable(Of T)(source As IEnumerable(Of T)) As DataTable
Return New ObjectShredder(Of T)().Shred(source, Nothing, Nothing).Copy
End Function
<Extension()> _
Public Function CopyToDataTable(Of T)(source As IEnumerable(Of T), table As DataTable, options As System.Nullable(Of LoadOption)) As DataTable
Return New ObjectShredder(Of T)().Shred(source, table, options).Copy
End Function
<Extension()>
Public Function ToEntity(Of T As New)(row As DataRow) As T
Dim item As New T
If row Is Nothing Then
Return item
End If
Dim pi = item.GetType.GetProperties
For Each p In pi
If Not CanSetPropertyValue(p, row) Then
Continue For
End If
Try
If row(p.Name) Is DBNull.Value Then
p.SetValue(item, Nothing, Nothing)
Continue For
End If
p.SetValue(item, row(p.Name), Nothing)
Catch ex As Exception
Dim e As New LSWFrameworkException(ex)
End Try
Next
Return item
End Function
Private Function CanSetPropertyValue(propertyInfo As PropertyInfo, adaptedRow As DataRow) As Boolean
If Not propertyInfo.CanWrite Then
Return False
End If
If Not adaptedRow.Table.Columns.Contains(propertyInfo.Name) Then
Return False
End If
Return True
End Function
End Module
End Namespace |
Imports System.Configuration
Imports AutoMapper
Imports UGPP.CobrosCoactivo.Entidades
Public Class TareaObservacionDAL
Inherits AccesObject(Of Entidades.TareaObservacion)
Public Property ConnectionString As String
''' <summary>
''' Entidad de conección a la base de datos
''' </summary>
Dim db As UGPPEntities
Dim _auditLog As LogAuditoria
Dim Parameters As List(Of SqlClient.SqlParameter) = New List(Of SqlClient.SqlParameter)()
Public Sub New()
ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ToString()
db = New UGPPEntities()
End Sub
Public Sub New(ByVal auditLog As LogAuditoria)
ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ToString()
db = New UGPPEntities()
_auditLog = auditLog
End Sub
''' <summary>
''' Convierte un objeto del tipo Entidades.TareaObservacion a Datos.TAREA_OBSERVACION
''' </summary>
''' <param name="prmObjTareaObervacionEntidad">Objeto de tipo Entidades.TareaObservacion</param>
''' <returns>Objeto de tipo Datos.TAREA_OBSERVACION</returns>
Public Function ConvertirADatosTareaObervacion(ByVal prmObjTareaObervacionEntidad As Entidades.TareaObservacion) As Datos.TAREA_OBSERVACION
Dim tareaObservacion As Datos.TAREA_OBSERVACION
Dim config As New MapperConfiguration(Function(cfg)
Return cfg.CreateMap(Of Datos.TAREA_OBSERVACION, Entidades.TareaObservacion)()
End Function)
Dim IMapper = config.CreateMapper()
tareaObservacion = IMapper.Map(Of Entidades.TareaObservacion, Datos.TAREA_OBSERVACION)(prmObjTareaObervacionEntidad)
Return tareaObservacion
End Function
''' <summary>
''' Metódo que agrega un nuevo registro en la tabla TAREA_ONSERVACION
''' </summary>
''' <param name="prmObjTareaObservacionEntidad">Objeto de tipo Entidades.TareaObservacion</param>
''' <returns>Objeto de tipo Datos.TAREA_OBSERVACION</returns>
Public Function crearTareaObservacion(ByVal prmObjTareaObservacionEntidad As Entidades.TareaObservacion) As Datos.TAREA_OBSERVACION
Parameters = New List(Of SqlClient.SqlParameter)()
Dim tareaObservacion = ConvertirADatosTareaObervacion(prmObjTareaObservacionEntidad)
Parameters.Add(New SqlClient.SqlParameter("@COD_ID_TAREA_OBSERVACION", tareaObservacion.COD_ID_TAREA_OBSERVACION))
Parameters.Add(New SqlClient.SqlParameter("@OBSERVACION", tareaObservacion.OBSERVACION))
Parameters.Add(New SqlClient.SqlParameter("@IND_ESTADO", tareaObservacion.IND_ESTADO))
Parameters.Add(New SqlClient.SqlParameter("@FEC_CREACION", tareaObservacion.FEC_CREACION))
db.TAREA_OBSERVACION.Add(tareaObservacion)
Utils.salvarDatos(db)
Utils.ValidaLog(_auditLog, "INSERT TAREA_OBSERVACION", Parameters.ToArray)
Return tareaObservacion
End Function
''' <summary>
''' Obtiene una observacion de una tarea por su ID
''' </summary>
''' <param name="prmIntITareaObservacion">Identificador de la observación</param>
''' <returns>Objeto del tipo Datos.TAREA_OBSERVACION</returns>
Public Function obtenerTareaObservacionPorId(ByVal prmIntITareaObservacion As Int32) As Datos.TAREA_OBSERVACION
Dim tareaObservacion = (From tob In db.TAREA_OBSERVACION
Where tob.COD_ID_TAREA_OBSERVACION = prmIntITareaObservacion
Select tob).FirstOrDefault()
Return tareaObservacion
End Function
End Class
|
Imports System.Windows.Forms
Friend Class DialogOpcions
Private sPiSelectedHost As String = ""
Public tPuConfiguracio As Configuracio
Private bPiInit As Boolean = False
Private Enum eCols
Studio
Cam
Host
IP
SourcePort
TargetPort
Protocol
Total
End Enum
Private Sub MostrarOpcions()
bPiInit = True
Try
Me.CheckBoxHosts.Checked = tPuConfiguracio.UseHosts
With Me.ListView1
.Items.Clear()
For Each CHost As TrackingHost In tPuConfiguracio.Hosts.LlistaHosts
Dim CItem As ListViewItem = .Items.Add(CHost.Studio)
CItem.SubItems.Add(CHost.CamNumber)
If CHost.TrackingType = eTrackingType.UDP_ORAD Then
CItem.SubItems.Add(CHost.Host)
CItem.SubItems.Add(CHost.IP)
CItem.SubItems.Add(CHost.SourcePort)
CItem.SubItems.Add("")
Else
CItem.SubItems.Add("")
CItem.SubItems.Add("")
CItem.SubItems.Add("")
CItem.SubItems.Add(CHost.TargetPort)
End If
CItem.SubItems.Add(CHost.TrackingType.ToString)
Next
End With
Catch ex As Exception
End Try
bPiInit = False
End Sub
Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
Me.DialogResult = System.Windows.Forms.DialogResult.OK
Me.Close()
End Sub
Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.Close()
End Sub
Private Sub AfegirHostToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AfegirHostToolStripMenuItem.Click
Try
Dim dlg As New DialogHost
dlg.CPuHost = Nothing
dlg.ShowDialog(Me)
If dlg.DialogResult = DialogResult.OK Then
tPuConfiguracio.Hosts.LlistaHosts.Add(dlg.CPuHost)
End If
Me.MostrarOpcions()
Catch ex As Exception
End Try
End Sub
Private Sub EliminarHostToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EliminarHostToolStripMenuItem.Click
Try
Dim CHost As TrackingHost
If Me.ListView1.SelectedItems.Count = 1 Then
Dim sHost As String = Me.ListView1.SelectedItems(0).SubItems(eCols.Host).Text
Dim nSourcePort As Integer = CInt("0" & Me.ListView1.SelectedItems(0).SubItems(eCols.SourcePort).Text)
Dim nTargetPort As Integer = CInt("0" & Me.ListView1.SelectedItems(0).SubItems(eCols.TargetPort).Text)
Dim eType As eTrackingType
Select Case Me.ListView1.SelectedItems(0).SubItems(eCols.Protocol).Text
Case eTrackingType.TCP_Client.ToString
eType = eTrackingType.TCP_Client
Case eTrackingType.UDP.ToString
eType = eTrackingType.UDP
Case eTrackingType.UDP_ORAD.ToString
eType = eTrackingType.UDP_ORAD
End Select
CHost = Me.tPuConfiguracio.Hosts.GetHost(sHost, nSourcePort, nTargetPort, eType)
If MsgBox("Estās segur?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
Me.tPuConfiguracio.Hosts.LlistaHosts.Remove(CHost)
End If
End If
Me.MostrarOpcions()
Catch ex As Exception
End Try
End Sub
Private Sub EditarHostToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EditarHostToolStripMenuItem.Click
Try
Dim CHost As TrackingHost
If Me.ListView1.SelectedItems.Count = 1 Then
Dim sHost As String = Me.ListView1.SelectedItems(0).SubItems(eCols.Host).Text
Dim nSourcePort As Integer = CInt("0" & Me.ListView1.SelectedItems(0).SubItems(eCols.SourcePort).Text)
Dim nTargetPort As Integer = CInt("0" & Me.ListView1.SelectedItems(0).SubItems(eCols.TargetPort).Text)
Dim eType As eTrackingType
Select Case Me.ListView1.SelectedItems(0).SubItems(eCols.Protocol).Text
Case eTrackingType.TCP_Client.ToString
eType = eTrackingType.TCP_Client
Case eTrackingType.TCP_Server.ToString
eType = eTrackingType.TCP_Server
Case eTrackingType.UDP.ToString
eType = eTrackingType.UDP
Case eTrackingType.UDP_ORAD.ToString
eType = eTrackingType.UDP_ORAD
End Select
CHost = Me.tPuConfiguracio.Hosts.GetHost(sHost, nSourcePort, nTargetPort, eType)
Dim dlg As New DialogHost
If Not CHost Is Nothing Then
dlg.CPuHost = CHost
dlg.ShowDialog(Me)
If dlg.DialogResult = DialogResult.OK Then
'tPuConfiguracio.Hosts.LlistaHosts.Add(dlg.CPuHost)
End If
End If
End If
Me.MostrarOpcions()
Catch ex As Exception
End Try
End Sub
Private Sub DialogOpcions_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.MostrarOpcions()
End Sub
#Region "Scan ports"
Private WithEvents dlgScan As New DialogScanPorts
Private Sub ButtonScan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonScan.Click
If dlgScan Is Nothing Then
dlgScan = New DialogScanPorts
End If
dlgScan.CPuHosts = tPuConfiguracio.Hosts
dlgScan.Show(Me)
Me.ButtonScan.Enabled = False
End Sub
Private Sub dlgScan_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles dlgScan.FormClosed
Me.ButtonScan.Enabled = True
dlgScan = Nothing
End Sub
Private Sub dlgScan_SelectHost(ByVal siHost As String, ByVal siIP As String, ByVal niPort As Integer) Handles dlgScan.SelectHost
Try
Dim CHost As TrackingHost
CHost = Me.tPuConfiguracio.Hosts.GetHost(siHost, niPort, 0, eTrackingType.UDP_ORAD)
If CHost Is Nothing Then
CHost = New TrackingHost()
CHost.Host = siHost
CHost.IP = siIP
CHost.SourcePort = niPort
CHost.TargetPort = 0
CHost.TrackingType = eTrackingType.UDP_ORAD
Me.tPuConfiguracio.Hosts.LlistaHosts.Add(CHost)
Me.MostrarOpcions()
End If
Catch ex As Exception
End Try
End Sub
#End Region
End Class
|
Imports System.Collections.Generic
Imports System.Runtime.Serialization
Namespace Route4MeSDK.DataTypes
<DataContract>
Public NotInheritable Class AddressGeocoded
<DataMember(Name:="address", EmitDefaultValue:=False)>
Public Property geocodedAddress As Address
<DataMember(Name:="member_id", EmitDefaultValue:=False)>
Public Property MemberId As Integer
<DataMember(Name:="member_type_id", EmitDefaultValue:=False)>
Public Property memberTypeID As Integer
<DataMember(Name:="userLat")>
Public Property userLatitude As Double?
<DataMember(Name:="userLng")>
Public Property userLongitude As Double?
<DataMember(Name:="intUserIP", EmitDefaultValue:=False)>
Public Property intUserIP As UInteger
<DataMember(Name:="strGeocodingMethod", EmitDefaultValue:=False)>
Public Property strGeocodingMethod As String
<DataMember(Name:="getCurbside", EmitDefaultValue:=False)>
Public Property getCurbside As Boolean
<DataMember(Name:="priority", EmitDefaultValue:=False)>
Public Property Priority As Integer
End Class
End Namespace
|
'=============================================================================
' Copyright © 2011 Point Grey Research, Inc. All Rights Reserved.
'
' This software is the confidential and proprietary information of Point
' Grey Research, Inc. ("Confidential Information"). You shall not
' disclose such Confidential Information and shall use it only in
' accordance with the terms of the license agreement you entered into
' with PGR.
'
' PGR MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
' SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
' IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
' PURPOSE, OR NON-INFRINGEMENT. PGR SHALL NOT BE LIABLE FOR ANY DAMAGES
' SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
' THIS SOFTWARE OR ITS DERIVATIVES.
'=============================================================================\
Imports System
Imports System.Text
Imports System.Drawing
Imports System.IO
Imports FlyCapture2Managed
Namespace GigEGrabEx_VB
Class Program
Shared Sub PrintBuildInfo()
Dim version As FC2Version = ManagedUtilities.libraryVersion
Dim newStr As StringBuilder = New StringBuilder()
newStr.AppendFormat("FlyCapture2 library version: {0}.{1}.{2}.{3}" & vbNewLine, _
version.major, version.minor, version.type, version.build)
Console.WriteLine(newStr)
End Sub
Shared Sub PrintCameraInfo(ByVal camInfo As CameraInfo)
Dim newStr As StringBuilder = New StringBuilder()
newStr.Append(vbNewLine & "*** CAMERA INFORMATION ***" & vbNewLine)
newStr.AppendFormat("Serial number - {0}" & vbNewLine, camInfo.serialNumber)
newStr.AppendFormat("Camera model - {0}" & vbNewLine, camInfo.modelName)
newStr.AppendFormat("Camera vendor - {0}" & vbNewLine, camInfo.vendorName)
newStr.AppendFormat("Sensor - {0}" & vbNewLine, camInfo.sensorInfo)
newStr.AppendFormat("Resolution - {0}" & vbNewLine, camInfo.sensorResolution)
newStr.AppendFormat("Firmware version - {0}" & vbNewLine, camInfo.firmwareVersion)
newStr.AppendFormat("Firmware build time - {0}" & vbNewLine, camInfo.firmwareBuildTime)
newStr.AppendFormat("GigE version - {0}.{1}" & vbNewLine, camInfo.gigEMajorVersion, camInfo.gigEMinorVersion)
newStr.AppendFormat("User defined name - {0}" & vbNewLine, camInfo.userDefinedName)
newStr.AppendFormat("XML URL 1 - {0}" & vbNewLine, camInfo.xmlURL1)
newStr.AppendFormat("XML URL 2 - {0}" & vbNewLine, camInfo.xmlURL2)
newStr.AppendFormat("MAC address - {0}" & vbNewLine, camInfo.macAddress.ToString())
newStr.AppendFormat("IP address - {0}" & vbNewLine, camInfo.ipAddress.ToString())
newStr.AppendFormat("Subnet mask - {0}" & vbNewLine, camInfo.subnetMask.ToString())
newStr.AppendFormat("Default gateway - {0}" & vbNewLine, camInfo.defaultGateway.ToString())
Console.WriteLine(newStr)
End Sub
Shared Sub PrintStreamChannelInfo(ByVal streamChannelInfo As GigEStreamChannel)
Dim newStr As StringBuilder = New StringBuilder()
newStr.Append(vbNewLine & "*** STREAM CHANNEL INFORMATION ***" & vbNewLine)
newStr.AppendFormat("Network interface - {0}" & vbNewLine, streamChannelInfo.networkInterfaceIndex)
newStr.AppendFormat("Host post - {0}" & vbNewLine, streamChannelInfo.hostPost)
newStr.AppendFormat("Do not fragment bit - {0}" & vbNewLine, IIf(streamChannelInfo.doNotFragment, "Enabled", "Disabled"))
newStr.AppendFormat("Packet size - {0}" & vbNewLine, streamChannelInfo.packetSize)
newStr.AppendFormat("Inter packet delay - {0}" & vbNewLine, streamChannelInfo.interPacketDelay)
newStr.AppendFormat("Destination IP address - {0}" & vbNewLine, streamChannelInfo.destinationIpAddress)
newStr.AppendFormat("Source port (on camera) - {0}" & vbNewLine & vbNewLine, streamChannelInfo.sourcePort)
Console.WriteLine(newStr)
End Sub
Sub RunSingleCamera(ByVal guid As ManagedPGRGuid)
Const k_numImages As Integer = 10
Dim cam As ManagedGigECamera = New ManagedGigECamera()
' Connect to a camera
cam.Connect(guid)
' Get the camera information
Dim camInfo As CameraInfo = cam.GetCameraInfo()
PrintCameraInfo(camInfo)
Dim numStreamChannels As UInteger = cam.GetNumStreamChannels()
For i As UInteger = 0 To (numStreamChannels - 1)
PrintStreamChannelInfo(cam.GetGigEStreamChannelInfo(i))
Next
Dim imageSettingsInfo As GigEImageSettingsInfo = cam.GetGigEImageSettingsInfo()
Dim imageSettings As GigEImageSettings = New GigEImageSettings()
imageSettings.offsetX = 0
imageSettings.offsetY = 0
imageSettings.height = imageSettingsInfo.maxHeight
imageSettings.width = imageSettingsInfo.maxWidth
imageSettings.pixelFormat = PixelFormat.PixelFormatMono8
cam.SetGigEImageSettings(imageSettings)
' Get embedded image info from camera
Dim embeddedInfo As EmbeddedImageInfo = cam.GetEmbeddedImageInfo()
' Enable timestamp collection
If (embeddedInfo.timestamp.available) Then
embeddedInfo.timestamp.onOff = True
End If
' Set embedded image info to camera
cam.SetEmbeddedImageInfo(embeddedInfo)
' Start capturing images
cam.StartCapture()
Dim rawImage As ManagedImage = New ManagedImage()
For imageCnt As Integer = 0 To (k_numImages - 1)
' Retrieve an image
cam.RetrieveBuffer(rawImage)
' Get the timestamp
Dim timeStamp As TimeStamp = rawImage.timeStamp
Console.WriteLine( _
"Grabbed image {0} - {1} {2} {3}", _
imageCnt, _
timeStamp.cycleSeconds, _
timeStamp.cycleCount, _
timeStamp.cycleOffset)
' Create a converted image
Dim convertedImage As ManagedImage = New ManagedImage()
' Convert the raw image
rawImage.Convert(PixelFormat.PixelFormatBgr, convertedImage)
' Create a unique filename
Dim filename As String = String.Format( _
"GigEGrabEx_CSharp-{0}-{1}.bmp", _
camInfo.serialNumber, _
imageCnt)
' Get the Bitmap object. Bitmaps are only valid if the
' pixel format of the ManagedImage is RGB or RGBU.
Dim bitmap As Bitmap = convertedImage.bitmap
' Save the image
bitmap.Save(filename)
Next
' Stop capturing images
cam.StopCapture()
' Disconnect the camera
cam.Disconnect()
End Sub
Shared Sub Main()
PrintBuildInfo()
Dim program As Program = New Program()
' Since this application saves images in the current folder
' we must ensure that we have permission to write to this folder.
' If we do not have permission, fail right away.
Dim fileStream As FileStream
Try
fileStream = New FileStream("test.txt", FileMode.Create)
fileStream.Close()
File.Delete("test.txt")
Catch ex As Exception
Console.WriteLine("Failed to create file in current folder. Please check permissions." & vbNewLine)
Return
End Try
Dim busMgr As ManagedBusManager = New ManagedBusManager()
Dim camInfos As CameraInfo() = ManagedBusManager.DiscoverGigECameras()
Console.WriteLine("Number of cameras discovered: {0}", camInfos.Length)
For Each camInfo As CameraInfo In camInfos
PrintCameraInfo(camInfo)
Next
Dim numCameras As UInteger = busMgr.GetNumOfCameras()
Console.WriteLine("Number of cameras enumerated: {0}", numCameras)
For i As UInteger = 0 To (numCameras - 1)
Dim guid As ManagedPGRGuid = busMgr.GetCameraFromIndex(i)
If (busMgr.GetInterfaceTypeFromGuid(guid) <> InterfaceType.GigE) Then
Continue For
End If
Try
program.RunSingleCamera(guid)
Catch ex As FC2Exception
Console.WriteLine( _
String.Format( _
"Error running camera {0}. Error: {1}", _
i, ex.Message))
End Try
Next
Console.WriteLine("Done! Press any key to exit...")
Console.ReadKey()
End Sub
End Class
End Namespace
|
Imports Automation
Imports Automation.Components.CommandStateMachine
Imports Automation.Components.Services
''' <summary>
''' Availiable for clamp-on-fly , static clamp , clamp 4 side
''' </summary>
''' <remarks></remarks>
Public Class clampModule
Inherits systemControlPrototype
Implements IFinishableStation
Implements IModuleSingle
Dim _triggerClampMethod As triggerClampMethodEnum = triggerClampMethodEnum.METHOD_BY_SENSOR
Dim _motionMethod As motorControl.motorCommandEnum = motorControl.motorCommandEnum.GO_POSITION_COMBINED
Dim _actuatorComponent As actuatorComponentEnum = actuatorComponentEnum.Motor
''' <summary>
''' Used to synchronize with conveyor (optional)
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property TargetPositionInfo As Func(Of shiftDataPackBase) Implements IModuleSingle.TargetPositionInfo
Public Property FinishableFlags As New flagController(Of IFinishableStation.controlFlags) Implements IFinishableStation.FinishableFlags
Public Property UpstreamStations As List(Of IFinishableStation) Implements IFinishableStation.UpstreamStations
#Region "control members"
Public motorClamp As motorControl = New motorControl()
Public motorConveyorReference As motorControl = Nothing
Public clampCylinder As cylinderGeneric = New cylinderGeneric
''' <summary>
''' Used to prevent interfered before motion start
''' </summary>
''' <remarks></remarks>
Public interfereSensors As List(Of sensorControl) = New List(Of sensorControl)
Public clampTriggerSensor As sensorControl = New sensorControl With {.InputBit = 0}
#End Region
#Region "External Data declare"
Public motorPointClamp As cMotorPoint
Public motorPointRelease As cMotorPoint
Private isTriggered As Func(Of Boolean) = AddressOf isTriggerSensorDetected '查看觸發條件是否成立
Private isTriggerReseted As Func(Of Boolean) = Function() (True)
Dim motionSequenceState As Integer = 0
Dim motionSequence As stateFunction = AddressOf motionMethodCombined
Dim homeSequence As stateFunction = AddressOf homeMethodMotor
Dim alarmPackHomingSensorCovered As alarmContentSensor = New alarmContentSensor With {.Sender = Me,
.PossibleResponse = alarmContextBase.responseWays.RETRY,
.Reason = alarmContentSensor.alarmReasonSensor.SHOULD_BE_OFF}
''' <summary>
'''
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property ConveyorTriggerDistanceInUnit As Double
Get
If motorConveyorReference Is Nothing Then
Return 0
End If
Return motorConveyorReference.pulse2Unit(ConveyorTriggerDistance)
End Get
Set(value As Double)
If motorConveyorReference IsNot Nothing Then
ConveyorTriggerDistance = motorConveyorReference.unit2Pulse(value)
End If
End Set
End Property
Public Property ConveyorTriggerDistance As Double = 0 'record conveyor trigger position
''' <summary>
'''
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Property TriggerClampMethod As triggerClampMethodEnum
Get
Return _triggerClampMethod
End Get
Set(value As triggerClampMethodEnum)
_triggerClampMethod = value
Select Case value
Case triggerClampMethodEnum.METHOD_BY_SENSOR
isTriggered = AddressOf isTriggerSensorDetected
isTriggerReseted = Function() (True)
Case triggerClampMethodEnum.METHOD_BY_BELT_POSITION
isTriggered = AddressOf isTriggerPositionDetected
isTriggerReseted = AddressOf isTriggerPositionReseted
Case triggerClampMethodEnum.METHOD_BY_MODULE_ACTION
isTriggered = AddressOf isTriggerModuleActionRised
isTriggerReseted = Function() (True)
End Select
End Set
End Property
''' <summary>
'''
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Property MotionMethod As motorControl.motorCommandEnum
Get
Return _motionMethod
End Get
Set(value As motorControl.motorCommandEnum)
_motionMethod = value
Select Case value
Case motorControl.motorCommandEnum.GO_POSITION_COMBINED
motionSequence = AddressOf motionMethodCombined
Case motorControl.motorCommandEnum.GO_POSITION
motionSequence = AddressOf motionMethodSoftSerial
Case Else
MsgBox(Me.DeviceName & " motion method setting error!")
End Select
End Set
End Property
''' <summary>
''' Clamp actuator maybe Motor or Cylinder
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Property ActuatorComponent As actuatorComponentEnum
Get
Return _actuatorComponent
End Get
Set(value As actuatorComponentEnum)
_actuatorComponent = value
Select Case value
Case actuatorComponentEnum.Motor
homeSequence = AddressOf homeMethodMotor
Case actuatorComponentEnum.Cylinder
homeSequence = AddressOf homeMethodCylinder
motionSequence = AddressOf motionMethodCylinder
End Select
End Set
End Property
#End Region
Enum triggerClampMethodEnum
METHOD_BY_BELT_POSITION
METHOD_BY_SENSOR
METHOD_BY_MODULE_ACTION 'Hsien , integrate with normal clamp , 2016.08.24
End Enum
Enum actuatorComponentEnum
Motor
Cylinder
End Enum
Sub alarmOccursHandler() Handles CentralAlarmObject.alarmOccured, PauseBlock.InterceptedEvent
If (MainState = systemStatesEnum.IGNITE) AndAlso _actuatorComponent = actuatorComponentEnum.Motor Then
motorClamp.drive(motorControl.motorCommandEnum.MOTION_PAUSE)
End If
End Sub
Sub alarmReleaseHandler() Handles CentralAlarmObject.alarmReleased, PauseBlock.UninterceptedEvent
If (MainState = systemStatesEnum.IGNITE) AndAlso _actuatorComponent = actuatorComponentEnum.Motor Then
motorClamp.drive(motorControl.motorCommandEnum.MOTION_RESUME)
End If
End Sub
Protected Function stateIgnite() As Integer
Select Case systemSubState
Case 0
If FinishableFlags.viewFlag(IFinishableStation.controlFlags.COMMAND_IGNITE) Then
systemSubState = 10
End If
Case 10
If interfereSensors.Count > 0 AndAlso
interfereSensors.Exists(Function(sensor As sensorControl) sensor.IsSensorCovered) Then
'had been interfered , error
With alarmPackHomingSensorCovered '只有重試
.Inputs = interfereSensors.Find(Function(sensor As sensorControl) sensor.IsSensorCovered).InputBit
End With
CentralAlarmObject.raisingAlarm(alarmPackHomingSensorCovered) 'Hsien , 2015.06.15
Else
systemSubState = 20
End If
Case 20
If homeSequence(motionSequenceState) Then
motionSequenceState = 0
systemSubState = 500
End If
Case 500 '設定連續動作
FinishableFlags.writeFlag(IFinishableStation.controlFlags.COMMAND_IGNITE, False)
systemMainState = systemStatesEnum.EXECUTE
End Select
Return 0
End Function
Protected Function stateExecute() As Integer
Select Case systemSubState
Case 0
If isTriggered.Invoke Then '偵測上緣觸發
systemSubState = 10
Else
'---------------------------------------------------------------
'not invoke release conveyor
'---------------------------------------------------------------
TargetPositionInfo.Invoke.ModuleAction.resetFlag(interlockedFlag.POSITION_OCCUPIED)
End If
Case 10
If motionSequence(motionSequenceState) Then
motionSequenceState = 0 ' reset state
systemSubState = 20
Else
'-----------------
' Motion is executing
'-----------------
End If
Case 20
'synchron after motion done , ensure all motion in regular sequence , Hsien , 2016.02.29
TargetPositionInfo.Invoke.ModuleAction.resetFlag(interlockedFlag.POSITION_OCCUPIED)
If (isTriggerReseted.Invoke) Then
systemSubState = 0
Else
'----------------
' Not reseted yet
'----------------
End If
End Select
Return 0
End Function
Function initMappingAndSetup()
systemMainStateFunctions(systemStatesEnum.IGNITE) = AddressOf stateIgnite
systemMainStateFunctions(systemStatesEnum.EXECUTE) = AddressOf stateExecute
systemMainState = systemStatesEnum.IGNITE
actionComponents.Remove(motorConveyorReference) 'Hsien , 2016.02.17 , do not inlcude the conveyor
Return 0
End Function
Public Sub New()
Me.initialize = [Delegate].Combine(Me.initialize,
New Func(Of Integer)(AddressOf Me.initMappingAndSetup),
New Func(Of Integer)(AddressOf Me.initEnableAllDrives))
End Sub
Protected Overrides Function process() As Integer
'Hsien , prevent interrupted by alarm , 2015.07.08
'----------------------------
'standard system control flow
'----------------------------
drivesRunningInvoke()
'on the executing mode ,wont be affectted by alarm , Hsien , 2015.07.08
If ((CentralAlarmObject.IsAlarmed AndAlso MainState = systemStatesEnum.IGNITE) OrElse
PauseBlock.IsPaused And systemSubState = 0) Then
'do not pause during moving , Hsien , 2015.09.07
Return 0
End If
stateControl()
processProgress()
Return 0
End Function
#Region "Trigger methods"
Function isTriggerSensorDetected() As Boolean
Return clampTriggerSensor.RisingEdge.IsDetected
End Function
Function isTriggerPositionDetected() As Boolean
Return motorConveyorReference.CommandPosition >= ConveyorTriggerDistance
End Function
Function isTriggerPositionReseted() As Boolean
Return motorConveyorReference.CommandPosition < ConveyorTriggerDistance
End Function
Function isTriggerModuleActionRised() As Boolean
Return TargetPositionInfo.Invoke.ModuleAction.viewFlag(interlockedFlag.POSITION_OCCUPIED) And
TargetPositionInfo.Invoke.IsPositionOccupied
End Function
#End Region
#Region "motion sequences"
Function motionMethodCombined(ByRef state As Integer) As Boolean
Return motorClamp.drive(motorControl.motorCommandEnum.GO_POSITION_COMBINED) =
motorControl.statusEnum.EXECUTION_END
End Function
Function motionMethodSoftSerial(ByRef state As Integer) As Boolean
Select Case state
Case 0
If motorClamp.drive(motorControl.motorCommandEnum.GO_POSITION, motorPointClamp) =
motorControl.statusEnum.EXECUTION_END Then
state = 10
End If
Case 10
If motorClamp.drive(motorControl.motorCommandEnum.GO_POSITION, motorPointRelease) =
motorControl.statusEnum.EXECUTION_END Then
Return True
End If
End Select
Return False
End Function
Function motionMethodCylinder(ByRef state As Integer) As Boolean
Select Case state
Case 0
If clampCylinder.drive(cylinderGeneric.cylinderCommands.GO_B_END) = IDrivable.endStatus.EXECUTION_END Then
state = 10
End If
Case 10
If clampCylinder.drive(cylinderGeneric.cylinderCommands.GO_A_END) = IDrivable.endStatus.EXECUTION_END Then
Return True
End If
End Select
Return False
End Function
Function homeMethodMotor(ByRef state As Integer) As Boolean
Select Case state
Case 0
If motorClamp.drive(motorControl.motorCommandEnum.GO_HOME) = motorControl.statusEnum.EXECUTION_END Then
state = 10
End If
Case 10
If motorClamp.drive(motorControl.motorCommandEnum.GO_POSITION, motorPointRelease) = motorControl.statusEnum.EXECUTION_END Then
state = 20
End If
Case 20 '設定連續動作
motorClamp.PointTable.Clear()
motorClamp.PointTable.AddRange({motorPointClamp, motorPointRelease})
Return True
End Select
Return False
End Function
Function homeMethodCylinder(ByRef state As Integer) As Boolean
Return clampCylinder.drive(cylinderGeneric.cylinderCommands.GO_A_END) =
IDrivable.endStatus.EXECUTION_END
End Function
#End Region
End Class
|
Imports DevExpress.XtraPrinting.BarCode.Native
Imports System
Imports System.Collections.Generic
Imports System.Linq
Namespace EditorsDemo
Public Class LinearBarCodeViewModel
Public Sub New()
Me.BarCodeSymbology = BarCodeSymbology.Code128
Me.Text = "101"
Me.BarCodeModule = 3
Me.AutoModule = True
Me.ShowText = True
End Sub
Public Overridable Property ShowText() As Boolean
Public Overridable Property AutoModule() As Boolean
Public Overridable Property Text() As String
Public Overridable Property BarCodeModule() As Double
Public Overridable Property BarCodeSymbology() As BarCodeSymbology
Public ReadOnly Property BarCodeTypes() As IEnumerable(Of BarCodeSymbology)
Get
Return GetBarCodeTypes()
End Get
End Property
Protected Overridable Function GetBarCodeTypes() As IEnumerable(Of BarCodeSymbology)
Return System.Enum.GetValues(GetType(BarCodeSymbology)).Cast(Of BarCodeSymbology)().TakeWhile(Function(bcs) bcs <> BarCodeSymbology.QRCode AndAlso bcs <> BarCodeSymbology.DataMatrix AndAlso bcs <> BarCodeSymbology.DataMatrixGS1 AndAlso bcs <> BarCodeSymbology.PDF417)
End Function
End Class
Public Class BarCode2DViewModel
Inherits LinearBarCodeViewModel
Public Sub New()
Me.BarCodeSymbology = BarCodeSymbology.QRCode
End Sub
Protected Overrides Function GetBarCodeTypes() As IEnumerable(Of BarCodeSymbology)
Return New BarCodeSymbology() { BarCodeSymbology.QRCode, BarCodeSymbology.DataMatrix, BarCodeSymbology.DataMatrixGS1, BarCodeSymbology.PDF417 }
End Function
End Class
End Namespace
|
Imports Microsoft.VisualBasic.ApplicationServices
Public Class Info
Private Sub Start_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Left = Me.Owner.Left + Me.Owner.Width / 2 - Me.Width / 2
Me.Top = Me.Owner.Top + Me.Owner.Height / 2 - Me.Height / 2
If Me.Top < 0 Then Me.Top = 0
If Me.Left < 0 Then Me.Left = 0
Me.Text = AppTitleLong & " info"
lblDisclaimer.Text = "Working with this version of " & Application.ProductName & " should be possible without problems, however, some smaller errors could occur. We recommend you to save your database whenever you've added some vocabulary and non change database manually. This software is distributed ""as is"", we are neither responisble for anything that happens using this software nor responsible for the correct function of this piece of software."
lblCopyrightOld.Text = "based on Vokabeltrainer, © 1995-2007"
lblCopyright.Text = "© 1995-2020"
lblCopyrightName.Text = "Jan-Philipp Kappmeier"
lblProductName.Text = Application.ProductName
lblVersion.Text = "Version: " & Application.ProductVersion
Dim db As IDataBaseOperation = New SQLiteDataBaseOperation()
db.Open(DBPathLoc)
Dim dbManagement As New ManagementDao(db)
lblDBVersion.Text = "DB-Version: " & dbManagement.LatestVersion.Major & "." & dbManagement.LatestVersion.Minor
End Sub
Public Overrides Sub LocalizationChanged()
End Sub
Private Sub chkGermanText_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkGermanText.CheckedChanged
If chkGermanText.Checked = True Then
lblDisclaimer.Text = "Das Arbeiten mit dieser Version von " & Application.ProductName & " sollte problemlos möglich sein, dennoch können noch kleinere Fehler auftreten. Wir emfehlen nach jeder Vokabeleingabe die Datenbank zu sichern und keine Änderungen an der Datenbank manuell durchzufüren. Diese Software wird vertrieben ""wie sie ist"", wir sind nicht verantwortlich für das, was durch Benutzung dieser Software geschieht, noch kann die Funktionsfähigkeit dieser Software garantiert werden."
lblCopyrightOld.Text = "basiert auf Vokabeltrainer, © 1995-2007"
Else
lblDisclaimer.Text = "Working with this version of " & Application.ProductName & " should be possible without problems, however, some smaller errors could occur. We recommend to save your database whenever you've added some vocabulary and to not change the database manually. This software is distributed ""as is"", we are neither responisble for anything that happens using this software nor responsible for the correct function of this piece of software."
lblCopyrightOld.Text = "based on Vokabeltrainer, © 1995-2007"
End If
End Sub
End Class |
Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Linq
Imports System.Windows.Forms
Imports Syncfusion.Windows.Forms.Tools
Imports System.Data.SqlServerCe
Namespace WF_TreeNavigatorDirectory
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
dataBaseView = GetOrderDetials()
End Sub
Private dataBaseView As DataView
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles button1.Click
Me.treeNavigator1.Visible = True
FillItems(Me.treeNavigator1)
End Sub
Private Sub FillItems(ByVal tree As TreeNavigator)
For Each col As DataColumn In dataBaseView.Table.Columns
Me.treeNavigator1.Items.Add(New TreeMenuItem() With {.Text = col.ColumnName})
Next col
For Each x As DataRow In dataBaseView.Table.Rows
For Each y As TreeMenuItem In Me.treeNavigator1.Items
If dataBaseView.Table.Columns.Contains(y.Text) Then
y.Items.Add(New TreeMenuItem() With {.Text = x(dataBaseView.Table.Columns(y.Text)).ToString()})
End If
Next y
Next x
End Sub
Private Shared Function GetOrderDetials() As DataView
Try
Dim ds As New DataSet()
Using con As New SqlCeConnection("DataSource=Data\Northwind.sdf")
con.Open()
Dim cmd As New SqlCeCommand("SELECT Top(20) [Order ID], [Product ID], [ColumnName], [Unit Price], Quantity" & ControlChars.CrLf & " FROM [Order Details] ", con)
Dim da As New SqlCeDataAdapter(cmd)
da.Fill(ds)
'Creation of DataView
Dim dataView As New DataView(ds.Tables(0), "[Unit Price] >= 20", "[Order ID]", DataViewRowState.CurrentRows)
Return dataView
End Using
Catch e As Exception
MessageBox.Show("Exception in connection: " & Constants.vbTab + e.Message)
Return Nothing
End Try
End Function
End Class
End Namespace
|
Imports System.Windows.Forms
Module TemplateMethod
Sub Main()
Dim objDebitsProcessor As New DebitsProcessor()
Dim objCreditsProcessor As New CreditsProcessor()
Console.WriteLine("Increment the Training Expense account by $10.50...")
objDebitsProcessor.SetAmount(10.5D)
objDebitsProcessor.Process("Training Expense")
Console.WriteLine("Decrement the Accounts Payable by $10.50...")
objCreditsProcessor.SetAmount(10.5D)
objCreditsProcessor.Process("Accounts Payable")
MessageBox.Show("Click OK to end")
End Sub
Public MustInherit Class AccountsProcessor
Protected m_Amount As Integer
Public Sub Process(ByVal Account As String)
Console.WriteLine(Account & " adjusted by " & m_Amount)
End Sub
Public MustOverride Sub SetAmount(ByVal Amount As Double)
End Class
Public Class DebitsProcessor : Inherits AccountsProcessor
Public Overrides Sub SetAmount(ByVal Amount As Double)
m_Amount = Math.Round(Amount, 2) * 100
End Sub
End Class
Public Class CreditsProcessor : Inherits AccountsProcessor
Public Overrides Sub SetAmount(ByVal Amount As Double)
m_Amount = -1 * Math.Round(Amount, 2) * 100
End Sub
End Class
End Module
|
' Instat-R
' Copyright (C) 2015
'
' 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 k
' along with this program. If not, see <http://www.gnu.org/licenses/>.
Imports instat.Translations
Public Class dlgFourVariableModelling
Public bFirstLoad As Boolean = True
Public clsRCIFunction, clsRConvert As New RFunction
Public clsRSingleModelFunction As RFunction
Dim clsModel, clsModel1, clsModel2 As New ROperator
Dim operation As String
Private Sub dlgFourVariableModelling_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'UcrInputComboBox1.SetItemsTypeAsModels()
If bFirstLoad Then
InitialiseDialog()
SetDefaults()
bFirstLoad = False
Else
ReopenDialog()
End If
autoTranslate(Me)
End Sub
Private Sub InitialiseDialog()
ucrBaseFourVariableModelling.clsRsyntax.iCallType = 2
clsModel.SetOperation("~")
ucrBaseFourVariableModelling.clsRsyntax.SetFunction("")
ucrResponse.Selector = ucrSelectorFourVariableModelling
ucrFirstExplanatory.Selector = ucrSelectorFourVariableModelling
ucrSecondExplanatoryVariable.Selector = ucrSelectorFourVariableModelling
ucrThirdExplanatoryVariable.Selector = ucrSelectorFourVariableModelling
ucrBaseFourVariableModelling.iHelpTopicID = 176 'this is not the correct ID
ucrFamily.SetGLMDistributions()
ucrModelName.SetDataFrameSelector(ucrSelectorFourVariableModelling.ucrAvailableDataFrames)
ucrModelName.SetPrefix("reg")
ucrModelName.SetItemsTypeAsModels()
ucrModelName.SetDefaultTypeAsModel()
ucrModelName.SetValidationTypeAsRVariable()
sdgSimpleRegOptions.SetRModelFunction(ucrBaseFourVariableModelling.clsRsyntax.clsBaseFunction)
ucrModelPreview.IsReadOnly = True
sdgSimpleRegOptions.SetRDataFrame(ucrSelectorFourVariableModelling.ucrAvailableDataFrames)
sdgSimpleRegOptions.SetRYVariable(ucrResponse)
sdgSimpleRegOptions.SetRXVariable(ucrFirstExplanatory)
sdgVariableTransformations.SetRYVariable(ucrResponse)
sdgVariableTransformations.SetRModelOperator(clsModel1)
sdgModelOptions.SetRCIFunction(clsRCIFunction)
sdgVariableTransformations.SetRCIFunction(clsRCIFunction)
AssignModelName()
End Sub
Private Sub ReopenDialog()
End Sub
Private Sub SetDefaults()
ucrSelectorFourVariableModelling.Reset()
ucrResponse.SetMeAsReceiver()
ucrSelectorFourVariableModelling.Focus()
cboModelOperators1.SelectedItem = "+"
cboModelOperators2.SelectedItem = "|"
'operation = "+"
chkSaveModel.Checked = True
ucrModelName.Visible = True
chkConvertToVariate.Checked = False
chkConvertToVariate.Visible = False
chkFirstFunction.Checked = False
chkFirstFunction.Visible = False
ucrModelName.SetName("reg")
sdgSimpleRegOptions.SetDefaults()
sdgModelOptions.SetDefaults()
ResponseConvert()
TestOKEnabled()
End Sub
Public Sub TestOKEnabled()
If (Not ucrResponse.IsEmpty()) And (Not ucrFirstExplanatory.IsEmpty()) And (Not ucrSecondExplanatoryVariable.IsEmpty()) And (Not ucrThirdExplanatoryVariable.IsEmpty()) And (operation <> "") Then
clsModel2.bBrackets = False
clsModel1.SetParameter(False, strValue:="(" & clsModel2.ToScript.ToString & ")")
clsModel1.SetOperation(operation)
clsModel1.bBrackets = False
clsModel.SetParameter(False, clsOp:=clsModel1)
ucrBaseFourVariableModelling.clsRsyntax.AddParameter("formula", clsROperatorParameter:=clsModel)
ucrBaseFourVariableModelling.OKEnabled(True)
ucrModelPreview.SetName(clsModel.ToScript)
Else
ucrBaseFourVariableModelling.OKEnabled(False)
End If
End Sub
Private Sub ucrSelectorThreeVariableModelling_DataFrameChanged() Handles ucrSelectorFourVariableModelling.DataFrameChanged
ucrBaseFourVariableModelling.clsRsyntax.AddParameter("data", clsRFunctionParameter:=ucrSelectorFourVariableModelling.ucrAvailableDataFrames.clsCurrDataFrame)
AssignModelName()
End Sub
Public Sub ResponseConvert()
If Not ucrResponse.IsEmpty Then
ucrFamily.RecieverDatatype(ucrSelectorFourVariableModelling.ucrAvailableDataFrames.cboAvailableDataFrames.Text, ucrResponse.GetVariableNames(bWithQuotes:=False))
If ucrFamily.strDataType = "numeric" Then
chkConvertToVariate.Checked = False
chkConvertToVariate.Visible = False
Else
chkConvertToVariate.Visible = True
End If
If chkConvertToVariate.Checked Then
clsRConvert.SetRCommand("as.numeric")
clsRConvert.AddParameter("x", ucrResponse.GetVariableNames(bWithQuotes:=False))
clsModel.SetParameter(True, clsRFunc:=clsRConvert)
ucrFamily.RecieverDatatype("numeric")
Else
clsModel.SetParameter(True, strValue:=ucrResponse.GetVariableNames(bWithQuotes:=False))
ucrFamily.RecieverDatatype(ucrSelectorFourVariableModelling.ucrAvailableDataFrames.cboAvailableDataFrames.Text, ucrResponse.GetVariableNames(bWithQuotes:=False))
End If
sdgModelOptions.ucrFamily.RecieverDatatype(ucrFamily.strDataType)
End If
If ucrFamily.lstCurrentDistributions.Count = 0 Or ucrResponse.IsEmpty() Then
ucrFamily.Enabled = False
ucrFamily.cboDistributions.Text = ""
cmdModelOptions.Enabled = False
Else
ucrFamily.Enabled = True
cmdModelOptions.Enabled = True
End If
End Sub
Private Sub ucrResponse_SelectionChanged() Handles ucrResponse.SelectionChanged
ResponseConvert()
TestOKEnabled()
End Sub
Private Sub ucrFirstExplanatory_SelectionChanged() Handles ucrFirstExplanatory.SelectionChanged
ExplanatoryFunctionSelect(ucrFirstExplanatory)
TestOKEnabled()
End Sub
Private Sub chkConvertToVariate_CheckedChanged(sender As Object, e As EventArgs) Handles chkConvertToVariate.CheckedChanged
ResponseConvert()
TestOKEnabled()
End Sub
Private Sub ExplanatoryFunctionSelect(currentReceiver As ucrReceiverSingle)
Dim strExplanatoryType As String
If Not currentReceiver.IsEmpty Then
strExplanatoryType = frmMain.clsRLink.GetDataType(ucrSelectorFourVariableModelling.ucrAvailableDataFrames.cboAvailableDataFrames.Text, currentReceiver.GetVariableNames(bWithQuotes:=False))
If strExplanatoryType = "numeric" Or strExplanatoryType = "positive integer" Or strExplanatoryType = "integer" Then
chkFirstFunction.Visible = True
Else
chkFirstFunction.Checked = False
chkFirstFunction.Visible = False
End If
If currentReceiver.Name = "ucrFirstExplanatory" Then
sdgVariableTransformations.SetRXVariable(ucrFirstExplanatory)
If chkFirstFunction.Checked Then
sdgVariableTransformations.ModelFunction(True)
Else
sdgVariableTransformations.rdoIdentity.Checked = True
clsModel1.SetParameter(True, strValue:=currentReceiver.GetVariableNames(bWithQuotes:=False))
End If
End If
End If
'ucrModelPreview.SetName(clsModel.ToScript)
End Sub
Private Sub ucrFirstRandomEffect_SelectionChanged() Handles ucrSecondExplanatoryVariable.SelectionChanged
clsModel2.SetParameter(True, strValue:=ucrSecondExplanatoryVariable.GetVariableNames(bWithQuotes:=False))
TestOKEnabled()
End Sub
Private Sub ucrSecondRandomEffect_SelectionChanged() Handles ucrThirdExplanatoryVariable.SelectionChanged
clsModel2.SetParameter(False, strValue:=ucrThirdExplanatoryVariable.GetVariableNames(bWithQuotes:=False))
TestOKEnabled()
End Sub
Private Sub ucrBaseFourVariableModelling_ClickReset(sender As Object, e As EventArgs) Handles ucrBaseFourVariableModelling.ClickReset
SetDefaults()
End Sub
Private Sub ucrModelName_NameChanged() Handles ucrModelName.NameChanged
AssignModelName()
TestOKEnabled()
End Sub
Private Sub ucrBaseFourVariableModelling_ClickOk(sender As Object, e As EventArgs) Handles ucrBaseFourVariableModelling.ClickOk
sdgSimpleRegOptions.RegOptions()
End Sub
Private Sub cmdDisplayOptions_Click(sender As Object, e As EventArgs) Handles cmdDisplayOptions.Click
sdgSimpleRegOptions.ShowDialog()
End Sub
'Private Sub cmdParallelLines_Click(sender As Object, e As EventArgs) Handles cmdParallelLines.Click
' operation = "+"
' TestOKEnabled()
'End Sub
'Private Sub cmdConditional_Click(sender As Object, e As EventArgs) Handles cmdConditional.Click
' operation = ":"
' TestOKEnabled()
'End Sub
'Private Sub cmdJointLines_Click(sender As Object, e As EventArgs) Handles cmdJointLines.Click
' operation = "*"
' TestOKEnabled()
'End Sub
'Private Sub cmdCommonIntercept_Click(sender As Object, e As EventArgs) Handles cmdCommonIntercept.Click
' operation = "/"
' TestOKEnabled()
'End Sub
Private Sub chkModelName_CheckedChanged(sender As Object, e As EventArgs) Handles chkSaveModel.CheckedChanged
If chkSaveModel.Checked Then
ucrModelName.Visible = True
Else
ucrModelName.Visible = False
End If
AssignModelName()
TestOKEnabled()
End Sub
Private Sub AssignModelName()
If chkSaveModel.Checked AndAlso Not ucrModelName.IsEmpty Then
ucrBaseFourVariableModelling.clsRsyntax.SetAssignTo(ucrModelName.GetText, strTempModel:=ucrModelName.GetText, strTempDataframe:=ucrSelectorFourVariableModelling.ucrAvailableDataFrames.cboAvailableDataFrames.Text)
ucrBaseFourVariableModelling.clsRsyntax.bExcludeAssignedFunctionOutput = True
Else
ucrBaseFourVariableModelling.clsRsyntax.SetAssignTo("last_model", strTempModel:="last_model", strTempDataframe:=ucrSelectorFourVariableModelling.ucrAvailableDataFrames.cboAvailableDataFrames.Text)
ucrBaseFourVariableModelling.clsRsyntax.bExcludeAssignedFunctionOutput = False
End If
End Sub
Private Sub cboModelOperators1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboModelOperators1.SelectedIndexChanged
operation = cboModelOperators1.SelectedItem.ToString
TestOKEnabled()
End Sub
Private Sub cboModelOperators2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboModelOperators2.SelectedIndexChanged
ChooseRFunction()
clsModel2.SetOperation(cboModelOperators2.SelectedItem.ToString)
TestOKEnabled()
End Sub
Public Sub ChooseRFunction()
sdgModelOptions.ucrFamily.RecieverDatatype(ucrFamily.strDataType)
sdgModelOptions.ucrFamily.cboDistributions.SelectedIndex = sdgModelOptions.ucrFamily.lstCurrentDistributions.FindIndex(Function(dist) dist.strNameTag = ucrFamily.clsCurrDistribution.strNameTag)
sdgModelOptions.RestrictLink()
'TODO: Include multinomial as an option And the appropriate function
If (ucrFamily.clsCurrDistribution.strNameTag = "Normal" And cboModelOperators2.SelectedItem.ToString <> "|") Then
ucrBaseFourVariableModelling.clsRsyntax.SetFunction("lm")
ucrBaseFourVariableModelling.clsRsyntax.RemoveParameter("family")
ElseIf (ucrFamily.clsCurrDistribution.strNameTag = "Normal" And cboModelOperators2.SelectedItem.ToString = "|") Then
ucrBaseFourVariableModelling.clsRsyntax.SetFunction("lmer")
ucrBaseFourVariableModelling.clsRsyntax.RemoveParameter("family")
ElseIf (ucrFamily.clsCurrDistribution.strNameTag <> "Normal" And cboModelOperators2.SelectedItem.ToString = "|") Then
clsRCIFunction.SetRCommand(ucrFamily.clsCurrDistribution.strGLMFunctionName)
ucrBaseFourVariableModelling.clsRsyntax.SetFunction("glmer")
ucrBaseFourVariableModelling.clsRsyntax.AddParameter("family", clsRFunctionParameter:=clsRCIFunction)
Else
clsRCIFunction.SetRCommand(ucrFamily.clsCurrDistribution.strGLMFunctionName)
ucrBaseFourVariableModelling.clsRsyntax.SetFunction("glm")
ucrBaseFourVariableModelling.clsRsyntax.AddParameter("family", clsRFunctionParameter:=clsRCIFunction)
End If
End Sub
Private Sub ucrSecondRandomEffect_SelectionChanged(sender As Object, e As EventArgs) Handles ucrThirdExplanatoryVariable.SelectionChanged
End Sub
Private Sub ucrFirstRandomEffect_SelectionChanged(sender As Object, e As EventArgs) Handles ucrSecondExplanatoryVariable.SelectionChanged
End Sub
Private Sub ucrFirstExplanatory_SelectionChanged(sender As Object, e As EventArgs) Handles ucrFirstExplanatory.SelectionChanged
End Sub
Private Sub ucrResponse_SelectionChanged(sender As Object, e As EventArgs) Handles ucrResponse.SelectionChanged
End Sub
Public Sub ucrFamily_cboDistributionsIndexChanged(sender As Object, e As EventArgs) Handles ucrFamily.cboDistributionsIndexChanged
ChooseRFunction()
End Sub
Private Sub cmdModelOptions_Click(sender As Object, e As EventArgs) Handles cmdModelOptions.Click
sdgModelOptions.ShowDialog()
ucrFamily.cboDistributions.SelectedIndex = ucrFamily.lstCurrentDistributions.FindIndex(Function(dist) dist.strNameTag = sdgModelOptions.ucrFamily.clsCurrDistribution.strNameTag)
End Sub
Private Sub chkFirstFunction_CheckedChanged(sender As Object, e As EventArgs) Handles chkFirstFunction.CheckedChanged
If chkFirstFunction.Checked Then
sdgVariableTransformations.ShowDialog()
End If
ExplanatoryFunctionSelect(ucrFirstExplanatory)
End Sub
End Class |
Imports BVSoftware.BVC5.Core
Imports BVSoftware.BVC5.Core.Orders
Imports System.IO
Imports System.Text
Imports BVSoftware.CredEx
Partial Class CredExPostBack
Inherits System.Web.UI.Page
Protected Sub CredExPostBack_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
' Find the Order Matching the Post Back Request
Dim orderBvin As String = Request("id")
If (orderBvin Is Nothing) Then
Return
End If
If (orderBvin = String.Empty) Then
Return
End If
Dim o As Order = Orders.Order.FindByBvin(orderBvin)
If (o Is Nothing) Then
Return
End If
If (o.Bvin = String.Empty) Then
Return
End If
' Read Xml Data Posted
Dim sr As New StreamReader(Request.InputStream)
Dim xmlData As String = sr.ReadToEnd()
Dim postData As New BVSoftware.CredEx.CreditPostBackData()
postData.FromXml(xmlData)
If (postData IsNot Nothing) Then
ProcessPost(postData, o)
End If
End If
End Sub
Private Sub ProcessPost(ByVal postData As CreditPostBackData, ByVal o As Orders.Order)
If (postData.StatusCode.Trim().ToUpper() = "Y") Then
For Each op As OrderPayment In o.Payments
If op.PaymentMethodId = WebAppSettings.PaymentIdCredEx Then
If (o.PaymentStatus = OrderPaymentStatus.Unpaid) Then
' Approve Credit on Order
op.AmountCharged = o.GrandTotal
Orders.OrderPayment.Update(op)
Dim previousPaymentStatus As Orders.OrderPaymentStatus = o.PaymentStatus
o.EvaluatePaymentStatus()
Orders.Order.Update(o)
' Run Workflow since Payment has Changed
Dim context As New BusinessRules.OrderTaskContext()
context.Order = o
context.UserId = o.UserID
context.Inputs.Add("bvsoftware", "PreviousPaymentStatus", previousPaymentStatus.ToString())
If Not BusinessRules.Workflow.RunByBvin(context, WebAppSettings.WorkflowIdPaymentChanged) Then
For Each item As BusinessRules.WorkflowMessage In context.Errors
EventLog.LogEvent(item.Name, item.Description, Metrics.EventLogSeverity.Error)
Next
End If
End If
End If
Next
ElseIf (postData.StatusCode.Trim().ToUpper() = "R") Then
' Citi App Card Info instead of credit approval
Dim op As New OrderPayment
op.AuditDate = DateTime.Now
op.CreditCardNumber = Utilities.CreditCardValidator.CleanCardNumber(postData.CardNumber)
If op.CreditCardNumber.StartsWith("4") Then
op.CreditCardType = "Visa"
Else
op.CreditCardType = "MasterCard"
End If
Dim expMonth As Integer = 1
Dim expYear As Integer = 1999
Integer.TryParse(postData.ExpMonth, expMonth)
Integer.TryParse(postData.ExpYear, expYear)
op.CreditCardSecurityCode = postData.CVV
op.Encrypted = True
op.OrderID = o.Bvin
op.TransactionReferenceNumber = postData.CredExReferenceNumber
op.ThirdPartyTransId = postData.CredExReferenceNumber
op.ThirdPartyOrderId = postData.MerchantRefernceNumber
op.PaymentMethodId = WebAppSettings.PaymentIdCreditCard
op.PaymentMethodName = "Credit Card"
op.AmountAuthorized = o.GrandTotal
o.AddPayment(op)
Orders.Order.Update(o)
CollectPayment(o, postData.CredExReferenceNumber, postData.MerchantRefernceNumber)
Else
Dim note As New OrderNote()
note.NoteType = OrderNoteType.Private
note.Note = "CredEx: " & postData.Status & " | " & postData.Reason & " | " & postData.CustomerAccountMessage
o.AddNote(note)
Orders.Order.Update(o)
End If
End Sub
Private Sub CollectPayment(ByVal o As Orders.Order, ByVal credExRef As String, ByVal merchRef As String)
Dim previousPaymentStatus As Orders.OrderPaymentStatus = o.PaymentStatus
For Each op As Orders.OrderPayment In o.Payments
If op.PaymentMethodId = WebAppSettings.PaymentIdCreditCard Then
Dim m As Payment.PaymentMethod = op.FindMethod(TaskLoader.LoadPaymentMethods())
Dim method As Payment.CollectablePaymentMethod = CType(m, Payment.CollectablePaymentMethod)
If method.CaptureIsValid(op) = True Then
Dim d As New Payment.PaymentData
d.OrderPaymentId = op.Bvin
d.StoreOrder = o
d.Amount = op.AmountAuthorized
method.Capture(d)
' Reload Order Status
o = Orders.Order.FindByBvin(o.Bvin)
Dim context As New BusinessRules.OrderTaskContext
context.Order = o
context.UserId = o.UserID
context.Inputs.Add("bvsoftware", "PreviousPaymentStatus", previousPaymentStatus.ToString())
If Not BusinessRules.Workflow.RunByBvin(context, WebAppSettings.WorkflowIdPaymentChanged) Then
SendCardResponse(False, credExRef, merchRef)
For Each item As BusinessRules.WorkflowMessage In context.Errors
EventLog.LogEvent("Payment Changed Workflow", item.Name & ": " & item.Description, Metrics.EventLogSeverity.Error)
Next
Else
SendCardResponse(True, credExRef, merchRef)
End If
End If
End If
Next
End Sub
Private Sub SendCardResponse(ByVal success As Boolean, ByVal credExRef As String, ByVal merchRef As String)
Dim res As New CreditPostBackResponse()
res.Data.CredExReferenceNumber = credExRef
res.Data.MerchantRefernceNumber = merchRef
If (success) Then
res.Data.StatusCode = "Y"
res.Data.Status = "approved"
Else
res.Data.StatusCode = "N"
res.Data.Status = "declined"
End If
res.Settings.CredExProductId = WebAppSettings.CredExProductId
res.Settings.IsTestMode = WebAppSettings.CredExTestMode
res.Settings.MerchantId = WebAppSettings.CredExMerchantId
res.Settings.MerchantKey = WebAppSettings.CredExMerchantKey
Dim svc As New CredExService()
svc.ProcessRequest(res)
End Sub
End Class
|
#Region "Microsoft.VisualBasic::cfc4822cbf1fa8148eb74eddf2de360b, mzkit\src\mzmath\MoleculeNetworking\Networking.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: 91
' Code Lines: 82
' Comment Lines: 0
' Blank Lines: 9
' File Size: 3.50 KB
' Module Networking
'
' Function: RepresentativeSpectrum, Tree
'
' /********************************************************************************/
#End Region
Imports System.Runtime.CompilerServices
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Ms1
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Spectra
Imports Microsoft.VisualBasic.DataMining.BinaryTree
Imports Microsoft.VisualBasic.Linq
Imports Microsoft.VisualBasic.Math.Distributions
Imports Microsoft.VisualBasic.Serialization.JSON
''' <summary>
''' Molecular networks are visual displays of the chemical space present
''' in tandem mass spectrometry (MS/MS) experiments. This visualization
''' approach can detect sets of spectra from related molecules (molecular
''' networks), even when the spectra themselves are not matched to any
''' known compounds.
'''
''' The visualization Of molecular networks In GNPS represents Each spectrum
''' As a node, And spectrum-To-spectrum alignments As edges (connections)
''' between nodes. Nodes can be supplemented With metadata, including
''' dereplication matches Or information that Is provided by the user, e.g.
''' As abundance, origin Of product, biochemical activity, Or hydrophobicity,
''' which can be reflected In a node's size or color. This map of all
''' related molecules is visualized as a global molecular network.
''' </summary>
Public Module Networking
''' <summary>
''' implements the molecule networking
''' </summary>
''' <param name="ions"></param>
''' <param name="mzdiff"></param>
''' <param name="intocutoff"></param>
''' <param name="equals"></param>
''' <returns></returns>
<Extension>
Public Function Tree(ions As IEnumerable(Of PeakMs2),
Optional mzdiff As Double = 0.3,
Optional intocutoff As Double = 0.05,
Optional equals As Double = 0.85) As TreeCluster
Dim cosine As New CosAlignment(
mzwidth:=Tolerance.DeltaMass(mzdiff),
intocutoff:=New RelativeIntensityCutoff(intocutoff)
)
Dim align As New MSScore(cosine, ions.ToArray, equals, equals)
Dim clustering As New ClusterTree
Dim ionsList As New List(Of PeakMs2)
For Each ion As PeakMs2 In align.Ions
Call ionsList.Add(ion)
Call ClusterTree.Add(clustering, ion.lib_guid, align, threshold:=equals)
Next
Return New TreeCluster With {
.tree = clustering,
.spectrum = ionsList.ToArray
}
End Function
Private Iterator Function normPeaki(i As PeakMs2) As IEnumerable(Of ms2)
Dim maxinto As Double = i.mzInto _
.Select(Function(mzi) mzi.intensity) _
.Max
For Each mzi As ms2 In i.mzInto
Yield New ms2 With {
.mz = mzi.mz,
.intensity = mzi.intensity / maxinto
}
Next
End Function
''' <summary>
'''
''' </summary>
''' <param name="cluster"></param>
''' <returns></returns>
''' <remarks>
''' <see cref="PeakMs2.collisionEnergy"/> is tagged as the cluster size
''' </remarks>
<Extension>
Private Function unionMetadata(cluster As IEnumerable(Of PeakMs2)) As Dictionary(Of String, String)
Return cluster _
.Select(Function(c) c.meta) _
.IteratesALL _
.GroupBy(Function(t) t.Key) _
.ToDictionary(Function(t) t.Key,
Function(t)
Return t _
.Select(Function(ti) ti.Value) _
.Distinct _
.JoinBy("; ")
End Function)
End Function
''' <summary>
''' merge the given collection of the ms2 spectrum data as an union spectrum data
''' </summary>
''' <param name="cluster"></param>
''' <param name="mzdiff">
''' the mzdiff tolerance value for grouping the union ms2 peaks based
''' on the centroid function
''' </param>
''' <param name="zero"></param>
''' <param name="key"></param>
''' <returns></returns>
<Extension>
Public Function RepresentativeSpectrum(cluster As PeakMs2(),
mzdiff As Tolerance,
zero As RelativeIntensityCutoff,
Optional key As String = Nothing) As PeakMs2
Dim union As ms2() = cluster _
.Select(AddressOf normPeaki) _
.IteratesALL _
.ToArray _
.Centroid(mzdiff, cutoff:=zero) _
.ToArray
Dim rt As Double = cluster _
.Select(Function(c) c.rt) _
.TabulateBin _
.Average
Dim mz1 As Double
Dim metadata = cluster.unionMetadata
If cluster.Length = 1 Then
mz1 = cluster(Scan0).mz
Else
mz1 = 0
metadata("mz1") = cluster _
.Select(Function(c) c.mz) _
.ToArray _
.GetJson
End If
Return New PeakMs2 With {
.rt = rt,
.activation = "NA",
.collisionEnergy = cluster.Length,
.file = key,
.intensity = cluster.Sum(Function(c) c.intensity),
.lib_guid = key,
.mz = mz1,
.mzInto = union,
.precursor_type = "NA",
.scan = "NA",
.meta = metadata
}
End Function
End Module
|
Public Class SplashWindow
Public Sub New(msg As String)
' This call is required by the designer.
InitializeComponent()
Me.textbox_msg.Text = msg
' Add any initialization after the InitializeComponent() call.
End Sub
End Class
|
Public Class Bloco
Public Property nomeArquivo As String
Public Property comprimento As String
Public Property profundidade As String
Public Property altura As String
Public Property peso As String
Public Property medidas As String
End Class
|
Imports System
Imports Microsoft.SPOT
Imports Microsoft.SPOT.Hardware
Imports Toolbox.NETMF
Imports Toolbox.NETMF.NET
' Copyright 2012 Stefan Thoolen (http://www.netmftoolbox.com/)
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
Namespace Programs
Public Module ShellCommands
''' <summary>
''' Binds to the Shell Core
''' </summary>
''' <param name="Shell">The ShellCore object</param>
Public Sub Bind(Shell As ShellCore)
AddHandler Shell.OnCommandReceived, AddressOf Shell_OnCommandReceived
AddHandler Shell.OnConnected, AddressOf Shell_OnConnected
End Sub
''' <summary>
''' Unbinds from the Shell Core
''' </summary>
''' <param name="Shell">The ShellCore object</param>
Public Sub Unbind(Shell As ShellCore)
RemoveHandler Shell.OnConnected, AddressOf Shell_OnConnected
RemoveHandler Shell.OnCommandReceived, AddressOf Shell_OnCommandReceived
End Sub
''' <summary>
''' Triggered when the connection has been made
''' </summary>
''' <param name="Shell">Reference to the shell</param>
''' <param name="RemoteAddress">Hostname of the user</param>
''' <param name="Time">Timestamp of the event</param>
Private Sub Shell_OnConnected(Shell As ShellCore, RemoteAddress As String, Time As DateTime)
Shell.Telnetserver.Color(TelnetServer.Colors.White, TelnetServer.Colors.Black)
Shell.Telnetserver.ClearScreen()
_SendMotd(Shell.Telnetserver)
End Sub
''' <summary>
''' Sends the MOTD
''' </summary>
Private Sub _SendMotd(Server As TelnetServer)
Server.Color(TelnetServer.Colors.HighIntensityWhite)
Server.Print("Welcome to the Netduino Telnet Server, " + Server.RemoteAddress)
Server.Print("Copyright 2012 by Stefan Thoolen (http://www.netmftoolbox.com/)")
Server.Print("Type HELP to see a list of all supported commands")
Server.Print("")
Server.Color(TelnetServer.Colors.White)
End Sub
''' <summary>
''' Triggered when a command has been given
''' </summary>
''' <param name="Shell">Reference to the shell</param>
''' <param name="Arguments">Command line arguments</param>
''' <param name="SuspressError">Set to 'true' if you could do anything with the command</param>
''' <param name="Time">Current timestamp</param>
Private Sub Shell_OnCommandReceived(Shell As ShellCore, Arguments() As String, ByRef SuspressError As Boolean, Time As DateTime)
Select Case Arguments(0).ToUpper()
Case "CLS"
Shell.Telnetserver.ClearScreen()
SuspressError = True
Case "MOTD"
_SendMotd(Shell.Telnetserver)
SuspressError = True
Case "ECHO"
Shell.Telnetserver.Print(Shell.LastCommandline.Substring(5))
SuspressError = True
Case "REBOOT"
Shell.Telnetserver.Print("Rebooting...")
Thread.Sleep(100)
Shell.Telnetserver.Close()
PowerState.RebootDevice(False)
SuspressError = True
Case "QUIT"
Shell.Telnetserver.Print("Bye!")
Thread.Sleep(100)
Shell.Telnetserver.Close()
SuspressError = True
Case "INFO"
Shell.Telnetserver.Print("Manufacturer: " + SystemInfo.OEMString)
Shell.Telnetserver.Print("Firmware version: " + SystemInfo.Version.ToString())
Shell.Telnetserver.Print("Memory available: " + Tools.MetricPrefix(Debug.GC(False), True) + "B")
If PowerState.Uptime.Days = 0 Then
Shell.Telnetserver.Print("Uptime: " + PowerState.Uptime.ToString())
Else
Shell.Telnetserver.Print("Uptime: " + PowerState.Uptime.Days.ToString() + " days, " + PowerState.Uptime.ToString())
End If
Shell.Telnetserver.Print("Hardware provider: " + Tools.HardwareProvider)
Shell.Telnetserver.Print("System clock: " + Tools.MetricPrefix(Cpu.SystemClock) + "hz")
If SystemInfo.IsBigEndian Then
Shell.Telnetserver.Print("Endianness: Big Endian")
Else
Shell.Telnetserver.Print("Endianness: Little Endian")
End If
If System.Diagnostics.Debugger.IsAttached Then
Shell.Telnetserver.Print("Debugger: attached")
Else
Shell.Telnetserver.Print("Debugger: not attached")
End If
SuspressError = True
Case "VER"
Dim Assemblies() As System.Reflection.Assembly = AppDomain.CurrentDomain.GetAssemblies()
For i As Integer = 0 To Assemblies.Length - 1
Shell.Telnetserver.Print(Assemblies(i).FullName)
Next
SuspressError = True
Case "HELP"
Dim PageFound As Boolean = False
If Arguments.Length = 1 Then
PageFound = DoHelp(Shell.Telnetserver, "")
Else
PageFound = DoHelp(Shell.Telnetserver, Arguments(1).ToUpper())
End If
If PageFound Then SuspressError = True
End Select
End Sub
''' <summary>
''' Shows a specific help page
''' </summary>
''' <param name="Server">The telnet server object</param>
''' <param name="Page">The page</param>
''' <returns>True when the page exists</returns>
Private Function DoHelp(Server As TelnetServer, Page As String) As Boolean
Select Case Page.ToUpper()
Case ""
Server.Print("CLS Clears the screen")
Server.Print("ECHO [TEXT] Prints out the text")
Server.Print("MOTD Shows the message of the day")
Server.Print("QUIT Closes the connection")
Server.Print("VER Shows the version of all loaded assemblies")
Server.Print("INFO Shows some system info")
Server.Print("REBOOT Restarts the device")
Return True
Case "VER"
Server.Print("VER Shows the version of all loaded assemblies")
Return True
Case "REBOOT"
Server.Print("REBOOT Restarts the device")
Return True
Case "MOTD"
Server.Print("MOTD Shows the message of the day")
Return True
Case "INFO"
Server.Print("INFO Shows some system info")
Return True
Case "CLS"
Server.Print("CLS Clears the screen")
Return True
Case "ECHO"
Server.Print("ECHO [TEXT] Prints out the text")
Server.Print("- [TEXT] Text to print out")
Return True
Case "QUIT"
Server.Print("QUIT Closes the connection")
Return True
Case Else
Return False
End Select
End Function
End Module
End Namespace
|
Imports System.ComponentModel.DataAnnotations
Public Class clsChargeArea
Inherits EskimoBaseClass
Property ID As Integer
Property Description As String
Property Charges As List(Of clsChargeNumber)
End Class
Public Class clsChargeNumber
Inherits EskimoBaseClass
Property ScopeNumber As Integer 'ticket/table
<Required>
Property Name As String
End Class |
Public Interface IClient
Sub ParticipantDisconnection(name As String)
Sub ParticipantReconnection(name As String)
Sub ParticipantLogin(client As User)
Sub ParticipantLogout(name As String)
Sub BroadcastMessage(sender As String, message As String)
Sub UnicastMessage(sender As String, message As String)
End Interface
|
Imports System.Windows
Imports MySql.Data.MySqlClient
Imports DTO
Public Class SuaSachDAL
Shared con As MySqlConnection = New MySqlConnection(ConnectionDTO.Connection)
''' <summary>
''' cập nhập lại thông tin sách
''' </summary>
''' <param name="MaSach"></param>
''' <param name="TenSach"></param>
''' <param name="TheLoai"></param>
''' <param name="TacGia"></param>
''' <param name="DonGia"></param>
''' <returns></returns>
Public Shared Function SuaSach(ByVal MaSach As String, ByVal TenSach As String, ByVal TheLoai As String, ByVal TacGia As String, ByVal DonGia As String) As Boolean
Using con
Try
con.Open()
Dim query = "update Sach set TenSach = @TenSach, TheLoai = @TheLoai, TacGia = @TacGia, DonGia = @DonGia where MaSach = @MaSach"
Dim cmd As MySqlCommand = New MySqlCommand(query, con)
cmd.Parameters.AddWithValue("@TenSach", TenSach)
cmd.Parameters.AddWithValue("@TheLoai", TheLoai)
cmd.Parameters.AddWithValue("@TacGia", TacGia)
cmd.Parameters.AddWithValue("@DonGia", DonGia)
cmd.Parameters.AddWithValue("@MaSach", MaSach)
Dim count = 0
count = cmd.ExecuteNonQuery()
If count > 0 Then
Return True
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
con.Close()
End Try
End Using
Return False
End Function
End Class
|
Imports System.Data.SqlClient
Namespace DataObjects.TableObjects
''' <summary>
''' Provides the functionality to manage data from tbl_country
''' </summary>
<Serializable()> _
Public Class tbl_country
Inherits DBObjectBase
#Region "Class Level Fields"
''' <summary>
''' Instance of DESettings
''' </summary>
Private _settings As New DESettings
''' <summary>
''' Class Name which is used in cache key construction
''' </summary>
Const CACHEKEY_CLASSNAME As String = "tbl_country"
#End Region
#Region "Constructors"
Sub New()
End Sub
''' <summary>
''' Initializes a new instance of the <see cref="tbl_country" /> class.
''' </summary>
''' <param name="settings">The DESettings instance</param>
Sub New(ByVal settings As DESettings)
_settings = settings
End Sub
#End Region
#Region "Public Methods"
''' <summary>
''' Get True or False value based on whether the provided country code can use gift aid
''' </summary>
''' <param name="countryCode">The country code provided</param>
''' <param name="cacheing">Cacheing On/Off - Default=True</param>
''' <param name="cacheTimeMinutes">Cache Time In Minutes - Default=30</param>
''' <returns>Boolean</returns>
Public Function CanCountryUseGiftAid(ByVal countryCode As String, Optional ByVal cacheing As Boolean = True, Optional ByVal cacheTimeMinutes As Integer = 30) As Boolean
Dim canUseGiftAid As Boolean = False
Dim outputDataSet As New DataSet
Dim cacheKeyPrefix As String = GetCacheKeyPrefix(CACHEKEY_CLASSNAME, "CanCountryUseGiftAid")
Dim talentSqlAccessDetail As New TalentDataAccess
Try
'Construct The Call
talentSqlAccessDetail.Settings = _settings
talentSqlAccessDetail.Settings.Cacheing = cacheing
talentSqlAccessDetail.Settings.CacheTimeMinutes = cacheTimeMinutes
talentSqlAccessDetail.Settings.CacheStringExtension = cacheKeyPrefix & countryCode.ToUpper
talentSqlAccessDetail.CommandElements.CommandExecutionType = CommandExecution.ExecuteDataSet
talentSqlAccessDetail.CommandElements.CommandText = "SELECT [CAN_USE_GIFT_AID_OPTION] FROM tbl_country WITH(NOLOCK) WHERE [COUNTRY_CODE] = @countryCode OR [COUNTRY_DESCRIPTION] = @countryCode"
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@countryCode", countryCode))
'Execute
Dim err As New ErrorObj
err = talentSqlAccessDetail.SQLAccess()
If (Not (err.HasError) And (talentSqlAccessDetail.ResultDataSet IsNot Nothing)) Then
outputDataSet = talentSqlAccessDetail.ResultDataSet
If outputDataSet.Tables.Count = 1 Then
If outputDataSet.Tables(0).Rows.Count = 1 Then
canUseGiftAid = CBool(outputDataSet.Tables(0).Rows(0)("CAN_USE_GIFT_AID_OPTION"))
End If
End If
End If
Catch ex As Exception
Throw
Finally
talentSqlAccessDetail = Nothing
End Try
'Return the result
Return canUseGiftAid
End Function
''' <summary>
''' Gets all the business unit records from the table tbl_country
''' </summary>
''' <param name="cacheing">if set to <c>true</c> [cacheing].</param>
''' <param name="cacheTimeMinutes">The cache time minutes.</param>
''' <returns>DataSet with records</returns>
Public Function GetAll(Optional ByVal cacheing As Boolean = True, Optional ByVal cacheTimeMinutes As Integer = 30) As DataTable
Dim outputDataTable As New DataTable
Dim cacheKeyPrefix As String = GetCacheKeyPrefix(CACHEKEY_CLASSNAME, "GetAll")
Dim talentSqlAccessDetail As New TalentDataAccess
Try
'Construct The Call
talentSqlAccessDetail.Settings = _settings
talentSqlAccessDetail.Settings.Cacheing = cacheing
talentSqlAccessDetail.Settings.CacheTimeMinutes = cacheTimeMinutes
talentSqlAccessDetail.Settings.CacheStringExtension = cacheKeyPrefix
talentSqlAccessDetail.CommandElements.CommandExecutionType = CommandExecution.ExecuteDataSet
talentSqlAccessDetail.CommandElements.CommandText = "Select * From TBL_COUNTRY"
'Execute
Dim err As New ErrorObj
err = talentSqlAccessDetail.SQLAccess()
If (Not (err.HasError)) And (Not (talentSqlAccessDetail.ResultDataSet Is Nothing)) Then
outputDataTable = talentSqlAccessDetail.ResultDataSet.Tables(0)
End If
Catch ex As Exception
Throw
Finally
talentSqlAccessDetail = Nothing
End Try
'Return the results
Return outputDataTable
End Function
''' <summary>
''' Get the country code by the given country description
''' </summary>
''' <param name="countryDescription">The country description provided</param>
''' <param name="cacheing">Cacheing On/Off - Default=True</param>
''' <param name="cacheTimeMinutes">Cache Time In Minutes - Default=30</param>
''' <returns>The country code</returns>
Public Function GetCountryCodeByDescription(ByVal countryDescription As String, Optional ByVal cacheing As Boolean = True, Optional ByVal cacheTimeMinutes As Integer = 30) As String
Dim countryCode As String = String.Empty
Dim outputDataSet As New DataSet
Dim cacheKeyPrefix As String = GetCacheKeyPrefix(CACHEKEY_CLASSNAME, "GetCountryCodeByDescription")
Dim talentSqlAccessDetail As New TalentDataAccess
Try
'Construct The Call
talentSqlAccessDetail.Settings = _settings
talentSqlAccessDetail.Settings.Cacheing = cacheing
talentSqlAccessDetail.Settings.CacheTimeMinutes = cacheTimeMinutes
talentSqlAccessDetail.Settings.CacheStringExtension = cacheKeyPrefix & countryDescription.ToUpper()
talentSqlAccessDetail.CommandElements.CommandExecutionType = CommandExecution.ExecuteDataSet
talentSqlAccessDetail.CommandElements.CommandText = "SELECT [COUNTRY_CODE] FROM tbl_country WITH(NOLOCK) WHERE [COUNTRY_DESCRIPTION] = @CountryDescription"
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@CountryDescription", countryDescription))
'Execute
Dim err As New ErrorObj
err = talentSqlAccessDetail.SQLAccess()
If (Not (err.HasError) And (talentSqlAccessDetail.ResultDataSet IsNot Nothing)) Then
outputDataSet = talentSqlAccessDetail.ResultDataSet
If outputDataSet.Tables.Count = 1 Then
If outputDataSet.Tables(0).Rows.Count = 1 Then
countryCode = outputDataSet.Tables(0).Rows(0)("COUNTRY_CODE")
End If
End If
End If
Catch ex As Exception
Throw
Finally
talentSqlAccessDetail = Nothing
End Try
'Return the result
Return countryCode
End Function
Public Function CanCountryAllowVATExemption(ByVal countryCode As String, Optional ByVal cacheing As Boolean = True, Optional ByVal cacheTimeMinutes As Integer = 30) As Boolean
Dim canAllow As Boolean = False
Dim outputDataSet As New DataSet
Dim cacheKeyPrefix As String = GetCacheKeyPrefix(CACHEKEY_CLASSNAME, "CanCountryAllowVATExemption")
Dim talentSqlAccessDetail As New TalentDataAccess
Try
'Construct The Call
talentSqlAccessDetail.Settings = _settings
talentSqlAccessDetail.Settings.Cacheing = cacheing
talentSqlAccessDetail.Settings.CacheTimeMinutes = cacheTimeMinutes
talentSqlAccessDetail.Settings.CacheStringExtension = cacheKeyPrefix & countryCode.ToUpper
talentSqlAccessDetail.CommandElements.CommandExecutionType = CommandExecution.ExecuteDataSet
talentSqlAccessDetail.CommandElements.CommandText = "SELECT [IS_VAT_EXEMPTED] FROM tbl_country WITH(NOLOCK) WHERE [COUNTRY_CODE] = @countryCode OR [COUNTRY_DESCRIPTION] = @countryCode"
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@countryCode", countryCode))
'Execute
Dim err As New ErrorObj
err = talentSqlAccessDetail.SQLAccess()
If (Not (err.HasError) And (talentSqlAccessDetail.ResultDataSet IsNot Nothing)) Then
outputDataSet = talentSqlAccessDetail.ResultDataSet
If outputDataSet.Tables.Count = 1 Then
If outputDataSet.Tables(0).Rows.Count = 1 Then
canAllow = Utilities.CheckForDBNull_Boolean_DefaultFalse(outputDataSet.Tables(0).Rows(0)("IS_VAT_EXEMPTED"))
End If
End If
End If
Catch ex As Exception
Throw
Finally
talentSqlAccessDetail = Nothing
End Try
'Return the result
Return canAllow
End Function
''' <summary>
''' Get ISO Alpha 3 code for given country code or description
''' </summary>
''' <param name="countryCodeOrDescription"></param>
''' <param name="cacheing"></param>
''' <param name="cacheTimeMinutes"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GetISOAlpha3ByCodeOrDescription(ByVal countryCodeOrDescription As String, Optional ByVal cacheing As Boolean = True, Optional ByVal cacheTimeMinutes As Integer = 30) As String
Dim countryCode As String = String.Empty
If String.IsNullOrWhiteSpace(countryCodeOrDescription) Then countryCodeOrDescription = ""
Dim moduleName As String = "GetISOAlpha3ByDescription"
Dim dtOutput As DataTable = Nothing
Dim cacheKey As String = GetCacheKeyPrefix(CACHEKEY_CLASSNAME, moduleName & _settings.BusinessUnit & countryCodeOrDescription.ToUpper)
Dim isCacheNotFound As Boolean = False
Dim talentSqlAccessDetail As TalentDataAccess = Nothing
Try
Me.ResultDataSet = TryGetFromCache(Of DataSet)(isCacheNotFound, cacheing, cacheKey)
If isCacheNotFound Then
'Construct The Call
talentSqlAccessDetail = New TalentDataAccess
talentSqlAccessDetail.Settings = _settings
talentSqlAccessDetail.Settings.CacheStringExtension = cacheKey
talentSqlAccessDetail.CommandElements.CommandExecutionType = CommandExecution.ExecuteDataSet
talentSqlAccessDetail.CommandElements.CommandText = "SELECT [ISO_ALPHA_3] FROM tbl_country WITH(NOLOCK) WHERE ([COUNTRY_CODE] = @countryCodeOrDescription OR [COUNTRY_DESCRIPTION] = @countryCodeOrDescription)"
talentSqlAccessDetail.CommandElements.CommandParameter.Add(ConstructParameter("@countryCodeOrDescription", countryCodeOrDescription))
Dim err As New ErrorObj
err = talentSqlAccessDetail.SQLAccess(DestinationDatabase.SQL2005, cacheing, cacheTimeMinutes)
If (Not (err.HasError)) AndAlso (talentSqlAccessDetail.ResultDataSet IsNot Nothing) Then
Me.ResultDataSet = talentSqlAccessDetail.ResultDataSet
End If
End If
If Me.ResultDataSet IsNot Nothing AndAlso Me.ResultDataSet.Tables.Count > 0 AndAlso Me.ResultDataSet.Tables(0).Rows.Count > 0 Then
countryCode = Utilities.CheckForDBNull_String(Me.ResultDataSet.Tables(0).Rows(0)("ISO_ALPHA_3")).ToUpper
End If
Catch ex As Exception
Throw
Finally
talentSqlAccessDetail = Nothing
End Try
Return countryCode
End Function
#End Region
End Class
End Namespace |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.