IOException Was Unhandled Error Help for Newbie - visual-studio-2010

You'll have to excuse me for a repeat question but I just can't seem to understand the responses others have been posting. My coding skills are very limited (barely a year in vb 2006 and vs 2010)
I know that the sr has opened too many of the same file but I cant figure out a fix for it. Explaining it to me in simple concepts would be very helpful. Once again sorry for the newby-ness.
Project Explanation: Create a bowling league stats keeper. cmdRegisterBowler adds bowler name to a dat file (bowlers.dat). cmdEnterScores will write name and stats to games.dat file.
Private Sub cmdRegisterBowler_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRegisterBowler.Click
'BOWLER REGISTRATION
Dim Person As String
Dim Team As String
txtName.Text.ToUpper()
txtTeam.Text.ToUpper()
Person = txtName.Text
Team = txtTeam.Text
If Person <> "" And Team <> "" Then
If IsInFile(Person & " " & Team) = True Then
MessageBox.Show(Person & " is already in the file.", "Error")
txtName.Clear()
txtTeam.Clear()
txtName.Focus()
Else
'swb = stream writer bowlers file
Dim swb As IO.StreamWriter = IO.File.AppendText("bowlers.dat")
swb.WriteLine(Person & " " & Team)
swb.Close()
MessageBox.Show(Person & " has been added to the file.", "Information Added")
txtName.Clear()
txtTeam.Clear()
txtName.Focus()
End If
Else
MessageBox.Show("You must enter a name.", "Information Incomplete")
End If
End Sub
Function IsInFile(ByVal person As String) As String
If IO.File.Exists("bowlers.dat") Then
Dim sr As IO.StreamReader = IO.File.OpenText("bowlers.dat")
Dim individual As String
Do Until sr.EndOfStream
individual = sr.ReadLine
If individual = person Then
Return True
sr.Close()
End If
Loop
sr.Close()
End If
Return False
End Function
Private Sub cmdEnterScores_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEnterScores.Click
'SCORE ENTRY
Dim Person As String
Dim Team As String
Dim Score1 As Double
Dim Score2 As Double
Dim Score3 As Double
Dim Average As Double
Dim Display As String = "{0,-10} {1,10} {2,20} {3,10} {4,10} {5,10} {6,10}"
Dim Total As Double
Person = txtName2.Text
Team = txtTeam2.Text
Score1 = Val(txtFirstGame.Text)
Score2 = Val(txtSecondGame.Text)
Score3 = Val(txtThirdGame.Text)
Total = Score1 + Score2 + Score3
Average = Total / 3
Dim swb As IO.StreamWriter = IO.File.AppendText("bowlers.dat")
'Checks for blank entries
If Person <> "" Then
'Checks to see if person is registered
If IsNotInFile(Person) Then
Dim Response As Integer
' Displays a message box with the yes and no options to register bowler.
Response = MsgBox(Prompt:="The bowler you have entered is currently not registered. Would you like to do so?", Buttons:=vbYesNo)
'Yes button was selected. Bowler is then registered to bowlers.dat
If Response = vbYes Then
''swb = stream writer bowlers file
swb.WriteLine(Person & " " & Team)
swb.Close()
MessageBox.Show(Person & " has been added to the file.", "Information Added")
'The no button was selected. Focus is set to bowler registration group box
Else : Response = vbNo
txtName2.Clear()
txtTeam2.Clear()
txtFirstGame.Clear()
txtSecondGame.Clear()
txtThirdGame.Clear()
txtName.Focus()
End If
'If no then clears score entry group box and sets focus back to bowler registr
txtName.Clear()
txtName.Focus()
Else
'Write scores to games.dat file
'swg = stream writer games file
Dim swg As IO.StreamWriter = IO.File.AppendText("games.dat")
swg.WriteLine(Name & " " & Team & " " & Score1 & " " & Score2 & " " & Score3)
swg.Close()
MessageBox.Show(Person & "'s stats added to the file.", "Information Added")
txtName.Clear()
txtName.Focus()
Dim Display2 As String = "{0,-10} {1,10} {2,20} {3,10} {4,10} {5,10} {6,10}"
lstDisplay.Items.Add(String.Format(Display2, Person, Team, Score1, Score2, Score3, Total, Average))
End If
Else
MessageBox.Show("You must enter a name.", "Information Incomplete")
End If
End Sub
Function IsNotInFile(ByVal person As String) As String
If IO.File.Exists("bowlers.dat") Then
Dim sr As IO.StreamReader = IO.File.OpenText("bowlers.dat")
Dim individual As String
Do Until sr.EndOfStream
individual = sr.ReadLine
If individual <> person Then
Return True
sr.Close()
End If
Loop
sr.Close()
End If
Return False
End Function
Heres all my code. Thanks for any help in advance.

I haven't used Visual Basic in quite a while, but I believe the solution is simple.
Basically, your interactions with the System.IO library are currently very optimistic. You should always wrap IO interactions within a TRY...CATCH...END TRY block.
Check it out here: MSDN Example of StreamReader.ReadLine
To illustrate more clearly my meaning, I've altered one of your functions here:
Function IsInFile(ByVal person As String) As String
Try
If IO.File.Exists("bowlers.dat") Then
Dim sr As IO.StreamReader = IO.File.OpenText("bowlers.dat")
Dim individual As String
Do Until sr.EndOfStream
individual = sr.ReadLine
If individual = person Then
Return True
sr.Close()
End If
Loop
sr.Close()
End If
Return False
Catch ie as IOException
MessageBox.Show("Failed to search for " & person & " in file.", "Error")
Return false
End Try
End Function
I'd apply similar logic to surround all your interactions with Files within your code. I'd also recommend against using MessageBox to report errors -- it's okay for small projects, but for anything larger you're going to want to look up using a logging framework. Or build a debug console into your application that you can selective turn on or off via configuration.

Related

Warn before sending Outlook message

My Outlook Address book by default storing e-mail addresses in the combination of upper and lower case letters, in that case below code is not working for me. Please advise.
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim Recipients As Outlook.Recipients
Dim recip As Outlook.Recipient
Dim i
Dim prompt As String
On Error Resume Next
' use lower case for the address
' LCase converts all addresses in the To field to lower case
Checklist = "firstname.lastname#domain.com"
Set Recipients = Item.Recipients
For i = Recipients.Count To 1 Step -1
Set recip = Recipients.Item(i)
If InStr(LCase(recip), LCase(Checklist)) Then
prompt$ = "You sending this to this messgae to Treasurer " & Item.To & ". Are you sure you want to send it?"
If MsgBox(prompt$, vbYesNo + vbQuestion + vbMsgBoxSetForeground, "Check Address") = vbNo Then
Cancel = True
End If
End If
Next i
End Sub

Validate entry of an input box

Im trying to get an input box to validate the entries a user will make.
i'm using the below script but cant get the validation to work, any help would be appreciated.
Sub inputbox()
Dim Manager As Long
On Error Resume Next
Application.DisplayAlerts = False
Manager = Application.inputbox(Prompt:="Please enter a manager.", Title:="Pick A Manager Name", Type:=1)
On Error GoTo 0
Application.DisplayAlerts = True
If Manager = "" Then
Exit Sub
ElseIf Manager <> Ben, Cameron, Chris, Martin, Peter Then
MsgBox "Incorrect Name, pick a new one!"
Else
MsgBox "Your input was " & Manager
End If
End Sub
Although a Sub name same as built in ones are not recommended, you can do what you are after like below.
First you need to change the InputBox Type to 2 (String), since you are comparing with String. Then you should make a function to check if the input is part of a Manager List.
Sub inputbox()
On Error Resume Next
Dim Manager As String
Manager = Application.inputbox(Prompt:="Please enter a manager name:", Title:="Pick A Manager Name", Type:=2)
If Manager <> "" Then
If IsManager(Manager) Then
MsgBox "Your input was " & Manager
Else
MsgBox "Incorrect Name, pick a new one!"
End If
End If
End Sub
Private Function IsManager(sTxt As String) As Boolean
Dim aManagers As Variant, oItem As Variant, bAns As Boolean
aManagers = Array("Ben", "Cameron", "Chris", "Martin", "Peter")
bAns = False
For Each oItem In aManagers
If LCase(oItem) = LCase(Trim(sTxt)) Then
bAns = True
Exit For
End If
Next
IsManager = bAns
End Function
UPDATE (Improved version suggested by Simon1979):
Private Function IsManager(sTxt As String) As Boolean
On Error Resume Next
Dim aManagers As Variant
aManagers = Array("Ben", "Cameron", "Chris", "Martin", "Peter")
IsManager = Not IsError(Application.WorksheetFunction.Match(Trim(sTxt), aManagers, 0))
End Function
Haven't used the InputBox with Excel but I imagine it will be very similar to the Access one. I use the below method to validate inputbox:
Dim strM as string
EnterManager:
strM = InputBox("Enter Manager.")
If StrPtr(strM) = 0 Then 'Cancel was pressed
' Handle what to do if cancel pressed
Exit Sub
ElseIf Len(strM) = 0 Then 'OK was pressed with nothing entered
MsgBox "You must enter a Manager."
GoTo EnterBuyer
End If
To add your criteria you could add on another If, I'm not sure you can use the approach you have for checking the list of names. Also don't understand how you compare a long Manager with a list of names Ben, Cameron, Chris, Martin, Peter, unless they are assigned variables, in which case I would suggest adding prefixes so it is more obvious such as lBen as opposed to strBen so you can easily see the difference in variable type.
If strM <> "Ben" And strM <> "Cameron" And strM <> "Chris" And strM <> _
"Martin" And strM <> "Peter" Then
MsgBox "Incorrect Name, pick a new one!"
Else
MsgBox "Your input was " & strM
End If

Change outlook subject line

How do I write a VBA method that replaces the subject if there is a specific word in the subject. This code would find a certain key word (different than the subject key word) in the body of the email. It would then replace the subject line with 13 charactars after the key word found in the body of the text.
The below was already found but doesn't mention how to find anything in the body of the email. And I don't get the MAPI reference.
Any help would truly be appreciated
Thank You in advance for any assistance
Rick
Sub RewriteSubject(MyMail As MailItem)
Dim mailId As String
Dim outlookNS As Outlook.NameSpace
Dim myMailItem As Outlook.MailItem
mailId = MyMail.EntryID
Set outlookNS = Application.GetNamespace("MAPI")
Set myMailItem = outlookNS .GetItemFromID(mailId)
' Do any detection here
mailItem.Subject = "Dept - " & mailItem.Subject
myMailItem.Save
Set mailItem = Nothing
Set outlookNS = Nothing
End Sub
If it is for all new messages then you can use the following
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim v As Variant
For Each v In Array("first", "second")
If InStr(1, Item.Subject, v, vbTextCompare) <> 0 Then
SearchForAttachWords = True
End If
Next
If SearchForAttachWords = True Then
Item.Subject = "Whatever subject you want"
End If
End Sub
Hope this helps.

VB dataset issue

The idea was to create a message box that stores my user name, message, and post datetime into the database as messages are sent.
Soon came to realize, what if the user changed his name?
So I decided to use the user id (icn) to identify the message poster instead. However, my chunk of codes keep giving me the same error. Says that there are no rows in the dataset ds2.
I've tried my Query on my SQL and it works perfectly so I really really need help to spot the error in my chunk of codes here.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim name As String
Dim icn As String
Dim message As String
Dim time As String
Dim tags As String = ""
Dim strConn As System.Configuration.ConnectionStringSettings
strConn = ConfigurationManager.ConnectionStrings("ufadb")
Dim conn As SqlConnection = New SqlConnection(strConn.ToString())
Dim cmd As New SqlCommand("Select * From Message", conn)
Dim daMessages As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim ds As New DataSet
cmd.Connection.Open()
daMessages.Fill(ds, "Messages")
cmd.Connection.Close()
If ds.Tables("Messages").Rows.Count > 0 Then
Dim n As Integer = ds.Tables("Messages").Rows.Count
Dim i As Integer
For i = 0 To n - 1
icn = ds.Tables("Messages").Rows(i).Item("icn")
Dim cmd2 As New SqlCommand("SELECT name FROM Member inner join Message ON Member.icn = Message.icn WHERE message.icn = #icn", conn)
cmd2.Parameters.AddWithValue("#icn", icn)
Dim daName As SqlDataAdapter = New SqlDataAdapter(cmd2)
Dim ds2 As New DataSet
cmd2.Connection.Open()
daName.Fill(ds2, "PosterName")
cmd2.Connection.Close()
name = ds2.Tables("PosterName").Rows(0).Item("name")
message = ds.Tables("Messages").Rows(i).Item("message")
time = ds.Tables("Messages").Rows(i).Item("timePosted")
tags = time + vbCrLf + name + ": " + vbCrLf + message + vbCrLf + tags
Next
txtBoard.Text = tags
Else
txtBoard.Text = "nothing to display"
End If
End Sub
Would it be more efficient to combine both cmd and cmd2, such that cmd becomes
SELECT msg.*,mem.Name FROM Message msg INNER JOIN Member mem ON msg.icn = mem.icn ?
This way, your Member.name would be in the same dataset as your Messages table, making your code much cleaner.
-Joel

Extracting data from an email message (or several thousand emails) [Exchange based]

My marketing department, bless them, has decided to make a sweepstakes where people enter over a webpage. That is great but the information isn't stored to a DB of any sort but is sent to an exchange mail box as an email. Great.
My challenge is to extract the entry (and marketing info) from these emails and store them someplace more useful, say a flat file or CSV. The only saving grace is that the emails have a highly consistant format.
I am sure I could spend the time saving all the emails to files and then write an app to munge through them all but was hoping for a much more elegant solution. Can I programmatically access an exchange mailbox, read all the emails and then save that data?
Here is the code I used....
Private Sub btnGo_Click()
If ComboBox1.SelText <> "" Then
Dim objOutlook As New Outlook.Application
Dim objNameSpace As Outlook.NameSpace
Dim objInbox As MAPIFolder
Dim objMail As mailItem
//Get the MAPI reference
Set objNameSpace = objOutlook.GetNamespace("MAPI")
//Pick up the Inbox
Set objInbox = objNameSpace.GetDefaultFolder(olFolderInbox)
For Each objFolder In objInbox.Folders
If (objFolder.Name = ComboBox1.SelText) Then
Set objInbox = objFolder
End If
Next objFolder
//Loop through the items in the Inbox
Dim count As Integer
count = 1
For Each objMail In objInbox.Items
lblStatus.Caption = "Count: " + CStr(count)
If (CheckBox1.Value = False Or objMail.UnRead = True) Then
ProcessMailItem (objMail.Body)
count = count + 1
objMail.UnRead = False
End If
Next objMail
End If
End Sub
Private Sub ProcessMailItem(strBody As String)
Open "C:\file.txt" For Append As 1
Dim strTmp As String
strTmp = Replace(strBody, vbNewLine, " ")
strTmp = Replace(strTmp, vbCrLf, " ")
strTmp = Replace(strTmp, Chr(13) & Chr(10), " ")
strTmp = Replace(strTmp, ",", "_")
//Extra Processing went here (Deleted for brevity)
Print #1, strTmp
Close #1
End Sub
Private Function Strip(strStart As String, strEnd As String, strBody As String) As String
Dim iStart As Integer
Dim iEnd As Integer
iStart = InStr(strBody, strStart) + Len(strStart)
If (strEnd = "xxx") Then
iEnd = Len(strBody)
Else
iEnd = InStr(strBody, strEnd) - 1
End If
Strip = LTrim(RTrim(Mid(strBody, iStart, iEnd - iStart)))
End Function
Private Sub UserForm_Initialize()
Dim objOutlook As New Outlook.Application
Dim objNameSpace As Outlook.NameSpace
Dim objInbox As MAPIFolder
Dim objFolder As MAPIFolder
//Get the MAPI reference
Set objNameSpace = objOutlook.GetNamespace("MAPI")
//Pick up the Inbox
Set objInbox = objNameSpace.GetDefaultFolder(olFolderInbox)
//Loop through the folders under the Inbox
For Each objFolder In objInbox.Folders
ComboBox1.AddItem objFolder.Name
Next objFolder
End Sub
There's lots of different ways to get at the messages in an exchange mailbox, but since it seems this is something you're only going to want to run once to extract the data I'd suggest writing a VBA macro to run inside Outlook itself (having opened the exchange mailbox in question within Outlook). It's pretty easy to iterate through the mail items in a specific mailbox and read the body text from them. You can then write a text file with just the stuff you want.

Resources