check for uniqueness of employee id number - vb.net

Cant seem to figure out how to check for a unique Employee id Number. I know the validation has to go in the form load, just not sure how to go about it.
Public Class Form1
Dim filename As String
Dim dataFile As System.IO.File
Dim dataWrite As System.IO.StreamWriter
''LOADING AND WRITE TO TEXT DOCUMENT
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'asks user for file name
filename = InputBox("Enter output file name")
If IO.File.Exists(filename) Then
dataWrite = IO.File.AppendText(filename)
Else
MessageBox.Show("filename does not exist")
filename = InputBox("Enter output file name")
dataWrite = IO.File.CreateText(filename)
End If
cboDepart.Items.Add("Accounting")
cboDepart.Items.Add("Administration")
cboDepart.Items.Add("Marketing")
cboDepart.Items.Add("MIS")
cboDepart.Items.Add("Sales")
End Sub
'------
Public EMPLOYEEIDS As String
Dim employeeID1 As ServerData()
Dim employeeID2 As ServerData()
Dim reader As String = My.Computer.FileSystem.ReadAllText("servers.lst")
Dim s() As String
Dim Totalemployeeids As String = CStr(reader.Length)
Dim x As Integer = 0
Dim myArray As String() = reader.Split("|"c)
For x = 1 To Totalemployeeids
employeeID1(x).ServerName = myArray(0)
employeeID2(x).IDname = myarray(0)
Form1_load.ListBox1.Items.Add(Servers(x).ServerName)
x += 1
Next
Structure ServerData
End Structure
End Class

You usually do not insert a unique ID from the client side. Instead, it is inserted automatically by the database server. There is a way to retrieve an inserted ID back, if you need it for display (can also act as a confirmation that a record was successfully inserted):
SELECT SCOPE_IDENTITY()
An example is shown in this answer:
How to get last inserted id? (C#)
On the client side, you need to implement insertion of everything but the ID, in this case you don't need to check for uniqueness. There may be other validation issues upon commit though (unique key violation, data type mismatch) - make sure you catch exceptions and display them to the user as appropriate.

Related

Copy serial numbers from string or txt file to Listbox

I have a string or a text file which contains some software serial number among other information.
I’m trying to pull out the software serial numbers which all start with EAN- and send them to a listbox.
Example of the string or text file:
2
EAN-3E4R5-5TGGG-6667Y
Software name Technology
PO #PORD-11111
INV-219149
3
EAN-SXDR5-5DDD-6DDDY
Software name Technology
PO #PORD-11111
INV-219149
I'm after just the serial numbers beging with EAN-.
So the listbox would be
EAN-3E4R5-5TGGG-6667Y
EAN-SXDR5-5DDD-6DDDY
This code would work:
Dim strBuf As String
strBuf = "EAN-3E4R5-5TGGG-6667Y Software nam.............."
Dim Tokens1() As String
Tokens1 = Split(strBuf, "EAN-")
For I = 1 To UBound(Tokens1)
Dim OneListItem As String = "EAN-" & Split(Tokens1(I), " ")(0)
ListBox1.Items.Add(OneListItem)
Next
I read the file with .ReadAllLines which returns an array of the lines in the file. I looped through the lines and if a line started with EAN- it was added to the list. Then the list is bound to the ListBox.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lstSerialNums As New List(Of String)
Dim lines = File.ReadAllLines("C:\Users\maryo\Desktop\Code\Serial Numbers.txt")
For Each line In lines
If line.StartsWith("EAN-") Then
lstSerialNums.Add(line)
End If
Next
ListBox1.DataSource = lstSerialNums
End Sub
With a small amount of LINQ, you can make quite readable code:
Dim srcFile = "C:\temp\SO67550806.txt"
Dim eans = File.ReadLines(srcFile).Where(Function(s) s.StartsWith("EAN-")).ToList()
yourListBoxName.DataSource = eans

Cycle through xml data in VB.Net

I posted a question about how to read the content of external xml files in VB.Net (find it here) and so far everything is going great, but I have no idea how to cycle through the data (they are all elements called savedPassword with a specific id number). Now, I know I am supposed to give a minimum of code, but I am just starting off in XML and VB.Net and I have no idea how much code I need to give for someone to help me out with a script, so here I am, giving a paragraph of code blocks...
I have the following code so far and it works amazingly well (so if no one could modify it, that would be amazing).
My module (Overview.vb):
' Dim values for directories and paths '
Public ReadOnly DirectoryHome As String = "C:\VelocityDK Codes"
Public ReadOnly DirectoryApp As String = "C:\VelocityDK Codes\Password Manager"
Public ReadOnly DataFile As String = "C:\VelocityDK Codes\Password Manager\appData.xml"
' Dim values for .xml file '
Public ReadOnly xmlRoot As String = "savedData"
My [general] form reading the data from my xml file (frmManager.vb):
Option Strict On
Imports System.IO
Imports System.Xml.Serialization
' Some unrelated code '
' This current line is not in the code, but I am disabling the error message with an "unused member" - which is refering to the xmlRoot value right below. '
#Disable Warning IDE0051 ' Remove unused private members
Private ReadOnly xmlRoot As String = "savedData"
#Enable Warning IDE0051 ' Remove unused private members
' Class to represent the xml file '
Public Class SavedData
<XmlElement("savedPassword")>
Public Property SavedPasswords As List(Of SavedPassword)
End Class
' Class to represent data from external xml file '
Public Class SavedPassword
<XmlAttribute("id")>
Public Property ID As Byte
<XmlElement("name")>
Public Property Name As String
<XmlElement("email")>
Public Property Email As String
<XmlElement("password")>
Public Property Password As String
End Class
' Read xml content at first load '
Private Sub FrmManager_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim filename = DataFile
Dim data As SavedData
Dim serializer As New XmlSerializer(GetType(SavedData))
Using sr = New StreamReader(filename)
data = CType(serializer.Deserialize(sr), SavedData)
End Using
For Each sp In data.SavedPasswords
txtID.Text = {sp.ID}.ToString
txtName.Text = {sp.Name}.ToString
txtEmail.Text = {sp.Email}.ToString
txtPassword.Text = {sp.Password}.ToString
Next
End Sub
Finally, my .xml file (appData.xml located in the directory C:\VelocityDK Codes\Password Manager) looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<savedData>
<savedPassword id="01">
<name>Name 01</name>
<email>email01#mail.com<email>
<password>password01</password>
</savedPassword>
<savedPassword id="02">
<name>Name 02</name>
<email>email02#mail.com<email>
<password>password02</password>
</savedPassword>
<!-- Other sections like the aboves going from id's 03 to 06 -->
<savedPassword id="07">
<name>Name 07</name>
<email>email07#mail.com<email>
<password>password07</password>
</savedPassword>
</savedData>
In brief, I have two buttons (btnPrevious & btnNext) and I want to make it so that when I click on the btnPrevious button, it goes to the previous savedPassword (located in my xml file) and vice versa for the btnNext button. How can I do so?
First of all, make your form's load event look like this.
'Make this global
Dim data As SavedData
Private Sub FrmManager_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim filename = DataFile
Dim serializer As New XmlSerializer(GetType(SavedData))
Using sr = New StreamReader(filename)
data = CType(serializer.Deserialize(sr), SavedData)
End Using
'Remove for loop to display just the first record. .
txtID.Text = {data.SavedPasswords(0).ID}.ToString
txtName.Text = {data.SavedPasswords(0).Name}.ToString
txtEmail.Text = {data.SavedPasswords(0).Email}.ToString
txtPassword.Text = {data.SavedPasswords(0).Password}.ToString
End Sub
Next, keep an index somewhere in your program for cycling back and forth the list.
Dim data As SavedData
Dim currentIndex As Integer = 0
Next, Under the button click events, add the following code
'Next button
Public Sub BtnNext_Click(sender As Object, e As EventArgs)
If currentIndex < data.SavedPasswords.Count() Then
currentIndex += 1
Else
MessageBox.Show("End of data reached")
End If
txtID.Text = {data.SavedPasswords(currentIndex).ID}.ToString
txtName.Text = {data.SavedPasswords(currentIndex).Name}.ToString
txtEmail.Text = {data.SavedPasswords(currentIndex).Email}.ToString
txtPassword.Text = {data.SavedPasswords(currentIndex) .Password}
End Sub
'Previous button
Public Sub BtnPrevious_Click(sender As Object, e As EventArgs)
If currentIndex > 0 Then
currentIndex -= 1
Else
MessageBox.Show("This is the first record!")
End If
txtID.Text = {data.SavedPasswords(currentIndex).ID}.ToString
txtName.Text = {data.SavedPasswords(currentIndex).Name}.ToString
txtEmail.Text = {data.SavedPasswords(currentIndex).Email}.ToString
txtPassword.Text = {data.SavedPasswords(currentIndex).Password}
End Sub
I would do the following.
First, create some global variable which would keep the current saved password ID. Then the following procedure will search for the next ID. Note that the actual getting XML must be realized by you.
Private curr_id$ = "01" '//Global variable
'// The direction we're searching
Enum Direction
Forward
Backward
End Enum
'// Get the <savedPassword> element. The function returns Nothing,
'// if it doesn't find ID.
Function GetSavedPassword(direction As Direction) As XElement
Dim obj_xml =
<?xml version="1.0" encoding="UTF-8"?>
<savedData>
<savedPassword id="01">
<name>Name 01</name>
<email>email01#mail.com</email>
<password>password01</password>
</savedPassword>
<savedPassword id="02">
<name>Name 02</name>
<email>email02#mail.com</email>
<password>password02</password>
</savedPassword>
<!-- Other sections like the aboves going from id's 03 to 06 -->
<savedPassword id="07">
<name>Name 07</name>
<email>email07#mail.com</email>
<password>password07</password>
</savedPassword>
</savedData>
Dim next_id = -1 '//ID we're searching (initial state)
Dim curr_id_num = CInt(curr_id) '//Convert string to int
'// Get all IDs from XML
Dim ids = obj_xml.<savedData>.<savedPassword>.Select(Function(x) CInt(x.#id))
'// Next we compare the current ID with available IDs
If direction = Direction.Forward Then
'// If we need to go FORWARD,
'// we must get all IDs which are greater than current id
Dim next_ids = ids.Where(Function(id) id > curr_id_num)
'// Make sure we have found something -
'// in this case it's safe to call Min()
If next_ids.Any() Then next_id = next_ids.Min()
ElseIf direction = Direction.Backward
'// If we need to go BACKWARD,
'// we must get all IDs which are less than current id
Dim next_ids = ids.Where(Function(id) id < curr_id_num)
'// Make sure we have found something -
'//in this case it's safe to call Max()
If next_ids.Any() Then next_id = next_ids.Max()
End If
'// If we found id, it will be greater than 0
If next_id > 0 Then
Dim id_string = If(next_id <= 9, "0" & next_id, next_id)
Return obj_xml.<savedData>.<savedPassword>.
Where(Function(p) p.#id = id_string).
FirstOrDefault()
End If
End Function
'// Usage
Sub Main()
Dim saved_password As XElement = GetSavedPassword(Direction.Forward)
If saved_password IsNot Nothing Then
'// Update current id
curr_id = saved_password.#id
Dim name = saved_password.<name>(0)
Dim email = saved_password.<email>(0)
Dim password = saved_password.<password>(0)
'// Update state of the program
'// ....
End If
End Sub

Read from text file, store data into corresponding structure every 6 element, and then form an array

The text file contains the following: inside the [], anything inside () was not in the text file, just for clarification
[1(ID)
Jimmy(First name)
Paul (Last name)
78 (marks1)
80 (marks2)
92 (marks3)
2
Ben
James
67
82
73
]
I created a structure that holds student details including their name, id, marks in each subject.
Private Structure StudInfo
Public FName As String
Public LName As String
Public StudentId As Integer
Public ScMark As Integer
Public EnMark As Integer
Public MaMark As Integer
The program needs to read the first six elements in a row, storing each element into the corresponding structure type, then let it become the first element of an array"students()", and then next six elements, let it become the second element of that array. I have no idea how to use loops to do that.
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
'create an array that hold student details
Dim Students() As StudInfo
' read from text file
Dim FileNum As Integer = FreeFile()
Dim TempS As String = ""
Dim TempL As String
FileOpen(FileNum, "some.text", OpenMode.Input)
Do Until EOF(FileNum)
TempL = LineInput(FileNum)
TempS = TempL + vbCrLf
Loop
End Sub
Thank you.
You have to use a BinaryReader (which takes a IO.Stream as it's constructor), then you can read the data type you want, into the variable you want.
The problem you will have is the data will not be searchable (ie. you cannot read the 30th record, unless you physically read the first 29, because the strings are of variable length, and therefore the record is variable length), this also applies to modifying a record (you cant make it bigger, because it will overwrite the next record).
The answer is to work with fixed length records, or field offsets or fixed length strings. Then you will have a records of predictable size, and you can determine the amount of records by dividing the file length by the record size.
Hope this helps.
You could try something like this:
Public Class Form1
Private Students As New List(Of StudInfo)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Students.Clear()
Dim fileName = "c:\some folder\directory\someFile.txt"
Using sr As New System.IO.StreamReader(fileName)
Dim value As Integer
Dim strValue As String
While Not sr.EndOfStream
Try
Dim student As New StudInfo
strValue = sr.ReadLine().Trim("[]")
If Integer.TryParse(strValue, value) Then
student.StudentId = value
Else
MessageBox.Show("Error Converting StudentID to Integer")
Exit Sub
End If
student.FName = sr.ReadLine().Trim("[]")
student.LName = sr.ReadLine().Trim("[]")
strValue = sr.ReadLine().Trim("[]")
If Integer.TryParse(strValue, value) Then
student.ScMark = value
Else
MessageBox.Show("Error Converting ScMark to Integer")
Exit Sub
End If
strValue = sr.ReadLine().Trim("[]")
If Integer.TryParse(strValue, value) Then
student.EnMark = value
Else
MessageBox.Show("Error Converting EnMark to Integer")
Exit Sub
End If
strValue = sr.ReadLine().Trim("[]")
If Integer.TryParse(strValue, value) Then
student.MaMark = value
Else
MessageBox.Show("Error Converting MaMark to Integer")
Exit Sub
End If
Students.Add(student)
Catch ex As Exception
MessageBox.Show("Error reading file. All records may not have been created.")
End Try
End While
MessageBox.Show("Done!")
End Using
End Sub
Private Class StudInfo
Public FName As String
Public LName As String
Public StudentId As Integer
Public ScMark As Integer
Public EnMark As Integer
Public MaMark As Integer
End Class
End Class
It depends a bit on the exact format of your text file.
If the file only contains the data for the two students (no brackets or blank lines), then all you need to do is to open the file and read 6 lines, add the data to your structure. and read the next 6 lines. If you have an undetermined number of students in the text file, then you would be better using a List. Other wise you're goiing to have to use extra processing time to Redim the array each time you want to add a student and keep track of the array size an all sorts of messing around.
However. Lets go with the most straightforward answer and assume your data has no brackets or blank lines and that there are only two students.
This code should work just fine. If you have a different definite number of students, then you will need to change the size of the Students array.
I'm also assuming that the data is correctly formatted and there are no non-numeric characters are in the lines where there shouldn't be.
Private Sub ReadStudentInfo()
'create an array that hold student details
Dim Students(2) As StudInfo
Dim index As Integer = 0
' read from text file
Dim datafile As New StreamReader("some.text")
Do Until datafile.EndOfStream
Dim tempStudent As StudInfo
With tempStudent
Integer.TryParse(datafile.ReadLine, .StudentId)
.FName = datafile.ReadLine
.LName = datafile.ReadLine
Integer.TryParse(datafile.ReadLine, .ScMark)
Integer.TryParse(datafile.ReadLine, .EnMark)
Integer.TryParse(datafile.ReadLine, .MaMark)
End With
Students(index) = tempStudent
index = index + 1
Loop
End Sub
If your text file does contain blank lines, just insert
datafile.ReadLine()
between each line of data - like this
Integer.TryParse(datafile.ReadLine, .ScMark)
datafile.ReadLine()
Integer.TryParse(datafile.ReadLine, .EnMark)
If you have the brackets in your text file, then you'll need to add extra code to remove them.

VB 2010 array/write array to file

I'm close to getting this to work, but currently can't get any output to display in the listbox. I had it working, but needed to move some things around to get the join function to work.
In my program, a user enters input into a textbox and an array is displayed in a listbox based on what they type in. For example, if they type in "a", all foods (in the textfile that is connected to the program) that start with "a" will be displayed.
When there is output, I need to find a way to name this array (which is created based on what the user inputs) and join all of the items in the listbox (example: foods stacked on top of each other in the listbox will be shown at the bottom as a string).
I am posting the code that I have thus far; all of the errors that I'm getting (and potentially my logic errors) are just in the first public class until the end of the first if-next statement:
Public Class frmFoods
Dim foods() As String = IO.File.ReadAllLines("foods.txt")
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
Dim Letter As String = txtLetter.Text.ToUpper
Dim smallerarray() As Array
Dim userarray As String
lstOutput.Items.Clear()
If IsNumeric(txtLetter.Text) = False Then
For Each food As String In foods
smallerarray = listfoods(Letter)
lstOutput.Items.Add(Letter)
userarray = Join(smallerarray, ", ")
lstOutput.Items.Add(userarray)
Next
ElseIf IsNumeric(txtLetter.Text) = True Then
MessageBox.Show("Please enter a letter.")
Else
MessageBox.Show("The text box is empty")
End If
End Sub
Function listfoods(ByVal letter As String) As String()
Dim foodarray(foods.Count - 1) As String
Dim counter As Integer = 0
For Each food As String In foods
If food.StartsWith(letter) Then
foodarray(counter) = food
counter += 1
End If
Next
ReDim Preserve foodarray(counter - 1)
Return foodarray
End Function
you need to save the results of the listfoods function in a dictionary or similar and associate it with a key if you want to 'Name' it, although its not clear why you need to do this
As for listing the foods starting with the particular letter, you just need to iterate your result of the function listfoods and separate each one by a comma don't you?
What you have now will create many lists of each food as you are getting the list of food beginning with a particular letter for each food.. As I understand the question you only need to do that once.
Example:
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
Dim Letter As String = txtLetter.Text.ToUpper
Dim smallerarray() As Array
Dim userarray As String
lstOutput.Items.Clear()
If IsNumeric(txtLetter.Text) = False Then
'get all items from the file which begin with the letter the user chose
smallerarray = listfoods(Letter)
'add that letter to the output listbox
lstOutput.Items.Add(Letter)
'join all of the elements which begin with that letter
'into a single comma separated string
userarray = Join(smallerarray, ", ")
'add that string to the output
lstOutput.Items.Add(userarray)
ElseIf IsNumeric(txtLetter.Text) = True Then
MessageBox.Show("Please enter a letter.")
Else
MessageBox.Show("The text box is empty")
End If
End Sub
it would probably be useful for you to step through the code and see the values of the variable at each place and compare this with what you expect to see if you can see where the actual value differs from what your logically expect so you can start to identify where the issue is

Error In VB.Net code

I am getting the error "Format Exception was unhandled at "Do While objectReader.Peek <> -1
" and after. any help would be wonderful.
'Date: Class 03/20/2010
'Program Purpose: When code is executed data will be pulled from a text file
'that contains the named storms to find the average number of storms during the time
'period chosen by the user and to find the most active year. between the range of
'years 1990 and 2008
Option Strict On
Public Class frmHurricane
Private _intNumberOfHuricanes As Integer = 5
Public Shared _intSizeOfArray As Integer = 7
Public Shared _strHuricaneList(_intSizeOfArray) As String
Private _strID(_intSizeOfArray) As String
Private _decYears(_intSizeOfArray) As Decimal
Private _decFinal(_intSizeOfArray) As Decimal
Private _intNumber(_intSizeOfArray) As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'The frmHurricane load event reads the Hurricane text file and
'fill the combotBox object with the data.
'Initialize an instance of the StreamReader Object and declare variable page 675 on the book
Dim objectReader As IO.StreamReader
Dim strLocationAndNameOfFile As String = "C:\huricanes.txt"
Dim intCount As Integer = 0
Dim intFill As Integer
Dim strFileError As String = "The file is not available. Please restart application when available"
'This is where we code the file if it exist.
If IO.File.Exists(strLocationAndNameOfFile) Then
objectReader = IO.File.OpenText(strLocationAndNameOfFile)
'Read the file line by line until the file is complete
Do While objectReader.Peek <> -1
**_strHuricaneList(intCount) = objectReader.ReadLine()
_strID(intCount) = objectReader.ReadLine()
_decYears(intCount) = Convert.ToDecimal(objectReader.ReadLine())
_intNumber(intCount) = Convert.ToInt32(objectReader.ReadLine())
intCount += 1**
Loop
objectReader.Close()
'With any luck the data will go to the Data Box
For intFill = 0 To (_strID.Length - 1)
Me.cboByYear.Items.Add(_strID(intFill))
Next
Else
MsgBox(strFileError, , "Error")
Me.Close()
End If
End Sub
Put a break-point on these lines and step through your code:
_decYears(intCount) = Convert.ToDecimal(objectReader.ReadLine())
_intNumber(intCount) = Convert.ToInt32(objectReader.ReadLine())
Whatever is being returned by ReadLine isn't in the proper decimal or integer format when passed to the converters. You'll need to add some try/catch blocks around the do-while loop operations to handle it gracefully and make sure your data is formatted the way you expected since the wrong parts are being used in this scenario.
Also, each call to ReadLine is returning an entirely new line and the Peek check won't account for those. As long as you can trust your data that's fine.
Instead of using Convert.ToDecimal an Convert.ToInt32, try using Decimal.TryParse() and Int32.TryParse(). If they don't parse, you know your file isn't setup correctly. If they do parse, then you've loaded the value into a variable for your use.
EDIT:
Use it like this.
Dim myDecimal As Decimal
If Decimal.TryParse(objectReader.ReadLine(), myDecimal) Then
'your string successfully parsed. Use myDecimal however you want. It has the parsed value.
Else
'your string is not a decimal. Now that you know that, you can handle this situation here without having to catch an exception.
End If