Menu Horisontal

Sabtu, 16 Maret 2013

Cara Membaca & Menulis INI File Vb6


Sumber : http://arifsoftgames.blogspot.com/2013/02/cara-membaca-menulis-ini-file-vb6.html

Pasti ada orang bertanya-tanya bagaimana menggunakan file INI untuk VB6???, nah Pada kesempatan ini saya akan memberikan cara untuk membaca dan menulis INI File pada VB6. Semoga membantu :)





Bahan - Bahan :
1. Visual Basic 6, kalo belom punya pake yang portable gak apa-apa. Download disini | Password : arifsoftgames
2. Kesabaran

Caranya :
1. Tambahkan 3 TextBox, 1 Timer dan 1 Command Button
Saya Menyusun Seperti ini.
2. Buat 2 Module
Module 1 kasih nama : Read
Module 2 kasih nama : Write
Klik kanan, pilih Add lalu klik Module
Sekarang Tahap Codingnya :
Klik 2x pada daerah form 1 dan masukkan code ini :
'Coding Form
Private Sub Command1_Click()
End
End Sub

Private Sub Form_Load()
Text1.Text = ReadIniValue(App.Path & "\INFO.ini", "Default", "Text1")
    Text2.Text = ReadIniValue(App.Path & "\INFO.ini", "Default", "Text2")
    Text3.Text = ReadIniValue(App.Path & "\INFO.ini", "Default", "Text3")
    Timer1.Enabled = True
End Sub

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
    If UnloadMode = 0 Then Cancel = 1
End Sub

Private Sub Timer1_Timer()
WriteIniValue App.Path & "\INFO.ini", "Default", "Text1", Text1.Text
    WriteIniValue App.Path & "\INFO.ini", "Default", "Text2", Text2.Text
    WriteIniValue App.Path & "\INFO.ini", "Default", "Text3", Text3.Text
End Sub

Pada Module 1 / Read masukkan Code ini
'Fungsi Module Read
Option Explicit

Public Function ReadIniValue(INIpath As String, KEY As String, Variable As String) As String
Dim NF As Integer
Dim Temp As String
Dim LcaseTemp As String
Dim ReadyToRead As Boolean
    
AssignVariables:
        NF = FreeFile
        ReadIniValue = ""
        KEY = "[" & LCase$(KEY) & "]"
        Variable = LCase$(Variable)
    
EnsureFileExists:
    Open INIpath For Binary As NF
    Close NF
    SetAttr INIpath, vbArchive
    
LoadFile:
    Open INIpath For Input As NF
    While Not EOF(NF)
    Line Input #NF, Temp
    LcaseTemp = LCase$(Temp)
    If InStr(LcaseTemp, "[") <> 0 Then ReadyToRead = False
    If LcaseTemp = KEY Then ReadyToRead = True
    If InStr(LcaseTemp, "[") = 0 And ReadyToRead = True Then
        If InStr(LcaseTemp, Variable & "=") = 1 Then
            ReadIniValue = Mid$(Temp, 1 + Len(Variable & "="))
            Close NF: Exit Function
            End If
        End If
    Wend
    Close NF
End Function

Pada Module 2 / Write masukkan Code ini :
'Fungsi Module Write
Option Explicit

Public Function WriteIniValue(INIpath As String, PutKey As String, PutVariable As String, PutValue As String)
Dim Temp As String
Dim LcaseTemp As String
Dim ReadKey As String
Dim ReadVariable As String
Dim LOKEY As Integer
Dim HIKEY As Integer
Dim KEYLEN As Integer
Dim VAR As Integer
Dim VARENDOFLINE As Integer
Dim NF As Integer
Dim X As Integer

AssignVariables:
    NF = FreeFile
    ReadKey = vbCrLf & "[" & LCase$(PutKey) & "]" & Chr$(13)
    KEYLEN = Len(ReadKey)
    ReadVariable = Chr$(10) & LCase$(PutVariable) & "="
        
EnsureFileExists:
    Open INIpath For Binary As NF
    Close NF
    SetAttr INIpath, vbArchive
    
LoadFile:
    Open INIpath For Input As NF
    Temp = Input$(LOF(NF), NF)
    Temp = vbCrLf & Temp & "[]"
    Close NF
    LcaseTemp = LCase$(Temp)
    
LogicMenu:
    LOKEY = InStr(LcaseTemp, ReadKey)
    If LOKEY = 0 Then GoTo AddKey:
    HIKEY = InStr(LOKEY + KEYLEN, LcaseTemp, "[")
    VAR = InStr(LOKEY, LcaseTemp, ReadVariable)
    If VAR > HIKEY Or VAR < LOKEY Then GoTo AddVariable:
    GoTo RenewVariable:
    
AddKey:
        Temp = Left$(Temp, Len(Temp) - 2)
        Temp = Temp & vbCrLf & vbCrLf & "[" & PutKey & "]" & vbCrLf & PutVariable & "=" & PutValue
        GoTo TrimFinalString:
        
AddVariable:
        Temp = Left$(Temp, Len(Temp) - 2)
        Temp = Left$(Temp, LOKEY + KEYLEN) & PutVariable & "=" & PutValue & vbCrLf & Mid$(Temp, LOKEY + KEYLEN + 1)
        GoTo TrimFinalString:
        
RenewVariable:
        Temp = Left$(Temp, Len(Temp) - 2)
        VARENDOFLINE = InStr(VAR, Temp, Chr$(13))
        Temp = Left$(Temp, VAR) & PutVariable & "=" & PutValue & Mid$(Temp, VARENDOFLINE)
        GoTo TrimFinalString:

TrimFinalString:
        Temp = Mid$(Temp, 2)
        Do Until InStr(Temp, vbCrLf & vbCrLf & vbCrLf) = 0
        Temp = Replace(Temp, vbCrLf & vbCrLf & vbCrLf, vbCrLf & vbCrLf)
        Loop
    
        Do Until Right$(Temp, 1) > Chr$(13)
        Temp = Left$(Temp, Len(Temp) - 1)
        Loop
    
        Do Until Left$(Temp, 1) > Chr$(13)
        Temp = Mid$(Temp, 2)
        Loop
    
OutputAmendedINIFile:
        Open INIpath For Output As NF
        Print #NF, Temp
        Close NF
    
End Function
' Selesai

Nah sekarang kita tinggal compile exe aja caranya :
Masuk menu file > Make EXE file
Make EXE file
Sekedar info aja, nanti file *.ini bernama INFO.ini

Membaca File Text VB6

Cara membaca file Text adalah dengan menggunakan fungsi berikut :

Versi 1
Private Function OpenTextFile() As String 
    Dim nFileNum As Integer, sText As String 
    Dim sNextLine As String, lLineCount As Long 
    nFileNum = FreeFile 
    Open "C:\daftar_driver.txt" For Input As nFileNum 
        lLineCount = 1 
        Do While Not EOF(nFileNum) 
            Line Input #nFileNum, sNextLine 
            MsgBox sNextLine 'ini akan membaca file text baris per baris 
            sNextLine = sNextLine & vbCrLf 
            sText = sText & sNextLine 
        Loop 
        OpenTextFile = sText 
    Close nFileNum 
End Function 


Versi 2
1. Menulis Ke File Text  
  Dim LocTextFile As String     LocTextFile = “C:\windows\SvAdd.txt”         Open LocTextFile For Output As #1   ‘Buka file text        Print #1, “Server_Name”    ‘Modify Baris Pertama”        Print #1, “Database_Name”  ‘Modify Baris Kedua        Print #1, “User”           ‘Modify Baris Ketiga        Print #1, “Pwd”            ‘Modify Baris Keempat     Close #1
2. Membaca dari File Text
    Dim LocTextFile As String     Dim ServerAddress  As String     Dim DatabaseName As String     Dim UserID As String     Dim PwdSql As String     LocTextFile = “C:\windows\SvAdd.txt”     Open LocTextFile For Input As #1    ‘Buka file text        Line Input #1, ServerAddress      ‘Baca Baris Pertama        Line Input #1, DatabaseName       ‘Baca Baris Kedua        Line Input #1, UserID             ‘Baca Baris Ketiga        Line Input #1, PwdSql             ‘Baca Baris Keempat     Close #1 ‘Tutup File file text
Versi 3
Ini Fungsinya
Function ReadTextFileContents(filename As String) As String
    Dim fnum As Integer, isOpen As Boolean
    On Error GoTo Error_Handler
    fnum = FreeFile()
    Open filename For Input As #fnum
    isOpen = True
    ReadTextFileContents = Input(LOF(fnum), fnum)
    
Error_Handler:
    If isOpen Then Close #fnum
    If Err Then Err.Raise Err.Number, , Err.Description
End Function

Ini Cara Pakainya
TxtPesan.Text = ReadTextFileContents(App.Path & "\service.log")



Kamis, 07 Maret 2013

How to Communicate to the Arduino in Visual Basic .NET

Sumber : http://social.technet.microsoft.com/wiki/contents/articles/14194.how-to-communicate-to-the-arduino-in-visual-basic-net.aspx

Communicating to the Arduino in the .NET platform is pretty much straightforward: The Arduino uses a virtual serial port to allow programs to be written onto it, but we can also use this port to get and send data to and from the Arduino.
Materials:

  • Arduino or Arduino Compatible Board (UNO, Mega, Etc.)
  • Compatible USB Cable to Connect the Arduino to the Host Computer
  • The Arduino Software (Available Here )
  • VB.NET 2010 or 2012 (Available Here )
I am assuming that you already have a simple knowledge of the .NET and Arduino (software & hardware) platforms. If not, there are many tutorials on the internet to help get you started. Let's begin by putting the program on the Arduino.


Step 1: Adding a Program to Send Data From the Arduino
Let's start by opening up the Arduino software, and copying/pasting in the following code:

void setup() {              
    Serial.begin(9600); 
}
 
//Sends the Number 1234 Over the Serial Port Once Every Second
void loop() {
Serial.write(1234)
delay(1000)
}

This program opens up a serial port, and sends the number string, 1234, over the port once every second in an infinite loop. The number '1234' has no special meaning, you could place any number there in place of it. Then plug in your Arduino board and upload the code to it. Leave it plugged in.

Step 2: Creating the .NET Program
Creating the .NET code in VB.NET is actually quite simple and easy to understand. Open a new VB.NET console program, clear all of the code, and paste in the following:

Module Module1
    Sub Main()
        Dim userRespond
        Dim fetchedData
        Dim writeString
        Console.WriteLine("Type R to Read Serial Port.")
        userRespond = Console.ReadLine
        If userRespond = "R" Or userRespond = "r" Then
            Dim port As New System.IO.Ports.SerialPort
            port.PortName = "COM4"
            port.Open()
            port.BaudRate = 9600
            fetchedData = port.ReadByte
            Console.WriteLine(fetchedData)
            Console.ReadLine()
  Else
            Console.WriteLine("Not a Recognized Command.")
        End If
    End Sub
End Module

This code should be fairly simple. It opens a new console window, then it asks the user if they want to get the data from the port, next (if they said yes), it opens up a new COM port and gets the data, finally it writes it to the console. You may need to change COM4 to the correct port for your Arduino. It lists what port Arduino is on in the Arduino software bottom right corner. You can not write a new program to the Arduino when this software is running, for it gives an error that says that the COM port is busy.

Step 3: Testing
To use this program, be sure your Arduino is plugged in, and it is running the code from step 1. Now, run the program from above and type in R. It may take a second (the Arduino only sends it once per second), but the number 1234 will come up! If you change the number 1234 in the Arduino code to "hello" and upload it and run the .NET program, it will only give you the decimal value for a lower-case h. This is because this program can only read one byte at a time. See if you can change it up to read the whole word and convert it to unicode! Post your inventions!

Kamis, 21 Februari 2013

Executing SQL Server Stored Procedure from PHP

Sumber : http://makdns.blogspot.com/2010/04/executing-microsoft-sql-server-stored.html
Difference between PHP on Windows and PHP on Linux is:

On windows, the MS SQL Server support module is running as a DLL file. In order to enable the extension, must uncomment the line from the php.ini file : extension=php_mssql.dll

On Linux, the MS SQL Server support module is compiled into libphp5.so, there is no need to load it from extensions.


Execute Microsoft SQL Server stored procedures from PHP by calling the following functions: mssql_connect(), mssql_bind(), mssql_select_db(), mssql_execute(), mssql_init(), mssql_free_statement and mssql_close().

Syntax
mssql_connect (string $servername, string $username, string $password, bool $new_link)

mssql_connect() establishes a connection to a MS SQL server. The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mssql_close().

$new_link - If a second call is made to mssql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. This parameter modifies this behavior and makes mssql_connect() always open a new link, even if mssql_connect() was called before with the same parameters.

Returns a MS SQL link identifier on success, or FALSE on error.

"Warning: mssql_connect() [function.mssql-connect]: message: Cannot open user default database. Using master database instead. (severity 11) in "

It means the default database for the user you are connecting with doesn't exist or you don't have permission to access it. To ignore the warning
replace mssql_connect($server, $username, $password); code to @mssql_connect($server, $username, $password);.

Accessing SQL Query and Stored Procedure from the pubs database:


Example 1
CREATE PROCEDURE [dbo].[spEmployee] AS
SELECT fname FROM employee;
GO

$server = "localhost,1433";
$username = "sa";
$password = "pwd";
$databasename = "pubs";

$sqlconnect = @mssql_connect($server, $username, $password) or die("Couldn't connect to SQL Server");
$sqldb = mssql_select_db($databasename,$sqlconnect) or die("Couldn't open database");

// Using SQL Query
$sqlquery = "SELECT fname FROM employee;";
$results = mssql_query($sqlquery);
while ($row=mssql_fetch_array($results))
{
echo $row['fname']."
\n";
}

//using stored procedure
$sp = mssql_init("spEmployee", $sqlconnect) or die("Couldn't call stored procedure");
$results= mssql_execute($sp) or die(mssql_get_last_message());
while ($row=mssql_fetch_array($results))
{
echo $row['fname']."
\n";
}
mssql_close($sqlconnect);
?>

Example 2
CREATE PROCEDURE [dbo].[spGetEmployee]
@sTitleID varchar(10),
@sBookTitle varchar(100) OUTPUT
AS
DECLARE @iTotalEmployee int
SELECT @sBookTitle =title FROM titles WHERE title_id = @sTitleID
SELECT @iTotalEmployee = COUNT(emp_id) FROM employee
RETURN @iTotalEmployee
GO
$sp = mssql_init("spGetTitle_TotalEmployee", $sqlconnect) or die("Couldn't call stored procedure");

$sTitleID = 'bu1032';
$iTotalEmployee = 0;
$sBookTitle = '';

// Bind the parameters
mssql_bind($sp, "@sTitleID", $sTitleID, SQLVARCHAR);
mssql_bind($sp, "@sBookTitle", $sBookTitle, SQLVARCHAR, TRUE, FALSE,100);

// Bind the return value
mssql_bind($sp, "RETVAL", $iTotalEmployee, SQLINT2);

mssql_execute ($sp);
mssql_free_statement ($sp);
mssql_close($sqlconnect);

echo "There were $iTotalEmployee Employees returned.";
echo "The book title was: $sBookTitle.";
?>


Baca Juga :
http://www.devarticles.com/c/a/PHP/Executing-SQL-Server-Stored-Procedures-With-PHP/

Rabu, 20 Februari 2013

Membuat Dokumen Excel 2007 (.xlsx) Menggunakan PHP Excel Reader

Sumber : http://setoelkahfi.web.id/membuat-dokumen-excel-2007-xlsx-menggunakan-php-excel-reader/
Mengolah dokumen excel, khususnya excel 2007 (exstensi .xlsx), menggunakan bahasa pemrograman PHP bisa dilakukan dengan mudah. Bagi yang belum tahu, saat ini sudah ada library khusus untuk menangani dokumen dengan format .xlsx bernama PHP Excel. Berikut saya coba jelaskan cara membuat report php dengan format .xlsx.
Aplikasi spreadsheet buatan Microsoft ini, yang sekarang sudah sampai seri 2010, adalah aplikasi perkantoran yang paling banyak dipakai. Dengan kemudahan interface dan penggunaannya, membuat banyak perusahaan menggunakannya sebagai aplikasi standar perkantoran. Berbedsa dengan versi 2003 (exstensi .xls), format .xlsx memerlukan penanganan yang berbeda saat kita akan menggunakannya dalam skrip php. Seperti kita ketahui, excel 2003 mempunyai batasan jumlah record yang mampu ditangani, yaitu sebanyak maksimal 65536 record. Sedangkan jika menggunakan excel 2007 jumlah record bisa ditampung sampai 1048576 record.
Dalam tutorial ini, saya menggunakan Wampserver versi 2.0. Alternatif lain yang banyak dipakai adalah XAMPP, yang tentunya teman-teman sudah mahir bagaimana cara menginstal xampp sebagai server local di komputer kita. Cara menggunakan PHP Excel ini cukup mudah, hanya ada beberapa langkah untuk menggunakannya bersama PHP.
Ok, ayo kita kemon :D
1.  Pertama-tama download file yang kita butuhkan, yaitu PHP Excel dari link berikut. Link ini adalah link resmi untuk project PHP Excel:
2. Setelah file berhasil di download, ekstrak file tersebut, lalu carilah folder bernama “classes”. Jika tidak ada, cek kembali darimana teman download file tersebut, hehehe.Jika benar, di dalam folder tersebut terdapat file bernama PHPExcel.php dan direktori PHPExcel
3. Selanjutnya, setelah mempersiapkan file yang dibutuhkan, buatlah sebuah index.php dengan skrip seperti ini:
getProperties()->setCreator(“Seto El Kahfi”)
->setLastModifiedBy(“Seto El Kahfi”)
 ->setTitle(“Office 2007 XLSX Test Document”)
 ->setSubject(“Office 2007 XLSX Test Document”)
 ->setDescription(“Test document for Office 2007 XLSX, generated using PHP classes.”);
$objPHPExcel->setActiveSheetIndex(0)
 ->setCellValue(‘A1′, ‘Hello’)
 ->setCellValue(‘B2′, ‘world!’)
 ->setCellValue(‘C1′, ‘Hello’)
 ->setCellValue(‘D2′, ‘world!’);
header(‘Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’);
 header(‘Content-Disposition: attachment;filename=”test.xlsx”‘);
 header(‘Cache-Control: max-age=0′);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel2007′);
 $objWriter->save(‘php://output’);
 ?>
Kedua file dan direktori tersebut harus sejajar dengan index.php. Bisa juga diletakkan di folder lain. Terserah teman :D
4. Save file tersebut pada direktori “excel” di dalam direktori root server. Dalam kasus saya, direktori root server wampserver ada di C:\wamp\www\. Sedangkan class PHPExcel.php menyesuaikan tutorial no. 3.
5. Aktifkan Wampserver, bisa dengna klik ikonnya di start menu. Cek dan pastikan php_zip sudah aktif dengan cara cek lewat php.info.
wampserver
wampserver
6. Saatnya menggunakan browser, buka localhost. Jika terdapat logo wampserver disana, berarti server teman sudah siap. Buka folder “excel”, dan file akan langsung didownload. Setelah file terdownload, buka dile tersebut, secara otomatis akan menggunakan MS Excel 2007 :D
Excel dengan PHP excel
Excel dengan PHP excel
Skrip di atas bisa disesuaikan dengan kebutuhan masing-masing. Karena tidak semua aplikasi membutuhkan skrip yang terlalu rumit ataupun terlampau sederhana.
PHP Excel adalah sebuah kelas. Untuk memahami konsep ini, disarankan untuk mempelajari terlebih dahulu konsep Object Oriented Programing. Karena dengan memahami apa itu object oriented programing tentunya akan mudah mencerna maksud dari listing program di atas.
Demikian postingan kali ini tentang cara menggunakan library PHP Excel untuk mengolah dokumen dengan format Excel 2007. Untuk dokumentasi lengkap silahkan mengunjungi website resmi dari PHP Excel yang ada pada link download di atas. Semoga tutorial ini bermanfaat. Ada pertanyaan sila langsung komentar sajah, happy coding :D

Baca Juga di :
http://dyshared.wordpress.com/2012/02/08/membuat-file-excel-di-php-dengan-phpexcel/
http://blog.sangkuriang.co.id/cara-termudah-export-table-ke-excel-dengan-php/

Senin, 21 Januari 2013

VB - Building Dynamic Forms at Runtime - Visual Basic.NET 2008

Sumber : http://visualbasic.w3computing.com/vb2008/5/vb-building-dynamic-forms-runtime.php   
 

Sometimes you won't know in advance how many instances of a given control might be required on a form. Let's say you're designing a form for displaying the names of all tables in a database. It's practically impossible to design a form that will accommodate every database users might throw at your application. Another typical example is a form for entering family related data, which includes the number of children in the family and their ages. As soon as the user enters (or changes) the number of children, you should display as many TextBox controls as there are children to collect their ages.
For these situations, it is possible to design dynamic forms, which are populated at runtime. The simplest approach is to create more controls than you'll ever need and set their Visible properties to False at design time. At runtime, you can display the controls by switching their Visible properties to True. As you know already, quick-and-dirty methods are not the most efficient ones. You must still rearrange the controls on the form to make it look nice at all times. The proper method to create dynamic forms at runtime is to add controls to and remove them from your form as needed, using the techniques discussed in this section.
Just as you can create new instances of forms, you can also create new instances of any control and place them on a form. The Form object exposes the Controls collection, which contains all the controls on the form. This collection is created automatically as you place controls on the form at design time, and you can access the members of this collection from within your code. It is also possible to add new members to the collection, or remove existing members, with the Add and Remove statements accordingly.

The Form's Controls Collection

All the controls on a form are stored in the Controls collection, which is a property of the Form object. The Controls collection exposes members for accessing and manipulating the controls at runtime, and they're the usual members of a collection:

Add method

The Add method adds a new element to the Controls collection. In effect, it adds a new control on the current form. The Add method accepts a reference to a control as an argument and adds it to the collection. Its syntax is the following, where controlObj is an instance of a control:
Controls.Add(controlObj)
To place a new Button control on the form, declare a variable of the Button type, set its properties, and then add it to the Controls collection:
Dim bttn As New System.WinForms.Button
bttn.Text = "New Button"
bttn.Left = 100
bttn.Top = 60
bttn.Width = 80
Me.Controls.Add(bttn)

Jumat, 11 Januari 2013

Daftar Fungsi-fungsi pada Visual Basic



Function Abs(Number)
    Member of VBA.Math
    Returns the absolute value of a number

Sub AppActivate(Title, [Wait])
    Member of VBA.Interaction
    Activates an application window

Function Asc(String As String) As Integer
    Member of VBA.Strings
    Returns the ANSI character code of the first character in a string

Function AscB(String As String) As Byte
    Member of VBA.Strings
    Returns the value of the first byte in a string

Function AscW(String As String) As Integer
    Member of VBA.Strings
    Returns the native character code of the first character in a string (Unicode or ANSI)

Function Atn(Number As Double) As Double
    Member of VBA.Math
    Returns the arctangent of a number

Sub Beep()
    Member of VBA.Interaction
    Sounds a tone through the computer's speaker

Sumber :


Function CallByName(Object As Object, ProcName As String, CallType As VbCallType, Args() As Variant)
    Member of VBA.Interaction
    Support IDispatch::Invoke

Function CBool(Expression) As Boolean
    Member of VBA.Conversion
    Converts an expression to a Boolean

Function CByte(Expression) As Byte
    Member of VBA.Conversion
    Converts an expression to a Byte

Function CCur(Expression) As Currency
    Member of VBA.Conversion
    Converts an expression to a Currency

Function CDate(Expression) As Date
    Member of VBA.Conversion
    Converts an expression to a Date