WebClient error with Arrays VB.NET - arrays

I'm using and array of files to be copied from a folder to another folder but it gives me an error.WebClient does not support concurrent I/O operations.
this is my code:
Protected Overrides Sub OnLoad(e As EventArgs)
MyBase.OnLoad(e)
CopyBtn.Text = "Copy File"
CopyBtn.Parent = Me
ProgBar.Left = CopyBtn.Right
End Sub
Dim WithEvents CopyBtn As New Button
Dim ProgBar As New ProgressBar
Dim WithEvents FileCopier As New WebClient
Private Sub CopyBtn_Click(sender As Object, e As EventArgs) Handles CopyBtn.Click
Dim src As String = "D:\test"
Dim dest As String = "D:\test2"
Dim filesToCopy As New ArrayList()
For Each Dir As String In System.IO.Directory.GetFiles(src)
Dim dirInfo As New System.IO.DirectoryInfo(Dir)
If Not System.IO.File.Exists(dest & "\" & dirInfo.Name) Then
filesToCopy.Add(dirInfo.Name)
End If
Next
If filesToCopy.Count > 0 Then
If MsgBox("There are new files found. Do you want to sync it now?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Confirm") = MsgBoxResult.Yes Then
For i = 0 To filesToCopy.Count - 1
CopyBtn.Enabled = False
ProgBar.Parent = Me
FileCopier.DownloadFileAsync(New Uri(src & "\" & filesToCopy(i)), dest & "\" & filesToCopy(i))
Next
End If
Else
MsgBox("No new files to be copied")
End If
End Sub
Private Sub FileCopier_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles FileCopier.DownloadProgressChanged
Dim bytesIn As Double = Double.Parse(e.BytesReceived.ToString())
Dim totalBytes As Double = Double.Parse(e.TotalBytesToReceive.ToString())
Dim percentage As Double = bytesIn / totalBytes * 100
ProgBar.Value = Int32.Parse(Math.Truncate(percentage).ToString())
End Sub
Private Sub FileCopier_DownloadFileCompleted(sender As Object, e As System.ComponentModel.AsyncCompletedEventArgs) Handles FileCopier.DownloadFileCompleted
ProgBar.Parent = Nothing
CopyBtn.Enabled = True
End Sub
but when i put this code before the copying/downloadfileasync
Dim FileCopier as WebClient = New Webclient
it successfully copies. but the progressbar is not working,even if i put this onDownloadProgressChangedProgBar.Value = e.ProgressPercentage it doesn't load. can you please help me? Just a newbie still learning here.

wew, i just needed to add this
AddHandler FileCopier.DownloadProgressChanged, AddressOf FileCopier_DownloadProgressChanged
AddHandler FileCopier.DownloadFileCompleted, AddressOf FileCopier_DownloadFileCompleted
with this codes:Dim FileCopier as WebClient = New Webclient
ProgBar.Value = e.ProgressPercentage

Related

argument out of range parameter name index

since i have the code of the auto generated text box
Insert data from auto generated textbox to SQL Server database
i am try to write a code for ensuring of the auto generated text box in FlowLayoutPanel1 contain data
the auto generated text box build depends on the number in Val(Label2.Text) of the real part
and if any text box is null or empty then the process will stop until fill all fields
the auto generated text box will be like this if the Val(Label2.Text)
is equal to 3
so i try this in the save button
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
For k As Integer = 1 To Val(Label2.Text)
If String.IsNullOrEmpty(FlowLayoutPanel1.Controls(i).Text) Then
MsgBox("Error , fill all text box")
Return
Else
UpdateUsers()
i += 1
End If
Next
MsgBox("Done , add all data to database ")
Button3.Enabled = False
End Sub
so i getting error after leave some text box and back to fill it again
and the all of form code is
Imports System.Data.SqlClient
'library for create folders
Imports System.IO
Public Class part
Dim cLeft As Integer = 1
Dim top1 As Integer = 5
Dim i As Integer = 0
Dim path1 As String
Dim cmd As SqlCommand
Public Sub AddNewTextBox()
Dim txt As New System.Windows.Forms.TextBox()
txt.Top = cLeft * 30
txt.Left = 100
'txt.Text = "TextBox " & Me.cLeft.ToString
cLeft = cLeft + 1
txt.ForeColor = Color.White
txt.BackColor = Color.Gray
txt.Font = New Font("Arial", 14.0, FontStyle.Regular)
txt.Size = New Size(350, 31)
txt.Location = New Point(156, 130 + top1)
txt.TextAlign = HorizontalAlignment.Center
FlowLayoutPanel1.Controls.Add(txt)
End Sub
Private Sub part_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'college part number
Label2.Visible = False
'college path folder
Label3.Visible = False
For m As Integer = 1 To Val(Label2.Text)
AddNewTextBox()
top1 = top1 + 35
Next
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub UpdateUsers()
Using cn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Hazim M\Desktop\stud_project\stud_project\Database1.mdf;Integrated Security=True;User Instance=True")
Using cmd As New SqlCommand("INSERT INTO college_part ([name],[coll_of_part],[part_path]) Values (#name,#coll_of_part,#part_path);", cn)
If i < Val(Label2.Text) Then
path1 = Label3.Text & "\" & FlowLayoutPanel1.Controls(i).Text.Trim & Date.Now.Year
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = FlowLayoutPanel1.Controls(i).Text
cmd.Parameters.Add("#coll_of_part", SqlDbType.NVarChar).Value = Label1.Text
cmd.Parameters.Add("#part_path", SqlDbType.NVarChar).Value = path1
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
If Not Directory.Exists(path1) Then
Directory.CreateDirectory(path1)
Else
MsgBox("folder is existing")
End If
End If
End Using
End Using
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
For k As Integer = 1 To Val(Label2.Text)
If String.IsNullOrEmpty(FlowLayoutPanel1.Controls(i).Text) Then
MsgBox("Error , fill all text box")
Return
Else
UpdateUsers()
i += 1
End If
Next
MsgBox("Done , add all data to database ")
Button3.Enabled = False
End Sub
End Class
thank u
I think you need to move dim i Integer=0 to local variable in the Button3_click method. ANd Pass i to the UpdateUser call (add the param to UpdateUser). The current global i keeps adding 1 and eventually out of range.

Moving file contents into an array

Im currently working on getting this piece of code to work so that I can read a text file, move the contents into an array and then display a certain column (such as price)
Imports System.IO
Public Class Form1
Dim FileName As String
Dim i As Integer = 0
Dim Alpha As Integer = 0
Dim Products(31) As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FileName = "Products.txt"
End Sub
Private Sub btnCreateArray_Click(sender As Object, e As EventArgs) Handles btnCreateArray.Click
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("Products.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
'MsgBox(currentField)
'txtShowNo.Text = currentField
'txtShowP.Text = i
i = i + 1
Products(i) = currentField
Next
End While
End Using
Do While Alpha <= i
If InStr((txtFileSearch.Text), (Products(Alpha))) Then
lstDisplayFile.Items.Add(Products(Alpha))
Alpha = Alpha + 1
End If
Loop
End Sub
Private Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click
txtFileSearch.Text = ""
End Sub
Private Sub btnAddToFilePrintFile_Click(sender As Object, e As EventArgs) Handles btnAddToFilePrintFile.Click
Dim Name As String
Dim SName As String
Dim IDNo As Integer
Name = txtName.Text
SName = txtSName.Text
IDNo = txtIDNo.Text
FileOpen(1, FileName, OpenMode.Append) ' create a new empty file & open it in append mode'
WriteLine(1, IDNo, Name, SName) ' Writes a line of data'
FileClose(1)
txtName.Text = ""
txtSName.Text = ""
txtIDNo.Text = ""
txtName.Focus()
End Sub
End Class
The program crashes on this line of code:
lstDisplayFile.Items.Add(Products(Alpha))
along with the following message :
An unhandled exception of type 'System.ArgumentNullException' occurred in System.Windows.Forms.dll
Alpha is my counter, and my thought process behind this was that if the input within the textbox is currently in the array, it will display the completed text in the array.
Here is the current contents within my text file :
"£5.00","50"
"£2.50","30"
If anyone could help me solve this I would be appreciative :)

Playing multiple audio files using system() in C

I've written a C code to play 3 audio files one after other using vlc but the after playing first file it's not proceeding I've to press Ctrl+C or q to go to next song which I want to happen itself.
I placed system("q") after every file so that it may fulfill my task but it's still not working.
#include<stdio.h>
int main(){
system("vlc 1.mp3");
system("q");
system("vlc 2.mp3");
system("q");
system("vlc 3.mp3");
system("q");
return 0;
}
I think you should use mplayer in slave mode instead of vlc. It is more flexible and has more control. you can send command to mplayer as you wish. please study the following link
http://www.mplayerhq.hu/DOCS/tech/slave.txt
I suggest you to use python for linux and C# or VB.NET for windows. I can supply some vb.net code if you need it.
This was my old answer for another question.
but I will post here for you too.
I am developing android phone remote control + VB.NET TCP server - mplayer. I am using mplayer in slave mode. I send command from android app to VB.NET TCP server. Then the command will send to mplayer.
I will show some code that control and send the mplayer desired commands, but the server part is not finished yet. The coding is no finished yet but I hope it is useful for you.
Imports System.ComponentModel
Imports System.IO
Imports System.Data.OleDb
Public Class Form1
Private bw As BackgroundWorker = New BackgroundWorker
Dim i As Integer = 0
Dim dbFile As String = Application.StartupPath & "\Data\Songs.accdb"
Public connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & dbFile & "; persist security info=false"
Public conn As New OleDbConnection(connstring)
Dim sw As Stopwatch
Dim ps As Process = Nothing
Dim jpgPs As Process = Nothing
Dim args As String = Nothing
Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
If bw.CancellationPending = True Then
e.Cancel = True
Exit Sub
Else
' Perform a time consuming operation and report progress.
'System.Threading.Thread.Sleep(500)
bw.ReportProgress(i * 10)
Dim dir_info As New DirectoryInfo(TextBox1.Text)
ListFiels("SongList", TextBox2.Text, dir_info)
End If
End Sub
Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
If e.Cancelled = True Then
Me.tbProgress.Text = "Canceled!"
ElseIf e.Error IsNot Nothing Then
Me.tbProgress.Text = "Error: " & e.Error.Message
Else
Me.tbProgress.Text = "Done!"
End If
End Sub
Private Sub bw_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
Me.tbProgress.Text = e.ProgressPercentage.ToString() & "%"
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
Try
ps.Kill()
Catch
Debug.Write("already closed")
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False 'To avoid error from backgroundworker
bw.WorkerReportsProgress = True
bw.WorkerSupportsCancellation = True
AddHandler bw.DoWork, AddressOf bw_DoWork
AddHandler bw.ProgressChanged, AddressOf bw_ProgressChanged
AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted
funPlayMusic()
End Sub
Private Sub buttonStart_Click(sender As Object, e As EventArgs) Handles buttonStart.Click
If Not bw.IsBusy = True Then
bw.RunWorkerAsync()
End If
End Sub
Private Sub buttonCancel_Click(sender As Object, e As EventArgs) Handles buttonCancel.Click
If bw.WorkerSupportsCancellation = True Then
bw.CancelAsync()
End If
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
If Not bw.IsBusy = True Then
sw = Stopwatch.StartNew()
bw.RunWorkerAsync()
sw.Stop()
Label1.Text = ": " + sw.Elapsed.TotalMilliseconds.ToString() + " ms"
End If
End Sub
Private Sub ListFiels(ByVal tblName As String, ByVal pattern As String, ByVal dir_info As DirectoryInfo)
i = 0
Dim fs_infos() As FileInfo = Nothing
Try
fs_infos = dir_info.GetFiles(pattern)
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
For Each fs_info As FileInfo In fs_infos
i += 1
Label1.Text = i
insertData(tblName, fs_info.FullName)
lstResults.Items.Add(i.ToString() + ":" + fs_info.FullName.ToString())
If i = 1 Then
Playsong(fs_info.FullName.ToString())
Else
i = 0
lstResults.Items.Clear()
End If
Next fs_info
sw.Stop()
Label1.Text = ": " + sw.Elapsed.TotalMilliseconds.ToString() + " ms"
fs_infos = Nothing
Dim subdirs() As DirectoryInfo = dir_info.GetDirectories()
For Each subdir As DirectoryInfo In subdirs
ListFiels(tblName, pattern, subdir)
Next
End Sub
Private Sub insertData(ByVal tableName As String, ByVal foundfile As String)
Try
If conn.State = ConnectionState.Open Then conn.Close()
conn.Open()
Dim SqlQuery As String = "INSERT INTO " & tableName & " (SngPath) VALUES (#sng)"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandType = CommandType.Text
.CommandText = SqlQuery
.Connection = conn
.Parameters.AddWithValue("#sng", foundfile)
.ExecuteNonQuery()
End With
conn.Close()
Catch ex As Exception
conn.Close()
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnClearList_Click(sender As Object, e As EventArgs) Handles btnClearList.Click
lstResults.Items.Clear()
End Sub
Private Sub funPlayMusic()
ps = New Process()
ps.StartInfo.FileName = "D:\Music\mplayer.exe "
ps.StartInfo.UseShellExecute = False
ps.StartInfo.RedirectStandardInput = True
jpgPs = New Process()
jpgPs.StartInfo.FileName = "D:\Music\playjpg.bat"
jpgPs.StartInfo.UseShellExecute = False
jpgPs.StartInfo.RedirectStandardInput = True
'ps.StartInfo.CreateNoWindow = True
args = "-fs -noquiet -identify -slave " '
args += "-nomouseinput -sub-fuzziness 1 "
args += " -vo direct3d, -ao dsound "
' -wid will tell MPlayer to show output inisde our panel
' args += " -vo direct3d, -ao dsound -wid ";
' int id = (int)panel1.Handle;
' args += id;
End Sub
Public Function SendCommand(ByVal cmd As String) As Boolean
Try
If ps IsNot Nothing AndAlso ps.HasExited = False Then
ps.StandardInput.Write(cmd + vbLf)
'MessageBox.Show(ps.StandardOutput.ReadToEndAsync.ToString())
Return True
Else
Return False
End If
Catch ex As Exception
Return False
End Try
End Function
Public Sub Playsong(ByVal Songfilelocation As String)
Try
ps.Kill()
Catch
End Try
Try
ps.StartInfo.Arguments = args + " """ + Songfilelocation + """"
ps.Start()
SendCommand("set_property volume " + "80")
Catch e As Exception
MessageBox.Show(e.Message)
End Try
End Sub
Private Sub lstResults_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstResults.SelectedIndexChanged
Playsong(lstResults.SelectedItem.ToString())
End Sub
Private Sub btnPlayJPG_Click(sender As Object, e As EventArgs) Handles btnPlayJPG.Click
Try
' jpgPs.Kill()
Catch
End Try
Try
'ps.StartInfo.Arguments = "–fs –mf fps=5 mf://d:/music/g1/Image00020.jpg –loop 200" '-vo gl_nosw
'jpgPs.Start()
Shell("d:\Music\playjpg.bat")
' SendCommand("set_property volume " + "80")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub btnPlayPause_Click(sender As Object, e As EventArgs) Handles btnPlayPause.Click
SendCommand("pause")
End Sub
Private Sub btnMute_Click(sender As Object, e As EventArgs) Handles btnMute.Click
SendCommand("mute")
End Sub
Private Sub btnKaraoke_Click(sender As Object, e As EventArgs) Handles btnKaraoke.Click
'SendCommand("panscan 0-0 | 1-1")
SendCommand("af_add pan=2:1:1:0:0")
End Sub
Private Sub btnStereo_Click(sender As Object, e As EventArgs) Handles btnStereo.Click
SendCommand("af_add pan=2:0:0:1:1")
End Sub
Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
Playsong("d:\music\iot.mp4")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'SendCommand("loadfile d:\music\iot.mp4")
'SendCommand("pt_step 1")
End Sub
End Class

VB.NET Count number of files to copy with WebClient

I'm trying to write a code that copy files from a folder to another folder with a progress bar and with a Label that count files, like Copying 0 files of 10 files. but my code is not working and throws and error.
Collection was modified; enumeration operation may not execute.
this is my code:
Imports System.IO
Imports System.Net
Public Class Form1
Dim filesToCopy As New ArrayList()
Protected Overrides Sub OnLoad(ByVal e As EventArgs)
MyBase.OnLoad(e)
CopyBtn.Text = "Copy File"
CopyBtn.Parent = Me
ProgBar.Left = CopyBtn.Right
End Sub
Dim WithEvents CopyBtn As New Button
Dim ProgBar As New ProgressBar
Dim WithEvents FileCopier As New WebClient
Public Sub check(ByVal sender As Object, ByVal e As EventArgs) Handles CopyBtn.Click
Dim src As String = "D:\test"
Dim dest As String = "D:\test2"
For Each Dir As String In System.IO.Directory.GetFiles(src)
Dim dirInfo As New System.IO.DirectoryInfo(Dir)
If Not System.IO.File.Exists(dest & "\" & dirInfo.Name) Then
filesToCopy.Add(dirInfo.Name)
End If
Next
If filesToCopy.Count > 0 Then
If MsgBox("There are new files found. Do you want to sync it now?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Confirm") = MsgBoxResult.Yes Then
For i = 0 To filesToCopy.Count - 1
Dim FileCopier As WebClient = New WebClient
AddHandler FileCopier.DownloadProgressChanged, AddressOf FileCopier_DownloadProgressChanged
AddHandler FileCopier.DownloadFileCompleted, AddressOf FileCopier_DownloadFileCompleted
CopyBtn.Enabled = False
ProgBar.Parent = Me
FileCopier.DownloadFileAsync(New Uri(src & "\" & filesToCopy(i)), dest & "\" & filesToCopy(i))
Next
End If
Else
MsgBox("No new files to be copied")
End If
End Sub
this is my code that tracks the number of files copying.
Private Sub FileCopier_DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs) Handles FileCopier.DownloadProgressChanged
ProgBar.Value = e.ProgressPercentage
For Each file In filesToCopy
total += filesToCopy.Add(file)
Next
Label2.Text = total \ filesToCopy.Count
End Sub
End Class
Add it here instead in DownloadProgressChanged
For i = 0 To filesToCopy.Count - 1
Dim FileCopier As WebClient = New WebClient
AddHandler FileCopier.DownloadProgressChanged, AddressOf FileCopier_DownloadProgressChanged
AddHandler FileCopier.DownloadFileCompleted, AddressOf FileCopier_DownloadFileCompleted
CopyBtn.Enabled = False
ProgBar.Parent = Me
FileCopier.DownloadFileAsync(New Uri(src & "\" & filesToCopy(i)), dest & "\" & filesToCopy(i))
Label2.Text = i + 1 & "/" & FilesToCopy.Count 'PUT IT HERE INSTEAD
Next

WPF asynchronous invoke question

What's wrong in my code? It's not updating the TextBox and the ProgressBar while deleting files.
Imports System.Windows.Threading
Imports System.IO
Class MainWindow
Private Sub bt_Click(ByVal sender As Object,
ByVal e As RoutedEventArgs) Handles bt.Click
Dim sb As New System.Text.StringBuilder
Dim files = IO.Directory.EnumerateFiles(
My.Computer.FileSystem.SpecialDirectories.Temp, "*.*",
SearchOption.TopDirectoryOnly)
Dim count = files.Count
pb.Minimum = 0
pb.Maximum = count
For i = 0 To count - 1
Dim f = files(i)
Dispatcher.BeginInvoke(
New Action(Of String, Integer)(
Sub(str, int)
tb.SetValue(TextBox.TextProperty, str)
pb.SetValue(ProgressBar.ValueProperty, int)
End Sub),
DispatcherPriority.Send,
f, i + 1)
Try
File.Delete(f)
Catch ex As Exception
sb.AppendLine(f)
End Try
Dim exceptions = sb.ToString
Stop
Next
End Sub
End Class
I got this working with the BackgroundWorker object. This places your work in a background thread, with calls to update the UI going through the ProgressChanged event. I also used Invoke instead of BeginInvoke within the work loop, which forces the loop to wait for the UI to become updated before it proceeds.
Imports System.ComponentModel
Imports System.IO
Class MainWindow
Private WithEvents bw As New BackgroundWorker
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As RoutedEventArgs) Handles btn.Click
pb.Minimum = 0
pb.Maximum = 100
bw.WorkerReportsProgress = True
bw.RunWorkerAsync()
End Sub
Private Sub bw_DoWork(ByVal sender As Object,
ByVal e As DoWorkEventArgs) Handles bw.DoWork
Dim sb As New System.Text.StringBuilder
Dim files = IO.Directory.EnumerateFiles(
My.Computer.FileSystem.SpecialDirectories.Temp, "*.*",
SearchOption.TopDirectoryOnly)
Dim count = files.Count
Me.Dispatcher.BeginInvoke(Sub()
tb.Text = "SOMETHING ELSE"
End Sub)
For i = 0 To count - 1
Dim f = files(i)
Dim myI = i + 1
Me.Dispatcher.Invoke(
Sub()
bw.ReportProgress(CInt((myI / count) * 100), f)
End Sub)
'Try
' File.Delete(f)
'Catch ex As Exception
' sb.AppendLine(f)
'End Try
Dim exceptions = sb.ToString
'Stop
Next
End Sub
Private Sub bw_ProgressChanged(
ByVal sender As Object,
ByVal e As ProgressChangedEventArgs) Handles bw.ProgressChanged
Dim fString As String = TryCast(e.UserState, String)
Me.Dispatcher.BeginInvoke(Sub()
tb.Text = fString
End Sub)
End Sub
End Class

Resources