String was not recognized as a valid DateTime in vb.NET - vb.net

I've got this error that said String was not recognized as a valid DateTime, can anyone help me what's wrong here?
Dim Br As New BL.Bridge
Me.DataSource = Br.List(DateTime.ParseExact(Me.txtTempo.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture)) 'error is right here
Me.ReportPath = "~/report/JaTem.rpt"
Me.HasPrintButton = True
Me.ShowGroupTree = False
If DataSource.Rows.Count > 0 Then
Me.HasPrintButton = True
Server.Transfer("~/report/rpt.aspx")
Else
lblMessage.Text = "No Data!"
End If
if txtTempo is filled with date it's work, but when txtTempo is empty, it's getting error

The DateTime.ParseExact method that you are using will give an error when it runs into data that it can't handle. You need to do one of 3 things,
validate the data before using the ParseExact method
use exception handling to catch the error and notify your user
or you can use the DateTime.TryParseExact which will give you a Boolean result to indicate if the method succeeded. You would use it something like this.:
Imports System.Globalization
Module Module1
Sub Main()
Dim Date1Data As String = ""
Dim Date2Data As String = "25-09-2015"
Dim result As DateTime
If DateTime.TryParseExact(Date1Data, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result) Then
'handle it here
Else
Console.WriteLine("Format Error")
End If
If DateTime.TryParseExact(Date2Data, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result) Then
Console.WriteLine(result) 'handle it here
Else
Console.WriteLine("Format Error")
End If
Console.ReadLine()
End Sub
End Module
or modifying your code something like this should work.
Dim Br As New BL.Bridge
Dim result as Date
If DateTime.TryParseExact(Me.txtJatem.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result) Then
Me.DataSource = Br.List(result) 'error is right here
Me.ReportPath = "~/report/JaTem.rpt"
Me.HasPrintButton = True
Me.ShowGroupTree = False
If DataSource.Rows.Count > 0 Then
Me.HasPrintButton = True
Server.Transfer("~/report/rpt.aspx")
Else
lblMessage.Text = "No Data!"
End If
Else
lblMessage.Text = "Format Error, please check input and try again"
End If

Related

VSTO MailItem.Save error “The operation cannot be performed because the message has been changed”

I am trying to change categories color of a current selected mail in outlook 2013 using the explorer object to get the current selected item. Everything seems to be well except when I save it gives the error mentioned above. I have been looking for solutions and no luck any ideas? Thanks. here is my code in VB
Private Sub exp_SelectionChange() Handles exp.SelectionChange ' errrrorr
Try
waitapprovemail = Application.Session.GetItemFromID(exp.Selection.Item(1).EntryID)
if (CheckForRedCategory(waitapprovemail)) Then
If (CheckToReleaseMail(waitapprovemail)) Then
waitapprovemail.Categories = "Green Category"
waitapprovemail.Save() ''' this gives the error
End If
End If
Catch Exc As System.Runtime.InteropServices.COMException
MsgBox(Exc.Message & " " & Exc.Source)
Catch exc As System.InvalidCastException
MsgBox("Casting problem")
End Try
End Sub
Private Function CheckToReleaseMail(mail As MailItem) As Boolean ' errrrrr
' check the id with the ids in the locked mail, if found id then check the other flag if it is false or true, if found true then set the category of that waitemail to empty "" else keep it
Dim r As Boolean = True
Dim sarray As String()
' ofile2 = fso2.OpenTextFile("C:\Users\" & userName & "\Documents\Outlook Files\LockedMail.txt", 8, True) '8 for appending in arg2 0 for tristatefalse optional opens as ascii
Try
Using sr As New StreamReader("C:\Users\" & userName & "\Documents\Outlook Files\LockedMail.txt")
Dim line As String
Do
line = sr.ReadLine()
If (line.Equals("") Or line Is Nothing) Then
r = True
Continue Do
Else
sarray = line.Split(",")
If (sarray.Count > 0) Then
If (sarray(0).Equals(mail.EntryID, StringComparison.InvariantCultureIgnoreCase)) Then
r = False
sr.Close()
mail.Close(OlInspectorClose.olDiscard)
Return r
End If
End If
End If
Loop Until line Is Nothing
sr.Close()
End Using
Catch exc As System.Exception
End Try
mail.Close(OlInspectorClose.olDiscard)
Return r
End Function
Private Function CheckForRedCategory(mail As MailItem) As Boolean ' errrrrr
Dim b As Boolean = False
Try
If (mail.Categories.Equals("Red Category")) Then
b = True
mail.Close(OlInspectorClose.olDiscard)
Return b
Else
b = False
End If
Catch exc As System.NullReferenceException
b = False
mail.Close(OlInspectorClose.olDiscard)
End Try
mail.Close(OlInspectorClose.olDiscard)
Return b
End Function

VB.Net issues calling a validation function

i have written code to save data to a database, this code works fine. However, when it comes to validating the code, i have been encountering some issues despite the validation code working in console mode. The issue is that when i call the functions (seen below in the code) CheckValidPassword() etc. they dont seem to return the correct value and when it comes to the If statement in the savebutton click event, the code kind of skips it and just saves the data to the database via a datagridview.
Here is the code.
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
Dim ValidUserName, ValidPassword, ValidTeacherUsername As Boolean
Dim Username, Password, TeacherUsername As String
Username = txtStudentID.Text
Password = txtStudentPassword.Text
TeacherUsername = txtTeacherID.Text
ValidUsernameCheck(ValidUserName, Username)
ValidPasswordCheck(ValidPassword, Password)
ValidTeacherUsernameCheck(ValidTeacherUsername, TeacherUsername)
If ValidUsernameCheck(ValidUserName, Username) <> True Or ValidPasswordCheck(ValidPassword, Password) <> True Or ValidTeacherUsernameCheck(ValidTeacherUsername, TeacherUsername) <> True Then
MsgBox("Saving failed", MsgBoxStyle.OkOnly)
'Exit Sub
Else
Try
Dim dataAdapter As New OleDbDataAdapter
Dim DataTable As New DataTable
Dim DataSet As New DataSet
Connection.Open() ' the following decleration are used to save content to the table.
DataSet.Tables.Add(DataTable)
Dim SQLQuery As String = (<sql>SELECT * FROM Students</sql>)
dataAdapter = New OleDbDataAdapter(SQLQuery, Connection)
dataAdapter.Fill(DataTable)
Dim newRow As DataRow = DataTable.NewRow
With newRow ' the with statement allows you do repeatedly apply a property to a certain object
.Item("StudentID") = txtStudentID.Text ' these statements add the content of the text boxes to these respective fields in the database
.Item("TeacherID") = txtTeacherID.Text
.Item("StudentFirstName") = txtStudentFirstname.Text
.Item("StudentSurname") = txtStudentSurname.Text
.Item("StudentPassword") = txtStudentPassword.Text
.Item("StudentGroup") = cbxStudentGroup.Text
End With
DataTable.Rows.Add(newRow)
Dim Command As New OleDbCommandBuilder(dataAdapter)
dataAdapter.Update(DataTable) 'updates the table
Connection.Close()
ShowItems() ' displays the table
Catch ex As Exception
MessageBox.Show(ex.Message)
Connection.Close()
End Try
End If
End Sub
Here are the three functions used to validate the three critical bits of data.
Function ValidUsernameCheck(ByRef ValidUserName As Boolean, ByVal Username As String) As Boolean
Dim Valid1, Valid2 As Boolean
If Char.IsLetter(Mid(Username, 1, 3)) Then ' takes the first 3 characters of a user name to see if they are
' letters
Valid1 = True
Else
Valid1 = False
End If
If Char.IsNumber(Mid(Username, 4, 8)) Then 'does the same with numbers, starting at char(4) and taking 8.
Valid2 = True
Else
Valid2 = False
End If
If Valid1 = True And Valid2 = True Then
ValidUsernameCheck = True
Else
ValidUsernameCheck = False
End If
Return ValidUsernameCheck
End Function
Function ValidTeacherUsernameCheck(ByRef ValidTeacherUsername As Boolean, ByVal TeacherUsername As String) As Boolean
Dim Valid1, Valid2 As Boolean
If Char.IsLetter(Mid(TeacherUsername, 1, 3)) Then ' takes the first 3 characters of a user name to see if they are
' letters
Valid1 = True
Else
Valid1 = False
End If
If Char.IsNumber(Mid(TeacherUsername, 4, 8)) Then 'does the same with numbers, starting at char(4) and taking 8.
Valid2 = True
Else
Valid2 = False
End If
If Valid1 = True And Valid2 = True Then
ValidTeacherUsernameCheck = True
Else
ValidTeacherUsernameCheck = False
End If
Return ValidTeacherUsernameCheck
End Function
Function ValidPasswordCheck(ByRef ValidPassword As Boolean, ByVal Password As String) As Boolean
If System.Text.RegularExpressions.Regex.Match(Password, "\d").Success Then
ValidPasswordCheck = True
Else
ValidPasswordCheck = False
End If
Return ValidPasswordCheck
End Function
Any help will be appreciated.
Your code appears to be a bit too complicated. You can return from a function at any point with a Return statement - as soon as you detect an input value is incorrect, you can Return False because any further validation checks are usually not needed.
It looks like you have at least some familiarity with regexes, so you could use one to check the usernames as well as the password.
The code appears to be setting credentials for a student, so there is no harm in letting the user know which entry had a problem, if any. Also, it is a good idea to tell the user what format the entry should be in.
You are checking the IDs, not the names - you should name the functions appropriately.
So, your code could look like this:
Private Function IsIdFormatCorrect(ID As String) As Boolean
If String.IsNullOrEmpty(ID) OrElse ID.Length <> 11 Then
Return False
End If
' require name to be exactly (three letters followed by eight digits)
Return Regex.IsMatch(ID, "^[A-Za-z]{3}[0-9]{8}$")
End Function
Private Function IsPasswordFormatCorrect(password As String) As Boolean
If String.IsNullOrEmpty(password) Then
Return False
End If
' require password to be only digits and at least four of them
Return Regex.IsMatch(password, "^[0-9]{4,}$")
End Function
Private Sub bnSave_Click(sender As Object, e As EventArgs) Handles bnSave.Click
Dim errorText As String = ""
If Not IsIdFormatCorrect(txtStudentID.Text) Then
errorText = "Student ID not in correct format (""ABC12345678"")." & vbCrLf
End If
If Not IsIdFormatCorrect(txtTeacherID.Text) Then
errorText &= "Teacher ID not in correct format (""ABC12345678"")." & vbCrLf
End If
If Not IsPasswordFormatCorrect(txtStudentPassword.Text) Then
errorText &= "Student password not in correct format (at least four digits)."
End If
If errorText.Length > 0 Then
MessageBox.Show(errorText, "Data entry problem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
' save to database
End If
End Sub

Adding Group Item in QuickBooks using QBFC

Need a little help here.
I just want to add a Group Item with Item List on it using the QBFC12 but am having a trouble with it. I have tried creating the same method like this with Inventory Assembly and it works well. but this one makes me feel terrible. When the request is processed, it return error telling that there're missing fields on the request. Hope anyone can help me out with this.
Thanks
Here's my code below:
Dim msgSetRequest As IMsgSetRequest
Dim QBSM As New QBSessionManager
Try
With QBSM
.OpenConnection("", "QB Test")
.BeginSession("", ENOpenMode.omDontCare)
End With
Catch ex As Exception
Throw New Exception(ex.Message)
Return False
End Try
msgSetRequest = QBSM.CreateMsgSetRequest("US", 8, 0)
msgSetRequest.Attributes.OnError = ENRqOnError.roeStop
msgSetRequest.ClearRequests()
Dim gAdd As IItemGroupAdd = msgSetRequest.AppendItemGroupAddRq
gAdd.IsActive.SetValue(True)
gAdd.Name.SetValue("Group Name")
gAdd.ItemDesc.SetValue("Group Description")
For Each gListItem As clsInventoryGroupItem In gItem.InventoryGroupItemList
Dim gItemAdd As IItemGroupLine = msgSetRequest.AppendItemGroupAddRq.ItemGroupLineList.Append
gItemAdd.ItemRef.FullName.SetValue(gListItem.ItemRef)
gItemAdd.Quantity.SetValue(gListItem.Quantity)
Next
Dim response As IMsgSetResponse = QBSM.DoRequests(msgSetRequest)
If response.ResponseList.GetAt(0).StatusCode = 0 Then
MessageBox.Show("Success")
else
MessageBox.Show("An Error occurred while inserting Group")
endif
I think the problem is how you are adding your group lines, but haven't tested it yet. Instead of using ItemGroupLineList.Append from the msgSetRequest, you should call it from your IItemGroupAdd object, gAdd. Here's what I came up with, but didn't test it.
Dim msgSetRequest As IMsgSetRequest
Dim QBSM As New QBSessionManager
Try
With QBSM
.OpenConnection("", "QB Test")
.BeginSession("", ENOpenMode.omDontCare)
End With
Catch ex As Exception
Throw New Exception(ex.Message)
Return False
End Try
msgSetRequest = QBSM.CreateMsgSetRequest("US", 8, 0)
msgSetRequest.Attributes.OnError = ENRqOnError.roeStop
msgSetRequest.ClearRequests()
Dim gAdd As IItemGroupAdd = msgSetRequest.AppendItemGroupAddRq
gAdd.IsActive.SetValue(True)
gAdd.Name.SetValue("Group Name")
gAdd.ItemDesc.SetValue("Group Description")
For Each gListItem As clsInventoryGroupItem In gItem.InventoryGroupItemList
Dim gItemAdd As IItemGroupLine = gAdd.ItemGroupLineList.Append
gItemAdd.ItemRef.FullName.SetValue(gListItem.ItemRef)
gItemAdd.Quantity.SetValue(gListItem.Quantity)
Next
Dim response As IMsgSetResponse = QBSM.DoRequests(msgSetRequest)
If response.ResponseList.GetAt(0).StatusCode = 0 Then
MessageBox.Show("Success")
else
MessageBox.Show("An Error occurred while inserting Group")
endif

VB.Net Converting from string to double

I have a bad bug in my program where if a user presses the check(calculate) button when there is no input in the textbox the program displays this error: "Conversion from string "" to type 'Double' is not valid." I would like to resolve this but I am not sure how to do the conversion. I was thinking possibly CType but I am hearing talk of parsing. How do I go about this? the textbox is called mskTxtInput and the button object is called btnCheck which does all the calculation and processing.
Update: This is my code except the parsing method so hope this helps a little!
Private Sub btnCheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheck.Click
pic1.Visible = False 'hide picture
pic1.Image = My.Resources.A
pic2.Image = My.Resources.F
Dim value As Double
If Double.TryParse(mskTxtInput.Text, value) = Then
MsgBox("parsing success") ' parsing worked, so use the value in here
Else
MsgBox("parsing failed") ' parsing failed, so alert the user to that fact
End If
If radAdd.Checked = True Then
totalNum = num1 + num2
End If
If radSub.Checked = True Then
totalNum = num1 - num2
End If
If radMulti.Checked = True Then
totalNum = num1 * num2
End If
If mskTxtInput.Text = totalNum Then
lblAns.Text = ("Correct!")
lblAns2.Text = ("Answer is " & totalNum)
pic1.Visible = True
wins = wins + 1
nScore = wins
Else
lblAns.Text = ("Incorrect")
lblAns2.Text = ("Answer should be " & totalNum)
pic2.Visible = True
End If
attempts = attempts + 1
If attempts = 5 Then
MessageBox.Show("Game Finished! ", "End Of Game", _
MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)
lblAns.Text = ("You scored " & wins & " Out of 5")
btnSpin.Enabled = False
pic1.Visible = False
pic2.Visible = False
lblAns2.Text = ""
lblAns2.Text = "Play again?"
btnCheck.Enabled = False
btnNew.Enabled = True
attempts = 0
wins = 0
End If
mskTxtInput.Clear()
mskTxtInput.Focus()
End Sub
Try using Double.TryParse Method (String, Double) rather
Something like
Dim s As String
Dim result As Double
Dim returnValue As Boolean
returnValue = Double.TryParse(s, result)
Use the TryParse method to do the parsing to avoid getting an exception if the parsing fails:
Dim value As Double
If Double.TryParse(mskTxtInput.Text, value) Then
' parsing worked, so use the value in here
Else
' parsing failed, so alert the user to that fact
End If
dim iVar as integer
dim sStr as string
sstr=""
ivar = val(sstr)
Use the static method Double.TryParse(). If it returns true then parsing was successful, and you can proceed with the operation. If it returns false then parsing was not successful, and you should show an error message (using MessageBox if you desire) and abort the operation.

Enumeration in vb.net

while executing this below lines i got an error. Error:
Collection was modified; enumeration operation may not execute.
Help me to solve this.
Dim i As IEnumerator
Dim item As DataGridItem
Dim bChk As Boolean = False
i = dgOfferStatus.Items.GetEnumerator
For Each item In dgOfferStatus.Items
i.MoveNext()
item = i.Current
item = CType(i.Current, DataGridItem)
Dim chkItemChecked As New CheckBox
chkItemChecked = CType(item.FindControl("chkItemChecked"), CheckBox)
If chkItemChecked.Checked = True Then
Try
bChk = True
lo_ClsInterviewProcess.JobAppID = item.Cells(1).Text
lo_ClsInterviewProcess.candId = item.Cells(9).Text
Dim str, strSchedule1, strSchedule As String
Dim dspath As DataSet
Dim candidateId As Integer
''Moving the resume to Completed folder
ObjInterviewAssessment = New ClsInterviewAssessment
dspath = ObjInterviewAssessment.GetOffComPath(CInt(lo_ClsInterviewProcess.JobAppID), "GetHoldPath")
If dspath.Tables(0).Rows.Count > 0 Then
If Not IsDBNull(dspath.Tables(0).Rows(0).Item(0)) Then
str = dspath.Tables(0).Rows(0).Item(0)
strSchedule1 = str.Replace("Hold", "Completed")
End If
End If
Dim str1 As String
str1 = Server.MapPath(str).Trim
strSchedule = Server.MapPath(strSchedule1).Trim
Dim file1 As File
If file1.Exists(str1) Then
If file1.Exists(strSchedule) Then
file1.Delete(strSchedule)
End If
file1.Move(str1, strSchedule)
End If
''
intResult = lo_ClsInterviewProcess.UpdateApproveStatus(Session("EmployeeId"), strSchedule1)
BindHoldGrid()
If intResult > 0 Then
Alert.UserMsgBox("btnsearch", "Status Updated")
Else
Alert.UserMsgBox("btnsearch", "Status not Updated")
End If
Catch ex As Exception
ExceptionManager.Publish(ex)
Throw (ex)
End Try
End If
Next
If bChk = False Then
Alert.UserMsgBox("btnsearch", "Please Select any Candidate")
End If
'Catch ex As Exception
' ExceptionManager.Publish(ex)
'End Try
End Sub
Look at this part of your code. I think it's what causes your exception.
Dim i As IEnumerator
...
Dim item As DataGridItem
...
i = dgOfferStatus.Items.GetEnumerator
For Each item In dgOfferStatus.Items
i.MoveNext()
item = i.Current ' <-- here be dragons!? '
...
Next
What you're doing seems a little strange. You iterate through the same collection (dgOfferStatus.Items) twice, once with the For Each loop, and once manually using the i iterator. Then you modify items in your collection with item = i.Current. I believe it's this assignment that causes the exception.
(I also don't understand why you would do this. This assignment seems to be completeley superfluous, since i.Current and item should be identical since both iterators are at the same position in the collection.)
The exception basically tries to tell you that you may not modify a collection while you are iterating through it. But you seem to be doing exactly that.