Need to change str from sql query to currency - mysql

How can I get the productPrice below to show as $7.99 etc.? I've tried everything I can find. It is small money in db table. Thanks.
Protected Sub printMenuBlock(ByVal productName As String)
'Set up variable storing the product and pull from databse
Dim product = ReadProduct(productName)
'Add necessary markup to str variable, with products information within
For i As Integer = 0 To product.Count - 1
str += "<div class='menuItem'>"
'str += " <img alt='Item Picture' class='itemPicture' src='" + product(i).ImagePath.Substring(3).Replace("\", "/") + "' />"
str += " <div class='itemInfo'>"
str += " <h1 class='itemName'>"
str += " " + product(i).Item("ProductName") + "</h1>"
'str += " <h3 class='itemDescription'>"
str += " " + product(i).Item("ProductDescription")
str += " <h1 class ='itemPrice'>"
str += " " + String.Format("{0:C}", product(i).Item("ProductPrice")) + "</h1>"
str += " "
str += " </div>"
str += " </div>"
Next
This is code from interaction class:
Public Class Interaction
' New instance of the Sql command object
Private cmdSelect As New SqlCommand
' Instance of the Connection class
Private conIn As New Connection
Region "Menu functions and subs"
' Set up the SQL statement for finding a Product by ProductCat
Private Sub GetProduct(ByVal CatIn As String)
' SQL String
Dim strSelect As String
strSelect = "SELECT * "
strSelect &= " FROM Menu "
'strSelect &= " WHERE ProductCat = #CatIn"
strSelect &= "ORDER BY 'ProductCat'"
' Set up the connection to the datebase
cmdSelect.Connection = conIn.Connect
' Add the SQL string to the connection
cmdSelect.CommandText = strSelect
' Add the parameters to the connection
cmdSelect.Parameters.Add("#CatIn", SqlDbType.NVarChar).Value = CatIn
End Sub
'Function to create list of rows and columns
Public Function ReadProduct(ByVal CatIn As String) As List(Of Dictionary(Of String, Object))
'Declare variable to hold list
Dim ReturnProducts As New List(Of Dictionary(Of String, Object))
Try
Call GetProduct(CatIn)
Dim dbr As SqlDataReader
' Execute the created SQL command from GetProduct and set to the SqlDataReader object
dbr = cmdSelect.ExecuteReader
'Get number of columns in current row
Dim FieldCount = dbr.FieldCount()
Dim ColumnList As New List(Of String)
'Loop through all columns and add to list
For i As Integer = 0 To FieldCount - 1
ColumnList.Add(dbr.GetName(i))
Next
While dbr.Read()
'Declare variable to hold list
Dim ReturnProduct As New Dictionary(Of String, Object)
'Loop through all rows and add to list
For i As Integer = 0 To FieldCount - 1
ReturnProduct.Add(ColumnList(i), dbr.GetValue(i).ToString())
Next
'Add to final list
ReturnProducts.Add(ReturnProduct)
End While
cmdSelect.Parameters.Clear()
'Close connection
dbr.Close()
Catch ex As SqlException
Dim strOut As String
strOut = ex.Message
Console.WriteLine(strOut)
End Try
' Return the Product object
Return ReturnProducts
End Function

Try using
+ String.Format("{0:C}", product(i).Item("ProductPrice")) +
P.S. You may want to use StringBuilder for these kinds of constructs.

Related

mysql connection issues in parallel foreach loop

I have two classes. One class hold the database information while the other class processes information to and from the database; this class also accesses a server but that should not matter for this.
My problem is that when I try to use a foreach loop in parallel, the program randomly generates ssl connection error. The errors build up until the server blocks my IP address. If I keep the loop not in parallel, I have no errors. Unfortunately, I need the program to run faster. As a note, this is a standalone application so no need to worry about sql injection or anything.
How can I make this function in parallel?
Imports Newtonsoft.Json
' This class handles searching and extracting relevant data to the database
Public Class RiotDataExtractor
Private rda As New RiotDataAdapter
Private rm As New RemoteManager
Private summonerQueryCount As Integer = -5
Private strInsertQuery As String = ""
Private strUpdateQuery As String = ""
Public Sub New()
Try
dataExtraction()
Catch ex As Exception
Console.WriteLine(ex.Message + " in RiotDataExtractor/new.")
End Try
End Sub
' Gathers the list of summoners, |summonerQueryCount| at a time and send them to search their match history
Private Sub dataExtraction()
Try
Dim summoner_count As Integer = rm.returnDBQueryAsDataTable("SELECT COUNT(*) FROM summoner_data;").Rows(0).Item(0)
For i As Integer = (summoner_count - 1) To 0 Step summonerQueryCount
Dim dt As DataTable = rm.returnDBQueryAsDataTable("SELECT * FROM summoner_data limit " & (i + summonerQueryCount).ToString & ", " & (-summonerQueryCount).ToString() & ";")
If dt.Rows.Count = 0 Then
Exit For
End If
For j As Integer = 0 To dt.Rows.Count - 1
searchMatchHistoryForSummoner(dt.Rows(j).Item(3).ToString(), dt.Rows(j).Item(0).ToString())
Next
Next
Catch ex As Exception
Console.WriteLine(ex.Message + " in RiotDataExtractor/dataExtraction.")
End Try
End Sub
' Find the match history for a player from the database
Private Sub searchMatchHistoryForSummoner(ByVal strRegion As String, ByVal strAccountId As String)
Try
Dim convertedId As String = JsonConvert.DeserializeObject(Of LeagueSummonerData)(rda.convertID(strRegion, strAccountId)).accountId.ToString()
Dim matchHistory As LeagueMatchManager = JsonConvert.DeserializeObject(Of LeagueMatchManager)(rda.returnMatchHistoryForDataExtractor(strRegion, convertedId))
Parallel.ForEach(matchHistory.matches, Function(match As LeagueMatchList)
searchMatchData(match.gameId.ToString(), strRegion)
Return Nothing
End Function)
Catch ex As Exception
Console.WriteLine(ex.Message + " in RiotDataExtractor/searchMatchHistory.")
End Try
End Sub
' Search for match data from an ID
Private Sub searchMatchData(ByVal matchId As String, ByVal strRegion As String)
Try
Dim league_match As LeagueMatch = JsonConvert.DeserializeObject(Of LeagueMatch)(rda.returnLeagueMatch(matchId, strRegion))
'Parallel.ForEach(league_match.participantIdentities, Function(player As LeagueParticipantIdentity)
' searchPlayerInformation(player.player.summonerId.ToString(), strRegion)
' Return Nothing
' End Function)
For Each player In league_match.participantIdentities
searchPlayerInformation(player.player.summonerId.ToString(), strRegion)
Next
Catch ex As Exception
Console.WriteLine(ex.Message + " in RiotDataExtractor/searchMatchData.")
End Try
End Sub
' Uses summoner id from a match to gather all relevant information and insert into database
Private Sub searchPlayerInformation(ByVal summonerId As String, ByVal strRegion As String)
Debug.WriteLine(summonerId & "||" & strRegion)
If summonerId > 0 Then
Try
Dim summonerData As LeagueSummonerData = JsonConvert.DeserializeObject(Of LeagueSummonerData)(rda.returnLeagueSummoner(strRegion, summonerId))
Dim dt As DataTable = rm.returnDBQueryAsDataTable("SELECT * FROM summoner_data WHERE account_id = " + summonerData.id.ToString() + ";")
If dt.Rows.Count > 1 Then
rm.executeDBQuery("DELETE * FROM summoner_data WHERE account_id = ")
End If
If dt.Rows.Count = 1 Then
rm.executeDBQuery("UPDATE summoner_data SET summoner_name = '" + summonerData.name + "', summoner_level = " + summonerData.summonerLevel.ToString() + " WHERE account_id = " + summonerData.id.ToString() + " AND region = '" + strRegion + "';")
ElseIf (dt.Rows.Count = 0) Then
rm.executeDBQuery("INSERT INTO summoner_data (account_id, summoner_name, summoner_level, region) VALUES (" + summonerData.id.ToString() + ", '" + summonerData.name + "', " + summonerData.summonerLevel.ToString() + ", '" + strRegion + "');")
End If
Catch ex As Exception
Console.WriteLine(ex.Message + " in RiotDataExtractor/searchPlayerInformation.")
End Try
End If
End Sub
End Class
********************************************************
This is the class where I access the remote database.
Public Function returnDBQueryAsDataTable(ByVal strQuery As String) As DataTable
Dim dtLogin As DataTable = New DataTable()
Dim conn = New MySqlConnection(String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", summoner_spell, item_text, map_name, champ))
conn.Open()
Try
Using conn
Using cmd = New MySqlCommand(strQuery, conn)
Dim daLogin = New MySqlDataAdapter(cmd)
daLogin.Fill(dtLogin)
End Using
End Using
Catch ex As Exception
System.Diagnostics.Debug.WriteLine("Query failed: " + strQuery)
Finally
conn.Close()
End Try
Return dtLogin
End Function
Public Sub executeDBQuery(ByVal strQuery As String)
Try
Dim conn = New MySqlConnection(String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", summoner_spell, item_text, map_name, champ))
conn.Open()
Using conn
Using cmd = New MySqlCommand(strQuery, conn)
cmd.ExecuteNonQuery()
End Using
End Using
conn.Close()
Debug.WriteLine("Query succeeded: " + strQuery)
Catch ex As Exception
Debug.WriteLine("Query failed: " + strQuery + "//" + ex.Message)
End Try
End Sub
End Class

Show File Path in Access 2010 Form

I have a form in Access 2010 that allows the user to find an Excel file and map it so that it can easily be accessed from another form. The simplest way to explain it, I think, is with a picture:
The form has this On Load event:
Private Sub Form_Load()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim sSQL As String
Dim sPath As String
Set db = CurrentDb
On Error GoTo Error_Handler
sPath = Application.CurrentProject.Path
sSQL = "Select Setting from tblBackendFiles where Code = 'SourceVerification'"
Set rs = db.OpenRecordset(sSQL)
Me.tVerificationPath = Nz(rs!Setting, "")
If Len(Me.tVerificationPath) = 0 Then
Me.tExcelPath = sPath
End If
Me.cmdAcceptPath.SetFocus
rs.Close
GoTo exit_sub
Error_Handler:
MsgBox Err.number & ": " & Err.Description, vbInformation + vbOKOnly, "Error!"
exit_sub:
Set rs = Nothing
Set db = Nothing
End Sub
What I want is to have the current path of the Excel file displayed in the textbox, which is currently unbound. I've looked around online but I'm having a hard time finding how to actually get the path to show up.
What would be the best way to do this? I'd prefer to do it without VBA if at all possible, but I'm not 100% opposed to it.
I have done this many times. You will have to create a form. On that form, place a textbox called "tbFile", another called "tbFileName" (which is invisible) and a button called "bBrowse".
Then, behind your form, put this:
Option Compare Database
Option Explicit
Private Sub bBrowse_Click()
On Error GoTo Err_bBrowse_Click
Dim strFilter As String
Dim lngFlags As Long
Dim varFileName As Variant
Me.tbHidden.SetFocus
' strFilter = "Access (*.mdb)" & vbNullChar & "*.mdb" _
' & vbNullChar & "All Files (*.*)" & vbNullChar & "*.*"
' strFilter = "Access Files (*.mdb)" & vbNullChar & "*.mdb*"
strFilter = "All Files (*.*)" & vbNullChar & "*.*"
lngFlags = tscFNPathMustExist Or tscFNFileMustExist Or tscFNHideReadOnly
varFileName = tsGetFileFromUser( _
fOpenFile:=True, _
strFilter:=strFilter, _
rlngflags:=lngFlags, _
strInitialDir:="C:\Windows\", _
strDialogTitle:="Find File (Select The File And Click The Open Button)")
'remove the strInitialDir:="C:\Windows\", _ line if you do not want the Browser to open at a specific location
If IsNull(varFileName) Or varFileName = "" Then
Debug.Print "User pressed 'Cancel'."
Beep
MsgBox "File selection was canceled.", vbInformation
Exit Sub
Else
'Debug.Print varFileName
tbFile = varFileName
End If
Call ParseFileName
Exit_bBrowse_Click:
Exit Sub
Err_bBrowse_Click:
MsgBox Err.Number & " - " & Err.Description
Resume Exit_bBrowse_Click
End Sub
Private Function ParseFileName()
On Error GoTo Err_ParseFileName
Dim sFullName As String
Dim sFilePathOnly As String
Dim sDrive As String
Dim sPath As String
Dim sLocation As String
Dim sFileName As String
sFullName = tbFile.Value
' Find the final "\" in the path.
sPath = sFullName
Do While Right$(sPath, 1) <> "\"
sPath = Left$(sPath, Len(sPath) - 1)
Loop
' Find the Drive.
sDrive = Left$(sFullName, InStr(sFullName, ":") + 1)
'tbDrive = sDrive
' Find the Location.
sLocation = Mid$(sPath, Len(sDrive) - 2)
'tbLocation = sLocation
' Find the Path.
sPath = Mid$(sPath, Len(sDrive) + 1)
'tbPath = sPath
' Find the file name.
sFileName = Mid$(sFullName, Len(sPath) + 4)
tbFileName = sFileName
Exit_ParseFileName:
Exit Function
Err_ParseFileName:
MsgBox Err.Number & " - " & Err.Description
Resume Exit_ParseFileName
End Function
Then, create a new Module and paste this into it:
Option Compare Database
Option Explicit
Private Declare Function ts_apiGetOpenFileName Lib "comdlg32.dll" _
Alias "GetOpenFileNameA" (tsFN As tsFileName) As Boolean
Private Declare Function ts_apiGetSaveFileName Lib "comdlg32.dll" _
Alias "GetSaveFileNameA" (tsFN As tsFileName) As Boolean
Private Declare Function CommDlgExtendedError Lib "comdlg32.dll" () As Long
Private Type tsFileName
lStructSize As Long
hwndOwner As Long
hInstance As Long
strFilter As String
strCustomFilter As String
nMaxCustFilter As Long
nFilterIndex As Long
strFile As String
nMaxFile As Long
strFileTitle As String
nMaxFileTitle As Long
strInitialDir As String
strTitle As String
flags As Long
nFileOffset As Integer
nFileExtension As Integer
strDefExt As String
lCustData As Long
lpfnHook As Long
lpTemplateName As String
End Type
' Flag Constants
Public Const tscFNAllowMultiSelect = &H200
Public Const tscFNCreatePrompt = &H2000
Public Const tscFNExplorer = &H80000
Public Const tscFNExtensionDifferent = &H400
Public Const tscFNFileMustExist = &H1000
Public Const tscFNPathMustExist = &H800
Public Const tscFNNoValidate = &H100
Public Const tscFNHelpButton = &H10
Public Const tscFNHideReadOnly = &H4
Public Const tscFNLongNames = &H200000
Public Const tscFNNoLongNames = &H40000
Public Const tscFNNoChangeDir = &H8
Public Const tscFNReadOnly = &H1
Public Const tscFNOverwritePrompt = &H2
Public Const tscFNShareAware = &H4000
Public Const tscFNNoReadOnlyReturn = &H8000
Public Const tscFNNoDereferenceLinks = &H100000
Public Function tsGetFileFromUser( _
Optional ByRef rlngflags As Long = 0&, _
Optional ByVal strInitialDir As String = "", _
Optional ByVal strFilter As String = "All Files (*.*)" & vbNullChar & "*.*", _
Optional ByVal lngFilterIndex As Long = 1, _
Optional ByVal strDefaultExt As String = "", _
Optional ByVal strFileName As String = "", _
Optional ByVal strDialogTitle As String = "", _
Optional ByVal fOpenFile As Boolean = True) As Variant
On Error GoTo tsGetFileFromUser_Err
Dim tsFN As tsFileName
Dim strFileTitle As String
Dim fResult As Boolean
' Allocate string space for the returned strings.
strFileName = Left(strFileName & String(256, 0), 256)
strFileTitle = String(256, 0)
' Set up the data structure before you call the function
With tsFN
.lStructSize = Len(tsFN)
.hwndOwner = Application.hWndAccessApp
.strFilter = strFilter
.nFilterIndex = lngFilterIndex
.strFile = strFileName
.nMaxFile = Len(strFileName)
.strFileTitle = strFileTitle
.nMaxFileTitle = Len(strFileTitle)
.strTitle = strDialogTitle
.flags = rlngflags
.strDefExt = strDefaultExt
.strInitialDir = strInitialDir
.hInstance = 0
.strCustomFilter = String(255, 0)
.nMaxCustFilter = 255
.lpfnHook = 0
End With
' Call the function in the windows API
If fOpenFile Then
fResult = ts_apiGetOpenFileName(tsFN)
Else
fResult = ts_apiGetSaveFileName(tsFN)
End If
' If the function call was successful, return the FileName chosen
' by the user. Otherwise return null. Note, the CancelError property
' used by the ActiveX Common Dialog control is not needed. If the
' user presses Cancel, this function will return Null.
If fResult Then
rlngflags = tsFN.flags
tsGetFileFromUser = tsTrimNull(tsFN.strFile)
Else
tsGetFileFromUser = Null
End If
tsGetFileFromUser_End:
On Error GoTo 0
Exit Function
tsGetFileFromUser_Err:
Beep
MsgBox Err.Description, , "Error: " & Err.Number _
& " in function basBrowseFiles.tsGetFileFromUser"
Resume tsGetFileFromUser_End
End Function
' Trim Nulls from a string returned by an API call.
Private Function tsTrimNull(ByVal strItem As String) As String
On Error GoTo tsTrimNull_Err
Dim I As Integer
I = InStr(strItem, vbNullChar)
If I > 0 Then
tsTrimNull = Left(strItem, I - 1)
Else
tsTrimNull = strItem
End If
tsTrimNull_End:
On Error GoTo 0
Exit Function
tsTrimNull_Err:
Beep
MsgBox Err.Description, , "Error: " & Err.Number _
& " in function basBrowseFiles.tsTrimNull"
Resume tsTrimNull_End
End Function
Public Sub tsGetFileFromUserTest()
On Error GoTo tsGetFileFromUserTest_Err
Dim strFilter As String
Dim lngFlags As Long
Dim varFileName As Variant
' strFilter = "Access (*.mdb)" & vbNullChar & "*.mdb" _
' & vbNullChar & "All Files (*.*)" & vbNullChar & "*.*"
strFilter = "All Files (*.*)" & vbNullChar & "*.*"
lngFlags = tscFNPathMustExist Or tscFNFileMustExist Or tscFNHideReadOnly
varFileName = tsGetFileFromUser( _
fOpenFile:=True, _
strFilter:=strFilter, _
rlngflags:=lngFlags, _
strDialogTitle:="GetFileFromUser Test (Please choose a file)")
If IsNull(varFileName) Then
Debug.Print "User pressed 'Cancel'."
Else
Debug.Print varFileName
'Forms![Form1]![Text1] = varFileName
End If
If varFileName <> "" Then MsgBox "You selected the '" & varFileName & "' file.", vbInformation
tsGetFileFromUserTest_End:
On Error GoTo 0
Exit Sub
tsGetFileFromUserTest_Err:
Beep
MsgBox Err.Description, , "Error: " & Err.Number _
& " in sub basBrowseFiles.tsGetFileFromUserTest"
Resume tsGetFileFromUserTest_End
End Sub
VOILA! Easy as that. ;o)

How to use http request query string property to filter where clause

I need to filter where clause in my GetProduct function using http request query string property. I have set up my filters in urls. (eg burgers.aspx?filter=burgers'). Burgers is the name of database table category(Where ProductCat = filter). I understand I need to pass parameter to interaction class because it does not handle requests. Please help.
Interaction class:
Public Class Interaction
Inherits System.Web.UI.Page
' New instance of the Sql command object
Private cmdSelect As New SqlCommand
' Instance of the Connection class
Private conIn As New Connection
Region "Menu functions and subs"
' Set up the SQL statement for finding a Product by ProductCat
Private Sub GetProduct(ByVal CatIn As String)
' SQL String
Dim strSelect As String
strSelect = "SELECT * "
strSelect &= " FROM Menu "
strSelect &= " WHERE ProductCat = "
strSelect &= "ORDER BY 'ProductCat'"
' Set up the connection to the datebase
cmdSelect.Connection = conIn.Connect
' Add the SQL string to the connection
cmdSelect.CommandText = strSelect
' Add the parameters to the connection
cmdSelect.Parameters.Add("filter", SqlDbType.NVarChar).Value = CatIn
End Sub
'Function to create list of rows and columns
Public Function ReadProduct(ByVal CatIn As String) As List(Of Dictionary(Of String, Object))
'Declare variable to hold list
Dim ReturnProducts As New List(Of Dictionary(Of String, Object))
Try
Call GetProduct(CatIn)
Dim dbr As SqlDataReader
' Execute the created SQL command from GetProduct and set to the SqlDataReader object
dbr = cmdSelect.ExecuteReader
'Get number of columns in current row
Dim FieldCount = dbr.FieldCount()
Dim ColumnList As New List(Of String)
'Loop through all columns and add to list
For i As Integer = 0 To FieldCount - 1
ColumnList.Add(dbr.GetName(i))
Next
While dbr.Read()
'Declare variable to hold list
Dim ReturnProduct As New Dictionary(Of String, Object)
'Loop through all rows and add to list
For i As Integer = 0 To FieldCount - 1
ReturnProduct.Add(ColumnList(i), dbr.GetValue(i).ToString())
Next
'Add to final list
ReturnProducts.Add(ReturnProduct)
End While
cmdSelect.Parameters.Clear()
'Close connection
dbr.Close()
Catch ex As SqlException
Dim strOut As String
strOut = ex.Message
Console.WriteLine(strOut)
End Try
' Return the Product object
Return ReturnProducts
End Function
Code Behind:
Partial Class Burger
Inherits System.Web.UI.Page
'String Used to build the necessary markup and product information
Dim str As String = ""
''Var used to interact with SQL database
Dim db As New Interaction
' New instance of the Sql command object
Private cmdSelect As New SqlCommand
' Instance of the Connection class
Private conIn As New Connection
Protected Sub printMenuBlock(ByVal productName As String)
'Set up variable storing the product and pull from databse
Dim product = db.ReadProduct(productName)
'Add necessary markup to str variable, with products information within
For i As Integer = 0 To product.Count - 1
str += "<div class='menuItem'>"
'str += " <img alt='Item Picture' class='itemPicture' src='" + product(i).ImagePath.Substring(3).Replace("\", "/") + "' />"
str += " <div class='itemInfo'>"
str += " <h1 class='itemName'>"
str += " " + product(i).Item("ProductName") + "</h1>"
'str += " <h3 class='itemDescription'>"
str += " " + product(i).Item("ProductDescription")
str += " <h1 class ='itemPrice'>"
str += " " + product(i).Item("ProductPrice") + "</h1>"
str += " "
str += " </div>"
str += " </div>"
Next
End Sub
''Uses
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Dim v = Request.QueryString("filter")
'Response.Write("filter is")
'Response.Write(v)
Dim value = Request.QueryString("filter")
'Get string from printMenuBlock method
printMenuBlock(str)
'Print the str variable in menuPlace div
menuPlace.InnerHtml = str
End Sub
End Class
I need a direction on how to pass the Request.QueryString("filter") to GetProduct function to filter by page according to ProductCategory. Thanks in advance.
Try something like this:
Dim filter = Request.QueryString("filter")
Dim sqlStr = "Select * From menu Where ProductCat = #filter Order By ProductCat"
cmdSelect.Parameters.Add("filter", SqlDbType.NVarChar).Value = filter

Connecting To A Database Via Class Object Visual Basic 2010

i have 2 classes
connect class
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class connect
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SqlCmd As MySqlCommand
Dim DR As MySqlDataReader
Public Function Con2Db() As Boolean
Try
'Prepare connection and query
dbCon = New MySqlConnection("Server=localhost; User Id = root; Pwd = 12345; Database = digitallibrary")
If dbCon.State = ConnectionState.Closed Then
dbCon.Open()
Return True
Else
dbCon.Close()
splash.Label1.Text = "Connection is Close"
Return False
End If
Catch ex As Exception
MsgBox("FAIL")
Return False
End Try
End Function
End Class
And query Class
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class query
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SqlCmd As MySqlCommand
Dim DR As MySqlDataReader
Public Sub insert(ByVal ln As String, ByVal fn As String, ByVal mn As String, ByVal user As String, ByVal email As String, ByVal bdate As String, ByVal jdate As String, ByVal jtime As String, ByVal pwd As String)
Try
strQuery = "INSERT INTO user_tbl(user_ln,user_fn,user_mn,username,user_email,user_bdate, user_jdate, user_jtime)VALUES('" + ln + "','" + fn + "','" + mn + "','" + user + "','" + email + "','" + bdate + "','" + jdate + "','" + jtime + "' );" & _
"INSERT INTO login_tbl(username,password)VALUES('" + user + "','" + pwd + "')"
SqlCmd = New MySqlCommand(strQuery, dbCon)
SqlCmd.ExecuteNonQuery()
dbCon.Close()
Catch ex As Exception
MsgBox("Error " & ex.Message)
End Try
End Sub
End Class
Also A registration form
Public Class registration
Private Sub registration_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As New connect
If (con.Con2Db = True) Then
Label13.Text = "Connected To Database"
Else
Label13.Text = "Not Connected To Database"
End If
End Sub
Private Sub submit_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles submit_btn.Click
Dim ins As New query
Dim ln As String = ln_txt.Text
Dim fn As String = fn_txt.Text
Dim mn As String = mn_txt.Text
Dim user As String = user_txt.Text
Dim pwd As String = pwd_txt.Text
Dim cpwd As String = cpwd_txt.Text
Dim email As String = email_txt.Text
Dim year As String = year_cbx.Text
Dim month As String = month_cbx.Text
Dim day As String = day_cbx.Text
Dim bdate As String = year + "-" + month + "-" + day
Dim jdate As String = Format(Date.Now, "yyyy-MM-dd")
Dim jtime As String = Format(Date.Now, "HH:mm:ss")
ins.insert(ln, fn, mn, user, email, bdate, jdate, jtime, pwd)
End Sub
End Class
Everything is okay and it is saying on the label that the connection is successful but when I run the code it gives an error
Error Connection must be valid and open
I don't understand why the connection is said to be closed when the function is returning true...
If people are wondering why separate it to each classes it's because i'm trying to code cleanly(i hope and think) and i want to be more flexible in programming
The problem is that your 'connect' class has no relationship to your 'insert' function, meaning you are creating a new connection in each one. What you would have to do is create a Shared connection to your database that your connect class would manage, and your 'insert' function would use the existing connection.
There is nothing wrong with separating code into various sections, but you must know how to do it efficiently. I typically keep connection management and query execution in the same sections to avoid passing around extra objects. Here is what I would do:
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class QueryManager
Dim dbCon As MySqlConnection
Public Sub ManageConnection(ByVal CloseConnection As Boolean)
Try
'Prepare connection and query'
dbCon = New MySqlConnection("Server=localhost; User Id = root; Pwd = 12345; Database = digitallibrary")
If CloseConnection = False Then
If dbCon.State = ConnectionState.Closed Then _
dbCon.Open()
Else
dbCon.Close()
End If
Catch ex As Exception
MsgBox("FAIL")
End Try
End Sub
Public Sub Insert(ByVal ln As String, ByVal fn As String, ByVal mn As String, ByVal user As String, ByVal email As String, ByVal bdate As String, ByVal jdate As String, ByVal jtime As String, ByVal pwd As String)
Try
ManageConnection(True) 'Open connection'
Dim strQuery As String = "INSERT INTO user_tbl(user_ln,user_fn,user_mn,username,user_email,user_bdate, user_jdate, user_jtime)" & _
"VALUES('" + ln + "','" + fn + "','" + mn + "','" + user + "','" + email + "','" + bdate + "','" + jdate + "','" + jtime + "' );" & _
"INSERT INTO login_tbl(username,password)VALUES('" + user + "','" + pwd + "')"
Dim SqlCmd As New MySqlCommand(strQuery, dbCon)
SqlCmd.ExecuteNonQuery()
ManageConnection(False) 'Close connection'
Catch ex As Exception
MsgBox("Error " & ex.Message)
End Try
End Sub
End Class
You would also no longer require the 'registration_Load' sub since the connection will only be opened while it's being used. If you wanted to create one shared connection and persist it through the entire application, you could adjust the functions to reflect your needs.

The given key was not present in the dictionary?

I having trouble deserializing this JSON.
The JSON looks like this:
{
"ticker": {
"high": 91.489,
"low": 88.3,
"avg": 89.8945,
"vol": 233637.9876,
"vol_cur": 2588.09448,
"last": 90.48,
"buy": 90.55,
"sell": 90.48,
"updated": 1372613806,
"server_time": 1372613807
}
}
And my function is this:
Private Function Btce(ByVal Address As String) As String
Dim rt As String = ""
Dim out As String
Dim wRequest As WebRequest
Dim wResponse As WebResponse
Dim SR As StreamReader
Dim Time As Date
Time = Now()
wRequest = WebRequest.Create(Address)
wResponse = wRequest.GetResponse
SR = New StreamReader(wResponse.GetResponseStream)
rt = SR.ReadToEnd
SR.Close()
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim testObj = js.Deserialize(rt, New Object().GetType())
Dim high = testObj("High")
Dim low = testObj("Low")
Dim avg = testObj("Average")
Dim vol = testObj("Volume")
Dim last = testObj("Last")
Dim buy = testObj("Buy")
Dim sell = testObj("Sell")
out = "Data from btc-e.com" + Environment.NewLine
out += (Time) + Environment.NewLine
out += "High: " + Environment.NewLine
out += "Low: " + Environment.NewLine
out += "Average: " + Environment.NewLine
out += "Volume: " + Environment.NewLine
out += "Last: " + Environment.NewLine
out += "Buy: " + Environment.NewLine
out += "Sell: "
Return out
End Function
Then I get this in the console:
An unhandled exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in Microsoft.VisualBasic.dll
Additional information: The given key was not present in the dictionary.
One of the problems is that you are looking for "Average" in testObj, but in the JSON it is "avg". And you are also looking for "Volume", not "vol".
In addition, the data returned by the deserialization is not a straight collection, it is a System.Collections.Dictionary(Of String, Object) where there is one entry for each of the representing the ticker objects in the json.
Each ticker object contains a String Key and a Value where Value is a System.Collections.Generic.KeyValuePair, which is case-sensitive. Value contains the collection of data (i.e. "high", 9.4189).
Based on this, your code should look like:
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim cObjects = js.Deserialize(rt, New Object().GetType())
Dim counter As Integer
Dim out As New System.Text.StringBuilder(1000)
' Use a stringbuilder to capture the output; much more efficient than constant string concat
out.Append("Data from btc-e.com").AppendLine()
For Each testObj In cObjects
Dim high = testObj.Value("high")
Dim low = testObj.Value("low")
Dim avg = testObj.Value("avg")
Dim vol = testObj.Value("vol")
Dim last = testObj.Value("last")
Dim buy = testObj.Value("buy")
Dim sell = testObj.Value("sell")
' Since you will be processing multiple records, show something
' in the output about where you are
counter += 1
out.Append("Element ").Append(counter).AppendLine()
out.Append(DateTime.Now).AppendLine()
out.Append("High: ").Append(high).AppendLine()
out.Append("Low: ").Append(low).AppendLine()
out.Append("Average: ").Append(avg).AppendLine()
out.Append("Volume: ").Append(vol).AppendLine()
out.Append("Last: ").Append(last).AppendLine()
out.Append("Buy: ").Append(buy).AppendLine()
out.Append("Sell: ").Append(sell).AppendLine()
Next
Return out.ToString()
When deserializing to an object graph, you can just use DeserializeObject
The keys you are looking for are not present under the object you've just deserialized, but are in fact keys of the object under "ticker".
The default equality comparer used for dictionaries is probably case sensitive. You might want to construct a new dictionary while explicitly specifying StringComparer.***IgnoreCase, where *** is any of Ordinal, InvariantCulture or CurrentCulture.
For example:
Dim testObj = js.Deserialize(Of Dictionary(Of String, Dictionary(Of String, Single)))(rt)("ticker")
testObj = New Dictionary(Of String, Single)(testObj, StringComparer.InvariantCultureIgnoreCase)
Dim high = testObj("High")