Having issues when 2 users are working with the same program - vb.net

Public Class DataAccess
Dim dataAcc As New DataAccess
Public Shared dtx As New DataTable
Private Shared ConStr As String = "Server = 10.18.206.30;database=PeajeFacturacion;User ID=FacturacionUsr;Password = ukShLq?U6&hNxDxN+67!XaYq"
Public Shared Function AddOneRecord(PK As String) As DataTable
Using cn As New SqlConnection(ConStr),
cmd As New SqlCommand("Select c.idCruce, c.FechaCruce, c.HoraCruce, c.claseVehiculo, c.Importe,
c.codigoCobro, n.nomCaseta
from dbo.Cruce AS c
JOIN dbo.nombre_caseta AS n
ON n.numCaseta=c.ClavePlaza
where c.CodigoCobro = #PK;", cn)
cmd.Parameters.Add("#PK", SqlDbType.VarChar).Value = PK
cn.Open()
dtx.Load(cmd.ExecuteReader)
End Using
Return dtx
End Function
End Class
I use that part to create the connection just like the example #Mary posted. Then:
Protected Sub btnAgregar_Click(sender As Object, e As EventArgs) Handles btnAgregar.ServerClick
Dim numTicket As String = txtNoTicket.Text
Dim dtx As New DataTable
Dim pk As String
pk = txtNoTicket.Text
Dim con2 As New SqlConnection
Dim cmd2 As New SqlCommand
Dim dr As SqlDataReader
Dim dtx2 As DataTable
Dim status As Boolean = False
'If Not Integer.TryParse(ticket.Text, pk) Then
If String.IsNullOrEmpty(pk) Then
'ScriptManager.RegisterStartupScript(Me, Page.GetType, "Script", "showDisplay();", True)
cFunciones.mostrarDivAlertaAA("Type a number", "dangerNormal", Me.Page, "")
Else
dtx = DataAccess.AddOneRecord(pk)
So when adding tickets the issue is the ticket 1 user adds, gets added to the other user even though they use different sessions and different computers. The program is in test fase right now.

You can get rid of Shared in the DatAccess class. Then each instance of the class will have its own data. Now you must declare an instance of the class and call the method on that instance.
Public Class DataAccess
Dim dataAcc As New DataAccess
Public dtx As New DataTable
Private ConStr As String = "Server = 10.18.206.30;database=PeajeFacturacion;User ID=FacturacionUsr;Password = ukShLq?U6&hNxDxN+67!XaYq"
Public Function AddOneRecord(PK As String) As DataTable
Using cn As New SqlConnection(ConStr),
cmd As New SqlCommand("Select c.idCruce, c.FechaCruce, c.HoraCruce, c.claseVehiculo, c.Importe,
c.codigoCobro, n.nomCaseta
from dbo.Cruce AS c
JOIN dbo.nombre_caseta AS n
ON n.numCaseta=c.ClavePlaza
where c.CodigoCobro = #PK;", cn)
cmd.Parameters.Add("#PK", SqlDbType.VarChar).Value = PK
cn.Open()
dtx.Load(cmd.ExecuteReader)
End Using
Return dtx
End Function
End Class
Protected Sub btnAgregar_Click(sender As Object, e As EventArgs) Handles btnAgregar.ServerClick
Dim dtx As New DataTable
Dim pk = txtNoTicket.Text
If String.IsNullOrEmpty(pk) Then
cFunciones.mostrarDivAlertaAA("Type a number", "dangerNormal", Me.Page, "")
Else
Dim datAcc As New DataAccess
dtx = datAcc.AddOneRecord(pk)
End If
End Sub

Related

FlowLayoutPanel Update & Delete Records in Database

Can someone tell me how i can manage Delete Record & Update Record from FlowLayoutPanel
So i have 1 user control :
then fetch the db:
Public Function FindTasksUser() As DataTable
Using cons As New SQLiteConnection(ServerStatus)
Using cmd As New SQLiteCommand()
cmd.Connection = cons
cmd.CommandText = "SELECT * FROM Tasks WHERE accountName = #GetUser ORDER BY [ID] ASC;"
cmd.Parameters.AddWithValue("#GetUser", UserUserAcc).ToString()
cons.Open()
Using sda As New SQLiteDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Function
then call the function in maincp form
Private Sub GenerateTasksUser()
FlowLayoutPanel3.Controls.Clear()
Dim dt As DataTable = New ClassBLL().GetTasksUser()
If dt IsNot Nothing Then
If dt.Rows.Count > 0 Then
Dim listItems As UserTasks() = New UserTasks(dt.Rows.Count - 1) {}
For i As Integer = 0 To 1 - 1
For Each row As DataRow In dt.Rows
Dim listItem As New UserTasks()
listItems(i) = listItem
listItems(i).TaskTitle = row("taskstitle").ToString()
listItems(i).TaskSubject = row("tasksubject").ToString()
listItems(i).TaskFrom = row("taskfromname").ToString()
FlowLayoutPanel3.Controls.Add(listItems(i))
Next
Next
End If
End If
End Sub
I have try inside user control img button this options, seems to delete the row, but im not sure is it the right one and how to delete from database
Private Sub Guna2ImageButton1_Click(sender As Object, e As EventArgs) Handles Guna2ImageButton1.Click
MainCP.FlowLayoutPanel3.Controls.RemoveByKey(Me.Name)
'or Directly to use Dispose
Dispose()
'or another option
Parent.Controls.Remove(Me)
'or another option i think is:
For Each control As Control In MainCP.FlowLayoutPanel3.Controls
MainCP.FlowLayoutPanel3.Controls.Remove(control)
control.Dispose()
Next
End Sub
And how to update in database when i click Checbox1 and button 2 to save the records in database in column "Status" with text "Done"
Most of the verbage to go with this code is provided in my comments. This has not been tested. Sqlite is an anethma to me. I gasp at the "flexable" typing.
The actual update code takes a list of the IDs from the original DataTable. You add the parameter once to the parameters collection and then loop through the values to update.
Public Class ClassBLL
Private ServerStatus As String = "Your connection string"
Public Sub UpdateRecords(lst As List(Of Integer))
Dim sql = "Update Tasks Set Status = 'Done' Where ID = #ID"
Using cn As New SQLiteConnection(ServerStatus),
cmd As New SQLiteCommand(sql, cn)
cmd.Parameters.Add("#ID", DbType.Int32)
cn.Open()
For Each i In lst
cmd.Parameters("#ID").Value = i
cmd.ExecuteNonQuery()
Next
End Using
End Sub
Public Function FindTasksUser(UserUserAcc As String) As DataTable
Dim dt As New DataTable()
Dim sql = "SELECT * FROM Tasks WHERE accountName = #GetUser ORDER BY [ID] ASC;"
Using cons As New SQLiteConnection(ServerStatus)
Using cmd As New SQLiteCommand(sql, cons)
cmd.Parameters.AddWithValue("#GetUser", UserUserAcc)
cons.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
End Using
Return dt
End Function
End Class
Private Class MainCP
Private UserAccount As String
Private Sub GenerateTasksUser()
FlowLayoutPanel3.Controls.Clear()
Dim dt As DataTable = New ClassBLL().FindTasksUser(UserAccount)
If dt IsNot Nothing Then
If dt.Rows.Count > 0 Then
Dim listItems As New List(Of UserTasks)
For Each row As DataRow In dt.Rows
Dim listItem As New UserTasks()
listItem.TaskTitle = row("taskstitle").ToString()
listItem.TaskSubject = row("tasksubject").ToString()
listItem.TaskFrom = row("taskfromname").ToString()
listItems.Add(listItem)
Next
FlowLayoutPanel3.Controls.AddRange(listItems.ToArray)
End If
End If
Dim IDList = (From row As DataRow In dt.AsEnumerable
Select CInt(row("ID"))).ToList
SomeOtherForm.ListOfIDs = IDList
End Sub
End Class
Public Class SomeOtherForm
Public Shared ListOfIDs As List(Of Integer)
Private Sub Guna2ImageButton1_Click(sender As Object, e As EventArgs) Handles Guna2ImageButton1.Click
'I don't think Me is referring to what you think it is.
For Each control As Control In MainCP.FlowLayoutPanel3.Controls
MainCP.FlowLayoutPanel3.Controls.Remove(control)
control.Dispose()
'You also need to get rid of any handlers you have added.
Next
Dim bll As New ClassBLL
bll.UpdateRecords(ListOfIDs)
End Sub
End Class
Public Class UserTasks
Inherits UserControl
Public Property TaskTitle As String
Public Property TaskSubject As String
Public Property TaskFrom As String
End Class

Populating a Menu from a Database

I found some very useful code on populating a menu from a database and customised it a bit but I am struggling to create a third level to menu as in the below example(2.1.1 and 2.1.2)
Home
About Us
2.1 Management Team
2.1.1 Team Member 1
2.1.2 Team Member 2
2.2 Company Information
Contact Us
I have listed my code below.
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports iconCloud_BL
Partial Class Main
Inherits System.Web.UI.MasterPage
Public Params As New List(Of SqlParameter)
Dim clsDatabase As New clsDatabaseLogic
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not Me.IsPostBack Then
Dim dt As DataTable = Me.GetData(0, 2)
PopulateMenu(dt, 0, Nothing)
End If
End Sub
Private Function GetData(parentMenuId As Integer, role As Integer) As DataTable
Dim query As String = "SELECT [menusMenuId], [menusTitle], [menusDescription], [menusUrl] FROM [configMenus] WHERE menusParentMenuId = #ParentMenuId AND menusRole = #Role"
Dim constr As String = ConfigurationManager.ConnectionStrings("iconDataConnections").ConnectionString
Using con As New SqlConnection(constr)
Dim dt As New DataTable()
Using cmd As New SqlCommand(query)
Using sda As New SqlDataAdapter()
cmd.Parameters.AddWithValue("#ParentMenuId", parentMenuId)
cmd.Parameters.AddWithValue("#Role", role)
cmd.CommandType = CommandType.Text
cmd.Connection = con
sda.SelectCommand = cmd
sda.Fill(dt)
End Using
End Using
Return dt
End Using
End Function
Private Sub PopulateMenu(dt As DataTable, parentMenuId As Integer, parentMenuItem As MenuItem)
Dim dtChild As DataTable
Dim currentPage As String = Path.GetFileName(Request.Url.AbsolutePath)
For Each row As DataRow In dt.Rows
Dim rowcount = getMaxRows()
Dim menuItem As New MenuItem() With {
.Value = row("menusMenuId").ToString(),
.Text = row("menusTitle").ToString(),
.NavigateUrl = row("menusUrl").ToString(),
.Selected = row("menusUrl").ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase)
}
If parentMenuId = 0 Then
mainMenu.Items.Add(menuItem)
dtChild = Me.GetData(Integer.Parse(menuItem.Value), 2)
PopulateMenu(dtChild, Integer.Parse(menuItem.Value), menuItem)
ElseIf parentMenuId > 0 Then
For i As Integer = 0 To rowcount
mainMenu.Items.Add(menuItem)
dtChild = Me.GetData(Integer.Parse(i), 2)
PopulateMenu(dtChild, Integer.Parse(i), menuItem)
Next
Else
parentMenuItem.ChildItems.Add(menuItem)
End If
Next
End Sub
Public Function getMaxRows()
clsDatabase.SQLCmd.CommandText = "sp_iconCloud_configMenuRowsCount"
clsDatabase.SQLCmd.CommandType = CommandType.StoredProcedure
clsDatabase.SQLCmd.Connection = clsDatabase.SQLConn
clsDatabase.SQLConn.Open()
Dim count As Integer = clsDatabase.SQLCmd.ExecuteScalar()
clsDatabase.SQLConn.Close()
clsDatabase.SQLCmd.Parameters.Clear()
Return count
End Function
End Class

SQLite Query is not working properly - can't load datatable

I am trying to write a function that queries the sqlite db I have. For some reason it does not work properly. Below are the supporting functions that I am using. I can get it to add tables perfectly fine.
Private Sub GetSqlConnection()
Me.SQLConnectionString = New SQLiteConnectionStringBuilder
Me.SQLConnectionString.DataSource = Path.Combine(Application.StartupPath, "mydb.sqlite")
Me.SQLConnectionString.Version = 3
SQLConnection = New SQLiteConnection(Me.SQLConnectionString.ConnectionString)
End Sub
Private Sub Query(ByVal SQLString As String)
Try
Dim SQLiteDRObj As SQLiteDataReader
Dim ResultsTableObj As DataTable = Nothing
Dim ResultSet As DataSet = Nothing
Dim SQLAdapter As SQLiteDataAdapter = Nothing
Me.GetSqlConnection()
SQLConnection.Open()
SQLCommand = New SQLiteCommand(SQLConnection)
SQLCommand.CommandText = SQLString
SQLiteDRObj = SQLCommand.ExecuteReader()
ResultsTableObj.Load(SQLiteDRObj)
SQLiteDRObj.Close()
SQLConnection.Close()
SQLConnection.Dispose()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
object shows as filled http://josephberardi.com/stackoverflow/objfilled.png
object shows as filled http://josephberardi.com/stackoverflow/exception.png
ResultsTableObj is Nothing when you call the Load method
Change this line to
Private Sub Query(ByVal SQLString As String)
Try
....
Dim ResultsTableObj As DataTable = New DataTable()
....

Multithreading Safe Calls not populating comboboxes vb.net

just curious on what im doing wrong here, the principle should work. Can anyone give me a hand?
The Code runs fine, but seems to not add them into my comboboxes
normal thread start like so
t1 = New Thread(New ThreadStart(AddressOf GetNewClientData))
t1.Start()
data is not empty or null... :)
Function GetNewClientData()
Try
Dim con As New SqlConnection
Dim myConString As String = My.Settings.ConString
Dim objcommand As SqlCommand = New SqlCommand
With objcommand
.Connection = con
Dim cmdText As String = "SELECT distinct Applicant,Client,Market,Project from AAClient order by Client"
.CommandText = cmdText
End With
con.ConnectionString = myConString
con.Open()
Using readerObj As SqlClient.SqlDataReader = objcommand.ExecuteReader
'This will loop through all returned records
While readerObj.Read
addClientInvoke(readerObj("Client").ToString)
addApplicantInvoke(readerObj("Client").ToString)
addMarketInvoke(readerObj("Client").ToString)
addProjectInvoke(readerObj("Client").ToString)
End While
End Using
con.Close()
Catch ex As Exception
End Try
Return Nothing
End Function
Delegate Sub addApplicant(s As String)
Sub addApplicantInvoke(ByVal s As String)
If CreateNewSite.cbApplicant.InvokeRequired Then
Dim d As New addApplicant(AddressOf addApplicantInvoke)
CreateNewSite.cbApplicant.Invoke(d, New Object() {s})
Else
CreateNewSite.cbApplicant.Items.Add(s)
End If
End Sub
Delegate Sub addClient(s As String)
Sub addClientInvoke(ByVal s As String)
If CreateNewSite.cbClient.InvokeRequired Then
Dim d As New addClient(AddressOf addClientInvoke)
CreateNewSite.cbClient.Invoke(d, New Object() {s})
Else
CreateNewSite.cbClient.Items.Add(s)
End If
End Sub
Delegate Sub addMarket(s As String)
Sub addMarketInvoke(ByVal s As String)
If CreateNewSite.cbMarket.InvokeRequired Then
Dim d As New addMarket(AddressOf addMarketInvoke)
CreateNewSite.cbMarket.Invoke(d, New Object() {s})
Else
CreateNewSite.cbMarket.Items.Add(s)
End If
End Sub
Delegate Sub addProject(s As String)
Sub addProjectInvoke(ByVal s As String)
If CreateNewSite.cbProject.InvokeRequired Then
Dim d As New addProject(AddressOf addProjectInvoke)
CreateNewSite.cbProject.Invoke(d, New Object() {s})
Else
CreateNewSite.cbProject.Items.Add(s)
End If
End Sub
possibly how i'm calling the delegate??
any help is appreciated
**** thanks to #jods here is the working code with one of the invoke methods****
starting thread in another modul
t1 = New Thread(New ParameterizedThreadStart(AddressOf GetNewClientData))
t1.Start(Me)
Code within the Modul
Function GetNewClientData(ByVal oldForm As CreateNewSite)
Try
Dim con As New SqlConnection
Dim myConString As String = My.Settings.ConString
Dim objcommand As SqlCommand = New SqlCommand
With objcommand
.Connection = con
Dim cmdText As String = "SELECT distinct Applicant,Client,Market,Project from AAClient order by Client"
.CommandText = cmdText
End With
con.ConnectionString = myConString
con.Open()
Using readerObj As SqlClient.SqlDataReader = objcommand.ExecuteReader
'This will loop through all returned records
While readerObj.Read
addApplicantInvoke(readerObj("Applicant").ToString, oldForm)
addClientInvoke(readerObj("Client").ToString)
addMarketInvoke(readerObj("Market").ToString)
addProjectInvoke(readerObj("Project").ToString)
End While
End Using
con.Close()
Catch ex As Exception
MsgBox(ex)
End Try
Return Nothing
End Function
Delegate Sub addApplicant(s As String, oldform As CreateNewSite)
Sub addApplicantInvoke(ByVal s As String, ByVal oldform As CreateNewSite)
If oldform.InvokeRequired Then
Dim d As New addApplicant(AddressOf addApplicantInvoke)
oldform.cbApplicant.Invoke(d, New Object() {s, oldform})
Else
oldform.cbApplicant.Items.Add(s)
End If
End Sub
The problem is CreateNewSite.cbProject. CreateNewSite is not your form instance. It's a nifty :p VB.NET feature called the default form instance:
VB has a concept of "Default Form Instances". For every Form in the application's namespace, there will be a default instance created in the My namespace under the Forms property.
You need to pass the correct form instance (i.e. 'Me' / 'this') to your background thread.

Error: A SQLParamenter wtih ParameterName #myparm is not contained by this SQLParameter Collection

Good Morning,
I'm working on an ASP.NET 3.5 webforms application and have written the following code:
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("Diel_inventoryConnectionString").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim adapter1 As New SqlDataAdapter
adapter1.SelectCommand = New SqlCommand
adapter1.SelectCommand.CommandType = CommandType.StoredProcedure
adapter1.SelectCommand.CommandText = "PartSproc"
Dim parmNSN As New SqlParameter("#NSN", SqlDbType.NVarChar)
Dim parmName As New SqlParameter("#PartName", SqlDbType.NVarChar)
txtNSN.Text = adapter1.SelectCommand.Parameters("#NSN").Value
txtSearch.Text = adapter1.SelectCommand.Parameters("#PartName").Value
Dim dt As New DataTable()
adapter1.Fill(dt)
MySearch.DataSource = dt
MySearch.DataBind()
End Sub
When I run the page, I receive the error A SQLParameter with #NSN is not contained by this SQLParameter Collection. I tried using apostrophes around the #NSN and #PartName but that does not work either and presents expression expected error.
How might I rectify the above code so that it references the #NSN and #PartName parameters correctly?
EDIT: New Code below
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("Diel_inventoryConnectionString").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim cmd As New SqlCommand("PartSproc", con)
cmd.CommandType = CommandType.StoredProcedure
Dim adapter1 As New SqlDataAdapter
Dim parmNSN As New SqlParameter("#NSN", SqlDbType.NVarChar)
Dim parmName As New SqlParameter("#PartName", SqlDbType.NVarChar)
adapter1.SelectCommand.Parameters.Add(parmNSN)
adapter1.SelectCommand.Parameters.Add(parmName)
adapter1.SelectCommand.Parameters("#NSN").Value = txtNSN.Text
adapter1.SelectCommand.Parameters("#PartName").Value = txtSearch.Text
Using con
Dim dt As New DataTable()
adapter1.SelectCommand = cmd
adapter1.Fill(dt)
MySearch.DataSource = dt
MySearch.DataBind()
End Using
End Sub
I now receive an error Object reference not set to an instance of an object referencing the add parameter parmNSN. Do I really need those to add paraameter statements since I've already set them equal to the text boxes below?
Thanks,
Sid
I think you accidentally transposed the assignment of the parameter values - try this instead:
adapter1.SelectCommand.Parameters("#NSN").Value = txtNSN.Text
adapter1.SelectCommand.Parameters("#PartName").Value = txtSearch.Text
Did you read the error message? The Sqlparameter you create is never added to the Sqlparameter collection of the command ;) This is what the error message also ells you.
You create the parameters, but they "hang in the air" so to say.
To add to what Andrew & TomTom said, you need to add the parameters to the parameters collection of SelectCommand.
Something like
adapter1.SelectCommand.Parameters.Add(parmNSN);
adapter1.SelectCommand.Parameters.Add(parmName);
Do this before you make a call to ExecuteReader() or ExecuteScalar