Ramdas Add

Thursday, 16 February 2012

Basic Networking Tutorial

Basic Networking Tutorial

What is a computer Network?

A network is any collection of independent computers that communicate with one another over a shared network medium. A computer network is a collection of two or more connected computers. When these computers are joined in a network, people can share files and peripherals such as modems, printers, tape backup drives, or CD-ROM drives. When networks at multiple locations are connected using services available from phone companies, people can send e-mail, share links to the global Internet, or conduct video conferences in real time with other remote users. When a network becomes open sourced it can be managed properly with online collaboration software. As companies rely on applications like electronic mail and database management for core business operations, computer networking becomes increasingly more important.
Every network includes:

  • At least two computers Server or Client workstation.
  • Networking Interface Card's (NIC)
  • A connection medium, usually a wire or cable, although wireless communication between networked computers and peripherals is also possible.
  • Network Operating system software, such as Microsoft Windows NT or 2000, Novell NetWare, Unix and Linux.

Types of Networks:

LANs (Local Area Networks)

A network is any collection of independent computers that communicate with one another over a shared network medium. LANs are networks usually confined to a geographic area, such as a single building or a college campus. LANs can be small, linking as few as three computers, but often link hundreds of computers used by thousands of people. The development of standard networking protocols and media has resulted in worldwide proliferation of LANs throughout business and educational organizations.

WANs (Wide Area Networks)

Wide area networking combines multiple LANs that are geographically separate. This is accomplished by connecting the different LANs using services such as dedicated leased phone lines, dial-up phone lines (both synchronous and asynchronous), satellite links, and data packet carrier services. Wide area networking can be as simple as a modem and remote access server for employees to dial into, or it can be as complex as hundreds of branch offices globally linked using special routing protocols and filters to minimize the expense of sending data sent over vast distances.

Internet

The Internet is a system of linked networks that are worldwide in scope and facilitate data communication services such as remote login, file transfer, electronic mail, the World Wide Web and newsgroups.

With the meteoric rise in demand for connectivity, the Internet has become a communications highway for millions of users. The Internet was initially restricted to military and academic institutions, but now it is a full-fledged conduit for any and all forms of information and commerce. Internet websites now provide personal, educational, political and economic resources to every corner of the planet.

Intranet

With the advancements made in browser-based software for the Internet, many private organizations are implementing intranets. An intranet is a private network utilizing Internet-type tools, but available only within that organization. For large organizations, an intranet provides an easy access mode to corporate information for employees.

MANs (Metropolitan area Networks)

The refers to a network of computers with in a City.

VPN (Virtual Private Network)

VPN uses a technique known as tunneling to transfer data securely on the Internet to a remote access server on your workplace network. Using a VPN helps you save money by using the public Internet instead of making long–distance phone calls to connect securely with your private network. There are two ways to create a VPN connection, by dialing an Internet service provider (ISP), or connecting directly to Internet.

Categories of Network:

Peer to Peer and Server/Client NetworkNetwork can be divided in to two main categories:

  • Peer-to-peer.
  • Server – based.
In peer-to-peer networking there are no dedicated servers or hierarchy among the computers. All of the computers are equal and therefore known as peers. Normally each computer serves as Client/Server and there is no one assigned to be an administrator responsible for the entire network.

Peer-to-peer networks are good choices for needs of small organizations where the users are allocated in the same general area, security is not an issue and the organization and the network will have limited growth within the foreseeable future.

The term Client/server refers to the concept of sharing the work involved in processing data between the client computer and the most powerful server computer.

The client/server network is the most efficient way to provide:

  • Databases and management of applications such as Spreadsheets, Accounting, Communications and Document management.
  • Network management.
  • Centralized file storage.
The client/server model is basically an implementation of distributed or cooperative processing. At the heart of the model is the concept of splitting application functions between a client and a server processor. The division of labor between the different processors enables the application designer to place an application function on the processor that is most appropriate for that function. This lets the software designer optimize the use of processors--providing the greatest possible return on investment for the hardware.

Client/server application design also lets the application provider mask the actual location of application function. The user often does not know where a specific operation is executing. The entire function may execute in either the PC or server, or the function may be split between them. This masking of application function locations enables system implementers to upgrade portions of a system over time with a minimum disruption of application operations, while protecting the investment in existing hardware and software.

OSI ModelThe OSI Model:

Open System Interconnection (OSI) reference model has become an International standard and serves as a guide for networking. This model is the best known and most widely used guide to describe networking environments. Vendors design network products based on the specifications of the OSI model. It provides a description of how network hardware and software work together in a layered fashion to make communications possible. It also helps with trouble shooting by providing a frame of reference that describes how components are supposed to function.

There are seven to get familiar with and these are the physical layer, data link layer, network layer, transport layer, session layer, presentation layer, and the application layer.
  • Physical Layer, is just that the physical parts of the network such as wires, cables, and there media along with the length. Also this layer takes note of the electrical signals that transmit data throughout system.
  • Data Link Layer, this layer is where we actually assign meaning to the electrical signals in the network. The layer also determines the size and format of data sent to printers, and other devices. Also I don't want to forget that these are also called nodes in the network. Another thing to consider in this layer is will also allow and define the error detection and correction schemes that insure data was sent and received.
  • Network Layer, this layer provides the definition for the connection of two dissimilar networks.
  • Transport Layer, this layer allows data to be broken into smaller packages for data to be distributed and addressed to other nodes (workstations).
  • Session Layer, this layer helps out with the task to carry information from one node (workstation) to another node (workstation). A session has to be made before we can transport information to another computer.
  • Presentation Layer, this layer is responsible to code and decode data sent to the node.
  • Application Layer, this layer allows you to use an application that will communicate with say the operation system of a server. A good example would be using your web browser to interact with the operating system on a server such as Windows NT, which in turn gets the data you requested.

Network Architectures:

Ethernet Network ArchitectureEthernet

Ethernet is the most popular physical layer LAN technology in use today. Other LAN types include Token Ring, Fast Ethernet, Fiber Distributed Data Interface (FDDI), Asynchronous Transfer Mode (ATM) and LocalTalk. Ethernet is popular because it strikes a good balance between speed, cost and ease of installation. These benefits, combined with wide acceptance in the computer marketplace and the ability to support virtually all popular network protocols, make Ethernet an ideal networking technology for most computer users today. The Institute for Electrical and Electronic Engineers (IEEE) defines the Ethernet standard as IEEE Standard 802.3. This standard defines rules for configuring an Ethernet network as well as specifying how elements in an Ethernet network interact with one another. By adhering to the IEEE standard, network equipment and network protocols can communicate efficiently.

Fast Ethernet

For Ethernet networks that need higher transmission speeds, the Fast Ethernet standard (IEEE 802.3u) has been established. This standard raises the Ethernet speed limit from 10 Megabits per second (Mbps) to 100 Mbps with only minimal changes to the existing cable structure. There are three types of Fast Ethernet: 100BASE-TX for use with level 5 UTP cable, 100BASE-FX for use with fiber-optic cable, and 100BASE-T4 which utilizes an extra two wires for use with level 3 UTP cable. The 100BASE-TX standard has become the most popular due to its close compatibility with the 10BASE-T Ethernet standard. For the network manager, the incorporation of Fast Ethernet into an existing configuration presents a host of decisions. Managers must determine the number of users in each site on the network that need the higher throughput, decide which segments of the backbone need to be reconfigured specifically for 100BASE-T and then choose the necessary hardware to connect the 100BASE-T segments with existing 10BASE-T segments. Gigabit Ethernet is a future technology that promises a migration path beyond Fast Ethernet so the next generation of networks will support even higher data transfer speeds.

Token Ring ArchitectureToken Ring

Token Ring is another form of network configuration which differs from Ethernet in that all messages are transferred in a unidirectional manner along the ring at all times. Data is transmitted in tokens, which are passed along the ring and viewed by each device. When a device sees a message addressed to it, that device copies the message and then marks that message as being read. As the message makes its way along the ring, it eventually gets back to the sender who now notes that the message was received by the intended device. The sender can then remove the message and free that token for use by others.

Various PC vendors have been proponents of Token Ring networks at different times and thus these types of networks have been implemented in many organizations.

FDDI architectureFDDI

FDDI (Fiber-Distributed Data Interface) is a standard for data transmission on fiber optic lines in a local area network that can extend in range up to 200 km (124 miles). The FDDI protocol is based on the token ring protocol. In addition to being large geographically, an FDDI local area network can support thousands of users.

Protocols:

Network protocols are standards that allow computers to communicate. A protocol defines how computers identify one another on a network, the form that the data should take in transit, and how this information is processed once it reaches its final destination. Protocols also define procedures for handling lost or damaged transmissions or "packets." TCP/IP (for UNIX, Windows NT, Windows 95 and other platforms), IPX (for Novell NetWare), DECnet (for networking Digital Equipment Corp. computers), AppleTalk (for Macintosh computers), and NetBIOS/NetBEUI (for LAN Manager and Windows NT networks) are the main types of network protocols in use today.

Although each network protocol is different, they all share the same physical cabling. This common method of accessing the physical network allows multiple protocols to peacefully coexist over the network media, and allows the builder of a network to use common hardware for a variety of protocols. This concept is known as "protocol independence,"

Some Important Protocols and their job:
Protocol Acronym Its Job
Point-To-Point TCP/IP The backbone protocol of the internet. Popular also for intranets using the internet
Transmission Control Protocol/internet Protocol TCP/IP The backbone protocol of the internet. Popular also for intranets using the internet
Internetwork Package Exchange/Sequenced Packet Exchange IPX/SPX This is a standard protocol for Novell Network Operating System
NetBIOS Extended User Interface NetBEUI This is a Microsoft protocol that doesn't support routing to other networks
File Transfer Protocol FTP Used to send and receive files from a remote host
Hyper Text Transfer Protocol HTTP Used for the web to send documents that are encoded in HTML.
Network File Services NFS Allows network nodes or workstations to access files and drives as if they were their own.
Simple Mail Transfer Protocol SMTP Used to send Email over a network
Telnet   Used to connect to a host and emulate a terminal that the remote server can recognize

Introduction to TCP/IP Networks:

TCP/IP-based networks play an increasingly important role in computer networks. Perhaps one reason for their appeal is that they are based on an open specification that is not controlled by any vendor.

What Is TCP/IP?

TCP stands for Transmission Control Protocol and IP stands for Internet Protocol. The term TCP/IP is not limited just to these two protocols, however. Frequently, the term TCP/IP is used to refer to a group of protocols related to the TCP and IP protocols such as the User Datagram Protocol (UDP), File Transfer Protocol (FTP), Terminal Emulation Protocol (TELNET), and so on.

The Origins of TCP/IP

In the late 1960s, DARPA (the Defense Advanced Research Project Agency), in the United States, noticed that there was a rapid proliferation of computers in military communications. Computers, because they can be easily programmed, provide flexibility in achieving network functions that is not available with other types of communications equipment. The computers then used in military communications were manufactured by different vendors and were designed to interoperate with computers from that vendor only. Vendors used proprietary protocols in their communications equipment. The military had a multi vendor network but no common protocol to support the heterogeneous equipment from different vendors

Net work Cables and Stuff:

In the network you will commonly find three types of cables used these are the, coaxial cable, fiber optic and twisted pair.

Thick Coaxial Cable

This type cable is usually yellow in color and used in what is called thicknets, and has two conductors. This coax can be used in 500-meter lengths. The cable itself is made up of a solid center wire with a braided metal shield and plastic sheathing protecting the rest of the wire.

Thin Coaxial Cable

As with the thick coaxial cable is used in thicknets the thin version is used in thinnets. This type cable is also used called or referred to as RG-58. The cable is really just a cheaper version of the thick cable.

Fiber Optic Cable

As we all know fiber optics are pretty darn cool and not cheap. This cable is smaller and can carry a vast amount of information fast and over long distances.

Twisted Pair Cables

These come in two flavors of unshielded and shielded.

Unshielded Twisted Pair and Shielded Twisted Pair

Shielded Twisted Pair (STP)

Is more common in high-speed networks. The biggest difference you will see in the UTP and STP is that the STP use's metallic shield wrapping to protect the wire from interference.

-Something else to note about these cables is that they are defined in numbers also. The bigger the number the better the protection from interference. Most networks should go with no less than a CAT 3 and CAT 5 is most recommended.

-Now you know about cables we need to know about connectors. This is pretty important and you will most likely need the RJ-45 connector. This is the cousin of the phone jack connector and looks real similar with the exception that the RJ-45 is bigger. Most commonly your connector are in two flavors and this is BNC (Bayonet Naur Connector) used in thicknets and the RJ-45 used in smaller networks using UTP/STP.

Unshielded Twisted Pair (UTP)

This is the most popular form of cables in the network and the cheapest form that you can go with. The UTP has four pairs of wires and all inside plastic sheathing. The biggest reason that we call it Twisted Pair is to protect the wires from interference from themselves. Each wire is only protected with a thin plastic sheath.

Ethernet Cabling

Now to familiarize you with more on the Ethernet and it's cabling we need to look at the 10's. 10Base2, is considered the thin Ethernet, thinnet, and thinwire which uses light coaxial cable to create a 10 Mbps network. The cable segments in this network can't be over 185 meters in length. These cables connect with the BNC connector. Also as a note these unused connection must have a terminator, which will be a 50-ohm terminator.

10Base5, this is considered a thicknet and is used with coaxial cable arrangement such as the BNC connector. The good side to the coaxial cable is the high-speed transfer and cable segments can be up to 500 meters between nodes/workstations. You will typically see the same speed as the 10Base2 but larger cable lengths for more versatility.

10BaseT, the “T” stands for twisted as in UTP (Unshielded Twisted Pair) and uses this for 10Mbps of transfer. The down side to this is you can only have cable lengths of 100 meters between nodes/workstations. The good side to this network is they are easy to set up and cheap! This is why they are so common an ideal for small offices or homes.

100BaseT, is considered Fast Ethernet uses STP (Shielded Twisted Pair) reaching data transfer of 100Mbps. This system is a little more expensive but still remains popular as the 10BaseT and cheaper than most other type networks. This on of course would be the cheap fast version.

10BaseF, this little guy has the advantage of fiber optics and the F stands for just that. This arrangement is a little more complicated and uses special connectors and NIC's along with hubs to create its network. Pretty darn neat and not to cheap on the wallet.

An important part of designing and installing an Ethernet is selecting the appropriate Ethernet medium. There are four major types of media in use today: Thickwire for 10BASE5 networks, thin coax for 10BASE2 networks, unshielded twisted pair (UTP) for 10BASE-T networks and fiber optic for 10BASE-FL or Fiber-Optic Inter-Repeater Link (FOIRL) networks. This wide variety of media reflects the evolution of Ethernet and also points to the technology's flexibility. Thickwire was one of the first cabling systems used in Ethernet but was expensive and difficult to use. This evolved to thin coax, which is easier to work with and less expensive.

Network Topologies:

What is a Network topology?

A network topology is the geometric arrangement of nodes and cable links in a LAN,

There are three topology's to think about when you get into networks. These are the star, rind, and the bus.

Star, in a star topology each node has a dedicated set of wires connecting it to a central network hub. Since all traffic passes through the hub, the hub becomes a central point for isolating network problems and gathering network statistics.

Ring, a ring topology features a logically closed loop. Data packets travel in a single direction around the ring from one network device to the next. Each network device acts as a repeater, meaning it regenerates the signal

Bus, the bus topology, each node (computer, server, peripheral etc.) attaches directly to a common cable. This topology most often serves as the backbone for a network. In some instances, such as in classrooms or labs, a bus will connect small workgroups

Collisions:

Ethernet is a shared media, so there are rules for sending packets of data to avoid conflicts and protect data integrity. Nodes determine when the network is available for sending packets. It is possible that two nodes at different locations attempt to send data at the same time. When both PCs are transferring a packet to the network at the same time, a collision will result.

Minimizing collisions is a crucial element in the design and operation of networks. Increased collisions are often the result of too many users on the network, which results in a lot of contention for network bandwidth. This can slow the performance of the network from the user's point of view. Segmenting the network, where a network is divided into different pieces joined together logically with a bridge or switch, is one way of reducing an overcrowded network.

Ethernet Products:

The standards and technology that have just been discussed help define the specific products that network managers use to build Ethernet networks. The following text discusses the key products needed to build an Ethernet LAN.

Transceivers

Transceivers are used to connect nodes to the various Ethernet media. Most computers and network interface cards contain a built-in 10BASE-T or 10BASE2 transceiver, allowing them to be connected directly to Ethernet without requiring an external transceiver. Many Ethernet devices provide an AUI connector to allow the user to connect to any media type via an external transceiver. The AUI connector consists of a 15-pin D-shell type connector, female on the computer side, male on the transceiver side. Thickwire (10BASE5) cables also use transceivers to allow connections.

For Fast Ethernet networks, a new interface called the MII (Media Independent Interface) was developed to offer a flexible way to support 100 Mbps connections. The MII is a popular way to connect 100BASE-FX links to copper-based Fast Ethernet devices.

Network Interface CardsNetwork Interface Cards:

Network interface cards, commonly referred to as NICs, and are used to connect a PC to a network. The NIC provides a physical connection between the networking cable and the computer's internal bus. Different computers have different bus architectures; PCI bus master slots are most commonly found on 486/Pentium PCs and ISA expansion slots are commonly found on 386 and older PCs. NICs come in three basic varieties: 8-bit, 16-bit, and 32-bit. The larger the number of bits that can be transferred to the NIC, the faster the NIC can transfer data to the network cable.

Many NIC adapters comply with Plug-n-Play specifications. On these systems, NICs are automatically configured without user intervention, while on non-Plug-n-Play systems, configuration is done manually through a setup program and/or DIP switches.

Cards are available to support almost all networking standards, including the latest Fast Ethernet environment. Fast Ethernet NICs are often 10/100 capable, and will automatically set to the appropriate speed. Full duplex networking is another option, where a dedicated connection to a switch allows a NIC to operate at twice the speed.

Hubs/Repeaters:

Hubs/repeaters are used to connect together two or more Ethernet segments of any media type. In larger designs, signal quality begins to deteriorate as segments exceed their maximum length. Hubs provide the signal amplification required to allow a segment to be extended a greater distance. A hub takes any incoming signal and repeats it out all ports.

Ethernet hubs are necessary in star topologies such as 10BASE-T. A multi-port twisted pair hub allows several point-to-point segments to be joined into one network. One end of the point-to-point link is attached to the hub and the other is attached to the computer. If the hub is attached to a backbone, then all computers at the end of the twisted pair segments can communicate with all the hosts on the backbone. The number and type of hubs in any one-collision domain is limited by the Ethernet rules. These repeater rules are discussed in more detail later.
Network Type Max Nodes
Per Segment
Max Distance
Per Segment
10BASE-T
10BASE2
10BASE5
10BASE-FL
2
30
100
2
100m
185m
500m
2000m

Adding Speed:

While repeaters allow LANs to extend beyond normal distance limitations, they still limit the number of nodes that can be supported. Bridges and switches, however, allow LANs to grow significantly larger by virtue of their ability to support full Ethernet segments on each port. Additionally, bridges and switches selectively filter network traffic to only those packets needed on each segment - this significantly increases throughput on each segment and on the overall network. By providing better performance and more flexibility for network topologies, bridges and switches will continue to gain popularity among network managers.

Bridges:

The function of a bridge is to connect separate networks together. Bridges connect different networks types (such as Ethernet and Fast Ethernet) or networks of the same type. Bridges map the Ethernet addresses of the nodes residing on each network segment and allow only necessary traffic to pass through the bridge. When a packet is received by the bridge, the bridge determines the destination and source segments. If the segments are the same, the packet is dropped ("filtered"); if the segments are different, then the packet is "forwarded" to the correct segment. Additionally, bridges do not forward bad or misaligned packets.

Bridges are also called "store-and-forward" devices because they look at the whole Ethernet packet before making filtering or forwarding decisions. Filtering packets, and regenerating forwarded packets enable bridging technology to split a network into separate collision domains. This allows for greater distances and more repeaters to be used in the total network design.

Ethernet Switches

Ethernet Switches:

Ethernet switches are an expansion of the concept in Ethernet bridging. LAN switches can link four, six, ten or more networks together, and have two basic architectures: cut-through and store-and-forward. In the past, cut-through switches were faster because they examined the packet destination address only before forwarding it on to its destination segment. A store-and-forward switch, on the other hand, accepts and analyzes the entire packet before forwarding it to its destination.

It takes more time to examine the entire packet, but it allows the switch to catch certain packet errors and keep them from propagating through the network. Both cut-through and store-and-forward switches separate a network into collision domains, allowing network design rules to be extended. Each of the segments attached to an Ethernet switch has a full 10 Mbps of bandwidth shared by fewer users, which results in better performance (as opposed to hubs that only allow bandwidth sharing from a single Ethernet). Newer switches today offer high-speed links, FDDI, Fast Ethernet or ATM. These are used to link switches together or give added bandwidth to high-traffic servers. A network composed of a number of switches linked together via uplinks is termed a "collapsed backbone" network.

Routers:

Routers filter out network traffic by specific protocol rather than by packet address. Routers also divide networks logically instead of physically. An IP router can divide a network into various subnets so that only traffic destined for particular IP addresses can pass between segments. Network speed often decreases due to this type of intelligent forwarding. Such filtering takes more time than that exercised in a switch or bridge, which only looks at the Ethernet address. However, in more complex networks, overall efficiency is improved by using routers.

What is a network firewall?

A firewall is a system or group of systems that enforces an access control policy between two networks. The actual means by which this is accomplished varies widely, but in principle, the firewall can be thought of as a pair of mechanisms: one which exists to block traffic, and the other which exists to permit traffic. Some firewalls place a greater emphasis on blocking traffic, while others emphasize permitting traffic. Probably the most important thing to recognize about a firewall is that it implements an access control policy. If you don't have a good idea of what kind of access you want to allow or to deny, a firewall really won't help you. It's also important to recognize that the firewall's configuration, because it is a mechanism for enforcing policy, imposes its policy on everything behind it. Administrators for firewalls managing the connectivity for a large number of hosts therefore have a heavy responsibility.

Network Design Criteria:

Ethernets and Fast Ethernets have design rules that must be followed in order to function correctly. Maximum number of nodes, number of repeaters and maximum segment distances are defined by the electrical and mechanical design properties of each type of Ethernet and Fast Ethernet media.

A network using repeaters, for instance, functions with the timing constraints of Ethernet. Although electrical signals on the Ethernet media travel near the speed of light, it still takes a finite time for the signal to travel from one end of a large Ethernet to another. The Ethernet standard assumes it will take roughly 50 microseconds for a signal to reach its destination.

Ethernet is subject to the "5-4-3" rule of repeater placement: the network can only have five segments connected; it can only use four repeaters; and of the five segments, only three can have users attached to them; the other two must be inter-repeater links.

If the design of the network violates these repeater and placement rules, then timing guidelines will not be met and the sending station will resend that packet. This can lead to lost packets and excessive resent packets, which can slow network performance and create trouble for applications. Fast Ethernet has modified repeater rules, since the minimum packet size takes less time to transmit than regular Ethernet. The length of the network links allows for a fewer number of repeaters. In Fast Ethernet networks, there are two classes of repeaters. Class I repeaters have a latency of 0.7 microseconds or less and are limited to one repeater per network. Class II repeaters have a latency of 0.46 microseconds or less and are limited to two repeaters per network. The following are the distance (diameter) characteristics for these types of Fast Ethernet repeater combinations:
Fast Ethernet Copper Fiber
No Repeaters
One Class I Repeater
One Class II Repeater
Two Class II Repeaters
100m
200m
200m
205m
412m*
272m
272m
228m
* Full Duplex Mode 2 km


When conditions require greater distances or an increase in the number of nodes/repeaters, then a bridge, router or switch can be used to connect multiple networks together. These devices join two or more separate networks, allowing network design criteria to be restored. Switches allow network designers to build large networks that function well. The reduction in costs of bridges and switches reduces the impact of repeater rules on network design.

Each network connected via one of these devices is referred to as a separate collision domain in the overall network.

Types of Servers:

Device Servers

A device server is defined as a specialized, network-based hardware device designed to perform a single or specialized set of server functions. It is characterized by a minimal operating architecture that requires no per seat network operating system license, and client access that is independent of any operating system or proprietary protocol. In addition the device server is a "closed box," delivering extreme ease of installation, minimal maintenance, and can be managed by the client remotely via a Web browser.

Print servers, terminal servers, remote access servers and network time servers are examples of device servers which are specialized for particular functions. Each of these types of servers has unique configuration attributes in hardware or software that help them to perform best in their particular arena.

Print Servers

Print servers allow printers to be shared by other users on the network. Supporting either parallel and/or serial interfaces, a print server accepts print jobs from any person on the network using supported protocols and manages those jobs on each appropriate printer.

Print servers generally do not contain a large amount of memory; printers simply store information in a queue. When the desired printer becomes available, they allow the host to transmit the data to the appropriate printer port on the server. The print server can then simply queue and print each job in the order in which print requests are received, regardless of protocol used or the size of the job.

Multiport Device Servers

Devices that are attached to a network through a multiport device server can be shared between terminals and hosts at both the local site and throughout the network. A single terminal may be connected to several hosts at the same time (in multiple concurrent sessions), and can switch between them. Multiport device servers are also used to network devices that have only serial outputs. A connection between serial ports on different servers is opened, allowing data to move between the two devices.

Given its natural translation ability, a multi-protocol multiport device server can perform conversions between the protocols it knows, like LAT and TCP/IP. While server bandwidth is not adequate for large file transfers, it can easily handle host-to-host inquiry/response applications, electronic mailbox checking, etc. And it is far more economical than the alternatives of acquiring expensive host software and special-purpose converters. Multiport device and print servers give their users greater flexibility in configuring and managing their networks.

Whether it is moving printers and other peripherals from one network to another, expanding the dimensions of interoperability or preparing for growth, multiport device servers can fulfill your needs, all without major rewiring.

Access Servers

While Ethernet is limited to a geographic area, remote users such as traveling sales people need access to network-based resources. Remote LAN access, or remote access, is a popular way to provide this connectivity. Access servers use telephone services to link a user or office with an office network. Dial-up remote access solutions such as ISDN or asynchronous dial introduce more flexibility. Dial-up remote access offers both the remote office and the remote user the economy and flexibility of "pay as you go" telephone services. ISDN is a special telephone service that offers three channels, two 64 Kbps "B" channels for user data and a "D" channel for setting up the connection. With ISDN, the B channels can be combined for double bandwidth or separated for different applications or users. With asynchronous remote access, regular telephone lines are combined with modems and remote access servers to allow users and networks to dial anywhere in the world and have data access. Remote access servers provide connection points for both dial-in and dial-out applications on the network to which they are attached. These hybrid devices route and filter protocols and offer other services such as modem pooling and terminal/printer services. For the remote PC user, one can connect from any available telephone jack (RJ45), including those in a hotel rooms or on most airplanes.

Network Time Servers

A network time server is a server specialized in the handling of timing information from sources such as satellites or radio broadcasts and is capable of providing this timing data to its attached network. Specialized protocols such as NTP or udp/time allow a time server to communicate to other network nodes ensuring that activities that must be coordinated according to their time of execution are synchronized correctly. GPS satellites are one source of information that can allow global installations to achieve constant timing.

IP Addressing:

An IP (Internet Protocol) address is a unique identifier for a node or host connection on an IP network. An IP address is a 32 bit binary number usually represented as 4 decimal values, each representing 8 bits, in the range 0 to 255 (known as octets) separated by decimal points. This is known as "dotted decimal" notation.

Example: 140.179.220.200

It is sometimes useful to view the values in their binary form.

140 .179 .220 .200

10001100.10110011.11011100.11001000

Every IP address consists of two parts, one identifying the network and one identifying the node. The Class of the address and the subnet mask determine which part belongs to the network address and which part belongs to the node address.

Address Classes:

There are 5 different address classes. You can determine which class any IP address is in by examining the first 4 bits of the IP address.

Class A addresses begin with 0xxx, or 1 to 126 decimal.

Class B addresses begin with 10xx, or 128 to 191 decimal.

Class C addresses begin with 110x, or 192 to 223 decimal.

Class D addresses begin with 1110, or 224 to 239 decimal.

Class E addresses begin with 1111, or 240 to 254 decimal.

Addresses beginning with 01111111, or 127 decimal, are reserved for loopback and for internal testing on a local machine. [You can test this: you should always be able to ping 127.0.0.1, which points to yourself] Class D addresses are reserved for multicasting. Class E addresses are reserved for future use. They should not be used for host addresses.

Now we can see how the Class determines, by default, which part of the IP address belongs to the network (N) and which part belongs to the node (n).

Class A -- NNNNNNNN.nnnnnnnn.nnnnnnn.nnnnnnn

Class B -- NNNNNNNN.NNNNNNNN.nnnnnnnn.nnnnnnnn

Class C -- NNNNNNNN.NNNNNNNN.NNNNNNNN.nnnnnnnn

In the example, 140.179.220.200 is a Class B address so by default the Network part of the address (also known as the Network Address) is defined by the first two octets (140.179.x.x) and the node part is defined by the last 2 octets (x.x.220.200).

In order to specify the network address for a given IP address, the node section is set to all "0"s. In our example, 140.179.0.0 specifies the network address for 140.179.220.200. When the node section is set to all "1"s, it specifies a broadcast that is sent to all hosts on the network. 140.179.255.255 specifies the example broadcast address. Note that this is true regardless of the length of the node section.

Private Subnets:

There are three IP network addresses reserved for private networks. The addresses are 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16. They can be used by anyone setting up internal IP networks, such as a lab or home LAN behind a NAT or proxy server or a router. It is always safe to use these because routers on the Internet will never forward packets coming from these addresses

Subnetting an IP Network can be done for a variety of reasons, including organization, use of different physical media (such as Ethernet, FDDI, WAN, etc.), preservation of address space, and security. The most common reason is to control network traffic. In an Ethernet network, all nodes on a segment see all the packets transmitted by all the other nodes on that segment. Performance can be adversely affected under heavy traffic loads, due to collisions and the resulting retransmissions. A router is used to connect IP networks to minimize the amount of traffic each segment must receive.

Subnet Masking

Applying a subnet mask to an IP address allows you to identify the network and node parts of the address. The network bits are represented by the 1s in the mask, and the node bits are represented by the 0s. Performing a bitwise logical AND operation between the IP address and the subnet mask results in the Network Address or Number.

For example, using our test IP address and the default Class B subnet mask, we get:

10001100.10110011.11110000.11001000 140.179.240.200 Class B IP Address

11111111.11111111.00000000.00000000 255.255.000.000 Default Class B Subnet Mask

10001100.10110011.00000000.00000000 140.179.000.000 Network Address

Default subnet masks:

Class A - 255.0.0.0 - 11111111.00000000.00000000.00000000

Class B - 255.255.0.0 - 11111111.11111111.00000000.00000000

Class C - 255.255.255.0 - 11111111.11111111.11111111.00000000

CIDR -- Classless InterDomain Routing.

CIDR was invented several years ago to keep the internet from running out of IP addresses. The "classful" system of allocating IP addresses can be very wasteful; anyone who could reasonably show a need for more that 254 host addresses was given a Class B address block of 65533 host addresses. Even more wasteful were companies and organizations that were allocated Class A address blocks, which contain over 16 Million host addresses! Only a tiny percentage of the allocated Class A and Class B address space has ever been actually assigned to a host computer on the Internet.

People realized that addresses could be conserved if the class system was eliminated. By accurately allocating only the amount of address space that was actually needed, the address space crisis could be avoided for many years. This was first proposed in 1992 as a scheme called Supernetting.

The use of a CIDR notated address is the same as for a Classful address. Classful addresses can easily be written in CIDR notation (Class A = /8, Class B = /16, and Class C = /24)

It is currently almost impossible for an individual or company to be allocated their own IP address blocks. You will simply be told to get them from your ISP. The reason for this is the ever-growing size of the internet routing table. Just 5 years ago, there were less than 5000 network routes in the entire Internet. Today, there are over 90,000. Using CIDR, the biggest ISPs are allocated large chunks of address space (usually with a subnet mask of /19 or even smaller); the ISP's customers (often other, smaller ISPs) are then allocated networks from the big ISP's pool. That way, all the big ISP's customers (and their customers, and so on) are accessible via 1 network route on the Internet.

It is expected that CIDR will keep the Internet happily in IP addresses for the next few years at least. After that, IPv6, with 128 bit addresses, will be needed. Under IPv6, even sloppy address allocation would comfortably allow a billion unique IP addresses for every person on earth

Examining your network with commands:

Ping

PING is used to check for a response from another computer on the network. It can tell you a great deal of information about the status of the network and the computers you are communicating with.

Ping returns different responses depending on the computer in question. The responses are similar depending on the options used.

Ping uses IP to request a response from the host. It does not use TCP

.It takes its name from a submarine sonar search - you send a short sound burst and listen for an echo - a ping - coming back.

In an IP network, `ping' sends a short data burst - a single packet - and listens for a single packet in reply. Since this tests the most basic function of an IP network (delivery of single packet), it's easy to see how you can learn a lot from some `pings'.

To stop ping, type control-c. This terminates the program and prints out a nice summary of the number of packets transmitted, the number received, and the percentage of packets lost, plus the minimum, average, and maximum round-trip times of the packets.

Sample ping session

PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=255 time=2 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=255 time=2 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=255 time=2 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=255 time=2 ms
64 bytes from 127.0.0.1: icmp_seq=4 ttl=255 time=2 ms
64 bytes from 127.0.0.1: icmp_seq=5 ttl=255 time=2 ms
64 bytes from 127.0.0.1: icmp_seq=6 ttl=255 time=2 ms
64 bytes from 127.0.0.1: icmp_seq=7 ttl=255 time=2 ms
64 bytes from 127.0.0.1: icmp_seq=8 ttl=255 time=2 ms
64 bytes from 127.0.0.1: icmp_seq=9 ttl=255 time=2 ms

localhost ping statistics

10 packets transmitted, 10 packets received, 0% packet loss
round-trip min/avg/max = 2/2/2 ms
meikro$

The Time To Live (TTL) field can be interesting. The main purpose of this is so that a packet doesn't live forever on the network and will eventually die when it is deemed "lost." But for us, it provides additional information. We can use the TTL to determine approximately how many router hops the packet has gone through. In this case it's 255 minus N hops, where N is the TTL of the returning Echo Replies. If the TTL field varies in successive pings, it could indicate that the successive reply packets are going via different routes, which isn't a great thing.

The time field is an indication of the round-trip time to get a packet to the remote host. The reply is measured in milliseconds. In general, it's best if round-trip times are under 200 milliseconds. The time it takes a packet to reach its destination is called latency. If you see a large variance in the round-trip times (which is called "jitter"), you are going to see poor performance talking to the host

NSLOOKUP

NSLOOKUP is an application that facilitates looking up hostnames on the network. It can reveal the IP address of a host or, using the IP address, return the host name.

It is very important when troubleshooting problems on a network that you can verify the components of the networking process. Nslookup allows this by revealing details within the infrastructure.

NETSTAT

NETSTAT is used to look up the various active connections within a computer. It is helpful to understand what computers or networks you are connected to. This allows you to further investigate problems. One host may be responding well but another may be less responsive.

IPconfig

This is a Microsoft windows NT, 2000 command. It is very useful in determining what could be wrong with a network.

This command when used with the /all switch, reveal enormous amounts of troubleshooting information within the system.

Windows 2000 IP Configuration

Host Name . . . . . . . . . . . . : cowder
Primary DNS Suffix . . . . . . . :
Node Type . . . . . . . . . . . . : Broadcast
IP Routing Enabled. . . . . . . . : No
WINS Proxy Enabled. . . . . . . . : No
WINS Proxy Enabled. . . . . . . . : No
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . :
WAN (PPP/SLIP) Interface
Physical Address. . . . . . . . . : 00-53-45-00-00-00
DHCP Enabled. . . . . . . . . . . : No
IP Address. . . . . . . . . . . . : 12.90.108.123
Subnet Mask . . . . . . . . . . . : 255.255.255.255
Default Gateway . . . . . . . . . : 12.90.108.125
DNS Servers . . . . . . . . . . . : 12.102.244.2
204.127.129.2

WPF tutorials for beginners

WPF tutorials for beginners

What Is WPF?

Birth Of WPF


Microsoft has developed numerous graphical interface toolkits like C++ Win32 API, VB6, MFC, etc. to build desktop applications. These technologies are capable of designing a good GUI interface for the Windows Applications. But these lacks in some additional and advanced features, such as, 2D & 3D Rendering support, Multimedia Support, Animation Support, etc. which are essential now a days. So Microsoft has introduced WPF(Windows Presentation Foundation) API in .NET3.0 framework for the first time. It is released in the year 2007.

.NET 3.0 is officially shipped for the first time with Windows Vista OS. But Windows XP and 2003 versions can also use .NET 3.0. Visual Studio 2005 is the first gateway to program .NET 3.0 applications. So to develop WPF application you need Visual Studio 2005 or later.

What's New?


.NET 2.0 supports 3D and Multimedia features, but the programmer has to use a number of unrelated APIs. For supporting 3D graphics he has to use DirectX APIs, to use multimedia he has to use Windows Media Player API, etc. So the programmer has to know all the different technologies to build a richer GUI. But it is very difficult to master all the different technologies and integrate them.

So WPF merged all the unrelated APIs into a single unified object model. So if you want to use 3D graphics or multimedia for your application you do not use to need use different APIs. WPF provides all the functionality you need to develop richer GUI applications.

Introducing XAML(An Integral Part Of WPF):-


WPF provides us the capability to design windows applications like an ASP.NET application using markup language. Microsoft called this as XAML(Extended Application Markup Language). XAML provides a separation of coding from designing. So you can develop your application using the toolbox and properties window like the general windows application or in a different form like web applications using markup language.

XAML is capable to provide all the simple UI elements (such as labels, textboxes, etc.) to complex functionality (animation, graphics rendering and multimedia support). If you want to animate a button with a picture on it you only need a few line of XAML code. WPF elements can also be customized using styles and templates, minimizing your efforts. There are also a lot of tools to generate XAML code for you. You have to just define the UI in a drag and drop manner. You can also apply rendering effects and animations to these UI using a simple IDE. Then the IDE will give you the XAML code to be used in your application. 

Tools To Develop WPF Application

 To develop an application in WPF you need to know one of the .NET languages(C# or VB.NET). You need to know how the different controls work and how to use them. Because development of WPF application has the same process as that of general Windows application, but with many new features and XAML support. We will discuss later about all the new features and XAML in detail.

To develop an application in WPF first you need .NET framework 3.0 or later. Then you need an IDE to design and develop. You can use the most popular .NET IDE Visual Studio 2005/2008 or the latest VS2010 Beta which has a WYSIWYG environment. Visual Studio has all the necessary tools to develop WPF application. It has a WPF designer and also a XAML editor. You can work in only with the designer or the XAML or work simultaneously with XAML using the split view. You can download the express editions of Visual Studio 2008 or the 90 days trial version of Visual Studio 2008 professional from the below link,
Visual Studio Products

VS 2008 VS 2008 Trial

The direct link to download the 90 days trial version of Visual Studio 2008 professional is here,MS VS2008 Trial

You can download Express Edition of only one language or the complete ISO. Express Editions are free and are meant for learning purpose. So you may not avail some of the advanced features as compared to Visual Studio 2008 Professional. But Express Editions are great for learning purpose.

There are also a lot of tools available to design the GUI for you and generating XAML code. One the popular GUI development tool for WPF is Microsoft Expression Blend. You can download the latest Microsoft Expression products from here, MS Expression Products
Here is the Expression Blend IDE,
ExpressionBlend

Microsoft Expression Blend has an interactive easy to use IDE to design WPF GUI in a fashion similar to that of Adobe Photoshop. You can design your GUI in the Expression Blend IDE and give different animations and effects to it. Then the IDE will generate the XAML file for your GUI which can be then imported to Visual Studio 2005/2008. Microsoft Expression Blend has a number of samples, templates and tutorials to help you in designing your GUI.

We will discuss later about a useful tool of .NET framework 3.0 SDK, i.e.” XamlPad.exe”. This is shipped with .NET framework 3.0 SDK. XamlPad give you a real time demonstration of how XAML tags actually generating the GUI elements. Once you get familiar with XAML, we will explore the features of this tool as it requires knowledge of XAML tags.

Checkouts For Your Needs


So at last you need the following tools to develop a WPF application,

1.The .NET Framework 3.0 or later.

2.Windows XP, Windows Server 2003, Windows Vista or Windows 7 as OS.

3.Visual Studio 2005/2008 Professional or Express Edition (or VS 2010 Beta).

4.Microsoft Expression Blend 3(Optional).

5.Last but not the least knowledge of any one of the .NET languages, i.e. C# or VB.NET.

 

Installation and Configuration of Visual Studio

 

Installing Microsoft Visual Studio


Visual Studio Express:-



1>> First download the Visual Studio Express edition.
If you have downloaded the ISO image, then first burn it to a blank DVD. You will get Visual C# Express 2008, Visual VC++ Express 2008, Visual Basic Express 2008 and Visual Web Developer Express in the complete ISO image file.

If you choose to download only one language then it will start the installation automatically after installation complete. It will be a web-install then. It is better to download the ISO file and make a DVD of it. It will be useful in future.

2>> Then insert the DVD into your DVD Drive. It will start the setup program automatically. If you are using Windows Vista or later then allow the setup program to run.

3>> You will get the following screen. Choose your language to install and click on it. After copying the files the installation will run automatically. Read the license agreement and accept it. Then click Next to start the installation.

VS Express SetUp

Visual Studio 2008 Professional:-



1>> First download the ISO file and burn it to a blank DVD. Then insert that DVD into your DVD drive. It will start the setup program automatically. Allow the Setup.exe file to run if you are using Windows Vista or later.

VS2008 Setup
2>> The Setup window will provide you three options,

Install Visual Studio 2008:- It will install the features of Visual Studio 2008.

Install Product Documentation:- It will install the MSDN library which includes the help files.

Check For Service Releases:- It will check for the new service releases for your product on the web.

As you can see in the picture the Product Documentation and the Service Releases options are not active. Once you install the Visual Studio 2008, then you can install the documentation and check for new releases.


3>> Click on Install Visual Studio 2008. The setup screen will appear after copying files.

VS2008 Setup1 VS2008 Setup2

As you can see in the pictures the Next button will be active after setup initializes the components. Then click Next to continue.

4>> Then in the next screen accept the license agreement and give your user name and click Next.

VS2008 Setup3

5>> In the next screen it will ask you to choose the type of install. It has three options,

VS2008 Setup4

Default Install:- It will install the minimal required features.

Full Install:- It will install all the features of the product.

Custom Install:- You can specify what to install in custom installation.

Select your desired choice. If you don’t have much disk space, it will be better to go for custom installation.

The custom installation screen will look like the below image.

Custom

Choose your desired options and set the installation path. You can see the disk cost also. Then click on install.
You can go to the previous steps at any point of time. But once installation starts you can’t modify in the middle.

6>> After clicking install the installation will start. Your computer may restart several times depending on the installed components.

Setup6 Setup7

You can abort the installation by clicking on cancel button. You will get the confirmation screen after the installation will finish.

Finish Setup

7>> Click on the finish button to finish the installation. It may ask you to restart your system.
After installation will finish, the setup program will return to the fist screen. Now you can install the product documentation.

8>> Now you can start Visual Studio 2008 by going to "Start-->All Programs-->Microsoft Visual Studio 2008-->Microsoft Visual Studio 2008". It will ask you to choose your environment settings.

Env Settings

9>> Choose your desired setting according to your choice and click on Start Visual Studio. You can change the environment settings at any time from the Tools menu. Environment settings will set the IDE to best suite your needs for a specific type of development. It does not mean that by choosing Visual C# setting you can’t develop VB applications. You can work in any language in any environment.

The Visual Studio IDE will start after a few seconds. Below is the Visual Studio IDE.

VS2008 IDE

The WPF Designer

The IDE for WPF development is similar to that of Windows Development with some extra elements. To start WPD design window create a new WPF project in C# or VB.NET. It will show you the WPF designer. We will learn how to develop an WPF application in the next chapter.

WPF Designer

Different Elements of IDE:-


1.The Menu Bar:-


WPF ToolBox
The menu bar is situated under the title bar of the window. The menu bar has menus like File, Edit, View, Properties, Build, Debug, Tools etc. You can work with the different menu items as in case of Windows application development

2.The Tool Bar:-



The tool bar is situated below menu bar. The tool bar has options to save project, copy and paste, build, run,etc.

3.The Toolbox:-



By default the tool box will appear in the left pane. You can make it auto hide, floating or docking as per your choice. It has all the controls to work with. It contains the common controls like Button, Label, TextBox, etc. These controls work in a similar manner as that of Window Application.
WPF Solution

4.The Solution Explorer:-



The solution Explorer is situated at the upper right corner of the IDE. It displays the classes, forms, modules, properties and preferences used by our application in a tree view. It makes the application development easy by displaying all the related items at one place. You can also make it floating, docking, or auto hide as per you choice.

WPF Property

5.The Property Window:-



The property window is situated below the Solution Explorer. The property window shows what properties the selected object has. You can set the different properties of the objects selected. You can also set these properties by coding manually. But it is easier to set the property by using the Property Window.
The property window plays a vital role while developing WPF application. We can set the different 3D effects and other properties of control using this property window without knowing the XAML. The Property Window in WPF has some extra properties for each control than that of Windows application. You can make it floating, docking, or auto hide as per you choice.

6.The WPF Form Designer:-



The WPF form designer has the same setting as that of Window Form Designer, but with some differences. The WPF designer contains a Zoom Tool to zoom the whole window so that you can develop your application more easily. You can place controls on the form by drag and drop method and resize it. It will display the distances from the window wall while resizing a control. It also provides to define grids in the window.

7.The XAML Editor:-


By default the XAML editor is displayed in split view below the WPD designer. You can choose your view to only Design or XAML according to your choice. In XAML editor you can define the XAML code to generate controls or set their properties.
In split view it is easy to work as you can see how the different XAML tags affect the design. You can also take your XAML editor above the designer by clicking on the double arrow button present in the middle of designer and XAML editor headings below the designer.

XAML Editor

Your First WPF Application

Welcome To WPF Application Development


--> First in the Visual Studio IDE choose to create a new application. It will give you the following window.

New Project

--> In this window in the Project Type pane choose your desired language and in the Template pane choose "WPF Application". Then give your application a name and click n the OK button. It will take you to the WPF Designer window.

--> First add a button from the toolbox to your window. Set its name property to "btnClick" and caption property to "Click Me". I have set its background color property and boarder properties. You can also set other properties.

--> Then change the form’s title property to "Welcome To WPF". You can set the form’s boarder, background, opacity and other properties.

--> To get your work quicker copy and paste the following XAML file to your XAML editor. Only copy the code inside the Grid element. The Window element will be generated by default. You can refer to the XAML document.
<Window x:Class="Welcome.Window1"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Welcome To WPF" Height="300" Width="300">
  <Grid>
       <Grid.ColumnDefinitions>
           <ColumnDefinition Width="2*" />
            <ColumnDefinition Width="0*" />
            <ColumnDefinition Width="274*" />
            <ColumnDefinition Width="2*" />
        </Grid.ColumnDefinitions>
        <Button Margin="72,103,64,118" Name="btnClick" Grid.Column="2" Click="btnClick_Click" ForceCursor="True" 
RenderTransformOrigin="23,34" Background="LimeGreen" BorderBrush="Chartreuse" OpacityMask="CadetBlue">
            <Button.BitmapEffectInput>
                <BitmapEffectInput />
           </Button.BitmapEffectInput>
            <Button.BitmapEffect>
               <DropShadowBitmapEffect Color="Chartreuse" />
            </Button.BitmapEffect> Click Me</Button>
    </Grid>
</Window>

--> Now your design is ready and you can now code it. This application will just show a message on the message box when the "Click Me" button is pressed. So now double click on the button to show up the code editor. In the click event handler of the button add the following code.
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Welcome
{
    /// 
    /// Interaction logic for Window1.xaml
    /// 
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void btnClick_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Welcome To World Of WPF");
        }
   }
}

--> Now your first application is ready. Save it and click on the select "build" from the build menu. Then run your application by selecting "Start Debugging" from the debug menu. You can also press F5 key to run your application or click on the play button in the tool bar.

The window you just created will appear with a button. You can see that the button starts glowing when you put the mouse on it. Now click on the button. It will give you a message box showing a message as in the below figure.

Welcome

To close the application first click on the OK button of the message box and then press the close button of the window. It is just a simple application to show you how WPF differ from Window Applications.  

 

Some Important Classes and Namespaces

Some Important WPF Classes and Namespaces:-


In the previous chapters you got a clear understanding of WPF, XAML and WPF Designer. You have also developed a simple application. You may notice that the application development in WPF has the same process as that of Window Application development. But behind the sense it has a lot of differences. Here we are actually designing the interface by writing XAL like code known as XAML. We will learn about XAML and how to work with detail in the next chapters onwards.

Before working with WPF you need to know some common classes and interfaces and their uses. So in this chapter you will get a clear understanding of different classes and interfaces and there uses.

Before knowing the classes and namespaces you need to know, what are the base assemblies that provide different classes ad interfaces for a WPF application. WPF has three base assemblies. These are as below,

1.WindowsBase.dll:- This assembly defines the core types that constitute the infrastructure WPF API.

2.PresentationCore.dll:- As the name specifies this assembly specifies different types for WPF GUI layer.

3.PresentationFoundation.dll:- It defines the WPF control types, animation, multimedia and data binding support. It also specifies some other functionality.

The above three namespaces are managed namespaces. Besides these three namespaces WPF also uses an unmanaged library, i.e. milcore.dll. This library is responsible to work with DirectX layer. It acts as a bridge between the managed WPF assemblies and the DirectX layer.

Some WPF Classes:-


All these three assemblies provides a number of new namespaces and hundreds of new .NET types(classes, interfaces, structures, enumerations and delegates) to work with WPF. For detailed list you can refer .NET 3.5 SDK documentation. Now have a look at the following class diagram and the class’s functionality.

WPF Class Diagram

DispatcherObject:- It is an abstract base class for classes that are bound to one thread. Classes that are derived from DispatcherObject have an associated Dispatcher object that can be used to switch the threads.

Application:- In every WPF application, one instance of Application class is created. This class implements a singleton pattern for access to the window of application, resources and properties. See the below image.
Application Class

DependencyObject: - It is the base class for all the classes that supports Dependency property.

Visual: - It is the base class for all the visual elements of WPF. This class includes features for transformation.

UIElement: - It is the abstract base class for all WPF elements that need basic presentation feature. This class provides evens such as mouse move, drag and drop, click, etc.

FrameworkElement: - It is derived from base class UIElements and implements the default behaviour of the methods defined by the base class.

Shape: - Shape is the base class for all the shape elements such as, line, rectangle, ellipse, polygon.

Control: - It is derived from FrameworkElement and is the base class for all the user-interactive elements.

Panel: - As the name suggest it is the abstract base class for all the panels and is derived from FrameworkElement. Panel class has a Children property for all the UI-Element that is inside a panel and defines methods for arranging the child controls. Panel defines different classes to define the behaviour of child controls such as, WrapPanel, StackPanel, Grid and Canvas.

ContentControl: - It is the base class for all the controls that have a single content such as, Buttons, Labels, CheckBox, RadioButton, etc.

You can also find the class hierarchy of your application using Object Browser in VS 2008. To view Object Browser go to view menu and select Object Browser. Object Browser also contains all the namespaces and its classes. See the below image for WPF class hierarchy. It is the class hierarchy of a simple WPF application that we have created earlier. Using Object Browser you can find all the methods, properties and events of a particular class by selecting that class.

WPF Class Heirarchy

Some WPF Namespaces:-


Now have a look at some important namespaces of the WPF.

System. Windows:- It is the core namespace of WPF. You will find all the base classes such as, Application, DependencyObject , DependencyProperty and FrameworkElement here.

System. Windows. Controls:- This namespaces contains all the controls of WPF. You will also find classes to work with complex controls such as PopUp, ScrollBar, StatusBar, TabPanel, etc. as well as all the basic controls.

System. Windows. Data:- This namespace is used by WPF for Data Binding.

System. Windows. Input:- This namespace provides several classes for command handling, keyboard input, etc.

System. Windows. Markup:- This namespace helper classes for XAML markup code.

System. Windows. Media:- This namespace is responsible to work with images, audio, and multimedia.

System. Windows. Shapes:- This namespace provides core classes for UI such as Line, Rectangle, Ellipse, etc.

System. Windows. Threading:- This namespace provides classes to work with multiple threads.

System. Windows. Navigation:- This namespace provides classes for navigation between WPF pages particularly when working with Web Applications.

Introduction to XAML

Introduction to XAML:-


Extensible Application Markup Language(XAML) is a new XML based code that allows you to define the different functionality of a .NET type through markup mainly in WPF. As XAML is a XML based technique we have all the advantages and disadvantages of XML. Some of the advantage and drawbacks of XAML are,

--> XAML is self describing.
--> XAML files represent each element as a type name such as button, window, etc.
--> XAML is case sensitive like XML.

One of the major advantages of XAML is that it improves the collaboration between designers and developers. Microsoft describes XAML as “toolable” that means XAML can be manipulated using software tools.
This helps the separation of the GUI design from implementation. Products like Microsoft’s Expression can be used to design the GUI and generate the XAML code. Then this code can be imported to a development environment like Visual Studio by the developers.

How it works:-


In XAML most of the interfaces have representations and each property is represented by an XML element and/or attribute.

XAML file contains all the information about the window and its components itself.

Each element in XAML is organised in a hierarchical manner making it easy for the programmer to add or delete codes easily at any time.

XAML in terms of its relationship to CLR objects and types, WPF defines types that represent controls and other UI elements and the XAML simply maps to that types.
Below is a simple code to create a button in XAML.
<!- -Define Button in XAML- - >
<Button Name="btnClick" 
Height="40" 
Width="100" 
Content="Click Me"/> 


It can be programmatically done like,
Button btnClick=new Button();
btnClick.Height=40;
btnClick.Width=100;
btnClick.Content="Click Me";
 
 


 

 

 

.NET tutorials for beginners

What Is .NET ? 

.NET is a major technology change for Microsoft and the software world. Just like the computer world moved from DOS to Windows, now they are moving to .NET. But don't be surprised if you find anyone saying that "I do not like .NET and I would stick with the good old COM and C++". There are still lot of people who like to use the bullock-cart instead of the latest Honda car.  

What is Visual Studio.NET ? 

 Many people always get confused with Visual Studio .NET (VS.NET) and .NET technology. VS.NET is just an editor, provided by Microsoft to help developers write .NET programs easily . VS.NET editor automatically generates lot of code, allows developers to drag and drop controls to a form, provide short cuts to compile and build the application etc.Understand Visual Studio .NET

VisualStudio is a very user friendly tool. But there are enough stuff to confuse any one new to Visual Studio family. The purpose of this chapter is to make you familiar with different options in Visual Studio.NET (VS.NET) We will not cover the entire visual studio guide. We are just explaining the most commonly used features of VS.NET.

When you work on any project, VS.NET has several child windows to assist you in the application development. These windows are attached on the left, bottom and right sides of the main window. You can click on these small windows to expand it and see the content of them. Some of the most commonly used child windows are explained below. Most of these windows will be enabled only when you have created a project and working on a WebForm/WinForm.

Toolbox
Toolbox provides all the drag and drop controls for your application. Depending on the kind of application you are working on, the toolbox will show appropriate controls and you can drag and drop them to your form. If you are developing a web application, toolbox will show ASP.NET controls and if you are developing a Windows application, it will show Windows controls (like Radio button, text box, buttons etc).


You can simply drag and drop any controls from the toolbox to your form. After you drag and drop any control, double click on the control to go the default event associated with the control.


The Toolbox will be enabled only when you have a WebForm or WinForm opened in Design mode and is usually located on TOP LEFT corner of the VS.NET.


By default, all windows including Toolbox will be displayed as Minimized (Marked as A in picture). You will see only the small icon and the text 'Toolbox' written vertically on the left bar of VS.NET. You can click on this minimized window to expand it (Expanded window is marked as C.). When you move the mouse away from the window, it will again automatically minimize. You can keep the toolbox always expanded by pressing the pushpin (Marked with B.)


The above behaviour is common for all the windows explained below. They will be minimized by default and you can point the mouse over it to expand it. Use the pushbutton to keep it expanded.

Picture 1 : Toolbox

Picture 2 : Design/HTML mode
Design mode & HTML mode


If you are developing a web application, you can switch between design mode and HTML mode for any web form. When you are in HTML mode, it will show you the HTML tags and ASP.NET code and you can manually edit it. YOu can switch to the Design mode by clicking the Design button on BOTTOM LEFT corner of VS.NET. In design mode, you can see how your ASP.NET page is going to look like when some one view your web page. Also, you can drag and drop controls from the toolbox, which will automatically generate the HTML for it.


Typically, developers switch between these two modes very frequently. You can go to design mode to drag/drop controls, right click on the controls to set correct properties etc. Then, click on the HTML mode to view the generated HTML. You can manually cmake changes to the automatically generated HTML. If you change any properties in HTML mode, the changes will be reflected when you switch to Design Mode
Solution Explorer


Solution Explorer, located on TOP RIGHT corner of VS.NET, displays your solution, all projects included in each solution and the list of files in each project. They are listed in the form of a tree control.


Typically, for a single application, you will have 1 solution and one or more projects. When you create a new application, you are have to create single Visual Studio project. In more complex applications, there may be more than one projects. All these projects are grouped into a single solution. Even if you do not create a solution separately, a solution will be automatically created for you.


To add a new file to your project, you can right click on the project name (JustTestis the project name in the picture) and choose the menu option Add. It will give you the option to choose a file type. You can choose an appropriate type.


For WinForms and WebForms, you can see the file in design mode and the code associated with it. Double click on any form and it will be opened in design mode. Right click on any form and select the menu option 'View Code' to view the code associate with the form.

Picture 3 : Solution Explorer

Picture 4 : Output
Output


Output window, located on BOTTOM LEFT corner of VS.NET, displays the result of your project compilation. When you compile your project, all errors, warnings and compilation results will be displayed in this window.


In addition to the Output window, they are few other windows located in the BOTTOM LEFT corner of VS.NET.


Task List - shows individual tasks. Typically, when you compile your project, all errors and warnings will be added to your task list. You can double click on any item in the task list to go directly to the code associated with the task


.Command Window - you can execute code statements here. When you are debugging, you can evaluate the value of any variables by typing ? followed by the variable name.


Find Results - when you search for any text in file(s) using VS.NET, the results will be displayed in this window.
Projects


VS.NET allows you to create several types of projects. Most of the time you will be using one of two categories:
  • Windows Application - to create any standard windows application.
  • ASP.NET Web Application - to create a web site.
    Creating a Project


    To create a new project, choose the main menu : File > New > Project.


    It will give you several options. First you must select a type from the left side of the popup - you may choose Visual Basic Projects or Visual C# projects based on the language you plan to use for development.


    After selecting a type, you choose a template from the right side. You may choose Windows Application, ASP.NET Web Application or any other templatebased on the nature of the application you want.

    Picture 4 : Create new project
    When you create a Windows Project or ASP.NET Web Project, VS.NET will add a sample file by default. You can simply Build your new project and see how it works.

    Building a project

    To try this, create a new Windows Project as explained above. It will create a sample form. Go to the main menu and select the menu item Build > Build Solution.

    This process will compile all the files included in your project and show you the result in the Output window. If the result shows '0 failed', your build is success and your application is ready to deliver!!

    To Run the application you just Built, go to the main menu and select Debug > Start Without Debugging. This will launch the application you just developed.

    You can drag and drop several controls to the form and try running it.

    When you compile (build) the code, if there is any errors or warnings, the details will be shown in the 'Task List' window. You can click on the specific item in this window to go directly to the line of code associated with the error.
  •  

    What is XML?

    First what you are thinking is it a programming language like our c,c++ or it’s presentation language like HTML .YES it’s a presentation language not a programming language . Before going into deep about XML we should remember one think ie it’s a case sensitive language where as HTML is not a case sensitive .As i said before that it’s mainly used for structured documents.You don'y have any pre defined tags here .  

    Download VS.NET

    Unfortunately, VS.NET is not a free download !

    If you want to have Visual Studio 2002 or Visual Studio 2003, you need to purchase it. It is going to cost you around US$ 750 or more...

    However, here is a good news. You can download trial versions of Visual Studio 2005 from Microsoft. Note that, this free download is a limited version. You have to download separate versiosn of C#, VB.NET etc.
     

    "Hello World" Application 

    Here we will guide you through step by step process to create your first sample .NET application. All our sample code will be using C# syntax. Readers are suggested to stick to this new elegant language, than going back to your favorite VB style.

    Hello World Application using C#

    Let us get started the traditional way, with a 'Hello World' application. We hope you all have Visual Studio.NET installed on your computer. If you have VS.NET, goto the menu option File > New > Project. Select 'Visual C# projects' and choose the project template 'Console Application'. This will create a default

    A simple C# program would look like the following.

    
     
     using System;
    
     public class Hello
     {
      public static void Main (string[] args)
      {
       Console.WriteLine("Hello C# World");
      }
     }
     
     

    When you create a new Console Application, it will create a default class and you can just insert one line of code into it:

    Console.WriteLine("Hello C# World");


    Now compile and run your first program by pressing Ctrl + F5. You will see the following result :

    > Hello C# World

    You are done! You got your first C# program successfully running.



    If you do not have VS.NET, you may use any editor (including notepad) to create your first C# program. Create a new file with the name sample.cs and type the C# code shown. Now go to the command prompt and navigate to the folder where you have the .NET framework installed. Compile your csharp file by using the command 'csc':

    csc c:\samples\sample.cs

    csc is the C# compiler. The above command will produce the output file sample.exe. You can run the sample.exe and you will see the output from the program.

    Analyzing your first program

    See the first line of code :
    using System;

    "System" is a namespace and the "using" directive says that all classes in the "System" namespace can beused in this class without using the fully qualified name. In our class, "Console" is a class in the namespace "System". To use this class you have to actually write :
    System.Console.WriteLine ("...");

    But the
    using System; directive on top of the classallows us to use the class without including the namespace. So, you can now simply write :
    Console.WriteLine("...");

    If you are familiar with Object Oriented Programming, you might not need more explanation for the next line - declaring a class.
    public static void Main (string[] args) - is the Main method, which is thestarting point of the application.
    string[] args is the list of arguments that are passed to this application. (In our case, we are not passing any command line parameters).
    Console.WriteLine("...") is another line of important code. Console is a class, part of .NET class library included in System namespace. WriteLine is a method part if this class and used to printoutput to the default Console.

     

    C# Language Syntax 

    Declaring Variables



    The following sample shows different ways you can declare a variable:
    int a;
    int salary, incomeTax, sum;
    int count = 10;
    
    string name;
    string fullName= "Little John";
    

    Loop Statements


    while
    int i = 0;
    while ( i < 5 )
    {
    Console.WriteLine ( i );
    ++i;
    }
    

    The above loop repeates 5 times and prints the value of i.
    The output of above code would be like this :
    0
    1
    2
    3
    4
    


    for
    
    for ( int i = 0; i < 5; i++ )
    {
    Console.WriteLine ( i );
    }
    

    The above loop repeates 5 times just like the while loop and prints the value of i.
    The output of above code would be like this :
    
    0
    1
    2
    3
    4
    


    do ... while
    
    int i = 0;
    do
    {
         Console.WriteLine ( i );
         i++;
    }
    while ( i < 5 );
    

    The above loop is pretty much same as the while loop. The only difference is, the condition is checked only after executing the code inside the loop.

    foreach
    
    string []  names = new string[]{ "Little John", "Pete", "Jim", "Bill" };
    foreach ( string name in names )
    {
             Console.WriteLine ( name );
    }
    


    foreach loop can be used to iterate through a collection like array, ArrayList etc.
    The above code displays the following output:
    
    Little john
    Pete
    Jim
    Bill
    


    Conditional Operators



    if ... else

    This is the conditional operator, used to selectively execute portions of code, based on some conditions.
    
    string name = "Little John";
    if ( name == "Jim" )
    {
         Console.WriteLine( "you are in 'if' block" );
    }
    else
    {
         Console.WriteLine( "you are in 'else' block" );
    }
    

    in the above case, it prints :
    
    you are in 'else' block
    

    Flow Control Statements



    break

    'break' statement is used to break out of loops ('while', 'for', switch' etc).
    
    string []  names = new string[] { "Little John", "Pete", "Jim", "Bill" };
    foreach ( string name in names )
    {
         Console.WriteLine ( name );
         if ( name == "Pete" )
          break;
    }
    

    In the above sample, it iterates through the array of 4 items, but when it encounters the name "Pete", it exits the loop and will not continue in the loop anymore.
    The output of above sample would be :
    
    Little John
    Pete
    


    continue

    'continue' statement is also used to in the loops ('while', 'for' etc). When executed, 'continue' statement will move the exection to the next iteration in the loop, without continuing the lines of code after the 'continue' inside the loop.
    
    string []  names = new string[]{ "Little John", "Pete", "Jim", "Bill" };
    
    foreach ( string name in names )
    {
            if ( name == "Pete" )
                 continue;
    
             Console.WriteLine ( name );
    }
    

    In the above sample, when the value of name is "Pete", it executes the 'continue' which will change the execution to the next iteration, without executing the lines below it. So, it will not print the name, if the name is "Pete".
    The output of above sample would be :
    
    Little John
    Jim
    Bill
    


    switch

    if you have to writeseveral if...else conditions in your code, switch statement is a better way of doing it. The following sample is self explanatory:
    
    int i = 3;
    switch ( i )
    {
        case 5:
                     Console.WriteLine( "Value of i is : " + 5 );
                      break;
         case 6:
                      Console.WriteLine( "Value of i is : " + 6 );
                       break;
          case 3:
                       Console.WriteLine( "Value of i is : " + 3 );
                       break;
          case 4:
                        Console.WriteLine( "Value of i is : " + 4 );
                        break;
           default:
                        Console.WriteLine( "Value of i is : " + i );
                        break;
    }
    

    In the above sample, depending on the value of the conditional item, it executes appripriate case. In our code, since the value of i is 3, it executes the third case. The output will be as shown below:
    Value of i is : 3


    DataTypes in C# 

    DataTypes are the basic building block of any language. Microsoft has tried to standardise the datatypes in .NET framework by introducing a limited, fixed set of types that can be used to represent almost anything in programming world.

    C++ was very rich in datatypes, but that leads to confusion too. Especially, when you write components that may be consumed by applications written in other platforms, you have to make sure the types used are compatible with other platforms too!

    .NET types start from a clean slate. All .NET languages share the same types. So, they are all compatible and no worries.This means, you can call C# code from VB.NET and vice versa, without worrying about type conversions.

    .NET data types are either
    structures or classes, part of the System namespace. For example, the following data types are implemented as struct in .NET:
  • Int16
  • Int32
  • Double


    (String is implemented as a class in .NET, for various reasons.)

    If you are not very familiar with struct and class, don't worry about it. You can just use them as if they are simple data types.

    Here is how you can declare variables of type Int, Double and String:
  • Int16 age, employeeNumber;
  • Double salary;
  • String name, address;

    You can use any of the .NET data types directly in any .NET language - in C#, VB.NET or xyz.NET.But in addition to the .NET types, each language provides a set of primitive types, which map to the corresponding types in .NET class library. This is why you may see some people use string and some others use String. There is no big difference. string is a primitive data type in C# and String is the corresponding class in .NET class library. The string in C# is mapped to the class in .NET class library. So, whether you use string or String,there is no real difference.

    DataTypes in C# and the corresponding class/struct in .NET class library

    The following list shows the list of data types available in C# and their corresponding class/struct in .NET class library.
    C# Data type Mapped to .NET class/struct
    sbyte System.SByte
    byte System.Byte
    char System.Char
    float System.Single
    decimal System.Decimal
    double System.Double
    ushort System.UInt16
    short System.Int16
    uint System.UInt32
    int System.Int32
    ulong System.UInt64
    long System.Int64
    bool System.Boolean
    string System.String
    object System.Object

    Value Types & Reference Types

    In C# data types are classified into two :
  • value types
  • reference types

    The following tables shows some of the differences between values types and reference types.
     
    value types reference types
    allocated on stack allocated on heap
    a value type variable contains the data itself reference type variable contains the address of memory location where data is actually stored.
    when you copy a value type variable to another one, the actual data is copied and each variable can be independently manipulated. when copying a reference type variable to another variable, only the memory address is copied. Both variables will still point to thesame memory location, which means, if you change one variable, the value will be changed for the other variable too.
    integer, float, boolean, double etc are value types. string and object are reference types.
    struct is value type. classes and interfaces are reference types.

  •  

     

    Classes and Object model in .NET 

    What is a 'class' ?

    In modern object oriented programming, large computer programs are divided into several 'classes'. Typically, a large project will have several hundred classes. A class represents an entity in a program. For example, if you are doing a small program called calculator, you will typically have a single (or more) class called 'Calculator' (you can give any name for your class). The class will have several 'methods', that will do the functionality of the class.

    So, your calculator may have methods like the following:
    Add()
    Subtract()
    Multiply()
    Divide()

    Here is a sample calculator class, written in C# :
    
    using System;
    
    public class Calculator
    {
                 public int Add(int value1, int value2)
                 {
                            return value1 + value2;
                  }
    
                 public int Subtract(int value1, int value2)
                 {
                           return value1 - value2;
                 }
    
                 public int Multiply(int value1, int value2)
                 {
                          return value1 * value2;
                 }
    
                public int Divide(int value1, int value2)
                {
                         return value1 / value2;
                }
    }
    
    
    
    

    Property in C# class 


    How do you access member variables of any class from outside the class ? In most of the languages including C++ , you will make the member variables public so that you can create an instance of the class and directly access the public fields, as shown below:
    
    public class Car
    {
     // private fields.
     public string color;
    
     // constructor
     public Car()
     {
     }
    }
    

    The above class has one public field : color. You may access this field from outside the class as shown below:
    
    Car car = new Car();
    
    car.color = "red";
    
    string color = car.color;

    But this is the old way ! This would still work with C#, but the suggested approach is to use "Property" instead of directly accessing member variables.

    The following code snippet shows how to create "Property" in a class.
    
    public class Car
    {
     // private fields.
     private string color;
    
     // constructor
     public Car()
     {
     }
    
     public string Color
     {
      get
      {
       return color; // return the value from privte field.
      }
      set
      {
       color = value; // save value into private field.
      }
     }
    }
    

    The above class has one private field - color. Then we have one "Property" called 'Color', which is used to represent the private field. Note that the field is private and the Property is public. (We have used the same name with upper/lower case to represent the 'Property' and 'field', but you may give any name you want.)

    Each property has two parts :
  • get

  • set


  • The get part is executed when you access the value of the Property as shown below:
    
    Car car = new Car();
    
    string color = car.Color;
    

    When executed, the above get accessor will return the value stored in the field 'color'.
    The set part is executed when you assign a value to the Property as shown below:
    
    Car car = new Car();
    
    car.Color = "RED";
    


    When executed, the above set accessor will assign the value "RED" to the private field 'color'. (Note that'value' is a keyword, which will have the value assigned to it.)
    So, what is the difference ?

    On the first look, there is no difference! You can achieve the same behaviour by writing 2 different methods ( like SetColor(...), GetColor() ).
    First advantage of using property is, code looks cleaner than having 2 separate methods. You can simply call a property as if it was a field in the class Well, then you may ask why make it 2 methods, we can make it a public field, so that we can access it by creating an instance of the class.
    The main advantage over using a Property instead of a public field is, with the property, you will get a chance to write few lines of code (if you want) in the get and set accessors. So, you can perform some validation or any other logic before returning any values or assigning to the private field.

    See the modifed class below:
    
    public class Car
    {
     // private fields.
      private string color;
    
     // constructor
     public Car()
     {
     }
    
     public string Color
     {
      get
      {
       if ( color == "" ) 
        return "GREEN";
       else
        return color;
      }
      set
      {
       if ( value == "" )
        thrown new Exception ("Wrong value.");
       else
        color = value;
      }
     }
    }

    Let us analyze the get part first. Here we are checking whether there is a valid value in the field 'color' before we return the value. If it is empty, we are getting a chance to return a default value 'Green'. This way, we can make sure that whoever calls the property 'Color' will always get a valid color, never an empty string.

    In the set part, we are doing a validation to make sure we always assign a a valid value to our field. If someone assign an empty string to the 'Color' property, he will get an exception (error).
    Car car = new Car();
    
    car.Color = "";


    The above code will throw an error because we are trying to assign an empty string and the set accessor will throw an error if it an empty string. This way, we can make sure that we allow only valid values to be assigned.
    So, i guess now you would appreciate the purpose of "Property". So, no more public fields! Always have private fields and write public properties as wrapper for them if required to expose them to outside the class.
      

    Namespaces 

    A Namespace is a group of related classes. It is a good practice to group related classes into a namespace when you create a class library.

    The main advantage of using namespaces is, to avoid conflicts when you have multiple classes with the same name. For example, .NET comes with a class called 'Form'. Suppose you also write another class called 'Form' in your application and if you refer to the class 'Form', how does the compiler know which Form you are refering to ?

    Here is the importance of 'namespace'. You can refer to the .NET Form using the fully qualified name, including the namespace like this :

    System.Windows.Forms.Form

    And you can refer to your own Form like this :

    MyApplication.Form, where MyApplication is your namespace.

    So, namespaces allow you to avoid name conflicts!

    All classes in .NET class library are grouped into namespaces. You can use all the classes using the fully qualified name, including the namespace also along with the class name.


  • System.Windows.Forms.Form
  • System.String
  • System.Double

    If you want to declare a Button object, you must do the following :

    System.Windows.Forms.Button myButton;

    It is not mandatory to use the namespace also along with the name. You may use the using directive on top of the class and safely avoid the need to write the fully qualified name everytime when you refer to a class.

    using System.Windows.Forms.Button;

    If you have the above line of code on top of the class file, you don't need to type the namespace name System.Windows.Forms with all the classes in this namespace. You can simply use class name directly as shown below:

    Button myButton;

    .NET Namespaces

    Here is a list of some of the namespaces in .NET class library.


  • System
  • System.Xml
  • System.Data
  • System.Data.OleDb
  • System.Data.SqlClient
  •  

    WinForms 

    WinForms is the most commonly used feature of .NET.
    'Windows' based applications in .NET is called 'WinForms'. The .NET framework comes with a good number of classes to support 'Form' based application development.
    A WinForm application will have atleast one 'Form' (window), which would be used for the interaction between the application and user. A Form can contain other controls like TextBox, Label, Button etc. Large WinForms applications will have several 'Forms', some of them used to capture data from user and some of them used to display data to user. By performing certain actions in each form, user can navigate to other 'Forms' in the application.

    Event driven programming

    Event Driven programming model is the most commonly used feature in modern programming. In this model, you will write appropriate code for each event. Examples for events are
  • Button Click
  • Mouse Move
  • Mouse Click
  • Key Press

    In Winforms application, users interact with the application using various actionsin the window (like clicking a button, moving mouse, pressing keys in keyboard etc). These actions will generate various events. When an event is generated, the code written for that event will be executed.

    For example, in a user registration screen, you may have several controls like text boxes where user can enter their name, address, age etc. Once user enter all the information, he may press the 'Submit' button. As a developer, you would have written code in the button click event, to save this user entered data into a database. This is how typically a WinForms based application works in an event driven programming model.

    To create WinForms applications:
  • Open Visual Studio .NET
  • Select the menu : File > New > Project
  • Choose from the project types : Visual C# Projects
  • From the Templates, choose the application type 'Windows Application'
  • Enter the project name in the space for 'Name'.
  • Make sure the 'Location' is pointing to your folder. You may press the Browse button to select your personal folder, so that all your projects will be saved in your folder.
  • Press 'OK' to create the projet. By default the project will be created with a sample form, named 'Form1'. You can drag and drop controls into this form, from the 'Toolbox' on the left hand side of the VS.NET.
  •  

    Displaying Simple MessageBox


  • Reading the text value from a textbox
  • Displaying a message box

    About the sample application This application has 1 textbox and a button. If you type anything in the textbox and press the button, it will display the same text you typed in a MessageBox.

    Download and unzip the sample application from this page. After you unzip, you will get several files. Some of the important files are :

    1. Chapter1.csproj - This is the C# project file. Double click this file to
    open the project.

    2. Form1.cs - This is the file for the Form1 in teh sample application.

    After you open the project, see the 'Solution Explorer' bar on the right side of the Visual Studio. You can click on that to expand it, which will display the list of all files in the project. (Or, you can go to the menu 'View > Solution Explorer' to open the solution explorer.

    Click on 'Form1.cs' in the solution explorer to open the Form. Now you can see the Form in 'design mode'. Right click on the 'Form1.cs' in the solution explorer and choose 'View Code' to see the source code behind this Form (Or, press F7 from the Form to see the code).

    Let us analyze the code:

    The code has lot of Visual Studio generated code. For timebeing ignore all those code and scroll down to the event handler code in the bottom of the file.
    System.Windows.Forms.MessageBox.Show( "You typed : " + txtMessage.Text );
    
    
    DialogResult result = MessageBox.Show( "Did you like this application ?", 
    "Caption", MessageBoxButtons.YesNo, MessageBoxIcon.Question );
    if ( result == DialogResult.Yes ) 
          MessageBox.Show("You selected YES");
    else
          MessageBox.Show("You selected NO");

    The first line will simply display a messagebox and show the text typed by the user. 'MessageBox' is a class inside the namespace 'System.Windows.Forms'. We have a statement 'using System.Windows.Forms' on top of the source code. This is like a source code. This will help us avoid typing 'System.Windows.Forms.' everytime when we want to use a class inside this namespace.

    The next few lines of code do a bit more. Here we are displaying a message box, with some additional attributes.

    The second optional parameter of the 'Show' method is the 'caption' for the messagebox.

    The third parameter tells that the messagebox will have two buttons - YES and NO. You have several other options like MessageBoxButtons.OK, MessageBoxButtons.OKCancel etc.

    And, the last parameter says 'display a question Icon in the messagebox'. There are many other types of icons you can display.

    And another important part is, the MessageBox returns a value when the user press a button to close the messagebox. Our MessageBox asks a question 'Did you like this application ?" and gives two options to the user - YES or NO.

    The return value is of type 'DialogResult' and is assigned to the variable 'result'. We are checking the value of the result and depending on whether user pressed the YES button or NO button, appropriate message will be displayed.
  • C# sample for basic file operations 

     In the attached sample application, you can type some text and save into a text file. Also, you can select a text file and display the content in a textbox.

    In addition to the basic file operations, you can learn some good programming practices and error handling/validation techniques.

    This chapter and the attached sample application demonstrates the usage of following .NET classes and methods:
  • System.IO.Path.GetExtension() - Method to check the extension of a file.
  • System.IO.File.Exists() - Check if a file alread exists.
  • System.Windows.Forms.OpenFileDialog - "File Open Dialog" to choose a file from the disk.
  • DialogResult.OK - Result from a File Open Dialog.
  • MessageBox.Show() - Displaying a message to the user.
  • string.Trim() - Remove white space characters from beginning and end of string.
  • throw new Exception() - Create and throw a new exception.
  • System.IO.StreamWriter - Stream writer to write into files.
  • System.IO.StreamReader - Read from file.
  • Application.Exit() - Closing an application.

  • C# sample for retrieving html content from any websites 

     

    This chapter will teach you how to retrieve content of any website using .NET classes.

    This chapter and the attached sample application demonstrates the usage of following .NET classes and methods:
  • System.Net.WebRequest() - Class to perform the web related operations.
  • System.Net.WebRequest.Create(url) - Create a web request.
  • System.Net.WebRequest.GetResponse() - Get the html content of the URL.
  • System.IO.StreamReader - Read from file.
  • Application Configuration Files 

    .NET gives an easy way to store configuration information in a ApplicationConfiguration File. In the simple implementation, you can store information as Key-Value pairs.

    For example, consider a case where you have to use a DataSource in your application. If you hardcore the DataSource information in your code, you will have a bad time when you have to change this datasource. You have to change your source code and re-compile it. This won't work everytime you give your product to different customers or when you run your application in different machines!

    In earlier days, programmers used to store this information in special files called ".ini" files or in system registry. The application can read the information from the .ini file or registry and no need to re-compile the code when the values are changed in .ini file or registry.

    But this is a pain most of the time. It is not fun opening the registry, locate your entries and make appropriate changes. It is quite possible that you may mess up with some important entries in the registry and make your system not running any more. In fact, in secured systems, administrator may deny access to the registry and users will not have the choice to edit the registry at all.

    .NET gives you a simple and easy solution for this problem - the ApplicationConfiguration File. Each application can have a configuration file, which is actually an XML file. You can use any text editor (including notepad) to open the configuration file and change the values. The application will load the values from this configuration file and you do not have to change your source code everytime you change your DataSource or any other information stored in configuration file.
    app.config for Windows applications

    Windows applications in VS.NET uses the name 'app.config' by default for the configuration file. This will not be automatically created when you create a Windows application. If you need a configuration file for your application, open your project in VS.NET, go to the 'Solution Explorer' and right click on the project name. Choose
    Add > Add new item from the menu and select 'Application Configuration file' from the list of choices. This will create an app.config file for you in the application root.

    By default, the app.config file will have the following content:

    
    <?xml version="1.0" encoding="utf-8" ?> 
    
    <configuration> 
    
    </configuration>


    To store values in configuration file, you can create xml elements in the
    format
    <add key="MyKey" value="MyValue" />


    See the sample config entries below:
    
    <?xml version="1.0" encoding="utf-8" ?>
    
    <configuration>
    
    <appSettings>
    
    <add key="DatabasePath" value="c:\\projects\data\spider.mdb" />
    
    <add key="SupportEmail" value="webmaster-6@dotnetspider.com" />
    
    </appSettings>
    
    </configuration>


    And to read from this config file, just use the following code in your application:
    string dbPath = System.Configuration.ConfigurationSettings.AppSettings["DatabasePath"];
    string email = System.Configuration.ConfigurationSettings.AppSettings["SupportEmail"];

    ConfigurationSettings
    is the class
    used to access the contents of the configuration file. Since this class is part
    of the namespace
    System.Configuration,
    we have to use the fully qualified name
    System.Configuration.ConfigurationSettings.
    As a shortcut, you can use the
    using directive
    on top of the file like below:
    using System.Configuration;

    If you have the above directive on top of the file, then you can directly use
    the class
    ConfigurationSettings.

    string dbPath = ConfigurationSettings.AppSettings["DatabasePath"];
    string email = ConfigurationSettings.AppSettings["SupportEmail"];


    Note:

    When you compile your application, VS.NET will automatically create a file called <your application name>.exe.config in your bin\debug folder. The contents of the app.config will be automatically copied to this new config file when you compile the application. When you deliver the application to the end user, you have to deliver the exe and this new config file called <your application name>.exe.config and NOT the app.config. Users can modify the data in <your application name>.exe.config file and application will read the data from the config file, when restarted.

    web.config for web applications

    The web applications use the same concept, but they use a config file with the name 'web.config'. There are couple of things to note in this case.
  • web.config is created automatically by VS.NET when you create any web project.
  • When you compile the web application, web.config is NOT renamed or copied to the BIN folder.
  • web.config has several default entries in it to support web/IIS configuration & security.
  • You can add the <appSettings> section in the web.config and add your key/value pairs in that section.
  • You can have separate web.config files for each directory in your web application, in addition to the one in the root. For each web page, by default system will look for a web.config in the same folder as the page and if not found, then looks in the parent folder.



  • In VB.NET, you have to use "( ... )" instead of the "[ ... ]", as shown below:
    
    Dim dbPath as String = ConfigurationSettings.AppSettings("DatabasePath")
    Dim email as String = ConfigurationSettings.AppSettings("SupportEmail

    Debugging in VS.NET



    Debugging in VS.NET





    If you make a syntax error, then the compiler will tell you and you can easily solve the issue. But what if there is a logical error? You may never know what went wrong, just by looking into the code. During runtime, the application may give wrong results, which may not be noticed immediately by anyone. When someone report that your "calculator program" gives the result 10 when adding 5 and 4, what will you do? A logical error in a small calculator program may be an easy to fix issue, but what if it is a very complex accounting software?

    The
    Debugger becomes a very handy tool in such situations. A Debugger is a software process that help you monitor the execution of your code. Microsoft gives us a very powerful debugger, integrated with the VS.NET. When you execute your code in debug mode, you can watch how it executes each line of code. You can run (debug) the application step by step, line by line and see the value of each variable at any point of time. You can visually count how many times a whileloop executes and see whether it executes the ifblock or else block.

    So, in short, debugger help you watch how your code is executed. You can see how your calculator program calculates 5 + 4 = 10 and easily figure out the logical error.
    Debugging your project

    Running your project in
    Debug mode doesn't need lot of work. Just choose the menu : Debug > Start or press F5. Now your application will run in debug mode. To run your application in non-debug mode, choose the menu : Debug > Start without Debugging or press Ctrl F5.

    You may not feel any difference whether you run in debug mode or non-debug mode. In both the cases, your application runs as usual! To find the difference, you can use
    breakpoints

    .
    BreakPoints

    BreakPoints are used to stop the execution at certain lines of code in the application and monitor the values of various variables etc at that point of time. To put breakpoints, click on any line of code and press
    F9or click on the leftbar of any line of code. When a breakpoint is enabled, the line will be highlighted with BROWN color and a BROWN circle will appear on the left bar (See image below). To remove a breakpoint, press F9 again.

    Open your project and mark breakpoints in different lines of code. Now start the debugger by pressing F5. Note that every time the execution passes through the lines marked as 'breakpoint', execution stops there. You can press F5 to continue the execution again. Or, press F10 to continue the execution line by line! When the execution stops on a breakpoint, or when you continue execution line by line by pressing F10, you can point your mouse over any variable and it will show you the value of that variable at that point of time. You can see how the values are changed at each line of code and this helps you easily figure out the logical errors. This process is called 'Debugging'. Next time, when you hear someone complaining about his 'debugging nightmares', you know what it is!
    Change path of execution

    When the execution reaches a breakpoint, you can see a little YELLOW Arrow on the leftbar of the current line of code and the line will be highlighted with YELLOW color (See image below). When you press the F10, the execution will proceed to the next line of code.

    You can change this execution path by clicking on the yellow arrow on the leftbar and dragging it into any other line of code. For example, if you are currently inside an
    if block, you can drag the execution to the else block (or, to some other line of code), thus changing the application behaviour the way you want! Don't you agree that the Debugger is a very powerful tool?
    Quick Watch

    While debugging, you can view the value of any variable instantly by pointing the mouse over the variable (See image below. You can see a very small light yellow window showing name = "Little John". This is displayed when the mouse is pointed over the variable name). But this will work only for simple types like int, string etc. In case of types like DataTable, DataSet, ArrayList etc, you can right click on the object name and choose
    Quick Watch. A small window will open and will show you the complete object. You can expand the properties of the object and view the values of each proeprty. In case of a DataSet, you can Quick Watch the dataset and expand each table inside the dataset, each row in each table, each column in each row etc. Thus the Quick Watch will help you view the values of the 'complete object'.
    Watch Window

    When you debug the application and step through each line, it is not really necessary to point the mouse on each variable to view the value. Just add the variable to the 'Watch Window' and the values are always visible in the little 'Watch Window' in the bottom of your VS.NET (see image below. The variable nameis added to the watch window). To add any variable to Watch Window, righ click on the variable and choose 'Add Watch'. You can choose the same option from the 'Quick Watch' window also.

    The 'Watch Window' may be minimized by default. You can point your mouse on the 'Watch' icon in the bottom of the VS.NET to expand this window. Use the 'push button' in the watch window to keep it always expanded.If 'Watch Window' is not visible in the bottom, select the menu option from VS.NET main menu :
    Debug > Windows > Watch > Watch 1
    System.Diagnostics.Debug.WriteLine

    You may use
    System.Diagnostics.Debug.WriteLineto print any values into the output window while debugging.Ex:

    System.Diagnostics.Debug.WriteLine( "*** My name is : " + name );System.Diagnostics.Debug.WriteLine( "+++ See the Output window now." );System.Diagnostics.Debug.WriteLine( "=== End." );


    See the image below to see how it appears in the output window.

    Advanced features

    The debugger comes with several other advanced features like conditional breakpoints, CallStack etc. You may find more information from MSDN or other web sites. To keep it simple and helpful for beginners, we have mentioned only the commonly used features of VS.NET debugger.



    Accessing Database 


    Database Concepts


    Database is the media to store data. If you have an application that has to store and retrieve data, your application must be using a database.

    A File is the simplest form of saving the data in the disk, but is not the most efficient way of managing application data. A database is basically a collection of one or more files, but in a custom format, and data is organized in a specific format such a way that it can be retrieved and stored very efficiently.

    Some examples for databases are :
  • MS Access
  • SQL Server
  • Oracle

    MS Access is a very light weight database provided by Microsoft for applications with less number of users and relatively small quantity of data. MS Access saves data into database files with the extension .mdb. Usually, MS Access comes along with MS Office package. If you already have the .mdb database file, you can freely use it with your application and you do not need MS Access software. The MS Access software is required only if you want to directly open the database and manipulate the data or change the database schema.

    SQL Server (Microsoft product) and Oracle (Oracle Corp.) are more complex, advanced, relational databases and they are much more expensive. It can support large number of users and very high quantity of data. If you are developing a software, which might be accessed simulatenously by 100s of users or if you expect your data may grow 100s of MBs, you might consider one of these. (We are learning Microsoft .NET.. so you might want to consider the SQL Server than Oracle, for which Microsoft provides special data access components!!)

    In this tutorial, we will be using only MS Access for simplicity. Most of the samples provided in this site uses MS Access database for simplicity and easy download.

    ADO.NET


    ADO.NET is the data access model that comes with the .NET Framework. ADO.NET provides the classes required to communicate with any database source (including Oracle, Sybase, Microsoft Access, Xml, and even text files).

    DataAccess Providers in .NET


    ADO.NET comes with few providers, including:
  • OleDb
  • SqlClient

    There are other providers available, but we are not including them here as this tutorial is meant for beginners! When you want them, search for ADO.NET providers in Google or MSDN

    Microsoft made the SQL Server. So they gave a separate provider, specifically made for SQL Server. We can use the OleDb provider for all other database sources including MS Access, Oracle, Sybase etc. There is a separate provider available for Oracle.

    A DATA PROVIDER is a set of classes that can be used to access, retrieve and manipulate data from the databases.

    Both OleDb and SqlClient has its own set of classes, but they have the same concepts. We would like to classify the classes into two broad categories (this is not a microsoft classification, anyway!)
  • Classes for communicate with database
  • Classes for holding/manipulating data

    The job of first category of classes is to communicate with database and send or retrieve data from the database. The second category of the classes will be used as a carrier of data.

    Classes for communicating with database


    The Connection, Command, DataReader, and DataAdapter
    objects are the core elements of the ADO.NET provider model.
    ObjectDescriptionSqlClient ObjectsOleDb Objects
    ConnectionEstablishes a connection to a specific data source.SqlConnectionOleDbConnection
    CommandExecutes a command against a data source.SqlCommandOleDbCommand
    DataReaderReads a forward-only, read-only stream of data from a data source.SqlDataReaderOleDbDataReader
    DataAdapterPopulates a DataSet and resolves updates with the data source.SqlDataAdapterOleDbDataAdapter


    Each provider may have classes equivalent to above objects. The name of the classes vary slightly to represent the provider type appropriately.

    Depending on the type of database you work on, you will have to choose either OleDb or SqlClient (or, some other provider) objects. Since all our samples use MS Access database, we will be using OleDb objects in all the samples. If you like to use SqlServer, you just need to replace the OleDb objects with the equivalent SqlClient objects.

    Classes for holding data



    The following are the main classes used to hold data in Ado.NET:
  • DataSet
  • DataTable
  • DataRow
  • A DataSet is an in-memory representation of the database.
  • DataSet contains DataTables (and more...)
  • DataTable represents a database table
  • DataTable contains DataRows (and more...)
  • A DataRow represents a record in a database table.
  • DataRow is a collection of all fields in a record.

    We can use the DataAdapter or DataReader to populate data in DataSet. Once we populate data from database, we can loop through all Tables in the DataSet and through each record in each Table.
  •  

    Create, Read, Update, Delete - ADO.NET sample 

     

    Here is some sample code to execute a simple query.


    string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\Employee.mdb";
    
    OleDbConnection myConnection = new OleDbConnection( connectionString );
    myConnection.Open();
    
    string query = "insert into EMPLOYEE_TABLE (EmployeeID, Name, Address) VALUES (101, 'John', '3960 CliffValley Way')";
    
    OleDbCommand myCommand = new OleDbCommand();
    myCommand.CommandText = query;
    myCommand.Connection = myConnection;
    myCommand.ExecuteNonQuery();
    
    myConnection.Close();


    Let us analyze the code. First we have declared a connection string. The connection string points to an MS Access database. Before you execute this code, make sure you have the database in the path specified. Or, change the path accordingly.

    In the next step, we are creating a OleDbConnectionobject and passing the connection string to this object. The line 'myConnection.Open();' will open a connection to the MS Access database specified in the connection string. If the database doesn't exists or if it is not able to open a connection for some other reason, the '.Open' call will fail.

    Next step is, creating a OleDbCommand object. This command object is used to execute sql statements and uses the connection opened by the OleDbConnection object.

    Note that before executing a command, we have to establish a valid connection to the database.

    And finally, after we have executed with the command, we will close the connection.

    The above sample code executes a sql statement and returns no data from database. We are calling the method 'ExecuteNonQuery()' on the command object. If we have a 'select ...' statement which returns data from database, we cannot use the 'ExecuteNonQuery()' method.

    The following sample demonstrates using OleDbDataAdapterObject and DataSet to retrieve data from databbase.

    string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\Employee.mdb";
    
    OleDbConnection myConnection = new OleDbConnection( connectionString );
    
    string query = "select * from EMPLOYEE_TABLE";
    
    OleDbDataAdapter myAdapter = new OleDbDataAdapter( query, myConnection );
    DataSet employeeData = new DataSet();
    myAdapter.Fill ( employeeData );


    Here we are creating a OleDbConnection object and we are just passing the object to the OleDbDataAdapterobject. Also, we pass the 'select ...' query to the OleDbDataAdapter. Next, we call the '.Fill()' method of the OleDbDataAdapter. This step will populate the dataset ( called 'employeeData' ) with the data retrieved for the sql statement 'select * from EMPLOYEE'.

    As you already know, a DataSet can contain a collection of tables. But in our case, our sql statement will retrieve data from only one table. So, our DataSet will have only one table.

    We can iterate through the table in the dataset and retrieve all the records. See the following code demonstrating this:


    string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\Employee.mdb";
    OleDbConnection myConnection = new OleDbConnection( connectionString );
    
    string query = "select * from EMPLOYEE_TABLE";
    
    OleDbDataAdapter myAdapter = new OleDbDataAdapter( query, myConnection );
    DataSet employeeData = new DataSet();
    myAdapter.Fill( employeeData );
    
    // Repeat for each table in the DataSet collection.
    foreach ( DataTable table in employeeData.Tables )
    {
    // Repeat for each row in the table.
    foreach ( DataRow row in table.Rows )
    {
    MessageBox.Show( "Employee Number : " + row["EmployeeNumber"].ToString() );
    MessageBox.Show( "Name : " + row["Name"].ToString() );
    MessageBox.Show( "Address : " + row["Address"].ToString() );
    }
    }
    
    

    DataSet, DataTable, DataRow 

     

    DataSet and DataTable are the key components in ADO.NET programming. In simple words, DataSet represents an in memory representation of the database. We can load an entire database into a DataSet and manipulate the data in memory. If you aremore familiar with DataSet, you can Add, Edit and Update data in the dataset and then just call a single method 'AcceptChanges()' whichwill save all the changes back to the database.
  • A DataSet contains one or more DataTables
  • A DataTable contains DataRows.

    What is DataSet ?

    A DataSet is an in memory representation of data loaded from any data source. Even though the most common data sourceis database, we can use DataSet to load data from other data sources including XML files etc. In this article, we will talk about the role of DataSet in manipulating data from database.

    In .NET, a DataSet is a class provided by the .NET Framework. The DataSet class exposes several proeprties and methods that can be used to retrieve, manipulate and save data from various data sources.

    Just like any other classes in object oriented programming, we have to create an instance of DataSet class to work with data. Typically, we may create a new instance of a DataSet and use other classes provided by .NET Framework to populate the DataSet. See the following example:


    string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\Employee.mdb";
    
    OleDbConnection myConnection = new OleDbConnection( connectionString );
    
    string query = "select * from EMPLOYEE_TABLE";
    
    OleDbDataAdapter myAdapter = new OleDbDataAdapter( query, myConnection );
    
    DataSet employeeData = new DataSet();
    myAdapter.Fill ( employeeData );


    Here we are creating a OleDbConnection object and we are just passing the object to the OleDbDataAdapterobject. Also, we pass the 'select ...' query to the OleDbDataAdapter. Next, we call the '.Fill()' method of the OleDbDataAdapter. This step will populate the dataset ( called 'employeeData' ) with the data retrieved for the sql statement 'select * from EMPLOYEE'.

    As you already know, a DataSet can contain a collection of tables. But in the above case, our sql statement will retrieve data from only one table. So, our DataSet will have only one table.

    Commonly used properties and methods of DataSet

    Property : Tables

    The Tables propertly allows us to retrieve the tables contained in the DataSet. This property returns a DataTableCollection object. The following sample code demonstrates iterating through the collection of tables in a data set and print the name of all the tables.


    DataSet employeeData = new DataSet();
    myAdapter.Fill( employeeData );
    
    // Repeat for each table in the DataSet collection.
    foreach ( DataTable table in employeeData.Tables )
    {
    MessageBox.Show ( table.TableName );
    }


    Or, you can use the indexer to access any specific table in the collection.


    DataSet employeeData = new DataSet();
    myAdapter.Fill( employeeData );
    
    // Repeat for each table in the DataSet collection.
    for ( int i = 0; i < employeeData.Tables.Count; i++ )
    {
    DataTable table = employeeData.Tables[i];
    MessageBox.Show ( table.TableName );
    }


    Method : GetXml()

    The GetXml() method returns the XML representation of the data from the DataSet.


    DataSet employeeData = new DataSet();
    myAdapter.Fill( employeeData );
    
    string xmlData = employeeData.GetXml();


    Method : WriteXml(...)

    The WriteXml() method allows to save XML representation of the data from the DataSet to an XML file. There are many overloaded method available, which takes various parameters. The example shown below takes a file name as parameter and saves the data in DataSet into xml format to the file name specified as parameter. We can optionally save only the data or both data and schema.


    DataSet employeeData = new DataSet();
    myAdapter.Fill( employeeData );
    
    employeeData.WriteXml( "c:\\MyData.xml" );


    Method : ReadXml(...)

    The ReadXml() method allows to load the DataSet from an XML representation of the data. There are many overloaded method available, which takes various parameters. The example shown below takes a file name as parameter and loads the data from XML file into the DataSet. This method can be used to load either the data only or both data and schema from the XML.


    DataSet employeeData = new DataSet();
    employeeData.ReadXml( "c:\\MyData.xml" );


    There is another method called 'ReadXmlSchema()', which can be used to load only the schema from a file.

    The methods WriteXml() and ReadXml() are useful to save the data from a database into some temporary files, transport to other places or keep it as a local file and load later. Many applications, including the SpiderAlerts tool available for download from this site, uses DataSet to manipulate data and saves/retrieves them from local disk using the WriteXml() and ReadXml() methods.

    The SpiderAlerts tool communicates with webservices in our site and retrieves the alerts in the form of a DataSet. Once the Alerts are retrieved, it is saved into local computer using the WriteXml method. (This implementation may be changed soon in the future versions of this tool. We are considering saving(serializing) the DataSet into Isolated Storage (IsolatedStorage is a new feature part of the .NET Framework - it is a kind of hidden file system).
  • More about DataTable and DataRow 

     

    A DataTable is a class in .NET Framework and in simple words a DataTable object represents a table from a database.

    DataSet and DataTable are the key components in ADO.NET programming. While DataSet can be used to represent a database as a whole, a DataTable object can be used to represent a table in the Database/DataSet. A DataSet can contain several DataTables.

    In typical database oriented applications, DataSet and DataTable are used a lot to manipulate data. DataAdapter or other classes can be used to populate a DataSet. Once a DataSet is populated, we can access the DataTables contained within the DataSet.

    Just like any database table contains multiple rows (records), a DataTable can contain multiple DataRows. Each row contains multiple fields representing each column in the table.

    The typical process to retrieve records from a database in ADO.NET includes the following steps:

  • Open a connection to database
  • Use a data adapter to fill a DataSet.
  • Access the DataTable contained in the DataSet
  • Access the DataRows contained in the DataTable.

    The following sample code explains these steps. This sample code retrieves data from an MS Access database.


    string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\Employee.mdb";
    OleDbConnection myConnection = new OleDbConnection( connectionString );
    
    string query = "select * from EMPLOYEE_TABLE";
    
    OleDbDataAdapter myAdapter = new OleDbDataAdapter( query, myConnection );
    DataSet employeeData = new DataSet();
    myAdapter.Fill( employeeData );
    
    // Repeat for each table in the DataSet collection.
    foreach ( DataTable table in employeeData.Tables )
    {
     // Repeat for each row in the table.
     foreach ( DataRow row in table.Rows )
     {
      MessageBox.Show( "Employee Number : " + row["EmployeeNumber"].ToString() );
    MessageBox.Show( "Name : " + row["Name"].ToString() );
    MessageBox.Show( "Address : " + row["Address"].ToString() );
     }
    }



    How to create a DataTable

    In most of the cases, we just access the DataTable in a DataSet. We do not need to create a new instance of the DataTable. When a DataSet is populated from database, the DataTable is created with proper schema and data.

    If we explicitely create DataTable, we have to create the proper schema. It is bit confusing if you are not very familiar with the database structure and schema.
  • Exception Handling in .NET 

     

    If you write a program, it is for sure that it will have errors and issues. You cannot avoid them. But what you can do is write the code such a way that it is easy to find the errors and issues so that you can solve them easily. You need the real skill to write 'maintainable code'.
    What is maintainable code ?
    If an existing application is given to a new employee in the company and ask him to fix a problem in that,most probably he will come back with the answer : "oh, it is stupid code.. I can't figure out what they have written. Instead of trouble shooting the issues in this code, I can re write the entire application with less time."

    This is a common scenario in the programming world. The above answer shows the code is not a maintainable code. Over a period of time, there will be lot of changes required in existing applications to adapt to the new requirements. Only if you write 'maintainable code', you can enhance your application when new requirements come up and solve issues.

    There is no specific set of rules to make an application 'maintainable'. There are lot of factors involved in it including following coding standards, writing lot of comments within code, writing self explanatory code, separating application into multiple well defined layers, having good exception handling etc.
    What is an 'Exception' ?

    'Exception' is an error situation that a program may encounter during runtime. For example, your program may be trying to write into a file, but your hard disk may be full. Or, the program may be trying to update a record in database, but that record may be already deleted. Such errors may happen any time and unless you handle such situation properly, your application may have un predictable behaviour.
    What is the difference between 'Exception' and 'Error' ?

    Error is an expected situation in an application. For example, you want to create a file in the folder "C:\Projects\Test\". If you attempt to create a file when this folder doesn't exists, it will make the operating system throw an exception. But you should not leave it to the operating system to throw the exception. This has to be handled through code. You must first check for the existence of the folder before you attempt to write the file. If the folder doesn't exists, you must first create the folder. This is how a stable application should be written.

    Exception is a runtime error that the program may encounter during the execution of the program. For example, hard disk may be full when you attempt to write into a file, network connection may be lost while your application is communicating with another computer etc. There is no clear definition, but typically, Exceptions are unpredictable errors during runtime.
    What is 'Exception Handling'?

    When you ride a bike, you may wear a helmet. When you go for boating, you might use a life jacket. A car driver might use seat belts while driving at high speed in a high way. What is the purpose ? To handle exceptions (accidents), right ? We do not know when it might happen, so we are prepared to 'handle' such situations any time.

    An exception can occur anytime during the execution of an application. Your application must be prepared to face such situations. An application will crash if an exception occurs and it is not handled.

    "An exception handler is a piece of code which will be called when an exception occurs."

    .NET Framework provides several classes to work with exceptions. The keywords try, catch are used to handle exceptions in .NET. You have to put the code (that can cause an exception) in a try block. If an exception occurs at any line of code inside a try block, the control of execution will be transfered to the code inside the catch block.

    Syntax :

    try
    {
    // Code which can cause an exception.
    }
    catch(Exception ex)
    {
    // Code to handle exception
    }

    Just like a bike rider wrap his head in a helmet to protect from accident, the above syntax will protect the code within the try block from accidents (exceptions).

    If any statement within the try block raises an exception, the control of execution will be transfered to the first line within the catch block. You can write the error handling code in the catch block, like recording the error message into a log file, sending an email to the administrator about the problem occurred, showing an appropriate error message to the user etc.

    See the following code :

    try
    {
    Statement 1
    Statement 2
    Statement 3
    }
    catch(Exception ex)
    {
    Statement 4
    Statement 5
    }
                
    Statement 6


    In normal flow of program, the statements 1, 2, 3, 6 will be executed. Statements 4 and 5 will be executed only if an exception occurs.

    Assume there is an exception at statement 2. In this scenario, statements 1, 2, 4, 5 and 6 will be executed. Statement 3 will not be executed at all, because an exception occurred at statement 2 and program flow was transferred to the catch block.
    'finally' block

    You can optionally use a 'finally' block along with the try-catch. The 'finally' block is guaranteed to be executed even if there is an exception.

    Sample Code :

    try
    {
    Statement 1
    Statement 2
    Statement 3
    }
    catch(Exception ex)
    {
    Statement 4
    Statement 5
    }
    finally
    {
    Statement 6
    Statement 7
    }
                
    Statement 8

    In normal flow of program, the statements 1, 2, 3, 6, 7 and 8 will be executed. Statements 4 and 5 will be executed only if an exception occurs.

    Assume there is an exception at statement 2. In this scenario, statements 1, 2, 4, 5, 6, 7 and 8 will be executed.

    Note that the statements 6 and 7 are executed in both the cases. The bottom line is, the code within the 'finally' block is executed whether there is an exception or not.

    You can use the finally block to do any code cleanup. For example, you are doing some database operations inside a try block.

    try
    {
    Statement 1 - Open database
    Statement 2 - Execute Query
    Statement 3 - Close Database
    }
    catch(Exception ex)
    {
    Statement 4 - Show messagebox to user
    }

    In the above code sample, what will happen if an exception occurs when the statement 2 is executed ? The catch block will be executed and a message box will be shown to the user. But the Statement 3 is never executed in that case, which means the database will not be closed.

    Here is where the finally block will be helpful.

    try
    {
    Statement 1 - Open database
    Statement 2 - Execute Query
    }
    catch(Exception ex)
    {
    Statement 3 - Show messagebox to user
    }
    finally
    {
    Statement 4 - Close Database
    }

    See the improved code. We have moved the code to close the database to the 'finally' block. The statement to close the database will be executed whether there is an exception or not.

    Why should we catch exceptions ?

    Why should you use a helmet when you ride a bike ? To protect your head from crashing when there is an accident, right ? Just like that, exception handling will protect your application from crashing when there is an exceptions.

    If an exception is not 'handled' in code, the application will crash and user will see an ugly message. Instead, you can catch the exception, log the errors and show a friendly message to the user.

     

    Exception classes in .NET 

     

    .NET Framework provides several classes to work with exceptions. When there is an exception, the .NET framework creates an object of type 'Exception' and 'throws' it. This Exception object contains all information about the 'error'.

    If you enclose your code within the try-catch block, you will receive the exception object in the 'catch' block when the exception occurs. You can use this object to retrieve the information regarding the error and take appropriate action.

    try
    {
    // Code which can cause an exception.
    }
    catch(Exception ex)
    {
    // Code to handle exception
    MessageBox.Show ( ex.Message );
    }

    Within the catch block, you can use the Exception object to get more information about the error. The exception object exposes a property called 'Message', which gives a description about the error. This may not be a very friendly message for the end user. But you can use it to log the error and show another friendly message to the user.
    The System.Exception class

    In .NET, all exceptions are derived from the Exception class. The Exception class is defined inside the System namespace.Other derived exception classes are spread across many other namespaces.

    Since all other exceptions are derived from the System.Exception class, if you catch System.Exception, that would cover all exceptions derived from System.Exception also. So, the statement catch (Exception) would catch all exceptions of type System.Exception and all derived exceptions. In .NET, all exceptions are derived from System.Exception. So,catch (Exception) will catch all posibble exceptions in your .NET application.
    Specify what exception type you want to catch

    See the catch block in the above sample code. catch ( Exception ex ) - specifies that we want to catch all exceptions of Type Exception. So, if there is an exception of Type Exception, it will be caught by the catch block.

    If you specify an exception Type in the catch statement, it will catch all exceptions of the specified type and all types derived from it.

    See the following sample :


    try
    {
    // Code which can cause an exception.
    }
    catch(System.Web.HttpException ex)
    {
    // Code to handle exception
    MessageBox.Show ( ex.Message );
    }

    The above example will only catch the exception of type System.Web.HttpException and any other exception derived from it. So, if there is any exception of type System.ArithmeticException, it will not be handled and it may lead to program termination.
    Handling specific Exception types

    In my previous article, I mentioned few examples from real life - "When you ride a bike, you may wear a helmet. When you go for boating, you might use a life jacket. A car driver might use seat belts while driving at high speed in a high way. What is the purpose ? To handle exceptions (accidents), right ? We do not know when it might happen, so we are prepared to 'handle' such situations any time. "

    Yes, a helmet helps a bike rider when he meet with an accident. A life jacket may be helpful in water and a seat belt would help a car driver. But what if some one ride a bike with a helpmet, life jacket and a seat belt ? That may not look good, right ?

    Similarly, in Exception handling, you do not need to catch all exceptions. You need to catch only the 'expected' exceptions. Which means,if you are doing an arithmetic calculation, you must handle ArithmeticException and DivideByZeroException. When you are accessing the web from your code, you must handle HttpException.

    The bottom line is, depending on the nature of the code, you must handle the appropriate, specific exceptions, instead of catching the father of all exceptions (System.Exception).
    Multiple catch blocks

    You can have any number of catch blocks for each try block. For example, if you are doing some operation which involve web access and also some arithmetic operations, you can handle both System.Web.HttpException and System.ArithmeticException. See the sample below:

    try
    {
    // Code which can cause a web exception or arithmetic exception.
    }
    catch(System.Web.HttpException ex)
    {
    MessageBox.Show ( "A web exception occurred." );
    }
    catch(System.ArithmeticException ex)
    {
    MessageBox.Show ( "An arithmetic exception occurred." );
    }

    Program Flow

    When an exception occurs within a try block, the program control will jump to the first catch block and compare if the exception type is same the as the type specified in the catch block. If the type matches, it will execute the catch block. If the types do not match, it will jump to the next catch block and compare. Like this, it will compare against all catch blocks until a match is found. If there is no catch block found which matches the exception type, it will become an unhandled exception and will lead to program termination
    Catch derived exceptions first and base exception last

    A base exception type will match the derived exceptions also. If there is a catch block with the type 'Exception', it will catch all types of exceptions. So, you have multiple catch blocks, you must specify the derived exception types first and the base types last. See the following code:

    try
    {
    // Code which can cause a web exception or arithmetic exception.
    }
    catch (System.Exception ex)
    {
    MessageBox.Show ( "An exception occurred." );
    }
    catch (System.Web.HttpException ex)
    {
    MessageBox.Show ( "A web exception occurred." );
    }

    In the above code, assume there is a web exception occurred. The exception type will be compared against the first catch block. Since the WebException is derived from System.Exception or oneof it's derived classes, the types will match and the first catch block will be executed. So, you might be expecting that the catch (System.Web.HttpException) block will be executed, but it would never get called because of the catch(System.Exception ex) before that.

    You must change the above code as shown below :

    try
    {
    // Code which can cause a web exception or arithmetic exception.
    }
    catch (System.Web.HttpException ex)
    {
    MessageBox.Show ( "A web exception occurred." );
    }
    catch(System.Exception ex)
    {
    MessageBox.Show ( "An exception occurred." );
    }

    Now, if there is a web exception, it will go to the catch (System.Web.HttpException ex) block. All other exceptions will go to catch (System.Exception ex).
    Some commonly used .NET Exception classes

    System.ArithmeticException - This is the base class for exceptions that occur during arithmetic operations, such as System.DivideByZeroException and System.OverflowException.

    System.ArrayTypeMismatchException - ArrayTypeMismatchException is thrown when a an incompatible object is attpemted to store into an Array.

    System.DivideByZeroException - This exception is thrown when an attempt to divide a number by zero.


    System.IndexOutOfRangeException - IndexOutOfRangeException is thrown when attempted to access an array using an index that is less than zero or outside the bounds of the array.

    System.InvalidCastException - Thrown when an explicit type conversion from a base type or interface to a derived type fails at run time.

    System.NullReferenceException - This exception is thrown when an object is accessed but it is null.

    System.OutOfMemoryException - OutOfMemoryException is thrown if the 'new' operation (creating new object) fails due to in sufficient memory.

    System.OverflowException - OverflowException is thrown when an arithmetic operation overflows.

    System.StackOverflowException - StackOverflowException is thrown when the execution stack is exhausted by having too many pending method calls, most probably due to infinite loop.

    ArgumentException - The exception that is thrown when one of the arguments provided to a method is not valid.

     

    Custom Exceptions 

     

    The Microsoft .NET team has done a good job by providing us a rich set of Exception classes. Most of the time, these exception classes are sufficient enough to handle any common error situation. However, it may be required that our application would need some additional exception classes, that are not available in .NET Framework.

    The .NET Framework exception handling mechanism allows us to create our own custom exception classes and use it in our applications.
    Custom Exceptions

    All exceptions in .NET are derived from the root exception class - System.Exception. There are two other
    exception classes immediately derived from the System.Exception :

  • System.SystemException

  • System.ApplicationException


  • All exceptions thrown by the .NET Framework is derived from the SystemException class. If we raise any exception from our application, it should be derived from the System.ApplicationException. This will differentiate our exceptions from the system generated exceptions.

    It is easy to create a custom exception class. Just create a new class and mark it as derived from System.ApplicationException
    
    public class UserNotExistsException : System.ApplicationException 
     {
     }   



    Now we have derived a custom exception class and we can use it in ourr application. See the sample code, showing how we

    can throw ourr custom exception.
    
     public void UpdateUser( User userObj )
     {
      if ( some error condition )
      {
       throw new UserNotExistsException();
      }
     }


    The 'throw' statement allows us to raise an exception programmatically. Here we are creating a new object of type 'UserNotExistsException' and throwing it. Another class or method which calls our method should handle this exception.
    
     try
     {
      UpdateUser( userObj );
     }
     catch ( UserNotExistsException ex )
     {
      MessageBox.Show ( ex.Message );
     }
       

    In this sample, we are calling the method UpdateUser(...), which might throw an exception of type UserNotExistsException. If this exception is raised, it will go to our catch block and we are showing a message to the user.
    Enhancing our custom exception

    In the custom exception we defined above, we haven't specified any constructor. But since we derive it from the ApplicationException, it will use the public constructors available in AppicationException. It is a good idea to provide at least one constructor, which takes an error message as a parameter.
    
     public class UserNotExistsException : System.ApplicationException 
     {
      public UserNotExistsException ( string message ) : base ( message )
      {
      }
     }   


    Now, when we throw this exception, we have to pass an error message to the constructor. The error handlers will be able to retrieve this message from the Exception object and show a better message to the user.
    
     public void UpdateUser( User userObj )
     {
      if ( some error condition )
      {
       throw new UserNotExistsException( "The user you are trying to update does not exists." );
      }
     }


    See the exception handler code :
    
     try
     {
      UpdateUser( userObj );
     }
     catch ( UserNotExistsException ex )
     {
      MessageBox.Show ( ex.Message );
     }

    Now the user will see the more friendly error message which we passed as part of the exception, while throwing it.

    You can customize the custom exception classes such a way that it passes any information you want including the date and time the exception occurred, the method name in which the exception was first raised, user name of the current user etc. You may also provide a Save() method for your custom exception class so that when a caller catch our custom exception, he can call the Save() method, which will record the error information to the disk.

    Introduction to XML 

     

     XML stands for eXtended Markup Language. XML has some similarities to HTML, which is also another Markup Language (HyperText Markup Language).

    An important difference between XML and HTML is, XML is used to define data, while HTML is basically used to display/format text. Main use of HTML is to make web pages. But XML is used in a wide variety of applications now and is becoming a standard for data exchange between different paltforms.
    Unlike HTML, XML has no pre-defined set of tags. You can define your own tags to structure and organize your data. Let us see some sample XML :
     
    <Company>
     <Employees>
      <Employee Id="101" Name="John" ></Employee>
      <Employee Id="102" Name="Lisa" ></Employee>
      <Employee Id="103" Name="Bill" ></Employee>
     </Employees>
     
     <Departments>
      <Department Name="Sales"></Department>
      <Department Name="Software"></Department>
      <Department Name="HR"></Department>
     </Departments>
    </Company>
    The above piece of XML is quite self explanatory. It is used to represent the data related to a company. One thing to note here is, the tags like <Company>, <Employees> etc are not predefined. Any XML document can have it's own set of tags. Only thing is, a valid XML document should follow some rules (like each tag should have a matching closing tag. There more such rules...)

    Need for XML

    XML is a platform neutral standard. Since it is represented in plain text, any platform can understand it. You can use XML to exchange data between Unix and Windows, Mainframes and windows applications and virtually any other platforms. It is a simple, easy to use *language* to exchange/store data.

    In real world, if you have to store data, you have several choices. One of the most common mechanism is databases. Databases are the best choice if you have lot of data to be stored/manipulated. But if you have to send data to another application or platform, databases will not be much helpful. Suppose you have your data stored in an SQL Server database. What if your manager ask you to give the list of Employees in the Sales department ? How will you give the data to him? You cannot give your SQL Server database to him. He may not have a SQL Server software or he may not have the technical expertise to view data from SQL Server. XML is very helpful in such scenarios. You just need to generate an XML from the SQL Server database with the required records and hand over the XML as a print out or email. XML is so simple so that any one can simply read it using any text editor.

    There are several XML viewers and editors available, which will help you read XML in the form of a tree view. Internet Explorer is a good XML viewer. Simply copy the above XML and save into a file called 'sample.xml'. Then open the xml file in internet explorer and see how it works!

    You can define your own XML tags based on your needs. You can have nested tags too, which help you organize the data any way you want it. See a slightly different version of the above XML:


    <Company>
     <Employees>
      <Employee Id="101" Name="John" ></Employee>
      <Employee Id="102" Name="Lisa" ></Employee>
      <Employee Id="103" Name="Bill" ></Employee>
     </Employees>
     
     <Departments>
      <Department Name="Sales">
       <Manager>
        <Name>Fred</Name>
        <Address>3000 Briarcliif Way</Address>
        <Email>Fred@spiderkerala.com</Email>
        <Phone>
         <ResidencePhone>616 304 1093</ResidencePhone>
         <OfficePhone>616 304 1093</OfficePhone>
        </Phone>
       </Manager>   
      </Department>
      
      <Department Name="Software">
       <Manager>
        <Name>Joe</Name>
        <Address>3960 Whispering Way</Address>
        <Email>Joe@spiderkerala.com</Email>
        <Phone>
         <ResidencePhone>616 304 1093</ResidencePhone>
         <OfficePhone>616 304 1093</OfficePhone>
        </Phone>
       </Manager>   
      </Department>
     </Departments>
    </Company>
    The XML data altogether is called an 'XML Document'. .NET gives several classes to read and manipulate XML Documents. We will explore some of them in upcoming chapters.

    You might have seen our Tutorial Index, which lists all chapters. You can click on any chapter title and navigate to the corresponding page. This index is populated from an XML file.

    Click here to view the XML file, from which we load our tutorial chapters.

    The reason we load it from an XML file is, our chapters are continuously changing and we add new chapters frequently. All our chapters have a link to Next Chapter. If we hard-code these links in all chapters, we have to make changes in several places when we change the order of some chapters or when we add new chapters. There is all possibility that we might make some mistakes and some of the chapters may lead to 'wrong next chapter'. In our current implementation, we programmatically read the XML file and display the Tutorial Index. Also, each page has a piece of code which read the current page URL and find the Next Page Url from the XML file based on the current page URL. This mechanism helps us add new chapters without making any changes to existing pages. All we have to do is, just insert one line of entry in the XML file and the changes will be automatically reflected in all other relevant pages. Even if we want to re-order some of the chapters, we just need to re-arrange the entries in the XML file.

    We use the following code to load our Chapter Index from the XML file:
    public string GetChapters( string filePath )
    {
     // Create an xml document.
     XmlDocument doc = new XmlDocument();   
    
     // Load the XML from the file.
     doc.Load(filePath);
    
     // Retrieve all categories from the xml.
     XmlNodeList categories  = doc.SelectNodes("DotNetSpider/tutorials/Category");
    
     string chapterString = "";
     int chapter = 0;
    
     // Iterate through all the categories
     foreach ( XmlNode categoryNode in categories )
     {
      // Add category name to the string.
      chapterString += "<BR><BR><font size=4>" + categoryNode.Attributes["Name"].Value + "</font><BR>";
    
      // Get all chapters in the current category.
      XmlNodeList chapters = categoryNode.SelectNodes("Chapter");
    
      // Loop through all chapters in the current category and add to the string.
      foreach ( XmlNode chapterNode in chapters )
      {
       ++chapter;
    
       chapterString += "       <LI>Chapter " + chapter + 
         " : <a href='" + chapterNode.Attributes["Url"].Value + "'>" + 
         chapterNode.Attributes["Name"].Value + "</a>";
      }
     }
    
     // Return the string, which contains the list of chapters.
     return chapterString;
    }
    We explored some areas where XML can be used. But XML can be used in a very wide range of ways. We will explore more advanced uses of XML in another chapter.

    XML Specification

    We gave a very brief introduction to XML in this chapter. This chapter is meant to give a very brief introduction and we haven't covered many important aspects of XML here. We will explain most of them in some other chapters.

    Introduction to HTML 

    What is HTML

    HTML(Hypertext Markup Language) - is the language used for creating hypertext documents (web pages) and controlling how Web pages appear.

    Even though it is a language, it is different from other programming languages like C++ or Java. In languages like C++ and Java, you can write complex applications and the language has its own syntax and rules. But you can use HTML to develop only web pages.
    Some facts about HTML
  • HTML is plain text, composed of tags.
  • HTML tags are always enclosed in angle-brackets ( < >)
  • HTML is not case sensitive, that means, it doesn't matter whether you type them in lower case or upper case.
  • Tags typically are used in begin-end pairs. Most of the HTML tags have an open tag and a close tag: Eg:
       <B>...</B>
       <I>...</I>
       <FONT>...</FONT>
       <BODY>...</BODY>

    Some tags like <HTML>, <HEAD> etc are mandatory in any html file. A basic HTML file will have the following structure:

    <html>
    
    <head>
    
    <title>your title</title>
    
    </head>
    
    <body>
    
    your page content
    
    </body>
    </html>


    All the HTML tags in the above code is mandatory for an HTML page. You may copy and paste the above code into a file in notepad and name it test.html. Open the file in internet explorer to see how it works.
  • Web Services 

     

    Webservices are services exposed over the internet. Typically, webservice is just like any other class library, written in any language. What make it a 'web service' is, it can be accessed across internet.

    Eventhough webservice is a new technology with a wide range of usage, it is a pretty simple concept. It doesn't require much additional knowledge to create web services if you are already familiar with C# or VB.NET. (Web services are not specific to .NET. Even Java has web service applications, but here we are discussing only the .NET web services.)

    As we mentioned, web services are exposed over internet. To make this happen, it has to be hosted with a web site. Othen than hosted as part of a web site to make this visible across internet, web services have no web pages or UI. It is just a set of classes with public/private methods and properties.

    Web services are a group of [web] methods. Consumer applications can treat this as just another class library. Regular class libraries are located along with the same application and we can call any methods in the class libraries (assemblies). But in case of web services, the assembly is located in the internet server. The consumer application will not have direct access to the assembly. Consumer applications have to add a reference to the webservice URL and then call methods in it. The method call goes across the internet using
    SOAP protocal and results are returned across internet in the form of XML. The communication across internet happens transparently and the application need not know anything about this communication.
    Creating a simple web service

    If you are using VS.NET, it won't take more than 2-3 minutes to create your first webservice. Follow the steps below to create a web service:
  • Choose New Projectfrom VS.NET and create a C# project of type 'ASP.NET Web Service' and give the name 'MyWebService'
  • The new project will have a default page 'Service1.asmx'. This is your first web service page. Web service pages have the extension .asmx (like ASP.NET pages have the extension .aspx)
  • The code behind file 'Service1.asmx.cs' have a class 'Service1'. This is like other regular classes with the only difference that it inherits the system class System.Web.Services.WebService. This is required for web service classes.
  • VS.NET creates a sample method for you. All you have to do is, uncomment the following method in Service1.asmx.cs
    //[WebMethod]
    //public string HelloWorld()
    //{
    //return "Hello World";
    //}
    Note that this method is pretty much same as any other regular method.
    The only difference is, it has an attribute [WebMethod]. This attribute make
    the method visible across internet. If you remove this attribute, your
    application will still compile, but the consumer applications cannot call this
    method across internet.

    Ok, thats all you have to do to create a simple webservice. Build your solution and your web service is ready to be called by other applications.

    Create a consumer application

    A wide range of applications can consume the web services, including web page, other web services, windows applications etc. let us create a sample windows application and call our web service.
  • Create a new C# Windows Application.
  • Right click on the 'References' in the Solution Explorer, under your project name. Choose 'Web References'.
  • Another window will open and will allow you to specify the URL of the web service to be referenced.

    Type the URL of your web service in the space provided for 'URL'. If you have created the web service in the local machine's default web site, the URL might be like this :


    http://localhost/MyWebService/Service1.asmx
    If you have given a different name fro the project or if you have changed the default service name, then your URL may differ. Type the URL and press enter. It will attempt to connect with the web service and if succeeded it will retrieve the public web methods and display. Once you get this success screen, press the 'Add Reference' button on the screen to add the web reference to your application. There is a space to specify the 'web reference name', which will have the default value 'localhost'. Leave it as it is.

    Now you are ready to make calls to the webservice. Just use the following code in your application:
    localhost.Service1 service = new localhost.Service1();
    string result = service.HelloWorld();
    
    MessageBox.Show( result );
    Let us analyze our code. The first line creates an instance of the Service1 class, just like any regular class. Only thing is it uses the namespace 'localhost'. This is same as the 'web reference name' we specified while adding the web reference. We can use any web reference name when we add the reference and have to use the same name as namespace while making calls to the web service class.

    In the second line, we are actually calling the web method 'HelloWorld()' and it returns the result as a string. Note this is just like any other method call. So, your application makes the call to web service as if it is calling any local class library calls!! The communication with web service, wrapping your calls in SOAP/XML, retrieve results from web service, unwrap the SOAP/XML to get the actual result etc are done behind the scene by the framework and you need not do any additional work to make all this work.

    Now you can go back to your web service, add more methods with different parameters and play around with that. You will be able to call methods in the web service just like you use any local class. Note that when you make any changes to the method name or parameters, or if you add new methods, you will need to refresh your web reference to get access to the updated web service methods. To do this, go to the Server Explorer, right click on the web reference name 'localhost' under the 'Web References'. Then choose 'Refresh'. This will communicate with the web service again and retrieve the latest web service data.

    How does all this work?

    To make calls to any classes, your application need to know the details of the class. To successfully compile your code, it has to have information about the class, what are the public methods and properties etc. But in your sample code which calls the web service, the actual Service1class resides in the web (in your case, in your local web server). So how does the application compile without having the 'Service1' class in your application?

    This is where the framework help you. When you add a 'web reference' to the web service URL, VS.NET actually creates local proxy in your application. A local proxy is a minimal version of the actual class. The proxy has just the sufficient information about the 'real class', which is required for your application to successfully compile. The proxy class has the list of all public web methods in the real web service class and it knows the parameters and their data types of each method.

    The most important thing is, your application is actually using this proxy class and not the real web service class.
    localhost.Service1 service = new localhost.Service1();
    string result = service.HelloWorld();
    
    MessageBox.Show( result );
    In the above code, localhost.Service1is actually the proxy class (a representative of a real class), which is created automatically by VS.NET when you added the web reference. You are creating an instance of the proxy class and calling the 'HelloWorld()' method of this proxy. Since the proxy class knows that it is 'only a proxy of the real class', it redirects all calls to the 'real web service class'. The method 'HelloWorld()' in the proxy class takes care of converting the call to a web request using SOAP/XML. After retrieving the result of the web request to the real web service class, this proxy class takes the responsibility of parsing the SOAP/XML response and returning only the result string to the calling applicationn. So the proxy class does all the dirty job for you.

    The proxy class has no implementation of the functionality. It just redirects the call to the web service. So, if you make any changes to the implementation in the web service, still you will get the 'updated result' when you make calls to web service. But, if you change the method name, or change the parameter types in the web service and do not 'refresh the web reference', then your application will compile with the old proxy. But when the proxy redirect the call to the web service, it will find that the parameters or method names do not match and it will fail. So, if there is any change in the method names or parameters, you must refresh your web reference.





  •