Function to generate random 8 Character Password - vb.net

I have this function in vb that had seemed to be working before to generate an 8 character password but now generates the same password for each user who registers to the website. I am unsure as to where I have went wrong as I have not fiddled with this piece of code (code was not written by me)? Any help would be appreciated.
function generatePassword()
Dim i, newPassword
newPassword = ""
For i = 1 to 3
newPassword = newPassword & Mid("ABCDEFGHJKLMNPQRSTUVWXYZ",randomInRange(1,24),1)
Next
For i = 4 to 7
newPassword = newPassword & Mid("23456789",randomInRange(1,8),1)
Next
'For i = 1 to 8
' newPassword = newPassword & Mid("ABCDEFGHJKLMNPQRSTUVWXYZ23456789",randomInRange(1,32),1)
'Next
generatePassword = newPassword
end function
function randomInRange(lo,hi)
randomInRange =(Int((hi - lo + 1) * rnd + lo))
end function
Dim newPassword = generatePassword()
Dim strSql As String = "INSERT INTO Student(" & _
"StudentNo," & _
"Surname," & _
"FirstName," & _
"MiddleName," & _
"Gender," & _
"Pathway," & _
"[Level]," & _
"QubEmail," & _
"[Password]," & _
"HomeEmail," & _
"MobilePhone," & _
"HomeTown," & _
"PlacementYear," & _
"Status," & _
"DateEdited," & _
"HomePhone) " & _
"VALUES " & _
"( " & _
"'" & StudentNo.Text.Replace("'", "''") & "'," & _
"'" & Surname.Text.Replace("'", "''") & "'," & _
"'" & Forename.Text.Replace("'", "''") & "'," & _
"'" & MiddleName.Text.Replace("'", "''") & "'," & _
"'" & ddlGender.SelectedValue & "'," & _
"'" & ddlPathway.SelectedValue & "'," & _
"'" & ddlLevel.SelectedValue & "'," & _
"'" & QUBEmail.Text.Replace("'", "''") & "'," & _
"'" & newPassword & "'," & _
"'" & HomeEmail.Text.Replace("'", "''") & "'," & _
"'" & MobileNo.Text.Replace("'", "''") & "'," & _
"'" & HomeTown.Text.Replace("'", "''") & "'," & _
"" & PlacementYear & "," & _
"'Seeking Placement'," & _
" GETDATE() ," & _
"'" & HomeNo.Text.Replace("'", "''") & "' " & _
")"
Dim addStudent As OleDbDataReader = Database.DoSQLReturnDataReader(strSql)
addStudent.Close()

There doesn't seem to be any code that is updating the rnd variable. This needs to update each time you call randomInRange to get different passwords.
I would suggest that you change randomInRange entirely to make it run more cleanly.
This is what you need to do:
Private rnd As Random = new Random()
Function randomInRange(lo As Integer, hi As Integer) As Integer
Return rnd.Next(lo, hi + 1)
End Function
Making this change produces random passwords.

You should probably talk to the person that wrote the code if you're not a programmer yourself. Nevertheless, a Rnd is really not random, but only a sofisticated mathematical equation using a seed to calculate its value.
This seed is set to the time when the program runs. Without any involvement, the seed will stay the same which means that all randoms will actually be the same value; use Randomize at each generatePassword().
Function generatePassword()
Randomize()
/.../
End Function

Related

Line break in an INSERT INTO statement

I have searched all the boards and can not find were anyone has asked how to do a line break in code for INSERT INTO statement. I have tried many variations, I can seem to get any of them to work. He is an example of my code and what I am trying. I know it is just a misplaced comma, quote or ampersand.
StrSQL = "INSERT INTO Tbl_Data_Shop & _
(ClaimNumber, ExposureNumber, ClaimSuffix, & _
Shop_Name, Shop_StreetAddress, Shop_City, & _
Shop_State, Shop_Zip, Shop_Phone) & _
"Values
('" & Forms!Frm_Data_Main!TBClaimNumber & "' & _
"'" & Forms!Frm_Data_Main!TBExposureNumber & "' & _
"'" & Forms!Frm_Data_Main!TBClaimSuffix & "'," & _
"'" & TBSShop_Name & "'," & _
"'" & TBSShop_StreetAddress & "'," & _
"'" & TBSShop_City & "'," & _
"'" & TBSShop_State & "'," & _
"'" & TBSShop_Zip & "'," & _
"'" & TBSShop_Phone & "'");"
Once again, a classic example to use the industry best practice of parameterization which you can do in MS Access with QueryDefs.Parameters. Beyond protecting against sql injection, you avoid any need to worry about quotes or ampersands with string interpolation and arguably build a more readable and maintainable code block.
Regardless of language (here being VBA), the process involves setting up a prepared SQL statement with placeholders. Then in a different step you bind data values to placeholders for execution.
SQL
Save below as a saved MS Access query (Ribbon > Create > Queries > SQL View). This SQL query uses the PARAMETERS clause (valid in Access SQL dialect) to define placeholders and their types and then uses the placeholders. You can break all the lines you want!
PARAMETERS TBClaimNumberParam TEXT(255), TBExposureNumberParam TEXT(255),
TBClaimSuffixParam TEXT(255), TBSShop_NameParam TEXT(255),
TBSShop_StreetAddressParam TEXT(255), TBSShop_CityParam TEXT(255),
TBSShop_StateParam TEXT(255), TBSShop_ZipParam TEXT(255),
TBSShop_PhoneParam TEXT(255);
INSERT INTO Tbl_Data_Shop (ClaimNumber, ExposureNumber, ClaimSuffix,
Shop_Name, Shop_StreetAddress, Shop_City,
Shop_State, Shop_Zip, Shop_Phone)
VALUES (TBClaimNumberParam, TBExposureNumberParam, TBClaimSuffixParam,
TBSShop_NameParam, TBSShop_StreetAddressParam, TBSShop_CityParam,
TBSShop_StateParam, TBSShop_ZipParam, TBSShop_PhoneParam)
VBA
In this step, you reference the above saved query, mySavedQuery, into a QueryDef object which then has VBA values binded to the query's named parameters (defined in above SQL).
Dim qdef As QueryDef
Set qdef = CurrentDb.QueryDefs("mySavedQuery")
' BIND VALUES TO PARAMETERS
qdef!TBClaimNumberParam = Forms!Frm_Data_Main!TBClaimNumber
qdef!TBExposureNumberParam = Forms!Frm_Data_Main!TBExposureNumber
qdef!TBClaimSuffixParam = Forms!Frm_Data_Main!TBClaimSuffix
qdef!TBSShop_NameParam = TBSShop_Name
qdef!TBSShop_StreetAddressParam = TBSShop_StreetAddress
qdef!TBSShop_CityParam = TBSShop_City
qdef!TBSShop_StateParam = TBSShop_State
qdef!TBSShop_ZipParam = TBSShop_Zip
qdef!TBSShop_PhoneParam = TBSShop_Phone
' EXECUTE ACTION
qdef.Execute dbFailOnError
Set qdef = Nothing
Make each line a string on its own - and correct the commas and parenthesis:
StrSQL = "INSERT INTO Tbl_Data_Shop " & _
"(ClaimNumber, ExposureNumber, ClaimSuffix, " & _
"Shop_Name, Shop_StreetAddress, Shop_City, " & _
"Shop_State, Shop_Zip, Shop_Phone) " & _
"Values (" & _
"'" & Forms!Frm_Data_Main!TBClaimNumber & "'," & _
"'" & Forms!Frm_Data_Main!TBExposureNumber & "'," & _
"'" & Forms!Frm_Data_Main!TBClaimSuffix & "'," & _
"'" & TBSShop_Name & "'," & _
"'" & TBSShop_StreetAddress & "'," & _
"'" & TBSShop_City & "'," & _
"'" & TBSShop_State & "'," & _
"'" & TBSShop_Zip & "'," & _
"'" & TBSShop_Phone & "');"
There are missing/misplaced quotation marks and &s . However I would use a prepared statement, for a number of reasons, namely safety and managability .
StrSQL = "INSERT INTO Tbl_Data_Shop & _
(ClaimNumber, ExposureNumber, ClaimSuffix, & _
Shop_Name, Shop_StreetAddress, Shop_City, & _
Shop_State, Shop_Zip, Shop_Phone) & _
Values ('" & Forms!Frm_Data_Main!TBClaimNumber & "', & _
'" & Forms!Frm_Data_Main!TBExposureNumber & "', & _
'" & Forms!Frm_Data_Main!TBClaimSuffix & "', & _
'" & TBSShop_Name & "', & _
'" & TBSShop_StreetAddress & "', & _
'" & TBSShop_City & "', & _
'" & TBSShop_State & "', & _
'" & TBSShop_Zip & "', & _
'" & TBSShop_Phone & "');"
Try and let us know.

Getting a subscript out of range error on list object

So, I've been working on a code that allows editing of database tables via excel, and I've run into a snag with a table object.
The code is written almost the exact same way on other worksheets, but for some reason, only this worksheet gives me the subscript out of range error when setting the list object. I've check the name of the table and tried changing it a couple of times. What am I missing?
Here's the code so far:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim CustomersConn As ADODB.Connection
Dim CustomersCmd As ADODB.Command
Dim lo As Excel.ListObject
Dim ws As Excel.Worksheet
Dim lrs As Range
Dim lr As Excel.ListRow
Dim Customers As Variant
Dim areaCount As Integer
Dim i As Integer
Dim Rows As Range
Dim rRow As Range
Dim lRows As Excel.ListRows
Dim Counter As Double
Set ws = ThisWorkbook.Worksheets(11)
Set lo = ws.ListObjects("TProspects")
Set CustomersConn = New ADODB.Connection
Set CustomersCmd = New ADODB.Command
Set lrs = Target
For Each Rows In lrs.Rows
On Error GoTo jmp
'========Section 1===========
If Counter < 1 Then
Intersect(lr.Range, lo.ListColumns("ID").Range).Value = WorksheetFunction.Max(lo.ListColumns("ID").Range) + 1
End If
'^^^^^^^^Section 1^^^^^^^^^^^
Set lr = lo.ListRows(Rows.Row - 5)
CustomersConn.ConnectionString = SQLConStr
CustomersConn.Open
CustomersCmd.ActiveConnection = CustomersConn
CustomersCmd.CommandText = _
GetUpdateText( _
Intersect(lr.Range, lo.ListColumns("ID").Range).Value, _
Intersect(lr.Range, lo.ListColumns("Prospect").Range).Value, _
Intersect(lr.Range, lo.ListColumns("Contact").Range).Value, _
Intersect(lr.Range, lo.ListColumns("Email").Range).Value, _
Intersect(lr.Range, lo.ListColumns("Phone").Range).Value, _
Intersect(lr.Range, lo.ListColumns("Address").Range).Value, _
Intersect(lr.Range, lo.ListColumns("City").Range).Value, _
Intersect(lr.Range, lo.ListColumns("State").Range).Value, _
Intersect(lr.Range, lo.ListColumns("Zip").Range).Value, _
Intersect(lr.Range, lo.ListColumns("Buying Group").Range).Value, _
Intersect(lr.Range, lo.ListColumns("Type").Range).Value)
CustomersCmd.Execute
Next Rows
CustomersConn.Close
Set CustomersConn = Nothing
Set lo = Nothing
Set ws = Nothing
Set lr = Nothing
Application.Calculation = xlCalculationAutomatic
jmp:
End Sub
GetUpdateText function:
Function GetUpdateText(ID As Double, Prospect As String, Contact As String, Email As String, Phone As String, Address As String, City As String, State As String, Zip As Double, Corp As String, CType As String) As String
Dim SQLStr As String
SQLStr = _
"UPDATE Prospect" & _
" SET Type = '" & CType & "'," & _
"Prospect = '" & Replace(Prospect, "'", "''") & "'," & _
"Contact = '" & Contact & "'," & _
"Email = '" & Email & "'," & _
"Phone = '" & Phone & "'," & _
"Address = '" & Address & "'," & _
"City = '" & City & "'," & _
"State = '" & State & "'," & _
"Zip = " & Zip & "," & _
"[Buying Group] = '" & Corp & "'" & _
"WHERE ID = " & ID & _
"IF ##ROWCOUNT=0" & _
"INSERT INTO Prospect (" & _
"Type,Contact,Prospect,Email,Phone,Address,City,State,Zip,[Buying Group])" & _
"VALUES (" & _
"'" & CType & "'," & _
"'" & Contact & "'," & _
"'" & Replace(Prospect, "'", "''") & "'," & _
"'" & Email & "'," & _
"'" & Phone & "'," & _
"'" & Address & "'," & _
"'" & City & "'," & _
"'" & State & "'," & "'" & Zip & "'," & "'" & Corp & "')"
GetUpdateText = SQLStr
End Function
Matt Cremeens and Andrew Wynn brought up a valid point which directed me to where I needed to be.
While I did indeed have the table on sheet index 11, for what ever reason, utilizing the name of the sheet instead of the index value worked. I totally forgot that Worksheets is an associative array. As far as why the index did not work, it's a total mystery.

Edit/Update datagridview VB form

When I try to edit and update the data in datagriview it comes up with an error message saying Operator '&' is not defined for type 'TextBox' and string "".
please help. Thanks
Here is my code
Private Sub btnaddrecord_Click(sender As Object, e As EventArgs) Handles btnaddrecord.Click
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
If Me.IdentificationNotest.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO vehicledefects(Codenumber, vehiclereg, datereported, defects1, repaired1, defects2, repaired2, defects3, repaired3, datefixed) " & _
" VALUES(" & Me.IdentificationNotest.Text & ",'" & Me.vehiclereg.Text & "','" & Me.datereported.Text & "','" & Me.defects1.Text & "','" & Me.repaired1.Text & "','" & _
Me.defects2.Text & "','" & Me.repaired2.Text & "','" & _
Me.defects3.Text & "','" & Me.repaired3.Text & "','" & _
Me.datefixed.Text & "')"
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE vehicledefects" & _
" SET Codenumber =" & Me.IdentificationNotest.Text & _
", vehiclereg ='" & Me.vehiclereg.Text & "'" & _
", datereported ='" & Me.datereported.Text & "'" & _
", defects1 ='" & Me.defects1.Text & "'" & _
", repaired1 ='" & Me.repaired1.Text & "'" & _
", defects2 ='" & Me.defects2.Text & "'" & _
", repaired2='" & Me.repaired2.Text & "'" & _
", defects3='" & Me.defects3.Text & "'" & _
", repaired3='" & Me.repaired3.Text & "'" & _
", datefixed='" & Me.datefixed.Text & "'" & _
" WHERE Codenumber =" & Me.IdentificationNotest.Tag
cmd.ExecuteNonQuery()
End If
refreshdata()
Me.btnclear.PerformClick()
cnn.Close()
datefixed.Text = ""
IdentificationNotest.Text = ""
End Sub
In the future, you should also post the line number the error is being thrown on.
The error is telling you that you're doing something like:
dim myString as String = myTextBox & " some more text"
in this case, you would need to do:
dim myString as String = myTextBox.Text & " some more text"
In the code you posted, I wasn't able to find an instance of this - so perhaps its somewhere else in the code. Though, the code was hard to read so I may have missed it.
You may also be aware that this code is susceptible to SQL Injection attacks

I'm trying to UPDATE some fields in my table in Access VBA

I need some help with this, sorry, I am new in VBA and I am trying to run a update query which should obtain a value from a variable and update an already existing table. This is done using VBA. On executing no error message is shown but the table isn't updated with the new value. The code is as follows:
Query = "UPDATE Results " & _
"SET fk_Report='" & Report & "'" & _
",fk_Name='" & Namevar & "'" & _
",fk_Age='" & Agevar & "'" & _
",fk_Sex='" & Sexvar & "'" & _
"WHERE [Count]='" & Countvar & "'" & _
",[Positives]='" & Posvar & "'" & _
",[Negatives]='" & Negvar & "'" & _
",[Unknow]='" & Unkvar & "';"
CurrentDb.Execute (Query)
If somebody can help...
You don't need the commas in the where clause
Query = "UPDATE Results " & _
"SET fk_Report='" & Report & "'" & _
",fk_Name='" & Namevar & "'" & _
",fk_Age='" & Agevar & "'" & _
",fk_Sex='" & Sexvar & "'" & _
"WHERE [Count]='" & Countvar & "' " & _
"AND [Positives]='" & Posvar & "' " & _
"AND [Negatives]='" & Negvar & "' " & _
"AND [Unknow]='" & Unkvar & "';"
CurrentDb.Execute (Query)
use AND instead of , (comma) after WHERE clause

VB.NET Remainder Function

What I am trying to do is make a line of text appear every 50 strings read. I was trying to find a reaminder function to use on the GlobalVariables.TransferTracker interger, but I couldn't find anything online. Is there such a funciton? Or a differen't/better way to do this? If it helps here is my code:
Do While TransferRecord.Read()
'Start of writing to the SQL server.
SQLServerConnection.Open()
'SQL statement to transfer all the data that fits the requirements to the SQL server.
Dim SQLCommand1 As New SqlCommand("INSERT INTO dbo.b_Pulp_PI_Forte (" & _
"mill, " & _
"keyprinter_datetime, " & _
"bale_line_num, " & _
"pulp_line_id, " & _
"bale_id, " & _
"drop_datetime, " & _
"layboy_position, " & _
"bale_gross_weight, " & _
"gross_value_flag, " & _
"bale_airdry_pct, " & _
"airdry_value_flag, " & _
"sheets_per_bale, " & _
"grader_test_flag, " & _
"dropped_num, " & _
"created_by, " & _
"CreatedDateTime, " & _
"Who_did_it, " & _
"Last_change_datetime) " & _
"VALUES (" & _
"'850', " & _
"'" & ProdDate & "', " & _
"'" & BaleLineNum & "', " & _
"'" & BaleLine & "', " & _
"'" & BaleNumber & "', " & _
"'" & ProdDate & "', " & _
"'0', " & _
"'" & GrossWeight & "', " & _
"'" & GrossWeightFlag & "', " & _
"'" & AirDry & "', " & _
"'" & AirDryFlag & "', " & _
"'0', " & _
"'N', " & _
"'0', " & _
"'BaleTrac', " & _
"'" & Date.Now & "', " & _
"'BaleTrac', " & _
"'" & Date.Now & "')")
'If DisplayCode is checked this will be printed to the screen.
If ApplicationPropertiesWindow.DisplayCodechkbx.Checked = True Then
MainTextBox.AppendText(Environment.NewLine & SQLCommand1.CommandText)
GlobalVariables.DisplayCode = True
End If
'Executing the SQL statement.
SQLCommand1.Connection = SQLServerConnection
SQLCommand1.ExecuteNonQuery()
SQLServerConnection.Close()
GlobalVariables.TransferTracker = GlobalVariables.TransferTracker + 1
'This is where I would like to have the remainder function.
'Making message to show that program is still running.
If GlobalVariables.TransferTracker = 50 Then
MainTextBox.AppendText(Environment.NewLine & "50 records transferred.")
End If
Loop
Right now I just have it set up so it will fire at 50 records, because I couldn't find the function.
The remainder is an operator in VB, Mod:
If GlobalVariables.TransferTracker Mod 50 = 0 Then …
As a general advice, don’t write … = True in your conditions. Its redundancy is redundant.