text
stringlengths
43
2.01M
'Represents a custom dialog generated by the NX Block UI Styler '------------------------------------------------------------------------------ Partial Public Class FavoritePicker Inherits Snap.UI.BlockDialog Public Shared theFavoritePicker As FavoritePicker Private ChooseFruit As Snap.UI.Block.Enumeration ' Block type: Enumeration Private ChooseNumber As Snap.UI.Block.Integer ' Block type: Integer Private BigButton As Snap.UI.Block.Button ' Block type: Button Private Message As Snap.UI.Block.String ' Block type: String '------------------------------------------------------------------------------ 'Constructor to which dlx file with complete path name is passed '------------------------------------------------------------------------------ Public Sub New(ByVal theDlxFileName As String) Try Me.NXOpenBlockDialog = New Snap.UI.BlockDialog(theDlxFileName).NXOpenBlockDialog Me.NXOpenBlockDialog.AddApplyHandler(AddressOf ApplyCallback) Me.NXOpenBlockDialog.AddOkHandler(AddressOf OkCallback) Me.NXOpenBlockDialog.AddUpdateHandler(AddressOf UpdateCallback) Me.NXOpenBlockDialog.AddInitializeHandler(AddressOf InitializeCallback) Catch ex As Exception Throw ex End Try End Sub End Class
Imports System.ComponentModel.DataAnnotations Public Class clsSalesChannel Enum ChannelTypeEnum ''' <summary> ''' A custom Channel Type ''' </summary> Custom = -2 ''' <summary> ''' The customer has taken this item. Nothing further to action. ''' </summary> CarryOutSale = -1 ''' <summary> ''' There is not enough stock to fulfil this item. The customer has placed an order for it. They will come back in to collect when available. ''' </summary> CustomerOrderItem = 0 ''' <summary> ''' ''' </summary> CustomerSale = 1 ''' <summary> ''' Item has been ordered via a website and needs to be either collected or dispatched. ''' </summary> WebOrder = 2 ''' <summary> ''' This is for items that will be fulfilled from a different location (perhaps a warehouse) ''' </summary> MailOrder = 3 ''' <summary> ''' Order has been generated and entered via eBay. ''' </summary> eBay = 4 ''' <summary> ''' Order has been generated and entered via Amazon. This is an FBM order. FBA orders come in as No Customer Action as there is no dispatching to perform on these. ''' </summary> Amazon = 5 End Enum <Required> Property ChannelID As Integer Property AcceptsDeposits As Boolean Property Description As String <EnumDataType(GetType(ChannelTypeEnum))> <Required> Property ChannelType As ChannelTypeEnum End Class
Public Module VbModule Public Class VbClass Public Shared Sub Main() Run() End Sub Public Shared Function encrptPassword(ByVal password As String) As String Dim I As Integer Dim strtemppassword As String = "" For I = 1 To Len(password) Dim midChar As String = Mid(password, I, 1) Dim ascii As String = Asc(midChar) Dim value As String = Chr(ascii + 1) 'Note: Method Chr's argument must be between 0 and 255 strtemppassword = strtemppassword + Chr(Asc(Mid(password, I, 1)) + 1) & "-" 'main encryption, VB accepts + selectively and & for concatenation Next I encrptPassword = strtemppassword 'same as using return keyword End Function Public Shared Sub Test() Console.WriteLine("A PROGRAM TO ENCRYPT TEXT") Dim repeat As String = "y" While repeat.ToUpper() = "Y" Or repeat.ToUpper = "YES" 'VB does not need brackets for parameterless methods Console.WriteLine() Console.Write("Enter the value you wish to encrypt: ") Dim value As String = Console.ReadLine Console.WriteLine("The encypted value is: " & encrptPassword(value)) Console.WriteLine("") Console.Write("Enter 'y' to encrypt another value or 'n' to exit: ") repeat = Console.ReadLine() End While Console.WriteLine() Console.WriteLine("THE END...") Console.ReadKey() End Sub Public Sub RuntimeBinding() Dim obj As Object = 5 + 2 Console.WriteLine("An object casted directly into an integer by VB" & vbNewLine & Math.Pow(obj, 2)) Console.ReadKey() End Sub Public Shared Sub Run() Test() End Sub End Class End Module
Imports System.ComponentModel Imports System.IO #Region "PersonRepository Class" ' ********************************************** ' **** ' ****** Class ' **** ' ********************************************** ' Public MustInherit Class PeopleRepository ' ' ********************************************** ' **** ' ****** Constructor ' **** ' ********************************************** ' Protected Friend Sub New(ByVal thepeoplepath As FileInfo, ByVal thepeopletype As String) PeoplePath = thepeoplepath m_PeopleType = thepeopletype GetList() End Sub ' ' ********************************************** ' **** ' ****** Methods ' **** ' ********************************************** ' Public Function GetList() As BindingList(Of PersonInfo) ' Let's make sure we don't keep adding and adding to the list! If IsLoaded Then Return PeopleList End If ' Open the file and assign it to a stream reader Dim reader As StreamReader Try reader = New StreamReader(PeoplePath.FullName, True) Catch e As Exception MsgBox(e.Message) Return PeopleList End Try ' Blow off the first line because it contains header information reader.ReadLine() ' Process the rest of the file While Not reader.EndOfStream Dim splitArray() As String = reader.ReadLine.Split(",") Dim thePerson As New PersonInfo Try With thePerson .FirstName = CType(splitArray(0), String) .LastName = CType(splitArray(1), String) .CompanyName = CType(splitArray(2), String) .Address1 = CType(splitArray(3), String) .Address2 = CType(splitArray(4), String) .City = CType(splitArray(5), String) .State = CType(splitArray(6), String) .PostalCode = CType(splitArray(7), String) ' Skip on purpose .eMail = CType(splitArray(9), String) .eMail2 = CType(splitArray(10), String) .eMail3 = CType(splitArray(11), String) .Phone = CType(splitArray(12), String) ' Skip on purpose .Note = CType(splitArray(18), String) .HGUserName = CType(splitArray(19), String) .Website = CType(splitArray(20), String) .GUID = CType(splitArray(21), String) .Type = CType(splitArray(22), String) End With ' Translate Client (or Agent) to Customer (or Rep) Dim testType As String If PeopleType = "Client" Then testType = "Customer" ElseIf PeopleType = "Agent" Then testType = "Rep" Else testType = PeopleType End If If thePerson.Type.Contains(testType) Then PeopleList.Add(thePerson) End If Catch ex As Exception MsgBox(ex.Message) End Try End While ' making sure we don't keep adding and adding to the list! m_IsLoaded = True Return PeopleList End Function ' ' ********************************************** ' **** ' ****** Properties ' **** ' ********************************************** ' Private ReadOnly m_PeopleType As String = "" Public Overridable ReadOnly Property PeopleType As String Get Return m_PeopleType End Get End Property Private m_PeoplePath As FileInfo Protected Friend Property PeoplePath As FileInfo Get Return m_PeoplePath End Get Set(value As FileInfo) If IsNothing(value) Then value = New FileInfo(My.Computer.FileSystem.SpecialDirectories.MyDocuments) m_PeoplePath = value End Set End Property Private m_list As BindingList(Of PersonInfo) Protected Friend Property PeopleList As IList(Of PersonInfo) Get If IsNothing(m_list) Then m_list = New BindingList(Of PersonInfo)() Return m_list End Get Set(value As IList(Of PersonInfo)) If IsNothing(value) Then value = New BindingList(Of PersonInfo)() m_list = value End Set End Property Private m_IsLoaded As Boolean Public ReadOnly Property IsLoaded As Boolean Get Return m_IsLoaded End Get End Property End Class #End Region
Imports System.Windows.Forms Imports System.Runtime.CompilerServices Namespace Extension Public Module TextBoxHelper Private lasttime As New Dictionary(Of TextBox, DateTime) <Extension()> Public Sub ShowMsg(tb As TextBox, msg As String) If tb.InvokeRequired Then tb.Invoke(Sub() tb.AppendText(Now & " " & msg & vbCrLf)) Else tb.AppendText(Now & " " & msg & vbCrLf) End If End Sub <Extension> Public Sub ShowMsg(tb As TextBox, msg As String, tick As Integer) If Not lasttime.Keys.Contains(tb) Then 'tb.Invoke(Sub() tb.AppendText(Now & " " & msg & vbCrLf)) tb.ShowMsg(msg) lasttime.Add(tb, Now) ElseIf (Now - lasttime(tb)).TotalMilliseconds > tick Then 'tb.Invoke(Sub() tb.AppendText(Now & " " & msg & vbCrLf)) tb.ShowMsg(msg) lasttime(tb) = Now End If End Sub <Extension> Public Sub InsertToFocus(tb As TextBox, msg As String) Dim i = tb.SelectionStart Dim txt = tb.Text tb.Text = txt.Insert(i, msg) tb.SelectionStart = i + msg.Length tb.Focus() End Sub End Module End Namespace
Namespace Agent Public Class AgentConfiguration Public Property AgentProperty As String Public Property AgentValue As String End Class Public Class AgentData Public Property AgentName As String Public Property AgentClass As String Public Property AgentProperty As String Public Property AgentValue As String Public Property AgentDate As Date End Class Public Class AgentState Public Property AgentName As String Public Property AgentClass As String Public Property AgentProperty As String Public Property AgentValue As String Public Property AgentDate As Date End Class Public Class AgentSystem Public Property AgentName As String Public Property AgentDomain As String Public Property AgentIP As String Public Property AgentOSName As String Public Property AgentOSBuild As String Public Property AgentOSArchitecture As String Public Property AgentProcessors As String Public Property AgentMemory As String Public Property AgentUptime As String Public Property AgentDate As String End Class End Namespace
Public Class clsRIFF Implements IDisposable Private Structure ChunkHeader Public ChunkID As String Public ChunkSize As UInt32 Public Format As String End Structure Private Structure Chunk Public Header As ChunkHeader Public Data As Byte() End Structure Private bValid As Boolean Private bDTS As Boolean Private bWAV As Boolean Private bAVI As Boolean 'http://msdn.microsoft.com/en-us/library/ms779636%28VS.85%29.aspx 'http://www.morgan-multimedia.com/download/odmlff2.pdf Public Structure AVIMAINHEADER Public fcc As String Public cb As UInt32 Public dwMicroSecPerFrame As UInt32 Public dwMaxBytesPerSec As UInt32 Public dwPaddingGranularity As UInt32 Public dwFlags As AVIMAINHEADER_FLAGS Public dwTotalFrames As UInt32 Public dwInitialFrames As UInt32 Public dwStreams As UInt32 Public dwSuggestedBufferSize As UInt32 Public dwWidth As UInt32 Public dwHeight As UInt32 Public dwReserved0 As UInt32 Public dwReserved1 As UInt32 Public dwReserved2 As UInt32 Public dwReserved3 As UInt32 End Structure <Flags()> Public Enum AVIMAINHEADER_FLAGS As UInt32 AVIF_HASINDEX = &H10 AVIF_MUSTUSEINDEX = &H20 AVIF_ISINTERLEAVED = &H100 AVIF_TRUSTCKTYPE = &H800 AVIF_WASCAPTUREFILE = &H10000 AVIF_COPYRIGHTED = &H20000 End Enum Public Structure AVISTREAMHEADERFRAME Public left As Int16 Public top As Int16 Public right As Int16 Public bottom As Int16 End Structure <Flags()> Public Enum AVISTREAMHEADER_FLAGS As UInt32 AVISF_DISABLED = &H1 AVISF_VIDEO_PALCHANGES = &H10000 End Enum Public Structure AVISTREAMHEADER Public fcc As String Public cb As UInt32 Public fccType As String Public fccHandler As String Public dwFlags As AVISTREAMHEADER_FLAGS Public wPriority As UInt16 Public wLanguage As UInt16 Public dwInitialFrames As UInt32 Public dwScale As UInt32 Public dwRate As UInt32 Public dwStart As UInt32 Public dwLength As UInt32 Public dwSuggestedBufferSize As UInt32 Public dwQuality As UInt32 Public dwSampleSize As UInt32 Public rcFrame As AVISTREAMHEADERFRAME Public StreamName As String End Structure <Flags()> Public Enum AVIOLDINDEX_ENTRY_FLAGS AVIIF_LIST = &H1 AVIIF_KEYFRAME = &H10 AVIIF_NO_TIME = &H100 AVIIF_COMPRESSOR = &HFFF0000 End Enum Public Structure AVIOLDINDEX Public fcc As String Public cb As UInt32 Public aIndex() As AVIOLDINDEX_ENTRY End Structure Public Structure AVIOLDINDEX_ENTRY Public dwChunkID As UInt32 Public dwFlags As AVIOLDINDEX_ENTRY_FLAGS Public dwOffset As UInt32 Public dwSize As UInt32 End Structure Public Structure IDVX_INFO Public Movie As String Public Author As String Public Year As String Public Comment As String Public Genre As IDVX_GENRE Public Rating As IDVX_RATING Public Extra As Byte() Public FileID As String End Structure Public Enum IDVX_GENRE As Integer Action = 0 <StringValue("Action/Adventure")> ActionAdventure Adventure Adult Anime Cartoon Claymation Comedy Commercial Documentary Drama <StringValue("Home Video")> HomeVideo Horror Infomercial Interactive Mystery <StringValue("Music Video")> MusicVideo Other Religion <StringValue("Science Fiction")> SciFi Thriller Western End Enum Public Enum IDVX_RATING As Byte Unrated = 0 G PG <StringValue("PG-13")> PG13 R <StringValue("NC-17")> NC17 End Enum Public Structure BITMAPINFO Public bmiHeader As BITMAPINFOHEADER Public bmiColors() As RGBQUAD End Structure Public Structure BITMAPINFOHEADER Public biSize As UInt32 Public biWidth As Int32 Public biHeight As Int32 Public biPlanes As UInt16 Public biBitCount As UInt16 Public biCompression As AVIFormatTag Public biSizeImage As UInt32 Public biXPelsPerMeter As Int32 Public biYPelsPerMeter As Int32 Public biClrUsed As UInt32 Public biClrImportant As UInt32 End Structure Public Structure RGBQUAD Public rgbBlue As Byte Public rgbGreen As Byte Public rgbRed As Byte Public rgbReserved As Byte Public Sub New(data As Byte()) rgbBlue = data(0) rgbGreen = data(1) rgbRed = data(2) rgbReserved = data(3) End Sub End Structure Public Structure WAVEFORMAT Public wFormatTag As WAVFormatTag Public nChannels As UInt16 Public nSamplesPerSec As UInt32 Public nAvgBytesPerSec As UInt32 Public nBlockAlign As UInt16 End Structure Public Structure WAVEFORMATEX Public Format As WAVEFORMAT Public wBitsPerSample As UInt16 Public cbSize As UInt16 End Structure Public Structure WAVEFORMATEXTENSIBLE_SAMPLES Public wValidBitsPerSample As UInt16 Public wSamplesPerBlock As UInt16 Public wReserved As UInt16 End Structure Public Structure WAVEFORMATEXTENSIBLE Public Format As WAVEFORMATEX Public Samples As WAVEFORMATEXTENSIBLE_SAMPLES Public dwChannelMask As UInt32 Public SubFormat As Guid End Structure Public Enum WAVFormatTag As UInt16 WAVE_FORMAT_UNKNOWN = &H0 WAVE_FORMAT_PCM = &H1 WAVE_FORMAT_ADPCM = &H2 WAVE_FORMAT_IEEE_FLOAT = &H3 WAVE_FORMAT_VSELP = &H4 WAVE_FORMAT_IBM_CVSD = &H5 WAVE_FORMAT_ALAW = &H6 WAVE_FORMAT_MULAW = &H7 WAVE_FORMAT_DTS = &H8 WAVE_FORMAT_DRM = &H9 WAVE_FORMAT_WMAVOICE9 = &HA WAVE_FORMAT_OKI_ADPCM = &H10 WAVE_FORMAT_DVI_ADPCM = &H11 WAVE_FORMAT_MEDIASPACE_ADPCM = &H12 WAVE_FORMAT_SIERRA_ADPCM = &H13 WAVE_FORMAT_G723_ADPCM = &H14 WAVE_FORMAT_DIGISTD = &H15 WAVE_FORMAT_DIGIFIX = &H16 WAVE_FORMAT_DIALOGIC_OKI_ADPCM = &H17 WAVE_FORMAT_MEDIAVISION_ADPCM = &H18 WAVE_FORMAT_CU_CODEC = &H19 WAVE_FORMAT_YAMAHA_ADPCM = &H20 WAVE_FORMAT_SONARC = &H21 WAVE_FORMAT_DSPGROUP_TRUESPEECH = &H22 WAVE_FORMAT_ECHOSC1 = &H23 WAVE_FORMAT_AUDIOFILE_AF36 = &H24 WAVE_FORMAT_APTX = &H25 WAVE_FORMAT_AUDIOFILE_AF10 = &H26 WAVE_FORMAT_PROSODY_1612 = &H27 WAVE_FORMAT_LRC = &H28 WAVE_FORMAT_DOLBY_AC2 = &H30 WAVE_FORMAT_GSM610 = &H31 WAVE_FORMAT_MSNAUDIO = &H32 WAVE_FORMAT_ANTEX_ADPCME = &H33 WAVE_FORMAT_CONTROL_RES_VQLPC = &H34 WAVE_FORMAT_DIGIREAL = &H35 WAVE_FORMAT_DIGIADPCM = &H36 WAVE_FORMAT_CONTROL_RES_CR10 = &H37 WAVE_FORMAT_NMS_VBXADPCM = &H38 WAVE_FORMAT_CS_IMAADPCM = &H39 WAVE_FORMAT_ECHOSC3 = &H3A WAVE_FORMAT_ROCKWELL_ADPCM = &H3B WAVE_FORMAT_ROCKWELL_DIGITALK = &H3C WAVE_FORMAT_XEBEC = &H3D WAVE_FORMAT_G721_ADPCM = &H40 WAVE_FORMAT_G728_CELP = &H41 WAVE_FORMAT_MSG723 = &H42 WAVE_FORMAT_MPEG = &H50 WAVE_FORMAT_RT24 = &H52 WAVE_FORMAT_PAC = &H53 WAVE_FORMAT_MPEGLAYER3 = &H55 WAVE_FORMAT_LUCENT_G723 = &H59 WAVE_FORMAT_CIRRUS = &H60 WAVE_FORMAT_ESPCM = &H61 WAVE_FORMAT_VOXWARE = &H62 WAVEFORMAT_CANOPUS_ATRAC = &H63 WAVE_FORMAT_G726_ADPCM = &H64 WAVE_FORMAT_G722_ADPCM = &H65 WAVE_FORMAT_DSAT = &H66 WAVE_FORMAT_DSAT_DISPLAY = &H67 WAVE_FORMAT_VOXWARE_BYTE_ALIGNED = &H69 WAVE_FORMAT_VOXWARE_AC8 = &H70 WAVE_FORMAT_VOXWARE_AC10 = &H71 WAVE_FORMAT_VOXWARE_AC16 = &H72 WAVE_FORMAT_VOXWARE_AC20 = &H73 WAVE_FORMAT_VOXWARE_RT24 = &H74 WAVE_FORMAT_VOXWARE_RT29 = &H75 WAVE_FORMAT_VOXWARE_RT29HW = &H76 WAVE_FORMAT_VOXWARE_VR12 = &H77 WAVE_FORMAT_VOXWARE_VR18 = &H78 WAVE_FORMAT_VOXWARE_TQ40 = &H79 WAVE_FORMAT_SOFTSOUND = &H80 WAVE_FORMAT_VOXWARE_TQ60 = &H81 WAVE_FORMAT_MSRT24 = &H82 WAVE_FORMAT_G729A = &H83 WAVE_FORMAT_MVI_MV12 = &H84 WAVE_FORMAT_DF_G726 = &H85 WAVE_FORMAT_DF_GSM610 = &H86 WAVE_FORMAT_ISIAUDIO = &H88 WAVE_FORMAT_ONLIVE = &H89 WAVE_FORMAT_SBC24 = &H91 WAVE_FORMAT_DOLBY_AC3_SPDIF = &H92 WAVE_FORMAT_ZYXEL_ADPCM = &H97 WAVE_FORMAT_PHILIPS_LPCBB = &H98 WAVE_FORMAT_PACKED = &H99 WAVE_FORMAT_RAW_AAC1 = &HFF WAVE_FORMAT_RHETOREX_ADPCM = &H100 WAVE_FORMAT_IRAT = &H101 WAVE_FORMAT_VIVO_G723 = &H111 WAVE_FORMAT_VIVO_SIREN = &H112 WAVE_FORMAT_DIGITAL_G723 = &H123 WAVE_FORMAT_WMAUDIO2 = &H161 WAVE_FORMAT_WMAUDIO3 = &H162 WAVE_FORMAT_WMAUDIO_LOSSLESS = &H163 WAVE_FORMAT_WMASPDIF = &H164 WAVE_FORMAT_CREATIVE_ADPCM = &H200 WAVE_FORMAT_CREATIVE_FASTSPEECH8 = &H202 WAVE_FORMAT_CREATIVE_FASTSPEECH10 = &H203 WAVE_FORMAT_QUARTERDECK = &H220 WAVE_FORMAT_RAW_SPORT = &H240 WAVE_FORMAT_ESST_AC3 = &H241 WAVE_FORMAT_FM_TOWNS_SND = &H300 WAVE_FORMAT_BTV_DIGITAL = &H400 WAVE_FORMAT_VME_VMPCM = &H680 WAVE_FORMAT_OLIGSM = &H1000 WAVE_FORMAT_OLIADPCM = &H1001 WAVE_FORMAT_OLICELP = &H1002 WAVE_FORMAT_OLISBC = &H1003 WAVE_FORMAT_OLIOPR = &H1004 WAVE_FORMAT_LH_CODEC = &H1100 WAVE_FORMAT_NORRIS = &H1400 WAVE_FORMAT_ISIAUDIO2 = &H1401 WAVE_FORMAT_SOUNDSPACE_MUSICOMPRESS = &H1500 WAVE_FORMAT_MPEG_ADTS_AAC = &H1600 WAVE_FORMAT_MPEG_LOAS = &H1602 WAVE_FORMAT_MPEG_HEAAC = &H1610 WAVE_FORMAT_DVM = &H2000 WAVE_FORMAT_DTS2 = &H2001 WAVE_FORMAT_EXTENSIBLE = &HFFFE WAVE_FORMAT_DEVELOPMENT = &HFFFF End Enum Public Class StringValueAttribute Inherits Attribute Public Property Value As String Public Sub New(ByVal val As String) Value = val End Sub Public Overrides Function ToString() As String Return Value End Function End Class Public Enum AVIFormatTag As ULong <StringValue("3IV1")> AVI_FORMAT_3IV1 = &H31564933 <StringValue("3IV2")> AVI_FORMAT_3IV2 = &H32564933 <StringValue("8BPS")> AVI_FORMAT_8BPS = &H53504238 <StringValue("AASC")> AVI_FORMAT_AASC = &H43534141 <StringValue("ABYR")> AVI_FORMAT_ABYR = &H52594241 <StringValue("ADV1")> AVI_FORMAT_ADV1 = &H31564441 <StringValue("ADVJ")> AVI_FORMAT_ADVJ = &H4A564441 <StringValue("AEMI")> AVI_FORMAT_AEMI = &H494D4541 <StringValue("AFLC")> AVI_FORMAT_AFLC = &H434C4641 <StringValue("AFLI")> AVI_FORMAT_AFLI = &H494C4641 <StringValue("AJPG")> AVI_FORMAT_AJPG = &H47504A41 <StringValue("AMPG")> AVI_FORMAT_AMPG = &H47504D41 <StringValue("ANIM")> AVI_FORMAT_ANIM = &H4D494E41 <StringValue("AP41")> AVI_FORMAT_AP41 = &H31345041 <StringValue("ASLC")> AVI_FORMAT_ASLC = &H434C5341 <StringValue("ASV1")> AVI_FORMAT_ASV1 = &H31565341 <StringValue("ASV2")> AVI_FORMAT_ASV2 = &H32565341 <StringValue("ASVX")> AVI_FORMAT_ASVX = &H58565341 <StringValue("AUR2")> AVI_FORMAT_AUR2 = &H32525541 <StringValue("AURA")> AVI_FORMAT_AURA = &H41525541 <StringValue("AVC1")> AVI_FORMAT_AVC1 = &H31435641 <StringValue("AVRN")> AVI_FORMAT_AVRN = &H4E525641 <StringValue("BA81")> AVI_FORMAT_BA81 = &H31384142 <StringValue("BINK")> AVI_FORMAT_BINK = &H4B4E4942 <StringValue("BLZ0")> AVI_FORMAT_BLZ0 = &H305A4C42 <StringValue("BT20")> AVI_FORMAT_BT20 = &H30325442 <StringValue("BTCV")> AVI_FORMAT_BTCV = &H56435442 <StringValue("BW10")> AVI_FORMAT_BW10 = &H30315742 <StringValue("BYR1")> AVI_FORMAT_BYR1 = &H31525942 <StringValue("BYR2")> AVI_FORMAT_BYR2 = &H32525942 <StringValue("CC12")> AVI_FORMAT_CC12 = &H32314343 <StringValue("CDVC")> AVI_FORMAT_CDVC = &H43564443 <StringValue("CFCC")> AVI_FORMAT_CFCC = &H43434643 <StringValue("CGDI")> AVI_FORMAT_CGDI = &H49444743 <StringValue("CHAM")> AVI_FORMAT_CHAM = &H4D414843 <StringValue("CJPG")> AVI_FORMAT_CJPG = &H47504A43 <StringValue("CLJR")> AVI_FORMAT_CLJR = &H524A4C43 <StringValue("CMYK")> AVI_FORMAT_CMYK = &H4B594D43 <StringValue("CPLA")> AVI_FORMAT_CPLA = &H414C5043 <StringValue("CRAM")> AVI_FORMAT_CRAM = &H4D415243 <StringValue("CSCD")> AVI_FORMAT_CSCD = &H44435343 <StringValue("CTRX")> AVI_FORMAT_CTRX = &H58525443 <StringValue("CVID")> AVI_FORMAT_CVID = &H44495643 <StringValue("CWLT")> AVI_FORMAT_CWLT = &H544C5743 <StringValue("CXY1")> AVI_FORMAT_CXY1 = &H31595843 <StringValue("CXY2")> AVI_FORMAT_CXY2 = &H32595843 <StringValue("CYUV")> AVI_FORMAT_CYUV = &H56555943 <StringValue("CYUY")> AVI_FORMAT_CYUY = &H59555943 <StringValue("D261")> AVI_FORMAT_D261 = &H31363244 <StringValue("D263")> AVI_FORMAT_D263 = &H33363244 <StringValue("DAVC")> AVI_FORMAT_DAVC = &H43564144 <StringValue("DCL1")> AVI_FORMAT_DCL1 = &H314C4344 <StringValue("DCL2")> AVI_FORMAT_DCL2 = &H324C4344 <StringValue("DCL3")> AVI_FORMAT_DCL3 = &H334C4344 <StringValue("DCL4")> AVI_FORMAT_DCL4 = &H344C4344 <StringValue("DCL5")> AVI_FORMAT_DCL5 = &H354C4344 <StringValue("DIV3")> AVI_FORMAT_DIV3 = &H33564944 <StringValue("DIV4")> AVI_FORMAT_DIV4 = &H34564944 <StringValue("DIV5")> AVI_FORMAT_DIV5 = &H35564944 <StringValue("DIVX")> AVI_FORMAT_DIVX = &H58564944 <StringValue("DM4V")> AVI_FORMAT_DM4V = &H56344D44 <StringValue("DMB1")> AVI_FORMAT_DMB1 = &H31424D44 <StringValue("DMB2")> AVI_FORMAT_DMB2 = &H32424D44 <StringValue("DMK2")> AVI_FORMAT_DMK2 = &H324B4D44 <StringValue("DSVD")> AVI_FORMAT_DSVD = &H44565344 <StringValue("DUCK")> AVI_FORMAT_DUCK = &H4B435544 <StringValue("DV25")> AVI_FORMAT_DV25 = &H35325644 <StringValue("DV50")> AVI_FORMAT_DV50 = &H30355644 <StringValue("DVAN")> AVI_FORMAT_DVAN = &H4E415644 <StringValue("DVCS")> AVI_FORMAT_DVCS = &H53435644 <StringValue("DVE2")> AVI_FORMAT_DVE2 = &H32455644 <StringValue("DVH1")> AVI_FORMAT_DVH1 = &H31485644 <StringValue("DVHD")> AVI_FORMAT_DVHD = &H44485644 <StringValue("DVSD")> AVI_FORMAT_DVSD = &H44535644 <StringValue("DVSL")> AVI_FORMAT_DVSL = &H4C535644 <StringValue("DVX1")> AVI_FORMAT_DVX1 = &H31585644 <StringValue("DVX2")> AVI_FORMAT_DVX2 = &H32585644 <StringValue("DVX3")> AVI_FORMAT_DVX3 = &H33585644 <StringValue("DX50")> AVI_FORMAT_DX50 = &H30355844 <StringValue("DXGM")> AVI_FORMAT_DXGM = &H4D475844 <StringValue("DXTC")> AVI_FORMAT_DXTC = &H43545844 <StringValue("DXT1")> AVI_FORMAT_DXT1 = &H31545844 <StringValue("DXT2")> AVI_FORMAT_DXT2 = &H32545844 <StringValue("DXT3")> AVI_FORMAT_DXT3 = &H33545844 <StringValue("DXT4")> AVI_FORMAT_DXT4 = &H34545844 <StringValue("DXT5")> AVI_FORMAT_DXT5 = &H35545844 <StringValue("EKQ0")> AVI_FORMAT_EKQ0 = &H30514B45 <StringValue("ELK0")> AVI_FORMAT_ELK0 = &H304B4C45 <StringValue("EM2V")> AVI_FORMAT_EM2V = &H56324D45 <StringValue("ES07")> AVI_FORMAT_ES07 = &H37305345 <StringValue("ESCP")> AVI_FORMAT_ESCP = &H50435345 <StringValue("ETV1")> AVI_FORMAT_ETV1 = &H31565445 <StringValue("ETV2")> AVI_FORMAT_ETV2 = &H32565445 <StringValue("ETVC")> AVI_FORMAT_ETVC = &H43565445 <StringValue("FFV1")> AVI_FORMAT_FFV1 = &H31564646 <StringValue("FLJP")> AVI_FORMAT_FLJP = &H504A4C46 <StringValue("FMP4")> AVI_FORMAT_FMP4 = &H34504D46 <StringValue("FMVC")> AVI_FORMAT_FMVC = &H43564D46 <StringValue("FPS1")> AVI_FORMAT_FPS1 = &H31535046 <StringValue("FRWA")> AVI_FORMAT_FRWA = &H41575246 <StringValue("FRWD")> AVI_FORMAT_FRWD = &H44575246 <StringValue("FVF1")> AVI_FORMAT_FVF1 = &H31465646 <StringValue("GEOX")> AVI_FORMAT_GEOX = &H584F4547 <StringValue("GJPG")> AVI_FORMAT_GJPG = &H47504A47 <StringValue("GLZW")> AVI_FORMAT_GLZW = &H575A4C47 <StringValue("GPEG")> AVI_FORMAT_GPEG = &H47455047 <StringValue("GWLT")> AVI_FORMAT_GWLT = &H544C5747 <StringValue("H260")> AVI_FORMAT_H260 = &H30363248 <StringValue("H261")> AVI_FORMAT_H261 = &H31363248 <StringValue("H262")> AVI_FORMAT_H262 = &H32363248 <StringValue("H263")> AVI_FORMAT_H263 = &H33363248 <StringValue("H264")> AVI_FORMAT_H264 = &H34363248 <StringValue("H265")> AVI_FORMAT_H265 = &H35363248 <StringValue("H266")> AVI_FORMAT_H266 = &H36363248 <StringValue("H267")> AVI_FORMAT_H267 = &H37363248 <StringValue("H268")> AVI_FORMAT_H268 = &H38363248 <StringValue("H269")> AVI_FORMAT_H269 = &H39363248 <StringValue("HDYC")> AVI_FORMAT_HDYC = &H43594448 <StringValue("HFYU")> AVI_FORMAT_HFYU = &H55594648 <StringValue("HMCR")> AVI_FORMAT_HMCR = &H52434D48 <StringValue("HMRR")> AVI_FORMAT_HMRR = &H52524D48 <StringValue("I263")> AVI_FORMAT_I263 = &H33363249 <StringValue("I420")> AVI_FORMAT_I420 = &H30323449 <StringValue("IAN ")> AVI_FORMAT_IAN = &H204E4149 <StringValue("ICLB")> AVI_FORMAT_ICLB = &H424C4349 <StringValue("IGOR")> AVI_FORMAT_IGOR = &H524F4749 <StringValue("IJPG")> AVI_FORMAT_IJPG = &H47504A49 <StringValue("ILVC")> AVI_FORMAT_ILVC = &H43564C49 <StringValue("ILVR")> AVI_FORMAT_ILVR = &H52564C49 <StringValue("IPDV")> AVI_FORMAT_IPDV = &H56445049 <StringValue("IR21")> AVI_FORMAT_IR21 = &H31325249 <StringValue("IRAW")> AVI_FORMAT_IRAW = &H57415249 <StringValue("ISME")> AVI_FORMAT_ISME = &H454D5349 <StringValue("IV30")> AVI_FORMAT_IV30 = &H30335649 <StringValue("IV31")> AVI_FORMAT_IV31 = &H31335649 <StringValue("IV32")> AVI_FORMAT_IV32 = &H32335649 <StringValue("IV33")> AVI_FORMAT_IV33 = &H33335649 <StringValue("IV34")> AVI_FORMAT_IV34 = &H34335649 <StringValue("IV35")> AVI_FORMAT_IV35 = &H35335649 <StringValue("IV36")> AVI_FORMAT_IV36 = &H36335649 <StringValue("IV37")> AVI_FORMAT_IV37 = &H37335649 <StringValue("IV38")> AVI_FORMAT_IV38 = &H38335649 <StringValue("IV39")> AVI_FORMAT_IV39 = &H39335649 <StringValue("IV40")> AVI_FORMAT_IV40 = &H30345649 <StringValue("IV41")> AVI_FORMAT_IV41 = &H31345649 <StringValue("IV42")> AVI_FORMAT_IV42 = &H32345649 <StringValue("IV43")> AVI_FORMAT_IV43 = &H33345649 <StringValue("IV44")> AVI_FORMAT_IV44 = &H34345649 <StringValue("IV45")> AVI_FORMAT_IV45 = &H35345649 <StringValue("IV46")> AVI_FORMAT_IV46 = &H36345649 <StringValue("IV47")> AVI_FORMAT_IV47 = &H37345649 <StringValue("IV48")> AVI_FORMAT_IV48 = &H38345649 <StringValue("IV49")> AVI_FORMAT_IV49 = &H39345649 <StringValue("IV50")> AVI_FORMAT_IV50 = &H30355649 <StringValue("JBYR")> AVI_FORMAT_JBYR = &H5259424A <StringValue("JPEG")> AVI_FORMAT_JPEG = &H4745504A <StringValue("JPGL")> AVI_FORMAT_JPGL = &H4C47504A <StringValue("KMVC")> AVI_FORMAT_KMVC = &H43564D4B <StringValue("L261")> AVI_FORMAT_L261 = &H3136324C <StringValue("L263")> AVI_FORMAT_L263 = &H3336324C <StringValue("LBYR")> AVI_FORMAT_LBYR = &H5259424C <StringValue("LCMW")> AVI_FORMAT_LCMW = &H574D434C <StringValue("LCW2")> AVI_FORMAT_LCW2 = &H3257434C <StringValue("LEAD")> AVI_FORMAT_LEAD = &H4441454C <StringValue("LGRY")> AVI_FORMAT_LGRY = &H5952474C <StringValue("LJ11")> AVI_FORMAT_LJ11 = &H31314A4C <StringValue("LJ22")> AVI_FORMAT_LJ22 = &H32324A4C <StringValue("LJ2K")> AVI_FORMAT_LJ2K = &H4B324A4C <StringValue("LJ44")> AVI_FORMAT_LJ44 = &H34344A4C <StringValue("LJPG")> AVI_FORMAT_LJPG = &H47504A4C <StringValue("LMP2")> AVI_FORMAT_LMP2 = &H32504D4C <StringValue("LMP4")> AVI_FORMAT_LMP4 = &H34504D4C <StringValue("LSVC")> AVI_FORMAT_LSVC = &H4356534C <StringValue("LSVM")> AVI_FORMAT_LSVM = &H4D56534C <StringValue("LSVX")> AVI_FORMAT_LSVX = &H5856534C <StringValue("LZO1")> AVI_FORMAT_LZO1 = &H314F5A4C <StringValue("M261")> AVI_FORMAT_M261 = &H3136324D <StringValue("M263")> AVI_FORMAT_M263 = &H3336324D <StringValue("M4CC")> AVI_FORMAT_M4CC = &H4343344D <StringValue("M4S2")> AVI_FORMAT_M4S2 = &H3253344D <StringValue("MC12")> AVI_FORMAT_MC12 = &H3231434D <StringValue("MCAM")> AVI_FORMAT_MCAM = &H4D41434D <StringValue("MJ2C")> AVI_FORMAT_MJ2C = &H43324A4D <StringValue("MJPG")> AVI_FORMAT_MJPG = &H47504A4D <StringValue("MMES")> AVI_FORMAT_MMES = &H53454D4D <StringValue("MP2A")> AVI_FORMAT_MP2A = &H4132504D <StringValue("MP2T")> AVI_FORMAT_MP2T = &H5432504D <StringValue("MP2V")> AVI_FORMAT_MP2V = &H5632504D <StringValue("MP42")> AVI_FORMAT_MP42 = &H3234504D <StringValue("MP43")> AVI_FORMAT_MP43 = &H3334504D <StringValue("MP4A")> AVI_FORMAT_MP4A = &H4134504D <StringValue("MP4S")> AVI_FORMAT_MP4S = &H5334504D <StringValue("MP4T")> AVI_FORMAT_MP4T = &H5434504D <StringValue("MP4V")> AVI_FORMAT_MP4V = &H5634504D <StringValue("MPEG")> AVI_FORMAT_MPEG = &H4745504D <StringValue("MPG4")> AVI_FORMAT_MPG4 = &H3447504D <StringValue("MPGI")> AVI_FORMAT_MPGI = &H4947504D <StringValue("MR16")> AVI_FORMAT_MR16 = &H3631524D <StringValue("MRCA")> AVI_FORMAT_MRCA = &H4143524D <StringValue("MRLE")> AVI_FORMAT_MRLE = &H454C524D <StringValue("MSVC")> AVI_FORMAT_MSVC = &H4356534D <StringValue("MSZH")> AVI_FORMAT_MSZH = &H485A534D <StringValue("MTX1")> AVI_FORMAT_MTX1 = &H3158544D <StringValue("MTX2")> AVI_FORMAT_MTX2 = &H3258544D <StringValue("MTX3")> AVI_FORMAT_MTX3 = &H3358544D <StringValue("MTX4")> AVI_FORMAT_MTX4 = &H3458544D <StringValue("MTX5")> AVI_FORMAT_MTX5 = &H3558544D <StringValue("MTX6")> AVI_FORMAT_MTX6 = &H3658544D <StringValue("MTX7")> AVI_FORMAT_MTX7 = &H3758544D <StringValue("MTX8")> AVI_FORMAT_MTX8 = &H3858544D <StringValue("MTX9")> AVI_FORMAT_MTX9 = &H3958544D <StringValue("MVI1")> AVI_FORMAT_MVI1 = &H3149564D <StringValue("MVI2")> AVI_FORMAT_MVI2 = &H3249564D <StringValue("MWV1")> AVI_FORMAT_MWV1 = &H3157564D <StringValue("NAVI")> AVI_FORMAT_NAVI = &H4956414E <StringValue("nAVI")> AVI_FORMAT_nAVI_LOWER = &H4956416E <StringValue("NDSC")> AVI_FORMAT_NDSC = &H4353444E <StringValue("NDSH")> AVI_FORMAT_NDSH = &H4853444E <StringValue("NDSM")> AVI_FORMAT_NDSM = &H4D53444E <StringValue("NDSP")> AVI_FORMAT_NDSP = &H5053444E <StringValue("NDSS")> AVI_FORMAT_NDSS = &H5353444E <StringValue("NDXC")> AVI_FORMAT_NDXC = &H4358444E <StringValue("NDXH")> AVI_FORMAT_NDXH = &H4858444E <StringValue("NDXM")> AVI_FORMAT_NDXM = &H4D58444E <StringValue("NDXP")> AVI_FORMAT_NDXP = &H5058444E <StringValue("NDXS")> AVI_FORMAT_NDXS = &H5358444E <StringValue("NHVU")> AVI_FORMAT_NHVU = &H5556484E <StringValue("NTN1")> AVI_FORMAT_NTN1 = &H314E544E <StringValue("NTN2")> AVI_FORMAT_NTN2 = &H324E544E <StringValue("NVDS")> AVI_FORMAT_NVDS = &H5344564E <StringValue("NVHS")> AVI_FORMAT_NVHS = &H5348564E <StringValue("NVS0")> AVI_FORMAT_NVS0 = &H3053564E <StringValue("NVS1")> AVI_FORMAT_NVS1 = &H3153564E <StringValue("NVS2")> AVI_FORMAT_NVS2 = &H3253564E <StringValue("NVS3")> AVI_FORMAT_NVS3 = &H3353564E <StringValue("NVS4")> AVI_FORMAT_NVS4 = &H3453564E <StringValue("NVS5")> AVI_FORMAT_NVS5 = &H3553564E <StringValue("NVT0")> AVI_FORMAT_NVT0 = &H3054564E <StringValue("NVT1")> AVI_FORMAT_NVT1 = &H3154564E <StringValue("NVT2")> AVI_FORMAT_NVT2 = &H3254564E <StringValue("NVT3")> AVI_FORMAT_NVT3 = &H3354564E <StringValue("NVT4")> AVI_FORMAT_NVT4 = &H3454564E <StringValue("NVT5")> AVI_FORMAT_NVT5 = &H3554564E <StringValue("PDVC")> AVI_FORMAT_PDVC = &H43564450 <StringValue("PGVV")> AVI_FORMAT_PGVV = &H56564750 <StringValue("PHMO")> AVI_FORMAT_PHMO = &H4F4D4850 <StringValue("PIM1")> AVI_FORMAT_PIM1 = &H314D4950 <StringValue("PIM2")> AVI_FORMAT_PIM2 = &H324D4950 <StringValue("PIMJ")> AVI_FORMAT_PIMJ = &H4A4D4950 <StringValue("PIXL")> AVI_FORMAT_PIXL = &H4C584950 <StringValue("PJPG")> AVI_FORMAT_PJPG = &H47504A50 <StringValue("PVEZ")> AVI_FORMAT_PVEZ = &H5A455650 <StringValue("PVMM")> AVI_FORMAT_PVMM = &H4D4D5650 <StringValue("PVW2")> AVI_FORMAT_PVW2 = &H32575650 <StringValue("qpeg")> AVI_FORMAT_qpeg = &H67657071 <StringValue("qpeq")> AVI_FORMAT_qpeq = &H71657071 <StringValue("RGBT")> AVI_FORMAT_RGBT = &H54424752 <StringValue("RLE ")> AVI_FORMAT_RLE = &H20454C52 <StringValue("RLE4")> AVI_FORMAT_RLE4 = &H34454C52 <StringValue("RLE8")> AVI_FORMAT_RLE8 = &H38454C52 <StringValue("RMP4")> AVI_FORMAT_RMP4 = &H34504D52 <StringValue("RPZA")> AVI_FORMAT_RPZA = &H415A5052 <StringValue("RT21")> AVI_FORMAT_RT21 = &H31325452 <StringValue("RV10")> AVI_FORMAT_RV10 = &H30315652 <StringValue("RV13")> AVI_FORMAT_RV13 = &H33315652 <StringValue("RV20")> AVI_FORMAT_RV20 = &H30325652 <StringValue("RV30")> AVI_FORMAT_RV30 = &H30335652 <StringValue("RV40")> AVI_FORMAT_RV40 = &H30345652 <StringValue("RVX ")> AVI_FORMAT_RVX = &H20585652 <StringValue("S422")> AVI_FORMAT_S422 = &H32323453 <StringValue("SAN3")> AVI_FORMAT_SAN3 = &H334E4153 <StringValue("SDCC")> AVI_FORMAT_SDCC = &H43434453 <StringValue("SEDG")> AVI_FORMAT_SEDG = &H47444553 <StringValue("SFMC")> AVI_FORMAT_SFMC = &H434D4653 <StringValue("SMP4")> AVI_FORMAT_SMP4 = &H34504D53 <StringValue("SMSC")> AVI_FORMAT_SMSC = &H43534D53 <StringValue("SMSD")> AVI_FORMAT_SMSD = &H44534D53 <StringValue("SMSV")> AVI_FORMAT_SMSV = &H56534D53 <StringValue("SP40")> AVI_FORMAT_SP40 = &H30345053 <StringValue("SP44")> AVI_FORMAT_SP44 = &H34345053 <StringValue("SP45")> AVI_FORMAT_SP54 = &H34355053 <StringValue("SPIG")> AVI_FORMAT_SPIG = &H47495053 <StringValue("SPLC")> AVI_FORMAT_SPLC = &H434C5053 <StringValue("SQZ2")> AVI_FORMAT_SQZ2 = &H325A5153 <StringValue("STVA")> AVI_FORMAT_STVA = &H41565453 <StringValue("STVB")> AVI_FORMAT_STVB = &H42565453 <StringValue("STVC")> AVI_FORMAT_STVC = &H43565453 <StringValue("STVX")> AVI_FORMAT_STVX = &H58565453 <StringValue("STVY")> AVI_FORMAT_STVY = &H59565453 <StringValue("SV10")> AVI_FORMAT_SV10 = &H30315653 <StringValue("SVQ1")> AVI_FORMAT_SVQ1 = &H31515653 <StringValue("SVQ3")> AVI_FORMAT_SVQ3 = &H33515653 '<StringValue("")> AVI_FORMAT_ = &H <StringValue("TLMS")> AVI_FORMAT_TLMS = &H534D4C54 <StringValue("TLST")> AVI_FORMAT_TLST = &H54534C54 <StringValue("TM20")> AVI_FORMAT_TM20 = &H30324D54 <StringValue("TMIC")> AVI_FORMAT_TMIC = &H43494D54 <StringValue("tmot")> AVI_FORMAT_tmot = &H746F6D74 <StringValue("TR20")> AVI_FORMAT_TR20 = &H30325254 <StringValue("ULTI")> AVI_FORMAT_ULTI = &H49544C55 <StringValue("UYVY")> AVI_FORMAT_UYVY = &H59565955 <StringValue("V422")> AVI_FORMAT_V422 = &H32323456 <StringValue("V655")> AVI_FORMAT_V655 = &H35353656 <StringValue("VCR1")> AVI_FORMAT_VCR1 = &H31524356 <StringValue("VCR2")> AVI_FORMAT_VCR2 = &H32524356 <StringValue("VCR3")> AVI_FORMAT_VCR3 = &H33524356 <StringValue("VCR4")> AVI_FORMAT_VCR4 = &H34524356 <StringValue("VCR5")> AVI_FORMAT_VCR5 = &H35524356 <StringValue("VCR6")> AVI_FORMAT_VCR6 = &H36524356 <StringValue("VCR7")> AVI_FORMAT_VCR7 = &H37524356 <StringValue("VCR8")> AVI_FORMAT_VCR8 = &H38524356 <StringValue("VCR9")> AVI_FORMAT_VCR9 = &H39524356 <StringValue("VDCT")> AVI_FORMAT_VDCT = &H54434456 <StringValue("VIDS")> AVI_FORMAT_VIDS = &H53444956 <StringValue("VIVO")> AVI_FORMAT_VIVO = &H4F564956 <StringValue("vivo")> AVI_FORMAT_vivo_LOWER = &H6F766976 <StringValue("VIXL")> AVI_FORMAT_VIXL = &H4C584956 <StringValue("VLV1")> AVI_FORMAT_VLV1 = &H31564C56 <StringValue("WBVC")> AVI_FORMAT_WBVC = &H43564257 <StringValue("WHAM")> AVI_FORMAT_WHAM = &H4D414857 <StringValue("X263")> AVI_FORMAT_X263 = &H33363258 <StringValue("XLV0")> AVI_FORMAT_XLV0 = &H30564C58 <StringValue("XVID")> AVI_FORMAT_XVID = &H44495658 <StringValue("Y211")> AVI_FORMAT_Y211 = &H30564C58 <StringValue("Y411")> AVI_FORMAT_Y411 = &H31313459 <StringValue("Y41B")> AVI_FORMAT_Y41B = &H42313459 <StringValue("Y41P")> AVI_FORMAT_Y41P = &H50313459 <StringValue("Y41T")> AVI_FORMAT_Y41T = &H54313459 <StringValue("Y42B")> AVI_FORMAT_Y42B = &H42323459 <StringValue("Y42T")> AVI_FORMAT_Y42T = &H54323459 <StringValue("YC12")> AVI_FORMAT_YC12 = &H32314359 <StringValue("YUV8")> AVI_FORMAT_YUV8 = &H38565559 <StringValue("YUV9")> AVI_FORMAT_YUV9 = &H39565559 <StringValue("YUY2")> AVI_FORMAT_YUY2 = &H32595559 <StringValue("YUYV")> AVI_FORMAT_YUYV = &H56595559 <StringValue("YV12")> AVI_FORMAT_YV12 = &H32315659 <StringValue("YVU9")> AVI_FORMAT_YVU9 = &H39555659 <StringValue("YVYU")> AVI_FORMAT_YVYU = &H55595659 <StringValue("ZPEG")> AVI_FORMAT_ZPEG = &H4745505A End Enum Public Enum ChannelStruct As UInt32 FrontLeft = &H1 FrontRight = &H2 FrontCenter = &H4 LFE = &H8 RearLeft = &H10 RearRight = &H20 FrontCenterLeft = &H40 FrontCenterRight = &H80 RearCenter = &H100 SideLeft = &H200 SideRight = &H400 TopCenter = &H800 TopFrontLeft = &H1000 TopFrontCenter = &H2000 TopFrontRight = &H4000 TopRearLeft = &H8000 TopRearCenter = &H10000 TopRearRight = &H20000 End Enum Public Structure DTSInfo Public uSYNC As UInt32 Public bFTYPE As Boolean Public iSHORT As UInt16 Public bCPF As Boolean Public iNBLKS As UInt16 Public iFSIZE As UInt16 Public iAMODE As UInt16 Public iSFREQ As UInt16 Public iRATE As UInt16 Public bFixedBit As Boolean Public bDYNF As Boolean Public bTIMEF As Boolean Public bAUXF As Boolean Public bHDCD As Boolean Public iEXT_AUDIO_ID As UInt16 Public bEXT_AUDIO As Boolean Public bASPF As Boolean Public iLFF As UInt16 Public bHFLAG As Boolean Public iHCRC As UInt16 Public bFILTS As Boolean Public iVERNUM As UInt16 Public iCHIST As UInt16 Public iPCMR As UInt16 Public bSUMF As Boolean Public bSUMS As Boolean Public iDIALNORM As UInt16 Public iDNG As Integer End Structure Private wfEX As WAVEFORMATEXTENSIBLE Private dtsEX As DTSInfo Private aviMain As AVIMAINHEADER Private aviStreams As List(Of AVISTREAMHEADER) Private aviIDVX As IDVX_INFO Private aviINDEX As AVIOLDINDEX Private aviBMP As List(Of BITMAPINFO) Private aviWAV As List(Of WAVEFORMATEX) Private aviINFO As Dictionary(Of String, String) Public ReadOnly Property WAVData As WAVEFORMATEXTENSIBLE Get Return wfEX End Get End Property Public ReadOnly Property DTSData As DTSInfo Get Return dtsEX End Get End Property Public ReadOnly Property AVIMainData As AVIMAINHEADER Get Return aviMain End Get End Property Public ReadOnly Property AVIStreamCount As Integer Get If aviStreams Is Nothing Then Return 0 Return aviStreams.Count End Get End Property Public ReadOnly Property AVIStreamData(Index As Integer) As AVISTREAMHEADER Get If aviStreams Is Nothing Then Return Nothing Return aviStreams(Index) End Get End Property Public ReadOnly Property AVIDIVXData As IDVX_INFO Get Return aviIDVX End Get End Property Public ReadOnly Property AVIINDEXData As AVIOLDINDEX Get Return aviINDEX End Get End Property Public ReadOnly Property AVIVideoCount As Integer Get If aviBMP Is Nothing Then Return 0 Return aviBMP.Count End Get End Property Public ReadOnly Property AVIVideoData(Index As Integer) As BITMAPINFO Get If aviBMP Is Nothing Then Return Nothing Return aviBMP(Index) End Get End Property Public ReadOnly Property AVIAudioCount As Integer Get If aviWAV Is Nothing Then Return 0 Return aviWAV.Count End Get End Property Public ReadOnly Property AVIAudioData(Index As Integer) As WAVEFORMATEX Get If aviWAV Is Nothing Then Return Nothing Return aviWAV(Index) End Get End Property Public ReadOnly Property AVIINFOData As Dictionary(Of String, String) Get Return aviINFO End Get End Property Public Sub New(FilePath As String) bValid = False If String.IsNullOrEmpty(FilePath) Then Return If Not io.file.exists(FilePath) Then Return Using ioFile As New IO.BinaryReader(New IO.FileStream(FilePath, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)) Dim mChunk As New Chunk mChunk.Header.ChunkID = ioFile.ReadChars(4) If Not mChunk.Header.ChunkID = "RIFF" Then Return mChunk.Header.ChunkSize = ioFile.ReadUInt32 mChunk.Header.Format = ioFile.ReadChars(4) Select Case mChunk.Header.Format Case "WAVE" 'WAVEFORMAT Do While ioFile.BaseStream.Position < mChunk.Header.ChunkSize Dim wavChunk As New Chunk wavChunk.Header.ChunkID = ioFile.ReadChars(4) wavChunk.Header.ChunkSize = ioFile.ReadUInt32 wavChunk.Data = ioFile.ReadBytes(wavChunk.Header.ChunkSize) Using ioData As New IO.BinaryReader(New IO.MemoryStream(wavChunk.Data)) Select Case wavChunk.Header.ChunkID Case "fmt " wfEX = New WAVEFORMATEXTENSIBLE Select Case wavChunk.Header.ChunkSize Case 16 'WAVEFORMAT wfEX.Format.Format.wFormatTag = ioData.ReadUInt16 wfEX.Format.Format.nChannels = ioData.ReadUInt16 wfEX.Format.Format.nSamplesPerSec = ioData.ReadUInt32 wfEX.Format.Format.nAvgBytesPerSec = ioData.ReadUInt32 wfEX.Format.Format.nBlockAlign = ioData.ReadUInt16 bWAV = True bValid = True Case 18, 20 ' WAVEFORMATEX wfEX.Format.Format.wFormatTag = ioData.ReadUInt16 wfEX.Format.Format.nChannels = ioData.ReadUInt16 wfEX.Format.Format.nSamplesPerSec = ioData.ReadUInt32 wfEX.Format.Format.nAvgBytesPerSec = ioData.ReadUInt32 wfEX.Format.Format.nBlockAlign = ioData.ReadUInt16 wfEX.Format.wBitsPerSample = ioData.ReadUInt16 wfEX.Format.cbSize = ioData.ReadUInt16 bWAV = True bValid = True Case 40 'WAVEFORMATEXTENSIBLE wfEX.Format.Format.wFormatTag = ioData.ReadUInt16 wfEX.Format.Format.nChannels = ioData.ReadUInt16 wfEX.Format.Format.nSamplesPerSec = ioData.ReadUInt32 wfEX.Format.Format.nAvgBytesPerSec = ioData.ReadUInt32 wfEX.Format.Format.nBlockAlign = ioData.ReadUInt16 wfEX.Format.wBitsPerSample = ioData.ReadUInt16 wfEX.Format.cbSize = ioData.ReadUInt16 wfEX.Samples.wValidBitsPerSample = ioData.ReadUInt16 wfEX.dwChannelMask = ioData.ReadUInt32 wfEX.SubFormat = New Guid(ioData.ReadBytes(16)) bWAV = True bValid = True Case Else Debug.Print("Unkown Size " & wavChunk.Header.ChunkSize) Return End Select Case "data" Dim firstFour As Byte() = ioData.ReadBytes(4) Do While firstFour(0) = 0 ioData.BaseStream.Position -= 3 firstFour = ioData.ReadBytes(4) Loop Select Case BitConverter.ToString(firstFour) Case "7F-FE-80-01" 'Raw Big Endian Case "FE-7F-01-80" 'Raw Little Endian Case "1F-FF-E8-00" '14-bit Big Endian Case "FF-1F-00-E8" '14-bit Little Endian ioData.BaseStream.Position -= 4 Dim bDTSa As Byte() = BytesTo14BitL(ioData.ReadBytes(24)) If bDTSa(0) = &H7F And bDTSa(1) = &HFE And bDTSa(2) = &H80 And bDTSa(3) = &H1 Then bDTS = True sizeLeft = 8 currentByte = bDTSa(0) dtsEX.uSYNC = ReadBits(bDTSa, 32) dtsEX.bFTYPE = ReadBits(bDTSa, 1) = 1 dtsEX.iSHORT = ReadBits(bDTSa, 5) dtsEX.bCPF = ReadBits(bDTSa, 1) = 1 dtsEX.iNBLKS = ReadBits(bDTSa, 7) dtsEX.iFSIZE = ReadBits(bDTSa, 14) dtsEX.iAMODE = ReadBits(bDTSa, 6) dtsEX.iSFREQ = ReadBits(bDTSa, 4) dtsEX.iRATE = ReadBits(bDTSa, 5) dtsEX.bFixedBit = ReadBits(bDTSa, 1) = 1 dtsEX.bDYNF = ReadBits(bDTSa, 1) = 1 dtsEX.bTIMEF = ReadBits(bDTSa, 1) = 1 dtsEX.bAUXF = ReadBits(bDTSa, 1) = 1 dtsEX.bHDCD = ReadBits(bDTSa, 1) = 1 dtsEX.iEXT_AUDIO_ID = ReadBits(bDTSa, 3) dtsEX.bEXT_AUDIO = ReadBits(bDTSa, 1) = 1 dtsEX.bASPF = ReadBits(bDTSa, 1) = 1 dtsEX.iLFF = ReadBits(bDTSa, 2) dtsEX.bHFLAG = ReadBits(bDTSa, 1) = 1 If dtsEX.bCPF Then dtsEX.iHCRC = ReadBits(bDTSa, 16) dtsEX.bFILTS = ReadBits(bDTSa, 1) dtsEX.iVERNUM = ReadBits(bDTSa, 4) dtsEX.iCHIST = ReadBits(bDTSa, 2) dtsEX.iPCMR = ReadBits(bDTSa, 3) dtsEX.bSUMF = ReadBits(bDTSa, 1) = 1 dtsEX.bSUMS = ReadBits(bDTSa, 1) = 1 dtsEX.iDIALNORM = ReadBits(bDTSa, 4) Select Case dtsEX.iVERNUM Case 6 dtsEX.iDNG = -1 * (16 + DTSData.iDIALNORM) Case 7 dtsEX.iDNG = -1 * DTSData.iDIALNORM Case Else dtsEX.iDNG = 0 dtsEX.iDIALNORM = 0 End Select Else bDTS = False Return End If Case Else ioData.BaseStream.Position -= 4 Dim bDTSa As Byte() = BytesTo14BitL(ioData.ReadBytes(16)) Debug.Print("Unknown Data ID: " & Hex(bDTSa(0)) & Hex(bDTSa(1)) & Hex(bDTSa(2)) & Hex(bDTSa(3))) End Select Exit Do Case Else Debug.Print("Unknown Chunk ID: " & wavChunk.Header.ChunkID) End Select End Using Loop Case "AVI " 'AVIFORMAT bAVI = True Do While ioFile.BaseStream.Position < mChunk.Header.ChunkSize Dim aviChunk As New Chunk aviChunk.Header.ChunkID = ioFile.ReadChars(4) aviChunk.Header.ChunkSize = ioFile.ReadUInt32 Dim aviOffset As Long = ioFile.BaseStream.Position 'aviChunk.Data = ioFile.ReadBytes(aviChunk.Header.ChunkSize) 'Using ioData As New IO.BinaryReader(New IO.MemoryStream(aviChunk.Data)) Select Case aviChunk.Header.ChunkID Case "LIST" aviChunk.Header.Format = ioFile.ReadChars(4) Select Case aviChunk.Header.Format Case "hdrl" Do While ioFile.BaseStream.Position - aviOffset < aviChunk.Header.ChunkSize Dim mainChunk As New Chunk mainChunk.Header.ChunkID = ioFile.ReadChars(4) mainChunk.Header.ChunkSize = ioFile.ReadUInt32 mainChunk.Data = ioFile.ReadBytes(mainChunk.Header.ChunkSize) Using ioMain As New IO.BinaryReader(New IO.MemoryStream(mainChunk.Data)) Select Case mainChunk.Header.ChunkID Case "avih" aviMain = New AVIMAINHEADER aviMain.fcc = mainChunk.Header.ChunkID aviMain.cb = mainChunk.Header.ChunkSize aviMain.dwMicroSecPerFrame = ioMain.ReadUInt32 aviMain.dwMaxBytesPerSec = ioMain.ReadUInt32 aviMain.dwPaddingGranularity = ioMain.ReadUInt32 aviMain.dwFlags = ioMain.ReadUInt32 aviMain.dwTotalFrames = ioMain.ReadUInt32 aviMain.dwInitialFrames = ioMain.ReadUInt32 aviMain.dwStreams = ioMain.ReadUInt32 aviMain.dwSuggestedBufferSize = ioMain.ReadUInt32 aviMain.dwWidth = ioMain.ReadUInt32 aviMain.dwHeight = ioMain.ReadUInt32 aviMain.dwReserved0 = ioMain.ReadUInt32 aviMain.dwReserved1 = ioMain.ReadUInt32 aviMain.dwReserved2 = ioMain.ReadUInt32 aviMain.dwReserved3 = ioMain.ReadUInt32 bValid = True Case "LIST" mainChunk.Header.Format = ioMain.ReadChars(4) Select Case mainChunk.Header.Format Case "strl" Do While ioMain.BaseStream.Position < mainChunk.Header.ChunkSize Dim streamChunk As New Chunk streamChunk.Header.ChunkID = ioMain.ReadChars(4) streamChunk.Header.ChunkSize = ioMain.ReadUInt32 streamChunk.Data = ioMain.ReadBytes(streamChunk.Header.ChunkSize) Using ioStream As New IO.BinaryReader(New IO.MemoryStream(streamChunk.Data)) Select Case streamChunk.Header.ChunkID Case "strh" streamChunk.Header.Format = ioStream.ReadChars(4) Dim streamHeader As New AVISTREAMHEADER streamHeader.fcc = streamChunk.Header.ChunkID streamHeader.cb = streamChunk.Header.ChunkSize streamHeader.fccType = streamChunk.Header.Format streamHeader.fccHandler = ioStream.ReadChars(4) streamHeader.dwFlags = ioStream.ReadUInt32 streamHeader.wPriority = ioStream.ReadUInt16 streamHeader.wLanguage = ioStream.ReadUInt16 streamHeader.dwInitialFrames = ioStream.ReadUInt32 streamHeader.dwScale = ioStream.ReadUInt32 streamHeader.dwRate = ioStream.ReadUInt32 streamHeader.dwStart = ioStream.ReadUInt32 streamHeader.dwLength = ioStream.ReadUInt32 streamHeader.dwSuggestedBufferSize = ioStream.ReadUInt32 streamHeader.dwQuality = ioStream.ReadUInt32 streamHeader.dwSampleSize = ioStream.ReadUInt32 streamHeader.rcFrame.top = ioStream.ReadInt16 streamHeader.rcFrame.left = ioStream.ReadInt16 streamHeader.rcFrame.right = ioStream.ReadInt16 streamHeader.rcFrame.bottom = ioStream.ReadInt16 If aviStreams Is Nothing Then aviStreams = New List(Of AVISTREAMHEADER) aviStreams.Add(streamHeader) Select Case streamHeader.fccType Case "vids" Dim vidsChunk As New Chunk vidsChunk.Header.ChunkID = ioMain.ReadChars(4) vidsChunk.Header.ChunkSize = ioMain.ReadUInt32 vidsChunk.Data = ioMain.ReadBytes(vidsChunk.Header.ChunkSize) Using ioVids As New IO.BinaryReader(New IO.MemoryStream(vidsChunk.Data)) Dim bmpInfo As New BITMAPINFO bmpInfo.bmiHeader.biSize = ioVids.ReadUInt32 bmpInfo.bmiHeader.biWidth = ioVids.ReadUInt32 bmpInfo.bmiHeader.biHeight = ioVids.ReadUInt32 bmpInfo.bmiHeader.biPlanes = ioVids.ReadUInt16 bmpInfo.bmiHeader.biBitCount = ioVids.ReadUInt16 bmpInfo.bmiHeader.biCompression = ioVids.ReadUInt32 bmpInfo.bmiHeader.biSizeImage = ioVids.ReadUInt32 bmpInfo.bmiHeader.biXPelsPerMeter = ioVids.ReadUInt32 bmpInfo.bmiHeader.biYPelsPerMeter = ioVids.ReadUInt32 bmpInfo.bmiHeader.biClrUsed = ioVids.ReadUInt32 bmpInfo.bmiHeader.biClrImportant = ioVids.ReadUInt32 Select Case bmpInfo.bmiHeader.biBitCount Case 0 'specified or implied Erase bmpInfo.bmiColors Case 1 'Monochrome ReDim bmpInfo.bmiColors(1) bmpInfo.bmiColors(0) = New RGBQUAD(ioVids.ReadBytes(4)) bmpInfo.bmiColors(1) = New RGBQUAD(ioVids.ReadBytes(4)) Case 4 '16 Color If bmpInfo.bmiHeader.biClrUsed = 0 Then ReDim bmpInfo.bmiColors(15) Else ReDim bmpInfo.bmiColors(bmpInfo.bmiHeader.biClrUsed - 1) End If For I As Integer = 0 To bmpInfo.bmiColors.Length - 1 bmpInfo.bmiColors(I) = New RGBQUAD(ioVids.ReadBytes(4)) Next Case 8 '256 Color If bmpInfo.bmiHeader.biClrUsed = 0 Then ReDim bmpInfo.bmiColors(255) Else ReDim bmpInfo.bmiColors(bmpInfo.bmiHeader.biClrUsed - 1) End If For I As Integer = 0 To bmpInfo.bmiColors.Length - 1 bmpInfo.bmiColors(I) = New RGBQUAD(ioVids.ReadBytes(4)) Next Case 16 '16-bit color If bmpInfo.bmiHeader.biClrUsed = 0 Then Erase bmpInfo.bmiColors Else ReDim bmpInfo.bmiColors(bmpInfo.bmiHeader.biClrUsed - 1) For I As Integer = 0 To bmpInfo.bmiColors.Length - 1 bmpInfo.bmiColors(I) = New RGBQUAD(ioVids.ReadBytes(4)) Next End If Case 24 Erase bmpInfo.bmiColors Case 32 '32-bit color If bmpInfo.bmiHeader.biClrUsed = 0 Then Erase bmpInfo.bmiColors Else ReDim bmpInfo.bmiColors(bmpInfo.bmiHeader.biClrUsed - 1) For I As Integer = 0 To bmpInfo.bmiColors.Length - 1 bmpInfo.bmiColors(I) = New RGBQUAD(ioVids.ReadBytes(4)) Next End If End Select If aviBMP Is Nothing Then aviBMP = New List(Of BITMAPINFO) aviBMP.Add(bmpInfo) End Using Case "auds" Dim audsChunk As New Chunk audsChunk.Header.ChunkID = ioMain.ReadChars(4) audsChunk.Header.ChunkSize = ioMain.ReadUInt32 audsChunk.Data = ioMain.ReadBytes(audsChunk.Header.ChunkSize) Using ioAuds As New IO.BinaryReader(New IO.MemoryStream(audsChunk.Data)) Dim wavInfo As New WAVEFORMATEX wavInfo.Format.wFormatTag = ioAuds.ReadUInt16 wavInfo.Format.nChannels = ioAuds.ReadUInt16 wavInfo.Format.nSamplesPerSec = ioAuds.ReadUInt32 wavInfo.Format.nAvgBytesPerSec = ioAuds.ReadUInt32 wavInfo.Format.nBlockAlign = ioAuds.ReadUInt16 wavInfo.wBitsPerSample = ioAuds.ReadUInt16 If Not ioAuds.BaseStream.Position = ioAuds.BaseStream.Length Then wavInfo.cbSize = ioAuds.ReadUInt16 End If If aviWAV Is Nothing Then aviWAV = New List(Of WAVEFORMATEX) aviWAV.Add(wavInfo) End Using Case "mids" Dim midsChunk As New Chunk midsChunk.Header.ChunkID = ioMain.ReadChars(4) midsChunk.Header.ChunkSize = ioMain.ReadUInt32 ioMain.BaseStream.Position += midsChunk.Header.ChunkSize Case "txts" Dim txtsChunk As New Chunk txtsChunk.Header.ChunkID = ioMain.ReadChars(4) txtsChunk.Header.ChunkSize = ioMain.ReadUInt32 ioMain.BaseStream.Position += txtsChunk.Header.ChunkSize Case "JUNK" 'Junk Data Dim junkChunk As New Chunk junkChunk.Header.ChunkID = ioMain.ReadChars(4) junkChunk.Header.ChunkSize = ioMain.ReadUInt32 ioMain.BaseStream.Position += junkChunk.Header.ChunkSize Case Else Debug.Print("Unknown AVI Stream Chunk ID: " & streamHeader.fccType) Dim unknownChunk As New Chunk unknownChunk.Header.ChunkID = ioMain.ReadChars(4) unknownChunk.Header.ChunkSize = ioMain.ReadUInt32 ioMain.BaseStream.Position += unknownChunk.Header.ChunkSize End Select Case "strn" Dim aStream = aviStreams(aviStreams.Count - 1) If Array.IndexOf(Of Byte)(streamChunk.Data, 0) = -1 Then aStream.StreamName = GetString(streamChunk.Data, 0, streamChunk.Data.Length) Else aStream.StreamName = GetString(streamChunk.Data, 0, Array.IndexOf(Of Byte)(streamChunk.Data, 0)) End If aviStreams(aviStreams.Count - 1) = aStream If ioMain.PeekChar = 0 Then ioMain.ReadByte() Case Else If ioMain.PeekChar = 0 Then ioMain.ReadByte() End Select End Using Loop Case "odml" Do While ioMain.BaseStream.Position < mainChunk.Header.ChunkSize Dim dmlChunk As New Chunk dmlChunk.Header.ChunkID = ioMain.ReadChars(4) dmlChunk.Header.ChunkSize = ioMain.ReadUInt32 dmlChunk.Data = ioMain.ReadBytes(dmlChunk.Header.ChunkSize) Using ioDML As New IO.BinaryReader(New IO.MemoryStream(dmlChunk.Data)) Select Case dmlChunk.Header.ChunkID Case "dmlh" Dim Frames As UInt32 = ioDML.ReadUInt32 Debug.Print("DML Frame Count: " & Frames) Case "JUNK" 'Junk Data Case Else Debug.Print("Unknown Open DML Header Chunk ID: " & dmlChunk.Header.ChunkID) End Select End Using Loop End Select Case "JUNK" 'Junk Data Case Else Debug.Print("Unknown AVI Header Chunk ID: " & mainChunk.Header.ChunkID) End Select End Using Loop Case "INFO" If aviINFO Is Nothing Then aviINFO = New Dictionary(Of String, String) Do While ioFile.BaseStream.Position - aviOffset < aviChunk.Header.ChunkSize Dim infoChunk As New Chunk infoChunk.Header.ChunkID = ioFile.ReadChars(4) infoChunk.Header.ChunkSize = ioFile.ReadUInt32 If infoChunk.Header.ChunkSize = 0 Then Continue Do infoChunk.Header.Format = ioFile.ReadChars(infoChunk.Header.ChunkSize) If infoChunk.Header.Format.Length = 0 Then Continue Do If infoChunk.Header.Format.Substring(infoChunk.Header.Format.Length - 1, 1) = vbNullChar Then infoChunk.Header.Format = infoChunk.Header.Format.Substring(0, infoChunk.Header.Format.Length - 1) aviINFO.Add(infoChunk.Header.ChunkID, infoChunk.Header.Format) 'IS THERE JUST ONE EXTRA BYTE AT THE END OF THIS CHUNK? If ioFile.BaseStream.Position - aviOffset = aviChunk.Header.ChunkSize - 1 Then ioFile.ReadByte() 'SOME SPECIFIC REQUIREMENT FOR READING ANOTHER BYTE EXISTS HERE ' WHAT IS IT? ' WHY DOES IT EXIST? ' DOES IT MEAN SOME ADDITIONAL DATA MAY EXIST OR IS IT ALWAYS NULL? If ioFile.PeekChar = 0 Then 'Stop ioFile.ReadByte() Debug.Print("Extra Null Byte at end of this sub-chunk, but not the end of this whole chunk?") End If Loop Case "movi" ioFile.BaseStream.Position += aviChunk.Header.ChunkSize - 4 'Do While ioFile.BaseStream.Position - aviOffset < aviChunk.Header.ChunkSize ' Do Until ioFile.ReadByte > 0 ' If ioFile.BaseStream.Position - aviOffset >= aviChunk.Header.ChunkSize Then Exit Do ' Loop ' If ioFile.BaseStream.Position- aviOffset >= aviChunk.Header.ChunkSize Then Exit Do ' ioFile.BaseStream.Position -= 1 ' Dim moviChunk as new chunk ' moviChunk.Header.ChunkID = ioFile.ReadChars(4) ' moviChunk.Header.ChunkSize = ioFile.ReadUInt32 ' If moviChunk.Header.ChunkSize > ioFile.BaseStream.Length - ioFile.BaseStream.Position Then Exit Do ' moviChunk.Data = ioFile.ReadBytes(moviChunk.Header.ChunkSize) ' 'Dim code As String = moviChunk.Header.ChunkID.Substring(0, 2) ' 'Dim chunk As String = moviChunk.Header.ChunkID.Substring(2, 2) 'Loop Case Else Debug.Print("Unknown AVI Chunk Format: " & aviChunk.Header.Format) End Select Case "idx1" 'Old Index aviINDEX = New AVIOLDINDEX aviINDEX.fcc = aviChunk.Header.ChunkID aviINDEX.cb = aviChunk.Header.ChunkSize Dim items As Integer = aviINDEX.cb / 16 ReDim aviINDEX.aIndex(items - 1) For I As Integer = 0 To items - 1 aviINDEX.aIndex(I).dwChunkID = ioFile.ReadUInt32 aviINDEX.aIndex(I).dwFlags = ioFile.ReadUInt32 aviINDEX.aIndex(I).dwOffset = ioFile.ReadUInt32 aviINDEX.aIndex(I).dwSize = ioFile.ReadUInt32 Next Case "indx" 'OpenDML Index Stop ioFile.BaseStream.Position += aviChunk.Header.ChunkSize Case "JUNK" 'Junk Data ioFile.BaseStream.Position += aviChunk.Header.ChunkSize Case Else Debug.Print("Unknown AVI Chunk ID: " & aviChunk.Header.ChunkID) ioFile.BaseStream.Position += aviChunk.Header.ChunkSize End Select 'End Using Loop Case Else Debug.Print("Unknown RIFF Format: " & mChunk.Header.Format) Return End Select If ioFile.BaseStream.Position < ioFile.BaseStream.Length Then Dim idvxChunk As New Chunk idvxChunk.Header.ChunkID = ioFile.ReadChars(4) idvxChunk.Header.ChunkSize = ioFile.ReadUInt32 idvxChunk.Data = ioFile.ReadBytes(idvxChunk.Header.ChunkSize) Using ioIDVX As New IO.BinaryReader(New IO.MemoryStream(idvxChunk.Data)) If idvxChunk.Header.ChunkID = "IDVX" Then aviIDVX = New IDVX_INFO aviIDVX.Movie = Trim(ioIDVX.ReadChars(32)) aviIDVX.Author = Trim(ioIDVX.ReadChars(28)) aviIDVX.Year = Trim(ioIDVX.ReadChars(4)) aviIDVX.Comment = Trim(ioIDVX.ReadChars(48)) aviIDVX.Genre = Val(Trim(ioIDVX.ReadChars(3))) aviIDVX.Rating = ioIDVX.ReadByte aviIDVX.Extra = ioIDVX.ReadBytes(5) aviIDVX.FileID = ioIDVX.ReadChars(7) If Not aviIDVX.FileID = "DIVXTAG" Then aviIDVX = Nothing End If End Using End If End Using End Sub Public ReadOnly Property IsValid As Boolean Get Return bValid End Get End Property Public ReadOnly Property IsDTS As Boolean Get Return bDTS End Get End Property Public ReadOnly Property IsWAV As Boolean Get Return bWAV End Get End Property Public ReadOnly Property IsAVI As Boolean Get Return bAVI End Get End Property Private Function BytesTo14BitL(inBytes As Byte()) As Byte() Dim bitPairs As Byte() = Nothing Dim j As Integer = 0 For I As Integer = 0 To inBytes.Count - 1 Step 2 Dim b1 As Byte = inBytes(I) Dim b0 As Byte = inBytes(I + 1) ReDim Preserve bitPairs(j + 6) bitPairs(j) = (b0 And &H30) >> 4 bitPairs(j + 1) = (b0 And &HC) >> 2 bitPairs(j + 2) = (b0 And &H3) bitPairs(j + 3) = (b1 And &HC0) >> 6 bitPairs(j + 4) = (b1 And &H30) >> 4 bitPairs(j + 5) = (b1 And &HC) >> 2 bitPairs(j + 6) = (b1 And &H3) j += 7 Next Dim bytes(bitPairs.Count / 4 - 1) As Byte j = 0 For I As Integer = 0 To bitPairs.Count - 1 Step 4 bytes(j) = (bitPairs(I) << 6) + (bitPairs(I + 1) << 4) + (bitPairs(I + 2) << 2) + (bitPairs(I + 3)) j += 1 Next Return bytes End Function Private sizeLeft As Integer Private currentByte As Byte Private idx As Integer Private Function ReadBits(bData As Byte(), size As Integer) As UInt32 Dim ret As UInt32 = 0 If (size <= sizeLeft) Then sizeLeft -= size ret = (currentByte >> sizeLeft) And (Math.Pow(2, size) - 1) Else Dim oSize As Integer = sizeLeft ret = ReadBits(bData, sizeLeft) << size - oSize ret = ret Or ReadBits(bData, size - oSize) End If If sizeLeft = 0 Then idx += 1 currentByte = bData(idx) sizeLeft = 8 End If Return ret End Function #Region "IDisposable Support" Private disposedValue As Boolean Protected Overridable Sub Dispose(disposing As Boolean) If Not Me.disposedValue Then If disposing Then End If End If Me.disposedValue = True End Sub Public Sub Dispose() Implements IDisposable.Dispose ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. Dispose(True) GC.SuppressFinalize(Me) End Sub #End Region End Class
Public MustInherit Class ArquivoRemessa Implements IRemessa Private MeuArquivo As List(Of LinhaArquivo) Public Shared Function GetInstance(ByVal CodigoLayout As Integer) As IRemessa Try Dim Valor As LayoutsDescricao = New LayoutsDescricao(CodigoLayout, String.Empty) Dim Novo As IRemessa = Activator.CreateInstance(Valor.TypeNameSpace, Valor.TypeClassName) Return Novo Catch ex As Exception Throw End Try End Function Protected Function Add(ByVal nTipo As TiposLinha, ByVal nSegmento As TipoSegmento, ByVal nPosicoes As Integer) As LinhaArquivo If MeuArquivo Is Nothing Then MeuArquivo = New List(Of LinhaArquivo) End If Dim NovaLinha As New LinhaArquivo(MeuArquivo.Count + 1, nTipo, nSegmento, nPosicoes) MeuArquivo.Add(NovaLinha) Return NovaLinha End Function Protected Function Item(ByVal Sequencia As Integer) As LinhaArquivo Try Dim pos As Integer = MeuArquivo.FindIndex(Function(i) i.Sequencia = Sequencia) If pos = -1 Then Return Nothing End If Return MeuArquivo(pos) Catch ex As Exception Throw End Try End Function Protected Function GetArquivoMontado(ByVal QuantidadePorArquivo As Integer) As String() Try Dim Arquivo As String = String.Empty Dim aux As String = String.Empty If MeuArquivo IsNot Nothing Then For Each l As LinhaArquivo In MeuArquivo Arquivo &= aux & l.GetLinha aux = vbNewLine Next End If Return {Arquivo} Catch ex As Exception Throw Finally MeuArquivo = Nothing End Try End Function Protected MustOverride Function GetLayoutPorCodigo() As LayoutsDescricao Public MustOverride ReadOnly Property Layout As LayoutsDescricao Implements IRemessa.Layout Public Property BancoCodigo As Integer Implements IRemessa.BancoCodigo Public Property DadosCedente As InfoCedente Implements IRemessa.DadosCedente Public Property DataGeracao As Date Implements IRemessa.DataGeracao Public Property DataGravacao As Date Implements IRemessa.DataGravacao Public Property HoraGeracao As Date Implements IRemessa.HoraGeracao Public Property Itens As List(Of InfoRemessa) Implements IRemessa.Itens Public Property Mensagem01 As String Implements IRemessa.Mensagem01 Public Property Mensagem02 As String Implements IRemessa.Mensagem02 Public Property MensagemEmpresa As String Implements IRemessa.MensagemEmpresa Public Property NSA As String Implements IRemessa.NSA Public MustOverride Function GetArquivoRemessa() As String() Implements IRemessa.GetArquivoRemessa Protected Class LinhaArquivo Protected Friend Sub New(ByVal nSequencia As Integer, ByVal nTipo As TiposLinha, ByVal nSegmento As TipoSegmento, ByVal nPosicoes As Integer) Try SequenciaValue = nSequencia TipoValue = nTipo SegmentoValue = nSegmento PosicoesValue = nPosicoes Lista = New List(Of ItensLinha) Catch ex As Exception Throw End Try End Sub Private SequenciaValue As Integer Public ReadOnly Property Sequencia As Integer Get Return SequenciaValue End Get End Property Private TipoValue As TiposLinha Public ReadOnly Property Tipo As TiposLinha Get Return TipoValue End Get End Property Private SegmentoValue As TipoSegmento Public ReadOnly Property Segmento As TipoSegmento Get Return SegmentoValue End Get End Property Private PosicoesValue As Integer Public ReadOnly Property Posicoes As Integer Get Return PosicoesValue End Get End Property Private Lista As List(Of ItensLinha) Public Sub Add(ByVal Valor As String, ByVal Pos As Integer, ByVal Tam As Integer, Optional ByVal TipVal As TipoFormato = TipoFormato.SpaceDireita) Try Dim Novo As New ItensLinha Novo.Inicio = Pos Novo.Tamanho = Tam Novo.Valor = Valor Novo.Formato = TipVal Lista.Add(Novo) Catch ex As Exception Throw End Try End Sub Public Function GetLinha() As String Try Dim aux As List(Of ItensLinha) = Lista.OrderBy(Function(i) i.Inicio).ToList Dim texto As New Text.StringBuilder Dim old As String For Each i As ItensLinha In aux Select Case i.Formato Case TipoFormato.SpaceEsquerda old = Space(i.Tamanho) & i.Valor.Trim old = old.PadLeft(i.Tamanho) Case TipoFormato.ZerosDireita old = i.Valor.PadRight(i.Tamanho, "0") Case TipoFormato.ZerosEsquerda old = i.Valor.PadLeft(i.Tamanho, "0") Case TipoFormato.Data If IsDate(i.Valor) Then old = CDate(i.Valor).ToString("ddMMyyyy") Else old = "00000000" End If Case TipoFormato.Hora If IsDate(i.Valor) Then old = CDate(i.Valor).ToString("HHmmss") Else old = "000000" End If Case TipoFormato.DataEhora If IsDate(i.Valor) Then old = CDate(i.Valor).ToString("ddMMyyyyHHmmss") Else old = "00000000000000" End If Case Else old = Space(i.Tamanho) & i.Valor.Trim old = old.PadLeft(i.Tamanho) End Select texto.Append(old) Next Return texto.ToString Catch ex As Exception Throw End Try End Function Private Class ItensLinha Public Property Inicio As Integer Public Property Tamanho As Integer Public Property Valor As String Public Property Formato As TipoFormato End Class End Class End Class Public Enum TiposLinha HeaderArquivo = 0 Headerlote = 1 Segmento = 2 TrailerLote = 3 TrailerArquivo = 4 End Enum Public Enum TipoSegmento Nenhum = 0 SegA = 1 SegB = 2 End Enum Public Enum TipoFormato ZerosEsquerda = 1 ZerosDireita = 2 SpaceEsquerda = 3 SpaceDireita = 4 Data = 5 Hora = 6 DataEhora = 7 End Enum
Namespace TrackingListener <Serializable()> Public MustInherit Class ATrackingListener Private WithEvents CPiTrackingSource As TrackingSource Public Channel As Integer = -1 #Region "Events" Public Event ValueReceived(ByVal CiValue As TrackingValue) Public Event Started() Public Event Stopped() #End Region #Region "Class functions" Public Sub New() 'UDPSender.Connect("192.168.146.255", 8747) Me.InitComm() End Sub Public Sub New(ByVal siHost As String, ByVal niPort As Integer) Me.broadcastAddress = siHost Me.BroadcastPort = niPort Me.InitComm() End Sub Protected Overrides Sub Finalize() MyBase.Finalize() End Sub #End Region #Region "Properties" Public Property TrackingSource() As TrackingSource Get Return Me.CPiTrackingSource End Get Set(ByVal value As TrackingSource) Me.CPiTrackingSource = value End Set End Property #End Region #Region "Broadcast" '''''''''''''''''''''''Set up variables'''''''''''''''''''' Public receivePort As Integer = 9653 Private receivingThread As Threading.Thread 'Create a separate thread to listen for incoming data, helps to prevent the form from freezing up Private closing As Boolean = False 'Used to close clients if form is closing Public MustOverride Sub InitComm() Public MustOverride Sub CloseComm() '''''''''''''''''''''Setup receiving client''''''''''''' Public MustOverride Sub InitializeReceiver() '''''''''''''''''''''Setup receiving thread''''''''''''' Public Sub InitializeReceiverThread() Dim start As Threading.ThreadStart = New Threading.ThreadStart(AddressOf Receiver) receivingThread = New Threading.Thread(start) receivingThread.IsBackground = True receivingThread.Start() End Sub '''''''''''''''''''''Start receiving loop''''''''''''''''''''''' Public MustOverride Sub Receiver() #End Region End Class End Namespace
Imports LN Imports LN.Estructuras Public Class frmBuscarUsuario Enum CAMPOS_COLUNMAS IDROL = 0 CEDULA = 1 NOMBRE = 2 APELLIDO1 = 3 APELLIDO2 = 4 CORREO = 5 GENERO = 6 NOMBREROL = 7 End Enum ''' <summary> ''' Evento del botón Salir ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks>Roberto Cordero</remarks> Private Sub btnSalir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSalir.Click Me.Close() End Sub ''' <summary> ''' Constructor del fomulario buscar usuario ''' </summary> ''' <remarks>Roberto Cordero Quiros</remarks> Sub New() ' Llamada necesaria para el diseñador. InitializeComponent() ' Agregue cualquier inicialización después de la llamada a InitializeComponent(). End Sub Private Sub PLlenarGrid() 'Lista temporal que almacena una lista de tipo estructura carrera Dim vloListaTem As List(Of LN.Estructuras.StrUsuario) vloListaTem = Gestores.GestorUsuario.listarUsuario 'Variable de tipo dataGridView row que sirve para ingresar a las columnas del gird Dim vldrRegistro As DataGridViewRow Dim vlcGeneroMasculino As String = "Masculino" Dim vlcGeneroFemenino As String = "Femenino" 'En caso de error Try Dim vlnIndice As Integer vloListaTem = Gestores.GestorUsuario.listarUsuario For vlnx As Integer = 0 To vloListaTem.Count - 1 vlnIndice = grdBuscarUsuarios.Rows.Add vldrRegistro = grdBuscarUsuarios.Rows(vlnx) vldrRegistro.Cells("vfoIdUsuario").Value = vloListaTem.Item(vlnx).IdUsuario vldrRegistro.Cells("vfoCedula").Value = vloListaTem.Item(vlnx).Cedula vldrRegistro.Cells("vfoNombre").Value = vloListaTem.Item(vlnx).Nombre vldrRegistro.Cells("vfoApellido1").Value = vloListaTem.Item(vlnx).Apellido1 vldrRegistro.Cells("vfoApellido2").Value = vloListaTem.Item(vlnx).Apellido2 vldrRegistro.Cells("vfoCorreo").Value = vloListaTem.Item(vlnx).Correo If (vloListaTem.Item(vlnx).Genero = "M") Then vldrRegistro.Cells("vfoGenero").Value = vlcGeneroMasculino Else vldrRegistro.Cells("vfoGenero").Value = vlcGeneroFemenino End If vldrRegistro.Cells("vfoNombreRol").Value = vloListaTem.Item(vlnx).NombreRol Next 'vloListaTem.GetEnumerator.Current.Id_Carrera Catch ex As Exception 'Invoca mensaje de error End Try End Sub ''' <summary> ''' Load ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks>Roberto Cordero</remarks> Private Sub frmBuscarUsuario_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'En caso de error Try ' Lista todos los usuariso de la base de datos ' grdBuscarUsuarios.DataSource = Gestores.GestorUsuario.listarUsuario() PLlenarGrid() Catch ex As Exception 'Invoca mensaje de error End Try End Sub Private frmAlAbrir As frmInterfaceBuscarModificarEliminar Public Property AlAbrir() As frmInterfaceBuscarModificarEliminar Get Return frmAlAbrir End Get Set(ByVal value As frmInterfaceBuscarModificarEliminar) frmAlAbrir = value End Set End Property ''' <summary> ''' Funcion encargada de poblar un DataTable con los Registros del Grid (se podria ''' perfecionar usando Linq) ''' </summary> ''' <param name="pvnIndex"></param> ''' <returns></returns> ''' <remarks>Roberto Cordero Q</remarks> Private Function FdtCargarDataTable(ByVal pvnIndex) As DataTable ' Se Declara e Instancia un DataTable Dim vldtTablaDatos As New DataTable 'Se construyen las columnas del DataTable (esos campos deberia ser los mismos que el grid 'Luego Explico porq en este ejemplo no lo he hecho) vldtTablaDatos.Columns.Add("Cedula") vldtTablaDatos.Columns.Add("Nombre") vldtTablaDatos.Columns.Add("Apellido1") vldtTablaDatos.Columns.Add("Apellido2") vldtTablaDatos.Columns.Add("Correo") vldtTablaDatos.Columns.Add("Genero") vldtTablaDatos.Columns.Add("NombreRol") 'Podria ser otro tipo de ciclo, si en un futuro quieren cargar mas datos, 'Se utuliza otro este es por cuestion de tiempo y inutilidad de mi parte- For i As Integer = 0 To 0 'Se declara una nueva fila para el datatable Dim row As DataRow = vldtTablaDatos.NewRow() 'Para la fila 0, de la columna (nombre de columna q construimos) asigne el item 'del grid, donde su columa (nombre de columana), y su fila, indice pasado por parametros row("Cedula") = grdBuscarUsuarios.Item(CAMPOS_COLUNMAS.CEDULA, pvnIndex).Value row("Nombre") = grdBuscarUsuarios.Item(CAMPOS_COLUNMAS.NOMBRE, pvnIndex).Value row("Apellido1") = grdBuscarUsuarios.Item(CAMPOS_COLUNMAS.APELLIDO1, pvnIndex).Value row("Apellido2") = grdBuscarUsuarios.Item(CAMPOS_COLUNMAS.APELLIDO2, pvnIndex).Value row("Correo") = grdBuscarUsuarios.Item(CAMPOS_COLUNMAS.CORREO, pvnIndex).Value row("Genero") = grdBuscarUsuarios.Item(CAMPOS_COLUNMAS.GENERO, pvnIndex).Value row("NombreRol") = grdBuscarUsuarios.Item(CAMPOS_COLUNMAS.NOMBREROL, pvnIndex).Value 'Agrege al datatable ese registro vldtTablaDatos.Rows.Add(row) Next Return vldtTablaDatos End Function ''' <summary> ''' Evento del boton Selecionar Registro del formulario ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks>Roberto Cordero Quiros</remarks> Private Sub btnSelecionar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelecionar.Click Dim vlcMensaje As String 'Resultado del dialogo Dim vloResultadoMensaje As DialogResult 'Valida que el grid tenga datos. o bien podria ser la lista de usuarios If Me.grdBuscarUsuarios.RowCount > 0 Then 'Mensaje de confirmacion vlcMensaje = "Desesa selecionar la linea: " + Me.grdBuscarUsuarios.CurrentRow.Index.ToString vloResultadoMensaje = MessageBox.Show(vlcMensaje, "Usuario", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) 'Si el mensaje fue arfimativo If vloResultadoMensaje = DialogResult.Yes Then PEnviarDatosAFormularioPadre() End If Else 'No existen datos que selecionar MessageBox.Show("No Existen registros para selecionar") End If 'Se podria Cerarr o no.. Pensarlo Me.Close() End Sub ''' <summary> ''' Procedimiento Encargado de enviar los datos al formulario padre de este formulario ''' </summary> ''' <remarks>Roberto Cordero Quiros</remarks> Public Sub PEnviarDatosAFormularioPadre() ' Se declara la variable fila de tipo entero Dim vlnFila As Integer ' Declaro un DataTable que almacena los registros del grid Dim vldtResultadoRegistros As DataTable ' Delcaro una variable de si la operacion fue correcta Dim vlbEstadoOperacion 'El currerow me indica en la fila que me encuentro vlnFila = Me.grdBuscarUsuarios.CurrentRow.Index() 'Se llama a la funcion CargarDataTable y se asigna a un datatable. vldtResultadoRegistros = FdtCargarDataTable(vlnFila) 'Utiliza el metodo implementado de la interface y establece el estado de la operacion 'Si quieren ver el comportamiento delen un break point en este punto vlbEstadoOperacion = Me.AlAbrir.FbCargarDataGrid(vldtResultadoRegistros) End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click End Sub End Class
Public Class Tile Property id As Integer Property id_mat1 As Integer Property id_mat2 As Integer Property material As Material Property material2 As Material Property texture As Rectangle Property texture2 As Rectangle Public Sub New(new_id As Integer, new_material As Material) Me.id = new_id Me.material = new_material Me.texture = New Rectangle(new_material.tileSquare.X + Constants.tileSize, new_material.tileSquare.Y + Constants.tileSize, Constants.tileSize, Constants.tileSize) End Sub Public Sub New(new_id1 As Integer, new_id2 As Integer, new_material1 As Material, new_material2 As Material) Me.id = 0 Me.id_mat1 = new_id1 Me.id_mat2 = new_id2 Me.material = new_material1 Me.material2 = new_material2 End Sub End Class
Imports cv = OpenCvSharp Imports System.Text.RegularExpressions Public Class FloodFill_Basics_MT : Implements IDisposable Public sliders As New OptionsSliders Dim grid As Thread_Grid Public srcGray As New cv.Mat Public externalUse As Boolean Public Sub New(ocvb As AlgorithmData) grid = New Thread_Grid(ocvb) sliders.setupTrackBar1(ocvb, "FloodFill Minimum Size", 1, 500, 50) sliders.setupTrackBar2(ocvb, "FloodFill LoDiff", 1, 255, 5) sliders.setupTrackBar3(ocvb, "FloodFill HiDiff", 1, 255, 5) If ocvb.parms.ShowOptions Then sliders.Show() ocvb.desc = "Use floodfill to build image segments with a grayscale image." End Sub Public Sub Run(ocvb As AlgorithmData) Dim minFloodSize = sliders.TrackBar1.Value Dim loDiff = cv.Scalar.All(sliders.TrackBar2.Value) Dim hiDiff = cv.Scalar.All(sliders.TrackBar3.Value) If externalUse = False Then srcGray = ocvb.color.CvtColor(cv.ColorConversionCodes.BGR2GRAY) ocvb.result2 = srcGray.Clone() grid.Run(ocvb) Parallel.ForEach(Of cv.Rect)(grid.roiList, Sub(roi) For y = roi.Y To roi.Y + roi.Height - 1 For x = roi.X To roi.X + roi.Width - 1 Dim nextByte = srcGray.At(Of Byte)(y, x) If nextByte <> 255 And nextByte > 0 Then Dim count = cv.Cv2.FloodFill(srcGray, New cv.Point(x, y), cv.Scalar.White, roi, loDiff, hiDiff, cv.FloodFillFlags.FixedRange) If count > minFloodSize Then count = cv.Cv2.FloodFill(ocvb.result2, New cv.Point(x, y), cv.Scalar.White, roi, loDiff, hiDiff, cv.FloodFillFlags.FixedRange) End If End If Next Next End Sub) End Sub Public Sub Dispose() Implements IDisposable.Dispose sliders.Dispose() grid.Dispose() End Sub End Class Public Class FloodFill_Color_MT : Implements IDisposable Dim flood As FloodFill_Basics_MT Dim grid As Thread_Grid Public src As New cv.Mat Public externalUse As Boolean Public Sub New(ocvb As AlgorithmData) grid = New Thread_Grid(ocvb) flood = New FloodFill_Basics_MT(ocvb) ocvb.desc = "Use floodfill to build image segments in an RGB image." End Sub Public Sub Run(ocvb As AlgorithmData) Dim minFloodSize = flood.sliders.TrackBar1.Value Dim loDiff = cv.Scalar.All(flood.sliders.TrackBar2.Value) Dim hiDiff = cv.Scalar.All(flood.sliders.TrackBar3.Value) If externalUse = False Then src = ocvb.color.Clone() ocvb.result2 = src.Clone() grid.Run(ocvb) Dim vec255 = New cv.Vec3b(255, 255, 255) Dim vec0 = New cv.Vec3b(0, 0, 0) Parallel.ForEach(Of cv.Rect)(grid.roiList, Sub(roi) For y = roi.Y To roi.Y + roi.Height - 1 For x = roi.X To roi.X + roi.Width - 1 Dim vec = src.At(Of cv.Vec3b)(y, x) If vec <> vec255 And vec <> vec0 Then Dim count = cv.Cv2.FloodFill(src, New cv.Point(x, y), cv.Scalar.White, roi, loDiff, hiDiff, cv.FloodFillFlags.FixedRange + cv.FloodFillFlags.Link4) If count > minFloodSize Then count = cv.Cv2.FloodFill(ocvb.result2, New cv.Point(x, y), cv.Scalar.White, roi, loDiff, hiDiff, cv.FloodFillFlags.FixedRange + cv.FloodFillFlags.Link4) End If End If Next Next End Sub) End Sub Public Sub Dispose() Implements IDisposable.Dispose grid.Dispose() flood.Dispose() End Sub End Class Public Class FloodFill_DCT : Implements IDisposable Dim flood As FloodFill_Color_MT Dim dct As DCT_FeatureLess_MT Public Sub New(ocvb As AlgorithmData) flood = New FloodFill_Color_MT(ocvb) flood.externalUse = True dct = New DCT_FeatureLess_MT(ocvb) ocvb.desc = "Find surfaces that lack any texture with DCT (highest frequency removed) and use floodfill to isolate those surfaces." End Sub Public Sub Run(ocvb As AlgorithmData) dct.Run(ocvb) flood.src = ocvb.result2.Clone() Dim mask As New cv.Mat cv.Cv2.BitwiseNot(ocvb.result1, mask) flood.src.SetTo(0, mask) flood.Run(ocvb) ocvb.result2.SetTo(0, mask) End Sub Public Sub Dispose() Implements IDisposable.Dispose dct.Dispose() flood.Dispose() End Sub End Class Public Class FloodFill_WithDepth : Implements IDisposable Dim flood As FloodFill_RelativeRange Dim shadow As Depth_Holes Public Sub New(ocvb As AlgorithmData) shadow = New Depth_Holes(ocvb) shadow.externalUse = True flood = New FloodFill_RelativeRange(ocvb) flood.fBasics.externalUse = True ocvb.desc = "Floodfill only the areas where there is depth" End Sub Public Sub Run(ocvb As AlgorithmData) shadow.Run(ocvb) flood.fBasics.srcGray = ocvb.color.CvtColor(cv.ColorConversionCodes.BGR2GRAY) flood.fBasics.initialMask = shadow.holeMask flood.Run(ocvb) End Sub Public Sub Dispose() Implements IDisposable.Dispose flood.Dispose() shadow.Dispose() End Sub End Class Public Class FloodFill_CComp : Implements IDisposable Dim ccomp As CComp_Basics Dim flood As FloodFill_RelativeRange Dim shadow As Depth_Holes Public Sub New(ocvb As AlgorithmData) shadow = New Depth_Holes(ocvb) shadow.externalUse = True ccomp = New CComp_Basics(ocvb) ccomp.externalUse = True flood = New FloodFill_RelativeRange(ocvb) flood.fBasics.externalUse = True ocvb.desc = "Use Floodfill with the output of the connected components to stabilize the colors used." End Sub Public Sub Run(ocvb As AlgorithmData) shadow.Run(ocvb) ccomp.srcGray = ocvb.color.CvtColor(cv.ColorConversionCodes.BGR2GRAY) ccomp.Run(ocvb) flood.fBasics.srcGray = ccomp.dstGray flood.fBasics.initialMask = shadow.holeMask flood.Run(ocvb) End Sub Public Sub Dispose() Implements IDisposable.Dispose ccomp.Dispose() flood.Dispose() shadow.Dispose() End Sub End Class Public Class FloodFill_RelativeRange : Implements IDisposable Public fBasics As FloodFill_Basics Dim check As New OptionsCheckbox Public Sub New(ocvb As AlgorithmData) fBasics = New FloodFill_Basics(ocvb) check.Setup(ocvb, 3) check.Box(0).Text = "Use Fixed range - when off, it means use relative range " check.Box(1).Text = "Use 4 nearest pixels (Link4) - when off, it means use 8 nearest pixels (Link8)" check.Box(1).Checked = True ' link4 produces better results. check.Box(2).Text = "Use 'Mask Only'" If ocvb.parms.ShowOptions Then check.Show() ocvb.desc = "Experiment with 'relative' range option to floodfill. Compare to fixed range option." End Sub Public Sub Run(ocvb As AlgorithmData) fBasics.floodFlag = 0 If check.Box(0).Checked Then fBasics.floodFlag += cv.FloodFillFlags.FixedRange If check.Box(1).Checked Then fBasics.floodFlag += cv.FloodFillFlags.Link4 Else fBasics.floodFlag += cv.FloodFillFlags.Link8 If check.Box(2).Checked Then fBasics.floodFlag += cv.FloodFillFlags.MaskOnly fBasics.Run(ocvb) End Sub Public Sub Dispose() Implements IDisposable.Dispose check.Dispose() fBasics.Dispose() End Sub End Class Public Class FloodFill_Basics : Implements IDisposable Dim check As New OptionsCheckbox Public sliders As New OptionsSliders Public srcGray As New cv.Mat Public externalUse As Boolean Public masks As New List(Of cv.Mat) Public maskSizes As New SortedList(Of Int32, Int32)(New CompareMaskSize) Public maskRects As New List(Of cv.Rect) Public initialMask As cv.Mat Public thumbNails As New cv.Mat Public floodFlag As cv.FloodFillFlags = cv.FloodFillFlags.FixedRange Public Class CompareMaskSize : Implements IComparer(Of Int32) Public Function Compare(ByVal a As Int32, ByVal b As Int32) As Integer Implements IComparer(Of Int32).Compare If a <= b Then Return 1 Return -1 End Function End Class Public Sub New(ocvb As AlgorithmData) check.Setup(ocvb, 1) check.Box(0).Text = "Show (up to) the first 16 largest objects in view (in order of size)" If ocvb.parms.ShowOptions Then check.Show() sliders.setupTrackBar1(ocvb, "FloodFill Minimum Size", 1, 5000, 2500) sliders.setupTrackBar2(ocvb, "FloodFill LoDiff", 1, 255, 5) sliders.setupTrackBar3(ocvb, "FloodFill HiDiff", 1, 255, 5) sliders.setupTrackBar4(ocvb, "Step Size", 1, ocvb.color.Width / 2, 20) If ocvb.parms.ShowOptions Then sliders.Show() ocvb.label1 = "Input image to floodfill" ocvb.desc = "Use floodfill to build image segments in a grayscale image." End Sub Public Sub Run(ocvb As AlgorithmData) Dim minFloodSize = sliders.TrackBar1.Value Dim loDiff = cv.Scalar.All(sliders.TrackBar2.Value) Dim hiDiff = cv.Scalar.All(sliders.TrackBar3.Value) Dim stepSize = sliders.TrackBar4.Value If externalUse = False Then sliders.TrackBar1.Value = 250 ' shows all the isolated regions in the grayscale image. srcGray = ocvb.color.CvtColor(cv.ColorConversionCodes.BGR2GRAY) initialMask = New cv.Mat(ocvb.color.Size, cv.MatType.CV_8U, 0) End If ocvb.result1 = srcGray.Clone() ocvb.result2.SetTo(0) Dim rect As New cv.Rect Dim maskPlus = New cv.Mat(New cv.Size(srcGray.Width + 2, srcGray.Height + 2), cv.MatType.CV_8UC1) Dim maskRect = New cv.Rect(1, 1, maskPlus.Width - 2, maskPlus.Height - 2) masks.Clear() maskSizes.Clear() maskRects.Clear() maskPlus.SetTo(0) Dim othersMask = initialMask.Clone() thumbNails = New cv.Mat(ocvb.color.Size(), cv.MatType.CV_8U, 0) Dim allSize = New cv.Size(thumbNails.Width / 4, thumbNails.Height / 4) ' show the first 16 masks For y = 0 To srcGray.Height - 1 Step stepSize For x = 0 To srcGray.Width - 1 Step stepSize Dim count = cv.Cv2.FloodFill(srcGray, maskPlus, New cv.Point(x, y), cv.Scalar.White, rect, loDiff, hiDiff, floodFlag Or (255 << 8)) If count > minFloodSize Then masks.Add(maskPlus(maskRect).Clone().SetTo(0, othersMask)) masks(masks.Count - 1).SetTo(0, initialMask) ' The initial mask is what should not be part of any mask. maskSizes.Add(masks(masks.Count - 1).CountNonZero(), masks.Count - 1) maskRects.Add(rect) End If ' Mask off any object that is too small or previously identified cv.Cv2.BitwiseOr(othersMask, maskPlus(maskRect), othersMask) Next Next Dim thumbCount As Int32 Dim allRect = New cv.Rect(0, 0, allSize.Width, allSize.Height) For i = 0 To masks.Count - 1 Dim maskIndex = maskSizes.ElementAt(i).Value Dim nextColor = ocvb.colorScalar(i Mod 255) ocvb.result2.SetTo(nextColor, masks(maskIndex)) If thumbCount < 16 Then thumbNails(allRect) = masks(maskIndex).Resize(allSize).Threshold(0, 255, cv.ThresholdTypes.Binary) thumbNails.Rectangle(allRect, cv.Scalar.White, 1) allRect.X += allSize.Width If allRect.X >= thumbNails.Width Then allRect.X = 0 allRect.Y += allSize.Height End If thumbCount += 1 End If Next If check.Box(0).Checked Then ocvb.result2 = thumbNails.CvtColor(cv.ColorConversionCodes.GRAY2BGR) ocvb.label2 = CStr(masks.Count) + " regions > " + CStr(minFloodSize) + " pixels" End Sub Public Sub Dispose() Implements IDisposable.Dispose sliders.Dispose() check.Dispose() End Sub End Class
Imports System.IO Imports System.Net Imports Newtonsoft.Json Public Class AppDetail Public appDetailInfo As AppInfos Public Sub showApp(appinfo As AppInfos) appDetailInfo = appinfo Dim webClient As New WebClient lblAppName.Text = appDetailInfo.Name lblAuthor.Text = appDetailInfo.Author lblCategory.Text = appDetailInfo.Section lblVersion.Text = appDetailInfo.Version Dim json As String Dim app As ItuneResult Try json = webClient.DownloadString("https://itunes.apple.com/lookup?id=" & appDetailInfo.Package) app = JsonConvert.DeserializeObject(Of ItuneResult)(json) Catch MsgBox("Cannot get app information") Exit Sub End Try Dim tClient As New WebClient If app.resultCount > 0 Then appDetailInfo.Size = app.results.ElementAt(0).fileSizeBytes appDetailInfo.Description = app.results.ElementAt(0).description.Replace(vbLf, vbCrLf) appDetailInfo.Architecture = app.results.ElementAt(0).minimumOsVersion Dim filesize As Long = CLng(appDetailInfo.Size) If (filesize / 1024 / 1024 / 1024) > 1 Then lblSize.Text = Math.Round((filesize / 1024 / 1024 / 1024), 2) & " GB" ElseIf (filesize / 1024 / 1024) > 1 Then lblSize.Text = Math.Round((filesize / 1024 / 1024), 2) & " MB" Else lblSize.Text = Math.Round((filesize / 1024), 2) & " KB" End If pic1.Image = Image.FromStream(New MemoryStream(tClient.DownloadData(app.results.ElementAt(0).screenshotUrls.ElementAt(0)))) pic2.Image = Image.FromStream(New MemoryStream(tClient.DownloadData(app.results.ElementAt(0).screenshotUrls.ElementAt(1)))) pic3.Image = Image.FromStream(New MemoryStream(tClient.DownloadData(app.results.ElementAt(0).screenshotUrls.ElementAt(2)))) pic4.Image = Image.FromStream(New MemoryStream(tClient.DownloadData(app.results.ElementAt(0).screenshotUrls.ElementAt(3)))) Else appDetailInfo.Size = "" appDetailInfo.Description = "" End If If appinfo.Icon <> "" And appinfo.Icon.StartsWith("http") Then imgApp.Image = Bitmap.FromStream(New MemoryStream(tClient.DownloadData(appinfo.Icon))) Else imgApp.Image = New Bitmap(AppConst.m_rootPath + AppConst.IMAGE + "/apptype_tweak.png") End If lblSupport.Text = appDetailInfo.Architecture txtDesc.Text = appDetailInfo.Description Me.ShowDialog() End Sub Private Sub cmdInstall_Click(sender As Object, e As EventArgs) Handles cmdInstall.Click Dim ipaLink As String Dim ipaName As String If appDetailInfo.Filename.IndexOf("dailyuploads.net") >= 0 Then ipaLink = appDetailInfo.Filename ipaName = "checking...ipa" Else ipaLink = appDetailInfo.Filename ipaName = appDetailInfo.Name & ".ipa" End If Me.Close() Common.Download(New DownloadProgress, ipaLink, ipaName) End Sub Private Sub cmdClose_Click(sender As Object, e As EventArgs) Handles cmdClose.Click Me.Close() End Sub End Class
Imports System.ComponentModel.DataAnnotations Imports Nukepayload2.ConsoleFramework Public Class App <EntryMethod()> Public Sub StartUp( <Display(Name:="original", ShortName:="o", Description:="原始文件目录。")> srcA As String, <Display(Name:="compare", ShortName:="c", Description:="要跟原始文件比较的文件目录。")> srcB As String, <Display(Name:="destination", ShortName:="d", Description:="比较输出的目录。")> dest As String, <Display(Name:="nogpu", ShortName:="ng", Description:="带有这个标签则说明强制使用 OpenCL。")> Optional OpenCL As Boolean = True ) Console.WriteLine(NameOf(srcA) & " = " & srcA) Console.WriteLine(NameOf(srcB) & " = " & srcB) Console.WriteLine(NameOf(dest) & " = " & dest) If OpenCL Then Console.WriteLine(NameOf(OpenCL)) Else Console.WriteLine("Don't " + NameOf(OpenCL)) End If End Sub End Class
Imports System Imports System.Collections.Generic Imports System.ComponentModel.DataAnnotations Imports System.ComponentModel.DataAnnotations.Schema Imports System.Data.Entity.Spatial Imports Newtonsoft.Json <Table("tblNOISubmissionTaxParcels")> Partial Public Class NOISubmissionTaxParcels Implements IEntity <Key> <DatabaseGenerated(DatabaseGeneratedOption.Identity)> Public Property SubmissionTaxParcelID As Integer Public Property SubmissionID As Integer <Required> <StringLength(100)> Public Property TaxParcelNumber As String <Required> <StringLength(1)> Public Property TaxParcelCounty As String <NotMapped> Public Property IsDeleted As Boolean = False <JsonIgnore> Public Overridable Property NOISubmission As NOISubmission Public Property EntityState As EntityState = NoticeOfIntent.EntityState.Unchanged Implements IEntity.EntityState End Class
' NOTE: You can use the "Rename" command on the context menu to change the class name "Service1" in code, svc and config file together. ' NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.vb at the Solution Explorer and start debugging. Imports WcfGeneric Imports MySql Imports MySql.Data.MySqlClient Public Class GarvGenericService Implements IGarvGenericService Public Sub New() End Sub Public Function InsertEmployee(employee As Employee) As Integer Implements IGarvGenericService.InsertEmployee Dim connectionString As String = GetConnectionString() Dim mySqlConnection As New MySqlConnection(connectionString) Dim rowsAffected As Integer = 0 Try mySqlConnection.Open() Dim mySqlCommand As New MySqlCommand With mySqlCommand .Connection = mySqlConnection .CommandText = $"INSERT INTO employees (Name, Charge, Email) VALUES ('{employee.Name}', '{employee.Charge}', '{employee.Email}')" .CommandType = CommandType.Text End With rowsAffected = mySqlCommand.ExecuteNonQuery() mySqlConnection.Close() Catch ex As Exception Finally End Try Return rowsAffected End Function Protected Function GetConnectionString() As String Dim server As String = "localhost" Dim database As String = "garv_company" Dim user As String = "user_admin" Dim password As String = "Sigma1702*" Return $"SERVER={server}; DATABASE={database}; UID={user}; PASSWORD={password};" End Function End Class
Imports System.Configuration Imports MySql.Data.MySqlClient Public Class writeExam Dim _con As New MySqlConnection(ConfigurationManager.ConnectionStrings("myConnection").ConnectionString) Dim _cmd As MySqlCommand ''' <summary> ''' The timercount ''' </summary> Dim _timercount As Integer 'The number of seconds Dim time_limit As String Private Sub Loadgrid() _con.Close() Try _con.Open() _cmd = New MySqlCommand("select * from results where username='" + FrmLogin.lblUsername.ToUpper + "' and status='PENDING' ", _con) Dim myda2 As MySqlDataAdapter = New MySqlDataAdapter(_cmd) Dim mydataset2 As DataSet = New DataSet myda2.Fill(mydataset2, "results") DataGridView1.DataSource = mydataset2.Tables("results").DefaultView DataGridView1.FirstDisplayedScrollingRowIndex = DataGridView1.RowCount - 1 DataGridView1.Rows(DataGridView1.RowCount - 1).Selected = True DataGridView1.CurrentCell = DataGridView1.Rows(DataGridView1.RowCount - 1).Cells(0) _con.Close() Catch ex As Exception _con.Close() ' MsgBox(ex.Message) End Try End Sub Private Sub DataGridView1_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick Try Dim dr As DataGridViewRow = DataGridView1.SelectedRows(0) e0.Text = dr.Cells(0).Value.ToString e1.Text = dr.Cells(2).Value.ToString e2.Text = dr.Cells(3).Value.ToString e3.Text = dr.Cells(4).Value.ToString e4.Text = dr.Cells(5).Value.ToString e5.Text = dr.Cells(6).Value.ToString e6.Text = dr.Cells(7).Value.ToString e1.Enabled = False SimpleButton7.Enabled = True Catch ex As Exception End Try End Sub Private Sub clearAlltxt() e0.Text = "" e1.Text = "" e2.Text = "" e3.Text = "" e4.Text = "" e5.Text = "" e6.SelectedIndex = -1 End Sub Private Sub FrmAdmin_Load(sender As Object, e As EventArgs) Handles MyBase.Load Try _con.Open() _cmd = New MySqlCommand("INSERT INTO results (questionID, industry, examID, question, option1, option2, option3, answer ,username) Select questionID,industry,examID,question,option1,option2,option3,answer ,'" + FrmLogin.lblUsername.ToUpper + "' from exams WHERE industry='" + FrmLogin.industry + "' and active='ACTIVE' ", _con) _cmd.ExecuteReader(CommandBehavior.CloseConnection) _cmd.Dispose() _con.Close() Catch ex As Exception _cmd.Dispose() _con.Close() MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try Loadgrid() Dim examdate As String Dim SQL As String = "SELECT distinct(exam_date),time_limit FROM exams where industry ='" + FrmLogin.industry + "' and active='ACTIVE'" Using _cmd = New MySqlCommand(SQL, _con) _con.Close() _con.Open() Try Dim dr = _cmd.ExecuteReader() While dr.Read() examdate = dr("exam_date").ToString() time_limit = dr("time_limit").ToString() _timercount = CInt(time_limit) End While Catch ex As MySqlException ' Do some logging or something. MessageBox.Show("There was an error accessing your exam centre. DETAIL: " & ex.ToString()) End Try End Using Timer1.Start() End Sub Private Sub SimpleButton7_Click_1(sender As Object, e As EventArgs) Handles SimpleButton7.Click If e1.Text = "" Or e2.Text = "" Or e3.Text = "" Or e4.Text = "" Or e5.Text = "" Or e6.Text = "" Then MsgBox("missing parameters") Exit Sub End If If e1.Enabled = True Then Try _con.Open() _cmd = New MySqlCommand("update exams set question='" + e2.Text.ToString.Replace("'", "''") + "', option1='" + e3.Text.ToString.Replace("'", "''") + "',option2='" + e4.Text.ToString.Replace("'", "''") + "',option3='" + e5.Text.ToString.Replace("'", "''") + "',answer='" + e6.Text + "' where questionID='" + e0.Text + "' ", _con) _cmd.ExecuteReader(CommandBehavior.CloseConnection) _cmd.Dispose() _con.Close() MessageBox.Show("Question Updated") e1.Enabled = True clearAlltxt() Loadgrid() Catch ex As Exception _cmd.Dispose() _con.Close() MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End If End Sub Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick 'MsgBox("Starting Exam") ' Panel2.Visible = True Label2.Text = _timercount.ToString() 'show the countdown in the label If _timercount = 0 Then 'Check to see if it has reached 0, if yes then stop timer and display done Timer2.Enabled = False Label2.Text = "EXAM TIME OUT" UpdateStats() Else 'If timercount is higher then 0 then subtract one from it _timercount -= 1 UpdateStats() End If End Sub Private Sub SimpleButton2_Click(sender As Object, e As EventArgs) End Sub Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick UpdateStats() End Sub Private Sub UpdateStats() Try 'exam ArcScaleComponent2.MaxValue = CInt(time_limit) ArcScaleComponent2.Value = Double.Parse(CInt(time_limit) - _timercount) LabelComponent1.Text = String.Format("{0} ", (CInt(time_limit) - _timercount)) Catch ex As Exception Debug.WriteLine(ex.Message) End Try End Sub Private Sub SimpleButton1_Click(sender As Object, e As EventArgs) Handles SimpleButton1.Click Dispose() End Sub Private Sub writeExam_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed Dispose() End Sub End Class
Imports Talent.Common Imports TEBUtilities = Talent.eCommerce.Utilities Imports TCUtilities = Talent.Common.Utilities Imports System.Data Partial Class PagesPublic_Basket_PromotionDetails Inherits TalentBase01 #Region "Class Level Fields" Private _wfrPage As New WebFormResource Private _languageCode As String = String.Empty Private _originalPrice As Decimal = 0 Private _salePrice As Decimal = 0 #End Region #Region "Constants" Const KEYCODE As String = "PromotionDetails.aspx" #End Region #Region "Protected Methods" Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load With _wfrPage .BusinessUnit = TalentCache.GetBusinessUnit() .PageCode = ProfileHelper.GetPageName .PartnerCode = TalentCache.GetPartner(HttpContext.Current.Profile, .BusinessUnit) .FrontEndConnectionString = ConfigurationManager.ConnectionStrings("TalentEBusinessDBConnectionString").ToString .KeyCode = KEYCODE End With _languageCode = TCUtilities.GetDefaultLanguage() 'Ticketing Promotions Dim ticketingPromotionToShow As Boolean = False If Request.QueryString("promotionid1") IsNot Nothing Then ticketingPromotionToShow = True If Request.QueryString("promotionid2") IsNot Nothing Then ticketingPromotionToShow = True If Request.QueryString("promotionid3") IsNot Nothing Then ticketingPromotionToShow = True If ticketingPromotionToShow Then If Request.QueryString("originalprice") IsNot Nothing Then _originalPrice = TEBUtilities.CheckForDBNull_Decimal(Request.QueryString("originalprice")) End If If Request.QueryString("saleprice") IsNot Nothing Then _salePrice = TEBUtilities.CheckForDBNull_Decimal(Request.QueryString("saleprice")) End If ticketingPromotionToShow = bindRepeater() End If plhTicketingPromotionDetails.Visible = ticketingPromotionToShow 'Merchandise Promotions Dim merchandisePromotionToShow As Boolean = handleMerchandisePromotions() plhMerchandisePromotionDetails.Visible = merchandisePromotionToShow If Not ticketingPromotionToShow AndAlso Not merchandisePromotionToShow Then plhPromotionNotFound.Visible = False ltlPromotionNotFound.Text = _wfrPage.Content("NoPromotionsFound", _languageCode, True) End If End Sub Protected Sub rptTicketingPromotionDetails_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs) Handles rptTicketingPromotionDetails.ItemDataBound If e.Item.ItemType = ListItemType.AlternatingItem OrElse e.Item.ItemType = ListItemType.Item Then If Not bindPromotions(e.Item.DataItem, e.Item) Then e.Item.Visible = False End If End If End Sub #End Region #Region "Private Methods" ''' <summary> ''' Set the text values on the page based on the given promotion data table ''' </summary> ''' <param name="promotionTable">A data table of promotions</param> ''' <remarks></remarks> Private Sub setPageText(ByVal promotionTable As DataTable, ByRef e As RepeaterItem) Dim ltlTicketingPromotionDescription1Label As Literal = CType(e.FindControl("ltlTicketingPromotionDescription1Label"), Literal) Dim ltlTicketingPromotionStartDateLabel As Literal = CType(e.FindControl("ltlTicketingPromotionStartDateLabel"), Literal) Dim ltlTicketingPromotionEndDateLabel As Literal = CType(e.FindControl("ltlTicketingPromotionEndDateLabel"), Literal) Dim ltlTicketingPromotionDescription1Value As Literal = CType(e.FindControl("ltlTicketingPromotionDescription1Value"), Literal) Dim ltlTicketingPromotionDescription2Value As Literal = CType(e.FindControl("ltlTicketingPromotionDescription2Value"), Literal) Dim ltlTicketingPromotionStartDateValue As Literal = CType(e.FindControl("ltlTicketingPromotionStartDateValue"), Literal) Dim ltlTicketingPromotionEndDateValue As Literal = CType(e.FindControl("ltlTicketingPromotionEndDateValue"), Literal) Dim ltlTicketingFeeRemoved As Literal = CType(e.FindControl("ltlTicketingFeeRemoved"), Literal) Dim plhTicketingFeeInformation As PlaceHolder = CType(e.FindControl("plhTicketingFeeInformation"), PlaceHolder) ltlTicketingPromotionDescription1Label.Text = _wfrPage.Content("PromotionDescriptionLabel", _languageCode, True) ltlTicketingPromotionStartDateLabel.Text = _wfrPage.Content("PromotionStartDateLabel", _languageCode, True) ltlTicketingPromotionEndDateLabel.Text = _wfrPage.Content("PromotionEndDateLabel", _languageCode, True) ltlTicketingPromotionDescription1Value.Text = TEBUtilities.CheckForDBNull_String(promotionTable.Rows(0)("ShortDescription")) ltlTicketingPromotionDescription2Value.Text = TEBUtilities.CheckForDBNull_String(promotionTable.Rows(0)("Description1")) & TEBUtilities.CheckForDBNull_String(promotionTable.Rows(0)("Description2")) ltlTicketingPromotionStartDateValue.Text = TEBUtilities.CheckForDBNull_String(promotionTable.Rows(0)("StartDate")) ltlTicketingPromotionEndDateValue.Text = TEBUtilities.CheckForDBNull_String(promotionTable.Rows(0)("EndDate")) If Not String.IsNullOrWhiteSpace(TEBUtilities.CheckForDBNull_String(promotionTable.Rows(0)("FeesRemoved"))) Then ltlTicketingFeeRemoved.Text = getFeeDescription(TEBUtilities.CheckForDBNull_String(promotionTable.Rows(0)("FeesRemoved"))) Else plhTicketingFeeInformation.Visible = False End If End Sub #End Region #Region "Private Functions" ''' <summary> ''' Bind the repeater of promotions and prices ''' </summary> ''' <returns><c>True</c> if the promotions have been set correctly otherwise <c>False</c></returns> ''' <remarks></remarks> Private Function bindRepeater() As Boolean Dim hasPromotions As Boolean = False Try Dim promotionList As New Generic.List(Of String) If Request.QueryString("promotionid1") IsNot Nothing Then promotionList.Add(TEBUtilities.CheckForDBNull_String(Request.QueryString("promotionid1"))) If Request.QueryString("promotionid2") IsNot Nothing Then promotionList.Add(TEBUtilities.CheckForDBNull_String(Request.QueryString("promotionid2"))) If Request.QueryString("promotionid3") IsNot Nothing Then promotionList.Add(TEBUtilities.CheckForDBNull_String(Request.QueryString("promotionid3"))) If promotionList.Count > 0 Then rptTicketingPromotionDetails.DataSource = promotionList rptTicketingPromotionDetails.DataBind() If _originalPrice > 0 Then ltlTicketingPromotionOriginalPriceLabel.Text = _wfrPage.Content("PromotionOriginalPriceLabel", _languageCode, True) ltlTicketingPromotionNewPriceLabel.Text = _wfrPage.Content("PromotionNewPriceLabel", _languageCode, True) ltlTicketingPromotionDiscountPriceLabel.Text = _wfrPage.Content("PromotionDiscountPriceLabel", _languageCode, True) ltlTicketingPromotionOriginalPriceValue.Text = TDataObjects.PaymentSettings.FormatCurrency(_originalPrice, _wfrPage.BusinessUnit, _wfrPage.PartnerCode) ltlTicketingPromotionNewPriceValue.Text = TDataObjects.PaymentSettings.FormatCurrency(_salePrice, _wfrPage.BusinessUnit, _wfrPage.PartnerCode) ltlTicketingPromotionDiscountPriceValue.Text = TDataObjects.PaymentSettings.FormatCurrency(_originalPrice - _salePrice, _wfrPage.BusinessUnit, _wfrPage.PartnerCode) Else plhTicketingPriceInformation.Visible = False End If hasPromotions = True End If Catch ex As Exception hasPromotions = False End Try Return hasPromotions End Function ''' <summary> ''' Try to call TALENT and bind the promotions to the page ''' </summary> ''' <returns>a boolean value to indicate whether or not promotions have been set</returns> ''' <remarks></remarks> Private Function bindPromotions(ByVal promotionId As String, ByRef e As RepeaterItem) As Boolean Dim hasPromotions As Boolean = False Dim promotions As New TalentPromotions Dim promoSettings As New DEPromotionSettings promoSettings.FrontEndConnectionString = ConfigurationManager.ConnectionStrings("TalentEBusinessDBConnectionString").ToString promoSettings.BusinessUnit = TalentCache.GetBusinessUnit() promoSettings.StoredProcedureGroup = Talent.eCommerce.Utilities.GetStoredProcedureGroup() If Profile.IsAnonymous Then promoSettings.AccountNo1 = TCUtilities.PadLeadingZeros(GlobalConstants.GENERIC_CUSTOMER_NUMBER, 12) Else promoSettings.AccountNo1 = TCUtilities.PadLeadingZeros(Profile.User.Details.Account_No_1, 12) End If promoSettings.Cacheing = TEBUtilities.CheckForDBNullOrBlank_Boolean_DefaultTrue(_wfrPage.Attribute("Caching")) promoSettings.CacheTimeMinutes = TEBUtilities.CheckForDBNull_Int(_wfrPage.Attribute("CacheTimeInMins")) promoSettings.CacheDependencyPath = ModuleDefaults.CacheDependencyPath promoSettings.OriginatingSource = TEBUtilities.GetOriginatingSource(Session.Item("Agent")) promoSettings.IncludeProductPurchasers = String.Empty Dim promotionDataEntity As New DEPromotions Dim err As New ErrorObj promotionDataEntity.PromotionId = promotionId promotions.Dep = promotionDataEntity promotions.Settings = promoSettings err = promotions.GetPromotionDetails() If Not err.HasError AndAlso promotions.ResultDataSet IsNot Nothing AndAlso promotions.ResultDataSet.Tables.Count > 0 Then If promotions.ResultDataSet.Tables(0).Rows.Count > 0 Then setPageText(promotions.ResultDataSet.Tables(0), e) hasPromotions = True End If End If Return hasPromotions End Function ''' <summary> ''' Retreives the text description against the fee code that is passed in ''' </summary> ''' <param name="feeCode">The fee code as a string</param> ''' <returns>The fee description</returns> ''' <remarks></remarks> Private Function getFeeDescription(ByVal feeCode As String) As String Dim feeDescription As String = String.Empty Select Case feeCode Case Is = GlobalConstants.BKFEE : feeDescription = _wfrPage.Content("BKFEERemoved", _languageCode, True) Case Is = GlobalConstants.WSFEE : feeDescription = _wfrPage.Content("WSFEERemoved", _languageCode, True) Case Is = GlobalConstants.DDFEE : feeDescription = _wfrPage.Content("DDFEERemoved", _languageCode, True) Case Is = GlobalConstants.CRFEE : feeDescription = _wfrPage.Content("CRFEERemoved", _languageCode, True) Case Is = GlobalConstants.ALLFEES : feeDescription = _wfrPage.Content("ALLFEESRemoved", _languageCode, True) Case Else : feeDescription = _wfrPage.Content("UnknownFeeRemoved", _languageCode, True) End Select Return feeDescription End Function ''' <summary> ''' Set any merchandise promotion details ''' </summary> ''' <returns><c>True</c> if the retail promotions are set otherwise <c>False</c></returns> ''' <remarks></remarks> Private Function handleMerchandisePromotions() As Boolean Dim hasMerchandisePromotion As Boolean = False blMerchandisePromotions.Items.Clear() If ModuleDefaults.PricingType <> 2 Then Dim promoResults As Data.DataTable Dim talentWebPricing As TalentWebPricing = Nothing If (Profile.Basket.WebPrices IsNot Nothing) Then talentWebPricing = Profile.Basket.WebPrices End If If (talentWebPricing Is Nothing) Then promoResults = New Data.DataTable Else If Not talentWebPricing.PromotionsResultsTable Is Nothing Then promoResults = talentWebPricing.PromotionsResultsTable Else promoResults = New Data.DataTable End If End If If Not promoResults Is Nothing AndAlso promoResults.Rows.Count > 0 Then For Each result As Data.DataRow In promoResults.Rows If TEBUtilities.CheckForDBNull_Boolean_DefaultFalse(result("Success")) Then Dim sPromoDisplay As String = "<<PromotionDisplayName>> ( x <<ApplicationCount>>)" If result("ActivationMechanism") = DBPromotions.code Then Dim sPromoDisplayCode As String = TEBUtilities.CheckForDBNull_String(_wfrPage.Content("PromotionsSummaryDisplayCode", _languageCode, True)) If sPromoDisplayCode <> String.Empty Then sPromoDisplay = sPromoDisplayCode End If ElseIf result("ActivationMechanism") = DBPromotions.auto Then Dim sPromoDisplayAuto As String = TEBUtilities.CheckForDBNull_String(_wfrPage.Content("PromotionsSummaryDisplayAuto", _languageCode, True)) If sPromoDisplayAuto <> String.Empty Then sPromoDisplay = sPromoDisplayAuto End If End If blMerchandisePromotions.Items.Add(sPromoDisplay.Replace("<<PromotionDisplayName>>", result("PromotionDisplayName")).Replace("<<ApplicationCount>>", result("ApplicationCount")).Replace("<<PromotionCode>>", result("PromotionCode"))) hasMerchandisePromotion = True End If Next End If End If Return hasMerchandisePromotion End Function #End Region End Class
Private Sub CityCode_Validate(results As ScreenValidationResultsBuilder) If Me.CityCode.Length < 3 Then results.AddPropertyError("This string must have at least 3 letters.") End If End Sub
' ################################################################################ ' # EMBER MEDIA MANAGER # ' ################################################################################ ' ################################################################################ ' # This file is part of Ember Media Manager. # ' # # ' # Ember Media Manager is free software: you can redistribute it and/or modify # ' # it under the terms of the GNU General Public License as published by # ' # the Free Software Foundation, either version 3 of the License, or # ' # (at your option) any later version. # ' # # ' # Ember Media Manager is distributed in the hope that it will be useful, # ' # but WITHOUT ANY WARRANTY; without even the implied warranty of # ' # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # ' # GNU General Public License for more details. # ' # # ' # You should have received a copy of the GNU General Public License # ' # along with Ember Media Manager. If not, see <http://www.gnu.org/licenses/>. # ' ################################################################################ Imports System.Windows.Forms Imports System Imports System.IO Imports System.Text.RegularExpressions Imports EmberAPI Imports NLog Imports Vlc.DotNet Public Class frmVideoPlayer #Region "Fields" Shared logger As Logger = NLog.LogManager.GetCurrentClassLogger() Dim PlayList As List(Of Uri) #End Region #Region "Events" #End Region #Region "Constructors" #End Region #Region "Methods" Public Sub SetUp() Dim aVlcControl As Forms.VlcControl Dim aPath As String PlayList = New List(Of Uri) aPath = clsAdvancedSettings.GetSetting("VLCPath", "", "generic.EmberCore.VLCPlayer") If Not File.Exists(Path.Combine(aPath, "libvlc.dll")) Then ' Add any initialization after the InitializeComponent() call. If Environment.Is64BitOperatingSystem Then If Environment.Is64BitProcess Then aPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "VideoLAN\VLC") Else aPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "VideoLAN\VLC") End If Else aPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "VideoLAN\VLC") End If End If If Directory.Exists(aPath) Then aVlcControl = New Forms.VlcControl aVlcControl.BeginInit() aVlcControl.Name = "VlcControl" aVlcControl.VlcLibDirectory = New DirectoryInfo(aPath) aVlcControl.Parent = pnlPlayer aVlcControl.Dock = DockStyle.Fill AddHandler aVlcControl.VlcLibDirectoryNeeded, AddressOf checkVLCDir pnlPlayer.Controls.Add(aVlcControl) aVlcControl.EndInit() Else End If End Sub Public Sub New() ' This call is required by the designer. InitializeComponent() Me.SetUp() End Sub Public Sub New(aFile As String) MyBase.New() InitializeComponent() Me.SetUp() PlaylistAdd(aFile) End Sub Public Sub PlayerPlay() Dim aVlcControl As Vlc.DotNet.Forms.VlcControl aVlcControl = CType(pnlPlayer.Controls.Find("VlcControl", True)(0), Vlc.DotNet.Forms.VlcControl) For Each aPath In PlayList aVlcControl.Play(aPath) Next End Sub Public Sub PlayerStop() Dim aVlcControl As Vlc.DotNet.Forms.VlcControl aVlcControl = CType(pnlPlayer.Controls.Find("VlcControl", True)(0), Vlc.DotNet.Forms.VlcControl) aVlcControl.Stop() End Sub Public Sub PlaylistAdd(ByVal URL As String) If Not String.IsNullOrEmpty(URL) Then If Regex.IsMatch(URL, "http:\/\/.*?") Then PlayList.Add(New Uri(URL)) Else PlayList.Add(New Uri(String.Concat("file:///", URL))) End If End If End Sub Public Sub PlaylistClear() PlayList.Clear() End Sub Private Sub checkVLCDir(sender As Object, e As Forms.VlcLibDirectoryNeededEventArgs) Dim aPath As String Dim aTitle As String If Environment.Is64BitOperatingSystem Then If Environment.Is64BitProcess Then aPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) aTitle = Master.eLang.GetString(1488, "Select VLC x64 bit Path") Else aPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) aTitle = Master.eLang.GetString(1490, "Select VLC x86 bit Path") End If Else aPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) aTitle = Master.eLang.GetString(1490, "Select VLC x86 bit Path") End If If Not File.Exists(Path.Combine(Path.Combine(aPath, "VideoLAN\VLC"), "libvlc.dll")) Then Using fbdDialog As New FolderBrowserDialog() fbdDialog.Description = aTitle fbdDialog.SelectedPath = aPath If fbdDialog.ShowDialog() = DialogResult.OK Then e.VlcLibDirectory = New DirectoryInfo(fbdDialog.SelectedPath) End If End Using Else e.VlcLibDirectory = New DirectoryInfo(Path.Combine(aPath, "VideoLAN\VLC")) End If e.VlcLibDirectory = Nothing End Sub #End Region End Class
Public Class ContextoTransaccion Public Property ID_CONTEXTO As Integer Public Property ID_TX As String Public Property FECHA_INICIO As Date Public Property ID_DEF_PROCESO As String Public Property NOMBRE_PROCESO As String Public Property ID_USUARIO_APP As String Public Property ID_EMISOR As String Public Property FECHA_CREACION As Date Public Property ID_TITULO As Integer Public Property COD_TX As String End Class
'============================================================================= ' ' Copyright 2008 Siemens Product Lifecycle Management Software Inc. All Rights Reserved. ' '============================================================================= ' ' =========================================================================== ' DESCRIPTION ' This program will cycle through all the surface contouring operations in the part and ' turn off smoothing in NCM Transfer/Rapid. ' ' This can be used as a boiler plate to set other NCM parameters. ' ============================================================================ Option Strict Off Imports System Imports System.IO Imports NXOpen Imports NXOpen.CAM Imports NXOpen.UF Imports NXOpen.Utilities Module SurfaceContourOperations Dim theSession As Session Dim theUfSession As UFSession Sub Main() theSession = Session.GetSession() theUfSession = UFSession.GetUFSession() Dim WorkPart As Part = TheSession.Parts.Work Dim setupTag As Tag Dim camObjectTag As Tag Dim programRootTag As Tag ' If there is a work part only then we can go further If WorkPart IsNot Nothing Then theUfSession.Cam.InitSession() theUfSession.Setup.AskSetup(setupTag) ' If there is a setup only then we go further If setupTag <> 0 Then Dim ptr As IntPtr = New System.IntPtr Dim cycle_cb_fn As UFNcgroup.CycleCbFT = New UFNcgroup.CycleCbFT(AddressOf cycle_cb) ' Get the Program View's Root theUfSession.Setup.AskProgramRoot(setupTag, programRootTag) If programRootTag <> 0 Then 'Cycle throught the Program and find every object theUfSession.Ncgroup.CycleMembers(programRootTag, cycle_cb_fn, ptr) End If End If End If End Sub 'This is the fucntion that is called on every object encountered in the cycling Function cycle_cb(ByVal camObjectTag As Tag, ByVal ptr As IntPtr) As Boolean Dim camObject As NXObject = NXObjectManager.Get(camObjectTag) Dim WorkPart As Part = TheSession.Parts.Work 'Check if the object is an Operation If TypeOf camObject Is CAM.Operation Then Dim operationType As Integer Dim operationSubtype As Integer 'Get the type and subtype of the operation theUFSession.Obj.AskTypeAndSubtype(camObjectTag, operationType, operationSubtype) 'Dim operationBuilder As CAM.OperationBuilder Dim operationBuilder As CAM.SurfaceContourBuilder If operationSubtype = 210 Then ' This is a Surface Contouring Operation so create a Builder operationBuilder = workPart.CAMSetup.CAMOperationCollection.CreateSurfaceContourBuilder(camObject) ElseIf operationSubtype = 211 Then ' This is a Variable Contour Operation so create a Builder operationBuilder = workPart.CAMSetup.CAMOperationCollection.CreateSurfaceContourBuilder(camObject) End If ' Check if there is a valid Builder If operationBuilder IsNot Nothing Then ' Turn off smoothing operationBuilder.NonCuttingBuilder.SmoothingOption = CAM.NcmScBuilder.SmoothingOptions.Off 'Commit the change to the operation( this is the equivalent of OK'ing the operation dialog ) operationBuilder.Commit() 'Destroy the builder its job is done(cleanup memory) operationBuilder.Destroy() End If End If Return True End Function End Module
Imports System.IO Imports Aspose.Tasks Imports Aspose.Tasks.Saving ' 'This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Tasks for .NET API reference 'when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information. 'If you do not wish to use NuGet, you can manually download Aspose.Tasks for .NET API from http://www.aspose.com/downloads, 'install it and then add its reference to this project. For any issues, questions or suggestions 'please feel free to contact us using http://www.aspose.com/community/forums/default.aspx ' Namespace ConvertingProjectData Public Class SaveToMultiplePDFFiles Public Shared Sub Run() ' The path to the documents directory. Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName) ' ExStart:SaveToMultiplePDFFiles Dim project As New Project(dataDir + "Software Development Plan.mpp") Dim saveOptions As New PdfSaveOptions() saveOptions.SaveToSeparateFiles = True saveOptions.Pages = New List(Of Integer)() saveOptions.Pages.Add(1) saveOptions.Pages.Add(4) project.Save(dataDir + "SaveToMultiplePDFFiles_out.pdf", saveOptions) ' ExEnd:SaveToMultiplePDFFiles End Sub End Class End Namespace
Imports System.Data Imports Microsoft.Data.Odbc Public Class NWDSAOdbcFactory : Inherits NWDSAAbstractFactory Private m_conODBC As New OdbcConnection() Protected Overrides Sub Finalize() If Not (m_conODBC.State = ConnectionState.Closed) Or _ Not (m_conODBC.State = ConnectionState.Broken) Then m_conODBC.Close() End If MyBase.Finalize() End Sub Public Overrides Function ExecuteDataReader(ByRef Request As NWDSARequest) As NWDSADataReader ' Returns a NWDSADataReader object, which wraps an object of type IDataReader ' Uses ODBC .NET data provider, hence the wrapped object is a OdbcDataReader object ' A OdbcDataReader object is a read-only, forward-only data stream. ' NOTE: DataReaders won't be used in queries that perform transactions. Dim sConnectStr As String Dim cmdODBC As New OdbcCommand() Dim prmODBC As OdbcParameter Dim oParam As NWDSARequest.Parameter Dim colODBCParams As OdbcParameterCollection Dim drODBC As OdbcDataReader Dim oDataReaderODBC As New NWDSAOdbcDataReader() Try m_conODBC.ConnectionString = g_ConnStrings.GetInstance.GetConnectStringByRole(Request.Role) ' open connection, and begin to set properties of command m_conODBC.Open() cmdODBC.Connection = m_conODBC cmdODBC.CommandType = Request.CommandType ' Check for parameters, and set Command property accordingly Dim iCounter As Integer If Request.Parameters.Count > 0 Then 'ODBC data provider requires something of the form "{call CustOrdersOrders(?, ?, ?)}" for parameterised stored procedures 'see http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q309486 cmdODBC.CommandText = "{call " & Request.Command & "(" For iCounter = 1 To Request.Parameters.Count cmdODBC.CommandText &= "?" If (iCounter < Request.Parameters.Count) Then cmdODBC.CommandText &= ", " Next cmdODBC.CommandText &= ")}" Else cmdODBC.CommandText = Request.Command End If ' Add parameters to Parameters property if they exist If Request.Parameters.Count > 0 Then For Each oParam In Request.Parameters prmODBC = cmdODBC.Parameters.Add(oParam.ParamName, oParam.ParamValue) Next End If drODBC = cmdODBC.ExecuteReader() oDataReaderODBC.ReturnedDataReader = drODBC Return oDataReaderODBC Catch exODBC As OdbcException Debug.WriteLine(exODBC.Message) Request.Exception = exODBC Catch ex As Exception Debug.WriteLine(ex.Message) Request.Exception = ex Finally End Try End Function Public Overrides Function ExecuteDataSet(ByRef Request As NWDSARequest) As NWDSADataSet ' Returns a NWDSADataSet object, which wraps an object of type DataSet ' Uses ODBC .NET data provider if a data provider is necessary ' - hence uses a OdbcDataAdapter to fill the DataSet Dim sConnectStr As String Dim conODBC As New OdbcConnection() Dim cmdODBC As New OdbcCommand() Dim prmODBC As OdbcParameter Dim oParam As NWDSARequest.Parameter Dim colODBCParams As OdbcParameterCollection Dim daODBC As OdbcDataAdapter Dim oDataSetODBC As New NWDSAOdbcDataSet() Dim tranODBC As OdbcTransaction Try conODBC.ConnectionString = g_ConnStrings.GetInstance.GetConnectStringByRole(Request.Role) ' open connection, and begin to set properties of command conODBC.Open() cmdODBC.Connection = conODBC cmdODBC.CommandType = Request.CommandType ' Check for parameters, and set Command property accordingly Dim iCounter As Integer If Request.Parameters.Count > 0 Then 'ODBC data provider requires something of the form "{call CustOrdersOrders(?, ?, ?)}" for parameterised stored procedures 'see http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q309486 cmdODBC.CommandText = "{call " & Request.Command & "(" For iCounter = 1 To Request.Parameters.Count cmdODBC.CommandText &= "?" If (iCounter < Request.Parameters.Count) Then cmdODBC.CommandText &= ", " Next cmdODBC.CommandText &= ")}" Debug.WriteLine("cmdODBC.CommandText = """ & cmdODBC.CommandText & """") Else cmdODBC.CommandText = Request.Command End If ' Add parameters to Parameters property if they exist If Request.Parameters.Count > 0 Then For Each oParam In Request.Parameters prmODBC = cmdODBC.Parameters.Add(oParam.ParamName, oParam.ParamValue) Next End If If Request.Transactional Then tranODBC = conODBC.BeginTransaction() End If daODBC = New OdbcDataAdapter(cmdODBC) daODBC.Fill(oDataSetODBC.ReturnedDataSet) Return oDataSetODBC Catch exODBC As OdbcException Debug.WriteLine(exODBC.Message) Request.Exception = exODBC If Request.Transactional Then tranODBC.Rollback() End If Catch ex As Exception Debug.WriteLine(ex.Message) Request.Exception = ex If Request.Transactional Then tranODBC.Rollback() End If Finally If Request.Transactional Then tranODBC.Commit() End If If conODBC.State = ConnectionState.Open Then conODBC.Close() End If End Try End Function End Class
Imports System.Linq Imports DevExpress.Data.Filtering Imports DevExpress.Xpo Imports DevExpress.Persistent.Base ''' <summary> ''' Represents a user that is allowed to use the DMS. Every filesystem user is allocated their own home directory for their own files, and may be granted access to other directories within the DMS. ''' </summary> ''' <remarks></remarks> <Persistent("File.UserGroup"), DefaultClassOptions(), ImageName("BO_Department")> Public Class FsUserGroup Inherits XPObject Public Shared Function CurrentUsersGroup(ses As Session) As FsUserGroup Try Dim cu = CType(DevExpress.ExpressApp.SecuritySystem.CurrentUser, IHaveHomeDirectory).DMSUser Return ses.FindObject(Of FsUser)(CriteriaOperator.Parse("Oid=?", cu.Oid)).UserGroups(0) Catch ex As Exception Return Nothing End Try End Function #Region "Constructors" Public Sub New() End Sub ''' <summary> ''' Default constructor ''' </summary> ''' <param name="session"></param> ''' <remarks></remarks> Public Sub New(ByVal session As Session) MyBase.New(session) End Sub ''' <summary> ''' Called after a new object is created ''' </summary> ''' <remarks></remarks> Public Overrides Sub AfterConstruction() MyBase.AfterConstruction() End Sub #End Region #Region "Private Fields" ' Fields... Private _name As String #End Region #Region "Public Properties" ''' <summary> ''' The name of this group ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <Size(64)> Public Property GroupName As String Get Return _name End Get Set(ByVal Value As String) SetPropertyValue("GroupName", _name, Value) End Set End Property ''' <summary> ''' A collection of all users in this group ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <Association("FsGroup-FsUsers")> Public ReadOnly Property GroupUsers As XPCollection(Of FsUser) Get Return GetCollection(Of FsUser)("GroupUsers") End Get End Property #End Region End Class
Public Class EditEventForm Private DB As New DBAccess Private Const SPRING As String = "Spring" Private Const SUMMER As String = "Fall" Private Const FALL As String = "Summer" Private Const NOT_CORRECT_INPUT As String = "Not correct input" Private Const CORRECT_INPUT As String = "correct" Private Sub CancelButton_Click(sender As Object, e As EventArgs) Handles CancelButton.Click Me.Close() End Sub Private Sub PopulateTextBoxes() Dim semester As String DB.AddParam("id", EventForm.EventIdTextBox.Text) DB.ExecuteQuery("select * from event where id=?") If DB.Exception <> String.Empty Then MessageBox.Show(DB.Exception) Exit Sub End If EventIdTextBox.Text = DB.DBDataTable(0)!id GameNameTextBox.Text = DB.DBDataTable(0)!name GameDescriptionRichTextBox.Text = DB.DBDataTable(0)!description GameDateTimePicker.Value = DB.DBDataTable(0)!date semester = DB.DBDataTable(0)!semester If semester = SPRING Then SemesterComboBox.SelectedIndex = 0 ElseIf semester = SUMMER Then SemesterComboBox.SelectedIndex = 2 ElseIf semester = FALL Then SemesterComboBox.SelectedIndex = 1 End If End Sub Private Sub EditEventForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load SetFieldsEditable(False) PopulateTextBoxes() End Sub Private Sub SetFieldsEditable(b As Boolean) GameDateTimePicker.Enabled = b GameNameTextBox.Enabled = b GameDescriptionRichTextBox.Enabled = b SemesterComboBox.Enabled = b End Sub Private Function validateInput() If String.IsNullOrWhiteSpace(GameNameTextBox.Text) Then Return NOT_CORRECT_INPUT ElseIf String.IsNullOrWhiteSpace(GameDescriptionRichTextBox.Text) Then Return NOT_CORRECT_INPUT Else Return CORRECT_INPUT End If End Function Private Sub EditSaveButton_Click(sender As Object, e As EventArgs) Handles EditSaveButton.Click Dim val As String If EditSaveButton.Text = "&Edit" Then SetFieldsEditable(True) EditSaveButton.Text = "&Save" Else SetFieldsEditable(False) EditSaveButton.Text = "&Edit" val = validateInput() If val <> CORRECT_INPUT Then MessageBox.Show(val) Exit Sub End If DB.AddParam("name", GameNameTextBox.Text) DB.AddParam("descrip", GameDescriptionRichTextBox.Text) DB.AddParam("date", GameDateTimePicker.Value) DB.AddParam("sem", SemesterComboBox.Text) DB.AddParam("id", EventIdTextBox.Text) DB.ExecuteQuery("update event set name=?, description=?,date=?,semester=? where id=?") If DB.Exception <> String.Empty Then MessageBox.Show(DB.Exception) Exit Sub Else MessageBox.Show("Successfully updated") Me.Close() End If End If End Sub End Class
Public Class PayStub #Region "CONSTANTS" Private Const FEDERAL_TAX_RATE As Decimal = 0.052 Private Const STATE_TAX_RATE As Decimal = 0.008 Private Const SOCAIL_SECURITY_TAX_RATE As Decimal = 0.062 Private Const MEDICARE_TAX_RATE As Decimal = 0.01449 #End Region #Region "PROPERTIES" ' Pay Period Start Date Private m_PayPeriodStartDate As Date Public ReadOnly Property PayPeriodStartDate() As Date Get Return m_PayPeriodStartDate End Get End Property ' Pay Period Length Private m_PayPeriodLength As Integer Public ReadOnly Property PayPeriodLength() As Integer Get Return m_PayPeriodLength End Get End Property ' Pay Rate Private m_PayRate As Decimal Public ReadOnly Property PayRate() As Decimal Get Return m_PayRate End Get End Property ' Total Minutes Worked Private m_TotalMinutesWorked As Decimal Public ReadOnly Property TotalMinutesWorked() As Decimal Get Return m_TotalMinutesWorked End Get End Property ' Additional Withholdings Private m_AdditionalWithholdings As AdditionalWithholding() Public Property AdditionalWithholdings() As AdditionalWithholding() Get Return m_AdditionalWithholdings End Get Set(ByVal value As AdditionalWithholding()) m_AdditionalWithholdings = value End Set End Property ' Regular Hours Public ReadOnly Property RegularHours() As Decimal Get Return ConvertMinutesToHours(GetRegularMinutes()) End Get End Property ' Regular Minutes Public ReadOnly Property RegularMinutes() As Decimal Get Return GetLeftOverMinutes(GetRegularMinutes()) End Get End Property ' Overtime Hours Public ReadOnly Property OvertimeHours() As Decimal Get Return ConvertMinutesToHours(GetOvertimeMinutes()) End Get End Property ' Overtime Minutes Public ReadOnly Property OvertimeMinutes() As Decimal Get Return GetLeftOverMinutes(GetOvertimeMinutes()) End Get End Property ' Overtime Pay Rate Public ReadOnly Property OvertimePayRate() As Decimal Get Return GetOvertimePayRate() End Get End Property ' Pay Period End Date Public ReadOnly Property PayPeriodEndDate() As Date Get Return GetPayPeriodEndDate() End Get End Property ' Pay Date Public ReadOnly Property PayDate() As Date Get Return GetPayDate() End Get End Property ' Regular Pay Public ReadOnly Property RegularPay() As Decimal Get Return GetRegularPay() End Get End Property ' Overtime Pay Public ReadOnly Property OvertimePay() As Decimal Get Return GetOverTimePay() End Get End Property ' Federal Withholding Public ReadOnly Property FederalWithholding() As Decimal Get Return GetTaxWithholdingAmount(FEDERAL_TAX_RATE) End Get End Property ' State Withholding Public ReadOnly Property StateWithholding() As Decimal Get Return GetTaxWithholdingAmount(STATE_TAX_RATE) End Get End Property ' Social Security Withholding Public ReadOnly Property SocialSecurityWithholding() As Decimal Get Return GetTaxWithholdingAmount(SOCAIL_SECURITY_TAX_RATE) End Get End Property ' Medicare Withholding Public ReadOnly Property MedicareWithholding() As Decimal Get Return GetTaxWithholdingAmount(MEDICARE_TAX_RATE) End Get End Property ' Total Tax Withholdings Public ReadOnly Property TotalTaxWithholdings() As Integer Get Return GetTotalTaxWithholdingsAmount() End Get End Property ' Total Additional Withholdings Public ReadOnly Property TotalAdditionalWithholdings() As Decimal Get Return GetTotalAdditionalWithholdingsAmount() End Get End Property ' Gross Income Public ReadOnly Property GrossIncome() As Decimal Get Return GetGrossIncome() End Get End Property ' Net Income Public ReadOnly Property NetIncome() As Decimal Get Return GetNetIncome() End Get End Property #End Region ' Initializer Public Sub New(payPeriodStartDate As Date, payPeriodLength As Double, payRate As Decimal, totalMinutesWorked As Decimal, additionalWitholdings As AdditionalWithholding()) With Me .m_PayPeriodStartDate = payPeriodStartDate .m_PayPeriodLength = payPeriodLength .m_PayRate = payRate .m_AdditionalWithholdings = additionalWitholdings .m_TotalMinutesWorked = totalMinutesWorked End With End Sub ' Get Regular Minutes Private Function GetRegularMinutes() As Decimal If IsOverTime(Me.TotalMinutesWorked) Then Return 2400 End If Return Me.TotalMinutesWorked End Function ' Get Overtime Minutes Private Function GetOvertimeMinutes() As Decimal If IsOverTime(Me.TotalMinutesWorked) Then Return Math.Round(Me.TotalMinutesWorked - 2400, 2) End If Return 0.0 End Function ' Get Left Over Minutes Public Shared Function GetLeftOverMinutes(ByVal minutes As Decimal) As Decimal Dim leftOverMinutes As Integer Math.DivRem(Convert.ToInt16(minutes), 60, leftOverMinutes) Return Convert.ToDecimal(leftOverMinutes) End Function ' Is Over Time Public Shared Function IsOverTime(ByVal minutes As Decimal) As Boolean If minutes > 2400 Then Return True End If Return False End Function ' Convert Minutes To Hours Public Shared Function ConvertMinutesToHours(ByVal minutes As Decimal) As Decimal Return Convert.ToDecimal(Math.Floor(minutes / 60)) End Function #Region "PRIVATE METHODS" ' Get Pay Period End Date Private Function GetPayPeriodEndDate() As Date Return Me.PayPeriodStartDate.AddDays(Me.PayPeriodLength - 1) End Function ' Get Pay Date Private Function GetPayDate() As Date Return Me.PayPeriodStartDate.AddDays(Me.PayPeriodLength + 1).Date End Function ' Get Gross Income Private Function GetGrossIncome() As Decimal Return Math.Round(Me.RegularPay + Me.OvertimePay, 2) End Function ' Get Net Income Private Function GetNetIncome() As Decimal Return Math.Round(Me.GrossIncome - Me.TotalTaxWithholdings - Me.TotalAdditionalWithholdings, 2) End Function ' Get Total Additional Withholdings Amount Private Function GetTotalAdditionalWithholdingsAmount() As Decimal Dim totalAmount As Decimal = 0.0 For i = 0 To Me.AdditionalWithholdings.Length - 1 totalAmount += AdditionalWithholdings(i).Amount Next Return Math.Round(totalAmount, 2) End Function ' Get Tax Withholding Amount Private Function GetTaxWithholdingAmount(ByVal taxRate As Decimal) As Decimal Return Math.Round(Me.GrossIncome * taxRate, 2) End Function ' Get Total Tax Withholdings Amount Private Function GetTotalTaxWithholdingsAmount() As Decimal Return Math.Round(Me.FederalWithholding + Me.StateWithholding + Me.SocialSecurityWithholding + Me.MedicareWithholding, 2) End Function ' Get Regular Pay Private Function GetRegularPay() As Decimal Return Math.Round((Me.RegularHours + ConvertMinutesToDecimal(Me.RegularMinutes)) * Me.PayRate, 2) End Function ' Get Overtime Pay Private Function GetOvertimePay() As Decimal Return Math.Round((Me.OvertimeHours + ConvertMinutesToDecimal(Me.OvertimeMinutes)) * Me.OvertimePayRate, 2) End Function ' Get Overtime Pay Rate Private Function GetOvertimePayRate() As Decimal Return Math.Round(Me.PayRate * 1.5, 2) End Function ' Convert Minutes To Decimal Public Shared Function ConvertMinutesToDecimal(ByVal minutes As Decimal) As Decimal Return Math.Round(minutes / 60, 2) End Function #End Region End Class
Imports System Public Module Program ' esta variable es accesible en cualquier lugar de la solución Public publica As String Sub Main() Dim dato1, dato2, resultado As Integer dato1 = 20 dato2 = 10 ' suma resultado = dato1 + dato2 ' el método writeline reemplaza en la cadena a un valor entre llaves por el número de parámetro respectivo Console.WriteLine("{0} + {1} = {2}", dato1, dato2, resultado) ' resta resultado = dato1 - dato2 Console.WriteLine("{0} - {1} = {2}", dato1, dato2, resultado) ' multiplicación resultado = dato1 * dato2 Console.WriteLine("{0} * {1} = {2}", dato1, dato2, resultado) ' división resultado = dato1 / dato2 Console.WriteLine("{0} / {1} = {2}", dato1, dato2, resultado) Dim a As Integer = 5 Dim b As Single = 10 Dim c As Byte = 2 Dim x As Double x = a + b * c / a Console.WriteLine("{0} + {1} * {2} / {0} = " & x, a, b, c) ' Acumulador Console.Write("{0} + {1} = ", x, b) x += b Console.WriteLine(x) ' booleano Dim verdadero As Boolean = True Dim falso As Boolean = False Console.WriteLine("valor 1 {0} y valor 2 {1}: " _ & (verdadero And falso), verdadero, falso) Console.WriteLine("valor 1 Verdadero y valor 2 Falso: " _ & (verdadero And falso)) ' resto Console.WriteLine("{0} mod {1}: " & (a Mod b), a, b) Console.WriteLine(Convert.ToByte("5")) ' concatenacion Dim numero As Integer = 6 Dim cadena As String = "pepe" 'concatenaciones ' con converción explícita Console.WriteLine(cadena + " " + Convert.ToString(numero)) ' con conversión implícita Console.WriteLine(cadena & " " & numero) End Sub End Module
Public Class Form1 Implements PIEHid32Net.PIEDataHandler Implements PIEHid32Net.PIEErrorHandler Dim devices() As PIEHid32Net.PIEDevice Dim selecteddevice As Integer Dim cbotodevice(127) As Integer 'max # of devices = 128 Dim wdata() As Byte = New Byte() {} 'write data buffer ' This delegate enables asynchronous calls for setting ' the text property on a TextBox control. Delegate Sub SetTextCallback(ByVal [text] As String) Delegate Sub SetIntCallback(ByVal [text] As Integer) Dim c As Control Dim mouseport As Integer Dim hidtochar(255) As String Public Sub HandlePIEHidData(ByVal data() As Byte, ByVal sourceDevice As PIEHid32Net.PIEDevice, ByVal perror As Integer) Implements PIEHid32Net.PIEDataHandler.HandlePIEHidData 'data callback If sourceDevice.Pid = devices(selecteddevice).Pid Then Dim output As String output = "Callback: " + sourceDevice.Pid.ToString + ", ID: " + selecteddevice.ToString + ", data=" For i As Integer = 0 To 5 output = output + data(i).ToString + " " Next 'Use thread-safe calls to windows forms controls SetListBox(output) 'mouse data Dim mousedata As String If (data(1) = 4 Or data(1) = 8) Then If (data(1) = 4) Then mouseport = 0 'mouse on Device 2 If (data(1) = 8) Then mouseport = 1 'mouse on Device 1 mousedata = "X: " + data(3).ToString() + " Y: " + data(4).ToString() + " " If (data(2) And 1) Then mousedata = mousedata + "Left Click " End If If (data(2) And 2) Then mousedata = mousedata + "Right Click " End If If (data(2) And 4) Then mousedata = mousedata + "Center Click " End If c = LblMouse SetText(mousedata) If (data(5) = 1) Then SetScrollBar(-10) ElseIf (data(5) = 255) Then SetScrollBar(10) End If End If 'keyboard data Dim keysdown As String = "" If (data(1) = 1 Or data(1) = 5) Then For i As Integer = 2 To 5 keysdown = keysdown + hidtochar(data(i)) + " " Next c = LblKeys SetText(keysdown) End If End If End Sub Public Sub HandlePIEHidError(ByVal sourceDevice As PIEHid32Net.PIEDevice, ByVal perror As Integer) Implements PIEHid32Net.PIEErrorHandler.HandlePIEHidError 'error callback Dim output As String output = "Error: " + perror.ToString c = LblStatus SetText(output) Beep() End Sub Public Sub SetListBox(ByVal [text] As String) ' InvokeRequired required compares the thread ID of the ' calling thread to the thread ID of the creating thread. ' If these threads are different, it returns true. If Me.ListBox1.InvokeRequired Then Dim d As New SetTextCallback(AddressOf SetListBox) Me.Invoke(d, New Object() {[text]}) Else Me.ListBox1.Items.Add(text) Me.ListBox1.SelectedIndex = Me.ListBox1.Items.Count - 1 End If End Sub Public Sub SetText(ByVal [text] As String) ' InvokeRequired required compares the thread ID of the ' calling thread to the thread ID of the creating thread. ' If these threads are different, it returns true. If Me.c.InvokeRequired Then Dim d As New SetTextCallback(AddressOf SetText) Me.Invoke(d, New Object() {[text]}) Else Me.c.Text = text End If End Sub Public Sub SetScrollBar(ByVal [text] As Integer) ' InvokeRequired required compares the thread ID of the ' calling thread to the thread ID of the creating thread. ' If these threads are different, it returns true. If Me.VScrollBar1.InvokeRequired Then Dim d As New SetIntCallback(AddressOf SetScrollBar) Me.Invoke(d, New Object() {[text]}) Else Me.VScrollBar1.Value = Me.VScrollBar1.Value + text End If End Sub Private Sub BtnEnumerate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnEnumerate.Click 'do this first to get the devices connected CboDevices.Items.Clear() selecteddevice = -1 'means no device is selected devices = PIEHid32Net.PIEDevice.EnumeratePIE() If devices.Length = 0 Then LblStatus.Text = "No Devices Found" Else Dim cbocount As Integer = 0 For i As Integer = 0 To devices.Length - 1 If devices(i).HidUsagePage = 12 Then Select Case devices(i).Pid Case 525 CboDevices.Items.Add("PS2 Host Emulator (" + devices(i).Pid.ToString + "): " + i.ToString) cbotodevice(cbocount) = i cbocount = cbocount + 1 Case 514 CboDevices.Items.Add("PS2 Host Emulator (" + devices(i).Pid.ToString + "): " + i.ToString) cbotodevice(cbocount) = i cbocount = cbocount + 1 Case 515 CboDevices.Items.Add("PS2 Host Emulator (" + devices(i).Pid.ToString + "): " + i.ToString) cbotodevice(cbocount) = i cbocount = cbocount + 1 Case Else CboDevices.Items.Add("Unknown Device (" + devices(i).Pid.ToString + "): " + i.ToString) cbotodevice(cbocount) = i cbocount = cbocount + 1 End Select Dim result As Integer = devices(i).SetupInterface() If result <> 0 Then LblStatus.Text = "Failed SetupInterface on device: " + i.ToString Else LblStatus.Text = "Success SetupInterface" End If End If Next End If If CboDevices.Items.Count > 0 Then CboDevices.SelectedIndex = 0 selecteddevice = cbotodevice(CboDevices.SelectedIndex) ReDim wdata(devices(selecteddevice).WriteLength - 1) 'initialize length of write buffer End If End Sub Private Sub Form1_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed 'close devices For i As Integer = 0 To CboDevices.Items.Count - 1 devices(cbotodevice(i)).CloseInterface() Next System.Environment.Exit(0) End Sub Private Sub BtnCallback_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnCallback.Click 'setup devices for data and error callbacks If CboDevices.SelectedIndex <> -1 Then For i As Integer = 0 To CboDevices.Items.Count - 1 devices(cbotodevice(i)).SetDataCallback(Me) devices(cbotodevice(i)).SetErrorCallback(Me) devices(cbotodevice(i)).callNever = False Next selecteddevice = cbotodevice(CboDevices.SelectedIndex) End If End Sub Private Sub CboDevices_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CboDevices.SelectedIndexChanged 'update selecteddevice with that chosen and redim the write array selecteddevice = cbotodevice(CboDevices.SelectedIndex) ReDim wdata(devices(selecteddevice).WriteLength - 1) 'initialize length of write buffer End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click ListBox1.Items.Clear() End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load selecteddevice = -1 For i As Integer = 0 To 255 hidtochar(i) = "" Next hidtochar(4) = "a" hidtochar(5) = "b" hidtochar(6) = "c" hidtochar(7) = "d" hidtochar(8) = "e" hidtochar(9) = "f" hidtochar(10) = "g" hidtochar(11) = "h" hidtochar(12) = "i" hidtochar(13) = "j" hidtochar(14) = "k" hidtochar(15) = "l" hidtochar(16) = "m" hidtochar(17) = "n" hidtochar(18) = "o" hidtochar(19) = "p" hidtochar(20) = "q" hidtochar(21) = "r" hidtochar(22) = "s" hidtochar(23) = "t" hidtochar(24) = "u" hidtochar(25) = "v" hidtochar(26) = "w" hidtochar(27) = "x" hidtochar(28) = "y" hidtochar(29) = "z" hidtochar(30) = "1" hidtochar(31) = "2" hidtochar(32) = "3" hidtochar(33) = "4" hidtochar(34) = "5" hidtochar(35) = "6" hidtochar(36) = "7" hidtochar(37) = "8" hidtochar(38) = "9" hidtochar(39) = "0" hidtochar(40) = "Return" hidtochar(41) = "Escape" hidtochar(42) = "Backspace" hidtochar(43) = "Tab" hidtochar(44) = "Space" hidtochar(45) = "-_" hidtochar(46) = "=+" hidtochar(47) = "[{" hidtochar(48) = "]}" hidtochar(49) = "'\'" hidtochar(50) = "Europe 1" hidtochar(51) = ":" hidtochar(52) = "'" hidtochar(53) = "`~" hidtochar(54) = ",<" hidtochar(55) = ".>" hidtochar(56) = "/?" hidtochar(57) = "Capslock" hidtochar(58) = "F1" hidtochar(59) = "F2" hidtochar(60) = "F3" hidtochar(61) = "F4" hidtochar(62) = "F5" hidtochar(63) = "F6" hidtochar(64) = "F7" hidtochar(65) = "F8" hidtochar(66) = "F9" hidtochar(67) = "F10" hidtochar(68) = "F11" hidtochar(69) = "F12" hidtochar(70) = "Print Screen" hidtochar(71) = "Scroll Lock" hidtochar(72) = "Break" hidtochar(73) = "Insert" hidtochar(74) = "Home" hidtochar(75) = "Page Up" hidtochar(76) = "Delete" hidtochar(77) = "End" hidtochar(78) = "Page Down" hidtochar(79) = "Right Arrow" hidtochar(80) = "Left Arrow" hidtochar(81) = "Down Arrow" hidtochar(82) = "Up Arrow" hidtochar(83) = "Num Lock" hidtochar(84) = "Keypad /" hidtochar(85) = "Keypad *" hidtochar(86) = "Keypad -" hidtochar(87) = "Keypad +" hidtochar(88) = "Keypad Enter" hidtochar(89) = "Keypad 1 End" hidtochar(90) = "Keypad 2 Down" hidtochar(91) = "Keypad 3 PageDn" hidtochar(92) = "Keypad 4 Left" hidtochar(93) = "Keypad 5" hidtochar(94) = "Keypad 6 Right" hidtochar(95) = "Keypad 7 Home" hidtochar(96) = "Keypad 8 Up" hidtochar(97) = "Keypad 9 PageUp" hidtochar(98) = "Keypad 0 Insert" hidtochar(99) = "Keypad . Delete" hidtochar(100) = "Europe 2" hidtochar(101) = "App" hidtochar(102) = "Pause/Break" 'unique to PS2 Host Emulator hidtochar(103) = "Keypad =" hidtochar(104) = "F13" hidtochar(105) = "F14" hidtochar(106) = "F15" hidtochar(107) = "F16" hidtochar(108) = "F17" hidtochar(109) = "F18" hidtochar(110) = "F19" hidtochar(111) = "F20" hidtochar(112) = "F21" hidtochar(113) = "F22" hidtochar(114) = "F23" hidtochar(115) = "F24" hidtochar(116) = "Keyboard Execute" hidtochar(117) = "Keyboard Help" hidtochar(118) = "Keyboard Menu" hidtochar(119) = "Keyboard Select" hidtochar(120) = "Keyboard Stop" hidtochar(121) = "Keyboard Again" hidtochar(122) = "Keyboard Undo" hidtochar(123) = "Keyboard Cut" hidtochar(124) = "Keyboard Copy" hidtochar(125) = "Keyboard Paste" hidtochar(126) = "Keyboard Find" hidtochar(127) = "Keyboard Mute" hidtochar(128) = "Keyboard Volume Up" hidtochar(129) = "Keyboard Volume Dn" hidtochar(130) = "Keyboard Locking Caps Lock" hidtochar(131) = "Keyboard Locking Num Lock" hidtochar(132) = "Keyboard Locking Scroll Lock" hidtochar(133) = "Keyboard ," hidtochar(134) = "Keyboard Equal Sign" hidtochar(135) = "Keyboard Int'l 1" hidtochar(136) = "Keyboard Int'l 2" hidtochar(137) = "Keyboard Int'l 2 Yen" hidtochar(138) = "Keyboard Int'l 4" hidtochar(139) = "Keyboard Int'l 5" hidtochar(140) = "Keyboard Int'l 6" hidtochar(141) = "Keyboard Int'l 7" hidtochar(142) = "Keyboard Int'l 8" hidtochar(143) = "Keyboard Int'l 9" hidtochar(144) = "Keyboard Lang 1" hidtochar(145) = "Keyboard Lang 2" hidtochar(146) = "Keyboard Lang 3" hidtochar(147) = "Keyboard Lang 4" hidtochar(148) = "Keyboard Lang 5" hidtochar(149) = "Keyboard Lang 6" hidtochar(150) = "Keyboard Lang 7" hidtochar(151) = "Keyboard Lang 8" hidtochar(152) = "Keyboard Lang 9" 'note modifier keys do not follow the HID code standard hidtochar(160) = "Left Control" hidtochar(161) = "Left Shift" hidtochar(162) = "Left Alt" hidtochar(163) = "Left GUI" hidtochar(164) = "Right Control" hidtochar(165) = "Right Shift" hidtochar(166) = "Right Alt" hidtochar(167) = "Right GUI" End Sub Private Sub BtnDefault_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnDefault.Click 'This code is for returning the mouse messages to the default setting. If selecteddevice <> -1 Then Dim portdes As String = "Device 2" If (mouseport = 1) Then portdes = "Device 1" End If Dim msg As String = "Is mouse plugged into " + portdes + "? If so click Yes. To change to the other port click No. To do nothing click Cancel." Dim dlgresult As DialogResult = MessageBox.Show(msg, "PS2 Host Emulator Demo", MessageBoxButtons.YesNoCancel) If (dlgresult = Windows.Forms.DialogResult.Cancel) Then Return ElseIf (dlgresult = Windows.Forms.DialogResult.No) Then mouseport = (mouseport) ^ 1 End If For i As Integer = 0 To devices(selecteddevice).WriteLength - 1 wdata(i) = 0 Next wdata(1) = mouseport wdata(2) = &HF3 Dim result As Integer result = 404 While (result = 404) result = devices(selecteddevice).WriteData(wdata) End While If result <> 0 Then LblStatus.Text = "1st Write Fail: " + result.ToString Else LblStatus.Text = "Write Success" End If System.Threading.Thread.Sleep(50) wdata(1) = mouseport wdata(2) = &H3C result = 404 While (result = 404) result = devices(selecteddevice).WriteData(wdata) End While If result <> 0 Then LblStatus.Text = "2nd Write Fail: " + result.ToString Else LblStatus.Text = "Write Success" End If End If End Sub Private Sub BtnSlow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSlow.Click 'This code is for slowing down the mouse messages if there is too much "lag" . If selecteddevice <> -1 Then Dim portdes As String = "Device 2" If (mouseport = 1) Then portdes = "Device 1" End If Dim msg As String = "Is mouse plugged into " + portdes + "? If so click Yes. To change to the other port click No. To do nothing click Cancel." Dim dlgresult As DialogResult = MessageBox.Show(msg, "PS2 Host Emulator Demo", MessageBoxButtons.YesNoCancel) If (dlgresult = Windows.Forms.DialogResult.Cancel) Then Return ElseIf (dlgresult = Windows.Forms.DialogResult.No) Then mouseport = (mouseport) ^ 1 End If For i As Integer = 0 To devices(selecteddevice).WriteLength - 1 wdata(i) = 0 Next wdata(1) = mouseport wdata(2) = &HF3 Dim result As Integer result = 404 While (result = 404) result = devices(selecteddevice).WriteData(wdata) End While If result <> 0 Then LblStatus.Text = "1st Write Fail: " + result.ToString Else LblStatus.Text = "Write Success" End If System.Threading.Thread.Sleep(50) wdata(1) = mouseport wdata(2) = &H14 result = 404 While (result = 404) result = devices(selecteddevice).WriteData(wdata) End While If result <> 0 Then LblStatus.Text = "2nd Write Fail: " + result.ToString Else LblStatus.Text = "Write Success" End If End If End Sub End Class
Imports System.ServiceProcess Imports System.Diagnostics Imports System.Runtime.Remoting Public Class RemotingService Inherits System.ServiceProcess.ServiceBase Public Shared SVC_NAME As String = ".NET Remoting Sample Service" Private Shared evt As New EventLog("Application") Public Sub New() MyBase.New() Me.ServiceName = SVC_NAME End Sub Shared Sub Main() ' start the service evt.Source = SVC_NAME evt.WriteEntry("Remoting Service initializing") ServiceBase.Run(New RemotingService()) End Sub Protected Overrides Sub OnStart(ByVal args() As String) evt.WriteEntry("Remoting Service started") Dim filename As String = "windowsservice.exe.config" RemotingConfiguration.Configure(filename) End Sub Protected Overrides Sub OnStop() evt.WriteEntry("Remoting Service stopped") End Sub End Class
Public MustInherit Class ISODownloadHelper Public MustOverride ReadOnly Property DownloadName As String Public MustOverride ReadOnly Property DownloadFileName As String Public MustOverride Function GetDownloadURL() As String Public Overridable Sub Download(strToFile As String, wndParent As IWin32Window) DownloadLarge(GetDownloadURL(), strToFile, DownloadName, wndParent) End Sub End Class
Namespace Route4MeSDK.QueryTypes ''' <summary> ''' Parameters for the address(es) geocoding request. ''' </summary> Public NotInheritable Class GeocodingParameters Inherits GenericParameters ''' <summary> ''' List of the addresses as a multiline text. ''' <remarks><para>The addresses are delimited with the newline character.</para> ''' <para>Query parameter.</para></remarks> ''' </summary> <HttpQueryMemberAttribute(Name:="addresses", EmitDefaultValue:=False)> Public Property Addresses As String ''' <summary> ''' Response format (xml, json). ''' Note: used in the forward And reverse geocodings as a url parameter. ''' </summary> <HttpQueryMemberAttribute(Name:="format", EmitDefaultValue:=False)> Public Property Format As String ''' <summary> ''' Response export format. ''' <para>Availbale values: <value> json, xml, csv.</value></para> ''' <remarks><para>Query parameter.</para></remarks> ''' </summary> <HttpQueryMemberAttribute(Name:="strExportFormat", EmitDefaultValue:=False)> Public Property ExportFormat As String ''' <summary> ''' Rapis string data index. ''' <remarks><para>Query parameter.</para></remarks> ''' </summary> <HttpQueryMemberAttribute(Name:="pk", EmitDefaultValue:=False)> Public Property Pk As Integer ''' <summary> ''' Only records from that offset will be considered. ''' <remarks><para>Query parameter.</para></remarks> ''' </summary> <HttpQueryMemberAttribute(Name:="offset", EmitDefaultValue:=False)> Public Property Offset As Integer ''' <summary> ''' Limit the number of records in response. ''' <remarks><para>Query parameter.</para></remarks> ''' </summary> <HttpQueryMemberAttribute(Name:="limit", EmitDefaultValue:=False)> Public Property Limit As Integer ''' <summary> ''' Zipcode. ''' <remarks><para>Query parameter.</para></remarks> ''' </summary> <HttpQueryMemberAttribute(Name:="zipcode", EmitDefaultValue:=False)> Public Property Zipcode As String ''' <summary> ''' House number. ''' <remarks><para>Query parameter.</para></remarks> ''' </summary> <HttpQueryMemberAttribute(Name:="housenumber", EmitDefaultValue:=False)> Public Property Housenumber() As String End Class End Namespace
Public Class Form1 Inherits System.Windows.Forms.Form Dim cmd As New OleDb.OleDbCommand() Dim param As New OleDb.OleDbParameter() Dim conn As New OleDb.OleDbConnection("Provider = Microsoft.Jet.OlEDB.4.0; Data Source = c:\myDataBase.mdb") Dim da As New OleDb.OleDbDataAdapter() Dim ds As New DataSet() #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. Friend WithEvents btnGet As System.Windows.Forms.Button Friend WithEvents btnSave As System.Windows.Forms.Button Friend WithEvents tbImagePath As System.Windows.Forms.TextBox Friend WithEvents tbBrowse As System.Windows.Forms.Button Friend WithEvents ofd As System.Windows.Forms.OpenFileDialog Friend WithEvents cbIDs As System.Windows.Forms.ComboBox Friend WithEvents pb As System.Windows.Forms.PictureBox <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Me.btnGet = New System.Windows.Forms.Button() Me.btnSave = New System.Windows.Forms.Button() Me.tbImagePath = New System.Windows.Forms.TextBox() Me.tbBrowse = New System.Windows.Forms.Button() Me.ofd = New System.Windows.Forms.OpenFileDialog() Me.cbIDs = New System.Windows.Forms.ComboBox() Me.pb = New System.Windows.Forms.PictureBox() Me.SuspendLayout() ' 'btnGet ' Me.btnGet.Location = New System.Drawing.Point(296, 256) Me.btnGet.Name = "btnGet" Me.btnGet.Size = New System.Drawing.Size(75, 24) Me.btnGet.TabIndex = 1 Me.btnGet.Text = "get Image" ' 'btnSave ' Me.btnSave.Location = New System.Drawing.Point(296, 296) Me.btnSave.Name = "btnSave" Me.btnSave.Size = New System.Drawing.Size(75, 24) Me.btnSave.TabIndex = 2 Me.btnSave.Text = "save image" ' 'tbImagePath ' Me.tbImagePath.Location = New System.Drawing.Point(104, 296) Me.tbImagePath.Name = "tbImagePath" Me.tbImagePath.Size = New System.Drawing.Size(184, 20) Me.tbImagePath.TabIndex = 3 Me.tbImagePath.Text = "" ' 'tbBrowse ' Me.tbBrowse.Location = New System.Drawing.Point(24, 296) Me.tbBrowse.Name = "tbBrowse" Me.tbBrowse.Size = New System.Drawing.Size(72, 23) Me.tbBrowse.TabIndex = 4 Me.tbBrowse.Text = "browse" ' 'cbIDs ' Me.cbIDs.Location = New System.Drawing.Point(216, 256) Me.cbIDs.Name = "cbIDs" Me.cbIDs.Size = New System.Drawing.Size(72, 21) Me.cbIDs.TabIndex = 5 ' 'pb ' Me.pb.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D Me.pb.Location = New System.Drawing.Point(16, 24) Me.pb.Name = "pb" Me.pb.Size = New System.Drawing.Size(376, 216) Me.pb.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage Me.pb.TabIndex = 6 Me.pb.TabStop = False ' 'Form1 ' Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.ClientSize = New System.Drawing.Size(408, 342) Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.pb, Me.cbIDs, Me.tbBrowse, Me.tbImagePath, Me.btnSave, Me.btnGet}) Me.Name = "Form1" Me.Text = "Form1" Me.ResumeLayout(False) End Sub #End Region Private Sub tbBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbBrowse.Click ofd.Filter = "Image Files (*.bmp) | *.bmp|JPEG Files (*.jpg)|*.jpg|AllFiles (*.*)|*.*" ofd.FilterIndex = 1 ofd.Title = "pick up a file o open" ofd.CheckFileExists = True ofd.CheckPathExists = True ofd.ValidateNames = True ofd.DereferenceLinks = True ofd.InitialDirectory = "C:\" ofd.RestoreDirectory = True ofd.ShowDialog() tbImagePath.Text = ofd.FileName End Sub Private Sub insertImage() End Sub Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click If (tbImagePath.Text = "") Then MsgBox("Error You must choose Picture") 'End Return End If Dim strFile As String = tbImagePath.Text Dim imageStream As New System.IO.FileStream(strFile, System.IO.FileMode.Open) Dim imageData(imageStream.Length) As Byte imageStream.Read(imageData, 0, imageStream.Length) imageStream.Close() cmd = New OleDb.OleDbCommand("spInsertImage", conn) cmd.CommandType = CommandType.StoredProcedure param = New OleDb.OleDbParameter("@ImageData", OleDb.OleDbType.LongVarBinary) param.Value = imageData cmd.Parameters.Add(param) Try If MessageBox.Show("هل فعلا تريد اضافة هذا السجل", "اضافة سجل", MessageBoxButtons.YesNo, MessageBoxIcon.Warning).CompareTo(DialogResult.No) Then conn.Open() cmd.ExecuteNonQuery() conn.Close() End If Catch ex As Exception conn.Close() MessageBox.Show(ex.Message) End Try Call getIds() tbImagePath.ResetText() End Sub Private Sub btnGet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGet.Click Dim imageData() As Byte Dim memoryStream As System.IO.MemoryStream cmd = New OleDb.OleDbCommand("spGetImage", conn) cmd.CommandType = CommandType.StoredProcedure param = New OleDb.OleDbParameter("@id", OleDb.OleDbType.Integer) param.Value = cbIDs.Text cmd.Parameters.Add(param) Try conn.Open() If Not cmd.ExecuteScalar Is System.DBNull.Value Then imageData = CType(cmd.ExecuteScalar, Byte()) If Not imageData Is Nothing Then memoryStream = New IO.MemoryStream(imageData) pb.Image = New Bitmap(memoryStream) memoryStream.Close() Else pb.Image = Nothing End If Else pb.Image = Nothing End If conn.Close() Catch ex As Exception conn.Close() MessageBox.Show(ex.Message) End Try End Sub Private Sub getIds() ds.Clear() cmd = New OleDb.OleDbCommand("spImageID", conn) cmd.CommandType = CommandType.StoredProcedure Try conn.Open() da.SelectCommand = cmd da.Fill(ds, "Id") conn.Close() cbIDs.DataSource = ds.Tables("Id") cbIDs.DisplayMember = "id" cbIDs.Text = "اختار رقم" Catch ex As Exception conn.Close() MessageBox.Show(ex.Message) End Try End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Call getIds() End Sub End Class
' ' 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-04-27: V1.0.0: Created. ' 2020-10-23: V1.0.1: Removed stray comment. ' 2021-07-12: V1.0.2: Removed unnecessary if statements. ' 2021-07-13: V1.1.0: Simplified blinding. ' ''' <summary> ''' Blinding for byte arrays. ''' </summary> Public NotInheritable Class ByteArrayBlinding #Region "Private constants" '****************************************************************** ' Private constants '****************************************************************** #Region "Constants for exceptions" ' ' Constants for exceptions ' Private Const ERROR_MESSAGE_INVALID_ARRAY As String = "Invalid blinded byte array" Private Const ERROR_MESSAGE_INVALID_MIN_LENGTH As String = "Invalid minimum length" #End Region #Region "Constants for indexing and lengths" ' ' Constants for indexing and lengths ' ' ' These are the indices of the lengths array returned by the GetBalancedBlindingLengths method ' Private Const INDEX_LENGTHS_PREFIX_LENGTH As Integer = 0 Private Const INDEX_LENGTHS_POSTFIX_LENGTH As Integer = 1 Private Const LENGTHS_LENGTH As Integer = 2 ' ' These are the indices of the lengths in the source byte array. ' They have the same value as the previous indices but are logically different. ' Private Const INDEX_SOURCE_PREFIX_LENGTH As Integer = 0 Private Const INDEX_SOURCE_POSTFIX_LENGTH As Integer = 1 Private Const INDEX_SOURCE_PACKED_LENGTH As Integer = 2 ''' <summary> ''' Maximum length of blinding bytes. ''' </summary> Private Const MAX_NORMAL_SINGLE_BLINDING_LENGTH As Integer = 15 ' This needs to be a power of 2 minus 1 so it can be used with an "And" operator ''' <summary> ''' Maximum value of the minimum length. ''' </summary> Private Const MAX_MINIMUM_LENGTH As Integer = 256 #End Region #End Region #Region "Public methods" '****************************************************************** ' Public methods '****************************************************************** ''' <summary> ''' Add blinders to a byte array ''' </summary> ''' <remarks>There may be no blinding, at all! I.e. the "blinded" array is the same as the source array ''' This behaviour is intentional. So an attacker will not known, whether there was blinding, or not.</remarks> ''' <param name="sourceBytes">Source bytes to add blinding to.</param> ''' <param name="minimumLength">Minimum length of blinded array.</param> ''' <returns>Blinded byte array.</returns> ''' <exception cref="ArgumentException">Thrown if minimum length is outside the allowed boundaries.</exception> ''' <exception cref="ArgumentNullException">Thrown if <paramref name="sourceBytes"/> is <c>Nothing</c>.</exception> Public Shared Function BuildBlindedByteArray(sourceBytes As Byte(), minimumLength As Integer) As Byte() RequireNonNull(sourceBytes, NameOf(sourceBytes)) CheckMinimumLength(minimumLength) Dim sourceLength As Integer = sourceBytes.Length Dim packedSourceLength As Byte() = PackedUnsignedInteger.FromInteger(sourceLength) Dim packedSourceLengthLength As Integer = packedSourceLength.Length ' The prefix and postfix blinding lengths need to be calculated. ' .Net does not support multiple return values so we have to take the detour over an integer array. Dim blindingLength As Integer() = GetBalancedBlindingLengths(packedSourceLength.Length, sourceLength, minimumLength) Dim prefixLength As Integer = blindingLength(INDEX_LENGTHS_PREFIX_LENGTH) Dim postfixLength As Integer = blindingLength(INDEX_LENGTHS_POSTFIX_LENGTH) Dim resultLength As Integer = LENGTHS_LENGTH + packedSourceLengthLength + prefixLength + sourceLength + postfixLength Dim result As Byte() = New Byte(0 To resultLength - 1) {} result(0) = CByte(prefixLength) result(1) = CByte(postfixLength) Dim offset As Integer = LENGTHS_LENGTH Array.Copy(packedSourceLength, 0, result, offset, packedSourceLengthLength) ArrayHelper.Clear(packedSourceLength) ' Clear the sensitive packed source length from memory offset += packedSourceLengthLength #Disable Warning IDE0059 ' Unnecessary assignment of a value packedSourceLengthLength = 0 ' This seemingly unnecessary assignment clears the sensitive packed source length length value from memory #Enable Warning IDE0059 ' Unnecessary assignment of a value SecurePseudoRandomNumberGenerator.GetBytes(result, offset, prefixLength) offset += prefixLength #Disable Warning IDE0059 ' Unnecessary assignment of a value prefixLength = 0 ' This seemingly unnecessary assignment clears the sensitive prefix length value from memory #Enable Warning IDE0059 ' Unnecessary assignment of a value Array.Copy(sourceBytes, 0, result, offset, sourceLength) offset += sourceLength #Disable Warning IDE0059 ' Unnecessary assignment of a value sourceLength = 0 ' This seemingly unnecessary assignment clears the sensitive source length value from memory #Enable Warning IDE0059 ' Unnecessary assignment of a value SecurePseudoRandomNumberGenerator.GetBytes(result, offset, postfixLength) #Disable Warning IDE0059 ' Unnecessary assignment of a value postfixLength = 0 ' This seemingly unnecessary assignment clears the sensitive postfix length value from memory #Enable Warning IDE0059 ' Unnecessary assignment of a value Return result End Function ''' <summary> ''' Remove blinders from a byte array. ''' </summary> ''' <param name="sourceBytes">Blinded byte array.</param> ''' <returns>Byte array without blinders.</returns> ''' <exception cref="ArgumentException">Thrown if <paramref name="sourceBytes"/> is not a valid blinded byte array.</exception> ''' <exception cref="ArgumentNullException">Thrown is <paramref name="sourceBytes"/> is <c>Nothing</c>.</exception> Public Shared Function UnBlindByteArray(sourceBytes As Byte()) As Byte() RequireNonNull(sourceBytes, NameOf(sourceBytes)) If sourceBytes.Length > LENGTHS_LENGTH Then Dim packedNumberLength As Integer = PackedUnsignedInteger.GetExpectedLength(sourceBytes, INDEX_SOURCE_PACKED_LENGTH) ' No. of bytes to skip is the blinding prefix length plus the two length bytes plus the source length Dim prefixBlindingLength As Integer = LENGTHS_LENGTH + sourceBytes(INDEX_SOURCE_PREFIX_LENGTH) + packedNumberLength Dim postfixBlindingLength As Integer = sourceBytes(INDEX_SOURCE_POSTFIX_LENGTH) Dim totalBlindingsLength As Integer = prefixBlindingLength + postfixBlindingLength Dim dataLength As Integer = PackedUnsignedInteger.ToInteger(sourceBytes, INDEX_SOURCE_PACKED_LENGTH) ' The largest number in the following addition can only be just over 1,073,741,823 ' This can never overflow into negative values If (totalBlindingsLength + dataLength) <= sourceBytes.Length Then _ Return ArrayHelper.CopyOf(sourceBytes, prefixBlindingLength, dataLength) End If Throw New ArgumentException(ERROR_MESSAGE_INVALID_ARRAY) End Function #End Region #Region "Private methods" '****************************************************************** ' Private methods '****************************************************************** ''' <summary> ''' Check the validity of the requested minimum length. ''' </summary> ''' <param name="minimumLength">Requested minimum length.</param> ''' <exception cref="ArgumentException">Thrown if minimum length is outside the allowed boundaries.</exception> Private Shared Sub CheckMinimumLength(minimumLength As Integer) If (minimumLength < 0) OrElse (minimumLength > MAX_MINIMUM_LENGTH) Then _ Throw New ArgumentException(ERROR_MESSAGE_INVALID_MIN_LENGTH) End Sub ''' <summary> ''' Get the length for a blinding part. ''' </summary> ''' <returns>Length for blinding.</returns> Private Shared Function GetBlindingLength() As Integer Return SecurePseudoRandomNumberGenerator.GetInteger() And MAX_NORMAL_SINGLE_BLINDING_LENGTH End Function ''' <summary> ''' Adapt blinding lengths to minimum length. ''' </summary> ''' <param name="blindingLength"> Array of blinding lengths.</param> ''' <param name="sourceLengthLength">Length of the source length.</param> ''' <param name="sourceLength">Length of source.</param> ''' <param name="minimumLength">Required minimum length.</param> Private Shared Sub AdaptBlindingLengthsToMinimumLength(blindingLength As Integer(), sourceLengthLength As Integer, sourceLength As Integer, minimumLength As Integer) Dim combinedLength As Integer = LENGTHS_LENGTH + sourceLengthLength + blindingLength(INDEX_LENGTHS_PREFIX_LENGTH) + sourceLength + blindingLength(INDEX_LENGTHS_POSTFIX_LENGTH) If combinedLength < minimumLength Then Dim diff As Integer = minimumLength - combinedLength Dim halfDiff As Integer = diff >> 1 blindingLength(INDEX_LENGTHS_PREFIX_LENGTH) += halfDiff blindingLength(INDEX_LENGTHS_POSTFIX_LENGTH) += halfDiff ' Adjust for odd difference If (diff And 1) <> 0 Then If (diff And 2) <> 0 Then blindingLength(INDEX_LENGTHS_PREFIX_LENGTH) += 1 Else blindingLength(INDEX_LENGTHS_POSTFIX_LENGTH) += 1 End If End If End If End Sub ''' <summary> ''' Create blinding lengths so that their combined lengths are at least minimum length. ''' </summary> ''' <param name="sourceLengthLength">Length of the source length.</param> ''' <param name="sourceLength">Length of source.</param> ''' <param name="minimumLength">Required minimum length.</param> ''' <returns>Array of blinding lengths.</returns> Private Shared Function GetBalancedBlindingLengths(sourceLengthLength As Integer, sourceLength As Integer, minimumLength As Integer) As Integer() Dim result As Integer() = New Integer(0 To LENGTHS_LENGTH - 1) {} result(INDEX_LENGTHS_PREFIX_LENGTH) = GetBlindingLength() result(INDEX_LENGTHS_POSTFIX_LENGTH) = GetBlindingLength() ' If minimumLength is greater than 0 adapt blinding lengths to be at least minimum length when combined. If minimumLength > 0 Then _ AdaptBlindingLengthsToMinimumLength(result, sourceLengthLength, sourceLength, minimumLength) Return result End Function #Region "Exception helper methods" ''' <summary> ''' Check if object is null and throw an exception, if it is. ''' </summary> ''' <param name="anObject">Object to check.</param> ''' <param name="parameterName">Parameter name for exception.</param> ''' <exception cref="ArgumentNullException">Thrown when <paramref name="anObject"/> is <c>Nothing</c>.</exception> Private Shared Sub RequireNonNull(anObject As Object, parameterName As String) If anObject Is Nothing Then _ Throw New ArgumentNullException(parameterName) End Sub #End Region #End Region End Class
Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports System.Net.Sockets Public MustInherit Class GameSocket Implements IDisposable Public Property Game() As IGame Get Return m_Game End Get Protected Set m_Game = Value End Set End Property Private m_Game As IGame Protected Property connection() As TcpClient Get Return m_connection End Get Set m_connection = Value End Set End Property Private m_connection As TcpClient Public ReadOnly Property IsConnected() As Boolean Get Return connection.Connected End Get End Property #Region "Asynchronous Reading" Protected ReceiveData As Byte() Public MustOverride Sub Start() #End Region Public MustOverride Function Connect() As Boolean Public Sub Dispose() Implements IDisposable.Dispose Disconnect() End Sub Public Sub Disconnect() If connection IsNot Nothing Then connection.Close() End If End Sub Public MustOverride Sub InitHandlers() End Class
Imports System.Data Imports Talent.eCommerce Imports Talent.eCommerce.Utilities '-------------------------------------------------------------------------------------------------- ' Project Trading E-Commerce ' ' Function User Controls - Checkout Delivery Address ' ' Date Feb 2007 ' ' Author ' ' � CS Group 2007 All rights reserved. ' ' Error Number Code base UCCASC- ' ' Modification Summary ' ' dd/mm/yy ID By Description ' -------- ----- --- ----------- ' '-------------------------------------------------------------------------------------------------- Partial Class UserControls_CheckoutDeliveryAddress Inherits ControlBase Dim ucr As New Talent.Common.UserControlResource Private _languageCode As String = Talent.Common.Utilities.GetDefaultLanguage Private addressLine1RowVisible As Boolean = True Private addressLine2RowVisible As Boolean = True Private addressLine3RowVisible As Boolean = True Private addressLine4RowVisible As Boolean = True Private addressLine5RowVisible As Boolean = True Private addressPostcodeRowVisible As Boolean = True Private addressCountryRowVisible As Boolean = True Private PurchaseOrderRowVisible As Boolean = True Dim eComDefs As ECommerceModuleDefaults Dim defs As ECommerceModuleDefaults.DefaultValues Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init Utilities.DoSapOciCheckout() Utilities.CheckBasketFreeItemHasOptions() eComDefs = New ECommerceModuleDefaults defs = eComDefs.GetDefaults With ucr .BusinessUnit = TalentCache.GetBusinessUnit .PartnerCode = TalentCache.GetPartner(HttpContext.Current.Profile) .PageCode = Talent.eCommerce.Utilities.GetCurrentPageName() .FrontEndConnectionString = ConfigurationManager.ConnectionStrings("TalentEBusinessDBConnectionString").ToString .KeyCode = "CheckoutDeliveryAddress.ascx" End With If defs.Call_Tax_WebService Then If Not HttpContext.Current.Session.Item("DunhillWSError") Is Nothing _ AndAlso CBool(HttpContext.Current.Session.Item("DunhillWSError")) Then 'Dunhill WS Error Response.Redirect("~/PagesPublic/Basket/Basket.aspx") End If End If End Sub Protected Function AllInStock_BackEndCheck() As Boolean Dim AllInStock As Boolean = True If defs.Perform_Back_End_Stock_Check Then Dim dep As New Talent.Common.DePNA Dim des As New Talent.Common.DESettings Dim tls As New Talent.Common.TalentStock Dim err As New Talent.Common.ErrorObj Dim dt As Data.DataTable = Nothing Dim dRow As Data.DataRow = Nothing Dim strResults As New StringBuilder Dim moduleDefaults As ECommerceModuleDefaults = New ECommerceModuleDefaults Dim def As ECommerceModuleDefaults.DefaultValues = moduleDefaults.GetDefaults Dim stockLocation As String = def.StockLocation Dim productcodes As String = String.Empty Dim alternateSKUs As String = String.Empty Dim locations As String = String.Empty For Each bi As TalentBasketItem In Profile.Basket.BasketItems 'Only perform the check if products have been selected, this could be a tickets only basket ' If Not productcodes.Trim.Equals("") Then If bi.PRODUCT_TYPE = "" OrElse bi.PRODUCT_TYPE = "M" Then If Not bi.MODULE_.ToUpper.Equals("TICKETING") Then If Not String.IsNullOrEmpty(productcodes) Then productcodes += "," productcodes += bi.Product If Not String.IsNullOrEmpty(locations) Then locations += "," locations += stockLocation If Not String.IsNullOrEmpty(alternateSKUs) Then alternateSKUs += "," alternateSKUs += bi.ALTERNATE_SKU End If End If Next If productcodes.EndsWith(",") Then productcodes = productcodes.TrimEnd(",") If locations.EndsWith(",") Then locations = locations.TrimEnd(",") If alternateSKUs.EndsWith(",") Then alternateSKUs = alternateSKUs.TrimEnd(",") 'Only perform the check if products have been selected, this could be a tickets only basket If Not productcodes.Trim.Equals("") Then dep.SKU = productcodes dep.Warehouse = locations dep.AlternateSKU = alternateSKUs With des .BusinessUnit = TalentCache.GetBusinessUnitGroup .FrontEndConnectionString = ConfigurationManager.ConnectionStrings("SqlServer2005").ToString .BackOfficeConnectionString = ConfigurationManager.ConnectionStrings("SYSTEM21").ToString .Cacheing = False If Profile.PartnerInfo.Details.Account_No_3 Is Nothing _ OrElse Profile.PartnerInfo.Details.Account_No_3.Trim = String.Empty Then .AccountNo3 = def.DEFAULT_COMPANY_CODE Else .AccountNo3 = Profile.PartnerInfo.Details.Account_No_3 End If .AccountNo4 = Profile.PartnerInfo.Details.Account_No_4 .DestinationDatabase = "SYSTEM21" .StoredProcedureGroup = Talent.eCommerce.Utilities.GetStoredProcedureGroup() .RetryFailures = def.StockCheckRetry .RetryAttempts = def.StockCheckRetryAttempts .RetryWaitTime = def.StockCheckRetryWait .RetryErrorNumbers = def.StockCheckRetryErrors .IgnoreErrors = def.StockCheckIgnoreErrors .LoginId = Profile.User.Details.LoginID .AccountNo1 = Profile.User.Details.Account_No_1 End With Try With tls .Settings = des .Dep = dep err = .GetMutlipleStock If Not err.HasError Then dt = .ResultDataSet.Tables(0) End With Catch ex As Exception Logging.WriteLog(Profile.UserName, "UCCASC-010", ex.Message, "Error contacting SYSTEM 21 for stock check", TalentCache.GetBusinessUnit, TalentCache.GetPartner(Profile), ProfileHelper.GetPageName, "CheckoutDeliverAddress.ascx") End Try If Not err.HasError Then ' ' We could have forced no error by ignoring the error code, therefore the datatable will be empty ' - just continue. If Not dt Is Nothing Then If dt.Rows.Count > 0 Then Dim productcode As String = String.Empty, quantity As String = String.Empty Dim ItemErrorLabel As New Label For Each row As Data.DataRow In dt.Rows For Each bi As TalentBasketItem In Profile.Basket.BasketItems productcode = bi.Product quantity = bi.Quantity If Utilities.CheckForDBNull_String(row("ProductNumber")).Trim = productcode Then If (defs.AllowCheckoutWhenBackEndUnavailable) And ((Utilities.CheckForDBNull_String(row("ErrorCode")).Trim = "UNAVAILABLE")) Then bi.STOCK_ERROR = False Exit For Else If Utilities.CheckForDBNull_Decimal(row("Quantity")) < CDec(quantity) Then AllInStock = False bi.STOCK_ERROR = True bi.QUANTITY_AVAILABLE = Utilities.CheckForDBNull_Decimal(row("Quantity")) '------------------- ' Discontinued check '------------------- If defs.PerformDiscontinuedProductCheck Then Dim dtProdInfo As New Data.DataTable dtProdInfo = Utilities.GetProductInfo(productcode) If Not dtProdInfo Is Nothing AndAlso dtProdInfo.Rows.Count > 0 Then If Utilities.CheckForDBNull_Boolean_DefaultFalse(dtProdInfo.Rows(0)("DISCONTINUED")) Then bi.STOCK_ERROR_CODE = "DISC" End If End If End If Exit For Else bi.STOCK_ERROR = False Exit For End If End If End If Next Next Else End If End If Else Logging.WriteLog(Profile.UserName, err, TalentCache.GetBusinessUnit, TalentCache.GetPartner(Profile), ProfileHelper.GetPageName, "CheckoutDeliverAddress.ascx") AllInStock = False End If End If Profile.Basket.STOCK_ERROR = Not AllInStock 'Save the basket regardless of stock status '------------------------------------------------ Profile.Basket.IsDirty = True Profile.Save() '------------------------------------------------ Else Profile.Basket.STOCK_ERROR = False 'Save the basket regardless of stock status '------------------------------------------------ Profile.Basket.IsDirty = True Profile.Save() '------------------------------------------------ End If Return AllInStock End Function '------------------------------------------------------ ' Back end call to check if items in basket are on stop ' and if so return the list of alternative products '------------------------------------------------------ Protected Function RetrieveAlternativeProducts() As Data.DataSet 'If defs.Perform_Back_End_Stock_Check Then 'Dim dep As New Talent.Common.DePNA Dim productCollection As New Collection Dim des As New Talent.Common.DESettings Dim talentProd As New Talent.Common.TalentProduct Dim err As New Talent.Common.ErrorObj Dim dt As Data.DataTable = Nothing Dim dRow As Data.DataRow = Nothing Dim results As New Data.DataSet Dim strResults As New StringBuilder Dim moduleDefaults As ECommerceModuleDefaults = New ECommerceModuleDefaults Dim def As ECommerceModuleDefaults.DefaultValues = moduleDefaults.GetDefaults Dim basketDetail As New TalentBasketDatasetTableAdapters.tbl_basket_detailTableAdapter Dim dtBasket As Data.DataTable = basketDetail.GetBasketItems_ByHeaderID_ALL(CType(Profile.Basket.Basket_Header_ID, Long)) '----------------------------------------------------------- ' Loop through basket and check if any items have alt items. ' If so put out message. (basket in profile may not be ' loaded yet so need to go to DB) '----------------------------------------------------------- For Each row As Data.DataRow In dtBasket.Rows productCollection.Add(row("PRODUCT")) Next talentProd.ProductCollection = productCollection With des .BusinessUnit = TalentCache.GetBusinessUnitGroup .FrontEndConnectionString = ConfigurationManager.ConnectionStrings("SqlServer2005").ToString .BackOfficeConnectionString = ConfigurationManager.ConnectionStrings("SYSTEM21").ToString .Cacheing = False If Profile.PartnerInfo.Details.Account_No_3 Is Nothing _ OrElse Profile.PartnerInfo.Details.Account_No_3.Trim = String.Empty Then .AccountNo3 = def.DEFAULT_COMPANY_CODE Else .AccountNo3 = Profile.PartnerInfo.Details.Account_No_3 End If .AccountNo4 = Profile.PartnerInfo.Details.Account_No_4 .DestinationDatabase = "SYSTEM21" .StoredProcedureGroup = Talent.eCommerce.Utilities.GetStoredProcedureGroup() End With Try With talentProd .Settings = des err = .RetrieveAlternativeProducts() If Not err.HasError Then dt = .ResultDataSet.Tables(0) End With Catch ex As Exception Logging.WriteLog(Profile.UserName, "UCCASC-011", _ ex.Message, _ "Error contacting " & _ talentProd.Settings.DestinationDatabase & _ " for alt products check", TalentCache.GetBusinessUnit, TalentCache.GetPartner(Profile), ProfileHelper.GetPageName, "CheckoutDeliverAddress.ascx") End Try If Not err.HasError Then results = talentProd.ResultDataSet Else Logging.WriteLog(Profile.UserName, err, TalentCache.GetBusinessUnit, TalentCache.GetPartner(Profile), ProfileHelper.GetPageName, "CheckoutDeliverAddress.ascx") End If Return results End Function Protected Function UserUnderAge() As Boolean 'Dim defs As New Talent.eCommerce.ECommerceModuleDefaults 'Dim values As New Talent.eCommerce.ECommerceModuleDefaults.DefaultValues 'Dim UnderAge As Boolean = False 'values = defs.GetDefaults 'If values.Use_Age_Check Then ' Dim products As New TalentProductInformationTableAdapters.tbl_productTableAdapter ' Dim orderLines As New TalentBasketDatasetTableAdapters.tbl_basket_detailTableAdapter ' Dim lines As New Data.DataTable ' Try ' 'lines = orderLines.Get_BasketDetailControl_Lines(Profile.Basket.Basket_Header_ID, TalentCache.GetPartner(Profile), TalentCache.GetBusinessUnit, values.PriceList) ' lines = orderLines.GetBasketItems_ByHeaderID_NonTicketing(Profile.Basket.Basket_Header_ID) ' 'If lines.Rows.Count < 1 Then ' ' lines = orderLines.Get_BasketDetailControl_Lines(Profile.Basket.Basket_Header_ID, Talent.Common.Utilities.GetAllString, TalentCache.GetBusinessUnit, values.PriceList) ' 'End If ' Catch ex As Exception ' Logging.WriteLog(Profile.UserName, "UCCAUA-010", ex.Message, "Error getting basket details for age check in UserUnderAge()", TalentCache.GetBusinessUnit, TalentCache.GetPartner(Profile), ProfileHelper.GetPageName, "CheckoutDeliverAddress.ascx") ' End Try ' If lines.Rows.Count > 0 Then ' Dim prods As Data.DataTable ' Dim age As Integer = ProfileHelper.GetAge(Profile.User.Details.DOB) ' For Each row As Data.DataRow In lines.Rows ' prods = products.GetDataByProduct_Code(CheckForDBNull_String(row("PRODUCT"))) ' If CheckForDBNull_Int(prods.Rows(0)("PRODUCT_MINIMUM_AGE")) > age Then ' UnderAge = True ' Exit For ' End If ' Next ' Else ' 'No items in basket so kick back to Basket page anyway ' UnderAge = True ' End If 'End If 'Return UnderAge Return False End Function Protected Sub PopulateAddressFromDDL() Try Dim ta As New TalentProfileAddress ta = Profile.User.Addresses(SelectAddressDDL.SelectedItem.Text) With ta building.Text = .Address_Line_1 postcode.Text = UCase(.Post_Code) Address2.Text = .Address_Line_2 Address3.Text = .Address_Line_3 Address4.Text = .Address_Line_4 Address5.Text = .Address_Line_5 Try Dim i As Integer = 0 For Each li As ListItem In CountryDDL.Items If li.Value.ToLower = .Country.ToLower OrElse li.Text.ToLower = .Country.ToLower Then CountryDDL.SelectedIndex = i End If i += 1 Next Catch End Try DeliveryContact.Text = Profile.User.Details.Full_Name SaveAddress.Text = ucr.Content("UpdateAddressText", _languageCode, True) End With 'check to see if we need to show a delivery message 'if we do, show the correct message with the calculated delivery slot If ucr.Attribute("DisplayDeliveryMessage").ToUpper = "TRUE" Then plhDeliveryMessage.Visible = True Dim deliveryZoneCode As String = ta.Delivery_Zone_Code Dim deliveryZoneType As String = GetDeliveryZoneType(deliveryZoneCode) Dim deliveryZoneDate As Date = GetDeliveryDate(Profile, deliveryZoneCode, deliveryZoneType) Dim deliveryZoneDay As String = "" If deliveryZoneDate = Date.MinValue Then deliveryZoneType = "2" Else deliveryZoneDay = deliveryZoneDate.DayOfWeek.ToString.ToUpper End If Dim deliveryDateFormat As String = Utilities.CheckForDBNull_String(ucr.Attribute("DeliveryDateFormat")).Trim If deliveryDateFormat.Length <= 0 Then deliveryDateFormat = "dd/MM/yyyy" End If DeliveryDate.Text = deliveryZoneDate.ToString(deliveryDateFormat) Select Case deliveryZoneType Case Is = "1" ltlDeliveryMessage.Text = ucr.Content("DeliveryMessage1", _languageCode, True).Replace("<<DELIVERY_SLOT>>", deliveryZoneDay) DeliveryDay.Text = ucr.Content("DeliveryMessage1", _languageCode, True).Replace("<<DELIVERY_SLOT>>", deliveryZoneDay) Case Is = "2" ltlDeliveryMessage.Text = ucr.Content("DeliveryMessage2", _languageCode, True) DeliveryDay.Text = ucr.Content("DeliveryMessage2", _languageCode, True) Case Else End Select Session("DeliveryDate") = deliveryZoneDate If PreferredDateRow.Visible Then Dim dtPreferredDeliveryDates As DataTable = GetPreferredDeliveryDates(Profile, deliveryZoneCode, deliveryZoneType) Session("dtPreferredDeliveryDates") = dtPreferredDeliveryDates If dtPreferredDeliveryDates.Rows.Count > 0 Then Dim strPreferredDates As String = String.Empty For rowIndex As Integer = 0 To dtPreferredDeliveryDates.Rows.Count - 1 If String.IsNullOrEmpty(strPreferredDates) Then strPreferredDates += CDate(dtPreferredDeliveryDates.Rows(rowIndex)("DeliveryDates")).ToString("[MM, dd, yyyy]") Else strPreferredDates += CDate(dtPreferredDeliveryDates.Rows(rowIndex)("DeliveryDates")).ToString(",[MM, dd, yyyy]") End If Next ltlPreferredDatesScript.Visible = True ltlPreferredDatesScript.Text = "" & _ "<script type=""text/javascript"">" & vbCrLf & _ "<!--" & vbCrLf & _ "var availableDays = [" & strPreferredDates & "];" & vbCrLf & _ "//-->" & vbCrLf & _ "</script>" End If PreferredDate.Text = deliveryZoneDate.ToString(deliveryDateFormat) End If End If Catch ex As Exception Logging.WriteLog(Profile.UserName, "UCCAPA-010", ex.Message, "Error populating address fields from profile PopulateAddressFromDDL()", TalentCache.GetBusinessUnit, TalentCache.GetPartner(Profile), ProfileHelper.GetPageName, "CheckoutDeliverAddress.ascx") End Try End Sub Protected Sub PopulateAddressDDL() Dim count As Integer = 0 Dim addressSelected As Boolean = False For i As Integer = 0 To Profile.User.Addresses.Count - 1 Dim ta As New TalentProfileAddress ta = ProfileHelper.ProfileAddressEnumerator(i, Profile.User.Addresses) '---------------------------------------------------- ' Don't add if we're using a default delivery country ' unless the address matches the delivery country '---------------------------------------------------- Dim moduleDefaults As ECommerceModuleDefaults = New ECommerceModuleDefaults Dim def As ECommerceModuleDefaults.DefaultValues = moduleDefaults.GetDefaults Dim defaultCountry As String = String.Empty Dim countryMatch As Boolean = True If def.UseDefaultCountryOnDeliveryAddress Then defaultCountry = TalentCache.GetDefaultCountryForBU() If defaultCountry <> String.Empty Then countryMatch = False '---------------------------------------------------- ' Loop through address dropdown to find address code. ' Then check if it matches default country. '---------------------------------------------------- For Each li As ListItem In CountryDDL.Items If UCase(li.Value) = UCase(ta.Country) OrElse UCase(li.Text) = UCase(ta.Country) Then If UCase(li.Value) = UCase(defaultCountry) Then countryMatch = True End If Exit For End If Next End If End If If countryMatch Then If ta.Default_Address AndAlso count = 0 Then Try SelectAddressDDL.Items.Insert(0, New ListItem(ta.Reference, i)) SelectAddressDDL.Items(0).Selected = True count += 1 addressSelected = True Catch ex As Exception End Try Else '------------------------------------ ' Don't add if it's a REGISTERED type '------------------------------------ If ta.Type <> "1" Then SelectAddressDDL.Items.Add(New ListItem(ta.Reference, i)) addressSelected = True End If End If End If Next If Not addressSelected AndAlso Utilities.CheckForDBNullOrBlank_Boolean_DefaultFalse(ucr.Attribute("MakeAddressFieldsReadOnly")) Then If Profile.User.Addresses.Count > 0 Then Dim ta As New TalentProfileAddress ta = ProfileHelper.ProfileAddressEnumerator(0, Profile.User.Addresses) Try SelectAddressDDL.Items.Insert(0, New ListItem(ta.Reference, 0)) SelectAddressDDL.Items(0).Selected = True count += 1 addressSelected = True Catch ex As Exception End Try End If End If 'check to see if the "add new address text" has been set 'if it is blank we need to force the address fields to be readonly Dim addNewAddressText As String = ucr.Content("AddNewAddressText", _languageCode, True) If String.IsNullOrEmpty(addNewAddressText) Then If ucr.Attribute("MakeAddressFieldsReadOnly").ToUpper = "TRUE" Then building.ReadOnly = True Address2.ReadOnly = True Address3.ReadOnly = True Address4.ReadOnly = True Address5.ReadOnly = True postcode.ReadOnly = True CountryDDL.Enabled = False DeliveryContact.ReadOnly = True DeliveryInstructions.ReadOnly = True PurchaseOrder.ReadOnly = True SaveAddress.Enabled = False proceed.CausesValidation = False End If Else SelectAddressDDL.Items.Add(addNewAddressText) End If End Sub Protected Sub PopulateCountryDDL() CountryDDL.DataSource = TalentCache.GetDropDownControlText(Utilities.GetCurrentLanguageForDDLPopulation, "DELIVERY", "COUNTRY") CountryDDL.DataTextField = "Text" CountryDDL.DataValueField = "Value" CountryDDL.DataBind() '---------------------------------------------------------------------------------------- ' If set up to use default country on module defaults and a default country is found then ' set the default country and protect it '---------------------------------------------------------------------------------------- Dim moduleDefaults As ECommerceModuleDefaults = New ECommerceModuleDefaults Dim def As ECommerceModuleDefaults.DefaultValues = moduleDefaults.GetDefaults If def.UseDefaultCountryOnDeliveryAddress Then Dim defaultCountry As String = TalentCache.GetDefaultCountryForBU() If defaultCountry <> String.Empty Then CountryDDL.SelectedValue = defaultCountry CountryDDL.Enabled = False End If End If End Sub Protected Sub SetLabelText() With ucr TitleText.Text = .Content("TitleText", _languageCode, True) InstructionsText.Text = .Content("InstructionsText", _languageCode, True) SelectAddressLabel.Text = .Content("SelectAddressLabel", _languageCode, True) BuildingLabel.Text = .Content("HouseNoLabel", _languageCode, True) PostcodeLabel.Text = .Content("PostcodeLabel", _languageCode, True) AddressLabel2.Text = .Content("AddressLabel2", _languageCode, True) AddressLabel3.Text = .Content("AddressLabel3", _languageCode, True) AddressLabel4.Text = .Content("AddressLabel4", _languageCode, True) AddressLabel5.Text = .Content("AddressLabel5", _languageCode, True) countryLabel.Text = .Content("CountryLabel", _languageCode, True) DeliveryContactLabel.Text = .Content("DeliveryContactLabel", _languageCode, True) DeliveryInsructionsLabel.Text = .Content("DeliveryInsructionsLabel", _languageCode, True) SaveAddress.Text = .Content("SaveAddressText", _languageCode, True) tandc.Text = .Content("TermsAndConditionsText", _languageCode, True) proceed.Text = .Content("ProceedButtonText", _languageCode, True) PurchaseOrderLabel.Text = .Content("PurchaseOrderText", _languageCode, True) DeliveryDayLabel.Text = .Content("DeliveryDayLabel", _languageCode, True) DeliveryDateLabel.Text = .Content("DeliveryDateLabel", _languageCode, True) 'DeliveryDay 'DeliveryDate 'PreferredDate PreferredDateLabel.Text = .Content("PreferredDateLabel", _languageCode, True) 'HelpLabel Text SelectAddressHelpLabel.Text = .Content("SelectAddressHelpLabel", _languageCode, True) DeliveryInsructionsHelpLabel.Text = .Content("DeliveryInsructionsHelpLabel", _languageCode, True) PurchaseOrderHelpLabel.Text = .Content("PurchaseOrderHelpLabel", _languageCode, True) DeliveryDateHelpLabel.Text = .Content("DeliveryDateHelpLabel", _languageCode, True) PreferredDateHelpLabel.Text = .Content("PreferredDateHelpLabel", _languageCode, True) End With End Sub Protected Sub SetupValidation() With ucr ' Required Fields '----------------------- If .Content("HouseNoMissingErrorText", _languageCode, True) = "" Then BuildingRFV.Enabled = False Else BuildingRFV.ErrorMessage = .Content("HouseNoMissingErrorText", _languageCode, True) End If If .Content("PostcodeMissingErrorText", _languageCode, True) = "" Then postcodeRFV.Enabled = False Else postcodeRFV.ErrorMessage = .Content("PostcodeMissingErrorText", _languageCode, True) End If If .Content("AddressLine2MissingErrorText", _languageCode, True) = "" Then Address2RFV.Enabled = False Else Address2RFV.ErrorMessage = .Content("AddressLine2MissingErrorText", _languageCode, True) End If If .Content("AddressLine3MissingErrorText", _languageCode, True) = "" Then Address3RFV.Enabled = False Else Address3RFV.ErrorMessage = .Content("AddressLine3MissingErrorText", _languageCode, True) End If If .Content("AddressLine4MissingErrorText", _languageCode, True) = "" Then Address4RFV.Enabled = False Else Address4RFV.ErrorMessage = .Content("AddressLine4MissingErrorText", _languageCode, True) End If If .Content("AddressLine5MissingErrorText", _languageCode, True) = "" Then Address5RFV.Enabled = False Else Address5RFV.ErrorMessage = .Content("AddressLine5MissingErrorText", _languageCode, True) End If If .Content("PurchaseOrderMissingErrorText", _languageCode, True) = "" Then PurchaseOrderRFV.Enabled = False Else PurchaseOrderRFV.ErrorMessage = .Content("PurchaseOrderMissingErrorText", _languageCode, True) End If If .Content("DeliveryContactMissingErrorText", _languageCode, True) = "" Then DeliveryContactRFV.Enabled = False Else DeliveryContactRFV.ErrorMessage = .Content("DeliveryContactMissingErrorText", _languageCode, True) End If If .Content("DeliveryInstructionsMissingErrorText", _languageCode, True) = "" Then DeliveryInstructionsRFV.Enabled = False Else DeliveryInstructionsRFV.ErrorMessage = .Content("DeliveryInstructionsMissingErrorText", _languageCode, True) End If ' Regular Expressions '------------------------- BuildingRegEx.ErrorMessage = .Content("HouseNoInvalidErrorText", _languageCode, True) BuildingRegEx.ValidationExpression = .Attribute("TextAndNumbersExpression") postcodeRegEx.ErrorMessage = .Content("PostcodeInvalidErrorText", _languageCode, True) postcodeRegEx.ValidationExpression = .Attribute("PostcodeExpression") Address2RegEx.ErrorMessage = .Content("Address2InvalidErrorText", _languageCode, True) Address2RegEx.ValidationExpression = .Attribute("TextAndNumbersExpression") Address3RegEx.ErrorMessage = .Content("Address3InvalidErrorText", _languageCode, True) Address3RegEx.ValidationExpression = .Attribute("TextOnlyExpression") Address4RegEx.ErrorMessage = .Content("Address4InvalidErrorText", _languageCode, True) Address4RegEx.ValidationExpression = .Attribute("TextOnlyExpression") Address5RegEx.ErrorMessage = .Content("Address5InvalidErrorText", _languageCode, True) Address5RegEx.ValidationExpression = .Attribute("TextOnlyExpression") PurchaseOrderRegEx.ValidationExpression = .Attribute("TextAndNumbersExpression") PurchaseOrderRegEx.ErrorMessage = .Content("PurchaseOrderInvalidErrorText", _languageCode, True) CountryDDLRegEx.ErrorMessage = .Content("NoCountrySelectedErrorText", _languageCode, True) ' CountryDDLRegEx.ValidationExpression = "^(?! -- )?[a-zA-Z\s]+" CountryDDLRegEx.ValidationExpression = "^[a-zA-Z\s]{0,50}$" DeliveryContactRegEx.ErrorMessage = .Content("DeliveryContactNameInvalidErrorText", _languageCode, True) DeliveryContactRegEx.ValidationExpression = .Attribute("TextOnlyExpression") DeliveryInstructionsRegEx.ErrorMessage = .Content("DeliveryInstructionsInvalidErrorText", _languageCode, True) DeliveryInstructionsRegEx.ValidationExpression = .Attribute("TextAndPuctExpression") PreferredDateRegEx.ValidationExpression = .Attribute("PreferredDateExpression") PreferredDateRegEx.ErrorMessage = .Content("PreferredDateInvalidErrorText", _languageCode, True) 'Readonly Fields If (Utilities.CheckForDBNull_Boolean_DefaultFalse(.Attribute("ReadOnlyAddressLine1"))) Then building.ReadOnly = True If (Utilities.CheckForDBNull_Boolean_DefaultFalse(.Attribute("ReadOnlyAddressLine2"))) Then Address2.ReadOnly = True If (Utilities.CheckForDBNull_Boolean_DefaultFalse(.Attribute("ReadOnlyAddressLine3"))) Then Address3.ReadOnly = True If (Utilities.CheckForDBNull_Boolean_DefaultFalse(.Attribute("ReadOnlyAddressLine4"))) Then Address4.ReadOnly = True If (Utilities.CheckForDBNull_Boolean_DefaultFalse(.Attribute("ReadOnlyAddressLine5"))) Then Address5.ReadOnly = True If (Utilities.CheckForDBNull_Boolean_DefaultFalse(.Attribute("ReadOnlyAddressPostcode"))) Then postcode.ReadOnly = True If (Utilities.CheckForDBNull_Boolean_DefaultFalse(.Attribute("ReadOnlyAddressCountry"))) Then CountryDDL.Enabled = False If (Utilities.CheckForDBNull_Boolean_DefaultFalse(.Attribute("ReadOnlyDeliveryContact"))) Then DeliveryContact.ReadOnly = True 'max length attributes PurchaseOrder.MaxLength = Utilities.CheckForDBNull_Int(.Attribute("PurchaseOrderMaxLength")) End With End Sub Protected Sub proceed_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles proceed.Click Try Session.Add("CheckoutBasketState", Profile.Basket) Catch ex As Exception End Try Checkout.CheckBasketValidity() ErrorLabel.Text = String.Empty Dim addressExternalID As String = String.Empty Dim deliveryDate As Date = Date.MinValue If Session("DeliveryDate") IsNot Nothing Then deliveryDate = Session("DeliveryDate") End If If ucr.Content("TermsAndConsNotTickedErrorText", _languageCode, True).Trim.Length > 0 Then If (tandc.Visible) AndAlso (Not tandc.Checked) Then ErrorLabel.Text = ucr.Content("TermsAndConsNotTickedErrorText", _languageCode, True) Exit Sub End If End If If SelectAddressDDL.SelectedValue = ucr.Content("AddNewAddressText", _languageCode, True) Then If SaveAddress.Checked Then Try Dim ta As TalentProfileAddress Dim reference As String = String.Empty If String.IsNullOrEmpty(building.Text.Trim) Then reference = building.Text & " " & Address2.Text Else reference = building.Text & " " & Address2.Text End If If Not Profile.User.Addresses.ContainsKey(reference) Then '-------------------------------- ' Reference doesn't already exist '-------------------------------- SaveAddressToDB(False) Else '------------------------- ' Reference already exists '------------------------- ta = Profile.User.Addresses(reference) If Not UCase(ta.Post_Code) = UCase(postcode.Text) Then SaveAddressToDB(True) Else 'The address already exists on this profile and so cannot be added ErrorLabel.Text = ucr.Content("AddressExistsErrorText", _languageCode, True) Exit Sub End If End If 'If String.IsNullOrEmpty(building.Text.Trim) Then ' ta = Profile.User.Addresses(Address2.Text & " " & Address3.Text) 'Else ' ta = Profile.User.Addresses(building.Text & " " & Address2.Text) 'End If 'If Not UCase(ta.Post_Code) = UCase(postcode.Text) Then ' SaveAddressToDB(True) 'Else ' 'The address already exists on this profile and so cannot be added ' ErrorLabel.Text = ucr.Content("AddressExistsErrorText", _languageCode, True) ' Exit Sub 'End If Catch ex As Exception ' SaveAddressToDB(False) End Try End If addressExternalID = String.Empty Else If Not SelectAddressDDL.SelectedItem Is Nothing Then With Profile.User.Addresses(SelectAddressDDL.SelectedItem.Text) If SaveAddress.Checked Then .Address_Line_1 = building.Text .Address_Line_2 = Address2.Text .Address_Line_3 = Address3.Text .Address_Line_4 = Address4.Text .Address_Line_5 = Address5.Text .Country = CountryDDL.SelectedItem.Text .Default_Address = True .Post_Code = UCase(postcode.Text) .Reference = building.Text & " " & Address2.Text Profile.Save() End If Profile.Provider.UpdateDefaultAddress(.LoginID, TalentCache.GetPartner(Profile), .Address_ID) End With addressExternalID = Profile.User.Addresses(SelectAddressDDL.SelectedItem.Text).External_ID 'decides the final delivery date Dim preferredDateExists As Boolean = True If PreferredDateRow.Visible Then If PreferredDate.Text.Length > 0 Then If Session("dtPreferredDeliveryDates") IsNot Nothing Then Dim dtPreferredDeliveryDates As DataTable = CType(Session("dtPreferredDeliveryDates"), DataTable) If dtPreferredDeliveryDates.Rows.Count > 0 Then preferredDateExists = False Dim deliveryDateFormat As String = Utilities.CheckForDBNull_String(ucr.Attribute("DeliveryDateFormat")).Trim If deliveryDateFormat.Length <= 0 Then deliveryDateFormat = "dd/MM/yyyy" End If For rowIndex As Integer = 0 To dtPreferredDeliveryDates.Rows.Count - 1 If CDate(dtPreferredDeliveryDates.Rows(rowIndex)("DeliveryDates")).ToString(deliveryDateFormat) = PreferredDate.Text Then preferredDateExists = True deliveryDate = PreferredDate.Text Exit For End If Next If Not preferredDateExists Then ErrorLabel.Text = ucr.Content("PreferredDateForZoneError", _languageCode, True) Exit Sub End If End If Session("dtPreferredDeliveryDates") = Nothing Session.Remove("dtPreferredDeliveryDates") End If End If End If End If End If Dim country As String = "" If defs.StoreCountryAsWholeName Then country = CountryDDL.SelectedItem.Text Else country = CountryDDL.SelectedItem.Value End If Dim order As New Order(DeliveryInstructions.Text, _ DeliveryContact.Text, _ building.Text, _ Address2.Text, _ Address3.Text, _ Address4.Text, _ Address5.Text, _ postcode.Text, _ country, _ PurchaseOrder.Text, _ addressExternalID, _ deliveryDate, CountryDDL.SelectedItem.Value) 'If CreateOrder() Then If order.CreateOrder() Then Try Dim status As New TalentBasketDatasetTableAdapters.tbl_order_statusTableAdapter status.Insert_Order_Status_Flow(TalentCache.GetBusinessUnit, _ Profile.Basket.TempOrderID, _ Talent.Common.Utilities.GetOrderStatus("DELIVERY"), _ Now, _ "") Catch ex As Exception Logging.WriteLog(Profile.UserName, "UCCAPR-010", ex.Message, "Error Inserting Order Status", TalentCache.GetBusinessUnit, TalentCache.GetPartner(Profile), ProfileHelper.GetPageName, "CheckoutDeliverAddress.ascx") End Try ' Response.Redirect("~/PagesLogin/Checkout/CheckoutOrderSummary.aspx") Else ErrorLabel.Text = ucr.Content("OrderCreationErrorText", _languageCode, True) End If End Sub Protected Function SaveAddressToDB(ByVal StorePostcode As Boolean) As Boolean Try Dim ta As New TalentProfileAddress With ta .LoginID = Profile.User.Details.LoginID If StorePostcode Then If String.IsNullOrEmpty(building.Text.Trim) Then .Reference = Address2.Text & " " & Address3.Text & " (" & UCase(postcode.Text) & ")" Else .Reference = building.Text & " " & Address2.Text & " (" & UCase(postcode.Text) & ")" End If Else If String.IsNullOrEmpty(building.Text.Trim) Then .Reference = Address2.Text & " " & Address3.Text Else .Reference = building.Text & " " & Address2.Text End If End If .Type = "" .Default_Address = True .Address_Line_1 = building.Text .Address_Line_2 = Address2.Text .Address_Line_3 = Address3.Text .Address_Line_4 = Address4.Text .Address_Line_5 = Address5.Text .Post_Code = UCase(postcode.Text) .Country = CountryDDL.SelectedValue .Sequence = GetNextSequenceNo() End With 'finally, check to see if the address reference is alrady taken 'Dim testAddress As TalentProfileAddress = Profile.User.Addresses.ContainsKey(ta.Reference) ' If testAddress Is Nothing Then If Not Profile.User.Addresses.ContainsKey(ta.Reference) Then Profile.Provider.AddAddressToUserProfile(ta) Else 'address already exists 'The address already exists on this profile and so cannot be added ErrorLabel.Text = ucr.Content("AddressExistsErrorText", _languageCode, True) Return False End If Try Profile.Provider.UpdateDefaultAddress(ta.LoginID, Profile.PartnerInfo.Details.Partner, ta.Address_ID) Catch ex As Exception Logging.WriteLog(Profile.UserName, "UCCASA-020", ex.Message, "Error updating the user's default address", TalentCache.GetBusinessUnit, TalentCache.GetPartner(Profile), ProfileHelper.GetPageName, "CheckoutDeliverAddress.ascx") End Try Catch ex As Exception Logging.WriteLog(Profile.UserName, "UCCASA-010", ex.Message, "Error adding a new address for the user", TalentCache.GetBusinessUnit, TalentCache.GetPartner(Profile), ProfileHelper.GetPageName, "CheckoutDeliverAddress.ascx") End Try Return True End Function Protected Function GetNextSequenceNo() As Integer Dim seq As Integer = 0 Try For Each tpa As TalentProfileAddress In Profile.User.Addresses.Values If tpa.Sequence > seq Then seq = tpa.Sequence Next seq += 1 Catch ex As Exception End Try Return seq End Function Protected Sub SelectAddressDDL_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles SelectAddressDDL.SelectedIndexChanged If SelectAddressDDL.SelectedValue = ucr.Content("AddNewAddressText", _languageCode, True) Then building.Text = String.Empty postcode.Text = String.Empty Address2.Text = String.Empty Address3.Text = String.Empty Address4.Text = String.Empty Address5.Text = String.Empty CountryDDL.SelectedIndex = 0 '---------------------------------------------------------------------------------------- ' If set up to use default country on module defaults and a default country is found then ' set the default country and protect it '---------------------------------------------------------------------------------------- Dim moduleDefaults As ECommerceModuleDefaults = New ECommerceModuleDefaults Dim def As ECommerceModuleDefaults.DefaultValues = moduleDefaults.GetDefaults If def.UseDefaultCountryOnDeliveryAddress Then Dim defaultCountry As String = TalentCache.GetDefaultCountryForBU() If defaultCountry <> String.Empty Then CountryDDL.SelectedValue = defaultCountry CountryDDL.Enabled = False End If End If DeliveryContact.Text = Profile.User.Details.Full_Name SaveAddress.Text = ucr.Content("SaveAddressText", _languageCode, True) SaveAddress.Visible = True Else PopulateAddressFromDDL() 'SaveAddress.Text = ucr.Content("UpdateAddressText", _languageCode, True) SaveAddress.Visible = False End If End Sub Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender If Not Page.IsPostBack Then If ucr.Content("TermsAndConsNotTickedErrorText", _languageCode, True).Trim.Length <= 0 Then tandc.Visible = False End If If UserUnderAge() Then Response.Redirect("~/PagesPublic/Basket/Basket.aspx") Else If Not defs.AllowCheckoutWhenNoStock AndAlso _ Not AllInStock_BackEndCheck() Then Response.Redirect("~/PagesPublic/Basket/Basket.aspx") End If '------------------------------------------------------- ' Check for discontinued products which are out of stock '------------------------------------------------------- If defs.PerformDiscontinuedProductCheck Then For Each bi As TalentBasketItem In Profile.Basket.BasketItems If bi.STOCK_ERROR AndAlso bi.STOCK_ERROR_CODE = "DISC" Then Response.Redirect("~/PagesPublic/Basket/Basket.aspx") End If Next End If '------------------------------------------------------- ' Check for mandatory account codes '------------------------------------------------------- If Not Profile.PartnerInfo.Details.COST_CENTRE Is Nothing And Not Profile.PartnerInfo.Details.COST_CENTRE Is String.Empty Then For Each bi As TalentBasketItem In Profile.Basket.BasketItems If bi.Cost_Centre = Nothing Or bi.Cost_Centre = String.Empty Or bi.Account_Code = Nothing Or bi.Account_Code = String.Empty Then Session("TalentErrorCode") = "CC" Response.Redirect("~/PagesPublic/Basket/Basket.aspx") End If Next End If '------------------------------------- ' Check for alt products ' If any exist then redirect to basket ' allowing user to select alt products '------------------------------------- If defs.RetrieveAlternativeProductsAtCheckout Then Dim ds As New Data.DataSet ds = RetrieveAlternativeProducts() If Not ds Is Nothing AndAlso ds.Tables.Count > 0 AndAlso ds.Tables.Item("ALTPRODUCTRESULTS").Rows.Count > 0 Then ' Save to session - this will be checked and cleared immediately in basket Session("AlternativeProducts") = ds Session.Remove("CheckoutBreadCrumbTrail") Response.Redirect("~/PagesPublic/Basket/Basket.aspx") End If End If If defs.DISPLAY_PAGE_BEFORE_CHECKOUT Then If Session.Item("CheckoutPromotionsShown") Is Nothing _ OrElse Not CBool(Session.Item("CheckoutPromotionsShown")) Then Session.Item("CheckoutPromotionsShown") = True Response.Redirect(defs.PAGE_BEFORE_CHECKOUT) End If End If SetLabelText() SetupValidation() PopulateCountryDDL() PopulateAddressDDL() SetAddressVisibilityProperties() SetAddressVisibility() '------------------------------------- ' Check if need to show 'Save Address' '------------------------------------- If SelectAddressDDL.SelectedValue <> ucr.Content("AddNewAddressText", _languageCode, True) Then SaveAddress.Visible = False PopulateAddressFromDDL() Else SaveAddress.Text = ucr.Content("SaveAddressText", _languageCode, True) SaveAddress.Visible = True End If ' SaveAddress.Visible = False End If 'Redirect to payment if basket content type is only ticketing 'Select Case Profile.Basket.BasketContentType ' Case "T" ' Session.Remove("CheckoutBreadCrumbTrail") ' Me.CreateOrderHeader() ' Session.Add("CheckoutBasketState", Profile.Basket) ' Response.Redirect("~/PagesLogin/Checkout/CheckoutPaymentDetails.aspx") ' Case Else 'End Select '--------------------------------------- ' Check what stage checkout should start ' (i.e. skip the delivery address page?) '--------------------------------------- 'Try ' 'Add the Basket Session Variable at the start of the Checkout ' Session.Add("CheckoutBasketState", Profile.Basket) 'Catch ex As Exception 'End Try 'If Not String.IsNullOrEmpty(defs.FirstCheckoutPage) Then ' If defs.FirstCheckoutPage.ToUpper <> "CHECKOUTDELIVERYDETAILS.ASPX" Then ' If Me.CreateOrderHeader Then ' Select Case defs.FirstCheckoutPage.ToUpper ' Case "CHECKOUTORDERSUMMARY.ASPX" ' Select Case Profile.Basket.BasketContentType ' Case "M", "C" ' Checkout.CheckBasketValidity() ' Session.Remove("CheckoutBreadCrumbTrail") ' Response.Redirect("~/PagesLogin/Checkout/CheckoutOrderSummary.aspx") ' Case "T" ' Session.Remove("CheckoutBreadCrumbTrail") ' Response.Redirect("~/PagesLogin/Checkout/CheckoutPaymentDetails.aspx") ' Case Else ' Session.Remove("CheckoutBreadCrumbTrail") ' Session.Remove("CheckoutBasketState") ' Response.Redirect("~/PagesPublic/Basket/Basket.aspx") ' End Select ' Case "CHECKOUTPAYMENTDETAILS.ASPX" ' Select Case Profile.Basket.BasketContentType ' Case "T", "M", "C" ' Session.Remove("CheckoutBreadCrumbTrail") ' Response.Redirect("~/PagesLogin/Checkout/CheckoutPaymentDetails.aspx") ' Case Else ' Session.Remove("CheckoutBreadCrumbTrail") ' Session.Remove("CheckoutBasketState") ' Response.Redirect("~/PagesPublic/Basket/Basket.aspx") ' End Select ' End Select ' End If ' Else ' Select Case Profile.Basket.BasketContentType ' Case "M", "C" ' Checkout.CheckBasketValidity() ' Case "T" ' Session.Remove("CheckoutBreadCrumbTrail") ' Me.CreateOrderHeader() ' Response.Redirect("~/PagesLogin/Checkout/CheckoutPaymentDetails.aspx") ' Case Else ' Session.Remove("CheckoutBreadCrumbTrail") ' Session.Remove("CheckoutBasketState") ' Response.Redirect("~/PagesPublic/Basket/Basket.aspx") ' End Select ' End If 'Else ' Select Case Profile.Basket.BasketContentType ' Case "M", "C" ' Checkout.CheckBasketValidity() ' Case "T" ' Me.CreateOrderHeader() ' Session.Remove("CheckoutBreadCrumbTrail") ' Response.Redirect("~/PagesLogin/Checkout/CheckoutPaymentDetails.aspx") ' Case Else ' Session.Remove("CheckoutBreadCrumbTrail") ' Session.Remove("CheckoutBasketState") ' Response.Redirect("~/PagesPublic/Basket/Basket.aspx") ' End Select 'End If If Utilities.CheckForDBNullOrBlank_Boolean_DefaultFalse(ucr.Attribute("MakeAddressFieldsReadOnly")) Then building.ReadOnly = True postcode.ReadOnly = True Address2.ReadOnly = True Address3.ReadOnly = True Address4.ReadOnly = True Address5.ReadOnly = True CountryDDL.Enabled = False End If 'check to see if we need to show a delivery message If ucr.Attribute("DisplayDeliveryMessage").ToUpper = "TRUE" Then plhDeliveryMessage.Visible = True End If End If If defs.UseEPOSOptions Then Response.Redirect("~/PagesLogin/Checkout/CheckoutOrderSummary.aspx") End Sub Protected Function CreateOrderHeader() As Boolean Dim createOrderOK As Boolean = False '------------- ' Create order '------------- Try Dim ta As New TalentProfileAddress ta = Profile.User.Addresses(SelectAddressDDL.SelectedItem.Text) Dim order As New Order(DeliveryInstructions.Text, _ DeliveryContact.Text, _ ta.Address_Line_1, _ ta.Address_Line_2, _ ta.Address_Line_3, _ ta.Address_Line_4, _ ta.Address_Line_5, _ ta.Post_Code, _ ta.Country, _ PurchaseOrder.Text, _ ta.External_ID) If order.CreateOrder() Then createOrderOK = True Try Dim status As New TalentBasketDatasetTableAdapters.tbl_order_statusTableAdapter status.Insert_Order_Status_Flow(TalentCache.GetBusinessUnit, _ Profile.Basket.TempOrderID, _ Talent.Common.Utilities.GetOrderStatus("DELIVERY"), _ Now, _ "") Catch ex As Exception Logging.WriteLog(Profile.UserName, "UCCAPR-010", ex.Message, "Error Inserting Order Status", TalentCache.GetBusinessUnit, TalentCache.GetPartner(Profile), ProfileHelper.GetPageName, "CheckoutDeliverAddress.ascx") End Try Else createOrderOK = False ErrorLabel.Text = ucr.Content("OrderCreationErrorText", _languageCode, True) End If Catch ex As Exception Logging.WriteLog(Profile.UserName, "UCCAPR-010", ex.Message, "Error Inserting Order Status", TalentCache.GetBusinessUnit, TalentCache.GetPartner(Profile), ProfileHelper.GetPageName, "CheckoutDeliverAddress.ascx") createOrderOK = False ErrorLabel.Text = ucr.Content("OrderCreationErrorText", _languageCode, True) End Try Return createOrderOK End Function Protected Sub SetAddressVisibility() Dim eComDefs As New ECommerceModuleDefaults Dim defs As ECommerceModuleDefaults.DefaultValues = eComDefs.GetDefaults If Not addressLine1RowVisible Then AddressLine1Row.Visible = False BuildingRFV.Enabled = False BuildingRegEx.Enabled = False End If If Not addressLine2RowVisible Then AddressLine2Row.Visible = False Address2RFV.Enabled = False Address2RegEx.Enabled = False End If If Not addressLine3RowVisible Then AddressLine3Row.Visible = False Address3RegEx.Enabled = False End If If Not addressLine4RowVisible Then AddressLine4Row.Visible = False Address4RegEx.Enabled = False End If If Not addressLine5RowVisible Then AddressLine5Row.Visible = False Address5RFV.Enabled = False Address5RegEx.Enabled = False End If If Not addressPostcodeRowVisible Then AddressPostcodeRow.Visible = False postcodeRFV.Enabled = False postcodeRegEx.Enabled = False End If If Not addressCountryRowVisible Then AddressCountryRow.Visible = False CountryDDLRegEx.Enabled = False End If If Not ucr.Attribute("addressingOnOff").Trim = "" Then If Not CType(ucr.Attribute("addressingOnOff"), Boolean) Then FindAddressButtonRow.Visible = False End If End If End Sub Protected Sub SetAddressVisibilityProperties() Dim eComDefs As New ECommerceModuleDefaults Dim defs As ECommerceModuleDefaults.DefaultValues = eComDefs.GetDefaults ' ' Set common address field visibility using system defaults, and then override by any control-level defaults. If Not defs.AddressLine1RowVisible Then addressLine1RowVisible = False End If If Not defs.AddressLine2RowVisible Then addressLine2RowVisible = False End If If Not defs.AddressLine3RowVisible Then addressLine3RowVisible = False End If If Not defs.AddressLine4RowVisible Then addressLine4RowVisible = False End If If Not defs.AddressLine5RowVisible Then addressLine5RowVisible = False End If If Not defs.AddressPostcodeRowVisible Then addressPostcodeRowVisible = False End If If Not defs.AddressCountryRowVisible Then addressCountryRowVisible = False End If ' ' Control-level overrides for visibility (these DO NOT need to exist on tbl_control_attributes) If Not ucr.Attribute("addressLine1RowVisible").Trim = "" Then If Not CType(ucr.Attribute("addressLine1RowVisible"), Boolean) Then addressLine1RowVisible = False Else addressLine1RowVisible = True End If End If If Not ucr.Attribute("addressLine2RowVisible").Trim = "" Then If Not CType(ucr.Attribute("addressLine2RowVisible"), Boolean) Then addressLine2RowVisible = False Else addressLine2RowVisible = True End If End If If Not ucr.Attribute("addressLine3RowVisible").Trim = "" Then If Not CType(ucr.Attribute("addressLine3RowVisible"), Boolean) Then addressLine3RowVisible = False Else addressLine3RowVisible = True End If End If If Not ucr.Attribute("addressLine4RowVisible").Trim = "" Then If Not CType(ucr.Attribute("addressLine4RowVisible"), Boolean) Then addressLine4RowVisible = False Else addressLine4RowVisible = True End If End If If Not ucr.Attribute("addressLine5RowVisible").Trim = "" Then If Not CType(ucr.Attribute("addressLine5RowVisible"), Boolean) Then addressLine5RowVisible = False Else addressLine5RowVisible = True End If End If If Not ucr.Attribute("addressPostcodeRowVisible").Trim = "" Then If Not CType(ucr.Attribute("addressPostcodeRowVisible"), Boolean) Then addressPostcodeRowVisible = False Else addressPostcodeRowVisible = True End If End If If Not ucr.Attribute("addresscountryRowVisible").Trim = "" Then If Not CType(ucr.Attribute("addressCountryRowVisible"), Boolean) Then addressCountryRowVisible = False Else addressCountryRowVisible = True End If End If ' ' Now the control-specific fields (these DO need to exist on tbl_control_attributes) If Not Utilities.CheckForDBNullOrBlank_Boolean_DefaultFalse(ucr.Attribute("addressingOnOff")) Then FindAddressButtonRow.Visible = False End If ' New to control PurchaseOrder this is required in tbl_control_attributes ' If ucr.Attribute("usePurchaseOrder") = "False" Then If Not CBool(ucr.Attribute("usePurchaseOrder")) Then PurchaseOrderRow.Visible = False PurchaseOrderRFV.EnableClientScript = False PurchaseOrderRegEx.EnableClientScript = False ElseIf Not CBool(ucr.Attribute("purchaseOrderRequired")) Then PurchaseOrderRFV.EnableClientScript = False End If DeliveryDayRow.Visible = False DeliveryDateRow.Visible = False PreferredDateRow.Visible = False If Utilities.CheckForDBNullOrBlank_Boolean_DefaultFalse(ucr.Attribute("deliveryDayRowVisible")) Then DeliveryDayRow.Visible = True End If If Utilities.CheckForDBNullOrBlank_Boolean_DefaultFalse(ucr.Attribute("deliveryDateRowVisible")) Then DeliveryDateRow.Visible = True End If If Profile.PartnerInfo.Details.SHOW_PREFERRED_DELIVERY_DATE Then PreferredDateRow.Visible = True End If End Sub Protected Function GetAddressingLinkText() As String Return ucr.Content("addressingLinkButtonText", _languageCode, True) End Function Protected Sub CreateAddressingJavascript() If Utilities.CheckForDBNullOrBlank_Boolean_DefaultFalse(ucr.Attribute("addressingOnOff")) Then Dim defaults As ECommerceModuleDefaults.DefaultValues Dim defs As New ECommerceModuleDefaults Dim sString As String = String.Empty defaults = defs.GetDefaults Response.Write(vbCrLf & "<script language=""javascript"" type=""text/javascript"">" & vbCrLf) Select Case defaults.AddressingProvider.ToUpper Case Is = "QAS" ' Create function to open child window Response.Write("function addressingPopup() {" & vbCrLf) Response.Write("win1 = window.open('../../PagesPublic/QAS/FlatCountry.aspx', 'QAS', '" & ucr.Attribute("addressingWindowAttributes") & "');" & vbCrLf) Response.Write("win1.creator=self;" & vbCrLf) Response.Write("}" & vbCrLf) Case Is = "HOPEWISER" ' Create function to open child window Response.Write("function addressingPopup() {" & vbCrLf) Response.Write("win1 = window.open('../../PagesPublic/Hopewiser/HopewiserPostcodeAndCountry.aspx', 'Hopewiser', '" & ucr.Attribute("addressingWindowAttributes") & "');" & vbCrLf) Response.Write("win1.creator=self;" & vbCrLf) Response.Write("}" & vbCrLf) End Select Dim sAllFields() As String = defaults.AddressingFields.ToString.Split(",") Dim count As Integer = 0 ' ' Create function to populate the address fields. This function is called from FlatAddress.aspx. Response.Write("function UpdateAddressFields() {" & vbCrLf) ' ' Create local function variables used to indicate whether an address element has already been used. Do While count < sAllFields.Length Response.Write("var usedHiddenAdr" & count.ToString & " = '';" & vbCrLf) count = count + 1 Loop ' ' Clear all address fields If addressLine1RowVisible Then Response.Write("document.forms[0]." & building.UniqueID & ".value = '';" & vbCrLf) If addressLine2RowVisible Then Response.Write("document.forms[0]." & Address2.UniqueID & ".value = '';" & vbCrLf) If addressLine3RowVisible Then Response.Write("document.forms[0]." & Address3.UniqueID & ".value = '';" & vbCrLf) If addressLine4RowVisible Then Response.Write("document.forms[0]." & Address4.UniqueID & ".value = '';" & vbCrLf) If addressLine5RowVisible Then Response.Write("document.forms[0]." & Address5.UniqueID & ".value = '';" & vbCrLf) If addressPostcodeRowVisible Then Response.Write("document.forms[0]." & postcode.UniqueID & ".value = '';" & vbCrLf) If addressCountryRowVisible Then Response.Write("document.forms[0]." & CountryDDL.UniqueID & ".value = '';" & vbCrLf) ' ' If an address field is in use and is defined to contain a QAS address element then create Javascript code to populate correctly. If addressLine1RowVisible And Not defaults.AddressingMapAdr1.Trim = "" Then sString = GetJavascriptString("document.forms[0]." & building.UniqueID & ".value", defaults.AddressingMapAdr1, defaults.AddressingFields) Response.Write(sString) End If If addressLine2RowVisible And Not defaults.AddressingMapAdr2.Trim = "" Then sString = GetJavascriptString("document.forms[0]." & Address2.UniqueID & ".value", defaults.AddressingMapAdr2, defaults.AddressingFields) Response.Write(sString) End If If addressLine3RowVisible And Not defaults.AddressingMapAdr3.Trim = "" Then sString = GetJavascriptString("document.forms[0]." & Address3.UniqueID & ".value", defaults.AddressingMapAdr3, defaults.AddressingFields) Response.Write(sString) End If If addressLine4RowVisible And Not defaults.AddressingMapAdr4.Trim = "" Then sString = GetJavascriptString("document.forms[0]." & Address4.UniqueID & ".value", defaults.AddressingMapAdr4, defaults.AddressingFields) Response.Write(sString) End If If addressLine5RowVisible And Not defaults.AddressingMapAdr5.Trim = "" Then sString = GetJavascriptString("document.forms[0]." & Address5.UniqueID & ".value", defaults.AddressingMapAdr5, defaults.AddressingFields) Response.Write(sString) End If If Not defaults.AddressingMapPost.Trim = "" Then sString = GetJavascriptString("document.forms[0]." & postcode.UniqueID & ".value", defaults.AddressingMapPost, defaults.AddressingFields) Response.Write(sString) End If If Not defaults.AddressingMapCountry.Trim = "" Then sString = GetJavascriptString("document.forms[0]." & CountryDDL.UniqueID & ".value", defaults.AddressingMapCountry, defaults.AddressingFields) Response.Write(sString) End If Response.Write("}" & vbCrLf) Response.Write("function trim(s) { " & vbCrLf & "var r=/\b(.*)\b/.exec(s); " & vbCrLf & "return (r==null)?"""":r[1]; " & vbCrLf & "}") Response.Write("</script>" & vbCrLf) End If End Sub Protected Function GetJavascriptString(ByVal sFieldString, ByVal sAddressingMap, ByVal sAddressingFields) As String Dim sString As String = String.Empty Dim count As Integer = 0 Dim count2 As Integer = 0 Const sStr1 As String = "document.forms[0].hiddenAdr" Const sStr2 As String = ".value" Const sStr3 As String = "usedHiddenAdr" Dim sAddressingMapFields() As String = sAddressingMap.ToString.Split(",") Dim sAddressingAllFields() As String = sAddressingFields.ToString.Split(",") Do While count < sAddressingMapFields.Length If Not sAddressingMapFields(count).Trim = "" Then count2 = 0 Do While count2 < sAddressingAllFields.Length If sAddressingMapFields(count).Trim = sAddressingAllFields(count2).Trim Then sString = sString & vbCrLf & _ "if (trim(" & sStr3 & count2.ToString & ") != 'Y' && trim(" & sStr1 & count2.ToString & sStr2 & ") != '') {" & vbCrLf & _ "if (trim(" & sFieldString & ") == '') {" & vbCrLf & _ sFieldString & " = " & sStr1 & count2.ToString & sStr2 & ";" & vbCrLf & _ "}" & vbCrLf & _ "else {" & vbCrLf & _ sFieldString & " = " & sFieldString & " + ', ' + " & sStr1 & count2.ToString & sStr2 & ";" & vbCrLf & _ "}" & vbCrLf & _ sStr3 & count2.ToString & " = 'Y';" & vbCrLf & _ "}" Exit Do End If count2 = count2 + 1 Loop End If count = count + 1 Loop Return sString End Function Protected Sub CreateAddressingHiddenFields() ' ' Create hidden fields for each Addressing field defined in defaults. Dim defaults As ECommerceModuleDefaults.DefaultValues Dim defs As New ECommerceModuleDefaults Dim qasFields() As String = Nothing Dim count As Integer = 0 Dim sString As String = String.Empty defaults = defs.GetDefaults If Utilities.CheckForDBNullOrBlank_Boolean_DefaultFalse(ucr.Attribute("addressingOnOff")) Then qasFields = defaults.AddressingFields.ToString.Split(",") Do While count < qasFields.Length If count = 0 Then Response.Write(vbCrLf) End If sString = "<input type=""hidden"" name=""hiddenAdr" & count.ToString & """ value="" "" />" Response.Write(sString & vbCrLf) count = count + 1 Loop End If End Sub End Class
Imports System.Xml Public Class Server Public serverError As String 'Server errors Public serverVersion As String 'Program version must be equal to server version Public serverRefreshRate As String 'How long program waits before searching for new jobs Public serverCheckIn As String 'Server checking frequency Public serverMaxUsers As String 'How many user can be online (Can be used in the future) Public serverOnline As String 'How long can program run continuously Public servercleanupTime As String 'How long can program be in standby mode before server account is removed Public serverCreation As String 'Server time when user was created (Can be used in the future) Public serverCheckOut As String 'Server time when user must log out (Can be used in the future) ''' <summary> ''' Get variables from XML and server errors. ''' Chekin and register funktion. ''' User exists = return 3 ''' Chekin = return 2 ''' Register = returne 1 ''' ERROR = returne 0 ''' Not valid XML Error = returne -1 ''' XmlReader Error = returne -2 ''' </summary> ''' <param name="URL">XML adress</param> ''' <returns></returns> Public Function GetServerData(ByVal URL As String) As Double Try Dim reader As XmlReader = XmlReader.Create(URL) serverError = "" reader.ReadToFollowing("Task") reader.Read() Select Case reader.Value Case "Checkin" reader.ReadToFollowing("Status") reader.Read() If reader.Value = "UnSuccessful" Then ' reader.ReadToFollowing("error") reader.Read() serverError = reader.Value reader.Close() Return 0 Else reader.Close() Return 2 End If Case "Register" reader.ReadToFollowing("Status") reader.Read() Select Case reader.Value Case "UnSuccessful" reader.ReadToFollowing("error") reader.Read() serverError = reader.Value If reader.Value = "User exists." Then reader.Close() Return 3 End If reader.Close() Return 0 Case "Successful" ReadSettings(reader) reader.Close() Return 1 Case "Semi-Successful" ReadSettings(reader) reader.Close() Return 3 End Select Case Else serverError = "Task not found!" reader.Close() Return -1 End Select Catch ex As Exception Return -1 End Try End Function ''' <summary> ''' Read all settings from server ''' </summary> ''' <param name="reader">XmlReader</param> Private Sub ReadSettings(ByVal reader As XmlReader) Try reader.ReadToFollowing("Version") reader.Read() serverVersion = reader.Value reader.ReadToFollowing("RefreshRate") reader.Read() serverRefreshRate = reader.Value reader.ReadToFollowing("CheckIn") reader.Read() serverCheckIn = reader.Value reader.ReadToFollowing("MaxUsers") reader.Read() serverMaxUsers = reader.Value reader.ReadToFollowing("Online") reader.Read() serverOnline = reader.Value reader.ReadToFollowing("cleanupTime") reader.Read() servercleanupTime = reader.Value reader.ReadToFollowing("Creation") reader.Read() serverCreation = reader.Value reader.ReadToFollowing("CheckOut") reader.Read() serverCheckOut = reader.Value Catch ex As Exception End Try End Sub ''' <summary> ''' Exit from server. Remove user data from server. ''' </summary> ''' <param name="userID">Registerd user ID</param> Public Sub ExitServer(ByVal userID As String) Try Dim reader As XmlReader = XmlReader.Create("http://ouroborosrg.16mb.com/Exit.php?user=" + userID) Catch ex As Exception End Try End Sub End Class
Imports System.Data.OleDb Imports System.IO Public Class frmPedidoMP Enum TagType eEditar = 1 eSalvar = 2 eLoc = 3 eNone = 0 End Enum Dim Ação As New TrfGerais() Dim cr As DevComponents.DotNetBar.SuperTabControl Dim iteRes As New ReservaMP Dim iteMP As New ClassMP Dim bs As BindingSource Dim db As New clsBancoDados Dim item As New clsItemMP Dim loadPed As New ClassMostraPedido Dim PMP As New clsPedidoMP Dim cls As New cCondicaoPgto ''' <summary>'''usando para indicar o status do botao ''' </summary> Public Value As TagType = TagType.eNone Dim valorParcelamento As Double Private Sub btnAdicionarItem_Click(sender As Object, e As EventArgs) Handles btnAdicionarItem.Click If String.IsNullOrEmpty(Me.ModeloVenda.Text) Or String.IsNullOrEmpty(CodigoVendedor.Text) Or String.IsNullOrEmpty(NomeCliente.Text) Or String.IsNullOrEmpty(Me.DataPrazo.Text) Or String.IsNullOrEmpty(Contato.Text) Then MessageBox.Show("Existem campos não preenchidos no cabeçalho.Verifique e tente novamente.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub End If If Me.chkConfirmado.Checked = True Then Return End If If NzZero(Me.NumeroPedido.Text) = 0 Then With PMP .CodigoCliente = NzZero(Me.CodigoCliente.Text) .nomeCliente = Me.NomeCliente.Text .Telefone = Me.txttelefone.Text .Email = Me.txtEmail.Text .DataPedido = Me.DataPedido.Text .DataPrazoEntrega = Me.DataPrazo.Text .Contato = Me.Contato.Text .CodigoFuncionario = Me.CodigoVendedor.Text .Status = Me.status.Text .Observacao = Me.Obs.Text .DataFechamento = Me.DataFechamento.Text .ValorBordado = Me.ValorBordado.Text .ValorSerigrafia = Me.ValorSerigrafia.Text .TotalBruto = Me.TotalBruto.Text .TotalLiquido = Me.TotalLiquido.Text .Modelo = Me.ModeloVenda.Text.Substring(0, 1) .Empresa = CodEmpresa .Datavalidade = DataValidade.Text End With PMP.Gravar() Dim var As String var = Retorno Me.NumeroPedido.Text = var.PadLeft(6, "0") Me.btnSalvaEditar.Enabled = True Value = TagType.eSalvar Me.ModeloVenda.Enabled = False End If vEnum = Operacao.inclusao My.Forms.frmAdicionarItemMP.ShowDialog() 'se inseriu dados nos item o cabeçalho do cliente é bloqueado, caso contrario é liberado If CDbl(Me.txtPecas.Text) > 1 Then Me.cabCliente.Enabled = False Me.btnGerarPedidos.Enabled = True Else Me.cabCliente.Enabled = True Me.btnGerarPedidos.Enabled = False End If Retorno = Nothing End Sub Private Sub btnFechar_Click(sender As Object, e As EventArgs) Handles btnFechar.Click If String.IsNullOrEmpty(Me.NumeroPedido.Text) Then Me.Dispose() Exit Sub End If If Value = TagType.eEditar Or Value = TagType.eNone Then Retorno = 0 Me.Close() Me.Dispose() Else MessageBox.Show("Você prescisa salvar o registro primeiro", "Validação de dados", MessageBoxButtons.OK, MessageBoxIcon.Warning) Exit Sub End If Me.Close() Me.Dispose() End Sub Private Sub btnNovo_Click(sender As Object, e As EventArgs) Handles btnNovo.Click If Value = TagType.eSalvar Then MessageBox.Show("O registro atual foi editado, Clique no botão salvar para processiguir", "Validação de dados", MessageBoxButtons.OK, MessageBoxIcon.Warning) Exit Sub End If Ação.LimpaTextBox(Me) Me.grpCab.Enabled = True Me.grpReservaMP.Enabled = True Me.stcMP.Enabled = True Me.DataPedido.Text = DataDia Me.TotalBruto.Text = FormatCurrency(0, 2) Me.TotalLiquido.Text = FormatCurrency(0, 2) Me.ValorSerigrafia.Text = FormatCurrency(0, 2) Me.ValorBordado.Text = FormatCurrency(0, 2) Me.TotalDosItem.Text = FormatCurrency(0, 2) Me.txtPecas.Text = FormatNumber(0, 2) Me.chkConfirmado.Checked = False Me.status.Text = "ABERTO" Me.status.ForeColor = Color.Green Me.btnConfirmar.Enabled = True Me.ValorDesconto.Enabled = True Me.ValorSerigrafia.Enabled = True Me.ValorBordado.Enabled = True Me.CodigoPagamento.Enabled = True Me.ValorAVista.Enabled = True Me.ValorOutros.Enabled = True Me.ValorAFaturar.Enabled = True Me.btnSalvaEditar.Enabled = True Me.lblGeradoPedido.Visible = False Me.chkGeradoPedido.Checked = False btnGerarPedidos.Enabled = False item.AtGrade(0) iteRes.AtGrade(0) 'iteMP.AtGrade(0) Me.dgvParcelamento.Rows.Clear() If Me.NumeroPedido.Text = "00000" Or String.IsNullOrEmpty(Me.NumeroPedido.Text) Then Me.ModeloVenda.Enabled = True Me.ModeloVenda.SelectedIndex = -1 Me.ModeloVenda.Focus() Me.btnSalvaEditar.Text = "Salvar" Value = TagType.eNone End Sub Private Sub CodigoCliente_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles CodigoCliente.KeyDown If e.KeyCode = Keys.F5 Then My.Forms.ClientesProcura.ShowDialog() If Not String.IsNullOrEmpty(Retorno) Then Me.CodigoCliente.Text = Retorno LocalizarCliente() End If End If End Sub Private Sub CodigoCliente_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles CodigoCliente.KeyPress Dim KeyAscii As Short = CShort(Asc(e.KeyChar)) KeyAscii = CShort(OnlyNumber(KeyAscii)) If KeyAscii = 0 Then e.Handled = True End If End Sub Private Sub CodigoCliente_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CodigoCliente.Leave LocalizarCliente() Me.Contato.Focus() End Sub Private Sub CodigoVendedor_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles CodigoVendedor.KeyDown If e.KeyCode = Keys.F5 Then My.Forms.PedidoVendaFindVendedores.ShowDialog() End If 'If Not IsNumeric(Chr(e.KeyCode)) And e.KeyCode <> 8 Then ' e.SuppressKeyPress = True 'End If End Sub Private Sub CodigoVendedor_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles CodigoVendedor.KeyPress Dim KeyAscii As Byte = Convert.ToByte(e.KeyChar) If KeyAscii = 13 Then Exit Sub If (KeyAscii < 48 Or KeyAscii > 58) And KeyAscii <> 8 Then e.Handled = True End If End Sub Private Sub CodigoVendedor_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CodigoVendedor.Leave Localizar(Me.CodigoVendedor.Text) End Sub Private Sub DataPrazo_KeyDown(sender As Object, e As KeyEventArgs) Handles DataPrazo.KeyDown If e.KeyCode = Keys.Return Then Me.stcMP.SelectedTab = Me.ItemPedidoGeral Me.btnAdicionarItem.Focus() End If End Sub Private Sub frmPedidoMP_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown Select Case e.KeyCode Case Keys.F4 btnReservaMP_Click(sender, e) 'chama o frmReservaLancar Case Keys.F6 If Value = TagType.eEditar Then MessageBox.Show("Clique no botão editar", "Validação de Dados", MessageBoxButtons.OK, MessageBoxIcon.Information) Exit Sub End If btnAdicionarItem_Click(sender, e) 'chama o frmAdicionarItemMP Case Keys.F7 Me.stcMP.SelectedTab = Me.ItemFechamento Me.DataFechamento.Focus() Me.DataFechamento.Text = DataDia Me.TotalBruto.Text = FormatCurrency(Me.TotalDosItem.Text, 2) End Select End Sub Private Sub frmPedidoMP_Load(sender As Object, e As EventArgs) Handles MyBase.Load cr = Me.stcMP cr.SelectedTabIndex = 0 Me.grpCab.Enabled = False Me.grpReservaMP.Enabled = False Me.stcMP.Enabled = False End Sub Public Sub Localizar(ByVal xID As Integer) Dim sql As String sql = "Select códigofuncionário,nome from funcionários where AdicionarEmVendas=true and códigofuncionário=" & xID Dim conn As New OleDbConnection Dim DR As OleDbDataReader Try conn = db.AbreBanco Dim cmd As New OleDbCommand(sql, conn) DR = cmd.ExecuteReader DR.Read() If DR.HasRows Then Me.CodigoVendedor.Text = DR.Item("códigofuncionário") Me.NomeVendedor.Text = DR.Item("nome") & "" Else MessageBox.Show("Código não existe para esse vendedor", "Erro...", MessageBoxButtons.OK, MessageBoxIcon.Error) Me.CodigoVendedor.Clear() End If Catch ex As Exception Throw ex Finally db.fechabanco(conn) End Try End Sub Private Sub LocalizarCliente() Dim conn As New OleDbConnection conn = db.AbreBanco Dim Sql As String = "Select * from Clientes where Codigo = " & Me.CodigoCliente.Text Dim CMD As New OleDb.OleDbCommand(Sql, conn) Dim DR As OleDb.OleDbDataReader DR = CMD.ExecuteReader DR.Read() If DR.HasRows Then If DR.Item("Bloqueado") = True Then MessageBox.Show("Este cliente esta bloqueado, Favor verificar", "Validação de Dados", MessageBoxButtons.OK, MessageBoxIcon.Information) Me.CodigoCliente.Clear() Me.NomeCliente.Clear() Exit Sub End If If IsDBNull(DR.Item("TpComercio")) Then MessageBox.Show("Este cliente esta sem o tipo de comércio, Favor verificar", "Validação de Dados", MessageBoxButtons.OK, MessageBoxIcon.Information) Me.CodigoCliente.Clear() Me.NomeCliente.Clear() Exit Sub End If Me.NomeCliente.Text = DR.Item("Nome").ToString Me.txttelefone.Text = DR.Item("Telefone").ToString Me.txtEmail.Text = DR.Item("email").ToString Else MessageBox.Show("Cliente não localizado, Favor verificar", "Validação de Dados", MessageBoxButtons.OK, MessageBoxIcon.Information) Me.CodigoCliente.Clear() Me.NomeCliente.Clear() Exit Sub End If End Sub Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click If String.IsNullOrEmpty(Me.ModeloVenda.Text) Or String.IsNullOrEmpty(CodigoVendedor.Text) Then MessageBox.Show("Falta informações no cabeçalho verifique os seguinte campos: [Modelo], [Tipo de Venda], [Vendedor]." _ & Microsoft.VisualBasic.ControlChars.CrLf & "Todos esses campos devem ser preenchidos.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub End If If dgvParcelamento.RowCount > 0 Then MessageBox.Show("Já foram gerados parcelamentos ou inseridos itens para esse pedido." _ & Microsoft.VisualBasic.ControlChars.CrLf & "Não será possível editá-los.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub End If 'Me.CodigoCliente.Clear() 'Me.NomeCliente.Clear() 'Me.txttelefone.Clear() 'Me.txtEmail.Clear() My.Forms.ClientesProcura.ShowDialog() Me.NomeCliente.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Me.txtEmail.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Me.txttelefone.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim If Not String.IsNullOrEmpty(CodigoCliente.Text) And CodigoCliente.Text <> 0 Then LocalizarCliente() End If End Sub Private Sub DataPrazo_Leave(sender As Object, e As EventArgs) Handles DataPrazo.Leave If Not String.IsNullOrEmpty(Me.DataPedido.Text) Then If DateDiff(DateInterval.Day, CDate(Me.DataPedido.Text), CDate(Me.DataPrazo.Text)) < 0 Then MessageBox.Show("A data do prazo não pode ser menor que a data do pedido.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Me.DataPrazo.Clear() Exit Sub End If End If End Sub Private Sub btnReservaMP_Click(sender As Object, e As EventArgs) Handles btnReservaMP.Click If String.IsNullOrEmpty(Me.ModeloVenda.Text) Or String.IsNullOrEmpty(CodigoVendedor.Text) Or String.IsNullOrEmpty(NomeCliente.Text) Then MessageBox.Show("Existem campos não preenchidos no cabeçalho.Verifique e tente novamente.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub End If 'verifica se o pedido não foi confirmado If Not Me.chkConfirmado.Checked Then My.Forms.frmReservaLancar.ShowDialog() End If End Sub Private Sub PictureBox2_Click(sender As Object, e As EventArgs) Handles imgBuscaCondicao.Click My.Forms.CondicaoPagamentoBuscaMP.ShowDialog() End Sub Private Sub CodigoPagamento_KeyPress(sender As Object, e As KeyPressEventArgs) Handles CodigoPagamento.KeyPress Dim KeyAscii As Short = CShort(Asc(e.KeyChar)) KeyAscii = CShort(OnlyNumber(KeyAscii)) If KeyAscii = 0 Then e.Handled = True End If End Sub Private Sub CodigoPagamento_KeyDown(sender As Object, e As KeyEventArgs) Handles CodigoPagamento.KeyDown If e.KeyCode = Keys.F5 Then My.Forms.CondicaoPagamentoBuscaMP.ShowDialog() End If End Sub Private Sub btnGerarParcelas_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGerarParcelas.Click If String.IsNullOrEmpty(Me.CodigoPagamento.Text) Then MessageBox.Show("Não foi selecionado o pagamento para este pedido." & Microsoft.VisualBasic.ControlChars.CrLf & "Para gerar novos parcelamentos, Escolha uma forma de Pagamento.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub End If If dgvParcelamento.RowCount > 0 Then MessageBox.Show("Já foi gerado parcelamento para este pedido." & Microsoft.VisualBasic.ControlChars.CrLf & "Para gerar novos parcelamentos, exclua as parcelas existentes.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub End If Try Me.TotalLiquido.Text = FormatCurrency(CDbl(Me.TotalBruto.Text) - CDbl(Me.ValorDesconto.Text), 2) Catch ex As Exception MessageBox.Show("Houve um erro de violação, digite o valor novamente", "Validação de dados", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End Try If dgvParcelamento.RowCount > 0 Then MessageBox.Show("Já foram geradas parcelas. Para gerar novamente exclua as existentes." _ & Microsoft.VisualBasic.ControlChars.CrLf & "--------------------------------------------------------------------------" _ & Microsoft.VisualBasic.ControlChars.CrLf & "Qualquer duvida contacte o suporte.", "Validação de dados", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Return End If If Me.chkConfirmado.Checked = True Then Return End If If Me.DataFechamento.Text = "" Then Me.DataFechamento.Text = DataDia End If cls.Localizar(Me.CodigoPagamento.Text) If cls.TemEntrada = True And NzZero(Me.ValorAVista.Text) = 0 Then MessageBox.Show("Esta condição de pagamento necessita de uma entrada." & Microsoft.VisualBasic.ControlChars.CrLf & "Digite um Valor no campo ""A vista"".", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Me.ValorAVista.Focus() Exit Sub End If 'Pegar o total de Parcelamentos Dim Parcelas() As String = Split(cls.DiasParcelamento, "-") Dim Contar As Integer Dim Dividido As Decimal Dim conn As New OleDbConnection conn = db.AbreBanco Dim Ds As New DataSet Dim Sql As String = "SELECT * from Receber Where Id = -1" Dim DAReceber As New OleDb.OleDbDataAdapter(Sql, conn) DAReceber.Fill(Ds, "Receber") If Me.DescricaoPagamento.Text = "MENSAL" Then 'Gerar valor mensal Dim DrNew As DataRow DrNew = Ds.Tables("Receber").NewRow Dim Parc As String = Me.NumeroPedido.Text & "-" & 1 & "/" & 1 DrNew("Documento") = Parc DrNew("DataDocumento") = Me.DataPedido.Text DrNew("ValorDocumento") = CDbl(Me.ValorAFaturar.Text) DrNew("LocalPgto") = "CARTEIRA" DrNew("PedidoMP") = Me.NumeroPedido.Text DrNew("CodCliente") = Me.CodigoCliente.Text DrNew("Cliente") = Me.NomeCliente.Text DrNew("Empresa") = CodEmpresa DrNew("OriginalParcial") = "O" DrNew("Vendedor") = Me.CodigoVendedor.Text DrNew("Vencimento") = DateSerial(Year(DataDia), Month(DataDia) + 1, DiaFechamentoMensal) 'gera o vencimento para o dia 10 de cada mês. DrNew("MediaDescontoPedido") = 0 DrNew("PercentComissao") = 0 DrNew("ContaValorBaixado") = Nz(CodLancamentoReceber, 1) DrNew("ContaCR") = Nz(VAR_ContaCrVenda, 1) DrNew("Virtual") = True Ds.Tables("Receber").Rows.Add(DrNew) Else 'caso contrário usa outro parcelamento Dividido = Me.ValorAFaturar.Text / Parcelas.Length For Contar = 1 To Parcelas.Length Dim DrNew As DataRow DrNew = Ds.Tables("Receber").NewRow Dim Parc As String = Me.NumeroPedido.Text & "MP-" & Contar & "/" & Parcelas.Length DrNew("Documento") = Parc DrNew("DataDocumento") = Me.DataPedido.Text DrNew("ValorDocumento") = Dividido DrNew("LocalPgto") = "CARTEIRA" DrNew("PedidoMP") = Me.NumeroPedido.Text DrNew("CodCliente") = Me.CodigoCliente.Text DrNew("Cliente") = Me.NomeCliente.Text DrNew("Empresa") = CodEmpresa DrNew("OriginalParcial") = "O" DrNew("Vendedor") = Me.CodigoVendedor.Text DrNew("Vencimento") = DataDia.AddDays(CInt(Parcelas(Contar - 1))) DrNew("MediaDescontoPedido") = 0 DrNew("PercentComissao") = 0 DrNew("ContaValorBaixado") = Nz(CodLancamentoReceber, 1) DrNew("ContaCR") = Nz(VAR_ContaCrVenda, 1) DrNew("Virtual") = True Ds.Tables("Receber").Rows.Add(DrNew) Next End If Dim objCommandBuilder As New OleDb.OleDbCommandBuilder(DAReceber) 'Usa a classe commandbuilder para criar os comandos de update,insert, delete DAReceber.Update(Ds, "Receber") 'faz uma Insert na tabela receber usando o commandbuilder. System.Threading.Thread.Sleep(1000) 'retarda 1s para a próxima execução atGridParcelas() 'atualiza o grid de recebimentos btnSalvaEditar_Click(sender, e) End Sub Private Sub atGridParcelas() Dim conn As New OleDbConnection conn = db.AbreBanco Dim Sql As String = "SELECT * FROM Receber Where Receber.Documento <> '" & Me.NumeroPedido.Text & "-AVISTA-MP' And Receber.Documento <> 'CHEQUE' AND PedidoMP=" & CInt(Me.NumeroPedido.Text) & " Order By id" Dim ocmd As New OleDb.OleDbCommand(Sql, conn) Dim odr As OleDb.OleDbDataReader odr = ocmd.ExecuteReader Dim i As Integer Dim row As New DataGridViewRow Dim cVlr As Double = 0 Me.dgvParcelamento.Rows.Clear() While odr.Read() i += 1 'preenche o grid com alguns dados Dim row0 As String() = {odr.Item("Id"), odr.Item("Documento"), odr.Item("NotaFiscal").ToString, odr.Item("Vencimento"), FormatCurrency(odr.Item("valorDocumento"), 2), odr.Item("LocalPgto")} 'adiciona as linhas With Me.dgvParcelamento.Rows .Add(row0) End With cVlr += odr.Item("valorDocumento") ' Me.txtTotal.Text = FormatCurrency(cVlr, 2) End While valorParcelamento = cVlr End Sub Private Sub CodigoPagamento_Leave(sender As Object, e As EventArgs) Handles CodigoPagamento.Leave cls.Localizar(Me.CodigoPagamento.Text) If Not cls.pReturnErro Then Me.DescricaoPagamento.Text = cls.Descricao End If btnGerarParcelas.Focus() Me.CodigoPagamento.Enabled = False Me.DescricaoPagamento.Enabled = False End Sub Private Sub ValorDesconto_Leave(sender As Object, e As EventArgs) Handles ValorDesconto.Leave Try If CDbl(Me.ValorDesconto.Text) < 0 Or String.IsNullOrEmpty(Me.ValorDesconto.Text) Then MessageBox.Show("O valor não pode ser negativo ou nulo", "Validação de dados", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Me.ValorDesconto.Text = FormatNumber(0, 2) Exit Sub End If Me.TotalLiquido.Text = FormatCurrency(CDbl(Me.TotalBruto.Text) - CDbl(Me.ValorDesconto.Text), 2) Catch ex As Exception MessageBox.Show("Houve um erro de violação, digite o valor novamente", "Validação de dados", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End Try End Sub Private Sub btnEditarParcelas_Click(sender As Object, e As EventArgs) Handles btnEditarParcelas.Click If dgvParcelamento.RowCount = 0 Then MessageBox.Show("Não foi gerado parcelamento para este pedido.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub End If If Me.chkConfirmado.Checked Then MessageBox.Show("Este pedido já foi confirmando, não é possível editar as parcelas.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub End If My.Forms.EditParcelaMP.Total.Text = Me.ValorAFaturar.Text My.Forms.EditParcelaMP.ShowDialog() atGridParcelas() End Sub Private Sub ValorAvista_Enter(sender As Object, e As EventArgs) Handles ValorAVista.Enter 'verifica se o valor a vista esta vazio entao coloca zero 'verifi se tem parcelamento ja feito or se o pedido esta confirmado entao bloqueia o valor a vista e outros If Me.ValorAVista.Text = "" Then Me.ValorAVista.Text = FormatCurrency(0, 2) If Me.dgvParcelamento.Rows.Count > 0 Or Me.chkConfirmado.Checked = True Then Me.ValorAVista.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Me.ValorOutros.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Else Me.ValorAVista.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não Me.ValorOutros.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não Me.CodigoPagamento.Clear() Me.DescricaoPagamento.Clear() End If End Sub Private Sub ValorAvista_Leave(sender As Object, e As EventArgs) Handles ValorAVista.Leave If CDbl(Me.ValorAVista.Text) > 0 Then Me.ValorOutros.Text = FormatCurrency(0, 2) Me.ValorAFaturar.Text = FormatCurrency(0, 2) End If Me.ValorAFaturar.Text = FormatCurrency(CDbl(NzZero(Me.TotalLiquido.Text)) - CDbl(NzZero(Me.ValorAVista.Text)) - CDbl(NzZero(Me.ValorOutros.Text)), 2) Me.ValorAVista.Text = FormatCurrency(Me.ValorAVista.Text, 2) If CDbl(Me.ValorAVista.Text) = CDbl(Me.TotalLiquido.Text) Then Me.Panel1.Enabled = False End If End Sub Private Sub ValorOutros_Enter(sender As Object, e As EventArgs) Handles ValorOutros.Enter If Me.dgvParcelamento.Rows.Count = 0 Then If CDbl(Me.ValorAVista.Text) = CDbl(Me.TotalLiquido.Text) Then Me.ValorOutros.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Exit Sub End If Me.ValorOutros.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não Else Me.ValorOutros.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim End If If Me.ValorOutros.Text = "" Then Me.ValorOutros.Text = FormatCurrency(0, 2) End Sub Private Sub ValorOutros_Leave(sender As Object, e As EventArgs) Handles ValorOutros.Leave Me.ValorAFaturar.Text = FormatCurrency(CDbl(NzZero(Me.TotalLiquido.Text)) - CDbl(NzZero(Me.ValorAVista.Text)) - CDbl(NzZero(Me.ValorOutros.Text)), 2) If CDbl(Me.ValorAFaturar.Text) = 0 Then Me.Panel1.Enabled = False Else Me.Panel1.Enabled = True Me.CodigoPagamento.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não End If If CDbl(Me.ValorAFaturar.Text) < 0 Then MessageBox.Show("O Valor do Cheque está utrapassado o valor total do pedido. Corrija este valor.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Me.ValorOutros.Clear() Me.ValorOutros.Text = FormatCurrency(0, 2) Me.ValorOutros.Focus() Me.ValorAFaturar.Text = FormatCurrency(CDbl(NzZero(Me.TotalLiquido.Text)) - CDbl(NzZero(Me.ValorAVista.Text)) - CDbl(NzZero(Me.ValorOutros.Text)), 2) Exit Sub End If Me.ValorOutros.Text = FormatCurrency(Me.ValorOutros.Text, 2) Me.CodigoPagamento.Focus() Me.btnConfirmar.Enabled = True End Sub Private Sub ValorAvista_Validated(sender As Object, e As EventArgs) Handles ValorAVista.Validated If CDbl(Me.ValorAVista.Text) > CDbl(Me.TotalLiquido.Text) Then MessageBox.Show("O Valor não pode ser maior que o total liquido do pedido", "Validadação de dados", MessageBoxButtons.OK, MessageBoxIcon.Warning) Me.ValorAVista.Text = FormatCurrency(0, 2) Me.ValorAFaturar.Text = FormatCurrency(CDbl(NzZero(Me.TotalLiquido.Text)) - CDbl(NzZero(Me.ValorAVista.Text)) - CDbl(NzZero(Me.ValorOutros.Text)), 2) Exit Sub End If End Sub Private Sub TotalBruto_Enter(sender As Object, e As EventArgs) Handles TotalBruto.Enter Me.TotalBruto.Text = FormatCurrency(Me.TotalDosItem.Text, 2) End Sub Private Sub ModeloVenda_Leave(sender As Object, e As EventArgs) Handles ModeloVenda.Leave If String.IsNullOrEmpty(ModeloVenda.Text) Then MessageBox.Show("Escolha {PEDIDO} ou {ORÇAMENTO} para prosseguir.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Me.ModeloVenda.Focus() Exit Sub Else If Me.ModeloVenda.Text = "ORCAMENTO" Then Me.ItemFechamento.Visible = False Me.grpReservaMP.Enabled = False Me.btEditarCliente.Enabled = True Me.txtEmail.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não Me.txttelefone.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não Me.NomeCliente.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não Me.cabCliente.Enabled = True Me.DataValidade.Text = DataDia.AddDays(10) Me.ModeloVenda.Enabled = False Else Me.ItemFechamento.Visible = True Me.grpReservaMP.Enabled = True Me.btEditarCliente.Enabled = True Me.btEditarCliente.Enabled = False Me.txtEmail.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Me.txttelefone.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Me.NomeCliente.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Me.DataPrazo.Enabled = True Me.cabCliente.Enabled = True Me.btnReservaMP.Enabled = True Me.ModeloVenda.Enabled = False End If Me.btnAdicionarItem.Enabled = True End If End Sub Private Sub btEditarCliente_Click(sender As Object, e As EventArgs) Handles btEditarCliente.Click If String.IsNullOrEmpty(Me.ModeloVenda.Text) Or String.IsNullOrEmpty(CodigoVendedor.Text) Then MessageBox.Show("Falta informações no cabeçalho verifique os seguinte campos: [Modelo], [Tipo de Venda], [Vendedor]." _ & Microsoft.VisualBasic.ControlChars.CrLf & "Todos esses campos devem ser preenchidos.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub End If Me.NomeCliente.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não Me.txtEmail.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não Me.txttelefone.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não Me.CodigoCliente.Text = 0 Me.NomeCliente.Clear() Me.txtEmail.Clear() Me.txttelefone.Clear() Me.CodigoCliente.Text = 0 Me.NomeCliente.Focus() End Sub Private Sub btnSalvaEditar_Click(sender As Object, e As EventArgs) Handles btnSalvaEditar.Click If String.IsNullOrEmpty(Me.NumeroPedido.Text) Then Exit Sub End If If Value = TagType.eEditar Then 'Libera os campos para ser editados e muda o lengenda do botão para salvar If Me.chkGeradoPedido.Checked Then MessageBox.Show("Este Orçamento já foi gerado um pedido", "Validação de Dados", MessageBoxButtons.OK, MessageBoxIcon.Warning) Exit Sub End If grpCab.Enabled = True Me.stcMP.Enabled = True Me.btnSalvaEditar.Text = "Salvar" Me.btnAdicionarItem.Enabled = True Value = TagType.eSalvar If Me.ModeloVenda.Text = "ORCAMENTO" Then Me.ModeloVenda.Enabled = False Me.ItemFechamento.Visible = False Me.grpReservaMP.Enabled = False Me.btEditarCliente.Enabled = True Me.txtEmail.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não Me.txttelefone.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não Me.NomeCliente.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não Me.cabCliente.Enabled = True Else Me.ModeloVenda.Enabled = False Me.ItemFechamento.Visible = True Me.grpReservaMP.Enabled = True Me.btEditarCliente.Enabled = True Me.btEditarCliente.Enabled = False Me.txtEmail.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Me.txttelefone.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Me.NomeCliente.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Me.DataPrazo.Enabled = True Me.cabCliente.Enabled = True Me.btnAdicionarItem.Enabled = True Me.btnReservaMP.Enabled = True End If ElseIf Value = TagType.eSalvar Then With PMP .CodigoCliente = NzZero(Me.CodigoCliente.Text) .DataPedido = Me.DataPedido.Text .DataPrazoEntrega = Me.DataPrazo.Text .Contato = Me.Contato.Text .CodigoFuncionario = Me.CodigoVendedor.Text .Status = Me.status.Text .Observacao = Me.Obs.Text .DataFechamento = Me.DataFechamento.Text .ValorBordado = Me.ValorBordado.Text .ValorSerigrafia = Me.ValorSerigrafia.Text .TotalBruto = Me.TotalBruto.Text .TotalLiquido = Me.TotalLiquido.Text .TotalDesconto = NzZero(Me.ValorDesconto.Text) '.ValorMP = Me.TotalMP.Text .CodigoPagamento = Nz(Me.CodigoPagamento.Text, 2) .nomeCliente = Me.NomeCliente.Text .Telefone = Me.txttelefone.Text .Email = Me.txtEmail.Text .Valorfaturar = CDbl(NzZero(Me.ValorAFaturar.Text)) .Valorvista = CDbl(NzZero(ValorAVista.Text)) .Valorcheque = CDbl(NzZero(ValorOutros.Text)) .Modelo = Me.ModeloVenda.Text.Substring(0, 1) .Datavalidade = Me.DataValidade.Text .Gerado_pedido = Me.chkGeradoPedido.Checked .Observacao = Me.Obs.Text End With PMP.Editar(Me.NumeroPedido.Text) Me.btnSalvaEditar.Enabled = True Value = TagType.eEditar 'Salva o registro e muda a lengenda do botão para editar Me.btnSalvaEditar.Text = "Editar" Value = TagType.eEditar Me.grpCab.Enabled = False Me.btnAdicionarItem.Enabled = False Me.btnReservaMP.Enabled = False End If End Sub Private Sub ButtonItem2_Click(sender As Object, e As EventArgs) Handles ButtonItem2.Click sTipoBusca = "P" BuscaPedido() Me.ItemFechamento.Visible = True If Me.dgvParcelamento.RowCount > 0 Then Me.CodigoPagamento.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Me.ValorAVista.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Me.ValorOutros.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Else Me.CodigoPagamento.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não Me.ValorAVista.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não Me.ValorOutros.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não End If End Sub Private Sub ButtonItem1_Click(sender As Object, e As EventArgs) Handles ButtonItem1.Click sTipoBusca = "O" BuscaPedido() Me.ItemFechamento.Visible = False End Sub Private Sub BuscaPedido() Me.grpCab.Enabled = False Me.grpReservaMP.Enabled = False Me.stcMP.Enabled = False Retorno = String.Empty My.Forms.PedidoMPBusca.ShowDialog() If Not String.IsNullOrEmpty(Retorno) Then PMP.MostrarPedido(Retorno, sTipoBusca) With PMP Me.NumeroPedido.Text = .NumeroPedido Me.DataPedido.Text = .DataPedido Me.CodigoVendedor.Text = .CodigoFuncionario Me.NomeVendedor.Text = .NomeVendedor Me.CodigoCliente.Text = .CodigoCliente Me.NomeCliente.Text = .nomeCliente Me.DataPrazo.Text = .DataPrazoEntrega Me.Contato.Text = .Contato Me.Obs.Text = .Observacao Me.chkConfirmado.Checked = .Fechado Me.TotalLiquido.Text = FormatCurrency(.TotalLiquido, 2) Me.TotalBruto.Text = FormatCurrency(.TotalBruto, 2) Me.ValorBordado.Text = FormatCurrency(.ValorBordado, 2) Me.ValorSerigrafia.Text = FormatCurrency(.ValorSerigrafia, 2) Me.ValorDesconto.Text = FormatCurrency(.TotalDesconto, 2) Me.CodigoPagamento.Text = .CodigoPagamento Me.DescricaoPagamento.Text = .Codigopagamentodesc Me.DataFechamento.Text = .DataFechamento Me.ValorAVista.Text = FormatCurrency(.Valorvista, 2) Me.ValorAFaturar.Text = FormatCurrency(.Valorfaturar, 2) Me.ValorOutros.Text = FormatCurrency(.Valorcheque, 2) Me.ModeloVenda.Text = .Modelo Me.txttelefone.Text = .Telefone Me.txtEmail.Text = .Email Me.chkGeradoPedido.Checked = .Gerado_pedido Me.chkConfirmado.Checked = .Fechado item.Modelo = .Modelo.Substring(0, 1) item.AtGrade(.NumeroPedido) If ModeloVenda.Text = "PEDIDO" Then btnGerarPedidos.Enabled = False If Me.chkConfirmado.Checked = True Then Me.status.Text = "FECHADO" Me.status.ForeColor = Color.Red Me.btnConfirmar.Enabled = False Me.btnSalvaEditar.Enabled = False Me.stcMP.Enabled = True Me.DataFechamento.Enabled = False Me.TotalBruto.Enabled = False Me.ValorBordado.Enabled = False Me.ValorSerigrafia.Enabled = False Me.ValorDesconto.Enabled = False Me.CodigoPagamento.Enabled = False Me.ValorAVista.Enabled = False Me.ValorOutros.Enabled = False Me.imgBuscaCondicao.Enabled = False Me.Obs.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Me.DataValidade.Clear() Else Me.status.Text = "ABERTO" Me.status.ForeColor = Color.Green Me.btnConfirmar.Enabled = True Me.DataFechamento.Enabled = True Me.TotalBruto.Enabled = True Me.ValorBordado.Enabled = True Me.ValorSerigrafia.Enabled = True Me.ValorDesconto.Enabled = True Me.CodigoPagamento.Enabled = True Me.ValorAVista.Enabled = True Me.ValorOutros.Enabled = True Me.imgBuscaCondicao.Enabled = True Me.btnSalvaEditar.Enabled = True Me.Obs.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não Me.Panel1.Enabled = False Me.lblGeradoPedido.Visible = False Me.DataValidade.Clear() Value = TagType.eEditar End If iteRes.AtGrade(.NumeroPedido) 'iteMP.AtGrade(.NumeroPedido) atGridParcelas() Else iteRes.AtGrade(0) Me.DataValidade.Text = .Datavalidade Me.status.Text = "ABERTO" Me.status.ForeColor = Color.Green Me.btnSalvaEditar.Enabled = True If Me.chkGeradoPedido.Checked Then Me.lblGeradoPedido.Visible = True Me.lblGeradoPedido.Text = "Orçamento gerado Pedido N. " & String.Format("{0:000000}", Convert.ToInt16(.OrcForPed)) btnGerarPedidos.Enabled = False Else Me.lblGeradoPedido.Visible = False If Me.dgvItemGeral.RowCount > 0 Then btnGerarPedidos.Enabled = True End If End If End If 'muda a lengenda do botão para editar Me.btnSalvaEditar.Text = "Editar" Value = TagType.eEditar End With End If Retorno = Nothing End Sub Private Sub btnPesquisar_Click(sender As Object, e As EventArgs) Handles btnPesquisar.Click If Value = TagType.eEditar Or Value = TagType.eNone Then Retorno = 0 Else MessageBox.Show("Você prescisa salvar o registro primeiro", "Validação de dados", MessageBoxButtons.OK, MessageBoxIcon.Warning) Exit Sub End If cr = Me.stcMP cr.SelectedTabIndex = 0 Me.grpCab.Enabled = False Me.grpReservaMP.Enabled = False Me.stcMP.Enabled = False End Sub Private Sub btnConfirmar_Click(sender As Object, e As EventArgs) Handles btnConfirmar.Click If CDbl(Me.ValorAVista.Text) + CDbl(Me.ValorOutros.Text) + CDbl(Me.ValorAFaturar.Text) <> CDbl(Me.TotalLiquido.Text) Then MessageBox.Show("Os valores não conferem.", "VALIDAÇÃO DE DADOS", MessageBoxButtons.OK, MessageBoxIcon.Warning) Exit Sub End If 'se o modo de venda for orcamento anula a operação. If ModeloVenda.Text = "ORCAMENTO" Then MessageBox.Show("Esta opção só válida para Pedidos.", "VALIDAÇÃO DE DADOS", MessageBoxButtons.OK, MessageBoxIcon.Warning) Exit Sub End If 'verifica se os valores estão batendo If valorParcelamento <> CDbl(Me.ValorAFaturar.Text) Then MessageBox.Show("Os valores do parcelamento não corresponde com o Valor a Faturar.", "VALIDAÇÃO DE DADOS", MessageBoxButtons.OK, MessageBoxIcon.Warning) Exit Sub End If Dim cxFechado As New CaixaFechado 'Verifica se o caixa está ativo cxFechado.CaixaEstaFechado() 'Soma os valores das parcelas valorParcelamento = 0 For Each row As DataGridViewRow In Me.dgvParcelamento.Rows valorParcelamento += row.Cells("gValor").Value Next row If Len(CaixaAtivo) <> 4 Then MessageBox.Show("O usuario deve selecionar um caixa antes de Confirmar o Pedido. Verifique", "Validação de Dados", MessageBoxButtons.OK, MessageBoxIcon.Error) If MsgBox("Deseja Ativar o caixa agora", 36, "Validação de Dados") = 6 Then TRVDados(UserAtivo, "CaixaAtivarDesativar") If Ina = True Then MsgBox("O usuário não esta autorizado a usar esta opção do sistema.", 64, "Validação de Dados") Exit Sub Else My.Forms.CaixaAtivarDesativar.ShowDialog() End If End If End If If String.IsNullOrEmpty(CaixaAtivo) Then Exit Sub End If 'abre a tela de confirmação do pedido My.Forms.PedidoVendaConfirmarOS.ShowDialog() End Sub Private Sub ValorDesconto_Enter(sender As Object, e As EventArgs) Handles ValorDesconto.Enter If Me.dgvParcelamento.RowCount > 0 Then Me.ValorDesconto.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Else Me.ValorDesconto.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não End If End Sub Private Sub EditarItemToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EditarItemToolStripMenuItem.Click If Value = TagType.eEditar Or Value = TagType.eNone Then MessageBox.Show("Você prescisa editar o registro primeiro", "Validação de dados", MessageBoxButtons.OK, MessageBoxIcon.Warning) Return End If vEnum = Operacao.alteracao 'verifica se foi confirmado desvia caso seja psositvo. If Me.status.Text = "FECHADO" Then MessageBox.Show("Este iten não pode mais ser editado, pois o pedido já foi confirmado", "Validação de Dados", MessageBoxButtons.OK, MessageBoxIcon.Information) Exit Sub End If 'Identifica se tem item seleciono atraves da vareavel IDItem., caso seja negativo desvia a rotina e não executa nada. If Retorno = 0 Then MsgBox("Selecione um produto para editá-lo", 48, "Validação de dados") Exit Sub End If 'Satifez todos os critérios acima executa as linhas abaixo. vEnum = Operacao.alteracao My.Forms.frmAdicionarItemMP.ShowDialog() End Sub Private Sub ExcluirItemToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExcluirItemToolStripMenuItem.Click If Me.chkConfirmado.Checked Then MessageBox.Show("O pedido já foi confirmado", "Validação de dados", MessageBoxButtons.OK, MessageBoxIcon.Warning) Return End If If Value = TagType.eEditar Or Value = TagType.eNone Then MessageBox.Show("Você prescisa editar o registro primeiro", "Validação de dados", MessageBoxButtons.OK, MessageBoxIcon.Warning) Return End If Retorno = Me.dgvItemGeral.CurrentRow.Cells("gID").Value If (MessageBox.Show("Deseja excluir o item: " & dgvItemGeral.CurrentRow.Cells("gItem").Value & "?", "Validação de Dados", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) = Windows.Forms.DialogResult.Yes Then item.Excluir(Retorno) item.Modelo = ModeloVenda.Text.Substring(0, 1) item.AtGrade(Me.NumeroPedido.Text) End If Retorno = Nothing End Sub Private Sub ExcluirTodosToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ExcluirTodosToolStripMenuItem1.Click If Value = TagType.eEditar Or Value = TagType.eNone Then MessageBox.Show("Você prescisa editar o registro primeiro", "Validação de dados", MessageBoxButtons.OK, MessageBoxIcon.Warning) Return End If item.Excluir(Me.NumeroPedido.Text, Me.ModeloVenda.Text.Substring(0, 1)) item.AtGrade(Me.NumeroPedido.Text) End Sub Private Sub ToolStripMenuItem3_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem3.Click Dim vvalue As Integer = Me.dgvReserva.CurrentRow.Cells("Codigo").Value Dim clR As New ReservaMP Retorno = Me.dgvReserva.CurrentRow.Cells(0).Value clR.delType = ReservaMP.eDel.One clR.Exluir(Retorno) clR.AtGrade(Me.NumeroPedido.Text) clR.AtSaldoReserva(vvalue) Retorno = 0 End Sub Private Sub dgvReserva_SelectionChanged(sender As Object, e As EventArgs) Handles dgvReserva.SelectionChanged Try Retorno = Me.dgvReserva.CurrentRow.Cells(0).Value Catch ex As Exception End Try End Sub Private Sub ToolStripMenuItem4_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem4.Click Dim clR As New ReservaMP clR.delType = ReservaMP.eDel.All clR.cloneTb() clR.Exluir(Me.NumeroPedido.Text) clR.AtSaldoReservaAll() clR.AtGrade(Me.NumeroPedido.Text) Retorno = 0 End Sub Private Sub ToolStripMenuItem9_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem9.Click If Not Me.chkConfirmado.Checked Then Dim cl As New ClassMP Retorno = Me.NumeroPedido.Text cl.delType = ClassMP.eDel.All cl.ExcluirPar(Retorno) atGridParcelas() Retorno = 0 Me.CodigoPagamento.Enabled = True Me.DescricaoPagamento.Enabled = True Me.imgBuscaCondicao.Enabled = True Me.CodigoPagamento.Clear() Me.DescricaoPagamento.Clear() Value = TagType.eSalvar btnSalvaEditar_Click(sender, e) Else MessageBox.Show("Não é possível excluir as parcelas, este pedido já foi confirmado.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End If End Sub Private Sub dgvParcelamento_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles dgvParcelamento.DataError Try Catch ex As Exception End Try End Sub Private Sub dgvItemGeral_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvItemGeral.CellClick Try Retorno = Me.dgvItemGeral.CurrentRow.Cells("gId").Value Catch ex As Exception End Try End Sub Private Sub CodigoCliente_Enter(sender As Object, e As EventArgs) Handles CodigoCliente.Enter If Me.dgvItemGeral.Rows.Count > 0 Then Me.CodigoCliente.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Sim Else Me.CodigoCliente.BloquearCx = TexBoxFocusNet.TextBoxFocusNet.Bloquear.Não End If End Sub Private Sub ItemFechamento_Click(sender As Object, e As EventArgs) Handles ItemFechamento.Click Me.stcMP.SelectedTab = Me.ItemFechamento Me.DataFechamento.Focus() Me.DataFechamento.Text = DataDia Me.TotalBruto.Text = FormatCurrency(Me.TotalDosItem.Text, 2) End Sub Private Sub btnGerarPedidos_Click(sender As Object, e As EventArgs) Handles btnGerarPedidos.Click If Not (Me.ModeloVenda.Text) = "ORCAMENTO" Then MessageBox.Show("Esta função só poderá ser executado se o modelo de venda for ORÇAMENTO.", "VALIDAÇÃO DE DADOS", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub End If If Me.chkGeradoPedido.Checked Then MessageBox.Show("Este Orçamento já foi gerado Pedido. Tente um outro orçamento.", "Validação de Dados", MessageBoxButtons.OK, MessageBoxIcon.Warning) Exit Sub End If If String.IsNullOrEmpty(CodigoCliente.Text) Or CodigoCliente.Text = "0" Then MessageBox.Show("O Cliente não pode ser nulo. Escolha um cliente cadastrado para processeguir.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub End If If String.IsNullOrEmpty(Me.DataPrazo.Text) Then MessageBox.Show("A data de Prazo não pode ser nulo.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub ElseIf String.IsNullOrEmpty(Me.Contato.Text) Then MessageBox.Show("O contanto não pode ser nulo.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub End If If Me.dgvItemGeral.RowCount = 0 Then MessageBox.Show("Não é possível gerar um pedido deste orçamento. Está faltando itens.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub End If If Value = TagType.eSalvar Then MessageBox.Show("O orçamento foi editado clique no botão salvar para processguir.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Exit Sub End If 'grava um novo pedido baseado no orcamento atual With PMP .CodigoCliente = Me.CodigoCliente.Text .nomeCliente = Me.NomeCliente.Text .Telefone = Me.txttelefone.Text .Email = Me.txtEmail.Text .DataPedido = Me.DataPedido.Text .DataPrazoEntrega = Me.DataPrazo.Text .Contato = Me.Contato.Text .CodigoFuncionario = Me.CodigoVendedor.Text .Status = Me.status.Text .Observacao = Me.Obs.Text .DataFechamento = Me.DataFechamento.Text .ValorBordado = Me.ValorBordado.Text .ValorSerigrafia = Me.ValorSerigrafia.Text .TotalBruto = Me.TotalBruto.Text .TotalLiquido = Me.TotalLiquido.Text .Modelo = "P" .Empresa = CodEmpresa .Datavalidade = Me.DataValidade.Text .Gerado_pedido = Me.chkGeradoPedido.Checked End With PMP.Gravar() 'grava as alterações Dim var As String var = Retorno 'sava os itens PMP.SaveItensPedido(Me.NumeroPedido.Text) Value = TagType.eSalvar 'Mostra o pedido Gerado PMP.OrcForPed = var Me.chkGeradoPedido.Checked = True 'salva as alteraçoes btnSalvaEditar_Click(sender, e) Value = TagType.eEditar 'carrega o pedido gerado Retorno = Nothing lblGeradoPedido.Text = "Orçamento gerado Pedido N. " & FormatNumber(var, "000000") Me.lblGeradoPedido.Visible = True End Sub Private Sub btnImprimir_Click(sender As Object, e As EventArgs) Handles btnImprimir.Click RelatorioCarregar = "PedidoMP.rpt" Dim filtro As String = "{PedidoMateriaPrima.NumeroPedido} =" & CInt(Me.NumeroPedido.Text) & " and {PedidoMateriaPrima.Modelo} ='" & Me.ModeloVenda.Text.Substring(0, 1) & "'" Dim f As New ClassView.cView f.frm(DirRelat & RelatorioCarregar, LocalBD & Nome_BD, SenhaBancoDados, "", filtro) End Sub Private Sub dgvItemGeral_SelectionChanged(sender As Object, e As EventArgs) Handles dgvItemGeral.SelectionChanged Try Retorno = dgvItemGeral.CurrentRow.Cells("gid").Value Catch ex As Exception End Try End Sub Private Sub ValorAVista_Layout(sender As Object, e As LayoutEventArgs) Handles ValorAVista.Layout End Sub Private Sub CodigoPagamento_Enter(sender As Object, e As EventArgs) Handles CodigoPagamento.Enter End Sub Private Sub btnOrdemProducao_Click(sender As Object, e As EventArgs) Handles btnOrdemProducao.Click If Value = TagType.eNone Or Me.dgvItemGeral.RowCount = 0 Then Exit Sub End If RelatorioCarregar = "OrdemProducao.rpt" Dim filtro As String = "{PedidoMateriaPrima.NumeroPedido} =" & CInt(Me.NumeroPedido.Text) & " and {PedidoMateriaPrima.Modelo} ='" & Me.ModeloVenda.Text.Substring(0, 1) & "'" Dim f As New ClassView.cView f.frm(DirRelat & RelatorioCarregar, LocalBD & Nome_BD, SenhaBancoDados, "", filtro) End Sub End Class
 Imports System.Runtime.CompilerServices Imports BioNovoGene.Analytical.MassSpectrometry.Math Imports BioNovoGene.BioDeep.Chemoinformatics Imports BioNovoGene.BioDeep.Chemoinformatics.Formula Imports BioNovoGene.BioDeep.Chemoinformatics.SMILES Imports BioNovoGene.BioDeep.Chemoinformatics.SMILES.Embedding Imports Microsoft.VisualBasic.CommandLine.Reflection Imports Microsoft.VisualBasic.Data.visualize.Network.Graph Imports Microsoft.VisualBasic.Linq Imports Microsoft.VisualBasic.Scripting.MetaData Imports Microsoft.VisualBasic.Serialization.Bencoding Imports SMRUCC.Rsharp.Runtime Imports list = SMRUCC.Rsharp.Runtime.Internal.Object.list Imports RDataframe = SMRUCC.Rsharp.Runtime.Internal.Object.dataframe <Package("SMILES", Category:=APICategories.UtilityTools)> Module SMILESTool Sub Main() Call Internal.Object.Converts.makeDataframe.addHandler(GetType(ChemicalFormula), AddressOf atoms_table) End Sub <MethodImpl(MethodImplOptions.AggressiveInlining)> Private Function atoms_table(smiles As ChemicalFormula, args As list, env As Environment) As RDataframe Return atomGroups(smiles) End Function ''' <summary> ''' Parse the SMILES molecule structre string ''' </summary> ''' <param name="SMILES"></param> ''' <param name="strict"></param> ''' <returns> ''' A chemical graph object that could be used for build formula or structure analysis ''' </returns> ''' <remarks> ''' SMILES denotes a molecular structure as a graph with optional chiral ''' indications. This is essentially the two-dimensional picture chemists ''' draw to describe a molecule. SMILES describing only the labeled ''' molecular graph (i.e. atoms and bonds, but no chiral or isotopic ''' information) are known as generic SMILES. ''' </remarks> ''' <MethodImpl(MethodImplOptions.AggressiveInlining)> <ExportAPI("parse")> Public Function parseSMILES(SMILES As String, Optional strict As Boolean = True) As ChemicalFormula Return ParseChain.ParseGraph(SMILES, strict) End Function <MethodImpl(MethodImplOptions.AggressiveInlining)> <ExportAPI("as.formula")> Public Function asFormula(SMILES As ChemicalFormula, Optional canonical As Boolean = True) As Formula Return SMILES.GetFormula(canonical) End Function <MethodImpl(MethodImplOptions.AggressiveInlining)> <ExportAPI("as.graph")> Public Function asGraph(smiles As ChemicalFormula) As NetworkGraph Return smiles.AsGraph End Function ''' <summary> ''' get atoms table from the SMILES structure data ''' </summary> ''' <param name="SMILES"></param> ''' <returns></returns> <ExportAPI("atoms")> Public Function atomGroups(SMILES As ChemicalFormula) As RDataframe Dim elements As SmilesAtom() = SMILES.GetAtomTable.ToArray Dim rowKeys As String() = elements.Select(Function(a) a.id).ToArray Dim atoms As String() = elements.Select(Function(a) a.atom).ToArray Dim groups As String() = elements.Select(Function(a) a.group).ToArray Dim ionCharge As Integer() = elements.Select(Function(a) a.ion_charge).ToArray Dim links As Integer() = elements.Select(Function(a) a.links).ToArray Dim partners As String() = elements.Select(Function(a) a.connected.JoinBy("; ")).ToArray Return New RDataframe With { .rownames = rowKeys, .columns = New Dictionary(Of String, Array) From { {"atom", atoms}, {"group", groups}, {"ion_charge", ionCharge}, {"links", links}, {"connected", partners} } } End Function <ExportAPI("links")> Public Function atomLinks(SMILES As ChemicalFormula, Optional kappa As Double = 2, Optional normalize_size As Boolean = False) As RDataframe Dim links As AtomLink() = SMILES.GraphEmbedding(kappa, normalize_size).ToArray Dim atom1 As String() = links.Select(Function(l) l.atom1).ToArray Dim atom2 As String() = links.Select(Function(l) l.atom2).ToArray Dim weight As Double() = links.Select(Function(l) l.score).ToArray Dim vk As Double() = links.Select(Function(l) l.vk).ToArray Dim v0 As Double() = links.Select(Function(l) l.v0).ToArray Dim vertex As String() = links _ .Select(Function(l) l.vertex.ToBEncodeString) _ .ToArray Return New RDataframe With { .columns = New Dictionary(Of String, Array) From { {"atom1", atom1}, {"atom2", atom2}, {"weight", weight}, {"vk", vk}, {"v0", v0}, {"vertex", vertex} } } End Function End Module
Imports Aspose.Tasks.Saving ' This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Tasks for .NET API reference ' when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information. ' If you do not wish to use NuGet, you can manually download Aspose.Tasks for .NET API from http://www.aspose.com/downloads, ' install it and then add its reference to this project. For any issues, questions or suggestions ' please feel free to contact us using http://www.aspose.com/community/forums/default.aspx Namespace WorkingWithProjects.WorkingWithExtendedAttributes Public Class CreateExtendedAttributes Public Shared Sub Run() Try ' The path to the documents directory. Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName) ' ExStart:CreateExtendedAttributes Dim project1 As New Project(dataDir & "Blank2010.mpp") Dim myText1Def As ExtendedAttributeDefinition = Nothing ' If the Custom field doesn't exist in Project, create it If project1.ExtendedAttributes.GetById(Convert.ToInt32(ExtendedAttributeTask.Text1.ToString("D"))) Is Nothing Then myText1Def = New ExtendedAttributeDefinition() myText1Def.Alias = "MyValue" myText1Def.CfType = CustomFieldType.Number myText1Def.FieldId = ExtendedAttributeTask.Text1.ToString("D") project1.ExtendedAttributes.Add(myText1Def) Else myText1Def = project1.ExtendedAttributes.GetById(Convert.ToInt32(ExtendedAttributeTask.Number1.ToString("D"))) End If ' Generate Extended Attribute from definition Dim text1TaskAttr As ExtendedAttribute = myText1Def.CreateExtendedAttribute() text1TaskAttr.Value = "20.55" ' Add extended attribute to task Dim tsk As Task = project1.RootTask.Children.Add("Task 1") tsk.ExtendedAttributes.Add(text1TaskAttr) project1.Save(dataDir & "CreateExtendedAttributes_out.mpp", SaveFileFormat.MPP) ' ExEnd:CreateExtendedAttributes Catch ex As Exception Console.Write(ex.Message & vbLf & "This example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http://www.aspose.com/purchase/default.aspx.") End Try End Sub End Class End Namespace
<Serializable()> _ Friend Class Control2_ToolboxItem Inherits ToolboxItem Public Sub New(ByVal toolType As Type) MyBase.New(toolType) End Sub Public Overrides Sub Initialize(ByVal toolType As Type) If Not toolType.Equals(GetType(Control2)) Then Throw New ArgumentException( _ String.Format(CultureInfo.CurrentCulture, _ "The {0} constructor argument must be of type {1}.", _ Me.GetType().FullName, GetType(Control2).FullName)) End If MyBase.Initialize(toolType) End Sub End Class
Public Class CreateDynamicForm Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then CreateDynamicControls() End If End Sub Public Function CustomFields() As DataTable Dim dt As DataTable = New DataTable() dt = New DataTable() dt.Columns.Add("FieldName", GetType(String)) dt.Columns.Add("FieldType", GetType(String)) dt.Columns.Add("FieldValue", GetType(String)) dt.Rows.Add("FirstName", "TextBox", String.Empty) dt.Rows.Add("LastName", "TextBox", String.Empty) dt.Rows.Add("IsActive", "Checkbox", String.Empty) dt.Rows.Add("State", "DropdownList", String.Empty) dt.Rows.Add("City", "TextBox", String.Empty) dt.Rows.Add("Zip", "TextBox", String.Empty) dt.Rows.Add("Gender", "RadioButton", String.Empty) dt.Rows.Add("Job", "DropdownList", String.Empty) Return dt End Function Public Sub CreateDynamicControls() Dim dt As DataTable = New DataTable() dt = CustomFields() If dt.Rows.Count > 0 Then For i As Int32 = 0 To dt.Rows.Count - 1 Dim tr As HtmlGenericControl = New HtmlGenericControl("tr") Dim td As HtmlGenericControl = New HtmlGenericControl("td") Dim td1 As HtmlGenericControl = New HtmlGenericControl("td") Dim FieldName As String = Convert.ToString(dt.Rows(i)("FieldName")) Dim FieldType As String = Convert.ToString(dt.Rows(i)("FieldType")) Dim FieldValue As String = Convert.ToString(dt.Rows(i)("FieldValue")) Dim lbcustomename As Label = New Label() lbcustomename.ID = "lb" & FieldName lbcustomename.Text = FieldName td.Controls.Add(lbcustomename) tr.Controls.Add(td) If FieldType.ToLower().Trim() = "textbox" Then Dim txtcustombox As TextBox = New TextBox() txtcustombox.ID = "txt" & FieldName txtcustombox.Text = FieldValue td1.Controls.Add(txtcustombox) ElseIf FieldType.ToLower().Trim() = "checkbox" Then Dim chkbox As CheckBox = New CheckBox() chkbox.ID = "chk" & FieldName If FieldValue = "1" Then chkbox.Checked = True Else chkbox.Checked = False End If td1.Controls.Add(chkbox) ElseIf FieldType.ToLower().Trim() = "radiobutton" Then Dim rbnlst As RadioButtonList = New RadioButtonList() rbnlst.ID = "rbnlst" & FieldName rbnlst.Items.Add(New ListItem("Male", "1")) rbnlst.Items.Add(New ListItem("Female", "2")) If FieldValue <> String.Empty Then rbnlst.SelectedValue = FieldValue Else rbnlst.SelectedValue = "1" End If rbnlst.RepeatDirection = RepeatDirection.Horizontal td1.Controls.Add(rbnlst) ElseIf FieldType.ToLower().Trim() = "dropdownlist" Then Dim ddllst As DropDownList = New DropDownList() ddllst.ID = "ddl" & FieldName ddllst.Items.Add(New ListItem("Select", "0")) If FieldName.ToLower().Trim() = "state" Then ddllst.Items.Add(New ListItem("Alabama", "AL")) ddllst.Items.Add(New ListItem("Alaska", "AK")) ddllst.Items.Add(New ListItem("Arizona", "AZ")) ddllst.Items.Add(New ListItem("California", "CA")) ddllst.Items.Add(New ListItem("New York", "NY")) ElseIf FieldName.ToLower().Trim() = "job" Then ddllst.Items.Add(New ListItem("Developer", "1")) ddllst.Items.Add(New ListItem("Tester", "2")) End If If FieldValue <> String.Empty Then ddllst.SelectedValue = FieldValue Else ddllst.SelectedValue = "0" End If td1.Controls.Add(ddllst) End If tr.Controls.Add(td1) placeholder.Controls.Add(tr) If i = dt.Rows.Count - 1 Then tr = New HtmlGenericControl("tr") td = New HtmlGenericControl("td") 'Dim btnSubmit As Button = New Button() 'btnSubmit.ID = "btnSubmit" 'btnSubmit.Click += btnsubmit_Click 'btnSubmit.OnClientClick = "return ValidateForm();" 'btnSubmit.Text = "Submit" 'td.Controls.Add(btnSubmit) td.Attributes.Add("Colspan", "2") td.Attributes.Add("style", "text-align:center;") tr.Controls.Add(td) placeholder.Controls.Add(tr) End If Next End If End Sub Public Sub Save() Dim dtFormValues As DataTable = New DataTable() dtFormValues.Columns.Add("FormId", GetType(Int32)) dtFormValues.Columns.Add("FieldName", GetType(String)) dtFormValues.Columns.Add("Value", GetType(String)) Dim dt As DataTable = New DataTable() dt = CustomFields() If dt.Rows.Count > 0 Then For i As Int32 = 0 To dt.Rows.Count - 1 Dim FieldName As String = Convert.ToString(dt.Rows(i)("FieldName")) Dim FieldType As String = Convert.ToString(dt.Rows(i)("FieldType")) dtFormValues.NewRow() If FieldType.ToLower().Trim() = "textbox" Then Dim txtbox As TextBox = CType(placeholder.FindControl("txt" & FieldName), TextBox) If txtbox IsNot Nothing Then dtFormValues.Rows.Add(ClientID, FieldName, txtbox.Text) End If ElseIf FieldType.ToLower().Trim() = "checkbox" Then Dim checkbox As CheckBox = CType(placeholder.FindControl("chk" & FieldName), CheckBox) If checkbox IsNot Nothing Then dtFormValues.Rows.Add(ClientID, FieldName, If(checkbox.Checked, "1", "0")) End If ElseIf FieldType.ToLower().Trim() = "radiobutton" Then Dim radiobuttonlist As RadioButtonList = CType(placeholder.FindControl("rbnlst" & FieldName), RadioButtonList) If radiobuttonlist IsNot Nothing Then dtFormValues.Rows.Add(ClientID, FieldName, radiobuttonlist.SelectedValue) End If ElseIf FieldType.ToLower().Trim() = "dropdownlist" Then Dim dropdownlist As DropDownList = CType(placeholder.FindControl("ddl" & FieldName), DropDownList) If dropdownlist IsNot Nothing Then dtFormValues.Rows.Add(ClientID, FieldName, dropdownlist.SelectedValue) End If End If Next End If End Sub Protected Sub btnsubmit_Click(sender As Object, e As EventArgs) Save() End Sub End Class
Imports System.Data.SQLite Imports System.Globalization Public Class VendaDAO : Inherits DatabaseController Public Function CreateVenda(ByVal Venda As Venda) As Boolean Dim Connection As SQLiteConnection = Connect() Dim Transaction As SQLiteTransaction = Connection.BeginTransaction() Dim Command As SQLiteCommand = Connection.CreateCommand() Command.Transaction = Transaction Try Command.CommandText = "INSERT INTO Venda (Data, RG_FK) VALUES (@data, @rg);" Command.Parameters.AddWithValue("@data", Venda.GetData().ToString("dd/mm/yyyy")) Command.Parameters.AddWithValue("@rg", Venda.GetCliente().GetRG()) Command.Prepare() Command.ExecuteNonQuery() Dim LastInsertedId As Integer = Connection.LastInsertRowId For Each Item In Venda.GetItens() Command.CommandText = "INSERT INTO ItemVenda (Codigo_FK, Numero_FK, Valor, Quantidade) VALUES (@codigo, @numero, @valor, @quantidade);" Command.Parameters.AddWithValue("@codigo", Item.GetProduto().GetCódigo()) Command.Parameters.AddWithValue("@numero", LastInsertedId) Command.Parameters.AddWithValue("@valor", Item.GetValor()) Command.Parameters.AddWithValue("@quantidade", Item.GetQuantidade()) Command.Prepare() Command.ExecuteNonQuery() Next Transaction.Commit() Disconnect(Connection) Return True Catch ex As Exception Transaction.Rollback() Disconnect(Connection) Return False End Try End Function Public Function EditVenda(ByVal Venda As Venda) As Boolean Dim Connection As SQLiteConnection = Connect() Dim Command As SQLiteCommand = Connection.CreateCommand() Command.CommandText = "UPDATE Venda SET Data = @data, RG_FK = @rg WHERE Numero = @numero;" Command.Parameters.AddWithValue("@data", Venda.GetData().ToString("dd/mm/yyyy")) Command.Parameters.AddWithValue("@rg", Venda.GetCliente().GetRG()) Command.Parameters.AddWithValue("@numero", Venda.GetNúmero()) Command.Prepare() Dim RowsAffected = Command.ExecuteNonQuery() Disconnect(Connection) Return RowsAffected > 0 End Function Public Function RemoveVenda(ByVal Venda As Venda) As Boolean Dim Connection As SQLiteConnection = Connect() Dim Command As SQLiteCommand = Connection.CreateCommand() Command.CommandText = "DELETE FROM Venda WHERE Numero = @numero;" Command.Parameters.AddWithValue("@numero", Venda.GetNúmero()) Command.Prepare() Dim RowsAffected = Command.ExecuteNonQuery() Disconnect(Connection) Return RowsAffected > 0 End Function Public Function GetVenda(ByRef Venda As Venda) As Venda Dim Connection As SQLiteConnection = Connect() Dim Command As SQLiteCommand = Connection.CreateCommand() Dim DataReader As SQLiteDataReader Command.CommandText = "SELECT Data, RG_FK FROM Venda WHERE Numero = @numero;" Command.Parameters.AddWithValue("@numero", Venda.GetNúmero()) DataReader = Command.ExecuteReader() If Not DataReader.HasRows Then Venda = Nothing Else While DataReader.Read() Venda.SetData(Date.ParseExact(DataReader("Data"), "dd/mm/yyyy", CultureInfo.InvariantCulture)) Venda.SetCliente(New Cliente(DataReader("RG_FK"))) End While End If DataReader.Close() Disconnect(Connection) Return Venda End Function Public Function GetAllVenda() As List(Of Venda) Dim Connection As SQLiteConnection = Connect() Dim Command As SQLiteCommand = Connection.CreateCommand() Dim DataReader As SQLiteDataReader Dim Vendas As New List(Of Venda) Command.CommandText = "SELECT Numero, Data, RG_FK FROM Venda;" DataReader = Command.ExecuteReader() While DataReader.Read() Dim Venda As New Venda(Integer.Parse(DataReader("Numero")), Date.ParseExact(DataReader("Data"), "dd/mm/yyyy", CultureInfo.InvariantCulture), New Cliente(DataReader("RG_FK")), New List(Of ItemVenda)) Vendas.Add(Venda) End While DataReader.Close() Disconnect(Connection) Return Vendas End Function End Class
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '* Arguments class: application arguments interpreter '* '* Authors: R. LOPES '* Contributors: R. LOPES '* Created: 25 October 2002 '* Modified: 28 October 2002 '* '* Version: 1.0 '* '* http://www.codeproject.com/KB/recipes/command_line.aspx '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Imports System.Collections.Specialized Imports System.Text.RegularExpressions Namespace CommandLine.Utility ''' <summary> ''' Arguments class ''' </summary> Public Class Arguments ' Variables Private Parameters As StringDictionary ' Constructor Public Sub New(ByVal Args As String()) Parameters = New StringDictionary() Dim Spliter As New Regex("^-{1,2}|^/|=", RegexOptions.IgnoreCase Or RegexOptions.Compiled) Dim Remover As New Regex("^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase Or RegexOptions.Compiled) Dim Parameter As String = Nothing Dim Parts As String() ' Valid parameters forms: ' {-,/,--}param{ ,=,:}((",')value(",')) ' Examples: -param1 value1 --param2 /param3:"Test-:-work" /param4=happy -param5 '--=nice=--' For Each Txt As String In Args ' Look for new parameters (-,/ or --) and a possible enclosed value (=,:) Parts = Spliter.Split(Txt, 3) Select Case Parts.Length ' Found a value (for the last parameter found (space separator)) Case 1 If Parameter IsNot Nothing Then If Not Parameters.ContainsKey(Parameter) Then Parts(0) = Remover.Replace(Parts(0), "$1") Parameters.Add(Parameter, Parts(0)) End If Parameter = Nothing End If ' else Error: no parameter waiting for a value (skipped) Exit Select ' Found just a parameter Case 2 ' The last parameter is still waiting. With no value, set it to true. If Parameter IsNot Nothing Then If Not Parameters.ContainsKey(Parameter) Then Parameters.Add(Parameter, "true") End If End If Parameter = Parts(1) Exit Select ' Parameter with enclosed value Case 3 ' The last parameter is still waiting. With no value, set it to true. If Parameter IsNot Nothing Then If Not Parameters.ContainsKey(Parameter) Then Parameters.Add(Parameter, "true") End If End If Parameter = Parts(1) ' Remove possible enclosing characters (",') If Not Parameters.ContainsKey(Parameter) Then Parts(2) = Remover.Replace(Parts(2), "$1") Parameters.Add(Parameter, Parts(2)) End If Parameter = Nothing Exit Select End Select Next ' In case a parameter is still waiting If Parameter IsNot Nothing Then If Not Parameters.ContainsKey(Parameter) Then Parameters.Add(Parameter, "true") End If End If End Sub ' Retrieve a parameter value if it exists Default Public ReadOnly Property Item(ByVal Param As String) As String Get Return Parameters(Param) End Get End Property Public Function GetParameterCount() As Integer Return Parameters.Count End Function Public Function ContainsKey(key As String) As Boolean Return Parameters.ContainsKey(key) End Function End Class End Namespace
Imports PivotUpdating.Model Imports Syncfusion.Windows.Shared Imports System.Collections.Generic Imports System.Windows.Threading Imports System Namespace PivotUpdating.ViewModel Public Class ViewModel Inherits Syncfusion.Windows.Shared.NotificationObject Dim timer As DispatcherTimer Dim updateRate As Integer = 200 'msecs Dim updateCount As Integer = 20 'updates per tick event Dim rand As Random = New Random(123123) Private _productSalesData As ProductSales.ProductSalesCollection Public Property ProductSalesData() As ProductSales.ProductSalesCollection Get If _productSalesData Is Nothing Then _productSalesData = ProductSales.GetSalesData() End If Return _productSalesData End Get Set(ByVal value As ProductSales.ProductSalesCollection) _productSalesData = value RaisePropertyChanged("ProductSalesData") End Set End Property Private _timerActivationCommand As DelegateCommand(Of Object) Public Property TimerActivationCommand() As DelegateCommand(Of Object) Get If _timerActivationCommand Is Nothing Then _timerActivationCommand = New DelegateCommand(Of Object)(AddressOf DoTimerActivation) End If Return _timerActivationCommand End Get Set(ByVal value As DelegateCommand(Of Object)) _timerActivationCommand = value End Set End Property Private _updateSourceCommand As DelegateCommand(Of Object) Public Property UpdateSourceCommand() As DelegateCommand(Of Object) Get If _updateSourceCommand Is Nothing Then _updateSourceCommand = New DelegateCommand(Of Object)(AddressOf UpdateItemSource) End If Return _updateSourceCommand End Get Set(ByVal value As DelegateCommand(Of Object)) _updateSourceCommand = value End Set End Property Public ReadOnly Property ThrottleUpdateRates() As List(Of Integer) Get Dim listOfThrottle As List(Of Integer) = New List(Of Integer) listOfThrottle.Add(0) listOfThrottle.Add(300) listOfThrottle.Add(500) listOfThrottle.Add(1000) listOfThrottle.Add(2000) Return listOfThrottle End Get End Property Private Sub DoTimerActivation(parm As Object) If TypeOf parm Is Boolean Then If timer Is Nothing Then timer = New DispatcherTimer() AddHandler timer.Tick, AddressOf timer_Tick timer.Interval = TimeSpan.FromMilliseconds(updateRate) End If If DirectCast(parm, Boolean) Then timer.Start() Else timer.Stop() End If End If End Sub Private Sub UpdateItemSource(parm As Object) Dim dr As ProductSales = Nothing Select Case parm.ToString() Case "Add at Top" dr = New ProductSales() With {.Country = "Canada", .State = "Brunswick", .Product = "Bike", .Date = "FY 2003", .Quantity = 1, .Amount = 100.0R} Case "Add at Middle" dr = New ProductSales() With {.Country = "Canada", .State = "Brunswick", .Product = "Bike", .Date = "FY 2007", .Quantity = 1, .Amount = 200.0R} Case "Add at Bottom" dr = New ProductSales() With {.Country = "Canada", .State = "Brunswick", .Product = "Bike", .Date = "FY 2010", .Quantity = 1, .Amount = 300.0R} End Select _productSalesData.Add(dr) End Sub Private Sub timer_Tick(ByVal sender As Object, ByVal e As EventArgs) For i As Integer = 0 To updateCount - 1 ChangeOneValue(1) Next i End Sub Private Sub ChangeOneValue(ByVal loc As Integer) Dim old As Double = CDbl(_productSalesData(loc).Amount) _productSalesData(loc).Amount = rand.Next(1000) End Sub End Class End Namespace
Imports PclWCommon Imports PclWTestCommon Public Class ClipperCSharpWrapper : Inherits TestableObj Private Const Scale As Integer = 1000 Public Sub New() Me.ClosedPolygonsRequired = False End Sub Public Overrides Function GetAdaptedInputFromPolygonSet(ByVal input As PclWCommon.PolygonSet) As Object If Me.ClosedPolygonsRequired Then ClosePolygons(input) Else OpenPolygons(input) End If Dim clprPolygons As New List(Of List(Of ClipperLib.IntPoint)) For Each polygon As PclWCommon.Polygon In input.Polygons Dim clprPolygon As New List(Of ClipperLib.IntPoint) For Each vertex As PclWCommon.Vertex In polygon.Vertices Dim clprPoint As New ClipperLib.IntPoint clprPoint.X = vertex.X * Scale clprPoint.Y = vertex.Y * Scale clprPolygon.Add(clprPoint) Next clprPolygons.Add(clprPolygon) Next Return clprPolygons End Function Public Overrides Function GetAdaptedInputFromRegion(ByVal input As PclWCommon.Region) As Object 'Not implemented. Return Nothing End Function Public Overrides Function GetAdaptedOutputToPolygonSet(ByVal output As Object) As PclWCommon.PolygonSet Dim polygonSet As New PclWCommon.PolygonSet For Each clprPolygon As List(Of ClipperLib.IntPoint) In output Dim polygon As New PclWCommon.Polygon For Each clprPoint As ClipperLib.IntPoint In clprPolygon Dim vertex As New PclWCommon.Vertex vertex.X = clprPoint.X / Scale vertex.Y = clprPoint.Y / Scale polygon.Vertices.Add(vertex) Next polygonSet.Polygons.Add(polygon) Next Return polygonSet End Function Public Overrides Function GetDifference(ByVal subject As Object, ByVal clip As Object) As Object Dim clipperCs As New ClipperLib.Clipper 'clipperCs.UseFullCoordinateRange = False clipperCs.AddPolygons(subject, ClipperLib.PolyType.ptSubject) clipperCs.AddPolygons(clip, ClipperLib.PolyType.ptClip) Dim result As New List(Of List(Of ClipperLib.IntPoint)) clipperCs.Execute(ClipperLib.ClipType.ctDifference, result) Return result End Function Public Overrides Function GetIntersection(ByVal subject As Object, ByVal clip As Object) As Object Dim clipperCs As New ClipperLib.Clipper 'clipperCs.UseFullCoordinateRange = False clipperCs.AddPolygons(subject, ClipperLib.PolyType.ptSubject) clipperCs.AddPolygons(clip, ClipperLib.PolyType.ptClip) Dim result As New List(Of List(Of ClipperLib.IntPoint)) clipperCs.Execute(ClipperLib.ClipType.ctIntersection, result) Return result End Function Public Overrides Function GetUnion(ByVal subject As Object, ByVal clip As Object) As Object Dim clipperCs As New ClipperLib.Clipper 'clipperCs.UseFullCoordinateRange = False clipperCs.AddPolygons(subject, ClipperLib.PolyType.ptSubject) clipperCs.AddPolygons(clip, ClipperLib.PolyType.ptClip) Dim result As New List(Of List(Of ClipperLib.IntPoint)) clipperCs.Execute(ClipperLib.ClipType.ctUnion, result) Return result End Function Public Overrides Function GetXor(ByVal subject As Object, ByVal clip As Object) As Object Dim clipperCs As New ClipperLib.Clipper 'clipperCs.UseFullCoordinateRange = False clipperCs.AddPolygons(subject, ClipperLib.PolyType.ptSubject) clipperCs.AddPolygons(clip, ClipperLib.PolyType.ptClip) Dim result As New List(Of List(Of ClipperLib.IntPoint)) clipperCs.Execute(ClipperLib.ClipType.ctXor, result) Return result End Function End Class
Public Class Cargar_Palabras 'variable que lleva la cuenta de las palabras ingresadas Public contador As Byte 'creacion del .txt Public Ruta As IO.StreamWriter 'Agregar palabras a la lista Private Sub btn_agregar_Click(sender As Object, e As EventArgs) Handles btn_agregar.Click If Txt_palabras.Text <> "" Then 'si esta vacio no entra If Txt_palabras.Text.Length >= 6 Then 'si la palabra es menor a 6 no entra Lista_palabras.Items.Add(Txt_palabras.Text) 'agrega una palabra en la lista contador = contador + 1 'aumenta el contador para indicar cuantas palabras ha incresado Txt_palabras.Text = "" 'limpia la caja de texto lb_contador.Text = "Palabras: " & contador 'actualiza el label con la cantidad de palabras que lleva ingresadas End If End If Txt_palabras.Focus() 'cuando cumpre el requisito de 15 palabras se bloquea el boton If contador = 15 Then btn_agregar.Enabled = False End If End Sub 'Eliminar palabras de la lista Private Sub btn_borrar_Click(sender As Object, e As EventArgs) Handles btn_borrar.Click If Lista_palabras.SelectedItem <> "" Then 'si seleciona una palabra entra el "if" Lista_palabras.Items.Remove(Lista_palabras.SelectedItem) 'elimina una palabra de la lista contador = contador - 1 'disminuye el contador para indicar cuantas palabras ha incresado lb_contador.Text = "Palabras: " & contador 'actualiza el label con la cantidad de palabras que lleva ingresadas btn_agregar.Enabled = True 'activa el boton de ingresar denuevo End If End Sub 'Crea un archivo .txt Private Sub btn_guardar_Click(sender As Object, e As EventArgs) Handles btn_guardar.Click Dim x As Byte 'contador If contador = 15 Then Ruta = New IO.StreamWriter("E:\Palabras.txt") 'crea el archivo .txt 'incresa las palabras al .txt For x = 0 To Lista_palabras.Items.Count - 1 Ruta.WriteLine(Lista_palabras.Items(x)) Next Ruta.Close() 'cierra el archivo MessageBox.Show("Guardado con exito") Else MsgBox("Alerta: Debe ingresar las 15 palabras", MsgBoxStyle.Exclamation, "Mensaje de error") End If End Sub 'Proceso para que solo permita Letras en el text box Private Sub Txt_palabras_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Txt_palabras.KeyPress If Char.IsLetter(e.KeyChar) Then e.Handled = False ElseIf Char.IsControl(e.KeyChar) Then e.Handled = False Else e.Handled = True End If End Sub End Class
Imports System.ComponentModel.DataAnnotations Imports System Imports System.Collections.Generic Public Class product_info <Key> <Display(Name:="ID")> Public Property productinfo_id As Integer <Required> <StringLength(50, ErrorMessage:="Must be less than 50 characters")> <Display(Name:="Product")> Public Property product_name As String <Required> <StringLength(500, ErrorMessage:="Must be less than 500 characters")> <Display(Name:="Description")> Public Property product_description As String Public Overridable Property products As ICollection(Of products) = New HashSet(Of products) End Class
Imports PagoProveedores.QB Public Class Examples Public Shared Function main() 'Se llama la constructor sin singun atributo Dim q As New QB.QueryBuilder Try 'La mayoria de las acciones se pueden encadenar. q = ejemplos_con_select(q) q = ejemplos_con_join(q) q = ejemplos_con_update(q) q = ejemplos_con_insert(q) ' -- Para obtener el query a ejecutar llamar al metodo build() del QueryBuilder Dim sqlFinal As String = q.build Return sqlFinal Catch ex As NoTableSettedException 'No Se selecciono ninguna tabla antes de hacer el build Return ex.Message Catch ex As NoValueSettedException 'Intentamos ejecutar un Insert o Update sin asignar valores Return ex.Message Catch ex As DomainNotMatchException 'No deberia aparece nunca. Si aparece es porque hay problemas con el dominio entre inserciones multiples Return ex.Message Catch ex As QB.QueryBuilderException 'Interceptamos cualquier tipo de excepcion del QueryBuilder Return ex.Message End Try End Function Public Shared Function ejemplos_con_select(q As QB.QueryBuilder) As QB.QueryBuilder 'Todos los elementos de la tabla Alumnos q.table("Alumnos").seleccionar() 'Nombre y apellido de la tabla alumnos q.table("Alumnos").seleccionar({"Nombres", "Apellido"}) 'cambiar el nombre del atributo nombres por Primer Nombre q.table("Alumnos").seleccionar({"Nombres [Primer Nombre]", "Apellido"}) 'Alumno con dni 37888888 q.table("Alumnos").seleccionar().where("@nro_documento", 37821733) ' -- Usamos el caracter @ para evitar que se tome como un texto. De esta forma toma el valor como el campo y no texto. ' -- El al usar el caracter @ asumimos que es un campo y se le agrega el nombre de la tabla antes. 'Alumnos con mas de 2 hijos q.table("Alumnos").seleccionar().where("@cant_hijos", ">", 2) 'Personas con mas gastos que ingresos [ingresos y gastos son campos de personas] q.table("Alumnos").seleccionar().where("@gastos", ">", "@ingresos") 'Personas con Ingreso 10% mayor o mas que los gastos q.table("Alumnos").seleccionar().where("@ingresos", ">", "@gastos * 1.1") 'Personas cuyo nombre terminen con BERTO q.table("Alumnos").seleccionar().where("@Nombres", "like", "%berto") 'Personas cuyos gastos sean inferior a 5000 e ingresos mayores a 10000 q.table("Alumnos").seleccionar(). where("@gastos", "<", 5000). where("@ingresos", ">", 10000) 'Si la clausula incluye elementos de otra tabla deben ser incluidos el el objeto devuelto por el metodo join. ' Ejemplos a continuacion. Return q End Function Public Shared Function ejemplos_con_join(q As QB.QueryBuilder) As QB.QueryBuilder 'NO ANIDAR DESPUES DE HACER UN JOIN, PUEDE MAL ENTENDERSE. 'Todos los elementos de la tabla Alumnos con los de la tabla carrera unidos por el elemento id_carrera en ambas q.table("Alumnos").seleccionar().join("carrera", "id_carrera") 'Idem pero con la Foraign Key distinta de la Primary key [ FK; id_carrera (En alumno), PK: id (En carrera)] q.table("Alumnos").seleccionar(). join("carrera", "id_carrera", "id") 'Idem pero con los datos del alumno y solo el nombre de la carrera y su descripcion q.table("Alumno").seleccionar. join("carrera", "id_carrera", {"nombre_carrera", "desc"}) 'Solo los datos de la carrera q.table("Alumnos").seleccionar({}).join("carrera", "id_carrera") 'El array vacio {} indica que no se quieren items de esa tabla. 'TODOS los alumnos aunque no tengan carrera asignada [LEFT JOIN] q.table("Alumnos").seleccionar().leftJoin("carrera", "id_carrera") '-- Para valuar una clausula de WHERE con elementos de la tabla join tienen que hacerse inmediatamete despues del join '-- ya que este debuelve otro objeto '-- el where se puede anidar con el correspondiente join 'Obtener solo los alumnos de la carrera de Medicina Dim tablaCarrera As TableSelected = q.table("Alumnos").seleccionar().join("carrera", "id_carrera") tablaCarrera.where("@n_carrera", "Medicina") 'Obtener todos los alumnos de Medicina cuyos ingresos sean mayores a 5000 q.table("Alumnos").seleccionar(). where("@ingresos", ">", 5000). join("carreras", "id_carreras"). where("@n_carrera", "Medicina") ' __________________________________________________________ '| | '| Union de tablas consecutivas | '|__________________________________________________________| '| Para unir una tabla con otra y esa con otra | '| Ej: Alumnos -> carreras -> tipo_carrera | '| | '| Se tiene que hacer el join con el objeto que se obtiene | '| del join entre la tabla principal y el primer join. | '| Todo join hecho sobre el Query Principal se intentara | '| hacer sobre la tabla principal. | '| Ej: Alumnos -> Carrera ^ Alumnos -> tipo_documentos | '|__________________________________________________________| 'Unir la tabla Alumnos con la de carrera y la de tipo_documento ' Alumnos -> Carrera y Alumnos -> tipo_documento q.table("Alumnos").seleccionar() q.join("carreras", "id_carrera") q.join("tipo_documento", "id_tipo_documento") 'Notese que ambos joins se hacen sobre el Query Principal 'Unir la tabla Alumnos con carrera y esta con tipo_carrera ' Alumnos -> Carrera -> tipo_carrera q.table("Alumnos").seleccionar().join("carrera", "id_carrera").join("tipo_carrera", Nothing, "id_tipo_carrera") 'Notese que el metodo del segundo join no es el mismo que el primero. 'Para hacer un segundo left join, o selecionar los items q.table("Alumnos").seleccionar().join("carrera", "id_carrera").join("tipo_carrera", {"nombre_tipo", "descripcion"}, "id_tipo_carrera", type:=JoinSelected.JoinType.Left) 'Sobre eso se puede hacer un WHERE para esae join Return q End Function Public Shared Function ejemplos_con_update(q As QB.QueryBuilder) As QB.QueryBuilder ' __________________________________________________________ '| | '| Actualizacion de datos | '|__________________________________________________________| '| Para hacer una actualizacion se selecciona primero la | '| tabla igual que antes. y luego de a pares los campos a | '| modificar junto con su valor en forma de dobles array | '| | '| Ese update tambien cumple con la regla del caracter | '| especial @ para uso de campos. Unicamente en el valor. | '| | '| De igual manera que antes se puede hacer WHERE para | '| modificar valores seleccionados. | '|__________________________________________________________| 'Actuaizar todos los Pagos Obligatorios a 0 q.table("Clientes").update({"pagos_obligatorios", 0}) 'Notese que si es un solo valor se puede hacer con un array simple 'Actualizar todos los pagos obligatorios a 0 y costos a 500 q.table("Clientes").update({ {"pagos_obligatorios", 0}, {"costos", 500} }) 'Actualizar los costos un 15% q.table("Producto").update({"costos", "@costos * 1.15"}) 'Aumentar la comicion de las empleadas mujeres q.table("Empleados").update({"comicion", "@comicion * 1.10"}).where("sexo", "m") 'Cambiar el nombre, apellido, nombre de la calle y numero de la calle del alumno con dni 555555 q.table("Alumnos").update({ {"Nombres", "Ramon"}, {"Apellidos", "Diaz"}, {"calle", "Humberto Primo"}, {"nro_calle", 522} }).where("nro_documento", 5555555) 'Tira excepcion si intentas hacer join Return q End Function Public Shared Function ejemplos_con_insert(q As QB.QueryBuilder) As QB.QueryBuilder ' __________________________________________________________ '| | '| Inercion de datos | '|__________________________________________________________| '| La insercion de datos es muy similar a la actualizacion | '| sin contar que es la mas facil. | '| Igual que en la actualizacion. los datos se pasan con | '| arrays dobles con el campo y el valor. | '| Este metodo no acepta joins ni where. | '| Se puede usar @null para insertar un valor nulo | '| de igual manera que Nothing | '| | '| Se pueden hacer inserciones multiples en el mismo | '| Query Builder | '|__________________________________________________________| 'Insertar un nuevo alumno q.table("Alumno").insert({ {"Nombres", "Juan Luis"}, {"Apellido", "Ramirez"}, {"id_tipo_documento", 1}, {"sexo", "h"}, {"calle", "@null"}, {"actividad", Nothing} }) 'Insertar Varios alumnos a la vez. Simplemente llamando al insert de vuelta antes del build. q.table("Alumno").insert({ {"Nombres", "Juan Luis"}, {"Apellido", "Ramirez"}, {"id_tipo_documento", 1}, {"sexo", "h"}, {"calle", "@null"}, {"actividad", Nothing} }) q.insert({ {"Nombres", "Juan Luis"}, {"Apellido", "Ramirez"}, {"id_tipo_documento", 1}, {"sexo", "h"}, {"calle", "@null"}, {"actividad", Nothing} }) q.build() Return q End Function End Class
Imports System.Runtime.InteropServices Imports System.Windows.Forms Public Class TransparentListView Inherits ListView Public Sub New() Me.OwnerDraw = True Me.DoubleBuffered = True End Sub Private _itemHeight As Integer = 16 Public Property ItemHeight As Integer Get Return _itemHeight End Get Set(value As Integer) _itemHeight = value If SmallImageList Is Nothing Then SmallImageList = New ImageList() End If SmallImageList.ImageSize = New Size(1, _itemHeight) End Set End Property Protected Overrides Sub OnDrawItem(ByVal e As DrawListViewItemEventArgs) Dim it As ListViewItem = e.Item Dim bg As Color = Color.Transparent Dim fg As Color = Color.Gold If e.State.HasFlag(ListViewItemStates.Selected) Then bg = Color.DarkBlue fg = Color.OrangeRed e.DrawFocusRectangle() End If it.ForeColor = fg it.BackColor = bg If Not View = Windows.Forms.View.Details Then e.DrawText(TextFormatFlags.VerticalCenter Or TextFormatFlags.LeftAndRightPadding) End If End Sub Protected Overrides Sub CreateHandle() MyBase.CreateHandle() UnsafeNativeMethods.SendMessage(Me.Handle, UnsafeNativeMethods.LVM_SETBKCOLOR, 0, UnsafeNativeMethods.CLR_NONE) End Sub Private Overloads Function UpdateBounds(ByVal item As ListViewItem, ByVal originalBounds As Rectangle, ByVal drawText As Boolean) As Rectangle Dim rectangle As Rectangle = originalBounds If (item.ListView.View = View.Details) Then If (Not item.ListView.FullRowSelect AndAlso (item.SubItems.Count > 0)) Then Dim subItem As ListViewItem.ListViewSubItem = item.SubItems(0) Dim size As Size = TextRenderer.MeasureText(subItem.Text, subItem.Font) rectangle = New Rectangle(originalBounds.X, originalBounds.Y, size.Width, size.Height) rectangle.X = (rectangle.X + 4) rectangle.Width += 1 Else rectangle.X = (rectangle.X + 4) rectangle.Width = (rectangle.Width - 4) End If If drawText Then rectangle.X -= 1 End If End If Return rectangle End Function Private Class UnsafeNativeMethods Friend Const CLR_NONE As Integer = -1 Friend Const LVM_FIRST As Integer = &H1000 Friend Const LVM_SETBKCOLOR As Integer = LVM_FIRST + 1 <DllImport("user32.dll", CharSet:=CharSet.Auto)> _ Friend Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As IntPtr End Function End Class End Class
 Option Compare Binary Option Infer On Option Strict On Option Explicit On Imports System Imports System.Collections.Generic Imports System.ComponentModel Imports System.ComponentModel.DataAnnotations Imports System.Linq Imports System.ServiceModel.DomainServices.Hosting Imports System.ServiceModel.DomainServices.Server Imports CableSoft.BLL.Utility 'TODO: 建立包含應用程式邏輯的方法。 Public Class DynamicUpdate 'Inherits DomainService Implements IDisposable Private _DynamicUpdate As CableSoft.BLL.Dynamic.DynamicUpdate.DynamicUpdate Private result As New RIAResult() Public Property isHTML As Boolean = False Private Sub InitClass(ByVal LoginInfo As LoginInfo) _DynamicUpdate = New CableSoft.BLL.Dynamic.DynamicUpdate.DynamicUpdate(LoginInfo.ConvertTo(LoginInfo)) End Sub Public Function Save(ByVal LoginInfo As LoginInfo, ByVal EditMode As EditMode, ByVal SysProgramId As String, ByVal dsSource As String) As RIAResult Try InitClass(LoginInfo) Dim ds As DataSet = Silverlight.DataSetConnector.Connector.FromXml(dsSource) result.ResultBoolean = True 'result.ResultXML = Silverlight.DataSetConnector.Connector.ToXml( ' _DynamicUpdate.Execute(EditMode, SysProgramId, ds)) 'result.ResultXML = CableSoft.BLL.Utility.JsonServer.ToJson( ' _DynamicUpdate.Execute(EditMode, SysProgramId, ds)) result = _DynamicUpdate.Execute(EditMode, SysProgramId, ds) If result.ResultDataSet IsNot Nothing Then result.ResultXML = CableSoft.BLL.Utility.JsonServer.ToJson(result.ResultDataSet, JsonServer.JsonFormatting.None, JsonServer.NullValueHandling.Ignore, True, True, isHTML) End If Catch ex As Exception ErrorHandle.BuildMessage(result, ex, LoginInfo.DebugMode) Return result Finally _DynamicUpdate.Dispose() End Try Return result End Function Public Function GetCompCode(ByVal LoginInfo As LoginInfo) As RIAResult Try InitClass(LoginInfo) Dim ds As DataSet = _DynamicUpdate.GetCompCode().DataSet result.ResultXML = CableSoft.BLL.Utility.JsonServer.ToJson(ds, JsonServer.JsonFormatting.None, JsonServer.NullValueHandling.Ignore, True, True, isHTML) 'result.ResultXML = Silverlight.DataSetConnector.Connector.ToXml(ds) result.ResultBoolean = True Catch ex As Exception ErrorHandle.BuildMessage(result, ex, LoginInfo.DebugMode) result.ResultBoolean = False Return result Finally _DynamicUpdate.Dispose() End Try Return result End Function Public Function CopyToOtherDB(ByVal LoginInfo As LoginInfo, ByVal sysProgramId As String, ByVal IsCover As Boolean, ByVal dsSource As String, ByVal dsCopyComps As String) As RIAResult Try InitClass(LoginInfo) Dim ds As DataSet = Silverlight.DataSetConnector.Connector.FromXml(dsSource) Dim dsComp As DataSet = Silverlight.DataSetConnector.Connector.FromXml(dsCopyComps) result = _DynamicUpdate.CopyToOtherDB(sysProgramId, IsCover, ds, dsComp) Catch ex As Exception result.ErrorCode = -999 result.ErrorMessage = ex.ToString Finally _DynamicUpdate.Dispose() _DynamicUpdate = Nothing End Try Return result End Function Public Function Execute(ByVal LoginInfo As LoginInfo, ByVal EditMode As EditMode, ByVal SysProgramId As String, ByVal dsSource As String) As RIAResult Try InitClass(LoginInfo) Dim ds As DataSet = Silverlight.DataSetConnector.Connector.FromXml(dsSource) result.ResultBoolean = True 'result.ResultXML = Silverlight.DataSetConnector.Connector.ToXml( ' _DynamicUpdate.Execute(EditMode, SysProgramId, ds)) 'result.ResultXML = CableSoft.BLL.Utility.JsonServer.ToJson( ' _DynamicUpdate.Execute(EditMode, SysProgramId, ds)) result = _DynamicUpdate.Execute(EditMode, SysProgramId, ds) If result.ResultDataSet IsNot Nothing Then result.ResultXML = CableSoft.BLL.Utility.JsonServer.ToJson(result.ResultDataSet, JsonServer.JsonFormatting.None, JsonServer.NullValueHandling.Ignore, True, True, isHTML) End If Catch ex As Exception If TypeOf ex Is OracleClient.OracleException Then If CType(ex, OracleClient.OracleException).Code = 1 Then result.ErrorCode = -1 result.ErrorMessage = "PK值重複!" result.ResultBoolean = False Else ErrorHandle.BuildMessage(result, ex, LoginInfo.DebugMode) result.ResultBoolean = False Return result End If Else ErrorHandle.BuildMessage(result, ex, LoginInfo.DebugMode) result.ResultBoolean = False Return result End If Finally _DynamicUpdate.Dispose() End Try Return result End Function Public Function QueryEnvironment(ByVal LoginInfo As LoginInfo, ByVal EditMode As EditMode, ByVal SysProgramId As String) As RIAResult Try InitClass(LoginInfo) Dim ds As DataSet = _DynamicUpdate.QueryEnvironment(SysProgramId) result.ResultXML = CableSoft.BLL.Utility.JsonServer.ToJson(ds, JsonServer.JsonFormatting.None, JsonServer.NullValueHandling.Ignore, True, True, isHTML) 'result.ResultXML = Silverlight.DataSetConnector.Connector.ToXml(ds) result.ResultBoolean = True Catch ex As Exception ErrorHandle.BuildMessage(result, ex, LoginInfo.DebugMode) Return result Finally _DynamicUpdate.Dispose() End Try Return result End Function #Region "IDisposable Support" Private disposedValue As Boolean ' 偵測多餘的呼叫 ' IDisposable Protected Overridable Sub Dispose(disposing As Boolean) If Not Me.disposedValue Then If disposing Then ' TODO: 處置 Managed 狀態 (Managed 物件)。 End If ' TODO: 釋放 Unmanaged 資源 (Unmanaged 物件) 並覆寫下面的 Finalize()。 ' TODO: 將大型欄位設定為 null。 End If Me.disposedValue = True End Sub ' TODO: 只有當上面的 Dispose(ByVal disposing As Boolean) 有可釋放 Unmanaged 資源的程式碼時,才覆寫 Finalize()。 'Protected Overrides Sub Finalize() ' ' 請勿變更此程式碼。在上面的 Dispose(ByVal disposing As Boolean) 中輸入清除程式碼。 ' Dispose(False) ' MyBase.Finalize() 'End Sub ' 由 Visual Basic 新增此程式碼以正確實作可處置的模式。 Public Sub Dispose() Implements IDisposable.Dispose ' 請勿變更此程式碼。在以上的 Dispose 置入清除程式碼 (ByVal 視為布林值處置)。 Dispose(True) GC.SuppressFinalize(Me) End Sub #End Region End Class
Imports System.Web Imports System.Web.Services Imports System.Web.Services.Protocols Imports System.Data Imports System.Data.SqlClient Imports System.Collections.Generic Imports System.Configuration ' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. <System.Web.Script.Services.ScriptService()> _ <WebService(Namespace:="http://tempuri.org/")> _ <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Public Class WSLookUp Inherits System.Web.Services.WebService Private Shared autoCompleteWordList As String() Public Sub New() 'constructor End Sub ' <WebMethod()> _ ' Public Function GetWordList(ByVal prefixText As String, ByVal count As Integer) As String() ' If (autoCompleteWordList Is Nothing) Then ' Dim temp() As String = IO.File.ReadAllLines(Server.MapPath("~/App_Data/words.txt")) ' Array.Sort(temp, New CaseInsensitiveComparer) ' autoCompleteWordList = temp ' End If ' Dim index As Integer = Array.BinarySearch(autoCompleteWordList, prefixText, New CaseInsensitiveComparer) ' If (index < 0) Then ' index = Not index ' End If ' Dim matchingCount As Integer ' matchingCount = 0 ' Do While ((matchingCount < count) _ ' AndAlso (index _ ' + (matchingCount < autoCompleteWordList.Length))) ' If Not autoCompleteWordList((index + matchingCount)).StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase) Then ' 'TODO: Warning!!! break;If ' End If ' matchingCount = (matchingCount + 1) ' Loop ' Dim returnValue() As String = New String((matchingCount) - 1) {} ' If (matchingCount > 0) Then ' Array.Copy(autoCompleteWordList, index, returnValue, 0, matchingCount) ' End If ' Return returnValue ' End Function <WebMethod(Description:="Method to retrieve Auto Complete List")> _ Public Function GetAutoCompleteList(ByVal prefixText As String, ByVal count As Integer) As Array Dim SqlConnection1 As New SqlConnection(ConfigurationManager.ConnectionStrings("astorwebdatabase20ConnectionString").ToString) Dim sSP As String = "GetAutoCompleteList_sp" Dim _scSC As New SqlCommand(sSP, SqlConnection1) Dim suggestions As New List(Of String) prefixText = Replace(prefixText, "%", String.Empty) prefixText = Replace(prefixText, """", String.Empty) prefixText = Replace(prefixText, "'", String.Empty) With _scSC .CommandType = CommandType.StoredProcedure With .Parameters .Add(New SqlParameter("@term", SqlDbType.VarChar, 150, ParameterDirection.Input)).Value = prefixText & "%" .Add(New SqlParameter("@nrows", SqlDbType.Int, 6, ParameterDirection.Input)).Value() = count End With Try .Connection.Open() Dim dr As SqlDataReader = .ExecuteReader(CommandBehavior.CloseConnection) While dr.Read suggestions.Add(dr(0).ToString) End While Catch ex As Exception Throw ex Finally If .Connection.State = ConnectionState.Open Then .Connection.Close() End If End Try End With Return suggestions.ToArray End Function End Class
Imports cv = OpenCvSharp ' https://github.com/JiphuTzu/opencvsharp/blob/master/sample/SamplesVB/Samples/FASTSample.vb Public Class FAST_Basics : Implements IDisposable Dim sliders As New OptionsSliders Public keypoints() As cv.KeyPoint Public Sub New(ocvb As AlgorithmData) sliders.setupTrackBar1(ocvb, "Threshold", 0, 200, 15) If ocvb.parms.ShowOptions Then sliders.Show() ocvb.desc = "Find interesting points with the FAST (Features from Accelerated Segment Test) algorithm" ocvb.label1 = "FAST_Basics nonMax = true" End Sub Public Sub Run(ocvb As AlgorithmData) Dim gray = ocvb.color.CvtColor(cv.ColorConversionCodes.BGR2GRAY) ocvb.color.CopyTo(ocvb.result1) keypoints = cv.Cv2.FAST(gray, sliders.TrackBar1.Value, True) For Each kp As cv.KeyPoint In keypoints ocvb.result1.Circle(kp.Pt, 3, cv.Scalar.Red, -1, cv.LineTypes.AntiAlias, 0) Next kp End Sub Public Sub Dispose() Implements IDisposable.Dispose sliders.Dispose() End Sub End Class Public Class FAST_Centroid : Implements IDisposable Dim check As New OptionsCheckbox Dim fast As FAST_Basics Dim kalman As Kalman_Point2f Public Sub New(ocvb As AlgorithmData) kalman = New Kalman_Point2f(ocvb) fast = New FAST_Basics(ocvb) check.Setup(ocvb, 1) check.Box(0).Text = "Turn Kalman filtering on" check.Box(0).Checked = True If ocvb.parms.ShowOptions Then check.Show() End Sub Public Sub Run(ocvb As AlgorithmData) fast.Run(ocvb) ocvb.result2.SetTo(0) For Each kp As cv.KeyPoint In fast.keypoints ocvb.result2.Circle(kp.Pt, 10, cv.Scalar.White, -1, cv.LineTypes.AntiAlias, 0) Next kp Dim gray = ocvb.result2.CvtColor(cv.ColorConversionCodes.BGR2GRAY) Dim m = cv.Cv2.Moments(gray, True) If m.M00 > 5000 Then ' if more than x pixels are present (avoiding a zero area!) If check.Box(0).Checked Then kalman.inputReal = New cv.Point2f(m.M10 / m.M00, m.M01 / m.M00) kalman.Run(ocvb) ocvb.result2.Circle(New cv.Point(kalman.statePoint.X, kalman.statePoint.Y), 10, cv.Scalar.Red, -1, cv.LineTypes.AntiAlias) Else ocvb.result2.Circle(New cv.Point2f(m.M10 / m.M00, m.M01 / m.M00), 10, cv.Scalar.Red, -1, cv.LineTypes.AntiAlias) End If End If End Sub Public Sub Dispose() Implements IDisposable.Dispose fast.Dispose() kalman.Dispose() check.Dispose() End Sub End Class
' This is a Client application programming code Imports System.Threading Imports System.Net Imports System.Net.Sockets Imports System.Text Imports Excel Public Class PrinterClient Public Event Disconnect(ByVal sender As PrinterClient) Public Event LineReceived(ByVal sender As PrinterClient, ByVal Data As String) Public Event ErrorMsg(ByVal sender As PrinterClient, ByVal ErrMsg As String) Public mClient As TcpClient Public s As Socket Dim connInfo As IPEndPoint = CType(s.RemoteEndPoint, IPEndPoint) Private readBytes(1024) As Byte Private mText As New StringBuilder() Public printMessage As String Public Sub New(ByVal client As TcpClient) mClient = client s = mClient.Client mClient.GetStream.BeginRead(readBytes, 0, 1024, AddressOf DoStreamReceive, Nothing) Send("A?") End Sub Public ReadOnly Property Name() As String Get Return connInfo.ToString End Get End Property Private Sub DoStreamReceive(ByVal ar As IAsyncResult) Dim BytesRead As Integer Try SyncLock mClient.GetStream BytesRead = mClient.GetStream.EndRead(ar) End SyncLock If BytesRead < 1 Then RaiseEvent Disconnect(Me) Exit Sub End If BuildString(readBytes, 0, BytesRead) SyncLock mClient.GetStream mClient.GetStream.BeginRead(readBytes, 0, 1024, AddressOf DoStreamReceive, Nothing) End SyncLock Catch e As Exception RaiseEvent Disconnect(Me) End Try End Sub Private Sub BuildString(ByVal Bytes() As Byte, ByVal offset As Integer, ByVal count As Integer) For intIndex = offset To offset + count - 1 If Bytes(intIndex) = 4 Or Bytes(intIndex) = 6 Then RaiseEvent LineReceived(Me, mText.ToString) mText = New StringBuilder() Else mText.Append(ChrW(Bytes(intIndex))) End If Next End Sub Public Sub Send(ByVal Data As String) SyncLock mClient.GetStream Dim w As New IO.StreamWriter(mClient.GetStream) w.Write(Chr(27) & Data & Chr(4)) w.Flush() End SyncLock End Sub Public Sub GetPrintMessage(ByVal printMsgNum As String) Try Dim objExcel As New Excel.Application Dim objWorkbook As Excel.Workbook Dim objSheet As Excel.Worksheet objWorkbook = objExcel.Workbooks.Open(msgFilePath, ReadOnly:=True) objSheet = objWorkbook.Worksheets(Val(msgWorkSheet)) objExcel.Visible = False Dim cellText As String Dim rowIndexMax As Integer = 2 Dim colmnIndex As Integer = Val(printMsgNum) printMessage = Nothing Do cellText = objSheet.Cells(rowIndexMax, 1).value() rowIndexMax += 1 Loop Until (cellText = "") For i As Integer = 2 To rowIndexMax If colmnIndex = objSheet.Cells(i, 1).Value Then printMessage = objSheet.Cells(i, 2).Value printMessage = printMessage.Replace(Chr(176), Chr(27) + "m1") printMessage = printMessage.Replace("?U", Chr(27) + "m2") printMessage = printMessage.Replace(timePrint, Chr(27) + "n1A" + "/" + Chr(27) + "n1G" + _ "/" + Chr(27) + "n1E") printMessage = printMessage.Replace(seqFootMarksPrint, Chr(27) + "j1N06000000999999000001NN000000000000N" + _ "ft") printMessage = printMessage.Replace(seqMeterMarksPrint, Chr(27) + "j1N06000000999999000001NN000000000000N" + _ "m") Exit For ElseIf i >= rowIndexMax Then End If Next objWorkbook.Close() objExcel.Quit() objSheet = Nothing objExcel = Nothing objWorkbook = Nothing Catch ex1 As System.IO.DirectoryNotFoundException RaiseEvent ErrorMsg(Me, "Drive not connected or file not found") Catch ex2 As Exception RaiseEvent ErrorMsg(Me, "GetPrintMessage: " & ex2.Message) GC.Collect() End Try GC.Collect() End Sub End Class
Imports System.Collections.Generic Imports System.Linq Imports System.Threading Public MustInherit Class FrequencyInfoSource Public MustOverride Sub Listen() Public MustOverride Sub [Stop]() Public Event FrequencyDetected As EventHandler(Of FrequencyDetectedEventArgs) Protected Sub OnFrequencyDetected(e As FrequencyDetectedEventArgs) RaiseEvent FrequencyDetected(Me, e) End Sub End Class Public Class FrequencyDetectedEventArgs Inherits EventArgs Private m_frequency As Double Public ReadOnly Property Frequency() As Double Get Return m_frequency End Get End Property Public Sub New(frequency As Double) Me.m_frequency = frequency End Sub End Class
Public Class frmLQVA Inherits System.Windows.Forms.Form Dim lstData As ItemData #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. Friend WithEvents grd As MSHierarchicalFlexGridLib.MSHFlexGrid Friend WithEvents lblsurah As System.Windows.Forms.Label Friend WithEvents cboSurah As System.Windows.Forms.ComboBox Friend WithEvents lbl As System.Windows.Forms.Label Friend WithEvents rtxtTahleel As System.Windows.Forms.RichTextBox Friend WithEvents lblTahleel As System.Windows.Forms.Label Friend WithEvents tipGrd As System.Windows.Forms.ToolTip Friend WithEvents chkArabic As System.Windows.Forms.CheckBox Friend WithEvents chkUrdu As System.Windows.Forms.CheckBox Friend WithEvents chkEnglish As System.Windows.Forms.CheckBox Friend WithEvents mnu As System.Windows.Forms.ContextMenu Friend WithEvents mnuShow As System.Windows.Forms.MenuItem Friend WithEvents pnl As System.Windows.Forms.Panel Friend WithEvents lstIndex As System.Windows.Forms.ListBox Friend WithEvents lnk As System.Windows.Forms.LinkLabel <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container() Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(frmLQVA)) Me.grd = New MSHierarchicalFlexGridLib.MSHFlexGrid() Me.lblsurah = New System.Windows.Forms.Label() Me.cboSurah = New System.Windows.Forms.ComboBox() Me.lbl = New System.Windows.Forms.Label() Me.rtxtTahleel = New System.Windows.Forms.RichTextBox() Me.mnu = New System.Windows.Forms.ContextMenu() Me.mnuShow = New System.Windows.Forms.MenuItem() Me.lblTahleel = New System.Windows.Forms.Label() Me.tipGrd = New System.Windows.Forms.ToolTip(Me.components) Me.chkArabic = New System.Windows.Forms.CheckBox() Me.chkUrdu = New System.Windows.Forms.CheckBox() Me.chkEnglish = New System.Windows.Forms.CheckBox() Me.pnl = New System.Windows.Forms.Panel() Me.lstIndex = New System.Windows.Forms.ListBox() Me.lnk = New System.Windows.Forms.LinkLabel() CType(Me.grd, System.ComponentModel.ISupportInitialize).BeginInit() Me.pnl.SuspendLayout() Me.SuspendLayout() ' 'grd ' Me.grd.DataSource = Nothing Me.grd.Location = New System.Drawing.Point(2, 56) Me.grd.Name = "grd" Me.grd.OcxState = CType(resources.GetObject("grd.OcxState"), System.Windows.Forms.AxHost.State) Me.grd.Size = New System.Drawing.Size(676, 336) Me.grd.TabIndex = 3 ' 'lblsurah ' Me.lblsurah.AutoSize = True Me.lblsurah.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Bold) Me.lblsurah.ForeColor = System.Drawing.Color.Blue Me.lblsurah.ImeMode = System.Windows.Forms.ImeMode.NoControl Me.lblsurah.Location = New System.Drawing.Point(608, 34) Me.lblsurah.Name = "lblsurah" Me.lblsurah.RightToLeft = System.Windows.Forms.RightToLeft.Yes Me.lblsurah.Size = New System.Drawing.Size(65, 15) Me.lblsurah.TabIndex = 4 Me.lblsurah.Text = "سورة الفاتحة" Me.lblsurah.TextAlign = System.Drawing.ContentAlignment.MiddleRight Me.lblsurah.Visible = False ' 'cboSurah ' Me.cboSurah.BackColor = System.Drawing.Color.FromArgb(CType(201, Byte), CType(233, Byte), CType(254, Byte)) Me.cboSurah.DropDownStyle = System.Windows.Forms.ComboBoxStyle.Simple Me.cboSurah.ForeColor = System.Drawing.Color.MediumBlue Me.cboSurah.ItemHeight = 13 Me.cboSurah.Location = New System.Drawing.Point(240, 34) Me.cboSurah.MaxDropDownItems = 10 Me.cboSurah.Name = "cboSurah" Me.cboSurah.RightToLeft = System.Windows.Forms.RightToLeft.Yes Me.cboSurah.Size = New System.Drawing.Size(272, 21) Me.cboSurah.TabIndex = 8 Me.cboSurah.Visible = False ' 'lbl ' Me.lbl.BackColor = System.Drawing.Color.Navy Me.lbl.Location = New System.Drawing.Point(-8, 0) Me.lbl.Name = "lbl" Me.lbl.Size = New System.Drawing.Size(690, 18) Me.lbl.TabIndex = 9 Me.lbl.TextAlign = System.Drawing.ContentAlignment.TopRight ' 'rtxtTahleel ' Me.rtxtTahleel.BackColor = System.Drawing.Color.FromArgb(CType(201, Byte), CType(233, Byte), CType(254, Byte)) Me.rtxtTahleel.BorderStyle = System.Windows.Forms.BorderStyle.None Me.rtxtTahleel.ContextMenu = Me.mnu Me.rtxtTahleel.Font = New System.Drawing.Font("Tahoma", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.rtxtTahleel.ForeColor = System.Drawing.Color.MediumBlue Me.rtxtTahleel.Location = New System.Drawing.Point(10, 419) Me.rtxtTahleel.Name = "rtxtTahleel" Me.rtxtTahleel.ReadOnly = True Me.rtxtTahleel.RightToLeft = System.Windows.Forms.RightToLeft.Yes Me.rtxtTahleel.Size = New System.Drawing.Size(656, 85) Me.rtxtTahleel.TabIndex = 10 Me.rtxtTahleel.Text = "" ' 'mnu ' Me.mnu.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuShow}) ' 'mnuShow ' Me.mnuShow.Index = 0 Me.mnuShow.Shortcut = System.Windows.Forms.Shortcut.F5 Me.mnuShow.Text = "اس لفظ کے بارے ميں جانيے" ' 'lblTahleel ' Me.lblTahleel.AutoSize = True Me.lblTahleel.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblTahleel.ForeColor = System.Drawing.Color.Blue Me.lblTahleel.ImeMode = System.Windows.Forms.ImeMode.NoControl Me.lblTahleel.Location = New System.Drawing.Point(636, 396) Me.lblTahleel.Name = "lblTahleel" Me.lblTahleel.Size = New System.Drawing.Size(36, 19) Me.lblTahleel.TabIndex = 11 Me.lblTahleel.Text = "تحليل" ' 'chkArabic ' Me.chkArabic.Cursor = System.Windows.Forms.Cursors.Hand Me.chkArabic.FlatStyle = System.Windows.Forms.FlatStyle.Popup Me.chkArabic.Font = New System.Drawing.Font("Arial", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.chkArabic.Location = New System.Drawing.Point(6, 26) Me.chkArabic.Name = "chkArabic" Me.chkArabic.Size = New System.Drawing.Size(54, 26) Me.chkArabic.TabIndex = 12 Me.chkArabic.Text = "عربى" Me.chkArabic.TextAlign = System.Drawing.ContentAlignment.MiddleRight ' 'chkUrdu ' Me.chkUrdu.Cursor = System.Windows.Forms.Cursors.Hand Me.chkUrdu.FlatStyle = System.Windows.Forms.FlatStyle.Popup Me.chkUrdu.Font = New System.Drawing.Font("Arial", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.chkUrdu.Location = New System.Drawing.Point(68, 26) Me.chkUrdu.Name = "chkUrdu" Me.chkUrdu.Size = New System.Drawing.Size(48, 26) Me.chkUrdu.TabIndex = 13 Me.chkUrdu.Text = "اردو" Me.chkUrdu.TextAlign = System.Drawing.ContentAlignment.MiddleRight ' 'chkEnglish ' Me.chkEnglish.Cursor = System.Windows.Forms.Cursors.Hand Me.chkEnglish.FlatStyle = System.Windows.Forms.FlatStyle.Popup Me.chkEnglish.Font = New System.Drawing.Font("Arial", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.chkEnglish.Location = New System.Drawing.Point(132, 26) Me.chkEnglish.Name = "chkEnglish" Me.chkEnglish.Size = New System.Drawing.Size(72, 26) Me.chkEnglish.TabIndex = 14 Me.chkEnglish.Text = "انگريزى" Me.chkEnglish.TextAlign = System.Drawing.ContentAlignment.MiddleRight ' 'pnl ' Me.pnl.Controls.AddRange(New System.Windows.Forms.Control() {Me.lstIndex}) Me.pnl.Location = New System.Drawing.Point(1, 56) Me.pnl.Name = "pnl" Me.pnl.Size = New System.Drawing.Size(675, 492) Me.pnl.TabIndex = 15 ' 'lstIndex ' Me.lstIndex.BackColor = System.Drawing.Color.FromArgb(CType(201, Byte), CType(233, Byte), CType(254, Byte)) Me.lstIndex.BorderStyle = System.Windows.Forms.BorderStyle.None Me.lstIndex.Cursor = System.Windows.Forms.Cursors.Hand Me.lstIndex.Location = New System.Drawing.Point(172, 9) Me.lstIndex.MultiColumn = True Me.lstIndex.Name = "lstIndex" Me.lstIndex.RightToLeft = System.Windows.Forms.RightToLeft.Yes Me.lstIndex.Size = New System.Drawing.Size(492, 416) Me.lstIndex.TabIndex = 1 ' 'lnk ' Me.lnk.Cursor = System.Windows.Forms.Cursors.Hand Me.lnk.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lnk.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline Me.lnk.Location = New System.Drawing.Point(264, 510) Me.lnk.Name = "lnk" Me.lnk.Size = New System.Drawing.Size(168, 30) Me.lnk.TabIndex = 16 Me.lnk.TabStop = True Me.lnk.Text = "قرآن کى فﮧرست دﻳکھﻳں" Me.lnk.TextAlign = System.Drawing.ContentAlignment.MiddleCenter Me.lnk.Visible = False ' 'frmLQVA ' Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.BackColor = System.Drawing.Color.FromArgb(CType(201, Byte), CType(233, Byte), CType(254, Byte)) Me.ClientSize = New System.Drawing.Size(682, 612) Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.lnk, Me.pnl, Me.chkEnglish, Me.chkUrdu, Me.chkArabic, Me.lblTahleel, Me.rtxtTahleel, Me.lbl, Me.lblsurah, Me.grd, Me.cboSurah}) Me.ForeColor = System.Drawing.Color.DarkBlue Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.Name = "frmLQVA" Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "Learn Quran Via Arabic" CType(Me.grd, System.ComponentModel.ISupportInitialize).EndInit() Me.pnl.ResumeLayout(False) Me.ResumeLayout(False) End Sub #End Region Private Sub grd_DblClick() Handles grd.DblClick Dim Rs As New ADODB.Recordset() Rs.Open("Select * From " & CType(cboSurah.SelectedItem, ItemData).ID & " where AN=" & grd.get_TextMatrix(grd.Row, 1), Cn, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockReadOnly) If Not (Rs.EOF Or Rs.BOF) Then rtxtTahleel.Text = Rs.Fields.Item(5).Value & "" End If Rs.Close() End Sub Private Sub frmLQVA_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load '201, 233, 254 Dim Rs As New ADODB.Recordset() Rs.Open("Select * from SURAH", Cn, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockReadOnly) cboSurah.Items.Clear() Do While Not Rs.EOF = True lstData = New ItemData() lstData.ID = Rs.Fields.Item(0).Value lstData.Value = Rs.Fields.Item(1).Value cboSurah.Items.Add(lstData) Rs.MoveNext() Loop Rs.Close() cboSurah.SelectedIndex = 0 CreateMyToolTip() grdIndexFormat() End Sub Private Sub cboSurah_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboSurah.SelectedIndexChanged Call ShowData() End Sub Private Sub ShowData() '---------------- All checks are true --------------------- If chkArabic.Checked = True And chkUrdu.Checked = True And chkEnglish.Checked = True Then Call ArabicUrduEnglish() Exit Sub End If '----------------------- English Urdu ----------------------- If chkEnglish.Checked = True And chkUrdu.Checked = True Then Call UrduEnglish() Exit Sub End If '-------------------- Arabic English ------------------------ If chkArabic.Checked = True And chkEnglish.Checked = True Then Call ArabicEnglish() Exit Sub End If '------------------------- Arabic Urdu --------------------- If chkArabic.Checked = True And chkUrdu.Checked = True Then Call ArabicUrdu() Exit Sub End If '----------------------- Arabic ----------------------------- If chkArabic.Checked = True Then Call Arabic() Exit Sub End If '----------------------- Urdu ----------------------------- If chkUrdu.Checked = True Then Call Urdu() Exit Sub End If '----------------------- English ----------------------------- If chkEnglish.Checked = True Then Call English() Exit Sub End If End Sub Private Sub CreateMyToolTip() ' Create the ToolTip and associate with the Form container. Dim toolTip1 As New ToolTip(Me.components) ' Set up the delays for the ToolTip. toolTip1.AutoPopDelay = 5000 toolTip1.InitialDelay = 1000 toolTip1.ReshowDelay = 500 ' Force the ToolTip text to be displayed whether or not the form is active. toolTip1.ShowAlways = True ' Set up the ToolTip text for the Button and Checkbox. toolTip1.SetToolTip(Me.grd, "Double click on any ayat to view tahleel") toolTip1.SetToolTip(Me.cboSurah, "Surah") End Sub Private Sub chkState() If chkArabic.Checked = False And _ chkUrdu.Checked = False And _ chkEnglish.Checked = False Then chkArabic.Checked = True End If End Sub Private Sub chkArabic_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkArabic.CheckedChanged Call chkState() Call ShowData() End Sub Private Sub ArabicUrduEnglish() rtxtTahleel.Text = "" grd.Clear() grd.Rows = 3 Dim Rs As New ADODB.Recordset() grd.set_ColWidth(1, 0, 0) grd.set_ColWidth(0, 0, 9700) grd.set_ColAlignment(0, 7) grd.WordWrap = True grd.RowHeightMin = 400 Rs.Open("Select * from " & CType(cboSurah.SelectedItem, ItemData).ID, Cn, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockReadOnly) Dim i As Integer Dim A As Integer Me.Cursor = System.Windows.Forms.Cursors.WaitCursor If Not (Rs.EOF Or Rs.BOF) Then For i = 0 To Rs.RecordCount - 1 ' ----------- Arabic Text ------------------ grd.Row = A 'for focus a row grd.CellFontName = "Microsoft Sans Serif" grd.WordWrap = True grd.set_TextMatrix(A, 0, Rs.Fields.Item(2).Value & "") grd.set_TextMatrix(A, 1, Rs.Fields.Item(0).Value & "") If Len(Rs.Fields.Item(2).Value) + 200 >= grd.get_RowHeight(A) Then grd.set_RowHeight(A, Len(Rs.Fields.Item(2).Value) + 1000) End If '--------------------------------------------- '--------------- Urdu ----------------------- grd.Row = A + 1 'for focus a row grd.CellFontSize = 10 grd.CellFontName = "Tahoma" grd.CellForeColor = Convert.ToUInt32(Color.DarkGreen) grd.WordWrap = True grd.set_TextMatrix(A + 1, 0, Rs.Fields.Item(3).Value & "") grd.set_TextMatrix(A + 1, 1, Rs.Fields.Item(0).Value & "") '-------------------------------------------- '--------------- English -------------------- grd.Row = A + 2 'for focus a row grd.CellFontName = "Verdana" grd.CellFontSize = 10 grd.CellForeColor = Convert.ToUInt32(Color.Maroon) 'DarkGoldenrod grd.WordWrap = True grd.set_TextMatrix(A + 2, 0, Rs.Fields.Item(4).Value & "") grd.set_TextMatrix(A + 2, 1, Rs.Fields.Item(0).Value & "") If Len(Rs.Fields.Item(4).Value & "") + 300 >= grd.get_RowHeight(A + 2) Then grd.set_RowHeight(A + 2, Len(Rs.Fields.Item(4).Value & "") + 800) grd.Row = A + 2 grd.CellAlignment = 1 End If '--------------------------------------------- A = A + 3 grd.Rows = grd.Rows + 3 Rs.MoveNext() Next grd.Rows = grd.Rows - 3 Rs.Close() End If Me.Cursor = System.Windows.Forms.Cursors.Default End Sub Private Sub ArabicUrdu() rtxtTahleel.Text = "" grd.Clear() grd.Rows = 2 Dim Rs As New ADODB.Recordset() grd.set_ColWidth(1, 0, 0) grd.set_ColWidth(0, 0, 9700) grd.set_ColAlignment(0, 7) grd.WordWrap = True grd.RowHeightMin = 400 Rs.Open("Select * from " & CType(cboSurah.SelectedItem, ItemData).ID, Cn, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockReadOnly) Dim i As Integer Dim A As Integer Me.Cursor = System.Windows.Forms.Cursors.WaitCursor If Not (Rs.EOF Or Rs.BOF) Then For i = 0 To Rs.RecordCount - 1 ' ----------- Arabic Text ------------------ grd.Row = A 'for focus a row grd.CellFontName = "Microsoft Sans Serif" grd.WordWrap = True grd.set_TextMatrix(A, 0, Rs.Fields.Item(2).Value & "") grd.set_TextMatrix(A, 1, Rs.Fields.Item(0).Value & "") If Len(Rs.Fields.Item(2).Value) + 200 >= grd.get_RowHeight(A) Then grd.set_RowHeight(A, Len(Rs.Fields.Item(2).Value) + 1000) End If '--------------------------------------------- '--------------- Urdu ----------------------- grd.Row = A + 1 'for focus a row grd.CellFontSize = 10 grd.CellFontName = "Tahoma" grd.CellForeColor = Convert.ToUInt32(Color.DarkGreen) grd.WordWrap = True grd.set_TextMatrix(A + 1, 0, Rs.Fields.Item(3).Value & "") grd.set_TextMatrix(A + 1, 1, Rs.Fields.Item(0).Value & "") '-------------------------------------------- A = A + 2 grd.Rows = grd.Rows + 2 Rs.MoveNext() Next grd.Rows = grd.Rows - 2 Rs.Close() End If Me.Cursor = System.Windows.Forms.Cursors.Default End Sub Private Sub ArabicEnglish() rtxtTahleel.Text = "" grd.Clear() grd.Rows = 2 Dim Rs As New ADODB.Recordset() grd.set_ColWidth(1, 0, 0) grd.set_ColWidth(0, 0, 9700) grd.set_ColAlignment(0, 7) grd.WordWrap = True grd.RowHeightMin = 400 Rs.Open("Select * from " & CType(cboSurah.SelectedItem, ItemData).ID, Cn, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockReadOnly) Dim i As Integer Dim A As Integer Me.Cursor = System.Windows.Forms.Cursors.WaitCursor If Not (Rs.EOF Or Rs.BOF) Then For i = 0 To Rs.RecordCount - 1 ' ----------- Arabic Text ------------------ grd.Row = A 'for focus a row grd.CellFontName = "Microsoft Sans Serif" grd.WordWrap = True grd.set_TextMatrix(A, 0, Rs.Fields.Item(2).Value & "") grd.set_TextMatrix(A, 1, Rs.Fields.Item(0).Value & "") If Len(Rs.Fields.Item(2).Value) + 200 >= grd.get_RowHeight(A) Then grd.set_RowHeight(A, Len(Rs.Fields.Item(2).Value) + 1000) End If '--------------------------------------------- '--------------- English -------------------- grd.Row = A + 1 'for focus a row grd.CellFontName = "Verdana" grd.CellFontSize = 10 grd.CellForeColor = Convert.ToUInt32(Color.Maroon) 'DarkGoldenrod grd.WordWrap = True grd.set_TextMatrix(A + 1, 0, Rs.Fields.Item(4).Value & "") grd.set_TextMatrix(A + 1, 1, Rs.Fields.Item(0).Value & "") If Len(Rs.Fields.Item(4).Value & "") + 300 >= grd.get_RowHeight(A + 1) Then grd.set_RowHeight(A + 1, Len(Rs.Fields.Item(4).Value & "") + 800) grd.Row = A + 1 grd.CellAlignment = 1 End If '--------------------------------------------- A = A + 2 grd.Rows = grd.Rows + 2 Rs.MoveNext() Next grd.Rows = grd.Rows - 2 Rs.Close() End If Me.Cursor = System.Windows.Forms.Cursors.Default End Sub Private Sub UrduEnglish() rtxtTahleel.Text = "" grd.Clear() grd.Rows = 2 Dim Rs As New ADODB.Recordset() grd.set_ColWidth(1, 0, 0) grd.set_ColWidth(0, 0, 9700) grd.set_ColAlignment(0, 7) grd.WordWrap = True grd.RowHeightMin = 400 Rs.Open("Select * from " & CType(cboSurah.SelectedItem, ItemData).ID, Cn, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockReadOnly) Dim i As Integer Dim A As Integer Me.Cursor = System.Windows.Forms.Cursors.WaitCursor If Not (Rs.EOF Or Rs.BOF) Then For i = 0 To Rs.RecordCount - 1 '--------------- Urdu ----------------------- grd.Row = A 'for focus a row grd.CellFontSize = 10 grd.CellFontName = "Tahoma" grd.CellForeColor = Convert.ToUInt32(Color.DarkGreen) grd.WordWrap = True grd.set_TextMatrix(A, 0, Rs.Fields.Item(3).Value & "") grd.set_TextMatrix(A, 1, Rs.Fields.Item(0).Value & "") '-------------------------------------------- '--------------- English -------------------- grd.Row = A + 1 'for focus a row grd.CellFontName = "Verdana" grd.CellFontSize = 10 grd.CellForeColor = Convert.ToUInt32(Color.Maroon) 'DarkGoldenrod grd.WordWrap = True grd.set_TextMatrix(A + 1, 0, Rs.Fields.Item(4).Value & "") grd.set_TextMatrix(A + 1, 1, Rs.Fields.Item(0).Value & "") If Len(Rs.Fields.Item(4).Value & "") + 300 >= grd.get_RowHeight(A + 1) Then grd.set_RowHeight(A + 1, Len(Rs.Fields.Item(4).Value & "") + 800) grd.Row = A + 1 grd.CellAlignment = 1 End If '--------------------------------------------- A = A + 2 grd.Rows = grd.Rows + 2 Rs.MoveNext() Next grd.Rows = grd.Rows - 2 Rs.Close() End If Me.Cursor = System.Windows.Forms.Cursors.Default End Sub Private Sub Arabic() rtxtTahleel.Text = "" grd.Clear() grd.Rows = 1 Dim Rs As New ADODB.Recordset() grd.set_ColWidth(1, 0, 0) grd.set_ColWidth(0, 0, 9700) grd.set_ColAlignment(0, 7) grd.WordWrap = True grd.RowHeightMin = 400 Rs.Open("Select * from " & CType(cboSurah.SelectedItem, ItemData).ID, Cn, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockReadOnly) Dim i As Integer Dim A As Integer Me.Cursor = System.Windows.Forms.Cursors.WaitCursor If Not (Rs.EOF Or Rs.BOF) Then For i = 0 To Rs.RecordCount - 1 ' ----------- Arabic Text ------------------ grd.Row = A 'for focus a row grd.CellFontName = "Microsoft Sans Serif" grd.WordWrap = True grd.set_TextMatrix(A, 0, Rs.Fields.Item(2).Value & "") grd.set_TextMatrix(A, 1, Rs.Fields.Item(0).Value & "") If Len(Rs.Fields.Item(2).Value) + 200 >= grd.get_RowHeight(A) Then grd.set_RowHeight(A, Len(Rs.Fields.Item(2).Value) + 1000) End If '--------------------------------------------- A = A + 1 grd.Rows = grd.Rows + 1 Rs.MoveNext() Next grd.Rows = grd.Rows - 1 Rs.Close() End If Me.Cursor = System.Windows.Forms.Cursors.Default End Sub Private Sub Urdu() rtxtTahleel.Text = "" grd.Clear() grd.Rows = 1 Dim Rs As New ADODB.Recordset() grd.set_ColWidth(1, 0, 0) grd.set_ColWidth(0, 0, 9700) grd.set_ColAlignment(0, 7) grd.WordWrap = True grd.RowHeightMin = 400 Rs.Open("Select * from " & CType(cboSurah.SelectedItem, ItemData).ID, Cn, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockReadOnly) Dim i As Integer Dim A As Integer Me.Cursor = System.Windows.Forms.Cursors.WaitCursor If Not (Rs.EOF Or Rs.BOF) Then For i = 0 To Rs.RecordCount - 1 '--------------- Urdu ----------------------- grd.Row = A 'for focus a row grd.CellFontSize = 10 grd.CellFontName = "Tahoma" grd.CellForeColor = Convert.ToUInt32(Color.DarkGreen) grd.WordWrap = True grd.set_TextMatrix(A, 0, Rs.Fields.Item(3).Value & "") grd.set_TextMatrix(A, 1, Rs.Fields.Item(0).Value & "") '-------------------------------------------- A = A + 1 grd.Rows = grd.Rows + 1 Rs.MoveNext() Next grd.Rows = grd.Rows - 1 Rs.Close() End If Me.Cursor = System.Windows.Forms.Cursors.Default End Sub Private Sub English() rtxtTahleel.Text = "" grd.Clear() grd.Rows = 1 Dim Rs As New ADODB.Recordset() grd.set_ColWidth(1, 0, 0) grd.set_ColWidth(0, 0, 9700) grd.set_ColAlignment(0, 7) grd.WordWrap = True grd.RowHeightMin = 400 Rs.Open("Select * from " & CType(cboSurah.SelectedItem, ItemData).ID, Cn, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockReadOnly) Dim i As Integer Dim A As Integer Me.Cursor = System.Windows.Forms.Cursors.WaitCursor If Not (Rs.EOF Or Rs.BOF) Then For i = 0 To Rs.RecordCount - 1 '--------------- English -------------------- grd.Row = A 'for focus a row grd.CellFontName = "Verdana" grd.CellFontSize = 10 grd.CellForeColor = Convert.ToUInt32(Color.Maroon) 'DarkGoldenrod grd.WordWrap = True grd.CellAlignment = 1 grd.set_TextMatrix(A, 0, Rs.Fields.Item(4).Value & "") grd.set_TextMatrix(A, 1, Rs.Fields.Item(0).Value & "") If Len(Rs.Fields.Item(4).Value & "") + 300 >= grd.get_RowHeight(A) Then grd.set_RowHeight(A, Len(Rs.Fields.Item(4).Value & "") + 800) grd.Row = A 'grd.CellAlignment = 1 End If '--------------------------------------------- A = A + 1 grd.Rows = grd.Rows + 1 Rs.MoveNext() Next grd.Rows = grd.Rows - 1 Rs.Close() End If Me.Cursor = System.Windows.Forms.Cursors.Default End Sub Private Sub chkUrdu_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkUrdu.CheckedChanged Call chkState() Call ShowData() End Sub Private Sub chkEnglish_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkEnglish.CheckedChanged Call chkState() Call ShowData() End Sub Private Sub mnuShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuShow.Click 'Dim frmGRM As New frmGrammar() Dim frmM As New frmMain() Dim FrmT As New frmTrems() If Len(rtxtTahleel.SelectedText) > 0 Then 'frmGRM.Activate() 'frmGRM.MdiParent = frmMain.ActiveForm 'frmGRM.Show() 'frmGRM.Width = frmMain.ActiveForm.Width - frmM.picLeft.Width - 13 'frmGRM.Top = 0 'frmGRM.Left = frmM.picLeft.Width 'frmGRM.Height = frmMain.ActiveForm.Height - 32 Dim Rs As New ADODB.Recordset() Rs.Open("Select * from TEHLEEL Where TERM='" & Trim(rtxtTahleel.SelectedText) & "'", Cn, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockReadOnly) If Not (Rs.EOF Or Rs.BOF) Then 'MsgBox(Rs.Fields.Item(2).Value & "") FrmT.MdiParent = frmMain.ActiveForm FrmT.Show() FrmT.Width = frmMain.ActiveForm.Width - frmM.picLeft.Width - 13 FrmT.Top = 0 FrmT.Left = frmM.picLeft.Width FrmT.Height = frmMain.ActiveForm.Height - 32 FrmT.lstTerms.SelectedIndex = Rs.Fields.Item(0).Value - 1 & "" End If Rs.Close() End If End Sub Private Sub mnu_Popup(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnu.Popup If Len(rtxtTahleel.SelectedText) > 0 Then mnuShow.Text = rtxtTahleel.SelectedText & " کے بارے ميں جانيے" Else mnuShow.Text = "کسى بھى لفظ کے بارے ميں جاننے کےليے اسے منتخب کريں" End If End Sub Private Sub grdIndexFormat() Dim Rs As New ADODB.Recordset() Rs.Open("Select * from SURAH", Cn, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockReadOnly) lstIndex.Items.Clear() Do While Not Rs.EOF = True lstData = New ItemData() lstData.ID = Rs.Fields.Item(0).Value lstData.Value = Rs.Fields.Item(1).Value lstIndex.Items.Add(lstData) Rs.MoveNext() Loop Rs.Close() End Sub Private Sub lstIndex_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstIndex.DoubleClick pnl.Visible = False lnk.Visible = True lblsurah.Visible = True cboSurah.SelectedIndex = lstIndex.SelectedIndex Try lblsurah.Text = (CType(lstIndex.Items.Item(lstIndex.SelectedIndex), ItemData).Value()) 'lstIndex.Items.Item(lstIndex.SelectedIndex) Finally End Try End Sub Private Sub lnk_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnk.LinkClicked pnl.Visible = True lnk.Visible = False lblsurah.Visible = False End Sub End Class
Imports System Imports System.Collections.Generic Imports System.ComponentModel Imports System.Linq Imports System.Runtime.InteropServices Imports System.Text Imports System.Windows Imports System.Windows.Data Imports System.Windows.Interop Imports DevExpress.Mvvm.Native Imports DevExpress.Mvvm.UI.Interactivity Imports DevExpress.Xpf.Bars.Native Imports DevExpress.Xpf.Core Imports DevExpress.Xpf.Core.Native Imports DevExpress.Xpf.DemoBase Namespace EditorsDemo Friend Class PinnedWindowBehaviorNativeMethods <DllImport("user32.dll", EntryPoint := "GetWindowLong")> Shared Function GetWindowLong32(ByVal hWnd As IntPtr, ByVal nIndex As Integer) As Integer End Function <DllImport("user32.dll", EntryPoint := "GetWindowLongPtr")> Shared Function GetWindowLongPtr64(ByVal hWnd As IntPtr, ByVal nIndex As Integer) As IntPtr End Function Public Shared Function GetWindowLong(ByVal hWnd As IntPtr, ByVal nIndex As Integer) As Long If IntPtr.Size = 4 Then Return GetWindowLong32(hWnd, nIndex) End If Return GetWindowLongPtr64(hWnd, nIndex).ToInt64() End Function Public Shared Function SetWindowLongPtr(ByVal hWnd As HandleRef, ByVal nIndex As Integer, ByVal dwNewLong As Long) As IntPtr If IntPtr.Size = 8 Then Return SetWindowLongPtr64(hWnd, nIndex, New IntPtr(dwNewLong)) End If Return New IntPtr(SetWindowLong32(hWnd, nIndex, CInt(dwNewLong))) End Function <DllImport("user32.dll", EntryPoint := "SetWindowLong")> Shared Function SetWindowLong32(ByVal hWnd As HandleRef, ByVal nIndex As Integer, ByVal dwNewLong As Integer) As Integer End Function <DllImport("user32.dll", EntryPoint := "SetWindowLongPtr")> Shared Function SetWindowLongPtr64(ByVal hWnd As HandleRef, ByVal nIndex As Integer, ByVal dwNewLong As IntPtr) As IntPtr End Function <DllImport("user32.dll", SetLastError := True)> Public Shared Function SetParent(ByVal hWndChild As IntPtr, ByVal hWndNewParent As IntPtr) As IntPtr End Function End Class End Namespace
Public Class Form1 Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. Friend WithEvents DirectoryGroupBox As System.Windows.Forms.GroupBox Friend WithEvents txtDirectory As System.Windows.Forms.TextBox Friend WithEvents btnCreateDirectory As System.Windows.Forms.Button Friend WithEvents txtFunctionOutput As System.Windows.Forms.TextBox Friend WithEvents Button1 As System.Windows.Forms.Button Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox Friend WithEvents Button2 As System.Windows.Forms.Button Friend WithEvents Button3 As System.Windows.Forms.Button Friend WithEvents Button4 As System.Windows.Forms.Button Friend WithEvents Button5 As System.Windows.Forms.Button Friend WithEvents Button6 As System.Windows.Forms.Button Friend WithEvents Label2 As System.Windows.Forms.Label Friend WithEvents Label3 As System.Windows.Forms.Label Friend WithEvents Label4 As System.Windows.Forms.Label Friend WithEvents Label5 As System.Windows.Forms.Label Friend WithEvents Label6 As System.Windows.Forms.Label Friend WithEvents Label7 As System.Windows.Forms.Label <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Me.DirectoryGroupBox = New System.Windows.Forms.GroupBox() Me.txtDirectory = New System.Windows.Forms.TextBox() Me.btnCreateDirectory = New System.Windows.Forms.Button() Me.txtFunctionOutput = New System.Windows.Forms.TextBox() Me.Button1 = New System.Windows.Forms.Button() Me.GroupBox1 = New System.Windows.Forms.GroupBox() Me.Label7 = New System.Windows.Forms.Label() Me.Label6 = New System.Windows.Forms.Label() Me.Label5 = New System.Windows.Forms.Label() Me.Label4 = New System.Windows.Forms.Label() Me.Label3 = New System.Windows.Forms.Label() Me.Label2 = New System.Windows.Forms.Label() Me.Button6 = New System.Windows.Forms.Button() Me.Button5 = New System.Windows.Forms.Button() Me.Button4 = New System.Windows.Forms.Button() Me.Button3 = New System.Windows.Forms.Button() Me.Button2 = New System.Windows.Forms.Button() Me.DirectoryGroupBox.SuspendLayout() Me.GroupBox1.SuspendLayout() Me.SuspendLayout() ' 'DirectoryGroupBox ' Me.DirectoryGroupBox.Controls.AddRange(New System.Windows.Forms.Control() {Me.txtDirectory, Me.btnCreateDirectory, Me.txtFunctionOutput}) Me.DirectoryGroupBox.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(204, Byte)) Me.DirectoryGroupBox.Location = New System.Drawing.Point(8, 0) Me.DirectoryGroupBox.Name = "DirectoryGroupBox" Me.DirectoryGroupBox.Size = New System.Drawing.Size(168, 128) Me.DirectoryGroupBox.TabIndex = 7 Me.DirectoryGroupBox.TabStop = False ' 'txtDirectory ' Me.txtDirectory.AccessibleDescription = "Dierctory text" Me.txtDirectory.AccessibleName = "Dierctory text" Me.txtDirectory.BackColor = System.Drawing.SystemColors.Window Me.txtDirectory.Location = New System.Drawing.Point(16, 24) Me.txtDirectory.Name = "txtDirectory" Me.txtDirectory.Size = New System.Drawing.Size(136, 20) Me.txtDirectory.TabIndex = 4 Me.txtDirectory.Text = "c:\My folder" ' 'btnCreateDirectory ' Me.btnCreateDirectory.AccessibleDescription = "Create Directory button" Me.btnCreateDirectory.AccessibleName = "Create Directory button" Me.btnCreateDirectory.BackColor = System.Drawing.SystemColors.Window Me.btnCreateDirectory.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.btnCreateDirectory.ImeMode = System.Windows.Forms.ImeMode.NoControl Me.btnCreateDirectory.Location = New System.Drawing.Point(16, 56) Me.btnCreateDirectory.Name = "btnCreateDirectory" Me.btnCreateDirectory.Size = New System.Drawing.Size(136, 22) Me.btnCreateDirectory.TabIndex = 3 Me.btnCreateDirectory.Text = "Create folder" ' 'txtFunctionOutput ' Me.txtFunctionOutput.AccessibleDescription = "Function output text" Me.txtFunctionOutput.AccessibleName = "Function output text" Me.txtFunctionOutput.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(204, Byte)) Me.txtFunctionOutput.Location = New System.Drawing.Point(16, 88) Me.txtFunctionOutput.Multiline = True Me.txtFunctionOutput.Name = "txtFunctionOutput" Me.txtFunctionOutput.Size = New System.Drawing.Size(136, 22) Me.txtFunctionOutput.TabIndex = 8 Me.txtFunctionOutput.Text = "" ' 'Button1 ' Me.Button1.AccessibleDescription = "Create Directory button" Me.Button1.AccessibleName = "Create Directory button" Me.Button1.BackColor = System.Drawing.SystemColors.Window Me.Button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.Button1.ImeMode = System.Windows.Forms.ImeMode.NoControl Me.Button1.Location = New System.Drawing.Point(24, 24) Me.Button1.Name = "Button1" Me.Button1.Size = New System.Drawing.Size(136, 22) Me.Button1.TabIndex = 9 Me.Button1.Text = "Create folder" ' 'GroupBox1 ' Me.GroupBox1.Controls.AddRange(New System.Windows.Forms.Control() {Me.Label7, Me.Label6, Me.Label5, Me.Label4, Me.Label3, Me.Label2, Me.Button6, Me.Button5, Me.Button4, Me.Button3, Me.Button2, Me.Button1}) Me.GroupBox1.Location = New System.Drawing.Point(184, 0) Me.GroupBox1.Name = "GroupBox1" Me.GroupBox1.Size = New System.Drawing.Size(336, 128) Me.GroupBox1.TabIndex = 10 Me.GroupBox1.TabStop = False ' 'Label7 ' Me.Label7.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(204, Byte)) Me.Label7.Location = New System.Drawing.Point(168, 88) Me.Label7.Name = "Label7" Me.Label7.Size = New System.Drawing.Size(16, 16) Me.Label7.TabIndex = 20 Me.Label7.Text = "6" ' 'Label6 ' Me.Label6.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(204, Byte)) Me.Label6.Location = New System.Drawing.Point(168, 56) Me.Label6.Name = "Label6" Me.Label6.Size = New System.Drawing.Size(16, 16) Me.Label6.TabIndex = 19 Me.Label6.Text = "5" ' 'Label5 ' Me.Label5.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(204, Byte)) Me.Label5.Location = New System.Drawing.Point(168, 24) Me.Label5.Name = "Label5" Me.Label5.Size = New System.Drawing.Size(16, 24) Me.Label5.TabIndex = 18 Me.Label5.Text = "4" ' 'Label4 ' Me.Label4.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(204, Byte)) Me.Label4.Location = New System.Drawing.Point(8, 96) Me.Label4.Name = "Label4" Me.Label4.Size = New System.Drawing.Size(16, 16) Me.Label4.TabIndex = 17 Me.Label4.Text = "3" ' 'Label3 ' Me.Label3.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(204, Byte)) Me.Label3.Location = New System.Drawing.Point(8, 56) Me.Label3.Name = "Label3" Me.Label3.Size = New System.Drawing.Size(16, 16) Me.Label3.TabIndex = 16 Me.Label3.Text = "2" ' 'Label2 ' Me.Label2.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(204, Byte)) Me.Label2.Location = New System.Drawing.Point(8, 24) Me.Label2.Name = "Label2" Me.Label2.Size = New System.Drawing.Size(16, 16) Me.Label2.TabIndex = 15 Me.Label2.Text = "1" ' 'Button6 ' Me.Button6.AccessibleDescription = "Create Directory button" Me.Button6.AccessibleName = "Create Directory button" Me.Button6.BackColor = System.Drawing.SystemColors.Window Me.Button6.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.Button6.ImeMode = System.Windows.Forms.ImeMode.NoControl Me.Button6.Location = New System.Drawing.Point(184, 88) Me.Button6.Name = "Button6" Me.Button6.Size = New System.Drawing.Size(136, 22) Me.Button6.TabIndex = 14 Me.Button6.Text = "Delete folder" ' 'Button5 ' Me.Button5.AccessibleDescription = "Create Directory button" Me.Button5.AccessibleName = "Create Directory button" Me.Button5.BackColor = System.Drawing.SystemColors.Window Me.Button5.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.Button5.ImeMode = System.Windows.Forms.ImeMode.NoControl Me.Button5.Location = New System.Drawing.Point(184, 56) Me.Button5.Name = "Button5" Me.Button5.Size = New System.Drawing.Size(136, 22) Me.Button5.TabIndex = 13 Me.Button5.Text = "Delete Text Document" ' 'Button4 ' Me.Button4.AccessibleDescription = "Create Directory button" Me.Button4.AccessibleName = "Create Directory button" Me.Button4.BackColor = System.Drawing.SystemColors.Window Me.Button4.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.Button4.ImeMode = System.Windows.Forms.ImeMode.NoControl Me.Button4.Location = New System.Drawing.Point(184, 24) Me.Button4.Name = "Button4" Me.Button4.Size = New System.Drawing.Size(136, 22) Me.Button4.TabIndex = 12 Me.Button4.Text = "Open Text Document" ' 'Button3 ' Me.Button3.AccessibleDescription = "Create Directory button" Me.Button3.AccessibleName = "Create Directory button" Me.Button3.BackColor = System.Drawing.SystemColors.Window Me.Button3.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.Button3.ImeMode = System.Windows.Forms.ImeMode.NoControl Me.Button3.Location = New System.Drawing.Point(24, 88) Me.Button3.Name = "Button3" Me.Button3.Size = New System.Drawing.Size(136, 22) Me.Button3.TabIndex = 11 Me.Button3.Text = "Open folder" ' 'Button2 ' Me.Button2.AccessibleDescription = "Create Directory button" Me.Button2.AccessibleName = "Create Directory button" Me.Button2.BackColor = System.Drawing.SystemColors.Window Me.Button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.Button2.ImeMode = System.Windows.Forms.ImeMode.NoControl Me.Button2.Location = New System.Drawing.Point(24, 56) Me.Button2.Name = "Button2" Me.Button2.Size = New System.Drawing.Size(136, 22) Me.Button2.TabIndex = 10 Me.Button2.Text = "Create Text Document" ' 'Form1 ' Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.BackColor = System.Drawing.Color.CadetBlue Me.ClientSize = New System.Drawing.Size(530, 136) Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.GroupBox1, Me.DirectoryGroupBox}) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow Me.Name = "Form1" Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "Create folder by Filip Spasojevic " & _ " E-mail: filip001@eunet.yu" Me.DirectoryGroupBox.ResumeLayout(False) Me.GroupBox1.ResumeLayout(False) Me.ResumeLayout(False) End Sub #End Region Private Sub btnCreateDirectory_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateDirectory.Click Dim security As New Win32API.SECURITY_ATTRIBUTES() If Win32API.CreateDirectory(txtDirectory.Text, security) Then txtFunctionOutput.Text = "Folder je napravljen." Else txtFunctionOutput.Text = "Folder nije napravljen." End If End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim fil As System.IO.Directory fil.CreateDirectory("c:\Filip Spasojevic") End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim fil As New System.IO.StreamWriter("c:\Filip Spasojevic\Filip Spasojevic.txt") fil.WriteLine("Filip Spasojevic play tennis every day") fil.Close() End Sub Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click Dim startInfo As New ProcessStartInfo("c:\Filip Spasojevic") startInfo.UseShellExecute = True Process.Start(startInfo) End Sub Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click Dim startInfo As New ProcessStartInfo("c:\Filip Spasojevic\Filip Spasojevic.txt") startInfo.UseShellExecute = True Process.Start(startInfo) End Sub Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click Dim fil As System.IO.File fil.Delete("c:\Filip Spasojevic\Filip Spasojevic.txt") End Sub Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click Dim fil As System.IO.Directory fil.Delete("c:\Filip Spasojevic") End Sub End Class
Imports System.Data.SqlClient Public Class DeduccionDAO Inherits DBConnection Public Function Generar(ByVal deduccion As Deduccion) As Boolean Dim command As New SqlCommand("GenerarDeduccion", connection) command.CommandType = CommandType.StoredProcedure command.Parameters.AddWithValue("@Desc_Deducc", deduccion.Descripcion) command.Parameters.AddWithValue("@Cant_Fija", deduccion.CantidadFija) command.Parameters.AddWithValue("@Cant_Porcent", deduccion.CantidadPorcentual) command.Parameters.AddWithValue("@ID_Empleado", deduccion.IDEmpleado) command.Parameters.AddWithValue("@Fecha", deduccion.Fecha) connection.Open() command.ExecuteNonQuery() connection.Close() Return True End Function Public Function VerTodas() As List(Of Deduccion) Dim command As New SqlCommand("VerDeducciones", connection) command.CommandType = CommandType.StoredProcedure Dim deducciones As New List(Of Deduccion) connection.Open() Dim reader As SqlDataReader reader = command.ExecuteReader() While (reader.Read()) Dim deduccion As New Deduccion With { .ID = reader.GetInt32(0), .Descripcion = reader.GetString(1), .CantidadFija = reader.GetDouble(2), .CantidadPorcentual = reader.GetDouble(3), .IDEmpleado = reader.GetInt32(4), .Fecha = reader.GetDateTime(5) } deducciones.Add(deduccion) End While reader.Close() connection.Close() Return deducciones End Function Public Function VerDeEmpleado(ByVal idEmpleado As Integer, ByVal inicio As Date, ByVal fin As Date) As List(Of Deduccion) Dim command As New SqlCommand("VerDeduccionesEmpleado", connection) command.CommandType = CommandType.StoredProcedure command.Parameters.AddWithValue("@ID_Empleado", idEmpleado) command.Parameters.AddWithValue("@From", inicio) command.Parameters.AddWithValue("@To", fin) Dim deducciones As New List(Of Deduccion) connection.Open() Dim reader As SqlDataReader reader = command.ExecuteReader() While (reader.Read()) Dim deduccion As New Deduccion With { .ID = reader.GetInt32(0), .Descripcion = reader.GetString(1), .CantidadFija = reader.GetDouble(2), .CantidadPorcentual = reader.GetDouble(3), .IDEmpleado = idEmpleado, .Fecha = reader.GetDateTime(4) } deducciones.Add(deduccion) End While reader.Close() connection.Close() Return deducciones End Function Public Function VerDeNomina(ByVal idNomina As Integer) As List(Of Deduccion) Dim command As New SqlCommand("VerDeduccionesNomina", connection) command.CommandType = CommandType.StoredProcedure command.Parameters.AddWithValue("@ID_Nomina", idNomina) Dim deducciones As New List(Of Deduccion) connection.Open() Dim reader As SqlDataReader reader = command.ExecuteReader() While (reader.Read()) Dim deduccion As New Deduccion With { .ID = reader.GetInt32(0), .Descripcion = reader.GetString(1), .CantidadFija = reader.GetDouble(2), .CantidadPorcentual = reader.GetDouble(3), .Fecha = reader.GetDateTime(4) } deducciones.Add(deduccion) End While reader.Close() connection.Close() Return deducciones End Function End Class
Imports System.Web Imports System.Web.Services Imports System.Web.Services.Protocols Imports System.Web.Script.Serialization Imports System.Data Imports System.Web.Script.Services ' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. ' <System.Web.Script.Services.ScriptService()> _ <WebService(Namespace:="http://tempuri.org/")> _ <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ <ScriptService()> _ Public Class PopulatecompanyBusinessAddress Inherits Aptify.Framework.Web.eBusiness.BaseWebService <WebMethod()> _ <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=False, XmlSerializeString:=False)> _ Public Function PopulateCompanyBusinessAddress(ByVal Company As String) As String Dim js As JavaScriptSerializer = New JavaScriptSerializer() Dim sSQL As String = String.Empty Dim dt As New DataTable Dim param(0) As IDataParameter Dim BusinessAddress As New List(Of BusinessAddress)() Dim strCompany As String() = Company.Split("\") Dim sCompanyName As String = strCompany(0) If Not String.IsNullOrEmpty(Company.Trim()) Then sSQL = Database & "..spGetBusinessAddress__c" param(0) = DataAction.GetDataParameter("@Company", SqlDbType.NVarChar, sCompanyName) dt = DataAction.GetDataTableParametrized(sSQL, Data.CommandType.StoredProcedure, param) If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then For Each row As DataRow In dt.Rows Dim Address As New List(Of BusinessAddress)() From { _ New BusinessAddress() With { _ .AddressLine1 = Convert.ToString(row("AddressLine1")), .AddressLine2 = Convert.ToString(row("AddressLine2")), .AddressLine3 = Convert.ToString(row("AddressLine3")), .AddressLine4 = Convert.ToString(row("AddressLine4")), .City = Convert.ToString(row("City")), .State = Convert.ToString(row("State")), .ZipCode = Convert.ToString(row("ZipCode")), .CountryCodeID = Convert.ToString(row("CountryCodeID")), .MainAreaCode = Convert.ToString(row("MainAreaCode")), .MainPhone = Convert.ToString(row("MainPhone")), .MainFaxAreaCode = Convert.ToString(row("MainFaxAreaCode")), .MainFaxNumber = Convert.ToString(row("MainFaxNumber"))}} BusinessAddress = Address Next End If End If Return js.Serialize(BusinessAddress) End Function <WebMethod()> _ <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=False, XmlSerializeString:=False)> _ Public Function PopulateCompanyStreetAddress(ByVal CompanyID As String) As String Dim js As JavaScriptSerializer = New JavaScriptSerializer() Dim sSQL As String = String.Empty Dim dt As New DataTable Dim param(0) As IDataParameter Dim BusinessAddress As New List(Of BusinessAddress)() 'Dim strCompany As String() = CompanyID.Split("\") Dim sCompanyName As Integer = CompanyID If IsNumeric(CompanyID) Then sSQL = Database & "..spGetCompanyStreetAddress__c" param(0) = DataAction.GetDataParameter("@CompanyID", SqlDbType.BigInt, sCompanyName) dt = DataAction.GetDataTableParametrized(sSQL, Data.CommandType.StoredProcedure, param) If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then For Each row As DataRow In dt.Rows Dim Address As New List(Of BusinessAddress)() From { _ New BusinessAddress() With { _ .AddressLine1 = Convert.ToString(row("AddressLine1")), .AddressLine2 = Convert.ToString(row("AddressLine2")), .AddressLine3 = Convert.ToString(row("AddressLine3")), .AddressLine4 = Convert.ToString(row("AddressLine4")), .City = Convert.ToString(row("City")), .State = Convert.ToString(row("State")), .ZipCode = Convert.ToString(row("ZipCode")), .CountryCodeID = Convert.ToString(row("CountryCodeID")), .MainAreaCode = Convert.ToString(row("MainAreaCode")), .MainPhone = Convert.ToString(row("MainPhone")), .MainFaxAreaCode = Convert.ToString(row("MainFaxAreaCode")), .MainFaxNumber = Convert.ToString(row("MainFaxNumber")), .County = Convert.ToString(row("County"))}} BusinessAddress = Address Next End If End If Return js.Serialize(BusinessAddress) End Function End Class Public Class BusinessAddress Public AddressLine1 As String Public AddressLine2 As String Public AddressLine3 As String Public AddressLine4 As String Public CountryCodeID As String Public City As String Public State As String Public ZipCode As String Public MainAreaCode As String Public MainPhone As String Public MainFaxAreaCode As String Public MainFaxNumber As String Public County As String End Class
Option Explicit On Option Strict On Imports System Public Interface ICustomerManager Function getCustomer(ByVal id As Integer) As Customer Function validate(ByVal cust As Customer) As ValidationResult End Interface <Serializable()> _ Public Class ValidationResult Public Sub New(ByVal ok As Boolean, ByVal msg As String) Console.WriteLine("ValidationResult.ctor: Object created") Me.Ok = ok Me.ValidationMessage = msg End Sub 'New Public Ok As Boolean Public ValidationMessage As String End Class <Serializable()> _ Public Class Customer Public FirstName As String Public LastName As String Public DateOfBirth As DateTime Public Sub New() Console.WriteLine("Customer.constructor: Object created") End Sub 'New Public Function getAge() As Integer Console.WriteLine("Customer.getAge(): Calculating age of {0}, " & _ "born on {1}.", FirstName, DateOfBirth.ToShortDateString()) Dim tmp As TimeSpan = DateTime.Today.Subtract(DateOfBirth) Return tmp.Days \ 365 ' rough estimation End Function End Class
Public Class frmOrderingSystem Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. Friend WithEvents grpFoodMenu As System.Windows.Forms.GroupBox Friend WithEvents grpDiscount As System.Windows.Forms.GroupBox Friend WithEvents rdoNoDiscount As System.Windows.Forms.RadioButton Friend WithEvents rdo5Discount As System.Windows.Forms.RadioButton Friend WithEvents rdo10Discount As System.Windows.Forms.RadioButton Friend WithEvents rdo20Discount As System.Windows.Forms.RadioButton Friend WithEvents txtHamburger As System.Windows.Forms.TextBox Friend WithEvents txtFrenchFries As System.Windows.Forms.TextBox Friend WithEvents txtSundae As System.Windows.Forms.TextBox Friend WithEvents txtFriedChicken As System.Windows.Forms.TextBox Friend WithEvents chkHamburger As System.Windows.Forms.CheckBox Friend WithEvents chkFrenchFries As System.Windows.Forms.CheckBox Friend WithEvents chkSundae As System.Windows.Forms.CheckBox Friend WithEvents chkSpaghetti As System.Windows.Forms.CheckBox Friend WithEvents chkFriedChicken As System.Windows.Forms.CheckBox Friend WithEvents cmdCompute As System.Windows.Forms.Button Friend WithEvents cmdReset As System.Windows.Forms.Button Friend WithEvents cmdExit As System.Windows.Forms.Button Friend WithEvents txtTotalAmt As System.Windows.Forms.TextBox Friend WithEvents txtSpaghetti As System.Windows.Forms.TextBox Friend WithEvents lblTotalAmt As System.Windows.Forms.Label <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Me.grpFoodMenu = New System.Windows.Forms.GroupBox Me.txtFriedChicken = New System.Windows.Forms.TextBox Me.txtSpaghetti = New System.Windows.Forms.TextBox Me.txtSundae = New System.Windows.Forms.TextBox Me.txtFrenchFries = New System.Windows.Forms.TextBox Me.txtHamburger = New System.Windows.Forms.TextBox Me.chkFriedChicken = New System.Windows.Forms.CheckBox Me.chkSpaghetti = New System.Windows.Forms.CheckBox Me.chkSundae = New System.Windows.Forms.CheckBox Me.chkFrenchFries = New System.Windows.Forms.CheckBox Me.chkHamburger = New System.Windows.Forms.CheckBox Me.grpDiscount = New System.Windows.Forms.GroupBox Me.rdo20Discount = New System.Windows.Forms.RadioButton Me.rdo10Discount = New System.Windows.Forms.RadioButton Me.rdo5Discount = New System.Windows.Forms.RadioButton Me.rdoNoDiscount = New System.Windows.Forms.RadioButton Me.lblTotalAmt = New System.Windows.Forms.Label Me.txtTotalAmt = New System.Windows.Forms.TextBox Me.cmdCompute = New System.Windows.Forms.Button Me.cmdReset = New System.Windows.Forms.Button Me.cmdExit = New System.Windows.Forms.Button Me.grpFoodMenu.SuspendLayout() Me.grpDiscount.SuspendLayout() Me.SuspendLayout() ' 'grpFoodMenu ' Me.grpFoodMenu.Controls.Add(Me.txtFriedChicken) Me.grpFoodMenu.Controls.Add(Me.txtSpaghetti) Me.grpFoodMenu.Controls.Add(Me.txtSundae) Me.grpFoodMenu.Controls.Add(Me.txtFrenchFries) Me.grpFoodMenu.Controls.Add(Me.txtHamburger) Me.grpFoodMenu.Controls.Add(Me.chkFriedChicken) Me.grpFoodMenu.Controls.Add(Me.chkSpaghetti) Me.grpFoodMenu.Controls.Add(Me.chkSundae) Me.grpFoodMenu.Controls.Add(Me.chkFrenchFries) Me.grpFoodMenu.Controls.Add(Me.chkHamburger) Me.grpFoodMenu.Font = New System.Drawing.Font("Arial Narrow", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.grpFoodMenu.Location = New System.Drawing.Point(8, 24) Me.grpFoodMenu.Name = "grpFoodMenu" Me.grpFoodMenu.Size = New System.Drawing.Size(280, 192) Me.grpFoodMenu.TabIndex = 0 Me.grpFoodMenu.TabStop = False Me.grpFoodMenu.Text = "Food Menu" ' 'txtFriedChicken ' Me.txtFriedChicken.Enabled = False Me.txtFriedChicken.Location = New System.Drawing.Point(184, 152) Me.txtFriedChicken.MaxLength = 5 Me.txtFriedChicken.Name = "txtFriedChicken" Me.txtFriedChicken.Size = New System.Drawing.Size(88, 22) Me.txtFriedChicken.TabIndex = 9 Me.txtFriedChicken.Text = "0" Me.txtFriedChicken.TextAlign = System.Windows.Forms.HorizontalAlignment.Right ' 'txtSpaghetti ' Me.txtSpaghetti.Enabled = False Me.txtSpaghetti.Location = New System.Drawing.Point(184, 120) Me.txtSpaghetti.MaxLength = 5 Me.txtSpaghetti.Name = "txtSpaghetti" Me.txtSpaghetti.Size = New System.Drawing.Size(88, 22) Me.txtSpaghetti.TabIndex = 8 Me.txtSpaghetti.Text = "0" Me.txtSpaghetti.TextAlign = System.Windows.Forms.HorizontalAlignment.Right ' 'txtSundae ' Me.txtSundae.Enabled = False Me.txtSundae.Location = New System.Drawing.Point(184, 88) Me.txtSundae.MaxLength = 5 Me.txtSundae.Name = "txtSundae" Me.txtSundae.Size = New System.Drawing.Size(88, 22) Me.txtSundae.TabIndex = 7 Me.txtSundae.Text = "0" Me.txtSundae.TextAlign = System.Windows.Forms.HorizontalAlignment.Right ' 'txtFrenchFries ' Me.txtFrenchFries.Enabled = False Me.txtFrenchFries.Location = New System.Drawing.Point(184, 56) Me.txtFrenchFries.MaxLength = 5 Me.txtFrenchFries.Name = "txtFrenchFries" Me.txtFrenchFries.Size = New System.Drawing.Size(88, 22) Me.txtFrenchFries.TabIndex = 6 Me.txtFrenchFries.Text = "0" Me.txtFrenchFries.TextAlign = System.Windows.Forms.HorizontalAlignment.Right ' 'txtHamburger ' Me.txtHamburger.Enabled = False Me.txtHamburger.Location = New System.Drawing.Point(184, 24) Me.txtHamburger.MaxLength = 5 Me.txtHamburger.Name = "txtHamburger" Me.txtHamburger.Size = New System.Drawing.Size(88, 22) Me.txtHamburger.TabIndex = 5 Me.txtHamburger.Text = "0" Me.txtHamburger.TextAlign = System.Windows.Forms.HorizontalAlignment.Right ' 'chkFriedChicken ' Me.chkFriedChicken.Font = New System.Drawing.Font("Arial Narrow", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.chkFriedChicken.Location = New System.Drawing.Point(8, 152) Me.chkFriedChicken.Name = "chkFriedChicken" Me.chkFriedChicken.Size = New System.Drawing.Size(168, 24) Me.chkFriedChicken.TabIndex = 4 Me.chkFriedChicken.Text = "Fried Chicken (Php 45.00)" ' 'chkSpaghetti ' Me.chkSpaghetti.Font = New System.Drawing.Font("Arial Narrow", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.chkSpaghetti.Location = New System.Drawing.Point(8, 120) Me.chkSpaghetti.Name = "chkSpaghetti" Me.chkSpaghetti.Size = New System.Drawing.Size(168, 24) Me.chkSpaghetti.TabIndex = 3 Me.chkSpaghetti.Text = "Spaghetti (Php 38.50)" ' 'chkSundae ' Me.chkSundae.Font = New System.Drawing.Font("Arial Narrow", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.chkSundae.Location = New System.Drawing.Point(8, 88) Me.chkSundae.Name = "chkSundae" Me.chkSundae.Size = New System.Drawing.Size(168, 24) Me.chkSundae.TabIndex = 2 Me.chkSundae.Text = "Sundae (Php 18.25)" ' 'chkFrenchFries ' Me.chkFrenchFries.Font = New System.Drawing.Font("Arial Narrow", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.chkFrenchFries.Location = New System.Drawing.Point(8, 56) Me.chkFrenchFries.Name = "chkFrenchFries" Me.chkFrenchFries.Size = New System.Drawing.Size(168, 24) Me.chkFrenchFries.TabIndex = 1 Me.chkFrenchFries.Text = "French Fries (Php 26.75)" ' 'chkHamburger ' Me.chkHamburger.Font = New System.Drawing.Font("Arial Narrow", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.chkHamburger.Location = New System.Drawing.Point(8, 24) Me.chkHamburger.Name = "chkHamburger" Me.chkHamburger.Size = New System.Drawing.Size(168, 24) Me.chkHamburger.TabIndex = 0 Me.chkHamburger.Text = "Hamburger (Php 20.00)" ' 'grpDiscount ' Me.grpDiscount.Controls.Add(Me.rdo20Discount) Me.grpDiscount.Controls.Add(Me.rdo10Discount) Me.grpDiscount.Controls.Add(Me.rdo5Discount) Me.grpDiscount.Controls.Add(Me.rdoNoDiscount) Me.grpDiscount.Font = New System.Drawing.Font("Arial Narrow", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.grpDiscount.Location = New System.Drawing.Point(296, 48) Me.grpDiscount.Name = "grpDiscount" Me.grpDiscount.Size = New System.Drawing.Size(128, 128) Me.grpDiscount.TabIndex = 1 Me.grpDiscount.TabStop = False Me.grpDiscount.Text = "Discount" ' 'rdo20Discount ' Me.rdo20Discount.Font = New System.Drawing.Font("Arial Narrow", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.rdo20Discount.Location = New System.Drawing.Point(8, 88) Me.rdo20Discount.Name = "rdo20Discount" Me.rdo20Discount.TabIndex = 13 Me.rdo20Discount.Text = "20% Discount" ' 'rdo10Discount ' Me.rdo10Discount.Font = New System.Drawing.Font("Arial Narrow", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.rdo10Discount.Location = New System.Drawing.Point(8, 64) Me.rdo10Discount.Name = "rdo10Discount" Me.rdo10Discount.TabIndex = 12 Me.rdo10Discount.Text = "10% Discount" ' 'rdo5Discount ' Me.rdo5Discount.Font = New System.Drawing.Font("Arial Narrow", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.rdo5Discount.Location = New System.Drawing.Point(8, 40) Me.rdo5Discount.Name = "rdo5Discount" Me.rdo5Discount.TabIndex = 11 Me.rdo5Discount.Text = "5% Discount" ' 'rdoNoDiscount ' Me.rdoNoDiscount.Checked = True Me.rdoNoDiscount.Font = New System.Drawing.Font("Arial Narrow", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.rdoNoDiscount.Location = New System.Drawing.Point(8, 16) Me.rdoNoDiscount.Name = "rdoNoDiscount" Me.rdoNoDiscount.TabIndex = 10 Me.rdoNoDiscount.TabStop = True Me.rdoNoDiscount.Text = "No Discount" ' 'lblTotalAmt ' Me.lblTotalAmt.Font = New System.Drawing.Font("Arial Narrow", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblTotalAmt.Location = New System.Drawing.Point(32, 232) Me.lblTotalAmt.Name = "lblTotalAmt" Me.lblTotalAmt.Size = New System.Drawing.Size(128, 24) Me.lblTotalAmt.TabIndex = 2 Me.lblTotalAmt.Text = "Total Amount Due Php:" ' 'txtTotalAmt ' Me.txtTotalAmt.Font = New System.Drawing.Font("Arial Narrow", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.txtTotalAmt.Location = New System.Drawing.Point(160, 232) Me.txtTotalAmt.Name = "txtTotalAmt" Me.txtTotalAmt.ReadOnly = True Me.txtTotalAmt.Size = New System.Drawing.Size(248, 22) Me.txtTotalAmt.TabIndex = 3 Me.txtTotalAmt.Text = "0" Me.txtTotalAmt.TextAlign = System.Windows.Forms.HorizontalAlignment.Right ' 'cmdCompute ' Me.cmdCompute.BackColor = System.Drawing.Color.LightGray Me.cmdCompute.Font = New System.Drawing.Font("Transformers Movie", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.cmdCompute.Location = New System.Drawing.Point(48, 272) Me.cmdCompute.Name = "cmdCompute" Me.cmdCompute.Size = New System.Drawing.Size(88, 24) Me.cmdCompute.TabIndex = 14 Me.cmdCompute.Text = "&COMPUTE" ' 'cmdReset ' Me.cmdReset.BackColor = System.Drawing.Color.LightGray Me.cmdReset.Font = New System.Drawing.Font("Transformers Movie", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.cmdReset.Location = New System.Drawing.Point(160, 272) Me.cmdReset.Name = "cmdReset" Me.cmdReset.Size = New System.Drawing.Size(88, 24) Me.cmdReset.TabIndex = 15 Me.cmdReset.Text = "&RESET" ' 'cmdExit ' Me.cmdExit.BackColor = System.Drawing.Color.LightGray Me.cmdExit.Font = New System.Drawing.Font("Transformers Movie", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.cmdExit.Location = New System.Drawing.Point(272, 272) Me.cmdExit.Name = "cmdExit" Me.cmdExit.Size = New System.Drawing.Size(88, 24) Me.cmdExit.TabIndex = 16 Me.cmdExit.Text = "E&XIT" ' 'frmOrderingSystem ' Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.BackColor = System.Drawing.Color.Orange Me.ClientSize = New System.Drawing.Size(432, 322) Me.Controls.Add(Me.cmdExit) Me.Controls.Add(Me.cmdReset) Me.Controls.Add(Me.cmdCompute) Me.Controls.Add(Me.txtTotalAmt) Me.Controls.Add(Me.lblTotalAmt) Me.Controls.Add(Me.grpDiscount) Me.Controls.Add(Me.grpFoodMenu) Me.MaximizeBox = False Me.MinimizeBox = False Me.Name = "frmOrderingSystem" Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "ORDERING SYSTEM" Me.grpFoodMenu.ResumeLayout(False) Me.grpDiscount.ResumeLayout(False) Me.ResumeLayout(False) End Sub #End Region Private Sub cmdCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCompute.Click Dim hamburger, frenchfries, sundae, spaghetti, friedchicken, totalamt, discount As Decimal If chkHamburger.Checked = True Then hamburger = Val(txtHamburger.Text) * 20.0 Else hamburger = 0 End If If chkFrenchFries.Checked = True Then frenchfries = Val(txtFrenchFries.Text) * 26.75 Else frenchfries = 0 End If If chkSundae.Checked = True Then sundae = Val(txtSundae.Text) * 18.25 Else sundae = 0 End If If chkSpaghetti.Checked = True Then spaghetti = Val(txtSpaghetti.Text) * 38.5 Else spaghetti = 0 End If If chkFriedChicken.Checked = True Then friedchicken = Val(txtFriedChicken.Text) * 45.0 Else friedchicken = 0 End If totalamt = hamburger + frenchfries + sundae + spaghetti + friedchicken If (rdoNoDiscount.Checked = True) Then discount = 0 ElseIf (rdo5Discount.Checked = True) Then discount = 0.05 ElseIf (rdo10Discount.Checked = True) Then discount = 0.1 ElseIf (rdo20Discount.Checked = True) Then discount = 0.2 End If totalamt -= (totalamt * discount) txtTotalAmt.Text = totalamt End Sub Private Sub cmdReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReset.Click chkHamburger.Checked = False chkFrenchFries.Checked = False chkSundae.Checked = False chkSpaghetti.Checked = False chkFriedChicken.Checked = False txtHamburger.Text = 0 txtHamburger.Enabled = False txtFrenchFries.Text = 0 txtFrenchFries.Enabled = False txtSundae.Text = 0 txtSundae.Enabled = False txtSpaghetti.Text = 0 txtSpaghetti.Enabled = False txtFriedChicken.Text = 0 txtFriedChicken.Enabled = False txtTotalAmt.Text = 0 rdoNoDiscount.Checked = True rdo5Discount.Checked = False rdo10Discount.Checked = False rdo20Discount.Checked = False End Sub Private Sub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click Dim reply As DialogResult reply = MsgBox("Are you sure you want to exit the Ordering System Program?", MsgBoxStyle.OKCancel + MsgBoxStyle.Question, "Ordering System Program") If reply = DialogResult.OK Then End End If End Sub Private Sub txtHamburger_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtHamburger.TextChanged If (IsNumeric(txtHamburger.Text) = True) Then Else txtHamburger.Clear() End If End Sub Private Sub txtFrenchFries_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtFrenchFries.TextChanged If (IsNumeric(txtFrenchFries.Text) = True) Then Else txtFrenchFries.Clear() End If End Sub Private Sub txtSundae_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSundae.TextChanged If (IsNumeric(txtSundae.Text) = True) Then Else txtSundae.Clear() End If End Sub Private Sub txtFriedChicken_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtFriedChicken.TextChanged If (IsNumeric(txtFriedChicken.Text) = True) Then Else txtFriedChicken.Clear() End If End Sub Private Sub txtSpaghetti_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSpaghetti.TextChanged If (IsNumeric(txtSpaghetti.Text) = True) Then Else txtSpaghetti.Clear() End If End Sub Private Sub chkHamburger_CheckStateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkHamburger.CheckStateChanged If (chkHamburger.CheckState = CheckState.Checked) Then txtHamburger.Enabled = True ElseIf (chkHamburger.CheckState = CheckState.Unchecked) Then txtHamburger.Enabled = False End If End Sub Private Sub chkFrenchFries_CheckStateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkFrenchFries.CheckStateChanged If (chkFrenchFries.CheckState = CheckState.Checked) Then txtFrenchFries.Enabled = True ElseIf (chkFrenchFries.CheckState = CheckState.Unchecked) Then txtFrenchFries.Enabled = False End If End Sub Private Sub chkFriedChicken_CheckStateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkFriedChicken.CheckStateChanged If (chkFriedChicken.CheckState = CheckState.Checked) Then txtFriedChicken.Enabled = True ElseIf (chkFriedChicken.CheckState = CheckState.Unchecked) Then txtFriedChicken.Enabled = False End If End Sub Private Sub chkSpaghetti_CheckStateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkSpaghetti.CheckStateChanged If (chkSpaghetti.CheckState = CheckState.Checked) Then txtSpaghetti.Enabled = True ElseIf (chkSpaghetti.CheckState = CheckState.Unchecked) Then txtSpaghetti.Enabled = False End If End Sub Private Sub chkSundae_CheckStateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkSundae.CheckStateChanged If (chkSundae.CheckState = CheckState.Checked) Then txtSundae.Enabled = True ElseIf (chkSundae.CheckState = CheckState.Unchecked) Then txtSundae.Enabled = False End If End Sub End Class
'--------------------------------------------------------------------------------------------------- ' copyright file="OrderLine.vb" company="CitrusLime Ltd" ' Copyright (c) CitrusLime Ltd. All rights reserved. ' copyright '--------------------------------------------------------------------------------------------------- '''------------------------------------------------------------------------------------------------- ''' <summary>A customer order line.</summary> '''------------------------------------------------------------------------------------------------- Public Class OrderLine '''------------------------------------------------------------------------------------------------- ''' <summary>Gets or sets the cost.</summary> ''' <value>The cost.</value> '''------------------------------------------------------------------------------------------------- Public Property Cost As Decimal '''------------------------------------------------------------------------------------------------- ''' <summary>Gets or sets the UID.</summary> ''' <value>The UID.</value> '''------------------------------------------------------------------------------------------------- Public Property uid As Integer '''------------------------------------------------------------------------------------------------- ''' <summary>Gets or sets the identifier of the item.</summary> ''' <value>The identifier of the item.</value> '''------------------------------------------------------------------------------------------------- Public Property ItemID As Integer '''------------------------------------------------------------------------------------------------- ''' <summary>Gets or sets the full price.</summary> ''' <remarks>This is the normal price of the item, but may differ from what it was sold at.</remarks> ''' <value>The full price.</value> '''------------------------------------------------------------------------------------------------- Public Property FullPrice As Decimal '''------------------------------------------------------------------------------------------------- ''' <summary>Gets or sets the price.</summary> ''' <value>The price.</value> '''------------------------------------------------------------------------------------------------- Public Property Price As Decimal '''------------------------------------------------------------------------------------------------- ''' <summary>Gets or sets the quantity on order.</summary> ''' <value>The quantity on order.</value> '''------------------------------------------------------------------------------------------------- Public Property QuantityOnOrder As Decimal '''------------------------------------------------------------------------------------------------- ''' <summary>Gets or sets the identifier of the sales rep.</summary> ''' <value>The identifier of the sales rep.</value> '''------------------------------------------------------------------------------------------------- Public Property SalesRepID As Integer '''------------------------------------------------------------------------------------------------- ''' <summary>Gets or sets the taxable amount.</summary> ''' <value>The taxable amount.</value> '''------------------------------------------------------------------------------------------------- Public Property Taxable As Integer '''------------------------------------------------------------------------------------------------- ''' <summary>Gets or sets the description.</summary> ''' <value>The description.</value> '''------------------------------------------------------------------------------------------------- Public Property Description As String '''------------------------------------------------------------------------------------------------- ''' <summary>Gets or sets the quantity returned.</summary> ''' <value>The quantity returned.</value> '''------------------------------------------------------------------------------------------------- Public Property QuantityRTD As Decimal '''------------------------------------------------------------------------------------------------- ''' <summary>Gets or sets the last updated date.</summary> ''' <value>The last updated date.</value> '''------------------------------------------------------------------------------------------------- Public Property LastUpdated As DateTime '''------------------------------------------------------------------------------------------------- ''' <summary>Gets or sets the comment.</summary> ''' <value>The comment.</value> '''------------------------------------------------------------------------------------------------- Public Property Comment As String End Class
Imports Excel = Microsoft.Office.Interop.Excel Public Module DataTableUtils '(注意)Excelシートの行、列のインデックスは1から始まる Private Const ROW_OFFSET As Integer = 2 'エクセルシートにデータを書き出す行番号 '(注意)Excelシートの行、列のインデックスは1から始まる Private Const COLUMN_OFFSET As Integer = 1 'エクセルシートにデータを書き出す列番号 '''<summary> '''ハッシュテーブルをエクセルファイルから取得します ''' Hashtable:key=SheetName,value=DataTable '''</summary> Public Function LoadDataSetFromExcel(ByVal filePath As String, Optional ByRef ds As DataSet = Nothing) As DataSet If IsNothing(ds) Then ds = New DataSet End If Dim xlsApplication As New Excel.Application Dim xlsBook As Excel.Workbook = Nothing Dim xlsSheets As Excel.Sheets = Nothing Dim xlsSheet As Excel.Worksheet = Nothing Dim xlsRange As Excel.Range = Nothing xlsApplication.DisplayAlerts = False '保存時の確認ダイアログを表示しない xlsBook = xlsApplication.Workbooks.Open(filePath) Dim sheetList As New List(Of String) Try For Each sheet As Excel.Worksheet In xlsBook.Sheets sheetList.Add(sheet.Name) Next xlsBook.Close(False) xlsApplication.Quit() Catch ex As Exception Console.WriteLine(ex.Message & vbCrLf & ex.StackTrace) Finally 'エクセル関係のオブジェクトは必ず解放すること ReleaseComObject(DirectCast(xlsRange, Object)) ReleaseComObject(DirectCast(xlsSheet, Object)) ReleaseComObject(DirectCast(xlsSheets, Object)) ReleaseComObject(DirectCast(xlsBook, Object)) ReleaseComObject(DirectCast(xlsApplication, Object)) End Try For Each sheetName As String In sheetList Dim dt As DataTable = getDataTableFromExcelSheet(filePath, sheetName) dt.TableName = sheetName ds.Tables.Add(dt) Next Return ds End Function '''<summary> '''ハッシュテーブルをエクセルファイルから取得します ''' Hashtable:key=SheetName,value=DataTable '''</summary> Public Function LoadHashTableFromExcel(ByVal filePath As String, Optional ByRef ht As Dictionary(Of String, DataTable) = Nothing) As Dictionary(Of String, DataTable) If IsNothing(ht) Then ht = New Dictionary(Of String, DataTable) End If Dim xlsApplication As New Excel.Application Dim xlsBook As Excel.Workbook = Nothing Dim xlsSheets As Excel.Sheets = Nothing Dim xlsSheet As Excel.Worksheet = Nothing Dim xlsRange As Excel.Range = Nothing xlsApplication.DisplayAlerts = False '保存時の確認ダイアログを表示しない xlsBook = xlsApplication.Workbooks.Open(filePath) Dim sheetList As New List(Of String) Try For Each sheet As Excel.Worksheet In xlsBook.Sheets sheetList.Add(sheet.Name) Next xlsBook.Close(False) xlsApplication.Quit() Catch ex As Exception Console.WriteLine(ex.Message & vbCrLf & ex.StackTrace) Finally 'エクセル関係のオブジェクトは必ず解放すること ReleaseComObject(DirectCast(xlsRange, Object)) ReleaseComObject(DirectCast(xlsSheet, Object)) ReleaseComObject(DirectCast(xlsSheets, Object)) ReleaseComObject(DirectCast(xlsBook, Object)) ReleaseComObject(DirectCast(xlsApplication, Object)) End Try For Each sheetName As String In sheetList Dim dt As DataTable = getDataTableFromExcelSheet(filePath, sheetName) ht.Add(sheetName, dt) Next Return ht End Function Private Function getDataTableFromExcelSheet(ByVal filePath As String, ByVal sheetName As String) As DataTable Dim Con As New OleDb.OleDbConnection Dim Command As New OleDb.OleDbCommand() Dim oDataTable1 As DataTable = New DataTable Dim ConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0; " & "Data Source=" & filePath & ";" & "Extended Properties=""Excel 12.0;HDR=YES;""" '条件を指定してデータを取得したい場合 Dim where As String = "" Try Dim oDataAdapter As New OleDb.OleDbDataAdapter Con.ConnectionString = ConnectionString Command.Connection = Con Command.CommandText = "SELECT * FROM [" & sheetName & "$]" & where oDataAdapter.SelectCommand = Command oDataAdapter.Fill(oDataTable1) Catch ex As Exception 'エラー処理 Throw Finally If Not Command Is Nothing Then Command.Dispose() End If If Not Con Is Nothing Then Con.Close() Con.Dispose() End If End Try Return oDataTable1 End Function '''<summary> '''DataSetをエクセルファイルに出力します '''</summary> Public Function CreateExcelFromDataSet(ByVal ds As DataSet, ByVal filePath As String) As Boolean If IO.File.Exists(filePath) Then IO.File.Delete(filePath) End If Dim xlsApplication As New Excel.Application Dim xlsBook As Excel.Workbook = Nothing Dim xlsSheets As Excel.Sheets = Nothing Dim xlsSheet As Excel.Worksheet = Nothing Dim xlsRange As Excel.Range = Nothing xlsApplication.DisplayAlerts = False '保存時の確認ダイアログを表示しない xlsBook = xlsApplication.Workbooks.Add() Dim tableNameList As New List(Of String) Try For Each table As DataTable In ds.Tables tableNameList.Add(table.TableName) Next tableNameList.Sort() tableNameList.Reverse() Dim dt As DataTable For Each tableName As String In tableNameList dt = ds.Tables(tableName) Dim sheetName As String = tableName 'ヘッダー名称のリスト Dim headers As List(Of String) = New List(Of String) For Each col As System.Data.DataColumn In dt.Columns headers.Add(col.ColumnName) Next xlsSheets = xlsBook.Worksheets '(注意)シートのインデックスは1から始まる xlsSheet = DirectCast(xlsSheets.Add, Excel.Worksheet) xlsSheet.Name = sheetName For i As Integer = 0 To headers.Count - 1 xlsRange = DirectCast(xlsSheet.Cells(1, i + 1), Excel.Range) xlsRange.Value = headers.Item(i) Next ' セルに値を設定する。 Dim sheetRowIndex As Integer = ROW_OFFSET For Each row As DataRow In dt.Rows Dim sheetColumnIndex As Integer = COLUMN_OFFSET For Each column As DataColumn In dt.Columns If Not row.IsNull(column) Then xlsRange = DirectCast(xlsSheet.Cells(sheetRowIndex, sheetColumnIndex), Excel.Range) If column.DataType.Name = "Integer" Or _ column.DataType.Name = "Int32" Or _ column.DataType.Name = "Decimal" Or _ column.DataType.Name = "Long" Or _ column.DataType.Name = "Double" Or _ column.DataType.Name = "Short" Then 'セルの書式を数値型に設定 xlsRange.NumberFormatLocal = "G/標準" ElseIf column.DataType.Name = "DateTime" Then xlsRange.NumberFormatLocal = "yyyy/m/d h:mm" Else 'セルの書式を文字列型に設定 xlsRange.NumberFormatLocal = "@" End If xlsRange.Value = row(column) ReleaseComObject(DirectCast(xlsRange, Object)) sheetColumnIndex += 1 End If Next sheetRowIndex += 1 Next Next xlsSheet = DirectCast(xlsSheets("Sheet1"), Excel.Worksheet) xlsSheet.Delete() ' 保存 xlsBook.Save() Return True Catch ex As Exception Return False Finally 'エクセル関係のオブジェクトは必ず解放すること ReleaseComObject(DirectCast(xlsRange, Object)) ReleaseComObject(DirectCast(xlsSheet, Object)) ReleaseComObject(DirectCast(xlsSheets, Object)) xlsBook.Close(False) ReleaseComObject(DirectCast(xlsBook, Object)) xlsApplication.Quit() ReleaseComObject(DirectCast(xlsApplication, Object)) End Try Return False End Function '''<summary> '''ハッシュテーブルをエクセルファイルに出力します ''' Hashtable:key=SheetName,value=DataTable '''</summary> Public Function CreateExcelFromHashTable(ByVal ht As Dictionary(Of String, DataTable), _ ByVal filePath As String) As Boolean If IO.File.Exists(filePath) Then IO.File.Delete(filePath) End If Dim xlsApplication As New Excel.Application Dim xlsBook As Excel.Workbook = Nothing Dim xlsSheets As Excel.Sheets = Nothing Dim xlsSheet As Excel.Worksheet = Nothing Dim xlsRange As Excel.Range = Nothing xlsApplication.DisplayAlerts = False '保存時の確認ダイアログを表示しない xlsBook = xlsApplication.Workbooks.Add() Dim tableNameList As New List(Of String) Try For Each sheetName As String In ht.Keys Dim dt As DataTable = DirectCast(ht(sheetName), DataTable) 'ヘッダー名称のリスト Dim headers As List(Of String) = New List(Of String) For Each col As System.Data.DataColumn In dt.Columns headers.Add(col.ColumnName) Next xlsSheets = xlsBook.Worksheets '(注意)シートのインデックスは1から始まる xlsSheet = DirectCast(xlsSheets.Add, Excel.Worksheet) xlsSheet.Name = sheetName For i As Integer = 0 To headers.Count - 1 xlsRange = DirectCast(xlsSheet.Cells(1, i + 1), Excel.Range) xlsRange.Value = headers.Item(i) Next ' セルに値を設定する。 Dim sheetRowIndex As Integer = ROW_OFFSET For Each row As DataRow In dt.Rows Dim sheetColumnIndex As Integer = COLUMN_OFFSET For Each column As DataColumn In dt.Columns If Not row.IsNull(column) Then xlsRange = DirectCast(xlsSheet.Cells(sheetRowIndex, sheetColumnIndex), Excel.Range) If column.DataType.Name = "Integer" Or _ column.DataType.Name = "Int32" Or _ column.DataType.Name = "Decimal" Or _ column.DataType.Name = "Long" Or _ column.DataType.Name = "Double" Or _ column.DataType.Name = "Short" Then 'セルの書式を数値型に設定 xlsRange.NumberFormatLocal = "G/標準" ElseIf column.DataType.Name = "DateTime" Then xlsRange.NumberFormatLocal = "yyyy/m/d h:mm" Else 'セルの書式を文字列型に設定 xlsRange.NumberFormatLocal = "@" End If xlsRange.Value = row(column) ReleaseComObject(DirectCast(xlsRange, Object)) sheetColumnIndex += 1 End If Next sheetRowIndex += 1 Next Next xlsSheet = DirectCast(xlsSheets("Sheet1"), Excel.Worksheet) xlsSheet.Delete() ' 保存 xlsBook.Save() Return True Catch ex As Exception Return False Finally 'エクセル関係のオブジェクトは必ず解放すること ReleaseComObject(DirectCast(xlsRange, Object)) ReleaseComObject(DirectCast(xlsSheet, Object)) ReleaseComObject(DirectCast(xlsSheets, Object)) xlsBook.Close(False) ReleaseComObject(DirectCast(xlsBook, Object)) xlsApplication.Quit() ReleaseComObject(DirectCast(xlsApplication, Object)) End Try 'IO.File.Move(tempFile, filePath) Return False End Function '''<summary> '''データセットをエクセルファイルに出力します '''</summary> Public Function CreateExcelFromDataSet(ByVal ds As DataSet, _ ByVal filePath As String, _ ByVal sheetName As String) As Boolean Dim xlsApplication As New Excel.Application Dim xlsBooks As Excel.Workbooks = Nothing Dim xlsBook As Excel.Workbook = Nothing Dim xlsSheets As Excel.Sheets = Nothing Dim xlsSheet As Excel.Worksheet = Nothing Dim xlsRange As Excel.Range = Nothing xlsApplication.DisplayAlerts = False '保存時の確認ダイアログを表示しない Try For Each dt As DataTable In ds.Tables 'ヘッダー名称のリスト Dim headers As List(Of String) = New List(Of String) For Each col As System.Data.DataColumn In dt.Columns headers.Add(col.ColumnName) Next xlsBooks = xlsApplication.Workbooks xlsBook = xlsBooks.Add xlsSheets = xlsBook.Worksheets '(注意)シートのインデックスは1から始まる If xlsSheets.Count = 1 Then xlsSheet = DirectCast(xlsSheets.Item(1), Excel.Worksheet) xlsSheet.Name = sheetName Else xlsSheet = DirectCast(xlsSheets.Add, Excel.Worksheet) xlsSheet.Name = sheetName End If For i As Integer = 0 To headers.Count - 1 xlsRange = DirectCast(xlsSheet.Cells(1, i + 1), Excel.Range) xlsRange.Value = headers.Item(i) Next ' セルに値を設定する。 Dim sheetRowIndex As Integer = ROW_OFFSET For Each row As DataRow In dt.Rows Dim sheetColumnIndex As Integer = COLUMN_OFFSET For Each column As DataColumn In dt.Columns If Not row.IsNull(column) Then xlsRange = DirectCast(xlsSheet.Cells(sheetRowIndex, sheetColumnIndex), Excel.Range) If column.DataType.Name = "Integer" Or _ column.DataType.Name = "Int32" Or _ column.DataType.Name = "Decimal" Or _ column.DataType.Name = "Long" Or _ column.DataType.Name = "Double" Or _ column.DataType.Name = "Short" Then 'セルの書式を数値型に設定 xlsRange.NumberFormatLocal = "G/標準" ElseIf column.DataType.Name = "DateTime" Then xlsRange.NumberFormatLocal = "yyyy/m/d h:mm" Else 'セルの書式を文字列型に設定 xlsRange.NumberFormatLocal = "@" End If xlsRange.Value = row(column) ReleaseComObject(DirectCast(xlsRange, Object)) sheetColumnIndex += 1 End If Next sheetRowIndex += 1 Next Next ' 保存 xlsBook.SaveAs(filePath) Return True Catch ex As Exception Return False Finally 'エクセル関係のオブジェクトは必ず解放すること ReleaseComObject(DirectCast(xlsRange, Object)) ReleaseComObject(DirectCast(xlsSheet, Object)) ReleaseComObject(DirectCast(xlsSheets, Object)) xlsBook.Close(False) ReleaseComObject(DirectCast(xlsBook, Object)) ReleaseComObject(DirectCast(xlsBooks, Object)) xlsApplication.Quit() ReleaseComObject(DirectCast(xlsApplication, Object)) End Try Return False End Function '''<summary> '''データテーブルをエクセルファイルに出力します '''</summary> Public Function CreateExcelFromDataTable(ByVal dt As DataTable, _ ByVal filePath As String, _ ByVal sheetName As String) As Boolean 'ヘッダー名称のリスト Dim headers As List(Of String) = New List(Of String) For Each col As System.Data.DataColumn In dt.Columns headers.Add(col.ColumnName) Next Dim xlsApplication As New Excel.Application Dim xlsBooks As Excel.Workbooks = Nothing Dim xlsBook As Excel.Workbook = Nothing Dim xlsSheets As Excel.Sheets = Nothing Dim xlsSheet As Excel.Worksheet = Nothing Dim xlsRange As Excel.Range = Nothing Try xlsApplication.DisplayAlerts = False '保存時の確認ダイアログを表示しない xlsBooks = xlsApplication.Workbooks xlsBook = xlsBooks.Add xlsSheets = xlsBook.Worksheets '(注意)シートのインデックスは1から始まる xlsSheet = DirectCast(xlsSheets.Item(1), Excel.Worksheet) xlsSheet.Name = sheetName For i As Integer = 0 To headers.Count - 1 xlsRange = DirectCast(xlsSheet.Cells(1, i + 1), Excel.Range) xlsRange.Value = headers.Item(i) Next ' セルに値を設定する。 Dim sheetRowIndex As Integer = ROW_OFFSET For Each row As DataRow In dt.Rows Dim sheetColumnIndex As Integer = COLUMN_OFFSET For Each column As DataColumn In dt.Columns If Not row.IsNull(column) Then xlsRange = DirectCast(xlsSheet.Cells(sheetRowIndex, sheetColumnIndex), Excel.Range) If column.DataType.Name = "Integer" Or _ column.DataType.Name = "Int32" Or _ column.DataType.Name = "Decimal" Or _ column.DataType.Name = "Long" Or _ column.DataType.Name = "Double" Or _ column.DataType.Name = "Short" Then 'セルの書式を数値型に設定 xlsRange.NumberFormatLocal = "G/標準" ElseIf column.DataType.Name = "DateTime" Then xlsRange.NumberFormatLocal = "yyyy/m/d h:mm" Else 'セルの書式を文字列型に設定 xlsRange.NumberFormatLocal = "@" End If xlsRange.Value = row(column) ReleaseComObject(DirectCast(xlsRange, Object)) sheetColumnIndex += 1 End If Next sheetRowIndex += 1 Next ' 保存 xlsBook.SaveAs(filePath) Return True Catch ex As Exception Return False Finally 'エクセル関係のオブジェクトは必ず解放すること ReleaseComObject(DirectCast(xlsRange, Object)) ReleaseComObject(DirectCast(xlsSheet, Object)) ReleaseComObject(DirectCast(xlsSheets, Object)) xlsBook.Close(False) ReleaseComObject(DirectCast(xlsBook, Object)) ReleaseComObject(DirectCast(xlsBooks, Object)) xlsApplication.Quit() ReleaseComObject(DirectCast(xlsApplication, Object)) End Try Return False End Function ''' <summary> ''' COMオブジェクトを開放します。 ''' </summary> Private Sub ReleaseComObject(ByRef target As Object) Try If Not target Is Nothing Then System.Runtime.InteropServices.Marshal.ReleaseComObject(target) End If Finally target = Nothing End Try End Sub End Module
'***************************************************** '* 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 SaBytesExtension <Extension()> Public Function IsValidImage(ByVal bytes As Byte()) As Boolean Try Using ms = New MemoryStream(bytes) Image.FromStream(ms) End Using Catch ex As ArgumentException Return False End Try Return True End Function <Extension()> Public Function ToImage(ByVal bytes As Byte()) As Image Dim img As Image Try Using ms = New MemoryStream(bytes) img = Image.FromStream(ms) End Using Catch ex As ArgumentException Return Nothing End Try Return img End Function <Extension()> Public Function TrimEnd(bytes As Byte(), bi As Integer) As Byte() Dim i As Integer = bytes.Length - 1 While bytes(i) = bi i = i - 1 End While Dim temp(i + 1) As Byte Array.Copy(bytes, temp, i + 1) Return temp End Function <Extension()> Public Function Cut(bytes As Byte(), startpos As Integer, length As Integer) As Byte() Dim temp(length) As Byte Array.Copy(bytes, startpos, temp, 0, length) Return temp End Function ''' <summary> ''' default input bytes is Int ''' </summary> ''' <param name="bytes"></param> ''' <returns></returns> <Extension()> Public Function BytesToStrings(bytes As Byte(), Optional isHex As Boolean = False) As String() Dim line As String Dim sb As List(Of String) = New List(Of String)() If isHex Then Dim newbytes = From b As Byte In bytes Select Convert.ToInt16(b, 16) line = Encoding.Default.GetString(newbytes) Else line = Encoding.Default.GetString(bytes) End If For Each s As String In line.Split(vbFormFeed) sb.Add(s) Next Return sb.ToArray() End Function ''' <summary> ''' String is Hex to Int ''' </summary> ''' <param name="bs"></param> ''' <returns></returns> <Extension()> Public Function BytesToStrings(bs As String) As String() Return StringToBytes(bs).BytesToStrings() End Function End Module End Namespace
Public Class CheckSearchReport Inherits GRNPrinting.PrintClassBase Private WithEvents previewDlg As PrintPreviewDialog Private chkList As ListView.ListViewItemCollection Private listIndex As Integer Private colGutter As Single = 10 Public Sub New() MyBase.New() Me.InitializeComponents() End Sub Private Sub InitializeComponents() Me.rptBody.DefaultFont = New Font("Courier New", 9) End Sub Public Sub PrintCheckList(ByVal list As ListView.ListViewItemCollection, Optional ByVal title As String = Nothing, Optional ByVal subTitle As String = Nothing) Me.chkList = list Dim params As New GRNPrinting.TextLineParams params.IsBoxed = False params.BoxPen = Pens.DodgerBlue params.TextFont = New Font("Times New Roman", 12, FontStyle.Bold) params.TextPen = Pens.Black params.Alignment = StringAlignment.Center params.LineAlignment = StringAlignment.Center If title <> Nothing Then Me.AddTitleTextLine(title, 0, params, True) End If If subTitle <> Nothing Then params.TextFont = New Font("Times New Roman", 10, FontStyle.Bold) Me.AddTitleTextLine(subTitle, 0, params, True) End If listIndex = 0 Dim previewDlg As New System.Windows.Forms.PrintDialog previewDlg.UseEXDialog = True previewDlg.Document = prtDoc 'previewDlg.WindowState = System.Windows.Forms.FormWindowState.Maximized AddHandler prtDoc.PrintPage, AddressOf Prtr_PrintSearchReport firstPass = True If previewDlg.ShowDialog() = DialogResult.OK Then previewDlg.Document.Print() End If ResetAllRecords() RemoveHandler prtDoc.PrintPage, AddressOf Prtr_PrintSearchReport End Sub Private Sub Prtr_PrintSearchReport(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) e.PageSettings.Margins.Left = 50 e.PageSettings.Margins.Right = 50 Dim xPos As Single = e.PageSettings.Margins.Left Dim yPos As Single = e.MarginBounds.Top - (rptBody.DefaultFont.GetHeight(e.Graphics) / 2) Dim lineHeight As Single = rptBody.DefaultFont.GetHeight(e.Graphics) Dim minColWidth As Single = 350 Dim colCount As Integer = CInt((e.PageSettings.Bounds.Width - e.PageSettings.Margins.Right - e.PageSettings.Margins.Left) / minColWidth) Dim colWidth As Single = CSng(((e.PageSettings.Bounds.Width - e.PageSettings.Margins.Right - e.PageSettings.Margins.Left) / colCount) - colGutter) columns.Clear() For i As Integer = 0 To colCount - 1 CreateColumn(i + 1, CInt(e.PageSettings.Margins.Left + ((colWidth + colGutter) * i)), CInt(colWidth)) Next Dim boxHght As Single = 3 * lineHeight Dim rect As New RectangleF(xPos, yPos, e.PageSettings.Margins.Right - xPos, boxHght) DrawTextBlockRecord(Me.rptTitle, e) yPos = Me.rptTitle.Rect.Bottom + Me.rptTitle.DefaultFont.GetHeight(e.Graphics) Dim prtRect As New Rectangle(CInt(xPos), CInt(yPos), CInt(colWidth), CInt(colWidth / 2)) 'Dim lstItem As ListViewItem Dim colIndex As Integer = 1 For i As Integer = listIndex To chkList.Count - 1 'For Each lstItem In chkList Dim chk As ChecksClass = CType(chkList(i).Tag, ChecksClass) Dim prtText As String = chk.ImageFullPath.Substring(chk.ImageFullPath.LastIndexOf("\") - 6, 6) + " " + chk.Text Dim chkPrtImage As New GRNPrinting.Image2PrintClass(New CheckImageClass(chk.ImageFullPath + chk.ImageFile).CheckImage, _ prtRect, prtText, rptBody.DefaultFont) e.Graphics.DrawImage(chkPrtImage.PrintImage, New Point(CInt(xPos), CInt(yPos))) colIndex += 1 If colIndex > colCount Then colIndex = 1 yPos += prtRect.Height + colGutter If yPos > e.MarginBounds.Bottom Then If chkList.Count - 1 > i Then listIndex = i + 1 firstPass = False e.HasMorePages = True Exit Sub Else e.HasMorePages = False End If End If End If xPos = columns.GetItemByID(CStr(colIndex)).ColumnLeft Next End Sub End Class
'-------------------------------------------------- ' HollowFontWidePen.vb (c) 2002 by Charles Petzold '-------------------------------------------------- Imports System Imports System.Drawing Imports System.Drawing.Drawing2D Imports System.Windows.Forms Class HollowFontWidePen Inherits FontMenuForm Shared Shadows Sub Main() Application.Run(New HollowFontWidePen()) End Sub Sub New() Text = "Hollow Font (Wide Pen)" Width *= 2 strText = "Wide Pen" fnt = New Font("Times New Roman", 108, _ FontStyle.Bold Or FontStyle.Italic) End Sub Protected Overrides Sub DoPage(ByVal grfx As Graphics, _ ByVal clr As Color, ByVal cx As Integer, ByVal cy As Integer) Dim path As New GraphicsPath() Dim fFontSize As Single = PointsToPageUnits(grfx, fnt) ' Add text to the path. path.AddString(strText, fnt.FontFamily, fnt.Style, _ fFontSize, New PointF(0, 0), New StringFormat()) ' Get the path bounds for centering. Dim rectfBounds As RectangleF = path.GetBounds() grfx.TranslateTransform( _ (cx - rectfBounds.Width) / 2 - rectfBounds.Left, _ (cy - rectfBounds.Height) / 2 - rectfBounds.Top) ' Draw the path. Dim br As New HatchBrush(HatchStyle.Trellis, _ Color.White, Color.Black) Dim pn As New Pen(br, fFontSize / 20) grfx.DrawPath(pn, path) End Sub End Class
Imports Microsoft.EnterpriseManagement.HealthService Imports System.Collections.Generic Imports System.Diagnostics Imports System.Xml Imports Microsoft.Win32 Imports System.Reflection Imports System.Runtime.InteropServices Imports Nest <MonitoringModule(ModuleType.WriteAction)> <ModuleOutput(False)> Public NotInheritable Class PreparedJSON_WritetoES 'Inherit the ModuleBase we will be working off of Inherits ModuleBase(Of DataItemBase) 'Shared objects are accessable from all instances Shared Logger As P2PLogging Shared ShutdownInProgress As Boolean = False 'This global object will help to control data useage with SyncLocks. Private shutdownLock As Object 'These items are Global, reducing the instantiation cost of reuse Private ESConnector As ElasticSearchConnector Private DataItemCollection As DataItemProcessor Public Overrides Sub Start() SyncLock shutdownLock 'We don't need to continue if Shutdowns are starting. If ShutdownInProgress Then Return End If 'Request the first data batch. 'The ME keyword unambiguously refers to this instance Me.ModuleHost.RequestNextDataItem() End SyncLock End Sub Public Overrides Sub Shutdown() 'Lock to prevent other operations during Shutdown SyncLock shutdownLock ShutdownInProgress = True Me.Finalize() End SyncLock End Sub Public Sub New(moduleHost As ModuleHost(Of DataItemBase), configuration As XmlReader, previousState As Byte()) 'Call the Base Constructor MyBase.New(moduleHost) Try Logger = New P2PLogging 'Verify we Have everything we need If configuration Is Nothing Then Throw New Exception("configuration is nothing") ''Add the Additional Libraries to our instantiation 'Dim LibraryLoader As New LibraryLoader(Assembly.GetExecutingAssembly(), False) 'LibraryLoader.LoadLibrariesFromResources() 'Extract from Config what we need and initiate the connections. Dim InstanceConfig As ParsedConfigData InstanceConfig = New ParsedConfigData(configuration, True) 'Create the Classes we will use throughout the life of this module DataItemCollection = New DataItemProcessor(Logger) ESConnector = New ElasticSearchConnector(InstanceConfig.ESNode, InstanceConfig.OtherIndex, InstanceConfig.WinEvtIndex, Logger) Catch ex As Exception Logger.LogErrorDetails("Failed to Start Module", ex) Finally Logger.WriteInformation("Completed PrePared JSON Write Startup") shutdownLock = New Object() End Try End Sub <InputStream(0)> Public Sub OnNewDataItems(dataItems As DataItemBase(), logicallyGrouped As Boolean, acknowledgedCallback As DataItemAcknowledgementCallback, acknowledgedState As Object, completionCallback As DataItemProcessingCompleteCallback, completionState As Object) If (acknowledgedCallback Is Nothing AndAlso completionCallback IsNot Nothing) OrElse (acknowledgedCallback IsNot Nothing AndAlso completionCallback Is Nothing) Then Throw New ArgumentOutOfRangeException("acknowledgedCallback, completionCallback", "Only one of acknowledgedCallback and completionCallback is non-null together") End If Dim ackNeeded As Boolean If acknowledgedCallback IsNot Nothing Then ackNeeded = True Else ackNeeded = False End If SyncLock shutdownLock Try ' If we have been shutdown stop processing. If ShutdownInProgress Then Logger.WriteInformation("Shutdown in Progress") Return End If Dim SB As New Text.StringBuilder SB.EnsureCapacity(dataItems.Count * 300) 'Get each item pulled For Each JSONItem As JSONEncodedDataItem In dataItems SB.Append(JSONItem.EncodedItem) Next 'Post Async ESConnector.ProccessBulkAsyncJSON(SB.ToString(), 8) SB.Clear() Catch ex As Exception Logger.LogErrorDetails("Failed to Process Data Items: ", ex) End Try If ackNeeded Then ' Send the ack and completion back for the input. acknowledgedCallback(acknowledgedState) completionCallback(completionState) ' Know that we have sent back both the completion and ' ack we can request the next data item. Threading.Thread.Sleep(100) ModuleHost.RequestNextDataItem() Else Threading.Thread.Sleep(100) ModuleHost.RequestNextDataItem() End If End SyncLock End Sub Public Shared Function LoadResource(ResourceName As String) As Assembly Dim ba As Byte() = Nothing Dim resource As String = ResourceName Dim curAsm As Assembly = Assembly.GetExecutingAssembly() Using stm As IO.Stream = curAsm.GetManifestResourceStream(resource) ba = New Byte(CInt(stm.Length) - 1) {} stm.Read(ba, 0, CInt(stm.Length)) Return Assembly.Load(ba) End Using End Function End Class
'----------------------------------------------------- ' SplitTwoProportional.vb (c) 2002 by Charles Petzold '----------------------------------------------------- Imports System Imports System.Drawing Imports System.Windows.Forms Class SplitTwoProportional Inherits Form Private pnl2 As Panel Private fProportion As Single = 0.5F Shared Sub Main() Application.Run(New SplitTwoProportional()) End Sub Sub New() Text = "Split Two Proportional" Dim pnl1 As New Panel() pnl1.Parent = Me pnl1.Dock = DockStyle.Fill pnl1.BackColor = Color.Red AddHandler pnl1.Resize, AddressOf PanelOnResize AddHandler pnl1.Paint, AddressOf PanelOnPaint Dim split As New Splitter() split.Parent = Me split.Dock = DockStyle.Left AddHandler split.SplitterMoving, AddressOf SplitterOnMoving pnl2 = New Panel() pnl2.Parent = Me pnl2.Dock = DockStyle.Left pnl2.BackColor = Color.Lime AddHandler pnl2.Resize, AddressOf PanelOnResize AddHandler pnl2.Paint, AddressOf PanelOnPaint OnResize(EventArgs.Empty) End Sub Protected Overrides Sub OnResize(ByVal ea As EventArgs) MyBase.OnResize(ea) pnl2.Width = CInt(fProportion * ClientSize.Width) End Sub Private Sub SplitterOnMoving(ByVal obj As Object, _ ByVal sea As SplitterEventArgs) fProportion = CSng(sea.SplitX) / ClientSize.Width End Sub Private Sub PanelOnResize(ByVal obj As Object, ByVal ea As EventArgs) DirectCast(obj, Panel).Invalidate() End Sub Private Sub PanelOnPaint(ByVal obj As Object, _ ByVal pea As PaintEventArgs) Dim pnl As Panel = DirectCast(obj, Panel) Dim grfx As Graphics = pea.Graphics grfx.DrawEllipse(Pens.Black, 0, 0, _ pnl.Width - 1, pnl.Height - 1) End Sub End Class
Imports System.Data Imports System.Data.OleDb Partial Class _Library_Controls_News Inherits System.Web.UI.UserControl Const QueryDateFormat As String = "dd-MMM-yyyy" Const BlogDatabase As String = "~/App_Data/Blog.mdb" Dim strPostKeyList As String = "any" Dim strBlogWidth As String = "500px" Dim strPostKeyLength As String = "100" Dim strPostID As String = "" Dim strPostMonth As String = "" Public Property BlogWidth() As String Get Return strBlogWidth End Get Set(ByVal Value As String) strBlogWidth = Value End Set End Property Public Property PostKeyList() As String Get Return strPostKeyList End Get Set(ByVal Value As String) strPostKeyList = Value End Set End Property Public Property PostKeyLength() As String Get Return strPostKeyLength End Get Set(ByVal Value As String) strPostKeyLength = Value End Set End Property Public Property PostID() As String Get Return strPostID End Get Set(ByVal Value As String) strPostID = Value End Set End Property Public Property PostMonth() As String Get Return strPostMonth End Get Set(ByVal Value As String) strPostMonth = Value End Set End Property Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim arrPostKeyList() As String = strPostKeyList.Split(",") Dim strSQL As String = "SELECT TOP " & strPostKeyLength & " * FROM Posts WHERE (PostVisible=True) " If arrPostKeyList(0) = "any" Then strSQL = strSQL Else 'add first postkey strSQL = strSQL & "AND ((PostKey='" & arrPostKeyList(0) & "')" 'add any other postkeys If arrPostKeyList.Length > 1 Then For i As Integer = 1 To arrPostKeyList.Length - 1 strSQL = strSQL & " OR (PostKey='" & arrPostKeyList(i) & "')" Next End If If strPostID.Length > 1 Then strSQL = strSQL & " AND (PostID=" & strPostID & ")" End If End If ' work out postings by month If strPostMonth <> Nothing Then Dim datStart As Date = strPostMonth & "/1/" & DateTime.Now.Year ' check the year If datStart > DateTime.Now Then datStart = datStart.AddYears(-1) End If Dim datEnd As Date = datStart.AddMonths(1) strSQL = strSQL & ") AND PostDate >= #" & datStart.ToString & "# AND PostDate < #" & datEnd.ToString & "#" Else strSQL = strSQL & ") AND PostDate <= #" & DateTime.Now.ToString(QueryDateFormat) & " 11:59 pm#" End If 'add sql closing strSQL = strSQL & " ORDER BY PostDate DESC" 'Specify the SQL string Dim SQLString As String = strSQL Dim myOleDbConnection As OleDbConnection myOleDbConnection = New OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;DATA SOURCE=" & Context.Server.MapPath(BlogDatabase)) myOleDbConnection.Open() Dim myOleDbCommand As OleDbCommand = New OleDbCommand(SQLString, myOleDbConnection) Dim myOleDbDataReader As OleDbDataReader = myOleDbCommand.ExecuteReader(CommandBehavior.CloseConnection) PostsRepeater.DataSource = myOleDbDataReader PostsRepeater.DataBind() divBlog.Attributes.Add("style", "width: " & strBlogWidth & "; overflow: hidden; display: block;") End Sub End Class
Imports System Imports Microsoft.VisualBasic Imports ChartDirector Public Class hlinearmeterorientation Implements DemoModule 'Name of demo module Public Function getName() As String Implements DemoModule.getName Return "H-Linear Meter Orientation" End Function 'Number of charts produced in this demo module Public Function getNoOfCharts() As Integer Implements DemoModule.getNoOfCharts Return 4 End Function 'Main code for creating charts Public Sub createChart(viewer As WinChartViewer, chartIndex As Integer) _ Implements DemoModule.createChart ' The value to display on the meter Dim value As Double = 74.25 ' Create a LinearMeter object of size 250 x 75 pixels with very light grey (0xeeeeee) ' backgruond and a light grey (0xccccccc) 3-pixel thick rounded frame Dim m As LinearMeter = New LinearMeter(250, 75, &Heeeeee, &Hcccccc) m.setRoundedFrame(Chart.Transparent) m.setThickFrame(3) ' This example demonstrates putting the text labels at the top or bottom. This is by setting ' the label alignment, scale position and label position. Dim alignment() As Integer = {Chart.Top, Chart.Top, Chart.Bottom, Chart.Bottom} Dim meterYPos() As Integer = {23, 23, 34, 34} Dim labelYPos() As Integer = {61, 61, 15, 15} ' Set the scale region m.setMeter(14, meterYPos(chartIndex), 218, 20, alignment(chartIndex)) ' Set meter scale from 0 - 100, with a tick every 10 units m.setScale(0, 100, 10) ' Add a smooth color scale at the default position Dim smoothColorScale() As Double = {0, &H6666ff, 25, &H00bbbb, 50, &H00ff00, 75, &Hffff00, _ 100, &Hff0000} m.addColorScale(smoothColorScale) ' Add a blue (0x0000cc) pointer at the specified value m.addPointer(value, &H0000cc) ' ' In this example, some charts have the "Temperauture" label on the left side and the value ' readout on the right side, and some charts have the reverse ' If chartIndex Mod 2 = 0 Then ' Add a label on the left side using 8pt Arial Bold font m.addText(10, labelYPos(chartIndex), "Temperature C", "Arial Bold", 8, _ Chart.TextColor, Chart.Left) ' Add a text box on the right side. Display the value using white (0xffffff) 8pt Arial ' Bold font on a black (0x000000) background with depressed rounded border. Dim t As ChartDirector.TextBox = m.addText(235, labelYPos(chartIndex), m.formatValue( _ value, "2"), "Arial Bold", 8, &Hffffff, Chart.Right) t.setBackground(&H000000, &H000000, -1) t.setRoundedCorners(3) Else ' Add a label on the right side using 8pt Arial Bold font m.addText(237, labelYPos(chartIndex), "Temperature C", "Arial Bold", 8, _ Chart.TextColor, Chart.Right) ' Add a text box on the left side. Display the value using white (0xffffff) 8pt Arial ' Bold font on a black (0x000000) background with depressed rounded border. Dim t As ChartDirector.TextBox = m.addText(11, labelYPos(chartIndex), m.formatValue( _ value, "2"), "Arial Bold", 8, &Hffffff, Chart.Left) t.setBackground(&H000000, &H000000, -1) t.setRoundedCorners(3) End If ' Output the chart viewer.Chart = m End Sub End Class
Imports System.Reflection Imports Microsoft.SqlServer.Dts.Runtime Friend Class cHResLookup Friend Shared Function get_com_symbolic_err_msg(errorCode As Integer) As String Dim symbolicName As String = String.Empty Dim hresults As New HResults() For Each fieldInfo As FieldInfo In hresults.[GetType]().GetFields() If CInt(fieldInfo.GetValue(hresults)) = errorCode Then symbolicName = fieldInfo.Name Exit For End If Next Return symbolicName End Function End Class
Imports Route4MeSDKLibrary.Route4MeSDK Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes Namespace Route4MeSDKTest.Examples Partial Public NotInheritable Class Route4MeExamples ''' <summary> ''' Add Avoidance Zone ''' </summary> ''' <param name="removeAvoidanceZone">If true, created avoidance zone removed</param> ''' <returns>Id of added territory </returns> Public Function AddAvoidanceZone( ByVal Optional removeAvoidanceZone As Boolean = True) As String Dim route4Me = New Route4MeManager(ActualApiKey) Dim avoidanceZoneParameters = New AvoidanceZoneParameters() With { .TerritoryName = "Test Territory", .TerritoryColor = "ff0000", .Territory = New Territory() With { .Type = TerritoryType.Circle.GetEnumDescription(), .Data = New String() {"37.569752822786455,-77.47833251953125", "5000"} } } Dim errorString As String = Nothing Dim avoidanceZone As AvoidanceZone = route4Me.AddAvoidanceZone(avoidanceZoneParameters, errorString) PrintExampleAvoidanceZone(avoidanceZone, errorString) Dim avZoneId As String = If(avoidanceZone IsNot Nothing AndAlso avoidanceZone.[GetType]() = GetType(AvoidanceZone), avoidanceZone.TerritoryId, Nothing) If removeAvoidanceZone Then RemoveAvidanceZone(avZoneId) Return If(removeAvoidanceZone, Nothing, avZoneId) End Function End Class End Namespace
Imports POS.Devices Imports OposPOSPrinter_CCO Imports System.IO 'Imports OposFiscalPrinter_CCO Public Class PointOfSale ''' <summary> ''' pos printer settings ''' </summary> Public Shared posPrinterLogicName As String = "" Public Shared posCashDrawerLogicName As String = "" Public Shared posLineDisplayLogicName As String = "" Public Shared posPrinterEnabled As String = "" ''' <summary> ''' 'fiscal printer settings ''' </summary> Public Shared strLogicalName As String = InstalledPPOSDevices.posLogicName 'get the available fiscal printer logical name Public Shared fiscalPrinterDeviceName As String = "" Public Shared operatorName As String = "" Public Shared operatorPassword As String = "" Public Shared port As String = "" Public Shared drawer As String = "" Public Shared fiscalPrinterEnabled As String = "" ''' <summary> ''' function to print receipt ''' </summary> ''' ''' <param name="tillNo"></param> ''' <param name="receiptNo"></param> ''' <param name="date_"></param> ''' <param name="TIN"></param> ''' <param name="VRN"></param> ''' <param name="itemCode"></param> ''' <param name="descr"></param> ''' <param name="qty"></param> ''' <param name="price"></param> ''' <param name="tax"></param> ''' <param name="amount"></param> ''' <param name="subTotal"></param> ''' <param name="VAT"></param> ''' <param name="grandTotal"></param> ''' <returns></returns> ''' Private Shared prn As New RawPrinterHelper Private Shared PrinterName As String = "EPSON TM-T20 Receipt" Private Shared eClear As String = Chr(27) + "@" Private Shared eCentre As String = Chr(27) + Chr(97) + "1" Private Shared eLeft As String = Chr(27) + Chr(97) + "0" Private Shared eRight As String = Chr(27) + Chr(97) + "2" Private Shared eDrawer As String = eClear + Chr(27) + "p" + Chr(0) + ".}" Private Shared eCut As String = Chr(27) + "i" + vbCrLf Private Shared eSmlText As String = Chr(27) + "!" + Chr(1) Private Shared eNmlText As String = Chr(27) + "!" + Chr(0) Private Shared eInit As String = eNmlText + Chr(13) + Chr(27) + "c6" + Chr(1) + Chr(27) + "R3" + vbCrLf Private Shared eBigCharOn As String = Chr(27) + "!" + Chr(56) Private Shared eBigCharOff As String = Chr(27) + "!" + Chr(0) Public Shared Function printFiscalReceipt(tillNo As String, receiptNo As String, date_ As String, TIN As String, VRN As String, itemCode() As String, descr() As String, qty() As String, price() As String, tax() As String, amount() As String, subTotal As String, VAT As String, grandTotal As String, cash As String, balance As String) Dim fileName As String = "Receipt" Dim strFile As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments & fileName & ".txt" Dim sw As StreamWriter Try If (Not File.Exists(strFile)) Then sw = File.CreateText(strFile) Else File.WriteAllText(strFile, "") sw = File.AppendText(strFile) End If Dim str As String = "" 'sw.WriteLine("R_TXT ""Receipt :" + receiptNo + """") str = str + "R_TXT ""Receipt :" + receiptNo + """" + vbCrLf 'sw.WriteLine("R_TXT ""Code Qty Price@ """) str = str + "R_TXT ""Code Qty Price@ """ + vbCrLf 'sw.WriteLine("R_TXT ""Description """) str = str + "R_TXT ""Description """ + vbCrLf 'sw.WriteLine("R_TXT ""===================================== """) str = str + "R_TXT ""===================================== """ + vbCrLf For i As Integer = 0 To descr.Length - 1 'sw.WriteLine("R_TRP """ + itemCode(i) + """" + """""" + qty(i).Replace(",", "") + "* " + price(i) + "V4") str = str + "R_TRP """ + itemCode(i) + """" + """""" + qty(i).Replace(",", "") + "* " + price(i) + "V4" + vbCrLf 'sw.WriteLine("R_TXT """ + descr(i) + """") str = str + "R_TXT """ + descr(i) + """" + vbCrLf 'sw.WriteLine("R_TXT ""------------------------------------- """) str = str + "R_TXT ""------------------------------------- """ + vbCrLf Next 'sw.WriteLine("R_TXT ""===================================== """) str = str + "R_TXT ""===================================== """ + vbCrLf sw.WriteLine("R_STT P") str = str + "R_STT P" sw.Write(str) sw.Close() Catch e As Exception MsgBox(e.StackTrace) End Try 'Dim Proc As New Process 'Proc.StartInfo.FileName = strFile ' Proc.StartInfo.Verb = "Print" 'Proc.Start() 'Proc.Close() Return vbNull End Function Public Shared Function printReceipt(tillNo As String, receiptNo As String, date_ As String, TIN As String, VRN As String, itemCode() As String, descr() As String, qty() As String, price() As String, tax() As String, amount() As String, subTotal As String, VAT As String, grandTotal As String, cash As String, balance As String) 'PointOfSale.printFiscalReceipt(tillNo, receiptNo, date_, TIN, VRN, itemCode, descr, qty, price, tax, amount, subTotal, VAT, grandTotal, cash, balance) Dim continue_ As Boolean = True prn.OpenPrint(posPrinterLogicName) Try Try prn.OpenPrint(posPrinterLogicName) Catch ex As Exception End Try If prn.PrinterIsOpen = False And PointOfSale.posPrinterEnabled = "ENABLED" Then Dim res As Integer = MsgBox("Could Not connect to POS printer. Continue operation without printing POS receipt?", vbYesNo + vbQuestion, "Error: POS Printer not available") If res = DialogResult.Yes Then continue_ = True Else continue_ = False Return continue_ Exit Function End If End If If PointOfSale.fiscalPrinterEnabled = "ENABLED" And continue_ = True Then 'insert options for fiscal printer in the future Dim res As Integer = MsgBox("Could not connect to Fiscal printer. Continue operation without printing Fiscal receipt?", vbYesNo + vbQuestion, "Error: Fiscal Printer not available") If res = DialogResult.Yes Then continue_ = True Else continue_ = False Return continue_ Exit Function End If End If If continue_ = False Then Return continue_ Exit Function End If Dim space As String = "" For i As Integer = 1 To (40 - Company.NAME.ToString.Length) / 2 space = space + " " Next Dim companyName As String = space + Company.NAME space = "" For i As Integer = 1 To (40 - Company.POST_CODE.ToString.Length) / 2 space = space + " " Next Dim postCode As String = space + Company.POST_CODE space = "" For i As Integer = 1 To (40 - Company.PHYSICAL_ADDRESS.ToString.Length) / 2 space = space + " " Next Dim physicalAddress As String = space + Company.PHYSICAL_ADDRESS space = "" For i As Integer = 1 To (40 - Company.TELEPHONE.ToString.Length) / 2 space = space + " " Next Dim telephone As String = space + Company.TELEPHONE space = "" For i As Integer = 1 To (40 - Company.EMAIL.ToString.Length) / 2 space = space + " " Next Dim email As String = space + Company.EMAIL Dim fDateTime As String Dim strOutputData As String = "" Dim CRLF Dim ESC fDateTime = Date.Now.ToString("yyyy/MM/dd HH:mm:ss") 'System date and time CRLF = Chr(13) + Chr(10) ESC = Chr(&H1B) strOutputData = strOutputData + companyName + CRLF strOutputData = strOutputData + postCode + CRLF strOutputData = strOutputData + physicalAddress + CRLF strOutputData = strOutputData + telephone + CRLF strOutputData = strOutputData + email + CRLF + CRLF strOutputData = strOutputData + " *** Sales Receipt ***" + CRLF strOutputData = strOutputData + "TIN: " + TIN + CRLF strOutputData = strOutputData + "VRN: " + VRN + CRLF strOutputData = strOutputData + "Till No: " + tillNo + CRLF strOutputData = strOutputData + "Receipt No: " + receiptNo + CRLF strOutputData = strOutputData + CRLF strOutputData = strOutputData + "CODE QTY PRICE@ AMOUNT" + CRLF strOutputData = strOutputData + "DESCRIPTION" + CRLF strOutputData = strOutputData + "====================================" + CRLF For i As Integer = 0 To descr.Length - 1 strOutputData = strOutputData + itemCode(i) + " x " + qty(i) + " " + price(i) + " " + amount(i) + CRLF strOutputData = strOutputData + descr(i) + CRLF Next strOutputData = strOutputData + "------------------------------------" + CRLF strOutputData = strOutputData + "Sub Total " + subTotal + CRLF strOutputData = strOutputData + "Tax " + VAT + CRLF strOutputData = strOutputData + "Total Amount " + grandTotal + CRLF strOutputData = strOutputData + "====================================" + CRLF strOutputData = strOutputData + "Cash " + cash + CRLF strOutputData = strOutputData + "Balance " + balance + CRLF strOutputData = strOutputData + "====================================" + CRLF strOutputData = strOutputData + " You are Welcome !" + CRLF strOutputData = strOutputData + "Sale Date&Time : " + fDateTime + CRLF + CRLF strOutputData = strOutputData + CRLF strOutputData = strOutputData + " Served by: " + User.FIRST_NAME + " " + User.LAST_NAME + CRLF strOutputData = strOutputData + (Chr(&H1D) & "V" & Chr(66) & Chr(0)) Try prn.OpenPrint(posPrinterLogicName) Print(strOutputData) prn.ClosePrint() Catch ex As Exception End Try Catch ex As Exception MsgBox("Operation canceled. Could not print POS receipt") Return continue_ Exit Function End Try Return continue_ End Function Public Shared Function printOrder(copy As String, orderNo As String, waiter As String, itemCode() As String, descr() As String, qty() As String, price() As String, amount() As String, grandTotal As String) Dim continue_ As Boolean = True prn.OpenPrint(posPrinterLogicName) Try Try prn.OpenPrint(posPrinterLogicName) Catch ex As Exception MsgBox(ex.StackTrace) End Try If prn.PrinterIsOpen = False And PointOfSale.posPrinterEnabled = "ENABLED" Then continue_ = False MsgBox("Could not print order. Printer error") Return continue_ Exit Function End If Dim space As String = "" For i As Integer = 1 To (40 - Company.NAME.ToString.Length) / 2 space = space + " " Next Dim companyName As String = space + Company.NAME Dim fDateTime As String Dim strOutputData As String = "" Dim CRLF Dim ESC fDateTime = Date.Now.ToString("yyyy/MM/dd HH:mm:ss") 'System date and time CRLF = Chr(13) + Chr(10) ESC = Chr(&H1B) strOutputData = strOutputData + companyName + CRLF strOutputData = strOutputData + " *** Order Slip ***" + CRLF strOutputData = strOutputData + "Order No: " + orderNo + CRLF strOutputData = strOutputData + "Slip: " + copy + CRLF strOutputData = strOutputData + "Waiter Name: " + waiter + CRLF strOutputData = strOutputData + CRLF strOutputData = strOutputData + "CODE QTY PRICE@ AMOUNT" + CRLF strOutputData = strOutputData + "DESCRIPTION" + CRLF strOutputData = strOutputData + "====================================" + CRLF For i As Integer = 0 To descr.Length - 1 strOutputData = strOutputData + itemCode(i) + " x " + qty(i) + " " + price(i) + " " + amount(i) + CRLF strOutputData = strOutputData + descr(i) + CRLF Next strOutputData = strOutputData + "------------------------------------" + CRLF strOutputData = strOutputData + "Total Amount " + grandTotal + CRLF strOutputData = strOutputData + "====================================" + CRLF strOutputData = strOutputData + "Printed Date&Time : " + fDateTime + CRLF strOutputData = strOutputData + (Chr(&H1D) & "V" & Chr(66) & Chr(0)) Try prn.OpenPrint(posPrinterLogicName) Print(strOutputData) prn.ClosePrint() Catch ex As Exception MsgBox(ex.Message) End Try Catch ex As Exception MsgBox("Operation canceled. Could not print Order Slip") Return continue_ Exit Function End Try Return continue_ End Function Private Shared Sub Print(Line As String) prn.SendStringToPrinter(PrinterName, Line + vbLf) End Sub Private Shared Sub PrintDashes() Print(eLeft + eNmlText + "-".PadRight(42, "-")) End Sub Public Sub EndPrint() prn.ClosePrint() End Sub 'Private Sub bnExit_Click(sender As System.Object, e As System.EventArgs) _ ' Handles bnExit.Click ' prn.ClosePrint() ' Me.Close() 'End Sub 'Private Sub bnPrint_Click(sender As System.Object, e As System.EventArgs) _ ' Handles bnPrint.Click ' StartPrint() ' If prn.PrinterIsOpen = True Then ' PrintHeader() ' PrintBody() ' PrintFooter() ' EndPrint() ' End If 'End Sub 'Dim posPrinter As New OPOSPOSPrinter 'Dim posprinter As New RawPrinterHelper ' Dim cashDrawer As New OPOSCashDrawer ' cash drawer to be implemented later ' Dim fiscalPrinter As New OPOSFiscalPrinter 'fiscal printer to be implemented later ' Dim posPrintJob As Long = posprinter.Open(posPrinterLogicName) ' Dim fiscalPrintJob As Long = fiscalPrinter.Open(fiscalPrinterDeviceName) ' If posPrintJob <> 0 And PointOfSale.posPrinterEnabled = "ENABLED" Then ' Dim res As Integer = MsgBox("Could not connect to POS printer. Continue operation without printing POS receipt?", vbYesNo + vbQuestion, "Error: POS Printer not available") ' If res = DialogResult.Yes Then ' continue_ = True ' Else ' continue_ = False ' Return continue_ ' Exit Function ' End If ' End If ' If fiscalPrintJob <> 0 And PointOfSale.fiscalPrinterEnabled = "ENABLED" And continue_ = True Then ' Dim res As Integer = MsgBox("Could not connect to Fiscal printer. Continue operation without printing Fiscal receipt?", vbYesNo + vbQuestion, "Error: Fiscal Printer not available") ' If res = DialogResult.Yes Then ' continue_ = True ' Else ' continue_ = False ' Return continue_ ' Exit Function ' End If ' End If ' If continue_ = False Then ' Return continue_ ' Exit Function ' End If ' Try ' If posPrintJob = 0 Then ' posPrintJob = posprinter.ClaimDevice(1000) ' If posPrintJob = 0 Then ' Try ' cashDrawer.Open(posCashDrawerLogicName) ' cashDrawer.OpenDrawer() ' Catch ex As Exception ' End Try ' posprinter.DeviceEnabled = True ' Dim fDateTime As String ' Dim strOutputData As String = "" ' Dim CRLF ' Dim ESC ' fDateTime = Date.Now.ToString("yyyy/MM/dd HH:mm:ss") 'System date and time ' CRLF = Chr(13) + Chr(10) ' ESC = Chr(&H1B) ' strOutputData = strOutputData + ESC + "|bC" + ESC + "|cA" + "*" + Company.NAME + "*" + CRLF ' strOutputData = strOutputData + ESC + "|N" + ESC + "|cA" + Company.POST_CODE + CRLF ' strOutputData = strOutputData + ESC + "|N" + ESC + "|cA" + Company.PHYSICAL_ADDRESS + CRLF ' strOutputData = strOutputData + ESC + "|N" + ESC + "|cA" + "Tel: " + Company.TELEPHONE + CRLF ' strOutputData = strOutputData + ESC + "|N" + ESC + "|cA" + Company.EMAIL + CRLF + CRLF ' strOutputData = strOutputData + ESC + "|N" + ESC + "|cA" + "*** Sales Receipt ***" + CRLF ' strOutputData = strOutputData + ESC + "|N" + ESC + "|bC" + "TIN " + TIN + CRLF ' strOutputData = strOutputData + ESC + "|N" + ESC + "|bC" + "VRN " + VRN + CRLF ' strOutputData = strOutputData + ESC + "|N" + ESC + "|bC" + "Till No " + tillNo + CRLF ' strOutputData = strOutputData + ESC + "|N" + ESC + "|bC" + "Receipt No " + receiptNo + CRLF ' strOutputData = strOutputData + ESC + "|N" + " " + CRLF ' strOutputData = strOutputData + "CODE QTY PRICE@ AMOUNT" + CRLF ' strOutputData = strOutputData + "DESCRIPTION" + CRLF ' strOutputData = strOutputData + "====================================" + CRLF ' For i As Integer = 0 To descr.Length - 1 ' strOutputData = strOutputData + itemCode(i) + " x " + qty(i) + " " + price(i) + " " + amount(i) + CRLF ' strOutputData = strOutputData + descr(i) + CRLF ' Next ' strOutputData = strOutputData + "-----------------------------------" + CRLF ' strOutputData = strOutputData + ESC + "|N" + ESC + "|bC" + "Sub Total " + subTotal + CRLF ' strOutputData = strOutputData + ESC + "|N" + ESC + "|bC" + "Tax " + VAT + CRLF ' strOutputData = strOutputData + ESC + "|N" + ESC + "|bC" + "Total Amount " + grandTotal + CRLF ' strOutputData = strOutputData + "===================================" + CRLF ' strOutputData = strOutputData + ESC + "|bC" + ESC + "|cA" + "You are Welcome !" + CRLF ' strOutputData = strOutputData + ESC + "|N" + ESC + "|cA" + "Sale Date&Time : " + fDateTime + CRLF + CRLF ' strOutputData = strOutputData + ESC + "|N" + " " + CRLF ' strOutputData = strOutputData + "Served by: " + User.FIRST_NAME + " " + User.LAST_NAME + CRLF ' posprinter.PrintNormal(2, strOutputData) ' If posprinter.CapRecPapercut = True Then ' posprinter.PrintNormal(2, ESC + "|fP") ' Else ' posprinter.PrintNormal(2, ESC + "|" + CStr(posprinter.RecLinesToPaperCut) + "lF") ' End If ' posprinter.Close() ' Else ' MsgBox("Printer claim error " + posprinter.ErrorString, vbCritical + vbOKOnly) ' continue_ = False ' Return continue_ ' Exit Function ' End If ' Else ' 'MsgBox("Printer open error " + posPrinter.ErrorString, vbCritical + vbOKOnly) ' 'continue_ = False ' 'Return continue_ ' 'Exit Function ' End If ' Catch ex As Exception ' 'MsgBox(ex.Message) ' 'Return continue_ ' 'Exit Function ' End Try ' Return continue_ 'End Function Public Shared Function printReceipt1(tillNo As String, receiptNo As String, date_ As String, TIN As String, VRN As String, itemCode() As String, descr() As String, qty() As String, price() As String, tax() As String, amount() As String, subTotal As String, VAT As String, grandTotal As String) Dim continue_ As Boolean = True Dim posPrinter As New OPOSPOSPrinter Dim cashDrawer As New OPOSCashDrawer ' cash drawer to be implemented later Dim fiscalPrinter As New OPOSFiscalPrinter 'fiscal printer to be implemented later Dim posPrintJob As Long = posPrinter.Open(posPrinterLogicName) Dim fiscalPrintJob As Long = fiscalPrinter.Open(fiscalPrinterDeviceName) If posPrintJob <> 0 And PointOfSale.posPrinterEnabled = "ENABLED" Then Dim res As Integer = MsgBox("Could not connect to POS printer. Continue operation without printing POS receipt?", vbYesNo + vbQuestion, "Error: POS Printer not available") If res = DialogResult.Yes Then continue_ = True Else continue_ = False Return continue_ Exit Function End If End If If fiscalPrintJob <> 0 And PointOfSale.fiscalPrinterEnabled = "ENABLED" And continue_ = True Then Dim res As Integer = MsgBox("Could not connect to Fiscal printer. Continue operation without printing Fiscal receipt?", vbYesNo + vbQuestion, "Error: Fiscal Printer not available") If res = DialogResult.Yes Then continue_ = True Else continue_ = False Return continue_ Exit Function End If End If If continue_ = False Then Return continue_ Exit Function End If Try If posPrintJob = 0 Then posPrintJob = posPrinter.ClaimDevice(1000) If posPrintJob = 0 Then Try cashDrawer.Open(posCashDrawerLogicName) cashDrawer.OpenDrawer() Catch ex As Exception End Try posPrinter.DeviceEnabled = True Dim fDateTime As String Dim strOutputData As String = "" Dim CRLF Dim ESC fDateTime = Date.Now.ToString("yyyy/MM/dd HH:mm:ss") 'System date and time CRLF = Chr(13) + Chr(10) ESC = Chr(&H1B) strOutputData = strOutputData + ESC + "|bC" + ESC + "|cA" + "*" + Company.NAME + "*" + CRLF strOutputData = strOutputData + ESC + "|N" + ESC + "|cA" + Company.POST_CODE + CRLF strOutputData = strOutputData + ESC + "|N" + ESC + "|cA" + Company.PHYSICAL_ADDRESS + CRLF strOutputData = strOutputData + ESC + "|N" + ESC + "|cA" + "Tel: " + Company.TELEPHONE + CRLF strOutputData = strOutputData + ESC + "|N" + ESC + "|cA" + Company.EMAIL + CRLF + CRLF strOutputData = strOutputData + ESC + "|N" + ESC + "|cA" + "*** Sales Receipt ***" + CRLF strOutputData = strOutputData + ESC + "|N" + ESC + "|bC" + "TIN " + TIN + CRLF strOutputData = strOutputData + ESC + "|N" + ESC + "|bC" + "VRN " + VRN + CRLF strOutputData = strOutputData + ESC + "|N" + ESC + "|bC" + "Till No " + tillNo + CRLF strOutputData = strOutputData + ESC + "|N" + ESC + "|bC" + "Receipt No " + receiptNo + CRLF strOutputData = strOutputData + ESC + "|N" + " " + CRLF strOutputData = strOutputData + "CODE QTY PRICE@ AMOUNT" + CRLF strOutputData = strOutputData + "DESCRIPTION" + CRLF strOutputData = strOutputData + "====================================" + CRLF For i As Integer = 0 To descr.Length - 1 strOutputData = strOutputData + itemCode(i) + " x " + qty(i) + " " + price(i) + " " + amount(i) + CRLF strOutputData = strOutputData + descr(i) + CRLF Next strOutputData = strOutputData + "-----------------------------------" + CRLF strOutputData = strOutputData + ESC + "|N" + ESC + "|bC" + "Sub Total " + subTotal + CRLF strOutputData = strOutputData + ESC + "|N" + ESC + "|bC" + "Tax " + VAT + CRLF strOutputData = strOutputData + ESC + "|N" + ESC + "|bC" + "Total Amount " + grandTotal + CRLF strOutputData = strOutputData + "===================================" + CRLF strOutputData = strOutputData + ESC + "|bC" + ESC + "|cA" + "You are Welcome !" + CRLF strOutputData = strOutputData + ESC + "|N" + ESC + "|cA" + "Sale Date&Time : " + fDateTime + CRLF + CRLF strOutputData = strOutputData + ESC + "|N" + " " + CRLF strOutputData = strOutputData + "Served by: " + User.FIRST_NAME + " " + User.LAST_NAME + CRLF posPrinter.PrintNormal(2, strOutputData) If posPrinter.CapRecPapercut = True Then posPrinter.PrintNormal(2, ESC + "|fP") Else posPrinter.PrintNormal(2, ESC + "|" + CStr(posPrinter.RecLinesToPaperCut) + "lF") End If posPrinter.Close() Else MsgBox("Printer claim error " + posPrinter.ErrorString, vbCritical + vbOKOnly) continue_ = False Return continue_ Exit Function End If Else 'MsgBox("Printer open error " + posPrinter.ErrorString, vbCritical + vbOKOnly) 'continue_ = False 'Return continue_ 'Exit Function End If Catch ex As Exception 'MsgBox(ex.Message) 'Return continue_ 'Exit Function End Try Return continue_ End Function End Class
Imports BasesParaCompatibilidad.ComboBoxExtension Public Class frmWstepDatosGenerales Implements wizardable Public Const TIPO_PALET As String = "tipoPalet" Public Const FORMATO As String = "tipoFormato" Public Const MARCA As String = "marca" Public Const MARCA_ID As String = "marcaId" Public Const LINEA As String = "linea" Public Const PRODUCTO As String = "producto" Public Const DESCRIPCION As String = "descripcion" Public Const CREAR_SECUNDARIO As String = "secundario" Public Const CREAR_FORMATO As String = "formato" Public Const CAJA As String = "caja" Private dtb As BasesParaCompatibilidad.DataBase Public Sub New() InitializeComponent() dtb = New BasesParaCompatibilidad.DataBase End Sub Private Sub frmWstepDatosGenerales_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Resize BasesParaCompatibilidad.Pantalla.centerIn(Me.panContenido, Me) End Sub Private Sub rbExisteFormato_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbExisteFormato.CheckedChanged Me.cboFormatos.Enabled = rbExisteFormato.Checked Me.panLinea.Enabled = rbNoExisteFormato.Checked End Sub Private Sub rbNoExisteFormato_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbNoExisteFormato.CheckedChanged Me.cboFormatos.Enabled = rbExisteFormato.Checked Me.panLinea.Enabled = rbNoExisteFormato.Checked End Sub Private Sub cboProducto_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboProducto.SelectedValueChanged componernombre() End Sub Private Sub cboPaletTipo_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboPaletTipo.SelectedValueChanged componernombre() End Sub Private Sub cboMarca_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboMarca.SelectedValueChanged componernombre() End Sub Public Sub establecerValores() Implements wizardable.EstablecerValores Me.cboLinea.mam_DataSource("LineasEnvasadoSelectCbo", False, dtb) Dim s As New spmarcas s.cargar_marcas(cboMarca, dtb) Dim spt As New spArticulosEnvasadosHistoricos spt.cargar_TiposFormatos_Libres(cboFormatos, dtb) Me.cboPaletTipo.mam_DataSource("PaletsTiposCbo", False, dtb) Me.cboProducto.mam_DataSource("TiposProductosSelectCbo", False, dtb) Me.cboCaja.mam_DataSource("TiposcajasCbo", False, dtb) End Sub Public Function recuperarValor(ByVal nombre As String) As Object Implements wizardable.recuperarValor Select Case (nombre) Case MARCA Return Me.cboMarca.SelectedValue Case MARCA_ID Return Me.cboMarca.SelectedValue Case FORMATO Return If(Me.rbExisteFormato.Checked, Me.cboFormatos.SelectedValue, Nothing) Case LINEA Return Me.cboLinea.SelectedValue Case TIPO_PALET Return Me.cboPaletTipo.SelectedValue Case PRODUCTO Return Me.cboProducto.SelectedValue Case DESCRIPCION Return Me.lNombre.Text Case CREAR_SECUNDARIO Return Not Me.cbCrearSecundario.Checked Case CREAR_FORMATO Return Me.rbNoExisteFormato.Checked Case CAJA Return Me.cboCaja.SelectedValue Case Else Return Nothing End Select End Function Public Function grabarDatos(ByRef dtb As BasesParaCompatibilidad.DataBase) As Boolean Implements wizardable.grabarDatos Dim retorno As Boolean = True If Me.rbNoExisteFormato.Checked Then ' se crea el formato con datos de relleno para modificarlo con los datos introducidos en la pestaña de secundario Dim m_DBO_TiposFormatos1 As New DBO_ArticulosEnvasadosHistorico m_DBO_TiposFormatos1.TipoFormatoID = 0 m_DBO_TiposFormatos1.CodigoQS = 0 m_DBO_TiposFormatos1.Descripcion = Me.lNombre.Text m_DBO_TiposFormatos1.Separadores = 0 m_DBO_TiposFormatos1.CajasPalet = 0 m_DBO_TiposFormatos1.Genericas = 0 m_DBO_TiposFormatos1.Particulares = 0 m_DBO_TiposFormatos1.TipoProductoID = 1 m_DBO_TiposFormatos1.TipoCajaID = cboCaja.SelectedValue Dim spTiposFormatos1 As New spArticulosEnvasadosHistorico1 If Not spTiposFormatos1.GrabarTiposFormatos1Sintransaccion(m_DBO_TiposFormatos1, dtb) Then Return False Dim spt As New spArticulosEnvasadosHistoricos Dim m_formato As Integer = spt.seleccionar_ultimo_registro(dtb) 'If Not ctlTipForLin_TipFor.GuardarTipoFormatoLinea(cboLinea.SelectedValue, m_formato, txtVelocidad.Text) Then Return False If Not Me.chbFormatoLinea.Checked Then 'Dim dbo As New DBO_TiposFormatosLineas 'dbo.LineaEnvasadoID = cboLinea.SelectedValue 'dbo.Descripcion = Me.cboCaja.SelectedText 'Dim sp As New spTiposFormatosLineas 'If Not sp.Grabar(dbo,dtb) Then Return False ''falta grabar tiposforamtos_tiposformatoslineas 'm_formatoLinea = RealizarConsulta("select max(tipoformatoLineaID) from tiposformatosLineas").Rows(0).Item(0) Else Dim dbo2 As New DBO_TiposFormatosLineas_TiposFormatos Dim sp2 As New spTiposFormatosLineas_TiposFormatos Dim m_formatoLinea As Integer m_formatoLinea = Me.cboFormatoLinea.SelectedValue dbo2.TipoFormatoID = m_formato dbo2.TipoFormatoLineaID = m_formatoLinea dbo2.Velocidad = Me.txtVelocidad.Text If Not sp2.Grabar(dbo2, dtb) Then Return False End If Return True Else Return True End If End Function Public Function comprobarCampos() As Boolean Implements wizardable.comprobarCampos If Me.rbNoExisteFormato.Checked Then If Me.txtVelocidad.Text = String.Empty Then txtVelocidad.Focus() MessageBox.Show("Se han encontrado los siguientes errores: " & Environment.NewLine & "El campo velocidad debe ser numérico.", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Return False End If End If Return True End Function Private Sub componernombre() Try 'Dim cadPalet As String 'cadPalet = convert.tostring(cboPaletTipo.SelectedItem(2)) & " x " & cboPaletTipo.SelectedItem(3) 'Me.lNombre.Text = cboProducto.Text & " " & cboMarca.Text & " " & cadPalet 'BasesParaCompatibilidad.DetailedSimpleForm.centerHorizontalyIn(lNombre, panContenido) Dim cadPalet As String cadPalet = Convert.ToString(cboCaja.SelectedItem(2)) & " x " & cboCaja.SelectedItem(3).ToString Me.lNombre.Text = cboProducto.Text & " " & cadPalet & " " & cboMarca.Text & " (" & cboPaletTipo.Text & ")" BasesParaCompatibilidad.Pantalla.centerHorizontalyIn(lNombre, panContenido) Catch ex As Exception End Try End Sub Private Sub cboCaja_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cboCaja.SelectedValueChanged componernombre() End Sub Private Sub btnMarca_Click(sender As System.Object, e As System.EventArgs) Handles btnMarca.Click Dim frm As New frmmarcas BasesParaCompatibilidad.Pantalla.mostrarDialogo(frm) Dim s As New spmarcas s.cargar_marcas(cboMarca, dtb) End Sub Private Sub cboLinea_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cboLinea.SelectedValueChanged Try Dim sp As New spTiposFormatosLineas_TiposFormatos sp.cargarCombo_por_linea(Me.cboFormatoLinea, Me.cboLinea.SelectedValue, dtb) Catch ex As Exception End Try End Sub Private Sub chbFormatoLinea_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chbFormatoLinea.CheckedChanged Me.cboFormatoLinea.Enabled = chbFormatoLinea.Checked End Sub Private Sub btnAddProducto_Click(sender As System.Object, e As System.EventArgs) Handles btnAddProducto.Click Dim frm As New frmEntTiposProductos() BasesParaCompatibilidad.Pantalla.mostrarDialogo(frm) Me.cboProducto.mam_DataSource("TiposProductosSelectCbo", False, dtb) End Sub Private Sub btnAddPalet_Click(sender As System.Object, e As System.EventArgs) Handles btnAddPalet.Click Dim frm As New frmPaletsTipos() BasesParaCompatibilidad.Pantalla.mostrarDialogo(frm) Me.cboPaletTipo.mam_DataSource("PaletsTiposCbo", False, dtb) End Sub Private Sub btnAddCaja_Click(sender As System.Object, e As System.EventArgs) Handles btnAddCaja.Click Dim frm As New frmTiposCajas BasesParaCompatibilidad.Pantalla.mostrarDialogo(frm) Me.cboCaja.mam_DataSource("TiposcajasCbo", False, dtb) End Sub End Class
Imports System.Reflection Imports System.Collections Namespace PogoloDataProvider.Data Public Class DataSetObject #Region "Methods & Subs" Public Function SortObjectArrayList(ByVal Col As ArrayList, ByVal PropertyName As String, Optional ByVal BlnCompareNumeric As Boolean = False) As ArrayList Try ' Sorts any arraylist by the property name you specify Dim colNew As New ArrayList Dim objCurrent As Object Dim objCompare As Object Dim lngCompareIndex As Long Dim strCurrent As Object Dim strCompare As Object Dim blnGreaterValueFound As Boolean For Each objCurrent In Col 'get value of current item... strCurrent = CallByName(objCurrent, PropertyName, vbGet) 'setup for compare loop blnGreaterValueFound = False lngCompareIndex = 0 For Each objCompare In colNew Dim compareInfo As PropertyInfo = objCompare.GetType().GetProperty(PropertyName) strCompare = CallByName(objCompare, PropertyName, vbGet) ' Short If strCompare.GetType Is GetType(Short) Then If Short.Parse(strCompare.ToString()).CompareTo(Short.Parse(strCurrent.ToString())) > 0 Then blnGreaterValueFound = True End If ' Integer ElseIf strCompare.GetType Is GetType(Integer) Then If Integer.Parse(strCompare.ToString()).CompareTo(Integer.Parse(strCurrent.ToString())) > 0 Then blnGreaterValueFound = True End If ' Double ElseIf strCompare.GetType Is GetType(Double) Then If Double.Parse(strCompare.ToString()).CompareTo(Double.Parse(strCurrent.ToString())) > 0 Then blnGreaterValueFound = True End If ' Decimal ElseIf strCompare.GetType Is GetType(Decimal) Then If Decimal.Parse(strCompare.ToString()).CompareTo(Decimal.Parse(strCurrent.ToString())) > 0 Then blnGreaterValueFound = True End If ' DateTime ElseIf strCompare.GetType Is GetType(DateTime) Then If DateTime.Parse(strCompare.ToString()).CompareTo(DateTime.Parse(strCurrent.ToString())) > 0 Then blnGreaterValueFound = True End If Else ' Convert to string If strCompare.ToString().CompareTo(strCurrent.ToString()) > 0 Then blnGreaterValueFound = True End If End If ' Insert in arraylist If blnGreaterValueFound Then colNew.Insert(lngCompareIndex, objCurrent) Exit For End If lngCompareIndex = lngCompareIndex + 1 Next ' If we didn't find something bigger, just add it to the end of the new collection... If blnGreaterValueFound = False Then colNew.Add(objCurrent) End If Next uDataList = colNew Return colNew Catch uDataList = Col Return Col End Try End Function #End Region #Region "Properties" Private uDataList As ArrayList Public Property DataList() As ArrayList Get Return uDataList End Get Set(ByVal Value As ArrayList) uDataList = Value End Set End Property #End Region End Class End Namespace
Imports System.ComponentModel Public Class HexGridCellCtrl #Region "Public enumerations" <Flags()> _ Public Enum CellPossibleValues CellValue_0 = &H1 'Cell could contain the digit '0' CellValue_1 = &H2 CellValue_2 = &H4 CellValue_3 = &H8 CellValue_4 = &H10 CellValue_5 = &H20 CellValue_6 = &H40 CellValue_7 = &H80 CellValue_8 = &H100 CellValue_9 = &H200 CellValue_A = &H400 CellValue_B = &H800 CellValue_C = &H1000 CellValue_D = &H2000 CellValue_E = &H4000 CellValue_F = &H8000 'Cell could contain the digit 'F' End Enum #End Region #Region "Private members" Private _CellValue As Integer = AllPossibleValues() Private _Column As Int16 Private _Row As Int16 Private _Locked As Boolean Private _ValueBrushes(15) As Brush #End Region #Region "Public interface" ''' <summary> ''' The column (1-16) that contains this cell ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks>This value is read left to right ''' </remarks> Public ReadOnly Property Column() As Int16 Get Return _Column End Get End Property ''' <summary> ''' The row (1-16) that contains this cell ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks>This value is read from top to bottom ''' </remarks> Public ReadOnly Property Row() As Int16 Get Return _Row End Get End Property ''' <summary> ''' Returns an integer which defines the remaining possible colour(s) in this cell ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks>Individual <see cref="CellPossibleValues">possible values</see> are combined with ''' a boolean OR operation to generate this value ''' </remarks> Public Property CellValue() As Integer Get Return _CellValue End Get Set(ByVal value As Integer) If _CellValue <> value And Not _Locked Then _CellValue = value RaiseEvent ValueChanged(Me, New HexCell.HexGridValueChangedEventArgs(_CellValue)) Me.Refresh() End If End Set End Property ''' <summary> ''' Returns true if only one of the 16 possible values is left ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public ReadOnly Property SingleValueSelected() As Boolean Get Return (_CellValue = CellPossibleValues.CellValue_0) OrElse (_CellValue = CellPossibleValues.CellValue_1) _ OrElse (_CellValue = CellPossibleValues.CellValue_2) OrElse (_CellValue = CellPossibleValues.CellValue_3) _ OrElse (_CellValue = CellPossibleValues.CellValue_4) OrElse (_CellValue = CellPossibleValues.CellValue_5) _ OrElse (_CellValue = CellPossibleValues.CellValue_6) OrElse (_CellValue = CellPossibleValues.CellValue_7) _ OrElse (_CellValue = CellPossibleValues.CellValue_8) OrElse (_CellValue = CellPossibleValues.CellValue_9) _ OrElse (_CellValue = CellPossibleValues.CellValue_A) OrElse (_CellValue = CellPossibleValues.CellValue_B) _ OrElse (_CellValue = CellPossibleValues.CellValue_C) OrElse (_CellValue = CellPossibleValues.CellValue_D) _ OrElse (_CellValue = CellPossibleValues.CellValue_E) OrElse (_CellValue = CellPossibleValues.CellValue_F) End Get End Property ''' <summary> ''' Returns row,column ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Overrides Function ToString() As String Return _Row.ToString & "," & _Column.ToString End Function ''' <summary> ''' Draws this cell onto the graphics object passed in, with a 4x4 grid of possible values ''' </summary> ''' <param name="g"></param> ''' <param name="rcBounds"></param> ''' <remarks></remarks> Public Sub Drawcell(ByVal g As Graphics, ByVal rcBounds As Rectangle) Dim _WidthFactor As Integer = CInt(rcBounds.Width / 4) Dim _HeightFactor As Integer = CInt(rcBounds.Height / 4) Dim _Row As Integer Dim _Column As Integer With HexGridCellPossibleValuesDecoder.ToBooleanList(_CellValue) Dim rcItem As Rectangle For n As Integer = 1 To 16 _Column = ((n - 1) Mod 4) _Row = (n - 1) \ 4 If SingleValueSelected Then rcItem = rcBounds Else rcItem = New Rectangle(rcBounds.Left + (_Column * _WidthFactor), rcBounds.Top + (_Row * _HeightFactor), _WidthFactor, _HeightFactor) End If g.DrawRectangle(Pens.DimGray, rcItem) 'If the value n is not possible, mark it with an x... rcItem.Inflate(-1, -1) If .Item(n) Then g.FillEllipse(_ValueBrushes(n - 1), rcItem) End If Next End With End Sub ''' <summary> ''' Returns true if the colour is one of the remaining possible colours ''' </summary> ''' <param name="Value"></param> ''' <returns></returns> ''' <remarks></remarks> Public Function IsValuePossible(ByVal Value As CellPossibleValues) As Boolean If (_CellValue And Value) > 0 Then Return True End If End Function ''' <summary> ''' Whether this value can be changed by the user ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Property Locked() As Boolean Get Return _Locked End Get Set(ByVal value As Boolean) _Locked = value End Set End Property #Region "Methods" ''' <summary> ''' Adds the value to the possible values for this cell ''' </summary> ''' <param name="value"></param> ''' <remarks></remarks> Public Sub SetValue(ByVal value As CellPossibleValues) CellValue = _CellValue Or value End Sub ''' <summary> ''' Removes the value from the possible colour values held by this hex cell ''' </summary> ''' <param name="Value"></param> ''' <remarks></remarks> Public Sub UnsetValue(ByVal Value As CellPossibleValues) CellValue = _CellValue And (&HFFFF - Value) End Sub #End Region #Region "Events" Public Delegate Sub HexGridCellValueChangedEvent(ByVal Sender As Object, ByVal e As HexGridValueChangedEventArgs) Public Event ValueChanged As HexGridCellValueChangedEvent #End Region #End Region #Region "Shared Interface" ''' <summary> ''' Returns a value indicating that the cell can hold all possible values ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Shared Function AllPossibleValues() As CellPossibleValues Return CellPossibleValues.CellValue_0 Or CellPossibleValues.CellValue_1 _ Or CellPossibleValues.CellValue_2 Or CellPossibleValues.CellValue_3 _ Or CellPossibleValues.CellValue_4 Or CellPossibleValues.CellValue_5 _ Or CellPossibleValues.CellValue_6 Or CellPossibleValues.CellValue_7 _ Or CellPossibleValues.CellValue_8 Or CellPossibleValues.CellValue_9 _ Or CellPossibleValues.CellValue_A Or CellPossibleValues.CellValue_B _ Or CellPossibleValues.CellValue_C Or CellPossibleValues.CellValue_D _ Or CellPossibleValues.CellValue_E Or CellPossibleValues.CellValue_F End Function #End Region #Region "Public constructor" Public Sub New() ' This call is required by the Windows Form Designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. _ValueBrushes(0) = Brushes.Aqua _ValueBrushes(1) = Brushes.Coral _ValueBrushes(2) = Brushes.Crimson _ValueBrushes(3) = Brushes.DarkKhaki _ValueBrushes(4) = Brushes.Firebrick _ValueBrushes(5) = Brushes.DarkGreen _ValueBrushes(6) = Brushes.Blue _ValueBrushes(7) = Brushes.Fuchsia _ValueBrushes(8) = Brushes.Green _ValueBrushes(9) = Brushes.Yellow _ValueBrushes(10) = Brushes.HotPink _ValueBrushes(11) = Brushes.Gold _ValueBrushes(12) = Brushes.Khaki _ValueBrushes(13) = Brushes.DarkBlue _ValueBrushes(14) = Brushes.LightBlue _ValueBrushes(15) = Brushes.LightSalmon End Sub ''' <summary> ''' Creates a new empty cell at the position specified ''' </summary> ''' <param name="RowIn">The row that this cell is in</param> ''' <param name="ColumnIn">The column that this cell is in</param> ''' <remarks></remarks> Public Sub New(ByVal RowIn As Int16, ByVal ColumnIn As Int16) Me.New() If RowIn < 1 OrElse RowIn > 16 Then Throw New ArgumentException("Row must be between 1 and 16", "RowIn") End If If ColumnIn < 1 OrElse ColumnIn > 16 Then Throw New ArgumentException("Column must be between 1 and 16", "ColumnIn") End If _Row = RowIn _Column = ColumnIn End Sub #End Region #Region "Custom drawing code" Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs) MyBase.OnPaint(e) Drawcell(e.Graphics, Me.ClientRectangle) End Sub #End Region #Region "Mouse events" Protected Overrides Sub OnMouseClick(ByVal e As System.Windows.Forms.MouseEventArgs) MyBase.OnMouseClick(e) If Not SingleValueSelected And Not Locked Then '\\ If over a hex cell item, raise the cell item clicked event Dim _column As Integer, _row As Integer, _index As Integer _column = (1 + CInt(e.X \ CInt(Me.Width / 4))) _row = (1 + CInt(e.Y \ CInt(Me.Height / 4))) _index = (((_row - 1) * 4) + _column) - 1 '\\ Convert the position into the appropriate possible value flag for that position Dim value As CellPossibleValues = CType((2 ^ _index), CellPossibleValues) My.Application.Log.WriteEntry("Column : " & _column.ToString & ", Row : " & _row.ToString & " Value:" & value.ToString) If e.Button = Windows.Forms.MouseButtons.Left Then If IsValuePossible(value) Then If _CellValue = value Then Beep() Exit Sub End If UnsetValue(value) Else SetValue(value) End If Me.Refresh() End If End If End Sub #End Region End Class ''' <summary> ''' Event argument for when a mouse click occurs on one of the coloured counters. ''' </summary> ''' <remarks> ''' </remarks> Public Class HexGridValueChangedEventArgs Inherits EventArgs #Region "Private members" Private _Value As Integer #End Region #Region "Public interface" ''' <summary> ''' Which of the possible values it was clicked over ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public ReadOnly Property Value() As Integer Get Return _Value End Get End Property #End Region #Region "Public constructor" Public Sub New(ByVal ValueIn As Integer) _Value = ValueIn End Sub #End Region End Class Public Class HexGridCellPossibleValuesDecoder ''' <summary> ''' Returns a list of integer (0-15) and whether or not they are a possible value in the values passed in ''' </summary> ''' <param name="Possiblevalues"></param> ''' <returns></returns> ''' <remarks></remarks> Public Shared Function ToBooleanList(ByVal PossibleValues As Integer) As Generic.Dictionary(Of Integer, Boolean) Dim Ret As New Dictionary(Of Integer, Boolean) For n As Integer = 1 To 16 Ret.Add(n, (PossibleValues And CInt(2 ^ (n - 1))) > 0) Next Return Ret End Function End Class ''' <summary> ''' Represents the 64 cells that make up a hex grid ''' </summary> ''' <remarks> ''' </remarks> Public Class HexGridCellCollection #Region "Private members" Private _Cells As New Generic.List(Of HexGridCellCtrl) #End Region #Region "Public interface" Public ReadOnly Property Cell(ByVal Row As Integer, ByVal Column As Integer) As HexGridCellCtrl Get If Row < 1 OrElse Row > 16 Then Throw New ArgumentOutOfRangeException("Row", "Row must be between 1 and 16") End If If Column < 1 OrElse Column > 16 Then Throw New ArgumentOutOfRangeException("Column", "Column must be between 1 and 16") End If Return _Cells.Item(GridPositionToListIndex(Row, Column)) End Get End Property #End Region #Region "Public constructor" ''' <summary> ''' Creates a new empty 16x16 grid of HexGridCell objects ''' </summary> ''' <remarks></remarks> Public Sub New() For _Row As Int16 = 1 To 16 For _Column As Int16 = 1 To 16 _Cells.Add(New HexGridCellCtrl(_Row, _Column)) Next Next End Sub #End Region #Region "Private methods" Private Function GridPositionToListIndex(ByVal Row As Integer, ByVal Column As Integer) As Integer Return ((Row - 1) * 16) + (Column - 1) End Function #End Region End Class
Imports DTIMiniControls Imports DTIServerControls Imports DTITagManager.dsTagger ''' <summary> ''' Control for associating string tags with a particular data row ''' </summary> ''' <remarks></remarks> #If DEBUG Then Public Class TagManager Inherits DTIServerBase #Else <System.ComponentModel.Description("A data-drive tag control. Add or remove tages from a data object set by contentType."), ToolboxData("<{0}:DTITagManager ID=""Sortable"" runat=""server"" contentType=""TagManager""> </{0}:DTITagManager>")> Public Class TagManager Inherits DTIServerBase #End If Protected WithEvents myTagger As New Tagger Public DataFetched As Boolean = False #Region "Properties" Private ReadOnly Property popularTags() As DTI_Content_TagsDataTable Get If Session("popularTags") Is Nothing Then Session("popularTags") = New DTI_Content_TagsDataTable End If Return Session("popularTags") End Get End Property Protected ReadOnly Property dsTagManagement() As dsTagger Get If DataSource Is Nothing Then DataSource = New dsTagger End If Return DataSource End Get End Property Protected ReadOnly Property pivotTable() As DTI_Content_Tag_PivotDataTable Get Return dsTagManagement.DTI_Content_Tag_Pivot End Get End Property Protected ReadOnly Property tagTable() As DTI_Content_TagsDataTable Get Return dsTagManagement.DTI_Content_Tags End Get End Property Private _content_id As Integer = -1 Public Property Content_Id() As Integer Get Return _content_id End Get Set(ByVal value As Integer) _content_id = value raiseDataChanged() End Set End Property Public Property ShowSubmit() As Boolean Get Return myTagger.ShowSubmit End Get Set(ByVal value As Boolean) myTagger.ShowSubmit = value End Set End Property Public Property AddTagText() As String Get Return myTagger.AddTagText End Get Set(ByVal value As String) myTagger.AddTagText = value End Set End Property Public Property CurrentTagText() As String Get Return myTagger.CurrentTagText End Get Set(ByVal value As String) myTagger.CurrentTagText = value End Set End Property Public Property SeparatorCharacter() As String Get Return myTagger.SeparatorCharacter End Get Set(ByVal value As String) myTagger.SeparatorCharacter = value End Set End Property Public Property ShowPopularTags() As Boolean Get Return myTagger.ShowPopularTags End Get Set(ByVal value As Boolean) myTagger.ShowPopularTags = value End Set End Property Public WriteOnly Property popularTagsSet() As List(Of String) Set(ByVal value As List(Of String)) myTagger.popularTagsSet = value End Set End Property Private _maxPopularCount As Integer = 6 Public Property MaxPopularCount() As Integer Get Return _maxPopularCount End Get Set(ByVal value As Integer) _maxPopularCount = value End Set End Property Public Property currentTagsList() As List(Of String) Get Return myTagger.currentTagsList End Get Set(ByVal value As List(Of String)) myTagger.currentTagsList = value End Set End Property Protected ReadOnly Property rowFilter() As String Get Return "Content_Id = " & Content_Id & " and Component_Type = '" & Component_Type & "'" End Get End Property Public Property ValidateOnFormSubmit() As Boolean Get Return myTagger.ValidateOnFormSubmit End Get Set(ByVal value As Boolean) myTagger.ValidateOnFormSubmit = value End Set End Property #End Region #Region "Events" Private Sub TagManager_DataChanged() Handles Me.DataChanged addSQLCall() End Sub Private Sub TagManager_DataReady() Handles Me.DataReady DataFetched = True End Sub Private Sub TagManager_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init If Not mypage.IsPostBack Then If tagTable.Count = 0 Then parallelhelper.addFillDataTable("select * from DTI_Content_Tags where Main_Id = " & MainID, tagTable) End If If popularTags.Count = 0 Then sqlhelper.checkAndCreateTable(popularTags) sqlhelper.checkAndCreateTable(pivotTable) sqlhelper.FillDataTable("select * from DTI_Content_Tags where Main_Id = " & MainID & " and Id in" & "(select top " & MaxPopularCount & " Tag_Id from DTI_Content_Tag_Pivot group by Tag_Id order by " & "count(*) desc)", popularTags) End If addSQLCall() End If End Sub Private Sub TagManager_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Controls.Add(myTagger) If Not mypage.IsPostBack Then If Not DataFetched Then parallelhelper.executeParallelDBCall() myTagger.currentTagsList.Clear() End If End Sub Private Sub TagManager_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender Dim myTagPivots() As DTI_Content_Tag_PivotRow = pivotTable.Select(rowFilter) For Each tagPivot As DTI_Content_Tag_PivotRow In myTagPivots currentTagsList.Add(tagTable.FindById(tagPivot.Tag_Id).Tag_Name) Next Dim myPopTags As New List(Of String) If popularTags.Count < 1 Then Me.ShowPopularTags = False Else For Each tag As DTI_Content_TagsRow In popularTags myPopTags.Add(tag.Tag_Name) Next myTagger.popularTagsSet = myPopTags End If End Sub #End Region #Region "Helper Functions" Private Sub addSQLCall() parallelhelper.addFillDataTable("select * from DTI_Content_Tag_Pivot where " & rowFilter, pivotTable) End Sub Public Sub saveTags() For Each tag As String In currentTagsList Dim tagId As Integer = -1 For Each tagRow As DTI_Content_TagsRow In tagTable If tag.Trim.ToLower = tagRow.Tag_Name.Trim.ToLower Then tagId = tagRow.Id Exit For End If Next If tagId > -1 Then Dim pivotExists As Boolean = False For Each pivot As DTI_Content_Tag_PivotRow In pivotTable If tag.Trim.ToLower = tagTable.FindById(pivot.Tag_Id).Tag_Name.Trim.ToLower AndAlso pivot.Content_Id = Content_Id Then pivotExists = True Exit For End If Next If Not pivotExists Then createPivot(tagId) End If Else Dim newTag As DTI_Content_TagsRow = tagTable.NewDTI_Content_TagsRow newTag.Main_Id = MainID newTag.Tag_Name = tag tagTable.AddDTI_Content_TagsRow(newTag) sqlhelper.Update(tagTable) createPivot(newTag.Id) End If Next Dim myPivots As DTI_Content_Tag_PivotRow() = pivotTable.Select("Content_Id = " & Content_Id) For Each pivot As DTI_Content_Tag_PivotRow In myPivots If Not pivot.RowState = DataRowState.Deleted AndAlso Not pivot.RowState = DataRowState.Detached Then Dim tagExists As Boolean = False For Each tag As String In currentTagsList If tag.Trim.ToLower = tagTable.FindById(pivot.Tag_Id).Tag_Name.Trim.ToLower AndAlso pivot.Content_Id = Content_Id Then tagExists = True Exit For End If Next If Not tagExists Then pivot.Delete() End If End If Next sqlhelper.Update(pivotTable) End Sub Private Sub createPivot(ByVal tag_id As Integer) Dim newPivot As DTI_Content_Tag_PivotRow = pivotTable.NewDTI_Content_Tag_PivotRow newPivot.Component_Type = Component_Type newPivot.Content_Id = Content_Id newPivot.Tag_Id = tag_id pivotTable.AddDTI_Content_Tag_PivotRow(newPivot) End Sub #End Region End Class
' Erweitrungsmethoden für Long Imports System.Runtime.CompilerServices Public Module FunctionalExtensions ''' <summary> ''' Curry- Operator: Bindet den 1. Parameter einer binären Funktion an eine übergebene Konstante, verpackt ihn in ''' einer unären Funktion und gibt diese zurück ''' Curry(f(x,y), a) -> fc(y) äquivalent f(a, y) ''' </summary> ''' <typeparam name="TP1"></typeparam> ''' <typeparam name="TP2"></typeparam> ''' <typeparam name="TRet"></typeparam> ''' <param name="f"></param> ''' <param name="a"></param> ''' <returns></returns> ''' <remarks></remarks> <Extension()> Public Function Curry(Of TP1, TP2, TRet)(f As Func(Of TP1, TP2, TRet), a As TP1) As Func(Of TP2, TRet) Return Function(b) f(a, b) End Function ''' <summary> ''' Curry- Operator für binäre Action ''' </summary> ''' <typeparam name="TP1"></typeparam> ''' <typeparam name="TP2"></typeparam> ''' <param name="f"></param> ''' <param name="a"></param> ''' <returns></returns> ''' <remarks></remarks> <Extension()> Public Function Curry(Of TP1, TP2)(f As Action(Of TP1, TP2), a As TP1) As Action(Of TP2) Return Sub(b) f(a, b) End Function End Module
Imports System.IO Public Class TextResourceConverter Implements IResourceConverter Public ReadOnly Property Extension As String Implements IResourceConverter.Extension Get Return ".txt" End Get End Property Public Function Convert(s As IO.Stream) As Object Implements IResourceConverter.Convert Return New StreamReader(s).ReadToEnd() End Function End Class
Imports System.Reflection Imports System.ComponentModel Imports System.Runtime.Serialization <DataContract()> Public Enum PackageStatus <EnumMember()> <Description("新建立")> NewCreated = 0 'Avilable,end with status 5 or 6 <EnumMember()> <Description("正在装箱")> Begin = 1 <EnumMember()> <Description("未满箱暂停")> Unfull = 2 'Avilable, end with status 5 or 6 <EnumMember()> <Description("从暂停恢复装箱")> Rebegin = 3 <EnumMember()> <Description("从故障恢复装箱")> BeginUnexpect = 4 'close with status 7 <EnumMember()> <Description("正常结束")> Close = 5 <EnumMember()> <Description("未满箱强制结束")> CloseUnfull = 6 <EnumMember()> <Description("结束,期间有中断")> CloseWithException = 7 <EnumMember()> <Description("未满箱暂停,期间有中断")> UnfullExpection = 8 <EnumMember()> <Description("已取消")> Scraped = 999 <EnumMember()> <Description("返工建立")> ReworkNew = 9 <EnumMember()> <Description("返工开始")> ReworkBegin = 10 <EnumMember()> <Description("返工暂停")> ReworkUnfull = 11 <EnumMember()> <Description("返工从暂停恢复装箱")> ReworkRebegin = 12 <EnumMember()> <Description("返工从故障恢复装箱")> ReworkBeginUnexpect = 13 <EnumMember()> <Description("返工结束")> ReworkClose = 14 <EnumMember()> <Description("返工结束,期间有中断")> ReworkCloseWithException = 15 <EnumMember()> <Description("返工未满箱暂停,期间有中断")> ReworkUnfullExpection = 16 <EnumMember()> <Description("模板")> Template = 99 End Enum
Imports System.Globalization Public Class ScriptResultCurator Public logger As log4net.ILog = log4net.LogManager.GetLogger("SRC") Public timer As New Timers.Timer Public Property Datastore As String Public Property Endpoint_Web_Address As String Public Property API_Username As String Public Property API_Password As String Public Property Check_Interval As Integer Public Property UpdateAllJobs As Boolean Public Property LastEndDate As DateTime Public Property IsRunning As Boolean = False Public Property UpdateMapping As Boolean = False Public Property FieldMapping As Dictionary(Of String, Dictionary(Of String, String)) Public Property DateMapping As Dictionary(Of String, Dictionary(Of String, String)) Sub New() 'Read Config Try ReadConfig() Catch ex As Exception logger.Error(ex.Message) End Try Try If Check_Interval > 0 Then 'Set Timer timer.Interval = Check_Interval * 1000 logger.Debug("Check Interval " & Check_Interval & " seconds.") Console.WriteLine("Check Interval " & Check_Interval & " seconds.") AddHandler timer.Elapsed, AddressOf DoWork Else logger.Error("Check_Interval Must Be Greater Than 0. Stopping.") Environment.Exit(0) End If Catch ex As Exception logger.Error(ex.Message) End Try End Sub Sub Start() logger = log4net.LogManager.GetLogger("SRC") Console.WriteLine("Script Result Curator Started.") logger.Info("Script Result Curator Started.") logger.Debug("Timer started.") Try 'Start work now DoWork() 'Start Timer timer.Start() Catch ex As Exception logger.Error(ex.Message) End Try End Sub Public Sub ReadConfig() logger.Debug("Read Config Called.") Console.WriteLine("Reading Config.") If IO.File.Exists(My.Application.Info.DirectoryPath & "\SRCConfig.yml") Then Dim ymlds = New YamlDotNet.Serialization.Deserializer Dim fileread = IO.File.OpenText(My.Application.Info.DirectoryPath & "\SRCConfig.yml") Try Dim SRCConfig = ymlds.Deserialize(Of SRC_Config)(fileread) fileread.Close() logger.Debug("Successfully Read Config.") Datastore = SRCConfig.DataStore_Server Endpoint_Web_Address = SRCConfig.Endpoint_Web_Server API_Username = SRCConfig.API_Username API_Password = SRCConfig.API_Password Check_Interval = SRCConfig.Check_Interval UpdateAllJobs = SRCConfig.UpdateAllJobs UpdateMapping = SRCConfig.UpdateMapping If DateTime.TryParse(SRCConfig.LastEndDate, LastEndDate) Then 'Good Else If DateTime.TryParseExact(SRCConfig.LastEndDate, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, LastEndDate) Then 'Good Else logger.Error("Couldn't read LastEndDate from config. Setting to current time. ") LastEndDate = Now End If End If Catch ex As Exception logger.Error("Read Config Error: " & ex.Message) Console.WriteLine("Read Config Error: " & ex.Message) Debug.WriteLine(ex.Message) End Try Else logger.Error("Config File Doesn't Exist....Exiting..") Environment.Exit(0) End If End Sub Public Sub ReadMappingConfig() logger.Debug("Read Mapping Config Called.") Console.WriteLine("Reading Mapping Config.") If IO.File.Exists(My.Application.Info.DirectoryPath & "\MappingConfig.yml") Then Dim ymlds = New YamlDotNet.Serialization.Deserializer Dim fileread = IO.File.OpenText(My.Application.Info.DirectoryPath & "\MappingConfig.yml") Try Dim MapConfig = ymlds.Deserialize(Of List(Of Mapping))(fileread) fileread.Close() logger.Debug("Successfully Read Mapping Config.") Dim mapdict As New Dictionary(Of String, Dictionary(Of String, String)) Dim datemap As New Dictionary(Of String, Dictionary(Of String, String)) For Each item In MapConfig mapdict.Add(item.Script_Type, item.Map) If Not item.Date Is Nothing Then datemap.Add(item.Script_Type, item.Date) End If Next FieldMapping = mapdict DateMapping = datemap Catch ex As Exception logger.Error("Read Mapping Config Error: " & ex.Message) Console.WriteLine("Read Mapping Config Error: " & ex.Message) UpdateMapping = False End Try Else Debug.WriteLine("No MappingConfig Found.") End If End Sub Public Sub UpdateConfig() logger.Debug("Update Config Called.") Console.WriteLine("Updating Config.") Dim y = New YamlDotNet.Serialization.Serializer Try Dim SRCConfig = New SRC_Config SRCConfig.DataStore_Server = Datastore SRCConfig.Endpoint_Web_Server = Endpoint_Web_Address SRCConfig.API_Username = API_Username SRCConfig.API_Password = API_Password SRCConfig.Check_Interval = Check_Interval SRCConfig.LastEndDate = LastEndDate.ToString("yyyy-MM-dd hh:mm:ss tt") SRCConfig.UpdateAllJobs = UpdateAllJobs SRCConfig.UpdateMapping = UpdateMapping Dim filewrite As IO.StreamWriter = IO.File.CreateText(My.Application.Info.DirectoryPath & "\SRCConfig.yml") y.Serialize(filewrite, SRCConfig) filewrite.Close() logger.Debug("Successfully Updated Config.") Catch ex As Exception logger.Error("Update Config Error: " & ex.Message) Debug.WriteLine(ex.Message) End Try End Sub Public Class SRC_Config Public Property DataStore_Server As String Public Property Endpoint_Web_Server As String Public Property API_Username As String Public Property API_Password As String Public Property Check_Interval As Integer Public Property UpdateAllJobs As Boolean Public Property LastEndDate As String Public Property UpdateMapping As Boolean End Class Public Class Mapping Public Property Script_Type As String Public Property Map As Dictionary(Of String, String) Public Property [Date] As Dictionary(Of String, String) End Class Public Sub DoWork() logger = log4net.LogManager.GetLogger("SRC") If IsRunning = True Then 'It's running skip this timer. logger.Debug("SRC is busy...Skipping this timer..") Else IsRunning = True logger.Debug("Do Work - Start") 'Reload Config Try ReadConfig() Catch ex As Exception logger.Error(ex.Message) End Try Try Dim fepclient As New FEPRestClient.Client fepclient.Username = API_Username fepclient.Password = API_Password fepclient.Server = Endpoint_Web_Address fepclient.IgnoreSSL = True Dim fepauth As FEPRestClient.Models.Response.ApiResponse(Of FEPRestClient.Models.Authentication.Token) Dim retries As Integer = 0 If fepclient.IsAuthenticated = False Then reauth: fepauth = fepclient.Authenticate() If Not fepauth.Success Then Select Case True Case fepauth.Error.Message.Contains("Access Denied. Bad username or password.") logger.Error("FEP Failure: " & fepauth.Error.Message) Console.WriteLine(fepauth.Error.Message) logger.Error("Invalid Settings, Stopping.") Console.WriteLine("Invalid Settings, Stopping.") Environment.Exit(0) Case fepauth.Error.Message.Contains("Object reference not set to an instance of an object.") logger.Error("FEP Failure: " & fepauth.Error.Message & ". This is commonly caused by an invalid hostname/IP for the FEP Server.") Console.WriteLine(fepauth.Error.Message) logger.Error("Invalid Settings, Stopping.") Console.WriteLine("Invalid Settings, Stopping.") Environment.Exit(0) Case Else 'Pause .5 seconds to see if the issue clears up logger.Debug("FEP Failure: " & fepauth.Error.Message & ". Not critical, waiting .5 seconds and trying again.") Threading.Thread.Sleep(500) retries += 1 If Not retries = 15 Then GoTo reauth Else logger.Error("FEP Failure: " & fepauth.Error.Message & ". Tried 15 times with no success. Returning to caller code.") Console.WriteLine(fepauth.Error.Message) IsRunning = False Return End If End Select End If End If Dim datetimefilter As String If UpdateAllJobs = True Then Console.WriteLine("Updating all job results....This could take some time...") logger.Debug("Updating all job results....This could take some time...") datetimefilter = "" ClearUpdateAll() Else 'API is looking for US style, so use format to send correct date style. datetimefilter = LastEndDate.ToString("MM/dd/yyyy hh:mm:ss tt") Console.WriteLine("Searching for jobs with End Date >= " & datetimefilter) logger.Debug("Searching for jobs with End Date >= " & datetimefilter) End If 'Update EndDateFilter to NOW SetEndDate() Dim esi As New ES_Interfacer(Datastore) 'Get jobs and do work Dim mapping = Nothing If UpdateMapping = True Then logger.Debug("UpdateMapping Enabled. Read Mapping Config") ReadMappingConfig() End If GetJobs(Me, fepclient, esi, datetimefilter) Catch ex As Exception logger.Error(ex.Message) Return End Try End If End Sub Public Sub SetEndDate() logger = log4net.LogManager.GetLogger("SRC") LastEndDate = Now logger.Debug("Setting LastEndDate to: " & Now.ToString("yyyy-MM-dd hh:mm:ss tt")) 'Save Changes Try UpdateConfig() Catch ex As Exception logger.Error(ex.Message) End Try End Sub Public Sub ClearUpdateAll() logger = log4net.LogManager.GetLogger("SRC") UpdateAllJobs = False logger.Debug("Setting UpdateAllJobs to False.") 'Save Changes Try UpdateConfig() Catch ex As Exception logger.Error(ex.Message) End Try End Sub End Class
Imports System Imports System.Text Public Class CodigoBarra Private _sName As String = "EAN13" Private _fMinimumAllowableScale As Single = 0.8F Private _fMaximumAllowableScale As Single = 2.0F Private _fWidth As Single = 37.29F Private _fHeight As Single = 25.93F Private _fFontSize As Single = 8.0F Private _fScale As Single = 1.0F Private _aOddLeft As String() = {"0001101", "0011001", "0010011", "0111101", "0100011", "0110001", "0101111", "0111011", "0110111", "0001011"} Private _aEvenLeft As String() = {"0100111", "0110011", "0011011", "0100001", "0011101", "0111001", "0000101", "0010001", "0001001", "0010111"} Private _aRight As String() = {"1110010", "1100110", "1101100", "1000010", "1011100", "1001110", "1010000", "1000100", "1001000", "1110100"} Private _sQuiteZone As String = "000000000" Private _sLeadTail As String = "101" Private _sSeparator As String = "01010" Private _sCountryCode As String = "00" Private _sManufacturerCode As String Private _sProductCode As String Private _sChecksumDigit As String Public Sub New() Me.CountryCode = "779" Me.ManufacturerCode = "1293" End Sub Public Sub New(ByVal mfgNumber As String, ByVal productId As String) Me.CountryCode = "00" Me.ManufacturerCode = mfgNumber Me.ProductCode = productId Me.CalculateChecksumDigit() End Sub Public Sub New(ByVal countryCode As String, ByVal mfgNumber As String, ByVal productId As String) Me.CountryCode = countryCode Me.ManufacturerCode = mfgNumber Me.ProductCode = productId Me.CalculateChecksumDigit() End Sub Public Sub New(ByVal countryCode As String, ByVal mfgNumber As String, ByVal productId As String, ByVal checkDigit As String) Me.CountryCode = countryCode Me.ManufacturerCode = mfgNumber Me.ProductCode = productId Me.ChecksumDigit = checkDigit End Sub Public Sub DrawEan13Barcode(ByVal g As System.Drawing.Graphics, ByVal pt As System.Drawing.Point) Dim width As Single = Me.Width * Me.Scale Dim height As Single = Me.Height * Me.Scale Dim lineWidth As Single = width / 113.0F Dim gs As System.Drawing.Drawing2D.GraphicsState = g.Save g.PageUnit = System.Drawing.GraphicsUnit.Millimeter g.PageScale = 1 Dim brush As System.Drawing.SolidBrush = New System.Drawing.SolidBrush(System.Drawing.Color.Black) Dim xPosition As Single = 0 Dim strbEAN13 As System.Text.StringBuilder = New System.Text.StringBuilder Dim sbTemp As System.Text.StringBuilder = New System.Text.StringBuilder Dim xStart As Single = pt.X Dim yStart As Single = pt.Y Dim xEnd As Single = 0 Dim font As System.Drawing.Font = New System.Drawing.Font("Arial", Me._fFontSize * Me.Scale) Me.CalculateChecksumDigit() sbTemp.AppendFormat("{0}{1}{2}{3}", Me.CountryCode, Me.ManufacturerCode, Me.ProductCode, Me.ChecksumDigit) Dim sTemp As String = sbTemp.ToString Dim sLeftPattern As String = "" sLeftPattern = ConvertLeftPattern(sTemp.Substring(0, 7)) strbEAN13.AppendFormat("{0}{1}{2}{3}{4}{1}{0}", Me._sQuiteZone, Me._sLeadTail, sLeftPattern, Me._sSeparator, ConvertToDigitPatterns(sTemp.Substring(7), Me._aRight)) Dim sTempUPC As String = strbEAN13.ToString Dim fTextHeight As Single = g.MeasureString(sTempUPC, font).Height Dim i As Integer = 0 While i < strbEAN13.Length If sTempUPC.Substring(i, 1) = "1" Then If xStart = pt.X Then xStart = xPosition End If If (i > 12 AndAlso i < 55) OrElse (i > 57 AndAlso i < 101) Then g.FillRectangle(brush, xPosition, yStart, lineWidth, height - fTextHeight) Else g.FillRectangle(brush, xPosition, yStart, lineWidth, height) End If End If xPosition += lineWidth xEnd = xPosition System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1) End While xPosition = xStart - g.MeasureString(Me.CountryCode.Substring(0, 1), font).Width Dim yPosition As Single = yStart + (height - fTextHeight) g.DrawString(sTemp.Substring(0, 1), font, brush, New System.Drawing.PointF(xPosition, yPosition)) xPosition += (g.MeasureString(sTemp.Substring(0, 1), font).Width + 43 * lineWidth) - (g.MeasureString(sTemp.Substring(1, 6), font).Width) g.DrawString(sTemp.Substring(1, 6), font, brush, New System.Drawing.PointF(xPosition, yPosition)) xPosition += g.MeasureString(sTemp.Substring(1, 6), font).Width + (11 * lineWidth) g.DrawString(sTemp.Substring(7), font, brush, New System.Drawing.PointF(xPosition, yPosition)) g.Restore(gs) End Sub Public Function CreateBitmap() As System.Drawing.Bitmap Dim tempWidth As Single = (Me.Width * Me.Scale) * 100 Dim tempHeight As Single = (Me.Height * Me.Scale) * 100 Dim bmp As System.Drawing.Bitmap = New System.Drawing.Bitmap(CType(tempWidth, Integer), CType(tempHeight, Integer)) Dim g As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmp) Me.DrawEan13Barcode(g, New System.Drawing.Point(0, 0)) g.Dispose() Return bmp End Function Private Function ConvertLeftPattern(ByVal sLeft As String) As String Select Case sLeft.Substring(0, 1) Case "0" Return CountryCode0(sLeft.Substring(1)) Case "1" Return CountryCode1(sLeft.Substring(1)) Case "2" Return CountryCode2(sLeft.Substring(1)) Case "3" Return CountryCode3(sLeft.Substring(1)) Case "4" Return CountryCode4(sLeft.Substring(1)) Case "5" Return CountryCode5(sLeft.Substring(1)) Case "6" Return CountryCode6(sLeft.Substring(1)) Case "7" Return CountryCode7(sLeft.Substring(1)) Case "8" Return CountryCode8(sLeft.Substring(1)) Case "9" Return CountryCode9(sLeft.Substring(1)) Case Else Return "" End Select End Function Private Function CountryCode0(ByVal sLeft As String) As String Return ConvertToDigitPatterns(sLeft, Me._aOddLeft) End Function Private Function CountryCode1(ByVal sLeft As String) As String Dim sReturn As System.Text.StringBuilder = New StringBuilder sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(0, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(1, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(2, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(3, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(4, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(5, 1), Me._aEvenLeft)) Return sReturn.ToString End Function Private Function CountryCode2(ByVal sLeft As String) As String Dim sReturn As System.Text.StringBuilder = New StringBuilder sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(0, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(1, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(2, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(3, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(4, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(5, 1), Me._aEvenLeft)) Return sReturn.ToString End Function Private Function CountryCode3(ByVal sLeft As String) As String Dim sReturn As System.Text.StringBuilder = New StringBuilder sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(0, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(1, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(2, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(3, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(4, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(5, 1), Me._aOddLeft)) Return sReturn.ToString End Function Private Function CountryCode4(ByVal sLeft As String) As String Dim sReturn As System.Text.StringBuilder = New StringBuilder sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(0, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(1, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(2, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(3, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(4, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(5, 1), Me._aEvenLeft)) Return sReturn.ToString End Function Private Function CountryCode5(ByVal sLeft As String) As String Dim sReturn As System.Text.StringBuilder = New StringBuilder sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(0, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(1, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(2, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(3, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(4, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(5, 1), Me._aEvenLeft)) Return sReturn.ToString End Function Private Function CountryCode6(ByVal sLeft As String) As String Dim sReturn As System.Text.StringBuilder = New StringBuilder sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(0, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(1, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(2, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(3, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(4, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(5, 1), Me._aOddLeft)) Return sReturn.ToString End Function Private Function CountryCode7(ByVal sLeft As String) As String Dim sReturn As System.Text.StringBuilder = New StringBuilder sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(0, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(1, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(2, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(3, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(4, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(5, 1), Me._aEvenLeft)) Return sReturn.ToString End Function Private Function CountryCode8(ByVal sLeft As String) As String Dim sReturn As System.Text.StringBuilder = New StringBuilder sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(0, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(1, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(2, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(3, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(4, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(5, 1), Me._aOddLeft)) Return sReturn.ToString End Function Private Function CountryCode9(ByVal sLeft As String) As String Dim sReturn As System.Text.StringBuilder = New StringBuilder sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(0, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(1, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(2, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(3, 1), Me._aOddLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(4, 1), Me._aEvenLeft)) sReturn.Append(ConvertToDigitPatterns(sLeft.Substring(5, 1), Me._aOddLeft)) Return sReturn.ToString End Function Private Function ConvertToDigitPatterns(ByVal inputNumber As String, ByVal patterns As String()) As String Dim sbTemp As System.Text.StringBuilder = New StringBuilder Dim iIndex As Integer = 0 Dim i As Integer = 0 While i < inputNumber.Length iIndex = Convert.ToInt32(inputNumber.Substring(i, 1)) sbTemp.Append(patterns(iIndex)) System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1) End While Return sbTemp.ToString End Function Public Sub CalculateChecksumDigit() Dim sTemp As String = Me.CountryCode + Me.ManufacturerCode + Me.ProductCode Dim iSum As Integer = 0 Dim iDigit As Integer = 0 Dim i As Integer = sTemp.Length While i >= 1 iDigit = Convert.ToInt32(sTemp.Substring(i - 1, 1)) If i Mod 2 = 0 Then iSum += iDigit * 3 Else iSum += iDigit * 1 End If System.Math.Max(System.Threading.Interlocked.Decrement(i), i + 1) End While Dim iCheckSum As Integer = (10 - (iSum Mod 10)) Mod 10 Me.ChecksumDigit = iCheckSum.ToString End Sub Public ReadOnly Property Name() As String Get Return _sName End Get End Property Public ReadOnly Property MinimumAllowableScale() As Single Get Return _fMinimumAllowableScale End Get End Property Public ReadOnly Property MaximumAllowableScale() As Single Get Return _fMaximumAllowableScale End Get End Property Public ReadOnly Property Width() As Single Get Return _fWidth End Get End Property Public ReadOnly Property Height() As Single Get Return _fHeight End Get End Property Public ReadOnly Property FontSize() As Single Get Return _fFontSize End Get End Property Public Property Scale() As Single Get Return _fScale End Get Set(ByVal value As Single) If value < Me._fMinimumAllowableScale OrElse value > Me._fMaximumAllowableScale Then Throw New Exception("Scale value out of allowable range. Value must be between " + Me._fMinimumAllowableScale.ToString + " and " + Me._fMaximumAllowableScale.ToString) End If _fScale = value End Set End Property Public Property CountryCode() As String Get Return _sCountryCode End Get Set(ByVal value As String) While value.Length < 2 value = "0" + value End While _sCountryCode = value End Set End Property Public Property ManufacturerCode() As String Get Return _sManufacturerCode End Get Set(ByVal value As String) _sManufacturerCode = value End Set End Property Public Property ProductCode() As String Get Return _sProductCode End Get Set(ByVal value As String) _sProductCode = value End Set End Property Public Property ChecksumDigit() As String Get Return _sChecksumDigit End Get Set(ByVal value As String) Dim iValue As Integer = Convert.ToInt32(value) If iValue < 0 OrElse iValue > 9 Then Throw New Exception("The Check Digit mst be between 0 and 9.") End If _sChecksumDigit = value End Set End Property End Class
'Project: StreamReader 'Author: Anthony DePinto 'Date: Fall 2014 'Description: ' Read a file sequentially and display contents based on ' account type specified by user (credit, debit or zero balances). ' Student information ' ------------------- ' Author: Keith Smith ' Date: 17 October 2018 Option Explicit On Option Strict On Imports System.IO ' using classes from this namespace Public Class CreditInquiry ' Declare variables Dim FileNameString As String ' Declare enumerables Enum AccountType DEBIT CREDIT ZERO End Enum ' Button subroutines Private Sub debitBalancesButton_Click(sender As Object, e As EventArgs) Handles debitBalancesButton.Click DisplayAccounts(AccountType.DEBIT) End Sub Private Sub creditBalancesButton_Click(sender As Object, e As EventArgs) Handles creditBalancesButton.Click DisplayAccounts(AccountType.CREDIT) End Sub Private Sub zeroBalancesButton_Click(sender As Object, e As EventArgs) Handles zeroBalancesButton.Click DisplayAccounts(AccountType.ZERO) End Sub ' Menu subroutines Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click ' Declare objects Dim FileDialogResult As DialogResult ' Store what button clicked ' Show file open dialog block Using FileOpenDialogResult As New OpenFileDialog ' Show file open dialog FileDialogResult = FileOpenDialogResult.ShowDialog() ' Get file name from dialog selection FileNameString = FileOpenDialogResult.FileName End Using If FileDialogResult <> Windows.Forms.DialogResult.Cancel Then ' Enable buttons debitBalancesButton.Enabled = True creditBalancesButton.Enabled = True zeroBalancesButton.Enabled = True ' Could load into a data structure here to be used ' in multiple other functions/subroutines ' Example: when searching for something, want to stop reading file ' once searched item is found End If End Sub Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click ' Display the about screen AboutBoxForm.Show() End Sub Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click ' Exit Application Me.Close() End Sub ' Subroutines and functions Private Sub DisplayAccounts(ByVal inAccountType As AccountType) ' Declare stream reader Dim AccountStreamReader As StreamReader ' Try to open the file Try ' Create new stream reader object AccountStreamReader = New StreamReader(FileNameString, True) ' Clear text box in anticipation of writing new data ' (don't clear if file open fails) accountsTextBox.Clear() ' Create header for text box before account information is added ' to text box accountsTextBox.Text &= "The relevant accounts are:" & vbCrLf ' Read and display account information ' Alt: ' Do While Not AccountStreamReader.EndOfStream Do Until AccountStreamReader.EndOfStream ' Local variable declaractions Dim LineString As String = AccountStreamReader.ReadLine Dim TempAccount() As String = LineString.Split(CChar(",")) Dim TempAccountValue As Decimal ' Try to parse account balance data from line ' read in from the file Try TempAccountValue = Convert.ToDecimal(TempAccount(3)) Catch ex As Exception MessageBox.Show("Error converting account balance", "Balance conversion error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End Try ' Test read account balance information to ' determine if the account should be displayed ' to the end user If ShouldDisplay(TempAccountValue, inAccountType) Then ' Format temporary account information and append to accounts text box accountsTextBox.Text &= String.Format("{0}{5}{1}{5}{2}{5}{3:c}{4}", TempAccount(0), TempAccount(1), TempAccount(2), TempAccountValue, vbCrLf, vbTab) End If Loop Catch ex As IOException ' Display error message if IOException occurs MessageBox.Show("Error reading file", "IO Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Finally ' Try to close file Try AccountStreamReader.Close() Catch ex As NullReferenceException MessageBox.Show("Error closing file", "IO Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End Try End Try End Sub Function ShouldDisplay(ByVal inAccountBalance As Decimal, ByVal _inAccountType As AccountType) As Boolean ' Logic to return true/false based on account type and account balance value If _inAccountType = AccountType.DEBIT AndAlso inAccountBalance > 0D Then Return True ElseIf _inAccountType = AccountType.CREDIT AndAlso inAccountBalance < 0D Then Return True ElseIf _inAccountType = AccountType.ZERO AndAlso inAccountBalance = 0D Then Return True Else Return False End If End Function End Class ' Credit Inquiry
' Instat+R ' Copyright (C) 2015 ' ' This program is free software: you can redistribute it and/or modify ' it under the terms of the GNU General Public License as published by ' the Free Software Foundation, either version 3 of the License, or ' (at your option) any later version. ' ' This program is distributed in the hope that it will be useful, ' but WITHOUT ANY WARRANTY; without even the implied warranty of ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ' GNU General Public License for more details. ' ' You should have received a copy of the GNU General Public License k ' along with this program. If not, see <http://www.gnu.org/licenses/>. Imports instat.Translations Imports instat.RSyntax Public Class ucrDistributions Public lstAllDistributions As List(Of Distribution) Public lstCurrentDistributions As List(Of Distribution) Public strDistributionType As String Public clsCurrDistribution As Distribution Public bDistributionsSet As Boolean Public clsCurrRFunction As RFunction Public strDataType As String Public Sub New() ' This call is required by the designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. lstAllDistributions = New List(Of Distribution) lstCurrentDistributions = New List(Of Distribution) strDistributionType = "" clsCurrDistribution = New Distribution bDistributionsSet = False clsCurrRFunction = New RFunction strDataType = "" CreateDistributions() End Sub Private Sub ucrDistributions_Load(sender As Object, e As EventArgs) Handles MyBase.Load End Sub Public Sub AddParameter(strArgumentName As String, strArgumentValue As String) Dim clsTempOp As ROperator Dim i As Integer clsTempOp = New ROperator clsTempOp.SetOperation("/") If clsCurrDistribution.strNameTag = "Exponential" AndAlso strArgumentName = "mean" Then clsTempOp.SetParameter(True, strValue:=1) clsTempOp.SetParameter(False, strValue:=strArgumentValue) clsCurrRFunction.AddParameter("rate", clsROperatorParameter:=clsTempOp) ElseIf clsCurrDistribution.strNameTag = "Gamma_With_Shape_and_Mean" AndAlso (strArgumentName = "shape" OrElse strArgumentName = "mean") Then If strArgumentName = "shape" Then clsCurrRFunction.AddParameter(strArgumentName, strArgumentValue) i = clsCurrRFunction.clsParameters.FindIndex(Function(x) x.strArgumentName = "mean") If i <> -1 Then clsTempOp.SetParameter(True, strValue:=clsCurrRFunction.clsParameters(i).strArgumentValue) clsTempOp.SetParameter(False, strValue:=strArgumentValue) clsCurrRFunction.AddParameter("scale", clsROperatorParameter:=clsTempOp) clsCurrRFunction.RemoveParameterByName("mean") End If ElseIf strArgumentName = "mean" Then i = clsCurrRFunction.clsParameters.FindIndex(Function(x) x.strArgumentName = "shape") If i = -1 Then clsCurrRFunction.AddParameter(strArgumentName, strArgumentValue) Else clsTempOp.SetParameter(True, strValue:=strArgumentValue) clsTempOp.SetParameter(False, strValue:=clsCurrRFunction.clsParameters(i).strArgumentValue) clsCurrRFunction.AddParameter("scale", clsROperatorParameter:=clsTempOp) End If End If Else clsCurrRFunction.AddParameter(strArgumentName, strArgumentValue) End If End Sub Public Sub SetRDistributions() strDistributionType = "RFunctions" SetDistributions() End Sub Public Sub SetPDistributions() strDistributionType = "PFunctions" SetDistributions() End Sub Public Sub SetQDistributions() strDistributionType = "QFunctions" SetDistributions() End Sub Public Sub SetDDistributions() strDistributionType = "DFunctions" SetDistributions() End Sub Public Sub SetGLMDistributions() strDistributionType = "GLMFunctions" SetDistributions() End Sub Private Sub SetDistributions() Dim bUse As Boolean lstCurrentDistributions.Clear() cboDistributions.Items.Clear() For Each Dist In lstAllDistributions bUse = False Select Case strDistributionType Case "RFunctions" bUse = (Dist.strRFunctionName <> "") Case "PFunctions" bUse = (Dist.strPFunctionName <> "") Case "QFunctions" bUse = (Dist.strQFunctionName <> "") Case "DFunctions" bUse = (Dist.strDFunctionName <> "") Case "GLMFunctions" If (Dist.strGLMFunctionName <> "") Then Select Case strDataType Case "numeric" If Dist.bNumeric Then bUse = True End If Case "positive integer" If Dist.bPositiveInt Then bUse = True End If Case "two level factor" If Dist.bTwoLevelFactor Then bUse = True End If End Select End If End Select If Dist.bIncluded And bUse Then lstCurrentDistributions.Add(Dist) cboDistributions.Items.Add(translate(Dist.strNameTag)) End If Next If cboDistributions.Items.Count > 0 Then cboDistributions.SelectedIndex = 0 End If End Sub Public Sub CreateDistributions() Dim clsNormalDist As New Distribution Dim clsExponentialDist As New Distribution Dim clsGeometricDist As New Distribution Dim clsExtremeValueDist As New Distribution Dim clsWeibullDist As New Distribution Dim clsUniformDist As New Distribution Dim clsBernouliDist As New Distribution Dim clsBinomialDist As New Distribution Dim clsPoissonDist As New Distribution Dim clsVonnMisesDist As New Distribution Dim clsCategoricalDist As New Distribution Dim clsGamma As New Distribution Dim clsGammaWithZerosDist As New Distribution Dim clsGammaWithShapeandScale As New Distribution Dim clsGammaWithShapeandMean As New Distribution Dim clsGammaWithShapeandRate As New Distribution Dim clsInverseGaussianDist As New Distribution Dim clsQuasiDist As New Distribution Dim clsQuasibinomialDist As New Distribution Dim clsQuasipoissonDist As New Distribution ' Normal distribution clsNormalDist.strNameTag = "Normal" clsNormalDist.strRFunctionName = "rnorm" clsNormalDist.strPFunctionName = "pnorm" clsNormalDist.strQFunctionName = "qnorm" clsNormalDist.strDFunctionName = "dnorm" clsNormalDist.strGLMFunctionName = "gaussian" clsNormalDist.bNumeric = True clsNormalDist.AddParameter("mean", "Mean", 0) clsNormalDist.AddParameter("sd", "Standard_deviation", 1) lstAllDistributions.Add(clsNormalDist) ' Exponential Distribution clsExponentialDist.strNameTag = "Exponential" clsExponentialDist.strRFunctionName = "rexp" clsExponentialDist.strPFunctionName = "pexp" clsExponentialDist.strQFunctionName = "qexp" clsExponentialDist.strDFunctionName = "dexp" clsExponentialDist.AddParameter("mean", "Mean", 1) lstAllDistributions.Add(clsExponentialDist) ' Geometric Distribution clsGeometricDist.strNameTag = "Geometric" clsGeometricDist.strRFunctionName = "rgeom" clsGeometricDist.strPFunctionName = "pgeom" clsGeometricDist.strQFunctionName = "qgeom" clsGeometricDist.strDFunctionName = "dgeom" clsGeometricDist.AddParameter("prob", "Probability", 0.5) lstAllDistributions.Add(clsGeometricDist) ' Extreme Value Distribution clsExtremeValueDist.strNameTag = "Extreme_Value" clsExtremeValueDist.strRFunctionName = "revd" clsExtremeValueDist.strPFunctionName = "pevd" clsExtremeValueDist.strQFunctionName = "qqevd" clsExtremeValueDist.strDFunctionName = "devd" clsExtremeValueDist.AddParameter("shape", "Shape", 0) clsExtremeValueDist.AddParameter("scale", "Scale", 1) clsExtremeValueDist.AddParameter("loc", "Location", 0) lstAllDistributions.Add(clsExtremeValueDist) ' Weibull Distribution clsWeibullDist.strNameTag = "Weibull" clsWeibullDist.strRFunctionName = "rweibull" clsWeibullDist.strPFunctionName = "pweibull" clsWeibullDist.strQFunctionName = "qweibull" clsWeibullDist.strDFunctionName = "dweibull" clsWeibullDist.AddParameter("shape", "Shape") clsWeibullDist.AddParameter("scale", "Scale", 1) lstAllDistributions.Add(clsWeibullDist) 'Uniform Distribution clsUniformDist.strNameTag = "Uniform" clsUniformDist.strRFunctionName = "runif" clsUniformDist.strPFunctionName = "punif" clsUniformDist.strQFunctionName = "qunif" clsUniformDist.strDFunctionName = "dunif" clsUniformDist.AddParameter("min", "Minimum", 0) clsUniformDist.AddParameter("max", "Maximum", 1) lstAllDistributions.Add(clsUniformDist) 'Bernouli Distribution clsBernouliDist.strNameTag = "Bernouli" clsBernouliDist.strRFunctionName = "rbinom" clsBernouliDist.strPFunctionName = "pbinom" clsBernouliDist.strQFunctionName = "qbinom" clsBernouliDist.strDFunctionName = "dbinom" clsBernouliDist.AddParameter("prob", "Probability", 0.5) lstAllDistributions.Add(clsBernouliDist) 'Binomial Distribution clsBinomialDist.strNameTag = "Binomial" clsBinomialDist.strRFunctionName = "rbinom" clsBinomialDist.strPFunctionName = "pbinom" clsBinomialDist.strQFunctionName = "qbinom" clsBinomialDist.strDFunctionName = "dbinom" clsBinomialDist.strGLMFunctionName = "binomial" clsBinomialDist.bTwoLevelFactor = True clsBinomialDist.AddParameter("size", "Number", 1) clsBinomialDist.AddParameter("prob", "Probability", 0.5) lstAllDistributions.Add(clsBinomialDist) 'poisson Distribution clsPoissonDist.strNameTag = "Poisson" clsPoissonDist.strRFunctionName = "rpois" clsPoissonDist.strPFunctionName = "ppois" clsPoissonDist.strQFunctionName = "qpois" clsPoissonDist.strDFunctionName = "dpois" clsPoissonDist.strGLMFunctionName = "poisson" clsPoissonDist.bPositiveInt = True clsPoissonDist.AddParameter("lambda", "Mean", 1) lstAllDistributions.Add(clsPoissonDist) ' von mises distribution clsVonnMisesDist.strNameTag = "von_mises" clsVonnMisesDist.strRFunctionName = "rvonmises" clsVonnMisesDist.strPFunctionName = "pvonmises" clsVonnMisesDist.strQFunctionName = "qvonmises" clsVonnMisesDist.strDFunctionName = "dvonmises" clsVonnMisesDist.AddParameter("mu", "Mean", "pi") clsVonnMisesDist.AddParameter("kappa", "Kappa", 0) lstAllDistributions.Add(clsVonnMisesDist) 'TODO Categorical distribution clsCategoricalDist.strNameTag = "Categorical" clsCategoricalDist.strRFunctionName = "" clsCategoricalDist.strPFunctionName = "" clsCategoricalDist.strQFunctionName = "" clsCategoricalDist.strDFunctionName = "" clsCategoricalDist.AddParameter("", "", "") clsCategoricalDist.AddParameter("", "", ) lstAllDistributions.Add(clsCategoricalDist) 'Gamma With Shape and Scale distribution clsGammaWithShapeandScale.strNameTag = "Gamma_With_Shape_and_Scale" clsGammaWithShapeandScale.strRFunctionName = "rgamma" clsGammaWithShapeandScale.strPFunctionName = "pgamma" clsGammaWithShapeandScale.strQFunctionName = "qgamma" clsGammaWithShapeandScale.strDFunctionName = "dgamma" clsGammaWithShapeandScale.AddParameter("shape", "Shape") clsGammaWithShapeandScale.AddParameter("scale", "Scale") lstAllDistributions.Add(clsGammaWithShapeandScale) 'Gamma With Shape and Mean distribution clsGammaWithShapeandMean.strNameTag = "Gamma_With_Shape_and_Mean" clsGammaWithShapeandMean.strRFunctionName = "rgamma" clsGammaWithShapeandMean.strPFunctionName = "pgamma" clsGammaWithShapeandMean.strQFunctionName = "qgamma" clsGammaWithShapeandMean.strDFunctionName = "dgamma" clsGammaWithShapeandMean.AddParameter("shape", "Shape") clsGammaWithShapeandMean.AddParameter("mean", "Mean") lstAllDistributions.Add(clsGammaWithShapeandMean) 'Gamma With Shape and Rate distribution clsGammaWithShapeandRate.strNameTag = "Gamma_With_Shape_and_Rate" clsGammaWithShapeandRate.strRFunctionName = "rgamma" clsGammaWithShapeandRate.strPFunctionName = "pgamma" clsGammaWithShapeandRate.strQFunctionName = "qgamma" clsGammaWithShapeandRate.strDFunctionName = "dgamma" clsGammaWithShapeandRate.AddParameter("shape", "Shape") clsGammaWithShapeandRate.AddParameter("rate", "Rate") lstAllDistributions.Add(clsGammaWithShapeandRate) 'Gamma With Shape and Scale distribution clsGamma.strNameTag = "Gamma" clsGamma.strGLMFunctionName = "Gamma" clsGamma.bNumeric = True lstAllDistributions.Add(clsGamma) 'Gamma with Zeros distribution 'TODO Paramaters clsGammaWithZerosDist.strNameTag = "Gamma_With_Zeros" clsGammaWithZerosDist.strRFunctionName = "rgamma" clsGammaWithZerosDist.strPFunctionName = "pgamma" clsGammaWithZerosDist.strQFunctionName = "qgamma" clsGammaWithZerosDist.strDFunctionName = "dgamma" clsGammaWithZerosDist.AddParameter("", "", "") clsGammaWithZerosDist.AddParameter("", "", ) lstAllDistributions.Add(clsGammaWithZerosDist) 'Inverse Gaussian distribution clsInverseGaussianDist.strNameTag = "Inverse_Gaussian" clsInverseGaussianDist.strGLMFunctionName = "inverse.gaussian" clsInverseGaussianDist.bNumeric = True lstAllDistributions.Add(clsInverseGaussianDist) 'Quasi distribution clsQuasiDist.strNameTag = "Quasi" clsQuasiDist.strGLMFunctionName = "quasi" clsQuasiDist.bNumeric = True lstAllDistributions.Add(clsQuasiDist) 'Quasibinomial distribution clsQuasibinomialDist.strNameTag = "Quasibinomial" clsQuasibinomialDist.strGLMFunctionName = "quasibinomial" clsQuasibinomialDist.bTwoLevelFactor = True lstAllDistributions.Add(clsQuasibinomialDist) 'Quasipoisson distribution clsQuasipoissonDist.strNameTag = "Quasipoisson" clsQuasipoissonDist.strGLMFunctionName = "quasipoisson" clsQuasipoissonDist.bPositiveInt = True lstAllDistributions.Add(clsQuasipoissonDist) bDistributionsSet = True End Sub Public Event cboDistributionsIndexChanged(sender As Object, e As EventArgs) Private Sub cboDistributions_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboDistributions.SelectedIndexChanged clsCurrDistribution = lstCurrentDistributions(cboDistributions.SelectedIndex) Select Case strDistributionType Case "RFunctions" clsCurrRFunction.SetRCommand(clsCurrDistribution.strRFunctionName) Case "PFunctions" clsCurrRFunction.SetRCommand(clsCurrDistribution.strPFunctionName) Case "DFunctions" clsCurrRFunction.SetRCommand(clsCurrDistribution.strDFunctionName) Case "QFunctions" clsCurrRFunction.SetRCommand(clsCurrDistribution.strQFunctionName) Case "GLMFunctions" clsCurrRFunction.SetRCommand(clsCurrDistribution.strGLMFunctionName) End Select RaiseEvent cboDistributionsIndexChanged(sender, e) End Sub Public Sub RecieverDatatype(DataFrame As String, Column As String) strDataType = frmMain.clsRLink.GetDataType(DataFrame, Column) SetDistributions() End Sub Public Sub RecieverDatatype(strNewType As String) strDataType = strNewType SetDistributions() End Sub End Class
'========================================================================== ' ' File: NumericStrings.vb ' Location: Firefly.Core <Visual Basic .Net> ' Description: 数值字符串操作 ' Version: 2012.03.20. ' Copyright(C) F.R.C. ' '========================================================================== Option Strict On Imports System Imports System.Globalization Imports System.Runtime.CompilerServices Public Module NumericStrings Public Function InvariantParseUInt8(ByVal s As String) As Byte If (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) Then Return Byte.Parse(s.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture) Return Byte.Parse(s, CultureInfo.InvariantCulture) End Function Public Function InvariantParseUInt16(ByVal s As String) As UInt16 If (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) Then Return UInt16.Parse(s.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture) Return UInt16.Parse(s, CultureInfo.InvariantCulture) End Function Public Function InvariantParseUInt32(ByVal s As String) As UInt32 If (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) Then Return UInt32.Parse(s.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture) Return UInt32.Parse(s, CultureInfo.InvariantCulture) End Function Public Function InvariantParseUInt64(ByVal s As String) As UInt64 If (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) Then Return UInt64.Parse(s.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture) Return UInt64.Parse(s, CultureInfo.InvariantCulture) End Function Public Function InvariantParseInt8(ByVal s As String) As SByte If (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) Then Return SByte.Parse(s.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture) Return SByte.Parse(s, CultureInfo.InvariantCulture) End Function Public Function InvariantParseInt16(ByVal s As String) As Int16 If (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) Then Return Int16.Parse(s.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture) Return Int16.Parse(s, CultureInfo.InvariantCulture) End Function Public Function InvariantParseInt32(ByVal s As String) As Int32 If (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) Then Return Int32.Parse(s.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture) Return Int32.Parse(s, CultureInfo.InvariantCulture) End Function Public Function InvariantParseInt64(ByVal s As String) As Int64 If (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) Then Return Int64.Parse(s.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture) Return Int64.Parse(s, CultureInfo.InvariantCulture) End Function Public Function InvariantParseFloat32(ByVal s As String) As Single Return Single.Parse(s, CultureInfo.InvariantCulture) End Function Public Function InvariantParseFloat64(ByVal s As String) As Double Return Double.Parse(s, CultureInfo.InvariantCulture) End Function Public Function InvariantParseBoolean(ByVal s As String) As Boolean Return Boolean.Parse(s) End Function Public Function InvariantParseDecimal(ByVal s As String) As Decimal Return Decimal.Parse(s, CultureInfo.InvariantCulture) End Function <Extension()> Public Function ToInvariantString(ByVal i As Byte) As String Return i.ToString(CultureInfo.InvariantCulture) End Function <Extension()> Public Function ToInvariantString(ByVal i As UInt16) As String Return i.ToString(CultureInfo.InvariantCulture) End Function <Extension()> Public Function ToInvariantString(ByVal i As UInt32) As String Return i.ToString(CultureInfo.InvariantCulture) End Function <Extension()> Public Function ToInvariantString(ByVal i As UInt64) As String Return i.ToString(CultureInfo.InvariantCulture) End Function <Extension()> Public Function ToInvariantString(ByVal i As SByte) As String Return i.ToString(CultureInfo.InvariantCulture) End Function <Extension()> Public Function ToInvariantString(ByVal i As Int16) As String Return i.ToString(CultureInfo.InvariantCulture) End Function <Extension()> Public Function ToInvariantString(ByVal i As Int32) As String Return i.ToString(CultureInfo.InvariantCulture) End Function <Extension()> Public Function ToInvariantString(ByVal i As Int64) As String Return i.ToString(CultureInfo.InvariantCulture) End Function <Extension()> Public Function ToInvariantString(ByVal f As Single) As String Return f.ToString("r", CultureInfo.InvariantCulture) End Function <Extension()> Public Function ToInvariantString(ByVal f As Double) As String Return f.ToString("r", CultureInfo.InvariantCulture) End Function <Extension()> Public Function ToInvariantString(ByVal b As Boolean) As String Return b.ToString() End Function <Extension()> Public Function ToInvariantString(ByVal i As Decimal) As String Return i.ToString(CultureInfo.InvariantCulture) End Function End Module
'=============================================================================== ' Microsoft Caching Application Block for .NET ' http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag/html/CachingBlock.asp ' ' InterfaceDefinitions.vb ' This class has all the interfaces with their method definitions required for ' the caching operations. ' '=============================================================================== ' Copyright (C) 2003 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.Xml #Region "ICacheItemExpiration" ' <summary> ' Allows end users to implement their own cache item ' expiration schema. ' </summary> Public Interface ICacheItemExpiration ' <summary> ' This method is used to provide two types of expirations. ' The expirations based on an asynchronous notification ' (which are not polled), and the expirations based on a ' polling thread which calls the HasExpired method. ' </summary> #Region "Synchronous expiration" ' <summary> ' Specifies if item has expired or not. ' </summary> Function HasExpired() As Boolean ' <summary> ' Notifies that the item was recently used. ' </summary> Sub Notify() #End Region #Region "Asynchronous expiration (user for external dependencies)" ' <summary> ' This method sets the external dependency key. ' </summary> Sub Key (ByVal keyValue As String) ' <summary> ' Event to indicate the cache item expiration. ' </summary> Event change As ItemDependencyChangeEventHandler #End Region End Interface #End Region #Region "ICacheMetadata" ' <summary> ' Allows end users to implement their own cache metadata ' management schema. ' </summary> Public Interface ICacheMetadata ' <summary> ' Adds new data to the cache metadata storage. ' </summary> Sub Add (ByVal key As String, ByVal expirations() As ICacheItemExpiration, _ ByVal priority As CacheItemPriority) ' <summary> ' Removes the element with the specified key from ' the metadata storage. ' </summary> Sub Remove (ByVal key As String) ' <summary> ' Gets all metadata from the metadata storage. ' </summary> Function GetMetadata() As Hashtable ' <summary> ' Removes all metadata from the metadata storage. ' </summary> Sub Flush() End Interface #End Region #Region "IScavengingAlgorithm" ' <summary> ' Allows end users to implement their own scavenging algorithm. ' </summary> Public Interface IScavengingAlgorithm ' <summary> ' Initializes the scavenging algorithm. ' </summary> Sub Init (ByVal cacheService As CacheService, _ ByVal cacheStorage As ICacheStorage, _ ByVal cacheMetadata As ICacheMetadata, ByVal config As XmlNode) ' <summary> ' Notifies that the element with the specified key ' was recently used. ' </summary> Sub Notify (ByVal key As String) ' <summary> ' Executes the algorithm. ' </summary> Sub Execute() ' <summary> ' Adds a new element to the item algorithm list. ' This list is used when the algorithm is executed. ' </summary> Sub Add (ByVal key As String, ByVal priority As CacheItemPriority) ' <summary> ' Removes the element with the specified key from ' the item algorithm list. ' </summary> Sub Remove (ByVal key As String) ' <summary> ' Removes all elements from the item algorithm list. ' </summary> Sub Flush() End Interface #End Region #Region "ICacheStorage" ' <summary> ' Allows end users to implement their own cache management storage. ' All storage providers must implement this interface. ' </summary> Public Interface ICacheStorage ' <summary> ' Inits the storage provider. ' </summary> Sub Init (ByVal config As XmlNode) ' <summary> ' Adds an element with the specified key and value ' into the storage. ' </summary> Sub Add (ByVal key As String, ByVal keyData As Object) ' <summary> ' Removes all elements from the storage. ' </summary> Sub Flush() ' <summary> ' Gets the element with the specified key. ' </summary> Function GetData (ByVal key As String) As Object ' <summary> ' Gets the DataTable with the specified key. ' </summary> Function GetDataTable (ByVal key As String) As DataTable ' <summary> ' Removes the element with the specified key. ' </summary> Sub Remove (ByVal key As String) ' <summary> ' Updates the element with the specified key. ' </summary> Sub Update (ByVal key As String, ByVal keyData As Object) ' <summary> ' Gets the number of elements actually contained in the storage. ' </summary> ReadOnly Property Size() As Integer End Interface #End Region #Region "IDataProtection" ' <summary> ' Allows end users to implement their own cache ' item protection schema. ' </summary> Public Interface IDataProtection ' <summary> ' Inits the data protection provider. ' </summary> Sub Init (ByVal config As XmlNode) ' <summary> ' Encrypts a raw of bytes. ' </summary> Function Encrypt (ByVal plainValue() As Byte) As Byte() ' <summary> ' Decrypts a raw of bytes. ' </summary> Function Decrypt (ByVal cipherValue() As Byte) As Byte() ' <summary> ' Computes a hash for data validation. ' </summary> Function ComputeHash (ByVal plainValue() As Byte) As Byte() End Interface #End Region #Region "IMmfReference" ' <summary> ' To increment or decrement the reference count of the ' memory mapped file object. ' </summary> Public Interface IMmfReference ' <summary> ' Increase the reference count value by one. ' </summary> Function AddReference (ByVal key As String) As Object ' <summary> ' Decrease the reference count by one. ' </summary> Sub RemoveReference (ByVal mmfs As Object) End Interface #End Region
Public Class SettingsFrame Dim n As String = "Settings" Public Overrides Property Text As String Get Return n End Get Set(value As String) n = value End Set End Property Private Sub Settings_Load(sender As Object, e As EventArgs) Handles MyBase.Load NumericUpDown1.Maximum = My.Computer.Screen.Bounds.Width NumericUpDown2.Maximum = My.Computer.Screen.Bounds.Height ' Load Settings Dim s As Settings = New Settings s.EncryptionKey = "LightDodgeByBefkiller" s.LoadFrom(My.Computer.FileSystem.CurrentDirectory + "\Settings.ldgs") CheckBox1.Checked = CBool(s.GetValue("Window.FullScreen")) NumericUpDown1.Value = CInt(s.GetValue("Window.Size.Width")) NumericUpDown2.Value = CInt(s.GetValue("Window.Size.Height")) CheckBox2.Checked = CBool(s.GetValue("Game.Trails.Enabled")) End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Loader.ChangeFrame(New StartMenu) End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim s As Settings = New Settings s.EncryptionKey = "LightDodgeByBefkiller" s.LoadFrom(My.Computer.FileSystem.CurrentDirectory + "\Settings.ldgs") s.SetValue("Window.FullScreen", CheckBox1.Checked.ToString) s.SetValue("Window.Size.Width", NumericUpDown1.Value.ToString) s.SetValue("Window.Size.Height", NumericUpDown2.Value.ToString) s.SetValue("Game.Trails.Enabled", CheckBox2.Checked.ToString) s.SaveTo(My.Computer.FileSystem.CurrentDirectory + "\Settings.ldgs") End Sub Private Sub NumericUpDown1_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown1.ValueChanged NumericUpDown1.Value = Math.Round(NumericUpDown1.Value / 8) * 8 End Sub Private Sub NumericUpDown2_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown2.ValueChanged NumericUpDown2.Value = Math.Round(NumericUpDown2.Value / 8) * 8 End Sub End Class
Imports System.Runtime.Serialization ''' <summary> ''' ''' </summary> ''' <remarks></remarks> <DataContract()> Public Class PrintTask Private pf_dataset As RecordSet Private pf_config As ReportGenConfig ''' <summary> ''' 打印数据集合 ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <DataMember()> Public Property DataSet As RecordSet Get If pf_dataset Is Nothing Then pf_dataset = New RecordSet End If Return pf_dataset End Get Set(value As RecordSet) pf_dataset = value End Set End Property ''' <summary> ''' 打印机本参数 ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> <DataMember()> Public Property Config As ReportGenConfig Get If pf_config Is Nothing Then pf_config = New ReportGenConfig End If Return pf_config End Get Set(value As ReportGenConfig) pf_config = value End Set End Property End Class
' =================================================================== ' ' Copyright (c) 2004 UGS PLM Solutions ' Unpublished - All rights reserved ' ' =================================================================== ' ******************************************************************* ' ' Description ' Sets up access to the Microsoft Word application and uses ' the spell checking functionality. ' ' ' ******************************************************************* Imports System Imports System.Runtime.InteropServices '---------------------------------------- Imports Microsoft.Office.Interop.Word Imports Microsoft.Office.Interop <ComImport(), Guid("00000016-0000-0000-C000-000000000046"), _ InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)> _ Friend Interface IOleMessageFilter <PreserveSig()> _ Function HandleInComingCall(ByVal dwCallType As Integer, ByVal hTaskCaller As IntPtr, _ ByVal dwTickCount As Integer, ByVal lpInterfaceInfo As IntPtr) As Integer <PreserveSig()> _ Function RetryRejectedCall(ByVal hTaskCallee As IntPtr, ByVal dwTickCount As Integer, _ ByVal dwRejectType As Integer) As Integer <PreserveSig()> _ Function MessagePending(ByVal hTaskCallee As IntPtr, ByVal dwTickCount As Integer, _ ByVal dwPendingType As Integer) As Integer End Interface Public Class WordSpellChecker <DllImport("ole32.dll", CallingConvention:=CallingConvention.StdCall)> _ Private Shared Function CoRegisterMessageFilter(ByVal newFilter As IOleMessageFilter, ByRef oldFilter As IOleMessageFilter) As Integer End Function ' Description: Performs spell checking on an input string ' Returns the string validated by the Word ' spell checker. Public Function CheckString(ByRef str As String) As String Dim app As Application = New Word.Application Dim doc As Document = app.Documents.Add app.Selection.Text = str Try Dim dlg As Word.Dialog dlg = app.Dialogs.Item(Word.WdWordDialog.wdDialogToolsSpellingAndGrammar) Dim oldFilter As IOleMessageFilter = Nothing Dim nullFilter As IOleMessageFilter = Nothing CoRegisterMessageFilter(nullFilter, oldFilter) Try dlg.Show() Finally CoRegisterMessageFilter(oldFilter, oldFilter) End Try app.Visible = False Dim docRange As Range = doc.Content str = docRange.Text str = str.TrimEnd(Environment.NewLine) Catch e As Exception System.Diagnostics.Trace.WriteLine("Spell checking...") System.Diagnostics.Trace.WriteLine(e.ToString) Finally doc.Close(WdSaveOptions.wdDoNotSaveChanges) app.Quit() End Try Return str End Function End Class
Public Class RevisedAmountProspectingBO Public Property RevisedBondReleasedHoles As Integer? Public Property RevisedHolesDrilled As Integer? Public Property RevisedHolesPermitted As Integer? Public Property RevisedMudDisposalPit As Integer? Public Property RevisedPadConstruction As Integer? Public Property RevisedRoadConstruction As Integer? Public Property RevisedRoadImprovements As Integer? Public Property RevisedSites As Integer? Public Property RevisedSitesDisturbed As Integer? Public Property CurrentBondReleasedHoles As Integer? Public Property CurrentHolesDrilled As Integer? Public Property CurrentHolesPermitted As Integer? Public Property CurrentMudDisposalPit As Integer? Public Property CurrentPadConstruction As Integer? Public Property CurrentRoadConstruction As Integer? Public Property CurrentRoadImprovements As Integer? Public Property CurrentSites As Integer? Public Property CurrentSitesDisturbed As Integer? End Class
Imports Taas.BackEnd Imports Taas.Common.Logging Imports Taas.HostProcess <TestClass()> Public Class EngineTest Public Class MockTask : Inherits TaskPayload Public Overrides Sub Execute() Logger.Warning("++++++ TASK EXECUTION +++++++") Threading.Thread.Sleep(1000) End Sub End Class Public Class FailTask : Inherits TaskPayload Public Overrides Sub Execute() Logger.Warning("++++++ TASK EXECUTION +++++++") Throw New Exception("This is a test.") End Sub End Class <TestMethod(), TestCategory("MockUpTask")> Public Sub Execute() Dim e As New TestEngine Dim o As New TaskOptions("Taas.Test.dll", "Taas.Test.EngineTest+MockTask") With { .ExecuteWithoutShell = False } Logger.AddDevice(CommonTest.TraceLogDevice.GetInstance) Logger.Verbosity = Level.Debug Using t As New TaskServer t.Initialize(e, o) Assert.AreEqual(TaskState.Initializing, t.State) AwaitTaskState(t, TaskState.Initialized) Assert.AreEqual(e.Tasks.Count, 1) t.Execute() Assert.AreEqual(TaskState.Executing, e.Tasks.First.State) AwaitTaskState(t, TaskState.Finished, 5000) End Using Assert.AreEqual(TaskState.Disposed, e.Tasks.First.State) Logger.AwaitQueueDrained() End Sub <TestMethod(), TestCategory("MockUpTask")> Public Sub Fail() Dim e As New TestEngine Dim o As New TaskOptions("Taas.Test.dll", "Taas.Test.EngineTest+FailTask") With { .ExecuteWithoutShell = False } Logger.AddDevice(CommonTest.TraceLogDevice.GetInstance) Logger.Verbosity = Level.Debug Using t As New TaskServer t.Initialize(e, o) AwaitTaskState(t, TaskState.Initialized) t.Execute() Assert.AreEqual(TaskState.Executing, e.Tasks.First.State) AwaitTaskState(t, TaskState.Failed, 5000) Assert.AreEqual(t.LastException.Message, "[Exception] This is a test.") End Using Assert.AreEqual(TaskState.Disposed, e.Tasks.First.State) Logger.AwaitQueueDrained() End Sub <TestMethod(), TestCategory("MockUpTask")> Public Sub Abort() Dim e As New TestEngine Dim o As New TaskOptions("Taas.Test.dll", "Taas.Test.EngineTest+MockTask") With { .ExecuteWithoutShell = False } Logger.AddDevice(CommonTest.TraceLogDevice.GetInstance) Logger.Verbosity = Level.Debug Using t As New TaskServer t.Initialize(e, o) AwaitTaskState(t, TaskState.Initialized) t.Execute() t.Abort() Assert.AreEqual(TaskState.Aborting, e.Tasks.First.State) AwaitTaskState(t, TaskState.Aborted, 5000) End Using Assert.AreEqual(TaskState.Disposed, e.Tasks.First.State) Logger.AwaitQueueDrained() End Sub <TestMethod(), TestCategory("MockUpTask")> Public Sub Pause() Dim e As New TestEngine Dim o As New TaskOptions("Taas.Test.dll", "Taas.Test.EngineTest+MockTask") With { .ExecuteWithoutShell = False } Logger.AddDevice(CommonTest.TraceLogDevice.GetInstance) Logger.Verbosity = Level.Debug Using t As New TaskServer t.Initialize(e, o) AwaitTaskState(t, TaskState.Initialized) t.Execute() Assert.AreEqual(TaskState.Executing, e.Tasks.First.State) t.Pause() Assert.AreEqual(TaskState.Paused, e.Tasks.First.State) t.Execute() Assert.AreEqual(TaskState.Executing, e.Tasks.First.State) AwaitTaskState(t, TaskState.Finished, 5000) End Using Assert.AreEqual(TaskState.Disposed, e.Tasks.First.State) Logger.AwaitQueueDrained() End Sub Private Sub AwaitTaskState(task As TaskServer, state As TaskState, Optional timeOut As Double = 1000) Dim stopWatch As New Stopwatch stopWatch.Start() While Not task.State = state Threading.Thread.Sleep(1) If stopWatch.ElapsedMilliseconds >= timeOut Then Assert.Fail("Waiting for task has timed out (" & stopWatch.ElapsedTicks & ").") End While stopWatch.Stop() End Sub Public Class TestEngine : Inherits TaskEngine Private _tasks As New List(Of TaskServer) Public ReadOnly Property Tasks As IReadOnlyList(Of TaskServer) Get Return Me._tasks End Get End Property Public Overrides Sub TaskEventSink(sender As Object, e As TaskEventArgs) If Not Me._tasks.Contains(sender) Then Me._tasks.Add(sender) End If End Sub End Class End Class
''' <summary> ''' Holds the agent related details ''' </summary> <Serializable()> _ Public Class DEPriceBands Public Property AgentCompany() As String Public Property PriceBand() As String Public Property Quantity() As string End Class
Option Strict On Public Class frmGolfers '-------------------------------------------------------------' ' Name: Golfers_Load ' Desc: subroutine to populate data and load it in upon launch '-------------------------------------------------------------' Private Sub frmGolfers_Load(sender As Object, e As EventArgs) Handles MyBase.Load Try '------load the shirt size and gender combo box------' Load_ShirtSize() Load_Gender() '------load all other data------' Load_Names() Catch ex As Exception MessageBox.Show(ex.Message) End Try '----SUB COMPLETE----' End Sub '-------------------------------------------------------------' ' Name: Load_Names ' Desc: subroutine to load all golfer names '-------------------------------------------------------------' Private Sub Load_Names() Try Dim strSelect As String = "" Dim cmdSelect As OleDb.OleDbCommand Dim drSourceTable As OleDb.OleDbDataReader Dim dt As DataTable = New DataTable '------textbox loop------' For Each cntrl As Control In Controls If TypeOf cntrl Is TextBox Then cntrl.Text = String.Empty End If Next '-----database open-------' If OpenDatabaseConnectionSQLServer() = False Then '---if db doesn't open warn user----' MessageBox.Show(Me, "Database application error." & vbNewLine & "The application will now close.", Me.Text + "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Me.Close() End If '-----select statement-----' strSelect = "SELECT intGolferID, strLastName FROM TGolfers" '---yoink the records---' cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator) drSourceTable = cmdSelect.ExecuteReader '-----------load table from data reader---------' dt.Load(drSourceTable) '---bind golfer PK to combo box selection----' cmbGolferChoice.ValueMember = "intGolferID" '-----bind golfer last name to be displayed----' cmbGolferChoice.DisplayMember = "strLastName" '--------feed in the data from the data table------' cmbGolferChoice.DataSource = dt '-----select first item in list as default----' If cmbGolferChoice.Items.Count > 0 Then cmbGolferChoice.SelectedIndex = 0 End If '----close the reader----' drSourceTable.Close() '----close connection---' CloseDatabaseConnection() Catch ex As Exception '---display error----' MessageBox.Show(ex.Message) End Try '----SUB COMPLETE----' End Sub '-------------------------------------------------------------' ' Name: AddGolfer_Click ' Desc: subroutine to call the add(new) golfer form '-------------------------------------------------------------' Private Sub btnAddGolfer_Click(sender As Object, e As EventArgs) Handles btnAddGolfer.Click Dim frmAddGolfer As New frmAddGolfer frmAddGolfer.ShowDialog() '---reload form and add player in----' frmGolfers_Load(sender, e) '----SUB COMPLETE----' End Sub '-------------------------------------------------------------' ' Name: UpdateGolfer_Click ' Desc: subroutine to handle the update golfer event '-------------------------------------------------------------' Private Sub btnUpdateGolfer_Click(sender As Object, e As EventArgs) Handles btnUpdateGolfer.Click Dim strSelect As String = "" Dim strFirstName As String = "" Dim strLastName As String = "" Dim strAddress As String = "" Dim strCity As String = "" Dim strState As String = "" Dim strZip As String = "" Dim strPhone As String = "" Dim strEmail As String = "" Dim intRowsAffected As Integer Try '---update statement---' Dim cmdUpdate As OleDb.OleDbCommand '----validation----' If Validation() = True Then '----pop open the db-----' '----check if the server connection was established------' If OpenDatabaseConnectionSQLServer() = False Then MessageBox.Show(Me, "Database connection error." & vbNewLine & "The application will now close.", Me.Text + " Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Me.Close() End If If Validation() = True Then '-------set the data variables-------' strFirstName = txtFName.Text strLastName = txtLName.Text strAddress = txtAddress.Text strCity = txtCity.Text strState = txtState.Text strZip = txtZip.Text strPhone = txtPhone.Text strEmail = txtEmail.Text '------Build the select statement--------' strSelect = "Update TGolfers Set strFirstName = '" & strFirstName & "', " & "strLastName = '" & strLastName & "', " & "strStreetAddress = '" & strAddress & "', " & "strCity = '" & strCity & "', " & "strState = '" & strState & "', " & "strZip = '" & strZip & "'," & "strPhoneNumber = '" & strPhone & "', " & "strEmail = '" & strEmail & "'" & "Where intGolferID = " & cmbGolferChoice.SelectedValue.ToString '----test message-----' 'MessageBox.Show(strSelect) '-----connect | inject select statement----' cmdUpdate = New OleDb.OleDbCommand(strSelect, m_conAdministrator) '-----execute-----' intRowsAffected = cmdUpdate.ExecuteNonQuery '----display to user if successful----' If intRowsAffected = 1 Then MessageBox.Show("Update successful") Else MessageBox.Show("Update failed") End If '---close connection | shockingly straight-forward command lol----' CloseDatabaseConnection() '---------reload the form with whatever magic parameters those are----------' frmGolfers_Load(sender, e) End If End If Catch ex As Exception '----display exception-----' MessageBox.Show(ex.Message) End Try '----SUB COMPLETE----' End Sub '-------------------------------------------------------------' ' Name: DeleteGolfer_Click ' Desc: subroutine to close the window '-------------------------------------------------------------' Private Sub btnDeleteGolfer_Click(sender As Object, e As EventArgs) Handles btnDeleteGolfer.Click Dim strDelete As String = "" Dim strSelect As String = "" Dim strName As String = "" Dim intRowsAffected As Integer Dim cmdDelete As OleDb.OleDbCommand Dim dt As DataTable = New DataTable Dim result As DialogResult Try 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 '----ensure the user wishes to delete the record----' result = MessageBox.Show("Are you sure you want to delete golfer: Last Name - " & cmbGolferChoice.Text _ & "?", "Confirm Deletion", MessageBoxButtons.YesNoCancel _ , MessageBoxIcon.Question) Select Case result Case DialogResult.Cancel MessageBox.Show("Action Canceled") Case DialogResult.No MessageBox.Show("Action Canceled") '-----if yes, build and execute delete statement------' Case DialogResult.Yes '-----delete child tables first-------' strDelete = "DELETE FROM TGolferEventYearSponsors WHERE intGolferID = " & cmbGolferChoice.SelectedValue.ToString cmdDelete = New OleDb.OleDbCommand(strDelete, m_conAdministrator) intRowsAffected = cmdDelete.ExecuteNonQuery() strDelete = "DELETE FROM TGolferEventYears WHERE intGolferID = " & cmbGolferChoice.SelectedValue.ToString cmdDelete = New OleDb.OleDbCommand(strDelete, m_conAdministrator) intRowsAffected = cmdDelete.ExecuteNonQuery() '----delete parent table-----' strDelete = "DELETE FROM TGolfers WHERE intGolferID = " & cmbGolferChoice.SelectedValue.ToString cmdDelete = New OleDb.OleDbCommand(strDelete, m_conAdministrator) intRowsAffected = cmdDelete.ExecuteNonQuery() If intRowsAffected > 0 Then MessageBox.Show("Delete Successful!") End If End Select CloseDatabaseConnection() frmGolfers_Load(sender, e) Catch ex As Exception MessageBox.Show(ex.Message) End Try '----SUB COMPLETE----' End Sub '-------------------------------------------------------------' ' Name: GolferChoice_SelectedIndexChange ' Desc: change the data presented once the selected golfer changes '-------------------------------------------------------------' Private Sub cmbGolferChoice_SelectedIndexChange(sender As Object, e As EventArgs) Handles cmbGolferChoice.SelectedIndexChanged Dim strSelect As String = "" Dim strName As String = "" Dim cmdSelect As OleDb.OleDbCommand Dim drSourceTable As OleDb.OleDbDataReader Dim dt As DataTable = New DataTable Dim intShirtSize As Integer Dim intGender As Integer Try If OpenDatabaseConnectionSQLServer() = False Then '----basically the same situation as the default load sub------' MessageBox.Show(Me, "Database connection error." & vbNewLine & "The application will now close.", Me.Text + " Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Me.Close() End If '----Build select statement based off PK----' strSelect = "SELECT strFirstName, strLastName, strStreetAddress, strCity, strState, strZip, strPhoneNumber, strEmail," _ & "intShirtSizeID, intGenderID FROM TGolfers Where intGolferID = " _ & cmbGolferChoice.SelectedValue.ToString '----snag the records------' cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator) drSourceTable = cmdSelect.ExecuteReader '-----load the data table from the reader--------' dt.Load(drSourceTable) '----populate the data | each item is the next column in the row-------' txtFName.Text = dt.Rows(0).Item(0).ToString txtLName.Text = dt.Rows(0).Item(1).ToString txtAddress.Text = dt.Rows(0).Item(2).ToString txtCity.Text = dt.Rows(0).Item(3).ToString txtState.Text = dt.Rows(0).Item(4).ToString txtZip.Text = dt.Rows(0).Item(5).ToString txtPhone.Text = dt.Rows(0).Item(6).ToString txtEmail.Text = dt.Rows(0).ItemArray(7).ToString '-----set shirt and gender combo-boxes to proper value-----' intShirtSize = CInt(dt.Rows(0).Item(8)) cmbShirtSize.SelectedValue = intShirtSize intGender = CInt(dt.Rows(0).Item(9)) cmbGender.SelectedValue = intGender '----close the connection----' CloseDatabaseConnection() Catch ex As Exception MessageBox.Show(ex.Message) End Try '----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----' cmbShirtSize.ValueMember = "intShirtSizeID" cmbShirtSize.DisplayMember = "strShirtSizeDesc" cmbShirtSize.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 gender----' cmbGender.ValueMember = "intGenderID" cmbGender.DisplayMember = "strGenderDesc" cmbGender.DataSource = dt '---close---' drSourceTable.Close() CloseDatabaseConnection() Catch excError As Exception MessageBox.Show(excError.Message) End Try '----SUB COMPLETE----' End Sub '-------------------------------------------------------------' ' Name: Validation ' Desc: validation tool '-------------------------------------------------------------' '----Validation function-----' Public Function Validation() As Boolean ' loop through the textboxes and check to make sure there is data in them 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 'every this is good so return true Return True '----FUNC COMPLETE----' End Function '-------------------------------------------------------------' ' Name: Exit_Click ' Desc: subroutine to close the window '-------------------------------------------------------------' Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click Close() '----SUB COMPLETE----' End Sub End Class
Imports System Imports Microsoft.VisualBasic Imports ChartDirector Public Class pyramidelevation Implements DemoModule 'Name of demo module Public Function getName() As String Implements DemoModule.getName Return "Pyramid Elevation" End Function 'Number of charts produced in this demo module Public Function getNoOfCharts() As Integer Implements DemoModule.getNoOfCharts Return 7 End Function 'Main code for creating charts Public Sub createChart(viewer As WinChartViewer, chartIndex As Integer) _ Implements DemoModule.createChart ' The data for the pyramid chart Dim data() As Double = {156, 123, 211, 179} ' The colors for the pyramid layers Dim colors() As Integer = {&H66aaee, &Heebb22, &Hcccccc, &Hcc88ff} ' The elevation angle Dim angle As Integer = chartIndex * 15 ' Create a PyramidChart object of size 200 x 200 pixels, with white (ffffff) background and ' grey (888888) border Dim c As PyramidChart = New PyramidChart(200, 200, &Hffffff, &H888888) ' Set the pyramid center at (100, 100), and width x height to 60 x 120 pixels c.setPyramidSize(100, 100, 60, 120) ' Set the elevation angle c.addTitle("Elevation = " & angle, "Arial Italic", 15) c.setViewAngle(angle) ' Set the pyramid data c.setData(data) ' Set the layer colors to the given colors c.setColors2(Chart.DataColor, colors) ' Leave 1% gaps between layers c.setLayerGap(0.01) ' Output the chart viewer.Chart = c End Sub End Class
Imports PclWCommon Public MustInherit Class TestableObj Public Property Id As String Public Property ClosedPolygonsRequired As Boolean Public Property InputAdapterFromPolygonSet As Object Public Property InputAdapterFromRegion As Object Public Property OutputAdapter As Object Public MustOverride Function GetAdaptedInputFromPolygonSet( ByVal input As PolygonSet) As Object Public MustOverride Function GetAdaptedInputFromRegion( ByVal input As Region) As Object Public MustOverride Function GetAdaptedOutputToPolygonSet( ByVal output As Object) As PolygonSet Public MustOverride Function GetDifference(ByVal subject As Object, ByVal clip As Object) As Object Public MustOverride Function GetIntersection(ByVal subject As Object, ByVal clip As Object) As Object Public MustOverride Function GetUnion(ByVal subject As Object, ByVal clip As Object) As Object Public MustOverride Function GetXor(ByVal subject As Object, ByVal clip As Object) As Object End Class
Imports System.Drawing.Drawing2D Imports System.Runtime.InteropServices Imports System.Runtime.CompilerServices Public Module GraphicsExtension Private Const Rad2Deg As Double = 180 / Math.PI Private Const Deg2Rad As Double = 1 / Rad2Deg <Extension()> Public Function GenerateRoundedRectangle(graphics As Graphics, rectangle As RectangleF, radius As Single, filter As RectangleEdgeFilter) As GraphicsPath Dim diameter As Single Dim path As New GraphicsPath() If radius <= 0.0F OrElse filter = RectangleEdgeFilter.None Then path.AddRectangle(rectangle) path.CloseFigure() Return path Else If radius >= (Math.Min(rectangle.Width, rectangle.Height)) / 2.0 Then Return graphics.GenerateCapsule(rectangle) End If diameter = radius * 2.0F Dim sizeF As New SizeF(diameter, diameter) Dim arc As New RectangleF(rectangle.Location, sizeF) If (RectangleEdgeFilter.TopLeft And filter) = RectangleEdgeFilter.TopLeft Then path.AddArc(arc, 180, 90) Else path.AddLine(arc.X, arc.Y + arc.Height, arc.X, arc.Y) path.AddLine(arc.X, arc.Y, arc.X + arc.Width, arc.Y) End If arc.X = rectangle.Right - diameter If (RectangleEdgeFilter.TopRight And filter) = RectangleEdgeFilter.TopRight Then path.AddArc(arc, 270, 90) Else path.AddLine(arc.X, arc.Y, arc.X + arc.Width, arc.Y) path.AddLine(arc.X + arc.Width, arc.Y + arc.Height, arc.X + arc.Width, arc.Y) End If arc.Y = rectangle.Bottom - diameter If (RectangleEdgeFilter.BottomRight And filter) = RectangleEdgeFilter.BottomRight Then path.AddArc(arc, 0, 90) Else path.AddLine(arc.X + arc.Width, arc.Y, arc.X + arc.Width, arc.Y + arc.Height) path.AddLine(arc.X, arc.Y + arc.Height, arc.X + arc.Width, arc.Y + arc.Height) End If arc.X = rectangle.Left If (RectangleEdgeFilter.BottomLeft And filter) = RectangleEdgeFilter.BottomLeft Then path.AddArc(arc, 90, 90) Else path.AddLine(arc.X + arc.Width, arc.Y + arc.Height, arc.X, arc.Y + arc.Height) path.AddLine(arc.X, arc.Y + arc.Height, arc.X, arc.Y) End If path.CloseFigure() End If Return path End Function <Extension()> Public Function GenerateCapsule(graphics As Graphics, rectangle As RectangleF) As GraphicsPath Dim diameter As Single Dim arc As RectangleF Dim path As New GraphicsPath() If rectangle.Width < 0 OrElse rectangle.Height < 0 Then path.AddEllipse(rectangle) path.CloseFigure() Return path End If Try If rectangle.Width > rectangle.Height Then diameter = rectangle.Height Dim sizeF As New SizeF(diameter, diameter) arc = New RectangleF(rectangle.Location, sizeF) path.AddArc(arc, 90, 180) arc.X = rectangle.Right - diameter path.AddArc(arc, 270, 180) ElseIf rectangle.Width < rectangle.Height Then diameter = rectangle.Width Dim sizeF As New SizeF(diameter, diameter) arc = New RectangleF(rectangle.Location, sizeF) path.AddArc(arc, 180, 180) arc.Y = rectangle.Bottom - diameter path.AddArc(arc, 0, 180) Else path.AddEllipse(rectangle) End If Catch path.AddEllipse(rectangle) Finally path.CloseFigure() End Try Return path End Function <Extension()> Public Sub DrawRoundedRectangle(graphics As Graphics, pen As Pen, x As Single, y As Single, width As Single, height As Single, radius As Single, filter As RectangleEdgeFilter) Dim rectangle As New RectangleF(x, y, width, height) Using path As GraphicsPath = graphics.GenerateRoundedRectangle(rectangle, radius, filter) Dim old As SmoothingMode = graphics.SmoothingMode graphics.SmoothingMode = SmoothingMode.AntiAlias graphics.DrawPath(pen, path) graphics.SmoothingMode = old End Using End Sub <Extension()> Public Sub DrawRoundedRectangle(graphics As Graphics, pen As Pen, x As Single, y As Single, width As Single, height As Single, radius As Single) graphics.DrawRoundedRectangle(pen, x, y, width, height, radius, RectangleEdgeFilter.All) End Sub <Extension()> Public Sub DrawRoundedRectangle(graphics As Graphics, pen As Pen, x As Integer, y As Integer, width As Integer, height As Integer, radius As Integer) graphics.DrawRoundedRectangle(pen, Convert.ToSingle(x), Convert.ToSingle(y), Convert.ToSingle(width), Convert.ToSingle(height), Convert.ToSingle(radius)) End Sub <Extension()> Public Sub DrawRoundedRectangle(graphics As Graphics, pen As Pen, rectangle As Rectangle, radius As Integer, filter As RectangleEdgeFilter) graphics.DrawRoundedRectangle(pen, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, radius, filter) End Sub <Extension()> Public Sub DrawRoundedRectangle(graphics As Graphics, pen As Pen, rectangle As Rectangle, radius As Integer) graphics.DrawRoundedRectangle(pen, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, radius, RectangleEdgeFilter.All) End Sub <Extension()> Public Sub DrawRoundedRectangle(graphics As Graphics, pen As Pen, rectangle As RectangleF, radius As Integer, filter As RectangleEdgeFilter) graphics.DrawRoundedRectangle(pen, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, radius, filter) End Sub <Extension()> Public Sub DrawRoundedRectangle(graphics As Graphics, pen As Pen, rectangle As RectangleF, radius As Integer) graphics.DrawRoundedRectangle(pen, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, radius, RectangleEdgeFilter.All) End Sub <Extension()> Public Sub FillRoundedRectangle(graphics As Graphics, brush As Brush, x As Single, y As Single, width As Single, height As Single, radius As Single, filter As RectangleEdgeFilter) Dim rectangle As New RectangleF(x, y, width, height) Using path As GraphicsPath = graphics.GenerateRoundedRectangle(rectangle, radius, filter) Dim old As SmoothingMode = graphics.SmoothingMode graphics.SmoothingMode = SmoothingMode.AntiAlias graphics.FillPath(brush, path) graphics.SmoothingMode = old End Using End Sub <Extension()> Public Sub FillRoundedRectangle(graphics As Graphics, brush As Brush, x As Single, y As Single, width As Single, height As Single, radius As Single) graphics.FillRoundedRectangle(brush, x, y, width, height, radius, RectangleEdgeFilter.All) End Sub <Extension()> Public Sub FillRoundedRectangle(graphics As Graphics, brush As Brush, x As Integer, y As Integer, width As Integer, height As Integer, radius As Integer) graphics.FillRoundedRectangle(brush, Convert.ToSingle(x), Convert.ToSingle(y), Convert.ToSingle(width), Convert.ToSingle(height), Convert.ToSingle(radius)) End Sub <Extension()> Public Sub FillRoundedRectangle(graphics As Graphics, brush As Brush, rectangle As Rectangle, radius As Integer, filter As RectangleEdgeFilter) graphics.FillRoundedRectangle(brush, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, radius, filter) End Sub <Extension()> Public Sub FillRoundedRectangle(graphics As Graphics, brush As Brush, rectangle As Rectangle, radius As Integer) graphics.FillRoundedRectangle(brush, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, radius, RectangleEdgeFilter.All) End Sub <Extension()> Public Sub FillRoundedRectangle(graphics As Graphics, brush As Brush, rectangle As RectangleF, radius As Integer, filter As RectangleEdgeFilter) graphics.FillRoundedRectangle(brush, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, radius, filter) End Sub <Extension()> Public Sub FillRoundedRectangle(graphics As Graphics, brush As Brush, rectangle As RectangleF, radius As Integer) graphics.FillRoundedRectangle(brush, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, radius, RectangleEdgeFilter.All) End Sub <Extension()> Public Sub DrawEllipseFromCenter(g As Graphics, pen As Pen, x As Single, y As Single, width As Single, height As Single) g.DrawEllipse(pen, x - width / 2, y - height / 2, width, height) End Sub <Extension()> Public Sub DrawEllipseFromCenter(g As Graphics, pen As Pen, x As Integer, y As Integer, width As Integer, height As Integer) g.DrawEllipse(pen, CInt(x - width / 2), CInt(y - height / 2), width, height) End Sub <Extension()> Public Sub DrawEllipseFromCenter(g As Graphics, pen As Pen, rect As Rectangle) DrawEllipseFromCenter(g, pen, rect.X, rect.Y, rect.Width, rect.Height) End Sub <Extension()> Public Sub DrawEllipseFromCenter(g As Graphics, pen As Pen, rect As RectangleF) DrawEllipseFromCenter(g, pen, rect.X, rect.Y, rect.Width, rect.Height) End Sub <Extension()> Public Sub FillEllipseFromCenter(g As Graphics, brush As Brush, x As Single, y As Single, width As Single, height As Single) g.FillEllipse(brush, CInt(x - width / 2), CInt(y - height / 2), width, height) End Sub <Extension()> Public Sub FillEllipseFromCenter(g As Graphics, brush As Brush, x As Integer, y As Integer, width As Integer, height As Integer) g.FillEllipse(brush, x - width \ 2, y - height \ 2, width, height) End Sub <Extension()> Public Sub FillEllipseFromCenter(g As Graphics, brush As Brush, rect As Rectangle) FillEllipseFromCenter(g, brush, rect.X, rect.Y, rect.Width, rect.Height) End Sub <Extension()> Public Sub FillEllipseFromCenter(g As Graphics, brush As Brush, rect As RectangleF) FillEllipseFromCenter(g, brush, rect.X, rect.Y, rect.Width, rect.Height) End Sub <Extension()> Public Sub DrawEllipseFromCenter(g As Graphics, brush As Brush, rect As RectangleF) FillEllipseFromCenter(g, brush, rect.X, rect.Y, rect.Width, rect.Height) End Sub <Extension()> Public Sub FillDonut(g As Graphics, backColor As Brush, donutColor As Brush, highlightColor As Brush, ByVal rect As Rectangle, donutSize As Integer, startAngle As Single, sweepAngle As Single, Optional drawEndCaps As Boolean = False) g.FillEllipse(donutColor, rect) If sweepAngle > 0 Then g.FillPie(highlightColor, rect, startAngle, sweepAngle) If drawEndCaps AndAlso sweepAngle > 0 Then Dim r As RectangleF r.X = CSng((rect.X + rect.Width / 2) + (rect.Width - donutSize) / 2 * Math.Cos(-startAngle * Deg2Rad)) r.Y = CSng((rect.Y + rect.Height / 2) + (rect.Height - donutSize) / 2 * Math.Sin(startAngle * Deg2Rad)) r.Width = donutSize r.Height = donutSize g.FillEllipseFromCenter(highlightColor, r) r.X = CSng((rect.X + rect.Width / 2) + (rect.Width - donutSize) / 2 * Math.Cos(-(startAngle + sweepAngle) * Deg2Rad)) r.Y = CSng((rect.Y + rect.Height / 2) + (rect.Height - donutSize) / 2 * Math.Sin((startAngle + sweepAngle) * Deg2Rad)) g.FillEllipseFromCenter(highlightColor, r) End If rect.Inflate(-donutSize, -donutSize) g.FillEllipse(backColor, rect) End Sub <Extension()> Public Sub DrawCurvedText(g As Graphics, text As String, centre As Point, distanceFromCentreToBaseOfText As Single, radiansToTextCentre As Single, font As Font, brush As Brush, Optional clockwise As Boolean = True) ' http://stackoverflow.com/a/11151457/518872 ' Circumference for use later Dim circleCircumference As Double = (Math.PI * 2 * distanceFromCentreToBaseOfText) ' Get the width of each character Dim characterWidths = GetCharacterWidths(g, text, font).ToArray() ' The overall height of the string Dim characterHeight = g.MeasureString(text, font).Height Dim textLength = characterWidths.Sum() ' The string length above Is the arc length we'll use for rendering the string. Work out the starting angle required to ' center the text across the radiansToTextCentre. Dim fractionOfCircumference As Double = textLength / circleCircumference Dim currentCharacterRadians As Double = radiansToTextCentre + If(clockwise, -1, 1) * (Math.PI * fractionOfCircumference) For characterIndex = 0 To text.Length - 1 Dim c As Char = text(characterIndex) ' Polar to Cartesian Dim x As Double = (distanceFromCentreToBaseOfText * Math.Sin(currentCharacterRadians)) Dim y As Double = -(distanceFromCentreToBaseOfText * Math.Cos(currentCharacterRadians)) Using characterPath As GraphicsPath = New GraphicsPath() characterPath.AddString(c.ToString(), font.FontFamily, font.Style, font.Size, Point.Empty, StringFormat.GenericTypographic) Dim pathBounds = characterPath.GetBounds() ' Transformation matrix to move the character to the correct location. ' Note that all actions on the Matrix class are prepended, so we apply them in reverse. Dim transform = New Matrix() ' Translate to the final position transform.Translate(CSng(centre.X + x), CSng(centre.Y + y)) ' Rotate the character Dim rotationAngleDegrees As Single = CSng(currentCharacterRadians * 180.0F / Math.PI - If(clockwise, 0, 180.0F)) transform.Rotate(rotationAngleDegrees) ' Translate the character so the center of its base Is over the origin transform.Translate(-pathBounds.Width / 2.0F, -characterHeight) characterPath.Transform(transform) ' Draw the character g.FillPath(brush, characterPath) End Using If characterIndex <> text.Length - 1 Then ' Move "currentCharacterRadians" on to the next character Dim distanceToNextChar = (characterWidths(characterIndex) + characterWidths(characterIndex + 1)) / 2.0F Dim charFractionOfCircumference As Double = distanceToNextChar / circleCircumference If clockwise Then currentCharacterRadians += charFractionOfCircumference * (2.0F * Math.PI) Else currentCharacterRadians -= charFractionOfCircumference * (2.0F * Math.PI) End If End If Next End Sub <Extension()> Public Sub Resize(ByRef bmp As Bitmap, newSize As Size, Optional mantainAspectRatio As Boolean = False) Dim srcRect As New Rectangle(Point.Empty, New Size(bmp.Width, bmp.Height)) Dim trgRect As Rectangle If mantainAspectRatio Then Dim ar As Double = srcRect.Width / srcRect.Height trgRect = New Rectangle(Point.Empty, New Size(newSize.Width, CInt(newSize.Height / ar))) Else trgRect = New Rectangle(Point.Empty, newSize) End If Dim newBmp As New Bitmap(trgRect.Width, trgRect.Height) Using g As Graphics = Graphics.FromImage(newBmp) g.InterpolationMode = InterpolationMode.High g.CompositingQuality = CompositingQuality.HighQuality g.SmoothingMode = SmoothingMode.AntiAlias g.DrawImage(bmp, trgRect, srcRect, GraphicsUnit.Pixel) End Using bmp.Dispose() bmp = newBmp End Sub <Extension()> Public Sub Resize(ByRef bmp As Bitmap, width As Integer, height As Integer, Optional mantainAspectRatio As Boolean = False) bmp.Resize(New Size(width, height), mantainAspectRatio) End Sub Private Function GetCharacterWidths(g As Graphics, text As String, font As Font) As IEnumerable(Of Single) ' The length of a space. Necessary because a space measured using StringFormat.GenericTypographic has no width. ' We can't use StringFormat.GenericDefault for the characters themselves, as it adds unwanted spacing. Dim spaceLength = g.MeasureString(" ", font, Point.Empty, StringFormat.GenericDefault).Width Return text.Select(Function(c) If(c = " ", spaceLength, g.MeasureString(c.ToString(), font, Point.Empty, StringFormat.GenericTypographic).Width)) End Function Private Enum TernaryRasterOperations As UInteger ''' <summary>dest = source</summary> SRCCOPY = &HCC0020 ''' <summary>dest = source OR dest</summary> SRCPAINT = &HEE0086 ''' <summary>dest = source AND dest</summary> SRCAND = &H8800C6 ''' <summary>dest = source XOR dest</summary> SRCINVERT = &H660046 ''' <summary>dest = source AND (NOT dest)</summary> SRCERASE = &H440328 ''' <summary>dest = (NOT source)</summary> NOTSRCCOPY = &H330008 ''' <summary>dest = (NOT src) AND (NOT dest)</summary> NOTSRCERASE = &H1100A6 ''' <summary>dest = (source AND pattern)</summary> MERGECOPY = &HC000CA ''' <summary>dest = (NOT source) OR dest</summary> MERGEPAINT = &HBB0226 ''' <summary>dest = pattern</summary> PATCOPY = &HF00021 ''' <summary>dest = DPSnoo</summary> PATPAINT = &HFB0A09 ''' <summary>dest = pattern XOR dest</summary> PATINVERT = &H5A0049 ''' <summary>dest = (NOT dest)</summary> DSTINVERT = &H550009 ''' <summary>dest = BLACK</summary> BLACKNESS = &H42 ''' <summary>dest = WHITE</summary> WHITENESS = &HFF0062 ''' <summary> ''' Capture window as seen on screen. This includes layered windows ''' such as WPF windows with AllowsTransparency="true" ''' </summary> CAPTUREBLT = &H40000000 End Enum <DllImport("gdi32.dll")> Private Function BitBlt(hdc As IntPtr, nXDest As Integer, nYDest As Integer, nWidth As Integer, nHeight As Integer, hdcSrc As IntPtr, nXSrc As Integer, nYSrc As Integer, dwRop As TernaryRasterOperations) As Boolean End Function <DllImport("Gdi32.dll")> Private Function SelectObject(hdc As IntPtr, hObject As IntPtr) As IntPtr End Function <DllImport("gdi32.dll", SetLastError:=True)> Private Function CreateCompatibleDC(hRefDC As IntPtr) As IntPtr End Function Private Declare Function DeleteDC Lib "gdi32.dll" (hdc As IntPtr) As Boolean Private Declare Function StretchBlt Lib "gdi32.dll" (hdcDest As IntPtr, nXOriginDest As Integer, nYOriginDest As Integer, nWidthDest As Integer, nHeightDest As Integer, hdcSrc As IntPtr, nXOriginSrc As Integer, nYOriginSrc As Integer, nWidthSrc As Integer, nHeightSrc As Integer, dwRop As TernaryRasterOperations) As Boolean Private Declare Function DeleteObject Lib "gdi32.dll" (hObject As IntPtr) As Boolean <Extension()> Public Sub DrawImageFast(g As Graphics, image As Bitmap, dstRect As Rectangle, srcRect As Rectangle) Dim srcGraphics As Graphics = Graphics.FromImage(image) Dim srcHDC As IntPtr = srcGraphics.GetHdc Dim pSource As IntPtr = CreateCompatibleDC(srcHDC) Dim dstHDC As IntPtr = g.GetHdc Dim srcHbitmap As IntPtr = image.GetHbitmap() SelectObject(pSource, srcHbitmap) If dstRect.Size = srcRect.Size Then BitBlt(dstHDC, dstRect.X, dstRect.Y, dstRect.Width, dstRect.Height, pSource, srcRect.X, srcRect.Y, TernaryRasterOperations.SRCCOPY) Else StretchBlt(dstHDC, dstRect.X, dstRect.Y, dstRect.Width, dstRect.Height, pSource, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, TernaryRasterOperations.SRCCOPY) End If DeleteObject(srcHbitmap) DeleteDC(pSource) g.ReleaseHdc(dstHDC) srcGraphics.ReleaseHdc(srcHDC) srcGraphics.Dispose() End Sub <Extension()> Public Sub DrawImageFast(g As Graphics, image As Bitmap, destRect As Rectangle, x As Integer, y As Integer, width As Integer, height As Integer) g.DrawImageFast(image, destRect, New Rectangle(Point.Empty, image.Size)) End Sub <Extension()> Public Sub DrawImageFast(g As Graphics, image As Bitmap, destRect As Rectangle) g.DrawImageFast(image, destRect, New Rectangle(Point.Empty, image.Size)) End Sub <Extension()> Public Sub DrawImageFast(g As Graphics, image As Bitmap, destPoint As Point) g.DrawImageFast(image, New Rectangle(destPoint, image.Size), New Rectangle(Point.Empty, image.Size)) End Sub <Extension()> Public Function GetFontMetrics(graphics As Graphics, font As Font) As FontMetrics Return FontMetricsImpl.GetFontMetrics(graphics, font) End Function <Extension()> Public Function GetCenter(r As Rectangle) As Point Return New Point(r.Left + r.Width / 2, r.Top + r.Height / 2) End Function Private Class FontMetricsImpl Inherits FontMetrics <StructLayout(LayoutKind.Sequential)> Public Structure TEXTMETRIC Public tmHeight As Integer Public tmAscent As Integer Public tmDescent As Integer Public tmInternalLeading As Integer Public tmExternalLeading As Integer Public tmAveCharWidth As Integer Public tmMaxCharWidth As Integer Public tmWeight As Integer Public tmOverhang As Integer Public tmDigitizedAspectX As Integer Public tmDigitizedAspectY As Integer Public tmFirstChar As Char Public tmLastChar As Char Public tmDefaultChar As Char Public tmBreakChar As Char Public tmItalic As Byte Public tmUnderlined As Byte Public tmStruckOut As Byte Public tmPitchAndFamily As Byte Public tmCharSet As Byte End Structure <DllImport("gdi32.dll", CharSet:=CharSet.Unicode)> Public Shared Function SelectObject(hdc As IntPtr, hgdiobj As IntPtr) As IntPtr End Function <DllImport("gdi32.dll", CharSet:=CharSet.Unicode)> Public Shared Function GetTextMetrics(hdc As IntPtr, lptm As TEXTMETRIC) As Boolean End Function <DllImport("gdi32.dll", CharSet:=CharSet.Unicode)> Public Shared Function DeleteObject(hdc As IntPtr) As Boolean End Function Private Function GenerateTextMetrics(graphics As Graphics, font As Font) As TEXTMETRIC Dim hDC As IntPtr = IntPtr.Zero Dim textMetric As TEXTMETRIC Dim hFont As IntPtr = IntPtr.Zero Try hDC = graphics.GetHdc() hFont = font.ToHfont() Dim hFontDefault As IntPtr = SelectObject(hDC, hFont) Dim result As Boolean = GetTextMetrics(hDC, textMetric) SelectObject(hDC, hFontDefault) Finally If hFont <> IntPtr.Zero Then DeleteObject(hFont) End If If hDC <> IntPtr.Zero Then graphics.ReleaseHdc(hDC) End If End Try Return textMetric End Function Private metrics As TEXTMETRIC Public Overrides ReadOnly Property Height() As Integer Get Return Me.metrics.tmHeight End Get End Property Public Overrides ReadOnly Property Ascent() As Integer Get Return Me.metrics.tmAscent End Get End Property Public Overrides ReadOnly Property Descent() As Integer Get Return Me.metrics.tmDescent End Get End Property Public Overrides ReadOnly Property InternalLeading() As Integer Get Return Me.metrics.tmInternalLeading End Get End Property Public Overrides ReadOnly Property ExternalLeading() As Integer Get Return Me.metrics.tmExternalLeading End Get End Property Public Overrides ReadOnly Property AverageCharacterWidth() As Integer Get Return Me.metrics.tmAveCharWidth End Get End Property Public Overrides ReadOnly Property MaximumCharacterWidth() As Integer Get Return Me.metrics.tmMaxCharWidth End Get End Property Public Overrides ReadOnly Property Weight() As Integer Get Return Me.metrics.tmWeight End Get End Property Public Overrides ReadOnly Property Overhang() As Integer Get Return Me.metrics.tmOverhang End Get End Property Public Overrides ReadOnly Property DigitizedAspectX() As Integer Get Return Me.metrics.tmDigitizedAspectX End Get End Property Public Overrides ReadOnly Property DigitizedAspectY() As Integer Get Return Me.metrics.tmDigitizedAspectY End Get End Property Private Sub New(graphics As Graphics, font As Font) Me.metrics = Me.GenerateTextMetrics(graphics, font) End Sub Public Shared Function GetFontMetrics(graphics As Graphics, font As Font) As FontMetrics Return New FontMetricsImpl(graphics, font) End Function End Class End Module Public Enum RectangleEdgeFilter None = 0 TopLeft = 1 TopRight = 2 BottomLeft = 4 BottomRight = 8 All = TopLeft Or TopRight Or BottomLeft Or BottomRight End Enum Public MustInherit Class FontMetrics Public Overridable ReadOnly Property Height() As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property Ascent() As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property Descent() As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property InternalLeading() As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property ExternalLeading() As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property AverageCharacterWidth() As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property MaximumCharacterWidth() As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property Weight() As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property Overhang() As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property DigitizedAspectX() As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property DigitizedAspectY() As Integer Get Return 0 End Get End Property End Class
Public Class UpdatePinStatusArgs : Inherits System.EventArgs Private _Pin As Integer Private _Status As Integer Public Sub New(ByVal pin As Integer, ByVal status As Integer) _Pin = pin _Status = status End Sub Public Property Pin() As Integer Get Return _Pin End Get Set(value As Integer) _Pin = value End Set End Property Public Property Status() As Integer Get Return _Status End Get Set(value As Integer) _Status = value End Set End Property Public Overrides Function ToString() As String Return "Pin: " & Pin & " Status: " & Status & vbCrLf End Function End Class
Public Class GamePiece Inherits Label Public Enum EffectEnum None Score Out End Enum Public Enum ActionEnum None Disappear End Enum Dim nHitEffect As EffectEnum = EffectEnum.None Dim nHitAction As ActionEnum = ActionEnum.None Public Sub New() Me.Text = "" Me.AutoSize = False Me.BackColor = mdUtility.GetRandomColor End Sub Public Sub Disappear() Me.Visible = False If Me.Parent Is Nothing = False Then Me.Parent.Controls.Remove(Me) End If End Sub 'Public Sub SetBackColorToRandom() ' Me.BackColor = mdUtility.GetRandomColor 'End Sub Public Property HitEffect As EffectEnum Get Return nHitEffect End Get Set(value As EffectEnum) nHitEffect = value End Set End Property Public Property HitAction As ActionEnum Get Return nHitAction End Get Set(value As ActionEnum) nHitAction = value End Set End Property End Class
#Region "Microsoft.VisualBasic::65fa889bca6b790972c1144a3cd2bbc3, mzkit\src\assembly\ThermoRawFileReader\ThermoReaderOptions.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: 110 ' Code Lines: 36 ' Comment Lines: 58 ' Blank Lines: 16 ' File Size: 3.54 KB ' Class ThermoReaderOptions ' ' ' Delegate Sub ' ' Properties: IncludeReferenceAndExceptionData, LoadMSMethodInfo, LoadMSTuneInfo, MaxMz, MaxScan ' MinIntensityThreshold, MinMz, MinRelIntensityThresholdRatio, MinScan, SignalToNoiseThreshold ' ' Function: ToString ' ' ' ' /********************************************************************************/ #End Region Imports Microsoft.VisualBasic.Serialization.JSON ''' <summary> ''' Thermo reader options ''' </summary> ''' <CLSCompliant(True)> Public Class ThermoReaderOptions #Region "Events" ''' <summary> ''' Delegate method for OptionsUpdatedEvent ''' </summary> ''' <param name="sender"></param> Public Delegate Sub OptionsUpdatedEventHandler(sender As Object) ''' <summary> ''' This event is raised when one of the options tracked by this class is changed ''' </summary> Public Event OptionsUpdatedEvent As OptionsUpdatedEventHandler #End Region #Region "Member variables" Private mIncludeReferenceAndExceptionData As Boolean #End Region #Region "Properties" ''' <summary> ''' When true, include reference and exception peaks when obtaining mass spec data ''' using GetScanData, GetScanData2D, or GetScanDataSumScans ''' </summary> ''' <remarks>Reference and exception peaks are internal mass calibration data within a scan</remarks> Public Property IncludeReferenceAndExceptionData As Boolean Get Return mIncludeReferenceAndExceptionData End Get Set(value As Boolean) If mIncludeReferenceAndExceptionData = value Then Return mIncludeReferenceAndExceptionData = value RaiseEvent OptionsUpdatedEvent(Me) End Set End Property Const DEFAULT_MAX_MZ = 10000000 ''' <summary> ''' Load MS Method Information when calling OpenRawFile ''' </summary> ''' <remarks> ''' Set this to false when using the ThermoRawFileReader on Linux systems; ''' CommonCore.RawFileReader raises an exception due to a null value when accessing ''' get_StorageDescriptions from get_InstrumentMethodsCount; stack trace: ''' ThermoRawFileReader.XRawFileIO.FillFileInfo ''' ThermoFisher.CommonCore.RawFileReader.RawFileAccessBase.get_InstrumentMethodsCount ''' ThermoFisher.CommonCore.RawFileReader.StructWrappers.Method.get_StorageDescriptions ''' </remarks> Public Property LoadMSMethodInfo As Boolean = True ''' <summary> ''' Load MS Tune Information when calling OpenRawFile ''' </summary> Public Property LoadMSTuneInfo As Boolean = True ''' <summary> ''' First scan to output ''' </summary> ''' <returns></returns> Public Property MinScan As Integer = -1 ''' <summary> ''' Lowest m/z to output ''' </summary> ''' <returns></returns> Public Property MinMz As Double = 0 ''' <summary> ''' Highest m/z to output ''' </summary> ''' <returns></returns> Public Property MaxMz As Double = DEFAULT_MAX_MZ ''' <summary> ''' Relative intensity threshold (value between 0 and 1) ''' </summary> ''' <returns></returns> Public Property MinRelIntensityThresholdRatio As Double = 0 ''' <summary> ''' Minimum S/N ratio ''' </summary> ''' <returns></returns> Public Property SignalToNoiseThreshold As Double = 0 ''' <summary> ''' Minimum intensity threshold (absolute value) ''' </summary> ''' <returns></returns> Public Property MinIntensityThreshold As Double = 0 ''' <summary> ''' Last scan to output ''' </summary> ''' <returns></returns> Public Property MaxScan As Integer = Short.MaxValue #End Region Public Overrides Function ToString() As String Return Me.GetJson End Function End Class