2007-12-21

Internet Explorer 8

Internet Explorer 8

Just as he was the first to talk about IE7, Bill Gates kept the tradition alive and discussed IE8 at the Mix ‘n Mash event here on campus yesterday. Bill was talking to some bloggers about IE.Next and called it IE8, the same way we do here in the IE team hallway.

So, yes, the version after IE7 is IE8. We looked at a lot of options for the product name. Among the names we considered and ruled out:

IE 7+1
IE VIII
IE 1000 (think binary)
IE Eight!
iIE
IE for Web 2.0 (Service Pack 2)
IE Desktop Online Web Browser Live Professional Ultimate Edition for the Internet (the marketing team really pushed for this one ;-)
Ie2.079 (we might still use this for the Math Major Edition)

Of course, some people care about other aspects of IE8 much more than they care about the name. As I’ve walked different people through the plan, I’ve gotten “Does it have feature X?” “When is the beta?” “When does it release” and even the more thoughtful “What are you trying to accomplish with this release?”

You will hear a lot more from us soon on this blog and in other places. In the meantime, please don’t mistake silence for inaction.

Thank you ieblog
Dean Hachamovitch
General Manager
Published Wednesday, December 05, 2007 2:33 PM by ieblog

2007-12-13

Serialize & Deserialize Class To File

This sample show serialize and deserialize by use binary format.

1. Import this 2 names space

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

2. The class or object that you want implement must insert attribute Serializable.

< system.serializable() >
Public Class Person
Private m_sFirstName As String
Private m_sLastName As String

Public Sub New()
End Sub

Public Property FirstName() As String
Get
Return Me.m_sFirstName
End Get
Set(ByVal value As String)
Me.m_sFirstName = value
End Set
End Property

Public Property LastName() As String
Get
Return Me.m_sLastName
End Get
Set(ByVal value As String)
Me.m_sLastName = value
End Set
End Property

Public ReadOnly Property FullName() As String
Get
Return Me.m_sFirstName & " " & Me.m_sLastName
End Get
End Property

End Class


3. Sample code show how to do this.

' Create object instance
Dim pPerson As New Person()

pPerson.FirstName = "TOM"
pPerson.LastName = "BROWN"

' Create file by FileStream class
Dim fs As FileStream = New FileStream("c:\test.bin", FileMode.OpenOrCreate)

' Creat binary object
Dim bf As New BinaryFormatter()

' Serialize object to file
bf.Serialize(fs, pPerson)
fs.Close()

' Open file and deserialize to object again
Dim fsRead As New FileStream("C:\test.bin", FileMode.Open)
Dim objTest As Object = bf.Deserialize(fsRead)
fsRead.Close()

2007-12-01

Caculate DateTime By TimeSpan Class

A TimeSpan object represents a time interval, or duration of time, measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The largest unit of time used to measure duration is a day. Time intervals are measured in days for consistency because the number of days in larger units of time, such as months and years, varies.

Sample Code

Dim dFirstDate As DateTime = DateTime.Now

' Add day
Dim dLastDate As DateTime = DateTime.Now.AddDays(15)

' Subtract DateTime
Dim pTimeSpan As TimeSpan = dLastDate.Subtract(dFirstDate)

' Subtract DateTime Output
Console.WriteLine("Days : " & pTimeSpan.TotalDays)
Console.WriteLine("Hours : " & pTimeSpan.TotalHours)
Console.WriteLine("Minutes : " & pTimeSpan.TotalMinutes)
Console.WriteLine("Seconds : " & pTimeSpan.TotalSeconds)

' Compare DateTime
Dim nResult As Integer = DateTime.Compare(dLastDate, dFirstDate)
If nResult = 0 Then
Console.WriteLine("First date is equals to Last date")
ElseIf nResult > 0 Then
Console.WriteLine("First date is lesser than the Last date")
Else
Console.WriteLine("First date is greater than Last date")
End If

2007-11-19

RegularExpressions Class

The Regex class contains several static methods that allow you to use a regular expression without explicitly creating a Regex object. Using a static method is equivalent to constructing a Regex object, using it once and then destroying it.

Sample Code 1

Imports System.Text.RegularExpressions
' import the namespace

'instantiate the objects
dim oRegex as new regex("test pattern")

'use the object
If oRegex.IsMatch("this is the string to test on") Then
msgbox "Match found"
else
msgbox "Did not find match"
end i


Sample Code 2

//Check for correct format of your name

Dim myMatch As Match = System.Text.RegularExpressions.Regex.Match(InsertYourName, "^[A-Z][a-zA-Z]*$")

If Not myMatch.Success Then

'Name was incorrect

ErrorMessage("Invalid Name", "Message")

txtFname.Focus()

Return

End If


Regular Expressions Elements:

* . Character except a newline character(\n)
* \d Any decimal digit
* \D Any nondigit
* \s Any white-space character
* \S Any Non-white-space charater
* \w Any word character
* \W Any nonword character
* ^ Beginning of string or line
* \A Beginning of string
* $ End of string or line
* \z End of string
* | Matches one of the expressions seprated by the vertical bar; example eee|ttt will match one of eee or ttt (tracing left to right)
* [abc] Match with one of the characters; example [rghy] will match r, g,h or c not any other character.
* [^abc] Match with any of character except in list; example [ghj] will match all character except g,h or k.
* [a-z] Match any character within specified range; example [a - c] will match a, b or c.
* ( ) Subexpression treated as a single element by regular expression elements described in this table.
* ? Match one or zero occurrences of the previous character or subexpression; example a?b will match a or ab not aab.
* * Match zero or more occurences of the previous character or subexpression; example a*b will match b, ab, aab and so on.
* + Match one or more occurences of the previous character or subexpression; example a+b will match ab, aab and so on but not b.
* {n} Match exactly n occurrences of the preceding character;example a{2} will match only aa.
* {n,} Match minimum n occurrences of the preceding character;example a{2,} will match only aa,aaa and so on.
* {n,m} Match minimum n and maximum n occurrences of the preceding character;example a{2, 4} will match aa, aaa, aaaa but not aaaaa.

2007-11-15

Visual Studio 2008 Beta 2 Professional Edition

Product Information and Availability

Visual Studio 2008 and the .NET Framework 3.5 will be available by the end of November 2007. The .NET Framework 3.5 will also be available to end users via a free, optional download from Microsoft Update. A CTP of Microsoft Sync Framework is available today at http://msdn.microsoft.com/sync. Popfly Explorer is a hosted development environment available today at http://www.popfly.com. More information about all of these releases is available at http://www.msdn.microsoft.com/vstudio.
Founded in 1975, Microsoft (Nasdaq “MSFT”) is the worldwide leader in software, services and solutions that help people and businesses realize their full potential.
Note to editors: If you are interested in viewing additional information on Microsoft, please visit the Microsoft Web page at http://www.microsoft.com/presspass on Microsoft’s corporate information pages. Web links, telephone numbers and titles were correct at time of publication, but may since have changed. For additional assistance, journalists and analysts may contact Microsoft’s Rapid Response Team or other appropriate contacts listed at http://www.microsoft.com/presspass/contactpr.mspx.

Download beta version at : http://msdn2.microsoft.com/en-us/evalcenter/bb655864.aspx

2007-11-08

Copying Data from one DataTable to Another

You can use ImportRow method to do this by calling NewRow adds a row to the table using the existing table schema, but with default values for the row, and sets the DataRowState to Added. Calling ImportRow preserves the existing DataRowState along with other values in the row. If the DataRow that is passed as a parameter is in a detached state, it is ignored, and no exception is thrown.

Sample Code

For Each dr As DataRow In sourceTable.Rows

destinationTable.ImportRow(dr)

Next

But if the destination table have the same structure you can use this clone method copies the structure of the DataSet that including all datatable schemas, relations, and constraints.

Sample Code

Dim dsDestination As DataSet
' clone method copies the structure of the DataSet,
' including all datatable schemas, relations, and constraints
dsDestination = ds.Clone()

For Each dr As DataRow In ds.Tables(0).Rows
dsDestination.Tables(0).ImportRow(dr)
Next

vb.net sample code

2007-11-06

Developers slam Microsoft's Visual Basic plan

More than 100 influential developers using Microsoft products have signed a petition demanding the software company reconsider plans to end support for Visual Basic in its "classic" form.

The developers, members of Microsoft's Most Valuable Professional program which recognizes influential members of the developer community, claim the move could kill development on millions of Visual Basic 6 (VB6) applications and "strand" programmers that have not been trained in newer languages.

Microsoft said it will end standard support for Visual Basic 6 at the end of this month, ending free incident support and critical updates. Both services will be available for a fee for another three years.

But MVPs hope Microsoft will reconsider not just VB6's support options, but will continue to develop the language alongside its newer Visual Basic.Net.

"By providing a new version of a COM-based Visual Basic within the Visual Studio IDE, Microsoft will help maintain the value of its clients' existing code, demonstrate its ongoing commitment to the core Visual Basic language, and greatly simplify the adoption of VB.NET by those that wish to do so," the petition says. "The decisions of if, how, and when to migrate code to .NET should lie with the customer."

The problem, say the dissenting developers, is that when Microsoft made Visual Basic.Net (or Visual Basic 7) the successor to VB6, it actually killed one language and replaced it with a fundamentally different one. It's effectively impossible to migrate VB6 applications to VB.Net, and for VB6 developers, learning VB.Net is as complex as learning a completely new programming language, critics say.

"The .Net version of Visual Basic is Visual Basic in name only," wrote developer and author Rich Levin in a recent blog entry. "Any organization with an investment in Visual Basic code--consultants, ISVs, IT departments, businesses, schools, governments--are forced to freeze development of their existing VB code base, or reinvest virtually all the time, effort, intellectual property, and expense to rewrite their applications from scratch."

Microsoft continues to develop C++ alongside C#, the language's .Net counterpart, and the company should do the same with "classic" Visual Basic and VB.Net, the petition argues. Microsoft introduced VB.Net in 2000, and since then, developer use of VB6 and older versions has declined steadily. Many of those leaving the language behind are migrating not to VB.Net but to non-Microsoft languages such as Java, according to some surveys. For example, a November 2004 survey of developers in Europe, the Middle East and Africa by Evans Data found that Visual Basic had lost 25 percent of its developer base in those areas since 2003.

In North America most Visual Basic developers continued to use VB6 and older versions--45 percent of all North American developers, compared with 34 percent for Visual Basic.Net. Fifty-four percent of North American developers used some sort of Visual Basic.

"One of the main issues keeping VB6 and earlier developers from making the migration to VB.Net is the steepness of the learning curve," said Albion Butters, Evans Data's international analyst, in a statement. "The difficulty in moving existing VB6 apps to VB.Net is, in some cases, insurmountable."

While the developers' argument may make sense, it is probably a moot point, as Microsoft is unlikely to change its stance on VB6, say some industry observers.

"All software--desktop apps, languages, databases, whatever--gets 'end-of-lifed' eventually, some unfortunately, some fortunately," said Jez Higgins, a Birmingham-based developer. "The fundamental programming disciplines aren't tied to any one language or any one way or working. They won't disappear out the side of your head. I suggest these blokes buck up and get on."

"The future of programming is clear, and object-oriented languages designed from the get-go for Web and Internet-enabled functionality are the future," wrote one developer in response to Levin's post. "No amount of romanticizing VB6 is going to change that."

www.news.com

2007-11-02

DataSet

A data set (or dataset) is a collection of data, usually presented in tabular form. Each column represents a particular variable. Each row corresponds to a given member of the data set in question. It lists values for each of the variables, such as height and weight of an object or values of random numbers. The data set may comprise data for one or more members, corresponding to the number of rows.

Historically, the term originated in the mainframe field, where it had a well-defined meaning, very close to contemporary computer file. This topic is not covered here.

In the simplest case, there is only one variable, and then the data set consists of a single column of values, often represented as a list.

The values may be numbers, such as real numbers or integers, for example representing a person's height in centimeters, but may also be nominal data (i.e., not consisting of numerical values), for example representing a person's ethnicity. For each variable, the values will normally all be of the same kind. However, there may also be "missing values", which need to be indicated in some way.

In statistics data sets usually come from actual observations obtained by sampling a statistical population, and each row corresponds to the observations on one element of that population. Data sets may further be generated by algorithms for the purpose of testing certain kinds of software.

While the term suggests a relationship to set theory it should not be assumed that a given data set is, in fact, a set in the usual mathematically sense. The rows of a data set need not be distinct, and so a data set is technically a multiset.

From Wikipedia, the free encyclopedia

2007-10-30

SQL Helper Class

Microsoft .net framework consists of ADO .NET which enables the developer to interact with the database. ADO .NET provides many rich features that can be used to retrieve and display data in a number of ways. Apart from the flexibility provided by the ADO .NET, sometimes we find ourselves repeating the same code again and again. Consider that at some point in our application we need to pass some parameters and retrieve some information from the database. We can perform this task by writing 5-6 lines of code which is cool. But when later we need to pass the parameters we have to write those 5-6 lines again which is not cool.

Methods

  • ExecuteDataset Retrieve multiple rows from the database and return value to DataSet class.
  • ExecuteNonQuery Executes a Transact-SQL statement against the connection and returns the number of rows affected
  • ExecuteNonQueryReturn No return value.
  • ExecuteReader Retrieve multiple rows from the database and return value to SqlDataReader class.
  • ExecuteScalar Retrieve a single row instead of group of rows and return value to object.
  • ExecuteXmlReader Sends the CommandText to the Connection and builds an XmlReader object.

Summary
  • It is used for Database Access other than System.Data.SqlClient or System.Data.Oledb
  • SqlHelper() - This method used to reduce the lines of connecting the database than when we are using the SqlDataAdapter or OleDbAdapter.
  • You can download sql helper dll at this

Sample Code

' Very short command
Dim nResult as integer
nResult = Convert.ToInt32(SqlHelper.ExecuteScalar(ConnectionString, CommandType.Text, "Select Count(id) from table"))

2007-10-29

Using SqlParameter Class

Represents a parameter to a SqlCommand and optionally its mapping to DataSet columns. This class cannot be inherited.

You should use parameters to filter queries in a secure manner. But I recommend to use parameters when you try to pass the datetime value in your query.

The process of using parameter contains two steps:

  • create SqlParameter object and insert there value with applicable properties
  • define the parameter in the SqlCommand command string, and assign the SqlParameter object to the SqlCommand object. When the SqlCommand executes, parameters will be replaced with values specified by the SqlParameter object.

Sample Code

Imports Namespace: System.Data.SqlClient

' Insert string
Dim sql As String = " INSERT INTO tblZipCode([ZIPCODE], [STATE], [CITY], [TestDate]) VALUES(@ZIPCODE, @STATE, @CITY), @TestDate"

' Create sql parameter
Dim param(3) As SqlParameter

param(0) = New SqlParameter("@ZIPCODE", SqlDbType.VarChar)
param(0).Value = "60000"

param(1) = New SqlParameter("@STATE", SqlDbType.VarChar)
param(1).Value = "Statename"

param(2) = New SqlParameter("@CITY", SqlDbType.VarChar)
param(2).Value = "Cityname"

' Recommend to use sql param when you try to send datetime value
param(3) = New SqlParameter("@TestDate", SqlDbType.DateTime)
param(3).Value = DateTime.Now

' Create Connection string
Dim sConnection As New SqlConnection("server=(local);uid=sa;pwd=pass;database=db")
sConnection.Open()

' Create Sql Command
Dim command As SqlCommand = sConnection.CreateCommand()
command.CommandText = sql

' Add Parameter to command
command.Parameters.AddRange(param)

' Execute command
Dim nResult As Integer = command.ExecuteNonQuery()

If nResult > 0 Then
Console.WriteLine("Insert completed")
End If

sConnection.Close()
command.Dispose()

2007-10-27

SqlCommand Methods

ExecuteNonQuery

  • Overridden. Executes a Transact-SQL statement against the connection and returns the number of rows affected.
ExecuteReader
  • Overloaded. Sends the CommandText to the Connection and builds a SqlDataReader.
ExecuteScalar
  • Overridden. Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
ExecuteXmlReader
  • Sends the CommandText to the Connection and builds an XmlReader object.

2007-10-25

Populate a DataSet from a Database

SqlDataAdapter class represents a set of data commands and a database connection that are used to fill the DataSet and update a SQL Server database. This class cannot be inherited.

Getting data from a database is easy, and working with data is easier than before. The most important concept to remember is that the DataSet is a data structure separate and distinct from a data store. Although you get data from a database in this example, it doesn't matter where the data comes from; the DataSet will always present a consistent programming model. It is a simple collection of data with relational database characteristics. There is no Load, Open, or Execute on a DataSet because it doesn't know where it gets its data from. This section describes how to use a SqlDataAdapter to get data from a database into a DataSet.

Sample Code (with MsSql)

Dim sConnection As String = "server=(local);uid=sa;pwd=password;database=yourDatabase"

Dim objDataAdapter As New SqlDataAdapter("Select * From tableName", sConnection)
Dim dsResult As New DataSet("Result")

If Not IsNothing(objDataAdapter) Then
' Fill data into dataset
objDataAdapter.Fill(dsResult)

objDataAdapter.Dispose()
End If

' Test by bind data into datagridview control
Me.DataGridView1.DataSource = dsResult.Tables(0)

Retrieving Data Using the DataReader

You can use the ADO.NET DataReader to retrieve a read-only, forward-only stream of data from a database. Results are returned as the query executes, and are stored in the network buffer on the client until you request them using the Read method of the DataReader. Using the DataReader can increase application performance both by retrieving data as soon as it is available, rather than waiting for the entire results of the query to be returned, and (by default) storing only one row at a time in memory, reducing system overhead.

The DataReader class in .NET provides similar functions to SQL Cursors, which are actually not supported in the .NET Framework. DataReades are used to efficiently retrieve a forward-only stream of data from a database. DataReaders are appropriate when the need is to simply display the result set, as only one record at a time is ever present in memory. The DataReader is mainly used in scenarios wherein data need not be updateable nor should persist across multiple requests.

Sample Code (with MsSql)
You must import SqlClient .

Imports System.Data.SqlClient

Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"

Dim objCommand As New SqlCommand
objCommand.CommandText = "Select * From tablename"
objCommand.Connection = New SqlConnection(sConnection)
objCommand.Connection.Open()

Dim objDataReader As SqlDataReader = objCommand.ExecuteReader()

If objDataReader.HasRows Then
Do While objDataReader.Read()
Console.WriteLine(" Your name is: " & Convert.ToString(objDataReader(0)))
Loop
Else
Console.WriteLine("No rows returned.")
End If

objDataReader.Close()
objCommand.Dispose()

2007-10-23

Arithmetic overflow error converting expression to data type datetime

I got this error when I tried to convert string to datetime in query.

This is Culture problem.

What culture is your webserver?
What culture is your ASP.NET application using?
What culture is your database?

This is due to an inconsistency in the language settings between the web server and SQL server (or SQL server user).

By default, SQL Server users are set to "us_english" as the default language. The result is that different date formats are being used and are therefore not recognized by the database.

There are several options to remedy this situation:

1. Change the SQL user's default language to match the language settings on the SQL server.To do this, open SQL enterprise manager and connect to your database server. Expand Security -> Logins and open the properties dialog for the user that you are using to connect to the database. On the main properties page, change the language to equal the same language that is set on your web server.

2. Modify your connection stringOn your SQL connection string, add a parameter of Language= and set it equal to the correct language. For example, Language=British. (www.prezzatech.com)

2007-10-12

What is ADO.NET?

ADO.NET
From Wikipedia, the free encyclopedia

ADO.NET is a set of computer software components that can be used by programmers to access data and data services. It is a part of the base class library that is included with the Microsoft .NET Framework. It is commonly used by programmers to access and modify data stored in relational database systems, though it can also be used to access data in non-relational sources. ADO.NET is sometimes considered an evolution of ActiveX Data Objects (ADO) technology, but was changed so extensively that it can be conceived of as an entirely new product.

ADO.NET consists of two primary parts:

1. Data provider

These classes provide access to a data source, such as a Microsoft SQL Server or Oracle database. Each data source has its own set of provider objects, but they each have a common set of utility classes:

* Connection: Provides a connection used to communicate with the data source. Also acts as an abstract factory for command objects.
* Command: Used to perform some action on the data source, such as reading, updating, or deleting relational data.
* Parameter: Describes a single parameter to a command. A common example is a parameter to a stored procedure.
* DataAdapter: A bridge used to transfer data between a data source and a DataSet object (see below).
* DataReader: A class used to efficiently process a large list of results one record at a time.


2. DataSets

DataSets objects, a group of classes describing a simple in-memory relational database, were the star of the show in the initial release (1.0) of the Microsoft .NET Framework. The classes form a containment hierarchy:

* A DataSet object represents a schema (either an entire database or a subset of one). It can contain tables and relationships between those tables.
- A DataTable object represents a single table in the database. It has a name, rows, and columns.
- A DataView object "sits over" a DataTable and sorts the data (much like a SQL "order by" clause) and filters the records (much like a SQL "where" clause) if a filter is set. An in-memory index is used to facilitate these operations. All DataTables have a default filter, while any number of additional DataViews can be defined, reducing interaction with the underlying database and thus improving performance.
- A DataColumn represents a column of the table, including its name and type.
- A DataRow object represents a single row in the table, and allows reading and updating of the values in that row, as well as retrieving any rows that are related to it through a primary-key foreign-key relationship.
- A DataRowView represents a single row of a DataView the distinction between a DataRow and DataRowView is important when iterating over a result set.
- A DataRelation is a relationship between tables, such as a primary-key foreign-key relationship. This is useful for enabling DataRow's functionality of retrieving related rows.
- A Constraint describes an enforced property of the database, such as the uniqueness of the values in a primary key column. As data is modified any violations that arise will cause exceptions.

A DataSet is populated from a database by a DataAdapter whose Connection and Command properties have been set. However, a DataSet can save its contents to XML (optionally with an XSD schema), or populate itself from XML, making it exceptionally useful for web services, distributed computing, and occasionally-connected applications.

ADO.NET and Visual Studio.NET

Functionality exists in the Visual Studio .NET IDE to create specialized subclasses of the DataSet classes for a particular database schema, allowing convenient access to each field through strongly-typed properties. This helps catch more programming errors at compile-time and makes the IDE's Intellisense feature more useful.

2007-09-25

FileInfo Class

Use the FileInfo class for typical operations such as copying, moving, renaming, creating, opening, deleting, and appending to files

Many of the FileInfo methods return other I/O types when you create or open files. You can use these other types to further manipulate a file. For more information, see specific FileInfo members such as Open, OpenRead, OpenText, CreateText, or Create.

Sample Code

Class FileManagement
Private m_pFile As IO.FileInfo
Private m_sTempFile As String = "C:\Test.Txt"


Public Sub SampleCreateFile()
m_pFile = New IO.FileInfo(m_sTempFile)

' Check exist file name
If Not m_pFile.Exists Then
Dim objStream As IO.StreamWriter = m_pFile.CreateText()

objStream.WriteLine("Welcome to My Blog")
objStream.WriteLine("Thank you")

objStream.Flush()
objStream.Close()
objStream.Dispose()
End If

End Sub

Public Sub SampleReadFile()
m_pFile = New IO.FileInfo(m_sTempFile)

If m_pFile.Exists Then
'Read Text
Dim objStream As IO.StreamReader = m_pFile.OpenText()

' Peek returns the next aviable charactor
While objStream.Peek() >= 0
Console.WriteLine(objStream.ReadLine)
End While

End If
End Sub

Public Sub SampleFileInfomation()

' Use class file to get file attributes

' Get Time
Console.WriteLine(IO.File.GetCreationTime(Me.m_sTempFile).ToLongTimeString())
Console.WriteLine(IO.File.GetLastAccessTime(Me.m_sTempFile).ToLongTimeString())
Console.WriteLine(IO.File.GetLastWriteTime(Me.m_sTempFile).ToLongTimeString())


' Set Time a
IO.File.SetCreationTime(m_sTempFile, DateTime.Now)
IO.File.SetLastAccessTime(m_sTempFile, DateTime.Now)
IO.File.SetLastWriteTime(m_sTempFile, DateTime.Now)

End Sub

Public Sub SampleOther()
m_pFile = New IO.FileInfo(m_sTempFile)

' Copy File
m_pFile.CopyTo("C:\test2.txt", True)

' Move File
m_pFile.MoveTo("C:\testMove.txt")

' Delete
m_pFile = New IO.FileInfo("C:\test2.txt")
m_pFile.Delete()
End Sub
End Class

2007-09-17

How to get table sizes for the database

sp_spaceused (Transact-SQL)

You can use this stored procedure (T-SQL) to get a report of the table sizes for the database.

Displays the number of rows, disk space reserved, and disk space used by a table, indexed view, or SQL Server 2005 Service Broker queue in the current database, or displays the disk space reserved and used by the whole database.

Sample Code

1. One table
exec sp_spaceused [tableName]

2. All tables in your database

DECLARE @@TableName Nvarchar(100)

DECLARE my_cursor CURSOR FOR
Select sysobjects.name From sysobjects Where xtype='u' OPEN my_cursor

FETCH NEXT FROM my_cursor INTO @@TableName
WHILE @@FETCH_STATUS = 0
BEGIN

exec sp_spaceused @@TableName

FETCH NEXT FROM my_cursor INTO @@TableName
END
CLOSE my_cursor
DEALLOCATE my_cursor
GO


Result value

Column name Data type Description

name

nvarchar(128)

Name of the object for which space usage information was requested.

The schema name of the object is not returned. If the schema name is required, use the sys.dm_db_partition_stats or sys.dm_db_index_physical_stats dynamic management views to obtain equivalent size information.

rows

char(11)

Number of rows existing in the table. If the object specified is a Service Broker queue, this column indicates the number of messages in the queue.

reserved

varchar(18)

Total amount of reserved space for objname.

data

varchar(18)

Total amount of space used by data in objname.

index_size

varchar(18)

Total amount of space used by indexes in objname.

unused

varchar(18)

Total amount of space reserved for objname but no yet used.

2007-09-04

Database Engine Tuning Advisor

I found this solution in microsoft web site and it's can resolve the problem.

Error message when you use Database Engine Tuning Advisor in SQL Server 2005: "Attempt to initialize the CRT more than once


When you use Database Engine Tuning Advisor to analyze the performance effects of workloads in Microsoft SQL Server 2005, you may receive the following error message:

R6031- Attempt to initialize the CRT more than once. This indicates a bug in your application.

CAUSE
This problem occurs because of the application compatibility settings. The application compatibility settings may be set separately for the application. Alternatively, the application compatibility settings may be inherited from the settings that are specific to the Explorer.exe process. When you explicitly set the application compatibility settings for the Explorer.exe process, all applications that are started from the Explorer.exe process inherit the same application compatibility settings.

If Database Engine Tuning Advisor inherits the application compatibility settings from the Explorer.exe process, the Microsoft Windows loader tries to initialize the C run-time library (CRT) Msvcp80.dll file two times when you start Database Engine Tuning Advisor. Therefore, Database Engine Tuning Advisor stops responding.

Warning Serious problems might occur if you modify the registry incorrectly by using Registry Editor or by using another method. These problems might require that you reinstall your operating system. Microsoft cannot guarantee that these problems can be solved. Modify the registry at your own risk.

To work around this problem, you must set the Explorer.exe process to stop using the application compatibility technology. To do this, follow these steps:
1. Click Start, click Run, type regedit, and then click OK.
2. Locate the following registry subkey:
HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers
3. In the right pane, right-click the registry entry for the Explorer.exe process, and then click Delete.
4. In the Confirm Value Delete dialog box, click Yes.
5. Exit Registry Editor.
6. Restart the computer.

2007-08-29

Database Limits

Today I try to update some tables in my database and I got the error message about Insufficient Resources and this is a problem.


MSDE Limits

An MSDE database is limited in total size to 2 GB. How quickly you reach 2 GB depends on the number of members you have, the frequency with which you send, how long you keep archives, incoming mail and outgoing mail, and other factors. If you are upgrading from 4.x or lower, and wish to use MSDE, you can determine how large your total database size is by adding together the size of all the files in your db directory.

ListManager will warn you via email if your database is growing too large. If you are running ListManager in the foreground and your database is too large, you'll see a message similar to this one:

severity: 17 - Insufficient Resources - The statement caused SQL Server to run out of resources (such as locks or disk space for the database) or to exceed some limit set by the system administrator.
msgtext: Could not allocate space for object 'members_' in database 'ListManager' because the 'PRIMARY' filegroup is full.

If you find that your database is growing too large under MSDE and are unable to trim its size by managing the length of time data is kept, you should consider upgrading to a stand-alone SQL server.

2007-08-23

Start And Kill process

Process Class

Provides access to local and remote processes and enables you to start and stop local system processes.

Sample Code

1. Start notepad
System.Diagnostics.Process.Start("notepad")

2. Start winword
System.Diagnostics.Process.Start("WINWORD")

3. Start excel
System.Diagnostics.Process.Start("Excel")

4. Start ie and parameter
System.Diagnostics.Process.Start("IExplore.exe", "http://vbnetsample.blogspot.com/")

5. Kill It!!
' Kill all notepad process
Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName("notepad")

For Each p As Process In pProcess
p.Kill()
Next

Platforms

2007-08-03

Gets Array of all DataRow

After you create or bind data into DataSet and you need select some data from them. You can use select method in datable.

DataTable.Select Method (String) Gets an array of all DataRow objects that match the filter criteria in order of primary key (or lacking one, order of addition.)

Sample 1. You can copy code from Step to Create Dataset topic and try to run this sample.

Dim drSelect As DataRow() = ds.Tables(0).Select("Column1=3")
Dim sTemp As String = ""

If drSelect.Length > 0 Then
For Each drItem As DataRow In drSelect
sTemp = sTemp & drItem("Column2").ToString() & ","
Next

MessageBox.Show(sTemp.Substring(0, sTemp.Length - 1))
End If


Sample 2.

Private Sub GetRowsByFilter()
Dim t As DataTable
t = DataSet1.Tables("Orders")
' Presuming the DataTable has a column named Date.
Dim strExpr As String
strExpr = "Date > '1/1/00'"
Dim foundRows() As DataRow
' Use the Select method to find all rows matching the filter.
foundRows = t.Select(strExpr)
Dim i As Integer
' Print column 0 of each returned row.
For i = 0 to foundRows.GetUpperBound(0)
Console.WriteLine(foundRows(i)(0))
Next i
End Sub

Get IP Address By Net Class

This sample show How to get ip address by use net class.

Private Function IPAddresses(ByVal server As String) As String
Dim objArray As New ArrayList
Dim ip As String = String.Empty

Try

' Get server related information.
Dim heserver As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(server)

' Loop on the AddressList
Dim curAdd As System.Net.IPAddress
For Each curAdd In heserver.AddressList

ip = curAdd.ToString
Exit For

Next curAdd


Catch e As Exception
Debug.WriteLine("Exception: " + e.ToString())
End Try

Return ip

End Function 'IPAddresses

For this sample you can call that funciton by pass name parameter or url such as

IPAddresses("YourPCName")
IPAddresses("www.hotmail.com")
...
...

System.Net Namespace
The System.Net namespace provides a simple programming interface for many of the protocols used on networks today. The WebRequest and WebResponse classes form the basis of what are called pluggable protocols, an implementation of network services that enables you to develop applications that use Internet resources without worrying about the specific details of the individual protocols.

more detail

2007-08-02

Development Tools

For programmers, a good tools lead to good performance. If it is free,it is very good. All tools are listed below. If any of you has any idea, please suggest.


1. SharpDevelop (Support VB.NET)
The Open Source Development Environment for .NET.

#develop (short for SharpDevelop) is a free IDE for C#, VB.NET and Boo projects on Microsoft's .NET platform. It is open-source, and you can download both sourcecode and executables from this site icsharpcode.net.

2. Microsoft SQL Server 2005 Express Edition
SQL Server Express is a powerful and reliable data management product that delivers rich features, data protection, and performance for embedded application clients, light Web applications, and local data stores. Click Here

3. Microsoft SQL Server 2000 Desktop Engine (MSDE 2000)
* MSDE 2000 is FREE to distribute with your applications if you own a MSDE Universal Subscription.
* Clients can access the MSDE for FREE without requiring a licence.
* Databases created with MSDE are 100 percent compatible with Microsoft SQL Server 2000.
* Microsoft are allowing companies to freely distribute the MSDE 2000 with the objective that you will purchase the Microsoft SQL 2000, because the latter version provides a Windows interface for administration (i.e. Microsoft Enterprise Manager). However why purchase the Microsoft Tools when other options are available?
Click Here

4. DbaMgr2k (graphical interface for MSDE 2000)
DbaMgr provides a graphical management interface for MS MSDE 2000 installations. It allows you to manage and administer your server, databases and database objects from a Windows interface similar to the one Enterprise Manager provides, rather than via the standard oSql.exe command line utility. In addition to traditional Sql Server objects management and permissions, DbaMgr adds a visual interface, a query interface, and a visual interface for BCP operation as well as SQL Agent management, providing Alerts, Operators and Jobs management features..
Click Here

2007-07-29

Database models

Database model

Various techniques are used to model data structure. Most database systems are built around one particular data model, although it is increasingly common for products to offer support for more than one model. For any one logical model various physical implementations may be possible, and most products will offer the user some level of control in tuning the physical implementation, since the choices that are made have a significant effect on performance. An example of this is the relational model: all serious implementations of the relational model allow the creation of indexes which provide fast access to rows in a table if the values of certain columns are known.

A data model is not just a way of structuring data: it also defines a set of operations that can be performed on the data. The relational model, for example, defines operations such as select, project, and join. Although these operations may not be explicit in a particular query language, they provide the foundation on which a query language is built.
Flat model
This may not strictly qualify as a data model, as defined above. The flat (or table) model consists of a single, two-dimensional array of data elements, where all members of a given column are assumed to be similar values, and all members of a row are assumed to be related to one another. For instance, columns for name and password that might be used as a part of a system security database. Each row would have the specific password associated with an individual user. Columns of the table often have a type associated with them, defining them as character data, date or time information, integers, or floating point numbers. This model is, incidentally, a basis of the spreadsheet.
Hierarchical model
In a hierarchical model, data is organized into a tree-like structure, implying a single upward link in each record to describe the nesting, and a sort field to keep the records in a particular order in each same-level list. Hierarchical structures were widely used in the early mainframe database management systems, such as the Information Management System (IMS) by IBM, and now describe the structure of XML documents. This structure allows one 1:N relationship between two types of data. This structure is very efficient to describe many relationships in the real world; recipes, table of contents, ordering of paragraphs/verses, any nested and sorted information. However, the hierarchical structure is inefficient for certain database operations when a full path (as opposed to upward link and sort field) is not also included for each record.
Network model
The network model (defined by the CODASYL specification) organizes data using two fundamental constructs, called records and sets. Records contain fields (which may be organized hierarchically, as in the programming language COBOL). Sets (not to be confused with mathematical sets) define one-to-many relationships between records: one owner, many members. A record may be an owner in any number of sets, and a member in any number of sets.

The operations of the network model are navigational in style: a program maintains a current position, and navigates from one record to another by following the relationships in which the record participates. Records can also be located by supplying key values.

Although it is not an essential feature of the model, network databases generally implement the set relationships by means of pointers that directly address the location of a record on disk. This gives excellent retrieval performance, at the expense of operations such as database loading and reorganization.
Relational model
The relational model was introduced in an academic paper by E. F. Codd in 1970 as a way to make database management systems more independent of any particular application. It is a mathematical model defined in terms of predicate logic and set theory.

The products that are generally referred to as relational databases in fact implement a model that is only an approximation to the mathematical model defined by Codd. The data structures in these products are tables, rather than relations: the main differences being that tables can contain duplicate rows, and that the rows (and columns) can be treated as being ordered. The same criticism applies to the SQL language which is the primary interface to these products. There has been considerable controversy, mainly due to Codd himself, as to whether it is correct to describe SQL implementations as "relational": but the fact is that the world does so, and the following description uses the term in its popular sense.

A relational database contains multiple tables, each similar to the one in the "flat" database model. Relationships between tables are not defined explicitly; instead, keys are used to match up rows of data in different tables. A key is a collection of one or more columns in one table whose values match corresponding columns in other tables: for example, an Employee table may contain a column named Location which contains a value that matches the key of a Location table. Any column can be a key, or multiple columns can be grouped together into a single key. It is not necessary to define all the keys in advance; a column can be used as a key even if it was not originally intended to be one.

A key that can be used to uniquely identify a row in a table is called a unique key. Typically one of the unique keys is the preferred way to refer to a row; this is defined as the table's primary key.

A key that has an external, real-world meaning (such as a person's name, a book's ISBN, or a car's serial number) is sometimes called a "natural" key. If no natural key is suitable (think of the many people named Brown), an arbitrary key can be assigned (such as by giving employees ID numbers). In practice, most databases have both generated and natural keys, because generated keys can be used internally to create links between rows that cannot break, while natural keys can be used, less reliably, for searches and for integration with other databases. (For example, records in two independently developed databases could be matched up by social security number, except when the social security numbers are incorrect, missing, or have changed.)
Relational operations
Users (or programs) request data from a relational database by sending it a query that is written in a special language, usually a dialect of SQL. Although SQL was originally intended for end-users, it is much more common for SQL queries to be embedded into software that provides an easier user interface. Many web sites, such as Wikipedia, perform SQL queries when generating pages.

In response to a query, the database returns a result set, which is just a list of rows containing the answers. The simplest query is just to return all the rows from a table, but more often, the rows are filtered in some way to return just the answer wanted.

Often, data from multiple tables are combined into one, by doing a join. Conceptually, this is done by taking all possible combinations of rows (the Cartesian product), and then filtering out everything except the answer. In practice, relational database management systems rewrite ("optimize") queries to perform faster, using a variety of techniques.

There are a number of relational operations in addition to join. These include project (the process of eliminating some of the columns), restrict (the process of eliminating some of the rows), union (a way of combining two tables with similar structures), difference (which lists the rows in one table that are not found in the other), intersect (which lists the rows found in both tables), and product (mentioned above, which combines each row of one table with each row of the other). Depending on which other sources you consult, there are a number of other operators - many of which can be defined in terms of those listed above. These include semi-join, outer operators such as outer join and outer union, and various forms of division. Then there are operators to rename columns, and summarizing or aggregating operators, and if you permit relation values as attributes (RVA - relation-valued attribute), then operators such as group and ungroup. The SELECT statement in SQL serves to handle all of these except for the group and ungroup operators.

The flexibility of relational databases allows programmers to write queries that were not anticipated by the database designers. As a result, relational databases can be used by multiple applications in ways the original designers did not foresee, which is especially important for databases that might be used for decades. This has made the idea and implementation of relational databases very popular with businesses.
Dimensional model
The dimensional model is a specialized adaptation of the relational model used to represent data in data warehouses in a way that data can be easily summarized using OLAP queries. In the dimensional model, a database consists of a single large table of facts that are described using dimensions and measures. A dimension provides the context of a fact (such as who participated, when and where it happened, and its type) and is used in queries to group related facts together. Dimensions tend to be discrete and are often hierarchical; for example, the location might include the building, state, and country. A measure is a quantity describing the fact, such as revenue. It's important that measures can be meaningfully aggregated - for example, the revenue from different locations can be added together.

In an OLAP query, dimensions are chosen and the facts are grouped and added together to create a summary.

The dimensional model is often implemented on top of the relational model using a star schema, consisting of one table containing the facts and surrounding tables containing the dimensions. Particularly complicated dimensions might be represented using multiple tables, resulting in a snowflake schema.

A data warehouse can contain multiple star schemas that share dimension tables, allowing them to be used together. Coming up with a standard set of dimensions is an important part of dimensional modeling.
Object database models
In recent years, the object-oriented paradigm has been applied to database technology, creating a new programming model known as object databases. These databases attempt to bring the database world and the application programming world closer together, in particular by ensuring that the database uses the same type system as the application program. This aims to avoid the overhead (sometimes referred to as the impedance mismatch) of converting information between its representation in the database (for example as rows in tables) and its representation in the application program (typically as objects). At the same time object databases attempt to introduce the key ideas of object programming, such as encapsulation and polymorphism, into the world of databases.

A variety of these ways have been tried for storing objects in a database. Some products have approached the problem from the application programming end, by making the objects manipulated by the program persistent. This also typically requires the addition of some kind of query language, since conventional programming languages do not have the ability to find objects based on their information content. Others have attacked the problem from the database end, by defining an object-oriented data model for the database, and defining a database programming language that allows full programming capabilities as well as traditional query facilities.

Object databases suffered because of a lack of standardization: although standards were defined by ODMG, they were never implemented well enough to ensure interoperability between products. Nevertheless, object databases have been used successfully in many applications: usually specialized applications such as engineering databases or molecular biology databases rather than mainstream commercial data processing. However, object database ideas were picked up by the relational vendors and influenced extensions made to these products and indeed to the SQL language.
Database internals
Indexing
All of these kinds of database can take advantage of indexing to increase their speed, and this technology has advanced tremendously since its early uses in the 1960s and 1970s. The most common kind of index is a sorted list of the contents of some particular table column, with pointers to the row associated with the value. An index allows a set of table rows matching some criterion to be located quickly. Various methods of indexing are commonly used; B-trees, hashes, and linked lists are all common indexing techniques.

Relational DBMSs have the advantage that indexes can be created or dropped without changing existing applications making use of it. The database chooses between many different strategies based on which one it estimates will run the fastest.

Relational DBMSs utilize many different algorithms to compute the result of an SQL statement. The RDBMS will produce a plan of how to execute the query, which is generated by analyzing the run times of the different algorithms and selecting the quickest. Some of the key algorithms that deal with joins are Nested Loops Join, Sort-Merge Join and Hash Join.
Transactions and concurrency
In addition to their data model, most practical databases ("transactional databases") attempt to enforce a database transaction model that has desirable data integrity properties. Ideally, the database software should enforce the ACID rules, summarized here:

* Atomicity: Either all the tasks in a transaction must be done, or none of them. The transaction must be completed, or else it must be undone (rolled back).
* Consistency: Every transaction must preserve the integrity constraints — the declared consistency rules — of the database. It cannot place the data in a contradictory state.
* Isolation: Two simultaneous transactions cannot interfere with one another. Intermediate results within a transaction are not visible to other transactions.
* Durability: Completed transactions cannot be aborted later or their results discarded. They must persist through (for instance) restarts of the DBMS after crashes.

In practice, many DBMS's allow most of these rules to be selectively relaxed for better performance.

Concurrency control is a method used to ensure that transactions are executed in a safe manner and follow the ACID rules. The DBMS must be able to ensure that only serializable, recoverable schedules are allowed, and that no actions of committed transactions are lost while undoing aborted transactions.
Replication
Replication of databases is closely related to transactions. If a database can log its individual actions, it is possible to create a duplicate of the data in real time. The duplicate can be used to improve performance or availability of the whole database system. Common replication concepts include:

* Master/Slave Replication: All write requests are performed on the master and then replicated to the slaves
* Quorum: The result of Read and Write requests is calculated by querying a "majority" of replicas.
* Multimaster: Two or more replicas sync each other via a transaction identifier.

Applications of databases
Databases are used in many applications, spanning virtually the entire range of computer software. Databases are the preferred method of storage for large multiuser applications, where coordination between many users is needed. Even individual users find them convenient, though, and many electronic mail programs and personal organizers are based on standard database technology. Software database drivers are available for most database platforms so that application software can use a common application programming interface (API) to retrieve the information stored in a database. Two commonly used database APIs are JDBC and ODBC

2007-07-19

Application Configuration File


Sample Code to manage app.config

Dim strConfig As String
strConfig = System.Reflection.Assembly.GetExecutingAssembly().
CodeBase.Replace("file:///", "") + ".config"


Dim doc As XmlDocument = New System.Xml.XmlDocument()
doc.Load(strConfig)

' Get Node value
MessageBox.Show(doc.SelectSingleNode("descendant::
appSettings/add[@key='ConnectionString']").
Attributes("value").Value())


' Update Node value
doc.SelectSingleNode("descendant::appSettings/
add[@key='ConnectionString']").Attributes("value").Value
= "This is new connection string"

System.Configuration Basics

The System.Configuration namespace provides the functionality for reading configuration files. Microsoft released an XML schema dictating the format for configuration files that can be read using the System.Configuration API, enabling the accessing object to automatically consume the configuration files. This way, you can allow configuration files to be read without having to develop a bunch of plumbing to read the file and find the desired setting. Multiple types of configuration files are relevant to .NET, but this article focuses exclusively on the configuration files containing application-specific settings.

The name and storage location of an application configuration file depends on the application type with which it is being used. A configuration file for an executable (.exe) is located in the same directory as the application. The file is the name of the application with a .config extension. For example, notepad.exe would have a configuration file of notepad.exe.config. A configuration file for an ASP.NET application is called web.config and is located in the root of the application's virtual directory.

appSettings Section

An application configuration file follows a specific XML schema. The appSettings section is a predefined section of the configuration file designed to make it very easy to retrieve a value based on a given name. This is the easiest way to add application-specific settings into an application configuration file. The appSettings section of the configuration file consists of a series of "add" elements with "key" and "value" attributes. While the appSettings section is predefined, it is not included in a configuration file by default and must be manually added. A simple example of a configuration file would be the following:



read more



Send Email with Gmail

This sample base on vb.net 2005.

There are two step to create this.

1. You must insert mailSettings tag in app.config for window application or insert in web.config for web application.

2. Use System.Net.Mail namespace.

Sample Code for window application.
1. Insert this tag in app.config (Config Google SMTP).










2. Use System.Net.Mail namespace.


Imports System.Net.Mail

Public
Sub SendEmail()

Dim client As New SmtpClient()
Dim sendTo As New MailAddress("sendToAccount@gmail.com")
Dim from As MailAddress = New MailAddress("from@address.com")
Dim
message As New MailMessage(from,sendTo)


message.IsBodyHtml = True
message.Subject = "HI"
message.Body = "Got it!!"

' Use the same account in app.config to authenticate.
Dim basicAuthenticationInfo As New System.Net.NetworkCredential("yourAccount@gmail.com", "YourPassword")


client.Host = "smtp.gmail.com"
client.UseDefaultCredentials = False

client.Credentials = basicAuthenticationInfo
client.EnableSsl = True

Try

client.Send(message)
Console.WriteLine("SUCCESS")

Catch ex As Exception

Console.WriteLine("SEND FAIL")

End Try

End Sub

2007-07-18

Create Data Dictionary By Query

This is a query that use for generate your simple data
dictionary.



Sample

select distinct syscolumns.name,systypes.name as Type,
syscolumns.length,sysproperties.value

From syscolumns
inner join sysobjects on sysobjects.id=syscolumns.id
left outer join sysproperties on
sysproperties.smallid=syscolumns.colid
and sysproperties.id = syscolumns.id
inner join systypes on
syscolumns.xtype = systypes.xtype
where sysobjects.name='TableName'

Solving The Multiple Inheritance Issue Under .NET Platform

.NET : Solving The Multiple Inheritance Issue Under .NET Platform


.NET platform does not support multiple inheritance. Do not confuse multilevel inheritance with multiple inheritance. With multiple inheritance we can have a subclass that inherits from two classes at the same time.

Let's suppose we have an application that has a class Customers and another class Vendors. If you wanted to combine these two classes into one CustomerVendor class it would be a combination of Customers and Vendors just like the diagram below.

Please copy the following link into a new browser windor to view the diagram: http://www.vbprofs.com/images/Article Images/VBNETinheritance.gif

In the above diagram we see how the CustomerVendor class inherits from both of those classes.

Multiple inheritance is complex and can be dangerous. The advantages of code re-usage prevail over complexity is up to your choice.

Multiple inheritance is not supported by VB.NET or .Net platform. Instead of multiple inheritance we can use multiple interfaces to achieve similar effect to multiple inheritance.

In VB.NET all objects have a primary or native interface, which is composed of properties, events, methods or member variables declared using Public keyword. Objects can implement also secondary interfaces by using Implement keyword.

Sometimes it is helpful for an object to have more than one interface, allowing us to interact with the object in different ways. Inheritance allow us to create subclasses that are a specialized case of the base class.

Example

Sometimes we have a group of objects that are not the similar, but we want to handle them the same manner. We want all the objects to act as if they are the same, even though they are different.

We can have some different objects in an application, such as customer, product, invoice etc. Each object would have a default interface appropriate to each individual object, and each of them is a different class. No natural inheritance is implied between these classes.

Let's suppose we want to print a document for each type of object. In this case we'd like to make them all act as printable object. To accomplish this we can define a generic interface that would enable generating a printed document. By implementing a common interface we are able to write a routine that accepts any object that implements a printed document.

To conclude, by implementing multiple interfaces in VB.NET, we can achieve a similar effect to that of multiple inheritance.


About the Author:

Thomas is an experienced Visual Basic developer, with expertise of 7+ years developing financial applications. His main IT skills are VB, SQL, Crystal Reports - should you need a VB developer for your projects feel free to contact Thomas through his personal website at http://www.Kaloyani.com or through http://www.VBprofs.com

2007-07-17

Regular expression


Sample Expression.

1. Email Address
Single email (xxx@xxx.com)
((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}

Email with semicolon
(xxx@xxx.com; aaa@aaa.com; bbb@bbb.com)

^(\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)
*\s*[,;]?\b)*$

2. Zip Code (32082)
\d{5}(-\d{4})?

3. Phone Number (111-111-1111)
((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}

-----------------------------------------------------------


What is Regular expression?

In computing, a regular expression is a string that is used to describe or match a set of strings, according to certain syntax rules.

Regular expressions are used by many text editors and utilities to search and manipulate bodies of text based on certain patterns. Many programming languages support regular expressions for string manipulation. For example, Perl and Tcl have a powerful regular expression engine built directly into their syntax. The set of utilities (including the editor ed and the filter grep) provided by Unix distributions were the first to popularize the concept of regular expressions. "Regular expression" is often shortened in speech to regex, and in writing to regexp or regex (singular) or regexps, regexes, or regexen (plural).

As an example of the syntax, the regular expression \bex can be used to describe (and search for) all of the instances of the string "ex" that occur at word breaks (signified by the \b). Thus in the phrase, "Texts for expert experimenters," the regular expresssion \bex returns the "ex" in "expert" and "experimenters," but not in "Texts" (because the "ex" occurs inside the word there and not at the word break).

Many modern computing systems provide wildcard characters in matching filenames from a file system. This is a core capability of many command-line shells and is known as globbing. Wildcards differ from regular expressions in that they can only express very restrictive forms of alternation.

more information please read http://en.wikipedia.org/wiki/Regular_expression