Youtube API - uploading large file using vb.net - vb.net

I am trying to upload a large (4MB+) file to youtube using the API in VB.NET.
Smaller files upload fine, but anything larger than about 4MB gives an error which (I think) is actually related to a timeout: The request was aborted: The request was canceled.
I have read and re-read the API doco, googled, etc looking for an example in VB.NET, but nothing seems to be out there for vb.net
A few coders have hit the same problem and the responses have all been around c# or Java - neither of which I am familiar with.
I tried different combinations of the settings.timeout and settings.maximum, but it does not seem to make a difference
Current code is:
Sub UploadYouTube(ByVal sSourceFile As String, ByVal sTitle As String, ByVal sMediaCategory As String, ByVal sDesc As String)
Dim uSettings As YouTubeRequestSettings, uRequest As YouTubeRequest, newVideo As Video, CreatedVideo As Video, VideoId As String
Dim vContentType As String = "video"
Try
uSettings = New YouTubeRequestSettings(, , , )
uRequest = New YouTubeRequest(uSettings)
newVideo = New Video()
newVideo.Title = sTitle '"Test";
newVideo.Tags.Add(New MediaCategory("Education", YouTubeNameTable.CategorySchema))
newVideo.Description = sDesc '"Testing Testing Testing"
newVideo.YouTubeEntry.Private = False
uRequest.Settings.Timeout = 60 * 60 * 1000
uRequest.Settings.Maximum = 2000000000
' Determine the content type
If sSourceFile.EndsWith(".mov") Then
vContentType = "video/quicktime"
ElseIf sSourceFile.EndsWith(".avi") Or sSourceFile.EndsWith(".mpg") Or sSourceFile.EndsWith(".mpeg") Then
vContentType = "video/mpeg"
ElseIf sSourceFile.EndsWith(".wmv") Then
vContentType = "video/x-ms-wmv"
ElseIf sSourceFile.EndsWith(".m4v") Then
vContentType = "video/m4v"
ElseIf sSourceFile.EndsWith(".mp4") Then
vContentType = "video/mp4"
ElseIf sSourceFile.EndsWith(".3gp") Then
vContentType = "video/3gpp"
End If
newVideo.YouTubeEntry.MediaSource = New MediaFileSource(sSourceFile, vContentType)
CreatedVideo = uRequest.Upload(newVideo)
VideoId = CreatedVideo.VideoId
' Save the video Id to the database!
Catch ex As Exception
debug.print("Error. MainModule.Main. " & ex.Message, 5)
End Try
End Sub
Any help is greatly appreciated
Tony

Python example : https://github.com/Mathieu69/Pitivi_Gargamel/blob/upload_merger/pitivi/uploader.py did that 3 months ago, hope it helps.

I tried to solve the timeout problem by using a backgroundworker. It works, sort of. It doesn't appear to actually be working in the background. I would think the RunWorkerAsync would start, move on to the next command, and postback. Instead it just hangs for a few minutes like it's uploading the whole 75MB file, then posts back successful. If I take away the backgroundworker and just execute the upload however, it fails like yours did. Here's my code that kind of works.
Sub up_load(s As Object, e As EventArgs)
Dim worker As BackgroundWorker = New BackgroundWorker
worker.WorkerReportsProgress = True
worker.WorkerSupportsCancellation = True
AddHandler (worker.DoWork), AddressOf begin_upload
worker.RunWorkerAsync()
lblmsg.Text = "Successfully initiated upload"
End Sub
Sub begin_upload(s As Object, e As DoWorkEventArgs)
Dim request As New YouTubeRequest(settings)
Dim vidupload As New Video()
vidupload.Title = "My Big Test Movie"
vidupload.Tags.Add(New MediaCategory("Nonprofit", YouTubeNameTable.CategorySchema))
vidupload.Keywords = "church, jesus"
vidupload.Description = "See the entire video"
vidupload.YouTubeEntry.Private = False
vidupload.YouTubeEntry.setYouTubeExtension("location", "Downers Grove, IL")
vidupload.YouTubeEntry.MediaSource = New MediaFileSource("c:\users\greg\test3.asf", "video/x-ms-wmv")
Dim createdVideo As Video = Request.Upload(vidupload)
End Sub

Related

Streamreader not reading all lines

I am working on a little tool that allows the selection of a single file. Where it will calculate the SHA2 hash and shows it in a simple GUI then takes the value and checks if that hash is listed in a blacklist text file. If it is listed then it will flag it as dirty, and if not it will pass it as clean.
But after hitting Google for hours on end and sifting through many online sources I decided let's just ask for advise and help.
That said while my program does work I seem to run into a problem, since no matter what I do ,it only reads the first line of my "blacklist" and refuses to read the whole list or to actually go line by line to see if there is a match.
No matter if I got 100 or 1 SHA2 hash in it.
So example if I were to have 5 files which I add to the so called blacklist. By pre-calculating their SHA2 value. Then no matter what my little tool will only flag one file which is blacklisted as a match.
Yet the moment I use the reset button and I select a different (also blacklisted) file, it passes it as clean while its not. As far as I can tell it is always the first SHA2 hash it seems to flag and ignoring the others. I personally think the program does not even check beyond the first hash.
Now the blacklist file is made up very simple.
*example:
1afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
2afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
3afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
4afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
....and so on.
So as you can see these fake example hashes are listed without any details.
Now my program is suppose to calculate the hash from a selected file.
Example:
somefile.exe (or any extension)
Its 5KB in size and its SHA2 value would be:
3afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
Well as you can see I took the third hash from the example list right?
Now if I select somefile.exe for scanning then it will pass it as clean. While its blacklisted. So if I move this hash to the first position. Then my little program does correctly flag it.
So long story short I assume that something is horrible wrong with my code, even though it seems to be working.
Anyway this is what I got so far:
Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports MetroFramework.Forms
Public Class Fsmain
Function SHA256_SIG(ByVal file_name As String)
Return SHA256_engine("SHA-256", file_name)
End Function
Function SHA256_engine(ByRef hash_type As String, ByRef file_name As String)
Dim SIG
SIG = SHA256.Create()
Dim hashValue() As Byte
Dim filestream As FileStream = File.OpenRead(file_name)
filestream.Position = 0
hashValue = SIG.ComputeHash(filestream)
Dim hash_hex = PrintByteArray(hashValue)
Stream.Null.Close()
Return hash_hex
End Function
Public Function PrintByteArray(ByRef array() As Byte)
Dim hex_value As String = ""
Dim i As Integer
For i = 0 To array.Length - 1
hex_value += array(i).ToString("x2")
Next i
Return hex_value.ToLower
End Function
Private Sub Browsebutton_Click(sender As Object, e As EventArgs) Handles Browsebutton.Click
If SampleFetch.ShowDialog = DialogResult.OK Then
Dim path As String = SampleFetch.FileName
Selectfile.Text = path
Dim Sample As String
Sample = SHA256_SIG(path)
SignatureREF.Text = SHA256_SIG(path)
Using f As System.IO.FileStream = System.IO.File.OpenRead("blacklist.txt")
Using s As System.IO.StreamReader = New System.IO.StreamReader(f)
While Not s.EndOfStream
Dim line As String = s.ReadLine()
If (line = Sample) Then
Result.Visible = True
SignatureREF.Visible = True
Result.Text = "Dirty"
Resetme.Visible = True
RemoveMAL.Visible = True
Else
Result.Visible = True
SignatureREF.Visible = True
Result.Text = "Clean"
Resetme.Visible = True
RemoveMAL.Visible = False
End If
End While
End Using
End Using
End If
End Sub
Private Sub Fsmain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Result.Visible = False
SignatureREF.Visible = False
Resetme.Visible = False
RemoveMAL.Visible = False
End Sub
Private Sub Resetme_Click(sender As Object, e As EventArgs) Handles Resetme.Click
Selectfile.Text = Nothing
SignatureREF.Text = Nothing
Result.Visible = False
SignatureREF.Visible = False
Resetme.Visible = False
RemoveMAL.Visible = False
End Sub
Private Sub RemoveMAL_Click(sender As Object, e As EventArgs) Handles RemoveMAL.Click
Dim ask As MsgBoxResult = MsgBox("Would you like to remove the Dirty file?", MsgBoxStyle.YesNo, MessageBoxIcon.None)
If ask = MsgBoxResult.Yes Then
System.IO.File.Delete(Selectfile.Text$)
Else
MsgBox("You sure you want to keep this file?")
Dim filepath As String = IO.Path.Combine("c:\Dirty\", "Dirty.txt")
Using sw As New StreamWriter(filepath)
sw.WriteLine(" " & DateTime.Now)
sw.WriteLine(" " & Selectfile.Text)
sw.WriteLine(" " & SignatureREF.Text)
sw.WriteLine(" " & Result.Text)
sw.WriteLine("-------------------")
sw.Close()
End Using
End If
End Sub
End Class
So if any of you guys can have a look at it and point out errors, or even can come up with a fix that would be great.
The simplest thing you can do to make your procedure working, is testing whether a defined condition is verified. Terminate the test if that condition is met.
Using a boolean variable, report the result of the test and take action accordingly.
The Using statement takes care of disposing the StreamReader.
You could modify you procedure this way:
Private Sub Browsebutton_Click(sender As Object, e As EventArgs) Handles Browsebutton.Click
If SampleFetch.ShowDialog <> DialogResult.OK Then Exit Sub
Dim sample As String = SHA256_SIG(SampleFetch.FileName)
SignatureREF.Text = sample
Dim isDirty As Boolean = False
Using reader As StreamReader = New StreamReader("blacklist.txt", True)
Dim line As String = String.Empty
While reader.Peek() > 0
line = reader.ReadLine()
If line = sample Then
isDirty = True
Exit While
End If
End While
End Using
If isDirty Then
'(...)
RemoveMAL.Visible = True
Result.Text = "Dirty"
Else
'(...)
RemoveMAL.Visible = False
Result.Text = "Clean"
End If
End Sub
If you have a String and you want to test whether it matches a line of a text file then you can use this simple one-liner:
If IO.File.ReadLines(filePath).Contains(myString) Then

VB.Net Thread Pool Maximum threads allowed

first question here, and its about vb.net threads. I have recently acquired a source code of a program, and I wish to make my own changes and touches to the form, but cannot seem to be able to change the maximum threads allowed. the maximum threads allowed for this program is two threads, where it goes to Netflix and logs in, bringing back the information of the account. It has a maximum of two threads, but it is also proxyless.
I included a part of code where the threadpool is, and I would love to know where to edit it whereas I can change the maximum amount of threads. I have tried looking for certain keywords, but have not found anything that would help.
Private Sub ButtonX1_Click(sender As Object, e As EventArgs) Handles ButtonX1.Click
If (Me.usernames.Count > 0) Then
If (Me.ButtonX1.Text = "Start") Then
Me.NumericUpDown1.Enabled = False
Me.ProgressBarX1.Maximum = Me.usernames.Count
Me.ProgressBarX1.Value = 0
Me.thread_status = True
Me.available = 0
Dim workerThreads As Integer = Me.NumericUpDown1.Value
ThreadPool.SetMinThreads(workerThreads, workerThreads)
ThreadPool.SetMaxThreads(workerThreads, workerThreads)
ServicePointManager.DefaultConnectionLimit = workerThreads
ServicePointManager.Expect100Continue = False
Dim str As String
For Each str In Me.usernames
ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf Me.Lam__R141), str)
Next
Me.ButtonX1.Text = "Stop"
Me.Label3.Text = "Cracking Start"
Else
Me.NumericUpDown1.Enabled = True
Me.thread_status = False
Me.ButtonX1.Text = "Start"
Me.Label3.Text = "Cracking Stop"
End If
Else
Me.Label3.Text = "Load Combolist"
End If
End Sub
Looking at it, I would suggest you change the bracket values from ThreadPool.SetMaxThreads(workerThreads, workerThreads), and you might also need to set ServicePointManager.DefaultConnectionLimit = workerThreads to equal something bigger.

Change label text in foreach loop

i want to update a label while a foreach-loop.
The problem is: the program waits until the loop is done and then updates the label.
Is it possible to update the label during the foreach-loop?
Code:
Dim count as Integer = 0
For Each sFile as String in Files
'ftp-code here, works well
count = count+1
progressbar1.value = count
label1.text = "File " & count & " of 10 uploaded."
next
Thanks in advance
Label is not updated because UI thread is blocked while executing your foreach loop.
You can use async-await approach
Private Async Sub Button_Click(sender As Object, e As EventArgs)
Dim count as Integer = 0
For Each sFile as String in Files
'ftp-code here, works well
count = count+1
progressbar1.value = count
label1.text = "File " & count & " of 10 uploaded."
Await Task.Delay(100)
Next
End Sub
Because you will work with Ftp connections, which is perfect candidate for using async-await.
The Await line will release UI thread which will update label with new value, and continue from that line after 100 milliseconds.
If you will use asynchronous code for ftp connection , then you don't need Task.Delay
You've already accepted an answer but just as an alternative a BackgroundWorker can also be used for something like this. In my case the FTP to get the original files happens very quickly so this snippet from the DoWork event is for downloading those files to a printer.
Dim cnt As Integer = docs.Count
Dim i As Integer = 1
For Each d As String In docs
bgwTest.ReportProgress(BGW_State.S2_UpdStat, "Downloading file " & i.ToString & " of " & cnt.ToString)
Dim fs As New IO.FileStream(My.Application.Info.DirectoryPath & "\labels\" & d, IO.FileMode.Open)
Dim br As New IO.BinaryReader(fs)
Dim bytes() As Byte = br.ReadBytes(CInt(br.BaseStream.Length))
br.Close()
fs.Close()
For x = 0 To numPorts - 1
If Port(x).IsOpen = True Then
Port(x).Write(bytes, 0, bytes.Length)
End If
Next
If bytes.Length > 2400 Then
'these sleeps are because it is only 1-way comm to printer so I have no idea when printer is ready for next file
System.Threading.Thread.Sleep(20000)
Else
System.Threading.Thread.Sleep(5000)
End If
i = i + 1
Next
In the ReportProgress event... (of course, you need to set WorkerReportsProgress property to True)
Private Sub bgwTest_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles bgwTest.ProgressChanged
Select Case e.ProgressPercentage
'BGW_State is just a simple enum for the state,
'which determines which UI controls I need to use.
'Clearly I copy/pasted from a program that had 15 "states" :)
Case BGW_State.S2_UpdStat
Dim s As String = CType(e.UserState, String)
lblStatus.Text = s
lblStatus.Refresh()
Case BGW_State.S15_ShowMessage
Dim s As String = CType(e.UserState, String)
MessageBox.Show(s)
End Select
End Sub
Is it not enough to use Application.DoEvents()? This clears the build up and you should be able to see the text fields being updated very quickly.

VB.NET StreamReader Only Returning One Char On ReadLine/Initialization Error?

I am having a slight mishap in my vb.net (.NET Framework 4.5) app. On startup with this code, nothing changes, and when I trigger the event later to change label11, I only get the letter e, and I can't for the life of my figure out what is wrong with the code. The file is encoded in UTF-8 I believe, but changing the encoding doesn't seem to help. steamDisplayName, steamID64, and steamID32 are defined as strings at the beginning of the program. Here is my code that is executed on startup:
Private Sub mainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim reader As New System.IO.StreamReader("C:\Program Files (x86)\Steam\config\loginusers.vdf")
steamDisplayName = reader.ReadLine(3)
steamDisplayName = steamDisplayName.Replace(Chr(34), "")
steamDisplayName = steamDisplayName.Replace("PersonaName", "")
steamID64 = reader.ReadLine(5)
steamID64 = steamID64.Replace(Chr(34), "")
steamID32 = steamID64.Substring(0, 3) - 61197960265728
Label11.Text = "Welcome, " + steamDisplayName
My.Settings.steamID = steamID32
reader.Close()
End Sub
And here is my C:\Program Files (x86)\Steam\config\loginusers.vdf:
"users"
{
"76561198041432370"
{
"AccountName" "snip"
"PersonaName" "tsunami"
"RememberPassword" "1"
"Timestamp" "1407351554"
"WantsOfflineMode" "0"
}
}
This is NOT a code writing service, however, the code below should help you, it's completely untested, so please check it carefully first.
Private Sub mainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim lines As New System.IO.File.ReadAllLines("C:\Program Files (x86)\Steam\config\loginusers.vdf")
Dim id As Long = 0
For Each line in lines
If line.Contains("PersonalName") Then
Dim parts = line.Split(Chr(34), SplitOptions.RemoveEmptyEntries)
steamDisplayName = parts(1)
ElseIf Long.TryParse(line.Trim.Replace(Chr(34), String.Empty), id) Then
steamID64 = id
steamID32 = steamID64.Substring(0, 3) - 61197960265728 ' What is this for?!
Label11.Text = "Welcome, " & steamDisplayName
My.Settings.steamID = steamID32
Next
End Sub
If Dharman could stop editing my posts from 9 years ago, it would be appreciated.

Twitterizer - TwitterStatusCollectionResponse ResponseObject nothing

I am trying to get the timeline of my user account so I can post the tweets on our website. However, the TwitterStatusCollectionResponse ResponseObject is always nothing. The Content property has what looks to be a valid json response. The Result property is "Unknown". Here is my code:
Dim tokens As New OAuthTokens()
tokens.AccessToken = "XX"
tokens.AccessTokenSecret = "XX"
tokens.ConsumerKey = "XX"
tokens.ConsumerSecret = "XX"
Dim options As New SearchOptions()
options.PageNumber = 2
options.NumberPerPage = 2
Dim timelineOptions As New TimelineOptions
timelineOptions.IncludeRetweets = False
timelineOptions.Count = 5
Dim statusCollectionResponse As TwitterResponse(Of TwitterStatusCollection) = TwitterTimeline.HomeTimeline(tokens, timelineOptions)
'this next line errors.....
For Each status In statusCollectionResponse.ResponseObject
next
Bet you got this version with nuget? There have been problems with twitterizer via nuget for a while, mostly due to incompatible json.net versions. I bet if you need it now you can get an older json.net and fix the issue for now.
Looks like this is a known bug that the author is fixing.
http://forums.twitterizer.net/viewtopic.php?f=9&t=3721&p=5568&hilit=TwitterResponse+Of+TwitterStatusCollection+#p5568
I"ll wait for the next release.
Just wrote this little test, it looks like it works just fine.
You can target the user using the UserId in the UerTimelineOptions
good luck.
'Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Dim s As New UserTimelineOptions
' s.Count = 3000
' s.UseSSL = True
' s.APIBaseAddress = "http://api.twitter.com/1/"
' s.IncludeRetweets = False
' s.UserId = 24769625
' Dim T As TwitterResponse(Of TwitterStatusCollection) = TwitterTimeline.UserTimeline(tokens, s)
' For Each Tweet As TwitterStatus In T.ResponseObject
' Console.WriteLine(Tweet.User.ScreenName & ": " & Tweet.Text)
' Next
'End Sub