Autogenerate alphanumeric ID - sql

Need help with autogenerate ID. I have this code that autogenerates ID but is only good up to 10 increments. It starts with PO0001 and countinues up to PO0010 only, once it gets to PO0010 the ID gets stuck in PO0001.
here is the code I used:
Public Function newPOID(prefix As String, storedProcedure As String) As String
Dim newId As String = prefix + "0001"
Dim adpt As New SqlDataAdapter
Dim ds As New DataSet
Dim dr As SqlDataReader
Dim conn As New SqlConnection
conn.ConnectionString = conString
utos = New SqlCommand(storedProcedure, conn)
utos.CommandType = CommandType.StoredProcedure
conn.Open()
dr = utos.ExecuteReader
If dr.Read Then
If dr.IsDBNull(0) Then
Dim num As Integer = 1
'Dim prefix As String = "PO"
Dim append As String = prefix + num.ToString().PadLeft(4, "000")
newId = append
Else
Dim POstring As String = dr(0).ToString.Substring(0, 3)
Dim POID As Integer = dr(0).ToString.Substring(5) + 1
Dim append As String = POstring + POID.ToString().PadLeft(3, "000")
newId = append
End If
conn.Close()
End If
Return newId
End Function

Replace num.ToString().PadLeft(4, "000") with Format(num,"000#)

Related

add listbox values to access database windows form application

I have a calculator with two textboxes where the user puts a number in each one. They then click a plus, minus, divide, or multiply button and it does that function to the numbers. These numbers are saved to a listbox called listbox1. When the user clicks to display the results, the listbox is populated with all their saved values, and the application is SUPPOSED to save the listbox items to an access database. it is not working. Below is my code, where numFirst is the name of a category in the database table:
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles
btnDisplay.Click
ListBox1.Items.Clear()
For arrayindex As Integer = 0 To intarrayCount - 1
ListBox1.Items.Add(Input(arrayindex))
ListBox1.Text = Convert.ToString(ListBox1.Items.Item(arrayindex))
Next arrayindex
Dim query As String = "SELECT * FROM wk6"
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\helse_000\Desktop\APU\VB Advanced\week4\ENTD461_wk4_Andrew_Helsel\ENTD461_wk2_Andrew_Helsel\calculator.mdb"
Dim command As OleDbCommand = New OleDbCommand
Dim var1 As String = Convert.ToString(ListBox1.Items.Item(0))
command.CommandText = "INSERT into wk6 (numFirst) VALUES (" + var1 + ")"
Figured it out, removed the select all query string and made my textbox fields into parameters after modifying their results a bit to fit the format I needed for the table.
For i As Integer = 0 To ListBox1.Items.Count - 1
Dim firstString As String = Convert.ToString(ListBox1.Items.Item(i))
Dim leftPart As String = firstString.Split(Convert.ToChar
(strButtonSelected))(0)
Dim rightPart As String = firstString.Split(Convert.ToChar("="))(1)
Dim a As Integer = firstString.IndexOf(strButtonSelected)
Dim b As Integer = firstString.IndexOf("=")
Dim secNum = firstString.Substring(a + 1, b - 4)
secNum = secNum.Trim
Dim conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\Users\helse_000\Desktop\APU\VB Advanced\week4\ENTD461_wk4_Andrew_Helsel\ENTD461_wk2_Andrew_Helsel\calculator.mdb")
Dim command As OleDbCommand = New OleDbCommand
Dim cmdstring As String = "INSERT INTO wk6 (numFirst, numSecond, Operator, equals, Answer)" + " VALUES (#firstName,#lastName,#Operator,#equals,#answer)"
command = New OleDbCommand(cmdstring, conn)
command.Parameters.AddWithValue("#firstName", leftPart)
command.Parameters.AddWithValue("#lastName", secNum)
command.Parameters.AddWithValue("#Operator", strButtonSelected)
command.Parameters.AddWithValue("#equals", "=")
command.Parameters.AddWithValue("#answer", rightPart)
conn.Open()
command.ExecuteNonQuery()
conn.Close()

Performance improvement on vb.net code

I need to write 50 million records with 72 columns into text file, the file size is growing as 9.7gb .
I need to check each and every column length need to format as according to the length as defined in XML file.
Reading records from oracle one by one and checking the format and writing into text file.
To write 5 crores records it is taking more than 24 hours. how to increase the performance in the below code.
Dim valString As String = Nothing
Dim valName As String = Nothing
Dim valLength As String = Nothing
Dim valDataType As String = Nothing
Dim validationsArray As ArrayList = GetValidations(Directory.GetCurrentDirectory() + "\ReportFormat.xml")
Console.WriteLine("passed xml")
Dim k As Integer = 1
Try
Console.WriteLine(System.DateTime.Now())
Dim selectSql As String = "select * from table where
" record_date >= To_Date('01-01-2014','DD-MM-YYYY') and record_date <= To_Date('31-12-2014','DD-MM-YYYY')"
Dim dataTable As New DataTable
Dim oracleAccess As New OracleConnection(System.Configuration.ConfigurationManager.AppSettings("OracleConnection"))
Dim cmd As New OracleCommand()
cmd.Connection = oracleAccess
cmd.CommandType = CommandType.Text
cmd.CommandText = selectSql
oracleAccess.Open()
Dim Tablecolumns As New DataTable()
Using oracleAccess
Using writer = New StreamWriter(Directory.GetCurrentDirectory() + "\FileName.txt")
Using odr As OracleDataReader = cmd.ExecuteReader()
Dim sbHeaderData As New StringBuilder
For i As Integer = 0 To odr.FieldCount - 1
sbHeaderData.Append(odr.GetName(i))
sbHeaderData.Append("|")
Next
writer.WriteLine(sbHeaderData)
While odr.Read()
Dim sbColumnData As New StringBuilder
Dim values(odr.FieldCount - 1) As Object
Dim fieldCount As Integer = odr.GetValues(values)
For i As Integer = 0 To fieldCount - 1
Dim vals As Array = validationsArray(i).ToString.ToUpper.Split("|")
valName = vals(0).trim
valDataType = vals(1).trim
valLength = vals(2).trim
Select Case valDataType
Case "VARCHAR2"
If values(i).ToString().Length = valLength Then
sbColumnData.Append(values(i).ToString())
'sbColumnData.Append("|")
ElseIf values(i).ToString().Length > valLength Then
sbColumnData.Append(values(i).ToString().Substring(0, valLength))
'sbColumnData.Append("|")
Else
sbColumnData.Append(values(i).ToString().PadRight(valLength))
'sbColumnData.Append("|")
End If
Case "NUMERIC"
valLength = valLength.Substring(0, valLength.IndexOf(","))
If values(i).ToString().Length = valLength Then
sbColumnData.Append(values(i).ToString())
'sbColumnData.Append("|")
Else
sbColumnData.Append(values(i).ToString().PadLeft(valLength, "0"c))
'sbColumnData.Append("|")
End If
'sbColumnData.Append((values(i).ToString()))
End Select
Next
writer.WriteLine(sbColumnData)
k = k + 1
Console.WriteLine(k)
End While
End Using
writer.WriteLine(System.DateTime.Now())
End Using
End Using
Console.WriteLine(System.DateTime.Now())
'Dim Adpt As New OracleDataAdapter(selectSql, oracleAccess)
'Adpt.Fill(dataTable)
Return Tablecolumns
Catch ex As Exception
Console.WriteLine(System.DateTime.Now())
Console.WriteLine("Error: " & ex.Message)
Console.ReadLine()
Return Nothing
End Try

How to change value of /GrpPwd/ Cell in all Rows?

I need to perform this SQL Query:
UPDATE Resurses SET GrpPwd = #GrpPwd1 WHERE Resurs = #Resurs1
For all rows in my Access Database using VB.NET
How can i do it?
I use this code but id doesn't work:
Password Generator:
Dim charset As String = nalf
Dim r As New Random()
Dim lenPass As Integer = r.Next(minLength, maxLength)
Dim str As String = String.Empty
For i As Integer = 0 To lenPass - 1
str += charset(r.Next(0, charset.Length))
Next
Return str
End Function
Update rows
If DataGridView1.CurrentRow.Cells(3).Value = "Yes" Then
nres = DataGridView1.CurrentRow.Cells(0).Value
nalf = DataGridView1.CurrentRow.Cells(6).Value
nsym = DataGridView1.CurrentRow.Cells(1).Value
Dim parol1 As String
Dim pwd As String = pass99(nsym, nsym) '
parol1 = pwd
Dim cmd As New OleDbCommand()
Dim Conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.oledb.12.0; Data source=" + bpath)
cmd.Connection = Conn
Conn.Open()
For i As Integer = 0 To k - 1
cmd.CommandText = String.Format("UPDATE Resurses SET GrpPwd = #GrpPwd1{0} WHERE Resurs = #Resurs1{0};", i)
cmd.Parameters.Add(String.Format("#GrpPwd1{0}", i), OleDbType.WChar).Value = parol1
cmd.Parameters.Add(String.Format("#Resurs1{0}", i), OleDbType.Integer).Value = nres
Next
cmd.ExecuteNonQuery()
Conn.Close()
MsgBox("All rows are updated!")
End If
f

VB: Count number of columns in csv

So, quite simple.
I am importing CSVs into a datagrid, though the csv always has to have a variable amount of columns.
For 3 Columns, I use this code:
Dim sr As New IO.StreamReader("E:\test.txt")
Dim dt As New DataTable
Dim newline() As String = sr.ReadLine.Split(";"c)
dt.Columns.AddRange({New DataColumn(newline(0)), _
New DataColumn(newline(1)), _
New DataColumn(newline(2))})
While (Not sr.EndOfStream)
newline = sr.ReadLine.Split(";"c)
Dim newrow As DataRow = dt.NewRow
newrow.ItemArray = {newline(0), newline(1), newline(2)}
dt.Rows.Add(newrow)
End While
DG1.DataSource = dt
This works perfectly. But how do I count the number of "newline"s ?
Can I issue a count on the number of newlines somehow? Any other example code doesn't issue column heads.
If my csv file has 5 columns, I would need an Addrange of 5 instead of 3 and so on..
Thanks in advance
Dim sr As New IO.StreamReader(path)
Dim dt As New DataTable
Dim newline() As String = sr.ReadLine.Split(","c)
' MsgBox(newline.Count)
' dt.Columns.AddRange({New DataColumn(newline(0)),
' New DataColumn(newline(1)),
' New DataColumn(newline(2))})
Dim i As Integer
For i = 0 To newline.Count - 1
dt.Columns.AddRange({New DataColumn(newline(i))})
Next
While (Not sr.EndOfStream)
newline = sr.ReadLine.Split(","c)
Dim newrow As DataRow = dt.NewRow
newrow.ItemArray = {newline(0), newline(1)}
dt.Rows.Add(newrow)
End While
dgv.DataSource = dt
End Sub
Columns and item values can be added to a DataTable individually, using dt.Columns.Add and newrow.Item, so that these can be done in a loop instead of hard-coding for a specific number of columns. e.g. (this code assumes Option Infer On, so adjust as needed):
Public Function CsvToDataTable(csvName As String, Optional delimiter As Char = ","c) As DataTable
Dim dt = New DataTable()
For Each line In File.ReadLines(csvName)
If dt.Columns.Count = 0 Then
For Each part In line.Split({delimiter})
dt.Columns.Add(New DataColumn(part))
Next
Else
Dim row = dt.NewRow()
Dim parts = line.Split({delimiter})
For i = 0 To parts.Length - 1
row(i) = parts(i)
Next
dt.Rows.Add(row)
End If
Next
Return dt
End Function
You could then use it like:
Dim dt = CsvToDataTable("E:\test.txt", ";"c)
DG1.DataSource = dt

Converted C# To VB.NET , But Vb.net code Not working ,Below converted code is pasted .i got the error Linq part

Dim dt As New DataTable("MyTable")
dt.Columns.Add(New DataColumn("Name"))
dt.Columns.Add(New DataColumn("Place"))
dt.Columns.Add(New DataColumn("date", Type.[GetType]("System.String")))
create the data table
Dim dr As DataRow = dt.NewRow()
dr("Name") = "500"
dr("Place") = "Chennai"
dr("date") = "10-May-2014"
dt.Rows.Add(dr)
Dim dr1 As DataRow = dt.NewRow()
dr1("Name") = "600"
dr1("Place") = "Chennai"
dr1("date") = "11-May-2014"
dt.Rows.Add(dr1)
added the row
Dim dr2 As DataRow = dt.NewRow()
dr2("Name") = "200"
dr2("Place") = "Bangalore"
dr2("date") = "12-Aug-2014"
dt.Rows.Add(dr2)
Dim dr3 As DataRow = dt.NewRow()
dr3("Name") = "40"
dr3("Place") = "Chennai"
dr3("date") = "14-May-2014"
dt.Rows.Add(dr3)
Dim dr5 As DataRow = dt.NewRow()
dr5("Name") = "9000"
dr5("Place") = "Bangalore"
dr5("date") = "15-Aug-2014"
dt.Rows.Add(dr5)
added the row to datatable
Dim dr4 As DataRow = dt.NewRow()
dr4("Name") = "9000"
dr4("Place") = "Bangalore"
dr4("date") = "1-Aug-2014"
dt.Rows.Add(dr4)
This below part get error
Dim grouped = From groupbyUD In From userdefinedtable In dt.AsEnumerable()Group userdefinedtable By New With { _
Key .placeCol = userdefinedtable("Place") _
}New With { _
Key .ValueUD = groupbyUD.Key, _
Key .ColumnValuesUD = groupbyUD _
}
Dim place As String = ""
Dim [date] As String = ""
Dim tempTable As New DataTable()
Dim slectedFieldsTable As New DataTable()
Dim newRow As DataRow
Dim list As New List(Of Object)()
create the data table
slectedFieldsTable = New DataTable()
slectedFieldsTable.Columns.Add("place")
slectedFieldsTable.Columns.Add("date")
Also below var get the error and grouped also get the error.
For Each keyUD As var In grouped
Console.WriteLine(keyUD.ValueUD.placeCol)
place = DirectCast(keyUD.ValueUD.placeCol, String)
Dim lst As New List(Of DateTime)()
For Each columnValue As var In keyUD.ColumnValuesUD
lst.Add(Convert.ToDateTime(columnValue("date")))
Next
Console.WriteLine(lst.Min())
[date] = DirectCast(Convert.ToString(lst.Min()), String)
slectedFieldsTable.Rows.Add(place, [date])
Next
bind the value data set to list
For Each drin As DataRow In slectedFieldsTable.Rows
list.Add(drin)
Next
tempTable.Columns.Add("place", GetType(String))
tempTable.Columns.Add("date", GetType(String))
For Each drlst As DataRow In list
newRow = tempTable.NewRow()
newRow("place") = drlst.ItemArray(0).ToString()
newRow("date") = drlst.ItemArray(1).ToString()
tempTable.Rows.Add(newRow)
tempTable.AcceptChanges()
Next
Console.ReadLine()
End Sub
End Class
End Namespace
I think following code solve your problem. Replace code with yours.
Dim grouped = From userdefinedtable In dt.AsEnumerable() _
Group userdefinedtable By Key = userdefinedtable("Place") Into Group _
Select ValueUD = Key, ColumnValuesUD = Group
Replace as Var with as Object
For Each keyUD As Object In grouped
Console.WriteLine(keyUD.ValueUD.placeCol)
place = DirectCast(keyUD.ValueUD.placeCol, String)
Dim lst As New List(Of DateTime)()
For Each columnValue As Object In keyUD.ColumnValuesUD
lst.Add(Convert.ToDateTime(columnValue("date")))
Next
Console.WriteLine(lst.Min())
[date] = DirectCast(Convert.ToString(lst.Min()), String)
slectedFieldsTable.Rows.Add(place, [date])
Next