Sunteți pe pagina 1din 170

Department of Information Technology

MIDDLEWARE TECHNOLOGIES Lab Manual for the Academic Year 2007-2008

III B.Tech

Guru Nanak Engineering College


Ibrahimpatnam, R R District 501 506 (A. P.)

In-charge Principal Prepared by:

HOD

Approved & Reviewed by:

Issued by:

w.e.f Date:

Guru Nanak Engineering College


Ibrahimpatnam, R R District 501 506 (A. P.)

Department of Information Technology Lab Manual for the Academic Year 2007-08 (In accordance with JNTU syllabus)
SUBJECT SUBJECT CODE SEMESTER STREAM INSTRUCTOR PROGRAMMERS : : : : : : MWT LAB IT (05409) III - II Information Technology S. SANTHI PRIYA

Head IT

-2-

Guru Nanak Engineering College


Ibrahimpatnam, R R District 501 506 (A. P.)

Suggestions from Principal :

Enhancement if any :

Comments :

-3-

INDEX S.No 1 2 3 4 Name of the Content Lab Objective Introduction About Lab LAB CODE List of Lab Exercises 4.1 Syllabus Programs (JNTU) Description about MWT Concepts Programs List References 7 8 166 PAGE NO. 1 2 4 5

5 6 7

-4-

Lab Objective:

The role of Middleware is to ease the task of designing, programming and managing distributed applications by providing a simple, consistent and integrated distributed programming environment. Essentially, Middleware is a distributed software layer, or platform which abstracts over the complexity and heterogeneity of the underlying distributed environment with its multitude of network technologies, machine architectures, operating systems and programming languages. Different Middleware platforms support different programming models. Perhaps the most popular model is object based Middleware in which applications are structured into (potentially distributed) objects that interact via location transparent method invocation.

-5-

INTRODUCTION ABOUT LAB There are 66 systems ( Compaq Presario ) installed in this Lab. Their configurations are as follows : Processor RAM Hard Disk Mouse Network Interface card Software 1 All systems are configured in DUAL BOOT mode i.e, Students can boot from Windows XP or Linux as per their lab requirement. This is very useful for students because they are familiar with different Operating Systems so that they can execute their programs in different programming environments. 2 Each student has a separate login for database access Oracle 9i client version is installed in all systems. On the server, account for each student has been created. This is very useful because students can save their work ( scenarios, pl/sql programs, data related projects ,etc) in their own accounts. Each student work is safe and secure from other students. 3 Latest Technologies like DOT NET and J2EE are installed in some systems. Before submitting their final project, they can start doing mini project from 2nd year onwards. 4 MASM ( Macro Assembler ) is installed in all the systems : : : : : AMD Athelon 1.67 GHz 256 MB 40 GB Optical Mouse Present

-6-

Students can execute their assembly language programs using MASM. MASM is very useful students because when they execute their programs they can see contents of Processor Registers and how each instruction is being executed in the CPU. 1 Rational Rose Software is installed in some systems Using this software, students can depict UML diagrams of their projects. 2 Software installed : C, C++, JDK1.5, MASM, OFFICE-XP, J2EE and DOT NET, Rational Rose. 3 Systems are provided for students in the 1:1 ratio. 4 Systems are assigned numbers and same system is allotted for students when they do the lab.

-7-

LAB CODE: 1. Students should report to the concerned labs as per time table schedule. 2. Students who turn up late to the labs will in no case be permited to do the program scheduled for the day. 3. After completion of the program , certification of the concerned staff in-charge in the observation book is necessary. 4. Students should bring a notebook of about 100 pages and should enter the reading/observations into the notebook while performing the experiment. 5. The record of observations along with the detailed experimental procedure of the experiment performed in the immediate last session should be submitted and certified by the staff ember in-charge. 6. Not more than three students in a group are permitted to perform the experiment on a setup. 7. The group-wise division made in the beginning should be adhered to and no mix up student among different groups will be permitted later. 8. The components required pertaining 9. When setup 10. to the experiment should be collected from stores in-charge after duly filling in the requisition form. the experiment is completed, students should disconnect the made by them, and should return all the

components/instruments taken for the purpose. Any damage of the equipment or burn-out of components will be viewed seriously either by putting penalty or by dismissing the total group of students from the lab for the semester/year. 11. 12. 13. Students should be present in the labs for the total scheduled duration. Students are required to prepare thoroughly to perform the experiment before coming to Laboratory. Procedure sheets/data sheets provided to the students groups should be maintained neatly and to be returned after the experiment.

-8-

Lab Programs Middleware Technologies Lab Programs List


Submission 1 1. Communication: Create a server that accepts the requests from client and client displays the server system information 2. File transfer: Create a server that asks for a password, then opens a file and sends the file over the network connection. Create a client that connects to this server, gives the appropriate password, then captures and saves the file. 3. Calculator: Create a remote server that implements a calculator with basic functionalities like addition, subtraction, division, multiplication and client, which uses the remote calculator. 4. Stockmarket: Create a remote stock server that accepts the company name and gives the share value. Stock client that retrieves the company share value and displays by giving the company name. 5. Phone book server: Create a remote phone book server that maintains names and phone numbers. Phone book client should provide a user interface that allows the user to scroll through entries, add a new entry, modify an existing entry and delete an existing entry. The client and the server should provide proper error handling.

Week 1

Week 2

Week 3

Week 4

Submission 2 Week 5 Introduction to C# 1. Working with callbacks and delegates in C# : Demonstrates the use of delegates, callbacks, and synchronous and asynchronous method invocation, including how Microsoft .NET Framework classes provide explicit asynchronous support using the BeginXXXX and EndXXXX naming conventions and how you can make use of this support in your own code. 2. Code access security with C# : Demonstrates the use of .NET Framework Code Access Security, in which code can have permissions independent of the person executing the code.

Week 6

Week 7

Submission 3 3. Creating a COM+ component with C# : Demonstrates how to create a COM+ component, that takes advantage of Transaction management service within COM+, then assign a strong name to the assembly, register the assembly in the Global Assembly Cache, and register the component with COM+.

Week 8

-9-

Week 9

Week 10

4. Creating a Windows Service with C# : Demonstrates how to create a Microsoft Windows Service that uses a File System Watcher object to monitor a specific directory for changes in files. 5. Read and Write Images to a SQL Server Database with C# : Demonstrates how to upload images into SQL Server by using standard HTML upload methods and then insert each image as a byte array into SQL Server.

Submission-4 Week - 11 6. Interacting with a Windows Service with C# : Develop a sample application that launches a Windows Form to allow the user to interact and manipulate the IIS Admin service on the local machine. The application should work by placing an icon in the System Tray. 7. Partitioning an Application into Multiple Assemblies with C# : Understand why it can be beneficial to create separate modules for an application download, and then demonstrates how to do so with C#. 8. Using System Printing in C# Applications : Develop a sample application that shows how to print a formatted report from sample data stored in an XML file using the PrintDocument class in the System.Drawing.Printing namespace. Also illustrates the user selection of a destination printer and multiple print fonts. 9. Using Reflection in C# : Demonstrate how to gather information on various types included in any assembly by using the System.Reflection namespace and some main .NET base classes. 10. Sending Mail with SmtpMail and C# : Uses a simple Web form to demonstrate how to use the SmtpMail class in the .NET Framework. 11. Perform String Manipulation with the String Builder and String Classes and C# : Demonstrates some basic string manipulation using both the String Builder and String classes. 12 . Application Configuration Using Configuration Files and the Registry Using C# : A sample application that demonstrates methods of storing application settings by making use of both the system registry and application configuration files. Implements a custom configuration section to show how you can tailor these files to the specific needs of a particular application. 13. Using the System.Net.WebClient to Retrieve or Upload Data with C# : Demonstrate how to create a Windows Form that can use HTTP to download and save a resource from a specified URI, upload a resource to a specified URI, or read and write data through a stream object. 14. Web Services Security with C# : Examines how to use IIS to perform user authentication so that no changes to the Web Service are required in order to provide superior security. 15. Reading and Writing XML Documents with the XmlTextReader and XmlTextWriter Class and C# : Demonstrate how to retrieve information from an existing XML document and how to create a new XML document of memory management.

Week - 12

Week - 13

Week 14

Week 15

- 10 -

Description about MWT Concepts:


In the computer industry, middleware is a general term for any programming that serves to "glue together" or mediate between two separate and often already existing programs. A common application of middleware is to allow programs written for access to a particular database to access other databases. Middleware, or "glue", is a layer of software between the network and the applications. This software provides services such as identification, authentication, authorization, directories, and security. In today's Internet, applications usually have to provide these services themselves, which leads to competing and incompatible standards. By promoting standardization and interoperability, middleware will make advanced network applications much easier to use. Typically, middleware programs provide messaging services so that different applications can communicate. The systematic tying together of disparate applications, often through the use of middleware, is known as enterprise application integration (EAI).

- 11 -

AIM
Create a server that accepts the requests from client and client displays the server system information

PROGRAM
import java.io.*; import java.net.*; public class EchoClient { public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket("taranis", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: taranis."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: taranis."); System.exit(1); } BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } out.close(); in.close(); stdIn.close(); echoSocket.close(); } }

- 12 -

AIM
Create a server that asks for a password, then opens a file and sends the file over the network connection. Create a client that connects to this server, gives the appropriate password, then captures and saves the file.

PROGRAM
import import import import java.io.*; java.util.*; org.omg.CosNaming.*; org.omg.CORBA.*;

public class FileClient { public static void main(String argv[]) { try { // create and initialize the ORB ORB orb = ORB.init(argv, null); // get the root naming context org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); NamingContext ncRef = NamingContextHelper.narrow(objRef); NameComponent nc = new NameComponent("FileTransfer", " "); // Resolve the object reference in naming NameComponent path[] = {nc}; FileInterfaceOperations fileRef = FileInterfaceHelper.narrow(ncRef.resolve(path)); if(argv.length < 1) { System.out.println("Usage: java FileClient filename"); } // save the file File file = new File(argv[0]); byte data[] = fileRef.downloadFile(argv[0]); BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(argv[0])); output.write(data, 0, data.length); output.flush(); output.close(); } catch(Exception e) { System.out.println("FileClient Error: " + e.getMessage()); e.printStackTrace(); }

} }

- 13 -

AIM
Create a remote server that implements a calculator with basic functionalities like addition, subtraction, division, multiplication and client, which uses the remote calculator.

PROGRAM Interfaces

The first step is to write and compile the Java code for the service interface. The Calculator interface defines all of the remote features offered by the service:
public interface Calculator extends java.rmi.Remote { public long add(long a, long b) throws java.rmi.RemoteException; public long sub(long a, long b) throws java.rmi.RemoteException; public long mul(long a, long b) throws java.rmi.RemoteException; public long div(long a, long b) throws java.rmi.RemoteException;

- 14 -

Implementation Next, you write the implementation for the remote service. This is the CalculatorImpl class:
public class CalculatorImpl extends java.rmi.server.UnicastRemoteObject implements Calculator { // Implementations must have an //explicit constructor // in order to declare the //RemoteException exception public CalculatorImpl() throws java.rmi.RemoteException { super(); } public long add(long a, long b) throws java.rmi.RemoteException { return a + b; } public long sub(long a, long b) throws java.rmi.RemoteException { return a - b; } public long mul(long a, long b) throws java.rmi.RemoteException { return a * b; } public long div(long a, long b) throws java.rmi.RemoteException { return a / b; } }

- 15 -

Host Server Remote RMI services must be hosted in a server process. The class CalculatorServer is a very simple server that provides the bare essentials for hosting.
import java.rmi.Naming; public class CalculatorServer { public CalculatorServer() { try { Calculator c = new CalculatorImpl(); Naming.rebind("rmi://localhost:1099/CalculatorService", c); } catch (Exception e) { System.out.println("Trouble: " + e); } } public static void main(String args[]) { new CalculatorServer(); }

PROGRAM
import import import import java.rmi.Naming; java.rmi.RemoteException; java.net.MalformedURLException; java.rmi.NotBoundException;

public class CalculatorClient { public static void main(String[] args) { try { Calculator c = (Calculator) Naming.lookup( "rmi://localhost /CalculatorService"); System.out.println( c.sub(4, 3) ); System.out.println( c.add(4, 5) ); System.out.println( c.mul(3, 6) ); System.out.println( c.div(9, 3) ); }

- 16 -

catch (MalformedURLException murle) { System.out.println(); System.out.println( "MalformedURLException"); System.out.println(murle); } catch (RemoteException re) { System.out.println(); System.out.println( "RemoteException"); System.out.println(re); } catch (NotBoundException nbe) { System.out.println(); System.out.println( "NotBoundException"); System.out.println(nbe); } catch ( java.lang.ArithmeticException ae) { System.out.println(); System.out.println( "java.lang.ArithmeticException"); System.out.println(ae); } } }

- 17 -

AIM
Create a remote stock server that accepts the company name and gives the share value. Stock client that retrieves the company share value and displays by giving the company name.

PROGRAM
import java.util.Random; /** * A Stock object is used to encapsulate stock update information * that is sent in an update notification. Note that the class * implements the java.io.Serializable interface in order to be * passed as an argument or return value in RMI. */ public class Stock implements java.io.Serializable { String symbol; float current; private static Random random = new Random(); private final static float MAX_VALUE = 67; /** * Constructs a stock with the given name with a initial random * stock price.*/ public Stock(String name) { symbol = name; if (symbol.equals("Sun")) { current = 30.0f; } else { // generate random stock price between 20 and 60 current = (float)(Math.abs(random.nextInt()) % 40 + 20); } } /** * Added 2/28/98 Rew */ public String toString() { return symbol + " " + current; }

- 18 -

Stock Continued
/** * Update the stock price (generates a random change). */ public float update() { float change = ((float)(random.nextGaussian() * 1.0)); if (symbol.equals("Sun") && current < MAX_VALUE - 5) change = Math.abs(change); // what did you expect? float newCurrent = current + change; // don't allow stock price to step outside range if (newCurrent < 0 || newCurrent > MAX_VALUE) change = 0; current += change; return change; }

StockNotify
import java.rmi.*; import java.util.Date; /** * The StockNotify remote interface is used to receive a stock * update. */ public interface StockNotify extends java.rmi.Remote { /** * Notification of stock updates for a particular time. * @param date the time of the stock update * @param stocks an array containing the stocks for which the * object has registered interest. * @exception RemoteException if a communication failure occurs */ void update (Date date, Stock[] stocks) throws RemoteException; }

- 19 -

StockWatch
import java.rmi.*; /** * The StockWatch remote interface is used to register interest in * receiving stock updates. */ public interface StockWatch extends java.rmi.Remote { /** * Request notification of stock updates. * @param stock the stock name * @param obj the remote object to be notified * @return the latest update of the stock * @exception StockNotFoundException if stock is not known * @exception RemoteException if some communication failure occurs */ Stock watch(String stock, StockNotify obj) throws StockNotFoundException, RemoteException; /** * Cancel request for stock updates for a particular stock. * @param stock the stock name * @param obj the remote object canceling the notification * @exception RemoteException if some communication failure occurs */ void cancel(String stock, StockNotify obj) throws RemoteException; /** * Returns an array of stock update information for the stocks * already registered by the remote object. * @param obj the remote object * @return the list of stocks, or null if obj is not watching any * stocks * @exception RemoteException if some communication failure occurs */ Stock[] list(StockNotify obj) throws RemoteException; /** * Cancel all requests for stock updates for the remote object. * @param obj the remote object canceling the request * @exception RemoteException if some communication failure occurs */ void cancelAll(StockNotify obj) throws RemoteException; }

- 20 -

StockNotFoundException
/* StockNotFoundException is thrown if a stock, for which notifications * of updates are requested, is not known. */ public class StockNotFoundException extends Exception { public StockNotFoundException(String s) { super(s); } }

StockServer
import java.rmi.*; import java.rmi.server.*; import java.rmi.registry.*; import java.util.*; import sdsu.util.*; public class StockServer extends UnicastRemoteObject implements StockWatch, Runnable { /** table that maps StockNotify objects to a vector of stocks */ private Hashtable notifyTable = new Hashtable(); /** table that maps stock names to stock update info */ private Hashtable stockTable = new Hashtable(); /** thread for notifying watchers of stock updates */ private Thread notifier = null; private static String name[] = { "Sun", "HP", "Microsoft", "DEC","Novell", "IBM","Apple","Netscape","Borland","SGI"}; /** * Construct the stock server * @exception RemoteException if remote object cannot be exported public StockServer() throws RemoteException { for (int i=0; i<name.length; i++) { stockTable.put(name[i], new Stock(name[i])); } }

*/

StockServer Continued

- 21 -

/** * Request notification of stock updates. * @param stock the stock name * @param obj the remote object to be notified * @return the latest update of the stock * @exception StockNotFoundException if stock is not known */ public synchronized Stock watch (String stock, StockNotify obj) throws StockNotFoundException { System.out.println("StockServer.watch: " + stock ); if (!stockTable.containsKey(stock)) throw new StockNotFoundException(stock); Vector stocks = (Vector)notifyTable.get(obj); // register intereted party... if (stocks == null) { stocks = new Vector(); notifyTable.put(obj, stocks); } // add stock to list if (!stocks.contains(stock)) { stocks.addElement(stock); } // start thread to notify watchers... if (notifier == null) { notifier = new Thread(this, "StockNotifier"); notifier.start(); } return (Stock)stockTable.get(stock); }

- 22 -

StockServer Continued
/** * Cancel request for stock updates for a particular stock. * @param stock the stock name * @param obj the remote object canceling the notification */ public void cancel(String stock, StockNotify obj) { Vector stocks = (Vector)notifyTable.get(obj); stocks.removeElement(stock); } /** * Returns an array of stock update information for the stocks * already registered by the remote object. * @param obj the remote object * @return the list of stocks, or null if obj is not watching any * stocks * @exception RemoteException if some communication failure occurs */ public Stock[] list(StockNotify obj) { Vector stocks = (Vector)notifyTable.get(obj); Stock[] stockList = null; if (stocks != null) { Enumeration enum = stocks.elements(); stockList = new Stock[stocks.size()]; int i=0; // collect updates to the stocks this watcher is // interested in while (enum.hasMoreElements()) { String stockname = (String)enum.nextElement(); stockList[i++] = (Stock)stockTable.get(stockname); } } return stockList; }

- 23 -

StockServer Continued
/** * Cancel all requests for stock updates for the remote object. * @param obj the remote object canceling the request * @exception RemoteException if some communication failure occurs */ public synchronized void cancelAll(StockNotify obj) { notifyTable.remove(obj); if (notifyTable.isEmpty()) { Thread thread = notifier; // in case current thread is notifier notifier = null; thread.stop(); } } /** * Private method to generate random stock updates */ private void generateUpdates() { Enumeration enum = stockTable.elements(); while (enum.hasMoreElements()) { Stock stock = (Stock)enum.nextElement(); stock.update(); } }

- 24 -

StockServer Continued
/** * The run method (called from the notifier thread) sends out stock * updates periodically to those remote objects that have * registered interest in being notified. */ public void run() { while (true) { try { // wait for a few seconds between updates Thread.currentThread().sleep(3000); } catch (InterruptedException e) { } Date date = new Date(); // update stocks in table generateUpdates(); // enumerate through each watcher... Enumeration enum = notifyTable.keys(); while (enum.hasMoreElements()) { StockNotify obj = (StockNotify)enum.nextElement(); Stock[] stockList = list(obj); if (stockList != null) { // send update try { System.out.println( "StockServer.run: sending update " + date); obj.update(date, stockList); } catch (RemoteException e) { // can't reach watcher; cancel notification request System.out.println("StockServer.run: exception"); e.printStackTrace(); cancelAll(obj); } } }

} }

- 25 -

StockServer Continued
/** * Start up the stock server; also creates a registry so that the * StockApplet can lookup the server. */ public static void main(String args[]) { // Create and install the security manager System.setSecurityManager(new RMISecurityManager()); try { // Some changes from Sun code ProgramProperties flags = new ProgramProperties( args ); int port = flags.getInt( "p", 1099 ); String serverLabel = "StockServer"; System.out.println( "StockServer.main: creating registry"); Registry localRegistry = LocateRegistry.createRegistry(port);; System.out.println("StockServer.main: creating server"); StockServer server = new StockServer(); System.out.println("StockServer.main: binding server "); localRegistry.rebind( serverLabel, server); System.out.println("StockServer.main: done"); } catch (Exception e) { System.out.println( "StockServer.main: an exception occurred: " + e.getMessage()); e.printStackTrace(); }

} } //end class

- 26 -

StockViewer
import java.io.*; import java.util.*; import java.rmi.*; import java.rmi.server.*; import sdsu.util.List; import sdsu.util.ProgramProperties; public class StockViewer implements StockNotify, Serializable { /** reference to StockWatch server */ private StockWatch stockServer = null; private PrintWriter out; public StockViewer( StockWatch stockServer, Writer output ) throws RemoteException { this.stockServer = stockServer; out = new PrintWriter( output); UnicastRemoteObject.exportObject(this); } public boolean watch( String stock ) { try { stockServer.watch( stock, this ); } catch (StockNotFoundException badName ) { return false; } catch (RemoteException transmissionError) { return false; } return true; }

- 27 -

StockViewer Continued
public boolean cancel( String stock ) { try { stockServer.cancel( stock, this ); } catch (RemoteException transmissionError) { return false; } return true; } public void update( Date stockUpdateTime, Stock[] stockList ) { System.err.println( "Viewer update" ); if ( stockList.length <=0 ) return; out.println( "The following stocks were updated on: " + stockUpdateTime ); for ( int k=0; k < stockList.length; k++ ) { out.println( stockList[k] ); } out.flush(); }

- 28 -

StockViewer Continued
public static void main( String[] args ) { try { String serverAddress = getServerAddress( args); StockWatch server = (StockWatch) Naming.lookup( serverAddress ); StockViewer aViewer = new StockViewer( server, new PrintWriter( System.out )); Enumeration stocks = getStockList( args ); while ( stocks.hasMoreElements() ) aViewer.watch( (String) stocks.nextElement() ); } catch ( Exception error) { error.printStackTrace(); } } private static Enumeration getStockList( String args[] ) throws IOException { ProgramProperties flags = new ProgramProperties( args ); String stockNames = flags.getString( "s" ); List stockList = new List(); stockList.fromString( stockNames ); return stockList.elements(); }

StockViewer Continued
private static String getServerAddress( String args[] ) throws IOException { ProgramProperties flags = new ProgramProperties( args ); String host = flags.getString( "h" ); String port = flags.getString( "p", "1099" ); return "rmi://" + host + ":" + port + "/StockServer"; }

- 29 -

AIM
Create a remote phone book server that maintains names and phone numbers. Phone book client should provide a user interface that allows the user to scroll through entries, add a new entry, modify an existing entry and delete an existing entry. The client and the server should provide proper error handling.

PROGRAM
RMI supports Java objects communicating via their methods, regardless of where the objects are located. The first step in creating a class to be accessed remotely is to define an interface describing the methods that are available remotely. The interface that will be made available remotely is:
// Lookup.java import java.rmi.*; public interface Lookup extends Remote { public String findInfo( String info) throws RemoteException; } java.rmi.Remote is an empty marker interface that indicates that an

object is remote, so class objects implementing Lookup are marked as being remote references. All the methods in a remote interface must declare that they can throw an exception of type java.rmi.RemoteException--which gets thrown whenever a remote method invocation fails. Develop the Server Code Once you specify the remote object definition via an interface, the next step is to develop the server code. The server implements the object interface and creates instances of the object to be shared remotely.

- 30 -

For this application, the server code looks like this:


// LookupServer.java import import import import java.io.*; java.util.*; java.rmi.*; java.rmi.server.*;

public class LookupServer extends UnicastRemoteObject plements Lookup { private Vector save = new Vector(); public LookupServer(String db) throws RemoteException { try { FileReader fr = new FileReader(db); BufferedReader br = new BufferedReader(fr); String s = null; while ((s = br.readLine()) != null) save.addElement(s); fr.close(); } catch (Throwable e) { System.err.println("exception"); System.exit(1); } } public String findInfo(String info) { if (info == null) return null; info = info.toLowerCase(); int n = save.size(); for (int i = 0; i < n; i++) { String dbs = (String)save.elementAt(i); if (dbs.toLowerCase().indexOf(info) != -1) return dbs; } } return null;

public static void main(String args[]) {

- 31 -

try { RMISecurityManager security = new RMISecurityManager(); System.setSecurityManager(security); String db = args[0]; LookupServer server = new LookupServer(db); Naming.rebind("LookupServer", server); System.err.println("LookupServer ready..."); } catch (Throwable e) { System.err.println("exception: " + e); System.exit(1); } } }

The server reads in a text database of phone numbers and names and stores them internally. findInfo then does a caseless lookup of a given name or number in the database. A simple example of the database is:
Smith, Joan 204-9987 Jones, Milton 898-9749 Brown, Gertrude 598-1265

- 32 -

Start the Server You start the server with:


java LookupServer database_name

For example, if you had a set of names and phone numbers in C:\PHONE.TXT, you would use:
java LookupServer C:\PHONE.TXT

Start the Client You start the client with:


java LookupClient smith

"smith" is a name or number to be looked up in the central database.

- 33 -

AIM
Demonstrates the use of delegates, callbacks, and synchronous and asynchronous method invocation, including how Microsoft .NET Framework classes provide explicit asynchronous support using the BeginXXXX and EndXXXX naming conventions and how you can make use of this support in your own code.

PROGRAM
Assembly Information
using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. //

- 34 -

// Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")]

Callback Option
using System; namespace CallbackSample { /// <summary> /// The CallbackOption enumeration defines the demonstrations included in this sample. /// </summary> internal enum CallbackOption { UseInterface = 1, UseSynchronousDelegate, UseAsynchronousDelegateWithWait, UseAsynchronousDelegateWithCallback, UseFrameworkSuppliedAsynchronousMethodWithWait, UseFrameworkSuppliedAsynchronousMethodWithCallback, UseFrameworkSuppliedSynchronousMethod } }

- 35 -

IResolve Callback
using System; using System.Net; namespace CallbackSample { /// <summary> /// The IResolveCallback interface defines a callback method to use when the called /// object completes its work. /// </summary> public interface IResolveCallback { /// <summary> /// This method will be called when the callback option is UseInterface /// and the host has been resolved. /// </summary> /// <param name="hostInformation">The host information returned to the caller.</param> void HostResolved(IPHostEntry hostInformation); } }

Resolve Callback Delegate


using System; using System.Net; namespace CallbackSample { /// <summary> /// The ResolveCallbackDelegate is used to wrap calls having this signature. /// </summary> public delegate void ResolveCallbackDelegate(IPHostEntry hostInformation); }

- 36 -

Resolve Console
using System; using System.Net; namespace CallbackSample { /// <summary> /// The ResolveConsole class demonstrates various types of callbacks and /// asynchronous calls. /// </summary> internal sealed class ResolveConsole : IResolveCallback { private bool resultsDisplayed = false; // This class can only be created by the Main static method. private ResolveConsole() { } /// <summary> /// This method implements the IResolveCallback interface and allows /// a called object to inform the caller of any results. /// </summary> /// <param name="hostInformation">The host information resulting from /// a DNS resolution</param> public void HostResolved(IPHostEntry hostInformation) { DisplayResults(hostInformation); } /// <summary> /// This method is called by the Main static method to perform the /// DNS resolutions requested by the user demonstrating the callback /// options specified. /// </summary> /// <param name="host">An IP address or host name to resolve</param> /// <param name="methodToUse">The callback option to demonstrate</param> private void DoResolve(string host, CallbackOption methodToUse) { resultsDisplayed = false; IPHostEntry hostInformation = null; Resolver resolver = new Resolver(); switch (methodToUse)

- 37 -

case CallbackOption.UseInterface: { Console.WriteLine("Resolving..."); // By passing an interface that this object supports, the called // method can notify this object of the results try { resolver.Resolve(host, (IResolveCallback)this); } catch (System.Net.Sockets.SocketException) { Console.WriteLine("Bad host name (SocketException)"); resultsDisplayed = true; } break; } case CallbackOption.UseSynchronousDelegate: { Console.WriteLine("Resolving...");

// By passing a delegate wrapping the HostResolved method, the // called object can notify this object of the result in a synchronous // or asynchronous manner, depending on how it is constructed. ResolveCallbackDelegate cb = new ResolveCallbackDelegate(HostResolved); resolver.Resolve(host, cb); break; } case CallbackOption.UseAsynchronousDelegateWithWait: { Console.Write("Resolving");

// By wrapping a synchronous long-running method (DNS resolution) // with a delegate, this object can call that method // asynchronously and show progress (in this case) or do other // work while it executes. In this scenario, it waits on the // result using the WaitHandle provided by IAsyncResult. ResolveDelegate synchMethod = new ResolveDelegate(resolver.Resolve); // The BeginInvoke method is supplied by the C# compiler... // The IntelliSense engine does not display this at design time.

- 38 -

IAsyncResult ar = synchMethod.BeginInvoke(host, null, null); // Write another period for each 100ms interval of wait time. while (!ar.AsyncWaitHandle.WaitOne(100, false)) Console.Write("."); Console.WriteLine(); // If any exceptions are raised by the called method, they won't // be thrown until the results are obtained. try { // The EndInvoke method is supplied by the C# compiler... // The IntelliSense engine does not display this at design time. hostInformation = synchMethod.EndInvoke(ar); DisplayResults(hostInformation); } catch (System.Net.Sockets.SocketException) { Console.WriteLine("Bad host name (SocketException)"); resultsDisplayed = true; } break; } case CallbackOption.UseAsynchronousDelegateWithCallback: { Console.WriteLine("Resolving...");

ResolveDelegate synchMethod = new ResolveDelegate(resolver.Resolve); AsyncCallback cb = new AsyncCallback(this.AsyncCustomCallbackMethod); // Begin the method's execution...when finished, the callback will be // called. IAsyncResult ar = synchMethod.BeginInvoke(host, cb, null); break; } case CallbackOption.UseFrameworkSuppliedSynchronousMethod: { Console.WriteLine("Resolving..."); // This calls the synchronous version of a framework-defined class // that also explicitly supports asynchronous invocation. try {

- 39 -

hostInformation = Dns.Resolve(host); DisplayResults(hostInformation); } catch (System.Net.Sockets.SocketException) { Console.WriteLine("Bad host name (SocketException)"); resultsDisplayed = true; } break;

case CallbackOption.UseFrameworkSuppliedAsynchronousMethodWithWait: { Console.Write("Resolving"); IAsyncResult ar = Dns.BeginResolve(host, null, null); // Write another period for each 100ms interval of wait time. while (!ar.AsyncWaitHandle.WaitOne(100, false)) Console.Write("."); Console.WriteLine(); // If any exceptions are raised by the called method, they won't // be thrown until the results are obtained. try { hostInformation = Dns.EndResolve(ar); DisplayResults(hostInformation); } catch (System.Net.Sockets.SocketException) { Console.WriteLine("Bad host name (SocketException)"); resultsDisplayed = true; } break;

case CallbackOption.UseFrameworkSuppliedAsynchronousMethodWithCallback: { Console.WriteLine("Resolving...");

AsyncCallback cb = new AsyncCallback(this.AsyncFrameworkCallbackMethod); // Begin the call...when it is finished, the callback method will be

- 40 -

// called. IAsyncResult ar = Dns.BeginResolve(host, cb, null); break;

default: Console.WriteLine("Not Implemented Yet"); break; } // If this method ends now, there is no guarantee that the host information // will be displayed before the next prompt to the user for more hosts to // resolve is shown. In order to force the wait, put the thread to sleep // for 100ms intervals until the output has been displayed. while (!resultsDisplayed) { // For the synchronous options, this will never get executed // because the results will have been displayed before execution // reaches this point. System.Threading.Thread.Sleep(100); } } private void AsyncFrameworkCallbackMethod(IAsyncResult ar) { // If any exceptions are raised by the called method, they won't // be thrown until the results are obtained. try { IPHostEntry hostInformation = Dns.EndResolve(ar); DisplayResults(hostInformation); } catch (System.Net.Sockets.SocketException) { Console.WriteLine("Bad host name (SocketException)"); resultsDisplayed = true; } } [System.Runtime.Remoting.Messaging.OneWay()] private void AsyncCustomCallbackMethod(IAsyncResult ar) { // If any exceptions are raised by the called method, they won't // be thrown until the results are obtained. try { // Unwrap the delegate so that the EndInvoke method can be called.

- 41 -

ResolveDelegate synchMethod = (ResolveDelegate) ((System.Runtime.Remoting.Messaging.AsyncResult)ar).AsyncDelegate; IPHostEntry hostInformation = synchMethod.EndInvoke(ar); DisplayResults(hostInformation); } catch (System.Net.Sockets.SocketException) { Console.WriteLine("Bad host name (SocketException)"); resultsDisplayed = true; } } /// <summary> /// Display the host information from an IPHostEntry object /// </summary> /// <param name="hostInformation">An IPHostEntry object containing host information</param> private void DisplayResults(IPHostEntry hostInformation) { Console.WriteLine("Host Information:\nName: \"{0}\"", hostInformation.HostName); if (hostInformation.Aliases.Length > 0) { Console.WriteLine("Aliases Found:"); foreach (string alias in hostInformation.Aliases) Console.WriteLine(" {0}", alias); } if (hostInformation.AddressList.Length > 0) { Console.WriteLine("IP Addresses:"); foreach (IPAddress ipAddress in hostInformation.AddressList) Console.WriteLine(" {0}", ipAddress.ToString()); } // Set the resultsDisplayed value. resultsDisplayed = true; } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { ResolveConsole app = new ResolveConsole(); string userInput; do {

- 42 -

Console.WriteLine("Please enter an IP address or host name to " + "resolve, or the letter 'x' to quit."); userInput = Console.ReadLine().ToLower().Trim(); // If the user wants to quit, then exit the main loop. if (userInput == "x") break; // Validate the user input, and reprompt the user if invalid. UriHostNameType hostType = Uri.CheckHostName(userInput); if (hostType == UriHostNameType.Dns || hostType == UriHostNameType.IPv4 || hostType == UriHostNameType.IPv6) { string host = userInput; // Prompt the user for the method to use when resolving the host. // The methods supported are defined in the CallbackOption enumeration. object enumValue; do { // First, show the user what valid options exist. string[] names = Enum.GetNames(typeof(CallbackOption)); int[] values = (int[])Enum.GetValues(typeof(CallbackOption)); Console.WriteLine("Valid Options Are:"); for (int index = 0; index < values.Length; index++) { Console.WriteLine("{0,2} = {1}", values[index], names[index]); } // end option enumeration (for loop) // Prompt the user Console.Write("Please indicate the method you would like " + "to use to receive results: "); userInput = Console.ReadLine().Trim(); // Cast to an int value, if possible...otherwise retain string input. try { enumValue = int.Parse(userInput); } // end try catch (Exception) { enumValue = userInput; } // end catch // Validate the user input and reprompt if invalid.

- 43 -

} while (!Enum.IsDefined(typeof(CallbackOption), enumValue)); // end option loop // Parse the input to an entry in the CallbackOption enumeration. CallbackOption methodToUse = (CallbackOption)Enum.Parse( typeof(CallbackOption), userInput, true ); app.DoResolve(host, methodToUse); } // end valid host entered. else { Console.WriteLine("The IP address or host name you entered was " + "formatted incorrectly, please try again."); } // end invalid host entered. // Continue looping until the user wants to quit. } while (true); // end primary loop. app = null; } // end Main method } // end class } // end namespace

Resolve Delegates
using System; using System.Net; namespace CallbackSample { /// <summary> /// The ResolveDelegate is used to wrap calls to methods having this signature. /// </summary> internal delegate IPHostEntry ResolveDelegate(string host); }

- 44 -

Resolver
using System; using System.Net; namespace CallbackSample { /// <summary> /// The Resolver class supplies some synchronous methods to do DNS resolution /// with (this wraps the Dns.Resolve method defined by the framework, but any /// long-running operation will suffice). Some of these methods accept a /// callback interface or delegate as a parameter to inform the caller when /// the operation is complete. /// </summary> internal sealed class Resolver { /// <summary> /// Resolve an IP address or host name, and return the result synchronously /// through the interface provided. /// </summary> /// <param name="host">The IP address or host name to resolve</param> /// <param name="callbackInterface">The interface defining the callback method</param> internal void Resolve(string host, IResolveCallback callbackInterface) { // This performs a long-running operation (DNS resolution) and // returns the result through the interface accepted as a parameter. callbackInterface.HostResolved(Dns.Resolve(host)); } /// <summary> /// Resolve an IP address or host name, and return the result synchronously /// through the delegate passed in by the caller. /// </summary> /// <param name="host">The IP address or host name to resolve</param> /// <param name="callbackDelegate">The delegate wrapping the callback method</param> internal void Resolve(string host, ResolveCallbackDelegate callbackDelegate) {

- 45 -

// This performs the same task as above, but instead of calling back // through an interface, a delegate is used to inform the caller of the // results. callbackDelegate(Dns.Resolve(host)); } /// <summary> /// Resolve an IP address or host name, and return the result synchronously. /// </summary> /// <param name="host">The IP address or host name to resolve</param> /// <returns>An IPHostEntry object containing information about the host</returns> internal IPHostEntry Resolve(string host) { // This simply forwards the request to a known long-running method // (DNS resolution). return Dns.Resolve(host); } } }

- 46 -

AIM
Demonstrates the use of .NET Framework Code Access Security, in which code can have permissions independent of the person executing the code.

PROGRAM ASSEMBLY INFORMATION


using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing.

- 47 -

// // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")]

- 48 -

FORM1
using using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data; System.IO;

namespace WindowsApplication27 { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Button CreateFileNoErrorHandling; private System.Windows.Forms.Button CreateFileWithErrorHandling; private System.Windows.Forms.StatusBar statusBar1; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); }

- 49 -

} base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.CreateFileNoErrorHandling = new System.Windows.Forms.Button(); this.CreateFileWithErrorHandling = new System.Windows.Forms.Button(); this.statusBar1 = new System.Windows.Forms.StatusBar(); this.SuspendLayout(); // // CreateFileNoErrorHandling // this.CreateFileNoErrorHandling.Location = new System.Drawing.Point(128, 48); this.CreateFileNoErrorHandling.Name = "CreateFileNoErrorHandling"; this.CreateFileNoErrorHandling.Size = new System.Drawing.Size(112, 23); this.CreateFileNoErrorHandling.TabIndex = 0; this.CreateFileNoErrorHandling.Text = "No Error Handling"; this.CreateFileNoErrorHandling.Click += new System.EventHandler(this.CreateFileNoErrorHandling_Click); // // CreateFileWithErrorHandling // this.CreateFileWithErrorHandling.Location = new System.Drawing.Point(304, 48); this.CreateFileWithErrorHandling.Name = "CreateFileWithErrorHandling"; this.CreateFileWithErrorHandling.Size = new System.Drawing.Size(112, 23); this.CreateFileWithErrorHandling.TabIndex = 1; this.CreateFileWithErrorHandling.Text = "With Error Handling"; this.CreateFileWithErrorHandling.Click += new System.EventHandler(this.CreateFileWithErrorHandling_Click); // // statusBar1 // this.statusBar1.Location = new System.Drawing.Point(0, 232); this.statusBar1.Name = "statusBar1"; this.statusBar1.Size = new System.Drawing.Size(608, 22); this.statusBar1.TabIndex = 2; // // Form1

- 50 -

// this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(608, 254); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.statusBar1, this.CreateFileWithErrorHandling, this.CreateFileNoErrorHandling}); this.Name = "Form1"; this.Text = "Code Access Security"; this.ResumeLayout(false); } #endregion /// <summary> /// This application attempts to create a file in the root of the C: drive. /// If it is downloaded via HTTP, this will fail. The first button fails /// ungracefully; the second button traps the error. /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } private void CreateFileNoErrorHandling_Click(object sender, System.EventArgs e) { /// <summary> /// This single line simply attempts to create a file called test.txt in /// the root of the C: drive. If this is run after the assembly has been /// downloaded with HTTP, it will fail and .NET will display a rather /// verbose error message. </summary> System.IO.File.Create("c:\\test1.txt"); statusBar1.Text = "File (test1.txt) Created Successfully"; } private void CreateFileWithErrorHandling_Click(object sender, System.EventArgs e) { try { /// <summary> /// This single line simply attempts to create a file called test.txt in /// the root of the C: drive. If this is run after the assembly has been /// downloaded with HTTP, it will generate an error, but the error will be /// caught and handled by the catch portion of the try...catch block. </summary> System.IO.File.Create("c:\\test2.txt");

- 51 -

statusBar1.Text = "File (test2.txt) Created Successfully"; } catch (Exception ex) { /// <summary> /// If there was an error creating the file, display that message to the user. /// While the message might not be too friendly, this does show that you have /// generated a trappable error. </summary> statusBar1.Text = "The following error occurred " + ex.Message + " creating file (test2.txt)"; } } } }

- 52 -

AIM
Demonstrates how to create a COM+ component, that takes advantage of Transaction management service within COM+, then assign a strong name to the assembly, register the assembly in the Global Assembly Cache, and register the component with COM+.

PROGRAM COMPlusClient ASSEMBLY INFORMATION:


using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the

- 53 -

// Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")]

- 54 -

CUSTOMER ORDERS:
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.EnterpriseServices; using COMPlusServicesExample; using System.Data; using System.Data.SqlClient; namespace COMPlus { /// <summary> /// Summary description for CustomerOrders. /// </summary> public class CustomerOrders : System.Windows.Forms.Form { private int m_OrderID; private string m_ProductName; private int m_Quantity; private int m_DetailRow; private System.Windows.Forms.ComboBox cboCustomers; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnGetCust; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button btnUpdate; private System.Windows.Forms.DataGrid dgOrders; private System.Windows.Forms.DataGrid dgOrderDetails; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public CustomerOrders() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // }

- 55 -

/// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.cboCustomers = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.btnGetCust = new System.Windows.Forms.Button(); this.dgOrders = new System.Windows.Forms.DataGrid(); this.label2 = new System.Windows.Forms.Label(); this.dgOrderDetails = new System.Windows.Forms.DataGrid(); this.btnUpdate = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.dgOrders)).BeginInit(); ((System.ComponentModel.ISupportInitialize) (this.dgOrderDetails)).BeginInit(); this.SuspendLayout(); // // cboCustomers // this.cboCustomers.Location = new System.Drawing.Point(112, 8); this.cboCustomers.Name = "cboCustomers"; this.cboCustomers.Size = new System.Drawing.Size(232, 21); this.cboCustomers.TabIndex = 0; // // label1 // this.label1.Location = new System.Drawing.Point(16, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(96, 23); this.label1.TabIndex = 1; this.label1.Text = "Select Customer:";

- 56 -

this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // btnGetCust // this.btnGetCust.Location = new System.Drawing.Point(360, 8); this.btnGetCust.Name = "btnGetCust"; this.btnGetCust.TabIndex = 2; this.btnGetCust.Text = "Get Orders"; this.btnGetCust.Click += new System.EventHandler(this.btnGetCust_Click); // // dgOrders // this.dgOrders.DataMember = ""; this.dgOrders.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dgOrders.Location = new System.Drawing.Point(16, 72); this.dgOrders.Name = "dgOrders"; this.dgOrders.Size = new System.Drawing.Size(424, 144); this.dgOrders.TabIndex = 3; this.dgOrders.MouseUp += new System.Windows.Forms.MouseEventHandler(this.dgOrders_MouseUp); // // label2 // this.label2.Location = new System.Drawing.Point(16, 56); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(100, 16); this.label2.TabIndex = 4; this.label2.Text = "Orders:"; // // dgOrderDetails // this.dgOrderDetails.DataMember = ""; this.dgOrderDetails.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dgOrderDetails.Location = new System.Drawing.Point(16, 248); this.dgOrderDetails.Name = "dgOrderDetails"; this.dgOrderDetails.Size = new System.Drawing.Size(424, 144); this.dgOrderDetails.TabIndex = 5; this.dgOrderDetails.MouseUp += new System.Windows.Forms.MouseEventHandler(this.dgOrderDetails_MouseUp); // // btnUpdate // this.btnUpdate.Location = new System.Drawing.Point(176, 416); this.btnUpdate.Name = "btnUpdate"; this.btnUpdate.Size = new System.Drawing.Size(88, 23); this.btnUpdate.TabIndex = 6;

- 57 -

this.btnUpdate.Text = "Update Details"; this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click); // // CustomerOrders // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(456, 464); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.btnUpdate, this.dgOrderDetails, this.label2, this.dgOrders, this.btnGetCust, this.label1, this.cboCustomers}); this.Name = "CustomerOrders"; this.Text = "Customer Orders"; this.Load += new System.EventHandler(this.CustomerOrders_Load); ((System.ComponentModel.ISupportInitialize)(this.dgOrders)).EndInit(); ((System.ComponentModel.ISupportInitialize) (this.dgOrderDetails)).EndInit(); this.ResumeLayout(false); } #endregion private void CustomerOrders_Load(object sender, System.EventArgs e) { //loads the form with the customer information. //create instance of CustomersDB class CustomersDB customerData = new CustomersDB(); //retrieve the Customers. DataSet datasetOrders = customerData.GetCustomers(); //create the dataview object. DataView dataviewOrders = new DataView(datasetOrders.Tables[0]); cboCustomers.DataSource = dataviewOrders; //set the display properties of the Customers combo box. cboCustomers.DisplayMember = dataviewOrders.Table.Columns["CompanyName"].ColumnName; cboCustomers.ValueMember = dataviewOrders.Table.Columns["CustomerID"].ColumnName; }

- 58 -

/// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new CustomerOrders()); } private void btnGetCust_Click(object sender, System.EventArgs e) { //get the customer id string customerID = this.cboCustomers.SelectedValue.ToString(); //create an instance of the CustomersDB class. CustomersDB customerData = new CustomersDB(); //get the orders for the selected customer. DataSet datasetOrders = customerData.GetOrders(customerID); //bind the dataset to the datagrid. dgOrders.SetDataBinding(datasetOrders, datasetOrders.Tables[0].TableName); } private void dgOrders_MouseUp(object sender, MouseEventArgs e) { //gets the row info when a user clicks inside the orders //datagrid. DataGrid dg = (DataGrid) sender; DataGrid.HitTestInfo hitinfo = dg.HitTest(e.X, e.Y); //get the order id from the datagrid. int OrderID = Convert.ToInt32(this.dgOrders[hitinfo.Row, 0].ToString()); m_OrderID = OrderID; //call the helper method to retrieve the //order details. FillOrderDetails(m_OrderID);

private void FillOrderDetails(int OrderID) { //create an instance of the CustomersDB class CustomersDB customer = new CustomersDB(); DataSet datasetOrders = customer.GetOrderDetails(OrderID); //bind the data set to the datagrid.

- 59 -

dgOrderDetails.SetDataBinding(datasetOrders, datasetOrders.Tables[0].TableName); } private void dgOrderDetails_MouseUp(object sender, MouseEventArgs e) { //gets the row info when a user clicks inside the orders //datagrid. DataGrid dg = (DataGrid) sender; DataGrid.HitTestInfo hitinfo = dg.HitTest(e.X, e.Y); //set the class variable. m_DetailRow = hitinfo.Row; string productName = this.dgOrderDetails[hitinfo.Row, 0].ToString(); //set the class variable. m_ProductName = productName; } private void btnUpdate_Click(object sender, EventArgs e) { //get the quantity from the quantity cell. int Quantity = Convert.ToInt32(this.dgOrderDetails[m_DetailRow,2].ToString()); m_Quantity = Quantity; //create an instance of the Customers class //to initiate the update. Customers customer = new Customers(); //call the Update method. //if the quantity is less than or equal to zero, then //the update will fail. bool updateIsSuccessful = customer.UpdateDetailQuantity(m_OrderID, m_ProductName, m_Quantity); string Message=""; if (updateIsSuccessful == true) { Message = "Operation Succeeded and Transaction was Committed!"; } else if (updateIsSuccessful == false) { Message = "Operation Failed and Transaction was Aborted!"; } //show the confirmation message box. MessageBox.Show(Message); FillOrderDetails(m_OrderID); } }}} }

- 60 -

CAMPLUS DOTNET
ASSEMBLY INFORMATION:
using System.Reflection; using System.Runtime.CompilerServices; using System.EnterpriseServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("COM+ Services Example")] [assembly: AssemblyDescription("This is an example for creating COM+ Serviced applications in .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("C#")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service

- 61 -

// Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("c:\\Components\\ComPlusKey.snk")] [assembly: AssemblyKeyName("")] //Here are attributes added to the assembly for the purposes of using COM+ [assembly: ApplicationActivation(ActivationOption.Server)] [assembly: ApplicationID("96D7999B-439B-4aea-9A06-DF8E3BE5CAB0")] [assembly: ApplicationName("COM Plus Services Example")] [assembly: Description("An example of creating a COM+ application from .NET")]

- 62 -

CAMPLUS SAMPLE:
using System; using System.Data; using System.Data.SqlClient; using System.EnterpriseServices; namespace COMPlusServicesExample { /// <summary> /// Summary description for CustomersDB. /// </summary> [Transaction(TransactionOption.Supported)] public class CustomersDB : ServicedComponent { //this class handles all data retrieval. //class constructor public CustomersDB() { } //method returns a connection object for the Northwind database. private SqlConnection CreateConnection() { SqlConnection databaseConnection = new SqlConnection("server=localhost;Trusted_Connection=false;uid=sa;pwd=;da tabase=Northwind"); return databaseConnection; } //gets a dataset with the customers public DataSet GetCustomers() { //grab the connection object SqlConnection currentConnection = CreateConnection(); //open the connection and create //the command object currentConnection.Open(); SqlCommand sqlCommandToExecute = new SqlCommand(); sqlCommandToExecute.Connection = currentConnection; //set the command type and provide //the command text sqlCommandToExecute.CommandType = CommandType.Text;

- 63 -

sqlCommandToExecute.CommandText = "Select * from Customers"; //create and fill the data adapter with the //command object. SqlDataAdapter dataadapterCustomer = new SqlDataAdapter(sqlCommandToExecute); //create the dataset DataSet datasetCustomer = new DataSet("dsCustomers"); //fill the data set with the results in //the data adapter dataadapterCustomer.Fill(datasetCustomer); //return the dataset return datasetCustomer; } //gets a dataset with the customer orders. public DataSet GetOrders(string CustomerID) { //grab the connection object SqlConnection currentConnection = CreateConnection(); //open the connection and create //the command object currentConnection.Open(); SqlCommand sqlCommandToExecute = new SqlCommand(); sqlCommandToExecute.Connection = currentConnection; //set the command type and provide //the command text sqlCommandToExecute.CommandType = CommandType.StoredProcedure; sqlCommandToExecute.CommandText = "CustOrdersOrders"; //add the parameters SqlParameter param1 = sqlCommandToExecute.Parameters.Add(new SqlParameter("@CustomerID", SqlDbType.NChar, 5)); param1.Value = CustomerID; //create and fill the data adapter with the //command object. SqlDataAdapter dataadapterCustomer = new SqlDataAdapter(sqlCommandToExecute); //create the dataset DataSet datasetCustomer = new DataSet("dsOrders"); //fill the data set with the results in //the data adapter dataadapterCustomer.Fill(datasetCustomer); //return the dataset

- 64 -

return datasetCustomer;

//gets a dataset with the order details. public DataSet GetOrderDetails(int OrderID) { //grab the connection object SqlConnection currentConnection = CreateConnection(); //open the connection and create //the command object currentConnection.Open(); SqlCommand sqlCommandToExecute = new SqlCommand(); sqlCommandToExecute.Connection = currentConnection; //set the command type and provide //the command text sqlCommandToExecute.CommandType = CommandType.StoredProcedure; sqlCommandToExecute.CommandText = "CustOrdersDetail"; //add the parameters SqlParameter param1 = sqlCommandToExecute.Parameters.Add(new SqlParameter("@OrderID", SqlDbType.Int, 4)); param1.Value = OrderID; //create and fill the data adapter with the //command object. SqlDataAdapter dataadapterCustomer = new SqlDataAdapter(sqlCommandToExecute); //create the dataset DataSet datasetCustomer = new DataSet("dsOrderDetails"); //fill the data set with the results in //the data adapter dataadapterCustomer.Fill(datasetCustomer); //return the dataset return datasetCustomer; } } /// <summary> /// Summary description for Customers. /// </summary> [Transaction(TransactionOption.Required)] public class Customers : ServicedComponent { //this class handles data modification. //class constructor public Customers() {

- 65 -

} //method returns a connection object for the Northwind database. private SqlConnection CreateConnection() { SqlConnection databaseConnection = new SqlConnection("server=localhost;Trusted_Connection=false;uid=sa;pwd=;da tabase=Northwind"); return databaseConnection; } //updates the detail quantity for the product. public bool UpdateDetailQuantity(int OrderID, string ProductName, int Quantity) { //grab the connection object SqlConnection currentConnection = CreateConnection(); //open the connection object currentConnection.Open(); try {

//try to update the quantity

//check to see if a transaction exists. //if not the throw an exception. if(!ContextUtil.IsInTransaction) throw new Exception("Requires Transaction"); //set the command text to be executed. string CommandText = "Update [Order Details] set Quantity = "+Quantity+" where OrderID = "+OrderID+" AND [Order Details].ProductID IN"; CommandText+= "(Select ProductID from Products where ProductName = '"+ProductName+"')"; //create the command object and //set the connection property. SqlCommand sqlCommandToExecute = new SqlCommand(); sqlCommandToExecute.Connection = currentConnection; //set the command type and provide //the command text. sqlCommandToExecute.CommandType = CommandType.Text; sqlCommandToExecute.CommandText = CommandText; //execute the query. sqlCommandToExecute.ExecuteNonQuery();

- 66 -

//complete the transaction. ContextUtil.SetComplete(); return true; } catch (Exception e) { //if an exception is thrown //close the connection object //and abort the transaction. currentConnection.Close(); ContextUtil.SetAbort(); return false; } finally { //close the connection object. currentConnection.Close(); }

} } }

- 67 -

AIM
Demonstrates how to create a Microsoft Windows Service that uses a File System Watcher object to monitor a specific directory for changes in files.

PROGRAM

DIRECTORY MONITOR
ASSEMBLY INFORMATION:
using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the

- 68 -

// Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")]

- 69 -

DIRECTORY MONITOR:
using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Diagnostics; System.ServiceProcess; System.Configuration; System.IO; System.Threading;

namespace DirectoryMonitorService { public class DirectoryMonitor : System.ServiceProcess.ServiceBase { private static string Path; private static string Filter; private static bool IncludeSubs; private System.IO.FileSystemWatcher FileMonitor; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public DirectoryMonitor() { // This call is required by the Windows.Forms Component Designer. InitializeComponent(); } // The main entry point for the process static void Main() { System.ServiceProcess.ServiceBase[] ServicesToRun; // More than one user Service may run within the same process. To add // another service to this process, change the following line to // create a second service object. For example, // ServicesToRun = New System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()}; //alter this code to create an instance of this service. ServicesToRun = new System.ServiceProcess.ServiceBase[] { new DirectoryMonitor() }; System.ServiceProcess.ServiceBase.Run(ServicesToRun); } /// <summary>

- 70 -

/// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.FileMonitor = new System.IO.FileSystemWatcher(); ((System.ComponentModel.ISupportInitialize) (this.FileMonitor)).BeginInit(); // // FileMonitor // this.FileMonitor.EnableRaisingEvents = true; this.FileMonitor.Deleted += new System.IO.FileSystemEventHandler(this.FileMonitor_Changed); this.FileMonitor.Renamed += new System.IO.RenamedEventHandler(this.FileMonitor_OnRenamed); this.FileMonitor.Changed += new System.IO.FileSystemEventHandler(this.FileMonitor_Changed); this.FileMonitor.Created += new System.IO.FileSystemEventHandler(this.FileMonitor_Changed); // // DirectoryMonitor // this.CanPauseAndContinue = true; this.CanShutdown = true; this.ServiceName = "DirectoryMonitor"; ((System.ComponentModel.ISupportInitialize) (this.FileMonitor)).EndInit(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } /// <summary> /// Set things in motion so your service can do its work.

- 71 -

/// </summary> protected override void OnStart(string[] args) { //retrieve the configuration properties from the Machine.config file. Path = ConfigurationSettings.AppSettings.Get("DirectoryMonitorPath").ToString(); Filter = ConfigurationSettings.AppSettings.Get("DirectoryMonitorFilter").ToString(); IncludeSubs = (Convert.ToBoolean(ConfigurationSettings.AppSettings.Get("DirectoryMonitor IncludeSubs").ToString())); //Set the path for the FileSystemWatcher to monitor. FileMonitor.Path = Path.ToString(); //Set the file type filter for the FileSystemWatcher to monitor. FileMonitor.Filter = Filter.ToString(); //Determine if the FileSystemWatcher should monitor subdirectories. FileMonitor.IncludeSubdirectories = IncludeSubs; //Set the NotifyFilters for raising events. FileMonitor.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite NotifyFilters.FileName | NotifyFilters.DirectoryName; //Begin monitoring. FileMonitor.EnableRaisingEvents = true; } /// <summary> /// Stop this service. /// </summary> protected override void OnStop() { //When the service is stopped the FileSystemMonitor should stop raising events. FileMonitor.EnableRaisingEvents = false; } protected override void OnPause() { //When the service is paused the FileSystemMonitor should stop raising events. FileMonitor.EnableRaisingEvents = false; } protected override void OnContinue() { //When the service is continued, then retrieve the configuration properties again. Path = ConfigurationSettings.AppSettings.Get("DirectoryMonitorPath").ToString(); Filter = ConfigurationSettings.AppSettings.Get("DirectoryMonitorFilter").ToString();

- 72 -

IncludeSubs = (Convert.ToBoolean(ConfigurationSettings.AppSettings.Get("DirectoryMonitor IncludeSubs").ToString())); //Set the properties on the monitor. FileMonitor.Path = Path.ToString(); FileMonitor.Filter = Filter.ToString(); FileMonitor.IncludeSubdirectories = IncludeSubs; } private void FileMonitor_OnRenamed(object source, RenamedEventArgs e) { // Specify what is done when a file is newName. // Here the Service makes an entry to the EventLog. string originalName = e.OldFullPath; string newName = e.FullPath; EventLog.WriteEntry("Directory Monitor", "File: "+originalName+" newName to "+e.OldName+" newName"); } private void FileMonitor_Changed(object sender, System.IO.FileSystemEventArgs e) { string ChangeType = e.ChangeType.ToString(); //write a log entry for the appropriate changetype. if (ChangeType=="Created") { EventLog.WriteEntry("Directory Monitor", "File: " + e.FullPath + " " + e.Name+" Created"); } else if(ChangeType=="Deleted") { EventLog.WriteEntry("Directory Monitor", "File: " + e.FullPath + " " +e.Name+" Deleted"); } else if(ChangeType=="Changed") { EventLog.WriteEntry("Directory Monitor", "File: "+e.FullPath+" "+e.Name+" Changed"); } } } }

- 73 -

PROJECT INSTALLER:
using using using using System; System.Collections; System.ComponentModel; System.Configuration.Install;

namespace DirectoryMonitor { /// <summary> /// Summary description for ProjectInstaller. /// </summary> [RunInstaller(true)] public class ProjectInstaller : System.Configuration.Install.Installer { private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1; private System.ServiceProcess.ServiceInstaller serviceInstaller1; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public ProjectInstaller() { // This call is required by the Designer. InitializeComponent(); // TODO: Add any initialization after the InitComponent call } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); // // serviceProcessInstaller1 // this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem; this.serviceProcessInstaller1.Password = null; this.serviceProcessInstaller1.Username = null; //

- 74 -

// serviceInstaller1 // this.serviceInstaller1.DisplayName = "Directory Monitor Service"; this.serviceInstaller1.ServiceName = "Directory Monitor"; this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic; // // ProjectInstaller // this.Installers.AddRange(new System.Configuration.Install.Installer[] { this.serviceProcessInstaller1, } #endregion

this.serviceInstaller1});

} }

- 75 -

AIM
Demonstrates how to upload images into SQL Server by using standard HTML upload methods and then insert each image as a byte array into SQL Server.

PROGRAM GETTING IMAGE


using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.SessionState; System.Web.UI; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Data.SqlClient;

namespace UploadImages1 { /// <summary> /// GetImage is the file used to actually retrieve the image from SQL Server /// and display it in a browser. /// </summary> public class GetImage : System.Web.UI.Page { private void Page_Load(object sender, System.EventArgs e) { /// <summary> /// The ImageID variable holds the ImageID passed from ViewImages </summary> int ImageId = System.Convert.ToInt32(Request.QueryString["ImageId"]); /// <summary> /// imageContent will be used to hold the record returned from the database. /// This line calls the GetImages function. </summary> SqlDataReader imageContent = GetImages(ImageId); /// <summary>/// The Read method is used to load the record into memory </summary> imageContent.Read();

- 76 -

/// <summary> /// The ImageType is retrieved from the database and sent to the browser as the /// ContentType. This tells the browser how to display the image. </summary> Response.ContentType = imageContent["ImageType"].ToString(); /// <summary> /// The OutputStream.Write is used to write a byte array of the image, starting at /// the first byte and proceeding through the entire file. </summary> Response.OutputStream.Write((byte[])imageContent["ImageFile"], 0, System.Convert.ToInt32(imageContent["ImageSize"])); /// <summary> /// Call the End method to indicate to the browser that the entire image has been sent. </summary> Response.End(); } /// <summary> /// GetImages is used to actually retrieve the record, based on the ImageId that is passed in. /// </summary> /// <param name="ImageId">ImageId is the ID of the image chosen on ViewImages.aspx.</param> /// <returns>GetImages returns a SqlDataReader, which is more efficient than a DataSet in this case.</returns> private SqlDataReader GetImages(int imageId) { /// <summary> /// Open a connection to the SQL Server </summary> SqlConnection Connection = new SqlConnection("server =localhost;uid= sa;database=ImageUpload"); /// <summary> /// The SqlCommand retrieves a single record from the Images table </summary> SqlCommand Command = new SqlCommand("Select * From Images Where ImageId=@ImageId", Connection); /// <summary> /// Create a SqlParameter that will allow you to pass in the ImageId to the query </summary> SqlParameter imageIDParameter = new SqlParameter("@ImageId", SqlDbType.Int); /// <summary> /// Assign the ImageId to the parameter that was created </summary> imageIDParameter.Value = imageId; /// <summary>

- 77 -

/// Add the Parameter to the SqlCommand's Parameters collection </summary> Command.Parameters.Add(imageIDParameter); /// <summary> /// Open the connection in order to retrieve the record </summary> Connection.Open(); /// <summary> /// Return a SqlDataReader to the calling procedure. Notice that the connection will /// be closed afer the record has been read </summary> return Command.ExecuteReader(CommandBehavior.CloseConnection); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // CODEGEN: This call is required by the ASP.NET Web Form Designer. InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion }

- 78 -

VIEWING IMAGE
using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.SessionState; System.Web.UI; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Data.SqlClient;

namespace UploadImages1 { /// <summary> /// ViewImages is used to display a list of the images in the database. Each /// image is listed by description and is a link that will call GetImage, passing /// in the ID of the image. /// </summary> public class ViewImages : System.Web.UI.Page { private void Page_Load(object sender, System.EventArgs e) { /// <summary> /// Open a connection to the SQL Server </summary> SqlConnection Connection = new SqlConnection("server=localhost;uid=sa;database=ImageUpload;pwd=;"); /// <summary> /// The SqlCommand retrieves a list of description and ImageID's from the Images table </summary> SqlCommand Command = new SqlCommand("Select ImageID, Description From Images", Connection); /// <summary> /// Open the connection in order to retrieve the record </summary> Connection.Open(); /// <summary> /// Output header text Response.Write("<H2 align='center'><FONT color='blue'>Image List from SQL Server</FONT></H2><BR><BR>"); /// <summary> /// Create a SqlDataReader that contains a list of the images in the database </summary> SqlDataReader myDR = Command.ExecuteReader();

- 79 -

/// <summary> /// Loop through the records using the Read method </summary> while (myDR.Read()) { /// <summary> /// Write out hyperlinks that show the descriptions and include the ImageID in a querystring </summary> Response.Write("<a href='GetImage.aspx?imageid=" + myDR["ImageID"] + "'>" + myDR["Description"] + "</a><br>"); } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion

} }

- 80 -

WEBFORM
using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.SessionState; System.Web.UI; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Data.SqlClient;

namespace UploadImages1 { /// <summary> /// WebForm1 allows you to upload images into the Images table. It uses standard /// HTML upload methods to get the file to the server. /// </summary> public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.TextBox imageDescription; protected System.Web.UI.WebControls.Button UploadImage; protected System.Web.UI.HtmlControls.HtmlInputFile ImageToUpload; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() {

- 81 -

this.UploadImage.Click += new System.EventHandler(this.UploadImage_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void UploadImage_Click(object sender, System.EventArgs e) { /// <summary> /// ContentType holds the content type of the file that was added to the ImageToUpload /// control, and HTML input control. </summary> string ContentType = ImageToUpload.PostedFile.ContentType; /// <summary> /// Length holds the size of the file that was added to the ImageToUpload control </summary> int Length = System.Convert.ToInt32(ImageToUpload.PostedFile.InputStream.Length); /// <summary> /// Content will hold the image. It is a byte array of size Length </summary> byte[] Content = new byte[Length]; /// <summary> /// The Read method is used to read the file from the ImageToUpload control </summary> ImageToUpload.PostedFile.InputStream.Read(Content,0,Length); /// <summary> /// Open a connection to the SQL Server </summary> SqlConnection Connection = new SqlConnection("server=localhost;uid=sa;pwd=;database=ImageUpload"); /// <summary> /// The SqlCommand will be used to insert the image into the Images table </summary> SqlCommand Command = new SqlCommand("INSERT Into Images(Description, ImageFile, ImageSize, ImageType) Values(@Description, @ImageFile, @ImageSize, @ImageType)", Connection); /// <summary> /// The Description parameter is used to add the image file description to the database SqlParameter imageDescriptionParameter = new SqlParameter("@Description", SqlDbType.NVarChar); imageDescriptionParameter.Value = imageDescription.Text; Command.Parameters.Add(imageDescriptionParameter); /// <summary> /// The ImageFile parameter is used to add the image file to the database SqlParameter imageFileParameter = new SqlParameter("@ImageFile", SqlDbType.Image);

- 82 -

imageFileParameter.Value = Content; Command.Parameters.Add(imageFileParameter); /// <summary> /// The ImageSize parameter is used to add the image file size to the database SqlParameter imageSizeParameter = new SqlParameter("@ImageSize", SqlDbType.Int); imageSizeParameter.Value = Length; Command.Parameters.Add(imageSizeParameter); /// <summary> /// The ImageType parameter is used to add the image file type to the database SqlParameter imageTypeParameter = new SqlParameter("@ImageType", SqlDbType.NVarChar); imageTypeParameter.Value = ContentType; Command.Parameters.Add(imageTypeParameter); /// <summary> /// Open the connection in order to retrieve the record </summary> Connection.Open(); /// <summary> /// The SQL statement is executed. ExecuteNonQuery is used since no records /// will be returned. </summary> Command.ExecuteNonQuery(); /// <summary> /// The connection is closed </summary> Connection.Close(); } } }

- 83 -

AIM
Develop a sample application that launches a Windows Form to allow the user to interact and manipulate the IIS Admin service on the local machine. The application should work by placing an icon in the System Tray.

PROGRAM ASSEMBLY INFORMATION:


using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing.

- 84 -

// // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] SYSTEM TRAY: using using using using using System; System.Drawing; System.Resources; System.ComponentModel; System.Windows.Forms;

public class SystemTray : System.Windows.Forms.Form { private System.Windows.Forms.NotifyIcon WSNotifyIcon; private System.ComponentModel.IContainer components; private Icon mDirIcon = new Icon(typeof(SystemTray).Assembly.GetManifestResourceStream("SystemTra yExample.FLGUSA02.ICO")); public SystemTray() { //constructor for the form

- 85 -

InitializeComponent(); //keep the form hidden this.Hide(); InitializeNotifyIcon(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.WSNotifyIcon = new System.Windows.Forms.NotifyIcon(this.components); // // WSNotifyIcon // this.WSNotifyIcon.Text = ""; this.WSNotifyIcon.Visible = true; // // SysTray // this.AccessibleRole = System.Windows.Forms.AccessibleRole.None; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(8, 7); this.ControlBox = false; this.Enabled = false; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

- 86 -

this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SystemTray"; this.Opacity = 0; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new SystemTray()); } public void ShowControlForm(object sender, EventArgs e) { //show the Control form. WSControllerForm controlForm = new WSControllerForm(); controlForm.Show(); } public void ExitControlForm(object sender, EventArgs e) { //Hide the NotifyIcon. WSNotifyIcon.Visible=false; this.Close(); } private void InitializeNotifyIcon() { //setup the Icon NotifyIcon WSNotifyIcon = new NotifyIcon(); WSNotifyIcon.Icon = mDirIcon; WSNotifyIcon.Text = "Right Click to Configure"; WSNotifyIcon.Visible = true; //Create the MenuItem objects and add them to //the context menu of the NotifyIcon. MenuItem[] mnuItems = new MenuItem[3]; //create the menu items array mnuItems[0] = new MenuItem("Show Control Form...", new EventHandler(this.ShowControlForm)); mnuItems[0].DefaultItem=true;

- 87 -

mnuItems[1] = new MenuItem("-"); mnuItems[2] = new MenuItem("Exit", new EventHandler(this.ExitControlForm)); //add the menu items to the context menu of the NotifyIcon ContextMenu notifyIconMenu = new ContextMenu(mnuItems); WSNotifyIcon.ContextMenu=notifyIconMenu; } }

- 88 -

WSCONTROLLERFORM: using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.ServiceProcess; public class WSControllerForm : System.Windows.Forms.Form { private System.ServiceProcess.ServiceController WSController; private System.Windows.Forms.Label Label1; private System.Windows.Forms.Button ButtonStart; private System.Windows.Forms.Button ButtonStop; private System.Windows.Forms.Button ButtonPause; private System.Windows.Forms.Label controlledService; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public WSControllerForm() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); }

- 89 -

#region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.WSController = new System.ServiceProcess.ServiceController(); this.Label1 = new System.Windows.Forms.Label(); this.ButtonStart = new System.Windows.Forms.Button(); this.ButtonStop = new System.Windows.Forms.Button(); this.ButtonPause = new System.Windows.Forms.Button(); this.controlledService = new System.Windows.Forms.Label(); this.SuspendLayout(); // // Label1 // this.Label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Label1.Location = new System.Drawing.Point(48, 8); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(232, 23); this.Label1.TabIndex = 0; this.Label1.Text = "Windows Service Controller"; this.Label1.TextAlign = System.Drawing.ContentAlignment.TopCenter; // // ButtonStart // this.ButtonStart.Location = new System.Drawing.Point(120, 48); this.ButtonStart.Name = "ButtonStart"; this.ButtonStart.TabIndex = 1; this.ButtonStart.Text = "Start"; this.ButtonStart.Click += new System.EventHandler(this.ButtonStart_Click); // // ButtonStop // this.ButtonStop.Location = new System.Drawing.Point(120, 112); this.ButtonStop.Name = "ButtonStop"; this.ButtonStop.TabIndex = 2; this.ButtonStop.Text = "Stop"; this.ButtonStop.Click += new System.EventHandler(this.ButtonStop_Click); // // ButtonPause // this.ButtonPause.Location = new System.Drawing.Point(120, 80); this.ButtonPause.Name = "ButtonPause";

- 90 -

this.ButtonPause.TabIndex = 3; this.ButtonPause.Text = "Pause"; this.ButtonPause.Click += new System.EventHandler(this.ButtonPause_Click); // // controlledService // this.controlledService.AutoSize = true; this.controlledService.Location = new System.Drawing.Point(96, 144); this.controlledService.Name = "controlledService"; this.controlledService.Size = new System.Drawing.Size(0, 13); this.controlledService.TabIndex = 4; // // WSControllerForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(336, 174); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.controlledService, this.ButtonPause, this.ButtonStop, this.ButtonStart, this.Label1}); this.MinimumSize = new System.Drawing.Size(264, 160); this.Name = "WSControllerForm"; this.Text = "Windows Service Controller"; this.Load += new System.EventHandler(this.WSControllerForm_Load); this.ResumeLayout(false); } #endregion private void WSControllerForm_Load(object sender, System.EventArgs e) { ServiceController[] AvailableServices = ServiceController.GetServices("."); foreach(ServiceController AvailableService in AvailableServices) { //Check the service name for IIS. if(AvailableService.ServiceName=="IISADMIN") { WSController.ServiceName="IISADMIN"; SetButtonStatus(); return; } } MessageBox.Show("The IIS Admin Service is not installed on this Machine", "IIS Admin Service is not available"); this.Close(); Application.Exit();

- 91 -

} private void SetButtonStatus() { //get the status of the service. string strServerStatus = WSController.Status.ToString(); //check the status of the service and enable the //command buttons accordingly. controlledService.Text = WSController.ServiceName; if (strServerStatus == "Running") { //check to see if the service can be paused if (WSController.CanPauseAndContinue == true) { ButtonPause.Enabled = true; } else { ButtonPause.Enabled = false; } ButtonStop.Enabled = true; ButtonStart.Enabled = false;

} else if(strServerStatus == "Paused") { ButtonStart.Enabled = true; ButtonPause.Enabled = false; ButtonStop.Enabled = true; } else if (strServerStatus == "Stopped") { ButtonStart.Enabled = true; ButtonPause.Enabled = false; ButtonStop.Enabled = false; } } private void ButtonStart_Click(object sender, System.EventArgs e) { //check the status of the service if(WSController.Status.ToString() == "Paused") { WSController.Continue(); } else if(WSController.Status.ToString() == "Stopped") {

- 92 -

//get an array of services this service depends upon, loop through //the array and prompt the user to start all required services. ServiceController[] ParentServices = WSController.ServicesDependedOn; //if the length of the array is greater than or equal to 1. if (ParentServices.Length >= 1) { foreach(ServiceController ParentService in ParentServices) { //make sure the parent service is running or at least paused. if(ParentService.Status.ToString() != "Running" || ParentService.Status.ToString() != "Paused") { if (MessageBox.Show("This service is required. Would you like to also start this service?\n"+ParentService.DisplayName, "Required Service", MessageBoxButtons.YesNo).ToString() == "Yes") { //if the user chooses to start the service ParentService.Start(); ParentService.WaitForStatus(ServiceControllerStatus.Running); } else { //otherwise just return. return; } } } } } WSController.Start();

WSController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus. Running); SetButtonStatus(); } private void ButtonStop_Click(object sender, System.EventArgs e) { //check to see if the service can be stopped. if (WSController.CanStop == true) { //get an array of dependent services, loop through the array and //prompt the user to stop all dependent services. ServiceController[] DependentServices = WSController.DependentServices; //if the length of the array is greater than or equal to 1. if (DependentServices.Length >= 1) {

- 93 -

foreach(ServiceController DependentService in DependentServices) { //make sure the dependent service is not already stopped. if(DependentService.Status.ToString() != "Stopped") { if (MessageBox.Show("Would you like to also stop this dependent service?\n"+DependentService.DisplayName, "Dependent Service", MessageBoxButtons.YesNo).ToString() == "Yes") { // not checking at this point whether the dependent service can be stopped. // developer may want to include this check to avoid exception. DependentService.Stop(); DependentService.WaitForStatus(ServiceControllerStatus.Stopped); } else { return; } } } } //check the status of the service if(WSController.Status.ToString() == "Running" || WSController.Status.ToString() == "Paused") { WSController.Stop(); } WSController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus. Stopped); SetButtonStatus(); } } private void ButtonPause_Click(object sender, System.EventArgs e) { //check to see if the service can be paused and continue if (WSController.CanPauseAndContinue == true) { //check the status of the service if(WSController.Status.ToString() == "Running") { WSController.Pause(); } WSController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus. Paused); SetButtonStatus(); } } }

- 94 -

AIM
Understand why it can be beneficial to create separate modules for an application download, and then demonstrates how to do so with C#.

PROGRAM
MATH:
using System; namespace myMath { public class MathStuff { public void SquareIt(int numToSquare) { System.Console.WriteLine(numToSquare * numToSquare); } } }

MATH CLIENT:
using System; using myMath; class MathClient { // Static method Main is the entry point method. public static void Main() { MathStuff myMathStuff = new MathStuff(); Console.WriteLine("Sqaring 5"); myMathStuff.SquareIt(5); } }

- 95 -

AIM
Develop a sample application that shows how to print a formatted report from sample data stored in an XML file using the PrintDocument class in the System.Drawing.Printing namespace. Also illustrates the user selection of a destination printer and multiple print fonts.

PROGRAM
ASSEMBLY INFORMATION: using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing.

- 96 -

// // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")]

- 97 -

FORM:
using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data;

namespace PrintDocument { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Label lblCompany; private System.Windows.Forms.Label lblHeaderFont; private System.Windows.Forms.Label lblBodyFont; private System.Windows.Forms.Label lblReportData; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; /// <summary> /// Used to display a font selection dialog. This single dialog is /// used for both the header and body text font selections. /// </summary> private System.Windows.Forms.FontDialog fontDialog1; /// <summary> /// Used to handle the actual formatting and printing of the report. /// </summary> private System.Drawing.Printing.PrintDocument printDocument1; /// <summary> /// Used to select a destination printer. /// </summary> private System.Windows.Forms.PrintDialog printDialog1; /// <summary> /// Font to use for printing the page header. /// </summary> private System.Drawing.Font headerFont; /// <summary> /// Font to use for printing the report body text. /// </summary> private System.Drawing.Font bodyFont;

- 98 -

private System.Windows.Forms.TextBox headerFontDefinition; private System.Windows.Forms.TextBox companyName; private System.Windows.Forms.Button PrintButton; private System.Windows.Forms.TextBox reportData; private System.Windows.Forms.TextBox bodyFontDefinition; private System.Windows.Forms.Button SelectHeaderFont; private System.Windows.Forms.Button SelectBodyFont; /// <summary> /// Used to read report data from a static XML file. /// </summary> private System.Xml.XmlTextReader xmlReader; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.lblReportData = new System.Windows.Forms.Label();

- 99 -

this.printDialog1 = new System.Windows.Forms.PrintDialog(); this.printDocument1 = new System.Drawing.Printing.PrintDocument(); this.headerFontDefinition = new System.Windows.Forms.TextBox(); this.companyName = new System.Windows.Forms.TextBox(); this.lblBodyFont = new System.Windows.Forms.Label(); this.SelectHeaderFont = new System.Windows.Forms.Button(); this.PrintButton = new System.Windows.Forms.Button(); this.reportData = new System.Windows.Forms.TextBox(); this.SelectBodyFont = new System.Windows.Forms.Button(); this.bodyFontDefinition = new System.Windows.Forms.TextBox(); this.lblHeaderFont = new System.Windows.Forms.Label(); this.fontDialog1 = new System.Windows.Forms.FontDialog(); this.lblCompany = new System.Windows.Forms.Label(); this.SuspendLayout(); // // lblReportData // this.lblReportData.Location = new System.Drawing.Point(8, 160); this.lblReportData.Name = "lblReportData"; this.lblReportData.TabIndex = 19; this.lblReportData.Text = "Report Data:"; // // printDialog1 // this.printDialog1.Document = this.printDocument1; // // printDocument1 // this.printDocument1.DocumentName = "Customer List"; this.printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDocument1_PrintP age); // // headerFontDefinition // this.headerFontDefinition.Location = new System.Drawing.Point(120, 40); this.headerFontDefinition.Multiline = true; this.headerFontDefinition.Name = "headerFontDefinition"; this.headerFontDefinition.ReadOnly = true; this.headerFontDefinition.Size = new System.Drawing.Size(408, 48); this.headerFontDefinition.TabIndex = 14; this.headerFontDefinition.Text = ""; // // companyName // this.companyName.Location = new System.Drawing.Point(120, 8); this.companyName.Name = "companyName"; this.companyName.Size = new System.Drawing.Size(408,20);

- 100 -

this.companyName.TabIndex = 12; this.companyName.Text = "Sample Company"; // // lblBodyFont //this.lblBodyFont.Location = new System.Drawing.Point(8, 104); this.lblBodyFont.Name = "lblBodyFont"; this.lblBodyFont.TabIndex = 16; this.lblBodyFont.Text = "Body Text Font:"; // // SelectHeaderFont // this.SelectHeaderFont.Location = new System.Drawing.Point(536, 40); this.SelectHeaderFont.Name = "SelectHeaderFont"; this.SelectHeaderFont.Size = new System.Drawing.Size(24, 20); this.SelectHeaderFont.TabIndex = 15; this.SelectHeaderFont.Text = "..."; this.SelectHeaderFont.Click += new System.EventHandler(this.SelectHeaderFont_Click); // // PrintButton // this.PrintButton.Location = new System.Drawing.Point(248, 312); this.PrintButton.Name = "PrintButton"; this.PrintButton.TabIndex = 21; this.PrintButton.Text = "Print"; this.PrintButton.Click += new System.EventHandler(this.PrintButton_Click); // // reportData // this.reportData.Location = new System.Drawing.Point(120, 160); this.reportData.Multiline = true; this.reportData.Name = "reportData"; this.reportData.ReadOnly = true; this.reportData.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.reportData.Size = new System.Drawing.Size(408, 144); this.reportData.TabIndex = 20; this.reportData.Text = ""; // // SelectBodyFont // this.SelectBodyFont.Location = new System.Drawing.Point(536, 104); this.SelectBodyFont.Name = "SelectBodyFont"; this.SelectBodyFont.Size = new System.Drawing.Size(24, 20); this.SelectBodyFont.TabIndex = 18; this.SelectBodyFont.Text = "..."; this.SelectBodyFont.Click += new System.EventHandler(this.SelectBodyFont_Click);

- 101 -

// // bodyFontDefinition // this.bodyFontDefinition.Location = new System.Drawing.Point(120, 104); this.bodyFontDefinition.Multiline = true; this.bodyFontDefinition.Name = "bodyFontDefinition"; this.bodyFontDefinition.ReadOnly = true; this.bodyFontDefinition.Size = new System.Drawing.Size(408, 48); this.bodyFontDefinition.TabIndex = 17; this.bodyFontDefinition.Text = ""; // // lblHeaderFont // this.lblHeaderFont.Location = new System.Drawing.Point(8, 40); this.lblHeaderFont.Name = "lblHeaderFont"; this.lblHeaderFont.TabIndex = 13; this.lblHeaderFont.Text = "Header Text Font:"; // // lblCompany // this.lblCompany.Location = new System.Drawing.Point(8, 8); this.lblCompany.Name = "lblCompany"; this.lblCompany.TabIndex = 11; this.lblCompany.Text = "Company Name:"; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(568, 340); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.lblBodyFont, this.SelectHeaderFont, this.PrintButton, this.reportData, this.SelectBodyFont, this.bodyFontDefinition, this.lblHeaderFont, this.lblCompany, this.lblReportData, this.headerFontDefinition, this.companyName}); this.Name = "Form1"; this.Text = "Customer List Printing Sample"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion /// <summary>

- 102 -

/// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } /// <summary> /// Occurs before a form is displayed for the first time. /// Contains code to update read an XML file and update /// the text of some form controls. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">An EventArgs that contains the event data.</param> private void Form1_Load(object sender, System.EventArgs e) { // Set the default fonts for the header and text. headerFont = new Font("Arial", 14); bodyFont = new Font("Arial", 10); // Update the form controls to display the default font settings. headerFontDefinition.Text = headerFont.ToString(); bodyFontDefinition.Text = bodyFont.ToString(); // Perform the reading of the data file within a try block in case // the data file doesn't exist or an error is encountered reading the file. try { // The XmlTextReader reads the specified XML file and provides a way to // scroll through the data elements. xmlReader = new System.Xml.XmlTextReader("..\\..\\..\\Misc\\ReportData.xml"); // Call the Read method in order to position the reader at the // first element. xmlReader.Read(); // Show the entire contents of the data file in // a textbox for comparison to the printed report. reportData.Text = xmlReader.ReadOuterXml(); // Closes the XmlReader. xmlReader.Close();

} catch(Exception ex) {

- 103 -

// An error was encountered opening or reading the data file. // Display an appropriate message to the user. MessageBox.Show("Error opening file: \r\n" + ex.Message); // Close the form since a report can't be printed without access // to the data file. this.Close(); } } /// <summary> /// This event displays a printer selection dialog and then starts the print /// process. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">An EventArgs that contains the event data.</param> private void PrintButton_Click(object sender, System.EventArgs e) { // Perform the print within a try block in case a failure // of any type occurs. For this sample, all errors will // be handled generically by simply displaying a messagebox.

- 104 -

try { // Open the XML Data file. xmlReader = new System.Xml.XmlTextReader("..\\..\\..\\Misc\\ReportData.xml"); // Position the pointer to the first element. xmlReader.Read(); // Display a printer selection dialog. // Only print the document if the user clicks OK. if (printDialog1.ShowDialog() == DialogResult.OK) { // This starts the actual print. The code to output // text to the selected printer resides in the PrintDocument1_PrintPage // event handler. PrintDocument1.Print(); } // Close the data file. xmlReader.Close(); } catch (Exception ex) { // If any error occurs, display a messagebox. MessageBox.Show("Error printing report: \r\n" + ex.Message); } } /// <summary> /// This event occurs when the output to print for the current page is needed, and /// contains the logic to handle the content and layout of the printed page. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">A PrintPageEventArgs that contains the event ata.</param> private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { // Determine the height of the header, based on the selected font. float headerHeight = headerFont.GetHeight(e.Graphics); // Determine the number of lines of body text that can be printed per page, taking // into account the presence of the header and the size of the selected body font. float linesPerPage = (e.MarginBounds.Height - headerHeight)/ bodyFont.GetHeight(e.Graphics); // Used to store the position at which the next body line // should be printed.

- 105 -

float yPosition = 0; // Used to store the number of lines printed so far on the // current page. int count = 0; // User to store the text of the current line. string line = null; // Print the page header, as specified by the user in the form. // Use the header font for this line only. e.Graphics.DrawString(companyName.Text.Trim(), headerFont, rushes.Black, e.MarginBounds.Left, e.MarginBounds.Top, new StringFormat()); // Print each line of the data file, but don't exceed the maximum allowable // number of lines per page. Also, stop when the end of the data file is // reached. This event is called once per page, so if the data exceeds a single // page, the XmlTextReader will pick up where it left off on the previous page. while(count < linesPerPage && !xmlReader.EOF) { // Move the pointer to the next "context" line in the Xml data file. // If the line is not an XML element, then it can be skipped. // Because the initial Read() call made when the xmlReader was opened // positioned the file to the first element (<Customers>) the following // call actually moves to the first <Customer> tag the first time through. if (xmlReader.MoveToContent() == System.Xml.XmlNodeType.Element) { // Based on the element, determine what to print and where to print it. switch (xmlReader.Name) { case "Customers": { // This is not really required, since the initial Read() call // when the xmlReader is loaded effectively bypasses the opening element // as described in the comments above. Included here for explanation only. // If a <Customers> tag is encountered, just print a blank line. line = ""; // Tell the XmlTextReader to move on to the next element. xmlReader.Read(); break; } case "Customer": { // Hitting a new <Customer> tag indicates the beginning of a // new customer record. Take this opportunity to print a blank line, // adding spacing between customer records in the report. line = ""; // Tell the XmlTextReader to move on to the next element. xmlReader.Read();

- 106 -

break; } default: { // All other elements in the sample XML file are actual data // fields pertaining to a customer record. Print the field name // and value. The ReadElementString retrieves the value and // automatically forces the XmlTextReader to move on to the // next element. Because this is handled generically, any additional // customer fields added inside the <Customer> tag in the xml file will // automatically be shown in the printed report. line = xmlReader.Name + ": " + xmlReader.ReadElementString(); break; } } // Determine the position at which to print. Since this report prints one line // at a time, only the height (or Y coordinate) needs to be calculated, because // every line will begin at the far left. The Y coordinate must take into // consideration the header, the height of each line of body text, and the // number of body lines printed so far on this page. yPosition = e.MarginBounds.Top + headerHeight + (count * bodyFont.GetHeight(e.Graphics)); // Draw the line of text on the page using the body font specified by the user. e.Graphics.DrawString(line, bodyFont, Brushes.Black, e.MarginBounds.Left, yPosition, new StringFormat()); // Increment the counter to show that another line has been printed. // This is used in the positioning of future lines of text on the current page. count++; } else { // If the XmlTextReader is positioned on a line that is NOT an // Element, then just go on to the next line. xmlReader.Read(); } } // If more data exists, print another page. If not stop this event from firin // again by setting the HasMorePages property to false. if(xmlReader.EOF) e.HasMorePages = false; else e.HasMorePages = true; } /// <summary> /// Uses the fontDialog to allow the user to specify a font

- 107 -

/// for the report header. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">An EventArgs that contains the event data.</param> private void SelectHeaderFont_Click(object sender, System.EventArgs e) { // Set the initial selection to the currently selected header font. // Since this one dialog is used for selection of both the header // and body fonts, this needs to be set each time. fontDialog1.Font = headerFont; // Show the font selection dialog. if (fontDialog1.ShowDialog() == DialogResult.OK) { // Update the selected font and the form controls // only if the user pressed OK. headerFont = fontDialog1.Font; headerFontDefinition.Text = headerFont.ToString(); } } /// <summary> /// Uses the fontDialog to allow the user to specify a font /// for the report body. /// </summary> /// <param name="sender">The source of the event.</param> // <param name="e">An EventArgs that contains the event data.</param> private void SelectBodyFont_Click(object sender, System.EventArgs e) { // Set the initial selection to the currently selected body font. // Since this one dialog is used for selection of both the header // and body fonts, this needs to be set each time. fontDialog1.Font = bodyFont; // Show the font selection dialog. if (fontDialog1.ShowDialog() == DialogResult.OK) { // Update the selected font and the form controls // only if the user pressed OK. bodyFont = fontDialog1.Font; bodyFontDefinition.Text = bodyFont.ToString(); } } } }

- 108 -

AIM
Demonstrate how to gather information on various types included in any assembly by using the System.Reflection namespace and some main .NET base classes.

PROGRAM
REFLECTION CODE:
ASSEMBLY INFORMATION: using System.Reflection; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // Use the attributes below to control which key is used for signing. // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used.

- 109 -

// (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")]

REFLECTION FORM using System; using System.Reflection; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace Reflection { /// <summary> /// Summary description for ReflectionForm. /// </summary> public class ReflectionForm : System.Windows.Forms.Form { private System.Windows.Forms.Button GetAssemblyInfo; private System.Windows.Forms.ComboBox listAssemblies; private System.Windows.Forms.Label label1; private System.Windows.Forms.ListBox listTypes; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private Type[] PersonTypes; private Type[] EmployeeTypes; private Type[] CustomerTypes; public ReflectionForm()

- 110 -

{ // Required for Windows Form Designer support InitializeComponent(); // TODO: Add any constructor code after InitializeComponent call } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.GetAssemblyInfo = new System.Windows.Forms.Button(); this.listAssemblies = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.listTypes = new System.Windows.Forms.ListBox(); this.SuspendLayout(); // GetAssemblyInfo this.GetAssemblyInfo.Location = new System.Drawing.Point(280, 40); this.GetAssemblyInfo.Name = "GetAssemblyInfo"; this.GetAssemblyInfo.TabIndex = 0; this.GetAssemblyInfo.Text = "Get Info"; this.GetAssemblyInfo.Click += new System.EventHandler(this.btnGetInfo_Click); // listAssemblies this.listAssemblies.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.listAssemblies.Items.AddRange(new object[] { "Person", "Employee", "Customer"}); this.listAssemblies.Location = new System.Drawing.Point(144, 40); this.listAssemblies.Name = "listAssemblies";

- 111 -

this.listAssemblies.Size = new System.Drawing.Size(121, 21); this.listAssemblies.TabIndex = 1; this.listAssemblies.SelectedIndexChanged += new System.EventHandler(this.cboAssemblies_SelectedIndexChanged); // label1 this.label1.Location = new System.Drawing.Point(16, 40); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(112, 16); this.label1.TabIndex = 2; this.label1.Text = "Select An Assembly: "; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // listTypes this.listTypes.Location = new System.Drawing.Point(8, 88); this.listTypes.Name = "listTypes"; this.listTypes.Size = new System.Drawing.Size(376, 173); this.listTypes.TabIndex = 3; // ReflectionForm this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(400, 273); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.listTypes, this.label1,this.listAssemblies, this.GetAssemblyInfo}); this.Name = "ReflectionForm"; this.Text = "Reflection Sample"; this.Load += new System.EventHandler(this.ReflectionForm_Load); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new ReflectionForm()); } private void btnGetInfo_Click(object sender, System.EventArgs e) { //get the name of the assembly selected by the user. string SelectedAssembly = this.listAssemblies.SelectedItem.ToString(); //call the LoadTypeInfo with the //correct assembly array. if(SelectedAssembly == "Person") { listTypes.Items.Clear(); LoadTypeInfo(PersonTypes); }

- 112 -

else if (SelectedAssembly == "Employee") { listTypes.Items.Clear(); LoadTypeInfo(EmployeeTypes); } else if (SelectedAssembly == "Customer") { listTypes.Items.Clear(); LoadTypeInfo(CustomerTypes); } else { listTypes.Items.Clear(); } } private void LoadTypeInfo(Type[] AssemblyType) { //loop through the Assembly Type and write the //attributes out to the list box. foreach(Type baseType in AssemblyType) { //get the full name of the assembly. listTypes.Items.Add("Assembly Type: "+baseType.FullName+"("+baseType.UnderlyingSystemType+")"); //get the base type of the assembly. listTypes.Items.Add("Base Type: "+baseType.BaseType); //is the assembly serializable. listTypes.Items.Add("Serializable: " + baseType.IsSerializable); //is the assembly defined as abstract. listTypes.Items.Add("Abstract: " + baseType.IsAbstract); //is the assembly a class library. listTypes.Items.Add("Class: " + baseType.IsClass); //is the assembly public. listTypes.Items.Add("Public: " + baseType.IsPublic); //is the assembly sealed. listTypes.Items.Add("Sealed: " + baseType.IsSealed); //get the attributes defined - returns only .NET base attributes. //for customattributes use the "GetCustomAttributes()" method. System.Reflection.TypeAttributes baseTypeAttributes = baseType.Attributes; listTypes.Items.Add(""); listTypes.Items.Add("Attributes:"); istTypes.Items.Add(baseTypeAttributes.ToString()); //get all of the properties defined on the assembly. PropertyInfo[] propInfo = baseType.GetProperties(); //get all of the methods defined on the assembly. MethodInfo[] methodInfo = baseType.GetMethods(); listTypes.Items.Add(""); listTypes.Items.Add("Properties:");

- 113 -

//loop through the property info array. foreach(PropertyInfo prop in propInfo) { //get the property name. listTypes.Items.Add("Name: " +prop.Name); //get the member type "Property". listTypes.Items.Add("Member Type: " +prop.MemberType); //get the property type. listTypes.Items.Add("Property Type: " +prop.PropertyType); //does the property have a get method defined. listTypes.Items.Add("Read: " +prop.CanRead); //does the property have a set method defined. listTypes.Items.Add("Write: " +prop.CanWrite); listTypes.Items.Add("") } listTypes.Items.Add(""); listTypes.Items.Add("Methods:"); //loop through the method info array. foreach(MethodInfo method in methodInfo) { //get the method name. listTypes.Items.Add("Name: " +method.Name); //get the membertype. listTypes.Items.Add("Member Type: " +method.MemberType); //get the return type of the method. listTypes.Items.Add("Return Type: " +method.ReturnType); //is the method defined as public. listTypes.Items.Add("Public: " +method.IsPublic); //is the method defined as private. listTypes.Items.Add("Private: " +method.IsPrivate); //is the method defined as abstract. listTypes.Items.Add("Abstract: " +method.IsAbstract); //is the method defined as virtual. listTypes.Items.Add("Virtual: " +method.IsVirtual); //is the method defined as static. listTypes.Items.Add("Static: " +method.IsStatic); listTypes.Items.Add(""); } } } private void ReflectionForm_Load(object sender, System.EventArgs e) //return the Assembly types Assembly PersonAssembly = Assembly.LoadFrom("..\\..\\Person.dll"); PersonTypes = PersonAssembly.GetTypes(); Assembly EmployeeAssembly = Assembly.LoadFrom("..\\..\\Employee.dll"); EmployeeTypes = EmployeeAssembly.GetTypes();

- 114 -

Assembly CustomerAssembly = Assembly.LoadFrom("..\\..\\Customer.dll"); CustomerTypes = CustomerAssembly.GetTypes(); listAssemblies.SelectedIndex=0; } private void cboAssemblies_SelectedIndexChanged(object sender, System.EventArgs e) { } } }

EMPLOYEE CODE
ASSEMBLY INFORMATION: using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")]

- 115 -

// // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")]

- 116 -

WORKER CODE: using System; namespace Employee { /// <summary> /// Summary description for Class1. /// </summary> public class Worker { public Worker() { // // TODO: Add constructor logic here // } public string GetWorker(String WorkerID) { return "ID is blank"; } } }

PERSON ASSEMBLY INFORMATION:


using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]

- 117 -

// Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // Use the attributes below to control which key is used for signing. // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")]

- 118 -

INDIVIDUAL CODE: using System; namespace Person { /// <summary> /// Summary description for Class1. /// </summary> public class Individual { public Individual() { // // TODO: Add constructor logic here // } public string GetIndividual(String IndividualID) { return "ID is blank"; } } }

- 119 -

CUSTOMER CODE ASSEMBLY INFORMATION


using System.Reflection; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is

- 120 -

// located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this.
//

[assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] CUSTOMER CODE: using System; namespace Customer { /// <summary> /// Summary description for Class1. /// </summary> public class Client { public Client() { // // TODO: Add constructor logic here // } public string GetClient(String ClientID) { return "ID is blank"; } } }

- 121 -

AIM
Uses a simple Web form to demonstrate how to use the SmtpMail class in the .NET Framework.

PROGRAM SendingMail
using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.SessionState; System.Web.UI; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Web.Mail;

namespace SendMail { /// <summary> /// SendingMail is a simple application that shows two different ways to send email. /// One of the examples is repeated in order to show how to make an attachment. /// </summary> public class SendingMail : System.Web.UI.Page { protected System.Web.UI.WebControls.TextBox fromAddress; protected System.Web.UI.WebControls.TextBox sendToAddress; protected System.Web.UI.WebControls.TextBox messageSubject; protected System.Web.UI.WebControls.TextBox messageBody; protected System.Web.UI.WebControls.TextBox fileNameToAttach; protected System.Web.UI.WebControls.Button SendMessageNoMessageObj; protected System.Web.UI.WebControls.Button SendMessageWithFile; protected System.Web.UI.WebControls.TextBox SMTPServerName; protected System.Web.UI.WebControls.Label statusLabel; protected System.Web.UI.WebControls.Button SendMessage;

- 122 -

private void Page_Load(object sender, System.EventArgs e) { } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // CODEGEN: This call is required by the ASP.NET Web Form Designer. InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.SendMessage.Click += new System.EventHandler(this.SendMessage_Click); this.SendMessageNoMessageObj.Click += new System.EventHandler(this.SendMessageNoMessageObj_Click); this.SendMessageWithFile.Click += new System.EventHandler(this.SendMessageWithFile_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void SendMessage_Click(object sender, System.EventArgs e) { /// <summary> /// Create a MailMessage object called myMail</summary> MailMessage myMail = new MailMessage(); /// <summary> /// Set the From property for the email</summary> /// <value> /// The value must be an address that can be relayed by the mail server.</value> myMail.From= fromAddress.Text; /// <summary> /// Set the To property for the email</summary> /// <value> /// The value is the address to which you want to send the email.</value> myMail.To=sendToAddress.Text;

- 123 -

HTML.</value>

/// <summary> /// Set the Subject property for the email</summary> /// <value> /// This property sets the subject for the email.</value> myMail.Subject=messageSubject.Text; /// <summary> /// Set the Body property for the email</summary> /// <value> /// This is the actual message. It can be text or myMail.Body=messageBody.Text; /// <summary> /// Set the SmtpServer property of the SmtpMail

class</summary>

/// <value> /// This server is the outgoing mail server. Make sure it can relay messages matching the address in the From property.</value> SmtpMail.SmtpServer=SMTPServerName.Text; /// <summary> /// The Send method of the SmtpMail class will send the email to the address listed in the To property</summary> /// <value> /// The mail object is passed to the Send method</value> SmtpMail.Send (myMail); /// Update the status message statusLabel.Text = "Mail has been sent"; } private void SendMessageNoMessageObj_Click(object sender, System.EventArgs e) { /// <summary> /// An alternative way to send an email is to use the SmtpMail class without /// creating a MailMessage object. Here you just pass some string values to /// the Send method.</summary> /// <summary> /// Set the from string to indicate the sender of the email </summary> /// <value> /// The value must be an address that can be relayed by the mail server. </value> string from = fromAddress.Text; /// <summary>

- 124 -

</summary>

/// Set the to string to indicate the recipient of the email

/// <value> /// The value is the address to which you want to send the email.</value> string to = sendToAddress.Text; /// <summary> /// Set the to string to indicate the subject of the email </summary> /// <value> /// The value is the subject of the email.</value> string subject = messageSubject.Text; /// <summary> /// Set the to string hold the body of the email </summary> /// <value> /// The value is the address to which you want to send the email.</value> string body = messageBody.Text; /// <summary> /// Set the to string to indicate the recipient of the email </summary> /// <value> /// The value is the address to which you want to send the email.</value> SmtpMail.SmtpServer=SMTPServerName.Text; /// Set the SmtpServer property of the SmtpMail class</summary> /// <value> /// This server is the outgoing mail server. Make sure it can relay messages matching the address in the From property.</value> SmtpMail.Send(from, to, subject, body); /// Update the status message statusLabel.Text = "Mail has been sent"; } private void SendMessageWithFile_Click(object sender, System.EventArgs e) { /// <summary> /// Returning to the first method, you now see how to create an attachment. /// This is accomplished by creating a MailAttachment object and adding it /// to the Attachments collection of a MailMessage object.</summary> if (fileNameToAttach.Text == "" )

- 125 -

{ an attachment";

statusLabel.Text = "File name is required to send return;

} /// <summary> /// Create a MailMessage object called mailWithAttachment</summary> MailMessage mailWithAttachment = new MailMessage(); /// <summary> /// Create a MailAttachment object called myAttachment</summary> /// <value> /// The name of the file to attach is passed into the MailAttachment constructor.</value> MailAttachment myAttachment = new MailAttachment(fileNameToAttach.Text); /// <summary> /// Add the file attachment to the MailMessage's Attachments collection</summary> /// <value> /// A MailAttachment object is added to the MailMessage's Attachments collection</value> mailWithAttachment.Attachments.Add(myAttachment); /// <summary> /// Set the From property for the email</summary> /// <value> /// The value must be an address that can be relayed by the mail server.</value> mailWithAttachment.From=fromAddress.Text; /// <summary> /// Set the Subject property for the email</summary> /// <value> /// This property sets the subject for the email.</value> mailWithAttachment.To=sendToAddress.Text; /// <summary> /// Set the Body property for the email</summary> /// <value> /// This is the actual message. It can be text or HTML.</value> mailWithAttachment.Body=messageBody.Text; /// <summary> /// Set the Subject property for the email</summary> /// <value> /// This property sets the subject for the email.</value> mailWithAttachment.Subject=messageSubject.Text; /// <summary>

- 126 -

class</summary>

/// Set the SmtpServer property of the SmtpMail

/// <value> /// This server is the outgoing mail server. Make sure it can relay messages matching the address in the From property.</value> SmtpMail.SmtpServer=SMTPServerName.Text; /// <summary> /// The Send method of the SmtpMail class will send the email to the address listed in the To property</summary> /// <value> /// The mail object is passed to the Send method</value> SmtpMail.Send(mailWithAttachment); /// Update the status message statusLabel.Text = "Mail has been sent"; } } }

- 127 -

AIM
Demonstrates some basic string manipulation using both the String Builder and String classes.

PROGRAM STRING SUBSTRING


ASSEMBLY INFORMATION:
using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the

- 128 -

// Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")]

SUBSTRING CODE:
using System; namespace StringSubstring { /// <summary> /// Summary description for Class1. /// </summary> class Substring { /// <summary> /// The main entry point for the application. /// </summary> [STAThread]

- 129 -

static void Main(string[] args) { // TODO: Add code to start application here string originalString = "abcdefghijklmnop"; Console.WriteLine("A Substring example:"); Console.WriteLine("String to Be Searched: " + originalString); string returnedString = originalString.Substring(4, 3).ToString(); Console.WriteLine("Start Index: " + "4"); Console.WriteLine("Length: " + "3"); Console.WriteLine("Substring: " + returnedString); Console.Read(); } } }

- 130 -

STRING SPLIT
ASSEMBLY INFORMATION using System.Reflection; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // Use the attributes below to control which key is used for signing. // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is

- 131 -

// located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")]

STRING SPLITTER CODE:


using System; namespace StringSplit { /// <summary> /// Summary description for StringSplitter. /// </summary> class StringSplitter { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { // TODO: Add code to start application here string textOriginal = "Value 1, Value 2, Value 3"; string[] textArray = textOriginal.Split(','); Console.WriteLine("An example of splitting a String:\r\n\r\n"); Console.WriteLine("The string to split: "+textOriginal); Console.WriteLine("The character to split from: ','"); Console.WriteLine("\r\nResults:"); foreach(string newText in textArray) { Console.WriteLine(newText.Trim().ToString()); } Console.WriteLine(""); Console.WriteLine("\r\n\r\nNow rejoin the textarray with a different delimiter:"); //now rejoin the array of strings string newJoin = string.Join(":", textArray); Console.WriteLine(newJoin); Console.Read(); } } }

- 132 -

STRING COPY
ASSEMBLY INFORMATION using System.Reflection; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be

- 133 -

// relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] STRING COPIER using System; namespace StringCopy { /// <summary> /// Summary description for StringCopier. /// </summary> class StringCopier { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { // TODO: Add code to start application here Console.WriteLine("An Example of String Copy"); Console.WriteLine("Type Some Text"); string inputText = Console.ReadLine(); string copiedText = string.Copy(inputText); copiedText+=" more text"; Console.WriteLine("Your text is here: "+inputText); Console.WriteLine("Copy of your text with some additions: "+copiedText); Console.Read(); } } }

- 134 -

BUILDER INSERT ASSEMBLY INFORMATION: using System.Reflection; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // Use the attributes below to control which key is used for signing. // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. //(*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]

- 135 -

// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] INSERTER CODE using System; using System.Text; namespace BuilderInsert { /// <summary> /// Summary description for Inserter. /// </summary> class Inserter { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { Console.WriteLine("Please Enter Your Name:"); string Name = Console.ReadLine(); StringBuilder Greeting = new StringBuilder(); Greeting.Append("Good Morning!"); if (Name.Length > 0) { Greeting.Insert(12,", "+ Name); } Console.WriteLine(Greeting); Console.Read(); } } }

- 136 -

BUILDER APPEND ASSEMBLY INFORMATION using System.Reflection; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // Use the attributes below to control which key is used for signing. // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile

- 137 -

// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] APPENDER using System; using System.Text; namespace BuilderAppend { /// <summary> /// Summary description for Appender. /// </summary> class Appender { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { Console.WriteLine("Please Enter Your Name:"); string Name = Console.ReadLine(); StringBuilder Greeting = new StringBuilder(); Greeting.Append("Good Morning"); if (Name.Length > 0) { Greeting.Append(", "+Name+"!"); } else { Greeting.Append("!"); } Console.WriteLine(Greeting); Console.Read(); } } }

- 138 -

BUILDER REPLACE ASSEMBLY INFORMATION: using System.Reflection; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // Use the attributes below to control which key is used for signing. // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]

- 139 -

// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")]

- 140 -

REPLACER: using System; using System.Text; namespace BuilderReplace { /// <summary> /// Summary description for Replacer. /// </summary> class Replacer { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { Console.WriteLine("Please Enter Your Name:"); string Name = Console.ReadLine(); StringBuilder Greeting = new StringBuilder(); Greeting.Append("Good Morning!"); if (Name.Length > 0) { Greeting.Insert(12,", "+ Name); } Console.WriteLine(Greeting); Console.WriteLine("Now Enter a Nickname:"); string NickName = Console.ReadLine(); //for this example the name and nickName lengths must be supplied. if(Name.Length > 0 && NickName.Length > 0) { Greeting.Replace(Name, NickName); } Console.WriteLine(Greeting); Console.Read(); } } }

- 141 -

AIM A sample application that demonstrates methods of storing application settings by making use of both the system registry and application configuration files. Implements a custom configuration section to show how you can tailor these files to the specific needs of a particular application. PROGRAM ASSEMBLY INFORMATION: using System.Reflection; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // Use the attributes below to control which key is used for signing. // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used.

- 142 -

// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] FORM1: using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; // The following directives were added to make the code // in the LoadColumns() and DisplayAppSettings() functions more readable. // This allows classes in these namespaces to be referenced without // a fully-qualified name. using System.Collections.Specialized; using System.Configuration; namespace SystemConfigurationFiles { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.ListView listView1; // <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public Form1() { // Required for Windows Form Designer support InitializeComponent();

- 143 -

// TODO: Add any constructor code after InitializeComponent call } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.listView1 = new System.Windows.Forms.ListView(); this.SuspendLayout(); // listView1 this.listView1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.listView1.FullRowSelect = true; this.listView1.Location = new System.Drawing.Point(8, 8); this.listView1.Name = "listView1"; this.listView1.Size = new System.Drawing.Size(328, 208); this.listView1.TabIndex = 1; this.listView1.View = System.Windows.Forms.View.Details; // Form1 this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(344, 228); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.listView1}); this.Name = "Form1"; this.Text = "System Files Configuration Sample"; this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing); this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false);

- 144 -

} #endregion /// <summary> // The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } /// <summary> /// This event fires when the form is loaded. At this time, the /// form size will be restored to that of the previous session as /// recorded in the registry. Grid columns will also be loaded from a /// custom section of a configuration file. Finally, some applications settings /// are displayed from the standard <appSettings> section of the config file. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">An EventArgs that contains the event data. </param> private void Form1_Load(object sender, System.EventArgs e) { // Restore the form size from the last session. RestoreFormSize(); // Load the grid columns dynamically from a config file. LoadColumns(); // Display some custom applications settings in the grid. DisplayAppSettings(); } /// <summary> /// This event fires when a form is closing. This will be used to persist /// the form size for use in future sessions. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">A CancelEventArgs that contains the event data.</param> private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) { // Persist the form size for the next session. SaveFormSize(); } /// <summary> /// This function demonstrates the use of the Registry class /// to retrieve settings from the CurrentUser section of the registry. /// </summary> private void RestoreFormSize() {

- 145 -

// Get a reference to the desired registry hive. // This example uses the CurrentUser hive in order to store user preferences // for each user on this machine separately. Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.CurrentUser; // The following line creates the desired sub key where the settings are be stored. // If the sub key already exists, a reference to the existing key is returned. Microsoft.Win32.RegistryKey regKey = hklm.CreateSubKey("Software\\SystemFilesConfigSample"); // The following lines retrieve the width and height settings from the sub key. // The second parameter indicates a default value if the setting // does not exist in the registry. int width = (int)regKey.GetValue("Width", 344); int height = (int)regKey.GetValue("Height", 228); // Restores the form size to persisted dimensions. this.ClientSize = new System.Drawing.Size(width, height); } /// <summary> /// This function demonstrates the use of the Registry class /// to save settings in the CurrentUser section of the registry. /// </summary> private void SaveFormSize() { // Get a reference to the desired registry hive. // This example uses the CurrentUser hive in order to store user preferences // for each user on this machine separately. Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.CurrentUser; // The following line creates the desired sub key where the settings will be stored. // If the sub key already exists, a reference to the existing key is returned. Microsoft.Win32.RegistryKey regKey = hklm.CreateSubKey("Software\\SystemFilesConfigSample"); // The following lines save the width and height of the form // in the specified registry keys. The settings will be created // if they don't already exist. regKey.SetValue("Width", this.ClientSize.Width); regKey.SetValue("Height", this.ClientSize.Height); } /// <summary> /// This function reads a custom configuration file section to determine /// the columns that should be displayed in the grid. The purpose of this function is /// to demonstrate how to read data from a custom section using the GetConfig() method. /// </summary> private void LoadColumns() {

- 146 -

// This code will return a reference to a custom section in the application config file. // This reference is cast to a NameValueCollection data type. // The NameValueCollection class is in the System.Collections.Specialized namespace. // See the "using System.Collections.Specialized" directive above. // The ConfigurationSettings class is in the System.Configuration namespace. // See the "using System.Configuration" directive above. NameValueCollection config = (NameValueCollection)ConfigurationSettings.GetConfig("gridSettings/gridColu mns"); // Because the config section is cast as a collection, it can be traversed. // In this example, the collection contains the text for the grid column headers. if (config != null) { for (int i = 0; i < config.Count; i++) { // For each entry in the config section, add a grid row. listView1.Columns.Add(config[i], 200, HorizontalAlignment.Left); } } } private void DisplayAppSettings() { // The assumption is made that these settings are used in code to control // the behavior of the application. Therefore, the number and names of the // settings are known, and they are accessed directly. Since this sample has // no true application logic, the settings are just displayed in a list. // The ConfigurationSettings class is in the System.Configuration namespace. // See the "using System.Configuration" directive above. listView1.Items.Add(new ListViewItem(new string[] {"Host", ConfigurationSettings.AppSettings["Host"]})); listView1.Items.Add(new ListViewItem(new string[] {"ServicePath", ConfigurationSettings.AppSettings["ServicePath"]})); listView1.Items.Add(new ListViewItem(new string[] {"Port", ConfigurationSettings.AppSettings["Port"]})); listView1.Items.Add(new ListViewItem(new string[] {"Timeout", ConfigurationSettings.AppSettings["Timeout"]})); listView1.Items.Add(new ListViewItem(new string[] {"UseSSL", ConfigurationSettings.AppSettings["UseSSL"]})); listView1.Items.Add(new ListViewItem(new string[] {"WSDLFile", ConfigurationSettings.AppSettings["WSDLFile"]})); listView1.Items.Add(new ListViewItem(new string[] {"WSMLFile", ConfigurationSettings.AppSettings["WSMLFile"]})); listView1.Items.Add(new ListViewItem(new string[] {"WebServiceName", ConfigurationSettings.AppSettings["WebServiceName"]}));

- 147 -

listView1.Items.Add(new ListViewItem(new string[] {"WebServicePort", ConfigurationSettings.AppSettings["WebServicePort"]})); } } }

- 148 -

AIM
Demonstrate how to create a Windows Form that can use HTTP to download and save a resource from a specified URI, upload a resource to a specified URI, or read and write data through a stream object. PROGRAM ASSEMBLY INFORMATION: using System.Reflection; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // Use the attributes below to control which key is used for signing. // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used.

- 149 -

// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] WebClientForm using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Net; using System.IO; namespace WebClient { /// <summary> /// Summary description for Form1. /// </summary> public class WebClientForm : System.Windows.Forms.Form { private System.Windows.Forms.Label Label1; private System.Windows.Forms.Label Label2; private System.Windows.Forms.TextBox targetURI; private System.Windows.Forms.Button GetTargetAtURI; private System.Windows.Forms.TextBox saveTargetToAddress; private System.Windows.Forms.Button SaveTextToTarget; private System.Windows.Forms.TextBox textOutput; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public WebClientForm() { // Required for Windows Form Designer support

- 150 -

InitializeComponent(); // TODO: Add any constructor code after InitializeComponent call } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { his.targetURI = new System.Windows.Forms.TextBox(); this.Label1 = new System.Windows.Forms.Label(); this.GetTargetAtURI = new System.Windows.Forms.Button(); this.saveTargetToAddress = new System.Windows.Forms.TextBox(); this.SaveTextToTarget = new System.Windows.Forms.Button(); this.Label2 = new System.Windows.Forms.Label(); this.textOutput = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // targetURI this.targetURI.Location = new System.Drawing.Point(8, 32); this.targetURI.Name = "targetURI"; this.targetURI.Size = new System.Drawing.Size(888, 20); this.targetURI.TabIndex = 2; this.targetURI.Text = "http://"; // Label1 this.Label1.Location = new System.Drawing.Point(8, 16); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(104, 16); this.Label1.TabIndex = 3; this.Label1.Text = "Download Address:"; // GetTargetAtURI this.GetTargetAtURI.Location = new System.Drawing.Point(904, 32); this.GetTargetAtURI.Name = "GetTargetAtURI"; this.GetTargetAtURI.Size = new System.Drawing.Size(56, 24);

- 151 -

this.GetTargetAtURI.TabIndex = 4; this.GetTargetAtURI.Text = "Go!"; this.GetTargetAtURI.Click += new System.EventHandler(this.ButtonGo_Click); // saveTargetToAddress this.saveTargetToAddress.Location = new System.Drawing.Point(8, 616); this.saveTargetToAddress.Name = "saveTargetToAddress"; this.saveTargetToAddress.Size = new System.Drawing.Size(880, 20); this.saveTargetToAddress.TabIndex = 5; this.saveTargetToAddress.Text = ""; // SaveTextToTarget this.SaveTextToTarget.Location = new System.Drawing.Point(896, 616); this.SaveTextToTarget.Name = "SaveTextToTarget"; this.SaveTextToTarget.Size = new System.Drawing.Size(56, 24); this.SaveTextToTarget.TabIndex = 6; this.SaveTextToTarget.Text = "Save"; this.SaveTextToTarget.Click += new System.EventHandler(this.ButtonSave_Click); // Label2 this.Label2.Location = new System.Drawing.Point(8, 592); this.Label2.Name = "Label2"; this.Label2.Size = new System.Drawing.Size(96, 16); this.Label2.TabIndex = 7; this.Label2.Text = "Save To Address:"; // textOutput this.textOutput.Location = new System.Drawing.Point(8, 64); this.textOutput.MaxLength = 50000; this.textOutput.Multiline = true; this.textOutput.Name = "textOutput"; this.textOutput.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.textOutput.Size = new System.Drawing.Size(992, 520); this.textOutput.TabIndex = 8; this.textOutput.Text = ""; // WebClientForm this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(1008, 656); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.textOutput, this.Label2, this.SaveTextToTarget, this.saveTargetToAddress, this.GetTargetAtURI, this.targetURI, this.Label1}); this.Name = "WebClientForm"; this.Text = "Source Viewer"; this.ResumeLayout(false); }

- 152 -

#endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new WebClientForm()); } private void ButtonGo_Click(object sender, System.EventArgs e) { string Address=targetURI.Text; if (Address!="") { //create an instance of the WebClient. System.Net.WebClient MyClient = new System.Net.WebClient(); //create a stream object to get the stream from the OpenRead method. System.IO.Stream MyStream = MyClient.OpenRead(Address); //create a streamreader to parse through the stream. System.IO.StreamReader MyStreamReader = new System.IO.StreamReader(MyStream); string NewLine; //loop through the stream and put the output in the textbox. while((NewLine=MyStreamReader.ReadLine())!=null) { textOutput.AppendText(NewLine+"\r\n"); } MyStream.Close(); } } private void ButtonSave_Click(object sender, System.EventArgs e) { string SaveAddress=saveTargetToAddress.Text; if (SaveAddress!="") { //create an instance of the WebClient. System.Net.WebClient MyClient = new System.Net.WebClient(); //create a stream object to hold the stream in the OpenWrite method. System.IO.Stream MyStream = MyClient.OpenWrite(SaveAddress, "PUT"); //create a streamwriter to write the stream to the specified location. System.IO.StreamWriter MyStreamWriter = new System.IO.StreamWriter(MyStream); //grab the stream and write the output. MyStreamWriter.Write(textOutput.Text); //close the writer. MyStreamWriter.Close(); MessageBox.Show("File has been created!"); }}}}

- 153 -

AIM Examines how to use IIS to perform user authentication so that no changes to the Web Service are required in order to provide superior security. PROGRAM WebServiceSecurityClient ASSEMBLY INFORMATION: using System.Reflection; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // Use the attributes below to control which key is used for signing. // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used.

- 154 -

// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] FORM: using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace WebServiceSecurityClient { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox WebServiceResults; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox Password; private System.Windows.Forms.TextBox UserName; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public Form1() { // Required for Windows Form Designer support InitializeComponent(); // TODO: Add any constructor code after InitializeComponent call

- 155 -

} /// <summary> // Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.WebServiceResults = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.Password = new System.Windows.Forms.TextBox(); this.UserName = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.SuspendLayout(); // button1 this.button1.Location = new System.Drawing.Point(144, 128); this.button1.Name = "button1"; this.button1.TabIndex = 6; this.button1.TabStop = false; this.button1.Text = "Go"; this.button1.Click += new System.EventHandler(this.button1_Click); // WebServiceResults this.WebServiceResults.Location = new System.Drawing.Point(72, 16); this.WebServiceResults.Name = "WebServiceResults"; this.WebServiceResults.Size = new System.Drawing.Size(136, 20); this.WebServiceResults.TabIndex = 2; this.WebServiceResults.TabStop = false; this.WebServiceResults.Text = ""; // label1 this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(8, 16); this.label1.Name = "label1";

- 156 -

this.label1.Size = new System.Drawing.Size(38, 13); this.label1.TabIndex = 3; this.label1.Text = "Output"; // Password this.Password.Location = new System.Drawing.Point(72, 80); this.Password.Name = "Password"; this.Password.PasswordChar = '*'; this.Password.Size = new System.Drawing.Size(136, 20); this.Password.TabIndex = 1; this.Password.Text = ""; // UserName this.UserName.Location = new System.Drawing.Point(72, 48); this.UserName.Name = "UserName"; this.UserName.Size = new System.Drawing.Size(136, 20); this.UserName.TabIndex = 0; this.UserName.Text = ""; // label2 this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(8, 80); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(54, 13); this.label2.TabIndex = 5; this.label2.Text = "Password"; // label3 this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(8, 48); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(61, 13); this.label3.TabIndex = 4; this.label3.Text = "User Name"; // Form1 this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(232, 166); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.label3, this.label2, this.UserName, this.Password, this.label1, this.WebServi this.button1}); this.Name = "Form1" this.Text = "Form1"; this.ResumeLayout(false); } #endregion /// <summary> /// void Main merely loads the form.

- 157 -

/// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } /// <summary> /// The button1_Click event handler runs when the button is clicked. The reference to the /// Greetings.asmx Web Service has already been set, so in this procedure you will /// instantiate the Web Service and also create a NetworkCredential object. // </summary> private void button1_Click(object sender, System.EventArgs e) { /// <summary> /// The NetworkCredential class is used to instantiate an object named myCred. /// This object will be passed to the Credentials property of the Web Service /// object you create.</summary> System.Net.NetworkCredential myCred = new System.Net.NetworkCredential(); /// <summary> /// myGreeting is the object you create that points to the Greetings Web Service. /// You may need to create a new Web Reference and change this line if the Web Service /// is not running on a local machine.</summary> localhost.Greetings myGreeting = new localhost.Greetings(); /// <summary> /// Setting the UserName property of the NetworkCredential object. </summary> myCred.UserName= UserName.Text; /// <summary> /// Setting the Password property of the NetworkCredential object. </summary> myCred.Password= Password.Text; /// <summary> /// Here you set the Credentials property of the Web Service variable to the /// NetworkCredential object you created earlier.</summary> myGreeting.Credentials=myCred; /// <summary> /// After the Credentials property is set, you call the Web Service method as you normally /// would, and the credential information is passed as part of the SOAP header.</summary> WebServiceResults.Text=myGreeting.HelloWorld(); } }}

- 158 -

WebServiceSecurityWS using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Web; using System.Web.Services; namespace WebServiceSecurity { /// <summary> /// Summary description for Service1. /// </summary> public class Greetings : System.Web.Services.WebService { public Greetings() { //CODEGEN: This call is required by the ASP.NET Web Services Designer InitializeComponent(); } #region Component Designer generated code //Required by the Web Services Designer private IContainer components = null; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if(disposing && components != null) { components.Dispose(); } base.Dispose(disposing); } #endregion /// <summary> /// This is a simple Web Service that just implements the classic "Hello world" /// program. Note that no coding is required to make it secure. This will be done

- 159 -

/// using the built-in capabilities of IIS and some client-side programming. /// </summary> [WebMethod] public string HelloWorld() { return "Hello World"; } } }

- 160 -

AIM Demonstrate how to retrieve information from an existing XML document and how to create a new XML document of memory management. PROGRAM XMLReade ASSEMBLY INFORMATION: using System.Reflection; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // Use the attributes below to control which key is used for signing. // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used.

- 161 -

// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] MAIN FORM using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Xml; namespace XMLTextReader { /// <summary> /// Summary description for MainForm. /// </summary> public class MainForm : System.Windows.Forms.Form { private System.Windows.Forms.Label fileName; private System.Windows.Forms.TextBox XMLOutput; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public MainForm() { // Required for Windows Form Designer support InitializeComponent(); // TODO: Add any constructor code after InitializeComponent call } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) {

- 162 -

if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.fileName = new System.Windows.Forms.Label(); this.XMLOutput = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // fileName this.fileName.AutoSize = true; this.fileName.Location = new System.Drawing.Point(24, 16); this.fileName.Name = "fileName"; this.fileName.Size = new System.Drawing.Size(47, 13); this.fileName.TabIndex = 1; this.fileName.Text = "fileName"; // XMLOutput this.XMLOutput.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) System.Windows.Forms.AnchorStyles.Right); this.XMLOutput.Location = new System.Drawing.Point(8, 48); this.XMLOutput.Multiline = true; this.XMLOutput.Name = "XMLOutput"; this.XMLOutput.Size = new System.Drawing.Size(776, 312); this.XMLOutput.TabIndex = 2; this.XMLOutput.Text = ""; // MainForm this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(792, 374); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.XMLOutput, this.fileName}); this.Name = "MainForm"; this.Text = "MainForm"; this.Load += new System.EventHandler(this.MainForm_Load); this.ResumeLayout(false); } #endregion static void Main() {

- 163 -

Application.Run(new MainForm()); } private void MainForm_Load(object sender, System.EventArgs e) { string XmlFile; System.IO.DirectoryInfo directoryInfo; System.IO.DirectoryInfo directoryXML; //Get the applications startup path directoryInfo = System.IO.Directory.GetParent(Application.StartupPath); //Set the output path if (directoryInfo.Name.ToString() == "bin") { directoryXML = System.IO.Directory.GetParent(directoryInfo.FullName); XmlFile = directoryXML.FullName + "\\customers.xml"; } else { XmlFile = directoryInfo.FullName + "\\customers.xml"; } fileName.Text = XmlFile; //load the xml file into the XmlTextReader object. XmlTextReader XmlRdr = new System.Xml.XmlTextReader(XmlFile); //while moving through the xml document. while(XmlRdr.Read()) { //check the node type and look for the element type //whose Name property is equal to name. if (XmlRdr.NodeType==XmlNodeType.Element&&XmlRdr.Name=="name") { XMLOutput.Text += XmlRdr.ReadString() + "\r\n"; } } } } }

- 164 -

ASSEMBLY INFORMATION:

XMLWriter

using System.Reflection; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]

- 165 -

// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] MAIN FORM using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Xml; namespace XMLTextWriter { /// <summary> // Summary description for MainForm. /// </summary> public class MainForm : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox OutputFileName; private System.Windows.Forms.StatusBar statusBar1; private System.Windows.Forms.Button WriteFile; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public MainForm() { // Required for Windows Form Designer support InitializeComponent(); // TODO: Add any constructor code after InitializeComponent call } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); }

- 166 -

} base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.OutputFileName = new System.Windows.Forms.TextBox(); this.statusBar1 = new System.Windows.Forms.StatusBar(); this.WriteFile = new System.Windows.Forms.Button(); this.SuspendLayout(); // label1 this.label1.Location = new System.Drawing.Point(16, 24); this.label1.Name = "label1"; this.label1.TabIndex = 0; this.label1.Text = "File Name"; // OutputFileName this.OutputFileName.Location = new System.Drawing.Point(144, 24); this.OutputFileName.Name = "OutputFileName"; this.OutputFileName.Size = new System.Drawing.Size(464, 20); this.OutputFileName.TabIndex = 1; this.OutputFileName.Text = "customers.xml"; // statusBar1 this.statusBar1.Location = new System.Drawing.Point(0, 416); this.statusBar1.Name = "statusBar1"; this.statusBar1.Size = new System.Drawing.Size(704, 22); this.statusBar1.TabIndex = 2; this.statusBar1.Text = "statusBar1"; // WriteFile this.WriteFile.Location = new System.Drawing.Point(144, 56); this.WriteFile.Name = "WriteFile"; this.WriteFile.TabIndex = 3; this.WriteFile.Text = "Write File"; this.WriteFile.Click += new System.EventHandler(this.WriteFile_Click); // MainForm this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(704, 438); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.WriteFile, this.statusBar1, this.OutputFileName, this.label1}); this.Name = "MainForm"; this.Text = "MainForm";

- 167 -

this.ResumeLayout(false); } #endregion static void Main() { Application.Run(new MainForm()); } private void WriteFile_Click(object sender, System.EventArgs e) { string XmlFile; System.IO.DirectoryInfo directoryInfo; System.IO.DirectoryInfo directoryXML; //Get the applications startup path directoryInfo = System.IO.Directory.GetParent(Application.StartupPath); //Set the output path if (directoryInfo.Name.ToString() == "bin") { directoryXML = System.IO.Directory.GetParent(directoryInfo.FullName); XmlFile = directoryXML.FullName + "\\" + OutputFileName.Text; } else { XmlFile = directoryInfo.FullName + "\\" + OutputFileName.Text; } //create the xml text writer object by providing the filename to write to //and the desired encoding. If the encoding is left null, then the writer //assumes UTF-8. XmlTextWriter XmlWtr = new System.Xml.XmlTextWriter(XmlFile,null); //set the formatting option of the xml file. The default indentation is 2 character spaces. //To change the default, use the Indentation property to set the number of IndentChars to use //and use the IndentChar property to set the character to use for indentation, such as the //tab character. Here the default is used. XmlWtr.Formatting=Formatting.Indented; //begin to write the xml document. This creates the xml declaration with the version attribute //set to "1.0". XmlWtr.WriteStartDocument(); //start the first element. XmlWtr.WriteStartElement("customers"); //create our first customer element. //this is a child element of the customers element. XmlWtr.WriteStartElement("customer"); //writes the entire element with the specified element name and //string value respectively. XmlWtr.WriteElementString("name", "Kevin Anders");

- 168 -

XmlWtr.WriteElementString("phone", "555.555.5555"); //end the customer element. XmlWtr.WriteEndElement(); //create another customer. XmlWtr.WriteStartElement("customer"); XmlWtr.WriteElementString("name", "Staci Richard"); XmlWtr.WriteElementString("phone", "555.122.1552"); //end the second customer element. XmlWtr.WriteEndElement(); //end the customers element. XmlWtr.WriteEndElement(); //now end the document. XmlWtr.WriteEndDocument(); //now flush the contents of the stream. XmlWtr.Flush(); //close the text writerj and write the xml file. XmlWtr.Close(); statusBar1.Text = "Output file has been written"; } } }

- 169 -

TEXT BOOKS:
1) Client/Server With Java And CORBA Robert Orfali And Dan Harkey, John Wiley And Sons, SPD 2nd Edition 2) Java Programming With CORBA 3rd Edition, G Brose, A. Vogel And K. Dudy, Wiley-Dreamtech, India. John Wiley And Sons

REFERENCES:
1) Distributed Computing, Principles And Applications, M.L. Liu, Pearson Edition 2) Client/Server Survival Guide 3rd Edition Robert Orfali And Dan Harkey & Jeri Edwards, John Weiley And Sons 3) Clien/Server Computing D T Dewire, TMH 4) IBM Webspere Starter Kit Ron Ben Natan Ori Sasson, TMH 5) Programming C#, Jesse Liberty, Spd-OReilly 6) C# Precisely Peter Sestoft And Henrik I. Hansen, Prentice Hall Of India 7) Introduction To C# Using .NET Pearson Education 8) C# How To Program, Pearson Education 9) C# And The .NET Platform Andrew Troelsen, Aprs Wiley-Dreamtech, India Pvt Ltd.

- 170 -