< Chap 1 TOC: Intro To Windows Network Programming | Main | C# .NET + ASP .NET Sample >

 


 

Chapter 1 Part 1

Network Programming with the Microsoft .NET Framework

 

 

What do we have in this chapter1 part 1?

  1. An Overview

  2. Common Language Runtime (CLR)

  3. Why the .NET Framework?

  4. Inherent Benefits of Building on Top of the CLR

  5. Extensive Use of Patterns

  6. Broad Windows Platform Support

  7. Class-Based Model

  8. Layered Architecture

  9. .NET Framework Classes

  10. System.* Namespaces Overview

  11. General-Purpose Class Libraries

  12. Application Model - Specific Classes

  13. ASP.NET

  14. Visual Basic .NET: Weather Service Sample Application

 

 

 

An Overview

 

Welcome to network programming with the Microsoft Windows .NET Framework. The .NET Framework is a platform for distributed computing that enables developers to create powerful network-aware applications with a new level of simplicity and interoperability. In this book, we’ll cover the details you need to know to get the most out of your distributed development efforts as you target this new platform. This text is intended to cover a range of network development scenarios, from writing your first socket-based application to developing high performance n-tier Web applications.

Before we get too far into the network-specific elements, it’s important to understand the basic principles behind the creation of the .NET Framework. This chapter will walk you through the basics of the .NET Framework and the common language runtime (CLR), with a particular focus on the network- related elements.

We’ll start with an overview of the CLR, the execution environment on which the .NET Framework is based. Next we’ll explain the overall goals behind the .NET Framework and define some key terms that will be used in this book. Then we’ll go over the System.*-level namespaces, including a look at each of the common models that can be used to create different types of applications such as Microsoft ASP.NET, Windows Forms, Windows Services, and console-based applications. Code examples that demonstrate a basic network application in the context of each application model are included. With the groundwork in place, the remaining portion of this chapter introduces the elements of the .NET Framework most commonly involved in network programming. You’ll see that these pieces represent a layered, cohesive stack, as shown in Figure 1-1. The information you get from reading this book will be applicable regardless of the level at which you interface with the .NET Framework.

 

THe .NEt framework and its component

 

Figure 1-1: An overview of the .NET Framework and related components

 

Throughout the course of this chapter, we’ll be referring to Figure 1-1 as we talk about the different components that make up the .NET Framework and its related components, such as the CLR.

 

Common Language Runtime (CLR)

 

The .NET Framework includes a set of classes that run on top of an execution environment called the CLR. The CLR enables the following key benefits:

 

Why the .NET Framework?

 

The .NET Framework was designed with one key goal in mind: to increase the productivity of software developers. This goal is accomplished through a number of features that are built into the framework. Understanding these features will help you maximize your development efforts when using the .NET Framework.

 

Inherent Benefits of Building on Top of the CLR

 

As previously mentioned, the .NET Framework is built on the CLR, which was done intentionally to guarantee that the classes in the framework could take advantage of the benefits provided by the CLR. The CLR by itself is an impressive feat of software engineering, but it’s the broad set of application functionality on top of the CLR known as the .NET Framework that makes it possible for developers to build fully functional applications that enjoy the benefits of the CLR.

 

Extensive Use of Patterns

 

One of the critical ways that the .NET Framework makes the development environment productive is by establishing common patterns for a particular development task that are applied across a broad set of functionality. Error handling, for example, is a task that developers must deal with regardless of the type of application programming interfaces (APIs) used. The .NET Framework simplifies this task by defining one general-purpose mechanism for handling errors so that you can learn it once and then apply the pattern across the development of your application. Examples of patterns in the framework include dealing with collections or groups of objects, interacting with system resources, and handling application events.

 

Broad Windows Platform Support

 

The .NET Framework is designed to support development across various versions of the Windows operating system, from Windows 98 up to the latest release of the operating system. This common API set across all the major Windows platforms in deployment today reduces the complexity of development when targeting multiple environments.

 

Class-Based Model

 

The APIs in the .NET Framework are encapsulated in classes. A class in the framework usually contains members such as properties and methods. Developers can create an instance of a class in the framework and use it to perform tasks that are required by the application. Developers can also extend classes to include additional behaviors or combine them to define new classes. This object-oriented approach offers a familiar model that you can quickly identify with and relate to as you explore the functionality exposed by the framework.

 

Layered Architecture

 

The classes that make up the .NET Framework are layered, meaning that at the base of the framework are simple types, which are built on and reused by more complex types. The more complex types often provide the ability to perform more significant operations. For example, the socket class provides raw access to the network. The amount of code that you might write when using the socket class to download a file from the Internet might be 50 lines. The HTTP classes in the framework build on top of the socket class and make it easier to perform the same task. For example, the example that downloads a file from the Internet could now be accomplished in 15 lines of code. More generic URI resolution classes make it possible to download the same file in one or two lines of code. This layered approach makes it possible to use the classes that are most applicable to the task your application needs to accomplish. Because one layer builds on top of the other, it also makes it possible for an application to use the higher levels to do most of the work without blocking the ability to access the lower levels for maximum control.  

 

.NET Framework Classes

 

Now that we’ve covered a bit of the motivation behind the framework, let’s take a deeper look at the classes. Classes in the .NET Framework are divided into logical groups called namespaces. Most classes in the .NET Framework exist under a top-level namespace known as System. The root System namespace contains the basic data types in the framework, such as numbers, Booleans, Uniform Resource Identifiers (URI), strings, and objects, the base type from which all other classes in the framework derive. System also contains a broad array of second-level namespaces that represent the core functionality in the framework, such as eventing, infrastructure, interfaces, attributes, and exceptions.

 

System.* Namespaces Overview

 

There are two general groups of classes in the .NET Framework:

 

  1. General-purpose base class libraries and

  2. Application model-specific classes.

 

It’s useful to understand the difference between the two so that you’ll better know when to use classes from each group as you build your application.

 

General-Purpose Class Libraries

 

General-purpose class libraries can be useful in almost any context. For example, System.String represents an immutable fixed-length string of Unicode characters. String manipulation is useful in a Web-based application that returns HTML content to the browser, a GUI client application that runs on the end user’s computer, or a long-running service that has no graphical representation at all.

Table 1-1 contains System namespaces along with a brief description and an indication of whether the namespace represents a general-purpose base class library or is part of a particular application model. Each namespace contains anywhere from 10 to more than 100 classes, depending on the number of lower-level namespaces it contains.

 

Table 1-1: Second-Level System Namespaces*

 

Namespace

Description

Base Class or Application Model

CodeDom

Classes that can be used to reference the structure of a code document.

Base

Collections

Contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hash tables, and dictionaries.

Base

ComponentModel

Provides classes that are used to implement the run- time behavior of components and controls.

Base

Configuration

Provides classes and interfaces that allow you to programmatically access .NET Framework configuration settings and handle errors in configuration files (.config files).

Base

Data

Contains the classes that represent ADO.NET, which enables you to build components that efficiently manage data.

Base

Diagnostics

Provides classes that enable you to interact with system processes, event logs, and performance counters

Base

DirectoryServices

Provides easy access to Active Directory directory services from managed code.

Base

Drawing

Provides access to GDI+ basic graphics functionality

Base

EnterpriseServices

Provides an important infrastructure for enterprise applications, including access to COM+.

Base

Globalization

Contains classes that define culture-related information, including the language; the country/region; the calendars in use; the format patterns for dates, currency, and numbers; and the sort order for strings.

Base

IO

Contains types that allow synchronous and asynchronous reading and writing on data streams and files.

Base

Management

Provides access to a rich set of management information and management events about the system, devices, and applications designed for the Windows Management Instrumentation (WMI) infrastructure.

Base

Messaging

Provides classes that allow you to connect to, monitor, and administer message queues on the network and send, receive, or peek messages.

Base

Net

Provides access to network resources over protocols such as Transmission Control Protocol (TCP), User Datagram Protocol (UDP), and Hypertext Transfer Protocol (HTTP).

Base

Reflection

Contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types

Base

Resources

Provides classes and interfaces that allow developers to create, store, and manage various culture-specific resources used in an application.

Base

Runtime

Includes a broad set of third-level namespaces such as a Win32 interoperability layer, remoting, and object serialization.

Base

Security

Provides the underlying structure of the CLR security system, including base classes for permissions.

Base

ServiceProcess

Provides classes that allow you to implement, install, and control Windows service applications.

Application model

Text

Contains classes representing ASCII, Unicode, UTF-7, and UTF-8 character encodings; abstract base classes for converting blocks of characters to and from blocks of bytes; and a helper class that manipulates and formats String objects without creating intermediate instances of String.

Base

Threading

Provides classes and interfaces that enable multithreaded programming.

Base

Timers

Provides classes that allow you to raise an event on a specified interval.

Base

Web

Supplies classes and interfaces that enable the browser/ server communication used by ASP.NET.

Application model

Windows.Forms

Contains classes for creating Windows-based applications that take full advantage of the rich user interface features available in the Microsoft Windows operating system.

Application model

Xml

Provides standards-based support for processing XML.

Base

...

Many more in newer version.

...

 

* Based on the .NET Framework Class Library overview at msdn.microsoft.com. As you can tell from Table 1-1, the .NET Framework contains a broad set of functionality.

 

Application Model–Specific Classes

 

Think of an application model as a set of classes that define a manner in which an application operates. They define the general structure of the application. The following sections provide a brief look at the application models in the .NET Framework.

 

ASP.NET

 

ASP.NET, contained in the System.Web namespace, is designed to make it easy for developers to build real-world Web applications. It offers a rich application environment for building server-side HTTP applications that dynamically create content and send it to a client, such as a browser or a mobile device.

Using ASP.NET and the base class libraries in the framework designed for distributed application development, you can build applications that gather data from multiple back-end or remote sources and present it to the browser in an aggregated format. The following example demonstrates an ASP.NET page that calls an XML-based Web service using the .NET Framework.

This weather service sample application is extremely simple. It takes a postal code as an input parameter and returns the forecast. In this case, it always returns sunny unless the zip code supplied is 11111, in which case it will say rainy, as shown in Figure 1-2. The following code listing shows the code for this application:

 

Visual Basic .NET: Weather Service Sample Application

 

The steps:

 

Create a new ASP.NET Web Service Application project.

 

ASP new project creation

 

ASP .NET web service application new project

 

Add the following code.

 

Imports System.Web.Services

Imports System.Web.Services.Protocols

Imports System.ComponentModel

 

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

' <System.Web.Script.Services.ScriptService()> _

<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _

<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

<ToolboxItem(False)> _

Public Class Service1 ' This class exposes a Web Service method that

    ' takes a zip code and returns the forecast

    ' for that area.

    Inherits System.Web.Services.WebService

    ' The logic for GetTodaysForecast is limited for the

    ' purposes of this example to check for

    ' zip = 11111 and return "rainy" if it matches,

    ' otherwise it will return "sunny".

    <WebMethod()> _

    Public Function GetTodaysForecast(ByVal zip As System.String) As System.String

        Dim forecast As String = "sunny"

        If zip = "11111" Then

            forecast = "rainy"

        End If

        Return forecast

    End Function

End Class

 

visual basic and asp codes in the editor

 

Build the project.

 

building the asp project using vidual studio 2008

 

Make sure there is no error.

 

Visual Studio 2008 Output window messages

Next, we add a web form.

 

Adding new item, web form into existing project

 

Adding a Visual basic web form into existing asp project

 

Add the following code.

 

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="WeatherServiceVB.WebForm1" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>A Dummy Weather Service</title>

</head>

<script language="VB" runat="server">

 

  Dim zip as String = "11111"

 

  Sub Submit_Click(sender As Object, e as EventArgs)

      Try

         zip = ZipCode.Text

      Catch ex As Exception

      ' exception ignored

      End Try

 

        Dim myService As New WeatherServiceVB.Service1()

        Result.Text = "Today's forecast is: " + myService.GetTodaysForecast(zip)

 

  End Sub

</script>

<body style="font: 10pt verdana">

  <h4>Weather Report </h4>

  <form id="Form1" runat="server">

  <div style="padding:15,15,15,15;background-color:Gray;width:300;border-color:black;border-width:1;border-style:solid">

    Zip Code: <br /><asp:TextBox id="ZipCode" Text="11111" runat="server"/><br />   

    <input type="submit" id="Add" value="Get Weather Report" OnServerClick="Submit_Click" runat="server" />

        <p />

    <asp:Label id="Result" runat="server"/>

  </div>

  </form>

</body>

</html>

 

Run the project.

 

Running an ASP project in visual studio without debugging

 

The following is a sample output.

 

ASP project in action in the Browser

 

Try key in different postcode and click the Get Weather Report button.

 

ASP project run in the Internet Browser

 

Figure 1-2: ASP.NET weather display page

 

The ASP.NET weather display page provides a mechanism for entering a postal code into a form and calling the weather service to retrieve and display the forecast, as shown in the following code:

 

 

 


 

< Chap 1 TOC: Intro To Windows Network Programming | Main | C# .NET + ASP .NET Sample >