What is Equivalent hash_hmac PHP on Visual Basic .Net - vb.net

I'm rewriting hash_hmac code I got on PHP to VB.Net.
I need same result generated both in PHP and VB.Net.
This is hash_hmac code on PHP:
$data = urlencode('2019-07-21T15:30:57.465Z');
$data = '_ts='.$data;
$signatureSecretKey = "secrete";
$hash = hash_hmac('sha256',$data,$signatureSecretKey,true);
$signature = base64_encode($hash);
echo $signature;
The result shows:
upLQYFI3pI2m9Pu5fyiobpvCRhTvRmEyxrVDrdJOYG4=
And here is my code on VB:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim _ts, data, signature, secrete, hash
secrete = "secret"
_ts = DateTime.Now.ToString("2019-07-21T15:30:57.465Z")
data = "_ts=" & HttpUtility.UrlEncode(_ts)
signature = Encrypt(data, secrete)
TextBox1.Text = signature
End Sub
Public Function Encrypt(Content As String, Secret As String) As String
Dim kode As New System.Text.ASCIIEncoding()
Dim getkode As Byte() = kode.GetBytes(Secret)
Dim cont As Byte() = kode.GetBytes(Content)
Dim hmcKu As New HMACSHA256(getkode)
Dim HashCode As Byte() = hmcKu.ComputeHash(cont)
Return Convert.ToBase64String(HashCode)
End Function
Result of my code is:
892q1ArPxIqrX48PQegliVql703V2fcipb5A08F053o=
You can see my VB code generates different result from PHP.
I have tried almost every method I got from internet but the result always different. So, what is equivalent hash_hmac of PHP on VB and what is the right way to make this same result?
Please help?

Use this:
dim hmac as HMACSHA256 = new HMACSHA256(key) ' key = Encoding.ASCII.GetBytes("<secret>")
dim hashValue as byte() = hmac.ComputeHash(Encoding.ASCII.GetBytes("<message>"))
dim result as string = BitConverter.ToString(hashValue).Replace("-", "").ToLower()
hmac.dispose()

I found solution from fb community.
This is exact solution for this cases:
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Imports System.Text.RegularExpressions
Public Class Form1
Private Shared DES As New TripleDESCryptoServiceProvider
Private Shared MD5 As New MD5CryptoServiceProvider
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim _ts, data, signature, secrete
secrete = "secret"
_ts = DateTime.Now.ToUniversalTime.ToString("yyyy-MM-dd\THH:mm:ss.fff\Z")
data = "_ts=" & HttpUtility.UrlEncode(_ts)
Dim reg = New Regex("%[a-f0-9]{2}")
data = reg.Replace(data, Function(m) m.Value.ToUpperInvariant())
signature = Encrypt(data, secrete)
TextBox1.Text = signature
End Sub
Public Function Encrypt(Content As String, Secret As String) As String
Try
Dim kode As New System.Text.ASCIIEncoding()
Dim getkode As Byte() = kode.GetBytes(Secret)
Dim cont As Byte() = kode.GetBytes(Content)
Dim hmcKu As New HMACSHA256(getkode)
Dim HashCode As Byte() = hmcKu.ComputeHash(cont)
Return Convert.ToBase64String(HashCode)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
End Class

Related

Creating a Microsoft Teams Meeting using VB.NET and Microsoft Graph API

I have created a login authentication using the Microsoft Graph API which means after I sign in, as a result, I have the access token of the current user signed-in. My next step is to create a Microsoft Teams Meeting on behalf of the current user signed-in.
I have tried to follow the Microsoft documentation Application POST onlinemeetings, where It shows the required steps to achieve this scenario.
Unfortunately, they didn't provide an example of how it can be achieved in VB.Net (which is not a big deal because I have converted the code to VB).
Currently, I am stuck on sending a POST request to generate this meeting based on the hard coded values when the user clicks on the button.
Please have a look at the code below:
Imports System.IO
Imports System.Net
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Threading.Tasks
Imports Microsoft.Graph
Imports Microsoft.IdentityModel.Clients.ActiveDirectory
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Public Class _Default
Inherits Page
Private Shared httpClient As HttpClient = New HttpClient()
Private Shared context As AuthenticationContext = Nothing
Private Shared credential As ClientCredential = Nothing
Private Shared graphClient As GraphServiceClient
Private Shared authprovider As IAuthenticationProvider
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim code = HttpContext.Current.Request.QueryString("Code")
If Not Page.IsPostBack Then
If code <> "" Then
Dim url = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
Dim myParameters = "grant_type=authorization_code&code=" & code & "&redirect_uri=https://localhost:4312/&client_id=CLIENTID&client_secret=CLIENTSECRET"
Dim wb = New WebClient
wb.Headers(HttpRequestHeader.ContentType) = "application/x-www-form-urlencoded"
Dim response = wb.UploadString(url, "POST", myParameters)
responseToken.Text = response
Success.Text = "O365 login successful. Below is the response token"
Dim SurroundingClass = JsonConvert.DeserializeObject(Of SurroundingClass)(response)
Dim rss As JObject = JObject.Parse(response)
Dim token = rss.SelectToken("access_token")
Dim res = GetUsers(token)
End If
End If
End Sub
Private Shared Async Function GetUsers(ByVal result As String) As Task(Of String)
Try
Dim users As String = Nothing
Dim querystring As String = "api-version=1.6"
Dim uri = "https://graph.microsoft.com/v1.0/me"
httpClient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Bearer", result)
httpClient.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
Dim User = GetMeAsync().Result
Console.WriteLine($"Welcome {User.DisplayName}!\n")
Dim getResult = Await httpClient.GetAsync(uri)
If getResult.Content IsNot Nothing Then
users = Await getResult.Content.ReadAsStringAsync()
End If
Return users
Catch ex As Exception
Throw ex
End Try
End Function
Protected Sub tes_Click(sender As Object, e As EventArgs)
Try
'Dim fr As System.Net.HttpWebRequest
Dim client_id = ""// App Client ID'
Dim uri = "https://localhost:4312/"
Dim targetURI As String = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=" & client_id &
"&redirect_uri=" & uri & "&response_type=code&scope=openid+Mail.Read"
Response.Redirect(targetURI)
Catch ex As System.Net.WebException
'Error in accessing the resource, handle it
End Try
End Sub
Public Shared Async Function CreateMeeting() As Task(Of OnlineMeeting)
Try
graphClient = New GraphServiceClient(authprovider)
Dim onlineMeeting = New OnlineMeeting With {
.StartDateTime = DateTimeOffset.Parse("2020-04-23T21:33:30.8546353+00:00"),
.EndDateTime = DateTimeOffset.Parse("2020-04-23T22:03:30.8566356+00:00"),
.Subject = "Application Token Meeting",
.Participants = New MeetingParticipants With {
.Organizer = New MeetingParticipantInfo With {
.Identity = New IdentitySet With {
.User = New Identity With {
.Id = "MYID"
}
}
}
}
}
Dim encodings As New UTF8Encoding
Dim serializer As New JavaScriptSerializer()
Dim arrayJson As String = serializer.Serialize(onlineMeeting)
Dim result As String = Nothing
Dim postRequest As HttpWebRequest = DirectCast(WebRequest.Create("https://graph.microsoft.com/v1.0/me/onlineMeetings"), HttpWebRequest)
postRequest.Method = "POST"
postRequest.ContentType = "application/json"
httpClient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Bearer", Token)
If postRequest.Method = "POST" Then
Dim parsedContent As String = JsonConvert.SerializeObject(onlineMeeting)
Dim encoding As ASCIIEncoding = New ASCIIEncoding()
Dim bytes As Byte() = encoding.GetBytes(parsedContent)
Dim newStream As Stream = postRequest.GetRequestStream()
newStream.Write(bytes, 0, bytes.Length)
newStream.Close()
End If
Dim createMeetings = Await graphClient.Communications.OnlineMeetings.Request().AddAsync(onlineMeeting)
Console.WriteLine("The meeting has been created")
Return createMeetings
Catch ex As ServiceException
Console.WriteLine($"Error while creating the meeting: {ex.Message}")
Return Nothing
End Try
End Function
Public Sub InvokeMeeting(sender As Object, e As EventArgs)
Try
Dim testing = CreateMeeting()
Catch ex As Exception
End Try
End Sub
PS: I have added the permission required to call this API to be able to create a Teams meeting.
Any suggestions on how to achieve the following scenario?
Any help will be greatly appreciated.
Thank you!

Aramex API yielding "Server Error in '/' Application"

I am trying to implement the Aramex API for Tracking on my VB.NET website, but I'm getting an error.
Here is my code:
Imports TrackingReference
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim _Request As New ShipmentTrackingRequest
_Request.ClientInfo = New ClientInfo
_Request.ClientInfo.AccountCountryCode = "JO"
_Request.ClientInfo.AccountEntity = "AMM"
_Request.ClientInfo.AccountNumber = "20016"
_Request.ClientInfo.AccountPin = "331421"
_Request.ClientInfo.UserName = "reem#reem.com"
_Request.ClientInfo.Password = "123456789"
_Request.ClientInfo.Version = "v1.0"
_Request.Transaction = New Transaction
Dim _Shipments As New List(Of String)
_Shipments.Add("7055174991")
_Request.Shipments = _Shipments.ToArray()
_Request.GetLastTrackingUpdateOnly = True
Dim _Client As New Service_1_0Client()
Dim _response As ShipmentTrackingResponse = Nothing
_Client.Open()
_response = _Client.TrackShipments(_Request)
If Not _response Is Nothing Then
For Each _Result As KeyValuePair(Of String, TrackingResult()) In _response.TrackingResults
Dim _trResult() As TrackingResult = _Result.Value
For Each trR In _trResult
Response.Write(trR.UpdateLocation & "<br>")
Next
Next
End If
_Client.Close()
End Sub
End Class
This is my error:
I have found the Aramex Developer community to be full of questions but no answers. How can I fix the problem?

Create Binary file of text that notepad can't read

I am attempting to create a binary file that is not readable by notepad in windows. This file needs to contain text information. The current code I run is readable in notepad (with a few extra characters here and there, but still human readable). Any assistance is greatly appreciated.
Using writer As BinaryWriter = New BinaryWriter(File.Open("file.bin", FileMode.Create))
writer.Write(rtbWriter.Text)
End Using
All files can be read by notepad - whether it is binary or not. If you don't want the text to be readable (or to be more accurate - understandable), consider using encryption.
EDIT: For an introduction on how to use encryption, see the link below to see how to use the 3DES cryptographic service provider in VB.NET:
simple encrypting / decrypting in VB.Net
*A more sophisticated approach would chain together the File Stream and Crypto Stream...
...but here's a very simple example showing how to encrypt/decrypt individual strings so you have something to play with and learn from:
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Public Class Form1
Private Key As String = "SomeRandomKeyThatIsHardCoded"
Private data As New List(Of String)
Private DataFileName As String = System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "SomeFile.txt")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Some data to play with:
data.Add("User X, Access Y")
data.Add("User Y, Access Z")
data.Add("User Z, Access A")
ListBox1.DataSource = data
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Write out each entry in encrypted form:
Using SW As New StreamWriter(DataFileName, False)
For Each entry As String In data
SW.WriteLine(Crypto.Encrypt(entry, Key))
Next
End Using
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
data.Clear()
ListBox1.DataSource = Nothing
' Read each encrypted line and decrypt it:
Using SR As New System.IO.StreamReader(DataFileName)
While Not SR.EndOfStream
data.Add(Crypto.Decrypt(SR.ReadLine, Key))
End While
End Using
ListBox1.DataSource = data
End Sub
End Class
Public Class Crypto
Private Shared DES As New TripleDESCryptoServiceProvider
Private Shared MD5 As New MD5CryptoServiceProvider
Public Shared Function MD5Hash(ByVal value As String) As Byte()
Return MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(value))
End Function
Public Shared Function Encrypt(ByVal stringToEncrypt As String, ByVal key As String) As String
DES.Key = Crypto.MD5Hash(key)
DES.Mode = CipherMode.ECB
Dim Buffer As Byte() = ASCIIEncoding.ASCII.GetBytes(stringToEncrypt)
Return Convert.ToBase64String(DES.CreateEncryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
End Function
Public Shared Function Decrypt(ByVal encryptedString As String, ByVal key As String) As String
Try
DES.Key = Crypto.MD5Hash(key)
DES.Mode = CipherMode.ECB
Dim Buffer As Byte() = Convert.FromBase64String(encryptedString)
Return ASCIIEncoding.ASCII.GetString(DES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
Return ""
End Try
End Function
End Class

Saving and loading a game in vb.net

Is there away I can save or load a game a lot more easier than I have?
Saving Code
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\Pugio Cadite\CharacterInformation.txt", True)
file.WriteLine(charactername)
file.WriteLine(characterrace)
file.WriteLine(characterclass)
file.WriteLine(characterGender)
file.WriteLine(charactergold)
file.WriteLine(characterlevel)
file.Close()
and I have not yet wrote the load function.
Imports System.Xml.Serialization
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'save the program variables
Dim p As New ProgramVars
p.Prop1 = "1"
p.Prop2 = "2"
p.Prop3 = "3"
p.Prop4 = "4"
Dim strFilename As String = "C:\Junk\Junk.xml"
p.Save(strFilename)
'load them into a different object
Dim p2 As ProgramVars = ProgramVars.Load(strFilename)
MsgBox(p2.Prop3)
End Sub
End Class
<Serializable>
Public Class ProgramVars
Property Prop1 As String
Property Prop2 As String
Property Prop3 As String
Property Prop4 As String
Sub Save(filename As String)
Using fs As New System.IO.FileStream(filename, IO.FileMode.OpenOrCreate)
Dim xs As New XmlSerializer(GetType(ProgramVars))
xs.Serialize(fs, Me)
End Using
End Sub
Shared Function Load(filename As String) As ProgramVars
Using fs As New System.IO.FileStream(filename, IO.FileMode.OpenOrCreate)
Dim xs As New XmlSerializer(GetType(ProgramVars))
Return xs.Deserialize(fs)
End Using
End Function
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