Custom Search

Thursday, October 11, 2007

Execute Non Query

A quick way of using sql executeNonQuery Method of sqlCommand

' ----------------------------------------

' Required Imports :
'
' System.Data
' System.Data.SqlClient
' ----------------------------------------

Dim rowCount As Integer
Dim previousConnectionState As ConnectionState
previousConnectionState = conn.State

Try
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
rowCount = cmd.ExecuteNonQuery()

Finally
If previousConnectionState = ConnectionState.Closed Then
conn.Close()
End If
End Try

Database Err Handling

' ----------------------------------------
' Required Imports :
'
' System.Data
' System
' ----------------------------------------

Try
' Add your data task here.
Catch concurrencyEx As DBConcurrencyException
Throw concurrencyEx
Catch constraintEx As ConstraintException
Throw constraintEx
Catch deletedRowEx As DeletedRowInaccessibleException
Throw deletedRowEx
Catch duplicateNameEx As DuplicateNameException
Throw duplicateNameEx
Catch inRowChangingEx As InRowChangingEventException
Throw inRowChangingEx
Catch invalidConstraintEx As InvalidConstraintException
Throw invalidConstraintEx
Catch invalidExpressionEx As InvalidExpressionException
Throw invalidExpressionEx
Catch missingPrimaryEx As MissingPrimaryKeyException
Throw missingPrimaryEx
Catch noNullEx As NoNullAllowedException
Throw noNullEx
Catch readOnlyEx As ReadOnlyException
Throw readOnlyEx
Catch rowNotInTableEx As RowNotInTableException
Throw rowNotInTableEx
Catch strongTypingEx As StrongTypingException
Throw strongTypingEx
Catch typedDataSetEx As TypedDataSetGeneratorException
Throw typedDataSetEx
Catch versionNotFoundEx As VersionNotFoundException
Throw versionNotFoundEx
Catch dataEx As DataException
Throw dataEx
Catch ex As Exception
Throw ex
Finally
' Dispose of any resources you used in the Try block.
End Try

Friday, October 5, 2007

Migration VS 2002 / 2003 to VS2005

Migration VS 2002 / 2003 to VS2005

Many people still confusing of migrating VS2002 / 2003 to VS2005.
Let's help people by putting your idea on migration.
Let's start with me first

Things you need to consider when you are migration from VS2002 / 2003 to VS2005
1. Third party component
Check if your third party components do support in VS 2005.
Check the support document what you need to change and what you need to have.

Ribbon Component

Ribbon Component is one of the most searching component.
Most Ribbon components supprt in VS 2005 and VS2002 / 2003. In order to run a proper
Ribbon Component you need to have MS Office 2007


Report
Report is you need to the most when you are developing application.
If you are using Crystal Report V9.xx with VS2002 / 2003. You need to upgrade it to
higher version.
Crystal Report V9 doesnt support Framework V2.
VS 2005 is using framework v2.


2. Database
You might want to change on your code. VS 2005 has a new features called ADONet Async. This a great features for speeding up your application and waiting time.
AdoNet Async is doing multiple jobs at the same time without waiting for the first task to finish.

Thursday, October 4, 2007

MS SQL Backup Script

MS SQL Backup Script


There are many ways to backup sql script. There are many post, articles talking about backup sql.

Here is one of the quick way to backup your MS SQL Database.

1. Clear Log
TO reduce rubbish on your drive. You do not need rubbish log.
2. Backup database after clear database log.

You may put this script into your scheduler. Just change a little of the script. :)

--CLEAR LOG
DBCC SHRINKDATABASE (N'IT_Medan', 0,TRUNCATEONLY)

-- BACKUP DABATABASE
BACKUP DATABASE [IT_Medan_DB] TO DISK = N'C:\Backup\IT_Medan.bk' WITH INIT , NOUNLOAD , NAME = N'IT_Medanbackup', NOSKIP , STATS = 10, NOFORMAT

Simple Console Application

Imports system
Imports microsoft.visualbasic ' For msgbox

Namespace N1
Class Ovrl
Shared Sub main()
myfunc("Mansih")
myfunc(22)
End Sub

'Accepts Integer
Overloads Shared Function myfunc(ByVal i As Integer) As String
msgbox("Overloaded Function Accepting Integer")
End Function

'Accepts String
Overloads Shared Function myfunc(ByVal s As String) As String
msgbox("Overloaded Function Accepting String")
End Function
End Class
End Namespace

This Example Demonstrated Function Overloading, It is also possible to overload a Constructor and its also one of my favourite feature.

Imports system
Imports microsoft.visualbasic ' For msgbox


Namespace N1
Class OvrConst
Shared Sub main()
Dim o As New OvrConst()
Dim x As New OvrConst("Constructor 2")
End Sub

'cosntructor 1 without parameter
Public Overloads Sub New()
msgbox("Constructor 1")
End Sub


'cosntructor 2 with a String parameter
Public Overloads Sub New(ByVal s As String)
msgbox(s)
End Sub

End Class
End Namespace

Reading XML FIle

After calling read method, you can go though the document node by node and get the data.

Source Code:
Imports System
Imports System.Xml
Module Module1

Sub Main()
' Open an XML file
Dim reader As XmlTextReader = New XmlTextReader("C:\\it_medan.xml")

While reader.Read()
Console.WriteLine(reader.Name)
End While

End Sub

End Module

Object Serialization

Option Strict Off
Imports System
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Public Module SerializationSample
'Class Node to hold the Linklist Item. Must be marked as
'serializable
Public Class Node
Public Value As Integer
Public NextNode As Node = Nothing
'Constructor
Public Sub New(ByVal NewValue As Integer)
MyBase.New()
Me.Value = NewValue
End Sub
End Class
'Linked List Class. MUst be marked with
'serializable attribute
Public Class LinkedList
Private m_head As Node = Nothing
Private m_tail As Node = Nothing
'Adding to Linklist
Public Function Add(ByVal iValue As Integer) As Boolean
Dim curNode As Node = m_head
While Not (curNode Is Nothing)
If (curNode.Value = iValue) Then Return False
curNode = curNode.NextNode
End While
Dim newNode As Node = New Node(iValue)
If (m_tail Is Nothing) Then
m_tail = newNode
m_head = m_tail
Else
m_tail.NextNode = newNode
m_tail = newNode
End If
Return True
End Function
'Remove from link list
Public Function Remove(ByVal iValue As Integer) _
As Boolean
Dim prevNode As Node = Nothing
Dim curNode As Node = m_head

While Not (curNode Is Nothing)
If (curNode.Value = iValue) Then
If (prevNode Is Nothing) Then
If (m_head Is m_tail) Then
m_tail = Nothing
m_head = m_tail
Else
m_head = m_head.NextNode
End If
Else
prevNode.NextNode = curNode.NextNode
Exit While
End If
Return True
End If
prevNode = curNode
curNode = curNode.NextNode
End While
Return False
End Function
'Find a specific node in linklist
Public Function FindNode(ByVal iValue As Integer) As Node
Dim curNode As Node = m_head
While Not (curNode Is Nothing)
If curNode.Value = iValue Then Return curNode
curNode = curNode.NextNode
End While
Return Nothing
End Function
'Swap the Node position in linked list
Public Function SwapPositions(ByVal iValue1 As Integer, _
ByVal iValue2 As Integer) As Boolean
Dim curNode As Node = m_head
Dim Node1 As Node = Nothing
Dim Node2 As Node = Nothing
Dim prevNode As Node = Nothing
Dim prevNode1 As Node = Nothing
Dim prevNode2 As Node = Nothing

If iValue1 = iValue2 Then
Return False
End If

While Not (curNode Is Nothing)
If (curNode.Value = iValue1) Then
prevNode1 = prevNode
Node1 = curNode
ElseIf (curNode.Value = iValue2) Then
prevNode2 = prevNode
Node2 = curNode
End If

If (Not (Node1 Is Nothing)) And (Not (Node2 Is Nothing)) Then
Exit While
End If

prevNode = curNode
curNode = curNode.NextNode
End While

If Node1 Is Nothing Or Node2 Is Nothing Then _
Return False

If (prevNode1 Is Nothing) Then
m_head = Node2
Else
prevNode1.NextNode = Node2
End If
If (prevNode2 Is Nothing) Then
m_head = Node1
Else
prevNode2.NextNode = Node1
End If
Dim tmp As Node = Node1.NextNode
Node1.NextNode = Node2.NextNode
Node2.NextNode = tmp

Return True
End Function
'Display
Public Sub Draw()
Dim curNode As Node = m_head
Debug.Write("List: ")
While Not (curNode Is Nothing)
Debug.Write(curNode.Value & " ")
curNode = curNode.NextNode
End While
Debug.WriteLine("")
End Sub
End Class
'Serialization implementation.
Public Class Ser
ReadOnly iMinValue As Integer = 1
ReadOnly iMaxValue As Integer = 9
Public Sub Scope1()
Dim list As LinkedList = New LinkedList()
Dim i As Integer
Debug.WriteLine("Entering Scope 1")
Debug.WriteLine("Creating and filling List ..")
For i = iMinValue To iMaxValue - 1
list.Add(i)
Next
SaveListToDisk(list)
Debug.WriteLine("Leaving Scope 1\n")
End Sub
Public Sub Scope2()
Debug.WriteLine("Entering Scope 2")
Dim list As LinkedList = LoadListFromDisk()
Debug.WriteLine("Swapping Entries")
Debug.WriteLine("Swapping 1 and 2")
list.SwapPositions(1, 2)
Debug.WriteLine("Swapping 3 and 4")
list.SwapPositions(3, 4)
Debug.WriteLine("Swapping 5 and 6")
list.SwapPositions(5, 6)
Debug.WriteLine("Swapping 7 and 8")
list.SwapPositions(7, 8)
SaveListToDisk(list)
Debug.WriteLine("Leaving Scope 2\n")
End Sub
Public Sub Scope3()
Debug.WriteLine("Entering Scope 3")
Dim list As LinkedList = LoadListFromDisk()
Debug.WriteLine("Swapping Random Entries")
Dim rnd As Random = New Random()
Dim num1, num2, i As Integer
For i = 0 To 15
While (True)
num1 = rnd.Next(iMinValue, iMaxValue + 1)
num2 = rnd.Next(iMinValue, iMaxValue + 1)
If num1 <> num2 Then
Exit While
End If
End While
Debug.WriteLine("Swapping " & num1 _
& " and " & num2)
list.SwapPositions(num1, num2)
Next
SaveListToDisk(list)
Debug.WriteLine("Leaving Scope 3\n")
End Sub

Public Sub Scope4()
Debug.WriteLine("Entering Scope 4")
Dim list As LinkedList = LoadListFromDisk()
Debug.WriteLine("Removing Entries")
Debug.WriteLine("Removing 1")
list.Remove(1)
Debug.WriteLine("Removing 2")
list.Remove(2)
Debug.WriteLine("Removing 3")
list.Remove(3)
SaveListToDisk(list)
Debug.WriteLine("Leaving Scope 4\n")
End Sub
Private Function LoadListFromDisk() As LinkedList
Debug.WriteLine _
("Deserializing LinkedList from file ..")
Dim s As Stream = New FileStream("linkedlist.bin", FileMode.Open)
Dim b As BinaryFormatter = New BinaryFormatter()
'This casting requires option strict option of vb to
' be off
'While compliing the code use the
' switch /optionstrict-
Dim list As LinkedList = b.Deserialize(s)

s.Close()
list.Draw()
Return list
End Function
Private Sub SaveListToDisk(ByRef list As LinkedList)
list.Draw()



Debug.WriteLine _
("Serializing LinkedList to file ..")

Dim s As Stream = New FileStream("linkedlist.bin", FileMode.Create)



Dim b As BinaryFormatter = New BinaryFormatter()
b.Serialize(s, list)
s.Close()
End Sub

End Class
Sub Main()
Dim SerSample As Ser = New Ser()
With SerSample
.Scope1()
.Scope2()
.Scope3()
.Scope4()
End With
End Sub

End Module

Using Delegate

' Delegate Definition
Public Delegate Sub mySingleCast(ByVal value As String)
Class myEcho
Public Sub Shout(ByVal Value As String)
MsgBox(Value)
End Sub
End Class
Class proVerb
Public Sub Verb(ByVal Value As String)
MsgBox(Value)
End Sub
End Class
Private Sub btnDelegate_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnDelegate.Click
' Declaration Section
Dim objMyEcho As New myEcho()
Dim objproVerb As New proVerb()
Dim dlgt As mySingleCast

' Assign the Function Pointer to delegate
dlgt = New mySingleCast(AddressOf objMyEcho.Shout)

' Call the Invoke Method of Delegate
dlgt.Invoke("Enjoy .Net Programming")

' Assign the Function Pointer of another class to delegate
dlgt = New mySingleCast(AddressOf objproVerb.Verb)

' Calling Invoke Method of Delegate
dlgt.Invoke("God is Great")

Using Threading

Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Imports System.Threading


Class MyThread
Shared Sub main()
Try
'Declare a Thread and Assign it to a Methord Hi
Dim t As New thread(AddressOf hi)
'Declare Another Thread and assign it to Bye
Dim b As New thread(AddressOf bye)

'Set the priority level for each thread
t.Priority = ThreadPriority.Normal
b.Priority = ThreadPriority.Lowest

'Start the thread execution
t.start()
b.start()
Catch e As exception
msgbox(e.tostring)
End Try
End Sub

Shared Sub hi()
'Infinite Loop CTRL + C to Exit
Do While True
console.writeline("hi")
Loop
End Sub

Shared Sub bye()
'Infinite Loop CTRL + C to Exit
Do While True
console.writeline("bye")
Loop
End Sub
End Class

Saving Images into database

FieldName Type
Pic OLE Object
FileSize Text

The following code establishes a database connection and inserts a file in the "Pic" field.

Save the file as SaveImage.vb

Imports System
Imports System.IO
Imports System.Data

Public Class SaveImage
Shared Sub main()
'Delaclare a file stream object
Dim o As System.IO.FileStream
'Declare a stream reader object
Dim r As StreamReader
Dim jpgFile As String
Console.Write("Enter a Valid .JPG file path")
jpgFile = Console.ReadLine
If Dir(jpgFile) = "" Then
Console.Write("Invalid File Path")
Exit Sub
End If
'Open the file
o = New FileStream(jpgFile, FileMode.Open, FileAccess.Read, FileShare.Read)
'Read the output in a stream reader
r = New StreamReader(o)
Try
'Declare an Byte array to save the content of the file to be saved
Dim FileByteArray(o.Length - 1) As Byte
o.Read(FileByteArray, 0, o.Length)
'Open the DataBase Connection, Please map the datasource name to match the 'Database path
Dim Con As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.3.51;Persist Security Info=False;Data Source=DbImages.mdb")
Dim Sql As String = "INSERT INTO DbImages (Pic,FileSize) VALUES (?,?)"
'Declare a OleDbCommand Object
Dim CmdObj As New System.Data.OleDb.OleDbCommand(Sql, Con)
'Add the parameters
CmdObj.Parameters.Add("@Pic", System.Data.OleDb.OleDbType.Binary, o.Length).Value = FileByteArray
CmdObj.Parameters.Add("@FileSize", System.Data.OleDb.OleDbType.VarChar, 100).Value = o.Length
Con.Open()
CmdObj.ExecuteNonQuery()
Con.Close()
Catch ex As Exception
Console.Write(ex.ToString)
End Try
End Sub
End Class

Compile the file as
vbc SaveImage.vb /r:system.data.dll /r:system.dll
A file will be inserted in the Database each time we execute SaveImage.exe.

Menghitung Umur

Fungsi Menghitung Waktu


» Publisher: Mustakin Caca | Post: 2/14/2006 | Click: 588


Print Page Favorites

Function cari_umur(TanggalAwal As Date, TanggalAkhir As Date) As String
On
Error GoTo salah
Dim tahun As Long, bln As Integer, bulan As Integer, thn As Long
Dim Counter As Integer, hari As Integer

hari = Format(CDate(TanggalAwal), "d")
bln = Format(CDate(TanggalAwal), "m")
thn = Format(CDate(TanggalAwal), "yyyy")

Do Until (hari = Format(CDate(TanggalAkhir), "d")
And _
bln = Format(CDate(TanggalAkhir), "mm")
And _
thn = Format(CDate(TanggalAkhir), "yyyy"))
hari = hari + 1


If hari = Format(CDate(TanggalAwal), "d") Then
bulan = bulan + 1 'jumlah bulan
Counter = 0 'jumlah hari
If bulan = 12 Then
bulan = 0
tahun = tahun + 1 'jumlah tahun
End If
Else
Counter = Counter + 1
End If

If CDate(hari & "/" & bln & "/" & thn) = CDate(Trim(TanggalAkhir)) Then Exit Do
If bln = 1 And hari = 31 Then
bln = bln + 1: hari = 0
ElseIf bln = 2 And hari = 29 And thn Mod 4 = 0 Then
bln = bln + 1: hari = 0
ElseIf bln = 2 And hari = 28 And thn Mod 4 > 0 Then
bln = bln + 1: hari = 0
ElseIf bln = 3 And hari = 30 Then
bln = bln + 1: hari = 0
ElseIf bln = 4 And hari = 30 Then
bln = bln + 1: hari = 0
ElseIf bln = 5 And hari = 31 Then
bln = bln + 1: hari = 0
ElseIf bln = 6 And hari = 30 Then
bln = bln + 1: hari = 0
ElseIf bln = 7 And hari = 31 Then
bln = bln + 1: hari = 0
ElseIf bln = 8 And hari = 31 Then
bln = bln + 1: hari = 0
ElseIf bln = 9 And hari = 30 Then
bln = bln + 1: hari = 0
ElseIf bln = 10 And hari = 31 Then
bln = bln + 1: hari = 0
ElseIf bln = 11 And hari = 30 Then
bln = bln + 1: hari = 0
ElseIf bln = 12 And hari = 31 Then
bln = 1: thn = thn + 1: hari = 0
End If
Loop

cari_umur = Counter & " hari " & bulan & " bulan " & tahun & " tahun"
Exit Function
salah:
If Err.Number = 13 Then
MsgBox "format tanggal salah"
End If
End Function

Private Sub Command3_Click()
'Mulai tanggal - s/d tanggal
MsgBox cari_umur(CDate(Text1), CDate(Text2))
End Sub

Tuesday, October 2, 2007

Get Latest MSDN Magazine and code

Great link http://www.ftponline.com/vsm/
You will find latest MSDN magazine and MSDN code here.

Connect to website

' ----------------------------------------
' Required Imports :
'
' Microsoft.VisualBasic
' System
' ----------------------------------------

Dim baseUri As New Uri("http://www.it-medan.blogspot.com/")
Dim relativeUri As New Uri("images/index.htm?id=null")

' Compose absolute Uri using the base and the relative Uri.
Dim absoluteUri As New Uri(baseUri, relativeUri)

Dim absolute As String = absoluteUri.AbsolutePath()

Using Comparer

' ----------------------------------------
' Required Imports :
'
' System.Collections.Generic
' ----------------------------------------

Public Class IntegerComparer
Inherits Comparer(Of Integer)

Public Overrides Function Compare(ByVal param1 As Integer, ByVal param2 As Integer) As Integer
If param1 < param2 Then
' result = <0 if param1 < param2
Return -1
ElseIf param1 > param2 Then
' result = >0 if param1 > param2
Return 1
Else
' result = 0 if param1 = param2
Return 0
End If
End Function
End Class