Showing posts with label Tutorial. Show all posts
Showing posts with label Tutorial. Show all posts

Friday, March 16, 2012

Play an audio file in VB.NET







Today we are going to play wav file in vb.net and spell the number using audio files. using winmm.dll, about winmm.dll, it is a module for the Windows Multimedia API, which contains low-level audio and joystick functions and we start to create the application follow the instructions below

Create a Windows Application
  1.   Start Microsoft Visual Studio .NET.
  2.   On the File menu, point to New, and then click Project.
  3.   And Project Types, click Visual Basic Projects.
  4.   Under Templates, click Windows Application.
  5.   Create your project name, type Project1, and then click OK
  6.   Design your form just like the picture below

create module with right clict in the project choose add and add new modul create modul name, type bassSound then we’re going to put this in our code:

we play sound using SND_NOSTOP flags this function will immediately return False without playing the requested sound.
Code:
Option Strict Off
Option Explicit On
Module bassSound
    Public Const SND_NOSTOP As Integer = &H10
    Public Declare Function sndPlaySound Lib "winmm.dll" Alias "sndPlaySoundA" (ByVal lpszSoundName As String, ByVal uFlags As Integer) As Integer
End Module

Specifies options for playing the sound using one or more of the following flags 
SND_SYNC: The sound is played synchronously and the function does not return until the sound ends
SND_ASYNC: The sound is played asynchronously and the function returns immediately after beginning the sound.
SND_NODEFAULT: If the sound cannot be found, the function returns silently without playing the default sound.
SND_LOOP: The sound will continue to play repeatedly until ' sndPlaySound is called again with the lpszSoundName$ parameter set to null, You must also specify the SND_ASYNC flag to loop sounds. 


create module type with spell and put the code below                                                                                       
Code:
Option Strict Off
Option Explicit On
Module spell
    Public Function say(ByRef Value As Integer) As String

        Select Case Value
            Case 0 : say = " zero"
            Case 1 : say = " one"
            Case 2 : say = " two"
            Case 3 : say = " three"
            Case 4 : say = " four"
            Case 5 : say = " five"
            Case 6 : say = " six"
            Case 7 : say = " seven"
            Case 8 : say = " eight"
            Case 9 : say = " nine"
            Case 10 : say = " ten"
            Case 11 : say = " eleven"
            Case 12 : say = " twelve"
            Case 13 : say = " thirteen"
            Case 14 To 19 : say = say(Value Mod 10) & " teen"
                '.....
        End Select
    End Function
End Module

In the main form we choose the button1, we're using handle click events or double click button1,to call
function module "say"

Code:
TextBox2.Text = Trim(say(CInt(TextBox1.Text)))

And we turn to button2 same as the button1,we're using handle click events or double click, to call function moudle "sndPlaySound", we call the name to play the sound
Code:
Dim i As Object
Dim path(1) As String
Dim arr() As String
arr = Split(TextBox2.Text, " ")
   For i = LBound(arr) To UBound(arr)
       Call sndPlaySound(path(1) + "Sounds\" & arr(i) + ".wav", SND_NOSTOP)
   Next

plus button and less button put this in our coude
Code:
TextBox1.Text = CStr(Val(TextBox1.Text) + 1)
TextBox1.Text = CStr(Val(TextBox1.Text) - 1)


wav files sourcecode

Monday, March 12, 2012

Reading and Writing XML in VB.net



how to store the data on listboxt and when you open the application, the data is still there , I searched on google how to do it, it turns out that using xmlrader and write it back use xmltextrwiter, the original code is not belongs to me,but I'll explain how it works with vb.net .

the code below represent how to read each of the element of xml, and write it into listbox.

Code:
Dim XMLReader As Xml.XmlReader
 XMLReader =New Xml.XmlTextReader("text.xml")'you also can change the directory from xml
   While XMLReader.Read                      'ex. ("Data\xmldata text.xml")
     Select Case XMLReader.NodeType          'selecet the node (file) from text.xml
         Case Xml.XmlNodeType.Element
            If XMLReader.AttributeCount > 0 Then 'xmlraeder will start from zero
              While XMLReader.MoveToNextAttribute
                 If XMLReader.Name = "File" Then
                    ListBox1.Items.Add(XMLReader.Value)'looping and add each of the elem                                                       'ent into listbox
                 Else
                 End If
              End While
            End If
     End Select
   End While
XMLReader.Close()

and how write it back and save into xml file, you can use the code below.

Code:
 Dim XMLobj As Xml.XmlTextWriter
 Dim ue As New System.[Text].UnicodeEncoding    'unicode 
 XMLobj = New Xml.XmlTextWriter("text.xml", ue) 'rewrite text.xml
 XMLobj.Formatting = Xml.Formatting.Indented
 XMLobj.Indentation = 3
 XMLobj.WriteStartDocument()   'xml will be declared with the xml version="1.0"
 XMLobj.WriteStartElement("List") ' write the node (file)
 Dim i As Integer
  For i = 0 To ListBox1.Items.Count - 1 'looping and  XmlTextWriter will be begun from listbox.value(0)        
     XMLobj.WriteStartElement("Text")   'from text.xml
     Dim temp As String = ""            
     ListBox1.SetSelected(i, True)
     temp = ListBox1.SelectedItem
     XMLobj.WriteAttributeString("File", temp)
     XMLobj.WriteEndElement()
  Next
 XMLobj.WriteEndElement()
 XMLobj.Close() 

besides xml you can also use my.setting  as a dynamic storage you can find it in project properties


My.Setting
to read and display
Code:
Me.TextBox1.Text = My.Settings.IPAddress
and rewrite
My.Settings.IPAddress = Me.TextBox1.Text 


sourcecode

Saturday, March 10, 2012

Creating a Report with Crystal Reports VB Net






This tutorial will help you to create a report with crystal report, we create ADO OLE DB as a connection string, to create a simple report with crystal report using  ADO OLE DB Connection string, follow the instructions, first we use sqlserver as a database and crystal report as our report. add your crystal report with right click on your current project properties > add  > new items then click and select reporting choose cystal report then ok.

Create crystal report a
and will show crystal reports gallery, choose "as a blank report" then ok, to select the connections string properties, right click the database fields in the field explorer located in your project left design and choose database expert.

Create crystal report b

microsoft provides many more available connections string, to hook up your sql server database with oledb(ado), create new connection > ole db (ado)  > make new connection > microsoft oledb provide for sql server.


create crystal report c

then click next to continue will show you to manage the connection string, fill the server name with your server connection, check the integrated securty if you connect using localhost, select the database that you want to select in the database field then click finish, ok now we have a connection string with provided connection by sql server, and we going to choose our table for crystal report design, choose the server name "192.168.1.1/sqlexpress"  > database > dbo > select your table by clicking the arrow, then click ok.


create crystal report d

now we have our current table,to put the field from the table in your crystal report design,choose the table, select field by using "drag and drop" you will get more tools design with right click in your report or from the toolbox on bottom left.
Cystral report design

ok now we take a look "windows form" in our project if you dont have it one right click on the current project, create with "add new" > "add windows form", create the same as the picture below by adding two datetimepicker,a button and a crystalreportviewer double click your button insert the code below.

Code:
        Dim Conn As New SqlClient.SqlConnection
        Dim Da As New SqlClient.SqlDataAdapter
        Dim ds As New DataSet
        Dim strConnection As String
        Dim SQL As New SqlClient.SqlCommand
        strConnection = "Data Source=192.168.1.1\SQLEXPRESS;Initial Catalog=Contoh; 
        User=admin; Pwd=1"
        Conn = New SqlClient.SqlConnection(strConnection)
        Conn.Open()
        SQL.Connection = Conn
        SQL.CommandText = "Select * From grafik Where tanggal between'" & 
        Format(DateTimePicker1.Value, "MM/dd/yyyy") & "' and '" &   
        Format(DateTimePicker2.Value, "MM/dd/yyyy") & "'order by Nomor asc "
        Da.SelectCommand = SQL
        Da.Fill(ds, "grafik")
        Dim a As New report 'your crystal report
        Dim b As New Reportform
        a.SetDataSource(ds.Tables!grafik) 'binding your cristal report to the datasource
        b.GroupBox1.Visible = False
        b.CrystalReportViewer1.Visible = True
        b.CrystalReportViewer1.ReportSource = a
  b.Refresh()
        b.WindowState = FormWindowState.Maximized
        b.Show()


form design

from the code I ask of the code to select between two date from the data in the table, the database relates with this article Insert,Save,Update dan Delete pada VB net

crystal report viewer
hope this article will help you.

sourcecode


Friday, March 9, 2012

Insert, Select, Update and Delete in VB.net db sqlserver



Form Penjualan


bagaimana mengeksekusi perintintah query sederhana seperti insert,update, delete dan select pada visual basic. net ??
disini saya menggunakan database sqlserver database dan table bisa di lihat pada artikel ini membuat database sederhana, buatlah project baru pada visual studio anda dan pada form buat tampilan  seperti tampilan gambar disamping,
jika anda telah selesai double click pada button insert copy paste kode berikut ini untuk perintah insert.

Code:
        Dim Str As String = "Data Source=192.168.1.1\SQLEXPRESS;Initial Catalog=Contoh;User=admin; Pwd=1"
        Try
            Dim cnt As New SqlClient.SqlConnection(Str) ' manambahkan connection string pada 
            client
            Dim cmd As New SqlClient.SqlCommand ' menambahkan printah query pada client yang   
            akan di eksekusi di database
            cnt.Close()
            cnt.Open()
            With cmd
                .Connection = cnt
                .CommandText = "insert into grafik (nomor, penjualan, tanggal) values('" &          
                 TextBox1.Text & "','" & TextBox2.Text & "','" & Format(DateTimePicker1.Value.Date,
                 "yyyy/MM/dd") & "')"
               .ExecuteNonQuery()
            End With
            cnt.Close()
            MsgBox("Data penjualan telah tersimpan", MsgBoxStyle.Information)
            TextBox1.Text = ""
            TextBox2.Text = ""
            DateTimePicker1.Value = Date.Now
            TextBox1.Focus()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try

Insert
untuk printah select, double click button select anda ketikan coding dibawah ini.

Code:
 
       Dim Str As String = "Data Source=192.168.1.1\SQLEXPRESS;Initial Catalog=Contoh;User=admin; Pwd=1"
        Dim cari As String
        cari = InputBox("masukan nomor yang anda cari ", "Konfirmasi")
        Try
            Dim cnt As New SqlClient.SqlConnection(Str)
            Dim cmd As New SqlClient.SqlCommand
            Dim read As SqlClient.SqlDataReader
            cnt.Close()
            cnt.Open()
            With cmd
                .Connection = cnt
                .CommandText = "select * from grafik where nomor ='" & cari.Trim & "'"
                read = cmd.ExecuteReader(CommandBehavior.SingleRow)
                If read.Read Then
                    TextBox1.Text = read.GetValue(0)
                    TextBox2.Text = read.GetString(1)
                    DateTimePicker1.Value = read.GetDateTime(2)
                Else
                    MsgBox("nomor tidak ada pada table grafik ", MsgBoxStyle.Information)
                End If
            End With
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try
   
Select
untuk perintah update tentunya anda harus tau terlebih mengetahui dahulu data yang ingin anda update, maka dari itu kita membutuhkan perintah select untuk mengetahui data yang ingin kita update, kita telah membuat perintah select sebelumnya maka kita panggil saja Button2_click atau Select_click
dan logika yang kita butuhkan
        kita butuh klik dua kali pada button update klik pertama untuk perintah select atau mengetahui data mana yang anda ingin perbarui dan klik kedua eksekusi printah update anda  lihat koding dibawah ini .

Code:
     If Button3.Text = "Perbaiki" ThenDim Str As String = "Data Source=192.168.1.1\SQLEXPRESS;Initial Catalog=Contoh; 
            User=admin; Pwd=1"
            Try
                Dim cnt As New SqlClient.SqlConnection(Str)
                Dim cmd As New SqlClient.SqlCommand
                cnt.Close()
                cnt.Open()
                With cmd
                    .Connection = cnt
                    .CommandText = "Update grafik set Penjualan='" & TextBox2.Text & "',tanggal='" & 
                     Format(DateTimePicker1.Value, "yyyy/MM/dd") & "' where nomor='" & TextBox1.Text & "'"
                    .ExecuteNonQuery()
                End With
                cnt.Close()
                MsgBox("Data penjualan telah diperbaiki", MsgBoxStyle.Information)
                TextBox1.Text = ""
                TextBox2.Text = ""
                DateTimePicker1.Value = Date.Now
                Button3.Text = "Update"
                TextBox1.Focus()
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical)
            End Try
            Exit Sub
        End If

Code:
Button2_Click(sender, e)
Button3.Text = "Perbaiki"


Update
Warna abu-abu itu logika pertama atau untuk mengupdate data dan logika kedua warna orange  atau untuk select data yang ingin kita update. anda juga bisa menggunakan cara seperti boolean atau cara anda sendiri.


Untuk perintah delete pada database kasusnya sama seperti update, anda harus tau data yang anda ingin hapus, dan eksekusi perintah delete query seperti code dibawah ini untuk menghapus record data anda.
Code:
.CommandText = "delete grafik where nomor='" & TextBox1.Text & "'"

Untuk melihat data pada tabel tambahkan datagirdview pada toolbox anda dan ketik koding berikut ini.
Code:
        
        Dim Str As String = "Data Source=192.168.1.1\SQLEXPRESS;Initial Catalog=Contoh; 
        User=admin; 
        Pwd=1"
        DataGridView1.Visible = True
        Dim cnt As New SqlClient.SqlConnection(Str)
        Dim cmd As New SqlClient.SqlCommand
        Dim db As New SqlClient.SqlDataAdapter
        Dim ds As New DataSet
        cnt.Close()
        cnt.Open()
        With Cmd
            .Connection = cnt
            .CommandType = CommandType.Text
            .CommandText = "Select * From grafik order by Nomor asc"
            db = New SqlClient.SqlDataAdapter
            db.SelectCommand = cmd
            ds = New DataSet
            db.Fill(ds, "grafik")
            DataGridView1.DataSource = ds
            DataGridView1.DataMember = "grafik"
        End With
        cnt.Close()

datagirdview

Wednesday, March 7, 2012

Simple sql database and table in sql server

                                         
Create database pada sqlserver bagaimana ??
Ok disini saya menggunakan sqlserver 2005, dan silahkan click "Connect" pada database anda, mulailah untuk membuat Query baru, dan cobalah untuk membuat table yang ada perlukan untuk apalikasi kita. 

Selamat mencoba..

Ohh iyaa sqlserver nga case sensitive huruf besal atau kecil di anggapnya sama, silahkan membuat query baru dan ketikan baris query berikut ini.







Create database Contoh -- membuat database dengan nama contoh
Use contoh -- Semua eksekusi perintah sql akan diterapkan pada database contoh


create table grafik(
nomor int primary key,
Penjualan int,
tanggal datetime
)


insert into grafik values ('1','900','2012/03/01')
insert into grafik values ('2','200','2012/03/02')
insert into grafik values ('3','190','2012/03/03')
insert into grafik values ('4','100','2012/03/04')
insert into grafik values ('5','120','2012/03/05')
insert into grafik values ('6','150','2012/03/06')



select * from grafik
update grafik set penjualan='Naik' where tanggal='2012/03/08'
select top 8 penjualan  from grafik where tanggal between   '2012/03/01' and '2012/03/01'



Untuk menjalankan Query yang kita buat cukup di blok Seperti dilihat di gambar ini dan tekan F5.


dan anda dapat membuat perintah Query sederhana seperti Select, Update, Delete, Insert, dan peritah struktur lainnya seperti trigger ataupun store procedure.

Grafik VB.net menggunakan tool mschart



Grafik


Bagaimana cara membuat grafik pada aplikasi yang akan kita buat dengan berbasis client - server ??
semoga artikel ini dapat membantu anda bagaimana cara membuat membuat grafik  berbasis database.


Saya develop aplikasi ini menggunakan Visual studio 2008, Sebagai database saya menggunakan sqlserver untuk membuat tabel pada sql server, silahkan lihat ini membuat database sederhana. mulailah untuk membuat project baru pada Visual studio anda,
pada  file > new > new project > visual basic buatlah window form, pastikan toolbox telah teriinstal mschart, jika mschart belum terinstal pada visual studio anda, anda dapat mendownload nya disini MSchart.


setelah mschart terinstal lakukan langkah-langkah ini untuk menampilkan mschart di toolbox
klik kanan pada toolbox pilih choose items.. klik Browse  ke directory C:\Program Files\Microsoft Chart Controls\Assemblies pilih System.Windows.Forms.DataVisualization.dll kilk ok, Pastikan Chart tercentang lalu ok.
Toolbox chart

drag chart ke windows form atau double click, anda dapat menambahkan beberapa fitur-fitur yang ada pada propertis sesuai yang ingin anda tampilkan pada form nanti


Grafik Propertis

untuk Binding data dari database ke grafik, double click form anda, masukan koding berikut ini.

        Dim Str As String = "Data Source=192.168.1.1\SQLEXPRESS;Initial Catalog=Contoh; User=admin; Pwd=1" ' String koneksi database anda
        Try
            Dim cnt As New SqlClient.SqlConnection(Str) 
            Dim cmd As New SqlClient.SqlCommand
            cnt.Open()
            cmd.Connection = cnt
            Dim Comment As String = "SELECT top 5 Penjualan, tanggal FROM grafik "
            Dim da As New SqlClient.SqlDataAdapter(Comment, cnt)
            Dim ds As New DataSet()
            da.Fill(ds, "grafik")
            Chart1.Series("Series1").XValueMember = "tanggal"
            Chart1.Series("Series1").YValueMembers = "Penjualan"
            Chart1.DataSource = ds.Tables("grafik")
            cnt.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try


      


dari perintah tersebut saya meminta pada database untuk menampilkan 5 teratas penjualan tertinggi untuk seluruh penjualan dari tanggal yang ada pada table grafik, pastikan database anda "tersimpan data" sehingga grafik dapat terlihat, database ini berkaitan dengan artikel yang dibuat sebelumnya membuat database sederhana untuk menyimpan data pada table sesuai dengan database yang anda ingin simpan anda dapat menyimpannya secara manual pada Query sql server atau melalui aplikasi seperti artikel berikut ini Insert,Save,Update dan Delete pada VB net.

sourcecode