VB won't show PDF Reader - vb.net

I use the following Code to Open a PDF File:
Public Sub Execute_Doc(afilename As String, Optional style As ProcessWindowStyle = ProcessWindowStyle.Minimized)
Dim myProcess As New Process
Const ERROR_FILE_NOT_FOUND As Integer = 2
Const ERROR_ACCESS_DENIED As Integer = 5
Try
myProcess.StartInfo.FileName = afilename
myProcess.StartInfo.WindowStyle = style
myProcess.Start()
Catch e As System.ComponentModel.Win32Exception
If e.NativeErrorCode = ERROR_FILE_NOT_FOUND Then
Console.WriteLine(e.Message + ". Check the path.")
MsgBox("File<" + afilename + "> not found!")
Else
If e.NativeErrorCode = ERROR_ACCESS_DENIED Then
Console.WriteLine(e.Message + ". You do not have permission to print this file.")
MsgBox("File <" + afilename + "> couldn't be opened!")
End If
End If
MsgBox(e.ToString())
Catch ex As Exception
MsgBox(e.ToString())
Finally
myProcess.Kill()
myProcess.Dispose()
End Try
End Sub
I call Execute_Doc("C:\ProgrammName\Test.pdf", ProcessWindowStyle.Normal) but the Adobe Reader won't show up. I can see it in the Task Manager.
Well it works if I start Adobe Reader first without any files by clicking the default Icon on my Desktop. It also works with the integrated PDF Reader from Windows 8.1. I can't debug this isse on my Windows 7 / VS 2013 Computer. The problem only exists on ONE! client computer.
Any tipps how to solve this?

Public Sub Execute_Doc(afilename As String, Optional style As ProcessWindowStyle = ProcessWindowStyle.Minimized)
Dim myProcess As New Process
Const ERROR_FILE_NOT_FOUND As Integer = 2
Const ERROR_ACCESS_DENIED As Integer = 5
Try
myProcess.StartInfo.FileName = "AcroRd32.exe " & afilename
myProcess.StartInfo.WindowStyle = style
myProcess.Start()
Catch e As System.ComponentModel.Win32Exception
If e.NativeErrorCode = ERROR_FILE_NOT_FOUND Then
Console.WriteLine(e.Message + ". Check the path.")
MsgBox("File<" + afilename + "> not found!")
Else
If e.NativeErrorCode = ERROR_ACCESS_DENIED Then
Console.WriteLine(e.Message + ". You do not have permission to print this file.")
MsgBox("File <" + afilename + "> couldn't be opened!")
End If
End If
MsgBox(e.ToString())
Catch ex As Exception
MsgBox(e.ToString())
Finally
myProcess.Kill()
myProcess.Dispose()
End Try
End Sub

Just use Shell Execute it is provided by the Win API so you do not have to worry about what program is installed to handle the extension. Windows does the work for you.
Private Function ShellExecute(ByVal File As String) As Boolean
Dim myProcess As New Process
myProcess.StartInfo.FileName = File
myProcess.StartInfo.UseShellExecute = True
myProcess.StartInfo.RedirectStandardOutput = False
myProcess.Start()
myProcess.Dispose()
End Function

Related

Close a MSI file handle after being downloaded from a website

I have a vsto add-in for outlook. There is a code where I download a MSI file from a website:
Public Sub DownloadMsiFile()
Try
Dim url As String = "https://www.website.com/ol.msi"
Dim wc As New WebClient()
wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;")
If File.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi") Then
System.IO.File.Delete(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi")
End If
wc.DownloadFile(url, My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi")
wc.Dispose()
Catch ex As Exception
MessageBox.Show("File couldn't be downloaded: " & ex.Message)
End Try
End Sub
And then I get the MSI version using the following function:
Function GetMsiVersion() As String
Try
Dim oInstaller As WindowsInstaller.Installer
Dim oDb As WindowsInstaller.Database
Dim oView As WindowsInstaller.View
Dim oRecord As WindowsInstaller.Record
Dim sSQL As String
oInstaller = CType(CreateObject("WindowsInstaller.Installer"), WindowsInstaller.Installer)
DownloadMsiFile()
If File.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi") Then
oDb = oInstaller.OpenDatabase(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi", 0)
sSQL = "SELECT `Value` FROM `Property` WHERE `Property`='ProductVersion'"
oView = oDb.OpenView(sSQL)
oView.Execute()
oRecord = oView.Fetch
Return oRecord.StringData(1).ToString()
Else
Return Nothing
End If
Catch ex As Exception
MessageBox.Show("File couldn't be accessed: " & ex.Message)
End Try
End Function
And then I do the comparison with the current dll version to see if there is a need to download a newer version or not:
Public Sub CheckOLUpdates()
Dim remoteVersion As String = GetMsiVersion()
Dim installedVersion As String = Assembly.GetExecutingAssembly().GetName().Version.ToString
If Not String.IsNullOrEmpty(remoteVersion) Then
Try
If String.Compare(installedVersion, remoteVersion) < 0 Then
Dim Result As DialogResult = MessageBox.Show("A newer version is available for download, do you want to download it now?", "OL", System.Windows.Forms.MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
If Result = 1 Then
System.Diagnostics.Process.Start("http://www.website.com/update")
Else
Exit Sub
End If
Else
MessageBox.Show("You have the latest version installed!", "OL", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Catch ex As Exception
End Try
End If
End Sub
This works pretty well if this ran once. However if I try again to check for update, I would get the following error which happens while trying to delete the file in DownloadMsiFile() :
The process cannot access the file %temp%\ol.msi because it is being used by another process
If I use the sysinternals handle.exe utility to check the handles on this file I get the outlook process having a handle lock on this file:
handle.exe %temp%\ol.msi
Nthandle v4.30 - Handle viewer
Copyright (C) 1997-2021 Mark Russinovich
Sysinternals - www.sysinternals.com
OUTLOOK.EXE pid: 25964 type: File 4FC8: %temp%\ol.msi
I was wondering how can I close the handle to avoid this error? Any help is really appreciated
So here is what I have to do to close the handle. I have added the following lines after opening the MSI file:
Marshal.FinalReleaseComObject(oRecord)
oView.Close()
Marshal.FinalReleaseComObject(oView)
Marshal.FinalReleaseComObject(oDb)
oRecord = Nothing
oView = Nothing
oDb = Nothing
So my final code looked like the following:
Function GetMsiVersion() As String
Try
Dim oInstaller As WindowsInstaller.Installer
Dim oDb As WindowsInstaller.Database
Dim oView As WindowsInstaller.View
Dim oRecord As WindowsInstaller.Record
Dim sSQL As String
Dim Version As String
oInstaller = CType(CreateObject("WindowsInstaller.Installer"), WindowsInstaller.Installer)
DownloadMsiFile()
If File.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi") Then
oDb = oInstaller.OpenDatabase(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi", 0)
sSQL = "SELECT `Value` FROM `Property` WHERE `Property`='ProductVersion'"
oView = oDb.OpenView(sSQL)
oView.Execute()
oRecord = oView.Fetch
Version = oRecord.StringData(1).ToString()
Marshal.FinalReleaseComObject(oRecord)
oView.Close()
Marshal.FinalReleaseComObject(oView)
Marshal.FinalReleaseComObject(oDb)
oRecord = Nothing
oView = Nothing
oDb = Nothing
Else
Version = Nothing
End If
Return Version
Catch ex As Exception
MessageBox.Show("File couldn't be accessed: " & ex.Message)
End Try
End Function

Screen capture code runs OK in WinForms but not as a service

I want to create a Windows service to screen capture but it's not working.
The process reaches the ScrenCapture.Start() but it does not do anything and does not throw an error.
If I test it in a Windows form the same code works well:
Code:
Imports Microsoft.Expression.Encoder.ScreenCapture
Imports isc.isc_utility
Public Class isc_utility_screen_capture
Dim ScrenCapture As ScreenCaptureJob = New ScreenCaptureJob()
Shared SrvDir As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.Location())
Function StartRecording(ByVal FileName As String)
Dim Dir = SrvDir
Dim FileToRecord As String
FileToRecord = Dir + "\" + FileName + ".wmv"
Try
ScrenCapture.OutputScreenCaptureFileName = FileToRecord
ScrenCapture.CaptureMouseCursor = True
ScrenCapture.Start()
WriteEventLogInformation("Capturing Video.... " + FileName + " " + Date.Now)
Return FileName
Catch ex As Exception
WriteEventLogError(ex.Message)
Return "-1"
End Try
End Function
Function StopRecording()
Try
ScrenCapture.Stop()
Return 1
Catch ex As Exception
WriteEventLogError(ex.Message)
Return -1
End Try
End Function
End Class
What could be happening?

Process.Start() with "manage-bde.exe" crashing in VB.NET

I'm trying to start manage-bde.exe as a new process in VB.net but when it tries to start the proc, Bitlocker crashes. Could anyone please tell me what I'm doing wrong here? This code was converted from C# where it works all day long....
Code:
Private Sub btnLock_Click(sender As Object, e As EventArgs) Handles btnLock.Click
Dim drvSelected As String = cmbDriveSelect.SelectedValue.ToString()
Dim sysDirWithBDE As String = Environment.SystemDirectory + "\manage-bde.exe"
Dim lockStatus As String = String.Empty
' This is the code for the base process
Dim myProcess As New Process()
' Start a new instance of this program
Dim myProcessStartInfo As New ProcessStartInfo(sysDirWithBDE, " -lock " + drvSelected.Remove(2))
'Set Use Shell to false so as to redirect process run info to application
myProcessStartInfo.UseShellExecute = False
myProcessStartInfo.RedirectStandardOutput = True
myProcess.StartInfo = myProcessStartInfo
Try
myProcess.Start()
lblDriveLockMsg.Show()
Catch err As Exception
lblDriveLockMsg.Text = err.Message
End Try
'Read the standard output of the process.
lockStatus = myProcess.StandardOutput.ReadToEnd()
If lockStatus.Contains("code 0x80070057") Then
lblDriveLockMsg.Text = "Drive selected is not Bit Locker encrypted"
ElseIf lockStatus.Contains("code 0x80070005") Then
lblDriveLockMsg.Text = "Drive selected is in use by an application on your machine, force dismounting might result in data loss, please check and close any applications using the drive"
Else
lblDriveLockMsg.Text = lockStatus
End If
myProcess.WaitForExit()
myProcess.Close()
End Sub

FTP Client uploads only 0KB files

I am having a small problem with my FTP client.
Choosing a file works, renaming that file with 4 variables works.
It's the upload that is causing me trouble.
Whenever a file is uploaded to the FTP server it says it is 0KB.
I am thinking of 2 possible problems:
Visual studio tells me that the variable file is used before it has been assigned a value, to make sure it isn't null i did the following.
Dim file As Byte()
If (Not file Is Nothing) Then
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
FileSystem.Rename(Filename, originalFile)
End If
This Takes care of any possible Errors.
The second one is fName, same warning as with file, and I took care of it the same way.
another possibility is that my code just takes the 4 variables and makes that into a file and uploads it, hence the 0KB size....
Here's my code:
Dim Filename As String
Dim originalFile As String
Private Function enumerateCheckboxes(ByVal path As String)
originalFile = path
Dim fName As String
For Each Control In Me.Controls
If (TypeOf Control Is ComboBox AndAlso DirectCast(Control, ComboBox).SelectedIndex > -1) Then
fName += CStr(Control.SelectedItem.Key) + "_"
End If
Next
Try
fName = path + fName.Substring(0, fName.Length - 1) + ".jpg"
Catch ex As Exception
MsgBox(ex.Message)
MsgBox("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
Return fName
End Function
Public Function OpenDialog()
Dim FD As OpenFileDialog = New OpenFileDialog()
FD.Title = "Selecteer een bestand"
FD.InitialDirectory = "C:\"
FD.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
FD.FilterIndex = 2
FD.RestoreDirectory = True
If FD.ShowDialog() = DialogResult.OK Then
Dim Filename As String = FD.FileName
Filename = StrReverse(Filename)
Filename = Mid(Filename, InStr(Filename, "\"), Len(Filename))
Filename = StrReverse(Filename)
MsgBox(enumerateCheckboxes(Filename))
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ip" & enumerateCheckboxes(Filename)), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("username", "password")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte
Try
Filename = OpenDialog()
If (Not Filename Is Nothing) Then
System.IO.File.ReadAllBytes(Filename)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
If (Not Filename Is Nothing) Then
FileSystem.Rename(originalFile, Filename)
End If
Dim strz As System.IO.Stream = request.GetRequestStream()
If (Not file Is Nothing) Then
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
FileSystem.Rename(Filename, originalFile)
End If
End Sub
End Class
I have looked at multiple threads with the same problem as me.
Threads like this
But i dont believe this applies to my problem.
If you would be so kind to explain what i did wrong and how i can fix and avoid this in the future, my debugging is still a bit rough...
Thank you in advance!
Visual Studio is giving you that warning because you never assign anything to the file array. I think that on the line where you have:
System.IO.File.ReadAllBytes(Filename)
You really meant to have:
file = System.IO.File.ReadAllBytes(Filename)

Download Direct links

My program has been using:
Dim DLLink1 As String
DLLink1 = Trim(TextBox2.Text)
Dim DownloadDirectory1 As String
DownloadDirectory1 = Trim(TextBox4.Text)
Try
Button3.Enabled = False
' My.Computer.Network.DownloadFile(DLLink1, (DownloadDirectory1 + "/UpdatedClient.zip"))
Dim HttpReq As HttpWebRequest = DirectCast(WebRequest.Create(DLLink1), HttpWebRequest)
Using HttpResponse As HttpWebResponse = DirectCast(HttpReq.GetResponse(), HttpWebResponse)
Using Reader As New BinaryReader(HttpResponse.GetResponseStream())
Dim RdByte As Byte() = Reader.ReadBytes(1 * 1024 * 1024 * 10)
Using FStream As New FileStream(DownloadDirectory1 + "/UpdatedClient.zip", FileMode.Create)
FStream.Write(RdByte, 0, RdByte.Length)
End Using
End Using
End Using
Finally
MsgBox("Finished Download.")
Button3.Enabled = True
Label4.Visible = True
I tried this previously, and it didn't work at all:
My.Computer.Network.DownloadFile(DLLink1, (DownloadDirectory1 + "/UpdatedClient.zip"))
The website requires you to be logged in, so I made a spare account for the program:
WebBrowser1.Navigate("http://www.mpgh.net/forum/admincp/")
Timer1.Start()
Button2.Enabled = False
Then
WebBrowser1.Document.GetElementById("vb_login_username").SetAttribute("value", "AutoUpdaterAccount")
WebBrowser1.Document.GetElementById("vb_login_password").SetAttribute("value", "password")
Dim allelements As HtmlElementCollection = WebBrowser1.Document.All
For Each webpageelement As HtmlElement In allelements
If webpageelement.GetAttribute("type") = "submit" Then
webpageelement.InvokeMember("click")
Timer1.Stop()
Label5.Text = "Authorized."
Button2.Enabled = True
So now you're logged into the account, on the website, but when the code above to download runs, it downloads a zip, but it's corrupted. So I opened it with notepad++ and this is what I get (Does this mean it didn't login for the download, and it only logged in with the webbrowser and they aren't linked? Or something? Like My firefox logins aren't linked with chrome?:
The code is huge, it's like a HTML coding. Here is the link to a online notepad I put it on:
http://shrib.com/nCOucdfL
Another thing, a webbrowser can't be showing on the program, it can be on the outside not showing, like I did with the login. They also can't click the save button like on a normal web browser when a window pops up, I want it to download automatically to where they set it using a button which sets the directory as DownloadDirectory1
It must be your lucky day because today I woke up and decided that I would like to help you with your cause. I first tried to get the download to work with the web browser control but unfortunately I am sure this is not possible without extending the web browser control and we don't want to do that today.
As I mentioned in the comments, the only way I really know that this is possible (without user interaction) is to log in via the HttpWebRequest method. It's pretty tricky stuff. Definitely not for beginners.
Now I must admit that this isn't the cleanest, most "proper" and user-friendly code around, so if anyone wants to suggest a better way to do things, I am all ears.
I suggest you test this first before you incorporate it into your existing app. Just create a new vb.net app and replace all of the code in Form1 with the code below. You will have to update the usernamehere and passwordhere strings with your real username and password. Also, the file is saving to C:\file.rar by default so you can change this path if you want. This code completely removes the need for the web browser control (unless you are using it for something else) so most likely you can remove that from your real application once you incorporate this properly:
Imports System.Net
Imports System.IO
Imports System.Text
Public Class Form1
Private Const gsUserAgent As String = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"
Const sUsername As String = "usernamehere"
Const sPassword As String = "passwordhere"
Const sMainURL As String = "http://www.mpgh.net/"
Const sCheckLoginURL As String = "http://www.mpgh.net/forum/login.php?do=login"
Const sDownloadURL As String = "http://www.mpgh.net/forum/attachment.php?attachmentid=266579&d=1417312178"
Const sCookieLoggedInMessage As String = "mpgh_imloggedin=yes"
Dim oCookieCollection As CookieCollection = Nothing
Dim sSaveFile As String = "c:\file.rar"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
StartScrape()
End Sub
Private Sub StartScrape()
Try
Dim bContinue As Boolean = True
Dim sPostData(15) As String
sPostData(0) = UrlEncode("vb_login_username")
sPostData(1) = UrlEncode(sUsername)
sPostData(2) = UrlEncode("vb_login_password")
sPostData(3) = UrlEncode(sPassword)
sPostData(4) = UrlEncode("vb_login_password_hint")
sPostData(5) = UrlEncode("Password")
sPostData(6) = UrlEncode("s")
sPostData(7) = UrlEncode("")
sPostData(8) = UrlEncode("securitytoken")
sPostData(9) = UrlEncode("guest")
sPostData(10) = UrlEncode("do")
sPostData(11) = UrlEncode("login")
sPostData(12) = UrlEncode("vb_login_md5password")
sPostData(13) = UrlEncode("")
sPostData(14) = UrlEncode("vb_login_md5password_utf")
sPostData(15) = UrlEncode("")
If GetMethod(sMainURL) = True Then
If SetMethod(sCheckLoginURL, sPostData, sMainURL) = True Then
' Login successful
If DownloadMethod(sDownloadURL, sMainURL) = True Then
MessageBox.Show("File downloaded successfully")
Else
MessageBox.Show("Error downloading file")
End If
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Function GetMethod(ByVal sPage As String) As Boolean
Dim req As HttpWebRequest
Dim resp As HttpWebResponse
Dim stw As StreamReader
Dim bReturn As Boolean = True
Try
req = HttpWebRequest.Create(sPage)
req.Method = "GET"
req.AllowAutoRedirect = False
req.UserAgent = gsUserAgent
req.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
req.Headers.Add("Accept-Language", "en-us,en;q=0.5")
req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7")
req.Headers.Add("Keep-Alive", "300")
req.KeepAlive = True
resp = req.GetResponse ' Get the response from the server
If req.HaveResponse Then
' Save the cookie info if applicable
SaveCookies(resp.Headers("Set-Cookie"))
resp = req.GetResponse ' Get the response from the server
stw = New StreamReader(resp.GetResponseStream)
stw.ReadToEnd() ' Read the response from the server, but we do not save it
Else
MessageBox.Show("No response received from host " & sPage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
bReturn = False
End If
Catch exc As WebException
MessageBox.Show("Network Error: " & exc.Message.ToString & " Status Code: " & exc.Status.ToString & " from " & sPage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
bReturn = False
End Try
Return bReturn
End Function
Private Function SetMethod(ByVal sPage As String, ByVal sPostData() As String, sReferer As String) As Boolean
Dim bReturn As Boolean = False
Dim req As HttpWebRequest
Dim resp As HttpWebResponse
Dim str As StreamWriter
Dim sPostDataValue As String = ""
Try
req = HttpWebRequest.Create(sPage)
req.Method = "POST"
req.UserAgent = gsUserAgent
req.Accept = "application/x-shockwave-flash,text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
req.Headers.Add("Accept-Language", "en-us,en;q=0.5")
req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7")
req.Referer = sReferer
req.ContentType = "application/x-www-form-urlencoded"
req.Headers.Add("Pragma", "no-cache")
req.Headers.Add("Keep-Alive", "300")
If oCookieCollection IsNot Nothing Then
' Pass cookie info from the login page
req.CookieContainer = SetCookieContainer(sPage)
End If
str = New StreamWriter(req.GetRequestStream)
If sPostData.Count Mod 2 = 0 Then
' There is an even number of post names and values
For i As Int32 = 0 To sPostData.Count - 1 Step 2
' Put the post data together into one string
sPostDataValue &= sPostData(i) & "=" & sPostData(i + 1) & "&"
Next i
sPostDataValue = sPostDataValue.Substring(0, sPostDataValue.Length - 1) ' This will remove the extra "&" at the end that was added from the for loop above
' Post the data to the server
str.Write(sPostDataValue)
str.Close()
' Get the response
resp = req.GetResponse
If req.HaveResponse Then
If resp.Headers("Set-Cookie").IndexOf(sCookieLoggedInMessage) > -1 Then
' Save the cookie info
SaveCookies(resp.Headers("Set-Cookie"))
bReturn = True
Else
MessageBox.Show("The email or password you entered are incorrect." & vbCrLf & vbCrLf & "Please try again.", "Unable to log in", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
bReturn = False
End If
Else
' This should probably never happen.. but if it does, we give a message
MessageBox.Show("The email or password you entered are incorrect." & vbCrLf & vbCrLf & "Please try again.", "Unable to log in", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
bReturn = False
End If
Else
' Did not specify the correct amount of parameters so we cannot continue
MessageBox.Show("POST error. Did not supply the correct amount of post data for " & sPage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
bReturn = False
End If
Catch ex As Exception
MessageBox.Show("POST error. " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
bReturn = False
End Try
Return bReturn
End Function
Private Function DownloadMethod(ByVal sPage As String, sReferer As String) As Boolean
Dim req As HttpWebRequest
Dim bReturn As Boolean = False
Try
req = HttpWebRequest.Create(sPage)
req.Method = "GET"
req.AllowAutoRedirect = False
req.UserAgent = gsUserAgent
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
req.Headers.Add("Accept-Language", "en-US,en;q=0.5")
req.Headers.Add("Accept-Encoding", "gzip, deflate")
req.Headers.Add("Keep-Alive", "300")
req.KeepAlive = True
If oCookieCollection IsNot Nothing Then
' Set cookie info so that we continue to be logged in
req.CookieContainer = SetCookieContainer(sPage)
End If
' Save file to disk
Using oResponse As System.Net.WebResponse = CType(req.GetResponse, System.Net.WebResponse)
Using responseStream As IO.Stream = oResponse.GetResponseStream
Using fs As New IO.FileStream(sSaveFile, FileMode.Create, FileAccess.Write)
Dim buffer(2047) As Byte
Dim read As Integer
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
oResponse.Close()
End Using
bReturn = True
Catch exc As WebException
MessageBox.Show("Network Error: " & exc.Message.ToString & " Status Code: " & exc.Status.ToString & " from " & sPage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
bReturn = False
End Try
Return bReturn
End Function
Private Function SetCookieContainer(sPage As String) As System.Net.CookieContainer
Dim oCookieContainerObject As New System.Net.CookieContainer
Dim oCookie As System.Net.Cookie
For c As Int32 = 0 To oCookieCollection.Count - 1
If IsDate(oCookieCollection(c).Value) = True Then
' Fix dates as they seem to cause errors/problems
oCookieCollection(c).Value = Format(CDate(oCookieCollection(c).Value), "dd-MMM-yyyy hh:mm:ss")
End If
oCookie = New System.Net.Cookie
oCookie.Name = oCookieCollection(c).Name
oCookie.Value = oCookieCollection(c).Value
oCookie.Domain = New Uri(sPage).Host
oCookie.Secure = False
oCookieContainerObject.Add(oCookie)
Next
Return oCookieContainerObject
End Function
Private Sub SaveCookies(sCookieString As String)
Dim sCookieStrings() As String = sCookieString.Trim.Replace(" HttpOnly,", "").Replace(" HttpOnly", "").Replace(" domain=.mpgh.net,", "").Split(";".ToCharArray())
oCookieCollection = New CookieCollection
For Each sCookie As String In sCookieStrings
If sCookie.Trim <> "" Then
Dim sName As String = sCookie.Trim().Split("=".ToCharArray())(0)
Dim sValue As String = sCookie.Trim().Split("=".ToCharArray())(1)
oCookieCollection.Add(New Cookie(sName, sValue))
End If
Next
End Sub
Private Function UrlEncode(ByRef URLText As String) As String
Dim AscCode As Integer
Dim EncText As String = ""
Dim bStr() As Byte = Encoding.ASCII.GetBytes(URLText)
Try
For i As Long = 0 To UBound(bStr)
AscCode = bStr(i)
Select Case AscCode
Case 48 To 57, 65 To 90, 97 To 122, 46, 95
EncText = EncText & Chr(AscCode)
Case 32
EncText = EncText & "+"
Case Else
If AscCode < 16 Then
EncText = EncText & "%0" & Hex(AscCode)
Else
EncText = EncText & "%" & Hex(AscCode)
End If
End Select
Next i
Erase bStr
Catch ex As WebException
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Return EncText
End Function
End Class