text stringlengths 43 2.01M |
|---|
#Region "Microsoft.VisualBasic::f34a6b0fa9e664d199ad0b50c92b35d5, mzkit\src\metadb\Massbank\Public\TMIC\HMDB\MetaReference\WebQuery.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: 29
' Code Lines: 24
' Comment Lines: 0
' Blank Lines: 5
' File Size: 1.15 KB
' Class WebQuery
'
' Constructor: (+1 Overloads) Sub New
' Function: ParseXml
'
'
' /********************************************************************************/
#End Region
Imports System.Runtime.CompilerServices
Imports BioNovoGene.BioDeep.Chemistry.MetaLib.Models
Imports Microsoft.VisualBasic.Net.Http
Namespace TMIC.HMDB.Repository
Public Class WebQuery : Inherits WebQuery(Of String)
Public Sub New(<CallerMemberName>
Optional cache As String = Nothing,
Optional interval As Integer = -1,
Optional offline As Boolean = False)
MyBase.New(url:=Function(id) $"http://www.hmdb.ca/metabolites/{id.FormatHMDBId}.xml",
contextGuid:=Function(id) id,
parser:=AddressOf ParseXml,
prefix:=Function(id) Mid(id.Match("\d+").ParseInteger.ToString, 1, 2),
cache:=cache,
interval:=interval,
offline:=offline
)
End Sub
<MethodImpl(MethodImplOptions.AggressiveInlining)>
Private Shared Function ParseXml(xml$, null As Type) As metabolite
Return xml.LoadFromXml(Of metabolite)(throwEx:=False)
End Function
End Class
End Namespace
|
'
' SPDX-FileCopyrightText: 2020 DB Systel GmbH
'
' SPDX-License-Identifier: Apache-2.0
'
' 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.
'
' Author: Frank Schwab, DB Systel GmbH
'
' Version: 1.1.0
'
' Change history:
' 2020-05-05: V1.0.0: Created.
' 2020-05-14: V1.1.0: Correct usage of Dispose interface.
'
Imports System.IO
'Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports DB.BCM.TUPW
<TestClass()> Public Class FileAndKeyEncryptionTest
''' <summary>
''' File name for the non-random bytes.
''' </summary>
Private Const NOT_RANDOM_FILE_NAME As String = "_not_random_file_.bin"
''' <summary>
''' HMAC key to be used for encryption.
''' </summary>
Private Shared ReadOnly HMAC_KEY As Byte() = {&HC1, &HC2, &HC8, &HF,
&HDE, &H75, &HD7, &HA9,
&HFC, &H92, &H56, &HEA,
&H3C, &HC, &H7A, &H8,
&H8A, &H6E, &HB5, &H78,
&H15, &H79, &HCF, &HB4,
&H2, &HF, &H38, &H3C,
&H61, &H4F, &H9D, &HDB}
''' <summary>
''' Known clear text to encrypt.
''' </summary>
Private Const CLEAR_TEXT_V5 As String = "This#" & ChrW(&H201D) & "s?a§StR4nGé€PàS!Wörd9"
''' <summary>
''' Subject for known encryption.
''' </summary>
Private Const SUBJECT As String = "strangeness+charm"
'
' Error message constants
'
Private Const TEXT_EXPECTED_EXCEPTION As String = "Expected exception Not thrown"
Private Const TEXT_UNEXPECTED_EXCEPTION As String = "Unexpected exception "
Private Const TEXT_SEPARATOR As String = " / "
''' <summary>
''' Create test file for all the tests.
''' </summary>
''' <param name="tc">Test context to use (not used here).</param>
#Disable Warning IDE0060
<ClassInitialize()> Public Shared Sub InitializeTests(tc As TestContext)
#Enable Warning IDE0060
'
' Generate a nonrandom key file with a predictable content, so the tests are reproducible.
'
Dim notRandomBytes As Byte() = New Byte(0 To 99999) {}
For i As Integer = 0 To notRandomBytes.Length - 1
notRandomBytes(i) = CByte(&HFF - (i And &HFF))
Next
Dim filePath As String = Path.GetFullPath(NOT_RANDOM_FILE_NAME)
Try
File.WriteAllBytes(filePath, notRandomBytes)
Catch ex As Exception
Assert.Fail("Could Not write to file '" & NOT_RANDOM_FILE_NAME & ": " & ex.Message())
End Try
End Sub
''' <summary>
''' Remove test file after all tests have been executed.
''' </summary>
<ClassCleanup()> Public Shared Sub CleanupTests()
Dim filePath As String = Path.GetFullPath(NOT_RANDOM_FILE_NAME)
Try
If File.Exists(filePath) Then _
File.Delete(filePath)
Catch ex As Exception
Assert.Fail("Could not delete file '" & NOT_RANDOM_FILE_NAME & ": " & ex.Message())
End Try
End Sub
#Region "Test methods"
''' <summary>
''' Test if the encryption of a given byte array is correctly decrypted.
''' </summary>
<TestMethod()> Public Sub TestEncryptionDecryptionForByteArray()
Dim myEncryptor As FileAndKeyEncryption = Nothing
Try
Dim testByteArray As Byte() = New Byte(0 To 255) {}
For i As Integer = 0 To testByteArray.Length - 1
testByteArray(i) = CByte(&HFF - i)
Next
myEncryptor = New FileAndKeyEncryption(HMAC_KEY, NOT_RANDOM_FILE_NAME)
Dim encryptedText As String = myEncryptor.EncryptData(testByteArray)
Dim decryptedByteArray As Byte() = myEncryptor.DecryptDataAsByteArray(encryptedText)
Assert.IsTrue(ArrayHelper.AreEqual(testByteArray, decryptedByteArray), "Decrypted byte array is not the same as original byte array")
myEncryptor.Dispose()
Catch ex As Exception
If myEncryptor IsNot Nothing Then _
myEncryptor.Dispose()
Assert.Fail(GetUnexpectedExceptionMessage(ex))
End Try
End Sub
''' <summary>
''' Test if the encryption of a given character array is correctly decrypted.
''' </summary>
<TestMethod()> Public Sub TestEncryptionDecryptionForCharacterArray()
Dim myEncryptor As FileAndKeyEncryption = Nothing
Try
Dim testCharArray As Char() = New Char() {"T"c, "h"c, "í"c, "s"c, " "c, "ì"c, "s"c, " "c, "a"c, " "c, "T"c, "ä"c, "s"c, "t"c}
myEncryptor = New FileAndKeyEncryption(HMAC_KEY, NOT_RANDOM_FILE_NAME)
Dim encryptedText As String = myEncryptor.EncryptData(testCharArray)
Dim decryptedCharArray As Char() = myEncryptor.DecryptDataAsCharacterArray(encryptedText)
myEncryptor.Dispose()
Assert.IsTrue(ArrayHelper.AreEqual(testCharArray, decryptedCharArray), "Decrypted character array is not the same as original character array")
Catch ex As Exception
If myEncryptor IsNot Nothing Then _
myEncryptor.Dispose()
Assert.Fail(GetUnexpectedExceptionMessage(ex))
End Try
End Sub
''' <summary>
''' Test if the encryption of a given text is correctly decrypted.
''' </summary>
<TestMethod()> Public Sub TestEncryptionDecryption()
Dim myEncryptor As FileAndKeyEncryption = Nothing
Try
myEncryptor = New FileAndKeyEncryption(HMAC_KEY, NOT_RANDOM_FILE_NAME)
Dim encryptedText As String = myEncryptor.EncryptData(CLEAR_TEXT_V5)
Dim decryptedText As String = myEncryptor.DecryptDataAsString(encryptedText)
Assert.AreEqual(CLEAR_TEXT_V5, decryptedText, "Decrypted text is not the same as original text")
myEncryptor.Dispose()
Catch ex As Exception
If myEncryptor IsNot Nothing Then _
myEncryptor.Dispose()
Assert.Fail(GetUnexpectedExceptionMessage(ex))
End Try
End Sub
''' <summary>
''' Test if the encryption of a given text is correctly decrypted with a subject present.
''' </summary>
<TestMethod()> Public Sub TestEncryptionDecryptionWithSubject()
Dim myEncryptor As FileAndKeyEncryption = Nothing
Try
myEncryptor = New FileAndKeyEncryption(HMAC_KEY, NOT_RANDOM_FILE_NAME)
Dim encryptedText As String = myEncryptor.EncryptData(CLEAR_TEXT_V5, SUBJECT)
Dim decryptedText As String = myEncryptor.DecryptDataAsString(encryptedText, SUBJECT)
Assert.AreEqual(CLEAR_TEXT_V5, decryptedText, "Decrypted text is not the same as original text")
myEncryptor.Dispose()
Catch ex As Exception
If myEncryptor IsNot Nothing Then _
myEncryptor.Dispose()
Assert.Fail(GetUnexpectedExceptionMessage(ex))
End Try
End Sub
''' <summary>
''' Test if the decryption of a byte array throws an exception if decrypted as a character array.
''' </summary>
<TestMethod()> Public Sub TestDecryptionToCharArrayWithInvalidByteArray()
Dim myEncryptor As FileAndKeyEncryption = Nothing
Try
Dim testByteArray As Byte() = New Byte(0 To 255) {}
For i As Integer = 0 To testByteArray.Length - 1
testByteArray(i) = CByte(&HFF - i)
Next
myEncryptor = New FileAndKeyEncryption(HMAC_KEY, NOT_RANDOM_FILE_NAME)
Dim encryptedText As String = myEncryptor.EncryptData(testByteArray, SUBJECT)
' This must throw an exception as the original byte array is not a valid UTF-8 encoding
#Disable Warning S1481 ' Unused local variables should be removed
Dim decryptedCharacterArray As Char() = myEncryptor.DecryptDataAsCharacterArray(encryptedText, SUBJECT)
#Enable Warning S1481 ' Unused local variables should be removed
myEncryptor.Dispose()
Assert.Fail(TEXT_EXPECTED_EXCEPTION)
Catch ex As ArgumentException
'
' This is the expected exception
'
If myEncryptor IsNot Nothing Then _
myEncryptor.Dispose()
Assert.IsTrue(ex.Message().Contains("Unicode"), GetUnexpectedExceptionMessage(ex))
Catch ex As Exception
If myEncryptor IsNot Nothing Then _
myEncryptor.Dispose()
Assert.Fail(GetUnexpectedExceptionMessage(ex))
End Try
End Sub
''' <summary>
''' Test if the decryption of a byte array throws an exception if decrypted as a string.
''' </summary>
<TestMethod()> Public Sub TestDecryptionToStringWithInvalidByteArray()
Dim myEncryptor As FileAndKeyEncryption = Nothing
Try
Dim testByteArray As Byte() = New Byte(0 To 255) {}
For i As Integer = 0 To testByteArray.Length - 1
testByteArray(i) = CByte(&HFF - i)
Next
myEncryptor = New FileAndKeyEncryption(HMAC_KEY, NOT_RANDOM_FILE_NAME)
Dim encryptedText As String = myEncryptor.EncryptData(testByteArray, SUBJECT)
' This must throw an exception as the original byte array is not a valid UTF-8 encoding
#Disable Warning S1481 ' Unused local variables should be removed
Dim decryptedString As String = myEncryptor.DecryptDataAsString(encryptedText, SUBJECT)
#Enable Warning S1481 ' Unused local variables should be removed
myEncryptor.Dispose()
Assert.Fail(TEXT_EXPECTED_EXCEPTION)
Catch ex As ArgumentException
'
' This is the expected exception
'
If myEncryptor IsNot Nothing Then _
myEncryptor.Dispose()
Assert.IsTrue(ex.Message().Contains("Unicode"), GetUnexpectedExceptionMessage(ex))
Catch ex As Exception
If myEncryptor IsNot Nothing Then _
myEncryptor.Dispose()
Assert.Fail(GetUnexpectedExceptionMessage(ex))
End Try
End Sub
''' <summary>
''' Test if a file that does not exist is correctly handled.
''' </summary>
<TestMethod()> Public Sub TestFileDoesNotExist()
Dim myEncryptor As FileAndKeyEncryption = Nothing
Try
myEncryptor = New FileAndKeyEncryption(HMAC_KEY, "/does/not/exist.txt")
#Disable Warning S1481 ' Unused local variables should be removed
Dim encryptedText As String = myEncryptor.EncryptData(CLEAR_TEXT_V5)
#Enable Warning S1481 ' Unused local variables should be removed
myEncryptor.Dispose()
Assert.Fail(TEXT_EXPECTED_EXCEPTION)
Catch ex As FileNotFoundException
If myEncryptor IsNot Nothing Then _
myEncryptor.Dispose()
Dim exceptionMessage As String = ex.Message()
Assert.IsTrue(exceptionMessage.Contains("does not exist"), GetUnexpectedExceptionMessage(ex))
Catch ex As Exception
If myEncryptor IsNot Nothing Then _
myEncryptor.Dispose()
Assert.Fail(GetUnexpectedExceptionMessage(ex))
End Try
End Sub
''' <summary>
''' Test if invalid file name throws an exception.
''' </summary>
<TestMethod()> Public Sub TestFileNameWithInvalidCharacters()
Dim myEncryptor As FileAndKeyEncryption = Nothing
Try
myEncryptor = New FileAndKeyEncryption(HMAC_KEY, "|<>&")
#Disable Warning S1481 ' Unused local variables should be removed
Dim encryptedText As String = myEncryptor.EncryptData(CLEAR_TEXT_V5)
#Enable Warning S1481 ' Unused local variables should be removed
myEncryptor.Dispose()
Assert.Fail(TEXT_EXPECTED_EXCEPTION)
Catch ex As FileNotFoundException
If myEncryptor IsNot Nothing Then _
myEncryptor.Dispose()
Dim exceptionMessage As String = ex.Message()
Assert.IsTrue(exceptionMessage.Contains("does not exist"), GetUnexpectedExceptionMessage(ex))
Catch ex As Exception
If myEncryptor IsNot Nothing Then _
myEncryptor.Dispose()
Assert.Fail(GetUnexpectedExceptionMessage(ex))
End Try
End Sub
''' <summary>
''' Test if null file name throws an exception.
''' </summary>
<TestMethod()> Public Sub TestNullFileName()
Dim myEncryptor As FileAndKeyEncryption = Nothing
Try
myEncryptor = New FileAndKeyEncryption(HMAC_KEY, Nothing)
#Disable Warning S1481 ' Unused local variables should be removed
Dim encryptedText As String = myEncryptor.EncryptData(CLEAR_TEXT_V5)
#Enable Warning S1481 ' Unused local variables should be removed
myEncryptor.Dispose()
Assert.Fail(TEXT_EXPECTED_EXCEPTION)
Catch ex As ArgumentNullException
If myEncryptor IsNot Nothing Then _
myEncryptor.Dispose()
Dim exceptionMessage As String = ex.Message()
Assert.IsTrue(exceptionMessage.Contains("keyFilePath"), GetUnexpectedExceptionMessage(ex))
Catch ex As Exception
If myEncryptor IsNot Nothing Then _
myEncryptor.Dispose()
Assert.Fail(GetUnexpectedExceptionMessage(ex))
End Try
End Sub
#End Region
#Region "Private methods"
''' <summary>
''' Get text for unexpected exceptions.
''' </summary>
''' <param name="ex">The unexpected exception</param>
''' <returns>Text that describes the unexpected exception.</returns>
Private Function GetUnexpectedExceptionMessage(ex As Exception) As String
Return TEXT_UNEXPECTED_EXCEPTION & ex.ToString() & TEXT_SEPARATOR & ex.Message() & TEXT_SEPARATOR & ex.StackTrace()
End Function
#End Region
End Class |
Imports Npgsql
Imports Common
Public Class UserDao
Inherits ConnectionToNpgsql
Public Function Login(email As String, pass As String) As Boolean
Using connection = GetConnection()
connection.Open()
Using command = New NpgsqlCommand()
command.Connection = connection
command.CommandText = "select *from users where email=@email and password=@pass"
command.Parameters.AddWithValue("@email", email)
command.Parameters.AddWithValue("@password", pass)
command.CommandType = CommandType.Text
Dim reader = command.ExecuteReader()
If reader.HasRows Then
While reader.Read() 'Obtenemos los datos de la columna y asignamos a los campos de usuario activo en cache'
ActiveUser.email = reader.GetString(0)
ActiveUser.password = reader.GetString(1)
End While
reader.Dispose()
Return True
Else
Return False
End If
End Using
End Using
End Function
End Class
|
Imports System
Namespace Route4MeSDK.QueryTypes.V5
''' <summary>
''' The telematics connection query parameters.
''' Used for create, update, get connectin(s).
''' </summary>
Public NotInheritable Class ConnectionParameters
Inherits GenericParameters
''' <summary>
''' Telemetics connection type. See "Enum.TelematicsVendorType".
''' </summary>
<HttpQueryMemberAttribute(Name:="vendor", EmitDefaultValue:=False)>
Public Property Vendor As String
''' <summary>
''' Telemetics connection type ID
''' </summary>
<HttpQueryMemberAttribute(Name:="vendor_id", EmitDefaultValue:=False)>
Public Property VendorId As Integer?
''' <summary>
''' Telemetics connection name
''' </summary>
<HttpQueryMemberAttribute(Name:="name", EmitDefaultValue:=False)>
Public Property Name As String
''' <summary>
''' Telematics connection access host.
''' </summary>
<HttpQueryMemberAttribute(Name:="host", EmitDefaultValue:=False)>
Public Property Host As String
''' <summary>
''' Telematics connection access api_key.
''' </summary>
<HttpQueryMemberAttribute(Name:="api_key", EmitDefaultValue:=False)>
Public Property ApiKey As String
''' <summary>
''' Telematics connection access account_id.
''' </summary>
<HttpQueryMemberAttribute(Name:="account_id", EmitDefaultValue:=False)>
Public Property AccountId As String
''' <summary>
''' Telematics connection access username
''' </summary>
<HttpQueryMemberAttribute(Name:="username", EmitDefaultValue:=False)>
Public Property UserName As String
''' <summary>
''' Telematics connection access password.
''' </summary>
<HttpQueryMemberAttribute(Name:="password", EmitDefaultValue:=False)>
Public Property Password As String
''' <summary>
''' Vehicle tracking interval in seconds (default value 60).
''' </summary>
<HttpQueryMemberAttribute(Name:="vehicle_position_refresh_rate", EmitDefaultValue:=False)>
Public Property VehiclePositionRefreshRate As Integer?
''' <summary>
''' Validate connections credentials.
''' </summary>
<HttpQueryMemberAttribute(Name:="validate_remote_credentials", EmitDefaultValue:=False)>
Public Property ValidateRemoteCredentials As Boolean?
''' <summary>
''' Disable/enable vehicle tracking.
''' </summary>
<HttpQueryMemberAttribute(Name:="is_enabled", EmitDefaultValue:=False)>
Public Property IsEnabled As Boolean?
''' <summary>
''' Metadata
''' </summary>
<HttpQueryMemberAttribute(Name:="metadata", EmitDefaultValue:=False)>
Public Property Metadata As String
''' <summary>
''' Telematics connection access token.
''' Required to show specified connection.
''' </summary>
<HttpQueryMemberAttribute(Name:="connection_token", EmitDefaultValue:=False)>
Public Property ConnectionToken As String
End Class
End Namespace
|
REM This is also a comment
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Do
'Step 1: Ask user for input
Console.WriteLine(Regex.Unescape("How Many Eggs \nwould you like?"))
'Step 2: Get text input from user
Dim user_input As String = Console.ReadLine
'Dim outside of the try block
Dim int_eggs
'Try to convert string to int
Try
'Step 3: Convert String to int
int_eggs = Integer.Parse(user_input)
Catch ex As Exception
'This only responds to FormatException
Console.WriteLine("That's not a number")
Console.ReadKey()
Continue Do
End Try
'Step 4: Respond with the number of eggs
Console.WriteLine("You bought {0}", int_eggs)
'Step 5: Wait for key press
Console.ReadKey()
'Exit the loop
Exit Do
Loop Until False
End Sub
End Module
|
'------------------------------------------------
' SysInfoFirstTry.vb (c) 2002 by Charles Petzold
'------------------------------------------------
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Class SysInfoFirstTry
Inherits Form
Shared Sub Main()
Application.Run(New SysInfoFirstTry())
End Sub
Sub New()
Text = "System Information: First Try"
BackColor = SystemColors.Window
ForeColor = SystemColors.WindowText
End Sub
Protected Overrides Sub OnPaint(ByVal pea As PaintEventArgs)
Dim grfx As Graphics = pea.Graphics
Dim br As New SolidBrush(ForeColor)
Dim y As Integer = 0
grfx.DrawString("ArrangeDirection: " & _
SystemInformation.ArrangeDirection.ToString(), _
Font, br, 0, y)
y += Font.Height
grfx.DrawString("ArrangeStartingPosition: " & _
SystemInformation.ArrangeStartingPosition.ToString(), _
Font, br, 0, y)
y += Font.Height
grfx.DrawString("BootMode: " & _
SystemInformation.BootMode.ToString(), _
Font, br, 0, y)
y += Font.Height
grfx.DrawString("Border3DSize: " & _
SystemInformation.Border3DSize.ToString(), _
Font, br, 0, y)
y += Font.Height
grfx.DrawString("BorderSize: " & _
SystemInformation.BorderSize.ToString(), _
Font, br, 0, y)
y += Font.Height
grfx.DrawString("CaptionButtonSize: " & _
SystemInformation.CaptionButtonSize.ToString(), _
Font, br, 0, y)
y += Font.Height
grfx.DrawString("CaptionHeight: " & _
SystemInformation.CaptionHeight.ToString(), _
Font, br, 0, y)
y += Font.Height
grfx.DrawString("ComputerName: " & _
SystemInformation.ComputerName.ToString(), _
Font, br, 0, y)
y += Font.Height
grfx.DrawString("CursorSize: " & _
SystemInformation.CursorSize.ToString(), _
Font, br, 0, y)
y += Font.Height
grfx.DrawString("DbcsEnabled: " & _
SystemInformation.DbcsEnabled.ToString(), _
Font, br, 0, y)
End Sub
End Class
|
Public Enum ChessBoardItem
Piece
Square
End Enum
|
Namespace Areas.Reports.Models
Public Class CampaignDashboardFilterTeamModel
Public Property TeamId As Integer
Public Property TeamName As String
End Class
End Namespace |
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''
'' Solicitud.vb
'' Implementation of the Class Solicitud
'' Generated by Enterprise Architect
'' Created on: 29-ago-2018 09:51:50 p.m.
'' Original author: Hernan
''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'' Modification history:
''
''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Option Explicit On
Public Class Solicitud
Public Shared Function getAll() As List(Of BE.Solicitud)
return Nothing
End Function
'''
''' <param name="id"></param>
Public Shared Function getOne(ByVal id As Integer) As TipoServicio
return Nothing
End Function
'''
''' <param name="obj"></param>
Public Shared Function add(ByVal obj As BE.Solicitud) As Boolean
add = False
End Function
'''
''' <param name="obj"></param>
Public Shared Function update(ByVal obj As BE.Solicitud) As Boolean
update = False
End Function
'''
''' <param name="obj"></param>
Public Shared Function canSave(ByVal obj As BE.Solicitud) As Boolean
canSave = False
End Function
Public Shared Function getPendientes() As List(Of BE.Solicitud)
getPendientes = Nothing
End Function
End Class ' Solicitud
|
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Namespace DTO
Public Class DTO_ThanhToan
Private _ma_thanh_toan As Integer
Private _ma_khach_hang As String
Private _ngay_thanh_toan As DateTime
Private _so_tien_thanh_toan As Single
Private _ma_hop_dong As String
Public Property ma_hop_dong() As String
Get
Return _ma_hop_dong
End Get
Set
_ma_hop_dong = value
End Set
End Property
Public Property ma_thanh_toan() As Integer
Get
Return _ma_thanh_toan
End Get
Set
_ma_thanh_toan = value
End Set
End Property
Public Property ma_khach_hang() As String
Get
Return _ma_khach_hang
End Get
Set
_ma_khach_hang = value
End Set
End Property
Public Property ngay_thanh_toan() As DateTime
Get
Return _ngay_thanh_toan
End Get
Set
_ngay_thanh_toan = value
End Set
End Property
Public Property so_tien_thanh_toan() As Single
Get
Return _so_tien_thanh_toan
End Get
Set
_so_tien_thanh_toan = value
End Set
End Property
End Class
End Namespace
|
'here will be more bypasses from my old project
Public Class pBypassList
Public Shared Classic As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Public Shared Unprintable As String = " "
End Class
|
#Region "Microsoft.VisualBasic::f33f9eae48f381a95f137203ec79dd95, mzkit\Rscript\Library\mzkit\annotations\library.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: 235
' Code Lines: 192
' Comment Lines: 5
' Blank Lines: 38
' File Size: 8.72 KB
' Module library
'
' Function: AddReference, asSpectrum, createAnnotation, createLibraryIO, createMetabolite
' createPrecursorIons, PopulateIonData, queryByMz, SaveResult
'
' /********************************************************************************/
#End Region
Imports System.Runtime.CompilerServices
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.mzData.mzWebCache
Imports BioNovoGene.Analytical.MassSpectrometry.Math
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Ms1
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Ms1.PrecursorType
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Spectra
Imports BioNovoGene.Analytical.MassSpectrometry.SpectrumTree
Imports BioNovoGene.BioDeep.Chemistry.MetaLib.Models
Imports BioNovoGene.BioDeep.Chemoinformatics.Formula
Imports Microsoft.VisualBasic.CommandLine.Reflection
Imports Microsoft.VisualBasic.Language
Imports Microsoft.VisualBasic.Linq
Imports Microsoft.VisualBasic.Scripting.MetaData
Imports SMRUCC.Rsharp.Runtime
Imports SMRUCC.Rsharp.Runtime.Components
Imports SMRUCC.Rsharp.Runtime.Internal.[Object]
Imports SMRUCC.Rsharp.Runtime.Interop
Imports SMRUCC.Rsharp.Runtime.Vectorization
Imports MetaData = BioNovoGene.BioDeep.Chemistry.MetaLib.Models.MetaInfo
''' <summary>
''' the metabolite annotation toolkit
''' </summary>
<Package("annotation")>
<RTypeExport("xref", GetType(xref))>
Module library
<ExportAPI("assert.adducts")>
<RApiReturn(GetType(MzCalculator))>
Public Function assertAdducts(formula As String,
<RRawVectorArgument>
adducts As Object,
Optional ion_mode As Object = "+",
Optional env As Environment = Nothing) As Object
Static asserts As New Dictionary(Of IonModes, PrecursorAdductsAssignRuler) From {
{IonModes.Positive, New PrecursorAdductsAssignRuler(IonModes.Positive)},
{IonModes.Negative, New PrecursorAdductsAssignRuler(IonModes.Negative)}
}
Dim ionVal = Math.GetIonMode(ion_mode, env)
Dim ruler = asserts(ionVal)
Dim precursors As MzCalculator() = Math.GetPrecursorTypes(adducts, env)
Return ruler.AssertAdducts(formula, precursors).ToArray
End Function
''' <summary>
''' a shortcut method for populate the peak ms2 data from a mzpack raw data file
''' </summary>
''' <param name="raw"></param>
''' <param name="mzdiff"></param>
''' <param name="env"></param>
''' <returns></returns>
<ExportAPI("populateIonData")>
<Extension>
<RApiReturn(GetType(PeakMs2))>
Public Function PopulateIonData(raw As mzPack,
Optional mzdiff As Object = "da:0.3",
Optional env As Environment = Nothing) As Object
Dim tolerance = Math.getTolerance(mzdiff, env)
If tolerance Like GetType(Message) Then
Return tolerance.TryCast(Of Message)
End If
Dim mzErr As Tolerance = tolerance.TryCast(Of Tolerance)
Dim ions As New List(Of PeakMs2)
For Each Ms1 As ScanMS1 In raw.MS
For Each ms2 In Ms1.products.SafeQuery
For Each mzi As Double In Ms1.mz
If mzErr(mzi, ms2.parentMz) Then
Dim ion2 As New PeakMs2 With {
.mz = mzi,
.rt = Ms1.rt,
.file = raw.source,
.lib_guid = ms2.scan_id,
.activation = ms2.activationMethod.Description,
.collisionEnergy = ms2.collisionEnergy,
.intensity = ms2.intensity,
.scan = ms2.scan_id,
.mzInto = ms2.GetMs.ToArray
}
Call ions.Add(ion2)
End If
Next
Next
Next
Return ions.ToArray
End Function
''' <summary>
''' create a new metabolite annotation information
''' </summary>
''' <param name="id"></param>
''' <param name="formula"></param>
''' <param name="name"></param>
''' <param name="synonym"></param>
''' <param name="xref"></param>
''' <returns></returns>
<ExportAPI("make.annotation")>
Public Function createAnnotation(id As String,
formula As String,
name As String,
Optional synonym As String() = Nothing,
Optional xref As xref = Nothing) As MetaData
Return New MetaData With {
.xref = If(xref, New xref),
.formula = formula,
.ID = id,
.name = name,
.synonym = synonym,
.exact_mass = CDbl(FormulaScanner.ScanFormula(formula))
}
End Function
<Extension>
Private Function ionsFromPeaktable(df As dataframe, env As Environment) As [Variant](Of Message, xcms2())
Dim id As String()
Dim println = env.WriteLineHandler
Call println("get data frame object for the ms1 ions features(with data fields):")
Call println(df.colnames)
If Not df.rownames Is Nothing Then
id = df.rownames
ElseIf df.hasName("xcms_id") Then
id = CLRVector.asCharacter(df("xcms_id"))
ElseIf df.hasName("ID") Then
id = CLRVector.asCharacter(df("ID"))
Else
Return Internal.debug.stop({
"missing the unique id of the ms1 ions in your dataframe!",
"required_one_of_field: xcms_id, ID"
}, env)
End If
Dim mz As Double() = CLRVector.asNumeric(df("mz"))
Dim rt As Double() = CLRVector.asNumeric(df("rt"))
Call println("get ms1 features unique id collection:")
Call println(id)
Return id _
.Select(Function(xcms_id, i)
Return New xcms2 With {
.ID = xcms_id,
.mz = mz(i),
.rt = rt(i)
}
End Function) _
.ToArray
End Function
''' <summary>
''' Check the ms1 parent ion is generated via the in-source fragment or not
''' </summary>
''' <param name="ms1">
''' the ms1 peaktable dataset, it could be a xcms peaktable object dataframe,
''' a collection of ms1 scan with unique id tagged.
''' </param>
''' <param name="ms2">
''' the ms2 products list
''' </param>
''' <param name="env"></param>
''' <returns>
''' a tuple key-value pair list object that contains the flags for each ms1 ion
''' corresponding slot value TRUE means the key ion is a possible in-source
''' fragment ion data, otherwise slot value FALSE means not.
''' </returns>
'''
<ExportAPI("checkInSourceFragments")>
<RApiReturn(GetType(Boolean))>
Public Function checkInSourceFragments(<RRawVectorArgument> ms1 As Object,
<RRawVectorArgument> ms2 As Object,
Optional da As Double = 0.1,
Optional rt_win As Double = 5,
Optional env As Environment = Nothing) As Object
Dim xcmsPeaks As xcms2()
Dim println = env.WriteLineHandler
If TypeOf ms1 Is dataframe Then
Dim pull = DirectCast(ms1, dataframe).ionsFromPeaktable(env)
If pull Like GetType(Message) Then
Return pull.TryCast(Of Message)
Else
xcmsPeaks = pull.TryCast(Of xcms2())
End If
Else
Dim ms1data = pipeline.TryCreatePipeline(Of xcms2)(ms1, env)
If ms1data.isError Then
Return ms1data.getError
End If
xcmsPeaks = ms1data _
.populates(Of xcms2)(env) _
.ToArray
End If
Dim ms2Products As pipeline = pipeline.TryCreatePipeline(Of PeakMs2)(ms2, env)
If ms2Products.isError Then
Return ms2Products.getError
End If
Dim check As New CheckInSourceFragments(ms2Products.populates(Of PeakMs2)(env), da)
Dim flags As New list With {.slots = New Dictionary(Of String, Object)}
For Each ms1_ion As xcms2 In xcmsPeaks
Call flags.add(
name:=ms1_ion.ID,
value:=check.CheckOfFragments(ms1_ion.mz, ms1_ion.rt, rt_win)
)
Next
Return flags
End Function
End Module
|
Imports System.Data.SqlClient
Namespace Base
''' <summary>
''' 2019.8.12
''' 操作数据库类库
''' </summary>
Public Class BaseSql
Inherits SecuriVerify(Of String, String, String)
#Region "类申明变量"
''' <summary>
''' 说明:错误信息记录
''' </summary>
''' <remarks></remarks>
Public MErrMessage As String
''' <summary>
''' 说明:'//过程及函数授权等级
''' </summary>
''' <remarks>只能在程序集或者派生类中访问</remarks>
Protected MProcLevel As EmpowerLevel
Property MConnectionTimeOut As Integer = 1200
#End Region
''' <summary>
''' 说明:设置超时时间
''' </summary>
''' <value></value>
''' <remarks></remarks>
Public WriteOnly Property ConnectionTimeOut As Integer
Set(value As Integer)
MConnectionTimeOut = value
End Set
End Property
''' <summary>
''' 返回错误信息
''' </summary>
''' <returns></returns>
Public Overrides ReadOnly Property ErrMessage As String
Get
Return MErrMessage
End Get
End Property
''' <summary>
''' 返回使用过程及函数授权等级
''' </summary>
''' <returns></returns>
Protected Overrides ReadOnly Property ProcLevel As EmpowerLevel
Get
Return MProcLevel
End Get
End Property
Protected Overrides ReadOnly Property SecuriPass As Integer
Get
Return MSecuriPass
End Get
End Property
#Region "类重构"
''' <summary>
''' 说明:重构
''' </summary>
''' <param name="vUserName">用户名</param>
''' <param name="vSecuriKey">类授权代码</param>
''' <param name="vProcKey">过程及函数使用授权码</param>
''' <remarks></remarks>
Public Sub New(ByVal vUserName As String, ByVal vSecuriKey As String, ByVal vProcKey As String)
MyBase.New(vUserName, vSecuriKey, vProcKey)
End Sub
''' <summary>
''' 说明:重构函数
''' </summary>
''' <param name="vUserSecurity">用户安全认证信息</param>
''' <remarks></remarks>
Public Sub New(ByVal vUserSecurity As UserSecurity)
MyBase.New(vUserSecurity.UserName, vUserSecurity.SecuriKey, vUserSecurity.ProcKey)
End Sub
#End Region
#Region "身份校验"
''' <summary>
''' 说明:进行类身份验证
''' </summary>
''' <param name="vUserName">用户名</param>
''' <param name="vCode">类授权验证码</param>
''' <returns>返回授权是否通过。1=通过,0=不通过</returns>
''' <remarks></remarks>
Friend Overrides Function CheckCode(vUserName As String, vCode As String) As Integer
Dim strPass As String
MSecuriPass = 0
Try
strPass = Entry.Decrypt(vUserName, "password", "drowssap") + Entry.Decrypt(vCode, "password", "drowssap")
Select Case strPass
Case "abcd1234"
MSecuriPass = 1
End Select
Catch ex As Exception
MErrMessage = ex.Message
End Try
Return MSecuriPass
End Function
''' <summary>
''' 说明:返回类中函数及过程授权等级
''' </summary>
''' <param name="vCode">函数及过程使用授权码</param>
''' <returns>返回授权等级</returns>
''' <remarks></remarks>
Friend Overrides Function ProcPermission(ByVal vCode As String) As EmpowerLevel
Dim vKey As String
MProcLevel = EmpowerLevel.Z
Try
vKey = Entry.Decrypt(vCode, "password", "drowssap")
Select Case vKey
Case "19001900"
MProcLevel = EmpowerLevel.A
Case "18001800"
MProcLevel = EmpowerLevel.B
Case Else
MProcLevel = EmpowerLevel.Z
End Select
Catch ex As Exception
ExportMessage(ex.Message)
End Try
Return MProcLevel
End Function
#End Region
#Region "类自定义函数及事件"
''' <summary>
''' 说明:输出消息,一般是错误信息居多
''' </summary>
''' <param name="vMsg"></param>
''' <remarks></remarks>
Protected Overrides Sub ExportMessage(ByVal vMsg As String)
MErrMessage = vMsg
End Sub
''' <summary>
''' 说明:释放链接
''' </summary>
''' <param name="vConn"></param>
''' <remarks></remarks>
Public Sub F_CancelConn(ByVal vConn As SqlConnection)
If (ConnectionState.Closed <> vConn.State) Then
vConn.Close()
vConn = Nothing '//销毁连接
End If
End Sub
''' <summary>
''' 作者: kevin zhu
''' 功能:销毁sql command
''' </summary>
''' <param name="vCmd">Sqlcommand参数</param>
''' <remarks></remarks>
Public Sub F_CancelCommand(ByVal vCmd As SqlCommand)
If Not IsNothing(vCmd) Then
vCmd.Dispose() '//销毁命令
vCmd = Nothing
End If
End Sub
#End Region
#Region "从数据库获取记录集"
''' <summary>
''' 说明:执行查询SQL语句,返回记录集内存库表DataTable
''' </summary>
''' <param name="commandText">数据库链接字符串</param>
''' <param name="commandType">命令类型</param>
''' <param name="commandParameters">SQL语句</param>
''' <param name="vConnection">数据库链接字符串</param>
''' <returns>返回内存库表DataTable</returns>
''' <remarks></remarks>
Public Overloads Function F_GetDataTable(
ByVal commandText As String,
ByVal commandType As CommandType,
ByVal commandParameters As SqlParameter(), ByVal vConnection As String) As DataTable
Dim dt As New DataTable
If MProcLevel > EmpowerLevel.D Then
ExportMessage("你无权限调用此函数")
Return dt
Else
'//数据库链接字符串
Dim cn As New SqlConnection(vConnection)
Dim ds As New DataSet
Try
If cn.State <> ConnectionState.Open Then
cn.Open()
End If
ds = ExecuteDataset(cn, commandType, commandText, commandParameters)
dt = ds.Tables(0)
Return dt
Finally
cn.Dispose()
End Try
Return dt
End If
End Function
''' <summary>
''' 说明:执行查询sqlcommand,返回记录集Dataset
''' </summary>
''' <param name="vSqlcon">sqlconnection参数</param>
''' <param name="vcommandType">命令类型</param>
''' <param name="vcommandText">SQL查询语句</param>
''' <param name="vSqlpara">参数数组</param>
''' <returns>数据记录集Dataset</returns>
''' <remarks></remarks>
Friend Overloads Function ExecuteDataset(ByVal vSqlcon As SqlConnection,
ByVal vcommandType As CommandType,
ByVal vcommandText As String,
ByVal ParamArray vSqlpara() As SqlParameter) As DataSet
Dim vSqlcmd As New SqlCommand()
Dim ds As New DataSet()
Dim da As SqlDataAdapter
Try
'//配置sqlcommand
'//如果连接未打开,则打开连接
If vSqlcon.State <> ConnectionState.Open Then
vSqlcon.Open()
End If
With vSqlcmd
'//设置sqlcommand对应数据库连接
.CommandTimeout = MConnectionTimeOut
.Connection = vSqlcon
.CommandText = vcommandText '//操作SQL命令
.CommandType = vcommandType '//命令操作类型
'//如果存在参数数组,则添加到sqlcommand
If Not (vSqlpara Is Nothing) Then
' AttachParameters(vSqlcmd, vSqlpara)
Dim p As SqlParameter
For Each p In vSqlpara
'//参数可输出也 可输入
If p.Direction = ParameterDirection.InputOutput And p.Value Is Nothing Then
p.Value = Nothing
End If
'对于存储过程,有些参数是输出
If p.Direction = ParameterDirection.Output Then
'//sqlcommand添加参数变量
vSqlcmd.Parameters.Add(p).Direction = ParameterDirection.Output
Else
'//sqlcommand添加参数变量
vSqlcmd.Parameters.Add(p)
End If
Next
End If
End With
'create the DataAdapter & DataSet
da = New SqlDataAdapter(vSqlcmd)
da.Fill(ds)
'//清理sqlpara
vSqlcmd.Parameters.Clear()
'关闭连接池
F_CancelConn(vSqlcon)
Catch ex As Exception
'//销毁链接及操作命令
F_CancelConn(vSqlcon)
F_CancelCommand(vSqlcmd)
ExportMessage(ex.Message) '传输错误信息出去
End Try
Return ds
End Function
#End Region
#Region "对数据库更新操作"
''' <summary>
''' 创建时间:2019.8.23
''' 说明:执行SQL命令,返回影响的记录数,执行错误返回-2
''' </summary>
''' <param name="vSqlcon">sqlconnection链接变量</param>
''' <param name="vCommandType">命令类型</param>
''' <param name="vCommandText">命令执行语句</param>
''' <param name="vSqlpara">参数数组</param>
''' <returns>执行是否成功,执行失败返回异常值-2</returns>
''' <remarks>程序集内部调用</remarks>
Friend Overloads Function ExecuteNonQuery(ByVal vSqlcon As SqlConnection,
ByVal vCommandType As CommandType,
ByVal vCommandText As String,
ByVal vSqlpara As SqlParameter()) As Integer
Dim vSqlcmd As New SqlCommand
Dim intsuc As Integer
Try
'//如果连接未打开,则打开连接
If vSqlcon.State <> ConnectionState.Open Then
vSqlcon.Open()
End If
With vSqlcmd
'//设置sqlcommand对应数据库连接
.CommandTimeout = MConnectionTimeOut
.Connection = vSqlcon
.CommandText = vCommandText '//操作SQL命令
.CommandType = vCommandType '//命令操作类型
'//如果存在参数数组,则添加到sqlcommand
If Not (vSqlpara Is Nothing) Then
' AttachParameters(vSqlcmd, vSqlpara)
Dim p As SqlParameter
For Each p In vSqlpara
'//参数可输出也 可输入
If p.Direction = ParameterDirection.InputOutput And p.Value Is Nothing Then
p.Value = Nothing
End If
'对于存储过程,有些参数是输出
If p.Direction = ParameterDirection.Output Then
'//sqlcommand添加参数变量
vSqlcmd.Parameters.Add(p).Direction = ParameterDirection.Output
Else
'//sqlcommand添加参数变量
vSqlcmd.Parameters.Add(p)
End If
Next
End If
End With
'//执行
intsuc = vSqlcmd.ExecuteNonQuery()
'//清理参数
vSqlcmd.Parameters.Clear()
'//释放连接池
F_CancelConn(vSqlcon)
Catch ex As Exception
ExportMessage(ex.Message)
F_CancelConn(vSqlcon)
intsuc = -2
End Try
Return intsuc
End Function
''' <summary>
''' 创建时间: 2019.8.23
''' 功能: 执行添加、删除、更新(无参数)操作,返回影响的记录数,执行错误返回-2
''' </summary>
''' <param name="vCommandText">SQL执行语句</param>
''' <param name="vCommandType">SQL语句类型,一般默认是语句,而不是存储过程</param>
''' <param name="vConnection">数据库链接字符串(可选)</param>
''' <returns>执行是否成功,执行失败返回异常值-2</returns>
''' <remarks></remarks>
Public Overloads Function F_UpdateSQLCommand(ByVal vCommandText As String, ByVal vCommandType As CommandType, ByVal vConnection As String) As Integer
Dim intsuc As Integer
If MProcLevel > EmpowerLevel.Z Then
ExportMessage(ErrorInfo.ErrorMessage(1))
intsuc = -2
Else
Dim cn As New SqlConnection(vConnection)
Try
If cn.State <> ConnectionState.Open Then
cn.Open()
End If
'//执行不带参数数组的sql命令
'//CType(Nothing, SqlParameter()),空白无用的参数数组字段
intsuc = ExecuteNonQuery(cn, vCommandType, vCommandText, CType(Nothing, SqlParameter()))
F_CancelConn(cn)
Catch ex As Exception
F_CancelConn(cn)
ExportMessage(ex.Message)
intsuc = -2
End Try
End If
Return intsuc
End Function
#End Region
End Class
End Namespace |
Imports Motor3D.Algebra
Imports Motor3D.Primitivas3D
Namespace Espacio3D.Transformaciones
Public Class Rotacion
Inherits Transformacion3D
Private mCuaternion As Cuaternion
Private mRotacion As Single
Private mSobreOrigen As Boolean
Private mTraslacion As Cuaternion
Private mVectorTraslacion As Vector3D
Public ReadOnly Property Cuaternion As Cuaternion
Get
Return mCuaternion
End Get
End Property
Public ReadOnly Property Rotacion As Single
Get
Return mRotacion
End Get
End Property
Public ReadOnly Property SobreOrigen As Boolean
Get
Return mSobreOrigen
End Get
End Property
Public ReadOnly Property Traslacion As Cuaternion
Get
Return mTraslacion
End Get
End Property
Public ReadOnly Property VectorTraslacion As Vector3D
Get
Return mVectorTraslacion
End Get
End Property
Public ReadOnly Property Eje As Vector3D
Get
Return mCuaternion.Vector
End Get
End Property
Public Sub New(ByVal Cuaternion As Cuaternion)
mCuaternion = Cuaternion
mMatriz = Cuaternion.Matriz
mRotacion = Cuaternion.ObtenerRotacion(Cuaternion)
mVectorTraslacion = New Vector3D
mTraslacion = New Cuaternion(mVectorTraslacion, 0, False)
mSobreOrigen = True
End Sub
Public Sub New(ByVal Rotacion As Single, ByVal Eje As EnumEjes)
Select Case Eje
Case EnumEjes.EjeX
mCuaternion = New Cuaternion(New Vector3D(1, 0, 0), Rotacion)
Case EnumEjes.EjeY
mCuaternion = New Cuaternion(New Vector3D(0, 1, 0), Rotacion)
Case EnumEjes.EjeZ
mCuaternion = New Cuaternion(New Vector3D(0, 0, 1), Rotacion)
End Select
mRotacion = Rotacion
mMatriz = mCuaternion.Matriz
mVectorTraslacion = New Vector3D
mTraslacion = New Cuaternion(mVectorTraslacion, 0, False)
mSobreOrigen = True
End Sub
Public Sub New(ByVal Rotacion As Single, ByVal Eje As EnumEjes, ByVal CentroRotacion As Punto3D)
Select Case Eje
Case EnumEjes.EjeX
mCuaternion = New Cuaternion(New Vector3D(1, 0, 0), Rotacion)
Case EnumEjes.EjeY
mCuaternion = New Cuaternion(New Vector3D(0, 1, 0), Rotacion)
Case EnumEjes.EjeZ
mCuaternion = New Cuaternion(New Vector3D(0, 0, 1), Rotacion)
End Select
mVectorTraslacion = New Vector3D(New Punto3D, CentroRotacion)
mTraslacion = New Cuaternion(mVectorTraslacion, 0, False)
'RECUERDA: El producto matricial al encadenar transformaciones es en el orden inverso:
mMatriz = New Traslacion(mVectorTraslacion).Matriz * mCuaternion.Matriz * New Traslacion(Not mVectorTraslacion).Matriz
mSobreOrigen = False
mRotacion = Rotacion
End Sub
Public Sub New(ByVal Cabeceo As Single, ByVal Alabeo As Single, ByVal Guiñada As Single)
mCuaternion = New Cuaternion(Cabeceo, Alabeo, Guiñada)
mMatriz = mCuaternion.Matriz
mVectorTraslacion = New Vector3D
mTraslacion = New Cuaternion(mVectorTraslacion, 0, False)
mSobreOrigen = True
mRotacion = 0
End Sub
Public Sub New(ByVal Angulos As AngulosEuler)
mCuaternion = New Cuaternion(Angulos)
mMatriz = mCuaternion.Matriz
mVectorTraslacion = New Vector3D
mTraslacion = New Cuaternion(mVectorTraslacion, 0, False)
mSobreOrigen = True
mRotacion = 0
End Sub
Public Sub New(ByVal Rotacion As Single, ByVal Eje As Vector3D)
mCuaternion = New Cuaternion(Eje, Rotacion)
mMatriz = mCuaternion.Matriz
mVectorTraslacion = New Vector3D
mTraslacion = New Cuaternion(mVectorTraslacion, 0, False)
mSobreOrigen = True
mRotacion = Rotacion
End Sub
Public Sub New(ByVal Rotacion As Single, ByVal Eje As Vector3D, ByVal CentroGiro As Punto3D)
mCuaternion = New Cuaternion(Eje, Rotacion)
mMatriz = mCuaternion.Matriz
mVectorTraslacion = New Vector3D(New Punto3D, CentroGiro)
mMatriz = New Traslacion(mVectorTraslacion).Matriz * mCuaternion.Matriz * New Traslacion(Not mVectorTraslacion).Matriz
mSobreOrigen = False
mRotacion = Rotacion
End Sub
Public Sub New(ByVal V1 As Vector3D, ByVal V2 As Vector3D)
Me.New(V1 ^ V2, V1 & V2)
End Sub
Public Sub New(ByVal V1 As Vector3D, ByVal V2 As Vector3D, ByVal CentroGiro As Punto3D)
Me.New(V1 ^ V2, V1 & V2, CentroGiro)
End Sub
Public Sub New(ByVal Rotacion As Single, ByVal Eje As Recta3D)
mCuaternion = New Cuaternion(Eje.VectorDirector, Rotacion)
If Eje.Pertenece(New Punto3D) Then
mVectorTraslacion = New Vector3D
mTraslacion = New Cuaternion(mVectorTraslacion, 0, False)
mMatriz = mCuaternion.Matriz
mSobreOrigen = True
Else
mVectorTraslacion = New Vector3D(New Punto3D, Recta3D.Proyeccion(New Punto3D, Eje))
mTraslacion = New Cuaternion(mVectorTraslacion, 0, False)
'RECUERDA: El producto matricial al encadenar transformaciones es en el orden inverso:
mMatriz = New Traslacion(mVectorTraslacion).Matriz * mCuaternion.Matriz * New Traslacion(Not mVectorTraslacion).Matriz
mSobreOrigen = False
End If
mRotacion = Rotacion
End Sub
#Region "AplicarTransformacion (DEBUGGING)"
Public Overloads Shared Function EncadenarTransformaciones(ByVal E1 As Rotacion, ByVal E2 As Rotacion) As Rotacion
Return New Rotacion(E1.Cuaternion * E2.Cuaternion)
End Function
Public Overloads Shared Function AplicarTransformacion(ByVal Punto As Punto3D, ByVal Rotacion As Rotacion) As Punto3D
If Rotacion.SobreOrigen Then
Return Cuaternion.ObtenerPunto(Rotacion.Cuaternion * New Cuaternion(Punto, False) * Not Rotacion.Cuaternion)
Else
Return Transformacion3D.AplicarTransformacion(Punto, Rotacion)
End If
End Function
Public Overloads Shared Function AplicarTransformacion(ByVal Vector As Vector3D, ByVal Rotacion As Rotacion) As Vector3D
If Rotacion.SobreOrigen Then
Return Cuaternion.ObtenerVector(Rotacion.Cuaternion * New Cuaternion(Vector, 0, False) * Not Rotacion.Cuaternion)
Else
Return Transformacion3D.AplicarTransformacion(Vector, Rotacion)
End If
End Function
Public Overloads Shared Function AplicarTransformacion(ByVal Vertice As Vertice, ByVal Rotacion As Rotacion) As Vertice
If Rotacion.SobreOrigen Then
Return New Vertice(Cuaternion.ObtenerPunto(Rotacion.Cuaternion * New Cuaternion(Vertice.CoodenadasSUR, False) * Not Rotacion.Cuaternion))
Else
Return Transformacion3D.AplicarTransformacion(Vertice, Rotacion)
End If
End Function
Public Overloads Shared Function AplicarTransformacion(ByVal Recta As Recta3D, ByVal Rotacion As Rotacion) As Recta3D
If Rotacion.SobreOrigen Then
Return New Recta3D(Cuaternion.ObtenerPunto(Rotacion.Cuaternion * New Cuaternion(Recta.PuntoInicial, False) * Not Rotacion.Cuaternion), Cuaternion.ObtenerVector(Rotacion.Cuaternion * New Cuaternion(Recta.VectorDirector, 0, False) * Not Rotacion.Cuaternion))
Else
Return Transformacion3D.AplicarTransformacion(Recta, Rotacion)
End If
End Function
Public Overloads Shared Function AplicarTransformacion(ByVal Plano As Plano3D, ByVal Rotacion As Rotacion) As Plano3D
Dim P As Punto3D = Plano.ObtenerPunto(0, 0)
If Rotacion.SobreOrigen Then
Return New Plano3D(Cuaternion.ObtenerPunto(Rotacion.Cuaternion * New Cuaternion(P, False) * Not Rotacion.Cuaternion), Cuaternion.ObtenerVector(Rotacion.Cuaternion * New Cuaternion(Plano.VectorNormal, 0, False) * Not Rotacion.Cuaternion))
Else
Transformacion3D.AplicarTransformacion(Plano, Rotacion)
End If
End Function
Public Overloads Shared Function AplicarTransformacion(ByVal AABB As AABB3D, ByVal Rotacion As Rotacion) As AABB3D
If Rotacion.SobreOrigen Then
Return New AABB3D(Cuaternion.ObtenerPunto(Rotacion.Cuaternion * New Cuaternion(AABB.Posicion, False) * Not Rotacion.Cuaternion), AABB.Dimensiones)
Else
Return Transformacion3D.AplicarTransformacion(AABB, Rotacion)
End If
End Function
Public Overloads Shared Function AplicarTransformacion(ByVal Segmento As Segmento3D, ByVal Rotacion As Rotacion) As Segmento3D
If Rotacion.SobreOrigen Then
Return New Segmento3D(Cuaternion.ObtenerPunto(Rotacion.Cuaternion * New Cuaternion(Segmento.ExtremoInicial, False) * Not Rotacion.Cuaternion), Cuaternion.ObtenerPunto(Rotacion.Cuaternion * New Cuaternion(Segmento.ExtremoFinal, False) * Not Rotacion.Cuaternion))
Else
Return Transformacion3D.AplicarTransformacion(Segmento, Rotacion)
End If
End Function
#End Region
Public Overloads Shared Function AplicarTransformacion(ByVal Poliedro As Poliedro, ByVal Rotacion As Rotacion) As Poliedro
Poliedro.AplicarTransformacion(Rotacion)
Return Poliedro
End Function
Public Overloads Shared Operator +(ByVal E1 As Rotacion, ByVal E2 As Rotacion) As Rotacion
Return EncadenarTransformaciones(E1, E2)
End Operator
Public Overloads Shared Operator *(ByVal Rotacion As Rotacion, ByVal Punto As Punto3D) As Punto3D
Return AplicarTransformacion(Punto, Rotacion)
End Operator
Public Overloads Shared Operator *(ByVal Punto As Punto3D, ByVal Rotacion As Rotacion) As Punto3D
Return AplicarTransformacion(Punto, Rotacion)
End Operator
Public Overloads Shared Operator *(ByVal Rotacion As Rotacion, ByVal Vector As Vector3D) As Vector3D
Return AplicarTransformacion(Vector, Rotacion)
End Operator
Public Overloads Shared Operator *(ByVal Vector As Vector3D, ByVal Rotacion As Rotacion) As Vector3D
Return AplicarTransformacion(Vector, Rotacion)
End Operator
Public Overloads Shared Operator *(ByVal Rotacion As Rotacion, ByVal Vertice As Vertice) As Vertice
Return AplicarTransformacion(Vertice, Rotacion)
End Operator
Public Overloads Shared Operator *(ByVal Vertice As Vertice, ByVal Rotacion As Rotacion) As Vertice
Return AplicarTransformacion(Vertice, Rotacion)
End Operator
Public Overloads Shared Operator *(ByVal Rotacion As Rotacion, ByVal Recta As Recta3D) As Recta3D
Return AplicarTransformacion(Recta, Rotacion)
End Operator
Public Overloads Shared Operator *(ByVal Recta As Recta3D, ByVal Rotacion As Rotacion) As Recta3D
Return AplicarTransformacion(Recta, Rotacion)
End Operator
Public Overloads Shared Operator *(ByVal Rotacion As Rotacion, ByVal Plano As Plano3D) As Plano3D
Return AplicarTransformacion(Plano, Rotacion)
End Operator
Public Overloads Shared Operator *(ByVal Plano As Plano3D, ByVal Rotacion As Rotacion) As Plano3D
Return AplicarTransformacion(Plano, Rotacion)
End Operator
Public Overloads Shared Operator *(ByVal Rotacion As Rotacion, ByVal AABB As AABB3D) As AABB3D
Return AplicarTransformacion(AABB, Rotacion)
End Operator
Public Overloads Shared Operator *(ByVal AABB As AABB3D, ByVal Rotacion As Rotacion) As AABB3D
Return AplicarTransformacion(AABB, Rotacion)
End Operator
Public Overloads Shared Operator *(ByVal Rotacion As Rotacion, ByVal Segmento As Segmento3D) As Segmento3D
Return AplicarTransformacion(Segmento, Rotacion)
End Operator
Public Overloads Shared Operator *(ByVal Segmento As Segmento3D, ByVal Rotacion As Rotacion) As Segmento3D
Return AplicarTransformacion(Segmento, Rotacion)
End Operator
Public Overloads Shared Operator *(ByVal Rotacion As Rotacion, ByVal Poliedro As Poliedro) As Poliedro
Return AplicarTransformacion(Poliedro, Rotacion)
End Operator
Public Overloads Shared Operator *(ByVal Poliedro As Poliedro, ByVal Rotacion As Rotacion) As Poliedro
Return AplicarTransformacion(Poliedro, Rotacion)
End Operator
End Class
End Namespace
|
#Region "Microsoft.VisualBasic::419fafa7f9f297b00dae4763680eae16, mzkit\src\mzmath\Mummichog\Permutation.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: 58
' Code Lines: 47
' Comment Lines: 0
' Blank Lines: 11
' File Size: 1.94 KB
' Module Permutation
'
' Function: CreateCombinations, GetRandom
'
' /********************************************************************************/
#End Region
Imports System.Runtime.CompilerServices
Imports Microsoft.VisualBasic.ComponentModel.Collection
Imports randf = Microsoft.VisualBasic.Math.RandomExtensions
Public Module Permutation
<Extension>
Public Iterator Function CreateCombinations(input As IEnumerable(Of MzSet), permutations As Integer) As IEnumerable(Of MzQuery())
Dim raw As MzSet() = input.ToArray
Dim block As New List(Of MzQuery)
Dim target As MzQuery
Dim filter As Index(Of String) = {}
Dim delta As Integer = permutations / 10
For i As Integer = 0 To permutations
Call filter.Clear()
Call block.Clear()
For Each mz As MzSet In raw
target = mz.GetRandom(filter)
If target Is Nothing Then
Continue For
End If
If Not target.unique_id Is Nothing Then
Call block.Add(target)
Call filter.Add(target.unique_id)
End If
Next
Yield block _
.GroupBy(Function(a) a.unique_id) _
.Select(Function(a) a.OrderBy(Function(v) v.ppm).First) _
.ToArray
If i Mod delta = 0 Then
Call VBDebugger.EchoLine($" -- {(i / permutations * 100).ToString("F2")}% [{i}/{permutations}]")
End If
Next
End Function
<Extension>
Private Function GetRandom(mzset As MzSet, filter As Index(Of String)) As MzQuery
Dim filters = mzset.query _
.Where(Function(a) Not a.unique_id Like filter) _
.ToArray
If filters.Length = 0 Then
Return Nothing
Else
Dim i As Integer = randf.NextInteger(mzset.size)
Dim target As MzQuery = mzset(i)
Return target
End If
End Function
End Module
|
Imports System.Drawing.Drawing2D
Public Class frmVlcFullSetup
#Region "GUI"
Private Sub frmMain_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles MyBase.Paint
e.Graphics.Clear(Color.DimGray)
e.Graphics.FillRectangle(New SolidBrush(Color.FromArgb(2, 15, 15)), New Rectangle(1, 1, Width - 2, Height - 2))
e.Graphics.SetClip(New Rectangle(1, 1, Width - 2, Height - 2))
Dim path As New GraphicsPath() : path.AddEllipse(New Rectangle(-100, -100, Width + 198, Height + 198))
Dim PGB As New PathGradientBrush(path)
PGB.CenterColor = Color.FromArgb(4, 35, 35) : PGB.SurroundColors = {Color.FromArgb(2, 15, 15)}
PGB.FocusScales = New Point(0.1F, 0.3F)
e.Graphics.FillPath(PGB, path)
e.Graphics.ResetClip()
Dim LGB As New LinearGradientBrush(New Rectangle(1, 16, 13, 55), Color.FromArgb(42, 177, 80), Color.FromArgb(49, 149, 178), 90.0F)
e.Graphics.FillRectangle(LGB, LGB.Rectangle)
End Sub
#End Region
#Region "Movable form"
Dim IsDraggingForm As Boolean = False
Private MousePos As New System.Drawing.Point(0, 0)
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseDown
If e.Button = MouseButtons.Left Then
IsDraggingForm = True
MousePos = e.Location
End If
End Sub
Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseUp
If e.Button = MouseButtons.Left Then IsDraggingForm = False
End Sub
Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseMove
If IsDraggingForm Then
Dim temp As Point = New Point(Me.Location + (e.Location - MousePos))
Me.Location = temp
temp = Nothing
End If
End Sub
#End Region
Private WithEvents setupVLC As SetupVLC
Private Const VLCRequiredVersion As String = "2.1.5"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub MetroButton1_Click(sender As Object, e As EventArgs) Handles MetroButton1.Click
setupVLC = New SetupVLC()
If setupVLC.IsVLCInstalled AndAlso setupVLC.VLCVersion <> VLCRequiredVersion Then 'If installed but wrong version
PanelManager1.SelectedPanel = PnlWrongVlcVersion
ElseIf setupVLC.IsVLCInstalled Then 'If installed and everything's fine
PanelManager1.SelectedPanel = PnlFinishSetup
ElseIf Not setupVLC.IsVLCInstalled AndAlso setupVLC.IsVLCAlreadyDownload Then 'if vlc's already downloaded
PanelManager1.SelectedPanel = PnlAlreadyDownload
Else
setupVLC.Setup()
PanelManager1.SelectedPanel = PnlDownloadVLC
End If
End Sub
Private Sub btnWaitInstallNext_Click(sender As Object, e As EventArgs) Handles btnWaitInstallNext.Click
If btnWaitInstallNext.Text <> "Waiting..." Then PanelManager1.SelectedPanel = PnlFinishSetup
End Sub
Private Sub setupVLC_VLCDownloadFinished(e As Exception) Handles setupVLC.VLCDownloadFinished
If e Is Nothing Then
PanelManager1.SelectedPanel = PnlLaunchSetup
Else
MessageBox.Show(e.Message, ".NET Streamer")
If IO.File.Exists(setupVLC.LocalPath) Then IO.File.Delete(setupVLC.LocalPath)
End If
End Sub
Private Sub setupVLC_VLCDownloadProgress(Progress As Integer, TimeLeft As String, Speed As String) Handles setupVLC.VLCDownloadProgress
lblPercentage.Text = String.Format("{0} %", Integer.Parse(Math.Truncate(Progress).ToString()))
pbProgress.Value = Progress
lblSpeed.Text = Speed
lblTimeLeft.Text = TimeLeft
End Sub
Private Sub setupVLC_VLCRegistered(path As String, e As Exception) Handles setupVLC.VLCRegistered
If e Is Nothing Then
lblPath.Text = String.Format("Path: {0}", path)
lblVersion.Text = "Version: 2.1.5"
lblInstalled.Text = "Installed: Successfully"
btnWaitInstallNext.Enabled = True
btnWaitInstallNext.Text = "Next"
btnWaitInstallNext.Invalidate()
Else
lblInstalled.Text = String.Format("Error: {0}", e.Message)
btnWaitInstallNext.Text = "Error."
End If
End Sub
Private Sub btnLaunchSetup_Click(sender As Object, e As EventArgs) Handles btnNextLaunchSetup.Click
setupVLC.LaunchSetupFile()
setupVLC.StartCheckForVLCIntallation()
PanelManager1.SelectedPanel = PnlWaitVlcInstallation
End Sub
Private Sub MetroButton2_Click(sender As Object, e As EventArgs) Handles btnNextAlreadyDownloaded.Click
setupVLC.LaunchSetupFile()
setupVLC.StartCheckForVLCIntallation()
PanelManager1.SelectedPanel = PnlWaitVlcInstallation
End Sub
Private Sub MetroButton2_Click_1(sender As Object, e As EventArgs) Handles MetroButton2.Click
frmMain.Show() : Me.Close()
End Sub
Private Sub btnUninstaller_Click(sender As Object, e As EventArgs) Handles btnUninstaller.Click
setupVLC.LaunchUninstaller()
setupVLC.StartCheckForVLCUnintallation()
PanelManager1.SelectedPanel = PnlWaitToUninstall
End Sub
Private Sub setupVLC_VLCUnregistered() Handles setupVLC.VLCUnregistered
lblUninstallStatus.Text = "Status: Sucessfull"
btnUninstallNext.Enabled = True
btnUninstallNext.Text = "Next"
btnUninstallNext.Invalidate()
End Sub
Private Sub btnUninstallNext_Click(sender As Object, e As EventArgs) Handles btnUninstallNext.Click
setupVLC.Setup()
If Not setupVLC.IsVLCInstalled AndAlso setupVLC.IsVLCAlreadyDownload Then 'if vlc's already downloaded
PanelManager1.SelectedPanel = PnlAlreadyDownload
Else
PanelManager1.SelectedPanel = PnlDownloadVLC
End If
End Sub
End Class
|
Option Explicit On
Option Strict On
Option Infer On
Public Module _01_05_04_Variablen_Typinferenz
Sub exe()
' Typinferenz: trotz strict kann auf den Datentypen verzichtet werden.
' Wird aus dem Typ des zugewiesenen Wertes hergeleitet
Dim meineVariableStrict As Double = 0.0
Dim meineVariable = 2.5
Dim deineVariable = 0
Dim eureVariable = "0"
'deineVariable = 5.8
deineVariable = CInt(5.8)
' Typinferenz verwässert die strengen Typisirungsregeln nicht !
' meineVariable = "1,2"
' Fehler ! Buchstabendreher führt zum impliziten Deklarieren einer neuen Variable
meineVariable = deineVariable + 1
' Ausgegeben wird im Direktfenster "Wert von meineVariable: 0" !
Debug.Print("Wert von meineVariable: " & meineVariable)
End Sub
End Module
|
#Region "Includes"
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Reflection
Imports System.Collections
#End Region
Public Class Comparator
Private _parents As New List(Of Object)()
Private obj1hashtable As New List(Of Object)()
Private obj2hashtable As New List(Of Object)()
#Region "Properties"
Private _objectName As String = ""
Public Property objectName() As String
Get
Return _objectName
End Get
Set(ByVal value As String)
_objectName = value
End Set
End Property
Private _maxDifferences As Integer = 100
Public Property MaxDifferences() As Integer
Get
Return _maxDifferences
End Get
Set(ByVal value As Integer)
_maxDifferences = value
End Set
End Property
Private _differences As New ComparatorDS.DTIPropDifferencesDataTable
Public ReadOnly Property differences() As ComparatorDS.DTIPropDifferencesDataTable
Get
Return _differences
End Get
End Property
#End Region
#Region "Shared methods"
Public Shared Function desearializeFromXMLString(ByVal row As ComparatorDS.DTIPropDifferencesRow) As Object
Try
Return desearializeFromXMLString(row.PropertyValue, row.PropertyType)
Catch ex As Exception
Return Nothing
End Try
End Function
Public Shared Function desearializeFromXMLString(ByVal xml As String, ByVal typename As String) As Object
Try
Dim x As New System.Xml.Serialization.XmlSerializer(Type.GetType(typename))
Dim strm As New System.IO.StringReader(xml)
Dim ret As Object = x.Deserialize(strm)
Return ret
Catch ex As Exception
End Try
Return Nothing
End Function
Public Shared Function searializeToXMLString(ByVal obj As Object) As String
Try
Dim x As New System.Xml.Serialization.XmlSerializer(obj.GetType)
Dim strm As New System.IO.StringWriter
x.Serialize(strm, obj)
Return strm.ToString
Catch ex As Exception
End Try
Return Nothing
End Function
Public Shared Function desearializeFromBase64String(ByVal row As ComparatorDS.DTIPropDifferencesRow) As Object
Try
Return desearializeFromBase64String(row.PropertyValue)
Catch ex As Exception
Return Nothing
End Try
End Function
Public Shared Function desearializeFromBase64String(ByVal obj As String) As Object
Try
Using stream As New System.IO.MemoryStream(Convert.FromBase64String(obj))
Dim formatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Return formatter.Deserialize(stream)
End Using
Catch
End Try
Return Nothing
End Function
Public Shared Function searializeToBase64String(ByVal obj As Object) As String
Try
Using stream As New System.IO.MemoryStream()
Dim formatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
formatter.Serialize(stream, obj)
Return Convert.ToBase64String(stream.ToArray())
End Using
Catch
End Try
Return Nothing
End Function
Public Shared Function CompareObjects(ByVal obj1 As Object, ByVal obj2 As Object, Optional ByRef maximumDifferences As Integer = 100) As Comparator
Dim c As New Comparator
c.Compare(obj1, obj2)
Return c
End Function
Public Shared Sub setProperties(ByVal dt As ComparatorDS.DTIPropDifferencesDataTable, ByRef instance As Object, Optional ByRef session As System.Web.SessionState.HttpSessionState = Nothing)
Dim propc As PropertyCreator = getPropertyCreator(session)
For Each row As ComparatorDS.DTIPropDifferencesRow In dt
Try
'setProperty(row, instance)
propc.SetValue(instance, row.PropertyPath, desearializeFromBase64String(row))
Catch ex As Exception
End Try
Next
End Sub
' Public Shared Sub setProperty(ByVal row As ComparatorDS.DifferencesRow, ByRef instance As Object, Optional ByVal session As System.Web.SessionState.HttpSessionState = Nothing)
' setProperty(row.PropertyPath, desearializeFromBase64String(row), instance)
' End Sub
' Public Shared Sub setProperty(ByVal propertyPath As String, ByVal newval As Object, ByRef instance As Object, Optional ByVal session As System.Web.SessionState.HttpSessionState = Nothing)
' Dim propc As PropertyCreator = getPropertyCreator(session)
'propc.SetValue(instance,
' End Sub
Private Shared Function getPropertyCreator(ByVal session As System.Web.SessionState.HttpSessionState) As PropertyCreator
If session Is Nothing Then
Return New PropertyCreator
End If
If session("propertyCreatorCache") Is Nothing Then
session("propertyCreatorCache") = New PropertyCreator
End If
Return session("propertyCreatorCache")
End Function
'Public Shared Sub SetProperties(ByVal fromFields As PropertyInfo(), ByVal toFields As PropertyInfo(), ByVal fromRecord As Object, ByVal toRecord As Object)
' Dim fromField As PropertyInfo = Nothing
' Dim toField As PropertyInfo = Nothing
' Try
' If fromFields Is Nothing Then Exit Sub
' If toFields Is Nothing Then Exit Sub
' For f As Integer = 0 To fromFields.Length - 1
' fromField = DirectCast(fromFields(f), PropertyInfo)
' For t As Integer = 0 To toFields.Length - 1
' toField = DirectCast(toFields(t), PropertyInfo)
' If fromField.Name <> toField.Name Then
' Continue For
' End If
' toField.SetValue(toRecord, fromField.GetValue(fromRecord, Nothing), Nothing)
' Exit For
' Next
' Next
' Catch generatedExceptionName As Exception
' Throw
' End Try
'End Sub
'Public Shared Function SetProperties(Of T)(ByVal fromRecord As T, ByVal toRecord As T) As T
' For Each field As PropertyInfo In GetType(T).GetProperties()
' field.SetValue(toRecord, field.GetValue(fromRecord, Nothing), Nothing)
' Next
' Return toRecord
'End Function
'Public Shared Function SetProperties(Of T, U)(ByVal fromRecord As U, ByVal toRecord As T) As T
' For Each fromField As PropertyInfo In GetType(U).GetProperties()
' If fromField.Name <> "Id" Then
' For Each toField As PropertyInfo In GetType(T).GetProperties()
' If fromField.Name = toField.Name Then
' toField.SetValue(toRecord, fromField.GetValue(fromRecord, Nothing), Nothing)
' Exit For
' End If
' Next
' End If
' Next
' Return toRecord
'End Function
#End Region
#Region "Public Methods"
Public Sub New(ByVal objName As String)
Me.objectName = objName
End Sub
Public Sub New()
End Sub
Public Function Compare(ByVal object1 As Object, ByVal object2 As Object) As Boolean
Dim defaultBreadCrumb As String = String.Empty
differences.Clear()
Compare(object1, object2, defaultBreadCrumb)
Return differences.Count = 0
End Function
Public Function DiffList() As String
Dim str As String = ""
For Each row As ComparatorDS.DTIPropDifferencesRow In differences
Dim val As Object = desearializeFromXMLString(row)
If val Is Nothing Then val = "{null}"
str &= row.PropertyPath & " : " & val.ToString & vbCrLf
Next
Return str
End Function
#End Region
#Region "Helper Methods"
Private Sub Compare(ByVal object1 As Object, ByVal object2 As Object, ByRef breadCrumb As String)
'If both null return true
If object1 Is Nothing AndAlso object2 Is Nothing Then
Exit Sub
End If
If object1 Is Nothing OrElse object2 Is Nothing Then
addDifference(breadCrumb, object2)
Exit Sub
End If
If obj1hashtable.Contains(object1) Then Exit Sub
If obj2hashtable.Contains(object2) Then Exit Sub
obj1hashtable.Add(object1)
obj2hashtable.Add(object2)
Dim t1 As Type = object1.[GetType]()
Dim t2 As Type = object2.[GetType]()
'Objects must be the same type
If t1 IsNot t2 Then
addDifference(breadCrumb, object2)
Exit Sub
End If
If IsIList(t1) Then
'This will do arrays, multi-dimensional arrays and generic lists
CompareIList(object1, object2, breadCrumb)
ElseIf IsIDictionary(t1) Then
CompareIDictionary(object1, object2, breadCrumb)
ElseIf IsEnum(t1) Then
CompareEnum(object1, object2, breadCrumb)
ElseIf IsSimpleType(t1) Then
CompareSimpleType(object1, object2, breadCrumb)
ElseIf IsClass(t1) Then
CompareClass(object1, object2, breadCrumb)
ElseIf IsTimespan(t1) Then
CompareTimespan(object1, object2, breadCrumb)
ElseIf IsStruct(t1) Then
CompareStruct(object1, object2, breadCrumb)
Else
Throw New NotImplementedException("Cannot compare object of type " & t1.Name)
End If
End Sub
#Region "Type Checks"
Private Function IsTimespan(ByVal t As Type) As Boolean
Return t Is GetType(TimeSpan)
End Function
Private Function IsEnum(ByVal t As Type) As Boolean
Return t.IsEnum
End Function
Private Function IsStruct(ByVal t As Type) As Boolean
Return t.IsValueType
End Function
Private Function IsSimpleType(ByVal t As Type) As Boolean
Return t.IsPrimitive OrElse t Is GetType(DateTime) OrElse t Is GetType(Decimal) OrElse t Is GetType(String) OrElse t Is GetType(Guid)
End Function
Private Function ValidStructSubType(ByVal t As Type) As Boolean
Return IsSimpleType(t) OrElse IsEnum(t) OrElse IsArray(t) OrElse IsClass(t) OrElse IsIDictionary(t) OrElse IsTimespan(t) OrElse IsIList(t)
End Function
Private Function IsArray(ByVal t As Type) As Boolean
Return t.IsArray
End Function
Private Function IsClass(ByVal t As Type) As Boolean
Return t.IsClass
End Function
Private Function IsIDictionary(ByVal t As Type) As Boolean
Return t.GetInterface("System.Collections.IDictionary", True) IsNot Nothing
End Function
Private Function IsIList(ByVal t As Type) As Boolean
Return t.GetInterface("System.Collections.IList", True) IsNot Nothing
End Function
#End Region
#Region "Comparators"
Private Sub CompareTimespan(ByVal object1 As Object, ByVal object2 As Object, ByRef breadCrumb As String)
If DirectCast(object1, TimeSpan).Ticks <> DirectCast(object2, TimeSpan).Ticks Then
addDifference(breadCrumb, object2)
End If
End Sub
Private Sub CompareEnum(ByVal object1 As Object, ByVal object2 As Object, ByRef breadCrumb As String)
If object1.ToString() <> object2.ToString() Then
Dim currentBreadCrumb As String = AddBreadCrumb(breadCrumb, object1.[GetType]().Name, String.Empty, -1)
addDifference(currentBreadCrumb, object2)
End If
End Sub
Private Sub CompareSimpleType(ByVal object1 As Object, ByVal object2 As Object, ByRef breadCrumb As String)
Dim valOne As IComparable = TryCast(object1, IComparable)
If valOne.CompareTo(object2) <> 0 Then
addDifference(breadCrumb, object2)
End If
End Sub
Private Sub CompareStruct(ByVal object1 As Object, ByVal object2 As Object, ByRef breadCrumb As String)
Dim currentCrumb As String
Dim t1 As Type = object1.[GetType]()
'Compare the fields
Dim currentFields As FieldInfo() = t1.GetFields()
For Each item As FieldInfo In currentFields
'Only compare simple types within structs (Recursion Problems)
If Not ValidStructSubType(item.FieldType) Then
Continue For
End If
currentCrumb = AddBreadCrumb(breadCrumb, item.Name, String.Empty, -1)
Compare(item.GetValue(object1), item.GetValue(object2), currentCrumb)
If differences.Count >= MaxDifferences Then
Exit Sub
End If
Next
End Sub
Private Sub CompareClass(ByVal object1 As Object, ByVal object2 As Object, ByRef breadCrumb As String)
Dim currentCrumb As String
Dim objectValue1 As Object
Dim objectValue2 As Object
Try
_parents.Add(object1)
_parents.Add(object2)
Dim t1 As Type = object1.[GetType]()
'Compare the properties
Dim currentProperties As PropertyInfo() = t1.GetProperties()
'PropertyInfo[] currentProperties = t1.GetProperties(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance);
Dim properties As ComponentModel.PropertyDescriptorCollection = ComponentModel.TypeDescriptor.GetProperties(object1)
'For Each info As PropertyInfo In currentProperties
For Each info As ComponentModel.PropertyDescriptor In properties
Try
If info.IsBrowsable = False Then
Continue For
End If
objectValue1 = info.GetValue(object1)
objectValue2 = info.GetValue(object2)
Dim object1IsParent As Boolean = objectValue1 IsNot Nothing AndAlso (objectValue1 Is object1 OrElse _parents.Contains(objectValue1))
Dim object2IsParent As Boolean = objectValue2 IsNot Nothing AndAlso (objectValue2 Is object2 OrElse _parents.Contains(objectValue2))
'Skip properties where both point to the corresponding parent
If IsClass(info.PropertyType) AndAlso (object1IsParent AndAlso object2IsParent) Then
Continue For
End If
currentCrumb = AddBreadCrumb(breadCrumb, info.Name, String.Empty, -1)
Compare(objectValue1, objectValue2, currentCrumb)
If differences.Count >= MaxDifferences Then
Exit Sub
End If
Catch ex As Exception
End Try
Next
Dim currentFields As FieldInfo() = t1.GetFields()
'FieldInfo[] currentFields = t1.GetFields(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance);
For Each item As FieldInfo In currentFields
objectValue1 = item.GetValue(object1)
objectValue2 = item.GetValue(object2)
Dim object1IsParent As Boolean = objectValue1 IsNot Nothing AndAlso (objectValue1 = object1 OrElse _parents.Contains(objectValue1))
Dim object2IsParent As Boolean = objectValue2 IsNot Nothing AndAlso (objectValue2 = object2 OrElse _parents.Contains(objectValue2))
'Skip fields that point to the parent
If IsClass(item.FieldType) AndAlso (object1IsParent OrElse object2IsParent) Then
Continue For
End If
currentCrumb = AddBreadCrumb(breadCrumb, item.Name, String.Empty, -1)
Compare(objectValue1, objectValue2, currentCrumb)
If differences.Count >= MaxDifferences Then
Exit Sub
End If
Next
Finally
_parents.Remove(object1)
_parents.Remove(object2)
End Try
End Sub
Private Sub CompareIDictionary(ByVal object1 As Object, ByVal object2 As Object, ByRef breadCrumb As String)
Dim iDict1 As IDictionary = TryCast(object1, IDictionary)
Dim iDict2 As IDictionary = TryCast(object2, IDictionary)
'Objects must be the same length
If iDict1.Count <> iDict2.Count Then
addDifference(breadCrumb, object2)
If differences.Count >= MaxDifferences Then
Exit Sub
End If
End If
Dim enumerator1 As IDictionaryEnumerator = iDict1.GetEnumerator()
Dim enumerator2 As IDictionaryEnumerator = iDict2.GetEnumerator()
Dim count As Integer = 0
While enumerator1.MoveNext() AndAlso enumerator2.MoveNext()
Dim currentBreadCrumb As String = AddBreadCrumb(breadCrumb, "Key", String.Empty, -1)
Compare(enumerator1.Key, enumerator2.Key, currentBreadCrumb)
If differences.Count >= MaxDifferences Then
Exit Sub
End If
currentBreadCrumb = AddBreadCrumb(breadCrumb, "Value", String.Empty, -1)
Compare(enumerator1.Value, enumerator2.Value, currentBreadCrumb)
If differences.Count >= MaxDifferences Then
Exit Sub
End If
count += 1
End While
End Sub
Private Sub CompareIList(ByVal object1 As Object, ByVal object2 As Object, ByRef breadCrumb As String)
Dim ilist1 As IList = TryCast(object1, IList)
Dim ilist2 As IList = TryCast(object2, IList)
'Objects must be the same length
If ilist1.Count <> ilist2.Count Then
addDifference(breadCrumb, object2)
If differences.Count >= MaxDifferences Then
Exit Sub
End If
End If
Dim enumerator1 As IEnumerator = ilist1.GetEnumerator()
Dim enumerator2 As IEnumerator = ilist2.GetEnumerator()
Dim count As Integer = 0
While enumerator1.MoveNext() AndAlso enumerator2.MoveNext()
Dim currentBreadCrumb As String = AddBreadCrumb(breadCrumb, String.Empty, String.Empty, count)
Compare(enumerator1.Current, enumerator2.Current, currentBreadCrumb)
If differences.Count >= MaxDifferences Then
Exit Sub
End If
count += 1
End While
End Sub
#End Region
Private Function [cStr](ByVal obj As Object) As String
Try
If obj Is Nothing Then
Return "(null)"
ElseIf obj Is System.DBNull.Value Then
Return "System.DBNull.Value"
Else
Return obj.ToString()
End If
Catch
Return String.Empty
End Try
End Function
Public Sub addDifference(ByVal location As String, ByVal value As Object, Optional ByVal oldval As Object = Nothing, Optional ByVal mainid As Integer = 0)
If location Is Nothing Then Exit Sub
location = location.Trim(New Char() {"."})
If value Is Nothing Then
differences.AddDTIPropDifferencesRow(location, Nothing, Nothing, objectName, mainid)
Else
Dim base63EncodedValue As String = searializeToBase64String(value)
If Not base63EncodedValue Is Nothing Then
differences.AddDTIPropDifferencesRow(location, base63EncodedValue, value.GetType.AssemblyQualifiedName, objectName, mainid)
End If
End If
End Sub
Private Function AddBreadCrumb(ByVal existing As String, ByVal name As String, ByVal extra As String, ByVal index As Integer) As String
Dim useIndex As Boolean = index >= 0
Dim useName As Boolean = name.Length > 0
Dim sb As New StringBuilder()
sb.Append(existing)
If useName Then
sb.AppendFormat(".")
sb.Append(name)
End If
sb.Append(extra)
If useIndex Then
sb.AppendFormat("[{0}]", index)
End If
Return sb.ToString()
End Function
#End Region
End Class
|
Imports DevExpress.XtraBars.Docking2010
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Views.Grid
Imports RTIS.CommonVB
Imports RTIS.Elements
Public Class frmPaySlipDetails
Private pController As fccPaySlipDetails
Private pIsActive As Boolean
Public Shared Sub OpenFormMDI(ByRef rMDI As Windows.Forms.Form, ByRef rDBConn As RTIS.DataLayer.clsDBConnBase, ByRef rRTISGlobal As clsRTISGlobal)
Dim mfrm As frmPaySlipDetails
mfrm = New frmPaySlipDetails
mfrm.pController = New fccPaySlipDetails(rDBConn, rRTISGlobal)
mfrm.MdiParent = rMDI
mfrm.Show()
End Sub
Private Sub RefreshControls()
Dim mIsActive As Boolean
mIsActive = pIsActive
pIsActive = False
datPeriodStart.DateTime = pController.PeriodStartDate
radPayPeriodType.EditValue = CInt(pController.PeriodType)
datStartDateStd.DateTime = pController.StandardStartDate
datEndDateStd.DateTime = pController.StandardEndDate
datStartDateOT.DateTime = pController.OverTimeStartDate
datEndDateOT.DateTime = pController.OverTimeEndDate
If pController.Employee IsNot Nothing Then
RTIS.Elements.clsDEControlLoading.SetDECombo(cboEmployee, pController.Employee.EmployeeID)
End If
pIsActive = mIsActive
End Sub
Private Sub UpdateObjects()
pController.PeriodStartDate = datPeriodStart.DateTime
pController.PeriodType = radPayPeriodType.EditValue
pController.StandardStartDate = datStartDateStd.DateTime
pController.StandardEndDate = datEndDateStd.DateTime
pController.OverTimeStartDate = datStartDateOT.DateTime
pController.OverTimeEndDate = datEndDateOT.DateTime
pController.SetCurrentEmployee(RTIS.Elements.clsDEControlLoading.GetDEComboValue(cboEmployee))
End Sub
Private Sub frmOverTime_Load(sender As Object, e As EventArgs) Handles Me.Load
pIsActive = False
pController.PeriodType = ePayPeriodType.Quincena
grdPaySlipItems.DataSource = pController.PaySlipItems
LoadCombos()
RefreshControls()
pIsActive = True
End Sub
Private Sub LoadCombos()
RTIS.Elements.clsDEControlLoading.FillDEComboVI(cboEmployee, AppRTISGlobal.GetInstance.RefLists.RefListVI(appRefLists.Employees))
End Sub
Private Sub CloseForm() 'Needs exit mode set first
Me.Close()
End Sub
Private Sub GridControl1_Click(sender As Object, e As EventArgs) Handles grdPaySlipItems.Click
End Sub
Private Sub grpPeriodAndEmployee_CustomButtonClick(sender As Object, e As BaseButtonEventArgs) Handles grpPeriodAndEmployee.CustomButtonClick
Select Case e.Button.Properties.Tag
Case "Load"
UpdateObjects()
pController.LoadPaySlipItems()
gvPaySlipItems.RefreshData()
Case "Print"
repPaySlip.OpenReportPrintPreview(pController.PaySlipItems, pController.Employee, pController.StandardStartDate, pController.StandardEndDate, pController.PeriodType, pController.GetEmployeeRateOfPay)
End Select
End Sub
Private Sub gvPaySlipItems_RowStyle(sender As Object, e As RowStyleEventArgs) Handles gvPaySlipItems.RowStyle
Dim mPSI As clsPaySlipItem
mPSI = TryCast(gvPaySlipItems.GetRow(e.RowHandle), clsPaySlipItem)
If mPSI IsNot Nothing Then
Select Case mPSI.ItemDate.DayOfWeek
Case DayOfWeek.Saturday, DayOfWeek.Sunday
e.Appearance.BackColor = Color.WhiteSmoke
End Select
End If
End Sub
Private Sub datPeriodStart_EditValueChanged(sender As Object, e As EventArgs) Handles datPeriodStart.EditValueChanged
Try
If pIsActive Then
UpdateObjects()
pController.ResetDefaultDates()
RefreshControls()
End If
Catch ex As Exception
If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyUserInterface) Then Throw
End Try
End Sub
Private Sub gvPaySlipItems_RowCellStyle(sender As Object, e As RowCellStyleEventArgs) Handles gvPaySlipItems.RowCellStyle
Dim mPSI As clsPaySlipItem
mPSI = TryCast(gvPaySlipItems.GetRow(e.RowHandle), clsPaySlipItem)
If mPSI IsNot Nothing Then
Select Case e.Column.Name
Case gcStandardHrs.Name, gcStandardPay.Name
If mPSI.InStandardRange = False Then
e.Appearance.BackColor = Color.DarkGray
End If
Case gcOTHrs.Name, gcOTPay.Name
If mPSI.InOverTimeRange = False Then
e.Appearance.BackColor = Color.DarkGray
End If
Case gcTotalPay.Name
If mPSI.InStandardRange = False And mPSI.InOverTimeRange = False Then
e.Appearance.BackColor = Color.DarkGray
End If
End Select
End If
End Sub
Private Sub radPayPeriodType_EditValueChanged(sender As Object, e As EventArgs) Handles radPayPeriodType.EditValueChanged
Try
If pIsActive Then
UpdateObjects()
pController.ResetDefaultDates()
RefreshControls()
End If
Catch ex As Exception
If clsErrorHandler.HandleError(ex, clsErrorHandler.PolicyUserInterface) Then Throw
End Try
End Sub
Private Sub cboEmployee_EditValueChanged(sender As Object, e As EventArgs) Handles cboEmployee.EditValueChanged
End Sub
Private Sub cboEmployee_SelectedValueChanged(sender As Object, e As EventArgs) Handles cboEmployee.SelectedValueChanged
Dim mSalary As Decimal
Dim mStdSalary As Decimal
Dim mOverTime As Decimal
UpdateObjects()
mSalary = pController.GetEmployeeRateOfPay()
mStdSalary = Math.Round((mSalary / 30 / 8), 2)
mOverTime = Math.Round(mStdSalary * 2, 2)
If mSalary > 0 Then
txtSalary.Text = mSalary.ToString()
txtStdSalary.Text = mStdSalary.ToString()
txtOverTime.Text = mOverTime.ToString()
Else
txtStdSalary.Text = ""
txtSalary.Text = ""
txtOverTime.Text = ""
End If
End Sub
End Class |
Module Module1
Dim Stack(8) As Integer
Const FullStack = 8
Const BaseOfStackPointer = 0
Dim TopOfStackPointer = -1
Const NullPointer = -1
Sub Main()
Dim choice, Value As Integer
Do
Console.Clear()
Console.WriteLine("1. Push to stack.")
Console.WriteLine("2. Pop from stack.")
Console.WriteLine("3. Exit program.")
Do
Console.Write("Enter your choice 1..3 : ")
choice = Console.ReadLine
Loop Until choice >= 1 And choice <= 3
Select Case choice
Case 1 : Call Push()
Case 2
Value = Pop()
If Value = -1 Then
Console.WriteLine("Underflow, Stack is empty. No value to pop.")
Console.ReadKey()
Else
Console.WriteLine("Stack Value Poped : " & Value)
Console.ReadKey()
End If
End Select
Loop Until choice = 3
End Sub
Sub Push()
Dim Value As Integer
If TopOfStackPointer = FullStack Then
Console.WriteLine("Overflow, Stack is full. No more value can be added.")
Console.ReadKey()
Else
Console.Write("Enter value to add to stack: ")
Value = Console.ReadLine
TopOfStackPointer = TopOfStackPointer + 1
Stack(TopOfStackPointer) = Value
End If
End Sub
Function Pop() As Integer
Dim Value As Integer
If TopOfStackPointer = NullPointer Then
Value = NullPointer
Else
Value = Stack(TopOfStackPointer)
TopOfStackPointer = TopOfStackPointer - 1
End If
Return Value
End Function
End Module
|
Imports System.Text.RegularExpressions
Public Class Translite
Public Enum TransliterationType
GOST
ISO
End Enum
Private GOST_CHARS As New Dictionary(Of String, String) From {
{"Є", "EH"},
{"№", "#"},
{"є", "eh"},
{"А", "A"},
{"Б", "B"},
{"В", "V"},
{"Г", "G"},
{"Д", "D"},
{"Е", "E"},
{"Ё", "JO"},
{"Ж", "ZH"},
{"З", "Z"},
{"И", "I"},
{"Й", "JJ"},
{"К", "K"},
{"Л", "L"},
{"М", "M"},
{"Н", "N"},
{"О", "O"},
{"П", "P"},
{"Р", "R"},
{"С", "S"},
{"Т", "T"},
{"У", "U"},
{"Ф", "F"},
{"Х", "KH"},
{"Ц", "C"},
{"Ч", "CH"},
{"Ш", "SH"},
{"Щ", "SHH"},
{"Ъ", "'"},
{"Ы", "Y"},
{"Ь", ""},
{"Э", "EH"},
{"Ю", "YU"},
{"Я", "YA"},
{"а", "a"},
{"б", "b"},
{"в", "v"},
{"г", "g"},
{"д", "d"},
{"е", "e"},
{"ё", "jo"},
{"ж", "zh"},
{"з", "z"},
{"и", "i"},
{"й", "jj"},
{"к", "k"},
{"л", "l"},
{"м", "m"},
{"н", "n"},
{"о", "o"},
{"п", "p"},
{"р", "r"},
{"с", "s"},
{"т", "t"},
{"у", "u"},
{"ф", "f"},
{"х", "kh"},
{"ц", "c"},
{"ч", "ch"},
{"ш", "sh"},
{"щ", "shh"},
{"ъ", ""},
{"ы", "y"},
{"ь", ""},
{"э", "eh"},
{"ю", "yu"},
{"я", "ya"},
{"«", ""},
{"»", ""},
{"—", "-"},
{" ", "-"}
}
Private ISO_CHARS As New Dictionary(Of String, String) From {
{"Є", "YE"},
{"Ѓ", "G"},
{"№", "#"},
{"є", "ye"},
{"ѓ", "g"},
{"А", "A"},
{"Б", "B"},
{"В", "V"},
{"Г", "G"},
{"Д", "D"},
{"Е", "E"},
{"Ё", "YO"},
{"Ж", "ZH"},
{"З", "Z"},
{"И", "I"},
{"Й", "J"},
{"К", "K"},
{"Л", "L"},
{"М", "M"},
{"Н", "N"},
{"О", "O"},
{"П", "P"},
{"Р", "R"},
{"С", "S"},
{"Т", "T"},
{"У", "U"},
{"Ф", "F"},
{"Х", "X"},
{"Ц", "C"},
{"Ч", "CH"},
{"Ш", "SH"},
{"Щ", "SHH"},
{"Ъ", "'"},
{"Ы", "Y"},
{"Ь", ""},
{"Э", "E"},
{"Ю", "YU"},
{"Я", "YA"},
{"а", "a"},
{"б", "b"},
{"в", "v"},
{"г", "g"},
{"д", "d"},
{"е", "e"},
{"ё", "yo"},
{"ж", "zh"},
{"з", "z"},
{"и", "i"},
{"й", "j"},
{"к", "k"},
{"л", "l"},
{"м", "m"},
{"н", "n"},
{"п", "p"},
{"р", "r"},
{"с", "s"},
{"т", "t"},
{"ф", "f"},
{"х", "x"},
{"ц", "c"},
{"ч", "ch"},
{"ш", "sh"},
{"щ", "shh"},
{"ъ", ""},
{"ы", "y"},
{"ь", ""},
{"э", "e"},
{"ю", "yu"},
{"я", "ya"},
{"«", ""},
{"»", ""},
{"—", "-"},
{" ", "-"}
}
#Region "Property"
Private mWithoutSpace As Boolean = True
''' <summary>
''' Заменять пробелы на символ "-"
''' </summary>
''' <returns></returns>
Public Property WithoutSpace As Boolean
Get
Return mWithoutSpace
End Get
Set(value As Boolean)
mWithoutSpace = value
If value Then
GOST_CHARS(" ") = "-"
ISO_CHARS(" ") = "-"
Else
GOST_CHARS(" ") = " "
ISO_CHARS(" ") = " "
End If
End Set
End Property
#End Region
''' <summary>
''' Подготовка текста
''' </summary>
''' <param name="text"></param>
''' <returns></returns>
Private Function ValidateText(text As String) As String
Dim output As String = Regex.Replace(text, "\s|\.|\(", " ")
output = Regex.Replace(output, "\s+", " ")
output = Regex.Replace(output, "[^\s\w\d-]", "")
output = output.Trim()
Return output
End Function
''' <summary>
''' Перевод на латиницу
''' </summary>
''' <param name="text">Текст для перевода</param>
''' <returns></returns>
Public Function TransferToLatin(text As String) As String
Return TransferToLatin(text, TransliterationType.ISO)
End Function
''' <summary>
''' Перевод на латиницу
''' </summary>
''' <param name="text">Текст для перевода</param>
''' <param name="type">Тип перевода</param>
''' <returns></returns>
Public Function TransferToLatin(text As String, type As TransliterationType) As String
Dim output As String = ValidateText(text)
Dim d As Dictionary(Of String, String) = GetDictonaryByType(type)
For Each item In d
output = output.Replace(item.Key, item.Value)
Next
Return output
End Function
''' <summary>
''' Перевод на кириллицу
''' </summary>
''' <param name="text">Текст перевода</param>
''' <returns></returns>
Public Function TransferToRus(text As String)
Return TransferToRus(text, TransliterationType.ISO)
End Function
''' <summary>
''' Перевод на кириллицу
''' </summary>
''' <param name="text">Текст перевода</param>
''' <param name="type">Тип перевода</param>
''' <returns></returns>
Public Function TransferToRus(text As String, type As TransliterationType)
Dim output As String = ValidateText(text)
Dim d As Dictionary(Of String, String) = GetDictonaryByType(type)
For Each item In d
If item.Value IsNot Nothing AndAlso item.Value.Count Then
output = output.Replace(item.Value, item.Key)
End If
Next
Return output
End Function
''' <summary>
''' Возвращает словарь по типу перевода
''' </summary>
''' <param name="type">Тип перевода</param>
''' <returns></returns>
Private Function GetDictonaryByType(type As TransliterationType) As Dictionary(Of String, String)
Select Case type
Case TransliterationType.GOST
Return GOST_CHARS
Case TransliterationType.ISO
Return ISO_CHARS
Case Else
Throw New ArgumentException("неизвестный тип словаря", "Translite")
End Select
End Function
End Class
|
Imports System
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Net.Sockets
Public Class Module1
Private Const BUFFER_SIZE As Integer = 1024
Private Const PORT_NUMBER As Integer = 9999
Shared encoding As ASCIIEncoding = New ASCIIEncoding()
Public Shared Sub Main()
Try
' 1. connect
Dim socket As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
socket.Connect("127.0.0.1", PORT_NUMBER)
Dim ns As NetworkStream = New NetworkStream(socket)
Dim reader As StreamReader = New StreamReader(ns)
Dim writer As StreamWriter = New StreamWriter(ns)
writer.AutoFlush = True
Console.WriteLine("Connected to TServer.")
While True
Console.Write("Enter your file name: ")
Dim str As String = Console.ReadLine()
' 2. send
writer.WriteLine(str)
' 3. receive
str = reader.ReadLine()
'File exist
If str.Equals("OK") Then
str = reader.ReadLine()
Dim FileName As String = str
Dim buff As Byte() = New Byte(1023) {}
'receive file size
Dim dataInfo As Integer = socket.Receive(buff, buff.Length, SocketFlags.None)
Dim s As String = encoding.GetString(buff, 0, dataInfo)
Dim Size As Long = Long.Parse(s)
Dim data As Byte() = New Byte(Size - 1) {}
#Region "receive one time"
'Dim rec As Int32 = socket.Receive(data, data.Length, SocketFlags.None)
#End Region
#Region "read from buffer then receive"
Dim buffer As Byte() = New Byte(1023) {}
Dim count As Long = 0
Dim i As Integer
While count < Size
If Size - count < buffer.Length Then
buffer = New Byte(Size - count - 1) {}
End If
socket.Receive(buffer, buffer.Length, SocketFlags.None)
For i = 0 To buffer.Length - 1
data(count) = buffer(i)
count += 1
Next
End While
#End Region
Console.WriteLine("Receive success")
File.WriteAllBytes(FileName, data)
Console.WriteLine("BYE")
Exit While
'File not exist
ElseIf str.Equals("NG") Then
Console.WriteLine("File is not exist!")
End If
If str.ToUpper().Equals("BYE") Then Exit While
End While
writer.Close()
reader.Close()
socket.Close()
Catch ex As Exception
Console.WriteLine("Error: {0}", ex)
End Try
Console.Read()
End Sub
End Class
|
Imports System.Xml
Imports System.IO
Imports System.Windows.Forms
Public Class sesCommonCodes
Private xDocDB As XmlDocument, xTableNode As XmlNode, sesDataFileName As String, sesDataFileExt As String, FBD As FolderBrowserDialog
Private ProgramPath As String, ProgramsDir As String, ExitSub As Boolean
Private sesConfigFName As String
Protected Friend ReadOnly Property GetProgramsDir() As String
Get
Return ProgramsDir
End Get
End Property
Public Sub New()
ProgramPath = My.Computer.FileSystem.SpecialDirectories.ProgramFiles
ProgramsDir = ProgramPath & "\" & PUBLISHER_DIR
End Sub
Private Sub GetxTableNode()
xDocDB = New XmlDocument
sesConfigFName = ProgramsDir & "\xconfig.xml"
xDocDB.Load(sesConfigFName)
sesDataFileName = xDocDB.SelectSingleNode("//ses-fname").InnerText
sesDataFileExt = xDocDB.SelectSingleNode("//ses-ext").InnerText
xTableNode = xDocDB.SelectSingleNode("//db-directory")
End Sub
Private Sub GetDirectoryPath(ByRef DBDir As String)
FBD = New FolderBrowserDialog : ExitSub = False
With FBD
.ShowNewFolderButton = False
.Description = "Databse files are missing. Either the files are deleted or moved to a different location. Choose the new directory location"
If .ShowDialog = DialogResult.OK Then
xTableNode.InnerText = .SelectedPath
DBDir = .SelectedPath
Else
MsgBox("No directory selected. Program will abort now.", MsgBoxStyle.OkOnly, "User cancelled the operation")
DBDir = ""
ExitSub = True
Exit Sub
End If
End With
xDocDB.Save(sesConfigFName)
End Sub
Protected Friend Sub FetchDBLocation(ByRef DBDir As String, Optional ByRef sesDFName As String = "")
GetxTableNode()
If xTableNode.InnerText = "" Then
GetDirectoryPath(DBDir)
If ExitSub Then Exit Sub
Else
DBDir = xTableNode.InnerText
End If
sesDFName = DBDir & "\" & sesDataFileName & sesDataFileExt
xDocDB = Nothing
End Sub
Protected Friend Sub GetDBLocation(ByRef DBDir As String, Optional ByRef sesDFName As String = "")
GetxTableNode()
GetDirectoryPath(DBDir)
If ExitSub Then Exit Sub
sesDFName = DBDir & "\" & sesDataFileName & sesDataFileExt
xDocDB = Nothing
End Sub
End Class
|
Option Strict On
Imports Gigasoft.ProEssentials.Enums
Imports System.Data
Public Class GraphsTimeSeriesGraph
Inherits System.Web.UI.Page
Protected WithEvents PesgoWeb As Gigasoft.ProEssentials.PesgoWeb
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not nwisanalyst.GraphsTimeSeries.mobjDataTable Is Nothing Then
Plot(nwisanalyst.GraphsTimeSeries.mobjDataTable, nwisanalyst.GraphsTimeSeries.mstrStationName, nwisanalyst.GraphsTimeSeries.mstrVariableName, nwisanalyst.GraphsTimeSeries.mobjOptions)
End If
End Sub
Public Sub Plot(ByRef objDataTable As DataTable, ByVal strStationName As String, ByVal strVariableName As String, ByRef objOptions As nwisanalyst.OptionsPlotOptions)
Dim i As Integer
'Verify that data exists in the table
If objDataTable Is Nothing Then Exit Sub
'Prepare images in memory
PesgoWeb.PeConfigure.PrepareImages = True
'Set dimensions
PesgoWeb.Width = System.Web.UI.WebControls.Unit.Pixel(507)
PesgoWeb.Height = System.Web.UI.WebControls.Unit.Pixel(390)
PesgoWeb.PeData.Subsets = 1
PesgoWeb.PeData.Points = objDataTable.Rows.Count
PesgoWeb.PeData.UsingXDataii = True ' Double precision x data
PesgoWeb.PeData.UsingYDataii = True ' Double precision y data
'Set date handling properties
PesgoWeb.PeData.StartTime = Convert.ToDateTime(objDataTable.Compute("MIN(TSDateTime)", "")).ToOADate
PesgoWeb.PeData.EndTime = Convert.ToDateTime(objDataTable.Compute("MAX(TSDateTime)", "")).ToOADate
'Plot data points
'Only plot data points if they are not censored. If the values are censored set equal
'to the null data value so that they are ignored.
For i = 0 To objDataTable.Rows.Count - 1
If Convert.ToString(objDataTable.Rows(i).Item("TSCensorCode")) = "<" Then
PesgoWeb.PeData.Xii.Item(0, i) = PesgoWeb.PeData.NullDataValueX
PesgoWeb.PeData.Yii.Item(0, i) = PesgoWeb.PeData.NullDataValue
Else
PesgoWeb.PeData.Xii.Item(0, i) = Convert.ToDateTime(objDataTable.Rows(i).Item("TSDateTime")).ToOADate
PesgoWeb.PeData.Yii.Item(0, i) = Convert.ToDouble(objDataTable.Rows(i).Item("TSValue"))
End If
Next
'Set graph properties
PesgoWeb.PeData.DateTimeMode = True
PesgoWeb.PeUserInterface.Allow.Zooming = AllowZooming.HorzAndVert
PesgoWeb.PeGrid.Style = GridStyle.Dot
PesgoWeb.PeGrid.Option.YearLabelType = YearLabelType.FourCharacters
PesgoWeb.PePlot.Option.NullDataGaps = True
PesgoWeb.PeGrid.Configure.AutoMinMaxPadding = 6
'Set plotting method
Select Case objOptions.PlottingMethod
Case "line"
PesgoWeb.PePlot.Method = SGraphPlottingMethod.Line
Case "point"
PesgoWeb.PePlot.Method = SGraphPlottingMethod.Point
Case "both"
PesgoWeb.PePlot.Method = SGraphPlottingMethod.PointsPlusLine
End Select
'Set control line
If objOptions.ControlLineValue <> Nothing Then
PesgoWeb.PeAnnotation.Line.YAxis.Item(0) = objOptions.ControlLineValue
PesgoWeb.PeAnnotation.Line.YAxisColor.Item(0) = objOptions.ControlLineColor
PesgoWeb.PeAnnotation.Line.YAxisType.Item(0) = LineAnnotationType.ThinSolid
PesgoWeb.PeAnnotation.Line.YAxisText.Item(0) = objOptions.ControlLineLabel
PesgoWeb.PeAnnotation.Line.TextSize = 100
PesgoWeb.PeAnnotation.Line.YAxisShow = True
PesgoWeb.PeAnnotation.Show = True
End If
'Set titles and labels
PesgoWeb.PeString.MainTitle = strStationName
PesgoWeb.PeString.SubTitle = String.Empty
PesgoWeb.PeString.YAxisLabel = strVariableName
PesgoWeb.PeString.XAxisLabel = "Date"
End Sub
End Class
|
Public Enum DisplayAlignment
Left
HCenter
Right
Top
VCenter
Bottom
End Enum
Public Class DispAlignment
Public Event AlignmentClicked(sender As Object, e As DisplayAlignment)
Private _recL As Rectangle
Private _recHC As Rectangle
Private _recR As Rectangle
Private _recT As Rectangle
Private _recVC As Rectangle
Private _recB As Rectangle
Private _selREc As Rectangle
Private Sub LineWidth_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SetStyle(ControlStyles.AllPaintingInWmPaint Or
ControlStyles.FixedHeight Or
ControlStyles.FixedWidth Or
ControlStyles.Opaque Or
ControlStyles.OptimizedDoubleBuffer Or
ControlStyles.Selectable Or
ControlStyles.UserPaint, True)
_recL = New Rectangle(0, 3, 16, 16)
_recVC = New Rectangle(_recL.Right + 5, 3, 16, 16)
_recR = New Rectangle(_recVC.Right + 5, 3, 16, 16)
_recT = New Rectangle(_recR.Right + 5, 3, 16, 16)
_recHC = New Rectangle(_recT.Right + 5, 3, 16, 16)
_recB = New Rectangle(_recHC.Right + 5, 3, 16, 16)
End Sub
Private Sub LineWidth_Resize(sender As Object, e As EventArgs) Handles Me.Resize
Me.Height = 23
Me.Width = 122
End Sub
Private Sub DispAlignment_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown
If _recL.Contains(e.X, e.Y) Then
_selREc = _recL
ElseIf _recHC.Contains(e.X, e.Y) Then
_selREc = _recHC
ElseIf _recR.Contains(e.X, e.Y) Then
_selREc = _recR
ElseIf _recT.Contains(e.X, e.Y) Then
_selREc = _recT
ElseIf _recVC.Contains(e.X, e.Y) Then
_selREc = _recVC
ElseIf _recB.Contains(e.X, e.Y) Then
_selREc = _recB
End If
Me.Invalidate()
End Sub
Private Sub me_MouseUp(sender As Object, e As MouseEventArgs) Handles Me.MouseUp
If _recL.Contains(e.X, e.Y) Then
RaiseEvent AlignmentClicked(Me, DisplayAlignment.Left)
ElseIf _recHC.Contains(e.X, e.Y) Then
RaiseEvent AlignmentClicked(Me, DisplayAlignment.HCenter)
ElseIf _recR.Contains(e.X, e.Y) Then
RaiseEvent AlignmentClicked(Me, DisplayAlignment.Right)
ElseIf _recT.Contains(e.X, e.Y) Then
RaiseEvent AlignmentClicked(Me, DisplayAlignment.Top)
ElseIf _recVC.Contains(e.X, e.Y) Then
RaiseEvent AlignmentClicked(Me, DisplayAlignment.VCenter)
ElseIf _recB.Contains(e.X, e.Y) Then
RaiseEvent AlignmentClicked(Me, DisplayAlignment.Bottom)
End If
_selREc = Rectangle.Empty
Me.Invalidate()
End Sub
Private Sub me_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
e.Graphics.Clear(Me.BackColor)
e.Graphics.DrawImage(My.Resources.AlignLeft, _recL)
e.Graphics.DrawImage(My.Resources.AlignVertCenters, _recVC)
e.Graphics.DrawImage(My.Resources.AlignRight, _recR)
e.Graphics.DrawImage(My.Resources.AlignTop, _recT)
e.Graphics.DrawImage(My.Resources.AlignHorzCenters, _recHC)
e.Graphics.DrawImage(My.Resources.AlignBottom, _recB)
If Not _selREc.IsEmpty Then
e.Graphics.DrawRectangle(Pens.DimGray, _selREc)
End If
End Sub
End Class
|
#Region "Microsoft.VisualBasic::3a1334a5518e2b5e9c70d5fe1566aa2a, mzkit\src\metadb\SMILES\ParseChain.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: 131
' Code Lines: 106
' Comment Lines: 3
' Blank Lines: 22
' File Size: 4.30 KB
' Class ParseChain
'
' Constructor: (+1 Overloads) Sub New
'
' Function: CreateGraph, ParseGraph, ToString
'
' Sub: WalkElement, WalkKey, WalkToken
'
' /********************************************************************************/
#End Region
Imports System.Runtime.CompilerServices
Imports BioNovoGene.BioDeep.Chemoinformatics.SMILES.Language
Imports Microsoft.VisualBasic.ComponentModel
Imports Microsoft.VisualBasic.Data.GraphTheory
Imports Microsoft.VisualBasic.Language
Imports Microsoft.VisualBasic.Linq
Public Class ParseChain
ReadOnly graph As New ChemicalFormula
ReadOnly chainStack As New Stack(Of ChemicalElement)
ReadOnly stackSize As New Stack(Of Counter)
ReadOnly SMILES As String
ReadOnly tokens As Token()
ReadOnly rings As New Dictionary(Of String, ChemicalElement)
Dim lastKey As Bonds?
Sub New(tokens As IEnumerable(Of Token))
Me.tokens = tokens.ToArray
Me.SMILES = Me.tokens _
.Select(Function(t)
If t.ring Is Nothing Then
Return t.text
Else
Return t.text & t.ring.ToString
End If
End Function) _
.JoinBy("")
End Sub
Public Shared Function ParseGraph(SMILES As String, Optional strict As Boolean = True) As ChemicalFormula
Dim tokens As Token() = New Scanner(SMILES).GetTokens().ToArray
Dim graph As ChemicalFormula = New ParseChain(tokens).CreateGraph(strict)
Dim degree = graph _
.AllBonds _
.DoCall(AddressOf Network.ComputeDegreeData(Of ChemicalElement, ChemicalKey))
For Each element As ChemicalElement In graph.AllElements
element.degree = (
degree.In.TryGetValue(element.label),
degree.Out.TryGetValue(element.label)
)
Next
Return graph
End Function
Public Function CreateGraph(Optional strict As Boolean = True) As ChemicalFormula
Dim i As i32 = 1
For Each t As Token In tokens
Call WalkToken(t, ++i)
Next
Call ChemicalElement.SetAtomGroups(formula:=graph)
Return graph.AutoLayout(strict:=strict)
End Function
Private Sub WalkToken(t As Token, i As Integer)
Select Case t.name
Case ElementTypes.Element, ElementTypes.AtomGroup : Call WalkElement(t, i)
Case ElementTypes.Key : Call WalkKey(t)
Case ElementTypes.Open
' do nothing
stackSize.Push(0)
Case ElementTypes.Close
Call chainStack.Pop(stackSize.Pop())
Case ElementTypes.Disconnected, ElementTypes.None
' unsure how to break the graph, do nothing?
Case Else
Throw New NotImplementedException(t.ToString)
End Select
End Sub
<MethodImpl(MethodImplOptions.AggressiveInlining)>
Private Sub WalkKey(t As Token)
lastKey = CType(CByte(ChemicalBonds.IndexOf(t.text)), Bonds)
End Sub
Private Sub WalkElement(t As Token, i As Integer)
Dim element As New ChemicalElement(t.text, index:=i) With {
.charge = Val(t.charge)
}
Dim ringId As String = If(t.ring Is Nothing, Nothing, t.ring.ToString)
element.ID = graph.vertex.Count + 1
graph.AddVertex(element)
If Not ringId Is Nothing Then
If rings.ContainsKey(ringId) Then
Dim [next] = rings(ringId)
Dim bond As New ChemicalKey With {
.U = [next],
.V = element,
.weight = 1,
.bond = Bonds.single
}
Call graph.Insert(bond)
Else
rings(ringId) = element
End If
End If
If chainStack.Count > 0 Then
Dim lastElement As ChemicalElement = chainStack.Peek
Dim bondType As Bonds = If(lastKey Is Nothing, Bonds.single, lastKey.Value)
' 默认为单键
Dim bond As New ChemicalKey With {
.U = lastElement,
.V = element,
.weight = 1,
.bond = bondType
}
Call graph.Insert(bond)
End If
If stackSize.Count > 0 Then
Call stackSize.Peek.Hit()
End If
lastKey = Nothing
chainStack.Push(element)
End Sub
Public Overrides Function ToString() As String
Return SMILES
End Function
End Class
|
Imports System.Runtime.Serialization
Namespace Route4MeSDK.DataTypes
''' <summary>
''' The class for the custom note of a route destination.
''' </summary>
<DataContract>
Public NotInheritable Class AddressCustomNote
''' <summary>
''' A unique ID (40 chars) of a custom note entry.
''' </summary>
''' <returns></returns>
<DataMember(Name:="note_custom_entry_id", EmitDefaultValue:=False)>
Public Property NoteCustomEntryID As String
''' <summary>
''' The custom note ID.
''' </summary>
''' <returns></returns>
<DataMember(Name:="note_id", EmitDefaultValue:=False)>
Public Property NoteID As String
''' <summary>
''' The custom note type ID.
''' </summary>
''' <returns></returns>
<DataMember(Name:="note_custom_type_id", EmitDefaultValue:=False)>
Public Property NoteCustomTypeID As String
''' <summary>
''' The custom note value.
''' </summary>
''' <returns></returns>
<DataMember(Name:="note_custom_value")>
Public Property NoteCustomValue As String
''' <summary>
''' The custom note type.
''' </summary>
''' <returns></returns>
<DataMember(Name:="note_custom_type")>
Public Property NoteCustomType As String
End Class
End Namespace
|
Imports System.Collections.ObjectModel
Imports SkyEditor.Core
Imports SkyEditor.Core.IO
Imports SkyEditor.Core.Projects
Imports SkyEditor.Core.UI
Imports SkyEditor.UI.WPF.MenuActions.Context
Imports SkyEditor.UI.WPF.ViewModels.Projects
Namespace ViewModels
Public Class SolutionExplorerViewModel
Inherits AnchorableViewModel
Public Sub New(applicationViewModel As ApplicationViewModel, pluginManager As PluginManager)
MyBase.New(applicationViewModel)
Me.Header = My.Resources.Language.SolutionExplorerToolWindowTitle
SolutionRoots = New ObservableCollection(Of SolutionHeiarchyItemViewModel)
CurrentApplicationViewModel = applicationViewModel
CurrentPluginManager = pluginManager
End Sub
Public ReadOnly Property SolutionRoots As ObservableCollection(Of SolutionHeiarchyItemViewModel)
Protected Property CurrentApplicationViewModel As ApplicationViewModel
Protected Property CurrentPluginManager As PluginManager
Public Async Function OpenNode(node As Object) As Task
Await ProjectNodeOpenFile.OpenFile(node, CurrentApplicationViewModel, CurrentPluginManager)
End Function
Private Sub SolutionExplorerViewModel_CurrentSolutionChanged(sender As Object, e As EventArgs) Handles Me.CurrentSolutionChanged
SolutionRoots.Clear()
SolutionRoots.Add(New SolutionHeiarchyItemViewModel(CurrentApplicationViewModel.CurrentSolution))
End Sub
End Class
End Namespace
|
Option Strict Off
Option Explicit On
Module SearchPdfUtils
' ADOBE SYSTEMS INCORPORATED
' Copyright (C) 1994-2003 Adobe Systems Incorporated
' All rights reserved.
'
' NOTICE: Adobe permits you to use, modify, and distribute this file
' in accordance with the terms of the Adobe license agreement
' accompanying it. If you have received this file from a source other
' than Adobe, then your use, modification, or distribution of it
' requires the prior written permission of Adobe.
'
' -------------------------------------------------------------------
'
' SearchPDFUtils.bas
'
' - When declaring DLL procedures in VB you must either specify the
' entire path to the DLL or it must be located along the standard
' VB search path. This means that you must do one of the following
' before using this sample:
'
' 1. move ddeproxy.dll (to the windows system directory)
' 2. add the full path to this file
' 3. add the path to ddeproxy.dll to the PATH environment variable.
'"D:\path\to\AcrobatSDK\InterAppSupport\Win\Visual Basic\SearchPDF\DdeProxy\Release\ddeproxy.dll"
'Used for storing the path to the executeable
Public buf As String
' Set the Query language
Declare Sub SetQueryLanguageType Lib "DdeProxy.dll" Alias "_SetQueryLanguageType@4"(ByVal language As Short)
' Set the MaxDocs
Declare Sub SetQueryMaxDocs Lib "DdeProxy.dll" Alias "_SetQueryMaxDocs@4"(ByVal maxDocs As Short)
' Override the Query word options
Declare Sub SetQueryOverideWordOptions Lib "DdeProxy.dll" Alias "_SetQueryOverrideWordOptions@0"()
' Set the Query word options
Declare Sub SetQueryWordOptions Lib "DdeProxy.dll" Alias "_SetQueryWordOptions@4"(ByVal flags As Integer)
' Set the Query target word
Declare Sub SetQueryWordTarget Lib "DdeProxy.dll" Alias "_SetQueryWordTarget@4"(ByVal target As String)
' Set the Sort option with boolean for ascending (0=descend, 1=ascend)
Declare Sub SetQuerySortOption Lib "DdeProxy.dll" Alias "_SetQuerySortOption@8"(ByVal field As String, ByVal ascending As Short)
' Set the Index Action Type
Declare Sub SetIndexAction Lib "DdeProxy.dll" Alias "_SetIndexAction@4"(ByVal action As Short)
' Set the Index name
Declare Sub SetIndexName Lib "DdeProxy.dll" Alias "_SetIndexName@4"(ByVal indexName As String)
' Set the Index temporary name
Declare Sub SetIndexTempName Lib "DdeProxy.dll" Alias "_SetIndexTempName@4"(ByVal TempIndexName As String)
' Initialize the Query DDE Conversation
Declare Sub SrchDDEInitQuery Lib "DdeProxy.dll" Alias "_SrchDDEInitQuery@0"()
' Initialize the Index DDE Conversation
Declare Sub SrchDDEInitIndex Lib "DdeProxy.dll" Alias "_SrchDDEInitIndex@0"()
' Send the QueryData packet and terminate DDE Conversation
Declare Sub SrchDDESendQuery Lib "DdeProxy.dll" Alias "_SrchDDESendQuery@0"()
' Send the IndexData packet and terminate DDE Conversation
Declare Sub SrchDDESendIndex Lib "DdeProxy.dll" Alias "_SrchDDESendIndex@0"()
' * Function Prototypes and datatypes for accessing the Windows Registry
Public Const HKEY_LOCAL_MACHINE As Integer = &H80000002
Public Const ERROR_SUCCESS As Short = 0
Public Const SYNCHRONIZE As Integer = &H100000
Public Const STANDARD_RIGHTS_READ As Integer = &H20000
Public Const KEY_QUERY_VALUE As Short = &H1s
Public Const KEY_ENUMERATE_SUB_KEYS As Short = &H8s
Public Const KEY_NOTIFY As Short = &H10s
Public Const KEY_READ As Boolean = ((STANDARD_RIGHTS_READ Or KEY_QUERY_VALUE Or KEY_ENUMERATE_SUB_KEYS Or KEY_NOTIFY) And (Not SYNCHRONIZE))
Public Const QPON_Case As Short = &H1s
Public Const QPON_Stemming As Short = &H2s
Public Const QPON_SoundsLike As Short = &H4s
Public Const QPON_Thesaurus As Short = &H8s
Public Const QPON_Proximity As Short = &H10s
Public Const QPON_Refine As Short = &H20s
End Module |
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class FrmDataSSI
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()
Me.components = New System.ComponentModel.Container()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(FrmDataSSI))
Dim DataGridViewCellStyle1 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle()
Dim DataGridViewCellStyle2 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle()
Dim DataGridViewCellStyle3 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle()
Dim DataGridViewCellStyle4 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle()
Dim DataGridViewCellStyle5 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle()
Dim DataGridViewCellStyle6 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle()
Me.grid = New System.Windows.Forms.DataGridView()
Me.ProductCode = New System.Windows.Forms.DataGridViewTextBoxColumn()
Me.mnuExport = New System.Windows.Forms.ToolStripButton()
Me.ToolStripSeparator6 = New System.Windows.Forms.ToolStripSeparator()
Me.mnuDelete = New System.Windows.Forms.ToolStripButton()
Me.mnuShowAll = New System.Windows.Forms.ToolStripButton()
Me.tlsMenu = New System.Windows.Forms.ToolStrip()
Me.mnuSave = New System.Windows.Forms.ToolStripButton()
Me.bdn = New System.Windows.Forms.BindingNavigator(Me.components)
Me.BindingNavigatorCountItem = New System.Windows.Forms.ToolStripLabel()
Me.BindingNavigatorMoveFirstItem = New System.Windows.Forms.ToolStripButton()
Me.BindingNavigatorMovePreviousItem = New System.Windows.Forms.ToolStripButton()
Me.BindingNavigatorSeparator = New System.Windows.Forms.ToolStripSeparator()
Me.BindingNavigatorPositionItem = New System.Windows.Forms.ToolStripTextBox()
Me.BindingNavigatorSeparator1 = New System.Windows.Forms.ToolStripSeparator()
Me.BindingNavigatorMoveNextItem = New System.Windows.Forms.ToolStripButton()
Me.BindingNavigatorMoveLastItem = New System.Windows.Forms.ToolStripButton()
Me.BindingNavigatorSeparator2 = New System.Windows.Forms.ToolStripSeparator()
Me.Label1 = New System.Windows.Forms.Label()
Me.txtMSP = New System.Windows.Forms.TextBox()
Me.DataGridViewTextBoxColumn1 = New System.Windows.Forms.DataGridViewTextBoxColumn()
Me.DataGridViewTextBoxColumn2 = New System.Windows.Forms.DataGridViewTextBoxColumn()
Me.DataGridViewTextBoxColumn3 = New System.Windows.Forms.DataGridViewTextBoxColumn()
Me.DataGridViewTextBoxColumn4 = New System.Windows.Forms.DataGridViewTextBoxColumn()
Me.DataGridViewTextBoxColumn5 = New System.Windows.Forms.DataGridViewTextBoxColumn()
Me.DataGridViewTextBoxColumn6 = New System.Windows.Forms.DataGridViewTextBoxColumn()
Me.DataGridViewTextBoxColumn7 = New System.Windows.Forms.DataGridViewTextBoxColumn()
Me.DataGridViewTextBoxColumn8 = New System.Windows.Forms.DataGridViewTextBoxColumn()
CType(Me.grid, System.ComponentModel.ISupportInitialize).BeginInit()
Me.tlsMenu.SuspendLayout()
CType(Me.bdn, System.ComponentModel.ISupportInitialize).BeginInit()
Me.bdn.SuspendLayout()
Me.SuspendLayout()
'
'grid
'
Me.grid.AllowUserToAddRows = False
Me.grid.AllowUserToDeleteRows = False
Me.grid.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.grid.BackgroundColor = System.Drawing.Color.White
Me.grid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
Me.grid.Columns.AddRange(New System.Windows.Forms.DataGridViewColumn() {Me.ProductCode})
Me.grid.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter
Me.grid.EnableHeadersVisualStyles = False
Me.grid.Location = New System.Drawing.Point(0, 57)
Me.grid.Margin = New System.Windows.Forms.Padding(2)
Me.grid.Name = "grid"
Me.grid.RowHeadersWidth = 20
Me.grid.Size = New System.Drawing.Size(939, 370)
Me.grid.TabIndex = 20
'
'ProductCode
'
Me.ProductCode.DataPropertyName = "ProductCode"
Me.ProductCode.HeaderText = "ProductCode"
Me.ProductCode.Name = "ProductCode"
Me.ProductCode.ReadOnly = True
Me.ProductCode.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
Me.ProductCode.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic
Me.ProductCode.Width = 60
'
'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.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
Me.mnuExport.ToolTipText = "Export(Ctrl+E)"
'
'ToolStripSeparator6
'
Me.ToolStripSeparator6.Name = "ToolStripSeparator6"
Me.ToolStripSeparator6.Size = New System.Drawing.Size(6, 55)
'
'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.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
Me.mnuDelete.ToolTipText = "Delete"
'
'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.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
Me.mnuShowAll.ToolTipText = "Show all (F5)"
'
'tlsMenu
'
Me.tlsMenu.AutoSize = False
Me.tlsMenu.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden
Me.tlsMenu.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.mnuShowAll, Me.mnuExport, Me.mnuDelete, Me.mnuSave, Me.ToolStripSeparator6})
Me.tlsMenu.Location = New System.Drawing.Point(0, 0)
Me.tlsMenu.Name = "tlsMenu"
Me.tlsMenu.Size = New System.Drawing.Size(939, 55)
Me.tlsMenu.TabIndex = 21
'
'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.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
Me.mnuSave.ToolTipText = "Save"
'
'bdn
'
Me.bdn.AddNewItem = Nothing
Me.bdn.CountItem = Me.BindingNavigatorCountItem
Me.bdn.DeleteItem = Nothing
Me.bdn.Dock = System.Windows.Forms.DockStyle.Bottom
Me.bdn.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.BindingNavigatorMoveFirstItem, Me.BindingNavigatorMovePreviousItem, Me.BindingNavigatorSeparator, Me.BindingNavigatorPositionItem, Me.BindingNavigatorCountItem, Me.BindingNavigatorSeparator1, Me.BindingNavigatorMoveNextItem, Me.BindingNavigatorMoveLastItem, Me.BindingNavigatorSeparator2})
Me.bdn.Location = New System.Drawing.Point(0, 431)
Me.bdn.MoveFirstItem = Me.BindingNavigatorMoveFirstItem
Me.bdn.MoveLastItem = Me.BindingNavigatorMoveLastItem
Me.bdn.MoveNextItem = Me.BindingNavigatorMoveNextItem
Me.bdn.MovePreviousItem = Me.BindingNavigatorMovePreviousItem
Me.bdn.Name = "bdn"
Me.bdn.PositionItem = Me.BindingNavigatorPositionItem
Me.bdn.Size = New System.Drawing.Size(939, 25)
Me.bdn.TabIndex = 22
Me.bdn.Text = "BindingNavigator1"
'
'BindingNavigatorCountItem
'
Me.BindingNavigatorCountItem.Name = "BindingNavigatorCountItem"
Me.BindingNavigatorCountItem.Size = New System.Drawing.Size(35, 22)
Me.BindingNavigatorCountItem.Text = "of {0}"
Me.BindingNavigatorCountItem.ToolTipText = "Total number of items"
'
'BindingNavigatorMoveFirstItem
'
Me.BindingNavigatorMoveFirstItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
Me.BindingNavigatorMoveFirstItem.Image = CType(resources.GetObject("BindingNavigatorMoveFirstItem.Image"), System.Drawing.Image)
Me.BindingNavigatorMoveFirstItem.Name = "BindingNavigatorMoveFirstItem"
Me.BindingNavigatorMoveFirstItem.RightToLeftAutoMirrorImage = True
Me.BindingNavigatorMoveFirstItem.Size = New System.Drawing.Size(23, 22)
Me.BindingNavigatorMoveFirstItem.Text = "Move first"
'
'BindingNavigatorMovePreviousItem
'
Me.BindingNavigatorMovePreviousItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
Me.BindingNavigatorMovePreviousItem.Image = CType(resources.GetObject("BindingNavigatorMovePreviousItem.Image"), System.Drawing.Image)
Me.BindingNavigatorMovePreviousItem.Name = "BindingNavigatorMovePreviousItem"
Me.BindingNavigatorMovePreviousItem.RightToLeftAutoMirrorImage = True
Me.BindingNavigatorMovePreviousItem.Size = New System.Drawing.Size(23, 22)
Me.BindingNavigatorMovePreviousItem.Text = "Move previous"
'
'BindingNavigatorSeparator
'
Me.BindingNavigatorSeparator.Name = "BindingNavigatorSeparator"
Me.BindingNavigatorSeparator.Size = New System.Drawing.Size(6, 25)
'
'BindingNavigatorPositionItem
'
Me.BindingNavigatorPositionItem.AccessibleName = "Position"
Me.BindingNavigatorPositionItem.AutoSize = False
Me.BindingNavigatorPositionItem.Name = "BindingNavigatorPositionItem"
Me.BindingNavigatorPositionItem.Size = New System.Drawing.Size(50, 23)
Me.BindingNavigatorPositionItem.Text = "0"
Me.BindingNavigatorPositionItem.ToolTipText = "Current position"
'
'BindingNavigatorSeparator1
'
Me.BindingNavigatorSeparator1.Name = "BindingNavigatorSeparator1"
Me.BindingNavigatorSeparator1.Size = New System.Drawing.Size(6, 25)
'
'BindingNavigatorMoveNextItem
'
Me.BindingNavigatorMoveNextItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
Me.BindingNavigatorMoveNextItem.Image = CType(resources.GetObject("BindingNavigatorMoveNextItem.Image"), System.Drawing.Image)
Me.BindingNavigatorMoveNextItem.Name = "BindingNavigatorMoveNextItem"
Me.BindingNavigatorMoveNextItem.RightToLeftAutoMirrorImage = True
Me.BindingNavigatorMoveNextItem.Size = New System.Drawing.Size(23, 22)
Me.BindingNavigatorMoveNextItem.Text = "Move next"
'
'BindingNavigatorMoveLastItem
'
Me.BindingNavigatorMoveLastItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
Me.BindingNavigatorMoveLastItem.Image = CType(resources.GetObject("BindingNavigatorMoveLastItem.Image"), System.Drawing.Image)
Me.BindingNavigatorMoveLastItem.Name = "BindingNavigatorMoveLastItem"
Me.BindingNavigatorMoveLastItem.RightToLeftAutoMirrorImage = True
Me.BindingNavigatorMoveLastItem.Size = New System.Drawing.Size(23, 22)
Me.BindingNavigatorMoveLastItem.Text = "Move last"
'
'BindingNavigatorSeparator2
'
Me.BindingNavigatorSeparator2.Name = "BindingNavigatorSeparator2"
Me.BindingNavigatorSeparator2.Size = New System.Drawing.Size(6, 25)
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(252, 4)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(69, 13)
Me.Label1.TabIndex = 26
Me.Label1.Text = "ProductCode"
'
'txtMSP
'
Me.txtMSP.Location = New System.Drawing.Point(255, 23)
Me.txtMSP.Name = "txtMSP"
Me.txtMSP.Size = New System.Drawing.Size(83, 20)
Me.txtMSP.TabIndex = 25
'
'DataGridViewTextBoxColumn1
'
Me.DataGridViewTextBoxColumn1.DataPropertyName = "ProductCode"
Me.DataGridViewTextBoxColumn1.HeaderText = "ProductCode"
Me.DataGridViewTextBoxColumn1.Name = "DataGridViewTextBoxColumn1"
Me.DataGridViewTextBoxColumn1.ReadOnly = True
Me.DataGridViewTextBoxColumn1.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
Me.DataGridViewTextBoxColumn1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic
Me.DataGridViewTextBoxColumn1.Width = 50
'
'DataGridViewTextBoxColumn2
'
Me.DataGridViewTextBoxColumn2.DataPropertyName = "ProductName"
Me.DataGridViewTextBoxColumn2.HeaderText = "ProductName"
Me.DataGridViewTextBoxColumn2.Name = "DataGridViewTextBoxColumn2"
'
'DataGridViewTextBoxColumn3
'
Me.DataGridViewTextBoxColumn3.DataPropertyName = "TotalLot"
DataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight
DataGridViewCellStyle1.Format = "N0"
Me.DataGridViewTextBoxColumn3.DefaultCellStyle = DataGridViewCellStyle1
Me.DataGridViewTextBoxColumn3.HeaderText = "Tổng Lot"
Me.DataGridViewTextBoxColumn3.Name = "DataGridViewTextBoxColumn3"
Me.DataGridViewTextBoxColumn3.Width = 70
'
'DataGridViewTextBoxColumn4
'
Me.DataGridViewTextBoxColumn4.DataPropertyName = "TotalNG"
DataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight
DataGridViewCellStyle2.Format = "N0"
Me.DataGridViewTextBoxColumn4.DefaultCellStyle = DataGridViewCellStyle2
Me.DataGridViewTextBoxColumn4.HeaderText = "Tổng lot NG"
Me.DataGridViewTextBoxColumn4.Name = "DataGridViewTextBoxColumn4"
Me.DataGridViewTextBoxColumn4.Width = 60
'
'DataGridViewTextBoxColumn5
'
Me.DataGridViewTextBoxColumn5.DataPropertyName = "TLOK"
DataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight
DataGridViewCellStyle3.Format = "N2"
Me.DataGridViewTextBoxColumn5.DefaultCellStyle = DataGridViewCellStyle3
Me.DataGridViewTextBoxColumn5.HeaderText = "Tỷ lệ lot đạt (OK)"
Me.DataGridViewTextBoxColumn5.Name = "DataGridViewTextBoxColumn5"
'
'DataGridViewTextBoxColumn6
'
Me.DataGridViewTextBoxColumn6.DataPropertyName = "AQL"
DataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight
DataGridViewCellStyle4.Format = "N0"
Me.DataGridViewTextBoxColumn6.DefaultCellStyle = DataGridViewCellStyle4
Me.DataGridViewTextBoxColumn6.HeaderText = "Tổng AQL"
Me.DataGridViewTextBoxColumn6.Name = "DataGridViewTextBoxColumn6"
Me.DataGridViewTextBoxColumn6.Width = 60
'
'DataGridViewTextBoxColumn7
'
Me.DataGridViewTextBoxColumn7.DataPropertyName = "TotalLoi"
DataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight
DataGridViewCellStyle5.Format = "N0"
Me.DataGridViewTextBoxColumn7.DefaultCellStyle = DataGridViewCellStyle5
Me.DataGridViewTextBoxColumn7.HeaderText = "Tổng lỗi"
Me.DataGridViewTextBoxColumn7.Name = "DataGridViewTextBoxColumn7"
Me.DataGridViewTextBoxColumn7.Width = 60
'
'DataGridViewTextBoxColumn8
'
Me.DataGridViewTextBoxColumn8.DataPropertyName = "PercentLoi"
DataGridViewCellStyle6.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight
DataGridViewCellStyle6.Format = "N2"
Me.DataGridViewTextBoxColumn8.DefaultCellStyle = DataGridViewCellStyle6
Me.DataGridViewTextBoxColumn8.HeaderText = "% Phần trăm lỗi"
Me.DataGridViewTextBoxColumn8.Name = "DataGridViewTextBoxColumn8"
Me.DataGridViewTextBoxColumn8.Width = 80
'
'FrmDataSSI
'
Me.Appearance.Options.UseFont = True
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(939, 456)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.txtMSP)
Me.Controls.Add(Me.bdn)
Me.Controls.Add(Me.grid)
Me.Controls.Add(Me.tlsMenu)
Me.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.KeyPreview = True
Me.Name = "FrmDataSSI"
Me.Tag = "0243QA01"
Me.Text = "Báo cáo SSI"
CType(Me.grid, System.ComponentModel.ISupportInitialize).EndInit()
Me.tlsMenu.ResumeLayout(False)
Me.tlsMenu.PerformLayout()
CType(Me.bdn, System.ComponentModel.ISupportInitialize).EndInit()
Me.bdn.ResumeLayout(False)
Me.bdn.PerformLayout()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents grid As System.Windows.Forms.DataGridView
Friend WithEvents mnuExport As System.Windows.Forms.ToolStripButton
Friend WithEvents ToolStripSeparator6 As System.Windows.Forms.ToolStripSeparator
Friend WithEvents mnuDelete As System.Windows.Forms.ToolStripButton
Friend WithEvents mnuShowAll As System.Windows.Forms.ToolStripButton
Friend WithEvents tlsMenu As System.Windows.Forms.ToolStrip
Friend WithEvents bdn As System.Windows.Forms.BindingNavigator
Friend WithEvents BindingNavigatorCountItem As System.Windows.Forms.ToolStripLabel
Friend WithEvents BindingNavigatorMoveFirstItem As System.Windows.Forms.ToolStripButton
Friend WithEvents BindingNavigatorMovePreviousItem As System.Windows.Forms.ToolStripButton
Friend WithEvents BindingNavigatorSeparator As System.Windows.Forms.ToolStripSeparator
Friend WithEvents BindingNavigatorPositionItem As System.Windows.Forms.ToolStripTextBox
Friend WithEvents BindingNavigatorSeparator1 As System.Windows.Forms.ToolStripSeparator
Friend WithEvents BindingNavigatorMoveNextItem As System.Windows.Forms.ToolStripButton
Friend WithEvents BindingNavigatorMoveLastItem As System.Windows.Forms.ToolStripButton
Friend WithEvents BindingNavigatorSeparator2 As System.Windows.Forms.ToolStripSeparator
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents txtMSP As System.Windows.Forms.TextBox
Friend WithEvents DataGridViewTextBoxColumn1 As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents DataGridViewTextBoxColumn2 As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents DataGridViewTextBoxColumn3 As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents DataGridViewTextBoxColumn4 As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents DataGridViewTextBoxColumn5 As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents DataGridViewTextBoxColumn6 As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents DataGridViewTextBoxColumn7 As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents DataGridViewTextBoxColumn8 As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents ProductCode As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents mnuSave As System.Windows.Forms.ToolStripButton
End Class
|
'Program: Uber, Subway, or Bus
'Developer: Logan Taylor
'Date: 12/16/20
'Purpose: To calculate yearly commute cost based on user inputs for how they commute.
Option Strict On
Public Class frmUberSubwayOrBus
'Class Variables
Dim decMonthlyCost As Decimal
Dim decYearlyCost As Decimal
Dim intTransportType As Integer
Dim intDaysInMonth As Integer
Dim decCostPerDay As Decimal
Dim strCostPerDay As String
Dim strDailyCost As String
Dim strDaysInMonth As String
Dim blnValidateDaysInMonth As Boolean = False
Dim blnValidateCostPerDay As Boolean = False
Dim blnValidateTransportation As Boolean = False
Private Sub frmUberSubwayOrBus_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Executes when application loads
Threading.Thread.Sleep(5000)
lblCommuteCostDisplay.Visible = False
End Sub
Private Sub cboTransportationMethod_SelectedIndexChanged(ByVal Sender As System.Object, ByVal e As EventArgs) Handles cboTransportationMethod.SelectedIndexChanged
'Allows the user to pick transportation type, then calls sub procedure to display a series of input boxes asking for additional information.
intTransportType = cboTransportationMethod.SelectedIndex
Select Case intTransportType
Case 0
UberGroup()
Case 1
SubwayGroup()
Case 2
BusGroup()
End Select
End Sub
Private Sub UberGroup()
ValidateTransportType()
End Sub
Private Sub BusGroup()
ValidateTransportType()
End Sub
Private Sub SubwayGroup()
ValidateTransportType()
End Sub
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
' asks for more information, Determines, and displays yearly commuting cost based on user inputs
'strings used in this sub
Dim strDailyCostAsk As String = "How much does it cost for one day of travel?"
Dim strCostTitle As String = "Daily Cost"
Dim strDaysInMonthAsk As String = "How many days do you travel to work, per month?"
Dim strDaysTitle As String = "Days Per Month"
'executed based on selected transportation type
Try
Select Case (cboTransportationMethod.SelectedIndex)
Case 0
If blnValidateTransportation = True Then
strDailyCost = InputBox(strDailyCostAsk, strCostTitle)
ValidateCostPerDay()
If blnValidateCostPerDay = True Then
strDaysInMonth = InputBox(strDaysInMonthAsk, strDaysTitle)
ValidateDaysInMonth()
If blnValidateDaysInMonth = True Then
decMonthlyCost = Convert.ToDecimal(Convert.ToDecimal(strDailyCost) * 1.2) * intDaysInMonth
decYearlyCost = decMonthlyCost * 12
lblCommuteCostDisplay.Text = "Your yearly commute cost is " & decYearlyCost.ToString("C")
lblCommuteCostDisplay.Visible = True
btnCalculate.Enabled = False
Else
MsgBox("Enter a reasonable number of days, please.", , "Wow, did you really?")
End If
Else
MsgBox("Your price has to be between $1 and $59.99", , "Wow, did you really?")
End If
Else
MsgBox("You have to pick a type of transportaion.", , "Wow, did you really?")
End If
Case 1
If blnValidateTransportation = True Then
strDailyCost = InputBox(strDailyCostAsk, strCostTitle)
ValidateCostPerDay()
If blnValidateCostPerDay = True Then
strDaysInMonth = InputBox(strDaysInMonthAsk, strDaysTitle)
ValidateDaysInMonth()
If blnValidateDaysInMonth = True Then
decMonthlyCost = Convert.ToDecimal(Convert.ToDecimal(strDailyCost) * 1) * intDaysInMonth
decYearlyCost = decMonthlyCost * 12
lblCommuteCostDisplay.Text = "Your yearly commute cost is " & decYearlyCost.ToString("C")
lblCommuteCostDisplay.Visible = True
btnCalculate.Enabled = False
Else
MsgBox("Enter a reasonable number of days, please.", , "Wow, did you really?")
End If
Else
MsgBox("Your price has to be between $1 and $59.99", , "Wow, did you really?")
End If
Else
MsgBox("You have to pick a type of transportaion.", , "Wow, did you really?")
End If
Case 2
If blnValidateTransportation = True Then
strDailyCost = InputBox(strDailyCostAsk, strCostTitle)
ValidateCostPerDay()
If blnValidateCostPerDay = True Then
strDaysInMonth = InputBox(strDaysInMonthAsk, strDaysTitle)
ValidateDaysInMonth()
If blnValidateDaysInMonth = True Then
decMonthlyCost = Convert.ToDecimal(Convert.ToDecimal(strDailyCost) * 1) * intDaysInMonth
decYearlyCost = decMonthlyCost * 12
lblCommuteCostDisplay.Text = "Your yearly commute cost is " & decYearlyCost.ToString("C")
lblCommuteCostDisplay.Visible = True
btnCalculate.Enabled = False
Else
MsgBox("Enter a reasonable number of days, please.", , "Wow, did you really?")
End If
Else
MsgBox("Your price has to be between $1 and $59.99", , "Wow, did you really?")
End If
Else
MsgBox("You have to pick a type of transportaion.", , "Wow, did you really?")
End If
End Select
Catch ex As Exception
MsgBox("You broke it, Way to go.", , "Wow, did you really?")
End Try
End Sub
Private Function ValidateDaysInMonth() As Boolean
'This procedure validates the input for workdays in a month
intDaysInMonth = Convert.ToInt32(strDaysInMonth)
If intDaysInMonth < 31 And intDaysInMonth > 0 Then
blnValidateDaysInMonth = True
Else
blnValidateDaysInMonth = False
intDaysInMonth = Convert.ToInt32(InputBox("Please enter your average number of workdays in a month; between 1 and 28 days. ", "Error"))
ValidateDaysInMonth()
End If
Return blnValidateDaysInMonth
End Function
Private Function ValidateCostPerDay() As Boolean
' This function validates the Cost Per Day Input
Dim strDailyCostError As String = "Please enter a valid cost between $1 and $59.99"
Dim strMessageBoxTitle As String = "Error"
decCostPerDay = Convert.ToDecimal(strDailyCost)
If decCostPerDay > 0.99 And decCostPerDay < 60 Then
blnValidateCostPerDay = True
Else
blnValidateCostPerDay = False
decCostPerDay = Convert.ToDecimal(InputBox(strDailyCostError, strMessageBoxTitle))
ValidateCostPerDay()
End If
Return blnValidateCostPerDay
End Function
Private Function ValidateTransportType() As Boolean
'Ensures that The type of transportation is selected.
Dim intTransportType As Integer
'call a funtion to ensure the type of transport is selected.
intTransportType = Convert.ToInt32(cboTransportationMethod.SelectedIndex)
If cboTransportationMethod.SelectedIndex <= 2 And cboTransportationMethod.SelectedIndex >= 0 Then
blnValidateTransportation = True
Else
'Detects If a Transport type is Selected
blnValidateTransportation = False
MsgBox("Please select a transport type", , "First Step")
End If
Return blnValidateTransportation
End Function
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Close()
End Sub
Private Sub ClearToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ClearToolStripMenuItem.Click
'Executed when menu item Clear is clicked
lblCommuteCostDisplay.Visible = False
cboTransportationMethod.Text = "Type of Transport"
btnCalculate.Enabled = True
End Sub
End Class
|
Imports System.Data.OleDb
Imports Powertrain_Task_Manager.Common
Imports Powertrain_Task_Manager.Models
Namespace Repositories
Public Class SectionsRepository
Property DbSqlHelper As SqlHelper
Public Sub New(ByVal dbSqlHelper As SqlHelper)
Me.DbSqlHelper = dbSqlHelper
End Sub
Public Function GetSections() As DataTable
Dim query As String = "select * from Sections "
Dim dt = New DataTable
Try
dt = DbSqlHelper.ExcuteDataSet(query).Tables(0)
Catch ex As Exception
Log_Anything("GetSections - " & GetExceptionInfo(ex))
End Try
Return dt
End Function
Public Sub InsertSection(sectionObj As SectionModel)
Dim query = "INSERT INTO Sections (Area_Name,Section_Name) VALUES (@Area_Name,@Section_Name)"
Dim params = New List(Of OleDbParameter)()
params.Add(New OleDbParameter("@Area_Name", sectionObj.AreaName))
params.Add(New OleDbParameter("@Section_Name", sectionObj.SectionName))
Try
DbSqlHelper.ExcuteNonQuery(CommandType.Text, query, params)
Catch ex As Exception
Log_Anything("InsertSection - " & GetExceptionInfo(ex))
End Try
End Sub
Public Sub DeleteAllSections()
Dim query = "DELETE * FROM Sections"
DbSqlHelper.ExcuteNonQuery(query)
End Sub
Public Function GetListSections(ByVal dt As DataTable) As List(Of SectionModel)
Dim listSectionStructure As List(Of SectionModel) = New List(Of SectionModel)
For i = 0 To dt.Rows.Count - 1
Dim sectionModel As SectionModel = New SectionModel
sectionModel.Id = Integer.Parse(dt.Rows(i)("ID").ToString)
sectionModel.AreaName = dt.Rows(i)("Area_Name").ToString
sectionModel.SectionName = dt.Rows(i)("Section_Name").ToString
listSectionStructure.Add(sectionModel)
Next
Return listSectionStructure
End Function
End Class
End Namespace
|
'Project: Sales Calculator Class
'Programmer: Arthur Buckowitz
'Date: August 6, 2012
'Description: Business Logic for sales calculator
Public Class SalesCommission
Const DECBASEPAY As Decimal = 250
Const DECQUOTA As Decimal = 1000
Const DECCOMMISSION As Decimal = 0.15
Private _name As String
Private _sales As Decimal
Private Shared EarnedCommission As Decimal
Private Shared Earned As Decimal
Private Shared TotalSales As Decimal
Private Shared TotalCommission As Decimal
Private Shared TotalEarned As Decimal
Public Sub New(Name As String, Sales As Decimal)
Me.Name = Name
Me.Sales = Sales
EarnedCommission = CalculateCommission()
Earned = CalculateEarned()
TotalSales = TotalSales + Sales
TotalCommission = TotalCommission + CalculateCommission()
TotalEarned = TotalEarned + CalculateEarned()
End Sub
Shared ReadOnly Property Pay As Decimal
Get
Return Earned
End Get
End Property
Shared ReadOnly Property Commission As Decimal
Get
Return EarnedCommission
End Get
End Property
Public Property Name As String
Get
Return Me._name
End Get
Set(value As String)
If value.Trim <> "" Then
Me._name = value
End If
End Set
End Property
Public Property Sales As Decimal
Get
Return Me._sales
End Get
Set(value As Decimal)
If value >= 0 Then
Me._sales = value
End If
End Set
End Property
Shared ReadOnly Property SalesTotal As Decimal
Get
Return TotalSales
End Get
End Property
Shared ReadOnly Property CommissionTotal As Decimal
Get
Return TotalCommission
End Get
End Property
Shared ReadOnly Property EarnedTotal As Decimal
Get
Return TotalEarned
End Get
End Property
Protected Function CalculateCommission() As Decimal
Dim Commission As Decimal
If _sales >= DECQUOTA Then
Commission = _sales * DECCOMMISSION
Else
Commission = 0
End If
Return Commission
End Function
Protected Function CalculateEarned() As Decimal
Dim Earned As Decimal
Earned = DECBASEPAY + CalculateCommission()
Return Earned
End Function
End Class
|
Imports Microsoft.VisualBasic
Imports System
Imports System.Xml
Imports Talent.Common
'--------------------------------------------------------------------------------------------------
' Project Trading Portal Project.
'
' Function This class is used to load Product Groups and their hierarchy
'
' Date 09/10/08
'
' Author Ben Ford
'
' © CS Group 2007 All rights reserved.
'
' Error Number Code base TTPRQPSLR-
'
' Modification Summary
'
' dd/mm/yy ID By Description
' -------- ----- --- -----------
'
'--------------------------------------------------------------------------------------------------
Namespace Talent.TradingPortal
Public Class XmlProductStockLoadRequest
Inherits XmlRequest
'Invoke constructor on base, passing web service name
Public Sub New(ByVal webserviceName As String)
MyBase.new(webserviceName)
End Sub
Dim deStock As New DEStock
Dim deWarehouses As DEWarehouses
Dim deProducts As DEStockProducts
Dim deDefaults As DEStockDefaults
Public Overrides Function AccessDatabase(ByVal xmlResp As XmlResponse) As XmlResponse
Dim xmlLoadResponse As XmlProductStockLoadResponse = CType(xmlResp, XmlProductStockLoadResponse)
Dim err As ErrorObj = Nothing
'--------------------------------------------------------------------
Select Case MyBase.DocumentVersion
Case Is = "1.0"
err = LoadXmlV1()
End Select
'--------------------------------------------------------------------
' Place the Request
'
Dim PRODUCT As New TalentProduct
If err.HasError Then
xmlResp.Err = err
Else
With PRODUCT
Settings.BackOfficeConnectionString = ""
.Settings = Settings
.Stock = deStock
err = .ProductStockLoad()
End With
If err.HasError Or Not err Is Nothing Then
xmlResp.Err = err
End If
End If
XmlLoadResponse.ResultDataSet = PRODUCT.ResultDataSet
xmlResp.SenderID = Settings.SenderID
xmlResp.CreateResponse()
Return CType(xmlLoadResponse, XmlResponse)
End Function
Private Function LoadXmlV1() As ErrorObj
Const ModuleName As String = "LoadXmlV1"
Dim err As New ErrorObj
'--------------------------------------------------------------------------
Dim node1 As XmlNode
Dim total As Integer = 0
Dim mode As String = String.Empty
Dim hierarchiesTotal As Integer = 0
Dim hierarchiesCount As Integer = 0
'-------------------------------------------------------------------------------------
' We have the full XMl document held in xmlDoc. Putting all the data found into Data
' Entities
'-------------------------------------------------------------------------------------
Try
For Each node1 In xmlDoc.SelectSingleNode("//ProductStockLoadRequest").ChildNodes
Select Case node1.Name
Case Is = "TransactionHeader"
Case Is = "warehouses"
deWarehouses = ExtractWarehouses(node1)
deStock.deWarehouses.add(deWarehouses)
Case Is = "Products"
deProducts = ExtractProducts(node1)
deStock.Products.Add(deProducts)
Case Is = "Defaults"
deDefaults = ExtractDefaults(node1)
deStock.Defaults.Add(deDefaults)
If hierarchiesTotal <> hierarchiesCount Then
With err
.ErrorMessage = "Invalid number of hierarchies supplied"
.ErrorStatus = ModuleName & " Error: " & .ErrorMessage
.ErrorNumber = "TTPRQPSLR-04"
.HasError = True
End With
End If
End Select
Next node1
Catch ex As Exception
With err
.ErrorMessage = ex.Message
.ErrorStatus = ModuleName & " Error" & ex.Message
.ErrorNumber = "TTPRQPSLR-01"
.HasError = True
End With
End Try
Return err
End Function
Private Function ExtractWarehouses(ByVal warehousesNode As XmlNode) As DEWarehouses
Dim deWarehouses As DEWarehouses = New DEWarehouses()
If Not warehousesNode.Attributes("Total") Is Nothing Then
deWarehouses.Total = Integer.Parse(warehousesNode.Attributes("Total").Value)
End If
If Not warehousesNode.Attributes("Mode") Is Nothing Then
deWarehouses.Mode = warehousesNode.Attributes("Mode").Value
End If
For Each warehouseNode As XmlNode In warehousesNode.ChildNodes
Select Case warehouseNode.Name
Case Is = "Warehouse"
Dim deWarehouse As DEWarehouse = New DEWarehouse()
If Not warehouseNode.Attributes("Mode") Is Nothing Then
deWarehouse.Mode = warehouseNode.Attributes("Mode").Value
End If
For Each child As XmlNode In warehouseNode.ChildNodes
Select Case child.Name
Case Is = "Code"
deWarehouse.Code = child.InnerText
Case Is = "Description"
deWarehouse.Description = child.InnerText
If Not child.Attributes("Language") Is Nothing Then
deWarehouse.DescriptionLanguage = child.Attributes("Language").Value
End If
Case Else
Throw New Exception("Unknown child node of warehouse node")
End Select
Next
deWarehouses.Warehouses.Add(deWarehouse)
Case Else
Throw New Exception("Unknown child node of warehouses node")
End Select
Next
Return deWarehouses
End Function
Private Function ExtractProducts(ByVal productsNode As XmlNode) As DEStockProducts
Dim products As DEStockProducts = New DEStockProducts()
If Not productsNode.Attributes("Total") Is Nothing Then
products.Total = Integer.Parse(productsNode.Attributes("Total").Value)
End If
If Not productsNode.Attributes("Mode") Is Nothing Then
products.Mode = productsNode.Attributes("Mode").Value
End If
For Each productNode As XmlNode In productsNode.ChildNodes
Select Case productNode.Name
Case Is = "Product"
Dim product As DEStockProduct = New DEStockProduct
If Not productNode.Attributes("Mode") Is Nothing Then
product.Mode = productNode.Attributes("Mode").Value
End If
For Each child As XmlNode In productNode.ChildNodes
Select Case child.Name
Case Is = "SKU"
product.SKU = child.InnerText
Case Is = "Quantity"
product.Quantity = Integer.Parse(child.InnerText)
If Not child.Attributes("Warehouse") Is Nothing Then
product.QuantityWarehouse = child.Attributes("Warehouse").Value
End If
If Not child.Attributes("ReStockCode") Is Nothing Then
product.QuantityReStockCode = child.Attributes("ReStockCode").Value
End If
Case Else
Throw New Exception("Unknown child node of products node")
End Select
Next
products.StockProducts.Add(product)
End Select
Next
Return products
End Function
Private Function ExtractDefaults(ByVal defaultsNode As XmlNode) As DEStockDefaults
Dim defaults As DEStockDefaults = New DEStockDefaults()
If Not defaultsNode.Attributes("Total") Is Nothing Then
defaults.Total = Integer.Parse(defaultsNode.Attributes("Total").Value)
End If
If Not defaultsNode.Attributes("Mode") Is Nothing Then
defaults.Mode = defaultsNode.Attributes("Mode").Value
End If
Dim stockDefault As DEStockDefault = New DEStockDefault
For Each defaultNode As XmlNode In defaultsNode.ChildNodes
Select Case defaultNode.Name
Case Is = "Warehouse"
stockDefault.Warehouse = defaultNode.InnerText
If Not defaultNode.Attributes("Mode") Is Nothing Then
stockDefault.Mode = defaultNode.Attributes("Mode").Value
End If
If Not defaultNode.Attributes("BusinessUnit") Is Nothing Then
stockDefault.BusinessUnit = defaultNode.Attributes("BusinessUnit").Value
End If
If Not defaultNode.Attributes("Partner") Is Nothing Then
stockDefault.Partner = defaultNode.Attributes("Partner").Value
End If
Case Else
End Select
Next
defaults.Defaults.Add(stockDefault)
Return defaults
End Function
'--------------------------------------------------
' Extract a product group from a product group node
'--------------------------------------------------
Private Function ExtractProductGroup(ByVal productGroupNode As XmlNode) As DEProductGroup
' Const ModuleName As String = "ExtractProductGroup"
Dim deProductGroup As New DEProductGroup
Dim node1, node2 As XmlNode
Dim deProductGroupDetails As DEProductGroupDetails
If Not productGroupNode.Attributes("Mode") Is Nothing Then
deProductGroup.Mode = productGroupNode.Attributes("Mode").Value
End If
deProductGroup.Details = New Collection
For Each node1 In productGroupNode.ChildNodes
Select Case node1.Name
Case Is = "Code"
deProductGroup.Code = node1.InnerText
Case Is = "Details"
'----------------------------------------
' Loop through language specific settings
' and add to details collection
'----------------------------------------
deProductGroupDetails = New DEProductGroupDetails
deProductGroupDetails.Language = node1.Attributes("Language").Value
For Each node2 In node1.ChildNodes
Select Case node2.Name
Case Is = "Description1"
deProductGroupDetails.Description1 = node2.InnerText
Case Is = "Description2"
deProductGroupDetails.Description2 = node2.InnerText
Case Is = "HTML1"
deProductGroupDetails.Html1 = node2.InnerText
Case Is = "HTML2"
deProductGroupDetails.Html2 = node2.InnerText
Case Is = "HTML3"
deProductGroupDetails.Html3 = node2.InnerText
Case Is = "PageTitle"
deProductGroupDetails.PageTitle = node2.InnerText
Case Is = "MetaDescription"
deProductGroupDetails.MetaDescription = node2.InnerText
Case Is = "MetaKeywords"
deProductGroupDetails.MetaKeywords = node2.InnerText
End Select
Next node2
deProductGroup.Details.Add(deProductGroupDetails)
End Select
Next node1
Return deProductGroup
End Function
'----------------------------------------------------------------------
' Extract a product group hierarchy from a product group hierarchy node
'----------------------------------------------------------------------
Private Function ExtractProductGroupHierarchy(ByVal productGroupHierarchyNode As XmlNode) As DEProductGroupHierarchy
Const ModuleName As String = "ExtractProductGroupHierarchy"
Dim deProductGroupHierarchy As New DEProductGroupHierarchy
deProductGroupHierarchy.Err = New ErrorObj
Dim node1, node2 As XmlNode
Dim deProductGroupHierarchyGroup1 As DEProductGroupHierarchyGroup
Dim level1groupsCount As Integer = 0
deProductGroupHierarchy.BusinessUnit = productGroupHierarchyNode.Attributes("BusinessUnit").Value
deProductGroupHierarchy.Partner = productGroupHierarchyNode.Attributes("Partner").Value
deProductGroupHierarchy.Mode = productGroupHierarchyNode.Attributes("Mode").Value
deProductGroupHierarchy.Level1Groups = New Collection
For Each node1 In productGroupHierarchyNode.ChildNodes
Select Case node1.Name
Case Is = "Defaults"
For Each node2 In node1.ChildNodes
Select Case node2.Name
Case Is = "LastProductAfterLevel"
deProductGroupHierarchy.LastProductAfterLevel = node2.InnerText
End Select
Next
Case Is = "Level1"
deProductGroupHierarchy.Level1GroupsTotal = CInt(node1.Attributes("Total").Value)
For Each node2 In node1.ChildNodes
Select Case node2.Name
Case Is = "ProductGroup"
level1groupsCount += 1
deProductGroupHierarchyGroup1 = ExtractProductGroupHierarchyGroup(node2, deProductGroupHierarchy.BusinessUnit, deProductGroupHierarchy.Partner)
If deProductGroupHierarchyGroup1.Err.HasError Then
deProductGroupHierarchy.Err = deProductGroupHierarchyGroup1.Err
End If
deProductGroupHierarchy.Level1Groups.Add(deProductGroupHierarchyGroup1)
End Select
Next
End Select
Next node1
If deProductGroupHierarchy.Level1GroupsTotal <> deProductGroupHierarchy.Level1Groups.Count Then
With deProductGroupHierarchy.Err
.ErrorMessage = "Invalid number of Level 1 groups supplied"
.ErrorStatus = ModuleName & " Error: " & .ErrorMessage
.ErrorNumber = "TTPRQPSLR-06"
.HasError = True
End With
End If
Return deProductGroupHierarchy
End Function
'----------------------------------------------------------------------------------
' Extract a product group hierarchy group from a product group hierarchy group node
'----------------------------------------------------------------------------------
Private Function ExtractProductGroupHierarchyGroup(ByVal productGroupHierarchyGroupNode As XmlNode, ByVal businessUnit As String, ByVal partner As String) As DEProductGroupHierarchyGroup
Const ModuleName As String = "ExtractProductGroupHierarchyGroup"
Dim deProductGroupHierarchyGroup As New DEProductGroupHierarchyGroup
deProductGroupHierarchyGroup.Err = New ErrorObj
Dim deProductGroupHierarchyGroup2 As DEProductGroupHierarchyGroup
Dim product As New DEProductEcommerceDetails
deProductGroupHierarchyGroup.NextLevelGroups = New Collection
Dim node2, node3, node4 As XmlNode
deProductGroupHierarchyGroup.BusinessUnit = businessUnit
deProductGroupHierarchyGroup.Partner = partner
deProductGroupHierarchyGroup.Products = New Collection
If Not productGroupHierarchyGroupNode.Attributes("Mode") Is Nothing Then
deProductGroupHierarchyGroup.Mode = productGroupHierarchyGroupNode.Attributes("Mode").Value
End If
deProductGroupHierarchyGroup.NextLevelGroups = New Collection
For Each node2 In productGroupHierarchyGroupNode.ChildNodes
Select Case node2.Name
Case Is = "Code"
deProductGroupHierarchyGroup.Code = node2.InnerText
Case Is = "DisplaySequence"
deProductGroupHierarchyGroup.DisplaySequence = node2.InnerText
Case Is = "AdvancedSearchTemplate"
deProductGroupHierarchyGroup.AdvancedSearchTemplate = node2.InnerText
Case Is = "ProductPageTemplate"
deProductGroupHierarchyGroup.ProductPageTemplate = node2.InnerText
Case Is = "ProductListTemplate"
deProductGroupHierarchyGroup.ProductListTemplate = node2.InnerText
Case Is = "ShowChildrenAsGroups"
deProductGroupHierarchyGroup.ShowChildrenAsGroups = node2.InnerText
Case Is = "ShowProductsAsList"
deProductGroupHierarchyGroup.ShowProductAsList = node2.InnerText
Case Is = "ShowInNavigation"
deProductGroupHierarchyGroup.ShowInNavigation = node2.InnerText
Case Is = "ShowInGroupedNavigation"
deProductGroupHierarchyGroup.ShowInGroupedNavigation = node2.InnerText
Case Is = "HTMLGroup"
deProductGroupHierarchyGroup.HtmlGroup = node2.InnerText
Case Is = "HTMLGroupType"
deProductGroupHierarchyGroup.HtmlGroupType = node2.InnerText
Case Is = "ShowProductDisplay"
deProductGroupHierarchyGroup.ShowProductDisplay = node2.InnerText
Case Is = "Theme"
deProductGroupHierarchyGroup.Theme = node2.InnerText
Case Is = "Products"
deProductGroupHierarchyGroup.ProductsTotal = CInt(node2.Attributes("Total").Value)
For Each node3 In node2.ChildNodes
Select Case node3.Name
Case Is = "Product"
product = New DEProductEcommerceDetails
If Not node3.Attributes("Mode") Is Nothing Then
product.Mode = node3.Attributes("Mode").Value
End If
For Each node4 In node3.ChildNodes
Select Case node4.Name
Case Is = "SKU"
product.Sku = node4.InnerText
Case Is = "DisplaySequence"
product.DisplaySequence = node4.InnerText
End Select
Next
deProductGroupHierarchyGroup.Products.Add(product)
End Select
Next
If deProductGroupHierarchyGroup.ProductsTotal <> deProductGroupHierarchyGroup.Products.Count Then
With deProductGroupHierarchyGroup.Err
.ErrorMessage = "Invalid number of products groups supplied: " & deProductGroupHierarchyGroup.Code
.ErrorStatus = ModuleName & " Error: " & .ErrorMessage
.ErrorNumber = "TTPRQPSLR-08"
.HasError = True
End With
End If
Case Is = "Level2", "Level3", "Level4", "Level5", "Level6", "Level7", "Level8", "Level9", "Level10"
deProductGroupHierarchyGroup.NextLevelGroupsTotal = CInt(node2.Attributes("Total").Value)
For Each node3 In node2.ChildNodes
Select Case node3.Name
Case Is = "ProductGroup"
'------------------------------------------------------------------------
' Recursive call to extract the next group. Add to this groups collection
' of child groups
'---------------------------------------------------------
deProductGroupHierarchyGroup2 = New DEProductGroupHierarchyGroup
deProductGroupHierarchyGroup2 = ExtractProductGroupHierarchyGroup(node3, businessUnit, partner)
If deProductGroupHierarchyGroup2.Err.HasError Then
deProductGroupHierarchyGroup.Err = deProductGroupHierarchyGroup2.Err
End If
deProductGroupHierarchyGroup2.BusinessUnit = businessUnit
deProductGroupHierarchyGroup2.Partner = partner
deProductGroupHierarchyGroup.NextLevelGroups.Add(deProductGroupHierarchyGroup2)
End Select
Next
If deProductGroupHierarchyGroup.NextLevelGroupsTotal <> deProductGroupHierarchyGroup.NextLevelGroups.Count Then
With deProductGroupHierarchyGroup.Err
.ErrorMessage = "Invalid number of Level groups supplied: " & deProductGroupHierarchyGroup.Code
.ErrorStatus = ModuleName & " Error: " & .ErrorMessage
.ErrorNumber = "TTPRQPSLR-07"
.HasError = True
End With
End If
End Select
Next node2
Return deProductGroupHierarchyGroup
End Function
End Class
End Namespace |
Imports System.Runtime.InteropServices
Imports System.Threading.Tasks
Public MustInherit Class GPU_FFT
Public Enum FFTType As Integer
GPU_FFT_FWD = 0
GPU_FFT_REV = 1
End Enum
Public Structure GPU_FFT_COMPLEX
Public Re As Single
Public Im As Single
Public Sub New(ByVal Re As Single, ByVal Im As Single)
Me.Re = Re
Me.Im = Im
End Sub
Public Overrides Function ToString() As String
Return Re & "+j" & Im
End Function
End Structure
Protected m_MB As Integer
Protected m_FFTType As FFTType
Protected Declare Auto Function gpu_fft_prepare Lib "gpufft" (ByVal MB As Integer, ByVal Log2_N As Integer, ByVal Direction As Integer, ByVal Jobs As Integer, ByRef GPU_FFT As IntPtr) As Integer
Protected Declare Auto Function mbox_open Lib "gpufft" () As Integer
Protected Declare Auto Sub mbox_close Lib "gpufft" (ByVal FilePtr As Integer)
Protected Declare Auto Function gpu_fft_execute Lib "gpufft" (ByVal GPU_FFT As IntPtr) As UInt32
Protected Declare Auto Sub gpu_fft_release Lib "gpufft" (ByVal GPU_FFT As IntPtr)
Protected Declare Auto Sub gpu_fft_copy_data_in Lib "gpufft" (ByVal GPU_FFT As IntPtr, ByVal array() As GPU_FFT_COMPLEX, ByVal data_width As Integer, ByVal data_height As Integer)
Protected Declare Auto Sub gpu_fft_copy_data_out Lib "gpufft" (ByVal GPU_FFT As IntPtr, ByVal array() As GPU_FFT_COMPLEX, ByVal data_width As Integer, ByVal data_height As Integer)
Protected Declare Auto Sub gpu_fft_clear_data_in Lib "gpufft" (ByVal GPU_FFT As IntPtr)
Protected Declare Auto Function gpu_fft_trans_prepare Lib "gpufft" (ByVal MB As Integer, ByVal GPU_FFT_Src As IntPtr, ByVal GPU_FFT_Dst As IntPtr, ByRef GPU_FFT_Trans_Out As IntPtr) As Integer
Protected Declare Auto Function gpu_fft_trans_execute Lib "gpufft" (ByVal GPU_FFT_Trans As IntPtr) As Integer
Protected Declare Auto Function gpu_fft_trans_release Lib "gpufft" (ByVal GPU_FFT_Trans As IntPtr) As Integer
Public Class GPU_FFTException
Inherits Exception
Public Code As Integer
Public Sub New(ByVal Code As Integer, ByVal Message As String)
MyBase.New(Message)
Me.Code = Code
End Sub
End Class
Public MustOverride Sub SetDataIn(ByRef Data() As GPU_FFT_COMPLEX)
Public MustOverride Function GetDataOut() As GPU_FFT_COMPLEX()
Public MustOverride Function GetScaledDataOut() As GPU_FFT_COMPLEX()
Public MustOverride Function Execute() As UInt32
Public MustOverride Sub Release()
Public Overridable Function GetClosestPow2(ByVal Number As Integer) As Integer
Dim Pow As Integer = 2
While Pow < Number
Pow <<= 1
End While
Return Pow
End Function
Public Overridable Function Log2(ByVal Number As Integer) As Integer
Dim Log As Integer = 0
While Number > 0
Number >>= 1
Log += 1
End While
Return Log - 1
End Function
Protected Overridable Function CheckInitResult(ByVal Result As Integer) As Boolean
Select Case Result
Case -1
Throw New GPU_FFTException(-1, "Unable to enable V3D. Please check your firmware is up to date.")
Case -2
Throw New GPU_FFTException(-2, "log2_N=%d not supported. Try between 8 and 22.")
Case -3
Throw New GPU_FFTException(-3, "Out of memory. Try a smaller batch or increase GPU memory.")
Case -4
Throw New GPU_FFTException(-4, "Unable to map Videocore peripherals into ARM memory space.")
Case -5
Throw New GPU_FFTException(-5, "Can't open libbcm_host.")
Case Else
Return True
End Select
Return False
End Function
Protected Overrides Sub Finalize()
MyBase.Finalize()
Release()
End Sub
End Class
Public Class GPU_FFT_1D
Inherits GPU_FFT
Protected m_GPU_FFT As IntPtr 'Pointer to FFT Handle
Protected m_DataOut As GPU_FFT_COMPLEX()
Protected m_WindowSize As Integer
Protected m_Size As Integer
Protected m_Jobs As Integer
Protected m_DataInSize As Integer
Protected m_DataOutSize As Integer
''' <summary>
''' Initializes a 1D FFT object
''' For FFTType=GPU_FFT_FWD
''' If size is not a power of 2 the input data will be zero padded to a power of 2
''' The output data size will always be a power of 2 >= size
''' For FFType=GPU_FFT_REV
''' Size determines the size of the output data, input data must always be a power of 2 >=size, complex numbers representing the frequencies, amplitude and phase
''' if size is not a power of 2 the output data size will be truncated to size
''' </summary>
''' <param name="Size">The x size of the: input data for FWD or output data for REV</param>
''' <param name="FFTType">Forward or reverse FFT</param>
''' <param name="Jobs">Number of FFTs to calculate, input data size must be: 2^log2N * jobs</param>
Public Sub New(ByVal Size As Integer, ByVal FFTType As FFTType, ByVal Jobs As Integer)
m_FFTType = FFTType
m_Size = Size
m_WindowSize = GetClosestPow2(Size)
m_MB = mbox_open()
m_Jobs = Jobs
If CheckInitResult(gpu_fft_prepare(m_MB, Log2(m_WindowSize), FFTType, Jobs, m_GPU_FFT)) Then
If Size < m_WindowSize Then gpu_fft_clear_data_in(m_GPU_FFT)
If FFTType = FFTType.GPU_FFT_FWD Then
m_DataOutSize = m_WindowSize
m_DataInSize = Size
Else
m_DataOutSize = Size
m_DataInSize = m_WindowSize
End If
ReDim m_DataOut(0 To m_DataOutSize * Jobs - 1)
End If
End Sub
''' <summary>
''' Copies input data array of the FFT
''' </summary>
''' <param name="Data"></param>
Public Overrides Sub SetDataIn(ByRef Data() As GPU_FFT_COMPLEX)
gpu_fft_copy_data_in(m_GPU_FFT, Data, m_DataInSize, m_Jobs)
End Sub
''' <summary>
''' Copies the output data of the FFT to an array
''' </summary>
''' <returns></returns>
Public Overrides Function GetDataOut() As GPU_FFT_COMPLEX()
gpu_fft_copy_data_out(m_GPU_FFT, m_DataOut, m_DataOutSize, m_Jobs)
Return m_DataOut
End Function
''' <summary>
''' Returns a scaled output after a forward FFT
''' Setting the scaled output data as input data for a reverse FFT will result in the original data
''' </summary>
''' <returns></returns>
Public Overrides Function GetScaledDataOut() As GPU_FFT_COMPLEX()
Dim Data() As GPU_FFT_COMPLEX = GetDataOut()
If m_FFTType = FFTType.GPU_FFT_FWD Then
Parallel.ForEach(Data, Sub(ByVal Sample As GPU_FFT_COMPLEX, loopstate As ParallelLoopState, Index As Integer)
With Data(Index)
.Re = Sample.Re / m_WindowSize
.Im = Sample.Im / m_WindowSize
End With
End Sub)
End If
Return Data
End Function
''' <summary>
''' Executes the FFT
''' </summary>
''' <returns></returns>
Public Overrides Function Execute() As UInt32
Return gpu_fft_execute(m_GPU_FFT)
End Function
''' <summary>
''' Returns the FFT window size
''' Usually this is the closest power of 2 in size
''' </summary>
''' <returns></returns>
Public Overridable ReadOnly Property WindowSize()
Get
Return m_WindowSize
End Get
End Property
''' <summary>
''' Returns the x size of the input data
''' total array size is DataInSize * Jobs
''' </summary>
''' <returns></returns>
Public Overridable ReadOnly Property DataInSize()
Get
Return m_DataInSize
End Get
End Property
''' <summary>
''' Returns the x size of the output data
''' total array size is DataOutSize * jobs
''' </summary>
''' <returns></returns>
Public Overridable ReadOnly Property DataOutSize()
Get
Return m_DataOutSize
End Get
End Property
''' <summary>
''' For forward FFT this returns the x size of the input data
''' for reverse FFT this returns the x size of the output data
''' </summary>
''' <returns></returns>
Public Overridable ReadOnly Property Size()
Get
Return m_Size
End Get
End Property
''' <summary>
''' Returns the Y-size of the input/output arrays
''' a.k.a. the number of FFT's to execute in one execute() call
''' </summary>
''' <returns></returns>
Public Overridable ReadOnly Property Jobs()
Get
Return m_Jobs
End Get
End Property
Public Overrides Sub Release()
If m_GPU_FFT <> 0 Then
gpu_fft_release(m_GPU_FFT)
m_GPU_FFT = 0
End If
End Sub
Protected Overrides Sub Finalize()
MyBase.Finalize()
Release()
End Sub
End Class
Public Class GPU_FFT_2D
Inherits GPU_FFT
Protected m_GPU_FFT(0 To 1) As IntPtr
Protected m_GPU_Trans As IntPtr
Protected m_DataOut() As GPU_FFT_COMPLEX
Protected m_WindowSizeX As Integer
Protected m_WindowSizeY As Integer
Protected m_DataOutSizeX As Integer
Protected m_DataOutSizeY As Integer
Protected m_DataInSizeX As Integer
Protected m_DataInSizeY As Integer
Protected m_y As Integer
Protected m_x As Integer
Protected m_InitOK As Boolean
''' <summary>
''' Initializes a 2D FFT object
''' For FFTType=GPU_FFT_FWD
''' If x/y not a power of 2 the input data will be zero padded to a power of 2
''' The output data size will always be a power of 2 >= size (and a square)
''' For FFType=GPU_FFT_REV
''' x,y determines the size of the output data, input data must always be a power of 2 >=size (and a square), complex numbers representing the frequencies, amplitude and phase
''' if x,y is not a power of 2 the output data will be truncated to x*y
''' </summary>
''' <param name="x">The x size of the: input data for forward FFT, size of output data for reverse FFT</param>
''' <param name="y">The y size of the: input data for forward FFT, size of the output data for reverse FFT</param>
''' <param name="FFTType">Forward or reverse FFT</param>
Public Sub New(ByVal x As Integer, ByVal y As Integer, ByVal FFTType As FFTType)
m_FFTType = FFTType
m_WindowSizeX = Math.Max(GetClosestPow2(x), GetClosestPow2(y))
m_WindowSizeY = m_WindowSizeX
m_MB = mbox_open()
m_x = x
m_y = y
If Not CheckInitResult(gpu_fft_prepare(m_MB, Log2(m_WindowSizeX), FFTType, m_WindowSizeY, m_GPU_FFT(0))) Then
Throw New Exception("GPU FFT prepare 1 failed!")
Exit Sub
End If
If Not CheckInitResult(gpu_fft_prepare(m_MB, Log2(m_WindowSizeY), FFTType, m_WindowSizeX, m_GPU_FFT(1))) Then
gpu_fft_release(m_GPU_FFT(0))
Throw New Exception("GPU FFT Prepare 2 failed")
End If
If gpu_fft_trans_prepare(m_MB, m_GPU_FFT(0), m_GPU_FFT(1), m_GPU_Trans) <> 0 Then
gpu_fft_release(m_GPU_FFT(0))
gpu_fft_release(m_GPU_FFT(1))
Throw New Exception("Initialization of GPU Trans failed!")
End If
If FFTType = FFTType.GPU_FFT_FWD Then
m_DataOutSizeX = m_WindowSizeX
m_DataOutSizeY = m_WindowSizeY
m_DataInSizeX = x
m_DataInSizeY = y
Else
m_DataOutSizeX = x
m_DataOutSizeY = y
m_DataInSizeX = m_WindowSizeX
m_DataInSizeY = m_WindowSizeY
End If
gpu_fft_clear_data_in(m_GPU_FFT(0))
gpu_fft_clear_data_in(m_GPU_FFT(1))
ReDim m_DataOut(0 To m_DataOutSizeX * m_DataOutSizeY - 1)
m_InitOK = True
End Sub
Public Overrides Sub SetDataIn(ByRef Data() As GPU_FFT_COMPLEX)
gpu_fft_copy_data_in(m_GPU_FFT(0), Data, m_DataInSizeX, m_DataInSizeY)
End Sub
Public Overrides Sub Release()
If m_InitOK Then
gpu_fft_release(m_GPU_FFT(0))
gpu_fft_release(m_GPU_FFT(1))
gpu_fft_trans_release(m_GPU_Trans)
m_InitOK = False
End If
End Sub
Public Overrides Function GetDataOut() As GPU_FFT_COMPLEX()
gpu_fft_copy_data_out(m_GPU_FFT(1), m_DataOut, m_DataOutSizeX, m_DataOutSizeY)
Return m_DataOut
End Function
''' <summary>
''' Returns a scaled output after a forward FFT
''' Setting the scaled output data as input data for a reverse FFT will result in the original image
''' </summary>
''' <returns></returns>
Public Overrides Function GetScaledDataOut() As GPU_FFT_COMPLEX()
Dim Data() As GPU_FFT_COMPLEX = GetDataOut()
Dim ScaleFactor As Single = m_WindowSizeX * m_WindowSizeY
If m_FFTType = FFTType.GPU_FFT_FWD Then
Parallel.ForEach(Data, Sub(ByVal Sample As GPU_FFT_COMPLEX, loopstate As ParallelLoopState, Index As Integer)
With Data(Index)
.Re = Sample.Re / ScaleFactor
.Im = Sample.Im / ScaleFactor
End With
End Sub)
End If
Return Data
End Function
Public Overrides Function Execute() As UInteger
gpu_fft_execute(m_GPU_FFT(0))
gpu_fft_trans_execute(m_GPU_Trans)
gpu_fft_execute(m_GPU_FFT(1))
Return 0
End Function
Public Overridable ReadOnly Property SizeX() As Integer
Get
Return m_x
End Get
End Property
Public Overridable ReadOnly Property SizeY() As Integer
Get
Return m_y
End Get
End Property
Public Overridable ReadOnly Property WindowSizeX() As Integer
Get
Return m_WindowSizeX
End Get
End Property
Public Overridable ReadOnly Property WindowSizeY() As Integer
Get
Return m_WindowSizeY
End Get
End Property
Public Overridable ReadOnly Property DataInSizeX() As Integer
Get
Return m_DataInSizeX
End Get
End Property
Public Overridable ReadOnly Property DataInSizey() As Integer
Get
Return m_DataInSizeY
End Get
End Property
Public Overridable ReadOnly Property DataOutSizeX() As Integer
Get
Return m_DataOutSizeX
End Get
End Property
Public Overridable ReadOnly Property DataOutSizeY() As Integer
Get
Return m_DataOutSizeY
End Get
End Property
End Class |
Imports Microsoft.VisualBasic
Imports Talent.eCommerce
''' <summary>
''' The base class for talent user controls, which contains common code
''' for all user controls.
'''
''' TODO - Jason Courcoux - 13/05/09 - We should pull up all common code
''' across the talent user controls into this class.
''' </summary>
''' <remarks></remarks>
Public MustInherit Class AbstractTalentUserControl
Inherits ControlBase
#Region "VARIABLES"
Protected _businessUnit As String
Protected _partner As String
Protected _currentPage As String
Protected ucr As New Talent.Common.UserControlResource
#End Region
''' <summary>
''' This should be called from all sub classes as in the following:-
''' MyBase.Page_Load( sender, e )
'''
''' This sets the common variables and creates the module defaults, before
''' setting the user control resources for the control.
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Overridable Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
_businessUnit = TalentCache.GetBusinessUnit
_partner = TalentCache.GetPartner(HttpContext.Current.Profile)
_currentPage = Talent.eCommerce.Utilities.GetCurrentPageName()
setupUCR()
End Sub
''' <summary>
''' This method should always be overidden to set the user control resources for
''' the specific sub class.
''' </summary>
''' <remarks></remarks>
Protected MustOverride Sub setupUCR()
Protected Sub ToggleControl(ByVal control As Control, ByVal enabled As Boolean)
If TypeOf control Is WebControl Then
CType(control, WebControl).Enabled = enabled
End If
End Sub
''' <summary>
''' Recursively adds controls of a page to a list. Useful when we want to make operations on all control on a page rather than just
''' manually listing it in a non reusable way as it has been done all over the system.
''' </summary>
''' <param name="page">The root level page where we want to get controls for. Normally "Me.Controls"</param>
''' <param name="controls">The list of controls</param>
''' <remarks></remarks>
Public Shared Sub AddControls(ByVal page As System.Web.UI.ControlCollection, ByVal controls As ArrayList)
For Each c As System.Web.UI.Control In page
controls.Add(c)
If c.HasControls() Then
AddControls(c.Controls, controls)
End If
Next
End Sub
End Class
|
'======================================
' Copyright EntitySpaces, LLC 2005 - 2006
'======================================
Imports System.Data
Imports NUnit.Framework
'using Adapdev.UnitTest;
Imports BusinessObjects
Namespace Tests.Base
<TestFixture> _
Public Class NamingFixture
Private namingTestColl As New NamingTestCollection()
Private namingTest As New NamingTest()
<TestFixtureSetUp> _
Public Sub Init()
End Sub
<SetUp> _
Public Sub Init2()
namingTestColl = New NamingTestCollection()
namingTest = New NamingTest()
' The table Naming.Test has a 'dot' in it,
' so that is being tested as well.
Select Case namingTestColl.es.Connection.ProviderSignature.DataProviderName
Case "EntitySpaces.SqlClientProvider"
namingTestColl.LoadAll()
namingTestColl.MarkAllAsDeleted()
namingTestColl.Save()
Exit Select
Case Else
Exit Select
End Select
End Sub
<Test> _
Public Sub ColumnWithSpaceAndAlias()
Select Case namingTestColl.es.Connection.ProviderSignature.DataProviderName
Case "EntitySpaces.SqlClientProvider"
namingTest = namingTestColl.AddNew()
namingTest.str.TestAliasSpace = "AliasSpace"
namingTestColl.Save()
Assert.IsTrue(namingTestColl.LoadAll())
Assert.AreEqual(1, namingTestColl.Count)
Exit Select
Case Else
Assert.Ignore("Database not set up, yet.")
Exit Select
End Select
End Sub
<Test> _
Public Sub ColumnWithDot()
Select Case namingTestColl.es.Connection.ProviderSignature.DataProviderName
Case "EntitySpaces.SqlClientProvider"
namingTest = namingTestColl.AddNew()
namingTest.str.TestFieldDot = "FieldDot"
namingTestColl.Save()
Assert.IsTrue(namingTestColl.LoadAll())
Assert.AreEqual(1, namingTestColl.Count)
Exit Select
Case Else
Assert.Ignore("Database not set up, yet.")
Exit Select
End Select
End Sub
<Test> _
Public Sub ColumnWithDotAndSetGuids()
Select Case namingTestColl.es.Connection.ProviderSignature.DataProviderName
Case "EntitySpaces.SqlClientProvider"
Dim keyGuid As Guid = Guid.NewGuid()
namingTest = namingTestColl.AddNew()
namingTest.GuidKeyAlias = keyGuid
namingTest.str.TestFieldDot = "FieldDot"
namingTestColl.Save()
Assert.IsTrue(namingTestColl.LoadAll())
Assert.AreEqual(1, namingTestColl.Count)
Assert.AreEqual(namingTestColl(0).GuidKeyAlias.Value, keyGuid)
Exit Select
Case Else
Assert.Ignore("Database not set up, yet.")
Exit Select
End Select
End Sub
<Test> _
Public Sub ColumnWithUnderScoreAndAlias()
Select Case namingTestColl.es.Connection.ProviderSignature.DataProviderName
Case "EntitySpaces.SqlClientProvider"
namingTest = namingTestColl.AddNew()
namingTest.str.Test_Alias_Underscore = "AliasUnder"
namingTestColl.Save()
Assert.IsTrue(namingTestColl.LoadAll())
Assert.AreEqual(1, namingTestColl.Count)
Exit Select
Case Else
Assert.Ignore("Database not set up, yet.")
Exit Select
End Select
End Sub
<Test> _
Public Sub ColumnWithSpaceWithoutAlias()
Select Case namingTestColl.es.Connection.ProviderSignature.DataProviderName
Case "EntitySpaces.SqlClientProvider"
namingTest = namingTestColl.AddNew()
namingTest.str.TestFieldSpace = "FieldSpace"
namingTestColl.Save()
Assert.IsTrue(namingTestColl.LoadAll())
Assert.AreEqual(1, namingTestColl.Count)
Exit Select
Case Else
Assert.Ignore("Database not set up, yet.")
Exit Select
End Select
End Sub
<Test> _
Public Sub ColumnWithUnderScoreWithoutAlias()
Select Case namingTestColl.es.Connection.ProviderSignature.DataProviderName
Case "EntitySpaces.SqlClientProvider"
namingTest = namingTestColl.AddNew()
namingTest.str.TestFieldUnderscore = "FieldUnder"
namingTestColl.Save()
Assert.IsTrue(namingTestColl.LoadAll())
Assert.AreEqual(1, namingTestColl.Count)
Exit Select
Case Else
Assert.Ignore("Database not set up, yet.")
Exit Select
End Select
End Sub
End Class
End Namespace
|
#Region "Microsoft.VisualBasic::841e91c0a3176428c2064bf102687d8d, mzkit\src\metadna\MetaDNA_visual\GraphAlgorithm.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: 117
' Code Lines: 99
' Comment Lines: 5
' Blank Lines: 13
' File Size: 5.18 KB
' Module GraphAlgorithm
'
' Function: CreateGraph
'
' /********************************************************************************/
#End Region
Imports System.Runtime.CompilerServices
Imports Microsoft.VisualBasic.Data.visualize.Network
Imports Microsoft.VisualBasic.Data.visualize.Network.FileStream.Generic
Imports Microsoft.VisualBasic.Data.visualize.Network.Graph
Public Module GraphAlgorithm
<Extension>
Public Function CreateGraph(metaDNA As XML) As NetworkGraph
Dim g As New NetworkGraph
Dim kegg_compound As Graph.Node
Dim candidate_compound As Graph.Node
Dim edge As Edge
Dim candidateParent As node
Dim seedNode As Graph.Node
For Each compound As compound In metaDNA.compounds
kegg_compound = New Graph.Node With {
.label = compound.kegg,
.data = New NodeData() With {
.label = compound.kegg,
.origID = compound.kegg,
.Properties = New Dictionary(Of String, String) From {
{NamesOf.REFLECTION_ID_MAPPING_NODETYPE, "kegg_compound"},
{"candidates", compound.size}
}
}
}
Call g.AddNode(kegg_compound)
For Each candidate As unknown In compound.candidates
candidate_compound = New Graph.Node With {
.label = candidate.name,
.data = New NodeData With {
.label = candidate.name,
.origID = candidate.Msn,
.Properties = New Dictionary(Of String, String) From {
{NamesOf.REFLECTION_ID_MAPPING_NODETYPE, "MetaDNA.candidate"},
{"intensity", candidate.intensity},
{"infer.depth", candidate.length}
}
}
}
edge = New Edge With {
.U = kegg_compound,
.V = candidate_compound,
.weight = candidate.edges.Length,
.data = New EdgeData With {
.label = $"{candidate_compound.label} infer as {kegg_compound.label}",
.Properties = New Dictionary(Of String, String) From {
{NamesOf.REFLECTION_ID_MAPPING_INTERACTION_TYPE, "is_candidate"},
{"score.forward", candidate.scores.ElementAtOrNull(0)},
{"score.reverse", candidate.scores.ElementAtOrNull(1)}
}
}
}
Call g.AddNode(candidate_compound)
Call g.AddEdge(edge)
' add common seed node
' is a metaDNA seed from reference library
' spectrum alignment result
seedNode = g.GetElementByID(candidate.edges(Scan0).ms1)
If seedNode Is Nothing Then
' 还没有添加进入网络之中
seedNode = New Graph.Node With {
.label = candidate.edges(Scan0).ms1,
.data = New NodeData With {
.label = candidate.edges(Scan0).ms1,
.origID = candidate.edges(Scan0).ms2,
.Properties = New Dictionary(Of String, String) From {
{NamesOf.REFLECTION_ID_MAPPING_NODETYPE, "seed"}
}
}
}
Call g.AddNode(seedNode)
End If
For i As Integer = 0 To candidate.length - 2
seedNode = g.GetElementByID(candidate.edges(i).ms1)
edge = New Edge With {
.data = New EdgeData With {
.label = $"{candidate.edges(i).kegg} -> {candidate.edges(i + 1).kegg}",
.Properties = New Dictionary(Of String, String) From {
{NamesOf.REFLECTION_ID_MAPPING_INTERACTION_TYPE, "infer"}
}
},
.U = seedNode,
.V = g.GetElementByID(candidate.edges(i + 1).ms1)
}
Call g.AddEdge(edge)
Next
' add edge that infer to current candidate
candidateParent = candidate.edges.Last
edge = New Edge With {
.data = New EdgeData With {
.label = $"{candidateParent.kegg} -> {compound.kegg}",
.Properties = New Dictionary(Of String, String) From {
{NamesOf.REFLECTION_ID_MAPPING_INTERACTION_TYPE, "infer"}
}
},
.U = g.GetElementByID(candidateParent.ms1),
.V = g.GetElementByID(candidate.name)
}
Call g.AddEdge(edge)
Next
Next
Return g
End Function
End Module
|
Namespace Web.RSS
Public Class RSSFeed
Dim x As XDocument
Public Property Title As String
Public Property Items As List(Of RSSItem)
Public Sub New(url As String)
x = XDocument.Load(url)
Title = x.<rss>.<channel>.<title>.FirstOrDefault.Value
Items = New List(Of RSSItem)
Items = (From item In x.<rss>.<channel>.<item>
Select New RSSItem With {
.Title = item.<title>.Value,
.Link = item.<link>.Value,
.Description = item.<description>.Value
}).ToList
End Sub
End Class
End Namespace |
Imports System.Configuration
Namespace log_event
Public Class log
''' <summary>
'''
''' </summary>
''' <param name="AD">ชื่อผู้ใช้</param>
''' <param name="page_name">ชื่อหน้า</param>
''' <param name="page_url">url</param>
''' <param name="detail">รายละเอียดที่กระทำ</param>
''' <remarks></remarks>
Public Sub insert_log(ByVal AD As String, ByVal page_name As String, ByVal page_url As String, _
ByVal detail As String, ByVal tbl_name As String, ByVal key_item As Integer)
Dim cls_l As New DAO_MAS.TB_LOG
cls_l.fields.CREATE_DATE = Date.Now()
cls_l.fields.LOG_DETAIL = detail
cls_l.fields.PAGE_NAME = page_name
cls_l.fields.PAGE_URL = page_url
cls_l.fields.USER_AD = AD
cls_l.fields.TABLE_NAME = tbl_name
cls_l.fields.TABLE_KEY_REF = key_item
cls_l.insert()
End Sub
End Class
End Namespace |
'---------------------------------------------------------------------------------------------------
' copyright file="ItemService.vb" company="CitrusLime Ltd"
' Copyright (c) CitrusLime Ltd. All rights reserved.
' copyright
'---------------------------------------------------------------------------------------------------
Imports CitrusLime.CloudPOS.Api.VBSampleApplication.Constants
Imports Newtonsoft.Json
'''-------------------------------------------------------------------------------------------------
''' <summary>A service for accessing item information.</summary>
'''-------------------------------------------------------------------------------------------------
Public Class ItemService
'''-------------------------------------------------------------------------------------------------
''' <summary>Gets all items.</summary>
''' <returns>A list of items.</returns>
'''-------------------------------------------------------------------------------------------------
Public Function GetAll() As List(Of Item)
Dim results As CallResults = AJAX.CallAPI("Item", enumRESTVerb.GET)
Dim items As List(Of Item) = JsonConvert.DeserializeObject(Of List(Of Item))(results.Json)
If Not results.Success Then
Throw (New Exception($"Error {Reflection.MethodBase.GetCurrentMethod().Name} the error is {results.ErrorMessage}"))
End If
Return items
End Function
End Class
|
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Xml
Imports Talent.Common
'--------------------------------------------------------------------------------------------------
' Project Trading Portal Project.
'
' Function This class is used to deal with Multiple Availability responses
'
' Date April 2007
'
' Author
'
' © CS Group 2007 All rights reserved.
'
' Error Number Code base TTPRSMAV-
'
' Modification Summary
'
' dd/mm/yy ID By Description
' -------- ----- --- -----------
'
'--------------------------------------------------------------------------------------------------
Namespace Talent.TradingPortal
Public Class XmlMultiAvailabilityResponse
Inherits XmlResponse
Private _dep As DEProductAlert
Private ndHeaderRoot, ndHeaderRootHeader As XmlNode
Private ndHeader, ndSection, ndManufacturerPartNumber, ndManufacturerPartNumberOccurs, _
ndWareHouse, ndAvailability, ndErrorStatus, ndOnOrder, ndETADate As XmlNode
Private atSku, atQuantity, atWareHouse, atName, atXmlNsXsi, atErrorNumber As XmlAttribute
Public Property Dep() As DEProductAlert
Get
Return _dep
End Get
Set(ByVal value As DEProductAlert)
_dep = value
End Set
End Property
Protected Overrides Sub InsertBodyV1()
'
Dim iCounter As Integer = 0
Dim dtDetail As DataTable = Nothing
Dim drDetail As DataRow
' Check for error (otherwise crashes if fails on invalid document)
If Not ResultDataSet Is Nothing And ResultDataSet.Tables.Count > 0 Then
dtDetail = ResultDataSet.Tables(0) ' Detail
Else
dtDetail = New DataTable
End If
'
With MyBase.xmlDoc
ndHeader = .CreateElement("MultiAvailability")
For Each drDetail In dtDetail.Rows
'-----------------------------------------------------------
CreateHeader()
Try
atSku.Value = (drDetail("ProductNumber").ToString).Trim
atQuantity.Value = (drDetail("Quantity").ToString).Trim
atWareHouse.Value = (drDetail("WareHouse").ToString).Trim
Catch ex As Exception
End Try
'-----------------------------------------------------------
If Not Err2 Is Nothing Then
If Not Err2.ItemErrorStatus(iCounter) Is Nothing Then
ndErrorStatus.InnerText = Err2.ItemErrorStatus(iCounter)
atErrorNumber = .CreateAttribute("ErrorNumber")
atErrorNumber.Value = Err2.ItemErrorCode(iCounter)
ndErrorStatus.Attributes.Append(atErrorNumber)
ndSection.AppendChild(ndErrorStatus)
End If
End If
If Not Err Is Nothing Then
If Not Err.ItemErrorStatus(iCounter) Is Nothing Then
ndErrorStatus.InnerText = Err.ItemErrorStatus(iCounter)
atErrorNumber = .CreateAttribute("ErrorNumber")
atErrorNumber.Value = Err.ItemErrorCode(iCounter)
ndErrorStatus.Attributes.Append(atErrorNumber)
ndSection.AppendChild(ndErrorStatus)
End If
End If
'-----------------------------------------------------------
AppendHeader()
Next
'--------------------------------------------------------------------------------------
' Insert the fragment into the XML document
'
Const c1 As String = "//" ' Constants are faster at run time
Const c2 As String = "/TransactionHeader"
'
ndHeaderRoot = .SelectSingleNode(c1 & RootElement())
ndHeaderRootHeader = .SelectSingleNode(c1 & RootElement() & c2)
ndHeaderRoot.InsertAfter(ndHeader, ndHeaderRootHeader)
'Insert the XSD reference & namespace as an attribute within the root node
atXmlNsXsi = CreateNamespaceAttribute()
ndHeaderRoot.Attributes.Append(atXmlNsXsi)
End With
End Sub
Private Function CreateHeader() As ErrorObj
Dim err As ErrorObj = Nothing
'--------------------------------------------------------------------------
Try
With MyBase.xmlDoc
ndSection = .CreateElement("Availability")
atSku = .CreateAttribute("SKU")
atQuantity = .CreateAttribute("Quantity")
atWareHouse = .CreateAttribute("WareHouse")
ndSection.Attributes.Append(atSku)
ndSection.Attributes.Append(atQuantity)
ndSection.Attributes.Append(atWareHouse)
ndErrorStatus = .CreateElement("ErrorStatus")
ndHeader.AppendChild(ndSection)
'-----------------------------------------------------------------
End With
Catch ex As Exception
Const strError As String = "Failed to Create Header Nodes"
With err
.ErrorMessage = ex.Message
.ErrorStatus = strError
.ErrorNumber = "TTPRSAV-15"
.HasError = True
End With
End Try
Return err
End Function
Private Function AppendHeader() As ErrorObj
Dim err As ErrorObj = Nothing
'--------------------------------------------------------------------------
Try
ndHeader.AppendChild(ndSection)
Catch ex As Exception
Const strError As String = "Failed to Append Order Header Nodes"
With err
.ErrorMessage = ex.Message
.ErrorStatus = strError
.ErrorNumber = "TTPRSAV-16"
.HasError = True
End With
End Try
Return err
End Function
End Class
End Namespace |
'Programmer: Samantha Naini
'Date: 3/5/2012
'Exercise: 4-2-24, pg.126
'Program Purpose: To display the cost of a number of copies when a copy center charges
'5 cents/copy for the first 100 copies, and 3 cents/copy for each ADDITIONAL copy.
Option Strict On
Option Explicit On
Public Class frmCopyCenter
Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
Dim NumOfCopies, Cost As Double
NumOfCopies = CDbl(InputBox("Number of copies:"))
If NumOfCopies < 100 Then
Cost = 0.05 * NumOfCopies 'copies at 5 cents each
ElseIf NumOfCopies > 100 Then
Cost = 0.03 * (NumOfCopies - 100) + 5 'copies at 3 cents each; the 5 is five dollars for 100 copies at 5 cents each
End If
txtOutput.Text = "The cost is " & FormatCurrency(Cost) & "."
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
txtOutput.Clear()
End Sub
Private Sub btnEnd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnd.Click
Me.Close()
End Sub
End Class
|
Imports System
Imports System.Collections.Generic
Imports System.Windows.Data
Imports System.Windows.Media
Imports System.Windows.Media.Imaging
Imports DevExpress.Xpf.DemoBase.DataClasses
Imports DevExpress.Xpf.Grid
Imports DevExpress.Xpf.Grid.TreeList
Namespace TreeListDemo
Partial Public Class UnboundMode
Inherits TreeListDemoModule
Private Const StateFieldName As String = "State"
Private Const StartDateFieldName As String = "StartDate"
Private Const EndDateFieldName As String = "EndDate"
Private Shared ReadOnly Random As New Random(Date.Now.Second)
Public Shared Function GetRandomEmployee() As Employee
If EmployeesData.DataSource Is Nothing Then
Return Nothing
End If
Return EmployeesData.DataSource(Random.Next(EmployeesData.DataSource.Count))
End Function
Public Sub New()
InitializeComponent()
InitData()
view.ExpandAllNodes()
End Sub
Private Sub InitData()
Dim stantoneProject As TreeListNode = view.Nodes(0)
InitStantoneProjectData(stantoneProject)
Dim betaronProject As TreeListNode = view.Nodes(1)
InitBetaronProjectData(betaronProject)
End Sub
Private Sub CellValueChanging(ByVal sender As Object, ByVal e As TreeListCellValueChangedEventArgs)
If e.Column.FieldName = StartDateFieldName OrElse e.Column.FieldName = EndDateFieldName OrElse e.Column.FieldName = StateFieldName Then
view.CommitEditing(True)
End If
End Sub
Private Sub GetColumnData(ByVal sender As Object, ByVal e As TreeListUnboundColumnDataEventArgs)
If e.IsSetData Then
SetUnboundCellData(sender, e)
Else
GetUnboundCellData(sender, e)
End If
End Sub
Private Sub GetUnboundCellData(ByVal sender As Object, ByVal e As TreeListUnboundColumnDataEventArgs)
Select Case e.Column.FieldName
Case StartDateFieldName
e.Value = GetUnboundStartDate(e, e.Node)
Case EndDateFieldName
e.Value = GetUnboundEndDate(e, e.Node)
Case StateFieldName
GetUnboundState(e, e.Node)
Case Else
End Select
End Sub
Private Sub SetUnboundCellData(ByVal sender As Object, ByVal e As TreeListUnboundColumnDataEventArgs)
Dim task_Renamed As TaskObject = TryCast(e.Node.Content, TaskObject)
Dim FieldName As String = e.Column.FieldName
If task_Renamed IsNot Nothing Then
Select Case FieldName
Case StartDateFieldName
task_Renamed.StartDate = CDate(If(e.Value, Date.MinValue))
Case EndDateFieldName
task_Renamed.EndDate = CDate(If(e.Value, Date.MinValue))
Case StateFieldName
Dim newState As State = CType(e.Value, State)
If task_Renamed.State IsNot newState Then
task_Renamed.State = newState
RecursiveNodeRefresh(e.Node.ParentNode)
End If
Case Else
End Select
End If
End Sub
Private Sub RecursiveNodeRefresh(ByVal node As TreeListNode)
If node IsNot Nothing Then
treeList.RefreshRow(node.RowHandle)
RecursiveNodeRefresh(node.ParentNode)
End If
End Sub
Private Sub EditorVisibility(ByVal sender As Object, ByVal e As TreeListShowingEditorEventArgs)
Dim fieldName As String = e.Column.FieldName
e.Cancel = (fieldName = StartDateFieldName OrElse fieldName = EndDateFieldName OrElse fieldName = StateFieldName) AndAlso Not(TypeOf e.Node.Content Is TaskObject)
End Sub
Private Sub CollectBoundStates(ByVal treeListNode As TreeListNode, ByVal states_Renamed As List(Of State))
Dim [iterator] As New TreeListNodeIterator(treeListNode)
For Each node As TreeListNode In [iterator]
Dim task_Renamed As TaskObject = TryCast(node.Content, TaskObject)
If task_Renamed IsNot Nothing Then
states_Renamed.Add(task_Renamed.State)
End If
Next node
End Sub
Private Sub GetUnboundState(ByVal e As TreeListUnboundColumnDataEventArgs, ByVal treeListNode As TreeListNode)
Dim task_Renamed As TaskObject = TryCast(treeListNode.Content, TaskObject)
If task_Renamed IsNot Nothing Then
e.Value = task_Renamed.State
Return
End If
Dim statesList As New List(Of State)()
CollectBoundStates(e.Node, statesList)
If statesList.Contains(States.DataSource(1)) OrElse (statesList.Contains(States.DataSource(0)) AndAlso statesList.Contains(States.DataSource(2))) Then
e.Value = States.DataSource(1)
ElseIf statesList.Contains(States.DataSource(0)) Then
e.Value = States.DataSource(0)
ElseIf statesList.Contains(States.DataSource(2)) Then
e.Value = States.DataSource(2)
End If
End Sub
Private Function GetUnboundStartDate(ByVal e As TreeListUnboundColumnDataEventArgs, ByVal treeListNode As TreeListNode) As Date
Dim task_Renamed As TaskObject = TryCast(treeListNode.Content, TaskObject)
Dim value As Date = Date.Now
Dim tempValue As Date
If task_Renamed IsNot Nothing Then
value = task_Renamed.StartDate
Else
value = Date.MaxValue
For Each item As TreeListNode In treeListNode.Nodes
tempValue = GetUnboundStartDate(e, item)
If tempValue < value Then
value = tempValue
End If
Next item
End If
Return value
End Function
Private Function GetUnboundEndDate(ByVal e As TreeListUnboundColumnDataEventArgs, ByVal treeListNode As TreeListNode) As Date
Dim task_Renamed As TaskObject = TryCast(treeListNode.Content, TaskObject)
Dim value As Date = Date.Now
Dim tempValue As Date
If task_Renamed IsNot Nothing Then
value = task_Renamed.EndDate
Else
value = Date.MinValue
For Each item As TreeListNode In treeListNode.Nodes
tempValue = GetUnboundEndDate(e, item)
If tempValue > value Then
value = tempValue
End If
Next item
End If
Return value
End Function
#Region "Unbound Data Initialization"
Private Sub InitBetaronProjectData(ByVal betaronProject As TreeListNode)
betaronProject.Image = ProjectObject.Image
Dim stage21 As New TreeListNode(New StageObject() With {.NameValue = "Information Gathering", .Executor = GetRandomEmployee()})
stage21.Image = StageObject.Image
stage21.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Market research", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 1), .EndDate = New Date(2011, 10, 5), .State = States.DataSource(2)}) With {.Image = TaskObject.Image})
stage21.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Making specification", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 5), .EndDate = New Date(2011, 10, 10), .State = States.DataSource(1)}) With {.Image = TaskObject.Image})
Dim stage22 As New TreeListNode(New StageObject() With {.NameValue = "Planning", .Executor = GetRandomEmployee()})
stage22.Image = StageObject.Image
stage22.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Documentation", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 15), .EndDate = New Date(2011, 10, 16), .State = States.DataSource(0)}) With {.Image = TaskObject.Image})
Dim stage23 As New TreeListNode(New StageObject() With {.NameValue = "Design", .Executor = GetRandomEmployee()})
stage23.Image = StageObject.Image
stage23.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Design of a web pages", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 13), .EndDate = New Date(2011, 10, 14), .State = States.DataSource(0)}) With {.Image = TaskObject.Image})
stage23.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Pages layout", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 13), .EndDate = New Date(2011, 10, 14), .State = States.DataSource(0)}) With {.Image = TaskObject.Image})
Dim stage24 As New TreeListNode(New StageObject() With {.NameValue = "Development", .Executor = GetRandomEmployee()})
stage24.Image = StageObject.Image
stage24.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Design", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 27), .EndDate = New Date(2011, 10, 28), .State = States.DataSource(0)}) With {.Image = TaskObject.Image})
stage24.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Coding", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 29), .EndDate = New Date(2011, 10, 30), .State = States.DataSource(0)}) With {.Image = TaskObject.Image})
Dim stage25 As New TreeListNode(New StageObject() With {.NameValue = "Testing and Delivery", .Executor = GetRandomEmployee()})
stage25.Image = StageObject.Image
stage25.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Testing", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 13), .EndDate = New Date(2011, 10, 14), .State = States.DataSource(0)}) With {.Image = TaskObject.Image})
stage25.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Content", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 13), .EndDate = New Date(2011, 10, 14), .State = States.DataSource(0)}) With {.Image = TaskObject.Image})
betaronProject.Nodes.Add(stage21)
betaronProject.Nodes.Add(stage22)
betaronProject.Nodes.Add(stage23)
betaronProject.Nodes.Add(stage24)
betaronProject.Nodes.Add(stage25)
End Sub
Private Sub InitStantoneProjectData(ByVal stantoneProject As TreeListNode)
stantoneProject.Image = ProjectObject.Image
Dim stage11 As New TreeListNode(New StageObject() With {.NameValue = "Information Gathering", .Executor = GetRandomEmployee()})
stage11.Image = StageObject.Image
stage11.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Market research", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 1), .EndDate = New Date(2011, 10, 5), .State = States.DataSource(2)}) With {.Image = TaskObject.Image})
stage11.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Making specification", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 5), .EndDate = New Date(2011, 10, 10), .State = States.DataSource(2)}) With {.Image = TaskObject.Image})
Dim stage12 As New TreeListNode(New StageObject() With {.NameValue = "Planning", .Executor = GetRandomEmployee()})
stage12.Image = StageObject.Image
stage12.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Documentation", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 13), .EndDate = New Date(2011, 10, 14), .State = States.DataSource(2)}) With {.Image = TaskObject.Image})
Dim stage13 As New TreeListNode(New StageObject() With {.NameValue = "Design", .Executor = GetRandomEmployee()})
stage13.Image = StageObject.Image
stage13.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Design of a web pages", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 13), .EndDate = New Date(2011, 10, 14), .State = States.DataSource(1)}) With {.Image = TaskObject.Image})
stage13.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Pages layout", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 13), .EndDate = New Date(2011, 10, 14), .State = States.DataSource(1)}) With {.Image = TaskObject.Image})
Dim stage14 As New TreeListNode(New StageObject() With {.NameValue = "Development", .Executor = GetRandomEmployee()})
stage14.Image = StageObject.Image
stage14.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Design", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 23), .EndDate = New Date(2011, 10, 24), .State = States.DataSource(1)}) With {.Image = TaskObject.Image})
stage14.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Coding", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 25), .EndDate = New Date(2011, 10, 26), .State = States.DataSource(0)}) With {.Image = TaskObject.Image})
Dim stage15 As New TreeListNode(New StageObject() With {.NameValue = "Testing and Delivery", .Executor = GetRandomEmployee()})
stage15.Image = StageObject.Image
stage15.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Testing", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 13), .EndDate = New Date(2011, 10, 14), .State = States.DataSource(0)}) With {.Image = TaskObject.Image})
stage15.Nodes.Add(New TreeListNode(New TaskObject() With {.NameValue = "Content", .Executor = GetRandomEmployee(), .StartDate = New Date(2011, 10, 13), .EndDate = New Date(2011, 10, 14), .State = States.DataSource(0)}) With {.Image = TaskObject.Image})
stantoneProject.Nodes.Add(stage11)
stantoneProject.Nodes.Add(stage12)
stantoneProject.Nodes.Add(stage13)
stantoneProject.Nodes.Add(stage14)
stantoneProject.Nodes.Add(stage15)
End Sub
#End Region
End Class
#Region "Classes"
Public Class State
Implements IComparable
Public Property Image() As ImageSource
Public Property TextValue() As String
Public Property StateValue() As Integer
Public Overrides Function ToString() As String
Return TextValue
End Function
Public Function CompareTo(ByVal obj As Object) As Integer Implements IComparable.CompareTo
Return Comparer(Of Integer).Default.Compare(StateValue, DirectCast(obj, State).StateValue)
End Function
End Class
Public Class TaskObject
Public Property NameValue() As String
Public Property StartDate() As Date
Public Property EndDate() As Date
Public Property Executor() As Employee
Public Property State() As State
Public Shared ReadOnly Property Image() As BitmapImage
Get
Return New BitmapImage(New Uri("/TreeListDemo;component/Images/Object_Task.png", UriKind.Relative))
End Get
End Property
End Class
Public Class States
Inherits List(Of State)
Private Shared src As List(Of State)
Public Shared ReadOnly Property DataSource() As List(Of State)
Get
If src Is Nothing Then
src = New List(Of State)()
src.Add(New State() With {.TextValue = "Not started", .StateValue = 0, .Image = New BitmapImage(New Uri("/TreeListDemo;component/Images/State_NotStarted.png", UriKind.Relative))})
src.Add(New State() With {.TextValue = "In progress", .StateValue = 1, .Image = New BitmapImage(New Uri("/TreeListDemo;component/Images/State_InProgress.png", UriKind.Relative))})
src.Add(New State() With {.TextValue = "Completed", .StateValue = 2, .Image = New BitmapImage(New Uri("/TreeListDemo;component/Images/State_Completed.png", UriKind.Relative))})
End If
Return src
End Get
End Property
End Class
Public Class ProjectObject
Public Property NameValue() As String
Private executor_Renamed As Employee
Public ReadOnly Property Executor() As Employee
Get
If executor_Renamed Is Nothing Then
executor_Renamed = UnboundMode.GetRandomEmployee()
End If
Return executor_Renamed
End Get
End Property
Public Shared ReadOnly Property Image() As BitmapImage
Get
Return New BitmapImage(New Uri("/TreeListDemo;component/Images/Object_Project.png", UriKind.Relative))
End Get
End Property
End Class
Public Class StageObject
Public Property NameValue() As String
Public Property Executor() As Employee
Public Shared ReadOnly Property Image() As BitmapImage
Get
Return New BitmapImage(New Uri("/TreeListDemo;component/Images/Object_Stage.png", UriKind.Relative))
End Get
End Property
End Class
#End Region
End Namespace
|
Public Class Form2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Select Case ComboBox1.Text
Case "+"
Label3.Text = "My Result : " & CInt(TextBox1.Text) + CInt(TextBox2.Text)
Case "-"
Label3.Text = "My Result : " & CInt(TextBox1.Text) - CInt(TextBox2.Text)
Case "*"
Label3.Text = "My Result : " & CInt(TextBox1.Text) * CInt(TextBox2.Text)
Case "/"
Label3.Text = "My Result : " & CInt(TextBox1.Text) / CInt(TextBox2.Text)
Case Else
Label3.Text = "Invalid"
End Select
End Sub
End Class |
Public Class CompanyForm
Private DB As New DBAccess
Private Sub loadCompanies()
DB.ExecuteQuery("select * from company")
If DB.Exception <> String.Empty Then
MessageBox.Show(DB.Exception)
Exit Sub
End If
CompanyDataGridView.DataSource = DB.DBDataTable
End Sub
Private Sub CompanyForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load, Me.Activated
loadCompanies()
EditToolStripMenuItem.Enabled = False
EditToolStripMenuItem.Visible = False
End Sub
Private Sub NewToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewToolStripMenuItem.Click
NewCompanyForm.ShowDialog()
End Sub
Private Sub CompanyDataGridView_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles CompanyDataGridView.CellClick
If e.RowIndex < 0 Or e.ColumnIndex < 0 Then
CompanyIdTextBox.Clear()
Exit Sub
End If
CompanyIdTextBox.Text = CompanyDataGridView.Item(0, e.RowIndex).Value
EditToolStripMenuItem.Visible = True
EditToolStripMenuItem.Enabled = True
End Sub
Private Sub searchByCompanyName(name As String)
DB.AddParam("@cname", name & "%")
DB.ExecuteQuery("select * from company where name like ?")
If DB.Exception <> String.Empty Then
MessageBox.Show(DB.Exception)
Exit Sub
End If
CompanyDataGridView.DataSource = DB.DBDataTable
End Sub
Private Sub CompanyNameTextBox_KeyUp(sender As Object, e As KeyEventArgs) Handles CompanyNameTextBox.KeyUp
searchByCompanyName(CompanyNameTextBox.Text)
End Sub
Private Sub EditToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EditToolStripMenuItem.Click
EditCompanyForm.ShowDialog()
End Sub
End Class |
Public Class Presentation
Public Shared Sub ChangeForm(acc As Account)
SetGridView()
RefreshForm(acc.AccountName)
DisplayGrid()
End Sub
'set up data grid view headers
Public Shared Sub SetGridView()
FrmAccounts.dgvTransactions.DataSource = Nothing
FrmAccounts.dgvTransactions.Rows.Clear()
FrmAccounts.dgvTransactions.ColumnCount = 5
FrmAccounts.dgvTransactions.Columns(0).HeaderText = "Date"
FrmAccounts.dgvTransactions.Columns(0).HeaderText = "Description"
FrmAccounts.dgvTransactions.Columns(0).HeaderText = "Amount"
FrmAccounts.dgvTransactions.Columns(0).HeaderText = "New Balance"
FrmAccounts.dgvTransactions.Columns(0).HeaderText = "Transaction Type"
End Sub
'display data on the form
Public Shared Sub RefreshForm(accName As String)
'do not display Checks panel for savings account
If accName = "Savings" Then
FrmAccounts.grpChecks.Visible = False
FrmAccounts.lblTransferFrom.Text = "Savings"
FrmAccounts.lblTransferTo.Text = "Checking"
Else
FrmAccounts.grpChecks.Visible = True
FrmAccounts.lblTransferFrom.Text = "Checking"
FrmAccounts.lblTransferTo.Text = "Savings"
End If
FrmAccounts.txtDeposit.Clear()
FrmAccounts.txtWithdrawal.Clear()
FrmAccounts.txtTransferAmount.Clear()
FrmAccounts.txtCheckAmount.Clear()
FrmAccounts.txtOrderOf.Clear()
End Sub
'display rows in data grid
Public Shared Sub DisplayGrid()
Dim trans As List(Of Transaction) = Transaction.TransactionList
Dim acc As List(Of Double) = Transaction.NewBalanceList
For i As Integer = 0 To trans.Count - 1
FrmAccounts.dgvTransactions.Rows.Add(trans(i).TransactionDate.ToString("MM/dd/yyyy"),
trans(i).TransactionName, trans(i).TransactionAmount,
acc(i), trans(i).TransactionDescription)
Next
'the last index holds the current account balance
DisplayBalance(acc(acc.Count - 1))
End Sub
Private Shared Sub DisplayBalance(balance As Double)
FrmAccounts.txtBalance.Text = FormatCurrency(balance, 2)
End Sub
End Class
|
''Class Definition - ProductBOM (to ProductBOM)'Generated from Table:ProductBOM
Imports RTIS.CommonVB
Public Class dmProductBOM : Inherits dmBase
Private pProductBOMID As Int32
Private pParentID As Int32
Private pProductID As Int32
Private pQuantity As Decimal
Private pStockCode As String
Private pDescription As String
Private pMaterialRequirementType As Byte
Private pUnitPiece As Int32
Private pNetThickness As Decimal
Private pNetWidth As Decimal
Private pNetLenght As Decimal
Private pQualityType As Int32
Private pMaterialTypeID As Int32
Private pWoodSpecie As Int32
Private pWoodFinish As Int32
Private pUoM As Integer
Private pAreaID As Int32
Private pSupplierStockCode As String
Private pComments As String
Private pPiecesPerComponent As Decimal
Private pTotalPieces As Decimal
Private pDateChange As DateTime
Private pDateOtherMaterial As DateTime
Private pStockItemID As Int32
Private pComponentDescription As String
Private pTempInStock As Decimal
Private pObjectType As Byte
Private pTmpSelectedItem As Boolean
Private pStockItemThickness As Integer
Private pWoodItemType As Integer
Public Sub New()
MyBase.New()
End Sub
Protected Overrides Sub NewSetup()
''Add object/collection instantiations here
End Sub
Protected Overrides Sub AddSnapshotKeys()
''Add PrimaryKey, Rowversion and ParentKeys properties here:
''AddSnapshotKey("PropertyName")
End Sub
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
Public Overrides ReadOnly Property IsAnyDirty() As Boolean
Get
Dim mAnyDirty = IsDirty
'' Check Objects and Collections
IsAnyDirty = mAnyDirty
End Get
End Property
Public Overrides Sub ClearKeys()
'Set Key Values = 0
ProductBOMID = 0
End Sub
Public Overrides Sub CloneTo(ByRef rNewItem As dmBase)
With CType(rNewItem, dmProductBOM)
.ProductBOMID = ProductBOMID
.ParentID = ParentID
.ProductID = ProductID
.Quantity = Quantity
.StockCode = StockCode
.Description = Description
.MaterialRequirementType = MaterialRequirementType
.UnitPiece = UnitPiece
.NetThickness = NetThickness
.NetWidth = NetWidth
.NetLenght = NetLenght
.QualityType = QualityType
.MaterialTypeID = MaterialTypeID
.WoodSpecie = WoodSpecie
.WoodFinish = WoodFinish
.UoM = UoM
.AreaID = AreaID
.SupplierStockCode = SupplierStockCode
.Comments = Comments
.PiecesPerComponent = PiecesPerComponent
.TotalPieces = TotalPieces
.DateChange = DateChange
.DateOtherMaterial = DateOtherMaterial
.StockItemID = StockItemID
.ComponentDescription = ComponentDescription
.ObjectType = ObjectType
'Add entries here for each collection and class property
'Entries for object management
.IsDirty = IsDirty
End With
End Sub
Public Property ProductBOMID() As Int32
Get
Return pProductBOMID
End Get
Set(ByVal value As Int32)
If pProductBOMID <> value Then IsDirty = True
pProductBOMID = value
End Set
End Property
Public Property ParentID() As Int32
Get
Return pParentID
End Get
Set(ByVal value As Int32)
If pParentID <> value Then IsDirty = True
pParentID = value
End Set
End Property
Public Property ProductID() As Int32
Get
Return pProductID
End Get
Set(ByVal value As Int32)
If pProductID <> value Then IsDirty = True
pProductID = value
End Set
End Property
Public Property Quantity() As Decimal
Get
Return pQuantity
End Get
Set(ByVal value As Decimal)
If pQuantity <> value Then IsDirty = True
pQuantity = value
End Set
End Property
Public Property StockCode() As String
Get
Dim mRetVal As String
If pStockItemID > 0 Then
mRetVal = AppRTISGlobal.GetInstance.StockItemRegistry.GetStockItemFromID(pStockItemID).StockCode
pStockCode = pStockCode
End If
Return pStockCode
End Get
Set(ByVal value As String)
If pStockCode <> value Then IsDirty = True
pStockCode = value
End Set
End Property
Public Property Description() As String
Get
Dim mRetVal As String = ""
Select Case ObjectType
Case eProductBOMObjectType.Wood
mRetVal = pDescription
Case eProductBOMObjectType.StockItems
If pStockItemID > 0 Then
mRetVal = AppRTISGlobal.GetInstance.StockItemRegistry.GetStockItemFromID(pStockItemID).Description
Else
mRetVal = ""
End If
End Select
Return mRetVal
End Get
Set(ByVal value As String)
If pDescription <> value Then IsDirty = True
pDescription = value
End Set
End Property
Public Property MaterialRequirementType() As Byte
Get
Return pMaterialRequirementType
End Get
Set(ByVal value As Byte)
If pMaterialRequirementType <> value Then IsDirty = True
pMaterialRequirementType = value
End Set
End Property
Public Property UnitPiece() As Int32
Get
Return pUnitPiece
End Get
Set(ByVal value As Int32)
If pUnitPiece <> value Then IsDirty = True
pUnitPiece = value
End Set
End Property
Public Property NetThickness() As Decimal
Get
Return pNetThickness
End Get
Set(ByVal value As Decimal)
If pNetThickness <> value Then IsDirty = True
pNetThickness = value
End Set
End Property
Public Property NetWidth() As Decimal
Get
Return pNetWidth
End Get
Set(ByVal value As Decimal)
If pNetWidth <> value Then IsDirty = True
pNetWidth = value
End Set
End Property
Public ReadOnly Property WidthInch() As Decimal
Get
Dim mRetVal As Decimal
mRetVal = clsSMSharedFuncs.CMToQuaterInches(pNetWidth)
Return mRetVal
End Get
End Property
Public Property NetLenght() As Decimal
Get
Return pNetLenght
End Get
Set(ByVal value As Decimal)
If pNetLenght <> value Then IsDirty = True
pNetLenght = value
End Set
End Property
Public ReadOnly Property LengthInch() As Decimal
Get
Dim mRetVal As Decimal
mRetVal = clsSMSharedFuncs.CMToHalfInchesLength(NetLenght)
Return mRetVal
End Get
End Property
Public ReadOnly Property GrossInchThickness() As Decimal
Get
Dim mRetVal As Decimal
mRetVal = clsSMSharedFuncs.GrosWoodThickness(NetThickness)
Return mRetVal
End Get
End Property
Public Property QualityType() As Int32
Get
Return pQualityType
End Get
Set(ByVal value As Int32)
If pQualityType <> value Then IsDirty = True
pQualityType = value
End Set
End Property
Public Property MaterialTypeID() As Int32
Get
Return pMaterialTypeID
End Get
Set(ByVal value As Int32)
If pMaterialTypeID <> value Then IsDirty = True
pMaterialTypeID = value
End Set
End Property
Public Property WoodSpecie() As Int32
Get
Return pWoodSpecie
End Get
Set(ByVal value As Int32)
If pWoodSpecie <> value Then IsDirty = True
pWoodSpecie = value
End Set
End Property
Public ReadOnly Property WoodSpecieDesc As String
Get
Dim mRetVal As String = ""
mRetVal = AppRTISGlobal.GetInstance.RefLists.RefListVI(appRefLists.WoodSpecie).DisplayValueString(WoodSpecie)
Return mRetVal.Trim
End Get
End Property
Public Property WoodFinish() As Int32
Get
Return pWoodFinish
End Get
Set(ByVal value As Int32)
If pWoodFinish <> value Then IsDirty = True
pWoodFinish = value
End Set
End Property
Public Property UoM() As Integer
Get
Dim mStockItem As dmStockItem
mStockItem = AppRTISGlobal.GetInstance.StockItemRegistry.GetStockItemFromID(pStockItemID)
If mStockItem IsNot Nothing Then
pUoM = mStockItem.UoM
End If
Return pUoM
End Get
Set(ByVal value As Integer)
If pUoM <> value Then IsDirty = True
pUoM = value
End Set
End Property
Public Property AreaID() As Int32
Get
Return pAreaID
End Get
Set(ByVal value As Int32)
If pAreaID <> value Then IsDirty = True
pAreaID = value
End Set
End Property
Public Property SupplierStockCode() As String
Get
Return pSupplierStockCode
End Get
Set(ByVal value As String)
If pSupplierStockCode <> value Then IsDirty = True
pSupplierStockCode = value
End Set
End Property
Public Property Comments() As String
Get
Return pComments
End Get
Set(ByVal value As String)
If pComments <> value Then IsDirty = True
pComments = value
End Set
End Property
Public Property PiecesPerComponent() As Decimal
Get
Return pPiecesPerComponent
End Get
Set(ByVal value As Decimal)
If pPiecesPerComponent <> value Then IsDirty = True
pPiecesPerComponent = value
End Set
End Property
Public Property TotalPieces() As Decimal
Get
Return pTotalPieces
End Get
Set(ByVal value As Decimal)
If pTotalPieces <> value Then IsDirty = True
pTotalPieces = value
End Set
End Property
Public Property DateChange() As DateTime
Get
Return pDateChange
End Get
Set(ByVal value As DateTime)
If pDateChange <> value Then IsDirty = True
pDateChange = value
End Set
End Property
Public Property DateOtherMaterial() As DateTime
Get
Return pDateOtherMaterial
End Get
Set(ByVal value As DateTime)
If pDateOtherMaterial <> value Then IsDirty = True
pDateOtherMaterial = value
End Set
End Property
Public Property StockItemID() As Int32
Get
Return pStockItemID
End Get
Set(ByVal value As Int32)
If pStockItemID <> value Then IsDirty = True
pStockItemID = value
End Set
End Property
Public Property ComponentDescription() As String
Get
Return pComponentDescription
End Get
Set(ByVal value As String)
If pComponentDescription <> value Then IsDirty = True
pComponentDescription = value
End Set
End Property
Public Property TempInStock As Decimal
Get
Return pTempInStock
End Get
Set(value As Decimal)
pTempInStock = value
End Set
End Property
Public Property ObjectType As Byte
Get
Return pObjectType
End Get
Set(value As Byte)
pObjectType = value
End Set
End Property
Public Property TmpSelectedItem As Boolean
Get
Return pTmpSelectedItem
End Get
Set(value As Boolean)
pTmpSelectedItem = value
End Set
End Property
Public Property StockItemThickness As Integer
Get
Return pStockItemThickness
End Get
Set(value As Integer)
If pStockItemThickness <> value Then IsDirty = True
pStockItemThickness = value
End Set
End Property
Public Property WoodItemType As Integer
Get
Return pWoodItemType
End Get
Set(value As Integer)
If pWoodItemType <> value Then IsDirty = True
pWoodItemType = value
End Set
End Property
Public ReadOnly Property InitialThicknessFraction As String
Get
Return clsSMSharedFuncs.DecToFraction(clsSMSharedFuncs.GrosWoodThickness(pNetThickness))
End Get
End Property
Public ReadOnly Property InitialWidthFraction As String
Get
Return clsSMSharedFuncs.DecToFraction(clsSMSharedFuncs.CMToQuaterInches(NetWidth))
End Get
End Property
Public ReadOnly Property InitialLenghtFraction As String
Get
Return clsSMSharedFuncs.DecToFraction(clsSMSharedFuncs.CMToHalfInchesLength(NetLenght))
End Get
End Property
End Class
''Collection Definition - ProductBOM (to ProductBOM)'Generated from Table:ProductBOM
'Private pProductBOMs As colProductBOMs
'Public Property ProductBOMs() As colProductBOMs
' Get
' Return pProductBOMs
' End Get
' Set(ByVal value As colProductBOMs)
' pProductBOMs = value
' End Set
'End Property
' pProductBOMs = New colProductBOMs 'Add to New
' pProductBOMs = Nothing 'Add to Finalize
' .ProductBOMs = ProductBOMs.Clone 'Add to CloneTo
' ProductBOMs.ClearKeys 'Add to ClearKeys
' If Not mAnyDirty Then mAnyDirty = ProductBOMs.IsDirty 'Add to IsAnyDirty
Public Class colProductBOMs : Inherits colBase(Of dmProductBOM)
Public Overrides Function IndexFromKey(ByVal vProductBOMID As Integer) As Integer
Dim mItem As dmProductBOM
Dim mIndex As Integer = -1
Dim mCount As Integer = -1
For Each mItem In MyBase.Items
mCount += 1
If mItem.ProductBOMID = vProductBOMID Then
mIndex = mCount
Exit For
End If
Next
Return mIndex
End Function
Public Sub New()
MyBase.New()
End Sub
Public Sub New(ByVal vList As List(Of dmProductBOM))
MyBase.New(vList)
End Sub
Public Function IndexFromStockItemID(ByVal vStockItemID As Integer) As Integer
Dim mItem As dmProductBOM
Dim mIndex As Integer = -1
Dim mCount As Integer = -1
For Each mItem In MyBase.Items
mCount += 1
If mItem.StockItemID = vStockItemID Then
mIndex = mCount
Exit For
End If
Next
Return mIndex
End Function
Public Function ItemFromStockItemID(ByVal vStockItemID As Integer) As dmProductBOM
Dim mRetVal As dmProductBOM = Nothing
Dim mIndex As Integer
mIndex = IndexFromStockItemID(vStockItemID)
If mIndex <> -1 Then
mRetVal = Me.Item(mIndex)
End If
Return mRetVal
End Function
End Class
|
Option Strict On
Public Class frmAddGolfer
'-------------------------------------------------------------'
' Name: SubmitNewGolfer_Click
' Desc: subroutine to handle calls after click event
'-------------------------------------------------------------'
Private Sub btnSubmitNewGolfer_Click(sender As Object, e As EventArgs) Handles btnSubmitNewGolfer.Click
'---------variables--------'
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 strPhone As String = ""
Dim strEmail As String = ""
' TODO - Set vars to txt
' pass
strFirstName = txtNewGolferFName.Text
strLastName = txtNewGolferLName.Text
strAddress = txtNewGolferAddress.Text
strCity = txtNewGolferCity.Text
strState = txtNewGolferState.Text
strZip = txtNewGolferZip.Text
strPhone = txtNewGolferPhone.Text
strEmail = txtNewGolferEmail.Text
'-----validate-----'
If ValidationTool() = True Then
'
AddGolfer(strFirstName, strLastName, strAddress, strCity, strState, strZip, strPhone, strEmail)
End If
'----SUB COMPLETE----'
End Sub
'-------------------------------------------------------------'
' Name: AddGolfer
' Desc: Subroutine to connect to db and add update table
'-------------------------------------------------------------'
Private Sub AddGolfer(ByVal strFirstName As String, ByVal strLastName As String, ByVal strAddress As String _
, ByVal strCity As String, ByVal strState As String, ByVal strZip As String, ByVal strPhone As String _
, ByVal strEmail As String)
'----number of rows affected-----'
Dim intRowsAffected As Integer
If ValidationTool() = True Then
' create command object and integer for number of returned rows
Dim cmdAddGolfer As New OleDb.OleDbCommand()
Dim intPKID As Integer ' this is what we pass in as the stored procedure requires it
Dim intShirtIndex As Integer
Dim intGenderIndex As Integer
Try
' open database
If OpenDatabaseConnectionSQLServer() = False Then
' No, warn the user
MessageBox.Show(Me, "Database connection error." & vbNewLine &
"The application will now close.",
Me.Text + " Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
' and close the form/application
Me.Close()
End If
intShirtIndex = cmbNewGolferSize.SelectedIndex
intGenderIndex = cmbNewGolferGender.SelectedIndex
' text to call stored proc
cmdAddGolfer.CommandText = "EXECUTE uspAddGolfer '" & intPKID & "','" & strFirstName & "','" & strLastName &
"', '" & strAddress & "','" & strCity & "', '" & strState & "','" & strZip & "','" & strPhone & "','" & strEmail & "', " &
intShirtIndex + 1 & ", " & intGenderIndex + 1
cmdAddGolfer.CommandType = CommandType.StoredProcedure
' Call stored proc which will insert the record
cmdAddGolfer = New OleDb.OleDbCommand(cmdAddGolfer.CommandText, m_conAdministrator)
' this return is the # of rows affected
intRowsAffected = cmdAddGolfer.ExecuteNonQuery()
'Close database connection
CloseDatabaseConnection()
'---if successful let user know-----'
If intRowsAffected > 0 Then
MessageBox.Show("Golfer has been added")
CloseDatabaseConnection()
Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Close()
End Try
End If
'----SUB COMPLETE----'
End Sub
'-------------------------------------------------------------'
' Name: Load_ShirtSize
' Desc: reload and insert shirt size into combo box
'-------------------------------------------------------------'
Private Sub Load_ShirtSize()
Try
Dim strSelect As String = ""
Dim cmdSelect As OleDb.OleDbCommand
Dim drSourceTable As OleDb.OleDbDataReader
Dim dt As DataTable = New DataTable
'---attempt to open db----'
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 connection works, continue with building statements-----'
strSelect = "SELECT intShirtSizeID, strShirtSizeDesc FROM TShirtSizes"
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
dt.Load(drSourceTable)
'---bind ID to size----'
cmbNewGolferSize.ValueMember = "intShirtSizeID"
cmbNewGolferSize.DisplayMember = "strShirtSizeDesc"
cmbNewGolferSize.DataSource = dt
'---close---'
drSourceTable.Close()
CloseDatabaseConnection()
Catch excError As Exception
MessageBox.Show(excError.Message)
End Try
'----SUB COMPLETE----'
End Sub
'-------------------------------------------------------------'
' Name: Load_Gender
' Desc: reload and insert gender into combo box
'-------------------------------------------------------------'
Private Sub Load_Gender()
Try
Dim strSelect As String = ""
Dim cmdSelect As OleDb.OleDbCommand
Dim drSourceTable As OleDb.OleDbDataReader
Dim dt As DataTable = New DataTable
'---attempt to open db----'
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 connection works, continue with building statements-----'
strSelect = "SELECT intGenderID, strGenderDesc FROM TGenders"
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
dt.Load(drSourceTable)
'---bind ID to size----'
cmbNewGolferGender.ValueMember = "intGenderID"
cmbNewGolferGender.DisplayMember = "strGenderDesc"
cmbNewGolferGender.DataSource = dt
'---close---'
drSourceTable.Close()
CloseDatabaseConnection()
Catch excError As Exception
MessageBox.Show(excError.Message)
End Try
'----SUB COMPLETE----'
End Sub
'-------------------------------------------------------------'
' Name: AddGolfer_Load
' Desc: reload golfer data
'-------------------------------------------------------------'
Private Sub frmAddGolfer_Load(Sender As Object, e As EventArgs) Handles MyBase.Load
Try
Load_ShirtSize()
Load_Gender()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
'----SUB COMPLETE----'
End Sub
'-------------------------------------------------------------'
' Name: ValidationTool
' Desc: Validate data
'-------------------------------------------------------------'
Public Function ValidationTool() As Boolean
For Each cntrl As Control In Controls
If TypeOf cntrl Is TextBox Then
cntrl.BackColor = Color.White
If cntrl.Text = String.Empty Then
cntrl.BackColor = Color.Yellow
cntrl.Focus()
Return False
End If
End If
Next
Return True
'----FUNC COMPLETE----'
End Function
'-------------------------------------------------------------'
' Name: Exit_Click
' Desc: subroutine to close the window
'-------------------------------------------------------------'
Private Sub btnExitNewGolfer_Click(sender As Object, e As EventArgs) Handles btnExitNewGolfer.Click
Close()
'----SUB COMPLETE----'
End Sub
End Class |
Imports C1.Win.C1TrueDBGrid
Imports System.ComponentModel
Imports Model
Public Class MitumoriNoComboBox
Implements IValidatable
Public Function ValidateMe() As Boolean Implements IValidatable.ValidateMe
Dim e As New System.ComponentModel.CancelEventArgs
OnValidating(e)
If e.Cancel = False Then
OnValidated(New EventArgs())
Return True
End If
Return False
End Function
Private valueSelected As Boolean
Private selectedDataRow As DataRow
Private NoValueOpen As Boolean
Public Overrides Property BackColor() As System.Drawing.Color
Get
Return MyBase.BackColor
End Get
Set(ByVal value As System.Drawing.Color)
MyBase.BackColor = value
TextControl.BackColor = value
End Set
End Property
Public ReadOnly Property SelectedValue() As DataRow
Get
Return selectedDataRow
End Get
End Property
Public ReadOnly Property GridControl() As C1.Win.C1TrueDBGrid.C1TrueDBGrid
Get
Return DropDownIcon
End Get
End Property
<Browsable(False)> _
Public Overrides Property AutoValidate() As System.Windows.Forms.AutoValidate
Get
Return Windows.Forms.AutoValidate.Disable
End Get
Set(ByVal value As System.Windows.Forms.AutoValidate)
MyBase.AutoValidate = value
End Set
End Property
Private Sub TypComboBox_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Resize
If Width > 20 Then
Dim w As Integer = Width
' w -= 20
w = CType(Int(w / 8), Integer) * 8
' w += 21
Width = w + 2
End If
Height = TextBoxControl.Height + 2
' TextBoxControl.Location = New System.Drawing.Point(0, 0)
' TextBoxControl.Size = New System.Drawing.Size(Me.Size.Width - 20, Me.Size.Height)
TextBoxControl.Left = 0
TextBoxControl.Top = 0
'TextBoxControl.Width = Width - 20
TextBoxControl.Width = 0
'DropDownIcon.Left = Width - 20
DropDownIcon.Left = 0
DropDownIcon.Top = 0
DropDownIcon.Width = 20
DropDownIcon.Height = 20
' DropDownIcon.Location = New System.Drawing.Point(Me.Size.Width - 20 - 0, 0)
' DropDownIcon.Size = New System.Drawing.Size(20, 20)
End Sub
Public Sub AttachDataSource(ByVal tableName As ComboBoxTableName, ByVal dataValueSource As DTO.ResponseGetComboBoxContents)
DropdownControl.DataSource = dataValueSource.Contents(tableName).ResultDataSet.Tables(0)
DropDown.DataMember = ""
DisplayMemberValue = dataValueSource.Contents(tableName).DataTextFields(1)
DropDown.ValueMember = dataValueSource.Contents(tableName).DataValueField
DropDown.SetWidth(tableName)
'プロパティ検証
#If DEBUG Then
'If Me.Width < 6 * GetCodeLength(tableName) Then
' 'Throw New ApplicationException(Me.Name & ":Widthを確認してください")
' MessageBox.Show(Me.Name & ":Widthを確認してください", FindForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning)
'End If
If UseZeroPadding = True Then
If ZeroPaddingLength <> GetCodeLength(tableName) Then
Throw New ApplicationException(Me.Name & ":ZeroPaddingLengthは" & GetCodeLength(tableName).ToString & "でなければなりません")
End If
End If
If UseUpdateLinkedTextByCodeChange = True And LinkedTextBox IsNot Nothing Then
If LinkedTextBox.Width < 8 * GetNameLength(tableName) Then
'Throw New ApplicationException(LinkedTextBox.Name & ":名称表示用のテキストボックスのWidthを確認してください")
MessageBox.Show(LinkedTextBox.Name & ":名称表示用のテキストボックスのWidthを確認してください", FindForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
If LinkedTextBox.ReadOnly = False Then
Throw New ApplicationException(LinkedTextBox.Name & ":名称表示用のテキストボックスはreadonlyでなければなりません")
End If
If LinkedTextBox.Enabled = True Then
Throw New ApplicationException(LinkedTextBox.Name & ":名称表示用のテキストボックスはEnabled = Falseでなければなりません")
End If
End If
If PopupErrorDialog = True Then
If Utility.NUCheck(Me.DisplayName) = True Then
Throw New ApplicationException(LinkedTextBox.Name & ":PopupErrorDialog使用時はDisplayNameをかならず指定してください")
End If
End If
#End If
'幅の計算
Dim x As Integer = 0
For i As Integer = 0 To DropDown.DisplayColumns.Count - 1
x += DropDown.DisplayColumns(i).Width + 1
'セルの境界線なし
DropDown.DisplayColumns(i).ColumnDivider.Style = C1.Win.C1TrueDBGrid.LineStyleEnum.None
Next
DropDown.Width = x + DropdownControl.VScrollBar.Width + 2
DropDown.Height = CulcHeight()
End Sub
Private Function GetCodeLength(ByVal tableName As ComboBoxTableName) As Integer
Select Case tableName
Case ComboBoxTableName.T_MITUMORIHED_MITUMORINO
Case ComboBoxTableName.T_JYUTYUHED_JYUTYUNO
Case ComboBoxTableName.T_HATYUHED_HATYUNO
Case ComboBoxTableName.T_SEIKYUHED_SEIKYUNO
Return 13
Case Else
Throw New ApplicationException("対応していないコンボボックス種別です。")
End Select
End Function
Private Function GetNameLength(ByVal tableName As ComboBoxTableName) As Integer
Select Case tableName
Case ComboBoxTableName.T_MITUMORIHED_MITUMORINO
Case ComboBoxTableName.T_JYUTYUHED_JYUTYUNO
Case ComboBoxTableName.T_HATYUHED_HATYUNO
Case ComboBoxTableName.T_SEIKYUHED_SEIKYUNO
Case Else
Throw New ApplicationException("対応していないコンボボックス種別です。")
End Select
End Function
Private Sub TypComboBox_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With DropDown
.AllowRowSizing = RowSizingEnum.None '行サイズの変更
.FlatStyle = FlatModeEnum.Standard
.RowDivider.Style = C1.Win.C1TrueDBGrid.LineStyleEnum.None '行の境界線スタイル
.DisplayColumns(0).ColumnDivider.Style = C1.Win.C1TrueDBGrid.LineStyleEnum.None
.HeadingStyle.Borders.BorderType = C1.Win.C1TrueDBGrid.BorderTypeEnum.None
'.HeadingStyle.BackColor = Color.FromArgb(0, 0, 192)
.HeadingStyle.BackColor = Color.DarkSlateBlue
.HeadingStyle.ForeColor = Color.White
.ColumnCaptionHeight = 20
.RowHeight = 20
.AllowSort = False
If Me.FindForm IsNot Nothing Then
.Font = Me.FindForm.Font
End If
.AllowRowSizing = RowSizingEnum.None 'スプリットのサイズ変更
.AllowColSelect = False
.VScrollBar.Style = ScrollBarStyleEnum.Always
.ExtendRightColumn = True 'デッドエリア(隙間)を埋める
End With
With DropDownIcon
.Splits(0).DisplayColumns(0).OwnerDraw = True
End With
End Sub
<Browsable(False)> _
Public ReadOnly Property TextControl() As TextBoxEx
Get
Return TextBoxControl
End Get
End Property
Private DropDownCLosed As Boolean = False
Private Sub Dropdown_DropDownClose(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropdownControl.DropDownClose
' DropDownIcon.Enabled = False
If valueSelected = True Then
RaiseEvent SelectionChangeCommitted(Me, e)
End If
' TextControl.Focus()
RaiseEvent DropDownClose(Me, e)
DropDownCLosed = True
DropDownIcon.Invalidate() 'OwnerDrawイベントを発生させる
End Sub
Private Sub DropDownIcon_OwnerDrawCell(ByVal sender As Object, ByVal e As C1.Win.C1TrueDBGrid.OwnerDrawCellEventArgs) Handles DropDownIcon.OwnerDrawCell
If DropDownCLosed = True Then
DropDownCLosed = False
TextControl.Focus() 'テキストボックスにフォーカス
' DropDownIcon.Enabled = True
End If
End Sub
Private Sub DropDownIcon_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DropDownIcon.KeyDown
If e.KeyCode = Keys.Enter Then
If DropDown.Bookmark >= 0 Then
valueSelected = True
selectedDataRow = CType(DropDown.DataSource, DataTable).Rows(DropDown.Bookmark)
Text = CType(DropDown.Columns(DropDown.ValueMember).Text, String)
End If
End If
End Sub
Private Function CulcHeight() As Integer
Dim offset As Integer = 0
Dim form As Control = Me.FindForm
Dim c As Control = Me
Do While True
offset += c.Top
c = c.Parent
If c.Name = form.Name Then
Exit Do
End If
Loop
Dim intNotBottomWorkingArea As Integer = ((System.Windows.Forms.Screen.GetBounds(Me).Height - System.Windows.Forms.Screen.GetWorkingArea(Me).Height) - System.Windows.Forms.Screen.GetWorkingArea(Me).Y) '画面下の作業領域外
Return CType((System.Windows.Forms.Screen.GetBounds(Me).Height - intNotBottomWorkingArea) - ((offset + form.Top) + 68), Integer)
End Function
Private Sub Dropdown_DropDownOpen(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropdownControl.DropDownOpen
valueSelected = False
NoValueOpen = False '2009.02.13 Ins asano V1~V3対応
Dim dataRow As DataRow() = CType(DropdownControl.DataSource, DataTable).Select(DropdownControl.ValueMember & " = '" & TextBoxControl.Text & "'")
If dataRow.Length = 1 Then
DropDown.Bookmark = CType(DropDown.DataSource, DataTable).Rows.IndexOf(dataRow(0))
DropDown.Row = CType(DropDown.DataSource, DataTable).Rows.IndexOf(dataRow(0))
Else
'↓2009.02.13 Ins asano V1~V3対応
If DropDown.Bookmark <> 0 Then
NoValueOpen = True
End If
DropDown.Bookmark = 0
DropDown.Row = 0
'↑2009.02.13 Ins asano V1~V3対応
End If
RaiseEvent DropDownOpen(Me, e)
End Sub
<Description("ドロップダウンが閉じるときに発生します。")> _
Public Event DropDownClose As EventHandler(Of EventArgs)
<Description("ドロップダウンが最初に表示されるときに発生します。")> _
Public Event DropDownOpen As EventHandler(Of EventArgs)
<Description("選択した項目が変更され、その変更が TypComboBox に表示されると発生します。")> _
Public Event SelectionChangeCommitted As EventHandler(Of EventArgs)
<Category("Key")> _
<Description("Enterキーが押されたときに発生します。")> _
Public Event PressEnter As EventHandler(Of EventArgs)
<Category("検証")> _
<Description("マスタ存在チェックの検証時に発生します。")> _
Public Event MasterCheckValidate As EventHandler(Of MasterCheckValidatorEventArgs)
<Category("Focus")> _
<Description("リンクテキストの値を変更する必要があるときに発生します。")> _
Public Event LinkedTextUpdate As EventHandler(Of LinkedTextUpdateEventArgs)
Public Sub OnLinkedTextUpdate(ByVal e As LinkedTextUpdateEventArgs)
RaiseEvent LinkedTextUpdate(Me, e)
End Sub
Public Sub OnMasterCheckValidate(ByVal e As MasterCheckValidatorEventArgs)
RaiseEvent MasterCheckValidate(Me, e)
End Sub
' Public Shadows Event KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs)
Public Shadows Event KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
<DefaultValue(32768)> _
<Description("エディットコントロールに入力できる最大文字数を指定します。")> _
Public Property MaxLength() As Integer
Get
Return TextBoxControl.MaxLength
End Get
Set(ByVal value As Integer)
TextBoxControl.MaxLength = value
End Set
End Property
<DefaultValue(True)> _
<Description("Enter押下時にフォーカスを次のコントロールに移動させるかどうかを示します。")> _
Public Property MoveFocusAfterEnter() As Boolean
Get
Return TextBoxControl.MoveFocusAfterEnter
End Get
Set(ByVal value As Boolean)
TextBoxControl.MoveFocusAfterEnter = value
End Set
End Property
<DefaultValue("0"c)> _
<Description("ゼロ詰めするときの文字を示します。")> _
Public Property ZeroPaddingChar() As Char
Get
Return TextBoxControl.ZeroPaddingChar
End Get
Set(ByVal value As Char)
TextBoxControl.ZeroPaddingChar = value
End Set
End Property
<DefaultValue(True)> _
<Description("コントロールがフォームのアクティブコントロールになったときにテキストをハイライトするかどうかを示します。")> _
Public Property UseHighlightText() As Boolean
Get
Return TextBoxControl.UseHighlightText
End Get
Set(ByVal value As Boolean)
TextBoxControl.UseHighlightText = value
End Set
End Property
<Description("データ ソースを取得します。")> _
<Browsable(False)> _
Public ReadOnly Property DataSource() As Object
Get
Return DropdownControl.DataSource
End Get
End Property
<Browsable(False)> _
Public ReadOnly Property DropDown() As DropdownEx
Get
Return DropdownControl
End Get
End Property
<Description("グリッドが連結するマルチメンバデータソースで特定のデータメンバを取得します。")> _
Public ReadOnly Property DataMember() As String
Get
Return DropDown.DataMember
End Get
End Property
Private DisplayMemberValue As String
<DefaultValue("")> _
<Description("名称の更新に使用するフィールドを取得します。")> _
Public ReadOnly Property DisplayMember() As String
Get
Return DisplayMemberValue
End Get
End Property
'Public Property Value() As String
' Get
' Return TextBoxControl.Text
' End Get
' Set(ByVal value As String)
' TextBoxControl.Text = value
' End Set
'End Property
Public Function GetDisplayMember() As String
If TextBoxControl.Text.IndexOf("'"c) <> -1 Then
Return ""
End If
Dim dataRow As DataRow() = CType(DropdownControl.DataSource, DataTable).Select(DropdownControl.ValueMember & " = '" & TextBoxControl.Text & "'")
If dataRow.Length = 0 Then
Return ""
Else
Return CType(dataRow(0)(DisplayMember), String)
End If
End Function
Public Function GetFirstCode() As String
If CType(DropdownControl.DataSource, DataTable).Rows.Count = 0 Then
Return ""
End If
Return CType(CType(DropdownControl.DataSource, DataTable).Rows(0)(DropdownControl.ValueMember), String)
End Function
Public Function GetMaxCode() As String
Return Utility.ZeroPadding("9", MaxLength, CChar("9"))
End Function
Public Function GetMinCode() As String
Return Utility.ZeroPadding("0", MaxLength, CChar("0"))
End Function
Private Sub fncLinkedTextUpdate()
If UseUpdateLinkedTextByCodeChange And LinkedTextBox IsNot Nothing And Utility.NUCheck(DisplayMember) = False Then
LinkedTextBox.Text = GetDisplayMember()
'Dim dataRow As DataRow() = CType(DropdownControl.DataSource, DataTable).Select(DropdownControl.ValueMember & " = '" & TextBoxControl.Text & "'")
'If dataRow.Length = 0 Then
' LinkedTextBox.Text = ""
'Else
' LinkedTextBox.Text = CType(dataRow(0)(DisplayMember), String)
'End If
End If
End Sub
<Browsable(True)> _
<Bindable(True)> _
<DefaultValue("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890")> _
Public Overrides Property Text() As String
Get
Return TextBoxControl.Text
End Get
Set(ByVal value As String)
TextBoxControl.Text = value
'fncLinkedTextUpdate()
End Set
End Property
Private Sub DropdownControl_RowChange(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DropdownControl.RowChange
If DropDown.Bookmark <> -1 Then
'↓2009.02.13 Ins asano V1~V3対応
'If NoValueOpen = False Then
valueSelected = True
selectedDataRow = CType(DropDown.DataSource, DataTable).Rows(DropDown.Bookmark)
Text = CType(DropDown.Columns(DropDown.ValueMember).Text, String)
'End If
NoValueOpen = False
'↑2009.02.13 Ins asano V1~V3対応
End If
End Sub
'Public Overrides Property Font() As System.Drawing.Font
' Get
' Return MyBase.Font
' End Get
' Set(ByVal value As System.Drawing.Font)
' TextBoxControl.Font = value
' MyBase.Font = value
' End Set
'End Property
<Category("Focus")> _
<Description("コントロールの検証が失敗したときに発生します。")> _
Public Event ValidateError As EventHandler(Of ValidateErrorEventArgs)
<Category("Focus")> _
<Description("Textが変更されるかフォーカスを失ったときに発生します。")> _
Public Event TextUpdated As EventHandler(Of EventArgs)
Public Sub OnValidateError(ByVal e As ValidateErrorEventArgs)
RaiseEvent ValidateError(Me, e)
End Sub
<DefaultValue(False)> _
<Description("コントロールがフォームのアクティブコントロールでなくなったときにゼロ詰めするかどうかを示します。")> _
Public Property UseZeroPadding() As Boolean
Get
Return TextBoxControl.UseZeroPadding
End Get
Set(ByVal value As Boolean)
TextBoxControl.UseZeroPadding = value
End Set
End Property
<DefaultValue(False)> _
<Category("検証")> _
<Description("値がNullかどうかの検証をするかどうかを示します。")> _
Public Property UseNullValidator() As Boolean
Get
Return TextBoxControl.UseNullValidator
End Get
Set(ByVal value As Boolean)
TextBoxControl.UseNullValidator = value
End Set
End Property
'Private UseMasterCheckValidatorValue As Boolean
'Private UseUpdateLinkedTextByCodeChangeValue As Boolean
<DefaultValue(False)> _
<Description("値が変更されたときに名称を更新するかどうかを示します。")> _
Public Property UseUpdateLinkedTextByCodeChange() As Boolean
Get
Return TextControl.UseUpdateLinkedTextByCodeChange
End Get
Set(ByVal value As Boolean)
TextControl.UseUpdateLinkedTextByCodeChange = value
End Set
End Property
<DefaultValue(False)> _
<Category("検証")> _
<Description("値がマスタに存在するかどうかの検証をするかどうかを示します。")> _
Public Property UseMasterCheckValidator() As Boolean
Get
Return TextControl.UseMasterCheckValidator
End Get
Set(ByVal value As Boolean)
TextControl.UseMasterCheckValidator = value
End Set
End Property
<DefaultValue("")> _
<Description("コントロールの表示名を示します。")> _
Public Property DisplayName() As String
Get
Return TextBoxControl.DisplayName
End Get
Set(ByVal value As String)
TextBoxControl.DisplayName = value
End Set
End Property
<DefaultValue(0)> _
<Description("ゼロ詰めの桁数を示します。")> _
Public Property ZeroPaddingLength() As Integer
Get
Return TextBoxControl.ZeroPaddingLength
End Get
Set(ByVal value As Integer)
TextBoxControl.ZeroPaddingLength = value
End Set
End Property
<DefaultValue(True)> _
<Category("検証")> _
<Description("検証失敗時に規定のメッセージを表示するかどうかを示します。")> _
Public Property PopupErrorDialog() As Boolean
Get
Return TextBoxControl.PopupErrorDialog
End Get
Set(ByVal value As Boolean)
TextBoxControl.PopupErrorDialog = value
End Set
End Property
Private Sub TextBoxControl_PreviewKeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles TextBoxControl.PreviewKeyDown
If e.KeyCode = Keys.Down Then
DropDownIcon.Focus()
SendKeys.Send("%{DOWN}")
End If
End Sub
<Description("コード変更時に名称を表示するコントロールを指定します。")> _
Public Property LinkedTextBox() As TextBox
Get
Return TextControl.LinkedTextBox
End Get
Set(ByVal value As TextBox)
TextControl.LinkedTextBox = value
End Set
End Property
Public Sub ResetLinkedTextBox()
LinkedTextBox = Nothing
End Sub
Public Function ShouldSerializeLinkedTextBox() As Boolean
If LinkedTextBox Is Nothing Then
Return False
Else
Return True
End If
End Function
Public Sub New()
DisplayMemberValue = ""
' この呼び出しは、Windows フォーム デザイナで必要です。
InitializeComponent()
' InitializeComponent() 呼び出しの後で初期化を追加します。
TextBoxControl.DigitOnly = True
'データの作成
Dim ds As DataSet = New DataSet
Dim dt As DataTable
dt = ds.Tables.Add("Dummy")
dt.Columns.Add("ColumnA", Type.GetType("System.String"))
dt.Rows.Add(New Object() {""})
'グリッドの設定
DropDownIcon.Columns.Add(New C1DataColumn("", "ColumnA", Type.GetType("System.String")))
DropDownIcon.Splits(0).DisplayColumns(0).Width = 17
DropDownIcon.Splits(0).DisplayColumns(0).HeadingStyle.HorizontalAlignment = AlignHorzEnum.Center
DropDownIcon.Splits(0).DisplayColumns(0).Style.HorizontalAlignment = AlignHorzEnum.Center
DropDownIcon.Splits(0).DisplayColumns(0).Visible = True
'データ連結
DropdownControl.DataSource = dt
DropdownControl.DataMember = "Dummy"
DropDownIcon.SetDataBinding(dt, "", True)
DropDownIcon.Columns(0).DropDown = DropdownControl
DropDownIcon.ColumnHeaders = False
DropDownIcon.RecordSelectors = False
End Sub
Private Sub ShowErrorMessageBox(ByVal type As ValidateErrorType)
Select Case type
Case ValidateErrorType.IsNull
CommonUtility.WinForm.MessageBoxEx.Show(MessageCode_Arg1.M015は必ず入力して下さい, DisplayName, FindForm.Text)
Case ValidateErrorType.NotFound
CommonUtility.WinForm.MessageBoxEx.Show(MessageCode_Arg1.M014が存在しません, DisplayName, FindForm.Text)
Case Else
Throw New ApplicationException("ShowErrorMessageBoxエラー")
End Select
End Sub
Protected Overrides Sub OnValidating(ByVal e As System.ComponentModel.CancelEventArgs)
If TextBoxControl.ValidateMe() = False Then
'Text = CType(DropDown.Columns(DropDown.ValueMember).Text, String)
DropDown.Bookmark = Nothing
e.Cancel = True
If Me.FindForm.AutoValidate = Windows.Forms.AutoValidate.EnablePreventFocusChange Then
TextBoxControl.Focus()
End If
Return
End If
MyBase.OnValidating(e)
End Sub
Private Sub TextBoxControl_LinkedTextUpdate(ByVal sender As Object, ByVal e As LinkedTextUpdateEventArgs) Handles TextBoxControl.LinkedTextUpdate
OnLinkedTextUpdate(e)
If e.Handled = False Then
fncLinkedTextUpdate()
End If
End Sub
Private Sub TextBoxControl_MasterCheckValidate(ByVal sender As Object, ByVal e As MasterCheckValidatorEventArgs) Handles TextBoxControl.MasterCheckValidate
End Sub
Private Sub TextBoxControl_PressEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBoxControl.PressEnter
OnPressEnter(e)
End Sub
Private Sub TextBoxControl_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBoxControl.TextChanged
OnTextChanged(e)
End Sub
Private Sub TextBoxControl_TextUpdated(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBoxControl.TextUpdated
If DesignMode = False Then
OnTextUpdated(e)
End If
End Sub
Private Sub TextBoxControl_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBoxControl.Validated
MyBase.OnValidated(e)
End Sub
Private Sub TextBoxControl_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBoxControl.Validating
MyBase.OnValidating(e)
End Sub
Public Sub OnTextUpdated(ByVal e As EventArgs)
If DesignMode = False Then
RaiseEvent TextUpdated(Me, e)
End If
End Sub
Public Sub OnPressEnter(ByVal e As EventArgs)
RaiseEvent PressEnter(Me, e)
End Sub
Protected Overrides Sub OnEnabledChanged(ByVal e As System.EventArgs)
MyBase.OnEnabledChanged(e)
If Me.Enabled = True Then
TextControl.BackColor = Color.White
Else
TextControl.BackColor = Color.FromArgb(236, 233, 216)
End If
End Sub
End Class
|
Imports System
Imports System.Windows.Forms
Imports Neurotec.Biometrics.Client
Imports Neurotec.Devices
Imports Neurotec.Biometrics
Partial Public Class MainForm
Inherits Form
#Region "Public constructor"
Public Sub New()
InitializeComponent()
End Sub
#End Region
#Region "Private fields"
Private _biometricClient As NBiometricClient
#End Region
#Region "Private form events"
Private Sub MainFormLoad(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
_biometricClient = New NBiometricClient With {.UseDeviceManager = True, .BiometricTypes = NBiometricType.Voice}
_biometricClient.Initialize()
enrollFromFilePanel.BiometricClient = _biometricClient
enrollFromMicrophonePanel.BiometricClient = _biometricClient
verifyVoicePanel.BiometricClient = _biometricClient
identifyVoicePanel.BiometricClient = _biometricClient
End Sub
Private Sub MainFormFormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles MyBase.FormClosing
If _biometricClient IsNot Nothing Then
_biometricClient.Cancel()
End If
End Sub
Private Sub TabControlSelecting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TabControlCancelEventArgs) Handles tabControl1.Selecting
If _biometricClient IsNot Nothing Then
_biometricClient.Cancel()
_biometricClient.Reset()
End If
End Sub
#End Region
End Class
|
Imports ENTITIES
Imports MAPPER
Public Class TipoProductoBLL
Dim TipoProductoENT As TipoProductoENT
Public Function ListarTipoProducto() As List(Of TipoProductoENT)
Dim ListaTipoProducto As New List(Of TipoProductoENT)
Dim lector As IDataReader = TipoProductoMAP.ListarTipoProducto.CreateDataReader
Do While lector.Read()
TipoProductoENT = New TipoProductoENT
With TipoProductoENT
.Tipo = Convert.ToString(lector("Tipo"))
End With
ListaTipoProducto.Add(TipoProductoENT)
Loop
lector.Close()
Return ListaTipoProducto
End Function
End Class
|
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Collections.Specialized
Imports System.Linq
Imports System.Text
Imports System.Windows.Threading
Namespace ChartsDemo
Public Class RealtimeViewModel
Private Const UpdateInterval As Integer = 40
Private ReadOnly dataSource_Renamed As New DataCollection()
Private ReadOnly timer As New DispatcherTimer(DispatcherPriority.Normal)
Private ReadOnly random As New Random()
Private value1 As Double = 10.0
Private value2 As Double = -10.0
Private inProcess As Boolean = True
Public Property TimeInterval() As Integer
Public Overridable Property IsTimerEnabled() As Boolean
Public ReadOnly Property DataSource() As DataCollection
Get
Return dataSource_Renamed
End Get
End Property
Public Overridable Property MinTime() As Date
Public Overridable Property MaxTime() As Date
Public Sub New()
IsTimerEnabled = True
TimeInterval = 10
timer.Interval = TimeSpan.FromMilliseconds(UpdateInterval)
AddHandler timer.Tick, Sub(_d, _e) OnTimerTick()
End Sub
Public Sub DisableProcess()
inProcess = timer.IsEnabled
IsTimerEnabled = False
End Sub
Public Sub RestoreProcess()
IsTimerEnabled = inProcess
End Sub
Public Sub ToggleIsTimerEnabled()
IsTimerEnabled = Not IsTimerEnabled
End Sub
Protected Sub OnIsTimerEnabledChanged()
timer.IsEnabled = IsTimerEnabled
End Sub
Private Sub OnTimerTick()
Dim argument As Date = Date.Now
Dim minDate As Date = argument.AddSeconds(-TimeInterval)
Dim itemsToInsert As IList(Of ProcessItem) = New List(Of ProcessItem)()
For i As Integer = 0 To UpdateInterval - 1
itemsToInsert.Add(New ProcessItem() With {.DateAndTime = argument, .Process1 = value1, .Process2 = value2})
argument = argument.AddMilliseconds(1)
value1 = CalculateNextValue(value1)
value2 = CalculateNextValue(value2)
Next i
dataSource_Renamed.AddRange(itemsToInsert)
dataSource_Renamed.RemoveRangeAt(0, dataSource_Renamed.TakeWhile(Function(item) item.DateAndTime < minDate).Count())
MinTime = minDate
MaxTime = argument
End Sub
Private Function CalculateNextValue(ByVal value As Double) As Double
Return value + (random.NextDouble() * 10.0 - 5.0)
End Function
End Class
Public Structure ProcessItem
Public Property DateAndTime() As Date
Public Property Process1() As Double
Public Property Process2() As Double
End Structure
Public Class DataCollection
Inherits ObservableCollection(Of ProcessItem)
Public Sub AddRange(ByVal items As IList(Of ProcessItem))
For Each item As ProcessItem In items
Me.Items.Add(item)
Next item
OnCollectionChanged(New NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, DirectCast(items, IList), Me.Items.Count - items.Count))
End Sub
Public Sub RemoveRangeAt(ByVal startingIndex As Integer, ByVal count As Integer)
Dim removedItems = New List(Of ProcessItem)(count)
For i As Integer = 0 To count - 1
removedItems.Add(Items(startingIndex))
Items.RemoveAt(startingIndex)
Next i
If count > 0 Then
OnCollectionChanged(New NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, DirectCast(removedItems, IList), startingIndex))
End If
End Sub
End Class
End Namespace
|
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.Collections.Generic
Namespace Ini
Public Class IniFile
Public path As String
<DllImport("KERNEL32.DLL", EntryPoint:="GetPrivateProfileStringW", SetLastError:=True, CharSet:=CharSet.Unicode, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Private Shared Function GetPrivateProfileString(ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnString As String, ByVal nSize As Integer, ByVal lpFilename As String) As Integer
End Function
<DllImport("KERNEL32.DLL", EntryPoint:="WritePrivateProfileStringW", SetLastError:=True, CharSet:=CharSet.Unicode, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Private Shared Function WritePrivateProfileString(ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpString As String, ByVal lpFilename As String) As Integer
End Function
Public Sub New(ByVal INIPath As String)
path = INIPath
End Sub
Public Sub IniWriteValue(ByVal Section As String, ByVal Key As String, ByVal Value As String)
WritePrivateProfileString(Section, Key, Value, Me.path)
End Sub
Public Function IniReadValue(ByVal Section As String, ByVal Key As String) As String
Dim result As New String(" "c, 255)
GetPrivateProfileString(Section, Key, "", result, 255, Me.path)
Return result
End Function
Public Function IniGetCategories() As List(Of String)
Dim returnString As New String(" "c, 65536)
GetPrivateProfileString(Nothing, Nothing, Nothing, returnString, 65536, Me.path)
Dim result As New List(Of String)(returnString.Split(ControlChars.NullChar))
result.RemoveRange(result.Count - 2, 2)
Return result
End Function
Public Function IniGetKeys(ByVal category As String) As List(Of String)
Dim returnString As New String(" "c, 32768)
GetPrivateProfileString(category, Nothing, Nothing, returnString, 32768, Me.path)
Dim result As New List(Of String)(returnString.Split(ControlChars.NullChar))
result.RemoveRange(result.Count - 2, 2)
Return result
End Function
End Class
End Namespace
|
'--------------------------------------------------
' DirectoryTreeView.vb (c) 2002 by Charles Petzold
'--------------------------------------------------
Imports System
Imports System.Drawing
Imports System.IO
Imports System.Windows.Forms
Class DirectoryTreeView
Inherits TreeView
Sub New()
' Make a little more room for long directory names.
Width *= 2
' Get images for tree.
ImageList = New ImageList()
ImageList.Images.Add(New Bitmap(Me.GetType(), "35FLOPPY.BMP"))
ImageList.Images.Add(New Bitmap(Me.GetType(), "CLSDFOLD.BMP"))
ImageList.Images.Add(New Bitmap(Me.GetType(), "OPENFOLD.BMP"))
' Construct tree.
RefreshTree()
End Sub
Sub RefreshTree()
' Turn off visual updating and clear tree.
BeginUpdate()
Nodes.Clear()
' Make disk drives the root nodes.
Dim astrDrives() As String = Directory.GetLogicalDrives()
Dim str As String
For Each str In astrDrives
Dim tnDrive As New TreeNode(str, 0, 0)
Nodes.Add(tnDrive)
AddDirectories(tnDrive)
If str = "C:\" Then
SelectedNode = tnDrive
End If
Next str
EndUpdate()
End Sub
Private Sub AddDirectories(ByVal tn As TreeNode)
tn.Nodes.Clear()
Dim strPath As String = tn.FullPath
Dim dirinfo As New DirectoryInfo(strPath)
Dim adirinfo() As DirectoryInfo
' Avoid message box reporting drive A has no diskette!
If Not dirinfo.Exists Then Return
Try
adirinfo = dirinfo.GetDirectories()
Catch
Return
End Try
Dim di As DirectoryInfo
For Each di In adirinfo
Dim tnDir As New TreeNode(di.Name, 1, 2)
tn.Nodes.Add(tnDir)
' We could now fill up the whole tree with this statement:
' AddDirectories(tnDir)
' But it would be too slow. Try it!
Next di
End Sub
Protected Overrides Sub OnBeforeExpand(ByVal tvcea As TreeViewCancelEventArgs)
MyBase.OnBeforeExpand(tvcea)
BeginUpdate()
Dim tn As TreeNode
For Each tn In tvcea.Node.Nodes
AddDirectories(tn)
Next tn
EndUpdate()
End Sub
End Class
|
'*****************************************************
'* Copyright 2017, SportingApp, all rights reserved. *
'* Author: Shih Peiting *
'* mailto: sportingapp@gmail.com *
'*****************************************************
Imports System.Drawing
Imports System.IO
Imports System.Runtime.CompilerServices
Imports System.Text
Namespace Extensions
Public Module SaStreamExtension
<Extension()>
Public Function CopyTo(ByVal input As Stream, ByVal output As Stream) As Boolean
Dim buffer As Byte() = New Byte(16383) {}
Dim bytesRead As Integer
While (bytesRead = input.Read(buffer, 0, buffer.Length)) > 0
output.Write(buffer, 0, bytesRead)
End While
End Function
End Module
End Namespace |
Namespace UI
Public Class SPFileDialog
Public Enum FileDialogTypes As Integer
General = 0
Picture
OfficeDocument
Video
Audio
End Enum
Public Shared Function ShowDialog(ByVal FileType As FileDialogTypes) As String
Try
Using myFileDialog As New OpenFileDialog
With myFileDialog
.Filter = GetFilters(FileType)
If .ShowDialog() = DialogResult.OK Then
Return .FileName
End If
End With
End Using
Catch ex As Exception
End Try
Return Nothing
End Function
Public Shared Function ShowMultiDialog(ByVal FileType As FileDialogTypes) As String()
Try
Using myFileDialog As New OpenFileDialog
With myFileDialog
If .ShowDialog() = DialogResult.OK Then
Return .FileNames
End If
End With
End Using
Catch ex As Exception
End Try
Return Nothing
End Function
Private Shared Function GetFilters(ByVal filetype As FileDialogTypes) As String
Select Case filetype
Case FileDialogTypes.Picture
Return "All Picture Files(*.jpeg,*.jpe,*.jpg,*.gif,*.png,*.bmp,*.wmf,*.ico)|*.jpeg;*.jpe;*.jpg;*.gif;*.png;*.bmp;*.wmf;*.ico|JPEG Files(*.jpg,*.jpe,*.jpeg)|*.jpg;*.jpe;*.jpeg"
Case Else
Return "All Files(*.*)|*.*"
End Select
Return Nothing
End Function
End Class
End Namespace
|
Interface IAnimal
Property Name As String
ReadOnly Property BornYear As Int16
Sub Eat()
Sub Hunting()
End Interface |
#Region "Microsoft.VisualBasic::892d0e2f3344f73e04a28ffd0f53a770, mzkit\Rscript\Library\mzkit\assembly\Assembly.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: 554
' Code Lines: 420
' Comment Lines: 70
' Blank Lines: 64
' File Size: 23.31 KB
' Module Assembly
'
' Function: GetFileType, getMs1Scans, ionMode, IonPeaks, LoadIndex
' MatrixDataFrame, (+2 Overloads) mzMLMs1, mzXML2Mgf, (+2 Overloads) mzXMLMs1, openXmlSeeks
' PeakMs2FileIndex, printPeak, rawScans, ReadMgfIons, ReadMslIons
' readMsp, ScanIds, Seek, summaryIons, writeMgfIons
'
' Sub: Main
'
' /********************************************************************************/
#End Region
Imports System.IO
Imports System.Runtime.CompilerServices
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.ASCII
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.ASCII.MGF
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.ASCII.MSL
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.ASCII.MSP
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.DataReader
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.MarkupData
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.MarkupData.mzML
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.mzData.mzWebCache
Imports BioNovoGene.Analytical.MassSpectrometry.Math
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Ms1
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Spectra
Imports Microsoft.VisualBasic.ApplicationServices.Debugging.Logging
Imports Microsoft.VisualBasic.CommandLine.Reflection
Imports Microsoft.VisualBasic.ComponentModel.Collection
Imports Microsoft.VisualBasic.Language
Imports Microsoft.VisualBasic.Linq
Imports Microsoft.VisualBasic.Scripting.MetaData
Imports Microsoft.VisualBasic.Text
Imports Microsoft.VisualBasic.ValueTypes
Imports SMRUCC.Rsharp.Runtime
Imports SMRUCC.Rsharp.Runtime.Components
Imports SMRUCC.Rsharp.Runtime.Internal.Object
Imports SMRUCC.Rsharp.Runtime.Interop
Imports SMRUCC.Rsharp.Runtime.Vectorization
Imports mzXMLAssembly = BioNovoGene.Analytical.MassSpectrometry.Assembly.MarkupData.mzXML
Imports REnv = SMRUCC.Rsharp.Runtime
Imports Rlist = SMRUCC.Rsharp.Runtime.Internal.Object.list
''' <summary>
''' The mass spectrum assembly file read/write library module.
''' </summary>
<Package("assembly", Category:=APICategories.UtilityTools)>
Module Assembly
<RInitialize>
Sub Main()
Call Internal.Object.Converts.makeDataframe.addHandler(GetType(Ions()), AddressOf summaryIons)
Call Internal.Object.Converts.makeDataframe.addHandler(GetType(PeakMs2), AddressOf MatrixDataFrame)
Call Internal.ConsolePrinter.AttachConsoleFormatter(Of PeakMs2)(AddressOf printPeak)
End Sub
Private Function MatrixDataFrame(peak As PeakMs2, args As Rlist, env As Environment) As dataframe
Dim dataframe As New dataframe With {
.columns = New Dictionary(Of String, Array)
}
dataframe.columns("mz") = peak.mzInto.Select(Function(x) x.mz).ToArray
dataframe.columns("into") = peak.mzInto.Select(Function(x) x.intensity).ToArray
dataframe.columns("annotation") = peak.mzInto.Select(Function(x) x.Annotation).ToArray
Return dataframe
End Function
Private Function printPeak(peak As PeakMs2) As String
Dim xcms_id As String = $"M{CInt(peak.mz)}T{CInt(peak.rt) + 1}"
Dim top6 As Double() = peak.mzInto _
.OrderByDescending(Function(m) m.intensity) _
.Take(6) _
.Select(Function(m) m.mz) _
.ToArray
Dim top6Str As String = top6 _
.Select(Function(d) d.ToString("F4")) _
.JoinBy(vbTab)
Return $"[{xcms_id}, {peak.intensity}] {peak.activation}-{peak.collisionEnergy}eV,{vbTab}{peak.fragments} fragments: {top6Str}..."
End Function
''' <summary>
''' summary of the mgf ions
''' </summary>
''' <param name="x"></param>
''' <param name="args"></param>
''' <param name="env"></param>
''' <returns></returns>
Private Function summaryIons(x As Ions(), args As Rlist, env As Environment) As dataframe
Dim title As MetaData() = x.Select(Function(a) New MetaData(a.Meta)).ToArray
Dim rt As Array = x.Select(Function(a) CInt(a.RtInSeconds)).ToArray
Dim mz As Array = x.Select(Function(a) Val(a.PepMass.name).ToString("F3")).ToArray
Dim into As Array = x.Select(Function(a) Val(a.PepMass.text).ToString("G2")).ToArray
Dim charge As Array = x.Select(Function(a) a.Charge).ToArray
Dim accession As Array = x.Select(Function(a) a.Accession).ToArray
Dim raw As Array = x.Select(Function(a) a.Rawfile).ToArray
Dim fragments As Array = x.Select(Function(a) a.Peaks.Length).ToArray
Dim da3 = Tolerance.DeltaMass(0.3)
Dim topN As Integer = args.getValue(Of Integer)("top.n", env, 3)
Dim metaFields As Index(Of String) = args.getValue(Of String())("meta", env, {})
Dim topNProduct As Array = x _
.Select(Function(a)
Return a.Peaks _
.Centroid(da3, LowAbundanceTrimming.Default) _
.OrderByDescending(Function(p) p.intensity) _
.Take(topN) _
.Select(Function(p)
Return p.mz.ToString("F3")
End Function) _
.JoinBy(", ")
End Function) _
.ToArray
Dim df As New dataframe With {
.columns = New Dictionary(Of String, Array) From {
{NameOf(mz), mz},
{NameOf(rt), rt},
{NameOf(into), into},
{NameOf(charge), charge},
{NameOf(raw), raw},
{"product(m/z)", topNProduct}
}
}
If "accession" Like metaFields Then
df.columns.Add(NameOf(accession), accession)
End If
If "fragments" Like metaFields Then
df.columns.Add(NameOf(fragments), fragments)
End If
df.columns.Add(NameOf(MetaData.activation), title.Select(Function(a) a.activation).ToArray)
df.columns.Add(NameOf(MetaData.collisionEnergy), title.Select(Function(a) a.collisionEnergy).ToArray)
df.columns.Add(NameOf(MetaData.kegg), title.Select(Function(a) a.kegg).ToArray)
df.columns.Add(NameOf(MetaData.precursor_type), title.Select(Function(a) a.precursor_type).ToArray)
If "compound_class" Like metaFields Then
df.columns.Add(NameOf(MetaData.compound_class), title.Select(Function(a) a.compound_class).ToArray)
End If
If "formula" Like metaFields Then
df.columns.Add(NameOf(MetaData.formula), title.Select(Function(a) a.formula).ToArray)
End If
If "mass" Like metaFields Then
df.columns.Add(NameOf(MetaData.mass), title.Select(Function(a) a.mass).ToArray)
End If
If "name" Like metaFields Then
df.columns.Add(NameOf(MetaData.name), title.Select(Function(a) a.name).ToArray)
End If
If "polarity" Like metaFields Then
df.columns.Add(NameOf(MetaData.polarity), title.Select(Function(a) a.polarity).ToArray)
End If
Return df
End Function
''' <summary>
''' read MSL data files
''' </summary>
''' <param name="file$"></param>
''' <param name="unit"></param>
''' <returns></returns>
<ExportAPI("read.msl")>
Public Function ReadMslIons(file$, Optional unit As TimeScales = TimeScales.Second) As MSLIon()
Return MSL.FileReader.Load(file, unit).ToArray
End Function
<ExportAPI("read.mgf")>
Public Function ReadMgfIons(file As String) As Ions()
Return MgfReader.StreamParser(path:=file).ToArray
End Function
<ExportAPI("read.msp")>
Public Function readMsp(file As String, Optional parseMs2 As Boolean = True) As Object
Return MspData.Load(file, ms2:=parseMs2).DoCall(AddressOf pipeline.CreateFromPopulator)
End Function
''' <summary>
''' this function ensure that the output result of the any input ion objects is peakms2 data type.
''' </summary>
''' <param name="ions">a vector of mgf <see cref="Ions"/> from the ``read.mgf`` function or other data source.</param>
''' <param name="env"></param>
''' <returns></returns>
<ExportAPI("mgf.ion_peaks")>
<RApiReturn(GetType(PeakMs2))>
Public Function IonPeaks(<RRawVectorArgument>
ions As Object,
Optional lazy As Boolean = True,
Optional env As Environment = Nothing) As Object
Dim pipeline As pipeline = pipeline.TryCreatePipeline(Of Ions)(ions, env)
If pipeline.isError Then
Return pipeline.getError
End If
If lazy Then
Return pipeline.populates(Of Ions)(env) _
.IonPeaks _
.DoCall(AddressOf pipeline.CreateFromPopulator)
Else
Return pipeline.populates(Of Ions)(env) _
.IonPeaks _
.ToArray
End If
End Function
<ExportAPI("open.xml_seek")>
Public Function openXmlSeeks(file As String, Optional env As Environment = Nothing) As Object
If Not file.FileExists Then
Return Internal.debug.stop({
$"the given file '{file}' is not found on your file system!",
$"file: {file}"
}, env)
Else
Return New XmlSeek(file).LoadIndex
End If
End Function
<ExportAPI("seek")>
Public Function Seek(file As XmlSeek, key As String) As MSScan
Return file.ReadScan(key)
End Function
<ExportAPI("scan_id")>
Public Function ScanIds(file As XmlSeek) As String()
Return file.IndexKeys
End Function
<ExportAPI("load_index")>
Public Function LoadIndex(file As String) As FastSeekIndex
Return FastSeekIndex.LoadIndex(file)
End Function
''' <summary>
''' write spectra data in mgf file format.
''' </summary>
''' <param name="ions"></param>
''' <param name="file">the file path of the mgf file to write spectra data.</param>
''' <param name="relativeInto">
''' write relative intensity value into the mgf file instead of the raw intensity value.
''' no recommended...
''' </param>
''' <returns></returns>
<ExportAPI("write.mgf")>
<RApiReturn(GetType(Boolean))>
Public Function writeMgfIons(<RRawVectorArgument>
ions As Object,
file$,
Optional relativeInto As Boolean = False,
Optional env As Environment = Nothing) As Object
If ions Is Nothing Then
Return Internal.debug.stop("the required ions data can not be nothing!", env)
ElseIf ions.GetType.IsArray AndAlso DirectCast(ions, Array).Length = 0 Then
env.AddMessage($"write empty mgf data to file '{file}', as the given ions collection is empty...", MSG_TYPES.WRN)
Return True
End If
If ions.GetType() Is GetType(pipeline) Then
Using mgfWriter As StreamWriter = file.OpenWriter(Encodings.ASCII, append:=False)
Dim pipeStream As pipeline = DirectCast(ions, pipeline)
If Not pipeStream.elementType Is Nothing AndAlso pipeStream.elementType Like GetType(Ions) Then
For Each ion As Ions In pipeStream.populates(Of Ions)(env)
Call ion.WriteAsciiMgf(mgfWriter, relativeInto)
Next
Else
For Each ionPeak As PeakMs2 In pipeStream.populates(Of PeakMs2)(env)
Call ionPeak _
.MgfIon _
.WriteAsciiMgf(mgfWriter, relativeInto)
Next
End If
End Using
ElseIf ions.GetType Is GetType(LibraryMatrix) Then
Using mgf As StreamWriter = file.OpenWriter
Call DirectCast(ions, LibraryMatrix) _
.MgfIon _
.WriteAsciiMgf(mgf)
End Using
ElseIf ions.GetType Is GetType(PeakMs2()) Then
Using mgfWriter As StreamWriter = file.OpenWriter(Encodings.ASCII, append:=False)
For Each ionPeak As PeakMs2 In DirectCast(ions, PeakMs2())
Call ionPeak _
.MgfIon _
.WriteAsciiMgf(mgfWriter, relativeInto)
Next
End Using
ElseIf ions.GetType Is GetType(Ions()) Then
Using mgfWriter As StreamWriter = file.OpenWriter(Encodings.ASCII, append:=False)
For Each ion As Ions In DirectCast(ions, Ions())
Call ion.WriteAsciiMgf(mgfWriter, relativeInto)
Next
End Using
ElseIf TypeOf ions Is Ions Then
Using mgfWriter As StreamWriter = file.OpenWriter(Encodings.ASCII, append:=False)
Call DirectCast(ions, Ions).WriteAsciiMgf(mgfWriter, relativeInto)
End Using
ElseIf ions.GetType Is GetType(PeakMs2) Then
Using mgfWriter As StreamWriter = file.OpenWriter(Encodings.ASCII, append:=False)
Call DirectCast(ions, PeakMs2) _
.MgfIon _
.WriteAsciiMgf(mgfWriter, relativeInto)
End Using
Else
Return Internal.debug.stop(Message.InCompatibleType(GetType(PeakMs2), ions.GetType, env), env)
End If
Return True
End Function
''' <summary>
''' is mzxml or mzml?
''' </summary>
''' <param name="path"></param>
''' <returns></returns>
Public Function GetFileType(path As String) As Type
Using xml As StreamReader = path.OpenReader
Dim header As String
For i As Integer = 0 To 1
header = xml.ReadLine
If InStr(header, "<indexedmzML ") > 0 Then
Return GetType(indexedmzML)
ElseIf InStr(header, "<mzXML ") > 0 Then
Return GetType(mzXMLAssembly.XML)
End If
Next
Return Nothing
End Using
End Function
''' <summary>
''' get file index string of the given ms2 peak data.
''' </summary>
''' <param name="ms2"></param>
''' <returns></returns>
<ExportAPI("file.index")>
Public Function PeakMs2FileIndex(ms2 As PeakMs2) As String
Return $"{ms2.file}#{ms2.scan}"
End Function
''' <summary>
''' Convert mzxml file as mgf ions.
''' </summary>
''' <param name="file"></param>
''' <returns></returns>
<ExportAPI("mzxml.mgf")>
<RApiReturn(GetType(PeakMs2))>
Public Function mzXML2Mgf(file$,
Optional relativeInto As Boolean = False,
Optional onlyMs2 As Boolean = True,
Optional env As Environment = Nothing) As pipeline
Dim raw As IEnumerable(Of PeakMs2)
Dim type As Type = GetFileType(file)
If type Is Nothing Then
Return Internal.debug.stop({"the given file is not exists or file format not supported!", "file: " & file}, env)
ElseIf type Is GetType(indexedmzML) Then
raw = file.mzMLScanLoader(relativeInto, onlyMs2)
Else
raw = file.mzXMLScanLoader(relativeInto, onlyMs2)
End If
Return raw _
.Where(Function(peak) peak.mzInto.Length > 0) _
.DoCall(Function(scans)
Return New pipeline(scans, GetType(PeakMs2))
End Function)
End Function
''' <summary>
''' get raw scans data from the ``mzXML`` or ``mzMl`` data file
''' </summary>
''' <param name="file"></param>
''' <param name="env"></param>
''' <returns></returns>
<ExportAPI("raw.scans")>
<RApiReturn(GetType(spectrum), GetType(mzXML.scan))>
Public Function rawScans(file As String, Optional env As Environment = Nothing) As Object
Dim type As Type = GetFileType(file)
If type Is Nothing Then
Return Internal.debug.stop({"the given file is not exists or file format not supported!", "file: " & file}, env)
ElseIf type Is GetType(indexedmzML) Then
Return indexedmzML.LoadScans(file).DoCall(AddressOf pipeline.CreateFromPopulator)
Else
Return mzXMLAssembly.XML.LoadScans(file).DoCall(AddressOf pipeline.CreateFromPopulator)
End If
End Function
''' <summary>
''' get polarity data for each ms2 scans
''' </summary>
''' <param name="scans"></param>
''' <param name="env"></param>
''' <returns></returns>
<ExportAPI("polarity")>
<RApiReturn(GetType(Integer))>
Public Function ionMode(scans As Object, Optional env As Environment = Nothing) As Object
Dim polar As New List(Of Integer)
If TypeOf scans Is BioNovoGene.Analytical.MassSpectrometry.Assembly.mzPack Then
Dim ms = DirectCast(scans, BioNovoGene.Analytical.MassSpectrometry.Assembly.mzPack).MS
For Each Ms1 As ScanMS1 In ms
For Each ms2 As ScanMS2 In Ms1.products.SafeQuery
Call polar.Add(ms2.polarity)
Next
Next
ElseIf TypeOf scans Is pipeline Then
Dim scanPip As pipeline = DirectCast(scans, pipeline)
If scanPip.elementType Like GetType(mzXMLAssembly.scan) Then
Dim reader As mzXMLScan = MsDataReader(Of mzXMLAssembly.scan).ScanProvider()
For Each scanVal As mzXMLAssembly.scan In scanPip.populates(Of mzXMLAssembly.scan)(env).Where(Function(s) reader.GetMsLevel(s) = 2)
Call polar.Add(PrecursorType.ParseIonMode(reader.GetPolarity(scanVal)))
Next
ElseIf scanPip.elementType Like GetType(spectrum) Then
Dim reader As mzMLScan = MsDataReader(Of spectrum).ScanProvider()
For Each scanVal As spectrum In scanPip.populates(Of spectrum)(env).Where(Function(s) reader.GetMsLevel(s) = 2)
Call polar.Add(PrecursorType.ParseIonMode(reader.GetPolarity(scanVal)))
Next
Else
Return Message.InCompatibleType(GetType(mzXMLAssembly.scan), scanPip.elementType, env)
End If
Else
Return Message.InCompatibleType(GetType(BioNovoGene.Analytical.MassSpectrometry.Assembly.mzPack), scans.GetType, env)
End If
Return polar.ToArray
End Function
''' <summary>
''' get all ms1 raw scans from the raw files
''' </summary>
''' <param name="raw">
''' the file path of the raw data files.
''' </param>
''' <param name="centroid">
''' the tolerance value of m/z for convert to centroid mode
''' </param>
''' <returns></returns>
<ExportAPI("ms1.scans")>
<RApiReturn(GetType(ms1_scan))>
Public Function getMs1Scans(<RRawVectorArgument>
raw As Object,
Optional centroid As Object = Nothing,
Optional env As Environment = Nothing) As Object
Dim ms1 As New List(Of ms1_scan)
Dim tolerance As Tolerance = Nothing
If Not centroid Is Nothing Then
With getTolerance(centroid, env)
If .GetUnderlyingType Is GetType(Message) Then
Return .TryCast(Of Message)
Else
tolerance = .TryCast(Of Tolerance)
End If
End With
End If
If TypeOf raw Is BioNovoGene.Analytical.MassSpectrometry.Assembly.mzPack Then
ms1.AddRange(DirectCast(raw, BioNovoGene.Analytical.MassSpectrometry.Assembly.mzPack).GetAllScanMs1(tolerance))
ElseIf TypeOf raw Is vector OrElse TypeOf raw Is String() Then
Dim files As String() = CLRVector.asCharacter(raw)
For Each file As String In files
Select Case file.ExtensionSuffix.ToLower
Case "mzxml"
ms1 += mzXMLMs1(file, tolerance)
Case "mzml"
ms1 += mzMLMs1(file, tolerance)
Case Else
Throw New NotImplementedException
End Select
Next
ElseIf TypeOf raw Is pipeline Then
Dim scanPip As pipeline = DirectCast(raw, pipeline)
If scanPip.elementType Like GetType(mzXMLAssembly.scan) Then
Call scanPip.populates(Of mzXMLAssembly.scan)(env) _
.mzXMLMs1(tolerance) _
.IteratesALL _
.DoCall(AddressOf ms1.AddRange)
ElseIf scanPip.elementType Like GetType(spectrum) Then
Call scanPip.populates(Of spectrum)(env) _
.mzMLMs1(tolerance) _
.IteratesALL _
.DoCall(AddressOf ms1.AddRange)
Else
Return Message.InCompatibleType(GetType(mzXMLAssembly.scan), scanPip.elementType, env)
End If
Else
Return Message.InCompatibleType(GetType(BioNovoGene.Analytical.MassSpectrometry.Assembly.mzPack), raw.GetType, env)
End If
Return ms1.ToArray
End Function
Private Function mzXMLMs1(file As String, centroid As Tolerance) As IEnumerable(Of ms1_scan)
Return mzXMLMs1(mzXML.XML _
.LoadScans(file) _
.Where(Function(s)
Return s.msLevel = 1
End Function), centroid).IteratesALL
End Function
<Extension>
Private Iterator Function mzXMLMs1(scans As IEnumerable(Of mzXML.scan), centroid As Tolerance) As IEnumerable(Of ms1_scan())
Dim reader As New mzXMLScan
Dim peakScans As ms2()
Dim rt_sec As Double
For Each scan As mzXML.scan In From item In scans Where Not reader.IsEmpty(item)
' ms1的数据总是使用raw intensity值
peakScans = reader.GetMsMs(scan)
rt_sec = reader.GetScanTime(scan)
If Not centroid Is Nothing Then
peakScans = peakScans.Centroid(centroid, LowAbundanceTrimming.intoCutff).ToArray
End If
Yield peakScans _
.Select(Function(frag)
Return New ms1_scan With {
.intensity = frag.intensity,
.mz = frag.mz,
.scan_time = rt_sec
}
End Function) _
.ToArray
Next
End Function
Private Function mzMLMs1(file As String, centroid As Tolerance) As IEnumerable(Of ms1_scan)
Dim reader As New mzMLScan
Return mzMLMs1(indexedmzML _
.LoadScans(file) _
.Where(Function(s)
Return reader.GetMsLevel(s) = 1
End Function), centroid).IteratesALL
End Function
<Extension>
Private Iterator Function mzMLMs1(scans As IEnumerable(Of spectrum), centroid As Tolerance) As IEnumerable(Of ms1_scan())
Dim reader As New mzMLScan
Dim peakScans As ms2()
Dim rt_sec As Double
For Each scan As spectrum In From item In scans Where Not reader.IsEmpty(item)
peakScans = reader.GetMsMs(scan)
rt_sec = reader.GetScanTime(scan)
If Not centroid Is Nothing Then
peakScans = peakScans.Centroid(centroid, LowAbundanceTrimming.intoCutff).ToArray
End If
Yield peakScans _
.Select(Function(frag)
Return New ms1_scan With {
.intensity = frag.intensity,
.mz = frag.mz,
.scan_time = rt_sec
}
End Function) _
.ToArray
Next
End Function
End Module
|
Imports Model
Imports CommonUtility
''' <summary>
''' 基本情報マスタのアクセスクラスです
''' </summary>
''' <remarks></remarks>
Public Class MessageInfo
Private S_MESSAGEValue As dsS_MESSAGE
''' <summary>
''' S_MESSAGE型として基本情報マスタを返します。
''' </summary>
''' <returns>基本情報マスタ</returns>
''' <remarks></remarks>
Public Function GetS_MESSAGE() As dsS_MESSAGE
Return S_MESSAGEValue
End Function
''' <summary>
''' S_MESSAGE型として基本情報マスタを返します。
''' </summary>
''' <returns>基本情報マスタ</returns>
''' <remarks></remarks>
Public Function Item() As dsS_MESSAGE
Return GetS_MESSAGE()
End Function
Public Sub New()
S_MESSAGEValue = Nothing
Dim resultDataSets As New dsS_MESSAGE
'DAC作成
Using masterAdapter As New dsS_MESSAGETableAdapters.S_MESSAGEViewTableAdapter, _
connection As New System.Data.SqlClient.SqlConnection(CommonUtility.DBUtility.GetConnectionString)
masterAdapter.Connection = connection : DBUtility.SetCommandTimeout(masterAdapter)
masterAdapter.Fill(resultDataSets.S_MESSAGEView)
End Using
S_MESSAGEValue = resultDataSets
End Sub
''' <summary>
''' 基本情報マスタのレコードを返します
''' </summary>
''' <returns>基本情報マスタの1レコード目</returns>
''' <remarks></remarks>
Public Function Record() As dsS_MESSAGE.S_MESSAGEViewRow
If S_MESSAGEValue Is Nothing Then
Throw New ApplicationException("S_MESSAGEが読み込まれていません")
End If
Return S_MESSAGEValue.S_MESSAGEView(0)
End Function
End Class
|
Imports BVSoftware.Bvc5.Core
Imports System.Collections.ObjectModel
Partial Class BVModules_Controls_CreditCardInput
Inherits System.Web.UI.UserControl
Private _ValidateErrors As New Collection(Of String)()
Private _tabIndex As Integer = -1
Public Property CardNumber() As String
Get
Dim result As String = Me.CardNumberField.Text.Trim
If result.StartsWith("*") = False Then
result = Utilities.CreditCardValidator.CleanCardNumber(result)
End If
Return result
End Get
Set(ByVal value As String)
Me.CardNumberField.Text = value
End Set
End Property
Public Property CardHolderName() As String
Get
Return Me.CardholderNameField.Text.Trim
End Get
Set(ByVal value As String)
Me.CardholderNameField.Text = value
End Set
End Property
Public Property SecurityCode() As String
Get
Return Me.CVVField.Text.Trim
End Get
Set(ByVal value As String)
Me.CVVField.Text = value
End Set
End Property
Public Property CardCode() As String
Get
Return Me.CardTypeField.SelectedValue
End Get
Set(ByVal value As String)
If Me.CardTypeField.Items.FindByValue(value) IsNot Nothing Then
Me.CardTypeField.ClearSelection()
Me.CardTypeField.Items.FindByValue(value).Selected = True
End If
End Set
End Property
Public Property ExpirationMonth() As Integer
Get
Return Me.ExpMonthField.SelectedValue
End Get
Set(ByVal value As Integer)
If Me.ExpMonthField.Items.FindByValue(value) IsNot Nothing Then
Me.ExpMonthField.ClearSelection()
Me.ExpMonthField.Items.FindByValue(value).Selected = True
End If
End Set
End Property
Public Property ExpirationYear() As Integer
Get
Return Me.ExpYearField.SelectedValue
End Get
Set(ByVal value As Integer)
If Me.ExpYearField.Items.FindByValue(value) IsNot Nothing Then
Me.ExpYearField.ClearSelection()
Me.ExpYearField.Items.FindByValue(value).Selected = True
End If
End Set
End Property
Public ReadOnly Property ValidateErrors() As Collection(Of String)
Get
Return _ValidateErrors
End Get
End Property
Public Property TabIndex() As Integer
Get
Return _tabIndex
End Get
Set(ByVal value As Integer)
_tabIndex = value
End Set
End Property
Public Sub EnabledValidators()
CardTypeFieldBVRequiredFieldValidator.Enabled = True
CardNumberBVRequiredFieldValidator.Enabled = True
ExpMonthFieldBVRequiredFieldValidator.Enabled = True
ExpYearFieldBVRequiredFieldValidator.Enabled = True
CVVFieldBVRequiredFieldValidator.Enabled = WebAppSettings.PaymentCreditCardRequireCVV
CardholderNameFieldBVRequiredFieldValidator.Enabled = True
End Sub
Public Sub DisableValidators()
CardTypeFieldBVRequiredFieldValidator.Enabled = False
CardNumberBVRequiredFieldValidator.Enabled = False
ExpMonthFieldBVRequiredFieldValidator.Enabled = False
ExpYearFieldBVRequiredFieldValidator.Enabled = False
CVVFieldBVRequiredFieldValidator.Enabled = False
CardholderNameFieldBVRequiredFieldValidator.Enabled = False
End Sub
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
InitializeFields()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If TypeOf Me.Page Is BaseAdminPage Then
Me.cvvdesclink.Visible = False
End If
If TabIndex <> -1 Then
CardTypeField.TabIndex = Me.TabIndex
CardNumberField.TabIndex = Me.TabIndex + 1
ExpMonthField.TabIndex = Me.TabIndex + 2
ExpYearField.TabIndex = Me.TabIndex + 3
CVVField.TabIndex = Me.TabIndex + 4
CardholderNameField.TabIndex = Me.TabIndex + 5
End If
End Sub
Public Sub InitializeFields()
LoadMonths()
LoadYears()
LoadCardTypes()
End Sub
Private Sub LoadYears()
ExpYearField.Items.Clear()
ExpYearField.Items.Add(New ListItem("----", 0))
Dim CurrentYear As Integer = System.DateTime.UtcNow.ToLocalTime.Year
For iTempCounter As Integer = 0 To 15 Step 1
Dim liTemp As New ListItem
liTemp.Text = iTempCounter + CurrentYear
liTemp.Value = iTempCounter + CurrentYear
ExpYearField.Items.Add(liTemp)
liTemp = Nothing
Next
End Sub
Private Sub LoadMonths()
ExpMonthField.Items.Clear()
ExpMonthField.Items.Add(New ListItem("--", 0))
For iTempCounter As Integer = 1 To 12 Step 1
Dim liTemp As New ListItem
liTemp.Text = iTempCounter.ToString()
liTemp.Value = iTempCounter
ExpMonthField.Items.Add(liTemp)
liTemp = Nothing
Next
End Sub
Private Sub LoadCardTypes()
CardTypeField.Items.Clear()
Try
CardTypeField.Items.Add(New ListItem("< Select A Card Type >", 0))
For Each ct As Payment.CreditCardType In Payment.CreditCardType.FindAllActive()
CardTypeField.Items.Add(New ListItem(ct.LongName, ct.Code))
If (ct.LongName.ToUpper() = "SWITCH") OrElse (ct.LongName.ToUpper() = "SOLO") OrElse (ct.LongName.ToUpper() = "MAESTRO / SWITCH") Then
issueNumberRow.Visible = True
End If
Next
Catch Ex As Exception
Throw New ArgumentException("Couldn't Load Card Types: " & Ex.Message)
End Try
End Sub
Public Sub LoadFromPayment(ByVal op As Orders.OrderPayment)
CardCode = op.CreditCardType
ExpirationMonth = op.CreditCardExpMonth
ExpirationYear = op.CreditCardExpYear
CardHolderName = op.CreditCardHolder
If op.CreditCardNumber.Trim.Length >= 4 Then
If WebAppSettings.DisplayFullCreditCardNumber Then
CardNumber = op.CreditCardNumber
Else
CardNumber = "****-****-****-" & op.CreditCardNumber.Substring(op.CreditCardNumber.Length - 4)
End If
End If
If op.CustomPropertyExists("bvsoftware", "issuenumber") Then
IssueNumberTextBox.Text = op.CustomPropertyGet("bvsoftware", "issuenumber")
End If
End Sub
Public Sub CopyToPayment(ByVal op As Orders.OrderPayment)
op.CreditCardExpMonth = ExpirationMonth
op.CreditCardExpYear = ExpirationYear
op.CreditCardHolder = CardHolderName
If CardNumber.StartsWith("*") = False Then
op.CreditCardNumber = CardNumber
End If
op.CreditCardType = CardCode
op.CreditCardSecurityCode = SecurityCode
If IssueNumberTextBox.Text.Trim() <> String.Empty Then
op.CustomPropertySet("bvsoftware", "issuenumber", IssueNumberTextBox.Text)
End If
End Sub
Public Function Validate() As Boolean
_ValidateErrors.Clear()
Dim bRet As Boolean = True
Dim CCVal As New Utilities.CreditCardValidator
Dim testCardNumber As String = ""
If CardNumber.StartsWith("****-****-****-") Then
'If paymentId.Trim.Length > 0 Then
'End If
'For i As Integer = 0 To thisOrder.Payments.Length - 1
' With thisOrder.Payments(i)
' If .PaymentType = BVSoftware.BVC.Interfaces.PaymentRecordType.Information Then
' If .PaymentMethod = BVSoftware.BVC.Interfaces.PaymentMethod.CreditCard Then
' testCardNumber = .CreditCardNumber
' End If
' End If
' End With
'Next
Else
CardNumber = Utilities.CreditCardValidator.CleanCardNumber(CardNumber)
testCardNumber = CardNumber
End If
If CardCode = "0" Then
_ValidateErrors.Add("Please select a card type.")
bRet = False
Else
Dim cardValidated As Boolean = False
cardValidated = CCVal.ValidateCard(testCardNumber, CardCode)
If cardValidated = True Then
bRet = True
Else
For Each message As String In CCVal.ErrorMessages
_ValidateErrors.Add(message)
Next
bRet = False
End If
End If
If ExpirationMonth < 1 Then
_ValidateErrors.Add("Please select an expiration month.")
bRet = False
End If
If ExpirationYear < 1 Then
_ValidateErrors.Add("Please select an expiration year.")
bRet = False
End If
If CardHolderName.Length < 1 Then
_ValidateErrors.Add("Please enter a card holder name.")
bRet = False
End If
If WebAppSettings.PaymentCreditCardRequireCVV = True Then
If SecurityCode.Length < 3 Then
_ValidateErrors.Add("Please enter a security code.")
bRet = False
End If
End If
If _ValidateErrors.Count > 0 Then
bRet = False
End If
Return bRet
End Function
End Class
|
' *********************************************************************************
' Surname, Initials:Kalombo A.K
' Student Number:218095095
' Practical: P2018A-09
' Class name: Fishing season
' *********************************************************************************
Option Strict On
Option Explicit On
Option Infer Off
Public Class frmFishingSeason
'Setting up period and week record structure
Private PeriodIn() As period
Private Structure period
Public name As String
Public nPeriods As Integer
Public nWeeks As Integer
Public Rating As Double
Public Week() As week
Public Index As Integer
End Structure
Private Structure week
Public nFish() As Integer
Public nVisitors As Integer
Public Visitor() As Integer
Public AveFish() As Double
Public TotAveFish As Double
End Structure
'Setting up subruitin that rights to grid
Private Sub WriteGrd(ByVal r As Integer, ByVal c As Integer, ByVal t As String)
grdUj.Row = r
grdUj.Col = c
grdUj.Text = t
End Sub
'Initializing sub routin
Private col, row As Integer
Private Sub btnInit_Click(sender As Object, e As EventArgs) Handles btnInit.Click
Dim A, B As Integer
row = CInt(InputBox("How many periods are there", "Number of periods"))
col = CInt(InputBox("How many weeks are there for all periods", "Number of weeks"))
grdUj.Cols = col + 3
grdUj.Rows = row + 1
For A = 1 To row
WriteGrd(A, 0, "Period " & CStr(A))
Next A
For B = 1 To col
WriteGrd(0, B, "Week " & CStr(B))
Next B
WriteGrd(0, col + 1, "Highest index")
WriteGrd(0, col + 2, "Rating")
grdUj.DebugState = False
End Sub
'Collecting data for Subroutins
Private Sub btnInfo_Click(sender As Object, e As EventArgs) Handles btnInfo.Click
Dim A, B, C As Integer
ReDim PeriodIn(row)
For A = 1 To row
PeriodIn(A).name = InputBox("What is the name of period " & CInt(A), "Name of period")
PeriodIn(A).nWeeks = col
ReDim PeriodIn(A).Week(col)
For B = 1 To PeriodIn(A).nWeeks
PeriodIn(A).Week(B).nVisitors = CInt(InputBox("How many visitors are there in week " & CStr(B), "Number of visitors"))
ReDim PeriodIn(A).Week(B).AveFish(PeriodIn(A).Week(B).nVisitors)
ReDim PeriodIn(A).Week(B).nFish(PeriodIn(A).Week(B).nVisitors)
For C = 1 To PeriodIn(A).Week(B).nVisitors
PeriodIn(A).Week(B).nFish(C) = CInt(InputBox("How many fish did visitor " & CStr(C) & " catch in week " & CStr(B) & "?", "Number of fish caught by visitor"))
PeriodIn(A).Week(B).AveFish(C) = CDbl(InputBox("What is the total average weight of the fish caught by visitor " & CStr(C) & " in week " & CStr(B) & "?", "Total weight of fish"))
Next C
Next B
Next A
End Sub
'Subroutin that calculates the average weight of fish caught by each visitors
Private answer As Double
Private Sub CalcAve(ByVal TotalAve As Double, ByVal TotFish As Integer)
answer = TotalAve / TotFish
End Sub
'Calculating and desplaying average per week
Private Sub btnCalcAve_Click(sender As Object, e As EventArgs) Handles btnCalcAve.Click
Dim A, B, C, TotFish As Integer
Dim TotalAve As Double
For A = 1 To row
For B = 1 To PeriodIn(A).nWeeks
TotalAve = 0
TotFish = 0
For C = 1 To PeriodIn(A).Week(B).nVisitors
TotalAve += PeriodIn(A).Week(B).AveFish(C)
TotFish += PeriodIn(A).Week(B).nFish(C)
Next C
CalcAve(TotalAve, TotFish)
PeriodIn(A).Week(B).TotAveFish = answer
WriteGrd(A, B, Format(answer, "0.00"))
Next B
Next A
End Sub
'Highest average weight index
Private Sub btnIndex_Click(sender As Object, e As EventArgs) Handles btnIndex.Click
Dim A, B, indexnew As Integer
Dim Highest As Double
For A = 1 To row
indexnew = 1
Highest = PeriodIn(A).Week(1).TotAveFish
For B = 2 To PeriodIn(A).nWeeks
If Highest < PeriodIn(A).Week(B).TotAveFish Then
Highest = PeriodIn(A).Week(B).TotAveFish
indexnew += 1
End If
Next B
PeriodIn(A).Index = indexnew
WriteGrd(A, col + 1, CStr(indexnew))
Next A
End Sub
'Sub routin for calculating average
Private Answre As String
Private Sub DetermineRating(ByVal HighestAve As Double)
Select Case HighestAve
Case 0 To 15
Answre = ("A")
Case < 25
Answre = ("B")
Case >= 25
Answre = ("C")
End Select
End Sub
'Calculating Rating per period and desplaying it
'using subroutin Determinerating
Private Sub btnRat_Click(sender As Object, e As EventArgs) Handles btnRat.Click
Dim A, B As Integer
Dim Highest As Double
For A = 1 To row
Highest = PeriodIn(A).Week(1).TotAveFish
For B = 1 To PeriodIn(A).nWeeks
If Highest < PeriodIn(A).Week(B).TotAveFish Then
Highest = PeriodIn(A).Week(B).TotAveFish
End If
DetermineRating(Highest)
PeriodIn(A).Rating = Highest
WriteGrd(A, col + 2, CStr(Answre))
Next B
Next A
'Determining if the rating is a decreasing trend
Dim Decreasing As Boolean
Dim Counter As Integer
Counter = 1
While Counter < col And Decreasing = True
If PeriodIn(Counter).Rating < PeriodIn(Counter + 1).Rating Then
Decreasing = False
End If
Counter += 1
End While
If Decreasing = True Then
txtChangeRat.Text = "It's Decreasing"
End If
If Decreasing = False Then
txtChangeRat.Text = "It's not decreasing"
End If
End Sub
End Class |
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("mPosEngine")>
<Assembly: AssemblyDescription("Mobile Point of Sale Backend Service")>
<Assembly: AssemblyCompany("Alex Hofmann")>
<Assembly: AssemblyProduct("mPosEngine")>
<Assembly: AssemblyCopyright("Copyright © Alex Hofmann 2014")>
<Assembly: AssemblyTrademark("")>
<Assembly: log4net.Config.XmlConfigurator(Watch:=False)>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("8f07a1de-ed3c-481b-b312-f627089d418f")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.1.4.1")>
<Assembly: AssemblyFileVersion("1.1.4.1")>
'v1042 isDefaultCardSaleProduct
'v1044 Redondea los montos que van a la DB.
'v1046 Payitem es un valueobject, l
'v1047 Implementa InvoiceNumber
'v1050 Agrega AuthorizePayment
'v1060 Agrega GetProductPages
'v1062 Arregla lo del Tax
'v1063 Arregla lo del Tax otra vez (ver services 1.0.3.3)
'v1064 services v1.0.3.4
'v1065 PlaycardBase v1.1.0.0
'v1070 Usa el PlaycardBase que permite tener prefixletter/number alfanumericos ambos
'v1071 'Services v1.0.3.7 Usa Playcardbase 1.1.4.0
'v1072
'Core 'v1.0.2.3 Mejor logueo en la parte del calculo de taxes
'v1080 Core 'v1.0.3.0 Maneja tax para que funcionen tanto sales tax como VATs
'v1081 Core 'v1.0.4.0 Cambios en la forma de calcular subtotal/taxes (Issue 4964)
'v1082 Core 'v1.0.4.1 Corrije error de la anterior que devolvia subtotal1 en 0 (Issue 4832)
'v1083 Data 'v1.0.0.4 No estaba implementado el "ChangeCardStatus", por lo cual productos que ponene en VIP la tarjeta no lo estaban haciendo
'v1090 Nuevo Playcardbase/PlaycardStatusEngine
'v1091 Core v1.0.5.0 -> Usa Counterovement.GetConvertedAmount en lugar de .Amount
'v1092 CheckDevice devuelve el computerId (de datStoreComputers)
' 1.1.0.0 nHibernate 5, implementación de descuentos y nuevo método GetDiscountsFromProducts
' 1.1.0.1 Try-catch en New Service
' 1.1.0.2 Se cambia el método GetDiscountsFromProducts para calcular en base a cantidades
' 1.1.0.3 Se envía mPosTransactionId como paymentId en CommitTransaction de ExternalSystem
' 1.1.0.4 Agrego ThumbUrl a AdminFunctions
' 1.1.0.5 Actualizo referencias
' 1.1.1.0 Agrego funcionalidad para facturación fiscal
' 1.1.2.0 Se agregan las funciones de treasury Cash Pull, Pay Out y Get Balance
' 1.1.2.1 Cash pull y pay out ahora devuelven SuccessResponse
' 1.1.2.2 Agrego validación contra valid.dat
' 1.1.2.3 Cambio en el response de GetBalance
' 1.1.2.4 Tomo el prefijo desde [International] en vez de [Taskman]
' 1.1.2.5 Bug al leer valid.dat
' 1.1.3.0 CreditCard support
' 1.1.3.1 Correcciones a CreditCard. Se agregan los métodos ReturnCreditCardTransaction, StartCreditCardAuthorization
' 1.1.3.2 Se cambia la respuesta de StartCreditCardAuthorizer
' 1.1.3.3 Agrego CardType y CreditCardNumber a GetTransactionStatus
' 1.1.3.4 Agrego InvoiceId en ReturnCreditCardTransaction
' 1.1.3.5 CardEngine 1.0.8.0 con PassportEngine 4.2.1.1
' 1.1.3.6 Se cambió referencias de todo
' 1.1.3.8 Refund voucher support
' 1.1.3.9 Nuevo endpoint: GetInvoiceImage
' 1.1.4.0 Agrego PlayAmountToPromote en AnalyzeCard
' 1.1.4.1 Fix en CommitTransaction |
Imports System.Collections.Generic
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Data
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Imaging
Imports System.Windows.Navigation
Imports System.Windows.Shapes
Imports devDept.Eyeshot
Imports devDept.Graphics
Imports devDept.Eyeshot.Entities
Imports devDept.Geometry
Imports System.Windows.Controls.Primitives
Imports devDept.Eyeshot.Labels
Imports Font = System.Drawing.Font
Imports devDept.Eyeshot.Translators
''' <summary>
''' Interaction logic for MainWindow.xaml
''' </summary>
Partial Public Class MainWindow
Private Const Textures As String = "../../../../../../dataset/Assets/Textures/"
Const mapleMatName As String = "Maple"
Const cherryMatName As String = "Cherry"
Const plasticMatName As String = "Plastic"
Private Enum materialEnum
Maple = 0
Cherry = 1
End Enum
Private currentFrameMaterial As materialEnum
Public Sub New()
InitializeComponent()
' model1.Unlock("") ' For more details see 'Product Activation' topic in the documentation.
End Sub
Protected Overrides Sub OnContentRendered(e As EventArgs)
model1.GetGrid().Visible = False
model1.Backface.ColorMethod = backfaceColorMethodType.Cull
currentFrameMaterial = materialEnum.Maple
Dim mapleMat As New Material(mapleMatName, System.Drawing.Color.FromArgb(100, 100, 100), System.Drawing.Color.White, 1, new Bitmap(Textures + "Maple.jpg"))
mapleMat.Density = 0.7 * 0.001
' set maple density
model1.Materials.Add(mapleMat)
Dim cherryMat As New Material(cherryMatName, System.Drawing.Color.FromArgb(100, 100, 100), System.Drawing.Color.White, 1, new Bitmap(Textures + "Cherry.jpg"))
cherryMat.Density = 0.8 * 0.001
' set cherry density
model1.Materials.Add(cherryMat)
model1.Layers.Add(plasticMatName, System.Drawing.Color.GreenYellow)
Dim plasticLayerMat As New Material(plasticMatName, System.Drawing.Color.GreenYellow)
model1.Layers(plasticMatName).MaterialName = plasticMatName
plasticLayerMat.Density = 1.4 * 0.001
' set plastic density
model1.Materials.Add(plasticLayerMat)
RebuildChair()
' sets trimetric view
model1.SetView(viewType.Trimetric)
' fits the model in the viewport
model1.ZoomFit()
' refresh the viewport
model1.Invalidate()
MyBase.OnContentRendered(e)
End Sub
Private Sub seatColor_Click(sender As Object, e As RoutedEventArgs)
Dim rb As ToggleButton = DirectCast(sender, ToggleButton)
model1.Layers(plasticMatName).Color = RenderContextUtility.ConvertColor(rb.Background)
' affects edges color
model1.Materials(plasticMatName).Diffuse = RenderContextUtility.ConvertColor(rb.Background)
' affects faces color
model1.Invalidate()
End Sub
Private Sub woodEssence_Click(sender As Object, e As RoutedEventArgs)
If mapleEssenceRadioButton.IsChecked.HasValue AndAlso mapleEssenceRadioButton.IsChecked.Value Then
currentFrameMaterial = materialEnum.Maple
ElseIf cherryEssenceRadioButton.IsChecked.HasValue AndAlso cherryEssenceRadioButton.IsChecked.Value Then
currentFrameMaterial = materialEnum.Cherry
End If
RebuildChair()
model1.Invalidate()
End Sub
Private Sub sizeTrackBar_ValueChanged(sender As Object, e As RoutedPropertyChangedEventArgs(Of Double))
If model1 Is Nothing Then
Return
End If
model1.Entities.Clear()
RebuildChair()
model1.Invalidate()
End Sub
Private Sub exportStlButton_Click(sender As Object, e As RoutedEventArgs)
Dim stlFile As String = "chair.stl"
Dim ws As New WriteSTL(New WriteParams(model1), stlFile, True)
ws.DoWork()
Dim fullPath As String = [String].Format("{0}\{1}", System.Environment.CurrentDirectory, stlFile)
MessageBox.Show([String].Format("File saved in {0}", fullPath))
End Sub
Private Sub exportObjButton_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim objFile As String = "chair.obj"
Dim ws As New WriteOBJ(New WriteParamsWithMaterials(model1), objFile)
ws.DoWork()
Dim fullPath As String = [String].Format("{0}\{1}", System.Environment.CurrentDirectory, objFile)
MessageBox.Show([String].Format("File saved in {0}", fullPath))
End Sub
Private Sub RebuildChair()
Dim currentMatName As String = If((currentFrameMaterial = materialEnum.Cherry), cherryMatName, mapleMatName)
model1.Entities.Clear()
model1.Labels.Clear()
Dim legDepth As Double = 3
Dim legWidth As Double = 3
Dim legHeight As Double = 56.5
Dim seatDepth As Double = 29
Dim seatWidth As Double = sizeTrackBar.Value
Dim seatHeight As Double = 1.6
Dim seatY As Double = 27.4
'
' Build the legs
'
Dim leg1 As Mesh = MakeBox(legWidth, legDepth, legHeight)
Dim leg4 As Mesh = DirectCast(leg1.Clone(), Mesh)
Dim leg2 As Mesh = MakeBox(legWidth, legDepth, seatY)
Dim leg3 As Mesh = DirectCast(leg2.Clone(), Mesh)
leg2.Translate(seatDepth - legDepth, 0, 0)
leg3.Translate(seatDepth - legDepth, seatWidth - legWidth, 0)
leg4.Translate(0, seatWidth - legWidth, 0)
AddEntityWithMaterial(leg1, currentMatName)
AddEntityWithMaterial(leg2, currentMatName)
AddEntityWithMaterial(leg3, currentMatName)
AddEntityWithMaterial(leg4, currentMatName)
'
' Build the seat
'
Dim dx As Double = 0.3
Dim dy As Double = 0.2
Dim delta As Double = 0.1
Dim seatPartDepth As Double = 4.5
Dim seatPartOffset As Double = 0.5
Dim seatFirstPartPoints As Point3D() = {New Point3D(legDepth + delta, 0, 0), New Point3D(seatPartDepth, 0, 0), New Point3D(seatPartDepth, seatWidth, 0), New Point3D(legDepth + delta, seatWidth, 0), New Point3D(legDepth + delta, seatWidth - legWidth + dy, 0), New Point3D(-dx, seatWidth - legWidth, 0), _
New Point3D(-dx, legWidth, 0), New Point3D(legDepth + delta, legWidth + dy, 0), New Point3D(legDepth + delta, 0, 0)}
Dim seatFirstPart As New Entities.Region(new LinearPath(seatFirstPartPoints))
Dim seatPart0 As Mesh = seatFirstPart.ExtrudeAsMesh(New Vector3D(0, 0, seatHeight), 0.01, Mesh.natureType.Smooth)
seatPart0.Translate(0, -dy, seatY)
Dim seatPart1 As Mesh = MakeBox(seatWidth + 2 * dx, seatPartDepth, seatHeight)
seatPart1.Translate(seatPartDepth + seatPartOffset, -dy, seatY)
Dim seatPart2 As Mesh = DirectCast(seatPart1.Clone(), Mesh)
seatPart2.Translate(seatPartDepth + seatPartOffset, 0, 0)
Dim seatPart3 As Mesh = DirectCast(seatPart2.Clone(), Mesh)
seatPart3.Translate(seatPartDepth + seatPartOffset, 0, 0)
Dim seatPart4 As Mesh = DirectCast(seatPart3.Clone(), Mesh)
seatPart4.Translate(seatPartDepth + seatPartOffset, 0, 0)
Dim seatPart5 As Mesh = DirectCast(seatPart4.Clone(), Mesh)
seatPart5.Translate(seatPartDepth + seatPartOffset, 0, 0)
model1.Entities.Add(seatPart0, plasticMatName)
model1.Entities.Add(seatPart1, plasticMatName)
model1.Entities.Add(seatPart2, plasticMatName)
model1.Entities.Add(seatPart3, plasticMatName)
model1.Entities.Add(seatPart4, plasticMatName)
model1.Entities.Add(seatPart5, plasticMatName)
'
' Build the bars under the seat
'
Dim underSeatXBarWidth As Double = legWidth * 0.8
Dim underSeatXBarDepth As Double = seatDepth - 2 * legDepth
Dim underSeatXBarHeight As Double = 5.0
Dim underSeatYBarWidth As Double = seatWidth - 2 * legWidth
Dim underSeatYBarDepth As Double = legDepth * 0.8
Dim underSeatYBarHeight As Double = underSeatXBarHeight
Dim barUnderSeatLeft As Mesh = MakeBox(underSeatXBarWidth, underSeatXBarDepth, underSeatXBarHeight)
barUnderSeatLeft.Translate(legDepth, (legWidth - underSeatXBarWidth) / 2, seatY - underSeatXBarHeight)
Dim barUnderSeatRight As Mesh = DirectCast(barUnderSeatLeft.Clone(), Mesh)
barUnderSeatRight.Translate(0, seatWidth - legWidth, 0)
Dim barUnderSeatBack As Mesh = MakeBox(seatWidth - 2 * legWidth, legDepth * 0.8, underSeatYBarHeight)
barUnderSeatBack.Translate((legDepth - underSeatYBarDepth) / 2, legWidth, seatY - underSeatYBarHeight)
Dim barUnderSeatFront As Mesh = DirectCast(barUnderSeatBack.Clone(), Mesh)
barUnderSeatFront.Translate(seatDepth - legDepth, 0, 0)
AddEntityWithMaterial(barUnderSeatLeft, currentMatName)
AddEntityWithMaterial(barUnderSeatRight, currentMatName)
AddEntityWithMaterial(barUnderSeatFront, currentMatName)
AddEntityWithMaterial(barUnderSeatBack, currentMatName)
'
' Build the two cylinders on the sides
'
Dim CylinderRadius As Double = legWidth / 3
Dim cylinderY As Double = 14.5
Dim leftCylinder As Mesh = MakeCylinder(CylinderRadius, seatDepth - 2 * legDepth, 16)
leftCylinder.ApplyMaterial(currentMatName, textureMappingType.Cylindrical, 0.25, 1)
leftCylinder.Rotate(Math.PI / 2, New Vector3D(0, 1, 0))
leftCylinder.Translate(legDepth, legWidth / 2, cylinderY)
model1.Entities.Add(leftCylinder)
Dim rightCylinder As Mesh = DirectCast(leftCylinder.Clone(), Mesh)
rightCylinder.Translate(0, seatWidth - legWidth, 0)
model1.Entities.Add(rightCylinder)
'
' Build the chair back
'
Dim chairBackHorizHeight As Double = 4
Dim chairBackHorizDepth As Double = 2
Dim horizHeight1 As Double = seatY + seatHeight + 7
Dim chairBackHorizontal1 As Mesh = MakeBox(seatWidth - 2 * legWidth, chairBackHorizDepth, chairBackHorizHeight)
chairBackHorizontal1.Translate((legDepth - chairBackHorizDepth) / 2.0, legWidth, horizHeight1)
Dim cylinderHeight As Double = 12
Dim horizHeight2 As Double = cylinderHeight + chairBackHorizHeight
Dim chairBackHorizontal2 As Mesh = DirectCast(chairBackHorizontal1.Clone(), Mesh)
chairBackHorizontal2.Translate(0, 0, horizHeight2)
AddEntityWithMaterial(chairBackHorizontal1, currentMatName)
AddEntityWithMaterial(chairBackHorizontal2, currentMatName)
Dim chairBackCylinderRadius As Double = chairBackHorizDepth / 4.0
Dim chairBackCylinderHeight As Double = horizHeight2 - chairBackHorizHeight
Dim chairBackCylinder As Mesh = MakeCylinder(chairBackCylinderRadius, chairBackCylinderHeight, 16)
chairBackCylinder.Translate(legDepth / 2.0, legWidth, horizHeight1 + chairBackHorizHeight)
Dim chairBackWidth As Double = seatWidth - 2 * legWidth
Dim cylinderOffset As Double = 7
Dim nCylinders As Integer = CInt(chairBackWidth / cylinderOffset)
Dim offset As Double = (chairBackWidth - (nCylinders + 1) * cylinderOffset) / 2.0
offset += cylinderOffset
Dim i As Integer = 0
While i < nCylinders
Dim cyl As Mesh = DirectCast(chairBackCylinder.Clone(), Mesh)
cyl.ApplyMaterial(currentMatName, textureMappingType.Cylindrical, 0.25, 1)
cyl.Translate(0, offset, 0)
model1.Entities.Add(cyl)
i += 1
offset += cylinderOffset
End While
'
' Add the linear dimension
'
Dim dimCorner As New Point3D(0, 0, legHeight)
Dim myPlane As Plane = Plane.YZ
myPlane.Origin = dimCorner
Dim ad As New LinearDim(myPlane, New Point3D(0, 0, legHeight + 1), New Point3D(0, seatWidth, legHeight + 1), New Point3D(seatDepth + 10, seatWidth / 2, legHeight + 10), 3)
ad.TextSuffix = " cm"
model1.Entities.Add(ad)
model1.Entities.UpdateBoundingBox()
'
' Update extents
'
widthTextBox.Text = model1.Entities.BoxSize.X.ToString("f2") + " cm"
depthTextBox.Text = model1.Entities.BoxSize.Y.ToString("f2") + " cm"
heightTextBox.Text = model1.Entities.BoxSize.Z.ToString("f2") + " cm"
'
' Update weight
'
Dim totalWeight As Double = CalcWeight()
weightTextBox.Text = totalWeight.ToString("f2") + " kg"
'
' Product ID label
'
Dim prodIdLabel As devDept.Eyeshot.Labels.LeaderAndText = New LeaderAndText(seatDepth / 2, seatWidth, 25, "Product ID goes here", New Font("Tahoma", 8.25F), System.Drawing.Color.Black, _
New Vector2D(20, 0))
model1.Labels.Add(prodIdLabel)
End Sub
Private Function CalcWeight() As Double
Dim totalWeight As Double = 0
For Each ent As Entity In model1.Entities
' Volume() method is defined in the IFace interface
If TypeOf ent Is Mesh Then
Dim mesh As Mesh = DirectCast(ent, Mesh)
Dim mp As New VolumeProperties(mesh.Vertices, mesh.Triangles)
If ent.LayerName = plasticMatName Then
' Gets plastic layer material density
totalWeight += model1.Materials(plasticMatName).Density * mp.Volume
Else
If TypeOf ent Is Mesh Then
Dim m As Mesh = DirectCast(ent, Mesh)
Dim mat As Material = model1.Materials(ent.MaterialName)
totalWeight += mat.Density * mp.Volume
End If
End If
End If
Next
Return totalWeight
End Function
Private Function MakeBox(Width As Double, Depth As Double, height As Double) As Mesh
Return Mesh.CreateBox(Depth, Width, height, Mesh.natureType.Smooth)
End Function
Private Function MakeCylinder(radius As Double, height As Double, slices As Integer) As Mesh
Return Mesh.CreateCylinder(radius, height, slices, Mesh.natureType.Smooth)
End Function
Private Sub AddEntityWithMaterial(ByRef m As Mesh, matName As String)
m.ApplyMaterial(matName, textureMappingType.Cubic, 1, 1)
model1.Entities.Add(m)
End Sub
End Class
|
Imports System.Collections.ObjectModel
Imports System.Windows
Imports System.Windows.Forms
Imports System.Windows.Input
Imports BAWGUI.Core
Imports BAWGUI.Core.Models
Imports BAWGUI.ReadConfigXml
Imports BAWGUI.SignalManagement.ViewModels
Imports BAWGUI.Utilities
Imports Microsoft.WindowsAPICodePack.Dialogs
Imports DissipationEnergyFlow
Imports DissipationEnergyFlow.ViewModels
Imports BAWGUI.CoordinateMapping.ViewModels
Namespace ViewModels
Public Class DetectorConfig
Inherits ViewModelBase
Public Sub New()
_detectorList = New ObservableCollection(Of DetectorBase)
_dataWriterDetectorList = New ObservableCollection(Of DetectorBase)
_alarmingList = New ObservableCollection(Of AlarmingDetectorBase)
_model = New DetectorConfigModel()
_resultUpdateIntervalVisibility = Visibility.Collapsed
_detectorNameList = New List(Of String) From {"Periodogram Forced Oscillation Detector",
"Spectral Coherence Forced Oscillation Detector",
"Ringdown Detector",
"Out-of-Range Detector",
"Wind Ramp Detector",
"Mode Meter Tool",
"Dissipation Energy Flow Detector"}
_alarmingDetectorNameList = New List(Of String) From {"Periodogram Forced Oscillation Detector",
"Spectral Coherence Forced Oscillation Detector",
"Ringdown Detector"}
'_addDataWriterDetector = New DelegateCommand(AddressOf _addADataWriterDetector, AddressOf CanExecute)
_signalsMgr = SignalManager.Instance
_browseSavePath = New DelegateCommand(AddressOf _openSavePath, AddressOf CanExecute)
_autoEventExporter = New AutoEventExportViewModel
End Sub
Public Sub New(detectorConfigure As ReadConfigXml.DetectorConfigModel, signalsMgr As SignalManager)
Me.New
Me._model = detectorConfigure
Dim newDetectorList = New ObservableCollection(Of DetectorBase)
Dim newDataWriterDetectorList = New ObservableCollection(Of DetectorBase)
For Each detector In _model.DetectorList
Select Case detector.Name
Case "Out-Of-Range Detector"
newDetectorList.Add(New OutOfRangeFrequencyDetector(detector, signalsMgr))
Case "Ringdown Detector"
newDetectorList.Add(New RingdownDetector(detector, signalsMgr))
Case "Wind Ramp Detector"
newDetectorList.Add(New WindRampDetector(detector, signalsMgr))
Case "Periodogram Forced Oscillation Detector"
newDetectorList.Add(New PeriodogramDetector(detector, signalsMgr))
ResultUpdateIntervalVisibility = Visibility.Visible
Case "Spectral Coherence Forced Oscillation Detector"
newDetectorList.Add(New SpectralCoherenceDetector(detector, signalsMgr))
ResultUpdateIntervalVisibility = Visibility.Visible
Case "Data Writer"
newDataWriterDetectorList.Add(New DataWriterDetectorViewModel(detector, signalsMgr))
Case "Dissipation Energy Flow Detector"
newDetectorList.Add(New DEFDetectorViewModel(detector, signalsMgr))
Case Else
Throw New Exception("Unknown element found in DetectorConfig in config file.")
End Select
Next
DetectorList = newDetectorList
DataWriterDetectorList = newDataWriterDetectorList
Dim newAlarmingList = New ObservableCollection(Of AlarmingDetectorBase)
For Each alarm In _model.AlarmingList
Select Case alarm.Name
Case "Spectral Coherence Forced Oscillation Detector"
newAlarmingList.Add(New AlarmingSpectralCoherence(alarm, signalsMgr))
Case "Periodogram Forced Oscillation Detector"
newAlarmingList.Add(New AlarmingPeriodogram(alarm, signalsMgr))
Case "Ringdown Detector"
newAlarmingList.Add(New AlarmingRingdown(alarm, signalsMgr))
Case Else
Throw New Exception("Error! Unknown alarming detector elements found in config file.")
End Select
Next
AlarmingList = newAlarmingList
_signalsMgr = signalsMgr
AutoEventExporter = New AutoEventExportViewModel(_model.AutoEventExporter)
End Sub
Private _signalsMgr As SignalManager
Private _model As DetectorConfigModel
Public Property Model As DetectorConfigModel
Get
Return _model
End Get
Set(ByVal value As DetectorConfigModel)
_model = value
OnPropertyChanged()
End Set
End Property
Private _eventPath As String
Public Property EventPath As String
Get
Return _model.EventPath
End Get
Set(ByVal value As String)
_model.EventPath = value
OnPropertyChanged()
End Set
End Property
Private _resultUpdateInterval As String
Public Property ResultUpdateInterval As String
Get
Return _model.ResultUpdateInterval
End Get
Set(ByVal value As String)
_model.ResultUpdateInterval = value
OnPropertyChanged()
End Set
End Property
Private _detectorList As ObservableCollection(Of DetectorBase)
Public Property DetectorList As ObservableCollection(Of DetectorBase)
Get
Return _detectorList
End Get
Set(ByVal value As ObservableCollection(Of DetectorBase))
_detectorList = value
OnPropertyChanged()
End Set
End Property
Private _dataWriterDetectorList As ObservableCollection(Of DetectorBase)
Public Property DataWriterDetectorList As ObservableCollection(Of DetectorBase)
Get
Return _dataWriterDetectorList
End Get
Set(ByVal value As ObservableCollection(Of DetectorBase))
_dataWriterDetectorList = value
OnPropertyChanged()
End Set
End Property
Private _alarmingList As ObservableCollection(Of AlarmingDetectorBase)
Public Property AlarmingList As ObservableCollection(Of AlarmingDetectorBase)
Get
Return _alarmingList
End Get
Set(ByVal value As ObservableCollection(Of AlarmingDetectorBase))
_alarmingList = value
OnPropertyChanged()
End Set
End Property
Private _detectorNameList As List(Of String)
Public Property DetectorNameList As List(Of String)
Get
Return _detectorNameList
End Get
Set(ByVal value As List(Of String))
_detectorNameList = value
OnPropertyChanged()
End Set
End Property
Private _alarmingDetectorNameList As List(Of String)
Public Property AlarmingDetectorNameList As List(Of String)
Get
Return _alarmingDetectorNameList
End Get
Set(ByVal value As List(Of String))
_alarmingDetectorNameList = value
OnPropertyChanged()
End Set
End Property
Private _resultUpdateIntervalVisibility As Visibility
Public Property ResultUpdateIntervalVisibility As Visibility
Get
Return _resultUpdateIntervalVisibility
End Get
Set(ByVal value As Visibility)
_resultUpdateIntervalVisibility = value
OnPropertyChanged()
End Set
End Property
'Private _addDataWriterDetector As ICommand
'Public Property AddDataWriterDetector As ICommand
' Get
' Return _addDataWriterDetector
' End Get
' Set(value As ICommand)
' _addDataWriterDetector = value
' End Set
'End Property
'Private Sub _addADataWriterDetector(obj As Object)
' Dim newDetector = New DataWriterDetectorViewModel
' newDetector.IsExpanded = True
' newDetector.ThisStepInputsAsSignalHerachyByType.SignalSignature.SignalName = "Detector " & (_signalsMgr.GroupedSignalByDataWriterDetectorInput.Count + 1).ToString & " " & newDetector.Name
' _signalsMgr.GroupedSignalByDataWriterDetectorInput.Add(newDetector.ThisStepInputsAsSignalHerachyByType)
' DataWriterDetectorList.Add(newDetector)
'End Sub
Private _lastSavePath As String
Private _browseSavePath As ICommand
Public Property BrowseSavePath As ICommand
Get
Return _browseSavePath
End Get
Set(ByVal value As ICommand)
_browseSavePath = value
End Set
End Property
Private Sub _openSavePath(obj As Object)
'Dim openDirectoryDialog As New FolderBrowserDialog()
'openDirectoryDialog.Description = "Select the Save Path"
'If _lastSavePath Is Nothing Then
' openDirectoryDialog.SelectedPath = Environment.CurrentDirectory
'Else
' openDirectoryDialog.SelectedPath = _lastSavePath
'End If
'openDirectoryDialog.ShowNewFolderButton = True
'If (openDirectoryDialog.ShowDialog = DialogResult.OK) Then
' _lastSavePath = openDirectoryDialog.SelectedPath
' obj.SavePath = openDirectoryDialog.SelectedPath
'End If
Dim openDirectoryDialog As New CommonOpenFileDialog
openDirectoryDialog.Title = "Select the Save Path"
openDirectoryDialog.IsFolderPicker = True
openDirectoryDialog.RestoreDirectory = True
If _lastSavePath Is Nothing Then
openDirectoryDialog.InitialDirectory = Environment.CurrentDirectory
Else
openDirectoryDialog.InitialDirectory = _lastSavePath
End If
openDirectoryDialog.AddToMostRecentlyUsedList = True
openDirectoryDialog.AllowNonFileSystemItems = False
openDirectoryDialog.DefaultDirectory = Environment.CurrentDirectory
openDirectoryDialog.EnsureFileExists = True
openDirectoryDialog.EnsurePathExists = True
openDirectoryDialog.EnsureReadOnly = False
openDirectoryDialog.EnsureValidNames = True
openDirectoryDialog.Multiselect = False
openDirectoryDialog.ShowPlacesList = True
If openDirectoryDialog.ShowDialog = CommonFileDialogResult.Ok Then
_lastSavePath = openDirectoryDialog.FileName
obj.SavePath = openDirectoryDialog.FileName
End If
End Sub
Private _autoEventExporter As AutoEventExportViewModel
Public Property AutoEventExporter As AutoEventExportViewModel
Get
Return _autoEventExporter
End Get
Set(ByVal value As AutoEventExportViewModel)
_autoEventExporter = value
OnPropertyChanged()
End Set
End Property
End Class
Public Class PeriodogramDetector
Inherits DetectorBase
Public Sub New()
_pfa = "0.01"
InputChannels = New ObservableCollection(Of SignalSignatureViewModel)
ThisStepInputsAsSignalHerachyByType = New SignalTypeHierachy(New SignalSignatureViewModel)
_model = New PeriodogramDetectorModel()
IsExpanded = False
_analysisLength = 600
_windowType = DetectorWindowType.hann
_windowLength = 200
_windowOverlap = 100
_pfa = "0.001"
_frequencyMin = "0.1"
_frequencyMax = "15"
_frequencyTolerance = "0.05"
End Sub
Public Sub New(detector As PeriodogramDetectorModel, signalsMgr As SignalManager)
Me.New
Me._model = detector
StepCounter = signalsMgr.GroupedSignalByDetectorInput.Count + 1
ThisStepInputsAsSignalHerachyByType.SignalSignature.SignalName = "Detector " & (signalsMgr.GroupedSignalByDetectorInput.Count + 1).ToString & " " & Name
Try
InputChannels = signalsMgr.FindSignals(detector.PMUElementList)
Catch ex As Exception
Throw New Exception("Error finding signal in step: " & Name)
End Try
For Each signal In InputChannels
signalsMgr.MappingSignals.Add(signal)
Next
Try
ThisStepInputsAsSignalHerachyByType.SignalList = signalsMgr.SortSignalByType(InputChannels)
Catch ex As Exception
Throw New Exception("Error sorting output signals by PMU in step: " & Name)
End Try
signalsMgr.GroupedSignalByDetectorInput.Add(ThisStepInputsAsSignalHerachyByType)
End Sub
Public Overrides Function CheckStepIsComplete() As Boolean
Return InputChannels.Count > 0
End Function
Private _model As PeriodogramDetectorModel
Public Property Model As PeriodogramDetectorModel
Get
Return _model
End Get
Set(ByVal value As PeriodogramDetectorModel)
_model = value
OnPropertyChanged()
End Set
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _model.Name
End Get
End Property
Private _mode As DetectorModeType
Public Property Mode As DetectorModeType
Get
Return _model.Mode
End Get
Set(ByVal value As DetectorModeType)
_model.Mode = value
OnPropertyChanged()
End Set
End Property
Private _analysisLength As Integer
Public Property AnalysisLength As Integer
Get
Return _model.AnalysisLength
End Get
Set(ByVal value As Integer)
_model.AnalysisLength = value
WindowLength = Math.Floor(value / 3)
OnPropertyChanged()
End Set
End Property
Private _windowType As DetectorWindowType
Public Property WindowType As DetectorWindowType
Get
Return _model.WindowType
End Get
Set(ByVal value As DetectorWindowType)
_model.WindowType = value
OnPropertyChanged()
End Set
End Property
Private _frequencyInterval As String
Public Property FrequencyInterval As String
Get
Return _model.FrequencyInterval
End Get
Set(ByVal value As String)
_model.FrequencyInterval = value
OnPropertyChanged()
End Set
End Property
Private _windowLength As Integer
Public Property WindowLength As Integer
Get
Return _model.WindowLength
End Get
Set(ByVal value As Integer)
_model.WindowLength = value
WindowOverlap = Math.Floor(value / 2)
OnPropertyChanged()
End Set
End Property
Private _windowOverlap As Integer
Public Property WindowOverlap As Integer
Get
Return _model.WindowOverlap
End Get
Set(ByVal value As Integer)
_model.WindowOverlap = value
OnPropertyChanged()
End Set
End Property
Private _medianFilterFrequencyWidth As String
Public Property MedianFilterFrequencyWidth As String
Get
Return _model.MedianFilterFrequencyWidth
End Get
Set(ByVal value As String)
_model.MedianFilterFrequencyWidth = value
OnPropertyChanged()
End Set
End Property
Private _pfa As String
Public Property Pfa As String
Get
Return _model.Pfa
End Get
Set(ByVal value As String)
_model.Pfa = value
OnPropertyChanged()
End Set
End Property
Private _frequencyMin As String
Public Property FrequencyMin As String
Get
Return _model.FrequencyMin
End Get
Set(ByVal value As String)
_model.FrequencyMin = value
OnPropertyChanged()
End Set
End Property
Private _frequencyMax As String
Public Property FrequencyMax As String
Get
Return _model.FrequencyMax
End Get
Set(ByVal value As String)
_model.FrequencyMax = value
OnPropertyChanged()
End Set
End Property
Private _frequencyTolerance As String
Public Property FrequencyTolerance As String
Get
Return _model.FrequencyTolerance
End Get
Set(ByVal value As String)
_model.FrequencyTolerance = value
OnPropertyChanged()
End Set
End Property
Public Property CalcDEF As Boolean
Get
Return _model.CalcDEF
End Get
Set(ByVal value As Boolean)
_model.CalcDEF = value
OnPropertyChanged()
End Set
End Property
End Class
Public Class SpectralCoherenceDetector
Inherits DetectorBase
Public Sub New()
_model = New SpectralCoherenceDetectorModel
_analysisLength = 60
_delay = 10
_numberDelays = 2
_thresholdScale = 3
_windowType = DetectorWindowType.hann
_windowLength = 12
_windowOverlap = 6
_frequencyMin = "0.1"
_frequencyMax = "15"
_frequencyTolerance = "0.05"
InputChannels = New ObservableCollection(Of SignalSignatureViewModel)
ThisStepInputsAsSignalHerachyByType = New SignalTypeHierachy(New SignalSignatureViewModel)
IsExpanded = False
'_windowLength = _analysisLength / 5
End Sub
Public Sub New(detector As SpectralCoherenceDetectorModel, signalsMgr As SignalManager)
Me.New
Me._model = detector
StepCounter = signalsMgr.GroupedSignalByDetectorInput.Count + 1
ThisStepInputsAsSignalHerachyByType.SignalSignature.SignalName = "Detector " & (signalsMgr.GroupedSignalByDetectorInput.Count + 1).ToString & " " & Name
Try
InputChannels = signalsMgr.FindSignals(detector.PMUElementList)
Catch ex As Exception
Throw New Exception("Error finding signal in step: " & Name)
End Try
For Each signal In InputChannels
signalsMgr.MappingSignals.Add(signal)
Next
Try
ThisStepInputsAsSignalHerachyByType.SignalList = signalsMgr.SortSignalByType(InputChannels)
Catch ex As Exception
Throw New Exception("Error sorting output signals by PMU in step: " & Name)
End Try
signalsMgr.GroupedSignalByDetectorInput.Add(ThisStepInputsAsSignalHerachyByType)
End Sub
Private _model As SpectralCoherenceDetectorModel
Public Property Model As SpectralCoherenceDetectorModel
Get
Return _model
End Get
Set(ByVal value As SpectralCoherenceDetectorModel)
_model = value
OnPropertyChanged()
End Set
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _model.Name
End Get
End Property
Private _mode As DetectorModeType
Public Property Mode As DetectorModeType
Get
Return _model.Mode
End Get
Set(ByVal value As DetectorModeType)
_model.Mode = value
OnPropertyChanged()
End Set
End Property
Private _analysisLength As Integer
Public Property AnalysisLength() As Integer
Get
Return _model.AnalysisLength
End Get
Set(ByVal value As Integer)
_model.AnalysisLength = value
'Delay = _analysisLength / 10
WindowLength = Math.Floor(value / 5)
OnPropertyChanged()
End Set
End Property
Private _delay As Double
Public Property Delay As Double
Get
Return _model.Delay
End Get
Set(ByVal value As Double)
_model.Delay = value
OnPropertyChanged()
End Set
End Property
Private _numberDelays As Integer
Public Property NumberDelays As Integer
Get
Return _model.NumberDelays
End Get
Set(ByVal value As Integer)
_model.NumberDelays = value
If _numberDelays < 2 Then
_numberDelays = 2
Throw New Exception("Error! Number of delays in Spectral Coherence detector must be an integer greater than or equal to 2.")
End If
OnPropertyChanged()
End Set
End Property
Private _thresholdScale As Integer
Public Property ThresholdScale As Integer
Get
Return _model.ThresholdScale
End Get
Set(ByVal value As Integer)
_model.ThresholdScale = value
If _thresholdScale <= 1 Then
_thresholdScale = 3
Throw New Exception("Error! ThresholdScale in Spectral Coherence detector must be greater than1.")
End If
OnPropertyChanged()
End Set
End Property
Private _windowType As DetectorWindowType
Public Property WindowType As DetectorWindowType
Get
Return _model.WindowType
End Get
Set(ByVal value As DetectorWindowType)
_model.WindowType = value
OnPropertyChanged()
End Set
End Property
Private _frequencyInterval As String
Public Property FrequencyInterval As String
Get
Return _model.FrequencyInterval
End Get
Set(ByVal value As String)
_model.FrequencyInterval = value
OnPropertyChanged()
End Set
End Property
Private _windowLength As Integer
Public Property WindowLength As Integer
Get
Return _model.WindowLength
End Get
Set(ByVal value As Integer)
_model.WindowLength = value
WindowOverlap = Math.Floor(value / 2)
OnPropertyChanged()
End Set
End Property
Private _windowOverlap As Integer
Public Property WindowOverlap As Integer
Get
Return _model.WindowOverlap
End Get
Set(ByVal value As Integer)
_model.WindowOverlap = value
OnPropertyChanged()
End Set
End Property
Private _frequencyMin As String
Public Property FrequencyMin As String
Get
Return _model.FrequencyMin
End Get
Set(ByVal value As String)
_model.FrequencyMin = value
OnPropertyChanged()
End Set
End Property
Private _frequencyMax As String
Public Property FrequencyMax As String
Get
Return _model.FrequencyMax
End Get
Set(ByVal value As String)
_model.FrequencyMax = value
OnPropertyChanged()
End Set
End Property
Private _frequencyTolerance As String
Public Property FrequencyTolerance As String
Get
Return _model.FrequencyTolerance
End Get
Set(ByVal value As String)
_model.FrequencyTolerance = value
OnPropertyChanged()
End Set
End Property
Public Property CalcDEF As Boolean
Get
Return _model.CalcDEF
End Get
Set(ByVal value As Boolean)
_model.CalcDEF = value
OnPropertyChanged()
End Set
End Property
Public Overrides Function CheckStepIsComplete() As Boolean
Return InputChannels.Count > 0
End Function
End Class
Public Class RingdownDetector
Inherits DetectorBase
Public Sub New()
InputChannels = New ObservableCollection(Of SignalSignatureViewModel)
ThisStepInputsAsSignalHerachyByType = New SignalTypeHierachy(New SignalSignatureViewModel)
_model = New RingdownDetectorModel()
IsExpanded = False
RMSlength = "15"
RMSmedianFilterTime = "120"
RingThresholdScale = "3"
End Sub
Public Sub New(detector As RingdownDetectorModel, signalsMgr As SignalManager)
Me.New
Me._model = detector
StepCounter = signalsMgr.GroupedSignalByDetectorInput.Count + 1
ThisStepInputsAsSignalHerachyByType.SignalSignature.SignalName = "Detector " & (signalsMgr.GroupedSignalByDetectorInput.Count + 1).ToString & " " & Name
Try
InputChannels = signalsMgr.FindSignals(detector.PMUElementList)
Catch ex As Exception
Throw New Exception("Error finding signal in step: " & Name)
End Try
For Each signal In InputChannels
signalsMgr.MappingSignals.Add(signal)
Next
Try
ThisStepInputsAsSignalHerachyByType.SignalList = signalsMgr.SortSignalByType(InputChannels)
Catch ex As Exception
Throw New Exception("Error sorting output signals by PMU in step: " & Name)
End Try
signalsMgr.GroupedSignalByDetectorInput.Add(ThisStepInputsAsSignalHerachyByType)
End Sub
Private _model As RingdownDetectorModel
Public Property Model As RingdownDetectorModel
Get
Return _model
End Get
Set(ByVal value As RingdownDetectorModel)
_model = value
OnPropertyChanged()
End Set
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _model.Name
End Get
End Property
Private _rmsLength As String
Public Property RMSlength As String
Get
Return _model.RMSlength
End Get
Set(ByVal value As String)
_model.RMSlength = value
OnPropertyChanged()
End Set
End Property
Private _rmsmedianFilterTime As String
Public Property RMSmedianFilterTime As String
Get
Return _model.RMSmedianFilterTime
End Get
Set(ByVal value As String)
_model.RMSmedianFilterTime = value
OnPropertyChanged()
End Set
End Property
Private _ringThresholdScale As String
Public Property RingThresholdScale As String
Get
Return _model.RingThresholdScale
End Get
Set(ByVal value As String)
_model.RingThresholdScale = value
OnPropertyChanged()
End Set
End Property
Private _maxDuration As String
Public Property MaxDuration As String
Get
Return _model.MaxDuration
End Get
Set(ByVal value As String)
_model.MaxDuration = value
OnPropertyChanged()
End Set
End Property
Public Overrides Function CheckStepIsComplete() As Boolean
Return InputChannels.Count > 0
End Function
End Class
''' <summary>
''' This class is not used anymore, as the outofrangeFrequencydetector is kept as the more general one.
''' </summary>
'Public Class OutOfRangeGeneralDetector
' Inherits DetectorBase
' Public Sub New()
' InputChannels = New ObservableCollection(Of SignalSignatureViewModel)
' ThisStepInputsAsSignalHerachyByType = New SignalTypeHierachy(New SignalSignatureViewModel)
' IsExpanded = False
' End Sub
' Public Overrides ReadOnly Property Name As String
' Get
' Return "Out-Of-Range Detector"
' End Get
' End Property
' Private _max As Double
' Public Property Max As Double
' Get
' Return _max
' End Get
' Set(ByVal value As Double)
' _max = value
' OnPropertyChanged()
' End Set
' End Property
' Private _min As Double
' Public Property Min As Double
' Get
' Return _min
' End Get
' Set(ByVal value As Double)
' _min = value
' OnPropertyChanged()
' End Set
' End Property
' Private _duration As String
' Public Property Duration As String
' Get
' Return _duration
' End Get
' Set(ByVal value As String)
' _duration = value
' OnPropertyChanged()
' End Set
' End Property
' Private _analysisWindow As String
' Public Property AnalysisWindow As String
' Get
' Return _analysisWindow
' End Get
' Set(ByVal value As String)
' _analysisWindow = value
' OnPropertyChanged()
' End Set
' End Property
' Public Overrides Function CheckStepIsComplete() As Boolean
' Return InputChannels.Count > 0
' End Function
'End Class
''' <summary>
''' This detector is considered the more general one and used in the GUI as the out-of-range general detector.
''' </summary>
Public Class OutOfRangeFrequencyDetector
Inherits DetectorBase
Public Sub New()
InputChannels = New ObservableCollection(Of SignalSignatureViewModel)
ThisStepInputsAsSignalHerachyByType = New SignalTypeHierachy(New SignalSignatureViewModel)
_model = New OutOfRangeFrequencyDetectorModel()
IsExpanded = False
End Sub
Public Sub New(detector As OutOfRangeFrequencyDetectorModel, signalsMgr As SignalManager)
Me.New
Me._model = detector
StepCounter = signalsMgr.GroupedSignalByDetectorInput.Count + 1
ThisStepInputsAsSignalHerachyByType.SignalSignature.SignalName = "Detector " & (signalsMgr.GroupedSignalByDetectorInput.Count + 1).ToString & " " & Name
Try
InputChannels = signalsMgr.FindSignals(detector.PMUElementList)
Catch ex As Exception
Throw New Exception("Error finding signal in step: " & Name)
End Try
For Each signal In InputChannels
signalsMgr.MappingSignals.Add(signal)
Next
Try
ThisStepInputsAsSignalHerachyByType.SignalList = signalsMgr.SortSignalByType(InputChannels)
Catch ex As Exception
Throw New Exception("Error sorting output signals by PMU in step: " & Name)
End Try
signalsMgr.GroupedSignalByDetectorInput.Add(ThisStepInputsAsSignalHerachyByType)
End Sub
Private _model As OutOfRangeFrequencyDetectorModel
Public Property Model As OutOfRangeFrequencyDetectorModel
Get
Return _model
End Get
Set(ByVal value As OutOfRangeFrequencyDetectorModel)
_model = value
OnPropertyChanged()
End Set
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _model.Name
End Get
End Property
Private _type As OutOfRangeFrequencyDetectorType
Public Property Type As OutOfRangeFrequencyDetectorType
Get
Return _model.Type
End Get
Set(ByVal value As OutOfRangeFrequencyDetectorType)
_model.Type = value
OnPropertyChanged()
End Set
End Property
Private _averageWindow As String
Public Property AverageWindow As String
Get
Return _model.AverageWindow
End Get
Set(ByVal value As String)
_model.AverageWindow = value
OnPropertyChanged()
End Set
End Property
Private _nominal As String
Public Property Nominal As String
Get
Return _model.Nominal
End Get
Set(ByVal value As String)
_model.Nominal = value
OnPropertyChanged()
End Set
End Property
''' <summary>
''' This value holds either the nominal or averageWindow value depends on the selected baseline creation type
''' </summary>
'Private _baselineCreationValue As String
'Public Property BaselineCreationValue As String
' Get
' Return _baselineCreationValue
' End Get
' Set(ByVal value As String)
' _baselineCreationValue = value
' OnPropertyChanged()
' End Set
'End Property
Private _durationMax As String
Public Property DurationMax As String
Get
Return _model.DurationMax
End Get
Set(ByVal value As String)
_model.DurationMax = value
OnPropertyChanged()
End Set
End Property
Private _durationMin As String
Public Property DurationMin As String
Get
Return _model.DurationMin
End Get
Set(ByVal value As String)
_model.DurationMin = value
OnPropertyChanged()
End Set
End Property
Private _duration As String
Public Property Duration As String
Get
Return _model.Duration
End Get
Set(ByVal value As String)
_model.Duration = value
OnPropertyChanged()
End Set
End Property
Private _analysisWindow As String
Public Property AnalysisWindow As String
Get
Return _model.AnalysisWindow
End Get
Set(ByVal value As String)
_model.AnalysisWindow = value
OnPropertyChanged()
End Set
End Property
Private _rateOfChangeMax As String
Public Property RateOfChangeMax As String
Get
Return _model.RateOfChangeMax
End Get
Set(ByVal value As String)
_model.RateOfChangeMax = value
OnPropertyChanged()
End Set
End Property
Private _rateOfChangeMin As String
Public Property RateOfChangeMin As String
Get
Return _model.RateOfChangeMin
End Get
Set(ByVal value As String)
_model.RateOfChangeMin = value
OnPropertyChanged()
End Set
End Property
Private _rateOfChange As String
Public Property RateOfChange As String
Get
Return _model.RateOfChange
End Get
Set(ByVal value As String)
_model.RateOfChange = value
OnPropertyChanged()
End Set
End Property
Private _eventMergeWindow As String
Public Property EventMergeWindow As String
Get
Return _model.EventMergeWindow
End Get
Set(ByVal value As String)
_model.EventMergeWindow = value
OnPropertyChanged()
End Set
End Property
Public Overrides Function CheckStepIsComplete() As Boolean
Return InputChannels.Count > 0
End Function
End Class
Public Class WindRampDetector
Inherits DetectorBase
Public Sub New()
InputChannels = New ObservableCollection(Of SignalSignatureViewModel)
ThisStepInputsAsSignalHerachyByType = New SignalTypeHierachy(New SignalSignatureViewModel)
_model = New WindRampDetectorModel()
IsExpanded = False
_isLongTrend = True
_apass = "1"
_astop = "60"
_fpass = "0.00005"
_fstop = "0.0002"
_valMin = "400"
_valMax = "1000"
_timeMin = "14400"
_timeMax = "45000"
End Sub
Public Sub New(detector As WindRampDetectorModel, signalsMgr As SignalManager)
Me.New
Me._model = detector
StepCounter = signalsMgr.GroupedSignalByDetectorInput.Count + 1
ThisStepInputsAsSignalHerachyByType.SignalSignature.SignalName = "Detector " & (signalsMgr.GroupedSignalByDetectorInput.Count + 1).ToString & " " & Name
Try
InputChannels = signalsMgr.FindSignals(detector.PMUElementList)
Catch ex As Exception
Throw New Exception("Error finding signal in step: " & Name)
End Try
Try
ThisStepInputsAsSignalHerachyByType.SignalList = signalsMgr.SortSignalByType(InputChannels)
Catch ex As Exception
Throw New Exception("Error sorting output signals by PMU in step: " & Name)
End Try
signalsMgr.GroupedSignalByDetectorInput.Add(ThisStepInputsAsSignalHerachyByType)
End Sub
Private _model As WindRampDetectorModel
Public Property Model As WindRampDetectorModel
Get
Return _model
End Get
Set(ByVal value As WindRampDetectorModel)
_model = value
OnPropertyChanged()
End Set
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _model.Name
End Get
End Property
''' <summary>
''' if false, is short trend
''' </summary>
Private _isLongTrend As Boolean
Public Property IsLongTrend As Boolean
Get
Return _model.IsLongTrend
End Get
Set(ByVal value As Boolean)
_model.IsLongTrend = value
If value Then
_fpass = "0.00005"
_fstop = "0.0002"
ValMin = "400"
ValMax = "1000"
TimeMin = "14400"
TimeMax = "45000"
Else
_fpass = "0.03"
_fstop = "0.05"
ValMin = "50"
ValMax = "300"
TimeMin = "30"
TimeMax = "300"
End If
OnPropertyChanged()
End Set
End Property
Private _fpass As String
Public Property Fpass As String
Get
Return _model.Fpass
End Get
Set(ByVal value As String)
_model.Fpass = value
OnPropertyChanged()
End Set
End Property
Private _fstop As String
Public Property Fstop As String
Get
Return _model.Fstop
End Get
Set(ByVal value As String)
_model.Fstop = value
OnPropertyChanged()
End Set
End Property
Private _apass As String
Public Property Apass As String
Get
Return _model.Apass
End Get
Set(ByVal value As String)
_model.Apass = value
OnPropertyChanged()
End Set
End Property
Private _astop As String
Public Property Astop As String
Get
Return _model.Astop
End Get
Set(ByVal value As String)
_model.Astop = value
OnPropertyChanged()
End Set
End Property
Private _valMin As String
Public Property ValMin As String
Get
Return _model.ValMin
End Get
Set(ByVal value As String)
_model.ValMin = value
OnPropertyChanged()
End Set
End Property
Private _valMax As String
Public Property ValMax As String
Get
Return _model.ValMax
End Get
Set(ByVal value As String)
_model.ValMax = value
OnPropertyChanged()
End Set
End Property
Private _timeMin As String
Public Property TimeMin As String
Get
Return _model.TimeMin
End Get
Set(ByVal value As String)
_model.TimeMin = value
OnPropertyChanged()
End Set
End Property
Private _timeMax As String
Public Property TimeMax As String
Get
Return _model.TimeMax
End Get
Set(ByVal value As String)
_model.TimeMax = value
OnPropertyChanged()
End Set
End Property
Public Overrides Function CheckStepIsComplete() As Boolean
Return InputChannels.Count > 0
End Function
End Class
Public Class DataWriterDetectorViewModel
Inherits DetectorBase
Public Sub New()
InputChannels = New ObservableCollection(Of SignalSignatureViewModel)
ThisStepInputsAsSignalHerachyByType = New SignalTypeHierachy(New SignalSignatureViewModel)
_model = New DataWriterDetectorModel()
IsExpanded = False
'_browseSavePath = New DelegateCommand(AddressOf _openSavePath, AddressOf CanExecute)
End Sub
Public Sub New(detector As DataWriterDetectorModel, signalsMgr As SignalManager)
Me.New
Me._model = detector
ThisStepInputsAsSignalHerachyByType.SignalSignature.SignalName = "Detector " & (signalsMgr.GroupedSignalByDataWriterDetectorInput.Count + 1).ToString & " " & Name
Try
InputChannels = signalsMgr.FindSignals(detector.PMUElementList)
Catch ex As Exception
Throw New Exception("Error finding signal in step: " & Name)
End Try
Try
ThisStepInputsAsSignalHerachyByType.SignalList = signalsMgr.SortSignalByType(InputChannels)
Catch ex As Exception
Throw New Exception("Error sorting output signals by PMU in step: " & Name)
End Try
signalsMgr.GroupedSignalByDataWriterDetectorInput.Add(ThisStepInputsAsSignalHerachyByType)
End Sub
Private _model As DataWriterDetectorModel
Public Property Model As DataWriterDetectorModel
Get
Return _model
End Get
Set(ByVal value As DataWriterDetectorModel)
_model = value
OnPropertyChanged()
End Set
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _model.Name
End Get
End Property
Private _savePath As String
Public Property SavePath As String
Get
Return _model.SavePath
End Get
Set(ByVal value As String)
_model.SavePath = value
OnPropertyChanged()
End Set
End Property
Private _separatePMUs As Boolean
Public Property SeparatePMUs As Boolean
Get
Return _model.SeparatePMUs
End Get
Set(ByVal value As Boolean)
_model.SeparatePMUs = value
OnPropertyChanged()
End Set
End Property
Private _mnemonic As String
Public Property Mnemonic As String
Get
Return _model.Mnemonic
End Get
Set(ByVal value As String)
_model.Mnemonic = value
OnPropertyChanged()
End Set
End Property
Public Overrides Function CheckStepIsComplete() As Boolean
Return InputChannels.Count > 0
End Function
'Private _lastSavePath As String
'Private _browseSavePath As ICommand
'Public Property BrowseSavePath As ICommand
' Get
' Return _browseSavePath
' End Get
' Set(ByVal value As ICommand)
' _browseSavePath = value
' End Set
'End Property
'Private Sub _openSavePath(obj As Object)
' Dim openDirectoryDialog As New FolderBrowserDialog()
' openDirectoryDialog.Description = "Select the save path"
' If _lastSavePath Is Nothing Then
' openDirectoryDialog.SelectedPath = Environment.CurrentDirectory
' Else
' openDirectoryDialog.SelectedPath = _lastSavePath
' End If
' openDirectoryDialog.ShowNewFolderButton = True
' If (openDirectoryDialog.ShowDialog = DialogResult.OK) Then
' _lastSavePath = openDirectoryDialog.SelectedPath
' SavePath = openDirectoryDialog.SelectedPath
' End If
'End Sub
End Class
Public Class AutoEventExportViewModel
Inherits ViewModelBase
Public Sub New()
_model = New AutoEventExportModel
_browseExportPath = New DelegateCommand(AddressOf _browseEventExportPath, AddressOf CanExecute)
End Sub
Public Sub New(autoEventExporter As AutoEventExportModel)
Me.New
_model = autoEventExporter
End Sub
Private _model As AutoEventExportModel
Public Property Flag As Boolean
Get
Return _model.Flag
End Get
Set(ByVal value As Boolean)
_model.Flag = value
OnPropertyChanged()
End Set
End Property
Public Property SurroundingMinutes As String
Get
Return _model.SurroundingMinutes
End Get
Set(ByVal value As String)
_model.SurroundingMinutes = value
OnPropertyChanged()
End Set
End Property
Public Property DeletePastFlag As Boolean
Get
Return _model.DeletePastFlag
End Get
Set(ByVal value As Boolean)
_model.DeletePastFlag = value
OnPropertyChanged()
End Set
End Property
Public Property DeletePastDays As String
Get
Return _model.DeletePastDays
End Get
Set(ByVal value As String)
_model.DeletePastDays = value
OnPropertyChanged()
End Set
End Property
Public Property ExportPath As String
Get
Return _model.ExportPath
End Get
Set(ByVal value As String)
_model.ExportPath = value
OnPropertyChanged()
End Set
End Property
Private _browseExportPath As ICommand
Public Property BrowseExportPath As ICommand
Get
Return _browseExportPath
End Get
Set(ByVal value As ICommand)
_browseExportPath = value
End Set
End Property
'Private _lastSavePath As String
Private autoEventExporter As AutoEventExportModel
Private Sub _browseEventExportPath(obj As Object)
Dim openDirectoryDialog As New CommonOpenFileDialog
openDirectoryDialog.Title = "Select the Event Export Path"
openDirectoryDialog.IsFolderPicker = True
openDirectoryDialog.RestoreDirectory = True
If String.IsNullOrEmpty(ExportPath) Then
openDirectoryDialog.InitialDirectory = Environment.CurrentDirectory
Else
openDirectoryDialog.InitialDirectory = ExportPath
End If
openDirectoryDialog.AddToMostRecentlyUsedList = True
openDirectoryDialog.AllowNonFileSystemItems = False
openDirectoryDialog.DefaultDirectory = Environment.CurrentDirectory
openDirectoryDialog.EnsureFileExists = True
openDirectoryDialog.EnsurePathExists = True
openDirectoryDialog.EnsureReadOnly = False
openDirectoryDialog.EnsureValidNames = True
openDirectoryDialog.Multiselect = False
openDirectoryDialog.ShowPlacesList = True
If openDirectoryDialog.ShowDialog = CommonFileDialogResult.Ok Then
'_lastSavePath = openDirectoryDialog.FileName
ExportPath = openDirectoryDialog.FileName
End If
End Sub
End Class
'Public Enum DetectorModeType
' <ComponentModel.Description("Single Channel")>
' SingleChannel
' <ComponentModel.Description("Multichannel")>
' MultiChannel
'End Enum
'Public Enum DetectorWindowType
' <ComponentModel.Description("Hann")>
' hann
' <ComponentModel.Description("Rectangular")>
' rectwin
' <ComponentModel.Description("Bartlett")>
' bartlett
' <ComponentModel.Description("Hamming")>
' hamming
' <ComponentModel.Description("Blackman")>
' blackman
'End Enum
'Public Enum OutOfRangeFrequencyDetectorType
' <ComponentModel.Description("Nominal Value")>
' Nominal
' <ComponentModel.Description("History for Baseline (seconds)")>
' AvergeWindow
'End Enum
Public Class AlarmingSpectralCoherence
Inherits AlarmingDetectorBase
Public Sub New()
IsExpanded = False
_model = New AlarmingSpectralCoherenceModel()
End Sub
Public Sub New(detector As AlarmingSpectralCoherenceModel, signalsMgr As SignalManager)
Me.New
Me._model = detector
End Sub
Public Overrides Function CheckStepIsComplete() As Boolean
Return True
End Function
Private _model As AlarmingSpectralCoherenceModel
Public Property Model As AlarmingSpectralCoherenceModel
Get
Return _model
End Get
Set(ByVal value As AlarmingSpectralCoherenceModel)
_model = value
OnPropertyChanged()
End Set
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _model.Name
End Get
End Property
Private _coherenceAlarm As String
Public Property CoherenceAlarm As String
Get
Return _model.CoherenceAlarm
End Get
Set(ByVal value As String)
_model.CoherenceAlarm = value
OnPropertyChanged()
End Set
End Property
Private _coherenceMin As String
Public Property CoherenceMin As String
Get
Return _model.CoherenceMin
End Get
Set(ByVal value As String)
_model.CoherenceMin = value
OnPropertyChanged()
End Set
End Property
Private _timeMin As String
Public Property TimeMin As String
Get
Return _model.TimeMin
End Get
Set(ByVal value As String)
_model.TimeMin = value
OnPropertyChanged()
End Set
End Property
Private _coherenceCorner As String
Public Property CoherenceCorner As String
Get
Return _model.CoherenceCorner
End Get
Set(ByVal value As String)
_model.CoherenceCorner = value
OnPropertyChanged()
End Set
End Property
Private _timeCorner As String
Public Property TimeCorner As String
Get
Return _model.TimeCorner
End Get
Set(ByVal value As String)
_model.TimeCorner = value
OnPropertyChanged()
End Set
End Property
End Class
Public Class AlarmingPeriodogram
Inherits AlarmingDetectorBase
Public Sub New()
IsExpanded = False
_model = New AlarmingPeriodogramModel()
End Sub
Public Sub New(detector As AlarmingPeriodogramModel, signalsMgr As SignalManager)
Me.New
Me._model = detector
End Sub
Public Overrides Function CheckStepIsComplete() As Boolean
Return True
End Function
Private _model As AlarmingPeriodogramModel
Public Property Model As AlarmingPeriodogramModel
Get
Return _model
End Get
Set(ByVal value As AlarmingPeriodogramModel)
_model = value
OnPropertyChanged()
End Set
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _model.Name
End Get
End Property
Private _snrAlarm As String
Public Property SNRalarm As String
Get
Return _model.SNRalarm
End Get
Set(ByVal value As String)
_model.SNRalarm = value
OnPropertyChanged()
End Set
End Property
Private _snrMin As String
Public Property SNRmin As String
Get
Return _model.SNRmin
End Get
Set(ByVal value As String)
_model.SNRmin = value
OnPropertyChanged()
End Set
End Property
Private _timeMin As String
Public Property TimeMin As String
Get
Return _model.TimeMin
End Get
Set(ByVal value As String)
_model.TimeMin = value
OnPropertyChanged()
End Set
End Property
Private _snrCorner As String
Public Property SNRcorner As String
Get
Return _model.SNRcorner
End Get
Set(ByVal value As String)
_model.SNRcorner = value
OnPropertyChanged()
End Set
End Property
Private _timeCorner As String
Public Property TimeCorner As String
Get
Return _model.TimeCorner
End Get
Set(ByVal value As String)
_model.TimeCorner = value
OnPropertyChanged()
End Set
End Property
End Class
Public Class AlarmingRingdown
Inherits AlarmingDetectorBase
Public Sub New()
IsExpanded = False
_model = New AlarmingRingdownModel
End Sub
Public Sub New(detector As AlarmingRingdownModel, signalsMgr As SignalManager)
Me.New
Me._model = detector
End Sub
Public Overrides Function CheckStepIsComplete() As Boolean
Return True
End Function
Private _model As AlarmingRingdownModel
Public Property Model As AlarmingRingdownModel
Get
Return _model
End Get
Set(ByVal value As AlarmingRingdownModel)
_model = value
OnPropertyChanged()
End Set
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _model.Name
End Get
End Property
Private _maxDuration As String
Public Property MaxDuration As String
Get
Return _model.MaxDuration
End Get
Set(ByVal value As String)
_model.MaxDuration = value
OnPropertyChanged()
End Set
End Property
End Class
End Namespace
|
'
' Copyright (c) 2006 Microsoft Corporation. All rights reserved.
'
' THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
' ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
' THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
' PARTICULAR PURPOSE.
'
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Text
Imports Microsoft.VisualBasic
Imports System.Management.Automation
Imports System.Management.Automation.Host
Imports System.Management.Automation.Runspaces
Namespace Microsoft.Samples.PowerShell.Runspaces
Class Runspace03
''' <summary>
''' This sample uses the RunspaceInvoke class to execute
''' a script that retrieves process information for the
''' list of process names passed into the script.
''' It shows how to pass input objects to a script and
''' how to retrieve error objects as well as the output objects.
''' </summary>
''' <param name="args">Unused</param>
''' <remarks>
''' This sample demonstrates the following:
''' 1. Creating an instance of the RunspaceInvoke class.
''' 2. Using this instance to execute a string as a PowerShell script.
''' 3. Passing input objects to the script from the calling program.
''' 4. Using PSObject to extract and display properties from the objects
''' returned by this command.
''' 5. Retrieving and displaying error records that were generated
''' during the execution of that script.
''' </remarks>
Shared Sub Main(ByVal args() As String)
' Define a list of processes to look for
Dim processNames() As String = {"lsass", "nosuchprocess", _
"services", "nosuchprocess2"}
' The script to run to get these processes. Input passed
' to the script will be available in the $input variable.
Dim script As String = "$input | get-process -name {$_}"
' Create an instance of the RunspaceInvoke class.
Dim invoker As New RunspaceInvoke()
Console.WriteLine("Process HandleCount")
Console.WriteLine("--------------------------------")
' Now invoke the runspace and display the objects that are
' returned...
Dim errors As System.Collections.IList = Nothing
Dim result As PSObject
For Each result In invoker.Invoke(script, processNames, errors)
Console.WriteLine("{0,-20} {1}", _
result.Members("ProcessName").Value, _
result.Members("HandleCount").Value)
Next result
' Now process any error records that were generated while
' running the script.
Console.WriteLine(vbCrLf & _
"The following non-terminating errors occurred:" & vbCrLf)
If Not (errors Is Nothing) AndAlso errors.Count > 0 Then
Dim err As PSObject
For Each err In errors
System.Console.WriteLine(" error: {0}", err.ToString())
Next err
End If
System.Console.WriteLine(vbCRLF & "Hit any key to exit...")
System.Console.ReadKey()
End Sub 'Main
End Class 'Runspace03
End Namespace
|
Imports Microsoft.VisualBasic
Imports System.data
Imports System.Web
Imports Talent.Common
<Serializable()> _
Public Class TalentWebPricing
Inherits TalentBase
Private _settings As DEWebPriceSetting
Private _resultDataSet As DataSet
Private _prices As Generic.Dictionary(Of String, DEWebPrice)
Public Property RetrievedPrices() As Generic.Dictionary(Of String, DEWebPrice)
Get
Return _prices
End Get
Set(ByVal value As Generic.Dictionary(Of String, DEWebPrice))
_prices = value
End Set
End Property
Private _products As Generic.Dictionary(Of String, WebPriceProduct)
Public Property Products() As Generic.Dictionary(Of String, WebPriceProduct)
Get
Return _products
End Get
Set(ByVal value As Generic.Dictionary(Of String, WebPriceProduct))
_products = value
End Set
End Property
Public Property WebPriceSettings() As DEWebPriceSetting
Get
Return _settings
End Get
Set(ByVal value As DEWebPriceSetting)
_settings = value
End Set
End Property
Public Property ResultDataSet() As DataSet
Get
Return _resultDataSet
End Get
Set(ByVal value As DataSet)
_resultDataSet = value
End Set
End Property
Private _totalValueGross As Decimal
Public Property Total_Items_Value_Gross() As Decimal
Get
Return _totalValueGross
End Get
Set(ByVal value As Decimal)
_totalValueGross = value
End Set
End Property
Private _totalValueNet As Decimal
Public Property Total_Items_Value_Net() As Decimal
Get
Return _totalValueNet
End Get
Set(ByVal value As Decimal)
_totalValueNet = value
End Set
End Property
Private _totalValueTax As Decimal
Public Property Total_Items_Value_Tax() As Decimal
Get
Return _totalValueTax
End Get
Set(ByVal value As Decimal)
_totalValueTax = value
End Set
End Property
Private _maxDelGross As Decimal
Public Property Max_Delivery_Gross() As Decimal
Get
Return _maxDelGross
End Get
Set(ByVal value As Decimal)
_maxDelGross = value
End Set
End Property
Private _maxDelNet As Decimal
Public Property Max_Delivery_Net() As Decimal
Get
Return _maxDelNet
End Get
Set(ByVal value As Decimal)
_maxDelNet = value
End Set
End Property
Private _maxdeltax As Decimal
Public Property Max_Delivery_Tax() As Decimal
Get
Return _maxdeltax
End Get
Set(ByVal value As Decimal)
_maxdeltax = value
End Set
End Property
Private _promoResultsTable As DataTable
Public Property PromotionsResultsTable() As DataTable
Get
Return _promoResultsTable
End Get
Set(ByVal value As DataTable)
_promoResultsTable = value
End Set
End Property
Private _totalItemsTax As Decimal
Public Property Total_Items_Tax() As Decimal
Get
Return _totalItemsTax
End Get
Set(ByVal value As Decimal)
_totalItemsTax = value
End Set
End Property
Private _totalItemsTax1 As Decimal
Public Property Total_Items_Tax1() As Decimal
Get
Return _totalItemsTax1
End Get
Set(ByVal value As Decimal)
_totalItemsTax1 = value
End Set
End Property
Private _totalItemsTax2 As Decimal
Public Property Total_Items_Tax2() As Decimal
Get
Return _totalItemsTax2
End Get
Set(ByVal value As Decimal)
_totalItemsTax2 = value
End Set
End Property
Private _totalItemsTax3 As Decimal
Public Property Total_Items_Tax3() As Decimal
Get
Return _totalItemsTax3
End Get
Set(ByVal value As Decimal)
_totalItemsTax3 = value
End Set
End Property
Private _totalItemsTax4 As Decimal
Public Property Total_Items_Tax4() As Decimal
Get
Return _totalItemsTax4
End Get
Set(ByVal value As Decimal)
_totalItemsTax4 = value
End Set
End Property
Private _totalItemsTax5 As Decimal
Public Property Total_Items_Tax5() As Decimal
Get
Return _totalItemsTax5
End Get
Set(ByVal value As Decimal)
_totalItemsTax5 = value
End Set
End Property
Private _totalOrderGross As Decimal
Public Property Total_Order_Value_Gross() As Decimal
Get
Return _totalOrderGross
End Get
Set(ByVal value As Decimal)
_totalOrderGross = value
End Set
End Property
Private _totalOrderNet As Decimal
Public Property Total_Order_Value_Net() As Decimal
Get
Return _totalOrderNet
End Get
Set(ByVal value As Decimal)
_totalOrderNet = value
End Set
End Property
Private _totalOrderTax As Decimal
Public Property Total_Order_Value_Tax() As Decimal
Get
Return _totalOrderTax
End Get
Set(ByVal value As Decimal)
_totalOrderTax = value
End Set
End Property
Private _freeDelivery As Boolean
Public Property Qualifies_For_Free_Delivery() As Boolean
Get
Return _freeDelivery
End Get
Set(ByVal value As Boolean)
_freeDelivery = value
End Set
End Property
Private _totalPromotionsValue As Decimal
Public Property Total_Promotions_Value() As Decimal
Get
Return _totalPromotionsValue
End Get
Set(ByVal value As Decimal)
_totalPromotionsValue = value
End Set
End Property
Private _displayPriceIncVAT As Boolean
Public Property DisplayPriceIncVAT() As Boolean
Get
Return _displayPriceIncVAT
End Get
Set(ByVal value As Boolean)
_displayPriceIncVAT = value
End Set
End Property
Private _freeDeliveryPromotion As Boolean
Public Property FreeDeliveryPromotion() As Boolean
Get
Return _freeDeliveryPromotion
End Get
Set(ByVal value As Boolean)
_freeDeliveryPromotion = value
End Set
End Property
Private _freeDeliveryValueForPriceList As Decimal
Public Property FreeDeliveryValueForPriceList() As Decimal
Get
Return _freeDeliveryValueForPriceList
End Get
Set(ByVal value As Decimal)
_freeDeliveryValueForPriceList = value
End Set
End Property
Public Property IsWebPricesModified() As Boolean = False
Public Sub New(ByVal WebPrice_Settings As DEWebPriceSetting, ByVal products As Generic.Dictionary(Of String, WebPriceProduct), ByVal DisplayPricesIncVAT As Boolean)
MyBase.New()
Me.WebPriceSettings = WebPrice_Settings
Me.Products = products
Me.DisplayPriceIncVAT = DisplayPricesIncVAT
Me.Settings = Me.WebPriceSettings
End Sub
Public Shared Function CheckDBNull(ByVal value As Object) As Object
If value.Equals(DBNull.Value) Then
Return Nothing
Else
Return value
End If
End Function
Public Function GetWebPrices() As ErrorObj
Const ModuleName As String = "GetWebProductPrices"
Dim err As New ErrorObj
If Me.Products.Count > 0 Then
'--------------------------------------------------------------------------
' Dim cacheKey As String = ModuleName & WebPriceSettings.BusinessUnit & WebPriceSettings.partner & WebPriceSettings.Company
'No cache because it is called whenever an item needs pricing
Me.GetConnectionDetails(WebPriceSettings.BusinessUnit, "", ModuleName)
Dim dbWebPrice As New DBWebPrice(Me.Products, Me.WebPriceSettings.PriceList, Me.WebPriceSettings.SecondaryPriceList)
With dbWebPrice
.Settings = Me.WebPriceSettings
err = .AccessDatabase
If Not err.HasError And Not .ResultDataSet Is Nothing Then
ResultDataSet = .ResultDataSet
ProcessPrices(False, False)
End If
End With
End If
Return err
End Function
''' <summary>
''' This function overrides the product properties with the master product properties to be called
''' when the OPTION_PRICE_FROM_MASTER_PRODUCT flag is set to true in ecommerce_module_defaults_bu table.
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function GetWebPricesWithMasterProducts() As ErrorObj
Const ModuleName As String = "GetWebProductPrices"
Dim err As New ErrorObj
If Me.Products.Count > 0 Then
'--------------------------------------------------------------------------
' Dim cacheKey As String = ModuleName & WebPriceSettings.BusinessUnit & WebPriceSettings.partner & WebPriceSettings.Company
'No cache because it is called whenever an item needs pricing
Me.GetConnectionDetails(WebPriceSettings.BusinessUnit, "", ModuleName)
Dim dbWebPrice As New DBWebPrice(Me.Products, Me.WebPriceSettings.PriceList, Me.WebPriceSettings.SecondaryPriceList)
With dbWebPrice
.Settings = Me.WebPriceSettings
err = .AccessDatabase
If Not err.HasError And Not .ResultDataSet Is Nothing Then
ResultDataSet = .ResultDataSet
ProcessPrices(False, True)
End If
End With
End If
Return err
End Function
Public Function GetWebPrices_WithPromotionDetails() As ErrorObj
Const ModuleName As String = "GetWebProductPrices"
Dim err As New ErrorObj
If Me.Products.Count > 0 Then
'--------------------------------------------------------------------------
Dim cacheKey As String = ModuleName & WebPriceSettings.BusinessUnit & WebPriceSettings.Partner & WebPriceSettings.Company
If WebPriceSettings.Cacheing AndAlso Talent.Common.TalentThreadSafe.ItemIsInCache(cacheKey) Then
ResultDataSet = CType(HttpContext.Current.Cache.Item(cacheKey), DataSet)
Else
Me.GetConnectionDetails(WebPriceSettings.BusinessUnit, "", ModuleName)
Dim dbWebPrice As New DBWebPrice(Me.Products, Me.WebPriceSettings.PriceList, Me.WebPriceSettings.SecondaryPriceList)
With dbWebPrice
.Settings = Me.WebPriceSettings
err = .AccessDatabase
If Not err.HasError And Not .ResultDataSet Is Nothing Then
ResultDataSet = .ResultDataSet
ProcessPrices(True, False)
End If
End With
End If
End If
Return err
End Function
Public Function GetWebPricesWithTotals() As ErrorObj
Const ModuleName As String = "GetWebProductPrices"
Dim err As New ErrorObj
If Me.Products.Count > 0 Then
'--------------------------------------------------------------------------
Dim cacheKey As String = ModuleName & WebPriceSettings.BusinessUnit & WebPriceSettings.Partner & WebPriceSettings.Company
If WebPriceSettings.Cacheing AndAlso Talent.Common.TalentThreadSafe.ItemIsInCache(cacheKey) Then
ResultDataSet = CType(HttpContext.Current.Cache.Item(cacheKey), DataSet)
Else
Me.GetConnectionDetails(WebPriceSettings.BusinessUnit, "", ModuleName)
Dim dbWebPrice As New DBWebPrice(Me.Products, Me.WebPriceSettings.PriceList, Me.WebPriceSettings.SecondaryPriceList)
With dbWebPrice
.Settings = Me.WebPriceSettings
err = .AccessDatabase
If Not err.HasError And Not .ResultDataSet Is Nothing Then
ResultDataSet = .ResultDataSet
ProcessPrices(True, False)
CalculateTotals()
EvaluatePricesWithPromotions()
End If
End With
End If
End If
Return err
End Function
Public Sub CalculateTotals(Optional ByVal promotionCode As String = "")
If Not Me.RetrievedPrices Is Nothing Then
Me.Total_Items_Value_Gross = 0
Me.Total_Items_Value_Net = 0
Me.Total_Items_Value_Tax = 0
For Each productCode As String In Me.RetrievedPrices.Keys
Dim requestedQty As Decimal = Me.RetrievedPrices(productCode).RequestedQuantity
Me.Total_Items_Value_Gross += (Me.RetrievedPrices(productCode).Purchase_Price_Gross * requestedQty)
Me.Total_Items_Value_Net += (Me.RetrievedPrices(productCode).Purchase_Price_Net * requestedQty)
Me.Total_Items_Value_Tax += (Me.RetrievedPrices(productCode).Purchase_Price_Tax * requestedQty)
If Me.Max_Delivery_Gross < Me.RetrievedPrices(productCode).DELIVERY_GROSS_PRICE Then
Me.Max_Delivery_Gross = Me.RetrievedPrices(productCode).DELIVERY_GROSS_PRICE
Me.Max_Delivery_Net = Me.RetrievedPrices(productCode).DELIVERY_NET_PRICE
Me.Max_Delivery_Tax = Me.RetrievedPrices(productCode).DELIVERY_TAX_AMOUNT
End If
Next
Me.FreeDeliveryValueForPriceList = GetFreeDeliveryValue()
If Me.FreeDeliveryValueForPriceList > 0 AndAlso Me.Total_Items_Value_Gross >= Me.FreeDeliveryValueForPriceList Then
Me.Qualifies_For_Free_Delivery = True
Me.Total_Order_Value_Gross = Me.Total_Items_Value_Gross
Me.Total_Order_Value_Net = Me.Total_Items_Value_Net
Me.Total_Order_Value_Tax = Me.Total_Items_Value_Tax
Else
Me.Qualifies_For_Free_Delivery = False
Me.Total_Order_Value_Gross = Me.Total_Items_Value_Gross + Me.Max_Delivery_Gross
Me.Total_Order_Value_Net = Me.Total_Items_Value_Net + Me.Max_Delivery_Net
Me.Total_Order_Value_Tax = Me.Total_Items_Value_Tax + Me.Max_Delivery_Tax
End If
End If
End Sub
Protected Sub ProcessPrices(ByVal withPromoCheck As Boolean, ByVal includeAllMasterProducts As Boolean)
Dim results As DataTable = ResultDataSet.Tables(0), _
wp As New DEWebPrice
If results.Rows.Count > 0 Then
Me.RetrievedPrices = New Generic.Dictionary(Of String, DEWebPrice)
Dim addedProducts As New Generic.List(Of String)
'Loop through the returned records and add the prices
For i As Integer = 0 To results.Rows.Count - 1
If Not Me.RetrievedPrices.ContainsKey(results.Rows(i)("PRODUCT")) Then
If Products.ContainsKey(results.Rows(i)("PRODUCT")) Then
wp = New DEWebPrice
wp = PopulateWebPriceEntity(results, wp, i)
wp.RequestedQuantity = Products(results.Rows(i)("PRODUCT")).Quantity
Me.RetrievedPrices.Add(wp.PRODUCT_CODE, wp)
'Keep a record of the products that have been added
addedProducts.Add(wp.PRODUCT_CODE)
End If
End If
Next
If Not includeAllMasterProducts Then
'Add the Master Product prices to any entries that were not found
If addedProducts.Count < Me.Products.Count Then
For Each prod As WebPriceProduct In Me.Products.Values
' Also need to check if master has already been added.
' If not, this crashes when purchasing a multibuy product
' along with something else
If (Not addedProducts.Contains(prod.ProductCode)) AndAlso _
(Not addedProducts.Contains(prod.MasterProductCode)) Then
For i As Integer = 0 To results.Rows.Count - 1
If results.Rows(i)("PRODUCT") = prod.MasterProductCode Then
wp = New DEWebPrice
wp = PopulateWebPriceEntity(results, wp, i)
wp.PRODUCT_CODE = prod.ProductCode
wp.RequestedQuantity = prod.Quantity
Me.RetrievedPrices.Add(wp.PRODUCT_CODE, wp)
Exit For 'We found the result for this product so exit
End If
Next
End If
Next
End If
Else
'Replace all the product properties with those of their master products.
For Each prod As WebPriceProduct In Me.Products.Values
For i As Integer = 0 To results.Rows.Count - 1
If results.Rows(i)("PRODUCT") = prod.MasterProductCode Then
If RetrievedPrices.ContainsKey(prod.ProductCode) Then
RetrievedPrices.Remove(prod.ProductCode)
End If
wp = New DEWebPrice
wp = PopulateWebPriceEntity(results, wp, i)
wp.PRODUCT_CODE = prod.ProductCode
wp.RequestedQuantity = prod.Quantity
Me.RetrievedPrices.Add(wp.PRODUCT_CODE, wp)
Exit For 'We found the result for this product so exit
End If
Next
Next
End If
If Me.RetrievedPrices.Count > 0 Then
CalculatePurchasePrices(withPromoCheck)
End If
End If
End Sub
Protected Sub CalculatePurchasePrices(ByVal incPromoCheck As Boolean)
For Each productCode As String In Me.RetrievedPrices.Keys
Dim wp As DEWebPrice = Me.RetrievedPrices(productCode), _
qty As Decimal = Products(productCode).Quantity
If qty = 0 Then qty = 1 'if qty has not been specified, default to 1
If wp.SALE_PRICE_BREAK_QUANTITY_1 = 0 AndAlso wp.SALE_GROSS_PRICE > 0 Then
'if the sale price break is not setup, but there is a sale price
'then treat it as a single sale price
wp.Purchase_Price_Gross = wp.SALE_GROSS_PRICE
wp.Purchase_Price_Net = wp.SALE_NET_PRICE
wp.Purchase_Price_Tax = wp.SALE_TAX_AMOUNT
wp.From_Price_Gross = wp.SALE_GROSS_PRICE
wp.From_Price_Net = wp.SALE_NET_PRICE
wp.From_Price_Tax = wp.SALE_TAX_AMOUNT
wp.IsSalePrice = True
wp.IsPartOfPromotion = False
ElseIf wp.SALE_PRICE_BREAK_QUANTITY_1 > 0 AndAlso wp.SALE_GROSS_PRICE > 0 Then
' if the sale price break is setup, process for sale price breaks
' determine which is the last level of price break and set
' the quantity to be greater than the requested quantity
' so that the select will fall into the correct category
If wp.SALE_PRICE_BREAK_QUANTITY_2 = 0 Then
wp.SALE_PRICE_BREAK_QUANTITY_2 = wp.RequestedQuantity + 10
wp.From_Price_Gross = wp.SALE_GROSS_PRICE
wp.From_Price_Net = wp.SALE_NET_PRICE
wp.From_Price_Tax = wp.SALE_TAX_AMOUNT
ElseIf wp.SALE_PRICE_BREAK_QUANTITY_3 = 0 Then
wp.SALE_PRICE_BREAK_QUANTITY_3 = wp.RequestedQuantity + 10
wp.From_Price_Gross = wp.SALE_GROSS_PRICE_2
wp.From_Price_Net = wp.SALE_NET_PRICE_2
wp.From_Price_Tax = wp.SALE_TAX_AMOUNT_2
ElseIf wp.SALE_PRICE_BREAK_QUANTITY_4 = 0 Then
wp.SALE_PRICE_BREAK_QUANTITY_4 = wp.RequestedQuantity + 10
wp.From_Price_Gross = wp.SALE_GROSS_PRICE_3
wp.From_Price_Net = wp.SALE_NET_PRICE_3
wp.From_Price_Tax = wp.SALE_TAX_AMOUNT_3
ElseIf wp.SALE_PRICE_BREAK_QUANTITY_5 = 0 Then
wp.SALE_PRICE_BREAK_QUANTITY_5 = wp.RequestedQuantity + 10
wp.From_Price_Gross = wp.SALE_GROSS_PRICE_4
wp.From_Price_Net = wp.SALE_NET_PRICE_4
wp.From_Price_Tax = wp.SALE_TAX_AMOUNT_4
ElseIf wp.SALE_PRICE_BREAK_QUANTITY_6 = 0 Then
wp.SALE_PRICE_BREAK_QUANTITY_6 = wp.RequestedQuantity + 10
wp.From_Price_Gross = wp.SALE_GROSS_PRICE_5
wp.From_Price_Net = wp.SALE_NET_PRICE_5
wp.From_Price_Tax = wp.SALE_TAX_AMOUNT_5
ElseIf wp.SALE_PRICE_BREAK_QUANTITY_7 = 0 Then
wp.SALE_PRICE_BREAK_QUANTITY_7 = wp.RequestedQuantity + 10
wp.From_Price_Gross = wp.SALE_GROSS_PRICE_6
wp.From_Price_Net = wp.SALE_NET_PRICE_6
wp.From_Price_Tax = wp.SALE_TAX_AMOUNT_6
ElseIf wp.SALE_PRICE_BREAK_QUANTITY_8 = 0 Then
wp.SALE_PRICE_BREAK_QUANTITY_8 = wp.RequestedQuantity + 10
wp.From_Price_Gross = wp.SALE_GROSS_PRICE_7
wp.From_Price_Net = wp.SALE_NET_PRICE_7
wp.From_Price_Tax = wp.SALE_TAX_AMOUNT_7
ElseIf wp.SALE_PRICE_BREAK_QUANTITY_9 = 0 Then
wp.SALE_PRICE_BREAK_QUANTITY_9 = wp.RequestedQuantity + 10
wp.From_Price_Gross = wp.SALE_GROSS_PRICE_8
wp.From_Price_Net = wp.SALE_NET_PRICE_8
wp.From_Price_Tax = wp.SALE_TAX_AMOUNT_8
ElseIf wp.SALE_PRICE_BREAK_QUANTITY_10 = 0 Then
wp.SALE_PRICE_BREAK_QUANTITY_10 = wp.RequestedQuantity + 10
wp.From_Price_Gross = wp.SALE_GROSS_PRICE_9
wp.From_Price_Net = wp.SALE_NET_PRICE_9
wp.From_Price_Tax = wp.SALE_TAX_AMOUNT_9
Else
wp.From_Price_Gross = wp.SALE_GROSS_PRICE_10
wp.From_Price_Net = wp.SALE_NET_PRICE_10
wp.From_Price_Tax = wp.SALE_TAX_AMOUNT_10
End If
Select Case qty
Case wp.SALE_PRICE_BREAK_QUANTITY_1 To wp.SALE_PRICE_BREAK_QUANTITY_2
wp.Purchase_Price_Gross = wp.SALE_GROSS_PRICE
wp.Purchase_Price_Net = wp.SALE_NET_PRICE
wp.Purchase_Price_Tax = wp.SALE_TAX_AMOUNT
Case wp.SALE_PRICE_BREAK_QUANTITY_2 + 0.001 To wp.SALE_PRICE_BREAK_QUANTITY_3
wp.Purchase_Price_Gross = wp.SALE_GROSS_PRICE_2
wp.Purchase_Price_Net = wp.SALE_NET_PRICE_2
wp.Purchase_Price_Tax = wp.SALE_TAX_AMOUNT_2
Case wp.SALE_PRICE_BREAK_QUANTITY_3 + 0.001 To wp.SALE_PRICE_BREAK_QUANTITY_4
wp.Purchase_Price_Gross = wp.SALE_GROSS_PRICE_3
wp.Purchase_Price_Net = wp.SALE_NET_PRICE_3
wp.Purchase_Price_Tax = wp.SALE_TAX_AMOUNT_3
Case wp.SALE_PRICE_BREAK_QUANTITY_4 + 0.001 To wp.SALE_PRICE_BREAK_QUANTITY_5
wp.Purchase_Price_Gross = wp.SALE_GROSS_PRICE_4
wp.Purchase_Price_Net = wp.SALE_NET_PRICE_4
wp.Purchase_Price_Tax = wp.SALE_TAX_AMOUNT_4
Case wp.SALE_PRICE_BREAK_QUANTITY_5 + 0.001 To wp.SALE_PRICE_BREAK_QUANTITY_6
wp.Purchase_Price_Gross = wp.SALE_GROSS_PRICE_5
wp.Purchase_Price_Net = wp.SALE_NET_PRICE_5
wp.Purchase_Price_Tax = wp.SALE_TAX_AMOUNT_5
Case wp.SALE_PRICE_BREAK_QUANTITY_6 + 0.001 To wp.SALE_PRICE_BREAK_QUANTITY_7
wp.Purchase_Price_Gross = wp.SALE_GROSS_PRICE_6
wp.Purchase_Price_Net = wp.SALE_NET_PRICE_6
wp.Purchase_Price_Tax = wp.SALE_TAX_AMOUNT_6
Case wp.SALE_PRICE_BREAK_QUANTITY_7 + 0.001 To wp.SALE_PRICE_BREAK_QUANTITY_8
wp.Purchase_Price_Gross = wp.SALE_GROSS_PRICE_7
wp.Purchase_Price_Net = wp.SALE_NET_PRICE_7
wp.Purchase_Price_Tax = wp.SALE_TAX_AMOUNT_7
Case wp.SALE_PRICE_BREAK_QUANTITY_8 + 0.001 To wp.SALE_PRICE_BREAK_QUANTITY_9
wp.Purchase_Price_Gross = wp.SALE_GROSS_PRICE_8
wp.Purchase_Price_Net = wp.SALE_NET_PRICE_8
wp.Purchase_Price_Tax = wp.SALE_TAX_AMOUNT_8
Case wp.SALE_PRICE_BREAK_QUANTITY_9 + 0.001 To wp.SALE_PRICE_BREAK_QUANTITY_10
wp.Purchase_Price_Gross = wp.SALE_GROSS_PRICE_9
wp.Purchase_Price_Net = wp.SALE_NET_PRICE_9
wp.Purchase_Price_Tax = wp.SALE_TAX_AMOUNT_9
Case Is >= wp.SALE_PRICE_BREAK_QUANTITY_10 And wp.PRICE_BREAK_QUANTITY_10 > 0
wp.Purchase_Price_Gross = wp.SALE_GROSS_PRICE_10
wp.Purchase_Price_Net = wp.SALE_NET_PRICE_10
wp.Purchase_Price_Tax = wp.SALE_TAX_AMOUNT_10
Case Else
'the qty does not fall into a category which means that
'we probably sent in a 0 qty so set to 1st price break
wp.Purchase_Price_Gross = wp.SALE_GROSS_PRICE
wp.Purchase_Price_Net = wp.SALE_NET_PRICE
wp.Purchase_Price_Tax = wp.SALE_TAX_AMOUNT
End Select
wp.IsPartOfPromotion = True
wp.IsSalePrice = True
ElseIf wp.PRICE_BREAK_QUANTITY_1 = 0 Then
'if we are not in single SALE price mode, and we are not in sale price break mode
'check to see if we are in standard single price mode
wp.Purchase_Price_Gross = wp.GROSS_PRICE
wp.Purchase_Price_Net = wp.NET_PRICE
wp.Purchase_Price_Tax = wp.TAX_AMOUNT
wp.From_Price_Gross = wp.GROSS_PRICE
wp.From_Price_Net = wp.NET_PRICE
wp.From_Price_Tax = wp.TAX_AMOUNT
wp.IsPartOfPromotion = False
wp.IsSalePrice = False
Else
' otherwise we are in standard price break mode
' determine which is the last level of price break and set
' the quantity to be greater than the requested quantity
' so that the select will fall into the correct category.
' BF - Only if requested qty will not fall into any other qty.
' This is because we now need the price break qty's returned to the
' front end when requested qty = 0
If wp.PRICE_BREAK_QUANTITY_2 = 0 Then
If wp.RequestedQuantity > wp.PRICE_BREAK_QUANTITY_1 Then
wp.PRICE_BREAK_QUANTITY_2 = wp.RequestedQuantity + 10
End If
wp.From_Price_Gross = wp.GROSS_PRICE
wp.From_Price_Net = wp.NET_PRICE
wp.From_Price_Tax = wp.TAX_AMOUNT
ElseIf wp.PRICE_BREAK_QUANTITY_3 = 0 Then
If wp.RequestedQuantity > wp.PRICE_BREAK_QUANTITY_2 Then
wp.PRICE_BREAK_QUANTITY_3 = wp.RequestedQuantity + 10
End If
wp.From_Price_Gross = wp.GROSS_PRICE_2
wp.From_Price_Net = wp.NET_PRICE_2
wp.From_Price_Tax = wp.TAX_AMOUNT_2
ElseIf wp.PRICE_BREAK_QUANTITY_4 = 0 Then
If wp.RequestedQuantity > wp.PRICE_BREAK_QUANTITY_3 Then
wp.PRICE_BREAK_QUANTITY_4 = wp.RequestedQuantity + 10
End If
wp.From_Price_Gross = wp.GROSS_PRICE_3
wp.From_Price_Net = wp.NET_PRICE_3
wp.From_Price_Tax = wp.TAX_AMOUNT_3
ElseIf wp.PRICE_BREAK_QUANTITY_5 = 0 Then
If wp.RequestedQuantity > wp.PRICE_BREAK_QUANTITY_4 Then
wp.PRICE_BREAK_QUANTITY_5 = wp.RequestedQuantity + 10
End If
wp.From_Price_Gross = wp.GROSS_PRICE_4
wp.From_Price_Net = wp.NET_PRICE_4
wp.From_Price_Tax = wp.TAX_AMOUNT_4
ElseIf wp.PRICE_BREAK_QUANTITY_6 = 0 Then
If wp.RequestedQuantity > wp.PRICE_BREAK_QUANTITY_5 Then
wp.PRICE_BREAK_QUANTITY_6 = wp.RequestedQuantity + 10
End If
wp.From_Price_Gross = wp.GROSS_PRICE_5
wp.From_Price_Net = wp.NET_PRICE_5
wp.From_Price_Tax = wp.TAX_AMOUNT_5
ElseIf wp.PRICE_BREAK_QUANTITY_7 = 0 Then
If wp.RequestedQuantity > wp.PRICE_BREAK_QUANTITY_6 Then
wp.PRICE_BREAK_QUANTITY_7 = wp.RequestedQuantity + 10
End If
wp.From_Price_Gross = wp.GROSS_PRICE_6
wp.From_Price_Net = wp.NET_PRICE_6
wp.From_Price_Tax = wp.TAX_AMOUNT_6
ElseIf wp.PRICE_BREAK_QUANTITY_8 = 0 Then
If wp.RequestedQuantity > wp.PRICE_BREAK_QUANTITY_7 Then
wp.PRICE_BREAK_QUANTITY_8 = wp.RequestedQuantity + 10
End If
wp.From_Price_Gross = wp.GROSS_PRICE_7
wp.From_Price_Net = wp.NET_PRICE_7
wp.From_Price_Tax = wp.TAX_AMOUNT_7
ElseIf wp.PRICE_BREAK_QUANTITY_9 = 0 Then
If wp.RequestedQuantity > wp.PRICE_BREAK_QUANTITY_8 Then
wp.PRICE_BREAK_QUANTITY_9 = wp.RequestedQuantity + 10
End If
wp.From_Price_Gross = wp.GROSS_PRICE_8
wp.From_Price_Net = wp.NET_PRICE_8
wp.From_Price_Tax = wp.TAX_AMOUNT_8
ElseIf wp.PRICE_BREAK_QUANTITY_10 = 0 Then
If wp.RequestedQuantity > wp.PRICE_BREAK_QUANTITY_7 Then
wp.PRICE_BREAK_QUANTITY_10 = wp.RequestedQuantity + 10
End If
wp.From_Price_Gross = wp.GROSS_PRICE_9
wp.From_Price_Net = wp.NET_PRICE_9
wp.From_Price_Tax = wp.TAX_AMOUNT_9
Else
wp.From_Price_Gross = wp.GROSS_PRICE_10
wp.From_Price_Net = wp.NET_PRICE_10
wp.From_Price_Tax = wp.TAX_AMOUNT_10
End If
Select Case qty
Case wp.PRICE_BREAK_QUANTITY_1 To wp.PRICE_BREAK_QUANTITY_2
wp.Purchase_Price_Gross = wp.GROSS_PRICE
wp.Purchase_Price_Net = wp.NET_PRICE
wp.Purchase_Price_Tax = wp.TAX_AMOUNT
Case wp.PRICE_BREAK_QUANTITY_2 + 0.001 To wp.PRICE_BREAK_QUANTITY_3
wp.Purchase_Price_Gross = wp.GROSS_PRICE_2
wp.Purchase_Price_Net = wp.NET_PRICE_2
wp.Purchase_Price_Tax = wp.TAX_AMOUNT_2
Case wp.PRICE_BREAK_QUANTITY_3 + 0.001 To wp.PRICE_BREAK_QUANTITY_4
wp.Purchase_Price_Gross = wp.GROSS_PRICE_3
wp.Purchase_Price_Net = wp.NET_PRICE_3
wp.Purchase_Price_Tax = wp.TAX_AMOUNT_3
Case wp.PRICE_BREAK_QUANTITY_4 + 0.001 To wp.PRICE_BREAK_QUANTITY_5
wp.Purchase_Price_Gross = wp.GROSS_PRICE_4
wp.Purchase_Price_Net = wp.NET_PRICE_4
wp.Purchase_Price_Tax = wp.TAX_AMOUNT_4
Case wp.PRICE_BREAK_QUANTITY_5 + 0.001 To wp.PRICE_BREAK_QUANTITY_6
wp.Purchase_Price_Gross = wp.GROSS_PRICE_5
wp.Purchase_Price_Net = wp.NET_PRICE_5
wp.Purchase_Price_Tax = wp.TAX_AMOUNT_5
Case wp.PRICE_BREAK_QUANTITY_6 + 0.001 To wp.PRICE_BREAK_QUANTITY_7
wp.Purchase_Price_Gross = wp.GROSS_PRICE_6
wp.Purchase_Price_Net = wp.NET_PRICE_6
wp.Purchase_Price_Tax = wp.TAX_AMOUNT_6
Case wp.PRICE_BREAK_QUANTITY_7 + 0.001 To wp.PRICE_BREAK_QUANTITY_8
wp.Purchase_Price_Gross = wp.GROSS_PRICE_7
wp.Purchase_Price_Net = wp.NET_PRICE_7
wp.Purchase_Price_Tax = wp.TAX_AMOUNT_7
Case wp.PRICE_BREAK_QUANTITY_8 + 0.001 To wp.PRICE_BREAK_QUANTITY_9
wp.Purchase_Price_Gross = wp.GROSS_PRICE_8
wp.Purchase_Price_Net = wp.NET_PRICE_8
wp.Purchase_Price_Tax = wp.TAX_AMOUNT_8
Case wp.PRICE_BREAK_QUANTITY_9 + 0.001 To wp.PRICE_BREAK_QUANTITY_10
wp.Purchase_Price_Gross = wp.GROSS_PRICE_9
wp.Purchase_Price_Net = wp.NET_PRICE_9
wp.Purchase_Price_Tax = wp.TAX_AMOUNT_9
Case Is >= wp.PRICE_BREAK_QUANTITY_10
wp.Purchase_Price_Gross = wp.GROSS_PRICE_10
wp.Purchase_Price_Net = wp.NET_PRICE_10
wp.Purchase_Price_Tax = wp.TAX_AMOUNT_10
Case Else
'the qty does not fall into a category which means that
'we probably sent in a 0 qty so set to 1st price break
wp.Purchase_Price_Gross = wp.GROSS_PRICE
wp.Purchase_Price_Net = wp.NET_PRICE
wp.Purchase_Price_Tax = wp.TAX_AMOUNT
End Select
wp.IsPartOfPromotion = True
wp.IsSalePrice = False
End If
wp.PromotionInclusivePriceGross = wp.Purchase_Price_Gross
If Me.DisplayPriceIncVAT Then
wp.DisplayPrice = wp.Purchase_Price_Gross
wp.DisplayPrice_From = wp.From_Price_Gross
Else
wp.DisplayPrice = wp.Purchase_Price_Net
wp.DisplayPrice_From = wp.From_Price_Net
End If
Next
If incPromoCheck Then CheckProductPromotionStatus()
End Sub
Protected Sub CheckProductPromotionStatus()
Dim dbWebPrice As New DBWebPrice(Me.Products, Me.WebPriceSettings.PriceList, Me.WebPriceSettings.SecondaryPriceList)
dbWebPrice.Settings = Me.WebPriceSettings
Dim priceBreakDescriptions As New DataTable
priceBreakDescriptions = dbWebPrice.GetPriceBreakDescription("PriceBreak", "PriceBreak")
Dim description As String = ""
Dim dtPromotionsForRequiredProduct As DataTable = Nothing
Dim dep As New Talent.Common.DEPromotions(Me.WebPriceSettings.BasketHeaderID, _
Products, _
Me.WebPriceSettings.BusinessUnit, _
Me.WebPriceSettings.Username, _
Now, _
Me.WebPriceSettings.PromotionTypePriority, _
Me.WebPriceSettings.Language, _
Me.WebPriceSettings.Partner, _
Me.Total_Items_Value_Gross, _
Me.WebPriceSettings.PromotionCode, _
Me.Max_Delivery_Gross, _
Me.WebPriceSettings.InvalidPromotionCodeErrorMessage, _
Me.WebPriceSettings.TempOrderID, _
Me.WebPriceSettings.PriceList, _
Me.WebPriceSettings.PartnerGroup, _
Me.WebPriceSettings.SecondaryPriceList, _
Me.WebPriceSettings.UsersAttributeList)
Dim dbPromo As New DBPromotions
With dbPromo
.Dep = dep
.Settings = Settings
End With
dtPromotionsForRequiredProduct = dbPromo.GetPromotionStatusForReqProducts(Me.RetrievedPrices)
For Each wp As DEWebPrice In Me.RetrievedPrices.Values
If wp.IsPartOfPromotion Then
description = ""
For Each rw As DataRow In priceBreakDescriptions.Rows
If UCase(Utilities.CheckForDBNull_String(rw("DESCRIPTION_CODE"))) = UCase(wp.PRICE_BREAK_CODE) Then
description = Utilities.CheckForDBNull_String(rw("LANGUAGE_DESCRIPTION"))
Exit For
End If
Next
wp.PromotionDescriptionText = description
wp.PromotionImagePath = wp.PRICE_BREAK_CODE
Else
If dtPromotionsForRequiredProduct IsNot Nothing Then
Dim results As Generic.Dictionary(Of String, String) = GetProductPromotionStatus(wp.PRODUCT_CODE, dtPromotionsForRequiredProduct)
If Not results Is Nothing AndAlso results.Keys.Count > 0 Then
Dim _activationMechanism As String = String.Empty
If results.TryGetValue("PromotionActivationMechanism", _activationMechanism) Then
If _activationMechanism.Equals("AUTO") Then
wp.IsPartOfPromotion = True
wp.PromotionDescriptionText = results("DisplayName")
wp.PromotionImagePath = results("PromotionCode")
End If
End If
End If
End If
End If
Next
End Sub
Protected Sub EvaluatePricesWithPromotions()
CalculateTotals()
Dim dep As New Talent.Common.DEPromotions(Me.WebPriceSettings.BasketHeaderID, _
Products, _
Me.WebPriceSettings.BusinessUnit, _
Me.WebPriceSettings.Username, _
Now, _
Me.WebPriceSettings.PromotionTypePriority, _
Me.WebPriceSettings.Language, _
Me.WebPriceSettings.Partner, _
Me.Total_Items_Value_Gross, _
Me.WebPriceSettings.PromotionCode, _
Me.Max_Delivery_Gross, _
Me.WebPriceSettings.InvalidPromotionCodeErrorMessage, _
Me.WebPriceSettings.TempOrderID, _
Me.WebPriceSettings.PriceList, _
Me.WebPriceSettings.PartnerGroup, _
Me.WebPriceSettings.SecondaryPriceList, _
Me.WebPriceSettings.UsersAttributeList)
Dim promo As New Talent.Common.TalentPromotions
promo.Settings = New Talent.Common.DESettings
promo.Settings.FrontEndConnectionString = Me.WebPriceSettings.FrontEndConnectionString
promo.Settings.BusinessUnit = Me.WebPriceSettings.BusinessUnit
promo.Dep = dep
promo.ResultDataSet = Nothing
promo.ProcessPromotions(1)
Dim promoResults As New Data.DataTable
If Not promo.ResultDataSet Is Nothing AndAlso Not promo.ResultDataSet.Tables("PromotionResults") Is Nothing Then
promoResults = promo.ResultDataSet.Tables("PromotionResults")
If promoResults.Rows.Count > 0 Then
Me.PromotionsResultsTable = promoResults
CalculateDiscountedPrices()
ReAssessDeliveryCharges()
End If
End If
End Sub
Protected Sub ReAssessDeliveryCharges()
If Not PromotionsResultsTable Is Nothing AndAlso PromotionsResultsTable.Rows.Count > 0 Then
For Each result As DataRow In PromotionsResultsTable.Rows
If CBool(Utilities.CheckForDBNull_Boolean_DefaultFalse(result("FreeDelivery"))) Then
Me.Qualifies_For_Free_Delivery = True
Me.FreeDeliveryPromotion = True
Exit For 'exit loop if found
End If
Next
End If
End Sub
Protected Sub CalculateDiscountedPrices()
Dim NormalPrice As Decimal = 0
Dim newPrice As Decimal = 0
Try
If Not Me.PromotionsResultsTable Is Nothing AndAlso Me.PromotionsResultsTable.Rows.Count > 0 Then
For Each promo As DataRow In Me.PromotionsResultsTable.Rows
If Utilities.CheckForDBNull_Boolean_DefaultFalse(promo("Success")) Then
If Utilities.CheckForDBNull_Decimal(promo("PromotionValue")) > 0 Then
Me.Total_Promotions_Value += CDec(promo("PromotionValue"))
If Not String.IsNullOrEmpty(Utilities.CheckForDBNull_String(promo("ProductCodes"))) Then
Dim products() As String = Utilities.CheckForDBNull_String(promo("ProductCodes")).Split(",")
For Each code As String In products
Try
Dim wp As DEWebPrice = Me.RetrievedPrices(code)
If Not wp Is Nothing Then
NormalPrice = wp.Purchase_Price_Gross * wp.RequestedQuantity
newPrice = NormalPrice
If CDec(promo("PromotionValue")) <= (NormalPrice) Then
newPrice = NormalPrice - CDec(promo("PromotionValue"))
promo("PromotionValue") = 0
wp.PromotionInclusivePriceGross = newPrice / wp.RequestedQuantity
Exit For 'We have accounted for all of this promotion's value here, so exit the 'for' loop
ElseIf CDec(promo("PromotionValue")) > (NormalPrice) Then
newPrice = 0
promo("PromotionValue") = CDec(promo("PromotionValue")) - NormalPrice
wp.PromotionInclusivePriceGross = 0
End If
End If
Catch ex As Exception
End Try
Next
End If
End If
End If
Next
End If
Catch ex As Exception
End Try
End Sub
Protected Function GetFreeDeliveryValue() As Decimal
Dim dbWebPrice As New DBWebPrice(Me.Products, Me.WebPriceSettings.PriceList, Me.WebPriceSettings.SecondaryPriceList)
dbWebPrice.Settings = Me.WebPriceSettings
Return dbWebPrice.GetFreeDeliveryValue_SQL2005
End Function
Protected Function GetPropertyNames(ByVal obj As Object) As ArrayList
Dim al As New ArrayList
Dim inf() As System.Reflection.PropertyInfo = obj.GetType.GetProperties
For Each info As System.Reflection.PropertyInfo In inf
al.Add(info.Name)
Next
Return al
End Function
Protected Function PopulateProperties(ByVal propertiesList As ArrayList, _
ByVal dt As System.Data.DataTable, _
ByVal webPrice As DEWebPrice, _
ByVal rowIndex As Integer) As Object
If dt.Rows.Count > 0 Then
For i As Integer = 0 To propertiesList.Count - 1
If dt.Columns.Contains(propertiesList(i)) Then
CallByName(webPrice, _
propertiesList(i), _
CallType.Set, _
CheckDBNull(dt.Rows(rowIndex)(propertiesList(i))))
Else
'If the column does not exist, handle any properties on the class that we know of
Select Case UCase(propertiesList(i))
Case "PRODUCT_CODE"
webPrice.PRODUCT_CODE = Utilities.CheckForDBNull_String(dt.Rows(rowIndex)("PRODUCT"))
Case "REQUESTEDQUANTITY"
If Products.ContainsKey(Utilities.CheckForDBNull_String(dt.Rows(rowIndex)("PRODUCT"))) Then
webPrice.RequestedQuantity = Products(Utilities.CheckForDBNull_String(dt.Rows(rowIndex)("PRODUCT"))).Quantity
Else
webPrice.RequestedQuantity = 0
End If
End Select
End If
Next
End If
Return webPrice
End Function
Protected Function PopulateWebPriceEntity(ByVal dt As System.Data.DataTable, _
ByVal webPrice As DEWebPrice, _
ByVal rowIndex As Integer) As Object
If dt.Rows.Count > 0 Then
Dim priceListDataRow As DataRow = dt.Rows(rowIndex)
With webPrice
.DELIVERY_GROSS_PRICE = CheckDBNull(priceListDataRow("DELIVERY_GROSS_PRICE"))
.DELIVERY_NET_PRICE = CheckDBNull(priceListDataRow("DELIVERY_NET_PRICE"))
.DELIVERY_TAX_AMOUNT = CheckDBNull(priceListDataRow("DELIVERY_TAX_AMOUNT"))
.GROSS_PRICE = CheckDBNull(priceListDataRow("GROSS_PRICE"))
.GROSS_PRICE_10 = CheckDBNull(priceListDataRow("GROSS_PRICE_10"))
.GROSS_PRICE_2 = CheckDBNull(priceListDataRow("GROSS_PRICE_2"))
.GROSS_PRICE_3 = CheckDBNull(priceListDataRow("GROSS_PRICE_3"))
.GROSS_PRICE_4 = CheckDBNull(priceListDataRow("GROSS_PRICE_4"))
.GROSS_PRICE_5 = CheckDBNull(priceListDataRow("GROSS_PRICE_5"))
.GROSS_PRICE_6 = CheckDBNull(priceListDataRow("GROSS_PRICE_6"))
.GROSS_PRICE_7 = CheckDBNull(priceListDataRow("GROSS_PRICE_7"))
.GROSS_PRICE_8 = CheckDBNull(priceListDataRow("GROSS_PRICE_8"))
.GROSS_PRICE_9 = CheckDBNull(priceListDataRow("GROSS_PRICE_9"))
.NET_PRICE = CheckDBNull(priceListDataRow("NET_PRICE"))
.NET_PRICE_10 = CheckDBNull(priceListDataRow("NET_PRICE_10"))
.NET_PRICE_2 = CheckDBNull(priceListDataRow("NET_PRICE_2"))
.NET_PRICE_3 = CheckDBNull(priceListDataRow("NET_PRICE_3"))
.NET_PRICE_4 = CheckDBNull(priceListDataRow("NET_PRICE_4"))
.NET_PRICE_5 = CheckDBNull(priceListDataRow("NET_PRICE_5"))
.NET_PRICE_6 = CheckDBNull(priceListDataRow("NET_PRICE_6"))
.NET_PRICE_7 = CheckDBNull(priceListDataRow("NET_PRICE_7"))
.NET_PRICE_8 = CheckDBNull(priceListDataRow("NET_PRICE_8"))
.NET_PRICE_9 = CheckDBNull(priceListDataRow("NET_PRICE_9"))
.PRICE_BREAK_CODE = CheckDBNull(priceListDataRow("PRICE_BREAK_CODE"))
.PRICE_BREAK_QUANTITY_1 = CheckDBNull(priceListDataRow("PRICE_BREAK_QUANTITY_1"))
.PRICE_BREAK_QUANTITY_10 = CheckDBNull(priceListDataRow("PRICE_BREAK_QUANTITY_10"))
.PRICE_BREAK_QUANTITY_2 = CheckDBNull(priceListDataRow("PRICE_BREAK_QUANTITY_2"))
.PRICE_BREAK_QUANTITY_3 = CheckDBNull(priceListDataRow("PRICE_BREAK_QUANTITY_3"))
.PRICE_BREAK_QUANTITY_4 = CheckDBNull(priceListDataRow("PRICE_BREAK_QUANTITY_4"))
.PRICE_BREAK_QUANTITY_5 = CheckDBNull(priceListDataRow("PRICE_BREAK_QUANTITY_5"))
.PRICE_BREAK_QUANTITY_6 = CheckDBNull(priceListDataRow("PRICE_BREAK_QUANTITY_6"))
.PRICE_BREAK_QUANTITY_7 = CheckDBNull(priceListDataRow("PRICE_BREAK_QUANTITY_7"))
.PRICE_BREAK_QUANTITY_8 = CheckDBNull(priceListDataRow("PRICE_BREAK_QUANTITY_8"))
.PRICE_BREAK_QUANTITY_9 = CheckDBNull(priceListDataRow("PRICE_BREAK_QUANTITY_9"))
.PRODUCT_CODE = CheckDBNull(priceListDataRow("PRODUCT"))
If Products.ContainsKey(Utilities.CheckForDBNull_String(priceListDataRow("PRODUCT"))) Then
.RequestedQuantity = Products(Utilities.CheckForDBNull_String(dt.Rows(rowIndex)("PRODUCT"))).Quantity
Else
.RequestedQuantity = 0
End If
.SALE_GROSS_PRICE = CheckDBNull(priceListDataRow("SALE_GROSS_PRICE"))
.SALE_GROSS_PRICE_10 = CheckDBNull(priceListDataRow("SALE_GROSS_PRICE_10"))
.SALE_GROSS_PRICE_2 = CheckDBNull(priceListDataRow("SALE_GROSS_PRICE_2"))
.SALE_GROSS_PRICE_3 = CheckDBNull(priceListDataRow("SALE_GROSS_PRICE_3"))
.SALE_GROSS_PRICE_4 = CheckDBNull(priceListDataRow("SALE_GROSS_PRICE_4"))
.SALE_GROSS_PRICE_5 = CheckDBNull(priceListDataRow("SALE_GROSS_PRICE_5"))
.SALE_GROSS_PRICE_6 = CheckDBNull(priceListDataRow("SALE_GROSS_PRICE_6"))
.SALE_GROSS_PRICE_7 = CheckDBNull(priceListDataRow("SALE_GROSS_PRICE_7"))
.SALE_GROSS_PRICE_8 = CheckDBNull(priceListDataRow("SALE_GROSS_PRICE_8"))
.SALE_GROSS_PRICE_9 = CheckDBNull(priceListDataRow("SALE_GROSS_PRICE_9"))
.SALE_NET_PRICE = CheckDBNull(priceListDataRow("SALE_NET_PRICE"))
.SALE_NET_PRICE_10 = CheckDBNull(priceListDataRow("SALE_NET_PRICE_10"))
.SALE_NET_PRICE_2 = CheckDBNull(priceListDataRow("SALE_NET_PRICE_2"))
.SALE_NET_PRICE_3 = CheckDBNull(priceListDataRow("SALE_NET_PRICE_3"))
.SALE_NET_PRICE_4 = CheckDBNull(priceListDataRow("SALE_NET_PRICE_4"))
.SALE_NET_PRICE_5 = CheckDBNull(priceListDataRow("SALE_NET_PRICE_5"))
.SALE_NET_PRICE_6 = CheckDBNull(priceListDataRow("SALE_NET_PRICE_6"))
.SALE_NET_PRICE_7 = CheckDBNull(priceListDataRow("SALE_NET_PRICE_7"))
.SALE_NET_PRICE_8 = CheckDBNull(priceListDataRow("SALE_NET_PRICE_8"))
.SALE_NET_PRICE_9 = CheckDBNull(priceListDataRow("SALE_NET_PRICE_9"))
.SALE_PRICE_BREAK_QUANTITY_1 = CheckDBNull(priceListDataRow("SALE_PRICE_BREAK_QUANTITY_1"))
.SALE_PRICE_BREAK_QUANTITY_10 = CheckDBNull(priceListDataRow("SALE_PRICE_BREAK_QUANTITY_10"))
.SALE_PRICE_BREAK_QUANTITY_2 = CheckDBNull(priceListDataRow("SALE_PRICE_BREAK_QUANTITY_2"))
.SALE_PRICE_BREAK_QUANTITY_3 = CheckDBNull(priceListDataRow("SALE_PRICE_BREAK_QUANTITY_3"))
.SALE_PRICE_BREAK_QUANTITY_4 = CheckDBNull(priceListDataRow("SALE_PRICE_BREAK_QUANTITY_4"))
.SALE_PRICE_BREAK_QUANTITY_5 = CheckDBNull(priceListDataRow("SALE_PRICE_BREAK_QUANTITY_5"))
.SALE_PRICE_BREAK_QUANTITY_6 = CheckDBNull(priceListDataRow("SALE_PRICE_BREAK_QUANTITY_6"))
.SALE_PRICE_BREAK_QUANTITY_7 = CheckDBNull(priceListDataRow("SALE_PRICE_BREAK_QUANTITY_7"))
.SALE_PRICE_BREAK_QUANTITY_8 = CheckDBNull(priceListDataRow("SALE_PRICE_BREAK_QUANTITY_8"))
.SALE_PRICE_BREAK_QUANTITY_9 = CheckDBNull(priceListDataRow("SALE_PRICE_BREAK_QUANTITY_9"))
.SALE_TAX_AMOUNT = CheckDBNull(priceListDataRow("SALE_TAX_AMOUNT"))
.SALE_TAX_AMOUNT_10 = CheckDBNull(priceListDataRow("SALE_TAX_AMOUNT_10"))
.SALE_TAX_AMOUNT_2 = CheckDBNull(priceListDataRow("SALE_TAX_AMOUNT_2"))
.SALE_TAX_AMOUNT_3 = CheckDBNull(priceListDataRow("SALE_TAX_AMOUNT_3"))
.SALE_TAX_AMOUNT_4 = CheckDBNull(priceListDataRow("SALE_TAX_AMOUNT_4"))
.SALE_TAX_AMOUNT_5 = CheckDBNull(priceListDataRow("SALE_TAX_AMOUNT_5"))
.SALE_TAX_AMOUNT_6 = CheckDBNull(priceListDataRow("SALE_TAX_AMOUNT_6"))
.SALE_TAX_AMOUNT_7 = CheckDBNull(priceListDataRow("SALE_TAX_AMOUNT_7"))
.SALE_TAX_AMOUNT_8 = CheckDBNull(priceListDataRow("SALE_TAX_AMOUNT_8"))
.SALE_TAX_AMOUNT_9 = CheckDBNull(priceListDataRow("SALE_TAX_AMOUNT_9"))
.TARIFF_CODE = CheckDBNull(priceListDataRow("TARIFF_CODE"))
.TAX_AMOUNT = CheckDBNull(priceListDataRow("TAX_AMOUNT"))
.TAX_AMOUNT_10 = CheckDBNull(priceListDataRow("TAX_AMOUNT_10"))
.TAX_AMOUNT_2 = CheckDBNull(priceListDataRow("TAX_AMOUNT_2"))
.TAX_AMOUNT_3 = CheckDBNull(priceListDataRow("TAX_AMOUNT_3"))
.TAX_AMOUNT_4 = CheckDBNull(priceListDataRow("TAX_AMOUNT_4"))
.TAX_AMOUNT_5 = CheckDBNull(priceListDataRow("TAX_AMOUNT_5"))
.TAX_AMOUNT_6 = CheckDBNull(priceListDataRow("TAX_AMOUNT_6"))
.TAX_AMOUNT_7 = CheckDBNull(priceListDataRow("TAX_AMOUNT_7"))
.TAX_AMOUNT_8 = CheckDBNull(priceListDataRow("TAX_AMOUNT_8"))
.TAX_AMOUNT_9 = CheckDBNull(priceListDataRow("TAX_AMOUNT_9"))
.TAX_CODE = CheckDBNull(priceListDataRow("TAX_CODE"))
End With
End If
Return webPrice
End Function
Private Function GetProductPromotionStatus(ByVal productCode As String, ByVal dtPromotions As DataTable) As Generic.Dictionary(Of String, String)
Dim results As New Generic.Dictionary(Of String, String)
If Not dtPromotions Is Nothing AndAlso dtPromotions.Rows.Count > 0 Then
Dim datarows As DataRowCollection = Nothing
Dim dvPromotions As New DataView
dtPromotions.DefaultView.RowFilter = "PRODUCT_CODE = '" & productCode & "' AND BUSINESS_UNIT = '" & Me.WebPriceSettings.BusinessUnit & "' AND PARTNER_GROUP = '" & Me.WebPriceSettings.PartnerGroup & "' AND PARTNER = '" & Me.WebPriceSettings.Partner & "' "
dvPromotions = dtPromotions.DefaultView
If dvPromotions.Count > 0 Then
datarows = dvPromotions.ToTable.Rows
Else
dtPromotions.DefaultView.RowFilter = "PRODUCT_CODE = '" & productCode & "' AND BUSINESS_UNIT = '" & Me.WebPriceSettings.BusinessUnit & "' AND PARTNER_GROUP = '" & Me.WebPriceSettings.PartnerGroup & "' AND PARTNER = '" & Utilities.GetAllString & "' "
dvPromotions = dtPromotions.DefaultView
If dvPromotions.Count > 0 Then
datarows = dvPromotions.ToTable.Rows
Else
dtPromotions.DefaultView.RowFilter = "PRODUCT_CODE = '" & productCode & "' AND BUSINESS_UNIT = '" & Me.WebPriceSettings.BusinessUnit & "' AND PARTNER_GROUP = '" & Utilities.GetAllString & "' AND PARTNER = '" & Utilities.GetAllString & "' "
dvPromotions = dtPromotions.DefaultView
If dvPromotions.Count > 0 Then
datarows = dvPromotions.ToTable.Rows
Else
dtPromotions.DefaultView.RowFilter = "PRODUCT_CODE = '" & productCode & "' AND BUSINESS_UNIT = '" & Utilities.GetAllString & "' AND PARTNER_GROUP = '" & Utilities.GetAllString & "' AND PARTNER = '" & Utilities.GetAllString & "' "
dvPromotions = dtPromotions.DefaultView
If dvPromotions.Count > 0 Then
datarows = dvPromotions.ToTable.Rows
End If
End If
End If
End If
If datarows IsNot Nothing Then
Dim promo As DataRow = datarows(0)
results.Add("PromotionCode", Utilities.CheckForDBNull_String(promo("PROMOTION_CODE")))
results.Add("PromotionType", Utilities.CheckForDBNull_String(promo("PROMOTION_TYPE")))
results.Add("PromotionActivationMechanism", Utilities.CheckForDBNull_String(promo("ACTIVATION_MECHANISM")))
results.Add("DisplayName", Utilities.CheckForDBNull_String(promo("DISPLAY_NAME")))
End If
dtPromotions.DefaultView.RowFilter = ""
End If
Return results
End Function
End Class
|
':: Class that is used for in-game sound effects ::
Public Class SndChanB
Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" _
(ByVal lpstrCommand As String, ByVal lpstrReturnString As String, _
ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer
Private strAudioLen As String = New String(CChar(" "), 128)
':: Properties for this class ::
Private SndToPLay As String
Public Sub New(ByVal Snd As String)
'------------------------------------------------------------------------------------------------------------------
' Purpose: Constructor for creating an instance of this class
'------------------------------------------------------------------------------------------------------------------
Me.SndToPLay = Snd
End Sub
Public Sub Open()
'------------------------------------------------------------------------------------------------------------------
' Purpose: Open audio file
'------------------------------------------------------------------------------------------------------------------
Dim Path As String
Path = CurDir() & "\" & Me.SndToPLay
mciSendString("close myaudio", "", 0, 0)
mciSendString("open """ & Path & """ alias myaudio", "", 0, 0)
mciSendString("set myaudio time format ms", "", 0, 0)
mciSendString("status myaudio length", strAudioLen, 128, 0)
End Sub
Public Sub Close()
'------------------------------------------------------------------------------------------------------------------
' Purpose: Close audio file
'------------------------------------------------------------------------------------------------------------------
mciSendString("close myaudio", "", 0, 0)
End Sub
Public Sub PlaySnd()
'------------------------------------------------------------------------------------------------------------------
' Purpose: Play audio file
'------------------------------------------------------------------------------------------------------------------
mciSendString("play myaudio", "", 0, 0)
End Sub
Public Sub StartFrom(ByVal Milliseconds As Integer)
'------------------------------------------------------------------------------------------------------------------
' Purpose: Play audio file from (n) mS position
'------------------------------------------------------------------------------------------------------------------
mciSendString("play myaudio from " & Milliseconds.ToString, "", 0, 0)
End Sub
End Class
|
Public Class TinhHinhMuonSachDTO
Private strTenTheLoai As String
Private iSoLuotMuon As Integer
Private iTiLe As Integer
Public Sub New()
End Sub
Public Sub New(strTenTheLoai As String, iSoLanMuon As Integer, iTiLe As Integer)
Me.strTenTheLoai = strTenTheLoai
Me.iSoLuotMuon = iSoLanMuon
Me.iTiLe = iTiLe
End Sub
Public Property TenTheLoai As String
Get
Return strTenTheLoai
End Get
Set(value As String)
strTenTheLoai = value
End Set
End Property
Public Property SoLuotMuon As Integer
Get
Return iSoLuotMuon
End Get
Set(value As Integer)
iSoLuotMuon = value
End Set
End Property
Public Property TiLe As Integer
Get
Return iTiLe
End Get
Set(value As Integer)
iTiLe = value
End Set
End Property
Public Function Clone() As TinhHinhMuonSachDTO
Return Me.MemberwiseClone()
End Function
End Class
|
' ***********************************************************************
' Assembly : FakeSteam
' Author : Elektro
' Modified : 03-May-2015
' ***********************************************************************
' <copyright file="Main.vb" company="Elektro Studios">
' Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************
#Region " Option Statements "
Option Explicit On
Option Strict On
Option Infer Off
#End Region
#Region " Imports "
Imports FakeSteam.Config
Imports FakeSteam.Tools
Imports FakeSteam.UserControls
Imports System.Globalization
Imports System.Threading
Imports System.Threading.Tasks
#End Region
Namespace UserInterface
''' <summary>
''' The <see cref="Main" /> user-interface Form.
''' </summary>
Public NotInheritable Class Main
#Region " Objects"
#Region " Form "
''' <summary>
''' The <see cref="FormDragger"/> instance that manages the form(s) dragging.
''' </summary>
Friend Shared FormDragger As FormDragger
''' <summary>
''' The child <see cref="TextBox"/> of the <see cref="ElektroTextBox_Username"/> instance.
''' </summary>
Private WithEvents usernameChildTb As TextBox
''' <summary>
''' The child <see cref="TextBox"/> of the <see cref="ElektroTextBox_Password"/> instance.
''' </summary>
Private WithEvents passwordChildTb As TextBox
#End Region
#Region " Imaging "
''' <summary>
''' The background image of the titlebar-title area.
''' </summary>
Private bgTitle As Bitmap
''' <summary>
''' The background image of the mnimize-button area.
''' </summary>
Private bgMinimizeButton As Bitmap
''' <summary>
''' The background image of the close-button area.
''' </summary>
Private bgCloseButton As Bitmap
''' <summary>
''' The background image of the username-label area.
''' </summary>
Private bgUsernameLabel As Bitmap
''' <summary>
''' The background image of the password-label area.
''' </summary>
Private bgPasswordLabel As Bitmap
''' <summary>
''' The background image of the remember-checkbox area.
''' </summary>
Private bgRememberCheckbox As Bitmap
''' <summary>
''' The background image of the login-button area.
''' </summary>
Private bgLoginButton As Bitmap
''' <summary>
''' The background image of the cancel-button area.
''' </summary>
Private bgCancelButton As Bitmap
''' <summary>
''' The background image of the createAccount-button area.
''' </summary>
Private bgCreateAccountButton As Bitmap
''' <summary>
''' The background image of the lostAccount-button area.
''' </summary>
Private bgLostAccountButton As Bitmap
#End Region
#Region " Debug "
#If DEBUG Then
''' <summary>
''' The control to test.
''' </summary>
Private debugPictureBox As PictureBox
''' <summary>
''' The background bitmap to test.
''' </summary>
Private debugBitmap As Bitmap
''' <summary>
''' The current Brightness value.
''' </summary>
Private debugBrightness As Single = 1.0F
''' <summary>
''' The current Contrast value.
''' </summary>
Private debugContrast As Single = 1.0F
''' <summary>
''' The current Gamma value.
''' </summary>
Private debugGamma As Single = 1.0F
#End If
#End Region
#End Region
#Region " Event-Handlers "
#Region " Form "
''' <summary>
''' Handles the <see cref="Form.Load"/> event of the <see cref="Main"/> form.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub Main_Load(ByVal sender As Object, ByVal e As EventArgs) _
Handles MyBase.Load
Me.usernameChildTb = Me.ElektroTextBox_Username.TextBox
Me.passwordChildTb = Me.ElektroTextBox_Password.TextBox
Me.LoadInterfaceLanguage()
Me.LoadAppSettings()
End Sub
''' <summary>
''' Handles the <see cref="Form.Shown"/> event of the <see cref="Main"/> form.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub Main_Shown(ByVal sender As Object, ByVal e As EventArgs) _
Handles MyBase.Shown
If FormDragger Is Nothing Then
FormDragger = New FormDragger
FormDragger.AddForm(Me, enabled:=True)
End If
#If DEBUG Then
Me.InitializeDebugTesting()
#End If
End Sub
''' <summary>
''' Handles the <see cref="Form.Activated"/> event of the <see cref="Main"/> form.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub Main_Activated(ByVal sender As Object, ByVal e As EventArgs) _
Handles MyBase.Activated
ImageUtil.RedrawBackground(Me.PictureBox_Title, Me.bgTitle, brightness:=1.0F, contrast:=1.6F, gamma:=1.3F)
End Sub
''' <summary>
''' Handles the <see cref="Form.Deactivate"/> event of the <see cref="Main"/> form.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub Main_Deactivate(ByVal sender As Object, ByVal e As EventArgs) _
Handles MyBase.Deactivate
Me.ResetBackgrounds()
Me.DisableBorders()
End Sub
#End Region
#Region " Minimize Button (PictureBox) "
''' <summary>
''' Handles the <see cref="PictureBox.MouseEnter"/> event of the <see cref="PictureBox_MinimizeButton"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_MinimizeButton_MouseEnter(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_MinimizeButton.MouseEnter
ImageUtil.RedrawBackground(DirectCast(sender, PictureBox), Me.bgMinimizeButton, brightness:=1.0F, contrast:=1.3F, gamma:=1.15F)
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.Click"/> event of the <see cref="PictureBox_MinimizeButton"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_MinimizeButton_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_MinimizeButton.Click
Me.WindowState = FormWindowState.Minimized
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.MouseLeave"/> event of the <see cref="PictureBox_MinimizeButton"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_MinimizeButton_MouseLeave(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_MinimizeButton.MouseLeave
DirectCast(sender, PictureBox).BackgroundImage = Nothing
End Sub
#End Region
#Region " Close Button (PictureBox) "
''' <summary>
''' Handles the <see cref="PictureBox.MouseEnter"/> event of the <see cref="PictureBox_CloseButton"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_CloseButton_MouseEnter(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_CloseButton.MouseEnter
ImageUtil.RedrawBackground(DirectCast(sender, PictureBox), Me.bgCloseButton, brightness:=1.0F, contrast:=1.3F, gamma:=1.15F)
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.Click"/> event of the <see cref="PictureBox_CloseButton"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_CloseButton_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_CloseButton.Click
Me.Close()
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.MouseLeave"/> event of the <see cref="PictureBox_CloseButton"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_CloseButton_MouseLeave(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_CloseButton.MouseLeave
DirectCast(sender, PictureBox).BackgroundImage = Nothing
End Sub
#End Region
#Region " Username TextBox (TextBox) "
''' <summary>
''' Handles the <see cref="ElektroTextBox.Enter"/> and <see cref="Textbox.GotFocus"/> event of the <see cref="ElektroTextBox_Username"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub ElektroTextBox_Username_Enter_Or_GotFocus(ByVal sender As Object, ByVal e As EventArgs) _
Handles ElektroTextBox_Username.Enter,
usernameChildTb.GotFocus
Me.ElektroTextBox_Username.ShowBorder = True
ImageUtil.RedrawBackground(Me.PictureBox_Username, Me.bgUsernameLabel, brightness:=1.0F, contrast:=1.3F, gamma:=1.15F)
End Sub
''' <summary>
''' Handles the <see cref="ElektroTextBox.Leave"/> event of the <see cref="ElektroTextBox_Username"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub ElektroTextBox_Username_Leave(ByVal sender As Object, ByVal e As EventArgs) _
Handles ElektroTextBox_Username.Leave
DirectCast(sender, ElektroTextBox).ShowBorder = False
Me.PictureBox_Username.BackgroundImage = Nothing
End Sub
#End Region
#Region " Password TextBox (TextBox) "
''' <summary>
''' Handles the <see cref="ElektroTextBox.Enter"/> and <see cref="Textbox.GotFocus"/> event of the <see cref="ElektroTextBox_Password"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub ElektroTextBox_Password_Enter_Or_GotFocus(ByVal sender As Object, ByVal e As EventArgs) _
Handles ElektroTextBox_Password.Enter,
passwordChildTb.GotFocus
Me.ElektroTextBox_Password.ShowBorder = True
ImageUtil.RedrawBackground(Me.PictureBox_Password, Me.bgPasswordLabel, brightness:=1.0F, contrast:=1.3F, gamma:=1.15F)
End Sub
''' <summary>
''' Handles the <see cref="ElektroTextBox.Leave"/> event of the <see cref="ElektroTextBox_Password"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub ElektroTextBox_Password_Leave(ByVal sender As Object, ByVal e As EventArgs) _
Handles ElektroTextBox_Password.Leave
DirectCast(sender, ElektroTextBox).ShowBorder = False
Me.PictureBox_Password.BackgroundImage = Nothing
End Sub
#End Region
#Region " Username/Password Child TextBoxes "
''' <summary>
''' Handles the <see cref="TextBox.TextChanged"/> event of the <see cref="usernameChildTb"/> control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub UsernameChildTb_TextChanged(ByVal sender As Object, ByVal e As EventArgs) _
Handles usernameChildTb.TextChanged
My.Settings.lastUsername = DirectCast(sender, TextBox).Text
End Sub
''' <summary>
''' Handles the <see cref="TextBox.TextChanged"/> event of the <see cref="passwordChildTb"/> control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PasswordChildTb_TextChanged(ByVal sender As Object, ByVal e As EventArgs) _
Handles passwordChildTb.TextChanged
My.Settings.lastPassword = DirectCast(sender, TextBox).Text
End Sub
''' <summary>
''' Handles the <see cref="TextBox.TextChanged"/> event of the <see cref="usernameChildTb"/> and <see cref="passwordChildTb"/> controls.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub ChildTb_TextChanged(ByVal sender As Object, ByVal e As EventArgs) _
Handles usernameChildTb.TextChanged,
passwordChildTb.TextChanged
If Not String.IsNullOrEmpty(usernameChildTb.Text) AndAlso Not String.IsNullOrEmpty(passwordChildTb.Text) Then
Me.PictureBox_Login.Enabled = True
ImageUtil.RedrawBackground(Me.PictureBox_Login, Me.bgLoginButton, brightness:=0.96F, contrast:=1.925F, gamma:=1.025F)
Else
Me.PictureBox_Login.BackgroundImage = Nothing
Me.PictureBox_Login.Enabled = False
End If
End Sub
''' <summary>
''' Handles the <see cref="TextBox.KeyDown"/> event of the
''' <see cref="usernameChildTb"/> and <see cref="passwordChildTb"/> controls.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="KeyEventArgs"/> instance containing the event data.</param>
Private Sub ChildTb_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) _
Handles usernameChildTb.KeyDown,
passwordChildTb.KeyDown
If (e.KeyCode = Keys.Enter) AndAlso
(Not String.IsNullOrEmpty(usernameChildTb.Text)) AndAlso
(Not String.IsNullOrEmpty(passwordChildTb.Text)) Then
Me.PictureBox_Login.PerformClick()
End If
End Sub
#End Region
#Region " Remember Password (CheckBox) "
''' <summary>
''' Handles the <see cref="ElektroCheckBox.Enter"/> and <see cref="ElektroCheckBox.GotFocus"/> event of the <see cref="ElektroCheckBox_Remember"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub ElektroCheckBox_Remember_Enter_Or_GotFocus(ByVal sender As Object, ByVal e As EventArgs) _
Handles ElektroCheckBox_Remember.Enter,
ElektroCheckBox_Remember.GotFocus
DirectCast(sender, ElektroCheckBox).BorderColor = Color.FromArgb(137, 137, 137)
ImageUtil.RedrawBackground(Me.PictureBox_Remember, Me.bgRememberCheckbox, brightness:=1.0F, contrast:=1.3F, gamma:=1.15F)
End Sub
''' <summary>
''' Handles the <see cref="ElektroCheckBox.Leave"/> and <see cref="ElektroCheckBox.LostFocus"/> event of the <see cref="ElektroCheckBox_Remember"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub ElektroCheckBox_Remember_Leave_Or_LostFocus(ByVal sender As Object, ByVal e As EventArgs) _
Handles ElektroCheckBox_Remember.Leave,
ElektroCheckBox_Remember.LostFocus
DirectCast(sender, ElektroCheckBox).BorderColor = Color.FromArgb(87, 87, 87)
Me.PictureBox_Remember.BackgroundImage = Nothing
End Sub
''' <summary>
''' Handles the <see cref="ElektroCheckBox.CheckedChanged"/> event of the <see cref="ElektroCheckBox_Remember"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub ElektroCheckBox_Remember_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) _
Handles ElektroCheckBox_Remember.CheckedChanged
My.Settings.rememberPassword = DirectCast(sender, ElektroCheckBox).Checked
End Sub
#End Region
#Region " Remember Password (PictureBox) "
''' <summary>
''' Handles the <see cref="PictureBox.MouseDown"/> event of the <see cref="PictureBox_Remember"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_Remember_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) _
Handles PictureBox_Remember.MouseDown
Me.ElektroCheckBox_Remember.Focus()
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.Click"/> event of the <see cref="PictureBox_Remember"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_Remember_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_Remember.Click
Me.ElektroCheckBox_Remember.Checked = Not Me.ElektroCheckBox_Remember.Checked
End Sub
#End Region
#Region " Login Button (PictureBox) "
''' <summary>
''' Handles the <see cref="PictureBox.MouseEnter"/> event of the <see cref="PictureBox_Login"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_Login_MouseEnter(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_Login.MouseEnter
ImageUtil.RedrawBackground(DirectCast(sender, PictureBox), Me.bgLoginButton, brightness:=1.0F, contrast:=2.3F, gamma:=1.25F)
Me.PictureBox_Login.BackgroundImage = ImageUtil.OverlayImages(My.Resources.Button, Me.PictureBox_Login.BackgroundImage, 0, 0, 0.75F)
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.MouseDown"/> event of the <see cref="PictureBox_Login"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_Login_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) _
Handles PictureBox_Login.MouseDown
ImageUtil.RedrawBackground(DirectCast(sender, PictureBox), Me.bgLoginButton, brightness:=1.0F, contrast:=2.3F, gamma:=1.65F)
Me.PictureBox_Login.BackgroundImage = ImageUtil.OverlayImages(My.Resources.Button, Me.PictureBox_Login.BackgroundImage, 0, 0, 0.75F)
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.Click"/> event of the <see cref="PictureBox_Login"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_Login_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_Login.Click
Task.Factory.StartNew(Sub()
StorageUtil.ManagePassword(username:=My.Settings.lastUsername, password:=My.Settings.lastPassword)
End Sub)
Me.Opacity = 0.0R
ErrorDialog.ShowDialog()
Me.CenterForm(ErrorDialog)
Me.Opacity = 1.0R
Me.BringToFront()
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.MouseLeave"/> event of the <see cref="PictureBox_Login"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_Login_MouseLeave(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_Login.MouseLeave
If Not String.IsNullOrEmpty(My.Settings.lastUsername) AndAlso Not String.IsNullOrEmpty(My.Settings.lastPassword) Then
ImageUtil.RedrawBackground(Me.PictureBox_Login, Me.bgLoginButton, brightness:=0.96F, contrast:=1.925F, gamma:=1.075F)
Me.PictureBox_Login.BackgroundImage = ImageUtil.OverlayImages(My.Resources.Button, Me.PictureBox_Login.BackgroundImage, 0, 0, 0.75F)
Else
DirectCast(sender, PictureBox).BackgroundImage = Nothing
End If
End Sub
#End Region
#Region " Cancel Button (PictureBox) "
''' <summary>
''' Handles the <see cref="PictureBox.MouseEnter"/> event of the <see cref="PictureBox_Cancel"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_Cancel_MouseEnter(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_Cancel.MouseEnter
ImageUtil.RedrawBackground(DirectCast(sender, PictureBox), Me.bgCancelButton, brightness:=1.0F, contrast:=1.3F, gamma:=1.15F)
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.MouseDown"/> event of the <see cref="PictureBox_Cancel"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_Cancel_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) _
Handles PictureBox_Cancel.MouseDown
ImageUtil.RedrawBackground(DirectCast(sender, PictureBox), Me.bgCancelButton, brightness:=1.0F, contrast:=1.3F, gamma:=1.65F)
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.Click"/> event of the <see cref="PictureBox_Cancel"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_Cancel_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_Cancel.Click
Me.Close()
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.MouseLeave"/> event of the <see cref="PictureBox_Cancel"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_Cancel_MouseLeave(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_Cancel.MouseLeave
DirectCast(sender, PictureBox).BackgroundImage = Nothing
End Sub
#End Region
#Region " Create Account Button (PictureBox) "
''' <summary>
''' Handles the <see cref="PictureBox.MouseEnter"/> event of the <see cref="PictureBox_CreateAccount"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_CreateAccount_MouseEnter(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_CreateAccount.MouseEnter
ImageUtil.RedrawBackground(DirectCast(sender, PictureBox), Me.bgCreateAccountButton, brightness:=1.0F, contrast:=1.3F, gamma:=1.15F)
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.MouseDown"/> event of the <see cref="PictureBox_CreateAccount"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_CreateAccount_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) _
Handles PictureBox_CreateAccount.MouseDown
ImageUtil.RedrawBackground(DirectCast(sender, PictureBox), Me.bgCreateAccountButton, brightness:=1.0F, contrast:=1.3F, gamma:=1.65F)
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.Click"/> event of the <see cref="PictureBox_CreateAccount"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_CreateAccount_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_CreateAccount.Click
Me.Opacity = 0.0R
CreateAccount.ShowDialog()
Me.CenterForm(CreateAccount)
Me.Opacity = 1.0R
Me.BringToFront()
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.MouseLeave"/> event of the <see cref="PictureBox_CreateAccount"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_CreateAccount_MouseLeave(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_CreateAccount.MouseLeave
DirectCast(sender, PictureBox).BackgroundImage = Nothing
End Sub
#End Region
#Region " Lost Account Button (PictureBox) "
''' <summary>
''' Handles the <see cref="PictureBox.MouseEnter"/> event of the <see cref="PictureBox_LostAccount"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_LostAccount_MouseEnter(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_LostAccount.MouseEnter
ImageUtil.RedrawBackground(DirectCast(sender, PictureBox), Me.bgLostAccountButton, brightness:=1.0F, contrast:=1.3F, gamma:=1.15F)
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.MouseDown"/> event of the <see cref="PictureBox_LostAccount"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_LostAccount_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) _
Handles PictureBox_LostAccount.MouseDown
ImageUtil.RedrawBackground(DirectCast(sender, PictureBox), Me.bgLostAccountButton, brightness:=1.0F, contrast:=1.3F, gamma:=1.65F)
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.Click"/> event of the <see cref="PictureBox_LostAccount"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_LostAccount_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_LostAccount.Click
Me.Opacity = 0.0R
CreateAccount.ShowDialog()
Me.CenterForm(CreateAccount)
Me.Opacity = 1.0R
Me.BringToFront()
End Sub
''' <summary>
''' Handles the <see cref="PictureBox.MouseLeave"/> event of the <see cref="PictureBox_LostAccount"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub PictureBox_LostAccount_MouseLeave(ByVal sender As Object, ByVal e As EventArgs) _
Handles PictureBox_LostAccount.MouseLeave
DirectCast(sender, PictureBox).BackgroundImage = Nothing
End Sub
#End Region
#Region " All Buttom PictureBoxes "
''' <summary>
''' Handles the <see cref="ElektroPictureBox.KeyDown"/> event of the
''' <see cref="PictureBox_Cancel"/>, <see cref="PictureBox_CreateAccount"/>,
''' <see cref="PictureBox_Login"/>, and <see cref="PictureBox_LostAccount"/> controls.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="KeyEventArgs"/> instance containing the event data.</param>
Private Sub PictureBoxes_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) _
Handles PictureBox_Cancel.KeyDown,
PictureBox_CreateAccount.KeyDown,
PictureBox_Login.KeyDown,
PictureBox_LostAccount.KeyDown
If e.KeyCode = Keys.Enter Then
DirectCast(sender, ElektroPictureBox).PerformClick()
End If
End Sub
#End Region
#Region " Debug TrackBars "
#If DEBUG Then
''' <summary>
''' Handles the <see cref="TrackBar.Scroll"/> event of the <see cref="TrackBar_Brightness"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub TrackBar_Brightness_Scroll(ByVal sender As Object, ByVal e As EventArgs) _
Handles TrackBar_Brightness.Scroll
Me.debugBrightness = Convert.ToSingle(DirectCast(sender, TrackBar).Value / 1000)
Me.Label_Brightness_Value.Text = Me.debugBrightness.ToString("0.000")
ImageUtil.RedrawBackground(Me.debugPictureBox, Me.debugBitmap, brightness:=Me.debugBrightness, contrast:=Me.debugContrast, gamma:=Me.debugGamma)
End Sub
''' <summary>
''' Handles the <see cref="TrackBar.Scroll"/> event of the <see cref="TrackBar_Contrast"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub TrackBar_Contrast_Scroll(ByVal sender As Object, ByVal e As EventArgs) _
Handles TrackBar_Contrast.Scroll
Me.debugContrast = Convert.ToSingle(DirectCast(sender, TrackBar).Value / 1000)
Me.Label_Contrast_Value.Text = Me.debugContrast.ToString("0.000")
ImageUtil.RedrawBackground(Me.debugPictureBox, Me.debugBitmap, brightness:=Me.debugBrightness, contrast:=Me.debugContrast, gamma:=Me.debugGamma)
End Sub
''' <summary>
''' Handles the <see cref="TrackBar.Scroll"/> event of the <see cref="TrackBar_Gamma"/> Control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub TrackBar_Gamma_Scroll(ByVal sender As Object, ByVal e As EventArgs) _
Handles TrackBar_Gamma.Scroll
Me.debugGamma = Convert.ToSingle(DirectCast(sender, TrackBar).Value / 1000)
Me.Label_Gamma_Value.Text = Me.debugGamma.ToString("0.000")
ImageUtil.RedrawBackground(Me.debugPictureBox, Me.debugBitmap, brightness:=Me.debugBrightness, contrast:=Me.debugContrast, gamma:=Me.debugGamma)
End Sub
#End If
#End Region
#End Region
#Region " Methods "
''' <summary>
''' Loads the user interface language.
''' </summary>
Private Sub LoadInterfaceLanguage()
Dim culture As CultureInfo
Dim titleResource As Object = Nothing
Dim mainFormResource As Object = Nothing
Dim errorDialogResource As Object = Nothing
Dim createAccountResource As Object = Nothing
' Set the language culture.
If UserConfig.UseDefaultSteamLanguage Then
culture = UserConfig.DefaultSteamLanguage
Else
culture = SteamHelper.GetClientCulture
' If the culture is not detected, set the O.S. culture.
If culture Is Nothing Then
culture = Thread.CurrentThread.CurrentCulture
End If
End If
' Load the title resource.
titleResource = My.Resources.ResourceManager.GetObject(String.Format("{0}_Title", culture.Name.Replace("-"c, "_"c)))
' Load the Main background image resource.
mainFormResource = My.Resources.ResourceManager.GetObject(String.Format("{0}_Main", culture.Name.Replace("-"c, "_"c)))
' Load the ErrorDialog background image resource.
errorDialogResource = My.Resources.ResourceManager.GetObject(String.Format("{0}_ErrorDialog", culture.Name.Replace("-"c, "_"c)))
' Load the CreateAccount background image resource.
createAccountResource = My.Resources.ResourceManager.GetObject(String.Format("{0}_CreateAccount", culture.Name.Replace("-"c, "_"c)))
' If one of the resources failed to load, fix all.
If (titleResource Is Nothing) OrElse
(mainFormResource Is Nothing) OrElse
(errorDialogResource Is Nothing) OrElse
(createAccountResource Is Nothing) Then
titleResource = My.Resources.en_US_Title
mainFormResource = My.Resources.en_US_Main
errorDialogResource = My.Resources.en_US_ErrorDialog
createAccountResource = My.Resources.en_US_CreateAccount
End If
Me.Text = DirectCast(titleResource, String)
Me.BackgroundImage = DirectCast(mainFormResource, Bitmap)
ErrorDialog.Text = DirectCast(titleResource, String)
ErrorDialog.BackgroundImage = DirectCast(errorDialogResource, Bitmap)
ErrorDialog.Width = ErrorDialog.BackgroundImage.Width ' Adjust the form width.
CreateAccount.Text = DirectCast(titleResource, String)
CreateAccount.BackgroundImage = DirectCast(createAccountResource, Bitmap)
End Sub
''' <summary>
''' Loads the application settings.
''' </summary>
Private Sub LoadAppSettings()
Me.ElektroCheckBox_Remember.Checked = My.Settings.rememberPassword
Me.usernameChildTb.Text = My.Settings.lastUsername
If My.Settings.rememberPassword AndAlso Not String.IsNullOrEmpty(My.Settings.lastUsername) Then
Me.passwordChildTb.Text = My.Settings.lastPassword
Else
My.Settings.lastPassword = String.Empty
End If
Me.Icon = My.Resources.SteamApp
End Sub
#If DEBUG Then
''' <summary>
''' Initialize a simple imaging debug testing.
''' </summary>
Private Sub InitializeDebugTesting()
Me.debugPictureBox = Me.PictureBox_Login
Me.debugBitmap = Me.bgLoginButton
Me.TrackBar_Brightness.Show()
Me.TrackBar_Contrast.Show()
Me.TrackBar_Gamma.Show()
Me.Label_Brightness.Show()
Me.Label_Brightness_Value.Show()
Me.Label_Contrast.Show()
Me.Label_Contrast_Value.Show()
Me.Label_Gamma.Show()
Me.Label_Gamma_Value.Show()
End Sub
#End If
''' <summary>
''' Resets the <see cref="PictureBox.BackgroundImage"/> of the <see cref="PictureBox"/> instances that composes the <see cref="Main"/> form.
''' </summary>
Private Sub ResetBackgrounds()
Me.PictureBox_Title.BackgroundImage = Nothing
Me.PictureBox_MinimizeButton.BackgroundImage = Nothing
Me.PictureBox_CloseButton.BackgroundImage = Nothing
Me.PictureBox_Username.BackgroundImage = Nothing
Me.PictureBox_Password.BackgroundImage = Nothing
Me.PictureBox_Remember.BackgroundImage = Nothing
Me.PictureBox_Cancel.BackgroundImage = Nothing
Me.PictureBox_CreateAccount.BackgroundImage = Nothing
Me.PictureBox_LostAccount.BackgroundImage = Nothing
End Sub
''' <summary>
''' Disables the <see cref="ElektroTextBox.ShowBorder"/> of the <see cref="ElektroTextBox"/> instances that composes the <see cref="Main"/> form.
''' </summary>
Private Sub DisableBorders()
Me.ElektroTextBox_Username.ShowBorder = False
Me.ElektroTextBox_Password.ShowBorder = False
End Sub
''' <summary>
''' Centers this <see cref="Main"/> form to a child form.
''' </summary>
Private Sub CenterForm(ByVal childForm As Form)
Me.Location = New Point(x:=childForm.Location.X + (childForm.Width - Me.Width) \ 2,
y:=childForm.Location.Y + (childForm.Height - Me.Height) \ 2)
End Sub
#End Region
End Class
End Namespace |
Option Explicit On
Option Strict On
' // *** Includes *** //
' // General
Imports System.Text
' // *** Class Definition *** //
Public Class CtlLoadPage : Inherits IWDEControl : Implements IReloadableControl
#Region "CtlLoadPage - Data Members"
#End Region
#Region "CtlLoadPage - Constructors"
Protected Sub New()
MyBase.New()
End Sub
#End Region
#Region "CtlLoadPage.UpdateControl.IWDEControl.UserControl - Event Handlers"
Protected Sub Control_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not Me.IsPostBack) Then
Me.EnableControls(Me.IWDEPage.CurrentUser.CurrentPermissions)
Me.BindPages()
End If
End Sub
#End Region
#Region "CtlLoadPage - Event Handlers"
Private Sub btnLoadPage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLoadPage.Click
Me.LoadPage()
End Sub
Private Sub btnCreatePage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCreatePage.Click
Me.CreatePage()
End Sub
Private Sub btnDeletePage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDeletePage.Click
Me.DeletePage()
End Sub
#End Region
#Region "CtlLoadPage - Properties"
Protected ReadOnly Property SelectedPageID As Integer
Get
Dim intResult As Integer = 0
If (
Me.lstPages.Items.Count > 0 _
AndAlso Me.lstPages.SelectedIndex >= 0
) Then
Integer.TryParse(Me.lstPages.SelectedValue, intResult)
End If
Return (intResult)
End Get
End Property
#End Region
#Region "CtlLoadPage - Methods"
#End Region
#Region "CtlLoadPage - Methods - Helpers"
Protected Sub EnableControls(
ByRef objPermissions As IWDEUserPermissions
)
Me.btnLoadPage.Enabled = objPermissions.CanEditPage
Me.btnCreatePage.Enabled = objPermissions.CanCreatePage
Me.btnDeletePage.Enabled = objPermissions.CanDeletePage
End Sub
Protected Sub BindPages()
Dim objUser As IWDEUser = Me.IWDEPage.CurrentUser
If (objUser IsNot Nothing) Then
Dim objDB As IWDEDB = IWDEDB.IWDEDBInstance
' NOTE: This procedure only returns Pages where read permissions exist for this user
Dim dtPages As DataTable = objDB.GetPages(objUser.AccountID, Me.IWDEPage.WebsiteID)
' NOTE: Do not bind if there are no results
If (dtPages IsNot Nothing) Then
' Bind with the list
Me.lstPages.DataTextField = "Name"
Me.lstPages.DataValueField = "Page_ID"
Me.lstPages.DataSource = dtPages
Me.lstPages.DataBind()
Else
Me.lstPages.Items.Clear()
End If
End If
End Sub
Protected Sub LoadPage()
Dim intSelectedPageID As Integer = Me.SelectedPageID
Dim objUser As IWDEUser = Me.IWDEPage.CurrentUser
If (
objUser IsNot Nothing _
AndAlso intSelectedPageID > 0 _
AndAlso objUser.CurrentPermissions.CanReadPage
) Then
Dim objDB As IWDEDB = IWDEDB.IWDEDBInstance
' Redirects
Me.IWDEPage.WebsitePageID = intSelectedPageID
Me.IWDEPage.Redirect("~/PageEditor.aspx")
End If
End Sub
Protected Sub CreatePage()
Dim objUser As IWDEUser = Me.IWDEPage.CurrentUser
If (
objUser IsNot Nothing _
AndAlso objUser.CurrentPermissions.CanCreatePage
) Then
Dim objDB As IWDEDB = IWDEDB.IWDEDBInstance
' Redirects
Me.IWDEPage.WebsitePageID = 0 ' NOTE: Force PageEditor to create a new page
Me.IWDEPage.Redirect("~/PageEditor.aspx")
End If
End Sub
Protected Sub DeletePage()
Dim intSelectedPageID As Integer = Me.SelectedPageID
Dim objUser As IWDEUser = Me.IWDEPage.CurrentUser
If (
objUser IsNot Nothing _
AndAlso intSelectedPageID > 0 _
AndAlso objUser.CurrentPermissions.CanDeletePage
) Then
' TODO: Double-check permissions? (does it at the
Dim objDB As IWDEDB = IWDEDB.IWDEDBInstance
objDB.DeletePage(objUser.AccountID, intSelectedPageID)
' If the deleted Page is the currently-loaded one, reload site
If (Me.IWDEPage.WebsitePageID = intSelectedPageID) Then
Me.IWDEPage.WebsitePageID = 0
End If
' Reload (since list should have one less item in it)
Me.Reload()
End If
End Sub
#End Region
#Region "CtlLoadPage.IWDEControl - Methods"
Public Sub Reload() Implements IReloadableControl.Reload
Me.BindPages()
End Sub
#End Region
End Class |
Imports System.ComponentModel
Imports System.Runtime.CompilerServices
Public Class DashBoardItemUc
Implements INotifyPropertyChanged
Private _valor As Double
Private _formato As String
<Bindable(True)>
Public Property Titulo As String
Get
Return lblTitle.Text
End Get
Set
SetProperty(lblTitle.Text, Value)
End Set
End Property
<Bindable(True)>
Public Property Valor As Double
Get
Return _valor
End Get
Set(value As Double)
If SetProperty(_valor, value) Then
UpdateValue()
End If
End Set
End Property
<Bindable(True), DefaultValue("")>
Public Property Formato As String
Get
Return _formato
End Get
Set(value As String)
SetProperty(_formato, value)
UpdateValue()
End Set
End Property
Private Sub UpdateValue()
lblValue.Text = Strings.Format(_valor, Formato)
End Sub
#Region "INotifyPropertyChanged"
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Protected Sub OnPropertyChanged(<CallerMemberName> Optional propertyName As String = Nothing)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
Protected Function SetProperty(Of T)(ByRef storage As T, value As T, <CallerMemberName> Optional propertyName As String = Nothing) As Boolean
If Equals(storage, value) Then
Return False
End If
storage = value
OnPropertyChanged(propertyName)
Return True
End Function
#End Region
End Class
|
Imports MySql.Data.MySqlClient
Public Class dbClientesDescuentos
Private comm As New MySqlCommand
Public idDescuento As Integer
Public idCliente As Integer
Public idClasificacion1 As Integer
Public idClasificacion2 As Integer
Public idClasificacion3 As Integer
Public descuento As Double
Public modo As Integer
Public idUsuarioAlta As Integer
Public fechaAlta As String
Public horaAlta As String
Public idUsuarioCambio As Integer
Public fechaCambio As String
Public horaCambio As String
Public Sub New(ByVal conexion As MySqlConnection)
comm.Connection = conexion
idDescuento = -1
idCliente = -1
idClasificacion1 = -1
idClasificacion2 = -1
idClasificacion3 = -1
descuento = 0
modo = 0
idUsuarioAlta = -1
fechaAlta = ""
horaAlta = ""
idUsuarioCambio = -1
fechaCambio = ""
horaCambio = ""
End Sub
Public Sub New(ByVal idDescuento As Integer, ByVal conexion As MySqlConnection)
comm.Connection = conexion
Me.idDescuento = idDescuento
llenaDatos()
End Sub
Private Sub llenaDatos()
comm.CommandText = "select * from tblclientesdescuentos where iddescuento=" + idDescuento.ToString + ";"
Dim dr As MySqlDataReader = comm.ExecuteReader
While dr.Read()
idCliente = dr("idcliente")
idClasificacion1 = dr("idclasificacion1")
idClasificacion2 = dr("idclasificacion2")
idClasificacion3 = dr("idclasificacion3")
descuento = dr("descuento")
modo = dr("modo")
idUsuarioAlta = dr("idusuarioalta")
fechaAlta = dr("fechaalta")
horaAlta = dr("horaalta")
idUsuarioCambio = dr("idusuariocambio")
fechaCambio = dr("fechacambio")
horaCambio = dr("horacambio")
End While
dr.Close()
End Sub
Public Function guardar(ByVal idCliente As Integer, ByVal idClasificacion1 As Integer, ByVal idClasificacion2 As Integer, ByVal idClasificacion3 As Integer, ByVal descuento As Double, ByVal modo As Integer) As Boolean
comm.CommandText = "insert into tblclientesdescuentos(idcliente,idclasificacion1,idclasificacion2,idclasificacion3,descuento,modo,idusuarioalta,fechaalta,horaalta,idusuariocambio,fechacambio,horacambio)"
comm.CommandText += " values(" + idCliente.ToString + "," + idClasificacion1.ToString + "," + idClasificacion2.ToString + "," + idClasificacion3.ToString + "," + descuento.ToString + "," + modo.ToString + "," + GlobalIdUsuario.ToString + ",'" + DateTime.Now.ToString("yyyy/MM/dd") + "','" + TimeOfDay.ToString("HH:mm:ss") + "'," + GlobalIdUsuario.ToString + ",'" + DateTime.Now.ToString("yyyy/MM/dd") + "','" + TimeOfDay.ToString("HH:mm:ss") + "');"
Try
comm.ExecuteNonQuery()
Return True
Catch ex As Exception
Return False
End Try
End Function
Public Function modificar(ByVal idDescuento As Integer, ByVal idCliente As Integer, ByVal idClasificacion1 As Integer, ByVal idClasificacion2 As Integer, ByVal idClasificacion3 As Integer, ByVal descuento As Double, ByVal modo As Integer) As Boolean
comm.CommandText = "update tblclientesdescuentos set idcliente=" + idCliente.ToString + ", idclasificacion1=" + idClasificacion1.ToString + ", idclasificacion2=" + idClasificacion2.ToString + ", idclasificacion3=" + idClasificacion3.ToString + ", descuento=" + descuento.ToString + ", modo=" + modo.ToString + ", idusuariocambio=" + GlobalIdUsuario.ToString + ", fechacambio='" + DateTime.Now.ToString("yyyy/MM/dd") + "', horacambio='" + TimeOfDay.ToString("HH:mm:ss") + "' "
comm.CommandText += "where iddescuento=" + idDescuento.ToString + ";"
Try
comm.ExecuteNonQuery()
Return True
Catch ex As Exception
Return False
End Try
End Function
Public Function eliminar(ByVal idDescuento As Integer) As Boolean
comm.CommandText = "delete from tblclientesdescuentos where iddescuento=" + idDescuento.ToString() + ";"
Try
comm.ExecuteNonQuery()
Return True
Catch ex As Exception
Return False
End Try
End Function
Public Function buscaFiltrado(ByVal idCliente As Integer) As DataView
Dim ds As New DataSet
comm.CommandText = "select d.iddescuento,ifnull((select nombre from tblinventarioclasificaciones where idclasificacion=d.idclasificacion1),'') Nivel1,ifnull((select nombre from tblinventarioclasificaciones2 where idclasificacion=d.idclasificacion2),'') Nivel2,ifnull((select nombre from tblinventarioclasificaciones3 where idclasificacion=d.idclasificacion3),'') Nivel3,d.descuento from tblclientesdescuentos d where d.idcliente=" + idCliente.ToString
Dim da As New MySqlDataAdapter(comm)
da.Fill(ds, "descuentos")
Return ds.Tables("descuentos").DefaultView
End Function
Public Function buscar(ByVal idDescuento As Integer) As Boolean
comm.CommandText = "select iddescuento from tblclientesdescuentos where iddescuento=" + idDescuento.ToString + ";"
Dim i As Integer = comm.ExecuteScalar
If i > 0 Then
Me.idDescuento = i
llenaDatos()
Return True
End If
Return False
End Function
Public Function buscaDescuento(ByVal idCliente As Integer, ByVal idClasificacion1 As Integer, ByVal idClasificacion2 As Integer, ByVal idClasificacion3 As Integer) As Double
comm.CommandText = "select ifnull((select descuento from tblclientesdescuentos where"
comm.CommandText += " idcliente=" + idCliente.ToString()
'If idClasificacion1 > 0 Then
comm.CommandText += " and idclasificacion1=" + idClasificacion1.ToString()
'End If
'If idClasificacion2 > 0 Then
comm.CommandText += " and idclasificacion2=" + idClasificacion2.ToString()
'End If
'If idClasificacion3 > 0 Then
comm.CommandText += " and idclasificacion3=" + idClasificacion3.ToString()
' End If
comm.CommandText += "),-1000)"
Dim res As Double = comm.ExecuteScalar
Return res
End Function
End Class
|
Imports BaseClasses
Public Class ForgotPassword
Inherits DTIServerControls.DTIServerBase
#Region "Control Properties"
Private _emailSentText As String = "Password Reset information has been sent to your email address."
Public Property EmailSentText As String
Get
Return _emailSentText
End Get
Set(value As String)
_emailSentText = value
End Set
End Property
Private _emailNotfoundtext As String = "Your email Address was not found."
Public Property EmailNotFoundText As String
Get
Return _emailNotfoundtext
End Get
Set(value As String)
_emailNotfoundtext = value
End Set
End Property
Private _messageText As String = "Please enter the email address associated with your account."
Public Property MessageText As String
Get
Return _messageText
End Get
Set(value As String)
_messageText = value
End Set
End Property
Private _ChangePasswordURL As String
Public Property ChangePasswordURL As String
Get
Return _ChangePasswordURL
End Get
Set(value As String)
_ChangePasswordURL = value
End Set
End Property
Private _LinkExpirationMinutes As Integer = 60
Public Property LinkExpirationMinutes As Integer
Get
Return _LinkExpirationMinutes
End Get
Set(value As Integer)
_LinkExpirationMinutes = value
End Set
End Property
Private _EmailText As String = Nothing
Public Property EmailText As String
Get
Return _EmailText
End Get
Set(value As String)
_EmailText = value
End Set
End Property
Private _EmailSubject As String = Nothing
Public Property EmailSubject As String
Get
Return _EmailSubject
End Get
Set(value As String)
_EmailSubject = value
End Set
End Property
#End Region
Private _DisableDefaultStyle As Boolean
''' <summary>
''' Remove defualt style of change password control
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
<System.ComponentModel.Description("Remove defualt style of change password control")> _
Public Property DisableDefaultStyle As Boolean
Get
Return _DisableDefaultStyle
End Get
Set(value As Boolean)
_DisableDefaultStyle = value
End Set
End Property
Private WithEvents forgot As New ForgotPasswordControl
Private Sub ForgotPassword_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim pantheman As New Panel
Me.Controls.Add(pantheman)
forgot = CType(Me.Page.LoadControl("~/res/DTIAdminPanel/ForgotPasswordControl.ascx"), ForgotPasswordControl)
With forgot
.MessageText = MessageText
.EmailNotFoundText = EmailNotFoundText
.EmailSentText = EmailSentText
.EmailSubject = EmailSubject
.EmailText = EmailText
.ChangePasswordURL = ChangePasswordURL
.LinkExpirationHours = LinkExpirationMinutes
End With
pantheman.Controls.Add(forgot)
If Not DisableDefaultStyle Then
'jQueryLibrary.jQueryInclude.addStyleBlock(Page, ".Kurk-login {width:240px} " & _
' ".Kurk-Spacer {clear:both; height:10px} " & _
' ".Kurk-Error {width: 240px} " & _
' ".Kurk-tbUser {width: 240px} " & _
' ".Kurk-tbPass { width: 240px} " & _
' ".Kurk-Remember {font-size: .8em;float:left} " & _
' ".Kurk-btnLogin {float:right} " & _
' ".Kurk-Forgot {font-size: .8em} ")
End If
End Sub
Public Shared Function CreateChangePassCode(ByRef User As dsDTIAdminPanel.DTIUsersRow, ByVal MinutesTilLinkExpires As Double, _
Optional ByVal EncryptionKey As String = "U?Ae26P7Z`#Mg@l>&sxJ?kLX2Kwg/S;g") As String
Dim linkData As String = BaseClasses.EncryptionHelper.Encrypt(User.Id & "@" & Now.AddMinutes(MinutesTilLinkExpires).ToString & _
"@" & User.Guid, EncryptionKey)
Return HttpUtility.UrlEncode(linkData)
End Function
Public Shared Function GetUserFromPassCode(ByVal Code As String, Optional ByVal DecryptionKey As String = "U?Ae26P7Z`#Mg@l>&sxJ?kLX2Kwg/S;g") As dsDTIAdminPanel.DTIUsersRow
Code = HttpUtility.UrlDecode(Code).Replace(" ", "+")
Dim linkData As String = BaseClasses.EncryptionHelper.Decrypt(Code, DecryptionKey)
Dim s As String() = linkData.Split("@"c)
Dim id As Integer = -1
Dim dt As DateTime = Nothing
Dim gid As String = Nothing
If s.Length = 3 Then
Try
id = Integer.Parse(s(0))
dt = DateTime.Parse(s(1))
gid = s(2)
Catch ex As Exception
Return Nothing
End Try
Else : Return Nothing
End If
If id <> -1 AndAlso dt <> Nothing AndAlso gid IsNot Nothing AndAlso Now <= dt Then
Dim dtUsers As New dsDTIAdminPanel.DTIUsersDataTable
BaseHelper.getHelper.FillDataTable("Select * from DTIUsers where Id=@id AND Guid=@gid", dtUsers, id, gid)
If dtUsers.Count = 1 Then
Return dtUsers(0)
Else : Return Nothing
End If
Else : Return Nothing
End If
End Function
End Class
|
Imports Microsoft.Office.Interop.Excel
Module OfficeApplicationHandler
Public ExportTitle As String
Public Sub ExcelExport(ByVal FileName As String, ByVal TableName As String, Optional ByVal Save As Boolean = True)
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim xlCol As Integer = MainAppForm.DataGridView2.ColumnCount - 1
Dim xlRow As Integer = MainAppForm.DataGridView2.RowCount - 1
Dim sFileName As String = FileName
Dim sTableName As String = TableName
Dim qTableName As String = ""
Dim ExportCellCount As Integer = 0
Dim sFileFormat As String = ""
Dim sFileSuffix As String = ""
Dim iRowCount As Integer = 0
Try
Select Case MainAppForm.ExportTargetFormat.SelectedIndex
Case 0
sFileFormat = XlFileFormat.xlExcel8
sFileSuffix = ".xls"
Case 1
sFileFormat = XlFileFormat.xlWorkbookDefault
sFileSuffix = ".xlsx"
Case 2
sFileFormat = XlFileFormat.xlCSV
sFileSuffix = ".csv"
End Select
sFileName = Replace(Replace(Replace(FileName, ".", "-"), ":", ""), " ", "_") & sFileSuffix.ToString
sTableName = Replace(Replace(Replace(Left(TableName, 31), ".", "_"), ":", ""), " ", "_")
MainAppForm.RecentFileName.Text = sFileName
xlApp = New Microsoft.Office.Interop.Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.ActiveSheet
If sTableName = Nothing Or sTableName = "" Then sTableName = "Empty"
xlWorkSheet.Name = sTableName
xlWorkBook.CheckCompatibility = False
'xlApp.Visible = True
Dim d As DataObject
If MainAppForm.ExcelExportSource = "DataGrid2" Then
'Main Grid (DataGrid2)
iRowCount = MainAppForm.DataGridView2.RowCount
If iRowCount > 0 Then
Debug.Print("TOTAL DATAGRID ROWS ==> " & iRowCount)
MainAppForm.DataGridView2.SelectAll()
Debug.Print(MainAppForm.DataGridView2.SelectedCells.ToString)
d = MainAppForm.DataGridView2.GetClipboardContent
Clipboard.SetDataObject(d)
Clipboard.GetText()
MainAppForm.DataGridView2.ClearSelection()
xlWorkSheet.Range("A5", "A5").Select()
'xlWorkSheet.Range("A5", "A5").PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationAdd)
xlWorkSheet.Range("A5", "A5").PasteSpecial()
xlWorkSheet.Paste()
xlWorkSheet.Range("A5", "A5").Select()
xlWorkSheet.Range("A5", "A5").EntireColumn.Delete()
Else
For k As Integer = 1 To MainAppForm.DataGridView2.Columns.Count
xlWorkSheet.Cells(5, k + 0) = "-"
Next
End If
xlWorkSheet.UsedRange.Select()
xlWorkSheet.ListObjects.AddEx.TableStyle = "TableStyleMedium16"
For k As Integer = 1 To MainAppForm.DataGridView2.Columns.Count
xlWorkSheet.Cells(5, k + 0) = MainAppForm.DataGridView2.Columns(k - 1).HeaderText
Next
Else
' Free Grid (DataGridSheet
If DataGridSheet.DataGridSheetView.RowCount > 0 Then
DataGridSheet.DataGridSheetView.SelectAll()
d = DataGridSheet.DataGridSheetView.GetClipboardContent
Clipboard.SetDataObject(d)
Clipboard.GetText()
DataGridSheet.DataGridSheetView.ClearSelection()
xlWorkSheet.Range("A5", "A5").Select()
'xlWorkSheet.Range("A5", "A5").PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationAdd)
xlWorkSheet.Range("A5", "A5").PasteSpecial()
xlWorkSheet.Paste()
xlWorkSheet.Range("A5", "A5").Select()
xlWorkSheet.Range("A5", "A5").EntireColumn.Delete()
Else
For k As Integer = 1 To DataGridSheet.DataGridSheetView.Columns.Count
xlWorkSheet.Cells(5, k + 0) = "-"
Next
End If
xlWorkSheet.UsedRange.Select()
xlWorkSheet.ListObjects.AddEx.TableStyle = "TableStyleMedium16"
For k As Integer = 1 To DataGridSheet.DataGridSheetView.Columns.Count
xlWorkSheet.Cells(5, k + 0) = DataGridSheet.DataGridSheetView.Columns(k - 1).HeaderText
Next
End If
'Excel Operations
xlWorkSheet.UsedRange.Select()
xlWorkSheet.Cells.WrapText = False
xlWorkSheet.Columns.AutoFit()
xlWorkSheet.Rows.AutoFit()
xlWorkSheet.Cells.Select()
xlWorkSheet.Cells.EntireColumn.AutoFit()
'Extract Table Name from Query
qTableName = MainAppForm.QueryBox.Text.ToString
If InStr(qTableName, "<TITLE>") <> 0 Then
Dim x1, x2 As Integer
x1 = InStr(qTableName, "<TITLE>") + 7
x2 = InStr(qTableName, "</TITLE>")
If x2 > 0 Then qTableName = Mid(qTableName, x1, x2 - x1)
xlWorkSheet.Cells(2, 1) = qTableName
xlWorkSheet.Range("A2").Select()
xlWorkSheet.Range("A2").Font.Bold = False
xlWorkSheet.Range("A2").Font.Underline = True
xlWorkSheet.Range("A2").Font.Size = 14
Else
MainAppForm.Focus()
qTableName = InputBox("Please add a Title:", "Titel is empty", MainAppForm.ReportAccount.Text.ToString)
xlWorkSheet.Cells(2, 1) = qTableName
End If
ExportTitle = qTableName
MainAppForm.outboundMailSubject = qTableName
'sFileName = Replace(MainAppForm.outboundMailReport, " ", "_") '+ "_" + sFileName
If MainAppForm.SaveFilePath.Text = "" Then MainAppForm.SaveFilePath.Text = xlWorkBook.Path.ToString
'MainAppForm.SaveFilePath.Text = xlWorkBook.Path.ToString
Dim strFile As String
strFile = MainAppForm.SaveFilePath.Text & sFileName
xlApp.DisplayAlerts = False
xlWorkBook.SaveAs(strFile, sFileFormat)
xlApp.DisplayAlerts = True
If MainAppForm.ExcelOpenFile.Checked = False Then
xlApp.Visible = False
xlWorkBook.Close()
xlApp.Quit()
Else
MainAppForm.Focus()
If MsgBox(MainAppForm.SaveFilePath.Text & sFileName, MsgBoxStyle.YesNo, "Open File") = MsgBoxResult.Yes Then
If xlApp.Workbooks.Count = 0 Then
xlApp.Workbooks.Open(MainAppForm.SaveFilePath.Text & sFileName)
End If
xlApp.Visible = True
End If
End If
If Save = True Then
MainAppForm.Focus()
Else
If Dir(strFile) <> "" Then
xlWorkBook.Close()
xlApp.Quit()
IO.File.Delete(strFile.ToString)
MainAppForm.Focus()
End If
End If
If MainAppForm.ExcelCreateMail.Checked = True Then
MainAppForm.Focus()
SendMailForm.Show()
SendMailForm.Focus()
End If
Catch ex As Exception
Debug.Print(ex.Message) : LogWriter.WriteRow(ex.TargetSite.ToString, ex.ToString)
UpdateStatusAction(ex.Message)
Finally
End Try
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
End Sub
Public Sub OpenExcelFile(ByVal sFilePath As String)
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Try
LogWriter.WriteRow("Begin: Open Excel Workbook", sFilePath.ToString)
xlApp = New Microsoft.Office.Interop.Excel.Application
xlApp.Workbooks.Open(sFilePath.ToString)
xlApp.Visible = True
LogWriter.WriteRow("Done: Open Excel Workbook", sFilePath.ToString)
Catch ex As Exception
Debug.Print(ex.Message) : LogWriter.WriteRow(ex.TargetSite.ToString, ex.ToString)
UpdateStatusAction(ex.Message)
UpdateStatusAction("Closing Excel Application on exception now for " & sFilePath)
xlApp.Workbooks.Close()
xlApp.Quit()
Finally
UpdateStatusAction("Open Excel File: " & sFilePath)
End Try
releaseObject(xlApp)
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
Debug.Print(ex.Message) : LogWriter.WriteRow(ex.TargetSite.ToString, ex.ToString)
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Module
|
Namespace Areas.Reports.Models
Public Class CampaignDashboardAvailableFilterTeamModel
Public Property TeamId As Integer
Public Property TeamName As String
End Class
End Namespace |
Public Class Crew
Public Sub New()
For Each cs In [Enum].GetValues(GetType(CrewSkill))
Skills.Add(cs, 0)
SkillsXP.Add(cs, 0)
Next
End Sub
Public Shared Function Generate(ByVal aRace As CrewRace, ByVal rng As Random, Optional ByVal skillMain As CrewSkill = Nothing, Optional ByVal skillSub As CrewSkill = Nothing) As Crew
Dim crew As New Crew
With crew
._Name = GenerateName(aRace, rng)
.Race = aRace
.Health = 100
.Morale = 100
.AddBonus("equipment", CrewBonus.Generate("Belaying Pin"))
Dim s As New List(Of CrewSkill)([Enum].GetValues(GetType(CrewSkill)))
If skillMain <> Nothing Then s.Remove(skillMain)
If skillSub <> Nothing Then s.Remove(skillSub)
Dim cs As CrewSkill = Nothing
If skillMain <> Nothing Then cs = skillMain Else cs = Dev.GrabRandom(Of CrewSkill)(s, rng)
.AddSkillXP(cs, SkillThresholds(2))
If skillSub <> Nothing Then cs = skillSub Else cs = Dev.GrabRandom(Of CrewSkill)(s, rng)
.AddSkillXP(cs, SkillThresholds(1))
Dim selectTalent As CrewTalent = GenerateTalent(aRace)
Select Case SelectTalent
Case CrewTalent.Ironwilled : .Health += 10
End Select
.AddTalent(selectTalent)
Select Case .Race
Case CrewRace.Human
.MoraleDemands.Add(GoodType.Rations, -5)
.MoraleDemands.Add(GoodType.Water, -10)
.MoraleWants.Add(GoodType.Coffee, 1)
.MoraleWants.Add(GoodType.Liqour, 2)
Case CrewRace.Windsworn
.MoraleDemands.Add(GoodType.Rations, -5)
.MoraleDemands.Add(GoodType.Water, -10)
.MoraleWants.Add(GoodType.Tobacco, 1)
.MoraleWants.Add(GoodType.Spice, 2)
Case CrewRace.Seatouched
.MoraleDemands.Add(GoodType.Rations, -5)
.MoraleDemands.Add(GoodType.Water, -10)
.MoraleWants.Add(GoodType.Salt, 2)
Case CrewRace.Unrelinquished
.MoraleDemands.Add(GoodType.Mordicus, -10)
End Select
End With
Return crew
End Function
Private Shared Function GenerateName(ByVal race As CrewRace, ByRef rng As Random) As String
If rng Is Nothing Then rng = New Random
If NamePrefixes.Count = 0 Then NamePrefixes = IO.SimpleFilegetAll("namePrefixes.txt")
If NameSuffixes.Count = 0 Then NameSuffixes = IO.SimpleFilegetAll("nameSuffixes.txt")
Dim prefix As String = Dev.GrabRandom(Of String)(NamePrefixes, rng)
Dim suffix As String = Dev.GrabRandom(Of String)(NameSuffixes, rng)
Return prefix & " " & suffix
End Function
Private Shared Function GenerateTalent(ByVal aRace As CrewRace) As CrewTalent
Dim possibleTalents As New List(Of CrewTalent)
For Each talent In [Enum].GetValues(GetType(CrewTalent))
'anything above 100 is a trained talent
If talent < 100 Then possibleTalents.Add(talent) Else Exit For
Next
Return Dev.GetRandom(Of CrewTalent)(possibleTalents, World.Rng)
End Function
Private Shared NamePrefixes As New List(Of String)
Private Shared NameSuffixes As New List(Of String)
Public Overrides Function ToString() As String
Return Name
End Function
Private _Name As String
Public Property Name As String
Get
If Title <> "" Then Return Title & " " & _Name Else Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
Private ReadOnly Property Title As String
Get
If Role = Nothing Then Return ""
Select Case Role
Case CrewRole.Captain : Return "Cpt."
Case CrewRole.FirstMate : Return "Bosun"
Case CrewRole.Sailor : Return "Seaman"
Case CrewRole.Doctor : Return "Dr."
Case CrewRole.Alchemist : Return "Hon."
Case CrewRole.Navigator : Return "Nav."
Case Else : Return Role.ToString
End Select
End Get
End Property
Public Race As CrewRace
#Region "Bonuses"
Private Scars As New List(Of CrewBonus)
Private Equipment As New List(Of CrewBonus)
Private CrewBonuses As List(Of CrewBonus)() = {Scars, Equipment}
Public Function CheckAddBonus(ByVal listName As String, ByVal effect As CrewBonus) As Boolean
'check slot against all lists
For Each cbl In CrewBonuses
If effect.Slot Is Nothing = False Then
If GetSlot(cbl, effect.Slot) Is Nothing = False Then Return False
End If
Next
Return True
End Function
Public Sub AddBonus(ByVal listName As String, ByVal effect As CrewBonus)
If CheckAddBonus(listName, effect) = False Then Exit Sub
Dim targetList As List(Of CrewBonus) = GetBonusList(listName)
targetList.Add(effect)
End Sub
Public Function CheckRemoveBonus(ByVal listname As String, ByVal effect As CrewBonus)
Dim targetList As List(Of CrewBonus) = GetBonusList(listname)
If targetList.Contains(effect) = False Then Return False
Return True
End Function
Public Function CheckRemoveBonus(ByVal listname As String, ByVal slot As String)
Dim targetList As List(Of CrewBonus) = GetBonusList(listname)
Dim target As CrewBonus = GetSlot(targetList, slot)
If target Is Nothing Then Return False
Return True
End Function
Public Sub RemoveBonus(ByVal listName As String, ByVal effect As CrewBonus)
Dim targetList As List(Of CrewBonus) = GetBonusList(listName)
If targetList.Contains(effect) Then targetList.Remove(effect)
End Sub
Public Sub RemoveBonus(ByVal listName As String, ByVal slot As String)
Dim targetList As List(Of CrewBonus) = GetBonusList(listName)
Dim target As CrewBonus = GetSlot(targetList, slot)
If target Is Nothing = False Then targetList.Remove(target)
End Sub
Public Function GetBonus(ByVal listName As String, ByVal name As String) As CrewBonus
Dim cbl As List(Of CrewBonus) = GetBonusList(listName)
For Each cb In cbl
If cb.Name = name Then Return cb
Next
Return Nothing
End Function
Public Function GetBonusList(ByVal listName As String) As List(Of CrewBonus)
Select Case listName.ToLower
Case "scars", "scar" : Return Scars
Case "equipment" : Return Equipment
End Select
Return Nothing
End Function
Private Function GetSlot(ByRef targetList As List(Of CrewBonus), ByVal slot As String) As CrewBonus
For Each e In targetList
If e.Slot = slot Then Return e
Next
Return Nothing
End Function
Private Function GetArmour(ByVal damageType As DamageType) As Integer
Dim total As Integer = 0
For Each cbl As List(Of CrewBonus) In CrewBonuses
For Each cb As CrewBonus In cbl
If cb.Armour.ContainsKey(damageType) Then total += cb.Armour(damageType)
Next
Next
Return total
End Function
Private Function GetWeapons() As List(Of CrewBonus)
Dim total As New List(Of CrewBonus)
For Each cbl In CrewBonuses
For Each cb In cbl
If cb.IsReady(Ship) = True AndAlso cb.Damage > 0 Then total.Add(cb)
Next
Next
Return total
End Function
Private Function GenerateScar(ByVal damage As Damage, ByVal fleshshapingBonus As Integer) As CrewBonus
Dim scarNames As List(Of String) = GenerateScarNames()
Dim scarName As String = Dev.GetRandom(Of String)(scarNames, World.Rng, fleshshapingBonus)
Dim total As New CrewBonus
With total
.Name = scarName
Select Case scarName
Case "Hook Hand"
.Slot = "Right Hand"
.Skill = CrewSkill.Melee
.Damage = 10
.DamageType = DamageType.Blade
Case "Gun Hand"
.Slot = "Left Hand"
.Skill = CrewSkill.Firearms
.Damage = 25
.DamageType = DamageType.Blunt
.AmmoUse = 1
Case "Dimwitted"
.SkillBonuses.Add(CrewSkill.Leadership, -2)
.SkillBonuses.Add(CrewSkill.Medicine, -2)
Case "Half-Blind"
.SkillBonuses.Add(CrewSkill.Navigation, -2)
.SkillBonuses.Add(CrewSkill.Gunnery, -2)
Case "Anosmia"
.SkillBonuses.Add(CrewSkill.Alchemy, -2)
.SkillBonuses.Add(CrewSkill.Cooking, -2)
Case "Lungshot"
.SkillBonuses.Add(CrewSkill.Melee, -2)
.SkillBonuses.Add(CrewSkill.Sailing, -2)
Case "Pegleg"
.Slot = "Feet"
.SkillBonuses.Add(CrewSkill.Bracing, -2)
Case "Touch of Death"
.Slot = "Talisman"
.Skill = CrewSkill.Alchemy
.Damage = 10
.DamageType = DamageType.Necromancy
Case "Tentacled Arm"
.Slot = "Left Hand"
.Skill = CrewSkill.Melee
.Damage = 20
.DamageType = DamageType.Blunt
Case "Crabclaw"
.Slot = "Right Hand"
.Skill = CrewSkill.Melee
.Damage = 10
.DamageType = DamageType.Blade
.Armour.Add(DamageType.Blade, 5)
Case "Angler's Light"
.Slot = "Head"
.Armour.Add(DamageType.Necromancy, 15)
Case "Sharkskin"
.Slot = "Body"
.Armour.Add(DamageType.Blunt, 20)
Case "Greenskin"
.Slot = "Body"
Case "Hardened Carapace"
.Slot = "Body"
.Armour.Add(DamageType.Blade, 10)
Case "Writhing Mass"
.Slot = "Feet"
.SkillBonuses.Add(CrewSkill.Bracing, +1)
Case Else : Throw New Exception("Out of roll range")
End Select
End With
Return total
End Function
Private Function GenerateScarNames() As List(Of String)
If Me.Race = CrewRace.Unrelinquished Then Return Nothing
Dim scarNames As New List(Of String)
scarNames.AddRange({"Hook Hand", "Gun Hand", "Dimwitted", "Half-Blind", "Anosmia", "Lungshot", "Pegleg", "Touch of Death"})
If Me.Race = CrewRace.Seatouched Then
scarNames.AddRange({"Tentacled Arm", "Crabclaw", "Angler's Light", "Sharkskin", "Greenskin", "Hardened Carapace", "Writhing Mass"})
End If
For Each thing In Scars
If scarNames.Contains(thing.Name) Then scarNames.Remove(thing.Name)
Next
If scarNames.Count <= 0 Then Return Nothing Else Return scarNames
End Function
#End Region
#Region "Skills"
Private Skills As New Dictionary(Of CrewSkill, Integer)
Private SkillsXP As New Dictionary(Of CrewSkill, Double)
Private Shared SkillThresholds As Integer() = {0, 100, 300, 600, 1000, 1500}
Public Function GetSkill(ByVal cs As CrewSkill)
Dim total As Integer = Skills(cs)
For Each s In Scars
If s.SkillBonuses.ContainsKey(cs) Then total += s.SkillBonuses(cs)
Next
For Each e In Equipment
If e.SkillBonuses.ContainsKey(cs) Then total += e.SkillBonuses(cs)
Next
'shortcircuit for non-ship crew
If Ship Is Nothing Then Return total
'get mascot bonus
If Ship.mascot Is Nothing = False Then
If Ship.Mascot.SkillBonuses.ContainsKey(cs) Then total += Ship.Mascot.SkillBonuses(cs)
End If
'get module cap and bonus
Dim m As ShipModule = Nothing
Dim t As CrewTalent = Nothing
Select Case cs
Case CrewSkill.Leadership : m = Ship.GetModule(ShipModule.ModuleType.Quarterdeck)
Case CrewSkill.Navigation : m = Ship.GetModule(ShipModule.ModuleType.Maproom) : t = CrewTalent.Saltblooded
Case CrewSkill.Steering : m = Ship.GetModule(ShipModule.ModuleType.Helm) : t = CrewTalent.Saltblooded
Case CrewSkill.Sailing : t = CrewTalent.Windtouched
Case CrewSkill.Gunnery : t = CrewTalent.Flamelicked
Case CrewSkill.Bracing : t = CrewTalent.Deathkissed
Case CrewSkill.Cooking : m = Ship.GetModule(ShipModule.ModuleType.Kitchen) : t = CrewTalent.Hyperosmia
Case CrewSkill.Alchemy : m = Ship.GetModule(ShipModule.ModuleType.Laboratory) : t = CrewTalent.Hyperosmia
Case CrewSkill.Medicine : m = Ship.GetModule(ShipModule.ModuleType.Apothecary) : t = CrewTalent.Deathkissed
Case CrewSkill.Firearms : t = CrewTalent.Flamelicked
Case CrewSkill.Melee : t = CrewTalent.Windtouched
End Select
If m Is Nothing = False Then
Dim mCap As Integer = m.Quality + 1
total = Math.Min(mCap, total)
End If
If t <> Nothing AndAlso GetTalent(t) = True Then
If total = 1 Then total = 2
If total = 0 Then total = 1
End If
Return total
End Function
Private Function GetBestSkill(ByVal meleeOnly As Boolean) As CrewSkill
Dim bestSkill As CrewSkill = Nothing
Dim bestSkillValue As Integer = -1
For Each cs In [Enum].GetValues(GetType(CrewSkill))
If meleeOnly = False OrElse cs > 100 Then
Dim skill As CrewSkill = cs
Dim skillValue As Integer = GetSkill(cs)
If skillValue > bestSkillValue Then
bestSkill = skill
bestSkillValue = skillValue
End If
End If
Next
Return bestSkill
End Function
Public Function GetSkillFromRole() As Integer
Dim cs As CrewSkill = ConvertRoleToSkill(Role)
If cs = Nothing Then Return -1
Return GetSkill(cs)
End Function
Public Sub AddSkillXP(ByVal cs As CrewSkill, ByVal value As Double)
Dim maxLevel As Integer = SkillThresholds.Count - 1
Dim maxThreshold As Integer = SkillThresholds(maxLevel)
If Skills(cs) >= maxLevel Then Exit Sub
SkillsXP(cs) += value
If SkillsXP(cs) > maxThreshold Then SkillsXP(cs) = maxThreshold
Dim level As Integer = Skills(cs)
While SkillsXP(cs) > SkillThresholds(level)
level += 1
Skills(cs) += 1
End While
End Sub
Public Shared Function ConvertSkillToRole(ByVal skill As CrewSkill) As CrewRole
Select Case skill
Case CrewSkill.Leadership : Return CrewRole.Captain
Case CrewSkill.Cooking : Return CrewRole.Cook
Case CrewSkill.Steering : Return CrewRole.Helmsman
Case CrewSkill.Gunnery : Return CrewRole.Gunner
Case CrewSkill.Sailing : Return CrewRole.Sailor
Case CrewSkill.Navigation : Return CrewRole.Navigator
Case CrewSkill.Alchemy : Return CrewRole.Alchemist
Case CrewSkill.Medicine : Return CrewRole.Doctor
Case Else : Return Nothing
End Select
End Function
Public Shared Function ConvertRoleToSkill(ByVal role As CrewRole) As CrewSkill
Select Case role
Case CrewRole.Captain, CrewRole.FirstMate : Return CrewSkill.Leadership
Case CrewRole.Cook : Return CrewSkill.Cooking
Case CrewRole.Gunner : Return CrewSkill.Gunnery
Case CrewRole.Helmsman : Return CrewSkill.Steering
Case CrewRole.Sailor : Return CrewSkill.Sailing
Case CrewRole.Navigator : Return CrewSkill.Navigation
Case CrewRole.Alchemist : Return CrewSkill.Alchemy
Case CrewRole.Doctor : Return CrewSkill.Medicine
Case Else : Return Nothing
End Select
End Function
Private Talents As New List(Of CrewTalent)
Public Function GetTalents() As List(Of CrewTalent)
Return Talents
End Function
Public Function GetTalent(ByVal t As CrewTalent) As Boolean
Return Talents.Contains(t)
End Function
Public Function CheckAddTalent(ByVal t As CrewTalent) As Boolean
If Talents.Contains(t) Then Return False
Return True
End Function
Public Sub AddTalent(ByVal t As CrewTalent)
If CheckAddTalent(t) = False Then Exit Sub
Talents.Add(t)
End Sub
#End Region
#Region "Combat"
Private DamageLog As New List(Of Damage)
Private Health As Integer
Private DamageSustained As Integer
Public ReadOnly Property IsInjured As Boolean
Get
If DamageSustained > 0 Then Return True Else Return False
End Get
End Property
Public Sub MeleeAttack(ByRef targets As List(Of Crew))
Dim target As Crew = Dev.GrabRandom(targets, World.Rng)
MeleeAttack(target)
End Sub
Public Sub MeleeAttack(ByRef target As Crew)
Dim weapons As List(Of CrewBonus) = getWeapons()
For Each weapon In weapons
Dim skill As CrewSkill = weapon.Skill
'roll skill vs skill
Dim attSkill As Integer = GetSkill(skill) + weapon.Accuracy + Dev.FateRoll(World.Rng)
Dim defSkill As Integer = target.GetSkill(skill) + weapon.Accuracy + Dev.FateRoll(World.Rng)
If attSkill > defSkill Then
'success, damage
Dim damage As New Damage(0, weapon.Damage, weapon.DamageType, _Name & "'s " & weapon.Name)
target.Damage(damage)
weapon.UseWeapon(ship)
ElseIf attSkill = defSkill Then
'glancing hit
Dim dmgValue As Integer = Dev.Constrain(weapon.Damage / 2, 1)
Dim damage As New Damage(0, dmgValue, weapon.DamageType, _Name & "'s " & weapon.Name)
target.Damage(damage)
weapon.UseWeapon(Ship)
Else
'miss
Report.Add("[" & target.Ship.ID & "] " & target._Name & " fended off " & _Name & "'s " & weapon.Name & ".", ReportType.CrewAttack)
End If
'add xp
Dim xp As Double = 0.5
AddSkillXP(skill, xp)
target.AddSkillXP(skill, xp)
Next
End Sub
Public Sub ShipAttack(ByVal accuracy As Integer, ByVal damage As Damage)
If damage.CrewDamage <= 0 Then Exit Sub
Dim skill As Integer = GetSkill(CrewSkill.Bracing) + Dev.FateRoll(World.Rng)
If skill > accuracy + Dev.FateRoll(World.Rng) Then
'Dim nuDamage As Damage = damage.Clone(damage)
'nuDamage.CrewDamage = Dev.Constrain(nuDamage.CrewDamage / 2, 1)
damage.CrewDamage = Dev.Constrain(damage.CrewDamage / 2, 1)
Me.Damage(damage)
Else
Me.Damage(damage)
End If
Dim xp As Double = 1
AddSkillXP(CrewSkill.Bracing, xp)
End Sub
Public Sub TickCombat()
For Each cbl In CrewBonuses
For Each cb In cbl
cb.TickCombat()
Next
Next
End Sub
Private Sub Damage(ByVal damage As Damage)
If Ship Is Nothing Then Exit Sub
If damage.CrewDamage <= 0 Then Exit Sub
DamageSustained += (damage.CrewDamage - GetArmour(damage.Type))
DamageLog.Add(damage)
Dim repType As ReportType
If TypeOf Ship Is ShipPlayer Then repType = ReportType.CrewDamage Else repType = ReportType.EnemyCrewDamage
Report.Add("[" & Ship.ID & "] " & _Name & " was struck for " & damage.CrewDamage & " damage by " & damage.Sender & ".", repType)
If DamageSustained >= Health Then Death()
End Sub
Public Sub TickHeal(ByVal doctor As Crew)
'doctors have disadvantage when treating patients not of their race
'failure to treat will deal damage
'unrelinquished do not gain scars but are harder to treat
'seatouched have a chance to gain mutation instead of scar
Dim currentDamage As Damage = GetWorstDamage()
If currentDamage.CrewDamage = 0 Then
'no more damage to treat in damage log
'check for lingering injuries to treat
If doctor Is Nothing = False AndAlso DamageSustained > 0 Then
Dim heal As Integer = doctor.GetSkillFromRole
Report.Add(_Name & "'s injuries recover under the ministrations of the doctor. (-" & heal & " damage)", ReportType.Doctor)
DamageSustained -= heal
If DamageSustained < 0 Then DamageSustained = 0
End If
Exit Sub
End If
If doctor Is Nothing Then
Report.Add(_Name & "'s injuries worsen without a doctor. (+5 damage)", ReportType.CrewDamage)
DamageSustained += 5
If DamageSustained > Health Then Death()
Exit Sub
End If
If doctor.Ship Is Nothing = False Then
'if doctor is shipdoctor, spend medicine
If Ship.CheckAddGood(GoodType.Medicine, -1) = False Then
Report.Add(_Name & "'s injuries worsen without medicine. (+1 damage)", ReportType.CrewDamage)
DamageSustained += 1
If DamageSustained > Health Then Death()
Exit Sub
End If
Ship.AddGood(GoodType.Medicine, -1)
End If
Dim skill As Integer = doctor.GetSkillFromRole
skill += Dev.FateRoll(World.Rng)
If doctor.Race <> Me.Race Then skill -= 1
If Me.Race = CrewRace.Unrelinquished Then skill -= 1
If GetTalent(CrewTalent.Fatebound) = True Then skill += 1
Dim difficulty As Integer
Select Case currentDamage.CrewDamage
Case Is <= 10 : difficulty = -1
Case Is <= 20 : difficulty = 0
Case Is <= 30 : difficulty = 1
Case Is <= 40 : difficulty = 2
Case Else : difficulty = 3
End Select
If skill > difficulty Then
Dim heal As Integer = currentDamage.CrewDamage / 2
DamageLog.Remove(currentDamage)
DamageSustained -= heal
Report.Add("The doctor successfully treated " & _Name & "'s worst injuries. (-" & heal & " damage)", ReportType.Doctor)
ElseIf skill = difficulty Then
Dim heal As Integer = currentDamage.CrewDamage / 2
DamageLog.Remove(currentDamage)
DamageSustained -= heal
Report.Add("The doctor treated " & _Name & "'s worst injuries with some difficulty. (-" & heal & " damage)", ReportType.Doctor)
If Me.Race <> CrewRace.Unrelinquished Then
Dim scarRollBonus As Integer = 0
If doctor.GetTalent(CrewTalent.Fleshshaper) = True AndAlso Me.Race = CrewRace.Seatouched Then scarRollBonus += 4
Dim scar As CrewBonus = GenerateScar(currentDamage, scarRollBonus)
If scar Is Nothing Then Exit Sub
AddBonus("scar", scar)
Report.Add(_Name & " gains a new scar: " & scar.Name, ReportType.Doctor)
'check for old scars and overwrite if necessary
If scar.Slot <> Nothing Then
Dim oldScar As CrewBonus = GetSlot(GetBonusList("scar"), scar.Slot)
If oldScar Is Nothing = False Then
RemoveBonus("scar", scar.Slot)
Report.Add(_Name & "'s new scar replaces an old scar: " & oldScar.Name, ReportType.Doctor)
End If
End If
End If
Else
Dim dmg As Integer = World.Rng.Next(1, 6)
If GetTalent(CrewTalent.Tough) = True Then dmg = 1
Report.Add("The doctor failed to treat " & _Name & "'s worst injuries. (+" & dmg & " damage)", ReportType.Doctor)
DamageSustained += dmg
If DamageSustained > Health Then Death()
End If
End Sub
Private Function GetWorstDamage() As Damage
Dim worstDmg As Damage = New Damage(0, 0, Nothing, "")
For Each dmg In DamageLog
If dmg.CrewDamage > worstDmg.CrewDamage Then worstDmg = dmg
Next
Return worstDmg
End Function
Private Sub Death()
Dim repType As ReportType
If TypeOf Ship Is ShipPlayer Then repType = ReportType.CrewDeath Else repType = ReportType.EnemyCrewDeath
Report.Add("[" & Ship.ID & "] " & _Name & " has perished!", repType)
If Ship.BattleSquare Is Nothing = False AndAlso Ship.BattleSquare.Battlefield Is Nothing = False Then Ship.BattleSquare.Battlefield.AddDead(Me) Else Ship.RemoveCrew(Me)
End Sub
#End Region
#Region "Movement"
Public Station As New CrewStation
Public BattleStation As New CrewStation
Public Ship As Ship
Public ShipQuarter As ShipQuarter
Public Role As CrewRole
Public Sub SetStation(ByVal aStation As CrewStation, ByVal inCombat As Boolean)
If inCombat = True Then BattleStation = aStation Else Station = aStation
End Sub
Public Quarters As ShipModule
Public Shrine As ShipModule
#End Region
#Region "Morale"
Public Morale As Integer
Public MoraleDemands As New Dictionary(Of GoodType, Integer)
Public MoraleWants As New Dictionary(Of GoodType, Integer)
Public ReadOnly Property MoraleLevel As CrewMorale
Get
Select Case Morale
Case Is <= 10 : Return CrewMorale.Mutinous
Case Is <= 25 : Return CrewMorale.Unhappy
Case Is <= 50 : Return CrewMorale.Neutral
Case Is <= 75 : Return CrewMorale.Content
Case Else : Return CrewMorale.Motivated
End Select
End Get
End Property
Public Sub TickMorale(Optional ByVal shoreProvisors As List(Of GoodType) = Nothing)
'morale ranges from 1 to 100
Dim change As Integer = 0
Dim hasEaten As Boolean = False
Dim hasDrunk As Boolean = False
For Each gt In MoraleDemands.Keys
Dim newChange As Integer = ConsumeGoods(gt, 1, 0, MoraleDemands(gt), shoreProvisors)
If gt = GoodType.Rations AndAlso newChange >= 0 Then hasEaten = True
If gt = GoodType.Water AndAlso newChange >= 0 Then hasDrunk = True
change += newChange
Next
If hasDrunk = True OrElse Race = CrewRace.Unrelinquished Then
For Each gt In MoraleWants.Keys
Dim newChange As Integer = ConsumeGoods(gt, 1, MoraleWants(gt), 0, shoreProvisors)
change += newChange
Next
End If
'special cases
Select Case Race
Case CrewRace.Seatouched
If shoreProvisors Is Nothing = False AndAlso shoreProvisors.Contains(GoodType.Salt) Then
change += 1
Else
If Shrine Is Nothing Then change -= 5 : Exit Select
change += Math.Ceiling(Shrine.Quality / 2)
End If
Case CrewRace.Unrelinquished
hasEaten = False
hasDrunk = False
If Ship.GetLeadership >= 7 Then change += 1
End Select
'other bonuses
If change >= 0 Then
If Quarters Is Nothing Then Throw New Exception("Crew has no quarters.")
change += (Quarters.Quality - 2)
change = Dev.Constrain(change, 0, 100)
'cooking
If hasEaten = True Then
If shoreProvisors Is Nothing = False AndAlso shoreProvisors.Contains(GoodType.Rations) Then
'eating at shore
change += 1
Else
Dim cook As Crew = Ship.GetCrew(Nothing, CrewRole.Cook)
If cook Is Nothing = False Then
change += Math.Ceiling(cook.GetSkillFromRole / 2)
Dim xp As Double = 0.25
cook.AddSkillXP(CrewSkill.Cooking, xp)
End If
End If
End If
End If
'apply
Morale = Dev.Constrain(Morale + change, 0, 100)
CType(Ship, ShipPlayer).MoraleChange += change
End Sub
Private Function ConsumeGoods(ByVal goodType As GoodType, ByVal qty As Integer, ByVal positiveChange As Integer, ByVal negativeChange As Integer, ByVal shoreProvisors As List(Of GoodType)) As Integer
If Not (TypeOf Ship Is ShipPlayer) Then Return 0
If shoreProvisors Is Nothing = False AndAlso shoreProvisors.Contains(goodType) Then Return positiveChange
Dim ps As ShipPlayer = CType(Ship, ShipPlayer)
Dim good As Good = good.Generate(goodType, -qty)
'shortcircuit for Greenskin mutation
If goodType = Pirates.GoodType.Rations AndAlso GetBonus("scar", "Greenskin") Is Nothing = False Then Return positiveChange
If ps.CheckGoodsFreeForConsumption(goodType) = False OrElse Ship.CheckAddGood(good) = False Then
Return negativeChange
Else
ps.AddGood(good)
If ps.GoodsConsumed.ContainsKey(goodType) = False Then ps.GoodsConsumed.Add(goodType, good.Generate(goodType))
ps.GoodsConsumed(goodType) += good
Return positiveChange
End If
End Function
Public Enum CrewMorale
Motivated
Content
Neutral
Unhappy
Mutinous
End Enum
#End Region
#Region "World"
Public Sub Tick(ByVal doctor As Crew)
TickMorale()
TickHeal(doctor)
'add xp for specialist roles
Select Case Role
Case CrewRole.Captain : AddSkillXP(CrewSkill.Leadership, 1)
Case CrewRole.FirstMate : AddSkillXP(CrewSkill.Leadership, 0.5)
Case CrewRole.Navigator : AddSkillXP(CrewSkill.Navigation, 1)
Case CrewRole.Sailor : AddSkillXP(CrewSkill.Sailing, 1)
Case CrewRole.Helmsman : AddSkillXP(CrewSkill.Sailing, 1)
Case CrewRole.Gunner 'handled in ship.shipattack
Case CrewRole.Cook 'handled in crew.tickmorale
Case CrewRole.Doctor 'handled in shipplayer.tick
End Select
End Sub
#End Region
#Region "Console"
Public Sub ConsoleReport()
Dim s As String = Dev.vbSpace(1)
Dim ss As String = Dev.vbSpace(2)
Dim t As Integer = 13
Console.WriteLine(_Name)
Console.WriteLine(s & "Race: " & Race.ToString)
Console.WriteLine(s & "Health: " & Health - DamageSustained & "/" & Health)
Console.WriteLine(s & "Morale: " & Morale & "/100 (" & MoraleLevel.ToString & ")")
Console.WriteLine(s & "Skills: ")
For Each k In Skills.Keys
Console.WriteLine(ss & Dev.vbTab(k.ToString & ":", t) & GetSkill(k))
Next
Console.WriteLine(s & "Talents: ")
For Each talent In Talents
Console.WriteLine(ss & talent.ToString)
Next
If Equipment.Count > 0 Then
For Each cb In Equipment
Console.WriteLine(s & "Equipment:")
Console.WriteLine(ss & cb.ToString)
Next
End If
End Sub
#End Region
End Class
|
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=NameOf(CommentFormatCodeFixProvider)), [Shared]>
Public Class VariableDeclarationCodeFixProvider
Inherits CodeFixProvider
Private Const title As String = "Variable declaration"
Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String)
Get
Return ImmutableArray.Create(VariableDeclarationAnalyzer.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().First(Function(f) TypeOf f Is FieldDeclarationSyntax OrElse TypeOf f Is LocalDeclarationStatementSyntax)
' Register a code action that will invoke the fix.
context.RegisterCodeFix(
CodeAction.Create(
title:=title,
createChangedDocument:=Function(c) Fix(context.Document, declaration, c),
equivalenceKey:=title),
diagnostic)
End Function
Private Async Function Fix(document As Document, declaration As SyntaxNode, cancellationToken As CancellationToken) As Task(Of Document)
Dim newDeclaration As SyntaxNode = Nothing
Dim localDeclaration = TryCast(declaration, LocalDeclarationStatementSyntax)
If (localDeclaration IsNot Nothing) Then newDeclaration = SyntaxFactory.LocalDeclarationStatement(localDeclaration.Modifiers, NewDeclarators(localDeclaration.Declarators, document))
Dim fieldDeclaration = TryCast(declaration, FieldDeclarationSyntax)
If (fieldDeclaration IsNot Nothing) Then newDeclaration = SyntaxFactory.FieldDeclaration(fieldDeclaration.AttributeLists, fieldDeclaration.Modifiers, NewDeclarators(fieldDeclaration.Declarators, document))
Return Await CodeFixHelper.ReplaceNodeInDocument(document, declaration, newDeclaration, cancellationToken)
End Function
Private Function NewDeclarators(oldDelcarators As SeparatedSyntaxList(Of VariableDeclaratorSyntax), document As Document) As SeparatedSyntaxList(Of VariableDeclaratorSyntax)
Dim result As New SeparatedSyntaxList(Of VariableDeclaratorSyntax)
For Each declarator In oldDelcarators
Dim typeOfDeclarator = DelcaratorType(declarator, document)
If typeOfDeclarator IsNot Nothing Then
If typeOfDeclarator.IsValueType Then
' Clear the initializer.
result = result.Add(ModifyDelcaratorInitializer(declarator, Nothing))
Else
If declarator.Initializer Is Nothing Then
' Add = Nothing initializer.
result = result.Add(ModifyDelcaratorInitializer(declarator, EqualsNothings()))
ElseIf TypeOf declarator.Initializer.Value Is ObjectCreationExpressionSyntax Then
' Convert to AsNew syntax.
result = result.Add(SyntaxFactory.VariableDeclarator(declarator.Names, SyntaxFactory.AsNewClause(DirectCast(declarator.Initializer.Value, NewExpressionSyntax)), Nothing))
End If
End If
End If
Next
Return result
End Function
Private Shared Function ModifyDelcaratorInitializer(delcarator As VariableDeclaratorSyntax, initializer As EqualsValueSyntax) As VariableDeclaratorSyntax
' Remove then add trivia to ensure it is preserved.
Return delcarator.WithoutTrivia().WithInitializer(initializer).WithTriviaFrom(delcarator)
End Function
Private Shared Function EqualsNothings() As EqualsValueSyntax
Return SyntaxFactory.EqualsValue(SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword)))
End Function
Private Shared Function DelcaratorType(declarator As VariableDeclaratorSyntax, document As Document) As ITypeSymbol
' Check if it has an as clause.
If (declarator.AsClause Is Nothing) Then Return Nothing
' This only makes sense for simple as clauses (as opposed to As New syntax).
Dim simpleAs = TryCast(declarator.AsClause, SimpleAsClauseSyntax)
If (simpleAs Is Nothing) Then Return Nothing
' Get info about type.
Dim initInfo = document.GetSemanticModelAsync().Result.GetTypeInfo(simpleAs.Type)
Return initInfo.Type
End Function
End Class |
'Standard dispense state codes
Public Enum EDispenseState As Integer
Ready = 101
Busy = 102
Auto = 201
Scheduled = 202
WaitDissolve = 205
Complete = 301
Manual = 302
[Error] = 309
End Enum |
Imports Microsoft.VisualBasic
Imports System.Xml
Public Class XMLTrafficHandler
Private Shared _xml As XmlDocument
Public Shared Property _xmlDoc() As XmlDocument
Get
'If _xml Is Nothing Then
' _xml = LoadXml()
'End If
Return _xml
End Get
Set(ByVal value As XmlDocument)
_xml = value
End Set
End Property
Public Shared Function LoadXml() As XmlDocument
Dim xml As New XmlDocument()
xml.Load(System.Configuration.ConfigurationManager.GetSection("appSettings")("TrafficDataPath").ToString)
Return xml
End Function
Public Shared Function LoadTrafficReport() As XMLTraffic
Dim Report As New XMLTraffic()
Dim ds As New DataSet
ds.ReadXml(System.Configuration.ConfigurationManager.GetSection("appSettings")("TrafficDataPath").ToString)
Dim record = (From p In ds.Tables(0) Where p.Item("Id") = 0).FirstOrDefault
If Not IsNothing(record) Then
Report.Road = If(Not String.IsNullOrEmpty(record.Item("Road").ToString), record.Item("Road").ToString, String.Empty)
Report.Current = If(Not String.IsNullOrEmpty(record.Item("Current").ToString), record.Item("Current").ToString, String.Empty)
Report.Trouble = If(Not String.IsNullOrEmpty(record.Item("Trouble").ToString), record.Item("Trouble").ToString, String.Empty)
Report.Construction = If(Not String.IsNullOrEmpty(record.Item("Construction").ToString), record.Item("Construction").ToString, String.Empty)
End If
Return Report
End Function
Public Shared Function LoadTrafficReportOLD() As XMLTraffic
Dim Report As New XMLTraffic()
Dim itemlist As XmlNodeList = _xmlDoc.DocumentElement.ChildNodes
For Each page As XmlNode In itemlist
Report.Road = If(Not IsNothing(page.Item("Road")), page.Item("Road").InnerText, String.Empty)
Report.Current = If(Not IsNothing(page.Item("Current")), page.Item("Current").InnerText, String.Empty)
Report.Trouble = If(Not IsNothing(page.Item("Trouble")), page.Item("Trouble").InnerText, String.Empty)
Report.Construction = If(Not IsNothing(page.Item("Construction")), page.Item("Construction").InnerText, String.Empty)
Next
Return Report
End Function
Public Shared Sub SaveTrafficReport(ByVal traffic As XMLTraffic)
UpdateTrafficReport(traffic)
End Sub
Public Shared Sub UpdateTrafficReport(ByVal traffic As XMLTraffic)
Dim doc As XDocument = XDocument.Load(System.Configuration.ConfigurationManager.GetSection("appSettings")("TrafficDataPath").ToString)
Dim record = (From r In doc.Root.Elements("Report") Where r.Attribute("Id") = 0.ToString).FirstOrDefault
Dim sRoad As String = traffic.Road
If sRoad = "" Then
sRoad = "<li>Road Conditions will be updated weekdays from 5 til 9 AM and from 3 til 6 PM.</li>"
Else
sRoad = traffic.Road
End If
Dim sCurrent As String = traffic.Current
If sCurrent = "" Then
sCurrent = "<li>Traffic Conditions will be updated weekdays from 5 til 9 AM and from 3 til 6 PM.</li>"
Else
sCurrent = traffic.Current
End If
Dim sTrouble As String = traffic.Trouble
If sTrouble = "" Then
sTrouble = "<li>Trouble Spots will be updated weekdays from 5 til 9 AM and from 3 til 6 PM.</li>"
Else
sTrouble = traffic.Trouble
End If
Dim sConstruction As String = traffic.Construction
If sConstruction = "" Then
sConstruction = "<li>Construction Delays will be updated weekdays from 5 til 9 AM and from 3 til 6 PM.</li>"
Else
sConstruction = traffic.Construction
End If
If Not IsNothing(record) Then
Try
record.SetElementValue("Road", sRoad)
record.SetElementValue("Current", sCurrent)
record.SetElementValue("Trouble", sTrouble)
record.SetElementValue("Construction", sConstruction)
doc.Save(System.Configuration.ConfigurationManager.GetSection("appSettings")("TrafficDataPath").ToString)
Catch ex As System.Exception
LogErrors.LogError(ex.Message & ": " & ex.StackTrace, "UpdateTrafficXMLDoc")
Throw
End Try
End If
End Sub
Private Shared Function GetXmlAttribute(ByVal name As String, ByVal value As String) As XmlAttribute
GetXmlAttribute = _xmlDoc.CreateAttribute(name)
GetXmlAttribute.Value = value
End Function
End Class
|
<CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1053:StaticHolderTypesShouldNotHaveConstructors")>
Public Class CountryFields
Public Const FULLCOUNTRYNAME As String = "FULLCOUNTRYNAME"
Public Const COUNTRYCODE As String = "COUNTRYCODE"
Public Const COUNTRYSTATUSCODEID As String = "COUNTRYSTATUSCODEID"
Public Const COUNTRYSTATUSDATE As String = "COUNTRYSTATUSDATE"
Public Const COUNTRYREGIONCODEID As String = "COUNTRYREGIONCODEID"
Public Const AREAINSQUAREKM As String = "AREAINSQUAREKM"
Public Const URBANPOPULATION As String = "URBANPOPULATION"
Public Const RURALPOPULATION As String = "RURALPOPULATION"
Public Const TOTALPOPULATION As String = "TOTALPOPULATION"
Public Const PEOPLEGROUPS As String = "PEOPLEGROUPS"
Public Const MAJORTOPOGRAPHICALFEATURECODEID As String = "MAJORTOPOGRAPHICALFEATURECODEID"
Public Const LANGUAGEAMHARIC As String = "LANGUAGEAMHARIC"
Public Const LANGUAGEARABIC As String = "LANGUAGEARABIC"
Public Const LANGUAGEBENGALI As String = "LANGUAGEBENGALI"
Public Const LANGUAGEBURMESE As String = "LANGUAGEBURMESE"
Public Const LANGUAGECHINESE As String = "LANGUAGECHINESE"
Public Const LANGUAGECREOLE As String = "LANGUAGECREOLE"
Public Const LANGUAGEENGLISH As String = "LANGUAGEENGLISH"
Public Const LANGUAGEFRENCH As String = "LANGUAGEFRENCH"
Public Const LANGUAGEHINDI As String = "LANGUAGEHINDI"
Public Const LANGUAGEKHMER As String = "LANGUAGEKHMER"
Public Const LANGUAGEKIRGHIZ As String = "LANGUAGEKIRGHIZ"
Public Const LANGUAGELAO As String = "LANGUAGELAO"
Public Const LANGUAGENEPALI As String = "LANGUAGENEPALI"
Public Const LANGUAGEROMANIAN As String = "LANGUAGEROMANIAN"
Public Const LANGUAGERUSSIAN As String = "LANGUAGERUSSIAN"
Public Const LANGUAGESINHALESE As String = "LANGUAGESINHALESE"
Public Const LANGUAGESISWATI As String = "LANGUAGESISWATI"
Public Const LANGUAGESPANISH As String = "LANGUAGESPANISH"
Public Const LANGUAGESWAHILI As String = "LANGUAGESWAHILI"
Public Const LANGUAGETAGALOG As String = "LANGUAGETAGALOG"
Public Const LANGUAGETAMIL As String = "LANGUAGETAMIL"
Public Const LANGUAGETHAI As String = "LANGUAGETHAI"
Public Const LANGUAGEURDU As String = "LANGUAGEURDU"
Public Const LANGUAGEOTHER As String = "LANGUAGEOTHER"
Public Const LANGUAGEOTHERDESC As String = "LANGUAGEOTHERDESC"
Public Const RELIGIONANIMIST As String = "RELIGIONANIMIST"
Public Const RELIGIONBUDDHIST As String = "RELIGIONBUDDHIST"
Public Const RELIGIONCATHOLIC As String = "RELIGIONCATHOLIC"
Public Const RELIGIONCOPTIC As String = "RELIGIONCOPTIC"
Public Const RELIGIONHINDU As String = "RELIGIONHINDU"
Public Const RELIGIONMUSLIM As String = "RELIGIONMUSLIM"
Public Const RELIGIONORTHODOX As String = "RELIGIONORTHODOX"
Public Const RELIGIONPROTESTANT As String = "RELIGIONPROTESTANT"
Public Const RELIGIONVOODOO As String = "RELIGIONVOODOO"
Public Const RELIGIONWITCHCRAFT As String = "RELIGIONWITCHCRAFT"
Public Const RELIGIONOTHER As String = "RELIGIONOTHER"
Public Const RELIGIONOTHERDESC As String = "RELIGIONOTHERDESC"
Public Const GOVERNMENTCAPITALIST As String = "GOVERNMENTCAPITALIST"
Public Const GOVERNMENTCOMMUNIST As String = "GOVERNMENTCOMMUNIST"
Public Const GOVERNMENTDEMOCRACY As String = "GOVERNMENTDEMOCRACY"
Public Const GOVERNMENTDICTATORSHIP As String = "GOVERNMENTDICTATORSHIP"
Public Const GOVERNMENTMONARCHY As String = "GOVERNMENTMONARCHY"
Public Const GOVERNMENTREPUBLIC As String = "GOVERNMENTREPUBLIC"
Public Const GOVERNMENTREVOLUTIONARY As String = "GOVERNMENTREVOLUTIONARY"
Public Const GOVERNMENTSOCIALIST As String = "GOVERNMENTSOCIALIST"
Public Const GOVERNMENTTRANSITIONAL As String = "GOVERNMENTTRANSITIONAL"
Public Const GOVERNMENTOTHER As String = "GOVERNMENTOTHER"
Public Const GOVERNMENTOTHERDESC As String = "GOVERNMENTOTHERDESC"
Public Const MAJORHOLIDAYSANDFESTIVALS As String = "MAJORHOLIDAYSANDFESTIVALS"
Public Const CULTURALTRADITIONS As String = "CULTURALTRADITIONS"
Public Const CHILDMORTALITYRATEUNDERFIVE As String = "CHILDMORTALITYRATEUNDERFIVE"
Public Const INFANTMORTALITYRATE As String = "INFANTMORTALITYRATE"
Public Const ANNUALINCOMEPERCAPITA As String = "ANNUALINCOMEPERCAPITA"
Public Const PERCENTPOPULATIONLIVINGLESSTHANONEDOLLAR As String = "PERCENTPOPULATIONLIVINGLESSTHANONEDOLLAR"
Public Const LIFEEXPECTANCYATBIRTH As String = "LIFEEXPECTANCYATBIRTH"
Public Const FERTILITYRATE As String = "FERTILITYRATE"
Public Const ADULTLITERACYRATE As String = "ADULTLITERACYRATE"
Public Const NETPRIMARYSCHOOLENROLLMENTATTENDANCE As String = "NETPRIMARYSCHOOLENROLLMENTATTENDANCE"
Public Const PERCENTCHILDRENREACHINGGRADEFIVE As String = "PERCENTCHILDRENREACHINGGRADEFIVE"
Public Const CHILDLABORPERCENTAGE As String = "CHILDLABORPERCENTAGE"
Public Const PERCENTINFANTSLOWBIRTHRATE As String = "PERCENTINFANTSLOWBIRTHRATE"
Public Const PERCENTCHILDRENUNDERFIVEUNDERWEIGHT As String = "PERCENTCHILDRENUNDERFIVEUNDERWEIGHT"
Public Const PERCENTCHILDRENUNDERFIVEWASTINGSTUNTED As String = "PERCENTCHILDRENUNDERFIVEWASTINGSTUNTED"
Public Const PERCENTURBANPOPULATIONUSINGIMPROVEDWATER As String = "PERCENTURBANPOPULATIONUSINGIMPROVEDWATER"
Public Const PERCENTRUALPOPULATIONUSINGIMPROVEDWATER As String = "PERCENTRUALPOPULATIONUSINGIMPROVEDWATER"
Public Const PERCENTTOTALPOPULATIONUSINGIMPROVEDWATER As String = "PERCENTTOTALPOPULATIONUSINGIMPROVEDWATER"
Public Const PERCENTURBANPOPULATIONUSINGADEQUATESANITATION As String = "PERCENTURBANPOPULATIONUSINGADEQUATESANITATION"
Public Const PERCENTRURALPOPULATIONUSINGADEQUATESANITATION As String = "PERCENTRURALPOPULATIONUSINGADEQUATESANITATION"
Public Const HIVAIDSADULTPREVALENCERATE As String = "HIVAIDSADULTPREVALENCERATE"
Public Const NUMBERPEOPLELIVINGWITHIVAIDS As String = "NUMBERPEOPLELIVINGWITHIVAIDS"
Public Const QUOTATYPECODE As String = "QUOTATYPECODE"
Public Const DECREASEDQUOTA As String = "DECREASEDQUOTA"
Public Const GROWTHQUOTA As String = "GROWTHQUOTA"
Public Const CURRENTQUOTA As String = "CURRENTQUOTA"
Public Const APPROVEDQUOTAINITIAL As String = "APPROVEDQUOTAINITIAL"
Public Const APPROVEDQUOTA01OCT As String = "APPROVEDQUOTA01OCT"
Public Const APPROVEDQUOTA02NOV As String = "APPROVEDQUOTA02NOV"
Public Const APPROVEDQUOTA03DEC As String = "APPROVEDQUOTA03DEC"
Public Const APPROVEDQUOTA04JAN As String = "APPROVEDQUOTA04JAN"
Public Const APPROVEDQUOTA05FEB As String = "APPROVEDQUOTA05FEB"
Public Const APPROVEDQUOTA06MAR As String = "APPROVEDQUOTA06MAR"
Public Const APPROVEDQUOTA07APR As String = "APPROVEDQUOTA07APR"
Public Const APPROVEDQUOTA08MAY As String = "APPROVEDQUOTA08MAY"
Public Const APPROVEDQUOTA09JUN As String = "APPROVEDQUOTA09JUN"
Public Const APPROVEDQUOTA10JUL As String = "APPROVEDQUOTA10JUL"
Public Const APPROVEDQUOTA11AUG As String = "APPROVEDQUOTA11AUG"
Public Const APPROVEDQUOTA12SEP As String = "APPROVEDQUOTA12SEP"
Public Const NEWCHILDRENSTATUSCODE As String = "NEWCHILDRENSTATUSCODE"
Public Const PERFORMANCECODEID As String = "PERFORMANCECODEID"
Public Const MARKETINGDEMANDSTATUSCODE As String = "MARKETINGDEMANDSTATUSCODE"
Public Const OVERRIDETRIGGERSTATUSCODE As String = "OVERRIDETRIGGERSTATUSCODE"
Public Const CHILDRENNOTENTERED As String = "CHILDRENNOTENTERED"
'View specific fields
Public Const COUNTRYSTATUSCODE As String = "COUNTRYSTATUSCODE"
Public Const COUNTRYREGIONCODE As String = "COUNTRYREGIONCODE"
Public Const MAJORTOPOGRAPHICALFEATURECODE As String = "MAJORTOPOGRAPHICALFEATURECODE"
Public Const PERFORMANCECODE As String = "PERFORMANCECODE"
Public Const LANGUAGEOTHERSEPARATOR As String = "LANGUAGEOTHERSEPARATOR"
Public Const RELIGIONOTHERSEPARATOR As String = "RELIGIONOTHERSEPARATOR"
Public Const GOVERNMENTOTHERSEPARATOR As String = "GOVERNMENTOTHERSEPARATOR"
End Class
|
Public Class DonViTinhDTO
Private iMaDonViTinh As Integer
Private strTenDonViTinh As String
Public Sub New()
End Sub
Public Sub New(iMaDonViTinh As Integer, strTenDonViTinh As String)
Me.iMaDonViTinh = iMaDonViTinh
Me.strTenDonViTinh = strTenDonViTinh
End Sub
Public Property MaDonViTinh As Integer
Get
Return iMaDonViTinh
End Get
Set(value As Integer)
iMaDonViTinh = value
End Set
End Property
Public Property TenDonViTinh As String
Get
Return strTenDonViTinh
End Get
Set(value As String)
strTenDonViTinh = value
End Set
End Property
End Class
|
' Agreggate Root
Public Class Restaurante
Private _nombre As String
Private _lasRecomendaciones As IList(Of Recomendacion)
Public Sub New(nombre As String, lasRecomendaciones As IList(Of Recomendacion))
_nombre = nombre
_lasRecomendaciones = New List(Of Recomendacion)
End Sub
Public Sub New(nombre As String)
_nombre = nombre
_lasRecomendaciones = New List(Of Recomendacion)
End Sub
Function RegistreRecomendacion(persona As String, opinion As String, laCalificacion As Calificacion, fechaDeVisita As String, fechaDeHoy As Date) As Boolean
Dim r As New Dominio.Recomendacion
r.RealizadaPor = persona
r.Opinion = opinion
r.Calificacion = laCalificacion
r.FechaDeVisita = fechaDeVisita
r.FechaCuandoFueRegistrada = fechaDeHoy
If RecomendacionPuedeRegistrarse(r.RealizadaPor, fechaDeHoy) Then
_lasRecomendaciones.Add(r)
Return True
Else
Return False
End If
End Function
Public Function RecomendacionPuedeRegistrarse(recomendador As String, fechaDehoy As Date) As Boolean
If NoHayMasDeLaMismaPersona(recomendador) Then
Return True
Else
Return NoHayRecomendacionesRecientes(recomendador, fechaDehoy)
End If
End Function
Private Function NoHayMasDeLaMismaPersona(realizadaPor As String) As Boolean
Dim resultados = _lasRecomendaciones.Where(Function(c) c.RealizadaPor.Equals(realizadaPor)).Select(Function(c) c)
Return resultados.Count = 0
End Function
Private Function NoHayRecomendacionesRecientes(realizadaPor As String, fechaDehoy As Date) As Boolean
Dim resultados = _lasRecomendaciones.Where(Function(c) c.RealizadaPor.Equals(realizadaPor)).Select(Function(c) c)
For Each c In resultados
If c.FechaCuandoFueRegistrada.AddDays(7).CompareTo(fechaDehoy) > 0 Then
Return False
End If
Next
Return True
End Function
Function DemeRecomendacionMasRecienteDe(elRecomendador As String) As Recomendacion
Return _lasRecomendaciones.Where(Function(c) c.RealizadaPor.Equals(elRecomendador)).Select(Function(c) c).FirstOrDefault
End Function
Function DemeRecomendacionesDe(elRecomendador As String) As IList(Of Recomendacion)
Return _lasRecomendaciones.Where(Function(c) c.RealizadaPor.Equals(elRecomendador)).Select(Function(c) c).ToList
End Function
End Class
|
Imports CommonUtility
''' <summary>
''' 中科目マスタのアクセスクラスです
''' </summary>
''' <remarks></remarks>
Public Class M_CYUKAMOKURead
Private M_CYUKAMOKUValue As dsM_CYUKAMOKU
''' <summary>
''' M_CYUKAMOKU型として中科目マスタを返します。
''' </summary>
''' <returns>中科目マスタ</returns>
''' <remarks></remarks>
Public Function GetM_CYUKAMOKU() As dsM_CYUKAMOKU
Return M_CYUKAMOKUValue
End Function
''' <summary>
''' M_CYUKAMOKU型として中科目マスタを返します。
''' </summary>
''' <returns>中科目マスタ</returns>
''' <remarks></remarks>
Public Function Item() As dsM_CYUKAMOKU
Return GetM_CYUKAMOKU()
End Function
Public Sub New()
M_CYUKAMOKUValue = Nothing
Dim resultDataSets As New dsM_CYUKAMOKU
'DAC作成
Using masterAdapter As New dsM_CYUKAMOKUTableAdapters.M_CYUKAMOKUTableAdapter,
connection As New System.Data.SqlClient.SqlConnection(CommonUtility.DBUtility.GetConnectionString)
masterAdapter.Connection = connection : DBUtility.SetCommandTimeout(masterAdapter)
masterAdapter.Fill(resultDataSets.M_CYUKAMOKU)
End Using
M_CYUKAMOKUValue = resultDataSets
End Sub
Public Sub New(ByVal kamokuCode As String)
M_CYUKAMOKUValue = Nothing
Dim resultDataSets As New dsM_CYUKAMOKU
'DAC作成
Using masterAdapter As New dsM_CYUKAMOKUTableAdapters.M_CYUKAMOKUTableAdapter,
connection As New System.Data.SqlClient.SqlConnection(CommonUtility.DBUtility.GetConnectionString)
masterAdapter.Connection = connection : DBUtility.SetCommandTimeout(masterAdapter)
masterAdapter.FillByPK(resultDataSets.M_CYUKAMOKU, kamokuCode)
End Using
M_CYUKAMOKUValue = resultDataSets
End Sub
End Class
|
Imports Microsoft.VisualBasic.CompilerServices
Imports System
<OptionText()>
Public Class Paginas
Private vDirRepositorio As String
Private vNombreDirDiccionario As String
Private vNombreArchivoImagen As String
Public Property dirRepositorio As String
Get
Return Me.vDirRepositorio
End Get
Set(ByVal value As String)
Me.vDirRepositorio = value
End Set
End Property
Public Property nombreArchivoImagen As String
Get
Return Me.vNombreArchivoImagen
End Get
Set(ByVal value As String)
Me.vNombreArchivoImagen = value
End Set
End Property
Public Property nombreDirDiccionario As String
Get
Return Me.vNombreDirDiccionario
End Get
Set(ByVal value As String)
Me.vNombreDirDiccionario = value
End Set
End Property
Public ReadOnly Property urlImagen As String
Get
Dim str As String = String.Concat(Me.dirRepositorio, Me.nombreDirDiccionario, "\", Me.nombreArchivoImagen)
Return str
End Get
End Property
Public Sub New()
MyBase.New()
End Sub
End Class |
Option Strict Off
Public Class frmSalesTaxCalc
Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
'Close application.
Me.Close()
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
'Reset form.
txtRetailSale.Text = Nothing
txtTaxRate.Text = Nothing
lblTax.Text = "$0.00"
lblSalesTotal.Text = "$0.00"
End Sub
Private Sub btnCalculate_Click(sender As System.Object, e As System.EventArgs) Handles btnCalculate.Click
Try
Dim dblRetailSale As Double
Dim dblTaxRate As Double
Dim dblSalesTax As Double
Dim dblTotal As Double
dblRetailSale = CDbl(txtRetailSale.Text)
'Allow usage of both percentages and decimals.
If (txtTaxRate.Text.Contains("%")) Then
dblTaxRate = Double.Parse((txtTaxRate.Text.Replace("%", "")) / 100)
Else
dblTaxRate = CDbl(txtTaxRate.Text)
End If
dblSalesTax = dblRetailSale * dblTaxRate
dblTotal = dblRetailSale + dblSalesTax
lblTax.Text = dblSalesTax.ToString("C")
lblSalesTotal.Text = dblTotal.ToString("C")
'If user inputs invalid characters, display error window with sound.
Catch FormatError As InvalidCastException
System.Media.SystemSounds.Exclamation.Play()
Dim message As String
Dim caption As String
message = "Can only input numbers!"
caption = "Format Exception"
MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
End Class
|
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Threading
Imports System.Web.Profile
Imports MB.TheBeerHouse.DAL
Imports System.Text.RegularExpressions
Imports System.Net.Mail
Namespace MB.TheBeerHouse.BLL.Newsletters
Public Structure SubscriberInfo
Public UserName As String
Public Email As String
Public FirstName As String
Public LastName As String
Public SubscriptionType As SubscriptionType
Public Sub New(ByVal userName As String, ByVal email As String, ByVal firstName As String, _
ByVal lastName As String, ByVal subscriptionType As SubscriptionType)
Me.UserName = userName
Me.Email = email
Me.FirstName = firstName
Me.LastName = lastName
Me.SubscriptionType = subscriptionType
End Sub
End Structure
Public Class Newsletter
Inherits BizObject
' ==========
' Private Variables
' ==========
Private _id As Integer = 0
Private _addedDate As DateTime = DateTime.Now
Private _addedBy As String = ""
Private _subject As String = ""
Private _plainTextBody As String ' For those that don't know:
' this is the equivalent of C# setting for null. VB variables are
' not assigned until initialized and are therefore null. Setting
' the VB variable to "nothing" initializes the variable type and sets
' it to a default value, ie. an empty string
Private _htmlBody As String
Public Shared Lock As New ReaderWriterLock
Private Shared _isSending As Boolean = False
Private Shared _percentageCompleted As Double = 0.0
Private Shared _totalMails As Integer = -1
Private Shared _sentMails As Integer = 0
' ==========
' Properties
' ==========
Public Shared ReadOnly Property Settings() As NewslettersElement
Get
Return Globals.Settings.Newsletters
End Get
End Property
Public Property ID() As Integer
Get
Return _id
End Get
Set(ByVal value As Integer)
_id = value
End Set
End Property
Public Property AddedDate() As DateTime
Get
Return _addedDate
End Get
Set(ByVal value As DateTime)
_addedDate = value
End Set
End Property
Public Property AddedBy() As String
Get
Return _addedBy
End Get
Set(ByVal value As String)
_addedBy = value
End Set
End Property
Public Property Subject() As String
Get
Return _subject
End Get
Set(ByVal value As String)
_subject = value
End Set
End Property
Public Property PlainTextBody() As String
Get
If IsNothing(_plainTextBody) Then
FillBody()
End If
Return _plainTextBody
End Get
Set(ByVal value As String)
_plainTextBody = value
End Set
End Property
Public Property HtmlBody() As String
Get
If IsNothing(_htmlBody) Then
FillBody()
End If
Return _htmlBody
End Get
Set(ByVal value As String)
_htmlBody = value
End Set
End Property
Public Shared Property IsSending() As Boolean
Get
Return _isSending
End Get
Set(ByVal value As Boolean)
_isSending = value
End Set
End Property
Public Shared Property PercentageCompleted() As Double
Get
Return _percentageCompleted
End Get
Set(ByVal value As Double)
_percentageCompleted = value
End Set
End Property
Public Shared Property TotalMails() As Integer
Get
Return _totalMails
End Get
Set(ByVal value As Integer)
_totalMails = value
End Set
End Property
Public Shared Property SentMails() As Integer
Get
Return _sentMails
End Get
Set(ByVal value As Integer)
_sentMails = value
End Set
End Property
' ==========
' Constructor
' ==========
Public Sub New(ByVal id As Integer, ByVal addedDate As DateTime, ByVal addedBy As String, _
ByVal subject As String, ByVal plainTextBody As String, ByVal htmlBody As String)
Me.ID = id
Me.AddedBy = addedBy
Me.AddedDate = addedDate
Me.Subject = subject
Me.PlainTextBody = plainTextBody
Me.HtmlBody = htmlBody
End Sub
' ==========
' Methods
' ==========
Public Function Delete() As Boolean
Dim success As Boolean = Newsletter.DeleteNewsletter(Me.ID)
If success Then
Me.ID = 0
End If
Return success
End Function
Public Function Update() As Boolean
Return Newsletter.UpdateNewsletter(Me.ID, Me.Subject, Me.PlainTextBody, Me.HtmlBody)
End Function
Private Sub FillBody()
Dim record As NewsletterDetails = SiteProvider.Newsletters.GetNewsletterByID(Me.ID)
Me.PlainTextBody = record.PlainTextBody
Me.HtmlBody = record.HtmlBody
End Sub
' ==========
' Shared Methods
' ==========
' Returns a collection with all newsletters sent before the specified date
Public Shared Function GetNewsletters() As List(Of Newsletter)
Return GetNewsletters(DateTime.Now)
End Function
Public Shared Function GetNewsletters(ByVal toDate As DateTime) As List(Of Newsletter)
Dim newsletters As List(Of Newsletter)
Dim key As String = "Newsletters_Newsletters_" + toDate.ToShortDateString()
If Settings.EnableCaching AndAlso Not IsNothing(BizObject.Cache(key)) Then
newsletters = CType(BizObject.Cache(key), List(Of Newsletter))
Else
Dim recordset As List(Of NewsletterDetails) = SiteProvider.Newsletters.GetNewsLetters(toDate)
newsletters = GetNewsletterListFromNewsletterDetailsList(recordset)
CacheData(key, newsletters)
End If
Return newsletters
End Function
' Returns a Newsletter object with the specified ID
Public Shared Function GetNewslettersByID(ByVal newsletterID As Integer) As Newsletter
Dim newsletter As Newsletter
Dim key As String = "Newsletters_Newsletter_" + newsletterID.ToString()
If Settings.EnableCaching AndAlso Not IsNothing(BizObject.Cache(key)) Then
newsletter = CType(BizObject.Cache(key), Newsletter)
Else
newsletter = GetNewsletterFromNewsletterDetails( _
SiteProvider.Newsletters.GetNewsletterByID(newsletterID))
CacheData(key, newsletter)
End If
Return newsletter
End Function
' Updates an existing newsletter
Public Shared Function UpdateNewsletter(ByVal id As Integer, ByVal subject As String, _
ByVal plainTextBody As String, ByVal htmlBody As String) As Boolean
Dim record As New NewsletterDetails(id, DateTime.Now, "", subject, plainTextBody, htmlBody)
Dim ret As Boolean = SiteProvider.Newsletters.UpdateNewsletter(record)
BizObject.PurgeCacheItems("newsletters_newsletter")
Return ret
End Function
' Deletes an existing newsletter
Public Shared Function DeleteNewsletter(ByVal id As Integer) As Boolean
Dim ret As Boolean = SiteProvider.Newsletters.DeleteNewsletter(id)
Dim ev As New RecordDeletedEvent("newsletter", id, Nothing)
ev.Raise()
BizObject.PurgeCacheItems("newsletters_newsletter")
Return ret
End Function
' Sends a newsletter
Public Shared Function SendNewsletter(ByVal subject As String, ByVal plainTextBody As String, ByVal htmlBody As String) As Integer
Lock.AcquireWriterLock(Timeout.Infinite)
Newsletter.TotalMails = -1
Newsletter.SentMails = 0
Newsletter.PercentageCompleted = 0.0
Newsletter.IsSending = True
Lock.ReleaseWriterLock()
' if the HTML body is an empty string, use the plain-text body
' converted to HTML
If htmlBody.Trim.Length = 0 Then
htmlBody = HttpUtility.HtmlEncode(plainTextBody).Replace( _
" ", " ").Replace("\t", " ").Replace("\n", "<br />")
End If
' create the record into the DB
Dim record As New NewsletterDetails(0, DateTime.Now, BizObject.CurrentUserName, _
subject, plainTextBody, htmlBody)
Dim ret As Integer = SiteProvider.Newsletters.InsertNewsletter(record)
BizObject.PurgeCacheItems("newsletters_newsletters_" & DateTime.Now.ToShortDateString)
' send the newsletters asyncronously
Dim parameters() As Object = {subject, plainTextBody, htmlBody, HttpContext.Current}
Dim pts As New ParameterizedThreadStart(AddressOf SendEmails)
Dim thread As New Thread(pts)
thread.Name = "SendEmails"
thread.Priority = ThreadPriority.BelowNormal
thread.Start(parameters)
Return ret
End Function
' Sends the newsletter e-mails to all subscribers
Public Shared Sub SendEmails(ByVal data As Object)
Dim parameters() As Object = CType(data, Object())
Dim subject As String = CStr(parameters(0))
Dim plainTextBody As String = CStr(parameters(1))
Dim htmlBody As String = CStr(parameters(2))
Dim context As HttpContext = CType(parameters(3), HttpContext)
Lock.AcquireWriterLock(Timeout.Infinite)
Newsletter.TotalMails = 0
Lock.ReleaseWriterLock()
' check if the plain-text and HTML bodies have personalization placeholders
' the will need to be replaced on a per-mail basis. If not, the parsing will
' be completely avoided later.
Dim plainTextIsPersonalized As Boolean = HasPersonalizationPlaceholders(plainTextBody, False)
Dim htmlIsPersonalized As Boolean = HasPersonalizationPlaceholders(htmlBody, True)
' retreive all subscribers to the plain-text and HTML newsletter
Dim subscribers As New List(Of SubscriberInfo)
Dim profile As ProfileCommon = CType(context.Profile, ProfileCommon)
For Each user As MembershipUser In Membership.GetAllUsers
Dim userProfile As ProfileCommon = profile.GetProfile(user.UserName)
If Not userProfile.Preferences.Newsletter = SubscriptionType.None Then
Dim subscriber As New SubscriberInfo(user.UserName, user.Email, _
userProfile.FirstName, userProfile.LastName, userProfile.Preferences.Newsletter)
subscribers.Add(subscriber)
Lock.AcquireWriterLock(Timeout.Infinite)
Newsletter.TotalMails += 1
Lock.ReleaseWriterLock()
End If
Next
' send the newsletter
Dim smtpClient As New SmtpClient
For Each subscriber As SubscriberInfo In subscribers
Dim mail As New MailMessage
mail.From = New MailAddress(Settings.FromEmail, Settings.FromDisplayName)
mail.To.Add(subscriber.Email)
mail.Subject = subject
If subscriber.SubscriptionType = SubscriptionType.PlainText Then
Dim body As String = plainTextBody
If plainTextIsPersonalized Then
body = ReplacePersonalizationPlaceholders(body, subscriber, False)
End If
mail.Body = body
mail.IsBodyHtml = False
Else
Dim body As String = htmlBody
If htmlIsPersonalized Then
body = ReplacePersonalizationPlaceholders(body, subscriber, True)
End If
mail.Body = body
mail.IsBodyHtml = True
End If
Try
smtpClient.Send(mail)
Catch
End Try
Lock.AcquireWriterLock(Timeout.Infinite)
Newsletter.SentMails += 1
Newsletter.PercentageCompleted = CDbl(Newsletter.SentMails) * 100 / CDbl(Newsletter.TotalMails)
Lock.ReleaseWriterLock()
Next
Lock.AcquireWriterLock(Timeout.Infinite)
Newsletter.IsSending = False
Lock.ReleaseWriterLock()
End Sub
' Returns whether the input text contains personalization placeholders
Private Shared Function HasPersonalizationPlaceholders(ByVal text As String, ByVal isHtml As Boolean) As Boolean
If isHtml Then
If Regex.IsMatch(text, "<%\s*username\s*%>", RegexOptions.IgnoreCase Or _
RegexOptions.Compiled) Then
Return True
End If
If Regex.IsMatch(text, "<%\s*email\s*%>", RegexOptions.IgnoreCase Or _
RegexOptions.Compiled) Then
Return True
End If
If Regex.IsMatch(text, "<%\s*firstname\s*%>", RegexOptions.IgnoreCase Or _
RegexOptions.Compiled) Then
Return True
End If
If Regex.IsMatch(text, "<%\s*lastname\s*%>", RegexOptions.IgnoreCase Or _
RegexOptions.Compiled) Then
Return True
End If
Else
If Regex.IsMatch(text, "<%\s*username\s*%>", RegexOptions.IgnoreCase Or _
RegexOptions.Compiled) Then
Return True
End If
If Regex.IsMatch(text, "<%\s*email\s*%>", RegexOptions.IgnoreCase Or _
RegexOptions.Compiled) Then
Return True
End If
If Regex.IsMatch(text, "<%\s*firstname\s*%>", RegexOptions.IgnoreCase Or _
RegexOptions.Compiled) Then
Return True
End If
If Regex.IsMatch(text, "<%\s*lastname\s*%>", RegexOptions.IgnoreCase Or _
RegexOptions.Compiled) Then
Return True
End If
End If
Return False
End Function
' Replaces the input text's personalization placeholders
Private Shared Function ReplacePersonalizationPlaceholders(ByVal text As String, _
ByVal subscriber As SubscriberInfo, ByVal isHtml As Boolean) As String
If isHtml Then
text = Regex.Replace(text, "<%\s*username\s*%>", _
subscriber.UserName, RegexOptions.IgnoreCase Or RegexOptions.Compiled)
text = Regex.Replace(text, "<%\s*email\s*%>", _
subscriber.Email, RegexOptions.IgnoreCase Or RegexOptions.Compiled)
Dim firstName As String = "reader"
If subscriber.FirstName.Length > 0 Then
firstName = subscriber.FirstName
End If
text = Regex.Replace(text, "<%\s*firstname\s*%>", firstName, _
RegexOptions.IgnoreCase Or RegexOptions.Compiled)
text = Regex.Replace(text, "<%\s*lastname\s*%>", _
subscriber.LastName, RegexOptions.IgnoreCase Or RegexOptions.Compiled)
Else
text = Regex.Replace(text, "<%\s*username\s*%>", _
subscriber.UserName, RegexOptions.IgnoreCase Or RegexOptions.Compiled)
text = Regex.Replace(text, "<%\s*email\s*%>", _
subscriber.Email, RegexOptions.IgnoreCase Or RegexOptions.Compiled)
Dim firstName As String = "reader"
If subscriber.FirstName.Length > 0 Then
firstName = subscriber.FirstName
End If
text = Regex.Replace(text, "<%\s*firstname\s*%>", firstName, _
RegexOptions.IgnoreCase Or RegexOptions.Compiled)
text = Regex.Replace(text, "<%\s*lastname\s*%>", _
subscriber.LastName, RegexOptions.IgnoreCase Or RegexOptions.Compiled)
End If
Return text
End Function
' Returns a Newsletter object filled with the data taken from the input NewsletterDetails
Private Shared Function GetNewsletterFromNewsletterDetails(ByVal record As NewsletterDetails) _
As Newsletter
If IsNothing(record) Then
Return Nothing
Else
Return New Newsletter(record.ID, record.AddedDate, record.AddedBy, record.Subject, _
record.PlainTextBody, record.HtmlBody)
End If
End Function
' Returns a list of Newsletter objects filled with the data taken from the input list of NewsletterDetails
Private Shared Function GetNewsletterListFromNewsletterDetailsList( _
ByVal recordset As List(Of NewsletterDetails)) _
As List(Of Newsletter)
Dim newsletters As New List(Of Newsletter)
For Each record As NewsletterDetails In recordset
newsletters.Add(GetNewsletterFromNewsletterDetails(record))
Next
Return newsletters
End Function
' Cache the input data, if caching is enabled
Private Shared Sub CacheData(ByVal key As String, ByVal data As Object)
If Settings.EnableCaching AndAlso Not IsNothing(data) Then
BizObject.Cache.Insert(key, data, Nothing, DateTime.Now.AddSeconds(Settings.CacheDuration), _
TimeSpan.Zero)
End If
End Sub
End Class
End Namespace
|
Imports System.Windows.Threading
Class GamePage
Private Field As Maze
Private Timer As DispatcherTimer
Private Paused As Boolean = False
Private BoundWindow As Window
Private Sub TogglePaused() Handles PlayPause.Click
If Paused Then
' Play
Paused = False
PlayPause.Template = Resources("PauseButton")
PauseBar.BeginStoryboard(Me.Resources("PauseBar.FadeOut"))
Else
' Pause
Paused = True
PlayPause.Template = Resources("PlayButton")
PauseBar.BeginStoryboard(Me.Resources("PauseBar.FadeIn"))
End If
End Sub
Private Sub Home() Handles HomeButton.Click
NavigationService.Navigate(New Uri("/Pages/TitlePage.xaml", UriKind.RelativeOrAbsolute))
End Sub
Private Sub Restart() Handles RestartButton.Click
NavigationService.Refresh()
End Sub
Private Sub Ready(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
PlayTrack(Track.Game)
Field = Level
Field.AddEntity(New Countdown)
BoundWindow = Window.GetWindow(Me)
Keyboard.AddKeyUpHandler(BoundWindow, AddressOf KeyPressed)
Timer = New DispatcherTimer(TimeSpan.FromMilliseconds(10), DispatcherPriority.Normal,
Sub()
If Not Paused Then Field.Tick()
End Sub, Dispatcher)
End Sub
Sub KeyPressed(sender As Object, e As KeyEventArgs)
If e.Key = Key.P Then TogglePaused()
End Sub
Private Sub Goodbye(sender As Object, e As RoutedEventArgs) Handles Me.Unloaded
Keyboard.RemoveKeyUpHandler(BoundWindow, AddressOf KeyPressed)
Timer.Stop()
End Sub
End Class
|
Imports System.Windows
Imports System.Windows.Input
Imports DevExpress.Mvvm.UI.Interactivity
Namespace NavigationDemo.Utils
Public Class SuppressMouseWheelBehavior
Inherits Behavior(Of UIElement)
Protected Overrides Sub OnAttached()
MyBase.OnAttached()
AddHandler AssociatedObject.PreviewMouseWheel, AddressOf OnPreviewMouseWheel
End Sub
Protected Overrides Sub OnDetaching()
MyBase.OnDetaching()
RemoveHandler AssociatedObject.PreviewMouseWheel, AddressOf OnPreviewMouseWheel
End Sub
Private Sub OnPreviewMouseWheel(ByVal sender As Object, ByVal e As MouseWheelEventArgs)
e.Handled = True
Dim args = New MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta)
args.RoutedEvent = UIElement.MouseWheelEvent
DirectCast(sender, UIElement).RaiseEvent(args)
End Sub
End Class
End Namespace
|
Imports System.IO
Imports System.Reactive.Linq
Public Class StockfishService
Implements IEngineService
Private strmReader As StreamReader
Private strmWriter As StreamWriter
Private engineProcess As Process
Private engineListener As IDisposable
Public Event EngineMessage(message As String) Implements IEngineService.EngineMessage
Public Sub SendCommand(command As String) Implements IEngineService.SendCommand
If strmWriter IsNot Nothing AndAlso command <> UciCommands.uci Then
strmWriter.WriteLine(command)
End If
End Sub
Public Sub StopEngine() Implements IEngineService.StopEngine
If engineProcess IsNot Nothing And Not engineProcess.HasExited Then
engineListener.Dispose()
strmReader.Close()
strmWriter.Close()
End If
End Sub
Public Sub StartEngine() Implements IEngineService.StartEngine
Dim engine As New FileInfo(Path.Combine(Environment.CurrentDirectory, "stockfish_8_x64.exe"))
If engine.Exists AndAlso engine.Extension = ".exe" Then
engineProcess = New Process
engineProcess.StartInfo.FileName = engine.FullName
engineProcess.StartInfo.UseShellExecute = False
engineProcess.StartInfo.RedirectStandardInput = True
engineProcess.StartInfo.RedirectStandardOutput = True
engineProcess.StartInfo.RedirectStandardError = True
engineProcess.StartInfo.CreateNoWindow = True
engineProcess.Start()
strmWriter = engineProcess.StandardInput
strmReader = engineProcess.StandardOutput
engineListener = Observable.Timer(TimeSpan.Zero, TimeSpan.FromMilliseconds(1)).Subscribe(Sub() ReadEngineMessages())
strmWriter.WriteLine(UciCommands.uci)
strmWriter.WriteLine(UciCommands.isready)
strmWriter.WriteLine(UciCommands.ucinewgame)
Else
Throw New FileNotFoundException
End If
End Sub
Private Sub ReadEngineMessages()
Dim message = strmReader.ReadLine()
If message <> String.Empty Then
RaiseEvent EngineMessage(message)
End If
End Sub
End Class |
'**************************************************************************
'*
'* A class for Base Table script object, inherits clsBaseTableObject
'*
'**************************************************************************
Public Class clsBaseTableObject
Inherits clsTableObject
#Region "Class declaration object"
'Shared class delaration
Private Shared intFileNameID As Integer
#End Region
#Region "Class constructors"
Public Sub New(ByVal strObjectType As String, ByVal objSystemArgs As Object(,))
'*************************************************************************
'* Function Name: New
'* Description: Public class constructor
'* Created by: Raz Davidovich
'* Created date: 10/02/2004
'* Last Modifyer: Raz Davidovich
'*************************************************************************
'Call the oveloaded constructor
Me.New(strObjectType, "Base_Table_Name_" & intFileNameID.ToString & "_Ta", objSystemArgs)
intFileNameID += 1
End Sub
Public Sub New(ByVal strObjectType As String, ByVal strObjectName As String, _
ByVal objSystemArgs As Object(,))
'*************************************************************************
'* Function Name: New
'* Description: Public class constructor
'* Created by: Raz Davidovich
'* Created date: 10/02/2004
'* Last Modifyer: Raz Davidovich
'*************************************************************************
'Call the oveloaded constructor
Me.New(strObjectType, strObjectName, "dbo", objSystemArgs)
End Sub
Public Sub New(ByVal strObjectType As String, ByVal strObjectName As String, _
ByVal strObjectOwner As String, ByVal objSystemArgs As Object(,))
'*************************************************************************
'* Function Name: New
'* Description: Public class constructor
'* Created by: Raz Davidovich
'* Created date: 10/02/2004
'* Last Modifyer: Raz Davidovich
'*************************************************************************
'Call the oveloaded constructor
Me.New(strObjectType, strObjectName, "dbo", True, True, objSystemArgs)
End Sub
Public Sub New(ByVal strObjectType As String, ByVal strObjectName As String, _
ByVal strObjectOwner As String, ByVal blnGenerateHeader As Boolean, ByVal objSystemArgs As Object(,))
'*************************************************************************
'* Function Name: New
'* Description: Public class constructor
'* Created by: Raz Davidovich
'* Created date: 10/02/2004
'* Last Modifyer: Raz Davidovich
'*************************************************************************
'Call the oveloaded constructor
Me.New(strObjectType, strObjectName, strObjectOwner, blnGenerateHeader, True, objSystemArgs)
End Sub
Public Sub New(ByVal strObjectType As String, ByVal strObjectName As String, _
ByVal strObjectOwner As String, ByVal blnGenerateHeader As Boolean, _
ByVal blnGenerateDropCommand As Boolean, ByVal objSystemArgs As Object(,))
'*************************************************************************
'* Function Name: New
'* Description: Public class constructor
'* Created by: Raz Davidovich
'* Created date: 10/02/2004
'* Last Modifyer: Raz Davidovich
'*************************************************************************
'Call the oveloaded constructor
Me.New(strObjectType, strObjectName, strObjectOwner, blnGenerateHeader, blnGenerateDropCommand, True, objSystemArgs)
End Sub
Public Sub New(ByVal strObjectType As String, ByVal strObjectName As String, _
ByVal strObjectOwner As String, ByVal blnGenerateHeader As Boolean, _
ByVal blnGenerateDropCommand As Boolean, ByVal blnGenerateTableKeys As Boolean, _
ByVal objSystemArgs As Object(,))
'*************************************************************************
'* Function Name: New
'* Description: Public class constructor
'* Created by: Raz Davidovich
'* Created date: 30/01/2005
'* Last Modifyer: Raz Davidovich
'*************************************************************************
MyBase.New(strObjectType, strObjectName, strObjectOwner, blnGenerateHeader, blnGenerateDropCommand, blnGenerateTableKeys, objSystemArgs)
Me.strSystemObjectType = "IsProcedure"
Me.strObjectName = "BT_" + Replace(strObjectName, "_Ta", "_Sp", , , CompareMethod.Text)
End Sub
#End Region
#Region "Class methods"
Public Overrides Function GenerateObjectScript() As String
'*************************************************************************
'* Function Name: GenerateObjectScript
'* Description: This class method generates the SQL Script
'* Created by: Raz Davidovich
'* Created date: 23/06/2005
'* Last Modifyer: Raz Davidovich
'*************************************************************************
Dim strTemp As String = String.Empty
'Generate the Object script header (if needed)
If blnGenerateHeader Then
strTemp += GenerateHeader()
End If
'Generate the Object drop script (if needed)
If blnGenerateDropCommand Then
strTemp += GenerateDrop()
End If
If objSystemArgs Is Nothing Then
strTemp += "/*===================================================================*/"
strTemp += vbCrLf
strTemp += "/*=== NO TABLE FIELDS WERE DEFINED OR BAD TABLE FIELDS DEFINITION ===*/"
strTemp += vbCrLf
strTemp += "/*===================================================================*/"
Else
strTemp += "CREATE PROCEDURE [" + strObjectOwner + "].[" + strObjectName + "] "
strTemp += vbCrLf
strTemp += vbTab + "@Operation INT," + vbCrLf
'Generate the parameters
strTemp += GenerateParameters()
strTemp += vbCrLf + "AS" + vbCrLf
'Generate the select part
strTemp += vbTab + "IF (@Operation = 1)" + vbCrLf
strTemp += vbTab + vbTab + "BEGIN" + vbCrLf
strTemp += vbTab + vbTab + vbTab + GenerateSelect() + vbCrLf
strTemp += vbTab + vbTab + "END" + vbCrLf
'Generate the Insert/Update part
strTemp += vbTab + "IF (@Operation = 2)" + vbCrLf
strTemp += vbTab + vbTab + "BEGIN" + vbCrLf
strTemp += vbTab + vbTab + vbTab + "IF EXISTS(" + GenerateSelect() + Space(1) + GenerateWhere() + ")" + vbCrLf
'Update the existing row
strTemp += vbTab + vbTab + vbTab + "BEGIN" + vbCrLf
strTemp += GenerateUpdate(vbTab + vbTab + vbTab + vbTab) + vbCrLf
strTemp += vbTab + vbTab + vbTab + "END" + vbCrLf
strTemp += vbTab + vbTab + "ELSE" + vbCrLf
'Insert a new row
strTemp += vbTab + vbTab + vbTab + "BEGIN" + vbCrLf
strTemp += GenerateInsert(vbTab + vbTab + vbTab + vbTab) + vbCrLf
strTemp += vbTab + vbTab + vbTab + "END" + vbCrLf
strTemp += vbTab + vbTab + "END" + vbCrLf
'Generate the Delete part
strTemp += vbTab + "IF(@Operation = 3)" + vbCrLf
strTemp += vbTab + vbTab + "BEGIN" + vbCrLf
strTemp += vbTab + vbTab + vbTab + GenerateDelete() + vbCrLf
strTemp += vbTab + vbTab + vbTab + GenerateWhere() + vbCrLf
strTemp += vbTab + vbTab + "END" + vbCrLf
strTemp += "GO"
strTemp += vbCrLf
strTemp += vbCrLf
End If
'Return the complete script
Return strTemp
End Function
Public Function GenerateConfigScript() As String
'*************************************************************************
'* Function Name: GenerateConfigScript
'* Description: This function generates a complete templete for the
'* base table config values (needs editing)
'* Created by: Raz Davidovich
'* Created date: 10/12/2007
'* Last Modifyer: Raz Davidovich
'*************************************************************************
Dim sbrConfig As New System.Text.StringBuilder
Dim clsAppAttribute As New clsApplicationAttributes
With sbrConfig
.AppendLine("<!-- The following table settings has been generated by " + clsAppAttribute.ApplicationTitle + " Version: " + clsAppAttribute.ApplicationVersion)
.AppendLine("<add key=""Table_" + objSystemArgs(1, 0).ToString + "_Text"" value=""" + strTableName + """ />")
End With
Return sbrConfig.ToString
End Function
#End Region
#Region "Class private functions"
Private Function GenerateSelect() As String
'*************************************************************************
'* Function Name: GenerateSelect
'* Description: This function generate a select statement for the
'* script
'* Created by: Raz Davidovich
'* Created date: 23/06/2005
'* Last Modifyer: Raz Davidovich
'*************************************************************************
'Generate the Select
Return "SELECT * FROM " + strObjectOwner + "." + strTableName
End Function
Private Function GenerateInsert(Optional ByVal strTabShift As String = vbNullString) As String
'*************************************************************************
'* Function Name: GenerateInsert
'* Description: This function generate a Insert statement for the
'* script
'* Created by: Raz Davidovich
'* Created date: 23/06/2005
'* Last Modifyer: Raz Davidovich
'*************************************************************************
Dim strTemp As String
Dim strTempFields As String
Dim strTempParameters As String
Dim blnDefaultValueUsed As Boolean
strTempParameters = "("
strTempFields = "("
'Loop the fields collection and generate script
For I As Integer = 0 To objSystemArgs.GetUpperBound(1)
'Generate field if it is not an identity field (Auto generated number)
If (objSystemArgs(5, I).ToString <> "Y") Then
'Reset the default values flag
blnDefaultValueUsed = False
'Start generate the SQL
If (objSystemArgs(1, I).ToString.Trim = vbNullString) Then
strTempParameters += "@" + DEFAULT_FIELD_NAME + "_" + I.ToString + ""
strTempFields += DEFAULT_FIELD_NAME + "_" + I.ToString + ""
blnDefaultValueUsed = True
Else
strTempParameters += GenerateParameter(objSystemArgs(1, I))
strTempFields += "[" + objSystemArgs(1, I) + "]"
End If
'Add comma if this is not the last field
If I <> objSystemArgs.GetUpperBound(1) Then
strTempParameters += ", "
strTempFields += ", "
End If
End If
Next
strTempParameters += ")"
strTempFields += ")"
'Combine the Insert
strTemp = strTabShift + "INSERT INTO " + strObjectOwner + "." + strTableName + vbCrLf
strTemp += strTabShift + vbTab + strTempFields + vbCrLf
strTemp += strTabShift + "VALUES" + vbCrLf
strTemp += strTabShift + vbTab + strTempParameters + vbCrLf
Return strTemp
End Function
Private Function GenerateUpdate(Optional ByVal strTabShift As String = vbNullString) As String
'*************************************************************************
'* Function Name: GenerateUpdate
'* Description: This function generate a Update statement for the
'* script
'* Created by: Raz Davidovich
'* Created date: 23/06/2005
'* Last Modifyer: Raz Davidovich
'*************************************************************************
Dim strTemp As String
'Generate the opening update clause
strTemp = strTabShift + "UPDATE " + strObjectOwner + "." + strTableName + " SET" + vbCrLf
'Generate the field list update
'Loop the fields collection and generate script
For I As Integer = 0 To objSystemArgs.GetUpperBound(1)
'Generate field if it is not an identity field (Auto generated number)
If (objSystemArgs(5, I).ToString <> "Y") Then
'Start generate the SQL
strTemp += strTabShift + vbTab + "[" + objSystemArgs(1, I) + "]" + " = " + GenerateParameter(objSystemArgs(1, I))
'Add comma if this is not the last field
If I <> objSystemArgs.GetUpperBound(1) Then strTemp += ", "
strTemp += vbCrLf
End If
Next
strTemp += strTabShift + GenerateWhere()
Return strTemp
End Function
Private Function GenerateDelete() As String
'*************************************************************************
'* Function Name: GenerateDelete
'* Description: This function generate a delete statement for the
'* script
'* Created by: Raz Davidovich
'* Created date: 23/06/2005
'* Last Modifyer: Raz Davidovich
'*************************************************************************
'Generate the Select
Return "DELETE FROM " + strObjectOwner + "." + strTableName
End Function
Private Function GenerateWhere() As String
'*************************************************************************
'* Function Name: GenerateWhere
'* Description: This function generate a where clause for the script
'* Created by: Raz Davidovich
'* Created date: 23/06/2005
'* Last Modifyer: Raz Davidovich
'*************************************************************************
Dim strTemp As String
Dim intKeyID As Integer = 1
'Generate the Select
strTemp = "WHERE "
For I As Integer = 0 To objSystemArgs.GetUpperBound(1)
If (objSystemArgs(4, I).ToString.Trim = "Y") Then
strTemp += "([" + objSystemArgs(1, I) + "] = " + "@Key" + intKeyID.ToString + ") AND "
intKeyID += 1
End If
Next
If strTemp.Trim.Length > 0 Then strTemp = strTemp.Remove(strTemp.Length - 5, 5)
Return strTemp
End Function
Private Function GenerateParameters() As String
'*************************************************************************
'* Function Name: GenerateParameters
'* Description: This function loops the fields collection and generate
'* the list of SP parameters for the script
'* Created by: Raz Davidovich
'* Created date: 23/06/2005
'* Last Modifyer: Raz Davidovich
'*************************************************************************
Dim strTemp As String = String.Empty
Dim intKeyID As Integer = 1
Dim blnDefaultValueUsed As Boolean
'=====================================
'= Step 1 - Generate fields parameters
'=====================================
'Loop the fields collection and generate script
For I As Integer = 0 To objSystemArgs.GetUpperBound(1)
'Reset the default values flag
blnDefaultValueUsed = False
'Start generate the SQL
If (objSystemArgs(1, I).ToString.Trim = vbNullString) Then
objSystemArgs(1, I) = DEFAULT_FIELD_NAME + "_" + I.ToString
strTemp += vbTab + "@" + DEFAULT_FIELD_NAME + "_" + I.ToString + vbTab + objSystemArgs(2, I)
blnDefaultValueUsed = True
Else
strTemp += vbTab + GenerateParameter(objSystemArgs(1, I)) + vbTab + objSystemArgs(2, I)
End If
If (LCase(objSystemArgs(2, I)) = "varchar") Or (LCase(objSystemArgs(2, I)) = "nvarchar") Then
strTemp += "("
If (objSystemArgs(3, I).ToString = vbNullString) Or Not IsNumeric(objSystemArgs(3, I)) Then
strTemp += DEFAULT_VARCHAR_LENGTH.ToString
blnDefaultValueUsed = True
Else
strTemp += objSystemArgs(3, I).ToString
End If
strTemp += ")"
End If
'If the current field is not a key, allow the field to accept null values
strTemp += " = NULL, "
'Add comma if this is not the last field
strTemp += IIf(blnDefaultValueUsed, " -- DEFAULT VALUES USED FOR THIS FIELD", String.Empty)
strTemp += vbCrLf
Next
'===========================================
'= Step 2 - Generate keys fields parameters
'===========================================
'Loop and add the primery key fields
For I As Integer = 0 To objSystemArgs.GetUpperBound(1)
If (objSystemArgs(4, I).ToString.Trim = "Y") Then
strTemp += vbTab + "@Key" + intKeyID.ToString + vbTab + objSystemArgs(2, I)
intKeyID += 1
If (LCase(objSystemArgs(2, I)) = "varchar") Or (LCase(objSystemArgs(2, I)) = "nvarchar") Then
strTemp += "("
If (objSystemArgs(3, I).ToString = vbNullString) Or Not IsNumeric(objSystemArgs(3, I)) Then
strTemp += DEFAULT_VARCHAR_LENGTH.ToString
blnDefaultValueUsed = True
Else
strTemp += objSystemArgs(3, I).ToString
End If
strTemp += ")"
End If
'If the current field is not a key, allow the field to accept null values
strTemp += " = NULL, "
'Add comma if this is not the last field
strTemp += IIf(blnDefaultValueUsed, " -- DEFAULT VALUES USED FOR THIS PARAMETER", String.Empty)
strTemp += vbCrLf
End If
Next
If strTemp.Trim.Length > 0 Then strTemp = strTemp.Remove(strTemp.Length - 4, 4) + vbCrLf
Return strTemp
End Function
#End Region
End Class
|
Imports System.Reflection
Imports SportingAppFW.Extensions
Imports SportingAppFW.Tools.SaAttributeUtility
Namespace Data.Common
Public Class SaFields
Inherits Object
' hashtable with propertyinfo, SaFieldsAttribute
Private _fieldAttributes As List(Of KeyValuePair(Of PropertyInfo, SaFieldsAttribute)) = New List(Of KeyValuePair(Of PropertyInfo, SaFieldsAttribute))()
Private _fieldUIAttributes As List(Of KeyValuePair(Of PropertyInfo, SaUIFieldsAttribute)) = New List(Of KeyValuePair(Of PropertyInfo, SaUIFieldsAttribute))()
Private _primaryKeys As String()
Private _names As String()
ReadOnly Property SaFielsdAttributes As List(Of KeyValuePair(Of PropertyInfo, SaFieldsAttribute))
Get
Return _fieldAttributes
End Get
End Property
ReadOnly Property SaUIFieldsAttributes As List(Of KeyValuePair(Of PropertyInfo, SaUIFieldsAttribute))
Get
Return _fieldUIAttributes
End Get
End Property
Public Shared Function GetSaFieldsAttribute(ByVal pro As PropertyInfo) As SaFieldsAttribute
Return CType(GetAttribute(pro, "SaFieldsAttribute"), SaFieldsAttribute)
End Function
Public Shared Function GetSaUIFieldsAttribute(ByVal pro As PropertyInfo) As SaUIFieldsAttribute
Return CType(GetAttribute(pro, "SaUIFieldsAttribute"), SaUIFieldsAttribute)
End Function
ReadOnly Property Names As String()
Get
Return _names
End Get
End Property
ReadOnly Property Values As String()
Get
Dim val = From attri As KeyValuePair(Of PropertyInfo, SaFieldsAttribute) In _fieldAttributes
Select attri.Key.GetValue(Me, Nothing).ToString().QuotedStr()
If val.Count < 1 Then
Return New String() {}
Else
Return val.ToArray()
End If
End Get
End Property
Public Function GetPropertyValue(ByVal propertyName As String) As Object
For Each attri As KeyValuePair(Of PropertyInfo, SaFieldsAttribute) In _fieldAttributes
If attri.Key.Name = propertyName Then
Dim res = attri.Key.GetValue(Me, Nothing)
If res IsNot Nothing Then
Return res
Else
Return attri.Value.DefaultValue
End If
End If
Next
Return Nothing
End Function
Sub New()
Try
For Each pro As PropertyInfo In Me.GetType.GetProperties()
Dim attri As SaFieldsAttribute = CType(GetAttribute(pro, "SaFieldsAttribute"), SaFieldsAttribute)
Dim attri2 As SaUIFieldsAttribute = CType(GetAttribute(pro, "SaUIFieldsAttribute"), SaUIFieldsAttribute)
If attri IsNot Nothing Then
_fieldAttributes.Add(New KeyValuePair(Of PropertyInfo, SaFieldsAttribute)(pro, attri))
If pro.CanWrite Then
If attri.HasDefaultValue Then
pro.SetValue(Me, attri.DefaultValue, Nothing)
Else
pro.SetValue(Me, Nothing, Nothing)
End If
End If
End If
If attri2 IsNot Nothing Then
_fieldUIAttributes.Add(New KeyValuePair(Of PropertyInfo, SaUIFieldsAttribute)(pro, attri2))
End If
Next
'所有欄位名稱
Dim val = From attri As KeyValuePair(Of PropertyInfo, SaFieldsAttribute) In _fieldAttributes
Select attri.Key.Name
If val.Count < 1 Then
_names = New String() {}
Else
_names = val.ToArray()
End If
'所有 primary keys
Dim attris = From attri As KeyValuePair(Of PropertyInfo, SaFieldsAttribute) In _fieldAttributes
Where attri.Value.PrimaryKey
Select attri.Key.Name
_primaryKeys = attris.ToArray()
Catch ex As Exception
Console.WriteLine(String.Format("{0} {1}", "SaFields", ex.Message))
End Try
End Sub
Public Function GetPrimaryKeys() As String()
Return _primaryKeys
End Function
Public Function GetPrimaryKeyValueSqls() As String()
Dim attris = From attri As KeyValuePair(Of PropertyInfo, SaFieldsAttribute) In _fieldAttributes
Where attri.Value.PrimaryKey
Select String.Format("({0} = {1})", attri.Key.Name, attri.Key.GetValue(Me, Nothing).ToString().QuotedStr())
If attris.Count = 0 Then
attris = From attri As KeyValuePair(Of PropertyInfo, SaFieldsAttribute) In _fieldAttributes
Where attri.Value.PrimaryKey
Select CType(IIf(attri.Key.GetValue(Me, Nothing) Is Nothing, String.Format("({0} IS NULL)", attri.Key.Name), String.Format("({0} = {1})", attri.Key.Name, attri.Key.GetValue(Me, Nothing).ToString().QuotedStr())), String)
End If
Return attris.ToArray()
End Function
Public Function GetValueSqls() As String()
Dim attris = From attri As KeyValuePair(Of PropertyInfo, SaFieldsAttribute) In _fieldAttributes
Where attri.Value.AutoDateTime OrElse attri.Key.GetValue(Me, Nothing) IsNot Nothing
Select CType(IIf(attri.Value.AutoDateTime, String.Format("{0} = {1}", attri.Key.Name, Now.ToString("yyyy-MM-dd HH:mm:ss").QuotedStr()), String.Format("{0} = {1}", attri.Key.Name, attri.Key.GetValue(Me, Nothing).ToString().QuotedStr())), String)
Return attris.ToArray()
End Function
Public Sub ClearFieldAttribute()
_fieldAttributes.Clear()
_fieldUIAttributes.Clear()
End Sub
Public Sub AddSaFieldAttribute(pro As PropertyInfo, attri As SaFieldsAttribute)
_fieldAttributes.Add(New KeyValuePair(Of PropertyInfo, SaFieldsAttribute)(pro, attri))
End Sub
Public Sub AddSaUIFieldAttribute(pro As PropertyInfo, attri As SaUIFieldsAttribute)
_fieldUIAttributes.Add(New KeyValuePair(Of PropertyInfo, SaUIFieldsAttribute)(pro, attri))
End Sub
End Class
End Namespace |
Imports System
Imports System.Collections.Generic
Imports System.Drawing
Imports System.Globalization
Imports DevExpress.Spreadsheet
Imports DevExpress.Spreadsheet.Functions
Imports DevExpress.XtraSpreadsheet
Namespace SpreadsheetDemo
Partial Public Class DocumentProperties
Inherits SpreadsheetDemoModule
Public Sub New()
InitializeComponent()
RegisterCustomFunctions()
InitializeWorkbook()
GenerateCustomPropertiesWorksheet()
AddHandler spreadsheetControl1.DocumentPropertiesChanged, AddressOf spreadsheetControl1_DocumentPropertiesChanged
End Sub
Private Sub spreadsheetControl1_DocumentPropertiesChanged(ByVal sender As Object, ByVal e As DocumentPropertiesChangedEventArgs)
If e.BuiltInPropertiesChanged Then
spreadsheetControl1.Document.CalculateFull()
End If
If e.CustomPropertiesChanged Then
GenerateCustomPropertiesWorksheet()
End If
End Sub
Private Sub InitializeWorkbook()
spreadsheetControl1.LoadDocument(DemoUtils.GetRelativePath("DocumentProperties_template.xlsx"))
spreadsheetControl1.Document.Unit = DevExpress.Office.DocumentUnit.Point
End Sub
Private Sub RegisterCustomFunctions()
Dim workbook As IWorkbook = spreadsheetControl1.Document
Dim customFunction As New DocumentPropertyFunction()
If Not workbook.GlobalCustomFunctions.Contains(DirectCast(customFunction, ICustomFunction).Name) Then
workbook.GlobalCustomFunctions.Add(customFunction)
End If
End Sub
Private Sub GenerateCustomPropertiesWorksheet()
If Not ShouldGenerateCustomPropertiesWorksheet() Then
Return
End If
Dim workbook As IWorkbook = spreadsheetControl1.Document
Dim worksheet As Worksheet = workbook.Worksheets(1)
Dim properties As DevExpress.Spreadsheet.DocumentProperties = workbook.DocumentProperties
workbook.BeginUpdate()
Try
Dim rowIndex As Integer = 3
Cleanup(worksheet, rowIndex)
For Each propertyName As String In properties.Custom.Names
Dim propertyValue As CellValue = properties.Custom(propertyName)
worksheet(rowIndex, 1).Value = propertyName
worksheet(rowIndex, 2).Formula = String.Format("=DOCPROP(""{0}"")", propertyName)
If rowIndex Mod 2 <> 0 Then
worksheet(rowIndex, 1).Style = workbook.Styles("PropName1")
worksheet(rowIndex, 2).Style = workbook.Styles("PropValue1")
Else
worksheet(rowIndex, 1).Style = workbook.Styles("PropName2")
worksheet(rowIndex, 2).Style = workbook.Styles("PropValue2")
End If
worksheet(rowIndex, 2).NumberFormat = If(propertyValue.IsDateTime, "m/d/yyyy", String.Empty)
worksheet.Rows(rowIndex).Height = 21
rowIndex += 1
Next propertyName
SetLastRowBorder(worksheet, rowIndex)
Finally
workbook.EndUpdate()
End Try
End Sub
Private Function ShouldGenerateCustomPropertiesWorksheet() As Boolean
Return spreadsheetControl1.Document.Worksheets.Contains("Custom")
End Function
Private Sub Cleanup(ByVal worksheet As Worksheet, ByVal rowIndex As Integer)
Dim usedRange As Range = worksheet.GetUsedRange()
If usedRange.BottomRowIndex >= rowIndex Then
Dim range As Range = worksheet.Range.FromLTRB(1, rowIndex, 2, usedRange.BottomRowIndex)
range.ClearContents()
range.ClearFormats()
range.Fill.BackgroundColor = Color.White
End If
End Sub
Private Sub SetLastRowBorder(ByVal worksheet As Worksheet, ByVal rowIndex As Integer)
Dim range As Range = worksheet.Range.FromLTRB(1, rowIndex - 1, 2, rowIndex - 1)
range.Borders.BottomBorder.LineStyle = BorderLineStyle.Medium
range.Borders.BottomBorder.Color = Color.Gray
End Sub
End Class
#Region "DocumentPropertyFunction"
Public Class DocumentPropertyFunction
Inherits Object
Implements ICustomFunction
Private Const functionName As String = "DOCPROP"
Private ReadOnly functionParameters() As ParameterInfo
Public Sub New()
Me.functionParameters = New ParameterInfo() { New ParameterInfo(ParameterType.Value) }
End Sub
Private ReadOnly Property IFunction_Name() As String Implements IFunction.Name
Get
Return functionName
End Get
End Property
Private ReadOnly Property IFunction_Parameters() As ParameterInfo() Implements IFunction.Parameters
Get
Return functionParameters
End Get
End Property
Private ReadOnly Property IFunction_ReturnType() As ParameterType Implements IFunction.ReturnType
Get
Return ParameterType.Value
End Get
End Property
Private ReadOnly Property IFunction_Volatile() As Boolean Implements IFunction.Volatile
Get
Return True
End Get
End Property
Private Function IFunction_Evaluate(ByVal parameters As IList(Of ParameterValue), ByVal context As EvaluationContext) As ParameterValue Implements IFunction.Evaluate
Dim propertyNameParam As ParameterValue = parameters(0)
If propertyNameParam.IsError Then
Return propertyNameParam
End If
If propertyNameParam.IsText Then
Dim propertyName As String = propertyNameParam.TextValue
Dim properties As DevExpress.Spreadsheet.DocumentProperties = context.Sheet.Workbook.DocumentProperties
If propertyName.Equals("Application", StringComparison.InvariantCultureIgnoreCase) Then
Return properties.Application
End If
If propertyName.Equals("Manager", StringComparison.InvariantCultureIgnoreCase) Then
Return properties.Manager
End If
If propertyName.Equals("Company", StringComparison.InvariantCultureIgnoreCase) Then
Return properties.Company
End If
If propertyName.Equals("Version", StringComparison.InvariantCultureIgnoreCase) Then
Return properties.Version
End If
If propertyName.Equals("Security", StringComparison.InvariantCultureIgnoreCase) Then
Return properties.Security.ToString()
End If
If propertyName.Equals("Title", StringComparison.InvariantCultureIgnoreCase) Then
Return properties.Title
End If
If propertyName.Equals("Subject", StringComparison.InvariantCultureIgnoreCase) Then
Return properties.Subject
End If
If propertyName.Equals("Author", StringComparison.InvariantCultureIgnoreCase) Then
Return properties.Author
End If
If propertyName.Equals("Keywords", StringComparison.InvariantCultureIgnoreCase) Then
Return properties.Keywords
End If
If propertyName.Equals("Description", StringComparison.InvariantCultureIgnoreCase) Then
Return properties.Description
End If
If propertyName.Equals("LastModifiedBy", StringComparison.InvariantCultureIgnoreCase) Then
Return properties.LastModifiedBy
End If
If propertyName.Equals("Category", StringComparison.InvariantCultureIgnoreCase) Then
Return properties.Category
End If
If propertyName.Equals("Created", StringComparison.InvariantCultureIgnoreCase) Then
If properties.Created <> Date.MinValue Then
Return properties.Created
End If
Return String.Empty
End If
If propertyName.Equals("Modified", StringComparison.InvariantCultureIgnoreCase) Then
If properties.Modified <> Date.MinValue Then
Return properties.Modified
End If
Return String.Empty
End If
If propertyName.Equals("Printed", StringComparison.InvariantCultureIgnoreCase) Then
If properties.Printed <> Date.MinValue Then
Return properties.Printed
End If
Return String.Empty
End If
Return properties.Custom(propertyName)
End If
Return ParameterValue.ErrorInvalidValueInFunction
End Function
Private Function IFunction_GetName(ByVal culture As CultureInfo) As String Implements IFunction.GetName
Return functionName
End Function
End Class
#End Region
End Namespace
|
Imports DCS.ProjectBase.Core
Imports DCS.mPosEngine.Core.Domain.Shared
Namespace Domain.Sales
Public Class OperationTaxInfoItem
Inherits DomainObject(Of Long)
Private _taxName As String
Private _taxAmount As Decimal
Private _taxTypeId As Integer
Private _parentOperation As MPosOperation
Public Enum TaxInfoSubtypeEnum
SalesTaxSubtype = 1
VatSubtype = 2
End Enum
Private _taxSubtype As TaxInfoSubtypeEnum
Public ReadOnly Property TaxSubtype() As TaxInfoSubtypeEnum
Get
Return _taxSubtype
End Get
End Property
Public Property TaxTypeId() As Integer
Get
Return _taxTypeId
End Get
Set(ByVal value As Integer)
_taxTypeId = value
End Set
End Property
Private Property ParentOperation As MPosOperation
Get
Return _parentOperation
End Get
Set(value As MPosOperation)
_parentOperation = value
End Set
End Property
Public Sub New(ByVal parentOperation As MPosOperation, ByVal subtype As TaxInfoSubtypeEnum, taxTypeId As Integer, ByVal taxName As String, ByVal taxAmount As Decimal)
_taxTypeId = taxTypeId
_taxName = taxName
_taxAmount = taxAmount
_taxSubtype = subtype
_parentOperation = parentOperation
End Sub
'For ORM
Private Sub New()
End Sub
Public Property TaxAmount() As Decimal
Get
Return _taxAmount
End Get
Set(ByVal value As Decimal)
_taxAmount = value
End Set
End Property
Public Property TaxName() As String
Get
Return _taxName
End Get
Set(ByVal value As String)
_taxName = value
End Set
End Property
Public Overrides Function GetHashCode() As Integer
Return (GetType(OperationTaxInfoItem).FullName & TaxTypeId.GetHashCode).GetHashCode
End Function
End Class
End Namespace
|
Imports System.ComponentModel
Public Class MitumoriNoTextBoxEx
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
MyBase.OnPaint(e)
'カスタム描画コードをここに追加します。
End Sub
Private LinkedComboBoxValue As MitumoriNoComboBox
<Description("リンクするコンボボックスを指定します。")>
Public Property LinkedComboBox() As MitumoriNoComboBox
Get
Return LinkedComboBoxValue
End Get
Set(ByVal value As MitumoriNoComboBox)
LinkedComboBoxValue = value
End Set
End Property
Public Sub New()
MyBase.New
LinkedComboBoxValue = Nothing
' この呼び出しは、Windows フォーム デザイナで必要です。
InitializeComponent()
' InitializeComponent() 呼び出しの後で初期化を追加します。
End Sub
Private Sub TextBoxControl_PreviewKeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles Me.PreviewKeyDown
'下キーでコンボボックスを開く
If e.KeyCode = Keys.Down Then
If LinkedComboBoxValue Is Nothing Then Return
'リンクするコンボボックスを選択
LinkedComboBoxValue.Focus()
'TypComboBoxのコンボボックスをフォーカスする為に下キーを発生させる
SendKeys.Send("{DOWN}")
'Alt+下キーでコンボボックスを開く
SendKeys.Send("%{DOWN}")
End If
End Sub
End Class
|
Imports System.Runtime.InteropServices
Imports System.Text
Public Class Form1
<DllImport("kernel32", SetLastError:=True)>
Private Shared Function WritePrivateProfileString(
ByVal lpAppName As String,
ByVal lpKeyName As String,
ByVal lpString As String,
ByVal lpFileName As String) As Boolean
End Function
<DllImport("kernel32", SetLastError:=True, EntryPoint:="GetPrivateProfileIntA")>
Public Shared Function GetPrivateProfileInt(
ByVal lpApplicationName As String,
ByVal lpKeyName As String,
ByVal nDefault As Integer,
ByVal lpFileName As String) As Integer
End Function
<DllImport("kernel32.dll", SetLastError:=True)>
Private Shared Function GetPrivateProfileString(ByVal lpAppName As String,
ByVal lpKeyName As String,
ByVal lpDefault As String,
ByVal lpReturnedString As StringBuilder,
ByVal nSize As Integer,
ByVal lpFileName As String) As Integer
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim bres As Boolean
bres = WritePrivateProfileString("test1", "value1", CStr(TextBox1.Text), Application.StartupPath & "\config.ini")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox2.Text = GetPrivateProfileInt("test1", "value1", 0, Application.StartupPath & "\config.ini")
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim res As Integer
Dim sb As StringBuilder = New StringBuilder(500)
res = GetPrivateProfileString("test1", "value1", "", sb, sb.Capacity, Application.StartupPath & "\config.ini")
TextBox3.Text = sb.ToString()
End Sub
End Class
|
Imports System.Data
Imports System.Text
Imports System.IO
Partial Class m_check_method
Inherits System.Web.UI.Page
Public BC AS NEW MCheckMethodBC
''' <summary>
''' PAGE LOAD
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.lblMsg.Text = ""
If Not IsPostBack Then
'固定項目設定
KoteiInit()
'明細項目設定
MsInit()
End If
End Sub
''' <summary>
''' 固定項目設定
''' </summary>
public Sub KoteiInit()
'EMAB ERR
Me.tbxChkId.Attributes.Item("itType") = "varchar"
Me.tbxChkId.Attributes.Item("itLength") = "10"
Me.tbxChkId.Attributes.Item("itName") = "检查方法ID"
Me.tbxChkName.Attributes.Item("itType") = "nvarchar"
Me.tbxChkName.Attributes.Item("itLength") = "20"
Me.tbxChkName.Attributes.Item("itName") = "检查方法名"
Me.tbxChkMethod.Attributes.Item("itType") = "nvarchar"
Me.tbxChkMethod.Attributes.Item("itLength") = "1"
Me.tbxChkMethod.Attributes.Item("itName") = "检查方法"
Me.tbxChkFormula.Attributes.Item("itType") = "nvarchar"
Me.tbxChkFormula.Attributes.Item("itLength") = "80"
Me.tbxChkFormula.Attributes.Item("itName") = "检查方公式"
Me.tbxVerifyMethodExplain.Attributes.Item("itType") = "nvarchar"
Me.tbxVerifyMethodExplain.Attributes.Item("itLength") = "200"
Me.tbxVerifyMethodExplain.Attributes.Item("itName") = "核对方法说明"
End Sub
''' <summary>
''' 明細項目設定
''' </summary>
public Sub MsInit()
'EMAB ERR
'明細設定
Dim dt As DataTable = GetMsData()
Me.gvMs.DataSource = dt
Me.gvMs.DataBind()
End Sub
''' <summary>
''' 検索
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub btnSelect_Click(sender As Object, e As System.EventArgs) Handles btnSelect.Click
MsInit()
End Sub
''' <summary>
''' 明細データ取得
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Private Function GetMsData() As Data.DataTable
'EMAB ERR
Return BC.SelMCheckMethod(tbxChkId_key.Text, tbxChkName_key.Text)
End Function
''' <summary>
''' データ存在チェック
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Private Function IsHaveData() As Boolean
'EMAB ERR
Return BC.SelMCheckMethod(tbxChkId.Text, tbxChkName.Text).Rows.Count > 0
End Function
''' <summary>
''' 更新
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub btnUpdate_Click(sender As Object, e As System.EventArgs) Handles btnUpdate.Click
Try
BC.UpdMCheckMethod(hidchkId.Text, hidchkName.Text,tbxchkId.Text, tbxchkName.Text, tbxchkMethod.Text, tbxchkFormula.Text, tbxverifyMethodExplain.Text)
MsInit()
Catch ex As Exception
Common.ShowMsg(Me.Page, ex.Message)
Exit Sub
End Try
Me.hidOldRowIdx.Text = ""
End Sub
''' <summary>
''' 登録
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub btnInsert_Click(sender As Object, e As System.EventArgs) Handles btnInsert.Click
'データ存在チェック
If IsHaveData() Then
Common.ShowMsg(Me.Page, "数据已经存在")
Exit Sub
End If
Try
BC.InsMCheckMethod(tbxchkId.Text, tbxchkName.Text, tbxchkMethod.Text, tbxchkFormula.Text, tbxverifyMethodExplain.Text)
MsInit()
Catch ex As Exception
Common.ShowMsg(Me.Page, ex.Message)
Exit Sub
End Try
Me.hidOldRowIdx.Text = ""
End Sub
''' <summary>
''' 削除
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub btnDelete_Click(sender As Object, e As System.EventArgs) Handles btnDelete.Click
Try
BC.DelMCheckMethod(hidchkId.Text, hidchkName.Text)
MsInit()
Catch ex As Exception
Common.ShowMsg(Me.Page, ex.Message)
Exit Sub
End Try
Me.hidOldRowIdx.Text = ""
End Sub
End Class
|
Imports System.Net.Mail
Imports DCS.KioskV15.ClubSpeedInterface.Models
Imports DCS.KioskV15.ClubSpeedInterface.Services
Public Class UserSignupPresenter
Private _webSvc As IClubSpeedService
Private WithEvents _view As IUserSignupView
Public Sub New(ByVal webSvc As IClubSpeedService,
ByVal view As IUserSignupView
)
_view = view
_webSvc = webSvc
End Sub
Public Function Signup() As Customer
If (_view.SignupUser = IUserSignupView.SignupResultEnum.Finished) Then
Dim customer = New Customer() With {
.FirstName = _view.FirstName,
.LastName = _view.LastName,
.RacerName = _view.RacerName,
.BirthDate = Date.Parse(_view.BirthDate),
.MobilePhone = _view.PhoneNumberFormatted,
.EMail = _view.Email,
.PhotoBase64String = _view.PhotoBase64
}
Try
_webSvc.AddCustomer(customer)
Catch ex As Exception
'_view.ErrorAddingCustomer
End Try
Return (customer)
Else
Return (Nothing)
End If
End Function
Private Sub _view_ValidateData(ByVal dataItemType As IUserSignupView.DataItemsEnum,
ByVal textToValidate As String
) Handles _view.ValidateData
Dim retVal As Boolean
If (dataItemType = IUserSignupView.DataItemsEnum.BirthDate) Then
retVal = Date.TryParse(textToValidate, New Date())
ElseIf (dataItemType = IUserSignupView.DataItemsEnum.PhoneNumber) Then
retVal = IsValidUSAPhoneNumber(textToValidate)
ElseIf (dataItemType = IUserSignupView.DataItemsEnum.Email) Then
Try
Dim email As New MailAddress(textToValidate)
retVal = True
Catch e As Exception
retVal = False
End Try
ElseIf (dataItemType = IUserSignupView.DataItemsEnum.Photo) Then
retVal = (textToValidate.Trim <> String.Empty)
Else
'This validates free text fields.
retVal = (textToValidate.Trim <> String.Empty)
End If
If (retVal) Then
_view.DataValidationSuccess(textToValidate)
Else
_view.DataValidationFailed()
End If
End Sub
Private Function IsValidUSAPhoneNumber(ByVal phoneToValidate As String) As Boolean
Dim retVal As Boolean = False,
phoneNumberChecker As New Text.RegularExpressions.Regex("^\([1-9]\d{2}\)[1-9]\d{2}-\d{4}$")
If (Not (String.IsNullOrEmpty(phoneToValidate))) Then
retVal = phoneNumberChecker.IsMatch(phoneToValidate)
End If
Return retVal
End Function
End Class
|
Namespace Base
''' <summary>
''' 创建时间:2019.8.23
''' 作者:kevin zhu
''' 说明:错误信息处理的类
''' </summary>
''' <remarks></remarks>
Public Class ErrorInfo
''' <summary>
''' 说明:根据错误代码,返回错误信息
''' </summary>
''' <param name="vIndex">错误代码</param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function ErrorMessage(ByVal vIndex As String) As String
Dim strError As String
strError = ""
Select Case vIndex
Case Is = 1 '//未授权
strError = "Error-1<未被授权无法调用>"
Case Is = 2 '//窗体加载失败
strError = " Error -2<窗体加载失败>"
End Select
Return strError
End Function
End Class
End NameSpace |
Imports ESRI.ArcGIS.Carto
Imports ESRI.ArcGIS.Geometry
Imports System.Text.RegularExpressions
Imports ESRI.ArcGIS.Geodatabase
Imports ESRI.ArcGIS.esriSystem
'**
'Nom de la composante : clsDecoupageElement.vb
'
'''<summary>
''' Classe qui permet de sélectionner les éléments du FeatureLayer dont l’attribut et la géométrie de découpage respecte ou non
''' l'élément de la classe de découpage spécifiée.
'''
''' La classe permet de traiter un seul attribut qui contient la valeur de l'identifiant de découpage à valider.
'''
''' Note : L'attribut spécifié correspond au nom de l'attribut présent dans la classe de découpage et qui contient la géométrie
''' et l'identifiant de découpage à traiter.
'''
'''</summary>
'''
'''<remarks>
''' Auteur : Michel Pothier
''' Date : 2 juin 2015
'''</remarks>
'''
Public Class clsDecoupageElement
Inherits clsValeurAttribut
'''<summary>Contient la position de l'attribut de découpage dans la classe de découpage.</summary>
Protected giPosAttributDecoupage As Integer = -1
'''<summary>Contient l'identifiant de l'élément de découpage.</summary>
Protected gsIdentifiantDecoupage As String = ""
#Region "Constructeur"
'''<summary>
''' Routine qui permet d'instancier la classe en objet avec les valeurs par défaut.
'''
'''</summary>
'''
Public Sub New()
Try
'Définir les valeurs par défaut
NomAttribut = "DATASET_NAME"
Expression = "DATASET_NAME"
Catch ex As Exception
'Retourner l'erreur
Throw ex
End Try
End Sub
'''<summary>
''' Routine qui permet d'instancier la classe en objet.
'''
'''<param name="pMap"> Interface ESRI contenant tous les FeatureLayers.</param>
'''<param name="pFeatureLayerSelection"> Interface contenant le FeatureLayer de sélection à traiter.</param>
'''<param name="sNomAttribut"> Nom de l'attribut à traiter.</param>
'''<param name="sExpression"> Expression régulière à traiter.</param>
'''
'''</summary>
'''
Public Sub New(ByRef pMap As IMap, ByRef pFeatureLayerSelection As IFeatureLayer,
ByVal sNomAttribut As String, ByVal sExpression As String,
Optional ByVal bLimite As Boolean = False, Optional ByVal bUnique As Boolean = False)
Try
'Définir les valeurs par défaut
Map = pMap
FeatureLayerSelection = pFeatureLayerSelection
NomAttribut = sNomAttribut
Expression = sExpression
Catch ex As Exception
'Retourner l'erreur
Throw ex
End Try
End Sub
'''<summary>
''' Routine qui permet d'instancier la classe en objet.
'''
'''<param name="pFeatureLayerSelection"> Interface contenant le FeatureLayer de sélection à traiter.</param>
'''<param name="sParametres"> Paramètres contenant le nom de l'attribut (0) et l'expression régulière (1) à traiter.</param>
'''
'''</summary>
'''
Public Sub New(ByRef pFeatureLayerSelection As IFeatureLayer, ByVal sParametres As String)
Try
'Définir les valeurs par défaut
FeatureLayerSelection = pFeatureLayerSelection
Parametres = sParametres
Catch ex As Exception
'Retourner l'erreur
Throw ex
End Try
End Sub
'''<summary>
''' Routine qui permet d'instancier la classe en objet.
'''
'''<param name="pMap"> Interface ESRI contenant tous les FeatureLayers.</param>
'''<param name="pFeatureLayerSelection"> Interface contenant le FeatureLayer de sélection à traiter.</param>
'''<param name="sParametres"> Paramètres contenant le nom de l'attribut (0) et l'expression régulière (1) à traiter.</param>
'''
'''</summary>
'''
Public Sub New(ByRef pMap As IMap, ByRef pFeatureLayerSelection As IFeatureLayer, ByVal sParametres As String)
Try
'Définir les valeurs par défaut
Map = pMap
FeatureLayerSelection = pFeatureLayerSelection
Parametres = sParametres
Catch ex As Exception
'Retourner l'erreur
Throw ex
End Try
End Sub
Protected Overrides Sub Finalize()
'Vider la mémoire
giPosAttributDecoupage = Nothing
gsIdentifiantDecoupage = Nothing
'Récupération de la mémoire disponible
GC.Collect()
'Finaliser
MyBase.finalize()
End Sub
#End Region
#Region "Propriétés"
'''<summary>
''' Propriété qui permet de retourner le nom de la contrainte d'intégrité à traiter.
'''</summary>
'''
Public Overloads Overrides ReadOnly Property Nom() As String
Get
Nom = "DecoupageElement"
End Get
End Property
'''<summary>
''' Propriété qui permet de définir et retourner la ligne de paramètre à traiter.
'''</summary>
'''
Public Overloads Overrides Property Parametres() As String
Get
'Retourner la valeur des paramètres
Parametres = gsNomAttribut & " " & gsExpression
End Get
Set(ByVal value As String)
'Déclarer les variables de travail
Dim params() As String 'Liste des paramètres 0:NomAttribut, 1:Expression régulière
Try
'Extraire les paramètres
params = value.Split(CChar(" "))
'Vérifier si les deux paramètres sont présents
If params.Length < 2 Then Err.Raise(1, , "Deux paramètres sont obligatoires: ATTRIBUT EXPRESSION")
'Définir les valeurs par défaut
gsNomAttribut = params(0)
gsExpression = params(1)
Catch ex As Exception
'Retourner l'erreur
Throw ex
Finally
'Vider la mémoire
params = Nothing
End Try
End Set
End Property
#End Region
#Region "Routine et fonction publiques"
'''<summary>
''' Fonction qui permet de retourner la liste des paramètres possibles.
'''</summary>
'''
Public Overloads Overrides Function ListeParametres() As Collection
'Déclarer les variables de travail
Dim pCursor As ICursor = Nothing 'Interface utilisé pour extraire les donnéées à traiter.
Dim pFeatureCursor As IFeatureCursor = Nothing 'Interface contenant le résultat de la recherche.
Dim pFeatureSel As IFeatureSelection = Nothing 'Interface utilisé pour extraire et sélectionner les éléments du FeatureLayer.
Dim pFeature As IFeature = Nothing 'Interface contenant le premier élément de la classeà traiter.
'Définir la liste des paramètres par défaut
ListeParametres = New Collection
'Définir le premier paramètre
ListeParametres.Add(gsNomAttribut + " " + gsNomAttribut)
Try
'Vérifier si FeatureLayer est valide
If gpFeatureLayerSelection IsNot Nothing Then
'Vérifier si FeatureLayer est valide
If gpFeatureLayerSelection.FeatureClass IsNot Nothing Then
'Interface pour extraire et sélectionner les éléments
pFeatureSel = CType(gpFeatureLayerSelection, IFeatureSelection)
'Vérifier si au moins un élément est sélectionné
If pFeatureSel.SelectionSet.Count = 0 Then
'Interface pour extraire le premier élément
pFeatureCursor = gpFeatureLayerSelection.Search(Nothing, False)
Else
'Interfaces pour extraire le premier élément sélectionné
pFeatureSel.SelectionSet.Search(Nothing, False, pCursor)
pFeatureCursor = CType(pCursor, IFeatureCursor)
End If
'Extraire l'élément de découpage
pFeature = pFeatureCursor.NextFeature
'Vérifier si un élémet est trouvé
If pFeature IsNot Nothing Then
'Extriare la position de l'attribut par défaut
giAttribut = gpFeatureLayerSelection.FeatureClass.Fields.FindField(gsNomAttribut)
'Vérifier si l'attribut par défaut est présent
If giAttribut > -1 Then
'Définir l'expression par défaut
gsExpression = gsNomAttribut & "='" & pFeature.Value(giAttribut).ToString & "'"
'Définir le paramètre avec identifiant
ListeParametres.Add(gsNomAttribut + " " + gsExpression)
End If
End If
End If
End If
Catch ex As Exception
'Retourner l'erreur
Throw ex
Finally
'Vider la mémoire
pCursor = Nothing
pFeatureCursor = Nothing
pFeatureSel = Nothing
pFeature = Nothing
End Try
End Function
'''<summary>
''' Routine qui permet d'indiquer si la FeatureClass est valide.
'''
'''<return>Boolean qui indique si la FeatureClass est valide.</return>
'''
'''</summary>
'''
Public Overloads Overrides Function FeatureClassValide() As Boolean
Try
'Définir la valeur par défaut, la contrainte est invalide.
FeatureClassValide = False
gsMessage = "ERREUR : La FeatureClass est invalide."
'Vérifier si la FeatureClass est valide
If gpFeatureLayerSelection.FeatureClass IsNot Nothing Then
'Vérifier si la FeatureClass est de type Polyline et Polygon
If gpFeatureLayerSelection.FeatureClass.ShapeType = esriGeometryType.esriGeometryPoint _
Or gpFeatureLayerSelection.FeatureClass.ShapeType = esriGeometryType.esriGeometryMultipoint _
Or gpFeatureLayerSelection.FeatureClass.ShapeType = esriGeometryType.esriGeometryPolyline _
Or gpFeatureLayerSelection.FeatureClass.ShapeType = esriGeometryType.esriGeometryPolygon Then
'La contrainte est valide
FeatureClassValide = True
gsMessage = "La contrainte est valide"
Else
'Définir le message d'erreur
gsMessage = "ERREUR : Le type de la FeatureClass n'est pas de type Point, MultiPoint, Polyline ou Polygon."
End If
End If
Catch ex As Exception
'Retourner l'erreur
Throw ex
End Try
End Function
'''<summary>
''' Routine qui permet d'indiquer si l'expression utilisée pour extraire l'élément de découpage est valide.
'''
'''<return>Boolean qui indique si l'expression est valide.</return>
'''
'''</summary>
'''
Public Overloads Overrides Function ExpressionValide() As Boolean
'Déclarer les variables de travail
Dim pQueryFilter As IQueryFilter = Nothing 'Interface contenant la requête attributive.
Dim pFeatureCursor As IFeatureCursor = Nothing 'Interface contenant le résultat de la recherche.
'Définir la valeur par défaut
ExpressionValide = False
gsMessage = "ERREUR : L'expression est invalide"
Try
'Vérifier si l'identifiant de découpage est présent
If Len(gsExpression) > 0 Then
'Vérifier la présence de la classe de découpage
If gpFeatureLayerDecoupage IsNot Nothing Then
'Vérifier si la FeatureClass est valide
If gpFeatureLayerDecoupage.FeatureClass IsNot Nothing Then
'vérifier si la FeatureClass de découpage est de type Polygon
If gpFeatureLayerDecoupage.FeatureClass.ShapeType = esriGeometryType.esriGeometryPolygon Then
'Vérifier si l'identifiant de découpage est spécifié
If gsExpression.Contains("=") Then
'Extraire la position de l'attribut de découpage
giPosAttributDecoupage = gpFeatureLayerDecoupage.FeatureClass.Fields.FindField(gsExpression.Split(CChar("="))(0))
'Vérifier si l'attribut est absent dans la classe de découpage
If giPosAttributDecoupage = -1 Then
gsMessage = "ERREUR : L'attribut de découpage est absent dans la classe de découpage."
'Si l'attribut est présent dans la classe de découpage
Else
'Définir l'identifiant de découpage
gsIdentifiantDecoupage = gsExpression.Split(CChar("="))(1)
gsIdentifiantDecoupage = gsIdentifiantDecoupage.Replace("'", "")
'Définir la requête attributive pour extraire l'élément de découpage
pQueryFilter = New QueryFilter
pQueryFilter.WhereClause = gsExpression
'Exécuter la recherche de la requête attributive
pFeatureCursor = gpFeatureLayerDecoupage.Search(pQueryFilter, False)
'Extraire l'élément de découpage
FeatureDecoupage = pFeatureCursor.NextFeature
'Vérifier si l'élément de découpage est présent
If gpFeatureDecoupage IsNot Nothing Then
'La contrainte est valide
ExpressionValide = True
gsMessage = "La contrainte est valide"
Else
gsMessage = "ERREUR : L'identifiant de découpage est absent de la classe de découpage."
End If
End If
'Si l'identifiant de découpage n'est pas spécifié
Else
'Extraire la position de l'attribut de découpage
giPosAttributDecoupage = gpFeatureLayerDecoupage.FeatureClass.Fields.FindField(gsExpression)
'Vérifier si l'attribut est absent dans la classe de découpage
If giPosAttributDecoupage = -1 Then
gsMessage = "ERREUR : L'attribut de découpage est absent dans la classe de découpage."
'Si l'attribut est présent dans la classe de découpage
Else
'Vérifier si l'élément de découpage est spécifié
If gpFeatureDecoupage IsNot Nothing Then
'Définir l'identifiant de découpage
gsIdentifiantDecoupage = gpFeatureDecoupage.Value(giPosAttributDecoupage).ToString
'Vérifier si l'identifiant n'est pas vide
If gsIdentifiantDecoupage.Length > 0 Then
'La contrainte est valide
ExpressionValide = True
gsMessage = "La contrainte est valide"
'Si l'identifiant est vide
Else
gsMessage = "ERREUR : L'identifiant de la classe de découpage est vide."
End If
'si l'élément de découpage est spécifié
Else
'La contrainte est valide
ExpressionValide = True
gsMessage = "La contrainte est valide"
End If
End If
End If
Else
gsMessage = "ERREUR : Le FeatureClass de découpage n'est pas de type Polygon."
End If
Else
gsMessage = "ERREUR : Le FeatureClass de découpage est invalide."
End If
Else
gsMessage = "ERREUR : Le FeatureLayer de découpage n'est pas spécifié correctement."
End If
Else
gsMessage = "ERREUR : L'attribut et l'identifiant de la classe de découpage sont absents."
End If
Catch ex As Exception
'Retourner l'erreur
Throw ex
Finally
'Vider la mémoire
pQueryFilter = Nothing
pFeatureCursor = Nothing
End Try
End Function
'''<summary>
''' Routine qui permet de sélectionner les éléments du FeatureLayer dont l'identifiant ou la géométrie de découpage sont invalides.
'''
''' Seuls les éléments sélectionnés sont traités.
''' Si aucun élément n'est sélectionné, tous les éléments sont considérés sélectionnés.
'''
''' bEnleverSelection=True : Les éléments qui respectent la contrainte sont enlevés dans la sélection.
''' bEnleverSelection=False : Les éléments qui respectent la contrainte sont conservés dans la sélection.
'''
'''<param name="pTrackCancel"> Permet d'annuler la sélection avec la touche ESC du clavier.</param>
'''<param name="bEnleverSelection"> Indique si on doit enlever les éléments de la sélection, sinon ils sont conservés. Défaut=True.</param>
'''
'''<return>Les géométries des éléments sélectionnés.</return>
'''
'''</summary>
'''
Public Overloads Overrides Function Selectionner(ByRef pTrackCancel As ITrackCancel, Optional ByVal bEnleverSelection As Boolean = True) As IGeometry
'Déclarer les variables de travail
Dim pFeatureSel As IFeatureSelection = Nothing 'Interface utilisé pour extraire et sélectionner les éléments du FeatureLayer.
Dim pSelectionSet As ISelectionSet = Nothing 'Interface utilisé pour extraire les éléments sélectionnés du FeatureLayer.
Dim pCursor As ICursor = Nothing 'Interface utilisé pour extraire les donnéées à traiter.
Dim pFeatureCursor As IFeatureCursor = Nothing 'Interface utilisé pour extraire les éléments à traiter.
Dim pQueryFilterDef As IQueryFilterDefinition = Nothing 'Interface utilisé pour indiquer que l'on veut trier.
Try
'Sortir si la contrainte est invalide
If Me.EstValide() = False Then Err.Raise(1, , Me.Message)
'Définir la géométrie par défaut
Selectionner = New GeometryBag
Selectionner.SpatialReference = gpFeatureLayerSelection.AreaOfInterest.SpatialReference
'Conserver le type de sélection à effectuer
gbEnleverSelection = bEnleverSelection
''Interface pour extraire et sélectionner les éléments
'pFeatureSel = CType(gpFeatureLayerSelection, IFeatureSelection)
''Interface utilisé pour extraire les éléments sélectionnés du FeatureLayer
'pSelectionSet = pFeatureSel.SelectionSet
''Vérifier si des éléments sont sélectionnés
'If pSelectionSet.Count = 0 Then
' 'Sélectionnées tous les éléments du FeatureLayer
' pFeatureSel.SelectFeatures(Nothing, esriSelectionResultEnum.esriSelectionResultNew, False)
' pSelectionSet = pFeatureSel.SelectionSet
'End If
''Enlever la sélection
'pFeatureSel.Clear()
''Créer une nouvelle requete vide
'pQueryFilterDef = New QueryFilter
''Indiquer la méthode pour trier
'pQueryFilterDef.PostfixClause = "ORDER BY " & gsNomAttribut
''Interfaces pour extraire les éléments sélectionnés
'pSelectionSet.Search(CType(pQueryFilterDef, IQueryFilter), False, pCursor)
'pFeatureCursor = CType(pCursor, IFeatureCursor)
'Créer la classe d'erreurs au besoin
CreerFeatureClassErreur(Me.Nom & "_" & gpFeatureLayerSelection.FeatureClass.AliasName, gpFeatureLayerSelection)
'Traiter le FeatureLayer selon un découpage spécifique
Selectionner = TraiterDecoupageEstInclus(pTrackCancel, bEnleverSelection)
''Vérifier si l'élément de découpage est spécifié
'If gpFeatureDecoupage IsNot Nothing Then
' 'Traiter le FeatureLayer selon un découpage spécifique
' Selectionner = TraiterDecoupageElementIdentifiant(pFeatureCursor, pTrackCancel, bEnleverSelection)
' 'Si l'élément de découpage n'est pas spécifié
'Else
' 'Traiter le FeatureLayer selon le découpage des élément traités
' Selectionner = TraiterDecoupageElement(pFeatureCursor, pTrackCancel, bEnleverSelection)
'End If
'Vérifier si la classe d'erreur est présente
If gpFeatureCursorErreur IsNot Nothing Then
'Conserver toutes les modifications
gpFeatureCursorErreur.Flush()
'Release the update cursor to remove the lock on the input data.
System.Runtime.InteropServices.Marshal.ReleaseComObject(gpFeatureCursorErreur)
End If
Catch ex As Exception
'Retourner l'erreur
Throw ex
Finally
'Vider la mémoire
pFeatureSel = Nothing
pSelectionSet = Nothing
pCursor = Nothing
pFeatureCursor = Nothing
pQueryFilterDef = Nothing
'Variables globales
gpFeatureCursorErreur = Nothing
End Try
End Function
#End Region
#Region "Routine et fonction privées"
'''<summary>
''' Routine qui permet de sélectionner les éléments du FeatureLayer dont la relation spatiale respecte ou non l'opérateur EST_INCLUS VRAI
''' avec ses éléments en relation.
'''
''' Seuls les éléments sélectionnés sont traités.
''' Si aucun élément n'est sélectionné, tous les éléments sont considérés sélectionnés.
'''
''' bEnleverSelection=True : Les éléments qui respectent la contrainte sont enlevés dans la sélection.
''' bEnleverSelection=False : Les éléments qui respectent la contrainte sont conservés dans la sélection.
'''
'''<param name="pTrackCancel"> Permet d'annuler la sélection avec la touche ESC du clavier.</param>
'''<param name="bEnleverSelection"> Indique si on doit enlever les éléments de la sélection, sinon ils sont conservés. Défaut=True.</param>
'''
'''<return>Les géométries des éléments qui respectent ou non les relations spatiales.</return>
'''
'''</summary>
'''
Private Function TraiterDecoupageEstInclus(ByRef pTrackCancel As ITrackCancel, Optional ByVal bEnleverSelection As Boolean = True) As IGeometryBag
'Déclarer les variables de travail
Dim pFeatureSel As IFeatureSelection = Nothing 'Interface utilisé pour extraire et sélectionner les éléments du FeatureLayer.
Dim pSelectionSet As ISelectionSet = Nothing 'Interface pour sélectionner les éléments.
Dim pGeomResColl As IGeometryCollection = Nothing 'Interface ESRI contenant les géométries résultantes trouvées.
Dim pGeomSelColl As IGeometryCollection = Nothing 'Interface contenant les géométries des l'élément à traiter.
Dim pGeomRelColl As IGeometryCollection = Nothing 'Interface contenant les géométries des éléments en relation.
Dim pFeatureLayerRel As IFeatureLayer = Nothing 'Interface contenant un FeatureLayer en relation.
Dim pRelOpNxM As IRelationalOperatorNxM = Nothing 'Interface utilisé pour traiter la relation spatiale.
Dim pRelResult As IRelationResult = Nothing 'Interface contenant le résultat du traitement de la relation spatiale.
Dim iOidSel(0) As Integer 'Vecteur des OIds des éléments à traiter.
Dim iOidRel(0) As Integer 'Vecteur des OIds des éléments en relation.
Dim iOidAdd(0) As Integer 'Vecteur du nombre de OIDs trouvés.
Dim sIdDecSel(0) As String 'Vecteur des positions d'identifiants de découapge pour la classe de sélection.
Dim sIdDecRel(0) As String 'Vecteur des positions d'identifiants de découapge pour la classe en relation.
Try
'Définir la géométrie par défaut
TraiterDecoupageEstInclus = New GeometryBag
TraiterDecoupageEstInclus.SpatialReference = gpFeatureLayerSelection.AreaOfInterest.SpatialReference
'Interface contenant les géométries des éléments sélectionnés
pGeomResColl = CType(TraiterDecoupageEstInclus, IGeometryCollection)
'Conserver la sélection de départ
pFeatureSel = CType(gpFeatureLayerSelection, IFeatureSelection)
'Afficher le message de lecture des éléments
If pTrackCancel.Progressor IsNot Nothing Then pTrackCancel.Progressor.Message = "Lecture des éléments (" & gpFeatureLayerSelection.Name & ") ..."
'Lire les éléments à traiter
LireGeometrieAttribut(gpFeatureLayerSelection, pTrackCancel, pGeomSelColl, iOidSel, sIdDecSel, giAttribut)
'Initialiser la liste des Oids trouvés
ReDim Preserve iOidAdd(pGeomSelColl.GeometryCount)
'Interface pour sélectionner les éléments
pSelectionSet = pFeatureSel.SelectionSet
'Afficher le message de lecture des éléments
If pTrackCancel.Progressor IsNot Nothing Then pTrackCancel.Progressor.Message = "Lecture des éléments de découpage (" & gpFeatureLayerDecoupage.Name & ") ..."
'Lire les éléments en relation
LireGeometrieAttribut(gpFeatureLayerDecoupage, pTrackCancel, pGeomRelColl, iOidRel, sIdDecRel, giPosAttributDecoupage)
'Afficher le message de traitement de la relation spatiale
If pTrackCancel.Progressor IsNot Nothing Then pTrackCancel.Progressor.Message = "Traitement de la relation spatiale EST_INCLUS (" & gpFeatureLayerSelection.Name & "/" & gpFeatureLayerDecoupage.Name & ") ..."
'Interface pour traiter la relation spatiale
pRelOpNxM = CType(pGeomSelColl, IRelationalOperatorNxM)
'Exécuter la recherche et retourner le résultat de la relation spatiale
pRelResult = pRelOpNxM.Within(CType(pGeomRelColl, IGeometryBag))
'Récupération de la mémoire disponible
pRelOpNxM = Nothing
GC.Collect()
'Afficher le message de traitement d'extraction des OIDs trouvés
If pTrackCancel.Progressor IsNot Nothing Then pTrackCancel.Progressor.Message = "Extraction des Oids trouvés (" & gpFeatureLayerSelection.Name & "/" & gpFeatureLayerDecoupage.Name & ") ..."
'Extraire les Oids d'éléments trouvés
ExtraireListeOid(pRelResult, iOidSel, iOidRel, iOidAdd)
'Afficher le message de sélection des éléments trouvés
If pTrackCancel.Progressor IsNot Nothing Then pTrackCancel.Progressor.Message = "Sélection des éléments trouvés (" & gpFeatureLayerSelection.Name & ") ..."
'Sélectionner les éléments en erreur
SelectionnerElementErreur(pGeomSelColl, pGeomRelColl, iOidSel, iOidRel, iOidAdd, sIdDecSel, sIdDecRel, bEnleverSelection, pTrackCancel, pSelectionSet, pGeomResColl)
Catch ex As Exception
'Retourner l'erreur
Throw ex
Finally
'Vider la mémoire
pGeomResColl = Nothing
pGeomSelColl = Nothing
pGeomRelColl = Nothing
pFeatureSel = Nothing
pSelectionSet = Nothing
pFeatureLayerRel = Nothing
pRelOpNxM = Nothing
pRelResult = Nothing
iOidSel = Nothing
iOidRel = Nothing
iOidAdd = Nothing
sIdDecSel = Nothing
sIdDecRel = Nothing
'Récupération de la mémoire disponible
GC.Collect()
End Try
End Function
'''<summary>
''' Routine qui permet de lire les géométries et les OIDs des éléments d'un FeatureLayer.
'''
''' Seuls les éléments sélectionnés sont lus.
''' Si aucun élément n'est sélectionné, tous les éléments sont considérés sélectionnés.
'''
'''<param name="pFeatureLayer"> Interface contenant les éléments à lire.</param>
'''<param name="pTrackCancel"> Permet d'annuler la sélection avec la touche ESC du clavier.</param>
'''<param name="pGeomColl"> Interface contenant les géométries des éléments lus.</param>
'''<param name="iOid"> Vecteur des OIDs d'éléments lus.</param>
'''<param name="iIdDec"> Vecteur des positions d'identifiants de déciupage.</param>
'''<param name="iPosAttribut"> Position de l'attribut de découpage.</param>
'''
'''</summary>
'''
Private Sub LireGeometrieAttribut(ByRef pFeatureLayer As IFeatureLayer, ByRef pTrackCancel As ITrackCancel, ByRef pGeomColl As IGeometryCollection,
ByRef iOid() As Integer, ByRef sIdDec() As String, ByVal iPosAttribut As Integer)
'Déclarer les variables de travail
Dim pFeatureSel As IFeatureSelection = Nothing 'Interface utilisé pour extraire et sélectionner les éléments du FeatureLayer.
Dim pSelectionSet As ISelectionSet = Nothing 'Interface pour sélectionner les éléments.
Dim pCursor As ICursor = Nothing 'Interface utilisé pour lire les éléments.
Dim pFeatureCursor As IFeatureCursor = Nothing 'Interface utilisé pour lire les éléments.
Dim pFeature As IFeature = Nothing 'Interface contenant l'élément lu.
Dim pGeometry As IGeometry = Nothing 'Interface contenant la géométrie de l'élément lu.
Dim pTopoOp As ITopologicalOperator = Nothing 'Interface pour extraire la limite de la géométrie.
Dim pQueryFilterDef As IQueryFilterDefinition = Nothing 'Interface utilisé pour indiquer que l'on veut trier.
Try
'Créer un nouveau Bag vide
pGeometry = New GeometryBag
'Définir la référence spatiale
pGeometry.SpatialReference = pFeatureLayer.AreaOfInterest.SpatialReference
pGeometry.SnapToSpatialReference()
'Interface pour ajouter les géométries dans le Bag
pGeomColl = CType(pGeometry, IGeometryCollection)
'Interface pour sélectionner les éléments
pFeatureSel = CType(pFeatureLayer, IFeatureSelection)
'Vérifier si des éléments sont sélectionnés
If pFeatureSel.SelectionSet.Count = 0 Then
'Sélectionnées tous les éléments du FeatureLayer
pFeatureSel.SelectFeatures(Nothing, esriSelectionResultEnum.esriSelectionResultNew, False)
End If
'Interface pour extraire les éléments sélectionnés
pSelectionSet = pFeatureSel.SelectionSet
'Afficher la barre de progression
InitBarreProgression(0, pSelectionSet.Count, pTrackCancel)
'Augmenter le vecteur des Oid selon le nombre d'éléments
ReDim Preserve iOid(pSelectionSet.Count)
ReDim Preserve sIdDec(pSelectionSet.Count)
'Créer une nouvelle requete vide
pQueryFilterDef = New QueryFilter
'Indiquer la méthode pour trier
pQueryFilterDef.PostfixClause = "ORDER BY " & pFeatureLayer.FeatureClass.Fields.Field(iPosAttribut).Name
'Interfaces pour extraire les éléments sélectionnés
pSelectionSet.Search(CType(pQueryFilterDef, IQueryFilter), False, pCursor)
pFeatureCursor = CType(pCursor, IFeatureCursor)
'Extraire le premier élément
pFeature = pFeatureCursor.NextFeature()
'Traiter tous les éléments du FeatureLayer
For i = 0 To pSelectionSet.Count - 1
'Vérifier si l'élément est présent
If pFeature IsNot Nothing Then
'Ajouter la position de l'identifiant
sIdDec(i) = pFeature.Value(iPosAttribut).ToString
'Définir la géométrie à traiter
pGeometry = pFeature.ShapeCopy
'Projeter la géométrie à traiter
pGeometry.Project(pFeatureLayer.AreaOfInterest.SpatialReference)
'Ajouter la géométrie dans le Bag
pGeomColl.AddGeometry(pGeometry)
'Ajouter le OID de l'élément avec sa séquence
iOid(i) = pFeature.OID
'Vérifier si un Cancel a été effectué
If pTrackCancel.Continue = False Then Throw New CancelException("Traitement annulé !")
End If
'Extraire le prochain élément à traiter
pFeature = pFeatureCursor.NextFeature()
Next
'Cacher la barre de progression
If pTrackCancel.Progressor IsNot Nothing Then pTrackCancel.Progressor.Hide()
'Enlever la sélection des éléments
pFeatureSel.Clear()
Catch ex As Exception
'Retourner l'erreur
Throw ex
Finally
'Vider la mémoire
pFeatureSel = Nothing
pSelectionSet = Nothing
pCursor = Nothing
pFeatureCursor = Nothing
pFeature = Nothing
pGeometry = Nothing
pTopoOp = Nothing
pQueryFilterDef = Nothing
End Try
End Sub
'''<summary>
''' Routine qui permet d'extraire la liste des Oids d'éléments du FeatureLayer traité qui respecte la relation spatiale.
'''
'''<param name="pRelResult"> Résultat du traitement de la relation spatiale obtenu.</param>
'''<param name="iOidSel"> Vecteur des OIDs d'éléments à traiter.</param>
'''<param name="iOidRel"> Vecteur des OIDs d'éléments en relation.</param>
'''<param name="iOidAdd"> Vecteur des OIDs de la classe de découpage trouvés.</param>
'''
'''</summary>
Private Sub ExtraireListeOid(ByVal pRelResult As IRelationResult, _
ByVal iOidSel() As Integer, ByVal iOidRel() As Integer, ByRef iOidAdd() As Integer)
'Déclarer les variables de travail
Dim iSel As Integer = -1 'Numéro de séquence de la géométrie traitée.
Dim iRel As Integer = -1 'Numéro de séquence de la géométrie en relation.
Try
'Traiter tous les éléments
For i = 0 To pRelResult.RelationElementCount - 1
'Extraire la géométrie traitée (left) et celle en relation (right) qui respectent la relation spatiale
pRelResult.RelationElement(i, iSel, iRel)
'Indiquer que le OID respecte la relation en conservant le OID de l'élément de découpage en relation
'iOidAdd(iSel) = iOidRel(iRel)
iOidAdd(iSel) = iRel + 1
Next
Catch ex As Exception
'Retourner l'erreur
Throw ex
Finally
'Vider la mémoire
iSel = Nothing
iRel = Nothing
End Try
End Sub
'''<summary>
''' Routine qui permet de sélectionner les éléments du FeatureLayer traité qui respecte la relation spatiale VRAI du masque à 9 intersections ou du SCL.
'''
'''<param name="pGeomSelColl"> Interface contenant les géométries des éléments à traiter.</param>
'''<param name="pGeomRelColl"> Interface contenant les géométries des éléments en relation.</param>
'''<param name="iOidSel"> Vecteur des OIDs d'éléments à traiter.</param>
'''<param name="iOidRel"> Vecteur des OIDs d'éléments en relation.</param>
'''<param name="iOidAdd"> Vecteur du nombre de OIds trouvés.</param>
'''<param name="bEnleverSelection">Indique si on veut enlever les éléments trouvés de la sélection.</param>
'''<param name="pTrackCancel"> Permet d'annuler la sélection avec la touche ESC du clavier.</param>
'''<param name="pSelectionSet">Interface contenant les éléments sélectionnés.</param>
'''<param name="pGeomResColl">GéométryBag contenant les géométries en erreur.</param>
'''
'''</summary>
'''
Private Sub SelectionnerElementErreur(ByVal pGeomSelColl As IGeometryCollection, ByVal pGeomRelColl As IGeometryCollection, _
ByVal iOidSel() As Integer, ByVal iOidRel() As Integer, ByVal iOidAdd() As Integer, _
ByVal sIdDecSel() As String, ByVal sIdDecRel() As String, _
ByVal bEnleverSelection As Boolean, ByRef pTrackCancel As ITrackCancel, ByRef pSelectionSet As ISelectionSet, _
ByRef pGeomResColl As IGeometryCollection)
'Déclarer les variables de travail
Dim pRelOp As IRelationalOperator = Nothing 'Interface pour vérifier la relation spatiale.
Dim pTopoOp As ITopologicalOperator2 = Nothing 'Interface pour définir la géométrie en erreur.
Dim pGeometry As IGeometry = Nothing 'Interface contenant une géométrie.
Dim pGeomColl As IGeometryCollection = Nothing 'Interface utilisé pour extraire le nombre de composantes.
Dim pGDBridge As IGeoDatabaseBridge2 = Nothing 'Interface pour ajouter une liste de OID dans le SelectionSet.
Dim sMessageAttribut As String = "" 'Contient le message pour l'identifiant de découpage.
Dim sMessageGeometrie As String = "" 'Contient le message pour la géométrie.
Dim bSucces As Boolean = True 'Indiquer si toutes les conditions sont respectés.
Dim iSecDec As Integer = 0 'Contient le numéro de séquence du découpage traité.
Dim iOid(0) As Integer 'Liste des OIDs à sélectionner.
Dim iNbOid As Integer = 0 'Compteur de OIDs à sélectionner.
Try
'Afficher la barre de progression
InitBarreProgression(0, pGeomSelColl.GeometryCount, pTrackCancel)
'Vérifier si un seul découpage est présent
If pGeomRelColl.GeometryCount = 1 Then
'Définir le numéro de séquence de l'élément de découpage
iSecDec = 0
'Définir la géométrie de découpage
gpPolygoneDecoupage = CType(pGeomRelColl.Geometry(0), IPolygon)
End If
'Traiter tous les éléments
For i = 0 To pGeomSelColl.GeometryCount - 1
'Indiquer que toutes les conditions sont respectés par défaut
bSucces = True
'Définir l'identifiant de découpage de l'élément traité
gsIdentifiantDecoupage = sIdDecSel(i)
'Définir le message de l'identifiant de découpage valide par défaut
sMessageAttribut = " #L'identifiant de découpage est valide : " & gsIdentifiantDecoupage
'Définir le message de la géométrie valide par défaut
sMessageGeometrie = " #La géométrie de l'élément est à l'intérieur du polygone de découpage"
'Définir la géométrie de l'élément
pGeometry = pGeomSelColl.Geometry(i)
'Vérifier si aucun OID de découpage n'a été trouvé
If iOidAdd(i) = 0 Then
'Aucun numéro de séquence de découpage trouvé par défaut
iSecDec = -1
'Trouver le polygone de découpage
For j = 0 To pGeomRelColl.GeometryCount - 1
'Vérifier si l'identifiant correspond
If gsIdentifiantDecoupage = sIdDecRel(j) Then
'Définir le numéro de séquence de l'élément de découpage
iSecDec = j
'Définir le polygone de découpage
gpPolygoneDecoupage = CType(pGeomRelColl.Geometry(j), IPolygon)
'Sortir de la boucle
Exit For
End If
Next
'Vérifier si le polygone de découpage est présent
If gpPolygoneDecoupage IsNot Nothing Then
'Interface pour enlever la partie du polygone de découpage
pRelOp = CType(pGeometry, IRelationalOperator)
'Vérifier si la géométrie de découpage est disjoint avec le polygone de découpage
If pRelOp.Disjoint(gpPolygoneDecoupage) Then
'Indiquer que les conditions ne sont pas respectés
bSucces = False
'Définir le message d'erreur de la géométrie
sMessageGeometrie = " #La géométrie de l'élément est complètement à l'extérieur du polygone de découpage"
'Si la géométrie de découpage n'est pas disjoint avec le polygone de découpage
Else
'Vérifier si la géométrie traité n'est pas un point
If pGeometry.GeometryType <> esriGeometryType.esriGeometryPoint Then
'Interface pour enlever la partie du polygone de découpage
pTopoOp = CType(pGeometry, ITopologicalOperator2)
'Enlever la partie avec le polygone du découpage
pGeometry = pTopoOp.Difference(gpPolygoneDecoupage)
'Vérifier si la géométrie est vide
If pGeometry.IsEmpty Then
'Définir la géométrie de l'élément
pGeometry = pGeomSelColl.Geometry(i)
'Si la géométrie n'est pas vide
Else
'Indiquer que les conditions ne sont pas respectés
bSucces = False
'Définir le message d'erreur de la géométrie
sMessageGeometrie = " #La géométrie de l'élément n'est pas à l'intérieur du polygone de découpage"
End If
End If
End If
'Si aucun polygone de découpage trouvé
Else
'Indiquer que les conditions ne sont pas respectés
bSucces = False
'Définir le message d'erreur de la géométrie
sMessageGeometrie = " #L'identifiant de l'élément ne correspond à aucun polygone de découpage"
End If
'Si un élément de découpage est trouvé
Else
'Vérifier si le découpage est différent
If iSecDec <> iOidAdd(i) - 1 Then
'Définir le numéro de séquence de l'élément de découpage
iSecDec = iOidAdd(i) - 1
'Définir la géométrie de découpage
gpPolygoneDecoupage = CType(pGeomRelColl.Geometry(iSecDec), IPolygon)
End If
'Si l'dentifiant de découpage est invalide
If gsIdentifiantDecoupage <> sIdDecRel(iSecDec) Then
'Indiquer que les condition ne sont pas respectés
bSucces = False
'Définir le message de l'identifiant de découpage
sMessageAttribut = " #L'identifiant de l'élément est différent de celui de découpage : '" & gsIdentifiantDecoupage & "' <> '" & sIdDecRel(iSecDec) & "'"
End If
End If
'Vérifier si on doit sélectionner l'élément traité
If (bEnleverSelection And bSucces = False) Or (bEnleverSelection = False And bSucces) Then
'Définir la liste des OIDs à sélectionner
iNbOid = iNbOid + 1
'Redimensionner la liste des OIDs à sélectionner
ReDim Preserve iOid(iNbOid - 1)
'Définir le OIDs dans la liste
iOid(iNbOid - 1) = iOidSel(i)
'Ajouter la géométrie en erreur dans le Bag
pGeomResColl.AddGeometry(pGeometry)
'Écrire une erreur
EcrireFeatureErreur("OID=" & iOidSel(i).ToString & sMessageAttribut & sMessageGeometrie & " /" & Parametres, pGeometry, iSecDec)
End If
'Vérifier si un Cancel a été effectué
If pTrackCancel.Continue = False Then Throw New CancelException("Traitement annulé !")
'Récupération de la mémoire disponble
pRelOp = Nothing
pTopoOp = Nothing
pGeometry = Nothing
sMessageAttribut = Nothing
sMessageGeometrie = Nothing
GC.Collect()
Next
'Interface pour enlever ou ajouter les OIDs trouvés dans le SelectionSet
pGDBridge = New GeoDatabaseHelperClass()
'Ajouter les OIDs trouvés dans le SelectionSet
pGDBridge.AddList(pSelectionSet, iOid)
'Cacher la barre de progression
If pTrackCancel.Progressor IsNot Nothing Then pTrackCancel.Progressor.Hide()
Catch ex As Exception
'Retourner l'erreur
Throw ex
Finally
'Vider la mémoire
pRelOp = Nothing
pTopoOp = Nothing
pGeometry = Nothing
pGDBridge = Nothing
sMessageAttribut = Nothing
sMessageGeometrie = Nothing
bSucces = Nothing
iSecDec = Nothing
iOid = Nothing
iNbOid = Nothing
End Try
End Sub
'''<summary>
''' Routine qui permet de sélectionner les éléments du FeatureLayer dont l'identifiant et la géométrie respecte ou non
''' l'identifiant de l'élément de découpage spécifié.
'''
''' Seuls les éléments sélectionnés sont traités.
''' Si aucun élément n'est sélectionné, tous les éléments sont considérés sélectionnés.
'''
''' bEnleverSelection=True : Les éléments qui respectent la contrainte sont enlevés dans la sélection.
''' bEnleverSelection=False : Les éléments qui respectent la contrainte sont conservés dans la sélection.
'''
'''<param name="pTrackCancel"> Permet d'annuler la sélection avec la touche ESC du clavier.</param>
'''<param name="bEnleverSelection"> Indique si on doit enlever les éléments de la sélection, sinon ils sont conservés. Défaut=True.</param>
'''
'''<return>Les intersections entre la géométrie des éléments sélectionnés et les géométries des éléments en relation.</return>
'''
'''</summary>
'''
Private Function TraiterDecoupageElementIdentifiant(ByRef pFeatureCursor As IFeatureCursor, ByRef pTrackCancel As ITrackCancel,
Optional ByVal bEnleverSelection As Boolean = True) As IGeometry
'Déclarer les variables de travail
Dim pFeatureSel As IFeatureSelection = Nothing 'Interface utilisé pour extraire et sélectionner les éléments du FeatureLayer.
Dim pFeature As IFeature = Nothing 'Interface contenant l'élément à traiter.
Dim pGeomSelColl As IGeometryCollection = Nothing 'Interface ESRI contenant les géométries sélectionnées.
Dim pGeometry As IGeometry = Nothing 'Interface contenant la géométrie de l'élément traité.
Dim pRelOp As IRelationalOperator = Nothing 'Interface pour valider la géométrie.
Dim pTopoOp As ITopologicalOperator2 = Nothing 'Interface pour définir la géométrie en erreur.
Dim sMessageAttribut As String = "" 'Contient le message pour l'identifiant.
Dim sMessageGeometrie As String = "" 'Contient le message pour la géométrie.
Dim bSucces As Boolean = False 'Indique si l'identifiant et la géométrie respecte l'élément de découpage.
Try
'Définir la géométrie par défaut
TraiterDecoupageElementIdentifiant = New GeometryBag
TraiterDecoupageElementIdentifiant.SpatialReference = gpFeatureLayerSelection.AreaOfInterest.SpatialReference
'Interface pour extraire et sélectionner les éléments
pFeatureSel = CType(gpFeatureLayerSelection, IFeatureSelection)
'Interface contenant les géométries des éléments sélectionnés
pGeomSelColl = CType(TraiterDecoupageElementIdentifiant, IGeometryCollection)
'Si la géométrie est de type MultiPoint, Polyline ou Polygon
If gpFeatureLayerSelection.FeatureClass.ShapeType = esriGeometryType.esriGeometryPoint _
Or gpFeatureLayerSelection.FeatureClass.ShapeType = esriGeometryType.esriGeometryMultipoint _
Or gpFeatureLayerSelection.FeatureClass.ShapeType = esriGeometryType.esriGeometryPolyline _
Or gpFeatureLayerSelection.FeatureClass.ShapeType = esriGeometryType.esriGeometryPolygon Then
'Projeter le polygone de découpage
gpPolygoneDecoupage.Project(TraiterDecoupageElementIdentifiant.SpatialReference)
'Interface pour valider la géométrie
pTopoOp = CType(gpPolygoneDecoupage, ITopologicalOperator2)
pRelOp = CType(pTopoOp.Buffer(gdPrecision), IRelationalOperator)
'Extraire le premier élément
pFeature = pFeatureCursor.NextFeature()
'Traiter tous les éléments sélectionnés du FeatureLayer
Do While Not pFeature Is Nothing
'Initialisation du traitement
bSucces = True
sMessageAttribut = "#L'identifiant de découpage de l'élément est valide"
sMessageGeometrie = "#La géométrie de l'élément est à l'intérieur du polygone de découpage"
'Interface pour projeter
pGeometry = pFeature.ShapeCopy
'Projeter la géométrie de l'élément
pGeometry.Project(TraiterDecoupageElementIdentifiant.SpatialReference)
'Vérifier si l'identifiant est valide
If pFeature.Value(giAttribut).ToString <> gsIdentifiantDecoupage Then
'Définir l'erreur
bSucces = False
sMessageAttribut = "#L'identifiant de découpage de l'élément est invalide," & gsNomAttribut & "=" & pFeature.Value(giAttribut).ToString
End If
'Vérifier si la géométrie est valide
If Not pRelOp.Contains(pGeometry) Then
'Interface pour définir la géométrie en erreur
pTopoOp = CType(pGeometry, ITopologicalOperator2)
'Définir la géométrie en erreur
pGeometry = pTopoOp.Difference(gpPolygoneDecoupage)
'Vérifier si la géométrie n'est pas vide
If Not pGeometry.IsEmpty Then
'Définir l'erreur
bSucces = False
sMessageGeometrie = "#La géométrie de l'élément n'est pas à l'intérieur du polygone de découpage"
Else
'Rédéfinir la géométrie de l'élément
pGeometry = CType(pTopoOp, IGeometry)
End If
End If
'Vérifier si on doit sélectionner l'élément
If (bSucces And Not bEnleverSelection) Or (Not bSucces And bEnleverSelection) Then
'Ajouter l'élément dans la sélection
pFeatureSel.Add(pFeature)
'Ajouter l'enveloppe de l'élément sélectionné
pGeomSelColl.AddGeometry(pGeometry)
'Écrire une erreur
EcrireFeatureErreur("OID=" & pFeature.OID.ToString _
& sMessageAttribut & sMessageGeometrie _
& "/" & gsExpression _
& "/Précision=" & gdPrecision.ToString, pGeometry)
End If
'Vérifier si un Cancel a été effectué
If pTrackCancel.Continue = False Then Exit Do
'Extraire le prochain élément à traiter
pFeature = pFeatureCursor.NextFeature()
Loop
End If
Catch ex As Exception
'Retourner l'erreur
Throw ex
Finally
'Vider la mémoire
pFeatureSel = Nothing
pFeature = Nothing
pGeomSelColl = Nothing
pGeometry = Nothing
pRelOp = Nothing
pTopoOp = Nothing
End Try
End Function
'''<summary>
''' Routine qui permet de sélectionner les éléments du FeatureLayer dont l'identifiant et la géométrie respecte ou non
''' l'identifiant de son élément de découpage en relation de position.
'''
''' Seuls les éléments sélectionnés sont traités.
''' Si aucun élément n'est sélectionné, tous les éléments sont considérés sélectionnés.
'''
''' bEnleverSelection=True : Les éléments qui respectent la contrainte sont enlevés dans la sélection.
''' bEnleverSelection=False : Les éléments qui respectent la contrainte sont conservés dans la sélection.
'''
'''<param name="pTrackCancel"> Permet d'annuler la sélection avec la touche ESC du clavier.</param>
'''<param name="bEnleverSelection"> Indique si on doit enlever les éléments de la sélection, sinon ils sont conservés. Défaut=True.</param>
'''
'''<return>Les intersections entre la géométrie des éléments sélectionnés et les géométries des éléments en relation.</return>
'''
'''</summary>
'''
Private Function TraiterDecoupageElement(ByRef pFeatureCursor As IFeatureCursor, ByRef pTrackCancel As ITrackCancel,
Optional ByVal bEnleverSelection As Boolean = True) As IGeometry
'Déclarer les variables de travail
Dim pFeatureSel As IFeatureSelection = Nothing 'Interface utilisé pour extraire et sélectionner les éléments du FeatureLayer.
Dim pFeature As IFeature = Nothing 'Interface contenant l'élément à traiter.
Dim pGeomSelColl As IGeometryCollection = Nothing 'Interface ESRI contenant les géométries sélectionnées.
Dim pGeometry As IGeometry = Nothing 'Interface contenant la géométrie de l'élément traité.
Dim pPoint As IPoint = Nothing 'Interface contenant le point du centre de l'élément.
Dim pSpatialFilter As ISpatialFilter = Nothing 'Interface contenant la relation spatiale de base.
Dim oFeatureColl As Collection = Nothing 'Objet contenant la collection des éléments en relation.
Dim pFeatureDecoupage As IFeature = Nothing 'Interface contenant l'élément de découpage.
Dim pGeometryDecoupage As IGeometry = Nothing 'Interface contenant la géométrie de l'élément de découpage.
Dim pRelOp As IRelationalOperator = Nothing 'Interface pour valider la géométrie.
Dim pTopoOp As ITopologicalOperator2 = Nothing 'Interface pour définir la géométrie en erreur.
Dim sIdentifiant As String = "" 'Identifiant de découpage à valider.
Dim sIdentifiantPrec As String = "" 'Identifiant de découpage précédant.
Dim sMessageAttribut As String = "" 'Contient le message pour l'identifiant.
Dim sMessageGeometrie As String = "" 'Contient le message pour la géométrie.
Dim bSucces As Boolean = False 'Indique si l'identifiant et la géométrie respecte l'élément de découpage.
Try
'Définir la géométrie par défaut
TraiterDecoupageElement = New GeometryBag
TraiterDecoupageElement.SpatialReference = gpFeatureLayerSelection.AreaOfInterest.SpatialReference
'Interface pour extraire et sélectionner les éléments
pFeatureSel = CType(gpFeatureLayerSelection, IFeatureSelection)
'Interface contenant les géométries des éléments sélectionnés
pGeomSelColl = CType(TraiterDecoupageElement, IGeometryCollection)
'Créer la requête spatiale
pSpatialFilter = New SpatialFilterClass
pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects
'Définir la référence spatiale de sortie dans la requête spatiale
pSpatialFilter.OutputSpatialReference(gpFeatureLayerDecoupage.FeatureClass.ShapeFieldName) = TraiterDecoupageElement.SpatialReference
'Extraire le premier élément
pFeature = pFeatureCursor.NextFeature()
'Traiter tous les éléments sélectionnés du FeatureLayer
Do While Not pFeature Is Nothing
'Initialisation du traitement
bSucces = True
sMessageAttribut = "#L'identifiant de découpage de l'élément est valide"
sMessageGeometrie = "#La géométrie de l'élément est à l'intérieur du polygone de découpage"
'Interface pour projeter
pGeometry = pFeature.ShapeCopy
pGeometry.Project(TraiterDecoupageElement.SpatialReference)
'Vérifier si l'identifiant précédant est différent celui de l'élément traité
If pFeature.Value(giAttribut).ToString <> sIdentifiant Then
'Extraire le centre d'une géométrie
pPoint = CentreGeometrie(pGeometry)
'Définir la géométrie utilisée pour la relation spatiale
pSpatialFilter.Geometry = pPoint
'Extraire les éléments en relation
oFeatureColl = ExtraireElementsRelation(pSpatialFilter, gpFeatureLayerDecoupage)
'Vérifier l'absence d'un élément de découpage
If oFeatureColl.Count = 0 Then
'Définir l'erreur
bSucces = False
sMessageAttribut = "#Aucun élément de découpage"
sMessageGeometrie = ""
'Plusieurs éléments de découpage
ElseIf oFeatureColl.Count > 1 Then
'Définir l'erreur
bSucces = False
sMessageAttribut = "#Plusieurs éléments de découpage"
sMessageGeometrie = ""
'Un élément de découpage
Else
'Définir l'élément de découpage
pFeatureDecoupage = CType(oFeatureColl.Item(1), IFeature)
'Définir la géométrie de découpage
pGeometryDecoupage = pFeatureDecoupage.ShapeCopy
pGeometryDecoupage.Project(TraiterDecoupageElement.SpatialReference)
'Interface pour valider la géométrie
pTopoOp = CType(pGeometryDecoupage, ITopologicalOperator2)
pRelOp = CType(pTopoOp.Buffer(gdPrecision), IRelationalOperator)
'Définir l'identifiant de découpage
sIdentifiant = pFeatureDecoupage.Value(giPosAttributDecoupage).ToString
'Définir l'identifiant de découpage précédant
sIdentifiantPrec = sIdentifiant
End If
End If
'Vérifier si un découpage est présent
If oFeatureColl.Count = 1 Then
'Vérifier si l'identifiant est valide
If pFeature.Value(giAttribut).ToString <> sIdentifiant Then
'Définir l'erreur
bSucces = False
sMessageAttribut = "#L'identifiant de découpage de l'élément est invalide," & gsNomAttribut & "=" & pFeature.Value(giAttribut).ToString
End If
'Vérifier si la géométrie est valide
If Not pRelOp.Contains(pGeometry) Then
'Interface pour définir la géométrie en erreur
pTopoOp = CType(pGeometry, ITopologicalOperator2)
'Définir la géométrie en erreur
pGeometry = pTopoOp.Difference(pGeometryDecoupage)
'Vérifier si la géométrie n'est pas vide
If Not pGeometry.IsEmpty Then
'Définir l'erreur
bSucces = False
sMessageGeometrie = "#La géométrie de l'élément n'est pas à l'intérieur du polygone de découpage"
Else
'Rédéfinir la géométrie de l'élément
pGeometry = CType(pTopoOp, IGeometry)
End If
End If
End If
'Vérifier si on doit sélectionner l'élément
If (bSucces And Not bEnleverSelection) Or (Not bSucces And bEnleverSelection) Then
'Ajouter l'élément dans la sélection
pFeatureSel.Add(pFeature)
'Ajouter l'enveloppe de l'élément sélectionné
pGeomSelColl.AddGeometry(pGeometry)
'Écrire une erreur
EcrireFeatureErreur("OID=" & pFeature.OID.ToString _
& sMessageAttribut & sMessageGeometrie _
& "/" & gsExpression & "=" & sIdentifiant _
& "/Précision=" & gdPrecision.ToString, pGeometry)
End If
'Vérifier si un Cancel a été effectué
If pTrackCancel.Continue = False Then Exit Do
'Extraire le prochain élément à traiter
pFeature = pFeatureCursor.NextFeature()
Loop
Catch ex As Exception
'Retourner l'erreur
Throw ex
Finally
'Vider la mémoire
pFeatureSel = Nothing
pFeature = Nothing
pGeomSelColl = Nothing
pGeometry = Nothing
pPoint = Nothing
pSpatialFilter = Nothing
oFeatureColl = Nothing
pFeatureDecoupage = Nothing
pGeometryDecoupage = Nothing
pRelOp = Nothing
pTopoOp = Nothing
End Try
End Function
#End Region
End Class
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.