Download a file from web into a specific location in PC - vb.net

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim imageAddress As String = String.Empty
Dim filename As String = String.Empty
Try
Dim fileReader As New WebClient()
Dim proxy As IWebProxy = New WebProxy("proxy adress", port number)
proxy.Credentials = New NetworkCredential("network userid", "network password")
imageAddress = "http://wwwimages.adobe.com/content/dam/Adobe/en/products/acrobat/pdfs/adobe-acrobat-xi-esign-pdf-file-tutorial-ue.pdf"
filename = imageAddress.Substring(imageAddress.LastIndexOf("/") + 1)
If Not (System.IO.File.Exists("D:\" + filename)) Then
fileReader.DownloadFile(imageAddress, "D:\" + filename)
End If
Catch ex As HttpListenerException
MsgBox("Error accessing " + imageAddress + " - " + ex.Message)
Catch ex As Exception
MsgBox("Error accessing " + imageAddress + " - " + ex.Message)
End Try
End Sub
The above code throws an error 407:proxy authentication required. I do not seem to understand the problem with my code. Any help is appreciated.Thanks in advance

Related

Debugging error: "Object reference not set to an instance of an object"

Introduction (Warning: Bad English)
Hello everybody. I need some help with my program.
So, basically my program is made for downloading one file and extracting it to known path, for example C:\Users\ProfileName\Documents\Windward. This path is suitable for most part of people. But for some people it's wrong path (Because file need's to be installed in Documents\Windward folder). So i decided to make changeable path. I thought I making everything right, but something gone wrong. And i thing something is frong with this: Dim path As String = TextBox1.Text & "\Localization.zip", but i don't know how to fix it.
Please help me!
Error:
An unhandled exception of type System.InvalidOperationException occurred in AutoDownloadV2.exe
Additional information: Error in form creating. Exception.InnerException. Error: Object reference not set to an instance of an object.
After Debug I recieve this:
in AutoDownloadV2.My.MyProject.MyForms.Create__Instance__[T](T Instance) in :string 190
in AutoDownloadV2.My.MyApplication.OnCreateMainForm() в B:\Projects\Progs\AutoDownloadV2\AutoDownloadV2\AutoDownloadV2\My Project\Application.Designer.vb:string 35
in Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
in Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
in Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
in AutoDownloadV2.My.MyApplication.Main(String[] Args) in :string 81 The program '[5452] AutoDownloadV2.exe' has exited with code 0 (0x0).
Here is my code (I have removed the useless part of code.)
Public Class Form1
Public WithEvents download As WebClient
Dim path As String = TextBox1.Text & "\Localization.zip"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "C:\Users\" & SystemInformation.UserName & "\Documents\Windward"
ProgressBar1.Value = 0
CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Try
Try
My.Computer.FileSystem.DeleteFile(path)
Catch ex As Exception
End Try
download = New WebClient
download.DownloadFileAsync(New Uri("http://http://exsite.example"), path)
Catch ex As Exception
MsgBox("Error! " & ex.Message)
End Try
End Sub
Private Sub download_DownloadProgressChanged(ByVal sender As System.Object, ByVal e As System.Net.DownloadProgressChangedEventArgs) Handles download.DownloadProgressChanged
Try
Label3.Text = "Downloaded : " & e.BytesReceived / 1024 & " kb / " & e.TotalBytesToReceive / 1024 & " kb "
Label4.Text = ProgressBar1.Value & "%"
ProgressBar1.Value = e.ProgressPercentage
Catch ex As Exception
MsgBox("Error! " & ex.Message)
End Try
If e.BytesReceived = e.TotalBytesToReceive Then
Unzip()
End If
End Sub
Public Sub Unzip()
Dim startPath As String = path
Dim zipPath As String = path
Dim extractPath As String = ("C:\Users\" + SystemInformation.UserName + "\Documents\Windward\")
If My.Computer.FileSystem.FileExists(extractPath + "mods\translateMod\Localization.txt") Then
My.Computer.FileSystem.DeleteFile(extractPath + "mods\translateMod\Localization.txt")
Try
My.Computer.FileSystem.DeleteFile(extractPath + "mods\translateMod\Version.txt")
Catch e As Exception
End Try
ZipFile.ExtractToDirectory(zipPath, extractPath)
My.Computer.FileSystem.DeleteFile(path)
Else
ZipFile.ExtractToDirectory(zipPath, extractPath)
My.Computer.FileSystem.DeleteFile(path)
End If
End Sub
End Class
Move the initialization of path inside the Form1_Load after setting the initial value in TextBox1
Dim path As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "C:\Users\" & SystemInformation.UserName & "\Documents\Windward"
path = TextBox1.Text & "\Localization.zip"
ProgressBar1.Value = 0
CheckForIllegalCrossThreadCalls = False
End Sub
The problem is caused by the reference to TextBox1 in the global area of your form class. At that point the TextBox1 is still Nothing (not initialized) thus you get the NRE message (Null Reference Exception)

How to save Received Messages From Gsm Modem to your Mysql Database?

I am trying to save received sms from my modem to MySQL database, and I am using MySQL Workbench for my database.
Here's my functionalities:
1. Auto detect modem
2. Connect modem
3. Send Messages
4. Read Messages
5. Handles (SerialPort Data received)
Here's the Code:1. Auto Detect Modem
'Some Imports
Imports System.Management
Imports System.Threading
Imports System.Text.RegularExpressions
Imports MySql.Data.MySqlClient
Public Class Form1
Dim result() As String
Dim query As String
Dim rcvdata As String = ""
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim ports() As String
ports = Split(ModemsConnected(), "***")
For i As Integer = 0 To ports.Length - 2
ComboBox1.Items.Add(ports(i))
Next
End Sub
Public Function ModemsConnected() As String
Dim modems As String = ""
Try
Dim searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_POTSModem")
For Each queryObj As ManagementObject In searcher.Get()
If queryObj("Status") = "OK" Then
modems = modems & (queryObj("AttachedTo") & " - " & queryObj("Description") & "***")
End If
Next
Catch err As ManagementException
MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
Return ""
End Try
Return modems
End Function
'Show Detected or Available modem
Private Sub ComboBox1_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedValueChanged
Label1.Text = Trim(Mid(ComboBox1.Text, 1, 5))
End Sub
2. Connect/Disconnect Modem
'button connect
Private Sub btnConnect_Click(sender As System.Object, e As System.EventArgs) Handles btnConnect.Click
Try
With SerialPort1
.PortName = Label1.Text
.BaudRate = 9600
.Parity = IO.Ports.Parity.None
.DataBits = 8
.StopBits = IO.Ports.StopBits.One
.Handshake = IO.Ports.Handshake.None
.RtsEnable = True
.ReceivedBytesThreshold = 1
.NewLine = vbCr
.ReadTimeout = 1000
.Open()
End With
If SerialPort1.IsOpen Then
Label3.Visible = True
btnDisconnect.Visible = True
Label3.Text = "Connected - Port " & Label1.Text & " is used"
Else
Label3.Text = "Got some Error, Check your connection with your Modem."
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Text Messaging")
End Try
End Sub
'button Disconnect
Private Sub btnDisconnect_Click(sender As System.Object, e As System.EventArgs) Handles btnDisconnect.Click
Try
If SerialPort1.IsOpen Then
With SerialPort1
.Close()
.Dispose()
Label1.Visible = False
Label3.Visible = False
btnDisconnect.Visible = False
ListView1.Items.Clear()
End With
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
3. Send Messages
Private Sub btnSend_Click(sender As System.Object, e As System.EventArgs) Handles btnSend.Click
Dim query As String
Try
Connection()
query = "INSERT INTO thesis.tblsentitems (PhoneNumber, message) VALUES('" & txtNumber.Text & "', '" & txtMessage.Text & "')"
sqlcmd = New MySqlCommand(query, conn)
sqlreader = sqlcmd.ExecuteReader
With SerialPort1
.Write("at" & vbCrLf)
Threading.Thread.Sleep(200)
.Write("at+cmgf=1" & vbCrLf)
Threading.Thread.Sleep(200)
.Write("at+cmgs=" & Chr(34) & txtNumber.Text & Chr(34) & vbCrLf)
.Write(txtMessage.Text & Chr(26))
Threading.Thread.Sleep(200)
End With
If rcvdata.ToString.Contains(">") Then
MsgBox("Message Succesfully Sent")
conn.Close()
Else
MsgBox("Got some error!")
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Text Messaging")
End Try
End Sub
4. Read Messages
Private Sub btnReadsms_Click(sender As System.Object, e As System.EventArgs) Handles btnReadsms.Click
Try
With SerialPort1
.Write("AT" & vbCrLf)
Threading.Thread.Sleep(1000)
.Write("AT+CMGF=1" & vbCrLf)
Threading.Thread.Sleep(1000)
.Write("AT+CPMS=""SM""" & vbCrLf)
Threading.Thread.Sleep(1000)
.Write("AT+CMGL=""ALL""" & vbCrLf)
Threading.Thread.Sleep(1000)
'MsgBox(rcvdata.ToString)
readmsg()
End With
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
'Save Received message to ListView1
Private Sub readmsg()
Try
Dim lineoftext As String
Dim i As Integer
Dim arytextfile() As String
lineoftext = rcvdata.ToString
arytextfile = Split(lineoftext, "+CMGL", , CompareMethod.Text)
For i = 1 To UBound(arytextfile)
Dim input As String = arytextfile(i)
Dim pattern As String = "(:)|(,"")|("","")"
result = Regex.Split(input, pattern)
Dim concat() As String
With ListView1.Items.Add("null")
'for index
.SubItems.AddRange(New String() {result(2).ToString})
'for status
.SubItems.AddRange(New String() {result(4).ToString})
'for number
Dim my_string, position As String
my_string = result(6)
position = my_string.Length - 2
my_string = my_string.Remove(position, 2)
.SubItems.Add(my_string)
'for date and time
concat = New String() {result(8)}
.SubItems.AddRange(concat)
'for message
Dim lineoftexts As String
Dim arytextfiles() As String
lineoftexts = arytextfile(i)
arytextfiles = Split(lineoftexts, "+32", , CompareMethod.Text)
.SubItems.Add(arytextfiles(1))
End With
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
5. Handles (SerialPort Data received)
Private Sub SerialPort1_datareceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim datain As String = ""
Dim numbytes As Integer = SerialPort1.BytesToRead
For i As Integer = 1 To numbytes
datain &= Chr(SerialPort1.ReadChar)
Next
test(datain)
End Sub
Private Sub test(ByVal indata As String)
rcvdata &= indata
End Sub
Hope someone can Help, please... :/

SQL Troubleshooting in VB.Net

Alright, here is my issue.
Working on a Inventory Control program, and got it mostly done, when a wild bug appears.
The system will check out a item, but will not check it back in, even though it throws all the proper messages that it does check the item in.
What's worse, is that the SQL statement is encapsulated in a try-catch class and acts as if nothing is wrong, and does not throw an exception.
And this is just a functional build, not a streamlined one, so it looks a little rough.
The statement in question is:
Dim OleCheckIn As New OleDbCommand("UPDATE Assets SET [Checked Out]='Checked In' WHERE [ID Number]=" + sBarcode + "", OleDbConn)
I am sure it is something very very obvious, but I have been rebuilding and staring at it for so long, I am likely glossing over a glaring hole in it.
Option Strict On
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Public EmpIDFlag As Boolean
Public ItemBCode As Boolean
Public CheckFlag As Boolean
Public dEmpID As Double
Public sEmpID As String
Public dbEmpID As Double
Public dBarcode As Double
Public sBarcode As String
Public sFirstName As String
Public sLastName As String
Public sFullName As String
Public sItem As String
Public sCheckedOut As String
Public sCheckedOutBy As String
Public OleDbConn As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\rcassel\Documents\Visual Studio 2012\Projects\Inventory Control\Inventory Control\Inventory Control2.accdb;")
Private Sub TextBox1_LostFocus(sender As Object, e As EventArgs) Handles TextBox1.LostFocus
dEmpID = (Val(TextBox1.Text))
'Checks to see if someone entered a Badge
If dEmpID = Nothing Then
MsgBox("You must scan your Badge!", MsgBoxStyle.OkOnly)
TextBox1.Focus()
Else
sEmpID = dEmpID.ToString
'Fire Query into Database
Try
OleDbConn.Open()
Dim OleEmp As New OleDbCommand("SELECT [First Name],[Last Name],[Employee ID] FROM Contacts WHERE [Employee ID]=" + sEmpID + "", OleDbConn)
Dim r1 As OleDbDataReader = OleEmp.ExecuteReader()
While r1.Read()
sFirstName = CStr(r1("First Name"))
sLastName = CStr(r1("Last Name"))
dbEmpID = CInt(r1("Employee ID"))
End While
r1.Close()
Catch ex As Exception
'MsgBox("Cannot Pull Data." & vbCrLf & ex.Message)
End Try
If dbEmpID = Nothing Then
MsgBox("You are not Authorised to use this device. This activity has been logged.", MsgBoxStyle.OkOnly)
Else
Me.ListBox1.Items.Add(sFirstName)
Me.ListBox1.Items.Add(sLastName)
Me.ListBox1.Items.Add(sEmpID)
TextBox2.Focus()
End If
OleDbConn.Close()
End If
End Sub
'Item Barcode
'Private Sub TextBox2_LostFocus(sender As Object, e As EventArgs) Handles TextBox2.LostFocus
Private Sub Textbox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
dBarcode = (Val(TextBox2.Text))
If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Enter) Then
sBarcode = dBarcode.ToString()
OleDbConn.Open()
Try
Dim OleItem As New OleDbCommand("SELECT [Item],[Checked Out],[Checked out Last by] FROM Assets WHERE [ID Number]=" + sBarcode + "", OleDbConn)
Dim r2 As OleDbDataReader = OleItem.ExecuteReader()
While r2.Read()
sItem = CStr(r2("Item"))
sCheckedOut = CStr(r2("Checked Out"))
sCheckedOutBy = CStr(r2("Checked out Last by"))
End While
ItemBCode = True
'Set Checkout Flag, this will be called later by the Check In/Check Out button
If sCheckedOut = "Checked Out" Then
CheckFlag = True
End If
r2.Close()
Catch ex As Exception
MsgBox("Barcode Invalid." & vbCrLf & ex.Message)
ItemBCode = False
End Try
If ItemBCode = True Then
Me.ListBox2.Items.Add(sItem)
Me.ListBox2.Items.Add(sCheckedOut)
Me.ListBox2.Items.Add(sCheckedOutBy)
End If
OleDbConn.Close()
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Focus()
End Sub
'This is the "Check In" button
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If ItemBCode = False Then
MsgBox("You must have a Valid Item Barcode!", MsgBoxStyle.OkOnly)
TextBox2.Focus()
Else
If CheckFlag Then
Try
OleDbConn.Open()
Dim OleCheckIn As New OleDbCommand("UPDATE Assets SET [Checked Out]='Checked In' WHERE [ID Number]=" + sBarcode + "", OleDbConn)
MsgBox("This Item has been Checked in!", MsgBoxStyle.OkOnly)
Catch ex As Exception
MsgBox("Barcode Invalid." & vbCrLf & ex.Message)
ItemBCode = False
End Try
Else
MsgBox("This Item is already Checked in!", MsgBoxStyle.OkOnly)
TextBox2.Focus()
End If
End If
OleDbConn.Close()
End Sub
'This is the "Check Out" button
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
If ItemBCode = False Then
MsgBox("You must have a Valid Item Barcode!", MsgBoxStyle.OkOnly)
TextBox2.Focus()
Else
If CheckFlag = False Then
Try
sFullName = String.Format("{0} {1}", sFirstName, sLastName)
OleDbConn.Open()
Dim OleCheckOut As New OleDbCommand("UPDATE Assets SET [Checked Out]='Checked Out',[Checked out Last by] ='" + sFullName + "' WHERE [ID Number]=" + sBarcode + "", OleDbConn)
MsgBox("This Item has been Checked Out!", MsgBoxStyle.OkOnly)
Catch ex As Exception
MsgBox("Barcode Invalid." & vbCrLf & ex.Message)
ItemBCode = False
End Try
Else
MsgBox("This Item is already Checked Out!", MsgBoxStyle.OkOnly)
TextBox2.Focus()
End If
End If
OleDbConn.Close()
End Sub
End Class
You never execute your update commands:
OleCheckIn.ExecuteNonQuery()
OleCheckOut.ExecuteNonQuery()
Also, use parameters. You are exposing your system to SQL injection.

Saving an Image in VB.NET

I have a little code for saving an image from an URL in VB.NET but im not finding the location where it saves the image, i added a location string but i dont know how to use it in the code.
How do i change the location whre my code saves the image ( Imports System.Drawing
Public Class Form1)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MyImage As System.Drawing.Image
Dim URL As String = TextBox1.Text
Dim FileName As String, URLpieces As String()
Dim location As String = "C:/SaveIMGURL/"
URLpieces = Split(URL, "/")
FileName = URLpieces.GetValue(UBound(URLpieces))
MyImage = GetImage(URL)
MyImage.Save(FileName)
MyImage = Nothing
End Sub
Function GetImage(ByVal URL As String) As System.Drawing.Image
Dim Request As System.Net.HttpWebRequest
Dim Response As System.Net.HttpWebResponse
Request = System.Net.WebRequest.Create(URL)
Response = CType(Request.GetResponse, System.Net.WebResponse)
If Request.HaveResponse Then
If Response.StatusCode = Net.HttpStatusCode.OK Then
GetImage = System.Drawing.Image.FromStream(Response.GetResponseStream)
End If
End If
Try
Catch e As System.Net.WebException
MsgBox("A web exception has occured [" & URL & "]." & vbCrLf & " System returned: " & e.Message, MsgBoxStyle.Exclamation, "Error!")
Exit Try
Catch e As System.Net.ProtocolViolationException
MsgBox("A protocol violation has occured [" & URL & "]." & vbCrLf & " System returned: " & e.Message, MsgBoxStyle.Exclamation, "Error!")
Exit Try
Catch e As System.Net.Sockets.SocketException
MsgBox("Socket error [" & URL & "]." & vbCrLf & " System returned: " & e.Message, MsgBoxStyle.Exclamation, "Error!")
Exit Try
Catch e As System.IO.EndOfStreamException
MsgBox("An IO stream exception has occured. System returned: " & e.Message, MsgBoxStyle.Exclamation, "Error!")
Exit Try
Finally
End Try
End Function
End Class

Clearing text boxes

I compiled the following little application only I want all the textpoxes cleard when the tabs areswitched by the user how can this be achieved?
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim FILE_NAME As String = "C:\test.pgp"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine((TextBox2.Text) + "," + " " + "*" + (TextBox1.Text))
objWriter.Close()
MsgBox("The acad.pgp file was successfully appended…")
Else
MsgBox("File missing reinstall or contact vendor…")
End If
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim FILE_NAME As String = "C:\test.pgp"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine((TextBox3.Text) + "," + " " + "START " + (TextBox4.Text) + ", 1,,")
objWriter.Close()
MsgBox("The acad.pgp file was successfully appended…")
Else
MsgBox("File missing reinstall or contact vendor…")
End If
End Sub
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
Dim FILE_NAME As String = "C:\test.pgp"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine((TextBox5.Text) + "," + " " + "START " + (TextBox6.Text) + ", 1,,")
objWriter.Close()
MsgBox("The acad.pgp file was successfully appended…")
Else
MsgBox("File missing reinstall or contact vendor…")
End If
End Class
Public Sub ClearTextBoxes(frmClearMe As Form)
Dim txt As Control
For Each txt In frmClearMe
If TypeOf txt Is TextBox Then txt.Text = ""
Next
End Sub