I am having a problem but don't know exactly what is wrong with it my code is below:
Imports System.Data.SqlClient
Imports System.Data
Public Class FormAdd
Private Sub btnBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBack.Click
FormAdmin.Show()
Me.Hide()
End Sub
Private Sub btnAdd_Click(ByRef Success As String, ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Call AddUser(Success)
MsgBox(" " & Success & " ")
End Sub
Private Sub AddUser(ByRef Success As String)
lblAdmin.Text = Str(chkAdminAccount.Checked)
Dim con As New SqlConnection
Dim lrd As SqlDataReader
Dim inscmd As New SqlCommand
inscmd.Parameters.AddWithValue("#Username", txtUsername.Text.Trim())
txtUsername.Text = txtUsername.Text
inscmd.Parameters.AddWithValue("#Password", txtPassword.Text.Trim)
txtPassword.Text = txtPassword.Text
inscmd.Parameters.AddWithValue("#Name", (txtName.Text.Trim))
txtName.Text = txtName.Text
inscmd.Parameters.AddWithValue("#AdminAccount", lblAdmin.Text.Trim)
lblAdmin = lblAdmin
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Alwyn\Desktop\Computing A2 Alwyn\Comp4ProjectRoomBookingSystem\WindowsApplication1\WindowsApplication1\Database1.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
Try
con.Open()
inscmd.CommandText = "INSERT INTO Admin (Username, Password, Name, AdminAccount) VALUES (#Username, #Password, #Name, #AdminAccount)"
inscmd.Connection = con
inscmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Could not add User" & ex.Message & " ")
Finally
con.Close()
inscmd.Parameters.Clear()
Success = "User has been added"
End Try
End Sub
End Class
If you could help it would be much appreciated error message is as follows:
Method 'Private Sub btnAdd_Click(ByRef Success As String, sender As Object, e As System.EventArgs)' cannot handle event 'Public Event Click(sender As Object, e As System.EventArgs)' because they do not have a compatible signature. C:\Users\Alwyn\Desktop\Computing A2 Alwyn\Comp4ProjectRoomBookingSystem\WindowsApplication1\WindowsApplication1\FormAdd.vb 10 130 WindowsApplication1
Many thanks in advance.
btnAdd_Click is an event handler, you can't change its predefined signature
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim Success as string
Call AddUser(Success)
MsgBox(" " & Success & " ")
End Sub
remove the Success variable from the declaration and insert as local variable inside the event handler. Of course, if you need that variable also outside the click event, then you need to declare it at form global level
If you want to just send success thru the signature, you can always do an optional call within the signature. (Ex:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs, Optional ByRef Success As String = Nothing ) Handles btnAdd.Click
If Success IsNot Nothing then
Call AddUser(Success)
MsgBox(" " & Success & " ")
End If
End Sub
If you use the optional keyword, and after sender and e, you should have no problems at all with your current way of doing things.
Related
I get this SQL Server error and I can't figure out where the trouble is:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
xception Details: System.Data.SqlClient.SqlException: 'Incorrect syntax near ''.'
Source Error: Line: 46
Error Line: cmdsql.ExecuteNonQuery()
Code:
Dim connexcel As OleDbConnection
Dim daexcel As OleDbDataAdapter
Dim dsexcel As DataSet
Dim cmdexcel As OleDbCommand
Dim drexcel As OleDbDataReader
Dim connsql As SqlConnection
Dim dasql As SqlDataAdapter
Dim dssql As DataSet
Dim cmdsql As SqlCommand
Dim drsql As SqlDataReader
Private Sub import_excel_to_sql_server_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CenterToScreen()
End Sub
Private Sub BtnImpExcelFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnImpExcelFile.Click
On Error Resume Next
OpenFileDialog1.Filter = "(* .xls) | * .xls | (*. Xlsx) | *. xlsx | All files (*. *) | *. * "
OpenFileDialog1.ShowDialog()
FileAdd.Text = OpenFileDialog1.FileName
connexcel = New OleDbConnection("provider = Microsoft.ace.OLEDB.12.0; data source =" & FileAdd.Text & "; Extended Properties = Excel 8.0;")
connexcel.Open()
Dim dtSheets As DataTable = connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
Next
For Each sheet As String In listSheet
ExcelSheetList.Items.Add(sheet)
Next
End Sub
Private Sub ExcelSheetList_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcelSheetList.SelectedIndexChanged
daexcel = New OleDbDataAdapter("select * from [" & ExcelSheetList.Text & "]", connexcel)
dsexcel = New DataSet
daexcel.Fill(dsexcel)
DGVImpData.DataSource = dsexcel.Tables(0)
DGVImpData.ReadOnly = True
End Sub
Sub connections()
connsql = New SqlConnection("data source =. \ MSSMLBIZ; initial catalog = MyInvoice; integrated security = true")
connsql.Open()
End Sub
Private Sub BtnSaveImpData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSaveImpData.Click
For line As Integer = 0 To DGVImpData.RowCount - 2
Call connections()
Dim save As String = "insert into InvoiceData values ('" & DGVImpData.Rows(line).Cells(0).Value & "', '" & DGVImpData.Rows(line).Cells(1).Value & "')"
cmdsql = New SqlCommand(save, connsql)
cmdsql.ExecuteNonQuery()
Next
MsgBox("data saved successfully")
DGVImpData.Columns.Clear()
End Sub
Keep your database objects local so you can be sure they are closed and disposed. Enclosing these objects with `Using...End Using blocks will accomplish this even if there is an error. You don't need variables for DataAdapters, DataSets, or DataReaders. I suggest only one form level variable for the Excel connection string since it is used in 2 methods.
A little bit of Linq will get the retrieved sheet names from the DataTable and fill an array. The array can then be passed to the list box with .AddRange.
I wouldn't use the SelectedIndexChanged event because the user can too easily click the wrong sheet or change their mind. I used a Button.Click event to fill the grid.
The Sql connection string looks strange to me. I suggest you test it separately. If it doesn't work, this is a good resource. https://www.connectionstrings.com/
I would specifically state the column names in the Insert statement. Replace FirstColumnName and SecondColumnName with the real column names. The parameter names can be anything you wish as long as the names in the statement match the names in the Parameters.Add method. I have guessed at the datatypes and the size. Check your database for correct values.
We add the parameters only once outside the loop then change only values inside the loop.
Private ExcelConString As String
Private Sub BtnImpExcelFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnImpExcelFile.Click
Dim strFileName As String
Dim dtSheets As DataTable
OpenFileDialog1.Filter = "(* .xls) | * .xls | (*. Xlsx) | *. xlsx | All files (*. *) | *. * "
OpenFileDialog1.ShowDialog()
strFileName = OpenFileDialog1.FileName
ExcelConString = "provider = Microsoft.ace.OLEDB.12.0; data source =" & strFileName & "; Extended Properties = Excel 8.0;"
Using connexcel = New OleDbConnection(ExcelConString)
connexcel.Open()
dtSheets = connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
End Using
Dim exSheets() As Object = (From dRow In dtSheets.AsEnumerable() Select dRow("TABLE_Name")).ToArray
ExcelSheetList.Items.AddRange(exSheets)
End Sub
Private Sub DisplayData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DisplayData.Click
Dim dt As New DataTable
Using cn As New OleDbConnection(ExcelConString)
'In older versions of Visual Studio you may have to use String.Format instead of the interpolated string.
Using cmd As New OleDbCommand($"select * from [{ExcelSheetList.Text}];", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DGVImpData.DataSource = dt
DGVImpData.ReadOnly = True
End Sub
Private Sub BtnSaveImpData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSaveImpData.Click
Using cn As New SqlConnection("data source =. \ MSSMLBIZ; initial catalog = MyInvoice; integrated security = true")
Using cmd As New SqlCommand("Insert Into InvoiceData (FirstColumnName, SecondColumnName) Values (#FirstColumn, #SecondColumn);", cn)
cmd.Parameters.Add("#FirstColumn", SqlDbType.VarChar, 100)
cmd.Parameters.Add("#SecondColumn", SqlDbType.VarChar, 100)
cn.Open()
For line As Integer = 0 To DGVImpData.RowCount - 2
cmd.Parameters("#FirstColumn").Value = DGVImpData.Rows(line).Cells(0).Value
cmd.Parameters("#SecondColumn").Value = DGVImpData.Rows(line).Cells(1).Value
cmd.ExecuteNonQuery()
Next
End Using
End Using
MsgBox("data saved successfully")
DGVImpData.Columns.Clear()
End Sub
As to error handling... On Error Resume Next is generally not used in new code. We have Try...Catch...Finally blocks. After your code is running add these blocks where needed.
EDIT
To use String.Format...
Using cmd As New OleDbCommand(String.Format("select * from [{0}];", ExcelSheetList.Text))
The first parameter is the string in which you wish to place variables. It contains indexed placeholders enclosed in braces. The following parameters are the variables you want for the placeholder substitution.
Thank you for helping me to a fixed error in my code. Here is Final code without System.Data.SqlClient.SqlException: 'Incorrect syntax near ''.' error.
Now I tried to improve code with the last section(mention below) to define parameters for exporting data. Because I have a large number of data for exporting to SQL Server I get a Timeout error. Can anyone be able to improve code for quick exporting data to SQL Server?
connsql.Open() "System.InvalidOperationException: 'Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.'"
Dim connexcel As OleDbConnection
Dim daexcel As OleDbDataAdapter
Dim dsexcel As DataSet
Dim cmdexcel As OleDbCommand
Dim drexcel As OleDbDataReader
Dim connsql As SqlConnection
Dim dasql As SqlDataAdapter
Dim dssql As DataSet
Dim cmdsql As SqlCommand
Dim drsql As SqlDataReader
Private Sub Import_excel_to_sql_server_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CenterToScreen()
End Sub
Private Sub PKGAbtnImpExcelFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PKGAbtnImpExcelFile.Click
On Error Resume Next
'OpenFileDialog1.Filter = "(*.xls)|*.xls|(*.xlsx)|*.xlsx|All files (*.*)|*.*"
PKGAofdImpOpenExcel.ShowDialog()
PKGAtxtImpFileAdd.Text = PKGAofdImpOpenExcel.FileName
connexcel = New OleDbConnection("provider=Microsoft.ace.OLEDB.12.0;data source=" & PKGAtxtImpFileAdd.Text & ";Extended Properties=Excel 8.0;")
connexcel.Open()
Dim dtSheets As DataTable = connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
Next
For Each sheet As String In listSheet
PKGAtxtImpExlSheetL.Items.Add(sheet)
Next
End Sub
Private Sub PKGAtxtImpExlSheetL_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PKGAtxtImpExlSheetL.SelectedIndexChanged
daexcel = New OleDbDataAdapter("select * from [" & PKGAtxtImpExlSheetL.Text & "]", connexcel)
dsexcel = New DataSet
daexcel.Fill(dsexcel)
PKGAdgvImpData.DataSource = dsexcel.Tables(0)
PKGAdgvImpData.ReadOnly = True
End Sub
'Last Section
Sub Connectonsql()
connsql = New SqlConnection("Data Source=DESKTOP-MIQGJTK\MSSMLBIZ;Initial Catalog=PkGlobalAccounting;Integrated Security=True")
connsql.Open()
End Sub
Private Sub PKGAbtnImpSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PKGAbtnImpSave.Click
For Line As Integer = 0 To PKGAdgvImpData.RowCount - 2
Call Connectonsql()
Dim save As String = "insert into Test values('" & PKGAdgvImpData.Rows(Line).Cells(0).Value & "','" & PKGAdgvImpData.Rows(Line).Cells(1).Value & "')"
cmdsql = New SqlCommand(save, connsql)
cmdsql.ExecuteNonQuery()
Next
MsgBox("Data Saved Successfully")
PKGAdgvImpData.Columns.Clear()
End Sub
Thanks for Your Help.
I've got two databases in SQL Server where one database (ConfigDb) references other (DataDb). Many of stored procedures and functions in ConfigDb uses tables and functions/SPs in DataDb. They are referenced like [DataDb].[dbo].[the_object].
Now, I would need to clone the databases to test version, i.e. restore them from backups as ConfigDb_Test and DataDb_Test. Obviously, ConfigDb_Test references DataDb, not the DataDb_Test.
Any tips how to handle this better than opening SP by SP and edit manually?
EDIT
For refernce, I put the utility at GitHub
OK, it is in VB (not c#) -- and I'm not a .net guy, so I'm sure there's a better way to do this.
I caution you to step through and observe the code work, but I use this a lot, and it works great!
Once you enter your servername/credentials, a list of db's will appear (system db's are excluded). Select the db's you want to run against (check list) and enter the find/replace text strings. When you click start, each proc will be opened/scanned, and a REPLACE() is run on matching strings -- so be careful what you put in the FIND/REPLACE text boxes!
Here it goes...
Please, be careful with this, and use at your own risk.
form2.vb
Object Names (in order)
cmbServer (Combo Box)
chkSSPI (Check Box)
txtUser (Text Box)
txtPass (Text Box)
btnConnect (Button)
btnExit (Button)
Code Behind:
Imports System.Data.SqlClient
Public Class Form2
Public objConn As SqlConnection = New SqlConnection()
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cmbServer.SelectedIndex = 0
chkSSPI.Checked = True
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Application.Exit()
End Sub
Private Sub chkSSPI_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkSSPI.CheckedChanged
txtUser.Enabled = Not chkSSPI.Checked
txtPass.Enabled = Not chkSSPI.Checked
txtUser.Select()
End Sub
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
If chkSSPI.Checked = False Then
objConn.ConnectionString = String.Format("Data Source={0};Initial Catalog=master;User ID={1};Password={2};", cmbServer.Text, txtUser.Text, txtPass.Text)
Else
objConn.ConnectionString = String.Format("Data Source={0}; Initial Catalog=master; Integrated Security=SSPI", cmbServer.Text)
End If
Dim frm2 As Form = New frmDBList()
Try
objConn.Open()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Hide()
frm2.Show()
End Sub
Private Sub txtUser_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtUser.TextChanged
End Sub
End Class
frmDBList.vb
Object Names (in order):
clbDatabase (Checked List Box)
txtFind (Text Box)
txtReplace (Text Box)
lblDBName (Label)
lblProcNum (Label) [0]
lblProcCount (Label) [123]
lblProcName (Label)
btnCheckAll (Button)
btnUnCheckAll (Button)
btnStart (Button)
btnClose (Button)
Code Behind:
Imports System.Data.SqlClient
Imports System.IO
Public Class frmDBList
Dim procText As String
Dim procList As New ArrayList
Dim errorLog As New ArrayList
Dim dbcount As Int16
Dim proccount As Int16
Dim replacecount As Int16
Dim procupdate As Boolean
Public Sub LogError(ByVal text As String, ByVal dbname As String, ByVal procname As String)
errorLog.Add("db=" + dbname + " proc=" + procname + " error=" + text)
End Sub
Public Sub SaveLog()
Dim datetime As String = Now.ToString()
datetime = Replace(datetime, "/", "")
datetime = Replace(datetime, ":", "")
Dim filename As String = "c:\procchanger_errorlog " + datetime + ".txt"
Dim objWriter As New System.IO.StreamWriter(filename)
For c As Int16 = 0 To errorLog.Count - 1
objWriter.WriteLine(errorLog(c).ToString())
Next
objWriter.Close()
End Sub
Public Sub AddListBoxItem(ByVal Item As Object, ByVal Check As Boolean)
clbDatabase.Items.Add(Item, Check)
End Sub
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
btnStart.Enabled = False
btnClose.Enabled = False
errorLog.Clear()
dbcount = 0
proccount = 0
replacecount = 0
grpProgress.Visible = True
If clbDatabase.SelectedItems.Count = 0 Then
MsgBox("Please select at least one database to process.", vbOKOnly)
Else
For i As Integer = 0 To clbDatabase.Items.Count - 1
If clbDatabase.GetItemChecked(i) = True Then
lblDBName.Text = clbDatabase.Items(i).ToString()
dbcount += 1
procList.Clear()
GetProcList(clbDatabase.Items(i).ToString())
End If
Next
MsgBox("Complete. Replaced " + replacecount.ToString() + " occurrences, in " + proccount.ToString() + " stored procedures, across " + dbcount.ToString() + " databases.")
If errorLog.Count > 0 Then
SaveLog()
End If
grpProgress.Visible = False
For i As Integer = 0 To clbDatabase.Items.Count - 1
clbDatabase.SetItemChecked(i, CheckState.Unchecked)
Next
End If
If Form2.objConn.State = ConnectionState.Open Then Form2.objConn.Close()
btnStart.Enabled = True
btnClose.Enabled = True
End Sub
Public Sub GetProcList(ByVal dbname As String)
If Form2.objConn.State = ConnectionState.Closed Then
If Form2.chkSSPI.Checked = False Then
Form2.objConn.ConnectionString = String.Format("Data Source={0};Initial Catalog=" + dbname + ";User ID={1};Password={2};", Form2.cmbServer.Text, Form2.txtUser.Text, Form2.txtPass.Text)
Else
Form2.objConn.ConnectionString = String.Format("Data Source={0}; Initial Catalog=" + dbname + "; Integrated Security=SSPI", Form2.cmbServer.Text)
End If
Try
Form2.objConn.Open()
Catch ex As Exception
LogError(ex.Message, dbname, "")
End Try
End If
Try
Dim sqlcmd = "select name from sysobjects where xtype='P' and name not like 'dt_%'"
Using cmd As New SqlCommand(sqlcmd, Form2.objConn)
Using reader = cmd.ExecuteReader()
If reader.HasRows Then
While reader.Read()
procList.Add(reader("name").ToString())
End While
End If
End Using
End Using
Catch ex As Exception
LogError(ex.Message, dbname, "")
End Try
lblProcCount.Text = procList.Count
proccount = procList.Count
For c = 0 To procList.Count - 1
lblProcNum.Text = c.ToString()
lblProcName.Text = procList(c).ToString()
Refresh()
procupdate = False
AlterProc(dbname, procList(c).ToString())
Next
If Form2.objConn.State = ConnectionState.Open Then Form2.objConn.Close()
End Sub
Public Sub AlterProc(ByVal dbname As String, ByVal procname As String)
If Form2.objConn.State = ConnectionState.Closed Then
If Form2.chkSSPI.Checked = False Then
Form2.objConn.ConnectionString = String.Format("Data Source={0};Initial Catalog=" + dbname + ";User ID={1};Password={2};", Form2.cmbServer.Text, Form2.txtUser.Text, Form2.txtPass.Text)
Else
Form2.objConn.ConnectionString = String.Format("Data Source={0}; Initial Catalog=" + dbname + "; Integrated Security=SSPI", Form2.cmbServer.Text)
End If
Try
Form2.objConn.Open()
Catch ex As Exception
LogError(ex.Message, dbname, "")
End Try
End If
Try
Dim sqlcmd = "select * from " + dbname + ".dbo.sysobjects o inner join " + dbname + ".dbo.syscomments c on o.id = c.id where name='" + procname + "'"
Using cmd As New SqlCommand(sqlcmd, Form2.objConn)
procText = ""
Using reader = cmd.ExecuteReader()
If reader.HasRows Then
While reader.Read()
procText = procText + reader("text")
End While
End If
End Using
Dim arrProcData() = Split(procText, vbNewLine)
Dim c As Integer
procText = ""
For c = 0 To UBound(arrProcData)
If InStr(UCase(arrProcData(c)), "CREATE") > 0 And InStr(UCase(arrProcData(c)), "PROCEDURE") > 0 Then
arrProcData(c) = Replace(Replace(Replace(arrProcData(c), "CREATE", "ALTER"), "create", "alter"), "Create", "Alter")
End If
If InStr(UCase(arrProcData(c)), UCase(txtFind.Text)) > 0 Then
arrProcData(c) = Replace(UCase(arrProcData(c)), UCase(txtFind.Text), UCase(txtReplace.Text))
replacecount += 1
procupdate = True
End If
procText = procText + arrProcData(c) + vbNewLine
Next
End Using
Catch ex As Exception
LogError(ex.Message, dbname, procname)
End Try
If procupdate = True Then
Try
Dim sqlcmd = procText
Using cmd As New SqlCommand(sqlcmd, Form2.objConn)
cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
LogError(ex.Message, dbname, procname)
End Try
End If
End Sub
Private Sub frmDBList_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
grpProgress.Visible = False
Try
Dim sqlcmd = "select name from master.dbo.sysdatabases where name not in ('msdb','master','temdb')"
Using cmd As New SqlCommand(sqlcmd, Form2.objConn)
Using reader = cmd.ExecuteReader()
If reader.HasRows Then
While reader.Read()
AddListBoxItem(reader("name").ToString(), CheckState.Unchecked)
End While
End If
End Using
End Using
Catch ex As Exception
LogError(ex.Message, "master", "")
End Try
Form2.objConn.Close()
End Sub
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
Application.Exit()
End Sub
Private Sub btnCheckAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheckAll.Click
For i As Integer = 0 To clbDatabase.Items.Count - 1
clbDatabase.SetItemChecked(i, CheckState.Checked)
Next
End Sub
Private Sub btnUnCheckAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUnCheckAll.Click
For i As Integer = 0 To clbDatabase.Items.Count - 1
clbDatabase.SetItemChecked(i, CheckState.Unchecked)
Next
End Sub
End Class
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
I've been working on a computing project in Visual Basic 2010 and I've encountered a error and I cannot find the problem causing it.
Whenever I try to save to my database I get a error in my OleDBConnection.vb form with the following
This is my Code
Class OleDbConnection
Private _p1 As Object
Sub New(ByVal p1 As Object)
' TODO: Complete member initialization
_p1 = p1
End Sub
Sub Close()
Throw New NotImplementedException
End Sub
Sub Open()
**Throw New NotImplementedException**
End Sub
End Class
my original code for the saving of the project to the database is
Public Class AddClass
Public Shared connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\Sami\Desktop\F454\VB_PrototypeDB.accdb;Persist Security Info=False;"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub DataView()
Throw New NotImplementedException
End Sub
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
Me.Hide()
MMenu.Show()
End Sub
Private Sub PictureBox2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox2.Click
Dim cn As New OleDbConnection(connectionString)
cn.Open()
Dim ClassName As String = TextBox1.Text
Dim Subject As String = ComboBox1.Text()
Dim cmd As New OleDbCommand("INSERT INTO Class (ClassName, Subject) VALUES ('" & ClassName & "', '" & Subject & "') ')", cn)
cmd.ExecuteNonQuery()
cn.Close()
Call MsgBox("Student Has Been Saved", 0, "Student Database")
End Sub
End Class
I know that you guys will find this simple, but can anyone tell me why I am getting a syntax error despite following every instruction on numerous sites?
My code in full is:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = F:\Brett\Programming Projects\Roster\Roster.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
' This is grabbing all the records from the listing table in the Roster Database
sql = "Select * FROM Listing"
' Or selected columns
'sql = "SELECT Listing.FName, Listing.LName FROM Listing"
da = New OleDb.OleDbDataAdapter(sql, con)
' Populate the dataset with the data adaptor. This can be any name
da.Fill(ds, "Roster")
con.Close()
MaxRows = ds.Tables("Roster").Rows.Count
inc = -1
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim iRow As Integer = Me.Label1.Text
Dim junk As Integer
ds.Tables("Roster").Rows(iRow).Item(5) = Me.TextBox3.Text
ds.Tables("Roster").Rows(iRow).Item(6) = Me.TextBox4.Text
ds.Tables("Roster").Rows(iRow).Item(8) = Me.TextBox5.Text
da.Update(ds, "Roster")
'da.Update(ds)
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim newtbl As DataTable
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim cmd As New OleDb.OleDbCommand
newtbl = ds.Tables("Roster")
Dim drCurrent As DataRow
drCurrent = newtbl.NewRow()
drCurrent(1) = "sfd"
drCurrent(2) = "werter"
newtbl.Rows.Add(drCurrent)
da.Update(ds, "Roster")
End Sub
No matter what I do, I get this error message. Any help will be greatly appreciated as this is two days now...
I would show you my error but as usual, some peanut won't let me without some crap.. It states OleDbException was unhandled, Syntax error in Insert Into statement.
Can you try wrapping your database calls in a try-catch block and inspect the InnerXml that's returned with the exception?
That might give you more information about the error that you're getting.