Recent Posts

Monday, December 22, 2008

How to work with asp master Pages,asp Theme,asp skin and java script in asp.net 2005? Step by Step tutorial with c# net source code

To make the application consistent and have consistent page layouts we need to make our look and feel of our web pages standard and consistent.
A master page helps to maintain the consistency in the application with many pages or group of pages.
First a master page is designed and overall web application theme is declared in
the master page and then content pages are added where we display our application contents.
When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page.

It is very helpful to have master and content pages and after you know how to work on them it will be very easy and handy while developing web applications.
In this article i will explain step by step process of how to work on master and content pages and also explain you a simple step of using java script in the pages.

Step 1


First create a web project in asp .net 2005.

Step 2 (Adding Master Page)



Add a new Item in the project and select master page and name the master page appropriately.

Step 3 (Adding Theme Folder)

Right click on the web project and Asp.net folder and click on theme and you will find App_Themes and one more theme folder added to your project. The folder can be renamed as per your needs, in this article i have renamed it to BlueTheme.
Theme defines the overall theme you want to use for your project and can have skin and .css files.

Step 4 (Adding Css and skin files)

Now right click the BlueTheme folder and add new item and click style sheet and give the appropriate name in this article i have named it BlueTheme.css.
Similarly right click the BlueTheme folder and add new item and click skin file and name it accordingly, I have named it MyTheme.skin here.

step 5 (Adding Code in skin and css)

In MyTheme.skin i have added the following code:

asp:Label runat="server" CssClass="RedLabel"
asp:Label runat="server" CssClass="BlueLabel" SkinID="BlueText"

Now in this above code we can see cssclass "Bluelabel" has skinID "BlueText" that means if lables used in the application then it appears red color unless it is given skin id "BlueText" then it appears blue.

I this this explains how the skin file works, this should be sufficient to understand the skin.
Similarly in css I have used the code that defines the whole application theme:


Step 6 (Adding Code in the Master page)

Add the following code in your master page:





Now in above code snipplet you can see the following section :

ContentPlaceHolder ID="MainContent"

This is the place where your main content pages show up and i have renamed its id to "MainContent".
In the above code i have used the following section:


(Note: we can easily find various calendar java scripts on web try google getting it. Or i have provided the link to download all the required files below this article.)

Now i am going to use this java script code to show calendar in our web page.
Now when we include this javascript code in master page then it is accessible to
all the content pages that we use. So only one include in Master page will be
very helpful and manageable code while developing other content pages.

Step 7 (Adding the content page)

To add the content page just right click on the project and click add new item and select web form and give the appropriate name.



Remember to tick the two checkboxes on the right indicating place code in separate file : This will allow to have separate code behind page.
select master page : This will allow to select the master page for this content page.

Step 8 (Adding code in the content Page)
Add the following code in the content page:



In the above code note the following snippet:

Over this code "ctl00_MainContent_txttoDate" this is the textbox control placed in content page.
In the above code note the following snipplet on the top of the page:
Theme="BlueTheme"
Now this will define the page on which theme to use.

Download source for How to work with asp master Pages,asp Theme,asp skin and java script in asp.net 2005?


Read more!

Friday, December 12, 2008

Get access to popular magazines like Penthouse, Playboy, MacWorld, PC magazine, MIT Technology Review for free.

This is really cool and works and you can actually get access to the following magazines. 

Follow the following steps to get access to all these  exciting magazines without subscription. 

Step 1 :

You need to have Mozilla Firefox internet browser installed in your PC, if you don't have it then download free internet browser from Mozilla Firefox Site



Step 2: 

Open Mozilla firefox and on your address bar type in "about:config"

Step3: 

Then type "useragent" in Filter bar

Step 4 

Now you will see 4 or 5 listing and check in your value column,  in one of those you will see firefox.

Double click that column and remove the value but copy it and save it somewhere so that later we have to change it to orginal configuration.

Now write the "Mobile Safari 1.1.3" in the value box.

Step 5 : 

Now try to open "zinio.com/iphone" from your address bar, you should get access to all the good magazines that require  magazine subscription

The full detail of this article is derived form the Digital inspiration blog .



Read more!

Wednesday, December 10, 2008

Read Wall Street Journal Articles for Free ( No registration Required)

I found this site where it shows how we can trick Wall Street Journal and get around its subscription and read full articles that were available to subscribers only.

Cool site to go through for all check it out :

Read Wall Street Journal Articles for Free from Digital Inspiration


Read more!

Sunday, December 7, 2008

Learn how to read a xml file from vb.Net application with full source code.

This small article will show you how to read the xml file for processing from the vb.net application. This can be very useful for Desktop or Asp.net application to process the xml files and for the beginners who will be willing to work with the web services and xslt.

Check the following steps to find out how to load and read a xml file:

1. Open an application in vb.net. 

2. Place a command button on the form.

3. on the command click write the following code.

 Dim myXMLdoc As New Xml.XmlDataDocument

Dim strFileName As String
            Dim strText As String

'Provide the path of the XML 
            strFileName = "C:test1.xml"
            

            Dim oFile As System.IO.File
            Dim oRead As System.IO.StreamReader

'Read the file from the provided path
            oRead = oFile.OpenText(strFileName)
            strText = oRead.ReadToEnd()

 'Selects the XML Text
        myXMLdoc.LoadXml(strText)
        Dim xnr As Xml.XmlNodeReader
        Dim xn As Xml.XmlNode
        Dim xe As Xml.XmlElement = myXMLdoc.DocumentElement

 'Selects the Single Node
        xn = myXMLdoc.SelectSingleNode("/Data/Name")
        If IsNothing(xn) = False Then
            xnr = New Xml.XmlNodeReader(xn)
            While xnr.Read
                If Not (xnr.Value = "") Then
                    Me.txtLatitude = xnr.Value
                End If
            End While
            xnr.Close()
        End If


Read more!

Tuesday, December 2, 2008

ObviouslySomething: Formatting Visual Basic 6 code for HTML

ObviouslySomething: Formatting Visual Basic 6 code for HTML


Read more!

Wednesday, November 19, 2008

Learn how to develop a three tier web application using (Asp.net) with source code

This article focuses on explaining how to code a three tier asp.net web application visual basic. Here I will be explaining how you can bind an object to the data grid and display the data from the database just by adding the references to the business logic and data access dlls.

Ok first open a web project in visual studio 2005 and in Default.aspx add a Gridview and name it grdStudents

Now you need to add the references to the business tier dlls and data tier dlls.

Add the following references to the project:

ThreeTierVB.BusinessLogic.dll
ThreeTierVB.DataAccess.dll
ThreeTierVB.Info.dll


How to get these dlls is explained in detail in How to develop a three tier .net application using visual basic with source Code.

Now after adding the references to the project
copy and paste the following code in the code behind page (Default.aspx.vb) of your Default.aspx

Partial Class _Default
Inherits System.Web.UI.Page
Private _students As ThreeTierVB.Info.StudentInfo()

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
BindGrid()
End Sub

Private Sub BindGrid()
Dim clsS As New ThreeTierVB.BusinessLogic.StudentsBLL
_students = clsS.GetStudentByClass(1)

With grdStudents

.DataSource = _students
.Columns.Item(0).Visible = False
.Columns.Item(3).Visible = False

.DataBind()
End With
End Sub
End Class

In the above code we have declared the collection of students and bind the collection of the students to the gridview grdStudents.

Now run the application and you can see the grid filled with data.

Now lets make the grid a bit preety by adding the following code in your default.aspx page:

just replace the grid view code with the following:


Now run the application and see the new look of the grid.

Thus now you can code any three tier web or desktop applicaion in .net.


Read more!

Thursday, November 6, 2008

Learn how to develop a three tier .net application using (vb.net) with visual basic source code

This article focuses on explaining how to code a three tier application using
visual basic .net . Here I will be explaining each an every step from creating
new sql server database table to running the vb program going through most of
the vb code in the application and also providing some links that I find useful
for the learners.In this visual basic net tutorial, I will be mainly focusing
the beginners to mid level .net programmers so I will try to expalin each and
every detail as I can but even that if I missed something don't hesitate to post
a comment on this blog article. I hope this will be a good vb tutorial for
whoever is interested in it and this application can be easily extended to asp
net three tier application for web developers.

Now lets start (Note: Source code of this tutorial is available at the end of
this article)

Step 1

Let's first create two tables in the sql server database with the following sql
query:

Table 1 : Class

CREATE TABLE [dbo].[Class](
[ClassID] [int] IDENTITY(1,1) NOT NULL,[ClassName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK_Class] PRIMARY KEY CLUSTERED
(
[ClassID] ASC) ON [PRIMARY]
) ON [PRIMARY]

(Note: You can create the tables yourself in Microsoft Sql Server Management
Studio and it looks like the image shown below)


Table 2 : Students

CREATE TABLE [dbo].[Students](
[StudentID] [int] IDENTITY(1,1) NOT NULL,
[StudentName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[ClassID] [int] NULL,
CONSTRAINT [PK_Students] PRIMARY KEY CLUSTERED
(
[StudentID] ASC
) ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [dbo].[Students] WITH CHECK ADD CONSTRAINT [FK_Students_Class]

FOREIGN KEY([ClassID])
REFERENCES [dbo].[Class] ([ClassID])

(Note: You can create the tables yourself in Microsoft Sql Server Management
Studio and it looks like the image shown below)




Now here you have to create a Foreign key constraint to classID (If you don't
know what foreign key is then you can (Learn Foreign key)

Step 2

Now create a window project in visual basic and name it ThreeTierVB and save
your project and solution in your desired Path.



Add Two folders in the project by right clicking the ThreeTierVB on your
solution explorer and
Add --> New Folder and name them
Forms
GlobalClasses

Right click the forms Folder and add a windows form and name it frmStudent then
add the following components in the form and name them accordingly as follows:

1 combobox
name:cboClass

4 command Buttons
name: cmdNew
Text: New Class

name: cmdClassSave
Text: Save Class

name: cmdSave
Text: Save

name: cmdExit
Text: Exit

2 text boxes
name: txtClassName

name: txtStudentName

1 Datagridview

name: grdStudents

A quick snapshot of my form is shown below:



(add the labels and name the labels appropriately and also you can place the controls wherever you like them comfortable)

Step 3

Now before going to the coding lets create the three tier structure so that it
would be easier to understand for beginner programmers.

1. Add a new Class library to the solution by going to
File --> Add --> New project

2. Select the class library and name it ThreeTierVB.BusinessLogic and
add two folders BLLClasses and GenericClasses as explained on step 2


3. Similarly add another class library as above and name it ThreeTierVB.DataAccess
and add three folders and name them DataClasses, GlobalClasses and Modules

4. Similarly add another class library as above and name it ThreeTierVB.Info
and add a folder and name it InfoClasses


Now your solution Explorer should look like the following



Step 4

Now we have got 4 projects in our solution Explorer. Lets make the idea clear
Now here we are making DataAccess , BusinessLogic and GuI the three tiers and
Info is the info for all the three tiers, so we have to be clear on what get
access to what.

Add the references to the projects

1. ThreeTierVB which is our presentation tier and this needs to know the info
and business logic but it doesn't worry about Dataaccess.


For this right click on ThreeTierVB project and Addreference in the add reference screen go to projects and select ThreeTierVB.Businesslogic and ThreeTierVB.Info by clicking ctrl and click ok button.



2. Similarly Businesslogic only needs to know the DataAccess and info so as done
in 1 add references to ThreeTierVB.DataAccess and ThreeTierVB.Info.


3. Now in DataAccess project just add ThreeTierVB.Info as a reference.

Step 5

Add the required classes in the projects to run the application now as we have
set up all the necessary references.

1. In ThreeTierVB.Info add two classes and name them as ClassInfo and StudentInfo in ClassInfo Write the following code:

Public Class ClassInfo 

#Region "Private Member Declarations"

Private mClassId As Integer
Private mClassName As String

Private mAction As Byte

#End Region

#Region "Public Properties"

Public Property Action() As Byte
Get
Return mAction
End Get
Set(ByVal value As Byte)
mAction = value
End Set
End Property

Public Property ClassID() As Integer
Get
Return mClassId
End Get
Set(ByVal value As Integer)
mClassId = value
End Set
End Property

Public Property ClassName() As String
Get
Return mClassName
End Get
Set(ByVal value As String)
mClassName = value
End Set
End Property


#End Region

End Class

In StudentInfo Write the following code:

Public Class StudentInfo

#Region "Private Member Declarations"

Private mStudentID As Integer
Private mStudentName As String
Private mClassID As Integer

Private mAction As Byte

#End Region

#Region " Public Properties"

Public Property Action() As Byte
Get
Return mAction
End Get
Set(ByVal value As Byte)
mAction = value
End Set
End Property

Public Property StudentID() As Integer
Get
Return mStudentID
End Get
Set(ByVal value As Integer)
mStudentID = value
End Set
End Property

Public Property ClassID() As Integer
Get
Return mClassID
End Get
Set(ByVal value As Integer)
mClassID = value
End Set
End Property

Public Property StudentName() As String
Get
Return mStudentName
End Get
Set(ByVal value As String)
mStudentName = value
End Set
End Property
#End Region

End Class

These two classes will act as objects of student and class throughout the
solution.

Now your Solution Explorer will look like the following:


2. In ThreeTierVB.DataAccess

In DataClasses folder add ClasDB and StudentsDB classes and in GlobalClasses
folder add sqlHelp class and add a module modDB in modules folder.
I will just provide the code below for this tutorial but for full details on how
to access data from the database you can check How to insert record in SQL
server database from VB.Net
?

Now in SQLHelp class add the following code:

Imports System.Data.SqlClient


Public NotInheritable Class SqlHelp

'Since this class provides only static methods, make the default constructor private to prevent
'instances from being created with "new SqlHelper()".


Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim isTran As Boolean
Private trans As SqlTransaction
Dim connStr As String

Private Function Connect() As Boolean
Dim bln As Boolean
' Try
If conn Is Nothing Then
bln = ReadDatabseConfig(strDBConfFile)
If bln = True Then
conn = New SqlConnection(connStr)
End If
End If
If conn.State = ConnectionState.Closed Then
conn.Open()
End If

Exit Function

End Function

Public Sub BeginTransaction()

If isTran Then Return
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
trans = conn.BeginTransaction()
isTran = True
End Sub

Public Sub CommitTransaction()
If Not isTran Then Return
trans.Commit()
conn.Close()
trans = Nothing
isTran = False
End Sub

Public Sub RollBackTransaction()
If Not isTran Then Return
trans.Rollback()
conn.Close()
trans = Nothing
isTran = False
End Sub

Public Sub CloseConn()
If Not conn Is Nothing Then
If Not conn.State = ConnectionState.Closed Then

conn.Close()
End If
End If
End Sub

Public Function ExecuteQuery(ByVal strCmdTxt As String) As Boolean
Dim intRows As Integer

If conn.State = ConnectionState.Closed Then
Connect()
End If

cmd = New SqlCommand
cmd.Connection = conn
cmd.CommandText = strCmdTxt
cmd.CommandType = CommandType.Text

If Not isTran Then
intRows = cmd.ExecuteNonQuery()
conn.Close()
Else
cmd.Transaction = trans
intRows = cmd.ExecuteNonQuery()

End If

If intRows> 0 Then
ExecuteQuery = True
Else
ExecuteQuery = False
End If

End Function

Public Function ExecuteAndGetID(ByVal strCmdTxt As String, Optional ByVal

blnNonID As Boolean = False) As String

If conn.State = ConnectionState.Closed Then
Connect()
End If
If Not blnNonID Then
strCmdTxt = strCmdTxt & " ; select scope_Identity();"
End If
cmd = New SqlCommand
cmd.Connection = conn
cmd.CommandText = strCmdTxt
cmd.CommandType = CommandType.Text

If Not isTran Then
ExecuteAndGetID = CStr(cmd.ExecuteScalar())
conn.Close()
Else
cmd.Transaction = trans
ExecuteAndGetID = CStr(cmd.ExecuteScalar())
End If

End Function


Public Function ExecuteAndGetReader(ByVal strCmdTxt As String) As

SqlDataReader

If conn.State = ConnectionState.Closed Then
Connect()
End If

cmd = New SqlCommand
cmd.Connection = conn
cmd.CommandText = strCmdTxt
cmd.CommandType = CommandType.Text

If Not isTran Then
ExecuteAndGetReader = cmd.ExecuteReader

Else
cmd.Transaction = trans
ExecuteAndGetReader = cmd.ExecuteReader
End If

End Function

Public Function ExecuteAndGetRow(ByVal strCmdTxt As String) As DataRow

Dim dt As DataTable
Dim da As SqlDataAdapter
Dim row As DataRow

If conn.State = ConnectionState.Closed Then
Connect()
End If
cmd = New SqlCommand
cmd.Connection = conn
cmd.CommandText = strCmdTxt
cmd.CommandType = CommandType.Text
dt = New DataTable
If Not isTran Then

da = New SqlDataAdapter(cmd)
Else
cmd.Transaction = trans
da = New SqlDataAdapter(cmd)
End If

da.Fill(dt)
da.Dispose()
row = dt.Rows(0)
ExecuteAndGetRow = row

End Function


Public Function getDataset(ByVal strCmdTxt As String) As DataSet
Dim da As SqlDataAdapter = New SqlDataAdapter
Dim ds As DataSet = New DataSet

If conn.State = ConnectionState.Closed Then

Connect()
End If

cmd = New SqlCommand
cmd.Connection = conn
cmd.CommandText = strCmdTxt
cmd.CommandType = CommandType.Text
If isTran Then
cmd.Transaction = trans
End If
da.SelectCommand = cmd
da.Fill(ds)
If Not isTran Then
conn.Close()
End If
Return ds

End Function

Public Sub New()

If Not Connect() Then
Exit Sub
End If
End Sub

Private Function ReadDatabseConfig(ByVal filename As String) As Boolean

Dim result As Boolean
Dim strDataSource As String = ""
Dim strInitialCatalog As String = ""
Dim strUserID As String = ""
Dim strPassword As String = ""

Dim sr As New IO.StreamReader(filename)
Dim ln As String = sr.ReadLine
While IsNothing(ln) = False
If ln.StartsWith("DataSource") = True Then
strDataSource = getConfigValue(ln)
ElseIf ln.StartsWith("DBaseName") = True Then
strInitialCatalog = getConfigValue(ln)
ElseIf ln.StartsWith("UserID") Then
strUserID = getConfigValue(ln)
ElseIf ln.StartsWith("Password") = True Then
strPassword = getConfigValue(ln)

End If
ln = sr.ReadLine
End While
sr.Close()
connStr = "Data Source=" & strDataSource & ";" & "Initial Catalog=" &

strInitialCatalog & _
";User ID=" & strUserID & ";Password=" & strPassword
result = True
ReadDatabseConfig = result

End Function

Private Function getConfigValue(ByVal line As String) As String
Dim values() As String = Split(line, "=")
Dim reply As String = values(1).Trim

Return reply
End Function
End Class

In Module modDB add the following code

Module modDB
Public strDBConfFile As String = "C:\DBConfig.ini"
Public Enum FlagAction
Insert = 1
Update = 2
Delete = 3
NoAction = 0
End Enum
End Module

Similarly in ClassDB add the following code

Imports System.Data.SqlClient
Imports ThreeTierVB.Info

Public Class classDB

' The function below will Delete the row of the class table with the provided
class ID. But to do this we have to first delete the related students in the
class because class has relation with the student table, this is the one of the
advantages of relational database.


Public Function DeleteClass(ByVal ClassID As Integer) As Boolean
Dim strSql As String
Dim objdb As New SqlHelp

strSql = "Delete from Students where ClassID= " & ClassID
objdb.ExecuteQuery(strSql)
objdb = New SqlHelp
strSql = "Delete from Class where ClassID= " & ClassID
objdb.ExecuteQuery(strSql)

Return True
End Function

' The function below gets all the rows of the class table and returns the
classInfo() collection so that this collection can be used in presentation
layer.


Public Function GetClass() As ClassInfo()
Dim strSql As String
Dim objdb As New SqlHelp

strSql = "Select * from Class"
Dim dr As SqlDataReader = objdb.ExecuteAndGetReader(strSql)
Dim arr As New ArrayList
While dr.Read

Dim cls As ClassInfo = New ClassInfo
cls.ClassID = IIf(IsDBNull(dr("ClassID")), 0, dr("ClassID"))
cls.ClassName = IIf(IsDBNull(dr("ClassName")), "", dr("ClassName"))
arr.Add(cls)
End While
dr.Close()
Return CType(arr.ToArray(GetType(ClassInfo)), ClassInfo())

End Function

'The function below gets the particular row of the class with the provided
classID and again returns the collection.


Public Function GetClass(ByVal ClassId As Integer) As ClassInfo()
Dim strSql As String
Dim objdb As New SqlHelp

strSql = "Select * from Class where classID= " & ClassId
Dim dr As SqlDataReader = objdb.ExecuteAndGetReader(strSql)
Dim arr As New ArrayList
While dr.Read

Dim cls As ClassInfo = New ClassInfo
cls.ClassID = IIf(IsDBNull(dr("ClassID")), 0, dr("ClassID"))
cls.ClassName = IIf(IsDBNull(dr("ClassName")), "", dr("ClassName"))
arr.Add(cls)
End While
dr.Close()
Return CType(arr.ToArray(GetType(ClassInfo)), ClassInfo())

End Function

' The below function gets the classInfo object as the parameter and saves the
record in the database and return true when inserted successfully.


Public Function Save(ByVal cls As ClassInfo) As Boolean
Dim strsql As String = ""
Dim objDB As New SqlHelp
If cls.Action = FlagAction.Insert Then
strsql = "Insert into Class (ClassName) " & _
"values( '" & cls.ClassName.Trim() & "')"
ElseIf cls.Action = FlagAction.Update Then
strsql = "Update Class set " & _
"ClassName='" & cls.ClassName.Trim() & "'" & _
" where ClassID=" & cls.ClassID
Else
Return False
End If
objDB.ExecuteQuery(strsql)
Return True
End Function

End Class

Similarly in StudentsDB add the following code

Imports System.Data.SqlClient
Imports ThreeTierVB.Info



Public Class StudentsDB

' The function deletes the student

Public Function DeleteStudent(ByVal StudentID As Integer) As Boolean
Dim strSql As String
Dim objDB As SqlHelp
strSql = "Delete from Students where StudentID=" & StudentID
objDB = New SqlHelp
objDB.ExecuteQuery(strSql)
Return True
End Function

'Retrieves the collection of student
Public Function GetStudent() As StudentInfo()
Dim objdb As New SqlHelp
Dim strSql As String = ""
strSql = "Select * from Students"
Dim dr As SqlDataReader = objdb.ExecuteAndGetReader(strSql)
Dim arr As New ArrayList
While dr.Read
Dim sI As StudentInfo = New StudentInfo
sI.ClassID = IIf(IsDBNull(dr("ClassID")), 0, dr("ClassID"))
sI.StudentID = IIf(IsDBNull(dr("StudentID")), 0, dr("StudentID"))
sI.StudentName = IIf(IsDBNull(dr("Student")), "", dr("StudentName"))
arr.Add(sI)
End While
dr.Close()
Return CType(arr.ToArray(GetType(StudentInfo)), StudentInfo())
End Function

'Retrieves the collection of student
Public Function GetStudent(ByVal StudentID As Integer) As StudentInfo()
Dim objdb As New SqlHelp
Dim strSql As String = ""
strSql = "Select * from Students where StudentID= " & StudentID
Dim dr As SqlDataReader = objdb.ExecuteAndGetReader(strSql)
Dim arr As New ArrayList
While dr.Read
Dim sI As StudentInfo = New StudentInfo
sI.ClassID = IIf(IsDBNull(dr("ClassID")), 0, dr("ClassID"))
sI.StudentID = IIf(IsDBNull(dr("StudentID")), 0, dr("StudentID"))
sI.StudentName = IIf(IsDBNull(dr("Student")), "", dr("StudentName"))
arr.Add(sI)
End While
dr.Close()
Return CType(arr.ToArray(GetType(StudentInfo)), StudentInfo())
End Function

'Retrieves the collection of student provided the classID as the parameter

Public Function GetStudentByClass(ByVal ClassID As Integer) As StudentInfo()
Dim objdb As New SqlHelp
Dim strSql As String = ""
strSql = "Select * from Students where ClassID= " & ClassID
Dim dr As SqlDataReader = objdb.ExecuteAndGetReader(strSql)
Dim arr As New ArrayList
While dr.Read
Dim sI As StudentInfo = New StudentInfo
sI.ClassID = IIf(IsDBNull(dr("ClassID")), 0, dr("ClassID"))
sI.StudentID = IIf(IsDBNull(dr("StudentID")), 0, dr("StudentID"))
sI.StudentName = IIf(IsDBNull(dr("StudentName")), "", dr

("StudentName"))
arr.Add(sI)
End While
dr.Close()
Return CType(arr.ToArray(GetType(StudentInfo)), StudentInfo())
End Function

' The function below saves the student

Public Function Save(ByVal student As StudentInfo) As Boolean
Dim strsql As String = ""
Dim objDB As New SqlHelp
If student.Action = FlagAction.Insert Then
strsql = "Insert into Students (StudentName,ClassID) " & _
"values( '" & student.StudentName.Trim() & "', " &

student.ClassID & ")"
ElseIf student.Action = FlagAction.Update Then
strsql = "Update Students set" & _
"StudentName='" & student.StudentName & "'," & _
" ClassID=" & student.ClassID & "' " & _
" where StudentID=" & student.StudentID
End If
objDB.ExecuteQuery(strsql)
Return True
End Function


End Class

3. In ThreeTierVB.BusinessLogic

In BLLClasses folder add classBll and studentsBll classes
and in classBLL add the following code:


Public Class classBLL
' This class now just acts as a bridge between the presentation layer and the
data access layer but later as the application grows most of the business cases
and business level logic can be implemented in this layer.


Public Function GetClass() As ThreeTierVB.Info.ClassInfo()
Dim db As New ThreeTierVB.DataAccess.classDB
Return db.GetClass()
End Function

Public Function GetClass(ByVal ClassID As Integer) As

ThreeTierVB.Info.ClassInfo()
Dim db As New ThreeTierVB.DataAccess.classDB
Return db.GetClass(ClassID)
End Function

Public Function Save(ByVal cls As ThreeTierVB.Info.ClassInfo)
Dim db As New ThreeTierVB.DataAccess.classDB
Return db.Save(cls)
End Function

Public Function Delete(ByVal intClassID As Integer)
Dim db As New ThreeTierVB.DataAccess.classDB
Return db.DeleteClass(intClassID)
End Function

End Class

Similarly in StudentBLL add the following code:

Public Class StudentsBLL
Public Function GetStudent() As ThreeTierVB.Info.StudentInfo()
Dim db As New ThreeTierVB.DataAccess.StudentsDB
Return db.GetStudent
End Function

Public Function GetStudent(ByVal studentID As Integer) As

ThreeTierVB.Info.StudentInfo()
Dim db As New ThreeTierVB.DataAccess.StudentsDB
Return db.GetStudent(studentID)
End Function

Public Function GetStudentByClass(ByVal intClassID As Integer)
Dim db As New ThreeTierVB.DataAccess.StudentsDB
Return db.GetStudentByClass(intClassID)
End Function

Public Function Save(ByVal student As ThreeTierVB.Info.StudentInfo)
Dim db As New ThreeTierVB.DataAccess.StudentsDB
Return db.Save(student)
End Function

Public Function Delete(ByVal intStudentID As Integer)
Dim db As New ThreeTierVB.DataAccess.StudentsDB
Return db.DeleteStudent(intStudentID)
End Function

End Class

Step 6 - Presentation Layer starts here

3. In ThreeTierVB

Now we have completed all the Business logic and Dataaccess coding and came back
to the form that we have left before.

Add the following code to the form: (Note if error you can copy individual
functions and subs and paste it in your form code page accordingly)


Public Enum FlagAction
Insert = 1
Update = 2
Delete = 3
NoAction = 0
End Enum

Public Class frmStudent

Private _students As ThreeTierVB.Info.StudentInfo()
Private _student As ThreeTierVB.Info.StudentInfo
Private _class As ThreeTierVB.Info.ClassInfo
Private _classes As ThreeTierVB.Info.ClassInfo()


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

LoadCbo()
LoadGrid(cboClass.SelectedValue)
End Sub

Sub LoadCbo()
' Get data for Class combo
Dim clsC As New ThreeTierVB.BusinessLogic.classBLL
_classes = clsC.GetClass
With cboClass

'to understand the following you can see How to use an object as a data source
in Visual Studio 2005
?
.DataSource = _classes
.DisplayMember = "ClassName"
.ValueMember = "ClassID"
End With
' cboClass.SelectedIndex = 0

End Sub

Sub LoadGrid(ByVal classID As Integer)
Dim clsS As New ThreeTierVB.BusinessLogic.StudentsBLL
_students = clsS.GetStudentByClass(classID)

With grdStudents

'to understand the following you can see How to use an object as a data
source in Visual Studio 2005
?
.DataSource = _students
.ColumnHeadersVisible = True

.ColumnHeadersDefaultCellStyle.ForeColor = Color.BurlyWood
.Columns.Item("ClassID").Visible = False
.Columns.Item("StudentID").HeaderText = "Student ID"
.Columns.Item("StudentName").HeaderText = "Student Name"
.Columns.Item("Action").Visible = False
End With
End Sub

Sub SaveClass()
Dim bln As Boolean
Dim clsC As New ThreeTierVB.BusinessLogic.classBLL
Dim clsInfo As New ThreeTierVB.Info.ClassInfo
clsInfo.ClassName = Me.txtClassName.Text.Trim
If cboClass.SelectedIndex = -1 Then
clsInfo.Action = FlagAction.Insert
Else
clsInfo.ClassID = cboClass.SelectedValue
clsInfo.Action = FlagAction.Update
End If
bln = clsC.Save(clsInfo)

If bln Then
MessageBox.Show("Data updated Successfully!!")
If cboClass.SelectedIndex = -1 Then
LoadCbo()
cboClass.SelectedIndex = UBound(_classes)
End If
_classes.SetValue(clsInfo, cboClass.SelectedIndex)

Refresh(cboClass.SelectedIndex)
grpNewClass.Visible = False
grpMain.Enabled = True
Else
MessageBox.Show("There is some error Updating record!! Try again")
End If
End Sub

Public Overloads Sub Refresh(ByVal intID As Integer)
cboClass.DataSource = _classes
cboClass.Refresh()
cboClass.SelectedIndex = intID

End Sub

Sub SaveStudent()
Dim bln As Boolean
Dim stuB As New ThreeTierVB.BusinessLogic.StudentsBLL
Dim stuInfo As New ThreeTierVB.Info.StudentInfo
Dim cls As ThreeTierVB.Info.ClassInfo
cls = _classes.GetValue(cboClass.SelectedIndex)
stuInfo.ClassID = cls.ClassID
stuInfo.StudentName = Me.txtStudentName.Text
stuInfo.Action = FlagAction.Insert
bln = stuB.Save(stuInfo)
MessageBox.Show("Student Data Updated Successfully!!")

End Sub

Private Sub cmdClassSave_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmdClassSave.Click

SaveClass()
End Sub

Private Sub cboClass_SelectedIndexChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles cboClass.SelectedIndexChanged

If cboClass.SelectedIndex = -1 Then Exit Sub
Dim cls As ThreeTierVB.Info.ClassInfo
grpNewClass.Text = "Change this Class Name"
cls = _classes.GetValue(cboClass.SelectedIndex)
LoadGrid(cls.ClassID)
Me.txtClassName.Text = cls.ClassName

End Sub

Private Sub cmdNew_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmdNew.Click
Me.txtClassName.Text = ""
Me.cboClass.SelectedIndex = -1
grpNewClass.Text = "Add New Class Name"
grpNewClass.BackColor = Color.MintCream
grpNewClass.Visible = True
grpMain.Enabled = False

Me.txtClassName.Focus()
End Sub

Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmdSave.Click
errDisplay.Clear()
If cboClass.SelectedIndex = -1 Then
errDisplay.SetError(Me.cboClass, "Please Select Class!!")
Exit Sub
End If
If Me.txtStudentName.Text.Trim() = "" Then
errDisplay.SetError(Me.txtStudentName, "Please Enter Student Name")

Exit Sub
End If
SaveStudent()

End Sub
Private Sub cmdExit_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles cmdExit.Click
Application.Exit()
End Sub

End Class

Now you can run the application and test, if you find errors try debugging it as
enough information was provided during this tutorial. If not you can download
this full application by clicking the link provided below.

Note: for website developers the presentation layer can be your web page and you
can bind your data to the _Students or _classes collection objects as well.


Download full three tier vb.net sample application


Read more!

Monday, October 20, 2008

Internet Explorer operation aborted error for blogspot (worked for me now hopefully)

I have a blogger blog and this internet explorer error is driving me insane, I tried to solve it for so long and spent hours on it. Once I thought i fixed the error and left my blog and didin't noticed it as i use firefox now google chrome, but later i found out after one of my friend told me my site is not working. I knew it was the same crappy IE problem and it happens on both internet explorer 7 or internet explorer 6.

Again now time for google and again found so many of them giving different advices some of them i tried are the following:



1 Fix the site meter

I was happy to see this site and thought it would work out after i replace the javascript code with its html code.
But surprise surprise!!! guys it didn't.

Now again google page no 2

2 Kontera blog it blogger ads widget: cause of operation aborted in IE

Again with a pretty relaxed mood i removed the widget from my blog but this wasn't the solution for me as well.

3 Other possible reason for such issue is Google Map API
I completely removed that from my blog to solve it ( It was not solved but I didn't brought back the map in my blog, I never wanted it again)

Later after going to different links in google i found microsft forum Fix operation aborted thread after going through, it clicked my head

Many people were commenting about different gadgets not working and later I experimented my site by removing some java script code of the widgets and ads and trying it one by one:

In my case blog catalog was the problem
Hence we can tell that the placement of the java script code in certain cases doesn't work so in that case we have to try one by one to find out which combination of the javascript placement is not working for you guys.

WE CAN CLEARLY THANK BILL GATES FOR THIS MANY HOURS PEOPLE SPENT WORKING ON HIS SHIT BROWSER!!!!


Read more!

Friday, October 10, 2008

Hotmail login trouble - Bad Request (Invalid Verb) Solved

I was having problem login to hotmail or getting into any of the microsoft sites.I am using vista and IE 7 but when i tried to login to hotmail account I get Bad request(Invalid verb) error and that's it i cannot login to my account.
After going through hours in the web and remembering what caused this errori finally found the solution

I remembered installing Windows Live onecare family safety and remembered after that hotmail had the problem.So I removed "Windows Live onecare Family Safety" from my computer and restarted the computer.You can do this going to control panel and unstall programs.
Then all worked sweetly (I don't know why microsoft didn't think about this). But guys for now it will work.


Read more!

Wednesday, October 1, 2008

Step by step tutorial to create a adobe pdf file from .net application?

While i was trying to build an automated program to generate pdf for my clients to send various files including receipts and their account details.

I came across iText# ( iTextSharp) which is an open source java library (itext) written entirely in C# for the .Net platform. Itext# is the library that allows you to generate pdf file on the fly after implementing it as an assembly.

So I went through it and discovered various simple ways to generate the pdfs from scratch. It was a very well written open source tool that can be used to create your own acrobat pdf writer program and so thought i should post it on my blog.
And here I am writing the complete tutorial

As i was browsing through the various sites while writing this I came across one article in code project which provided the same solution as I wanted to post here.

So for the complete knowledge on how to generate efficient pdfs from your .net applications you can go to:


also there are many tutorials on the iTextSharp Demo (asp .net 2.0)




Read more!

How to build website site map without writing single line of code in asp .net 2.0 ?

This is a step by step asp net 2.0 tutorial on how to create a site map for your web site.

Site maps can be very important for every website to increase search engine rankings. When we submit url to search engines the search engines use site maps to crawl the web sites.

So they can be very vital for search engine optimisation and to improve your web site search engine rankings.Most traditional way of maintaining site maps were in plain html formats which could be a major drawback when a website pages keep on changing and new web pages are being added.

Now Asp.net 2.0 have introduced a special file called web.sitemap that can be included in the project and just making few changes in this file the sitemap of the website can be managed.

Now lets see how to develop a site map for a web site using asp.net 2.0

step 1

open a web project and add web.sitemap in the root directory
add a web form and name it sitemap.aspx

now manage your site map as shown below :
SiteMapNode element is every page in your site. Manage the elements as per your web sites and give the path of your web pages.

Since the site map is stored in XML format it can be very useful in using it as a datasource and bind it in the tree view control to display the tree structure in your web page.
Step 2

Add a SiteMapDataSource control in your siteMap.aspx page

Add a Treeview control in your sitemap.aspx page

and set the tree view datasourceID="SiteMapDataSource1"

which will look like the following:
Now run the application and you can view a site map for your web site

References:
Introducing Microsoft Visual Basic 2005 for Developers
Microsoft Press


Read more!

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!

Sunday, August 24, 2008

Different Ways of Loading data in combobox in .Net Applicatons

First go to following link
Secure connection and easy transaction handling in .Net

to understand the logic for the connection
and to get the idea of what objDB means.

Just create a objDB class from the above link provided and use the following code

The follwoing are the two ways of loading the data in the combobox or drop down list in
.Net Application:



Private Sub LoadCats()

Dim objdb As New clsObjDB
Dim ds As New DataSet
Dim str As String
cboCats.Items.Clear()
str = "Select * from cat order by catID desc"

ds = objdb.getDataset(str)

Dim dt As DataTable
dt = ds.Tables(0)
For Each row As DataRow In dt.Rows

cboCats.ValueMember = row("CatID")
cboCats.Items.Add(row("CatName"))

Next

End Sub


In the above function I have used Data row to go through the each every record
of the datbase

but in the following example i have directly specified the data source to the
combo box control and determined which value to display.


Private Sub LoadCats1()

Dim objdb As New clsObjDB
Dim ds As New DataSet
Dim str As String
cboCats.Items.Clear()

str = "Select * from cat order by catID desc"

ds = objdb.getDataset(str)

cboCats.DataSource = ds.Tables(0)
cboCats.DisplayMember = "CatName"

End Sub


Read more!

How to insert record in SQL server database from VB.Net?

First go to following link
Secure connection and easy transaction handling in .Net

to understand the logic for the connection
and to get the idea of what objDB means.

Just create a objDB class from the above link provided and use the following code
to insert a record in the table named dog.

Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSingle.Click
Dim str As String
Dim objDB As clsObjDB

Try
objDB = New clsObjDB
str = "insert into Dog (DogName,Active)values('Lika',1) "


objDB.ExecuteQuery(str)
objDB = Nothing

messagebox.Show("Successfully Inserted Single row in dog!!" & vbCrLf)

Catch ex As Exception
Messagebox.show(ex.ToString())

objDB = Nothing
End Try

End Sub

In the above function I have just created a new instance of clsObjDB andpassed the sql query in the ExecuteQuery function and that's it, it does the rest of the work.


Read more!

Thursday, August 21, 2008

How to handle and log Asp.Net Error in Event Viewer ?

You can just use the following to descently handle you ASP.net error messages and log the error in the event viewer .

Also if you want to add the email function in the function.

the following code is the simplest way to handle error messages in ASP.net:


using System;
using System.Diagnostics;


void Page_Error(Object sender, EventArgs args)
{
Response.Write("Error:\n");
Exception e = Server.GetLastError();

EventLog.WriteEntry("Test Web",
"MESSAGE: " + e.Message +
"\nSOURCE: " + e.Source +
"\nFORM: " + Request.Form.ToString() +
"\nQUERYSTRING: " + Request.QueryString.ToString() +
"\nTARGETSITE: " + e.TargetSite +
"\nSTACKTRACE: " + e.StackTrace,
EventLogEntryType.Error);

Trace.Write("Message", e.Message);
Trace.Write("Source", e.Source);
Trace.Write("Stack Trace", e.StackTrace);
Response.Write("Sorry, an error was encountered.");
Context.ClearError();
}


Read more!

Wednesday, August 20, 2008

VB Split() function in C# (Stupid mistake made while converting! Solved now)

I was trying to convert the vb Split() function to C#
and while going through google it seemed pretty much easy but my function is not working or giving me errors.

I went through it more than 30 mins and later found out my mistake that I will
explain in the end of this post.

Ok here is the vb code that uses the split function to split a string line.

Dim strLine As String
strLine = "DataSource = GetDatabase"
lblMsg.Text = getTextLine(strLine)


Public Function getTextLine(ByVal strline As String) As String

Dim spChar As String
spChar = "="
Dim values() As String = Split(line, spChar)
Dim reply As String = values(1).Trim

Return reply
End Function

and the exact replica of this code in C# is :

string strLine;
strLine = "DataSource = GetDatabase";
lblMsg.Text = getTextLine(strLine);

public string getTextLine(string line)
{
char spChar = '=';


string[] arr = line.Split(spChar);
string reply = arr[1];
return reply;


}

Now where i spent my 30 mins making following mistakes:

1. The big mistake what i didn't figure out for long was i did

char spChar= "=";

2. And so I ended up declaring spChar as string. Then the problem worsened.


Read more!

Blog for Programmers (Prateek Regmi): How to get data from the Database using dataset in .Net

Blog for Programmers (Prateek Regmi): How to get data from the Database using dataset in .Net


Read more!

Monday, August 18, 2008

How to get data from the Database using dataset in .Net

First go to following link
Secure connection and easy transaction handling in .Net

to understand the logic for the connection
and to get the idea of what objDB.getDataSet means.

Then use the following function to get the values from the table named Books:


Private Function GetBooks() As Boolean
Dim strSql As String
Dim ds As DataSet

dim objBook as clsBook()

Try
strSql = "SELECT * from Books"

ds = objDB.getDataset(strSql)
If ds.Tables(0).Rows.Count > 0 Then
For Each row As DataRow In ds.Tables(0).Rows
objBook = new clsBook()

objBook.BookID = row("BookingID")
ObjBook.BookName = row ("BookName")
'etc

Next
GetBooks=true
Else

GetBooks = False
End If
Catch ex As Exception

Throw ex
End Try
End Function


Read more!