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

2007-07-15

Will Microsoft Kill Free Email on the Net?

Spam has been such a problem that email filters are now widespread on the Net. These filters are a necessary response to the menace of spam. However, will the excuse of spam be used by companies such as Hotmail to charge for email?

Disturbing news that Hotmail (owned by Microsoft) is blocking perfectly legitimate emails because they have been caught by their anti-spam filters is increasing these fears.

Allan Gardyne of Associateprograms.com has been commenting recently about the difficulties SiteSell (owner of the website building package SiteBuildIt) has had with Hotmail.

http://associateprograms.com/discus/viewtopic.php?t=2847

When SiteSell complained to Hotmail they did not get a helpful response. Microsoft suggested that they use the services of a company called Bonded Sender which would ensure that SiteSell’s legitimate non-spam emails would reach their customers. It just happens that one of the owners of Bonded Sender is a former employee of Microsoft!

Many other companies have had similar problems with Hotmail. Bill Gates is on record as wishing to charge for email as a method of preventing spam. Unfortunately, when the big companies on the Net gang up like this, a sort of inevitability about charging for email creeps in. Nearly 60% of email is handled by Hotmail, AOL, and Yahoo combined. These three companies could have the power to force customers to pay for their email.

However, customers still have bargaining power. They may decide to stop using Hotmail and opt for a genuine free service. The founding fathers of the Internet had a public service attitude to the free dissemination of information. If the big companies charge for email, this egalitarian ideal will be lost.

The most appealing aspect of the Internet for many people was precisely this level-playing field that it created. The hobbyist in any part of the world could communicate and pass information (through email!) to other enthusiasts. The small entrepreneur could set up a website and make money without reference to the multinationals. However, this freedom will be lost if customers are not vigilant. The big companies like Microsoft are businesses concerned with profit. The freedom of access that the Internet gives to the small person in any part of the world is not a priority of the multinationals.


© John Lynch
==================================================
For Free Internet marketing E-books on Net Writing, Web Mastering, Net Auctions, Affiliate help go to: http://www.merchant-account-service.com/free_courses_online.html
==================================================


Read more articles by: John Lynch
.
Article Source: www.iSnare.com

2007-07-13

Change All Column's Collation By Sql Script

Change All Column's Collation By Sql Script

You can change your database collation from enterprise manager. But your columns in table did not change accordingly.
Here is show how to change all collation columns in database. (You can change Thai_CI_AS to your collation.)


Sample Script
DECLARE @@TableName Nvarchar(100)
DECLARE @@ColumnName Nvarchar(100)
DECLARE @@ColumnType NvarChar(100)
DECLARE @@ColumnLengh FLOAT
DECLARE
@@SQL NvarChar(1000)
DECLARE
@@IsNullAble NvarChar(50)

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

DECLARE my_column CURSOR FOR

select syscolumns.name,systypes.name as Type, syscolumns.length ,syscolumns.isnullable

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.xtype='u' And sysobjects.name=@@TableName And (systypes.name='nvarchar' or systypes.name='varchar')


OPEN my_column

FETCH NEXT FROM my_column INTO @@ColumnName,@@ColumnType,@@ColumnLengh,@@IsNullAble


WHILE @@FETCH_STATUS = 0

BEGIN

IF (@@IsNullAble=1)

BEGIN

Select @@SQL =( 'ALTER TABLE ' + @@TableName + ' ALTER COLUMN ' + @@ColumnName + ' ' + @@ColumnType +
'(' + CAST(@@ColumnLengh as
NVARCHAR) + ') COLLATE ' + ' Thai_CI_AS NULL')

END

ELSE

BEGIN

Select @@SQL =( 'ALTER TABLE ' + @@TableName + ' ALTER COLUMN ' + @@ColumnName + ' ' +
@@ColumnType +
'(' + CAST(@@ColumnLengh as NVARCHAR) + ') COLLATE ' + ' Thai_CI_AS NOT NULL')
END


PRIN(@@SQL)
--EXEC
(@@SQL)


FETCH NEXT FROM my_column INTO @@ColumnName,@@ColumnType,@@ColumnLengh,@@IsNullAble

END

CLOSE my_column

DEALLOCATE my_column


FETCH NEXT FROM my_cursor INTO @@TableName

END
CLOSE my_cursor
DEALLOCATE my_cursor
GO
.

Clear all text on one method

There are two parameters that send to this method.

1. Parent control such as panel , group box etc.
2. Control that you want to ignore.

Sample Code


Private Sub ClearData(ByVal parentCtr As Control, _

Optional ByVal ignoreControl As Control = Nothing)
Dim
ctr As Control

For Each ctr In parentCtr.Controls

If Not (ctr Is ignoreControl) Then

If TypeOf ctr Is TextBox Then

ctr.Text = ""

ElseIf TypeOf ctr Is ComboBox Then

DirectCast(ctr, ComboBox).SelectedIndex = -1

ElseIf TypeOf ctr Is ListBox Then

CType(ctr, ListBox).Items.Clear()

End If

End If

ClearData(ctr, ignoreControl)

Next

End Sub



2007-07-12

Step to Create Dataset

This sample show the basic step to create dataset and there element.


Sample Code

Step 1 you should to Imports System.Data

Step 2 please see sample code below.

Dim ds As New DataSet("DataSetSample")

' Create Table
Dim dt As New DataTable("DataTable")

' Create Column
Dim cl1 As New DataColumn("Column1")
cl1.DataType = GetType(Integer)

Dim cl2 As New DataColumn("Column2")
cl2.DataType = GetType(String)

' Add column to table
dt.Columns.Add(cl1)
dt.Columns.Add(cl2)

' Add DataTable to DataSet
ds.Tables.Add(dt)

' Step to add DataRow
' Create new row
Dim dr As DataRow
dr = ds.Tables("DataTable").NewRow

dr("Column1") = 1
dr("Column2") = "Welcome to vb.net Sample code"

' Add Row1
ds.Tables("DataTable").Rows.Add(dr)


' If you can use array of datarow.
Dim drArray(1) As DataRow

drArray(0) = ds.Tables(0).NewRow
drArray(0)("Column1") = 2
drArray(0)("Column2") = "Show easy sample code"
ds.Tables("DataTable").Rows.Add(drArray(0))

drArray(1) = ds.Tables(0).NewRow
drArray(1)("Column1") = 3
drArray(1)("Column2") = "Easy to understand"
ds.Tables("DataTable").Rows.Add(drArray(1))


' binddata to gridview
Me.DataGridView1.DataSource = ds.Tables("DataTable").Copy()


vb.net sample code

2007-07-11

VB.Net: Dynamic Usage Of Eventhandlers

VB.Net: Dynamic Usage Of Eventhandlers

WithEvents and Handles clause requires form us to declare the object variable and the event handler as we write our code, so linkage is created upon compilation. On the other hand, with AddHandler and RemoveHandler, linkage is created and removed at runtime, which is more flexible.

Let's assume that we want to load several MDI child forms, allowing each of them to be loaded only once, and of course to know when one of the child forms is closed. Since we have several forms to load we would like to use the AddHandler and RemoveHandler keywords so we can be flexible and write the minimal code we can.

Let's get dirty.

1. In each MDI child form we have to declare a public event.
Public Event FormClosed(ByVal f As Form)

2. In each MDI child form we have to use the Form_Closed method which handles the MyBase.Closed class and raise the FormClosed event.

Private Sub Form1_Closed(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles MyBase.Closed
RaiseEvent FormClosed(Me)
End Sub


3. On our MDI form we need to declare two member variables. The first's of type Form and the second's type is ArrayList.
Private m_f(0) as Form
Private m_sLoadedChildForms As New ArrayList


4. We need to implement a method the will search the MDI child forms that are loaded. We'll also use this method when we unload the MDI child forms.

Private Function SearchChildForm(ByVal strSearchForm As String, _Optional ByVal idxEventHandler As Long = -1) As Long
Dim i As Long = 0
For i = 0 To m_sLoadedForms.Count - 1
If m_sLoadedForms.Item(i) = strSearchForm Then
Dim j As Long = 0
For j = m_f.GetLowerBound(0) To m_f.GetUpperBound(0)
If m_f(j).Name = strSearchForm Then idxEventHandler = j
Next j
Return i
End If
Next
Return -1
End Function


5. We need to implement a method to load the mdi child forms and use the SearchChildForm method in order not to load the same mdi child form second time.

Private Sub LoadChildForms(ByVal f As Form)
If m_f.GetUpperBound(0) > 0 Then
ReDim Preserve m_f(m_f.GetUpperBound(0) + 1)
End If
m_f(m_f.GetUpperBound(0)) = f I
f Not SearchChildForm(m_f(m_f.GetUpperBound(0)).Name()) >= 0 Then
m_f(m_f.GetUpperBound(0)).MdiParent = Me
AddHandler m_f(m_f.GetUpperBound(0)).Closed, _
AddressOf UnloadChildForm
m_f(m_f.GetUpperBound(0)).Show()
m_sLoadedChildForms.Add(m_f(m_f.GetUpperBound(0)).Name)
Else
If m_f.GetUpperBound(0) > 0 Then
ReDim Preserve m_f(m_f.GetUpperBound(0) - 1)
End If
End If
End Sub


6. At last we need to implement a method to take out our mdi child form from the array list so we can load it again if we want.

Private Sub UnloadForm(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim i As Long
Dim s As String = sender.GetType().Name
Dim IndexForEventHandler = -1
i = SearchChildForm(s, IndexForEventHandler)
If i >= 0 Then m_sLoadedForms.RemoveAt(i)
If IndexForEventHandler >= 0 Then
RemoveHandler m_f(IndexForEventHandler).Closed, AddressOf UnloadForm
m_f(IndexForEventHandler) = Nothing
End If
End Sub


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-10

Programmer?

Are you programmer?

Do you know , What is programmer?
Today I found this and this is the meaning.

pro·gram·mer or pro·gram·er

n.
One who programs, especially:
a. Computer Science One who writes computer programs.
b. One who prepares or writes instructional programs.



Thank you www.thefreedictionary.com

2007-07-03

Read xml content by XmlDocument

This sample show, How to read xml content by use XmlDocument namespace.

You can see this link for xml sample content.

Sample Code


Dim m_xmld As XmlDocument
Dim m_nodelist As XmlNodeList
Dim m_node As XmlNode

'Create the XML Document
m_xmld = New XmlDocument()

'Load the Xml file
m_xmld.Load("YourPath\test.xml")

'Show all data in your xml
MessageBox.Show(m_xmld.OuterXml)


'Get the list of name nodes
m_nodelist = m_xmld.SelectNodes("/family/name")

'Loop through the nodes
For Each m_node In m_nodelist
'Get the Gender Attribute Value
Dim genderAttribute = m_node.Attributes.GetNamedItem("gender").Value

'Get the firstName Element Value
Dim firstNameValue = m_node.ChildNodes.Item(0).InnerText

'Get the lastName Element Value
Dim lastNameValue = m_node.ChildNodes.Item(1).InnerText

'Write Result to the Console
Console.Write("Gender: " & genderAttribute _
& " FirstName: " & firstNameValue & " LastName: " _
& lastNameValue)
Console.Write(vbCrLf)
Next


2007-07-02

Read xml content to DataSet.

This sample show, How to read xml's content to dataset.


Use System.Xml and System.IO namespace.

Imports System.Xml

Imports System.IO



Sample XML




Sample Code

Dim ds As New DataSet
' use filestream class to read xml content.
Dim streamRead As New System.IO.FileStream("C\test.xml", _
System.IO.FileMode.Open)


'Dataset can read content from FileStream.
ds.ReadXml(streamRead)

' Bind data to your control.
DataGridView1.DataSource = ds.Tables(0)


' Close FileStream object

streamRead.Close()


You will see you data in your data control.