Object not instantiated? - sql

I get the following error when running this code. I am trying to query data out of my SQL database using parameters and appear to have most everything I need, but I can't quite figure out the error on this one. My debugging attempts have failed:
"Object reference not set to an instance of an object"
Option Strict Off
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
Imports System.Drawing
Imports System.IO
Public Class Form1
Dim thisConnection = New SqlConnection("Server=myserver;Database=myDatabase;User Id=username;Password=password")
Dim DBCommand As SqlCommand
Dim myReader As SqlDataReader
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
thisConnection.Open()
Console.WriteLine("Connect Open")
DBCommand.Parameters.AddWithValue("#dateOld", "20151215")
DBCommand.Parameters.AddWithValue("#dateNew", "20151231")
Dim myReader = DBCommand.ExecuteReader()
Dim fNextResult As Boolean = True
Dim fileName As String = "C:\Users\Documents\MomInt.txt"
DBCommand = New SqlCommand("*****SQL code*****")
Dim outputStream As StreamWriter = New StreamWriter(fileName)
'Get all values from the current item on the reader as long asRead() returns true...
Do While myReader.Read
'make an array the length of the available fields
Dim values(myReader.FieldCount - 1) As Object
'get all the field values
myReader.GetValues(values)
'write the text version of each value to a comma seperated string
Dim line As String = String.Join(",", values)
'write the csv line to the file
outputStream.WriteLine(line)
Loop
myReader.Close()
outputStream.Close()
Me.Text = "Success!"
Me.BackColor = Color.Chartreuse()
thisConnection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Connection Failed!", MessageBoxButtons.AbortRetryIgnore)
End Try
End Sub
End Class

Related

How do i get the data to my database using vb.net (class, module and form)

I hope the title is enough to understand my problem, I already installed whats need to run the ADO.NET, I already have a connection string in my module and data query in my class,
Imports System.Data
Imports System.Data.OleDb
Module GlobalVariables
Public sGlobalConnectionString As String
Friend conString As String
Public dr As OleDbDataReader
Sub Main()
Dim sGlobalConnectionString As New OleDb.OleDbConnection
Dim sDataserver As String
Dim sDatabaseName As String
Dim sDatabaseConnection As String
sDataserver = "localhost"
sDatabaseName = "employee"
sDatabaseConnection = "Driver={MariaDB ODBC 3.1 Driver}; SERVER=" & sDataserver & "; UID=root;PWD=******; Database=" & sDatabaseName & "; PORT=3307; OPTION=3"
sGlobalConnectionString = New OleDb.OleDbConnection(conString)
End Sub
End Module
this is my class
Imports System.Data.OleDb
Public Class clsDataQuery
Public Shared Sub Class_initialize()
Dim con = New OleDb.OleDbConnection
con.ConnectionString = sGlobalConnectionString
con.Open()
End Sub
Public Shared Sub Class_Terminate()
Dim con = New OleDb.OleDbConnection
If Not con Is Nothing Then
con.Close()
con = Nothing
End If
End Sub
Public Function GetRecordDataSet(ByVal sStoreProcName As String, ByVal sParameterList As String)
Dim cmd As New OleDbCommand()
Dim arrParameter, arrParamName
Dim sParamName As String
Dim sDataValue
Dim lCtr As Long
On Error GoTo errhandler
cmd.Connection = New OleDb.OleDbConnection
cmd.CommandTimeout = 1800
cmd.CommandText = CommandType.Text
If Not Trim(sParameterList) = "" Then
arrParameter = Split(sParameterList, "|", , vbTextCompare)
If UBound(arrParameter) >= 0 And IsArray(arrParameter) Then
For lCtr = 0 To UBound(arrParameter)
arrParamName = Split(arrParameter(lCtr), "$", , vbTextCompare)
sParamName = arrParamName(0)
sDataValue = arrParamName(1)
cmd.Parameters.Item(sParamName) = sDataValue
Next lCtr
End If
End If
GetRecordDataSet = cmd.ExecuteReader
cmd = Nothing
Exit Function
errhandler:
MessageBox.Show("Records Not Found!!!")
End Function
End Class
if this button is click, the value of Textbox1.text will search in the database if it is exist, if exist it will continue into another form if not error message will appear, how do i do that?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim username = txtbox_lastname.Text
If username <> "" Then
Try
clsDataQuery.Class_initialize()
Catch ex As Exception
MessageBox.Show("No Record Found")
End Try
Else
MessageBox.Show("No Record Found!!!")
End If
End Sub
If this is MariaDb then you want to use the provider for MySql. Not ODBC and not OleDb. No wonder you are having problems. There is not much information available for this database compared to the usual Access database used for beginners.
Do not declare database objects anywhere but the method they are used in. You can declare a Private variable for the connection string at the class level.
Although one of these is a Module level variable and one is a local variable, it is very confusing and bad practice. Why would you call a connection object a String?
Public sGlobalConnectionString As String
Dim sGlobalConnectionString As New OleDb.OleDbConnection
BTW, it is fine to declare and initialize your variables in a single line.
Dim sDataserver = "localhost"
You create a new connection on the first line of Sub Main, then you throw it away and create another new connection on the last line. Since sDataServer and sDatabaseName are hard coded why not just put the literal values directly into the connection string.
After all that you pass conStr to the constructor of the connection instead of sDatabaseConnection. Why were you building sDatabaseConnection (another misnomer, it is not a connection, its a string) and then never use it. Has conStr been set elsewhere?
At any rate, throw out the whole module.
Moving on to your DataQuery class. First, the name should begin with an upper case letter.
Get rid of Class_initialize. We don't want to create or open any connection except in the method where it is used. You never call Class_Terminate so dump that too.
The GetRecordDataSet method...
Functions in vb.net require a datatype. The old VB6 syntax of assigning the return value to the name of the function will work but it is not the .net way. In vb.net we use the Return keyword.
You have not initialized or given a datatype to arrParameter, arrParamName or sDataValue which violates Option Strict. (You do have Option Strict On, don't you?)
On Error GoTo errhandler is a sad leftover from VB6. .net languages have structured error handling with Try...Catch...Finally...End Try.
cmd.Connection = New OleDb.OleDbConnection sets the connection property however this new connection has no connection string.
cmd.CommandText = CommandType.Text Now this is just silly. What I think you want is cmd.CommandType =CommandType.StoredProcedure
Using...End Using blocks take care of declaring, closing and disposing database objects even if there is an error. You don't want to return a DataReader because a reader requires an open connection. cmd.ExecuteReader returns a DataReader. I used the reader to load a DataTable and returned the DataTable.
It seems you are trying to develop a factory pattern but it is way too advanced for your. Just pass value and call a method specific to what your are searching for. You want your DataQuery code to be independent from your user interface. The Button code doesn't care where the data is coming from. It could be a database, a text file, or a web service. Likewise the DataQuery code doesn't know where the values are coming from. It could be a WinForms app, a web application or a phone app.
Public Class DataQuery
Private Shared ConStr As String = "server=localhost;userid=root;database=employee"
Public Shared Function SearchByLastName(ByVal LName As String) As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection(ConStr),
cmd As New MySqlCommand("Select * From PutTableNameHere Where LastName = #LName", cn)
cmd.Parameters.Add("#LName", MySqlDbType.VarChar).Value = LName
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
End Class
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim dt As DataTable = Nothing
If txtbox_lastname.Text <> "" Then
Try
dt = DataQuery.SearchByLastName(txtbox_lastname.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End If
DataGridView1.DataSource = dt
End Sub
Before answering, I really think that the GetRecordDataSet() at the very least a darn good tidy up, better yet removed from history
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim username = txtbox_lastname.Text
If username <> "" Then
Try
clsDataQuery.Class_initialize()
Dim reader = GetRecordDataSet("storedProcName", txtbox_lastName.Text)
Do While reader.Read()
'Process record etc
Loop
Catch ex As Exception
MessageBox.Show("No Record Found")
End Try
Else
MessageBox.Show("No Record Found!!!")
End If
End Sub
Might be a bit rough, but should get you heading in the right direction

Why I am getting System.Data.DataRowViewā€¯ instead of real values from my Listbox in vb.net

Could someone help here?
I need to extract data from a Database into a combolistbox in VB.net. I have got the data, but now find that The first and the 'x' line need to be removed from the combolistbox (they are validation entries for another software) and shouldn't be selected for this application.
I tried to simply remove the offending entries from lists by using :- cbCubeARivet.Items.RemoveAt(index), but had an error letting me know I cannot use "Items" with a DataSource.
I decided to send the data to a listbox, and then try to transfer the entries to the combolistbox. This then lead me to getting multiple entries of System.Data.DataRowView in the combolist box. To demonstrate my problem I include an example code modified from MSDN.
Imports System
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Collections
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Populate the list box using an array as DataSource.
Dim SQLConnectionString As String = "Data Source=HL605\RIVWARE;Database=RIVWARE;Integrated Security=true;"
Dim mySQLConnection As New SqlConnection(SQLConnectionString)
mySQLConnection.Open()
Dim SQLDataTable As New System.Data.DataTable
'Create new DataAdapter
'Use DataAdapter to fill DataTable
Dim mySQLDataAdapter = New SqlDataAdapter("SELECT * FROM [Rivware].[dbo].[RivetTypes]", mySQLConnection)
mySQLDataAdapter.Fill(SQLDataTable)
ListBox1.DataSource = SQLDataTable
ListBox1.DisplayMember = "RivetType"
'original code from MSDN
'Dim USStates As New ArrayList()
'USStates.Add(New USState("Alabama", "AL"))
'USStates.Add(New USState("Washington", "WA"))
'USStates.Add(New USState("West Virginia", "WV"))
'USStates.Add(New USState("Wisconsin", "WI"))
'USStates.Add(New USState("Wyoming", "WY"))
'ListBox1.DataSource = USStates
' Set the long name as the property to be displayed and the short
' name as the value to be returned when a row is selected. Here
' these are properties; if we were binding to a database table or
' query these could be column names.
' Bind the SelectedValueChanged event to our handler for it.
AddHandler ListBox1.SelectedValueChanged, AddressOf ListBox1_SelectedValueChanged
' Ensure the form opens with no rows selected.
ListBox1.ClearSelected()
End Sub 'NewNew
Private Sub ListBox1_SelectedValueChanged(ByVal sender As Object, ByVal e As EventArgs)
If ListBox1.SelectedIndex <> -1 Then
TextBox1.Text = ListBox1.SelectedValue.ToString()
' If we also wanted to get the displayed text we could use
' the SelectedItem item property:
' Dim s = CType(ListBox1.SelectedItem, USState).LongName
End If
End Sub
End Class 'ListBoxSample3
Public Class USState
Private myShortName As String
Private myLongName As String
Public Sub New(ByVal strLongName As String, ByVal strShortName As String)
Me.myShortName = strShortName
Me.myLongName = strLongName
End Sub 'NewNew
Public ReadOnly Property ShortName() As String
Get
Return myShortName
End Get
End Property
Public ReadOnly Property LongName() As String
Get
Return myLongName
End Get
End Property
End Class 'USState
I may not get this correct so here goes, the following uses mocked up data to display a string in both a ListBox and ComboBox where a integer is available by casting the current item as a DataRowView, access Row then access the data via Row.Field(Of Integer)("ID").
In the code I use a copy of the underlying DataTable for the ComboBox as using the same data table for listbox and combobox will cause one to traverse when is generally unwanted. The cast aspect would be done in another event but wanted to stay simple. Again I may not be on track here, let me know and can adjust to better suit your question.
Code using Option Infer On for the Linq anonymous statement which could be strongly typed too.
Dim dt As New DataTable
dt.Columns.Add(New DataColumn With {.ColumnName = "ID", .DataType = GetType(Integer)})
dt.Columns.Add(New DataColumn With {.ColumnName = "Name", .DataType = GetType(String)})
Dim data =
(
From M In System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
Where Not String.IsNullOrEmpty(M)).ToList.Select(
Function(monthName, index) New With
{
.ID = index, .Name = monthName
}
).ToList
For Each item In data
dt.Rows.Add(New Object() {item.ID, item.Name})
Next
ListBox1.DataSource = dt
ListBox1.DisplayMember = "Name"
ComboBox1.DataSource = dt.Copy
ComboBox1.DisplayMember = "Name"
Dim theTable As DataTable = CType(ComboBox1.DataSource, DataTable)
Dim theRow As DataRow = theTable.AsEnumerable _
.Where(
Function(row) row.Field(Of String)("Name") = "September") _
.FirstOrDefault()
If theRow IsNot Nothing Then
theTable.Rows.Remove(theRow)
End If
Thanks again #Karen Payne,
I used your code to lead me in the right direction.
I created a new application and added a textbox, and two Listboxes, then paste the code. To run you will need to point to your own Server, Database, and Table.
This is what I came up with. It is useful as this will give you the actual data in a useable form:-
Imports System
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Collections
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' get the data
Dim SQLConnectionString As String = "Data Source=HL605\RIVWARE;Database=RIVWARE;Integrated Security=true;"
Dim mySQLConnection As New SqlConnection(SQLConnectionString)
' Populate the list box using an array as DataSource.
mySQLConnection.Open()
Dim SQLDataTable As New System.Data.DataTable
'Create new DataAdapter
Dim mySQLDataAdapter = New SqlDataAdapter("SELECT * FROM [Rivware].[dbo].[RivetTypes]", mySQLConnection)
mySQLDataAdapter.Fill(SQLDataTable)
ListBox1.DataSource = SQLDataTable
ListBox1.DisplayMember = "RivetType"
' remove validation data from list
Dim Count As Integer
Dim X As Integer
'get the column of data to search for
For Count = 0 To ListBox1.DataSource.Columns.Count - 1
X = InStr(ListBox1.DataSource.Columns.Item(Count).ToString, "Name")
If X <> 0 Then Exit For
Next
' now search for any invalid rows, in that column. those containing "---"
Dim TheTable As DataTable = CType(ListBox1.DataSource, DataTable)
Dim theRow As DataRow() = TheTable.Select()
Dim RowNumber As Integer
For RowNumber = 0 To UBound(theRow) - 1
If theRow(RowNumber).Item(Count).ToString <> "---" Then
' data is OK so transer it to the other listbox
ListBox2.Items.Add(theRow(RowNumber).Item(Count - 1).ToString)
End If
Next
ListBox2.ClearSelected()
End Sub 'NewNew
Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
TextBox1.Text = ListBox2.SelectedItem.ToString()
End Sub
End Class 'ListBoxSample3

referencing a dll in a windows service

I wrote an OPC client using interop.opcautomation.dll. I wrote it as a windows form in vb 2010 express. everything is currently working well. I wanted to make it a windows service though. The problem I am having is that it will not connect to the opc server when I run the service. I get the following exception "Object reference not set to an instance of an object.- OPC Connect Error" I get the exception at the end of the code where I am trying to connect. Below is the code. Thanks for any input, it is appreciated.
Imports System.ServiceProcess
Imports System.Threading
Imports System.Text
Imports System.Windows.Forms
Imports System
Imports System.IO
Imports System.IO.File
Imports System.Net
Imports OPCAutomation
Public Class Service1
Inherits System.ServiceProcess.ServiceBase
Dim WithEvents OPCServer As OPCAutomation.OPCServer
Dim WithEvents ConnectedGroup As OPCAutomation.OPCGroup
Dim Batch As String
Dim Group As String
Dim Press As String
Dim Line As String
Dim sWidth As String
Dim sHeight As String
Dim sBifold As String
Dim sCore As String
Dim StartUp As Integer
Dim iHandle As Integer
Dim sError As String
Dim ItemIds(60) As String
Dim ServerHandles As Array
Dim ClientHandles(60) As Integer
Dim ServerErrors As Array
Dim SnapServerURL As String = "snapserver"
Private trd As Thread
Private Stopping As Boolean = False
Private StoppedEvent As New ManualResetEvent(False)
Protected Overrides Sub OnStart(ByVal args() As String)
EventLog.WriteEntry("PressControlService in OnStart.")
trd = New Thread(AddressOf ServiceMain)
trd.IsBackground = True
trd.Start()
End Sub
Protected Overrides Sub OnStop()
EventLog.WriteEntry("PressControlService in OnStop.")
Me.Stopping = True
Me.StoppedEvent.WaitOne()
End Sub
Private Sub ServiceMain()
Dim strOPCServerName As String
Dim strOPCServerNode As String
Dim strOPCGroupName As String
Dim i As Integer
StartUp = 0
strOPCServerName = "Kepware.KEPServerEX.V5"
strOPCServerNode = ""
strOPCGroupName = "MyGroup"
Try
Dim OPCServer As New OPCAutomation.OPCServer
Catch ex As Exception
EventLog.WriteEntry(ex.Message & " - New OPC Server")
End Try
Try
OPCServer.Connect(strOPCServerName, strOPCServerNode)
Catch ex As Exception
EventLog.WriteEntry(ex.Message & "- OPC Connect Error")
End Try
End Sub
End Class

Insert data into database by linking class to btnRegister

I am new for programming and trying to learn VB.net through youtube tutorials.
I created a windows form app for users to create new account.
I am also trying to apply the hash and salt technique to store the password for security reason.
The main issue I have is maintaining successful connection between a two class I called "DatabaseManager" and "DataHandling", codes in "btnRegister" and the database called "Test".
The program runs fine. When I click btnRegister after filling the "txtUsername.Text" and "txtPassword.Text", it gives me error that says "ColumnUser_IDdoes not allow nulls.".
So this is where I keep getting issues. I tried to make it work a lot and I have no idea why it is not recording the new data. Here are my codes. I use V Studio 2012. Please help.
Just to be clear I copied some of the codes from internet and tried to make them work with the class
Imports System
Imports System.IO
Imports System.Text
Imports System.Data.OleDb
Imports System.Data
Imports System.Windows.Forms
Imports System.Data.SqlClient
Imports System.Security.Cryptography
Public Class DatabaseManager
Private Const CONNECTION_STRING As String = "Data Source=(localdb)\Projects;Initial Catalog=Test;Integrated Security=True"
Private connection As SqlConnection = Nothing
Private usersdataadapter As SqlDataAdapter = Nothing
Sub New()
connection = New SqlConnection(CONNECTION_STRING)
usersdataadapter = New SqlDataAdapter("select * from Test", connection)
End Sub
Public Sub Register(ByVal Username As String, ByVal Password As String)
connection.Open()
Dim usersDataset As New DataSet()
usersdataadapter.FillSchema(usersDataset, SchemaType.Source, "Test")
Dim table As DataTable = usersDataset.Tables("Test")
Dim newRecord As DataRow = table.NewRow()
newRecord("Username") = Username
newRecord("Password") = Password
table.Rows.Add(newRecord)
Dim command As New SqlCommandBuilder(usersdataadapter)
usersdataadapter.Update(usersDataset, "Test")
usersDataset.Dispose()
connection.Close()
End Sub
Public Function UsernameAvailable(ByVal username As String) As Boolean
Dim usersDataset As New DataSet()
usersdataadapter.FillSchema(usersDataset, SchemaType.Source, "Test")
usersdataadapter.Fill(usersDataset, "Test")
Dim table As DataTable = usersDataset.Tables("Test")
For i As Integer = 0 To table.Rows.Count - 1
Dim currnetUser As String = table.Rows(i)("Username").ToString().Trim()
If (currnetUser = username) Then
usersDataset.Dispose()
connection.Close()
Return False
End If
Next
Return True
usersDataset.Dispose()
connection.Close()
End Function
Public Function Login(ByVal username As String, ByVal password As String) As Boolean
Dim usersDataset As New DataSet()
usersdataadapter.FillSchema(usersDataset, SchemaType.Source, "Test")
usersdataadapter.Fill(usersDataset, "Test")
Dim table As DataTable = usersDataset.Tables("Test")
For i As Integer = 0 To table.Rows.Count - 1
Dim currnetUser As String = table.Rows(i)("Username").ToString().Trim()
Dim currnetPassword As String = table.Rows(i)("Password").ToString().Trim()
If (currnetUser = username AndAlso currnetPassword = password) Then
usersDataset.Dispose()
connection.Close()
Return True
End If
Next
usersDataset.Dispose()
connection.Close()
Return False
End Function
End Class
Imports System
Imports System.Text
Imports System.Data.OleDb
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
Imports System.Security.Cryptography
Public Class DataHandling
Inherits Form1
Public Shared Function GenerateRandomString() As String
Dim i_key As Integer
Dim Random1 As Single
Dim arrIndex As Int16
Dim sb As New StringBuilder
Dim RandomLetter As String
Dim KeyLetters As String = "abcdefghijklmnopqrstuvwxyz"
Dim KeyNumbers As String = "0123456789"
Dim KeyLength As Integer = 12
Dim LettersArray = KeyLetters.ToCharArray
Dim NumbersArray = KeyNumbers.ToCharArray
For i_key = 1 To KeyLength
Randomize()
Random1 = Rnd()
arrIndex = -1
If (CType(Random1 * 111, Integer)) Mod 2 = 0 Then
Do While arrIndex < 0
arrIndex = _
Convert.ToInt16(LettersArray.GetUpperBound(0) _
* Random1)
Loop
RandomLetter = LettersArray(arrIndex)
If (CType(arrIndex * Random1 * 99, Integer)) Mod 2 <> 0 Then
RandomLetter = LettersArray(arrIndex).ToString
RandomLetter = RandomLetter.ToUpper
End If
sb.Append(RandomLetter)
Else
Do While arrIndex < 0
arrIndex = _
Convert.ToInt16(NumbersArray.GetUpperBound(0) _
* Random1)
Loop
sb.Append(NumbersArray(arrIndex))
End If
Next
Return sb.ToString
End Function
Public Shared Function CheckPassword(ByVal plainText As String, ByVal passwordHash As Byte(), ByVal salt As Byte()) As Boolean
Dim encoding As New System.Text.UTF8Encoding
'Retrieve Salt String from byte array
Dim saltStr As String = encoding.GetString(salt)
Dim hashable As String = Trim(plainText) & Trim(saltStr)
' Convert into hash strings
Dim testhash As String = EncryptStringAsHash(hashable)
Dim realHash As String = encoding.GetString(passwordHash)
' Compare and return result
Return testhash = realHash
End Function
Public Shared Function EncryptStringAsHash(ByVal value As String) As String
Dim encoding As New System.Text.UTF8Encoding
Dim stringBytes As Byte() = encoding.GetBytes(value)
Dim SHhash As SHA512Managed = New SHA512Managed
Dim hash As String = Convert.ToBase64String(SHhash.ComputeHash(stringBytes))
Return hash
End Function
Public Shared Function ConvertStringToByteArray(ByVal value As String) As Byte()
Dim encoding As New System.Text.UTF8Encoding
Return encoding.GetBytes(value)
End Function
End Class
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Imports System.Data.OleDb
Imports System.Windows.Forms
Imports System.Data.OleDb.OleDbConnection
Imports System.Data.SqlClient
Public Class Form1
Dim maxrows As Integer
Dim incdec As Integer
Dim con As New OleDb.OleDbConnection
Dim dbprovider As String
Dim dbsource As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New OleDbConnection
Dim dbprovider As String
Dim dbsource As String
dbprovider = "PROVIDER = Microsoft.ACE.OLEDB.12.0;"
dbsource = "Data Source=(localdb)\Projects;Initial Catalog=Test;Integrated Security=True"
con.ConnectionString = dbprovider & dbsource
End Sub
Private Sub btnRegister_Click(sender As Object, e As EventArgs) Handles btnRegister.Click
Dim dbmanager As New DatabaseManager
Dim Data As New DataHandling
'Generate Hash and Salt for password
Dim salt As String = DataHandling.GenerateRandomString
Dim hashable As String = Trim(txtPassword.Text) & Trim(salt) 'txtPassword.Text used to be password
Dim hash As String = DataHandling.EncryptStringAsHash(hashable)
Dim confirmationId As String = System.Guid.NewGuid.ToString
Dim reg As user
reg.Username = txtUsername.Text 'txtUsername.Text used to be username
reg.Password = DataHandling.ConvertStringToByteArray(hash)
reg.Salt = DataHandling.ConvertStringToByteArray(salt)
If dbmanager.UsernameAvailable(txtUsername.Text) Then
dbmanager.Register(txtUsername.Text, txtPassword.Text)
Dim password As String
If txtPassword.Text = String.Empty Then
password = "217tABCDEF42#$tolq"
Else
password = txtPassword.Text
End If
Dim salt As String = GenerateRandomString(12)
Dim hashable As String = Trim(password) & Trim(salt)
MsgBox("Hashable = " & hashable)
Dim hash As String = EncryptStringAsHash(hashable)
CheckPassword(password, ConvertStringToByteArray(hash), ConvertStringToByteArray(salt))
frmAccessGranted.Show()
Me.Hide()
Else
MessageBox.Show("Cannot Register, Username Already Taken!")
End If
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtUsername.Clear()
txtPassword.Clear()
End Sub
End Class
I think your User table User_id value is just missing Identity Specification option. It makes the User_id field to be generated automatically and increased by 1 (by default) for each User you add into
If you have SQL Server management studio you can put this option on:
Right click User table -> Select "Desing" -> Select "User_id" field -> in "Column Propetries" window put "Indentity Specification" option to "Yes" and save
Example SQL Command to create table could be something like this:
CREATE TABLE User (User_id BIGINT IDENTITY NOT NULL, Username NVARCHAR(100) NOT NULL, Password NVARCHAR(100) NOT NULL)
The problem in your code is not in the VB side, it is in the database.
You have set primary key to UserId but you are not passing any values to the userId, you are just passing values to the user name and password.
So there are two ways to solve this issues
you can send userid also from the VB code
you can just make the column UserId as autoincrement field by the following code
CREATE TABLE [dbo].[Test1](
[id] [int] IDENTITY(1,1) NOT NULL,
YourColumnname1 datatype,
YourColumnname2 datatype
)
This works only in the later versions of sqlserver 2008
alter table tablename
alter column columnname
add Identity(100,1)
To know more Click here

SQLBulkCopy does not work

This is my first attempt to use sqlbulkcopy class. When I run it, nothing happens, no errors whatsoever. Please help me.
Here is my code:-
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration.ConfigurationManager
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim connectionString As String = GetConnectionString()
' Open a connection
Using sourceConnection As SqlConnection = New SqlConnection(connectionString)
sourceConnection.Open()
' Perform an initial count on the destination table.
Dim commandRowCount As New SqlCommand("SELECT COUNT(*) FROM dbo.BRANCH;", sourceConnection)
Dim countStart As Long = System.Convert.ToInt32(commandRowCount.ExecuteScalar())
Console.WriteLine("Starting row count = {0}", countStart)
' Get data from the source table as a SqlDataReader.
Dim commandSourceData As SqlCommand = New SqlCommand("select * from BRANCH", sourceConnection)
Dim reader As SqlDataReader = commandSourceData.ExecuteReader
UpdateHQDB(reader)
End Using
End Sub
Private Function GetConnectionString() As String
Return "Data Source=127.0.0.1;Initial Catalog=SOURCEDB;User ID=sa;Password="
End Function
Private Function GetDestString() As String
Return "Data Source=192.168.123.194;Initial Catalog=DESTINATIONDB;User ID=sa;Password="
End Function
Public Sub UpdateHQDB(ByVal reader)
Dim DestConString As String = GetDestString()
' Open a connection
Using DestinationConnection As SqlConnection = New SqlConnection(DestConString)
DestinationConnection.Open()
' Perform an initial count on the destination table.
Dim DestcommandRowCount As New SqlCommand("SELECT COUNT(*) FROM dbo.BRANCH;", DestinationConnection)
Dim DestcountStart As Long = System.Convert.ToInt32(DestcommandRowCount.ExecuteScalar())
Console.WriteLine("Starting row count at destination = {0}", DestcountStart)
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(DestinationConnection)
bulkCopy.DestinationTableName = "dbo.BRANCH"
Try
' Write from the source to the destination.
bulkCopy.WriteToServer(reader)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
' Close the SqlDataReader. The SqlBulkCopy
' object is automatically closed at the end
' of the Using block.
reader.Close()
End Try
End Using
' Perform a final count on the destination table
' to see how many rows were added.
Dim countEnd As Long = _
System.Convert.ToInt32(DestcommandRowCount.ExecuteScalar())
Console.WriteLine("Ending row count = {0}", countEnd)
Console.WriteLine("{0} rows were added.", countEnd - DestcountStart)
Console.WriteLine("Press Enter to finish.")
Console.ReadLine()
End Using
End Sub
End Class
i would say that use NotifyAfter and SqlRowsCopied event of SqlBulkCopy to troubleshoot
following code in c#
sb.NotifyAfter = 1;
sb.SqlRowsCopied += new SqlRowsCopiedEventHandler(sb_SqlRowsCopied);
void sb_SqlRowsCopied(object sender, SqlRowsCopiedEventArgs e)
{
// See if this event fired
}