Recent Posts

Monday, September 29, 2008

How to use an object as a data source in Visual Studio 2005 ?

This article can serve the following topics as well:

Step by step tutorial on how to display a data (bind a data) in the text box controls and data grid view in visual studio 2005.

This can be the perfect vb net tutorial or asp net tutorial for vb net three tier application or asp net application using asp net 2.0 and vb net 2.0. 
By reading this article learner can distinctly distinguish the presentation layer, business layer and data access layer and understand the logic of the code.

Main article starts here


In the .NET Framework 2.0, any object that exposes public properties can serve as a data source.
In this application I have just used one form and one class named customer to make the tutorial easier for the beginners.

To make the readers clear on what are the data in the customers and make the data binding clear, this application creates an array of Customer objects and uses the BindingContext to navigate through the array of objects in much the same way as you would navigate through records in a DataSet.

Step 1


First open a project in .net 2005 and add a form named Customer having following controls:

4 text boxes named txtCustName, txtCustAddress,txtCustPhone,txtCustMobile

4 labels and write the logical text

1 Data grid view named grdDisplay

3 buttons named cmdPrev, cmdNext,cmdExit


Step 2

Add a class named clsCustomer and write the following code:

Public Class clsCustomer
#Region "Private Declarations"

Private _mCustName As String
Private _mCustAdd As String
Private _mCustPhone As Long
Private _mCustMobile As Long


#End Region

#Region "Public Declarations"

Public Property CustName() As String
Get
Return _mCustName
End Get
Set(ByVal value As String)
_mCustName = value
End Set
End Property

Public Property CustAddress() As String
Get
Return _mCustAdd
End Get
Set(ByVal value As String)
_mCustAdd = value
End Set
End Property

Public Property CustPhone() As Long
Get
Return _mCustPhone
End Get
Set(ByVal value As Long)
_mCustPhone = value
End Set
End Property

Public Property CustMobile() As Long
Get
Return _mCustMobile
End Get
Set(ByVal value As Long)
_mCustMobile = value
End Set
End Property

#End Region
End Class

(Note in this above class I have declared the public properties of the customer)


Step 3

Now in the form add the follwoing code

Public Class Customer
Private Customers(3) As clsCustomer
Private myBinding As BindingManagerBase

' In the above declarations there is a customer collection of 4 customers and binding manager



Private Sub LoadCustomers()

' Customers can be loaded manually for testing purpose but
' here we can retrieve the information from the database
' for more on retrieve from the database go to 

' How to get data from sql server database from visual basic .net or asp.net application


Customers(0) = New clsCustomer
Customers(0).CustName = "Harry Potter"
Customers(0).CustAddress = "Potter Village"
Customers(0).CustMobile = 6665555
Customers(0).CustPhone = 999945444


Customers(1) = New clsCustomer
Customers(1).CustName = "Bat Man"
Customers(1).CustAddress = "Bat Cave"
Customers(1).CustMobile = 666
Customers(1).CustPhone = 999

Customers(2) = New clsCustomer
Customers(2).CustName = "Spiderman"
Customers(2).CustAddress = " Spider Web"
Customers(2).CustMobile = 111111
Customers(2).CustPhone = 2222222

Customers(3) = New clsCustomer
Customers(3).CustName = "Hulk"
Customers(3).CustAddress = "Hulk house"
Customers(3).CustMobile = 55555
Customers(3).CustPhone = 44444

End Sub

Private Sub cmdPrev_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPrev.Click

myBinding.Position -= 1

End Sub

Private Sub cmdNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNext.Click

myBinding.Position += 1

End Sub

Private Sub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click

Me.Close()

End Sub

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

LoadCustomers()
txtCustName.DataBindings.Add("Text", Customers, "CustName")
txtCustAdd.DataBindings.Add("Text", Customers, "CustAddress")
txtCustMobile.DataBindings.Add("Text", Customers, "CustMobile")
txtCustPhone.DataBindings.Add("Text", Customers, "CustPhone")
'Binding the text boxes to the customers object
myBinding = BindingContext.Item(Customers)

grdDisplay.DataSource = Customers


End Sub

End Class

Now run the application and look how it works.

The main objective of this application is to provide the knowlege of how to use the objects directly as a datasource.

The ability to work with your own business entity classes instead of DataTables can be beneficial in many situations, such as in ntier systems that require the user interface to be completely  ignorant of the type and structure of the underlying data stores for a given system. In such a situation, the presentation layer can retrieve a set of objects from a middle tier and bind those objects directly to the user interface.

Certainly object data sources are not appropriate for all applications, but in many situations they are an extremely powerful and useful option.

And Visual Studio 2005 makes data binding with objects amazingly easy.


References:
Introducing Microsoft Visual Basic 2005 for Developers
Microsoft Press


Read more!

Thursday, September 25, 2008

How to read or write ini file from visual basic .net Application?

Step 1

In a project add a module and add the following api declarations:

Private Declare Unicode Function WritePrivateProfileString Lib "kernel32" _
Alias "WritePrivateProfileStringW" (ByVal lpApplicationName As String, _
ByVal lpKeyName As String, ByVal lpString As String, _
ByVal lpFileName As String) As Int32

Private Declare Unicode Function GetPrivateProfileString Lib "kernel32" _
Alias "GetPrivateProfileStringW" (ByVal lpApplicationName As String, _
ByVal lpKeyName As String, ByVal lpDefault As String, _
ByVal lpReturnedString As String, ByVal nSize As Int32, _
ByVal lpFileName As String) As Int32


Step 2

Write the following functions to read or write ini files


Public Sub writeIni(ByVal iniFileName As String, ByVal Section As String, ByVal ParamName As String, ByVal ParamVal As String)
Dim Result As Integer

Result = WritePrivateProfileString(Section, ParamName, ParamVal, iniFileName)

End Sub

Public Function ReadIni(ByVal IniFileName As String, ByVal Section As String, ByVal ParamName As String, ByVal ParamDefault As String) As String

Dim ParamVal As String
Dim LenParamVal As Long

ParamVal = Space$(1024)
LenParamVal = GetPrivateProfileString(Section, ParamName, ParamDefault, ParamVal, Len(ParamVal), IniFileName)

ReadIni = Left$(ParamVal, LenParamVal)


End Function


Step 3

Add a form and
a command button named cmdCheckIni
a label named lbldisplay
a text box named txtvalue

Now on the command button click event add the following:

Private Sub cmdCheckIni_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCheckIni.Click
Dim strFilepath As String
' create a file test.ini in the bin folder in your application path

strFilepath = My.Application.Info.DirectoryPath & "\test.ini"

lblDisplay.Text = ReadIni(strFilepath, "Logon", "LastUserId", "")
writeIni(strFilepath, "Logon", "LastUserId", txtValue.Text)
lblDisplay.Text = lblDisplay.Text & "!!!!" & ReadIni(strFilepath, "Logon", "LastUserId", "")

End Sub

your test.ini file should contain the following info
[Logon]
LastUserId=dd


Now you can run your application and test to see how it can store and retrieve the userID in the iniFile

This can be used both in Asp.net or Vb.net applications. The above code is written in visual basic 2005.


Read more!

Monday, September 22, 2008

10 Smart Javascript Techniques to Improve Your UI

here are many clever and useful ways to improve a site from the user interface perspective. A developer can find nearly any snippet of Javascript to achieve what he or she wants to accomplish.

read more | digg story


Read more!

Different ways of Binding Data in comboBox in visual basic net application


The following code can be used in asp net and net desktop applications.
It is good piece of code for visual basic programmer who are learning the visual basic net programming.

Binding with the array of animals


dim mypets() as String = {"Cat","Dog","Mouse","Cow","Horse","emu","chicken"}
combobox1.DataSource=mypets
combobox1.SelectedIndex=0


Binding with the array list

dim mypets as new ArrayList
with mypets
.Add("Cat")
.Add("Dog")
.Add("Mouse")
.Add("Cow")
.Add("Horse")
.Add("emu")
.Add("Chicken")
End With

combobox1.DataSource=mypets

combobox1.SelectedIndex=0


Binding with the dataset where data is filled from the database
private dsPets as new Dataset

First we have to fill the dataset dsPets from the sql server database or any other databases
and then use the following code to bind it to the combobox

With combobox1
.Datasource=dspetss.Tables("Pets")
.Displaymember="PetName"
.ValueMember="PetID"
End With

combobox1.SelectedIndex=0
txtDisplay.Text=ctype(combobox1.SelectedValue,String)


Binding with the dataview where data is filled from the database

private dvPets as new DataView

We have to fill up the dataview dvPets from the sql server database or any other database source and then use the following code to bind the combobox. 

With combobox1
.Datasource=dvPets
.Displaymember="PetName"
.ValueMember="PetID"
End With

combobox1.SelectedIndex=0
txtDisplay.Text=ctype(combobox1.SelectedValue,String)


Read more!

Sunday, September 21, 2008

Visual Basic 2005 ( vb .net 2.0) Introduces “My Object”

My object which is introduced by vb net 2005.
This is very useful for the software developers who are trying to learn visual basic in vb .Net 2.0 environment.
It is very helpful for the visual basic programmers to get various information about the computer where the application is running, previously each process were to be coded manually but now this new feature has just made it too simple to use.
The functionality previously available by calling COM libraries or the Win32 API, are now easily accessible through My Object.

Visual Basic 2005 now provides a “speed dial” called The My Object.
By using The My Object, you have the ability to easily access computer, application, and user information, as well as obtain access to Web services and forms.
It is important to understand that The My Object is accessible to you only when writing Visual Basic .NET applications and is not directly available to you when using C#.

Some common questions answered by My objects are listed below:

1. How can I get the user name of the windows user from visual basic net?

My.User.Name

2. How can I check if the windows user is an Admin from visual basic net?

My.User.IsInRole("BUILTIN\Administrators")

3. What is name of the computer where the application is running (vb net)?

My.Computer.Name

4. What is the local or GMT time in the computer where the application is running (vb net)?

My.Computer.Clock.LocalTime
My.Computer.Clock.GmtTime

5. What is the resolution of the computer where the application is running (vb net)?

My.Computer.Screen.Bounds.Width & _
"x" & My.Computer.Screen.Bounds.Height

6. Check if the network of the computer is available where the application is running from vb net application?

My.Computer.Network.IsAvailable

7. What is the operating system of the application where the application is running from vb net?

My.Computer.Info.OSFullName


8. What is the directory path of the application from vb net?

My.Application.Info.DirectoryPath

9. How to get collection of open Ports in the computer from vb net?

My.Computer.Ports.SerialPortNames.Item(1).ToString

10. How to play an Audio (.wav) file stored in the computer from vb net?

Here strFile is the path of the file located
Dim strFile As String
strFile = "C:\Program Files\Messenger\online.wav"
Me.lblDisplay.Text =my.Computer.Audio.Play(strFile)

11. How can I get Access to System’s Clipboard from vb net?

If My.Computer.Clipboard.ContainsText = True Then

Me.lblDisplay.Text = My.Computer.Clipboard.GetText.ToString()
ElseIf My.Computer.Clipboard.ContainsImage = True Then
‘ code for getting image
ElseIf My.Computer.Clipboard.ContainsAudio = True Then
‘ code for getting Audio file
ElseIf My.Computer.Clipboard.ContainsData("dd") = True Then
‘ code for getting data “dd”
End If


12. How can I read or write registry from vb net?

my.Computer.Registry.


13. How can I issue ping command and find out if the host is reachable or not from vb net?

Dim pingResult As Boolean
PingResult= my.Computer.Network.Ping(txtPing.Text)
If pingResult = True Then
MessageBox.Show("Ping of IP:" & txtPing.Text & " succeeded")
Else
MessageBox.Show("Ping of IP:" & txtPing.Text & " was not Successful")
End If

14. How can I read all the text in a file from vb net?

filePath is the path of the file
my.Computer.FileSystem.ReadAllText(filePath)

15. How to copy or move folders from vb net?

My.Computer.FileSystem.CopyDirectory(sourcePath, targetPath, True, True)

The preceding True will overwrite the directory or a file if it already exists in the target path.

16. How to determine the location of My Documents folder with one line of code from vb net application?

MessageBox.Show(My.Computer.FileSystem.SpecialDirectories.MyDocuments)

Reference:

Introducing Microsoft Visual Basic 2005 for Developers

Microsoft Press


Read more!

Tuesday, September 16, 2008

Top 10 Must Have SEO Tools

A compiled list of best free SEO tools from around the web. The list includes keyword research tools, keyword discovery tools, Link analysis Tools, alternate keyword ideas, Rank Checker Tools, Link Finder Tool, keyword trends Tool and more. A must have list for a SEO beginner or Pro.

read more | digg story


Read more!

Tuesday, September 9, 2008

How to open a crystal reports from VB Application?

Instead of using crystal reports viewer we can directly open a crystal reports.

Sometimes we have to print the reports directly to the printers for the items
like printing the receipt.

In those cases we don't need to view the receipt on the screen.
Also some businesses require just to print the report, so that user can't
reprint the receipt again and put the transaction on cancelled transaction.

Also if you guys are wondering how to directly print the crystal reports to
the printer without opening the report then this is also solved in the
following example.

First add the crystalreports object named CReport in the form

Private Sub PrintReceipt(ByVal lngtranno As Long, strNewReg As String)
Dim CLName As String

Me.CReport.Connect = "dsn=testDSN;UID=test;PWD=test"
Me.CReport.SelectionFormula = "({Account.TranNo})=" & lngtranno & " AND

({Registration.RegNo})='" & strNewReg & "'"
Me.CReport.Formulas(0) = "OrgName='" & MDIMain.lblOrgName.Caption & "'"
Me.CReport.Formulas(1) = "User='" & MDIMain.lblUser.Caption & "'"

Me.CReport.ReportFileName = App.Path + "\Report\rptReceiptNew.rpt"
Me.CReport.DiscardSavedData = True
' Me.CReport.Destination = crptToPrinter
' Me.CReport.PrintReport


Me.CReport.WindowState = crptMaximized
Me.CReport.Action = 1

End Sub

In the above function PrintReceipt

first the report object is connected.
And the selection formula is provided to filter the data
Passing the values to the report fromulas
Providing the report path where the report is located.
Discard saved data will refresh the report with new data.

Destination provides where the report is to be printed
PrintReport prints the report directly.
( if you just want to show the report on sreen then disable these lines)





Read more!

Wednesday, September 3, 2008

How to serialize or restore Serialized File in .Net?

What is Serialization?

serialization is process of converting object into stream

Lets learn how to serialize and restore serialized file
In the following lines I will show how we can serialize a class in binary and soap format.


1. First create a class with the tag in front which denotes that class is serializable.

Public Class Serilize

Public Title As String
Public Number As Int16

End Class


2. create a form and add the following imports and code

Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization.Formatters.soap

' this sub would create the instance of the class and add in the arraylist and then finally save the 'object in Serilize.txt file which can be viewed in notepad

Sub SaveSerializedFile()
Dim lst As New ArrayList
Dim obj As New Serilize

obj.Title = "This is First title"
obj.Number = 1
lst.Add(obj)

obj = New Serilize
obj.Title = "This is Second Title"
obj.Number = 2
lst.Add(obj)

obj = New Serilize
obj.Title = "This is third Title"
obj.Number = 3
lst.Add(obj)

Dim s As New FileStream("Serilize.txt", FileMode.Create)

'Dim f As New BinaryFormatter
' If we want to serilize the object using binary formatter then
' we have to disable the soap formatter and enable Binaryformatter
' declarations.


Dim f As New SoapFormatter
f.Serialize(s, lst)
s.Close()
End Sub


Sub RestoreSerializedFile()
Dim s = New FileStream("Serilize.txt", FileMode.Open)

'Dim f As BinaryFormatter = New BinaryFormatter
' If we want to serilize the object using binary formatter then
' we have to disable the soap formatter and enable Binaryformatter
' declarations.


Dim f As SoapFormatter = New SoapFormatter

Dim RestoredList As ArrayList
RestoredList = CType(f.Deserialize(s), ArrayList)
s.close()
Dim x As Serilize
For Each x In RestoredList
txtDisplay.Text = txtDisplay.Text & x.Title & " Lesson Number " & x.Number

Next


End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SaveSerializedFile()
End Sub


Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
RestoreSerializedFile()
End Sub


Read more!

Tuesday, September 2, 2008

How to reverse a string in .Net

This simple example explains many different small utilities in .Net that might
take hours to explore on the net.

First lets talk about reversing the string

This can be done in many ways but two simple ways I am explaining is as follows

1. first way

You can use StrReverse(string) function and to use that you have to use
imports Microsoft.visualbasic

This function will simply reverse the string .

2 The next way

Look at the following code for reversing the string

str = txtInput.Text


Dim charArray() As Char = str.ToCharArray
charArray.Reverse(charArray)

Dim alphabet As New String(charArray)


lblDisplay.Text = alphabet



The above piece of code also explains

How to convert string into character array?
Dim charArray() As Char = str.ToCharArray

and

How to reverse an array?

charArray.Reverse(charArray)

and

How to convert character array into string?

Dim alphabet As New String(charArray)


Read more!