Jumat, 25 Mei 2012

Memanggil Stored Procedure pada VB.NET dengan Parameter Input Output

Memanggil Stored Procedure pada VB.NET dengan OleDb SQL Server :

    Private Sub BtnUpdSQL_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnUpdSQL.Click
        Dim con As New SqlConnection
        con.ConnectionString = "Data Source=.\sqlexpress;Initial Catalog=btc;Integrated Security=True"
        con.Open()

        Dim cmd As New SqlCommand
        cmd.Connection = con
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "hitungGaji"

        'parameter input SP "jmlgaji"=@kode dari textboxkodedepartemen.text
        cmd.Parameters.Add("@kodedept", OdbcType.VarChar)
        cmd.Parameters("@kodedept").Direction = ParameterDirection.Input
        cmd.Parameters("@kodedept").Value = TextBoxKodeDeptMySQL.Text

        cmd.Parameters.Add("@total", OdbcType.Double)
        cmd.Parameters("@total").Direction = ParameterDirection.Output

        cmd.ExecuteNonQuery()
        

        Dim intCount As Integer = 0
        Double.TryParse(cmd.Parameters("@total").Value, intCount)

        If intCount > 0 Then TextBoxJumlahMySQL.Text = intCount.ToString 

    End Sub


Pada Odbc, memanggil Stored Procedure tidak bisa dilakukan secara langsung dengan Tipe CommandType.StoredProcedure, harus menggunakan  Memanggil Stored Procedure dengan VB.NET pada Odbc MySQL :

    Private Sub ButtonCariMySQL_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonCariMySQL.Click
        Dim con As New OdbcConnection
        Dim cmd As New OdbcCommand
        Dim lreturn As Boolean = True

            'koneksi ke sql server---------------------------------
            con.ConnectionString = "driver={mysql odbc 3.51 driver};server=localhost;database=karyawan;uid=root;password= ;"
            con.Open()

            'nama stored procedure=jmlgaji---------------------------
            cmd.Connection = con
            cmd.CommandType = CommandType.StoredProcedure
            cmd.CommandText = "call hitungGaji('" & TextBoxKodeDeptMySQL.Text & "',@total)"

            cmd.Parameters.Add("@total", OdbcType.Double)
            cmd.Parameters("@total").Direction = ParameterDirection.Output

            cmd.ExecuteNonQuery()

            'command mengambil hasil procedure hitungGaji
            Dim cmd2 As New OdbcCommand("SELECT @total", con)
            MsgBox(cmd2.ExecuteScalar.ToString)
    End Sub

ASP.NET VB Header Force Download Untuk Report Excel, MHT, HTML, Word


Jika kita ingin membuat Report Excel, MHT, HTML, Word. Bisa dilakukan dengan membuat Dokumen di Microsoft Excel atau Microsoft Word. Kemudian Save As MHT atau HTML. Kemudian ubah ekstensi filenya menjadi ASPX. Setelah itu beri coding ASP VB.NET berikut di atasnya, maka jika dijalankan akan langsung keluar perintah Download, Do You Want to Open or Save this Document. Dan jika dipilih Open maka akan langsung keluar ke Microsoft Office tergantung extensinya *.doc atau *.xls atau *.xlsx atau *.docx bahkan *.mht atau *.htm.

Untuk mengisi data dinamis pada Report tersebut mudah tinggal beri saja coding PHP di dalamnya seperti biasa misal mengambil data dari database dst.

<%@ Page Language="VB" %>
<%@ import Namespace = "System.Data.SqlClient" %>
<%@ import Namespace = "System.Data" %>
<%@ import Namespace = "System.IO" %>
<%
    Response.ClearHeaders()
    Response.AddHeader("Content-Type ", "application/download")
    Response.AddHeader("Content-Disposition", " attachment; filename=laporan.xls")
    Response.AddHeader("Content-Transfer-Encoding", "binary")
    Response.AddHeader("Expires", "0")
    Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0")
    Response.AddHeader("Pragma", "public")

  //Dim cn As SqlConnection
  //cn = new SqlConnection("Data Source=localhost;Initial Catalog=penjualan;Integrated Security=True")

  //cn.Open()
  //Dim cm As SqlCommand
  //cm = new SqlCommand("SELECT * FROM penjualan_muncul WHERE outlet = '" + System.Convert.ToString(Request.Params["outlet"]) + "' AND tanggal >= '" + tgl1 + "' AND tanggal <= '" + tgl2 + "' ORDER BY id_penjualan ASC", cn)
  //Dim rd As SqlDataReader 
  //rd = cm.ExecuteReader()
  //while (rd.Read())
  //
%>

MIME-Version: 1.0
X-Document-Type: Workbook
Content-Type: multipart/related; boundary="----=_NextPart_01CD0915.924C0070"

This document is a Single File Web Page, also known as a Web Archive file.  If you are seeing this message, your browser or editor doesn't support Web Archive files.  Please download a browser that supports Web Archive, such as Windows® Internet Explorer®.

------=_NextPart_01CD0915.924C0070
Content-Location: file:///C:/0A4A9512/barber.htm
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset="windows-1252"
....

Rabu, 23 Mei 2012

ASP.NET C# Header Force Download Untuk Report Excel, MHT, HTML, Word

Jika kita ingin membuat Report Excel, MHT, HTML, Word. Bisa dilakukan dengan membuat Dokumen di Microsoft Excel atau Microsoft Word. Kemudian Save As MHT atau HTML. Kemudian ubah ekstensi filenya menjadi ASPX. Setelah itu beri coding ASP.NET C# berikut di atasnya, maka jika dijalankan akan langsung keluar perintah Download, Do You Want to Open or Save this Document. Dan jika dipilih Open maka akan langsung keluar ke Microsoft Office tergantung extensinya *.doc atau *.xls atau *.xlsx atau *.docx bahkan *.mht atau *.htm.

Untuk mengisi data dinamis pada Report tersebut mudah tinggal beri saja coding PHP di dalamnya seperti biasa misal mengambil data dari database dst.

<%@ Page Language="C#" %>
<%@ import Namespace = "System.Data.SqlClient" %>
<%@ import Namespace = "System.Data" %>
<%@ import Namespace = "System.IO" %>
<%
    Response.ClearHeaders();
    Response.AddHeader("Content-Type ", "application/download");
    Response.AddHeader("Content-Disposition", " attachment; filename=laporan.xls");
    Response.AddHeader("Content-Transfer-Encoding", "binary");
    Response.AddHeader("Expires", "0");
    Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    Response.AddHeader("Pragma", "public");

  //public SqlConnection cn;
  //cn = new SqlConnection("Data Source=localhost;Initial Catalog=penjualan;Integrated Security=True");

    
  //cn.Open();
  //SqlCommand cm;
  //cm = new SqlCommand("SELECT * FROM penjualan_muncul WHERE outlet = '" + System.Convert.ToString(Request.Params["outlet"]) + "' AND tanggal >= '" + tgl1 + "' AND tanggal <= '" + tgl2 + "' ORDER BY id_penjualan ASC", cn);
  //SqlDataReader rd;
  //rd = cm.ExecuteReader();
  //while (rd.Read())
  //{
%>

MIME-Version: 1.0
X-Document-Type: Workbook
Content-Type: multipart/related; boundary="----=_NextPart_01CD0915.924C0070"

This document is a Single File Web Page, also known as a Web Archive file.  If you are seeing this message, your browser or editor doesn't support Web Archive files.  Please download a browser that supports Web Archive, such as Windows® Internet Explorer®.

------=_NextPart_01CD0915.924C0070
Content-Location: file:///C:/0A4A9512/barber.htm
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset="windows-1252"
....

Web Reader Java ME NetBeans


Web Reader J2ME
Untuk membuat aplikasi Web Reader di Java ME NetBeans dapat digunakan library import javax.microedition.io.*. Langkah-langkah pembuatannya sebagai berikut :

1. Buka Netbeans. Klik menu File-New Project. Pilih Categories : Java ME, Projects : Mobile Application. Klik Next. Pada dialog berikutnya, isikan Project Name : MobileWebReader. Kemudian cek Set As Main Project dan hilangkan cek pada Create Hello Midlet. Klik Next. Klik Next. Klik Finish.


2. Pada Project TreeView klik kanan, pilih New – Visual Midlet. Kemudian akan muncul dialog, isikan Class Name : MWeb, package : my.appwebreader. Klik Finish. Akan ditampilkan MIDlet kosong pada Design. Dari Palette Displayables tambahkan Form, kemudian ubah namanya menjadi FMain. Kemudian pada Form FMain tambahkan itemCommand dan exitCommand dari Pallete Commands. Ubah name dari itemCommand menjadi cmWeather dan label-nya menjadi “Cuaca”. Setelah itu tarik garis dari MIDlet Started menuju FMain, kemudian dari FMain exitCommand tarik garis ke MIDlet Resumed..



3. Pada Screen Design akan ditampilkan Design dari FMain. Ubah title dari FMain menjadi “Web Reader”, kemudian tambahkan 1 buah TextField. Ubah name-nya menjadi tResult. Kemudian ubah property label dari TextField tersebut menjadi “Result”. Kemudian property text-nya kosongkan, menjadi “”. Sehingga tampak seperti pada tampilan berikut ini :



4. Pada cmWeather, klik kanan pilih Go to Source. Pada Source akan muncul kode program dari method public void commandAction(), di dalamnya pada blok if (command == cmWeather) { } tambahkan kode program berikut :

    public void commandAction(Command command, Displayable displayable) {                                              
        // write pre-action user code here
        if (displayable == FMain) {                                          
            if (command == cmWeather) {                                        
                // write pre-action user code here
                try {
                    new Thread(new Runnable()
                    {
                        public void run()
                        {
                            try {
                                tResult.setString("");
                                StreamConnection sCon = (StreamConnection)Connector.open("http://localhost/cuaca.htm");
                                InputStream is = sCon.openInputStream();
                                StringBuffer b = new StringBuffer();
                                int ch;
                                while ((ch = is.read()) != -1) {
                                    b.append((char) ch);
                                }
                                int cutidx = b.toString().indexOf("Yogyakarta");
                                cutidx = b.toString().indexOf("<small>", cutidx);
                                int lstidx = b.toString().indexOf("</small>", cutidx);
                                String result = "Cuaca Yogyakarta " + b.toString().substring((cutidx + 7), (lstidx));
                                tResult.setString(result);
                            } catch (Exception e) {
                            }
                        }
                    }).start();
                } catch (Exception e) {
                }
                                         
                // write post-action user code here
            } else if (command == exitCommand) {                                        
                // write pre-action user code here
                exitMIDlet();                                          
                // write post-action user code here
            }                                                
        }                                              
        // write post-action user code here
    }

5. Klik Run untuk menjalankan aplikasi. Kemudian klik menu Cuaca, maka akan ditampilkan Prakiraan Cuaca dari Web (misalnya web BMG) untuk suatu kota (misalnya kota Yogyakarta). Hasilnya akan tampak seperti di bawah ini :




Selasa, 22 Mei 2012

PHP Header Force Download Untuk Report Excel, MHT, HTML, Word

Jika kita ingin membuat Report Excel, MHT, HTML, Word. Bisa dilakukan dengan membuat Dokumen di Microsoft Excel atau Microsoft Word. Kemudian Save As MHT atau HTML. Kemudian ubah ekstensi filenya menjadi PHP. Setelah itu beri coding PHP berikut di atasnya, maka jika dijalankan akan langsung keluar perintah Download, Do You Want to Open or Save this Document. Dan jika dipilih Open maka akan langsung keluar ke Microsoft Office tergantung extensinya *.doc atau *.xls atau *.xlsx atau *.docx bahkan *.mht atau *.htm.

Untuk mengisi data dinamis pada Report tersebut mudah tinggal beri saja coding PHP di dalamnya seperti biasa misal mengambil data dari database dst.

<?php
header("Content-Type: application/download\n");
header("Content-Disposition: attachment; filename=\"grafik barber johnson.xls\"");
header("Content-Transfer-Encoding: binary");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: public");


//include "koneksi.php";

//hari perawatan
//$qhp=mysql_query("SELECT SUM(DATEDIFF(tgl_keluar, tgl_pendaftaran) + 1) AS jmlhp FROM //kunjungan WHERE (tgl_pendaftaran >= '$tgl1' and tgl_pendaftaran <= '$tgl2') or (tgl_keluar >= '$tgl1' //and tgl_keluar <= '$tgl2') and jenis_kunjungan = 'Rawat Inap' AND NOT tgl_keluar IS NULL");
//$datahp=mysql_fetch_array($qhp);
//$nilaihp = $datahp['jmlhp'];

//...

?>


MIME-Version: 1.0
X-Document-Type: Workbook
Content-Type: multipart/related; boundary="----=_NextPart_01CD0915.924C0070"

This document is a Single File Web Page, also known as a Web Archive file.  If you are seeing this message, your browser or editor doesn't support Web Archive files.  Please download a browser that supports Web Archive, such as Windows® Internet Explorer®.

------=_NextPart_01CD0915.924C0070
Content-Location: file:///C:/0A4A9512/barber.htm
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset="windows-1252"
....

Membuat RSS Reader dengan J2ME NetBeans


RSS Reader dengan J2ME
Untuk membuat aplikasi RSS Reader di Java ME NetBeans dapat digunakan library KXML. Langkah-langkah pembuatannya sebagai berikut :

1. Buka Netbeans. Klik menu File-New Project. Pilih Categories : Java ME, Projects : Mobile Application. Klik Next. Pada dialog berikutnya, isikan Project Name : MobileRSSReader. Kemudian cek Set As Main Project dan hilangkan cek pada Create Hello Midlet. Klik Next. Klik Next. Klik Finish.


2. Pada Project TreeView klik kanan, pilih New – Visual Midlet. Kemudian akan muncul dialog, isikan Class Name : MNews, package : my.apprsseader. Klik Finish. Akan ditampilkan MIDlet kosong pada Design. Dari Palette Displayables tambahkan Form, kemudian ubah namanya menjadi FMain. Kemudian pada Form FMain tambahkan itemCommand dan exitCommand dari Pallete Commands. Ubah name dari itemCommand menjadi cmGet dan label-nya menjadi “Get”. Setelah itu tarik garis dari MIDlet Started menuju FMain, kemudian dari FMain exitCommand tarik garis ke MIDlet Resumed..


3. Pada Screen Design akan ditampilkan Design dari FMain. Ubah title dari FMain menjadi “New Reader”, kemudian tambahkan 1 buah TextField. Ubah name-nya menjadi tList. Kemudian ubah property label dari TextField tersebut menjadi “News List”. Kemudian property text-nya kosongkan, menjadi “”. Sehingga tampak seperti pada tampilan berikut ini :


4. Pada cmGet, klik kanan pilih Go to Source. Pada Source akan muncul kode program dari method public void commandAction(), di dalamnya pada blok if (command == cmGet) { } tambahkan kode program berikut :

    public void commandAction(Command command, Displayable displayable) {
        // write pre-action user code here
        if (displayable == FMain) {
            if (command == cmGet) {
                // write pre-action user code here
                try {
                    new Thread(new Runnable()
                    {
                        public void run()
                        {
                            try {
                                HttpConnection conn;
                                DataInputStream dis;
                                DataOutputStream dos;

                                conn = (HttpConnection) Connector.open("http://www.nytimes.com/services/xml/rss/nyt/National.xml");
                                conn.setRequestMethod(HttpConnection.GET);
                                conn.setRequestProperty("Content-Type", "text/xml");
                                dos = new DataOutputStream(conn.openDataOutputStream());

                                dis = new DataInputStream(conn.openDataInputStream());
                                if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
                                    doParse(dis);
                                    String newsList = "";
                                    for (int i = 0; i < jumlah; i++) {
                                        newsList = newsList + sTitle + "\n";
                                        newsList = newsList + sLink + "\n";
                                        newsList = newsList + sDescription + "\n";
                                        newsList = newsList + "--------------------------\n";
                                    }
                                } else {
                                    tList.setString("Koneksi Error");
                                }
                            } catch (Exception e) {
                            }
                        }
                    }).start();
                } catch (Exception e) {
                }

                // write post-action user code here
            } else if (command == exitCommand) {
                // write pre-action user code here
                exitMIDlet();
                // write post-action user code here
            }
        }
        // write post-action user code here
    }

5. Lanjutkan untuk cmEdit, cmDelete, cmSave, cmCancel dan lainnya. Berikut ini kode program selengkapnya :

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;

import java.io.*;
import org.kxml2.io.*;
import org.xmlpull.v1.*;

public class MNews extends MIDlet implements CommandListener {

    private boolean midletPaused = false;

    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">
    private Form FMain;
    private TextField tList;
    private KXmlParser parser;
    private int jumlah = 0;
    private String sTitle[] = new String[100];
    private String sLink[] = new String[100];
    private String sDescription[] = new String[100];
    public void commandAction(Command command, Displayable displayable) {
        // write pre-action user code here
        if (displayable == FMain) {
            if (command == cmGet) {
                // write pre-action user code here
                try {
                    new Thread(new Runnable()
                    {
                        public void run()
                        {
                            try {
                                HttpConnection conn;
                                DataInputStream dis;
                                DataOutputStream dos;

                                conn = (HttpConnection) Connector.open("http://www.nytimes.com/services/xml/rss/nyt/National.xml");
                                conn.setRequestMethod(HttpConnection.GET);
                                conn.setRequestProperty("Content-Type", "text/xml");
                                dos = new DataOutputStream(conn.openDataOutputStream());

                                dis = new DataInputStream(conn.openDataInputStream());
                                if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
                                    doParse(dis);
                                    String newsList = "";
                                    for (int i = 0; i < jumlah; i++) {
                                        newsList = newsList + sTitle + "\n";
                                        newsList = newsList + sLink + "\n";
                                        newsList = newsList + sDescription + "\n";
                                        newsList = newsList + "--------------------------\n";
                                    }
                                } else {
                                    tList.setString("Koneksi Error");
                                }
                            } catch (Exception e) {
                            }
                        }
                    }).start();
                } catch (Exception e) {
                }

                // write post-action user code here
            } else if (command == exitCommand) {
                // write pre-action user code here
                exitMIDlet();
                // write post-action user code here
            }
        }
        // write post-action user code here
    }
    public void doParse(InputStream isxml) {
        parser = new KXmlParser();
        try {
            parser.setInput(new InputStreamReader(isxml));
            parser.next();
            parser.require(XmlPullParser.START_TAG, null, "rss");
            parser.nextTag();

            parser.require(XmlPullParser.START_TAG, null, "channel");

                while (parser.nextTag() != XmlPullParser.END_TAG) {
                    parser.require(XmlPullParser.START_TAG, null, "title");
                    sTitle[jumlah] = new String("Title: " + parser.nextText());
                    parser.require(XmlPullParser.END_TAG, null, "title");
                    parser.nextTag();

                    parser.require(XmlPullParser.START_TAG, null, "link");
                    sLink[jumlah] = new String("Link: " + parser.nextText());
                    parser.require(XmlPullParser.END_TAG, null, "link");
                    parser.nextTag();
                   
                    parser.require(XmlPullParser.START_TAG, null, "description");
                    sDescription[jumlah] = new String("Description: " + parser.nextText());
                    parser.require(XmlPullParser.END_TAG, null, "description");
                    parser.nextTag();
                }
                parser.require(XmlPullParser.END_TAG, null, "channel");
                jumlah++;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

6. Klik Run untuk menjalankan aplikasi. Kemudian klik menu Get, maka akan ditampilkan Berita (News) dalam bentuk RSS dari Web (misalnya web New York Times). 

Pemrograman OOP Class Entity, Control, Boundary pada VB.NET

Pada pemrograman web dikenal cara pemrograman MVC atau Model View Controller. Di pemrograman Desktop VB.NET juga dikenal model pemrograman OOP  tersebut dengan bentuk class Entity Boundary Control. Misalnya ingin membuat aplikasi yang menampilkan data Buku, maka kita harus membuat Entity/Buku.vb, Control/BukuManager.vb dan Boundary/BukuUI.vb

Pertama-tama pisahkan dahulu koneksi database di Class Connection.vb :


Imports System.Data.OleDb

Public Class Connection
    'Public Shared _con_str As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.IO.Path.GetDirectoryName(Application.ExecutablePath) & "\DatabasePerpus.mdb"
    Public Shared _con_str As String = System.IO.File.ReadAllText(System.IO.Path.GetDirectoryName(Application.ExecutablePath) & "\settings.txt")

    Public Sub Connection()
        '_con_str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.IO.Path.GetDirectoryName(Application.ExecutablePath) & "\DatabasePerpus.mdb"
        _con_str = System.IO.File.ReadAllText(System.IO.Path.GetDirectoryName(Application.ExecutablePath) & "\settings.txt")
    End Sub

    Public Property CON_STR() As String
        Get
            Return _con_str
        End Get
        Private Set(ByVal value As String)
            _con_str = value
        End Set
    End Property

    Public Shared ReadOnly Property CON() As OleDbConnection
        Get
            Return New OleDbConnection(_con_str)
        End Get
    End Property
End Class


Kemudian buat folder Entity untuk menempatkan file Entity/Buku.vb :

Public Class Buku
    Dim _idbuku As String
    Dim _judul As String
    Dim _ringkasan As String
    Dim _tglterbit As Date
    Dim _harga As Double
    Dim _cover As Image

    Public Sub Buku()
        _idbuku = ""
        _judul = ""
        _ringkasan = ""
        _tglterbit = Now
        _harga = 0
        _cover = Nothing
    End Sub

    Public Sub Buku(ByVal idbuku As String, ByVal judul As String, ByVal ringkasan As String, ByVal tglterbit As Date, ByVal harga As Double, ByVal cover As Image)
        _idbuku = idbuku
        _judul = judul
        _ringkasan = ringkasan
        _tglterbit = tglterbit
        _harga = harga
        _cover = cover
    End Sub


    Public Property IdBuku() As String
        Get
            Return _idbuku
        End Get
        Set(ByVal value As String)
            _idbuku = value
        End Set
    End Property

    Public Property Judul() As String
        Get
            Return _judul
        End Get
        Set(ByVal value As String)
            _judul = value
        End Set
    End Property
    Public Property Ringkasan() As String
        Get
            Return _ringkasan
        End Get
        Set(ByVal value As String)
            _ringkasan = value
        End Set
    End Property
    Public Property TglTerbit() As Date
        Get
            Return _tglterbit
        End Get
        Set(ByVal value As Date)
            _tglterbit = value
        End Set
    End Property
    Public Property Harga() As Double
        Get
            Return _harga
        End Get
        Set(ByVal value As Double)
            _harga = value
        End Set
    End Property

    Public Property Cover() As Image
        Get
            Return _cover
        End Get
        Set(ByVal value As Image)
            _cover = value
        End Set
    End Property
End Class



Kemudian buat folder Control untuk menempatkan file Control/BukuManager.vb :



Imports System.Data.OleDb
Imports System.IO

Public Class BukuManager
    Public Sub BukuManager()

    End Sub

    Public Function addBuku(ByVal _buku As Buku) As Boolean
        Dim con As OleDbConnection = Connection.CON

        Try
            Dim ms As MemoryStream = New MemoryStream()
            _buku.Cover.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)

            Dim Pic_arr(ms.Length) As Byte

            ms.Position = 0
            ms.Read(Pic_arr, 0, Pic_arr.Length)

            con.Open()
            Dim sc As OleDbCommand = New OleDbCommand("INSERT INTO BUKU VALUES('" + _buku.IdBuku + "','" + _buku.Judul + "','" + _buku.Ringkasan + "',#" + _buku.TglTerbit.ToShortDateString + "#," + _buku.Harga.ToString + ", @cover)", con)
            Console.WriteLine(sc.CommandText)

            sc.Parameters.AddWithValue("@cover", Pic_arr)

            sc.ExecuteNonQuery()
            Return True
        Catch e As System.Data.SqlClient.SqlException

            Return False

        Catch e2 As Exception

            Return False

        Finally

            con.Close()
        End Try
    End Function

    'public bool validateIsbn(string isbn)
    '{
    '    SqlConnection con = Connection.CON;
    '    Try
    '    {
    '        con.Open();
    '        SqlCommand sc = new SqlCommand("SELECT * FROM BUKU where ISBN= '" + isbn + "'", con);
    '        SqlDataReader dr = sc.ExecuteReader();
    '        return (dr.HasRows ? false : true);
    '    }
    '    catch (System.Data.SqlClient.SqlException e)
    '    {
    '        return false;
    '    }
    '    catch (Exception e1)
    '    {
    '        return false;
    '    }
    '    Finally
    '    {
    '        con.Close();
    '    }
    '}

    Public Function getAllBuku() As DataTable
        Dim dt As DataTable = New DataTable()
        Dim con As OleDbConnection = Connection.CON
        Try
            con.Open()
            Dim ad As OleDbDataAdapter = New OleDbDataAdapter("SELECT * FROM BUKU", con)
            ad.Fill(dt)
            Return (dt)
        Catch e As System.Data.OleDb.OleDbException
            Console.WriteLine(e.Message)
            Return Nothing
        Catch e2 As Exception
            Console.WriteLine(e2.Message)
            Return Nothing
        Finally
            con.Close()
        End Try
    End Function

    Public Function updateBukuByidbuku(ByVal idbukulama As String, ByVal _buku As Buku) As Boolean
        Dim con As OleDbConnection = Connection.CON

        Try

            con.Open()
            Dim sc As OleDbCommand = New OleDbCommand("UPDATE BUKU SET IDBUKU ='" + _buku.IdBuku + "', Judul='" + _buku.Judul + "', Ringkasan='" + _buku.Ringkasan + "', TglTerbit=#" + _buku.TglTerbit.ToShortDateString + "#, Harga=" + _buku.Harga.ToString + " WHERE Idbuku='" + idbukulama + "'", con)
            Console.WriteLine(sc.CommandText)
            sc.ExecuteNonQuery()
            Return True

        Catch e As System.Data.OleDb.OleDbException
            Return False

        Catch e2 As Exception

            Return False

        Finally

            con.Close()
        End Try
    End Function

    Public Function deleteBukuByidbuku(ByVal idbukulama As String) As Boolean

        Dim con As OleDbConnection = Connection.CON
        Try

            con.Open()
            Dim sc As OleDbCommand = New OleDbCommand("DELETE FROM BUKU WHERE IDBUKU = '" + idbukulama + "'", con)
            sc.ExecuteNonQuery()
            Return True

        Catch e As System.Data.OleDb.OleDbException

            Return False

        Catch e2 As Exception

            Return False

        Finally

            con.Close()
        End Try
    End Function
End Class




Setelah itu terakhir buat folder Boundary untuk menempatkan file Boundary/BukuUI.vb :



Imports System.IO

Public Class BukuUI
    Dim idbukulama As String = ""

    Private Sub BukuUI()
        RefreshGrid()
    End Sub

    Private Sub RefreshGrid()
        Dim dt As DataTable = New DataTable()
        Dim bukMan As BukuManager = New BukuManager()

        Try

            dt.Clear()
            dt = bukMan.getAllBuku()
            dgBuku.DataSource = dt

        Catch e1 As System.Data.OleDb.OleDbException

            MessageBox.Show("Terjadi kesalahan pada Koneksi database" + e1.Message.ToString().Trim(), "Perhatian", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

        Catch e2 As Exception

            MessageBox.Show("Terjadi kesalahan pada Koneksi database" + e2.Message.ToString().Trim(), "Perhatian", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

    Private Sub BukuUI_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        RefreshGrid()
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Dim _buku As Buku = New Buku()
        Dim bukMan As BukuManager = New BukuManager()
        If (txtID.Text.Trim() <> String.Empty And txtJudul.Text.Trim() <> String.Empty And txtRingkasan.Text.Trim() <> String.Empty And txtHarga.Text.Trim() <> String.Empty) Then
            'If (bukMan.validateIsbn(textISBN.Text.Trim())) Then

            _buku.IdBuku = txtID.Text.Trim()
            _buku.Judul = txtJudul.Text.Trim()
            _buku.Ringkasan = txtRingkasan.Text.Trim()
            _buku.TglTerbit = Date.Parse(txtTgl.Text.Trim())
            _buku.Harga = Double.Parse(txtHarga.Text)

            If Not PicCover.Image Is Nothing Then

                _buku.Cover = PicCover.Image

                'Dim ms As MemoryStream = New MemoryStream()
                'PicCover.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)

                'Dim Pic_arr(ms.Length) As Byte

                'ms.Position = 0
                'ms.Read(Pic_arr, 0, Pic_arr.Length)

            End If

            If (bukMan.addBuku(_buku)) Then

                MessageBox.Show("Data berhasil disimpan!", "Informasi", MessageBoxButtons.OK, MessageBoxIcon.Information)
                RefreshGrid()

            Else
                MessageBox.Show("Data gagal disimpan", "Perhatian", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End If
            'Else
            '   MessageBox.Show("Judul '" + txtJudul.Text.Trim() + "' sudah terdaftar di database, masukkan Judul yang lain", "Informasi", MessageBoxButtons.OK, MessageBoxIcon.Information)
            'End If
        Else
            MessageBox.Show("Masukkan data dengan benar!", "Perhatian", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

    Private Sub dgBuku_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgBuku.CellClick
        txtID.Text = dgBuku.CurrentRow.Cells("idbuku").Value.ToString
        txtJudul.Text = dgBuku.CurrentRow.Cells("judul").Value.ToString
        txtRingkasan.Text = dgBuku.CurrentRow.Cells("ringkasan").Value.ToString
        txtTgl.Text = dgBuku.CurrentRow.Cells("tglterbit").Value.ToString
        txtHarga.Text = dgBuku.CurrentRow.Cells("harga").Value.ToString
        idbukulama = txtID.Text
    End Sub

    Private Sub dgBuku_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgBuku.CellContentClick

    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        Dim _buku As Buku = New Buku()
        Dim bukMan As BukuManager = New BukuManager()
        If (txtID.Text.Trim() <> String.Empty And txtJudul.Text.Trim() <> String.Empty And txtRingkasan.Text.Trim() <> String.Empty And txtHarga.Text.Trim() <> String.Empty) Then
            'If (bukMan.validateIsbn(textISBN.Text.Trim())) Then

            _buku.IdBuku = txtID.Text.Trim()
            _buku.Judul = txtJudul.Text.Trim()
            _buku.Ringkasan = txtRingkasan.Text.Trim()
            _buku.TglTerbit = Date.Parse(txtTgl.Text.Trim())
            _buku.Harga = Double.Parse(txtHarga.Text)
            If (bukMan.updateBukuByidbuku(idbukulama, _buku)) Then

                MessageBox.Show("Data berhasil diupdate!", "Informasi", MessageBoxButtons.OK, MessageBoxIcon.Information)
                RefreshGrid()

            Else
                MessageBox.Show("Data gagal diupdate", "Perhatian", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End If
            'Else
            '   MessageBox.Show("Judul '" + txtJudul.Text.Trim() + "' sudah terdaftar di database, masukkan Judul yang lain", "Informasi", MessageBoxButtons.OK, MessageBoxIcon.Information)
            'End If
        Else
            MessageBox.Show("Masukkan data dengan benar!", "Perhatian", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

    Private Sub BtnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnDelete.Click
        Dim bukman As BukuManager = New BukuManager
        If (bukman.deleteBukuByidbuku(idbukulama)) Then

            MessageBox.Show("Data berhasil dihapus!", "Informasi", MessageBoxButtons.OK, MessageBoxIcon.Information)
            RefreshGrid()

        Else
            MessageBox.Show("Data gagal dihapus!", "Perhatian", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End If
    End Sub

    Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
        txtID.Text = ""
        txtJudul.Text = ""
        txtRingkasan.Text = ""
        txtTgl.Text = ""
        txtHarga.Text = ""
    End Sub

    Private Sub btnbrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnbrowse.Click
        If (OD.ShowDialog = Windows.Forms.DialogResult.OK) Then
            PicCover.Image = Image.FromFile(OD.FileName)
        End If
    End Sub
End Class