Internal server error (500) httpwebrequest - httpwebrequest

System.Net.WebException: The remote
server returned an error: (500)
Internal Server Error. at
System.Net.HttpWebRequest.GetResponse()
at
refill.btnRequestRefill_Click(Object
sender, EventArgs e)
I get this error when trying to submit a form. Here is my code:
Protected Sub btnRequestRefill_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRequestRefill.Click
Try
Dim url As String = "www.domainname.com"
url += "lastName=" & LastName.Text
url += "&birthDate=" & Birthdate.Text
url += "&RxNumbers=" & RxNumber.Text
url += "&deliveryMethod=" & deliverymethod.SelectedValue
url += "&phone=" & PhoneNumber.Text
url += "&email=" & Email.Text
Dim myrequest As HttpWebRequest = TryCast(WebRequest.Create(url), HttpWebRequest)
Dim docresponse As WebResponse = myrequest.GetResponse()
Dim responsestream As Stream = docresponse.GetResponseStream()
Dim objXMLDoc As New XmlDocument()
Dim colElements As XmlNodeList
Dim colElements2 As XmlNodeList
Dim mywebclient As New WebClient()
Dim a As Object
Dim listingscount As Integer = 0
objXMLDoc.Load(responsestream)
colElements = objXMLDoc.GetElementsByTagName("script")
For Each objnode As XmlNode In colElements
Dim attCol As XmlAttributeCollection = objnode.Attributes
If objnode.Name = "script" Then
If attCol(0).Value = "false" Then
colElements2 = objXMLDoc.GetElementsByTagName("rxResponse")
For Each objnode2 As XmlNode In colElements2
Response.Write("<br/>" & objnode2.InnerText & "<br/>")
Next
Else
Response.Write("<br/>yay it when through<br/>")
Dim redir, mailto, mailfrom, subject, item, body, cc, bcc, message, html, template, usetemplate, testmode
subject = "Refill Submit - test"
usetemplate = False
Dim msg = Server.CreateObject("CDO.Message")
msg.subject = subject
msg.to = "name#domainname.com,name#domainname.com,name#domainname.com"
msg.from = "name#domainname.com"
For Each item In Request.Form
Select Case item
Case "redirect", "mailto", "cc", "bcc", "subject", "message", "template", "html", "testmode", "__EVENTTARGET", "__EVENTARGUMENT", "__VIEWSTATE", "__EVENTVALIDATION", "btnRequestRefill","__LASTFOCUS"
Case Else
If Not usetemplate Then
If item <> "mailfrom" Then body = body & item & ": " & Request.Form(item) & vbCrLf & vbCrLf
Else
body = Replace(body, "[$" & item & "$]", Replace(Request.Form(item), vbCrLf, "<br>"))
End If
End Select
Next
If usetemplate Then 'remove any leftover placeholders
Dim rx As New Regex("\[\$.*\$\]")
body = rx.Replace(body, "")
End If
If usetemplate And LCase(Request.Form("html")) = "yes" Then
msg.htmlbody = body
Else
msg.textbody = body
End If
msg.send()
msg = Nothing
End If
Else
Response.Write("<br/>" & "not script" & "<br/>")
End If
'Response.Write("<br/>" & objnode.Name & ": " & objnode.InnerText & "<br/>")
Next
Catch ex As Exception
Response.Write("<br/>" & ex.ToString & "<br/>")
End Try
End Su

I just wanted to make note that i was taking over this code from another developer. I found from the company that this was suppose to before that there was actually a missing querystring that was required by the service. by just adding url +="querystring=" & value it worked.

Related

TaskCanceledException in Google Drive APIs

it has been some days since I implemented in several PCs my Google Drive upload programme. It is developed in VB.NET console app and I can say it works out pretty good. Except that in some PCs it continues throwing the taskcanceled exception. Basically the programme works at night, where the internet traffic in the pcs should be likely to 0 and it continues trying to upload to a google folder until it succesfully do it OR the time (of an hour usually) runs out.
The Exception looks like this
Ex: System.AggregateException: One or more errors occured. ---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
--- Fine della traccia dello stack dell'eccezione interna ---
in System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
in System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
in System.Threading.Tasks.Task`1.get_Result()
in Google.Apis.Upload.ResumableUpload.Upload() in C:\Apiary\2021-09-08.15-52-39\Src\Support\Google.Apis\Upload\ResumableUpload.cs:riga 388
in TeraDriveServ.Service1.UploadFile(String FilePath) in C:\Sviluppo\TeraDriveServ\Service1.vb:row 291
---> (Internal exception 0) System.Threading.Tasks.TaskCanceledException: A Task was canceled.<---
This is the code I use
Private Sub UploadFile(FilePath As String)
Dim pathDb As String = System.Configuration.ConfigurationManager.AppSettings("DB")
If Service.ApplicationName <> "Google Drive VB Dot Net" Then CreateService()
Dim mail As String = ""
Dim destinatari As String = ""
Dim TheFile As New Google.Apis.Drive.v2.Data.File()
Dim nome As String = Path.GetFileName(FilePath)
Dim infofile As New IO.FileInfo(FilePath)
' I get some data from the file
Dim dataultimaModifica As DateTime = infofile.LastWriteTime
Dim nomefileeffettivo As String = infofile.Name
Dim estensione = Path.GetExtension(FilePath)
'Getting the file folder
Dim folderId As String = System.Configuration.ConfigurationManager.AppSettings("CARTELLADRIVE")
TheFile.Parents = New List(Of ParentReference) From {New ParentReference() With {.Id = folderId}}
TheFile.Title = nome
TheFile.Description = ""
Dim esiste As Boolean = False
' A query to check if the file is uploaded
Using con As System.Data.SQLite.SQLiteConnection = New System.Data.SQLite.SQLiteConnection("data source=" & pathDb & "databaseFile.db3")
Using com As System.Data.SQLite.SQLiteCommand = New System.Data.SQLite.SQLiteCommand(con)
con.Open()
com.CommandText = "Select ID FROM CARICATI WHERE NOME = '" & nome & "' AND DATA='" & dataultimaModifica & "'"
Using reader As System.Data.SQLite.SQLiteDataReader = com.ExecuteReader()
While reader.Read()
esiste = True
End While
con.Close()
End Using
End Using
End Using
If esiste = True Then
' already loaded
Return
Else
Select Case estensione
Case ".bak"
TheFile.MimeType = "application/octet-stream"
Case ".zip"
TheFile.MimeType = "application/zip"
'Case ".jpeg", ".jpg"
' TheFile.MimeType = "image/ jpeg"
'Case ".txt"
' TheFile.MimeType = "text/plain"
'Case ".pdf"
' TheFile.MimeType = "application/pdf"
'Case ".xls"
' TheFile.MimeType = "application/ vnd.ms - excel"
'Case ".doc"
' TheFile.MimeType = "application/msword"
'Case ".docx"
' TheFile.MimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
'Case ".xlsx"
' TheFile.MimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
'Case ".odt"
' TheFile.MimeType = "application/ vnd.oasis.opendocument.text"
Case Else
' I dont like the file extension
Return
End Select
Dim fatto As Integer = 0
' I upload the file details in the DB
Using con As System.Data.SQLite.SQLiteConnection = New System.Data.SQLite.SQLiteConnection("data source=" & pathDb & "databaseFile.db3")
Using com As System.Data.SQLite.SQLiteCommand = New System.Data.SQLite.SQLiteCommand(con)
con.Open()
com.CommandText = "INSERT INTO CARICATI (NOME,DATA) VALUES('" & nome & "','" & dataultimaModifica & "') "
com.ExecuteNonQuery()
fatto = con.LastInsertRowId
' UPLOADED
con.Close()
End Using
End Using
End If
Try
Dim ByteArray As Byte() = System.IO.File.ReadAllBytes(FilePath)
Dim Stream As New System.IO.MemoryStream(ByteArray)
Dim UploadRequest As Google.Apis.Drive.v2.FilesResource.InsertMediaUpload = Service.Files.Insert(TheFile, Stream, TheFile.MimeType)
logger.Debug("Oggetto creato")
' UploadRequest.ContentStream.WriteTimeout = 600000
'If contaUp = 0 Then
' UploadRequest.Service.HttpClient.Timeout = Service.HttpClient.Timeout
'End If
'contaUp = 1
logger.Debug("Starting upload: " & DateTime.Now)
' Here is where the exception points at, the Google Upload() Method
UploadRequest.Upload()
logger.Debug("Upload completed: " & DateTime.Now)
Dim file As File = Nothing
file = UploadRequest.ResponseBody
If file Is Nothing Then
logger.Debug("Upload failed")
' deletes the data from db to try again
AnnulloCaricamento(nome, dataultimaModifica, pathDb)
Else
' I send some stuff to a server
logger.Debug("Cerco di fare POST")
Dim testoSucc As String = System.Configuration.ConfigurationManager.AppSettings("TESTOS")
POST(nomefileeffettivo, dataultimaModifica)
eseguito = True
End If
Catch ex As Exception
' deletes the data from db to try again
AnnulloCaricamento(nome, dataultimaModifica, pathDb) ''05/10/2021
End Try
End Sub
Thanks everyone

Needs to get default program association on remote computers

I am using the below code to get some information on remote computers. Basically, I need to get the OS version (which is working well) and the default program for .pdf files and the default browser. I can get the OS version but the code fails to get the default program association. The Remote Registry is enabled and started but even though I am getting an "access is denied" error message. Any clue guys? Hope you could help me. Thanks
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Const HKEY_LOCAL_MACHINE As String = "80000002"
Const HKEY_current_user1 As String = "80000001"
'Dim remoteRegistryController As New System.ServiceProcess.ServiceController("RemoteRegistry", computerNameTB.Text)
'remoteRegistryController.Start()
Dim osName, pdf, browser As String
Dim options As New ConnectionOptions
options.Impersonation = ImpersonationLevel.Impersonate
options.EnablePrivileges = True
options.Username = "hd_juann"
options.Password = "Diosteamo42="
Dim myScope As New ManagementScope("\\" & computerNameTB.Text & "\root\default", options)
Dim mypath As New ManagementPath("StdRegProv")
Dim mc As New ManagementClass(myScope, mypath, Nothing)
Try
Dim inParams As ManagementBaseObject = mc.GetMethodParameters("GetDWORDValue")
inParams("hDefKey") = UInt32.Parse(HKEY_LOCAL_MACHINE, System.Globalization.NumberStyles.HexNumber) 'RegistryHive.LocalMachine
inParams("sSubKeyName") = "Software\Microsoft\Windows NT\currentVersion"
inParams("sValueName") = "ProductName"
'Dim osName As String
Dim outParams As ManagementBaseObject = mc.InvokeMethod("GetStringValue", inParams, Nothing)
If (outParams("ReturnValue").ToString() = "0") Then
'MessageBox.Show(outParams("sValue").ToString())
osName = outParams("sValue").ToString()
Else
MessageBox.Show("Error retrieving value : " + outParams("ReturnValue").ToString())
End If
'get pdf
Dim inParamsPDF As ManagementBaseObject = mc.GetMethodParameters("GetDWORDValue")
inParamsPDF("hDefKey") = UInt32.Parse(HKEY_current_user1, System.Globalization.NumberStyles.HexNumber) 'RegistryHive.LocalMachine
inParamsPDF("sSubKeyName") = "Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.pdf\UserChoice"
inParamsPDF("sValueName") = "ProgId"
'Dim pdf As String
Dim outParamsPDF As ManagementBaseObject = mc.InvokeMethod("GetStringValue", inParamsPDF, Nothing)
If (outParamsPDF("ReturnValue").ToString() = "0") Then
pdf = outParamsPDF("sValue").ToString()
Else
pdf = "No value Set"
End If
'MessageBox.Show(pdf)
'remoteRegistryController.Stop()
'get browser
Dim inParamsBrowser As ManagementBaseObject = mc.GetMethodParameters("GetDWORDValue")
inParamsBrowser("hDefKey") = UInt32.Parse(HKEY_current_user1, System.Globalization.NumberStyles.HexNumber) 'RegistryHive.LocalMachine
inParamsBrowser("sSubKeyName") = "SOFTWARE\Microsoft\Windows\Shell\Associations\URLAssociations\https\UserChoice"
inParamsBrowser("sValueName") = "ProgId"
'Dim browser As String
Dim outParamsBrowser As ManagementBaseObject = mc.InvokeMethod("GetStringValue", inParamsBrowser, Nothing)
If (outParamsBrowser("ReturnValue").ToString() = "0") Then
browser = outParamsBrowser("sValue").ToString()
Else
browser = "No value Set"
End If
MsgBox(osName & " is installed on computer " & computerNameTB.Text & vbCrLf & "PDF Default App: " & pdf & vbCrLf & "Default Browser: " & browser,, "ComputerInfo W10 Upgrade Project")
Catch err As Exception
If osName <> "" Then
MsgBox(osName & " is installed on computer: " & computerNameTB.Text & ". No default program association information could be accessed " & err.Message,, "ComputerInfo W10 Upgrade Project")
Else
MsgBox("It was no possible to query computer: " & computerNameTB.Text,, "ComputerInfo W10 Upgrade Project")
End If
'MsgBox("It was no possible to query computer: " & computerNameTB.Text,, "ComputerInfo W10 Upgrade Project")
End Try
End Sub
eoor

Downloading files code gets unexpected 404 error

My code downloads files in loop but after the last file downloads it keeps downloading files that aren't there. Website shows redirect and 404 error.
I'm new with visual basic so I'm asking for help here.
My.Computer.Network.DownloadFile(strFullUrlDownload, strFullSavePath, False, 1000)
404 error
redirect
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strMainUrl As String = "http://jixxer.com/123/"
Dim dt As DateTime = DateTime.Now
Dim dtDate As String = dt.ToString("yyyy-MM-dd")
Dim strSlash As String = "/"
Dim strPdf As String = "pdf"
Dim strDot As String = "."
Dim strPage As String = "page"
Dim strPageNbr As String = 1
Dim intCounter As Integer = 1
Dim strPageCounter As String = String.Format("{0:000}", intCounter)
Dim strSavePath As String = "D:\dls\title1\"
Dim strFullSavePath As String = strSavePath & strPageCounter & strDot & strPdf
Dim strFullUrlDownload As String = strMainUrl & dtDate & strSlash & strPdf & strSlash & strPage & strPageNbr & strDot & strPdf
Do Until strPageCounter = 200
' Downloads the resource with the specified URI to a local file.
My.Computer.Network.DownloadFile(strFullUrlDownload, strFullSavePath, False, 1000)
intCounter = intCounter + 1
strPageNbr = strPageNbr + 1
strPageCounter = String.Format("{0:000}", intCounter)
strFullSavePath = strSavePath & strPageCounter & strDot & strPdf
strFullUrlDownload = strMainUrl & dtDate & strSlash & strPdf & strSlash & strPage & strPageNbr & strDot & strPdf
Loop
End Sub
End Class
Try
'TRY to download the file using https first...
My.Computer.Network.DownloadFile(New Uri("https://" & ServerAddress & WebLogoPath & Convert.ToString(RowArray(0)) & ".png"), Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\" & AppDataFolder & PCLogoPath & Convert.ToString(RowArray(0)) & ".png", "", "", False, 500, True)
Catch ex_https As Exception
'Unable to locate file or write file
'If the operation timed out...
If (ex_https.Message = "The operation has timed out") Then
'Re-TRY to download the file using http instead, as a time out error may indicate that HTTPS is not supported.
Try
My.Computer.Network.DownloadFile(New Uri("http://" & ServerAddress & WebLogoPath & Convert.ToString(RowArray(0)) & ".png"), Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\" & AppDataFolder & PCLogoPath & Convert.ToString(RowArray(0)) & ".png", "", "", False, 500, True)
Catch ex_http As Exception
'Most likely, the file doesn't exist on the server. Either way, we cannot obtain the file so we need to perform the same action,
'which is handled outside of this Try block.
End Try
Else
'This is most likely a 404 error. Either way, we cannot obtain the file (and the connection is not timing out) - so
'we need to perform the same action, which is handled outside of this Try block.
End If
End Try
I just put the counter at 200 to test and make sure it works. But I know I need a way to quit on error but not sure how to code it yet. Appreciate any help.
If you don't know how many documents are stored in that remote directory, you have to handle the exception when a page is not found.
It's always possible to receive WebExceptions when a resource is requested from a site, so you should handle this case anyway.
I suggest to use the WebClient class directly instead of Network.DownloadFile(), which may be handy if you want to show a predefined UI of the progress (when it's possible), but using WebClient directly, lets you perform the download asynchrounously if you need it to, using the async/await pattern and the WebClient.DownloadFileTaskAsync() method.
Another suggestion: use a method to download those files, so you can call it from anywhere in your code. You can use a class or a module to store your methods, so you don't clutter your UI and you can also easily reuse these classes or modules in different projects, just including in a project the file that contains them.
Your code could be modified as follow (synchronous version):
You need to pass to the DownloadPdfPages method the remote base address: http://jixxer.com/123, the Path where the files are store (filesPath).
The third and fourth parameters are optional:
- If you don't specify a resourceName, Date.Now.ToString("yyyy-MM-dd") is assumed,
- If you don't specify a startPage, it will default to 1, converted in page1.pdf (the example here asks to start from page 3).
Note: I'm using String Interpolation here: $"page{startPage + pageCount}.pdf".
If your VB.Net version doesn't support it, use String.Format() instead.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim numberOfPages = DownloadPdfPages("http://jixxer.com/123", "D:\dls\title1", "", 3)
If numberOfPages > 0 Then
MessageBox.Show($"Download completed. Number of pages: {numberOfPages}")
Else
MessageBox.Show("Download failed")
End If
End Sub
Private Function DownloadPdfPages(baseAddress As String, filesPath As String, Optional resourceName As String = "", Optional startPage As Integer = 1) As Integer
If String.IsNullOrEmpty(resourceName) Then resourceName = Date.Now.ToString("yyyy-MM-dd")
Dim resourceAddr = Path.Combine(baseAddress, resourceName, "pdf")
Dim pageCount = 0
Dim client = New WebClient()
Try
Do
Dim documentName = $"page{startPage + pageCount}.pdf"
Dim resourceUri = New Uri(Path.Combine(resourceAddr, documentName), UriKind.Absolute)
Dim fileName = Path.Combine(filesPath, documentName)
client.DownloadFile(resourceUri, fileName)
pageCount += 1
Loop
Catch ex As WebException
If ex.Response IsNot Nothing Then
Dim statusCode = DirectCast(ex.Response, HttpWebResponse).StatusCode
If statusCode = HttpStatusCode.NotFound Then
Return pageCount
End If
ElseIf ex.Status = WebExceptionStatus.ProtocolError AndAlso ex.Message.Contains("404") Then
Return pageCount
Else
' Log and/or ...
Throw
End If
Return 0
Finally
client.Dispose()
End Try
End Function
Asynchronous version, using the WebClient.DownloadFileTaskAsync() method.
Just a few changes ae necessary, note the Async keyword added to both the Button.Click handler and the DownloadPdfPagesAsync() method.
The Await keyword is then used to wait for a method to complete, without blocking the UI:
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim numberOfPages = Await DownloadPdfPagesAsync("http://jixxer.com/123", "D:\dls\title1", "", 3)
If numberOfPages > 0 Then
MessageBox.Show($"Download completed. Number of pages: {numberOfPages}")
Else
MessageBox.Show("Download failed")
End If
End Sub
Private Async Function DownloadPdfPagesAsync(baseAddress As String, filesPath As String, Optional resourceName As String = "", Optional startPage As Integer = 1) As Task(Of Integer)
If String.IsNullOrEmpty(resourceName) Then resourceName = Date.Now.ToString("yyyy-MM-dd")
Dim resourceAddr = Path.Combine(baseAddress, resourceName, "pdf")
Dim pageCount = 0
Dim client = New WebClient()
Try
Do
Dim documentName = $"page{startPage + pageCount}.pdf"
Dim resourceUri = New Uri(Path.Combine(resourceAddr, documentName), UriKind.Absolute)
Dim fileName = Path.Combine(filesPath, documentName)
Await client.DownloadFileTaskAsync(resourceUri, fileName)
pageCount += 1
Loop
Catch ex As WebException
If ex.Response IsNot Nothing Then
Dim statusCode = DirectCast(ex.Response, HttpWebResponse).StatusCode
If statusCode = HttpStatusCode.NotFound Then
Return pageCount
End If
ElseIf ex.Status = WebExceptionStatus.ProtocolError AndAlso ex.Message.Contains("404") Then
Return pageCount
Else
' Log and/or ...
Throw
End If
Return 0
Finally
client.Dispose()
End Try
End Function

Visual Basic InputBox closing error

This is a bit of a weird question, and apologies for the vast amount of code the question contains, but, I've been given somebody else's project to maintain, and the user has come to me with an error. There is a button which opens the InputBox, seen below.
The form is used to enter a path of a file to import. If the user enters no path, or an incorrect one, an error is displayed - fine. Now, the problem is, is that if the user presses the 'Cancel' button or the x in the top right to close the form, it also returns the same error, saying that the path cannot be found.
After looking through the following code, I can't work out how to make it so that the error is not displayed when pressing the x or Cancel, so can anybody help me out at all?
Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click
Try
Dim importbox As String = InputBox("Input path", "Import", "")
Dim fi As New FileInfo(importbox)
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName
Dim conn As New OleDbConnection(connectionString)
conn.Open()
Dim add1 As String = ""
Dim add2 As String = ""
Dim add3 As String = ""
Dim add4 As String = ""
Dim add5 As String = ""
Dim postcode As String = ""
Dim telephone As String = ""
Dim fax As String = ""
Dim email As String = ""
Dim customercode As String = ""
Dim customername As String = ""
Dim webpage As String = ""
Dim mobile As String = ""
Dim headerTable As DataTable = ugHeaders.DataSource
Dim csvArray(headerTable.Rows.Count) As String
Dim i As Integer = 0
For Each dr As DataRow In headerTable.Rows
csvArray(i) = dr.Item("CSVName")
Next
For Each dr As DataRow In headerTable.Rows
Select Case dr.Item("DBName").ToString.Trim
Case "Add1"
add1 = dr.Item("CSVName")
Case "Add2"
add2 = dr.Item("CSVName")
Case "Add3"
add3 = dr.Item("CSVName")
Case "Add4"
add4 = dr.Item("CSVName")
Case "Add5"
add5 = dr.Item("CSVName")
Case "PostCode"
postcode = dr.Item("CSVName")
Case "Telephone"
telephone = dr.Item("CSVName")
Case "Fax"
fax = dr.Item("CSVName")
Case "Email"
email = dr.Item("CSVName")
Case "Customer_Name"
customername = dr.Item("CSVName")
Case "Customer_Code"
customercode = dr.Item("CSVName")
Case "webpage"
webpage = dr.Item("CSVName")
Case "mobile_phone"
mobile = dr.Item("CSVName")
End Select
Next
Dim sqlSelect As String = "SELECT Company, [" & add1 & "], [" & add3 & "], [" & postcode & "], [" & add2 & "], " & _
"[" & telephone & "], [" & fax & "], [" & email & "], [" & customercode & "], " & _
"[" & add4 & "], [" & add5 & "], [" & webpage & "], [" & mobile & "] FROM " & fi.Name
Dim cmdSelect As New OleDbCommand(sqlSelect, conn)
Dim adapter1 As New OleDbDataAdapter(cmdSelect)
Dim ds As New DataSet
adapter1.Fill(ds, "DATA")
pb_progress.Maximum = ds.Tables(0).Rows.Count
pb_progress.Value = 0
For Each dr As DataRow In ds.Tables(0).Rows
Try
Debug.WriteLine(dr.Item(customercode).ToString.Trim)
If dr.Item(customercode).ToString.Trim = "" Then
Dim str As String = dr.Item(customername)
If str.Trim = "" Then Continue For
Dim length As Integer = str.Length
If length < 20 Then
Else
length = 20
End If
str = Replace(str.Substring(0, length), " ", "_").ToUpper
str = Regex.Replace(str, "[^a-zA-Z _&]", "")
Dim found As Boolean = True
Dim loopcount As Integer = 1
Do Until found = False
Dim checkSql As String = "SELECT * FROM Customers WHERE [Customer_Code] = #ccode"
Dim checkCmd As New OleDb.OleDbCommand(checkSql, con)
checkCmd.Parameters.AddWithValue("#ccode", str)
Dim checkDa As New OleDb.OleDbDataAdapter(checkCmd)
Dim checkDt As New DataTable
checkDa.Fill(checkDt)
If checkDt.Rows.Count <> 0 Then
found = True
str &= CStr(loopcount)
loopcount += 1
Else
found = False
End If
Loop
dr.Item(customercode) = str
Else
Dim found As Boolean = True
Dim loopcount As Integer = 1
Do Until found = False
Dim checkSql As String = "SELECT * FROM Customers WHERE [Customer_Code] = #ccode"
Dim checkCmd As New OleDb.OleDbCommand(checkSql, con)
checkCmd.Parameters.AddWithValue("#ccode", dr.Item(customercode))
Dim checkDa As New OleDb.OleDbDataAdapter(checkCmd)
Dim checkDt As New DataTable
checkDa.Fill(checkDt)
If checkDt.Rows.Count <> 0 Then
found = True
dr.Item(customercode) &= CStr(loopcount)
loopcount += 1
Else
found = False
End If
Loop
End If
Dim sql As String
sql = "INSERT INTO Customers(Customer_Code, Customer_Name, Contract_Payment_Terms, Aq_Date, Telephone, Fax, Email, Average_Payment_Terms, webpage, mobile_phone) " & _
"VALUES(#ccode, #cname, 30, #01/01/2016#, #ctele, #cfax, #email, 30, #webpage, #mobile);"
Dim cmd As New OleDb.OleDbCommand(sql, con)
With cmd.Parameters
.AddWithValue("#ccode", dr.Item(customercode))
.AddWithValue("#cname", dr.Item(customername))
.AddWithValue("#ctele", dr.Item(telephone).ToString.Truncate(48))
.AddWithValue("#cfax", dr.Item(fax))
.AddWithValue("#email", dr.Item(email))
.AddWithValue("#webpage", dr.Item(webpage))
.AddWithValue("#mobile", dr.Item(mobile))
End With
cmd.ExecuteNonQuery()
sql = "INSERT INTO [Customer_Addresses] (Cust_Code, PostCode, Alias, Add1, Add2, Add3, Add4, Add5) VALUES(#ccode, #pcode, 'Default'" & _
",#add1, #add2, #add3, #add4, #add5);"
cmd = New OleDb.OleDbCommand(sql, con)
With cmd.Parameters
.AddWithValue("#ccode", dr.Item(customercode))
.AddWithValue("#pcdoe", dr.Item(postcode))
.AddWithValue("#add1", dr.Item(add1))
.AddWithValue("#add2", dr.Item(add2))
.AddWithValue("#add3", dr.Item(add3))
.AddWithValue("#add4", dr.Item(add4))
.AddWithValue("#add5", dr.Item(add5))
End With
cmd.ExecuteNonQuery()
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
pb_progress.Increment(1)
Next
MsgBox("Import successful", MsgBoxStyle.OkOnly, "Success")
Catch ex As Exception
errorLog(ex)
End Try
End Sub
Inputbox will always return a String.
If the Users presses "OK" it will return the String put into the TextBox.
If he cancels the box by pressing X or Cancel it returns "".
I would generally not recommend using an Inputbox for getting a filepath. Use an OpenFileDialog instead. If you have the fullpath already in your Clipboard you can just paste it into the Filename-Textboxof the OFD and press enter.
This should get you started:
Dim ofd as new OpenFileDialog()
// Show the File Dialog to the user and detect he pressed OK or Cancelled
if ofd.ShowDialog = Windows.Forms.DialogResult.OK
// Always check, if the file really exists
if IO.File.exists(ofd.FileName)
importbox = ofd.FileName
Else
msgbox("File does not exist")
Exit Sub
End if
Else
Exit Sub
End if

For-loop doesn't complete all iterations

I have problem with this - I try to send broadcast SMS using AT Commands in my system. After that the SMS content will be stored in my database. My store content SMS function works well. I can store all my SMS content that I send, but the send function just sends message to my first data on my datagridview.
Please help me to deal with this - I posted my code below
Private Sub ButtonKirim_Click(sender As Object, e As EventArgs) Handles ButtonKirim.Click
Dim noPel As String
Dim isiPesan As String = ""
Dim tgl As Date = Now.Date
Dim strReplace(2) As String
Dim strIsi(2) As String
Dim tagBulan As String = "<bulan>"
Dim tagtagihan As String = "<tagihan>"
Dim tagLokasi As String = "<lokasi>"
Dim pesanKirim As String = ""
My.Settings.SettingPesan = RichTextBoxPesan.Text
My.Settings.Save()
'Label4.Text = isiPesan
For pelanggan As Integer = 0 To DataGridViewKirimPesan.RowCount - 1
'mengirim pesan/send message
noPel = DataGridViewKirimPesan.Rows(pelanggan).Cells(3).Value()
strReplace(0) = tagBulan
strReplace(1) = tagtagihan
strReplace(2) = tagLokasi
strIsi(0) = DataGridViewKirimPesan.Rows(pelanggan).Cells(4).Value
strIsi(1) = DataGridViewKirimPesan.Rows(pelanggan).Cells(5).Value
strIsi(2) = DataGridViewKirimPesan.Rows(pelanggan).Cells(6).Value
isiPesan = RichTextBoxPesan.Text
For i As Integer = LBound(strReplace) To UBound(strReplace)
isiPesan = isiPesan.Replace(strReplace(i), strIsi(i))
Next
SendMessage(noPel, isiPesan)
''menyimpan pesan keluar ke sms_terkirim/this query store my content SMS to table
Dim sqlSmsKeluar As String = "INSERT INTO sms_terkirim (`tgl_sms`,`id_pelanggan`, `isi_sms`) VALUES ( NOW()," & DataGridViewKirimPesan.Rows(pelanggan).Cells(0).Value & " , '" & isiPesan & "');"
cudMethod(sqlSmsKeluar)
MsgBox(sqlSmsKeluar)
'ProgressBarKirimPesan.Increment(1)
Next
'MsgBox("Pesan Sukses Terkirim")
' Catch ex As Exception
' MsgBox("Pesan Gagal Terkirim" + ex.Message)
'End Try
' End If
End Sub
and this code is AT Command to send message
Public Sub SendMessage(ByVal NomorPelanggan As String, ByVal IsiPesan As String)
If SerialModem.IsOpen() Then
With SerialModem
.Write("AT" & vbCrLf)
Threading.Thread.Sleep(100)
.Write("AT+CMGF=1" & vbCrLf)
Threading.Thread.Sleep(100)
.Write("AT+CMGS=" & Chr(34) & NomorPelanggan & Chr(34) & vbCrLf)
Threading.Thread.Sleep(100)
.Write(IsiPesan & vbCrLf & Chr(26))
Threading.Thread.Sleep(100)
End With
Else
MsgBox("Modem Belum Tersambung")
End If
End Sub